Mechanisms over intentions: request-time lesson delivery, self-referential rules, enforced question dialog
ci / tests (macos-latest, python 3.10) (push) Canceled after 0s
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.10) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.10) (push) Canceled after 0s
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.10) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s
sisi prompt hands the matching recipe and lessons to the agent when the human's request arrives. Every rule ends with the command that prints its reasons, history, lessons and enforcement; sisi rule lists what enforces each rule. Ending a turn by asking in reply text instead of the question dialog is sent back. Rulebook budget raised to 200 lines and 12,000 characters. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
f7bc6eded1
commit
11be8e3664
21 files changed
+1087
-44
No files matched your search
@@ -21,3 +21,4 @@ __pycache__/
|
||||
*~
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.crush/
|
||||
@@ -6,8 +6,29 @@ All notable changes to this project are recorded here. The format follows
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Changed
|
||||
|
||||
- The always-loaded rulebook budget is raised to the largest size vendor guidance supports; growth
|
||||
still requires shortening elsewhere.
|
||||
|
||||
### Added
|
||||
|
||||
- Request-time delivery (`sisi prompt`): where a tool documents a prompt-submission event with a
|
||||
context channel (Claude Code, Codex CLI, Gemini CLI, Muse CLI, Pi), the matching
|
||||
recipe's "done means" list and the strictly matching lessons are injected when the human's
|
||||
request arrives — no asking needed — each with the command that prints it in full. Nothing is
|
||||
injected for trivial or unmatched messages, the injection is size-capped, showings are counted as
|
||||
listings, and the hook can never block a turn. No prompt hook is wired where the event or its
|
||||
injection channel is unconfirmed (Qwen Code, Cursor, OpenCode); see docs/harnesses.md.
|
||||
- `sisi rule [N|ID]`: every rule in the effective rulebook with how it is enforced, derived from
|
||||
code facts, and one rule in full with its reasons, history and folded lessons. The generated
|
||||
rulebook ends each rule with `More: sisi rule N`; the size budgets grow only by those pointer
|
||||
lines (rule text keeps its former budgets).
|
||||
- The end-of-turn gate enforces the question-dialog rule where a dialog exists and the transcript
|
||||
is readable (Claude Code; Qwen Code wired the same way pending transcript confirmation): ending
|
||||
a turn by asking in reply text without using the dialog is sent back once, with subagents and
|
||||
dialog-less tools exempt.
|
||||
|
||||
- Lessons gain an optional short line (one plain sentence, at most 140 characters) and topic
|
||||
(between one and three lower-case words, at most 30 characters), written at `sisi retro` with
|
||||
`--short` and `--topic` or by a learning round with a `set-short` note action. The cycle brief
|
||||
|
||||
@@ -28,7 +28,9 @@ shown, it is strengthened: a note, a candidate rule, then an enforced check the
|
||||
`sisi cycle` consolidates lessons into rules and library entries without growing the rulebook.
|
||||
Whether it is due is checked during normal use, so nothing is scheduled; see
|
||||
[docs/learning.md](docs/learning.md). `sisi lessons digest` prints what has been learned in plain
|
||||
words, grouped by topic.
|
||||
words, grouped by topic. Where a tool allows it, the matching recipe and lessons are also delivered
|
||||
the moment a request arrives (`sisi prompt`), and each rule names the command that explains it
|
||||
(`sisi rule`).
|
||||
|
||||
Improvement needs a way to tell success from failure:
|
||||
|
||||
|
||||
+28
-9
@@ -20,7 +20,7 @@ in an owner-only (0700) folder, each with its source file's permissions.
|
||||
|
||||
Wiring is always by reference: an import line, a symlink to the generated rulebook
|
||||
(`~/.local/share/sisi/generated/core.md`), hook entries that run `sisi tick --tool NAME` /
|
||||
`sisi gate --tool NAME`, or a small generated plugin/extension (recognised by its exact
|
||||
`sisi prompt --tool NAME` / `sisi gate --tool NAME`, or a small generated plugin/extension (recognised by its exact
|
||||
`sisi:generated …` first line, never by the words appearing anywhere else in the file). Every registered
|
||||
shell hook command first checks the sisi launcher still exists, so deleting the sisi folder without
|
||||
uninstalling makes hooks exit silently instead of erroring on every turn. The per-tool translation
|
||||
@@ -32,13 +32,20 @@ state. Hooks fail open: any error lets the agent finish. Where a tool's hook inp
|
||||
## Claude Code
|
||||
|
||||
Fully wired, as before: an `@import` line in `~/.claude/CLAUDE.md`, `SessionStart` → `sisi tick`,
|
||||
`UserPromptSubmit` → `sisi prompt` (the matching recipe and lessons for the human's request, as
|
||||
added context; silent when nothing strictly matches, and never able to block a turn),
|
||||
`Stop`/`SubagentStop` → `sisi gate` (blocking), and `PreToolUse`/`PostToolUse` with matcher `Bash` →
|
||||
`sisi watch` (before/after tree measurement) in `~/.claude/settings.json`. Nothing for you to do.
|
||||
`sisi watch` (before/after tree measurement) in `~/.claude/settings.json`. The gate also enforces
|
||||
the question-dialog rule here: `AskUserQuestion` exists and the transcript is readable, so ending a
|
||||
turn by asking in reply text without using the dialog is sent back once. Evidence: the hooks
|
||||
reference documents `UserPromptSubmit` and its added-context output. Nothing for you to do.
|
||||
|
||||
## Codex CLI
|
||||
|
||||
Rulebook symlink at `~/.codex/AGENTS.md` (or `$CODEX_HOME/AGENTS.md`), plus hooks in
|
||||
`~/.codex/hooks.json`: `SessionStart` → tick, `Stop`/`SubagentStop` → gate,
|
||||
`~/.codex/hooks.json`: `SessionStart` → tick, `UserPromptSubmit` → prompt (the hooks page documents
|
||||
the event and its added-context output; it needs the same one-time trust below),
|
||||
`Stop`/`SubagentStop` → gate,
|
||||
`PreToolUse`/`PostToolUse` (matcher `Bash`) → `sisi watch`, blocking with
|
||||
`{"decision":"block","reason":...}`. One step is yours: Codex only runs hooks you have trusted, by exact
|
||||
definition hash. After `sisi install`, open Codex, run `/hooks`, and trust the sisi hooks; repeat after
|
||||
@@ -52,7 +59,8 @@ file path.
|
||||
## Gemini CLI
|
||||
|
||||
Rulebook symlink at `~/.gemini/GEMINI.md`, hooks merged into `~/.gemini/settings.json`: `SessionStart`
|
||||
→ tick (lessons injected as `additionalContext`), `AfterAgent` → gate, `BeforeTool`/`AfterTool` →
|
||||
→ tick (lessons injected as `additionalContext`), `BeforeAgent` → prompt (the documented
|
||||
before-turn event, carrying the request text), `AfterAgent` → gate, `BeforeTool`/`AfterTool` →
|
||||
`sisi watch` (`{"decision":"deny","reason":...}`
|
||||
rejects the response and forces a retry). Built from the hooks reference; Gemini is not installed on the
|
||||
development machine, so this has not run live. Gemini has no subagent-stop event in its hook list, so
|
||||
@@ -61,7 +69,8 @@ only the main turn is gated.
|
||||
## GitHub Copilot CLI
|
||||
|
||||
Rulebook symlink at `~/.copilot/copilot-instructions.md` (or under `$COPILOT_HOME`), hooks in
|
||||
`~/.copilot/hooks/sisi.json`: `sessionStart` → tick (`additionalContext`), `agentStop`/`subagentStop` →
|
||||
`~/.copilot/hooks/sisi.json`: `sessionStart` → tick (`additionalContext`),
|
||||
`userPromptSubmitted` → prompt (the documented before-prompt event), `agentStop`/`subagentStop` →
|
||||
gate (`{"decision":"block","reason":...}` forces another turn), `preToolUse`/`postToolUse` → `sisi watch`. Verified end to end in a throwaway home:
|
||||
a secret planted in session-start context was answered by the model, and a blocking `agentStop` visibly
|
||||
forced a second turn. The cloud coding agent only runs hooks committed in the repository
|
||||
@@ -75,14 +84,20 @@ Rulebook symlink at `~/.qwen/QWEN.md`, hooks merged into `~/.qwen/settings.json`
|
||||
first run, so run Qwen once before `sisi install`. Verified: the session-start hook was observed firing
|
||||
with its documented payload (a full turn needs an auth type configured). Qwen's question tool is named
|
||||
`ask_user_question` (the rulebook still names Claude Code's dialog; generalising that wording is future
|
||||
work). Qwen's before/after tool event names are not confirmed, so sisi registers no watch hooks there:
|
||||
work). The gate's question-dialog check is wired for Qwen the same way as for Claude Code, but
|
||||
Qwen's transcript shape is unconfirmed, so the check reads nothing — and therefore sends nothing
|
||||
back — until that shape is verified. No prompt hook is registered either: Qwen's prompt-submission
|
||||
event name is not confirmed in its hooks reference excerpts or in the installed package's text, and
|
||||
sisi does not guess event names into a config. Qwen's before/after tool event names are not confirmed, so sisi registers no watch hooks there:
|
||||
shell edits in Qwen are still judged from the command text.
|
||||
|
||||
## Pi
|
||||
|
||||
Rulebook symlink at `~/.pi/agent/AGENTS.md` (or `$PI_CODING_AGENT_DIR/AGENTS.md`; skipped if you already
|
||||
have your own file there) plus a generated extension at `~/.pi/agent/extensions/sisi.ts`. The extension
|
||||
runs `sisi tick` on `session_start` and injects the lessons at `before_agent_start`, and runs the gate on
|
||||
runs `sisi tick` on `session_start` and injects the lessons at `before_agent_start`, runs
|
||||
`sisi prompt` there too with the request text that event carries (the installed extension docs
|
||||
confirm the event and its message injection; a missing text field leaves it silent), and runs the gate on
|
||||
`agent_before_settle`, forcing one continuation with the failure report when checks fail (capped by the
|
||||
gate's own three send-backs). Verified: the extension loads in real Pi and tick runs; the blocking
|
||||
continuation could not be exercised end to end without a model login in the throwaway home. Pi gets no
|
||||
@@ -92,7 +107,9 @@ still judged from the command text.
|
||||
## Cursor
|
||||
|
||||
Hooks merged into `~/.cursor/hooks.json`: `sessionStart` → tick (lessons as `additional_context`),
|
||||
`stop`/`subagentStop` → gate, `preToolUse`/`postToolUse` → `sisi watch`. Cursor cannot veto a stop; instead a non-empty `followup_message` is
|
||||
`stop`/`subagentStop` → gate, `preToolUse`/`postToolUse` → `sisi watch`. No prompt hook: Cursor's
|
||||
documented `beforeSubmitPrompt` event can allow or stop a submission, but no channel for injecting
|
||||
added context is documented for it, so there is nothing for `sisi prompt` to print into. Cursor cannot veto a stop; instead a non-empty `followup_message` is
|
||||
auto-submitted as the next user message, which is how the gate sends the agent back (Cursor caps this at
|
||||
5 per script by default; sisi's own cap is 3). Only completed (not aborted/error) stops are gated.
|
||||
There is no confirmed user-global instruction *file* for Cursor, so sisi wires no global rulebook there;
|
||||
@@ -108,7 +125,9 @@ client prompt API where one exists. Be clear about the limits: `session.idle` fi
|
||||
finished and cannot veto anything, and on OpenCode v2.3.2 no plugin event delivery or lesson injection
|
||||
could be confirmed in headless runs (the plugin itself is loaded — verified — and the v1-style hooks and
|
||||
v2 `setup()` registration are both attempted, all fail-open). Treat OpenCode enforcement as unproven
|
||||
until it is observed on your version; `sisi doctor` says `unknown` on purpose. OpenCode gets no watch
|
||||
until it is observed on your version; `sisi doctor` says `unknown` on purpose. It also gets no
|
||||
prompt hook: a per-message plugin callback exists, but the transform that would inject added
|
||||
context is unconfirmed on the installed version. OpenCode gets no watch
|
||||
hooks either, so shell edits there are still judged from the command text.
|
||||
|
||||
## Muse Code
|
||||
|
||||
+32
-5
@@ -41,7 +41,16 @@ what "done" means, verifying, or being sent back by the gate.
|
||||
out) for the agent to open with `sisi lessons show ID`. Being printed or listed counts as
|
||||
*listed*; opening counts as *read* — the two are reported separately, because "listed many times,
|
||||
never read, still recurs" means the heading is bad, and the cycle brief says so. `sisi verifiers
|
||||
show` and the gate's send-back message keep the older single strong-match block. Draft recipe notes
|
||||
show` and the gate's send-back message keep the older single strong-match block. The same strict
|
||||
part-one test also runs at the moment the human's request arrives: where the tool documents a
|
||||
prompt-submission event with a context channel, `sisi prompt` injects the best-matching recipe's
|
||||
"done means" list in short form plus the matching lessons' short lines, each with the command
|
||||
that prints it in full (`sisi done ID`, `sisi lessons show ID`), within a 2,000-character cap.
|
||||
A recipe counts only when at least two distinct non-generic request words hit its title,
|
||||
applies-to or id (matched on stems, so "tag" meets "tagging"); trivial messages (a bare yes or
|
||||
no, a slash command, a short question) and unmatched requests inject nothing at all. These
|
||||
showings count as *listed* at place `prompt`. The hook never blocks a turn: any error exits
|
||||
silently. Draft recipe notes
|
||||
appear in `sisi done for` when their words match. Lesson text is always framed as information to
|
||||
weigh, not as commands, and text from a lesson is never executed. One-line headings — the
|
||||
other-lessons list, session-start notes, `sisi backlog` and `sisi lessons` — use the short
|
||||
@@ -59,8 +68,8 @@ what "done" means, verifying, or being sent back by the gate.
|
||||
5. **Recurring lessons get stronger.** Each lesson has a strength: 1 (a note), 2 (a candidate rule),
|
||||
3 (enforced). A recurrence after at least two showings since the last promotion moves it up one
|
||||
step — each step needs its own fresh evidence. A strength-2 lesson
|
||||
becomes a real rule only through consolidation (below), because the rulebook has hard budgets of
|
||||
120 lines and 7,200 characters and must not grow. A strength-3 lesson needs a check the gate can run; a folded lesson
|
||||
becomes a real rule only through consolidation (below), because the rulebook has hard budgets in
|
||||
lines and characters (`sisi canon cost` prints them), and must not grow without shortening. A strength-3 lesson needs a check the gate can run; a folded lesson
|
||||
shown 20 times with no recurrence is retired from the notes (it stays in history); a lesson that
|
||||
still recurs at strength 3 is withdrawn, and the same wording will not be learned again.
|
||||
6. **Consolidation happens in a cycle**, run by whichever agent is working — see below.
|
||||
@@ -129,8 +138,9 @@ when present: folded lessons no longer count toward the learned-notes limit, whi
|
||||
|
||||
`sisi cycle apply FILE` checks the file before writing anything: every lesson id exists, the base
|
||||
version is still current, changed rules keep their id and their Why, named `sisi` commands and
|
||||
enforced programs exist, and the resulting rulebook is inside both budgets (120 lines and 7,200
|
||||
characters) and no longer in characters than before unless `shortens` names what was removed.
|
||||
enforced programs exist, and the resulting rulebook is inside both budgets (lines and
|
||||
characters, printed by `sisi canon cost`) and no longer in characters than before
|
||||
unless `shortens` names what was removed.
|
||||
Rules are re-wrapped to 100 characters on apply. The base version covers only what a cycle may
|
||||
change (lesson content and status, short lines and topics, rules, notes, enforced checks), not
|
||||
listed/read counters, and
|
||||
@@ -148,6 +158,23 @@ contract-requirement fails a contract that touches its subject without a check o
|
||||
a command check runs in the project like a contract check, and only in projects already on the trust
|
||||
list.
|
||||
|
||||
## Every rule points at its own detail (`sisi rule`)
|
||||
|
||||
The generated rulebook ends each rule with one generated line — `More: sisi rule N` — so a rule an
|
||||
agent is reading names the command that explains it. `sisi rule` with no argument tables every rule
|
||||
in the effective rulebook with how it is enforced, in plain words, derived from what the code does
|
||||
(which hooks are wired, whether the floors and the gate checks exist): a rule with no mechanism
|
||||
says so ("not enforced: depends on the agent") instead of implying otherwise. `sisi rule N` (or
|
||||
`sisi rule ID`) prints the rule in full with its reasons, how it is enforced, whether the text is
|
||||
base or overlay, which learning rounds changed it, and the lessons folded into it, each with
|
||||
`sisi lessons show ID`. One rule gained a mechanism this way: where the tool has a question dialog
|
||||
and a readable transcript (Claude Code; Qwen Code is wired the same way but its transcript shape is
|
||||
unconfirmed, so the check may find nothing to read there), the end-of-turn gate sends the agent back
|
||||
once when its final message ends by asking the human a question in reply text and no dialog was
|
||||
used in that turn — the last sentence ending in a question mark outside code blocks, quotes and
|
||||
known rhetorical forms. Subagents and dialog-less tools are exempt, and the same message is never
|
||||
sent back twice.
|
||||
|
||||
## What has been learned, in plain words
|
||||
|
||||
`sisi lessons digest` is for the human, not for agents. Its first line says how much has been
|
||||
|
||||
@@ -45,7 +45,7 @@ Ids: rules are `## 1. Title {#rule-id}` in `canon/core.md`; verifiers and recipe
|
||||
|
||||
Commands: `sisi overlay list | diff | add-rule | replace-rule | disable-rule | enable-rule` (and the same for
|
||||
`verifier` and `recipe`), `sisi overlay revert COMMIT`. Each change is one commit and rebuilds the rulebook.
|
||||
The generated rulebook may not exceed 120 lines: a change that would pass it is refused, so a rule is added
|
||||
The generated rulebook may not exceed its line and character budgets: a change that would pass it is refused, so a rule is added
|
||||
by shortening or replacing another. `sisi canon cost` prints the always-loaded size.
|
||||
|
||||
On `sisi update` the overlay is applied to the new product. A replacement whose base item changed keeps the
|
||||
|
||||
+23
-10
@@ -514,6 +514,7 @@ class Codex(Adapter):
|
||||
def spec(self):
|
||||
return {
|
||||
"SessionStart": {"cmd": _cmd("tick", "codex"), "timeout": 10, "sub": "tick", "matcher": "startup|resume"},
|
||||
"UserPromptSubmit": {"cmd": _cmd("prompt", "codex"), "timeout": 10, "sub": "prompt"},
|
||||
"Stop": {"cmd": _cmd("gate", "codex"), "timeout": _gate_timeout(), "sub": "gate"},
|
||||
"SubagentStop": {"cmd": _cmd("gate", "codex", True), "timeout": 30, "sub": "gate"},
|
||||
"PreToolUse": {"cmd": _cmd("watch", "codex"), "timeout": 60, "sub": "watch", "matcher": "Bash"},
|
||||
@@ -538,7 +539,7 @@ class Codex(Adapter):
|
||||
% os.path.join(self.dir(), "AGENTS.override.md"))
|
||||
|
||||
def unwire(self, m, notes):
|
||||
subs = {"SessionStart": "tick", "Stop": "gate", "SubagentStop": "gate",
|
||||
subs = {"SessionStart": "tick", "UserPromptSubmit": "prompt", "Stop": "gate", "SubagentStop": "gate",
|
||||
"PreToolUse": "watch", "PostToolUse": "watch"}
|
||||
unmerge_json(m, self.hooks_file(), "nested", subs, self.spec(), notes, "codex")
|
||||
|
||||
@@ -551,6 +552,7 @@ class Codex(Adapter):
|
||||
hw = nested_wired(_load_obj(self.hooks_file()) or {}, self.spec())
|
||||
rb = _link_ok(link)
|
||||
missing = [n for n, ok in (("rulebook link", rb), ("tick hook", hw["SessionStart"]),
|
||||
("prompt hook", hw.get("UserPromptSubmit", False)),
|
||||
("gate hook", hw["Stop"]), ("subagent hook", hw["SubagentStop"]),
|
||||
("watch-before hook", hw.get("PreToolUse", False)), ("watch-after hook", hw.get("PostToolUse", False))) if not ok]
|
||||
if self.shadowed():
|
||||
@@ -578,6 +580,7 @@ class Gemini(Adapter):
|
||||
def spec(self):
|
||||
return {
|
||||
"SessionStart": {"cmd": _cmd("tick", "gemini"), "timeout": 10000, "sub": "tick", "name": "sisi-tick"},
|
||||
"BeforeAgent": {"cmd": _cmd("prompt", "gemini"), "timeout": 10000, "sub": "prompt", "name": "sisi-prompt"},
|
||||
"AfterAgent": {"cmd": _cmd("gate", "gemini"), "timeout": _gate_timeout() * 1000, "sub": "gate", "name": "sisi-gate"},
|
||||
"BeforeTool": {"cmd": _cmd("watch", "gemini"), "timeout": 60000, "sub": "watch", "name": "sisi-watch-before"},
|
||||
"AfterTool": {"cmd": _cmd("watch", "gemini"), "timeout": 60000, "sub": "watch", "name": "sisi-watch-after"},
|
||||
@@ -598,7 +601,7 @@ class Gemini(Adapter):
|
||||
wiring._link(m, os.path.join(self.dir(), "GEMINI.md"), wiring.core(), notes, "gemini")
|
||||
|
||||
def unwire(self, m, notes):
|
||||
unmerge_json(m, self.settings(), "nested", {"SessionStart": "tick", "AfterAgent": "gate",
|
||||
unmerge_json(m, self.settings(), "nested", {"SessionStart": "tick", "BeforeAgent": "prompt", "AfterAgent": "gate",
|
||||
"BeforeTool": "watch", "AfterTool": "watch"},
|
||||
self.spec(), notes, "gemini")
|
||||
unlink_ours(os.path.join(self.dir(), "GEMINI.md"), notes)
|
||||
@@ -608,7 +611,8 @@ class Gemini(Adapter):
|
||||
link = os.path.join(self.dir(), "GEMINI.md")
|
||||
hw = nested_wired(_load_obj(self.settings()) or {}, self.spec())
|
||||
rb = _link_ok(link)
|
||||
missing = [n for n, ok in (("rulebook link", rb), ("tick hook", hw["SessionStart"]), ("gate hook", hw["AfterAgent"]),
|
||||
missing = [n for n, ok in (("rulebook link", rb), ("tick hook", hw["SessionStart"]),
|
||||
("prompt hook", hw.get("BeforeAgent", False)), ("gate hook", hw["AfterAgent"]),
|
||||
("watch-before hook", hw.get("BeforeTool", False)), ("watch-after hook", hw.get("AfterTool", False))) if not ok]
|
||||
st.update(rulebook=rb, tick=hw["SessionStart"], wired=not missing,
|
||||
detail=("missing: " + ", ".join(missing)) if missing else "rulebook link + tick + gate hooks (shared ~/.gemini file also serves Antigravity)")
|
||||
@@ -627,6 +631,7 @@ class Copilot(Adapter):
|
||||
def spec(self):
|
||||
return {
|
||||
"sessionStart": {"cmd": _cmd("tick", "copilot"), "timeout": 10, "sub": "tick"},
|
||||
"userPromptSubmitted": {"cmd": _cmd("prompt", "copilot"), "timeout": 10, "sub": "prompt"},
|
||||
"agentStop": {"cmd": _cmd("gate", "copilot"), "timeout": _gate_timeout(), "sub": "gate"},
|
||||
"subagentStop": {"cmd": _cmd("gate", "copilot", True), "timeout": 30, "sub": "gate"},
|
||||
"preToolUse": {"cmd": _cmd("watch", "copilot"), "timeout": 60, "sub": "watch"},
|
||||
@@ -652,7 +657,7 @@ class Copilot(Adapter):
|
||||
wiring._link(m, os.path.join(self.dir(), "copilot-instructions.md"), wiring.core(), notes, "copilot")
|
||||
|
||||
def unwire(self, m, notes):
|
||||
subs = {"sessionStart": "tick", "agentStop": "gate", "subagentStop": "gate",
|
||||
subs = {"sessionStart": "tick", "userPromptSubmitted": "prompt", "agentStop": "gate", "subagentStop": "gate",
|
||||
"preToolUse": "watch", "postToolUse": "watch"}
|
||||
unmerge_json(m, self.hooks_file(), "flat", subs, self.spec(), notes, "copilot",
|
||||
created_version=1, make_entry=self._entry)
|
||||
@@ -664,6 +669,7 @@ class Copilot(Adapter):
|
||||
hw = flat_wired(_load_obj(self.hooks_file()) or {}, self.spec())
|
||||
rb = _link_ok(link)
|
||||
missing = [n for n, ok in (("rulebook link", rb), ("tick hook", hw["sessionStart"]),
|
||||
("prompt hook", hw.get("userPromptSubmitted", False)),
|
||||
("gate hook", hw["agentStop"]), ("subagent hook", hw["subagentStop"]),
|
||||
("watch-before hook", hw.get("preToolUse", False)), ("watch-after hook", hw.get("postToolUse", False))) if not ok]
|
||||
st.update(rulebook=rb, tick=hw["sessionStart"], wired=not missing,
|
||||
@@ -770,7 +776,7 @@ class Cursor(Adapter):
|
||||
|
||||
|
||||
def _pi_extension():
|
||||
body = '''// sisi:generated by `sisi install` -- runs `sisi tick` at session start and `sisi gate` before the session settles. Remove with `sisi uninstall`.
|
||||
body = '''// sisi:generated by `sisi install` -- runs `sisi tick` at session start, `sisi prompt` on each request and `sisi gate` before the session settles. Remove with `sisi uninstall`.
|
||||
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
||||
import { execFile } from "node:child_process";
|
||||
|
||||
@@ -780,13 +786,13 @@ const SID = "pi-" + process.pid + "-" + Math.random().toString(36).slice(2, 10);
|
||||
let tickText = "";
|
||||
let blocks = 0;
|
||||
|
||||
function runSisi(args, timeout) {
|
||||
function runSisi(args, timeout, payload) {
|
||||
return new Promise((resolve) => {
|
||||
const child = execFile(SISI, args, { timeout, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
|
||||
const code = err && typeof err.code === "number" ? err.code : err ? -1 : 0;
|
||||
resolve({ code, out: String(stdout ?? "") + String(stderr ?? "") });
|
||||
});
|
||||
if (child.stdin) child.stdin.end(JSON.stringify({ session_id: SID, cwd: process.cwd() }));
|
||||
if (child.stdin) child.stdin.end(JSON.stringify({ session_id: SID, cwd: process.cwd(), ...(payload || {}) }));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -798,10 +804,17 @@ export default function (pi: ExtensionAPI) {
|
||||
tickText = "";
|
||||
}
|
||||
});
|
||||
pi.on("before_agent_start", async () => {
|
||||
if (!tickText) return;
|
||||
const content = tickText;
|
||||
pi.on("before_agent_start", async (event) => {
|
||||
let promptText = "";
|
||||
try {
|
||||
const userText = event && typeof event.prompt === "string" ? event.prompt : "";
|
||||
if (userText) promptText = (await runSisi(["prompt", "--tool", "pi"], 10000, { prompt: userText })).out.trim();
|
||||
} catch {
|
||||
promptText = "";
|
||||
}
|
||||
const content = [tickText, promptText].filter(Boolean).join("\\n\\n");
|
||||
tickText = "";
|
||||
if (!content) return;
|
||||
return { message: { customType: "sisi-tick", content, display: false } };
|
||||
});
|
||||
pi.on("agent_before_settle", async (event) => {
|
||||
|
||||
+12
@@ -12,6 +12,8 @@ HELP = """sisi: shared rulebook and enforced definitions of done for every AI co
|
||||
sisi verify --all | --state run both tiers; print only the deep-check state (with --json)
|
||||
sisi gate [--tool NAME] end-of-turn hook (reads hook JSON on stdin; NAME selects the tool's hook shape)
|
||||
sisi tick [--tool NAME] session-start hook
|
||||
sisi prompt [--tool NAME] prompt-submission hook: prints the matching recipe and lessons for the human's request as added context (silent when nothing strictly matches); `sisi prompt "<request>"` tries it by hand
|
||||
sisi rule [N|ID] the effective rules and how each is enforced; with N or ID: one rule in full (reasons, history, lessons behind it, how it is enforced)
|
||||
sisi watch [--before|--after] before/after shell-tool hook: measures whether the command changed the project
|
||||
sisi install [--dry-run] | uninstall | doctor
|
||||
wire sisi into the tools (by reference), undo, inspect; --dry-run only prints what would change
|
||||
@@ -379,6 +381,16 @@ def main(argv):
|
||||
return hookio.tick_main(t, args)
|
||||
from . import tick
|
||||
return tick.main(args)
|
||||
if cmd == "prompt":
|
||||
if t and t != "claude-code":
|
||||
from . import hookio
|
||||
if hookio.known(t):
|
||||
return hookio.prompt_main(t, args)
|
||||
from . import prompt
|
||||
return prompt.main(args)
|
||||
if cmd == "rule":
|
||||
from . import rulecmd
|
||||
return rulecmd.main(args)
|
||||
if cmd in ("version", "--version", "-V"):
|
||||
from . import paths
|
||||
try:
|
||||
|
||||
+3
-2
@@ -453,7 +453,8 @@ and enforced checks, not listed/read counters. A stale refusal names exactly wha
|
||||
Rules - format: {"id", "title", "body", "action": "add|replace", "shortens": "..."}.
|
||||
Body: prose paragraphs wrapped at 100 characters (apply re-wraps for you), ending with a
|
||||
paragraph starting "Why:". Keep the id and the Why when replacing. Title is the heading text.
|
||||
Budget: at most 120 lines AND at most 7200 characters, and a cycle must not increase the
|
||||
Budget: at most 200 lines AND at most 12000 characters, counting the one generated
|
||||
`More: sisi rule N` pointer line per rule, and a cycle must not increase the
|
||||
characters unless it names in "shortens" which existing rule text gets shorter or is replaced
|
||||
(required whenever a rule is added or the book would grow in characters); never past the budget.
|
||||
Rule numbers in lessons ("rule 5") mean the numbered list in the brief, which maps number to id.
|
||||
@@ -1284,7 +1285,7 @@ def check_file(path):
|
||||
parts.append(pre)
|
||||
for n, rid in enumerate(order, 1):
|
||||
if rid in by_id:
|
||||
parts.append("## %d. %s {#%s}\n\n%s" % (n, by_id[rid]["title"], rid, by_id[rid]["body"]))
|
||||
parts.append("## %d. %s {#%s}\n\n%s\n%s" % (n, by_id[rid]["title"], rid, by_id[rid]["body"], overlay.more_line(n)))
|
||||
cand = "\n\n".join(parts) + "\n"
|
||||
lines, chars = overlay.size(cand)
|
||||
out.append(" rulebook: %s lines, %s characters -> %d lines, %d characters "
|
||||
|
||||
+135
-1
@@ -434,7 +434,127 @@ def _other_sessions(top, cwd, changed, sid, tp):
|
||||
return found[:3]
|
||||
|
||||
|
||||
def decide(payload):
|
||||
# ---------------------------------------------------------------- rule 5: ask through the dialog
|
||||
# Tools with a confirmed question dialog whose transcripts sisi can read in Claude-Code shape.
|
||||
# Codex's request_user_input is behind a flag that is off by default, OpenCode's question tool has
|
||||
# no readable transcript file here, and the other tools name no dialog at all, so they are exempt.
|
||||
QUESTION_DIALOG_TOOLS = {"claude-code": ("AskUserQuestion",), "qwen": ("ask_user_question",)}
|
||||
_RHETORICAL = (r"^who (wouldn'?t|couldn'?t|doesn'?t)\b", r"^what could possibly\b",
|
||||
r"^(isn'?t|aren'?t) it (obvious|clear)\b")
|
||||
|
||||
|
||||
def ends_with_question(text):
|
||||
"""True when a final message ends by asking the reader a question. The rule, exactly: after
|
||||
removing fenced code blocks, blockquote lines and inline code, the last sentence of the last
|
||||
paragraph ends with a question mark that is not inside a closing quote (a quoted question),
|
||||
and the sentence does not start with a known rhetorical form."""
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return False
|
||||
kept, in_fence = [], False
|
||||
for line in text.split("\n"):
|
||||
if line.strip().startswith("```"):
|
||||
in_fence = not in_fence
|
||||
continue
|
||||
if in_fence or line.lstrip().startswith(">"):
|
||||
continue
|
||||
kept.append(re.sub(r"`[^`]*`", "", line))
|
||||
paras = [p.strip() for p in re.split(r"\n\s*\n", "\n".join(kept)) if p.strip()]
|
||||
if not paras:
|
||||
return False
|
||||
para = " ".join(paras[-1].split())
|
||||
t = para.rstrip("*_ ")
|
||||
if t.endswith(('?"', "?\"", "?'", "?’", "?”")): # the question mark sits inside a quotation
|
||||
return False
|
||||
t = t.rstrip(')]*_ ')
|
||||
if not t.endswith("?"):
|
||||
return False
|
||||
start = max(t.rfind(".", 0, len(t) - 1), t.rfind("!", 0, len(t) - 1), t.rfind("?", 0, len(t) - 1)) + 1
|
||||
sentence = t[start:].strip().lower()
|
||||
return not any(re.match(p, sentence) for p in _RHETORICAL)
|
||||
|
||||
|
||||
def _last_turn(tp):
|
||||
"""(final assistant text, tool names used) after the last message the human typed, from the
|
||||
transcript tail. None when the turn cannot be bounded (the caller then exempts the turn)."""
|
||||
try:
|
||||
size = os.path.getsize(os.path.expanduser(tp))
|
||||
with open(os.path.expanduser(tp), "rb") as f:
|
||||
f.seek(max(0, size - 2 * 1024 * 1024))
|
||||
data = f.read()
|
||||
except OSError:
|
||||
return None
|
||||
from . import harvest
|
||||
recs = []
|
||||
for raw in data.split(b"\n"):
|
||||
if not raw.strip():
|
||||
continue
|
||||
try:
|
||||
d = json.loads(raw.decode("utf-8", "replace"))
|
||||
except ValueError:
|
||||
continue # a cut first line or a corrupt one: it cannot be the turn's evidence either way
|
||||
if isinstance(d, dict):
|
||||
recs.append(d)
|
||||
last_human = -1
|
||||
for i, d in enumerate(recs):
|
||||
if d.get("type") == "user":
|
||||
try:
|
||||
if harvest.typed_text(d)[0] is not None:
|
||||
last_human = i
|
||||
except Exception:
|
||||
pass
|
||||
if last_human < 0:
|
||||
return None
|
||||
final, tools = "", set()
|
||||
for d in recs[last_human + 1:]:
|
||||
content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None
|
||||
texts = []
|
||||
for x in content if isinstance(content, list) else []:
|
||||
if not isinstance(x, dict):
|
||||
continue
|
||||
if x.get("type") == "tool_use" and isinstance(x.get("name"), str):
|
||||
tools.add(x["name"])
|
||||
elif x.get("type") == "text" and isinstance(x.get("text"), str):
|
||||
texts.append(x["text"])
|
||||
if texts and d.get("type") in ("assistant", None):
|
||||
final = "\n".join(texts)
|
||||
return final, tools
|
||||
|
||||
|
||||
def _question_sendback(payload):
|
||||
"""('block', reason) when this turn ended by asking in reply text and no question dialog was
|
||||
used in it; None otherwise. At most once per final message, keyed by its hash in the session
|
||||
record, so a session can never be trapped. Subagents and dialog-less tools are exempt."""
|
||||
tool = store.tool()
|
||||
dialogs = QUESTION_DIALOG_TOOLS.get(tool or "")
|
||||
if not dialogs:
|
||||
return None
|
||||
if payload.get("agent_id") or payload.get("agent_transcript_path"):
|
||||
return None # a subagent has no human to ask through a dialog
|
||||
cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd()
|
||||
sid = _session_key(payload, cwd)
|
||||
sess = store.load_session(sid)
|
||||
tp = payload.get("transcript_path") if isinstance(payload.get("transcript_path"), str) else sess.get("transcript_path")
|
||||
if not isinstance(tp, str) or not tp:
|
||||
return None
|
||||
turn = _last_turn(tp)
|
||||
if not turn:
|
||||
return None
|
||||
final, tools = turn
|
||||
if any(d in tools for d in dialogs) or not ends_with_question(final):
|
||||
return None
|
||||
key = hashlib.sha1(final.encode("utf-8", "replace")).hexdigest()[:16]
|
||||
if sess.get("q_block_key") == key:
|
||||
return None
|
||||
sess["q_block_key"] = key
|
||||
sess["req_blocks"] = int(sess.get("req_blocks", 0)) + 1
|
||||
store.save_session(sid, sess)
|
||||
return "block", ("sisi: you ended by asking the human a question in the text of your reply. Ask it through the "
|
||||
"tool's question dialog (%s), with options to pick from and the one you recommend marked — or "
|
||||
"decide it yourself, record the assumption, and finish without the question. "
|
||||
"(Rule 5 in full: `sisi rule 5`.)" % dialogs[0])
|
||||
|
||||
|
||||
def _decide(payload):
|
||||
"""Return ('allow', message_or_None) or ('block', reason)."""
|
||||
cfg = store.config()
|
||||
g = cfg["gate"]
|
||||
@@ -716,6 +836,20 @@ def decide(payload):
|
||||
"the change needs no checks, run `sisi contract waive \"<reason>\"` instead." % (dl, df))
|
||||
|
||||
|
||||
def decide(payload):
|
||||
"""The gate's answer: the contract/retro decision, then — only on an otherwise-clean stop —
|
||||
the rule-5 question check, which sends the agent back at most once per final message."""
|
||||
action, msg = _decide(payload)
|
||||
if action != "allow":
|
||||
return action, msg
|
||||
try:
|
||||
q = _question_sendback(payload)
|
||||
except Exception as e: # the question check must never break the gate
|
||||
store.log_error("gate-question", e)
|
||||
q = None
|
||||
return q if q else (action, msg)
|
||||
|
||||
|
||||
def subagent_edits(transcript):
|
||||
"""(edited_files, start_ts) from a subagent transcript (JSONL). start_ts is in sisi's timestamp format, or None."""
|
||||
edited, start = False, None
|
||||
|
||||
@@ -62,6 +62,9 @@ def normalize(tool, d):
|
||||
if isinstance(d.get(k), dict):
|
||||
out["tool_input"] = d[k]
|
||||
break
|
||||
prompt = _s(d, "prompt", "user_prompt", "userPrompt")
|
||||
if prompt:
|
||||
out["prompt"] = prompt
|
||||
cwd = _s(d, "cwd")
|
||||
if not cwd and isinstance(d.get("workspace_roots"), list):
|
||||
roots = [r for r in d["workspace_roots"] if isinstance(r, str) and r]
|
||||
@@ -173,6 +176,55 @@ def _tick_out(tool, text):
|
||||
return _dump({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": text}})
|
||||
|
||||
|
||||
# Prompt-submission events with a documented context-injection channel, per tool. Cursor's
|
||||
# beforeSubmitPrompt can only allow or stop a submission (no injection channel is documented),
|
||||
# Qwen's prompt event name is not confirmed, and OpenCode's injection transform is unconfirmed on
|
||||
# the installed version, so sisi wires no prompt hook for those three (see docs/harnesses.md).
|
||||
PROMPT_EVENTS = {"codex": "UserPromptSubmit", "gemini": "BeforeAgent", "copilot": "userPromptSubmitted"}
|
||||
|
||||
|
||||
def _prompt_out(tool, text):
|
||||
text = (text or "").strip("\n")
|
||||
if tool in ("pi", "opencode"):
|
||||
return (text + "\n") if text else None
|
||||
if not text:
|
||||
return _dump({}) if tool in ("gemini", "qwen", "cursor") else None
|
||||
if tool == "copilot":
|
||||
return _dump({"additionalContext": text})
|
||||
if tool == "cursor":
|
||||
return _dump({"additional_context": text})
|
||||
return _dump({"hookSpecificOutput": {"hookEventName": PROMPT_EVENTS.get(tool, "UserPromptSubmit"),
|
||||
"additionalContext": text}})
|
||||
|
||||
|
||||
def prompt_main(tool, args=()):
|
||||
"""`sisi prompt --tool NAME`: build the request-time context and print it in the tool's shape.
|
||||
Pi's extension passes the request text as an argument. Always exits 0."""
|
||||
try:
|
||||
import os as _os
|
||||
from . import prompt as P
|
||||
positional = [a for a in args if not a.startswith("--")]
|
||||
if positional:
|
||||
text = P.build_context(" ".join(positional))
|
||||
else:
|
||||
d = _payload(store.read_stdin())
|
||||
if d is None:
|
||||
return 0
|
||||
norm = normalize(tool, d)
|
||||
cwd = norm.get("cwd")
|
||||
if cwd and _os.path.isdir(cwd):
|
||||
_os.chdir(cwd)
|
||||
query = P.extract_prompt(norm)
|
||||
text = P.build_context(query, session=norm.get("session_id")) if query else ""
|
||||
out = _prompt_out(tool, text)
|
||||
except Exception as e: # fail open: a prompt hook must never fail a turn
|
||||
store.log_error("prompt-%s" % tool, e)
|
||||
return 0
|
||||
if out:
|
||||
sys.stdout.write(out)
|
||||
return 0
|
||||
|
||||
|
||||
def tick_main(tool, args=()):
|
||||
try:
|
||||
d = _payload(store.read_stdin()) or {}
|
||||
|
||||
+14
-7
@@ -18,12 +18,14 @@ import contextlib, hashlib, json, os, re, sys, tempfile, time
|
||||
|
||||
from . import paths
|
||||
|
||||
MAX_LINES = 120
|
||||
# Character budget as well as lines: the base rulebook renders to 6,525 characters in 120 lines.
|
||||
# Wrapping games (fewer, longer lines) must not load more text into every session, so the honest
|
||||
# measure is characters. 7,200 allows modest headroom (about 10%) for a short replacement while
|
||||
# still refusing any real growth.
|
||||
MAX_CHARS = 7200
|
||||
# Budgets for what every session always loads, including the generated `More: sisi rule N` line
|
||||
# under each rule. 200 lines is the largest size vendor guidance supports (Anthropic: "target under
|
||||
# 200 lines per CLAUDE.md file"); published measurements say adherence falls as the number of
|
||||
# simultaneous instructions grows, so the book stays small and exactness comes from enforced checks
|
||||
# and request-time delivery. Characters are budgeted too, in the same proportion, because wrapping
|
||||
# games must not load more text. A learning round still may not grow the book without shortening.
|
||||
MAX_LINES = 200
|
||||
MAX_CHARS = 12000
|
||||
HOUSE_WIDTH = 100
|
||||
KINDS = ("rule", "verifier", "recipe")
|
||||
ID_TAIL = re.compile(r"\s*\{#([A-Za-z0-9][A-Za-z0-9_-]*)\}\s*$")
|
||||
@@ -200,6 +202,11 @@ def overlay_hash():
|
||||
return h.hexdigest()[:8] if any_ else "none"
|
||||
|
||||
|
||||
def more_line(n):
|
||||
"""The generated pointer under each rule: the command that prints the rule in full."""
|
||||
return "More: `sisi rule %d` (reasons, history, lessons behind it, how it is enforced)." % n
|
||||
|
||||
|
||||
def render():
|
||||
pre, rules = effective()
|
||||
try:
|
||||
@@ -212,7 +219,7 @@ def render():
|
||||
if pre.strip():
|
||||
parts.append(pre)
|
||||
for n, r in enumerate(rules, 1):
|
||||
parts.append("## %d. %s {#%s}\n\n%s" % (n, r["title"], r["id"], r["body"]))
|
||||
parts.append("## %d. %s {#%s}\n\n%s\n%s" % (n, r["title"], r["id"], r["body"], more_line(n)))
|
||||
return "\n\n".join(parts) + "\n"
|
||||
|
||||
|
||||
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
"""Request-time delivery: `sisi prompt` runs on the human's message (the tool's prompt-submission hook)
|
||||
and injects the matching "what done means" recipe and lessons as added context, so the agent does not
|
||||
have to remember to ask (`sisi done for`). Matching is the strict "likely to apply" test from
|
||||
retro.delivery; when nothing strictly matches, or the message is trivial, nothing is printed. Any
|
||||
error exits 0 silently: a hook must never block or fail a turn.
|
||||
"""
|
||||
import json, os, sys
|
||||
|
||||
from . import store
|
||||
|
||||
MAX_CHARS = 2000 # hard cap on the injected context, in characters
|
||||
RECIPE_MIN_SCORE = 6.0 # two title/applies-to word hits in `sisi done for`'s scoring; below it, no recipe
|
||||
_TRIVIAL = {"yes", "no", "y", "n", "ok", "okay", "sure", "yep", "nope", "thanks", "thank you",
|
||||
"go ahead", "do it", "continue", "stop", "wait", "hi", "hello"}
|
||||
|
||||
|
||||
def is_trivial(text):
|
||||
"""A message no recipe or lesson can help with: empty, a slash command, a bare yes/no, or a short
|
||||
question. A wrong injection on every message is worse than none."""
|
||||
t = " ".join((text or "").split())
|
||||
if len(t) < 15:
|
||||
return True
|
||||
if t.startswith("/"):
|
||||
return True
|
||||
if t.lower().rstrip(".! ") in _TRIVIAL:
|
||||
return True
|
||||
words = t.split()
|
||||
if len(words) < 3:
|
||||
return True
|
||||
if t.endswith("?") and len(words) <= 7: # a short question: the agent just answers it
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _best_recipe(query):
|
||||
"""The best-matching recipe, or None. Scoring starts from `sisi done for`'s own, but request-time
|
||||
delivery must be more precise than an answer the agent asked for: a recipe counts only when at
|
||||
least two distinct words of the request hit its title, applies-to or id (one generic word like
|
||||
"new" once outscored "release" + "tag" that way), and the leader must clear RECIPE_MIN_SCORE."""
|
||||
from . import retro, verifiers as V
|
||||
# Match on stems, as lesson matching does: "release" must meet "Releasing" and "tag" must meet
|
||||
# "Tagging", which done-for's prefix rule (both words longer than three letters) misses.
|
||||
toks = {retro._stem(t) for t in V._words(query)}
|
||||
|
||||
def stems_of(text):
|
||||
return {retro._stem(x) for x in V._words(text.replace("-", " "))}
|
||||
|
||||
scored = []
|
||||
for r in V.usable(V.load_recipes()):
|
||||
s, primary = 0.0, set()
|
||||
for text, w in ((r["title"], 3.0), (r["applies_to"], 3.0), (r["id"].replace("-", " "), 3.0), (r["body"], 0.2)):
|
||||
hit = toks & stems_of(text)
|
||||
s += w * len(hit)
|
||||
if w > 1.0:
|
||||
primary |= hit - retro.COMMON # generic words (new, fix, change) never carry a match alone
|
||||
if s > 0:
|
||||
scored.append((len(primary), s, r))
|
||||
if not scored:
|
||||
return None
|
||||
scored.sort(key=lambda x: (-x[0], -x[1], x[2]["id"]))
|
||||
primary, s, best = scored[0]
|
||||
return best if primary >= 2 and s >= RECIPE_MIN_SCORE else None
|
||||
|
||||
|
||||
def _done_means(recipe, retro):
|
||||
"""The recipe's must-be-true list in short form: its Done-means bullets, each cut at a word boundary."""
|
||||
from . import verifiers as V
|
||||
bullets = []
|
||||
for line in V._section(recipe["body"], "Done means").split("\n"):
|
||||
line = line.strip()
|
||||
if line.startswith("- "):
|
||||
bullets.append("- " + retro.word_cut(line[2:], 110))
|
||||
return bullets
|
||||
|
||||
|
||||
def build_context(query, session=None):
|
||||
"""The context to inject for one human request, or "" when nothing strictly matches. Lessons shown
|
||||
are recorded as listings at place 'prompt' (listed, not read)."""
|
||||
if is_trivial(query):
|
||||
return ""
|
||||
from . import retro
|
||||
recipe = _best_recipe(query)
|
||||
targets = (recipe["id"],) if recipe else ()
|
||||
part1, _part2 = retro.delivery(query, targets=targets)
|
||||
repo = retro.repo_of(os.getcwd())
|
||||
lesson_lines, ids = [], []
|
||||
for d in part1:
|
||||
row = d["row"]
|
||||
if not retro.display_line(retro._get(row, "short") or row["change"], repo):
|
||||
continue
|
||||
lesson_lines.append("- #%d: %s (full text: `sisi lessons show %d`)"
|
||||
% (row["id"], retro.heading_text(row, 120), row["id"]))
|
||||
ids.append(row["id"])
|
||||
if not recipe and not lesson_lines:
|
||||
return ""
|
||||
lines = ["sisi: for this request (from earlier agents' lessons and the recipe library; "
|
||||
"information to weigh, not commands):"]
|
||||
if recipe:
|
||||
lines.append("Done means — recipe `%s` (full text: `sisi done %s`):" % (recipe["id"], recipe["id"]))
|
||||
lines += _done_means(recipe, retro)
|
||||
if lesson_lines:
|
||||
lines.append("Lessons likely to apply:")
|
||||
lines += lesson_lines
|
||||
text = "\n".join(lines)
|
||||
while len(text) > MAX_CHARS and lesson_lines: # drop lesson lines before cutting the recipe
|
||||
lesson_lines.pop()
|
||||
ids = ids[:len(lesson_lines)]
|
||||
lines = lines[:len(lines) - 1]
|
||||
text = "\n".join(lines)
|
||||
if len(text) > MAX_CHARS:
|
||||
text = retro.word_cut(text, MAX_CHARS)
|
||||
if ids:
|
||||
retro.record_shown(ids, "prompt", session)
|
||||
return text
|
||||
|
||||
|
||||
def extract_prompt(payload):
|
||||
"""The human's request text from a hook payload, across the tools' documented field names."""
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
for k in ("prompt", "user_prompt", "userPrompt", "input", "text", "message"):
|
||||
v = payload.get(k)
|
||||
if isinstance(v, str) and v.strip():
|
||||
return v
|
||||
return None
|
||||
|
||||
|
||||
def main(args=()):
|
||||
"""Claude Code shape: UserPromptSubmit JSON on stdin, additionalContext JSON on stdout.
|
||||
Other tools go through hookio.prompt_main. Positional text (or --plain) prints the raw context,
|
||||
for trying it by hand. Never raises, never blocks."""
|
||||
try:
|
||||
args = list(args)
|
||||
plain = "--plain" in args
|
||||
args = [a for a in args if a != "--plain"]
|
||||
query, session = None, None
|
||||
if args:
|
||||
query = " ".join(args)
|
||||
plain = True
|
||||
else:
|
||||
raw = store.read_stdin() if sys.stdin is not None and not sys.stdin.isatty() else ""
|
||||
try:
|
||||
payload = json.loads(raw or "{}")
|
||||
except ValueError:
|
||||
return 0
|
||||
if not isinstance(payload, dict):
|
||||
return 0
|
||||
query = extract_prompt(payload)
|
||||
session = payload.get("session_id") if isinstance(payload.get("session_id"), str) else None
|
||||
cwd = payload.get("cwd")
|
||||
if isinstance(cwd, str) and os.path.isdir(cwd):
|
||||
os.chdir(cwd)
|
||||
if not query:
|
||||
return 0
|
||||
text = build_context(query, session=session)
|
||||
if not text:
|
||||
return 0
|
||||
if plain:
|
||||
sys.stdout.write(text + "\n")
|
||||
else:
|
||||
sys.stdout.write(json.dumps({"hookSpecificOutput": {
|
||||
"hookEventName": "UserPromptSubmit", "additionalContext": text}}) + "\n")
|
||||
except Exception as e: # fail open: a prompt hook must never fail a turn
|
||||
try:
|
||||
store.log_error("prompt", e)
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
"""`sisi rule`: every rule in the effective rulebook, how (or whether) it is enforced, and one rule in
|
||||
full with its reasons, history and the lessons folded into it. The generated rulebook prints
|
||||
`More: sisi rule N` under each rule, so every rule an agent sees names the command that explains it.
|
||||
|
||||
The enforcement wording is derived from code facts (which hooks are wired, whether the gate carries
|
||||
the question check, whether the floors exist), not from prose: if a mechanism is removed, this
|
||||
output stops claiming it. A rule with no entry below is reported honestly as depending on the agent.
|
||||
"""
|
||||
import os, sys
|
||||
|
||||
|
||||
def _gate_wired():
|
||||
try:
|
||||
from . import wiring
|
||||
return "Stop" in wiring.hook_cmds()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _floors():
|
||||
try:
|
||||
from . import contract, paths
|
||||
return os.path.exists(paths.canon("floors.json")) and callable(contract.floor_failures)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _question_gate():
|
||||
try:
|
||||
from . import gate
|
||||
return bool(gate.QUESTION_DIALOG_TOOLS) and callable(gate.ends_with_question)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _delivery_measured():
|
||||
try:
|
||||
from . import delivery
|
||||
return callable(delivery.record)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
_NOT = "not enforced: depends on the agent"
|
||||
|
||||
ENFORCEMENT = {
|
||||
"know-done": lambda: ("end-of-turn check sends the agent back (no contract on a large change)"
|
||||
if _gate_wired() else _NOT),
|
||||
"strongest-check": lambda: ("minimum rungs refused when the contract is checked; the choice of check depends on the agent"
|
||||
if _floors() else _NOT),
|
||||
"protect-working": lambda: ("contract invariants are run by the end-of-turn check; writing them depends on the agent"
|
||||
if _gate_wired() else _NOT),
|
||||
"feedback-as-amendment": lambda: _NOT,
|
||||
"decide-dont-ask": lambda: ("end-of-turn check: ending by asking in reply text instead of the question dialog is sent back"
|
||||
if _question_gate() else _NOT),
|
||||
"finish-by-verifying": lambda: ("end-of-turn check runs the checks and sends the agent back on a failure"
|
||||
if _gate_wired() else _NOT),
|
||||
"retro-every-time": lambda: ("retro required before stopping (end-of-turn check)"
|
||||
if _gate_wired() else _NOT),
|
||||
"deliver-quickly": lambda: ("not enforced: measured only (`sisi time`); a slower learned change is flagged for reversal"
|
||||
if _delivery_measured() else _NOT),
|
||||
}
|
||||
|
||||
|
||||
def enforcement_for(rule_id):
|
||||
fn = ENFORCEMENT.get(rule_id)
|
||||
if fn is None:
|
||||
return _NOT
|
||||
try:
|
||||
return fn()
|
||||
except Exception:
|
||||
return _NOT
|
||||
|
||||
|
||||
def _table(rules):
|
||||
print("The rules every agent here works under, and what makes each one happen.")
|
||||
print("One rule in full (reasons, history, lessons behind it): `sisi rule N`.\n")
|
||||
w_id = max(len(r["id"]) for r in rules)
|
||||
w_title = max(len(r["title"]) for r in rules)
|
||||
for n, r in enumerate(rules, 1):
|
||||
print("%-3d %-*s %-*s %s" % (n, w_id, r["id"], w_title, r["title"], enforcement_for(r["id"])))
|
||||
return 0
|
||||
|
||||
|
||||
def _why_paragraphs(body):
|
||||
out, cur = [], []
|
||||
for line in (body or "").split("\n") + [""]:
|
||||
if line.strip():
|
||||
cur.append(line)
|
||||
elif cur:
|
||||
para = "\n".join(cur)
|
||||
if para.lstrip().startswith("Why:"):
|
||||
out.append(para)
|
||||
cur = []
|
||||
return out
|
||||
|
||||
|
||||
def _folded_lessons(rule_id):
|
||||
try:
|
||||
from . import retro
|
||||
if not os.path.exists(retro.db_path()):
|
||||
return []
|
||||
con = retro.connect()
|
||||
try:
|
||||
return [dict(r) for r in con.execute(
|
||||
"SELECT * FROM lessons WHERE folded_into=? ORDER BY id", (rule_id,))]
|
||||
finally:
|
||||
con.close()
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def _history(rule_id):
|
||||
"""Learning rounds that changed this rule, from the cycle records' changed-files evidence."""
|
||||
try:
|
||||
from . import cycle
|
||||
out = []
|
||||
suffix = "rules/%s.md" % rule_id
|
||||
for rec in cycle.cycle_records():
|
||||
changed = rec.get("changed_files") or {}
|
||||
if any(k.endswith(suffix) for k in changed):
|
||||
line = "%s (%s): %s" % (rec.get("id"), (rec.get("ts") or "")[:10], rec.get("summary") or "")
|
||||
if rec.get("reverted"):
|
||||
line += " (reverted)"
|
||||
out.append(line)
|
||||
return out
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
_ORIGIN = {"base": "base text, from the product rulebook (canon/core.md)",
|
||||
"replaced": "your overlay replaces the base rule (`sisi overlay diff` shows the difference)",
|
||||
"added": "added by your overlay; there is no base rule with this id"}
|
||||
|
||||
|
||||
def _detail(n, rule):
|
||||
from . import retro
|
||||
print("Rule %d: %s {#%s}\n" % (n, rule["title"], rule["id"]))
|
||||
print(rule["body"].strip("\n"))
|
||||
why = _why_paragraphs(rule["body"])
|
||||
if why:
|
||||
print("\nWhy, in short:")
|
||||
for p in why:
|
||||
print(" " + "\n ".join(p.split("\n")))
|
||||
print("\nHow it is enforced: %s." % enforcement_for(rule["id"]).rstrip("."))
|
||||
print("Origin: %s." % _ORIGIN.get(rule.get("origin") or "base", rule.get("origin") or "base"))
|
||||
hist = _history(rule["id"])
|
||||
print("\nHistory: " + ("no learning round has changed this rule." if not hist else ""))
|
||||
for h in hist:
|
||||
print(" - " + h)
|
||||
lessons = _folded_lessons(rule["id"])
|
||||
if lessons:
|
||||
print("\nLessons folded into this rule:")
|
||||
for r in lessons:
|
||||
date = (retro._get(r, "last_seen") or retro._get(r, "applied_at") or "")[:10]
|
||||
print(" - #%d (%s, seen %d times): %s (full text: `sisi lessons show %d`)"
|
||||
% (r["id"], date or "undated", r["count"] or 0,
|
||||
retro.heading_text(r, 140), r["id"]))
|
||||
examples = [r for r in lessons if (r.get("moment") or "").strip()]
|
||||
if examples:
|
||||
print("\nExamples (what actually happened):")
|
||||
for r in examples[:3]:
|
||||
print(" - %s (lesson %d; `sisi lessons show %d`)"
|
||||
% (retro.word_cut(r["moment"], 160), r["id"], r["id"]))
|
||||
else:
|
||||
print("\nLessons folded into this rule: none yet.")
|
||||
return 0
|
||||
|
||||
|
||||
def main(args):
|
||||
from . import overlay
|
||||
args = [a for a in args if a not in ("-h", "--help")]
|
||||
try:
|
||||
_pre, rules = overlay.effective()
|
||||
except Exception as e:
|
||||
print("sisi rule: %s" % e, file=sys.stderr)
|
||||
return 1
|
||||
if not args:
|
||||
return _table(rules)
|
||||
if len(args) != 1:
|
||||
print("usage: sisi rule [N|ID]", file=sys.stderr)
|
||||
return 1
|
||||
want = args[0]
|
||||
if want.isdigit():
|
||||
n = int(want)
|
||||
if 1 <= n <= len(rules):
|
||||
return _detail(n, rules[n - 1])
|
||||
else:
|
||||
for n, r in enumerate(rules, 1):
|
||||
if r["id"] == want:
|
||||
return _detail(n, r)
|
||||
print("sisi rule: no rule %r (see `sisi rule`)" % want, file=sys.stderr)
|
||||
return 1
|
||||
+8
-4
@@ -236,6 +236,7 @@ def hook_cmds():
|
||||
gate_to = int(store.config()["gate"].get("budget_s", 120)) + 30
|
||||
watch = hookjson.fail_open_command(paths.launcher(), "watch", "claude-code")
|
||||
return {"SessionStart": (hookjson.fail_open_command(paths.launcher(), "tick", "claude-code"), 10),
|
||||
"UserPromptSubmit": (hookjson.fail_open_command(paths.launcher(), "prompt", "claude-code"), 10),
|
||||
"Stop": (hookjson.fail_open_command(paths.launcher(), "gate", "claude-code"), gate_to),
|
||||
"SubagentStop": (hookjson.fail_open_command(paths.launcher(), "gate", "claude-code", True), 30),
|
||||
"PreToolUse": (watch, 60),
|
||||
@@ -325,7 +326,7 @@ def remove_hooks(obj):
|
||||
hooks = obj.get("hooks")
|
||||
if not isinstance(hooks, dict):
|
||||
return False
|
||||
for ev, sub in (("SessionStart", "tick"), ("Stop", "gate"), ("SubagentStop", "gate"),
|
||||
for ev, sub in (("SessionStart", "tick"), ("UserPromptSubmit", "prompt"), ("Stop", "gate"), ("SubagentStop", "gate"),
|
||||
("PreToolUse", "watch"), ("PostToolUse", "watch")):
|
||||
groups = hooks.get(ev)
|
||||
if not isinstance(groups, list):
|
||||
@@ -353,7 +354,8 @@ def remove_hooks(obj):
|
||||
def _hooks_wired(obj):
|
||||
hooks = obj.get("hooks") if isinstance(obj, dict) else None
|
||||
out = {}
|
||||
for ev, sub, name in (("SessionStart", "tick", "tick"), ("Stop", "gate", "gate"), ("SubagentStop", "gate", "subagent"),
|
||||
for ev, sub, name in (("SessionStart", "tick", "tick"), ("UserPromptSubmit", "prompt", "prompt"),
|
||||
("Stop", "gate", "gate"), ("SubagentStop", "gate", "subagent"),
|
||||
("PreToolUse", "watch", "pre"), ("PostToolUse", "watch", "post")):
|
||||
groups = hooks.get(ev) if isinstance(hooks, dict) else None
|
||||
sub, key = sub, name
|
||||
@@ -590,7 +592,7 @@ def uninstall():
|
||||
elif data is not None:
|
||||
try:
|
||||
text = data.decode("utf-8")
|
||||
subs = {"SessionStart": "tick", "Stop": "gate", "SubagentStop": "gate",
|
||||
subs = {"SessionStart": "tick", "UserPromptSubmit": "prompt", "Stop": "gate", "SubagentStop": "gate",
|
||||
"PreToolUse": "watch", "PostToolUse": "watch"}
|
||||
orig = _read(os.path.join(_idir(), "backups", ent["backup"])) if ent and ent["backup"] else None
|
||||
drop_hooks, _dv = hookjson.backup_drop_flags(
|
||||
@@ -645,10 +647,11 @@ def doctor():
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
hw = {"tick": False, "gate": False, "subagent": False, "pre": False, "post": False}
|
||||
missing = [n for n, ok in (("import line", _claude_md_wired(cm)), ("tick hook", hw["tick"]),
|
||||
("prompt hook", hw.get("prompt", False)),
|
||||
("gate hook", hw["gate"]), ("subagent hook", hw["subagent"]),
|
||||
("watch-before hook", hw["pre"]), ("watch-after hook", hw["post"])) if not ok]
|
||||
rows.append({"tool": "claude-code", "status": "not wired" if missing else "wired",
|
||||
"detail": ("missing: " + ", ".join(missing)) if missing else "import + tick + gate registered",
|
||||
"detail": ("missing: " + ", ".join(missing)) if missing else "import + tick + prompt + gate registered",
|
||||
"blocking_hook": "yes (Stop)" if hw["gate"] else "no",
|
||||
"rulebook": not missing and _claude_md_wired(cm), "tick": hw["tick"],
|
||||
"enforcement": "blocks", "action": None})
|
||||
@@ -735,6 +738,7 @@ def doctor_claude():
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
hw = {"tick": False, "gate": False, "subagent": False, "pre": False, "post": False}
|
||||
missing = [n for n, ok in (("import line", _claude_md_wired(cm)), ("tick hook", hw["tick"]),
|
||||
("prompt hook", hw.get("prompt", False)),
|
||||
("gate hook", hw["gate"]), ("subagent hook", hw["subagent"]),
|
||||
("watch-before hook", hw["pre"]), ("watch-after hook", hw["post"])) if not ok]
|
||||
return ", ".join(missing)
|
||||
|
||||
@@ -355,6 +355,36 @@ class MergePropertyTests(AdapterBase):
|
||||
self.cycle()
|
||||
|
||||
|
||||
class PromptHookTests(AdapterBase):
|
||||
def test_prompt_hooks_registered_and_removed_per_tool(self):
|
||||
cases = {"codex": (".codex", ".codex/hooks.json", "UserPromptSubmit", False),
|
||||
"gemini": (".gemini", ".gemini/settings.json", "BeforeAgent", False),
|
||||
"copilot": (".copilot", ".copilot/hooks/sisi.json", "userPromptSubmitted", True)}
|
||||
for name, (d, f, ev, flat) in cases.items():
|
||||
with self.subTest(tool=name):
|
||||
self.fresh_home()
|
||||
os.makedirs(self.path(d), exist_ok=True)
|
||||
if name == "copilot":
|
||||
os.makedirs(self.path(".copilot", "hooks"), exist_ok=True)
|
||||
self.cycle() # install x2 idempotent, uninstall exact, prompt hook included
|
||||
wiring.install()
|
||||
obj = json.load(open(self.path(f)))
|
||||
cmds = [e.get("bash") or e.get("command") for e in obj["hooks"][ev]] if flat else \
|
||||
[h["command"] for g in obj["hooks"][ev] for h in g["hooks"]]
|
||||
self.assertTrue(any("prompt --tool %s" % name in (c or "") for c in cmds), (name, ev, cmds))
|
||||
self.assertEqual(self.rows()[name]["status"], "wired")
|
||||
wiring.uninstall()
|
||||
|
||||
def test_pi_extension_carries_prompt_call(self):
|
||||
self.assertIn(b'"prompt", "--tool", "pi"', adapters._pi_extension())
|
||||
|
||||
def test_no_prompt_hook_where_injection_is_unconfirmed(self):
|
||||
for a in adapters.ADAPTERS:
|
||||
spec = a.spec() if hasattr(a, "spec") else {}
|
||||
if a.name in ("qwen", "cursor"):
|
||||
self.assertFalse(any(s.get("sub") == "prompt" for s in spec.values()), a.name)
|
||||
|
||||
|
||||
class GeneratedScriptTests(AdapterBase):
|
||||
def test_opencode_plugin_parses_as_javascript(self):
|
||||
node = shutil.which("node")
|
||||
|
||||
@@ -463,8 +463,10 @@ class WidenedPropertyTests(SafetyBase):
|
||||
json.dump(obj, open(p, "w"), indent=2)
|
||||
wiring.install()
|
||||
raw = open(p, "rb").read()
|
||||
# tick + gate + subagent gate + watch (registered for both tool events) = at most 5
|
||||
self.assertLessEqual(raw.count(b"--tool " + tool.encode()), 5, (tool, raw))
|
||||
# exactly one registration per event in the tool's spec (tick, prompt where wired,
|
||||
# gate, subagent gate, watch before/after), however many duplicates were planted
|
||||
adapter = next(a for a in adapters.ADAPTERS if a.name == tool)
|
||||
self.assertLessEqual(raw.count(b"--tool " + tool.encode()), len(adapter.spec()), (tool, raw))
|
||||
d2 = json.load(open(p))
|
||||
for ev, entries in d2.get("hooks", {}).items():
|
||||
flat = [e.get("bash") or e.get("command") for e in entries if isinstance(e, dict)]
|
||||
|
||||
@@ -160,14 +160,15 @@ class OverlayTests(PersonalCase):
|
||||
def test_size_budget_refuses_and_changes_nothing(self):
|
||||
self.ok("build-canon")
|
||||
gen0, log0 = self.generated(), self.git_log()
|
||||
big = rule_file("Big", "\n".join("line %d" % i for i in range(150)))
|
||||
room = overlay.MAX_LINES - len(gen0.splitlines())
|
||||
big = rule_file("Big", "\n".join("line %d" % i for i in range(room + 30)))
|
||||
r = self.sisi("overlay", "add-rule", "--id", "big", "-", stdin=big)
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("budget", r.stderr)
|
||||
self.assertEqual((self.generated(), self.git_log()), (gen0, log0))
|
||||
self.assertFalse(os.path.exists(os.path.join(self.data, "overlay", "rules", "big.md")))
|
||||
# fits after something is made shorter or replaced
|
||||
fill = rule_file("Fill", "\n".join("x%d" % i for i in range(80)))
|
||||
fill = rule_file("Fill", "\n".join("x%d" % i for i in range(room - 20)))
|
||||
self.ok("overlay", "add-rule", "--id", "fill", "-", stdin=fill)
|
||||
self.assertLessEqual(len(self.generated().splitlines()), overlay.MAX_LINES)
|
||||
r = self.sisi("overlay", "add-rule", "--id", "more", "-", stdin=rule_file("More", "\n".join("y%d" % i for i in range(30))))
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""`sisi prompt`: request-time delivery of the matching recipe and lessons on the human's message.
|
||||
|
||||
The hook must never block or fail a turn, must stay silent when nothing strictly matches, and must be
|
||||
fast. Matching reuses the strict "likely to apply" test from retro.delivery; the labelled set below
|
||||
phrases requests in different words from the lessons so only the when-terms can bridge them.
|
||||
"""
|
||||
import json, os, statistics, time, unittest
|
||||
from support import *
|
||||
from sisi import retro
|
||||
|
||||
|
||||
def fields(**kw):
|
||||
f = dict(aim="verified", change_kind="recipe", target="release",
|
||||
moment="the tagged build shipped with a changelog for the previous version",
|
||||
cause="nobody compared the tag, the manifest version and the changelog before publishing",
|
||||
change="Before publishing, check the tag, the manifest version and the changelog agree",
|
||||
when="release, tagging, version, publish, changelog, package, ship it",
|
||||
short="Check tag, version and changelog agree before publishing.")
|
||||
f.update(kw)
|
||||
return f
|
||||
|
||||
|
||||
class PromptCase(SisiCase):
|
||||
def mk(self, **kw):
|
||||
con = retro.connect()
|
||||
try:
|
||||
lid = retro.new_lesson(con, fields(**kw), self.proj, None)
|
||||
con.commit()
|
||||
return lid
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def prompt(self, payload, tool=None):
|
||||
args = ["prompt"] + (["--tool", tool] if tool else [])
|
||||
return self.sisi(*args, stdin=json.dumps(payload))
|
||||
|
||||
|
||||
class PromptHookTests(PromptCase):
|
||||
def test_release_request_gets_recipe_and_lesson_with_full_text_commands(self):
|
||||
lid = self.mk()
|
||||
r = self.prompt({"prompt": "cut a new release and tag it", "session_id": "s1", "cwd": self.proj})
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
out = json.loads(r.stdout)
|
||||
ctx = out["hookSpecificOutput"]["additionalContext"]
|
||||
self.assertEqual(out["hookSpecificOutput"]["hookEventName"], "UserPromptSubmit")
|
||||
self.assertIn("release", ctx)
|
||||
self.assertIn("sisi done release", ctx)
|
||||
self.assertIn("Check tag, version and changelog agree", ctx)
|
||||
self.assertIn("sisi lessons show %d" % lid, ctx)
|
||||
from sisi import prompt as P
|
||||
self.assertLessEqual(len(ctx), P.MAX_CHARS)
|
||||
|
||||
def test_listing_is_counted(self):
|
||||
lid = self.mk()
|
||||
self.prompt({"prompt": "cut a new release and tag it", "session_id": "s1", "cwd": self.proj})
|
||||
con = retro.connect()
|
||||
try:
|
||||
self.assertGreaterEqual(retro.listed_count(con, lid), 1)
|
||||
places = [r[0] for r in con.execute("SELECT place FROM impressions WHERE lesson_id=?", (lid,))]
|
||||
self.assertIn("prompt", places)
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def test_nothing_for_trivial_or_unmatched_messages(self):
|
||||
self.mk()
|
||||
for text in ("yes", "no thanks", "/clear", "what time is it?", "ok",
|
||||
"rename the local variable in the slug helper to something clearer"):
|
||||
with self.subTest(text=text):
|
||||
r = self.prompt({"prompt": text, "session_id": "s1", "cwd": self.proj})
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout.strip(), "")
|
||||
|
||||
def test_garbage_input_exits_zero_silently(self):
|
||||
for stdin in ("not json", "", "[]", '{"prompt": 42}'):
|
||||
with self.subTest(stdin=stdin):
|
||||
r = self.sisi("prompt", stdin=stdin)
|
||||
self.assertEqual(r.returncode, 0)
|
||||
|
||||
def test_other_tool_shapes(self):
|
||||
self.mk()
|
||||
payload = {"prompt": "cut a new release and tag it", "session_id": "s1", "cwd": self.proj}
|
||||
r = self.prompt(payload, tool="copilot")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertIn("sisi done release", json.loads(r.stdout)["additionalContext"])
|
||||
r = self.prompt(payload, tool="gemini")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertIn("sisi done release",
|
||||
json.loads(r.stdout)["hookSpecificOutput"]["additionalContext"])
|
||||
r = self.prompt(payload, tool="pi")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertIn("sisi done release", r.stdout)
|
||||
|
||||
def test_fast_enough_median_of_twenty(self):
|
||||
skip_timing_if_busy(self)
|
||||
self.mk()
|
||||
payload = json.dumps({"prompt": "cut a new release and tag it", "session_id": "s1", "cwd": self.proj})
|
||||
times = []
|
||||
for _ in range(20):
|
||||
t0 = time.time()
|
||||
r = self.sisi_proc("prompt", stdin=payload)
|
||||
times.append(time.time() - t0)
|
||||
self.assertEqual(r.returncode, 0)
|
||||
med = statistics.median(times)
|
||||
self.assertLess(med, 1.0, "median prompt-hook run %.3fs over 20 runs" % med)
|
||||
|
||||
|
||||
class LabelledMatchingTests(PromptCase):
|
||||
"""Requests rephrased away from the lessons' own wording. A hit means the lesson's short line (or
|
||||
the recipe it targets) is in the injected context; a false match means context was injected for a
|
||||
request it does not apply to."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.release_id = self.mk()
|
||||
self.csv_id = self.mk(
|
||||
target=None, change_kind="rule",
|
||||
moment="a spreadsheet export broke on a field containing a newline",
|
||||
cause="rows were joined by hand instead of with a quoting writer",
|
||||
change="Write delimited files with a quoting writer so embedded newlines survive",
|
||||
when="csv, tsv, spreadsheet, tabular data, export, delimited file, quoting",
|
||||
short="Use a quoting writer for delimited exports.")
|
||||
|
||||
def ctx(self, text):
|
||||
from sisi import prompt as P
|
||||
return P.build_context(text, session="labelled")
|
||||
|
||||
def test_labelled_set(self):
|
||||
# A hit: the expected lesson's short line is injected. A false match: either lesson is
|
||||
# injected for a request it does not apply to. (A recipe for the request's own kind of work
|
||||
# is the feature working, not a false match, so it is measured separately below.)
|
||||
release_short = "Check tag, version and changelog agree"
|
||||
csv_short = "Use a quoting writer"
|
||||
should = [
|
||||
("cut a new release and tag it", release_short),
|
||||
("publish the next version to the package index please", release_short),
|
||||
("ship it: bump the version and push the tag", release_short),
|
||||
("export the table as a spreadsheet file", csv_short),
|
||||
("write these rows out as a delimited file for the spreadsheet", csv_short),
|
||||
]
|
||||
should_not = [
|
||||
"rename the helper that formats release notes headings in the docs",
|
||||
"why is the test suite slow on this machine",
|
||||
"add a dark mode toggle to the settings page",
|
||||
"fix the off-by-one in the pagination control",
|
||||
"explain how the quoting in this shell one-liner works",
|
||||
]
|
||||
hits = sum(1 for t, want in should if want in self.ctx(t))
|
||||
false_alarms = sum(1 for t in should_not
|
||||
if release_short in self.ctx(t) or csv_short in self.ctx(t))
|
||||
self.assertEqual((hits, false_alarms), (len(should), 0),
|
||||
"lesson hits %d/%d, false matches %d/%d" % (hits, len(should), false_alarms, len(should_not)))
|
||||
# the release request also names the right recipe, not a neighbour
|
||||
self.assertIn("sisi done release", self.ctx("cut a new release and tag it"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Rule 5 enforcement: ending a turn by asking the human a question in reply text sends the agent back
|
||||
once, where a question dialog exists and was not used in that turn (Claude Code)."""
|
||||
import json, os, unittest
|
||||
from support import *
|
||||
from sisi import gate
|
||||
|
||||
ASK = [
|
||||
"All checks pass. Should I also update the changelog?",
|
||||
"Done. Do you want the button blue or grey?",
|
||||
"The migration is ready.\n\nWhich name should the new column have?",
|
||||
"Implemented and verified. Shall I open the pull request now?",
|
||||
"Fixed. What do you think of the new layout?",
|
||||
"Tests are green. Would you like me to remove the old parser too?",
|
||||
"Ready when you are. Can I go ahead and delete the legacy table?",
|
||||
"The export works. Do we need the legacy format as well?",
|
||||
"All set. Is Thursday still the target for this?",
|
||||
"The build passes. Should we ship it?",
|
||||
]
|
||||
|
||||
NOT_ASK = [
|
||||
"All checks pass. The changelog is updated.",
|
||||
"Who wouldn't want a faster build?",
|
||||
"The issue asked: \"why does it crash on startup?\" and the fix answers it.",
|
||||
"Done.\n\n```\nresult = value if ready else fallback # what about None?\n```",
|
||||
"> Should we cache this?\n\nNo: the data changes on every request, so I left it uncached.",
|
||||
"Fixed the `a ? b : c` case and the suite passes.",
|
||||
"What could possibly go wrong? Quite a lot, so the change is behind a flag.",
|
||||
"The report ends with the customer's words: \"can you fix it by Friday?\"",
|
||||
"Verified: rung 3, 41 examples, all passing.",
|
||||
"Why did it fail? Because the fixture was stale; it is regenerated now and checks pass.",
|
||||
"Shipped. The remaining question of naming is recorded as an assumption in the contract.",
|
||||
"Isn't it obvious in hindsight? The guard was inverted; fixed and pinned by a test.",
|
||||
]
|
||||
|
||||
|
||||
class DetectionTests(unittest.TestCase):
|
||||
def test_labelled_set(self):
|
||||
hits = [t for t in ASK if gate.ends_with_question(t)]
|
||||
alarms = [t for t in NOT_ASK if gate.ends_with_question(t)]
|
||||
self.assertEqual(len(hits), len(ASK), "missed: %r" % [t for t in ASK if t not in hits])
|
||||
self.assertEqual(alarms, [], "false alarms: %r" % alarms)
|
||||
|
||||
|
||||
def transcript(path, final_text, dialog=False):
|
||||
recs = [
|
||||
{"type": "user", "timestamp": "2026-01-01T00:00:00Z",
|
||||
"message": {"role": "user", "content": "please fix the widget"}},
|
||||
]
|
||||
if dialog:
|
||||
recs.append({"type": "assistant", "timestamp": "2026-01-01T00:01:00Z",
|
||||
"message": {"role": "assistant", "content": [
|
||||
{"type": "tool_use", "name": "AskUserQuestion", "input": {"questions": []}}]}})
|
||||
recs.append({"type": "assistant", "timestamp": "2026-01-01T00:02:00Z",
|
||||
"message": {"role": "assistant", "content": [{"type": "text", "text": final_text}]}})
|
||||
with open(path, "w") as f:
|
||||
for r in recs:
|
||||
f.write(json.dumps(r) + "\n")
|
||||
|
||||
|
||||
class GateQuestionTests(SisiCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.git_init()
|
||||
self.tp = os.path.join(self.tmp, "t.jsonl")
|
||||
os.environ["SISI_TOOL"] = "claude-code"
|
||||
|
||||
def payload(self, **kw):
|
||||
p = {"session_id": "qsess", "cwd": self.proj, "transcript_path": self.tp}
|
||||
p.update(kw)
|
||||
return p
|
||||
|
||||
def test_asking_in_prose_sends_back_once(self):
|
||||
transcript(self.tp, "Fixed and verified. Should I also update the docs?")
|
||||
action, msg = gate.decide(self.payload())
|
||||
self.assertEqual(action, "block", msg)
|
||||
self.assertIn("dialog", msg.lower())
|
||||
action2, _ = gate.decide(self.payload())
|
||||
self.assertEqual(action2, "allow", "second stop on the same message must not trap the session")
|
||||
|
||||
def test_dialog_used_in_turn_is_exempt(self):
|
||||
transcript(self.tp, "Fixed and verified. Should I also update the docs?", dialog=True)
|
||||
action, _ = gate.decide(self.payload())
|
||||
self.assertEqual(action, "allow")
|
||||
|
||||
def test_plain_finish_is_allowed(self):
|
||||
transcript(self.tp, "Fixed and verified. All checks pass.")
|
||||
action, _ = gate.decide(self.payload())
|
||||
self.assertEqual(action, "allow")
|
||||
|
||||
def test_subagent_is_exempt(self):
|
||||
transcript(self.tp, "Fixed and verified. Should I also update the docs?")
|
||||
action, _ = gate.decide(self.payload(agent_id="agent-1"))
|
||||
self.assertEqual(action, "allow")
|
||||
|
||||
def test_tool_without_dialog_is_exempt(self):
|
||||
os.environ["SISI_TOOL"] = "cursor"
|
||||
transcript(self.tp, "Fixed and verified. Should I also update the docs?")
|
||||
action, _ = gate.decide(self.payload())
|
||||
self.assertEqual(action, "allow")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,96 @@
|
||||
"""`sisi rule`: every rule points at its own detail, and the enforcement column comes from code facts."""
|
||||
import json, os, unittest
|
||||
from support import *
|
||||
from sisi import overlay, retro
|
||||
|
||||
|
||||
class RuleTableTests(SisiCase):
|
||||
def test_table_lists_every_rule_with_enforcement(self):
|
||||
r = self.sisi("rule")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
_, rules = overlay.base_rules()
|
||||
for rule in rules:
|
||||
self.assertIn(rule["id"], r.stdout)
|
||||
self.assertIn(rule["title"], r.stdout)
|
||||
self.assertIn("not enforced", r.stdout) # at least one rule is honestly only an intention
|
||||
|
||||
def test_every_base_rule_has_an_enforcement_entry(self):
|
||||
from sisi import rulecmd
|
||||
_, rules = overlay.base_rules()
|
||||
for rule in rules:
|
||||
self.assertIn(rule["id"], rulecmd.ENFORCEMENT, rule["id"])
|
||||
self.assertTrue(rulecmd.enforcement_for(rule["id"]).strip())
|
||||
|
||||
def test_enforcement_wording_names_real_mechanisms(self):
|
||||
from sisi import rulecmd
|
||||
self.assertIn("end-of-turn", rulecmd.enforcement_for("know-done"))
|
||||
self.assertIn("retro", rulecmd.enforcement_for("retro-every-time").lower())
|
||||
ask = rulecmd.enforcement_for("decide-dont-ask").lower()
|
||||
self.assertTrue("dialog" in ask or "asking" in ask, ask)
|
||||
|
||||
|
||||
class RuleDetailTests(SisiCase):
|
||||
def test_rule_by_number_and_by_id(self):
|
||||
by_num = self.sisi("rule", "5")
|
||||
by_id = self.sisi("rule", "decide-dont-ask")
|
||||
self.assertEqual(by_num.returncode, 0, by_num.stderr)
|
||||
self.assertEqual(by_id.returncode, 0, by_id.stderr)
|
||||
for out in (by_num.stdout, by_id.stdout):
|
||||
self.assertIn("Decide, do not ask", out)
|
||||
self.assertIn("Why:", out)
|
||||
self.assertIn("AskUserQuestion", out)
|
||||
self.assertIn("base", out.lower())
|
||||
|
||||
def test_unknown_rule_fails(self):
|
||||
self.assertEqual(self.sisi("rule", "no-such-rule").returncode, 1)
|
||||
self.assertEqual(self.sisi("rule", "99").returncode, 1)
|
||||
|
||||
def test_folded_lessons_are_shown_with_show_command(self):
|
||||
con = retro.connect()
|
||||
try:
|
||||
lid = retro.new_lesson(con, dict(
|
||||
aim="hands-off", change_kind="rule", target=None,
|
||||
moment="the agent buried a naming question at the end of a long report",
|
||||
cause="asking in prose felt quicker than opening the dialog",
|
||||
change="Ask naming questions through the dialog with options",
|
||||
when="naming, question, dialog, options, ask the human, choice",
|
||||
short="Ask through the dialog, with options."), self.proj, None)
|
||||
con.execute("UPDATE lessons SET folded_into='decide-dont-ask', count=3 WHERE id=?", (lid,))
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
r = self.sisi("rule", "decide-dont-ask")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertIn("Ask through the dialog, with options.", r.stdout)
|
||||
self.assertIn("sisi lessons show %d" % lid, r.stdout)
|
||||
self.assertIn("buried a naming question", r.stdout) # the moment, as the example
|
||||
|
||||
def test_overlay_replacement_is_named_as_overlay(self):
|
||||
d = os.path.join(self.data, "overlay", "rules")
|
||||
os.makedirs(d, exist_ok=True)
|
||||
with open(os.path.join(d, "deliver-quickly.md"), "w") as f:
|
||||
f.write("## Deliver quickly\n\nReplacement body written by the owner.\n\nWhy: a test.\n")
|
||||
r = self.sisi("rule", "deliver-quickly")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertIn("Replacement body", r.stdout)
|
||||
self.assertIn("overlay", r.stdout.lower())
|
||||
|
||||
|
||||
class MoreLineTests(SisiCase):
|
||||
def test_generated_rulebook_points_each_rule_at_its_detail(self):
|
||||
text = overlay.render()
|
||||
_, rules = overlay.effective()
|
||||
for n, rule in enumerate(rules, 1):
|
||||
self.assertIn("More: `sisi rule %d`" % n, text, rule["id"])
|
||||
lines, chars = overlay.size(text)
|
||||
self.assertLessEqual(lines, overlay.MAX_LINES)
|
||||
self.assertLessEqual(chars, overlay.MAX_CHARS)
|
||||
|
||||
def test_help_names_rule_and_prompt(self):
|
||||
out = self.sisi("help").stdout
|
||||
self.assertIn("sisi rule", out)
|
||||
self.assertIn("sisi prompt", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user