diff --git a/canon/guard.json b/canon/guard.json index 00f4e07..0e12c22 100644 --- a/canon/guard.json +++ b/canon/guard.json @@ -35,6 +35,18 @@ "review", "docs" ], + "output_filters": [ + "head", + "tail", + "grep", + "wc", + "sort", + "uniq", + "cut", + "tr", + "cat", + "less" + ], "build_words": [ "change", "fix", diff --git a/docs/design.md b/docs/design.md index 8a2f59a..eb20a78 100644 --- a/docs/design.md +++ b/docs/design.md @@ -363,8 +363,14 @@ session's own model exists. Every entry point fails open. only the outcome and the check. A worker other than the router's pick is allowed and recorded (`chosen_against_route`); `sisi workers` shows how often and how those turned out (too few under five). `sisi route --retry-of ID` keeps the same worker with an instruction to improve the brief after the first - rejection and moves to a stronger one (judged record, else benchmark standing, else host-native) after a - second. + rejection and then moves to a worker whose evidence is strictly better (`routing.retry_choice`: the cheapest + capable one with better evidence, else the strongest known usable one) after a second. +- **One before-tool path, one refusal at a time.** `sisi/watch.py` runs, for every tool: workers and subagents + are exempt from all of it; then the contract guard (a call that would change a project file, or delegate a + build, with no valid unit: rule 3); then the delegation guard (a model is named and is not the main thread's + own; a routing decision exists); then the direct-work budget. The agent sees only the first refusal in that + order, so an agent told to delegate is never refused afterwards for a contract it was not told about. A + refused call is not counted by the meter. Every stage fails open on its own. - **Repeat failure.** The fourth identical failing shell command (whitespace-normalised) with no file changed in between is refused once (rule 5). - **Unavailable workers.** A limit, quota, login or connection failure arriving as a delegation result or as a diff --git a/docs/developing.md b/docs/developing.md index 7cef63f..43c72da 100644 --- a/docs/developing.md +++ b/docs/developing.md @@ -25,9 +25,13 @@ Before any release that touches the hooks or the rulebook, run python3 tools/live_orchestration_check.py -It starts the host's command-line tool headless with its least expensive model in two small temporary +It starts the host's command-line tool headless with its least expensive model in small temporary projects, with the hooks from this checkout and a temporary `SISI_DATA` and `SISI_STATE` (the real sisi data is -never read or written; the script asserts that it did not change). Scenario 1 asserts that the meter refused a +never read or written; the script asserts that it did not change). Scenario 3 starts from a project with no +open unit and a task that needs more than six calls, with a witness hook recording whether a valid unit stood +behind each call: no file may change before one does, and the agent must meet the guards in the order the rules +give (the contract before the budget), each refusal in at most twelve lines. `--model NAME` sets the main +thread's model. Scenario 1 asserts that the meter refused a tool call with its message, that the session then ran `sisi route` and delegated with a named model or recorded a reason with `sisi unit direct`, and that the ledger or events hold the matching record. Scenario 2 uses a fake provider that always answers with a quota error and a reset time: the provider must be marked down until that diff --git a/docs/workers.md b/docs/workers.md index e67996c..15a129a 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -99,7 +99,11 @@ the host's own tool is written to the ledger by the hooks as a pending run with completed when it returns; `sisi delegate judge ID --outcome O --check C` then needs nothing else. A worker other than the router's pick is recorded as an override, and `sisi workers` ends with one line on how often and how they turned out. After a rejection `sisi delegate judge` prints `sisi route --retry-of ID`: the same -worker with a better brief first, a stronger one after a second rejection. +worker with a better brief first, then a worker whose evidence is strictly better (`routing.retry_choice`, the +same ladder the capability routing uses). `sisi route --kind K` takes only the ledger's kinds (`impl`, `impl-multi`, +`edit`, `tests`, `debug` build; `read`, `search`, `research`, `review`, `docs` do not; the list is data in +canon/guard.json) and names them when given another; the decision is kept in the session's orchestration meter, +which is also where the contract guard reads it to tell a build delegation from a read. When a worker fails for a reason that is not about its work (a quota, limit, login or connection failure, arriving as a delegation result or as a host notice), the hooks record it down until the reset time in the diff --git a/sisi/unitguard.py b/sisi/unitguard.py index 1c52487..fbe48e2 100644 --- a/sisi/unitguard.py +++ b/sisi/unitguard.py @@ -323,9 +323,10 @@ def bound_fresh(sess, project, c): def _ignored(rel): import fnmatch - p = rel.replace(os.sep, "/").lower() + base = rel.replace(os.sep, "/").lower() + # a folder itself counts as what is inside it (`rm -rf src/__pycache__` is as ignorable as its files) return any(fnmatch.fnmatchcase(p, g.lower()) or (g.startswith("**/") and fnmatch.fnmatchcase(p, g[3:].lower())) - or (g.endswith("/**") and p.startswith(g[:-2].lower())) for g in _list("ignore_changed")) + or (g.endswith("/**") and p.startswith(g[:-2].lower())) for g in _list("ignore_changed") for p in (base, base + "/x")) def _rel_in_project(path, root, cwd): @@ -393,7 +394,7 @@ def _absorb(sess, root): covered = set(sess.get("ug_covered") or []) sess["ug_covered"] = [p for p in covered if p in since] # settled stops empty attr_since_pass: forget have = sess.setdefault("ug_paths", []) - new = False + new, dirty = False, None for p in since: rel = p if os.path.isabs(p): @@ -402,11 +403,39 @@ def _absorb(sess, root): continue if p in covered or rel in have or _is_sisi(rel) or _ignored(rel): continue + if dirty is None: + dirty = _changed_in_tree(root) + if dirty is not None and rel not in dirty: + continue # the host's transcript shows the attempt; the tree shows it changed nothing (a refused edit, a failed one) have.append(rel) new = True return new +def _changed_in_tree(root): + """The set of paths git sees as changed or new in the working tree (renames and deletions included), or None + when that cannot be told.""" + try: + from . import gitutil + rc, out = gitutil._git(root, "status", "--porcelain", "-z", "--untracked-files=all") + if rc != 0: + return None + names, parts = set(), out.split("\0") + i = 0 + while i < len(parts): + e = parts[i] + i += 1 + if len(e) > 3: + names.add(e[3:]) + if e[0] in "RC" and i < len(parts): + names.add(parts[i]) + i += 1 + return names + except Exception as e: + store.log_error("unitguard-tree", e) + return None + + def _cover(sess): """A valid unit stands behind everything changed so far.""" sess["ug_covered"] = [p for p in (sess.get("attr_since_pass") or []) if isinstance(p, str) and not p.startswith("*")] @@ -635,7 +664,11 @@ def _is_sisi_command(cmd): cur.append(t) segs.append(cur) segs = [s for s in segs if s] - return bool(segs) and all(os.path.basename(s[0]) == "sisi" for s in segs) + if any(t in (">", ">>") for t in toks): + return False # a file written by redirection is a change of its own + # `sisi ... 2>&1 | head -40`: the filters after a pipe only read what sisi printed + return bool(segs) and os.path.basename(segs[0][0]) == "sisi" and all( + os.path.basename(s[0]) == "sisi" or os.path.basename(s[0]) in _list("output_filters") for s in segs[1:]) def classify(tool, payload, cmd): diff --git a/tests/test_integration.py b/tests/test_integration.py index 24f8958..822f38f 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -401,6 +401,41 @@ class SendBackSaysWhy(TG.GuardCase): self.assertIn("because the contract declares the integration profile", msg.splitlines()[0]) +class NoDeadlockAfterARefusedEdit(TG.GuardCase): + """Found by the live check: the transcript shows an edit the hook refused, the guard counted it as a change, and + from then on every shell command was refused, `sisi contract init 2>&1 | head` included.""" + + def transcript_shows_edit(self, rel=SRC): + sess = store.load_session(self.sid) + sess["attr_since_pass"] = [os.path.join(self.proj, rel)] + store.save_session(self.sid, sess) + + def test_an_edit_the_tree_never_saw_is_not_a_change(self): + self.assertIn("sisi contract init", self.edit()) + self.transcript_shows_edit() + self.assertIsNone(self.bash("python3 -c 'print(1)'")) + self.assertEqual(G.session_paths(store.load_session(self.sid)), []) + + def test_an_edit_the_tree_did_see_still_is(self): + self.put(SRC, "def greet():\n return 'yo'\n") + self.transcript_shows_edit() + msg = self.bash("python3 -c 'print(1)'") + self.assertIn("already changed", msg) + self.assertIn("sisi contract init", msg) + + def test_the_way_out_is_never_refused_even_piped_through_a_filter(self): + self.put(SRC, "def greet():\n return 'yo'\n") + self.transcript_shows_edit() + for cmd in ("sisi contract init", "sisi contract init 2>&1 | head -60", "sisi unit continue 2>&1 | tail -5", + "sisi contract check | grep -n goal"): + self.assertIsNone(self.bash(cmd), cmd) + for cmd in ("sisi contract init > notes.txt", "sisi contract init | tee notes.txt"): + self.assertIsNotNone(self.bash(cmd), cmd) + + def test_a_cache_folder_is_as_ignorable_as_the_files_in_it(self): + self.assertIsNone(self.bash("rm -rf src/__pycache__")) + + class CopySurvivesVanishingFiles(SisiCase): """Fix C.""" diff --git a/tools/measure_hooks.py b/tools/measure_hooks.py index 2cda85f..d241d2c 100644 --- a/tools/measure_hooks.py +++ b/tools/measure_hooks.py @@ -25,7 +25,10 @@ cases={"before Read":("PreToolUse","Read",{"file_path":"/x"},None), "before Bash ls":("PreToolUse","Bash",{"command":"ls"},None), "after Bash ls":("PostToolUse","Bash",{"command":"ls"},{"tool_response":{"stdout":"a","exit_code":0}}), "before Edit":("PreToolUse","Edit",{"file_path":"/x"},None), - "after Edit":("PostToolUse","Edit",{"file_path":"/x"},{"tool_response":"ok"})} + "after Edit":("PostToolUse","Edit",{"file_path":"/x"},{"tool_response":"ok"}), + # the contract guard on a project file: a document change (never refused) and a source change with no unit (refused) + "before Edit README (in project)":("PreToolUse","Edit",{"file_path":proj+"/README.md"},None), + "before Edit src (refused, no unit)":("PreToolUse","Edit",{"file_path":proj+"/src/app.py"},None)} for name,(ev,tool,inp,ex) in cases.items(): m=med(lambda: one([sys.executable,B,"watch","--tool","claude-code"],payload(ev,tool,inp,ex))) print("%-26s median wall %6.1f ms cpu %5.1f ms (cpu over a bare python start: %.1f ms)"%(name,m[0],m[1],m[1]-base[1]))