diff --git a/canon/core.md b/canon/core.md index 70f6f92..2f8cf7a 100644 --- a/canon/core.md +++ b/canon/core.md @@ -84,8 +84,11 @@ Give each task to the least expensive worker that is capable enough, counting re and keep your own context for judgement. Use the host's own delegation first. Run independent work in parallel when it shortens the critical path. Brief a worker with a contract (`sisi delegate brief`), check what comes back in proportion to the risk, and record the -judgement (`sisi delegate judge`). `sisi route` recommends a worker from that record, and -`sisi delegate guide` is the playbook. +judgement (`sisi delegate judge`). Before delegating, ask `sisi route`, which recommends a worker +from that record and keeps your difficulty guess. When a worker is unavailable, give the same +brief to the next worker the router names, without asking the person and without reporting it: +worker availability is internal, and only a changed outcome or time is theirs to hear. `sisi delegate guide` +is the playbook. Why: verified value per unit of time, cost and attention is the objective, and the strongest model's attention is the scarcest resource. @@ -95,7 +98,8 @@ model's attention is the scarcest resource. When you finish, say what was delivered, the decisions that matter, what was verified and how, what was not verified, and any risk or follow-up, in proportion to the change. Leave out the story of how you got there. State assumptions and departures from what was asked. Never describe -unverified work as done. +unverified work as done. Say what you verified yourself and what you took on a worker's word. Leave +out which workers, tools or providers were used or unavailable, unless it changes the outcome. Why: the person acts on your report. A false or padded one costs them more than a late one. diff --git a/canon/guard.json b/canon/guard.json index e89017d..0e12c22 100644 --- a/canon/guard.json +++ b/canon/guard.json @@ -28,6 +28,25 @@ "tests", "debug" ], + "other_kinds": [ + "read", + "search", + "research", + "review", + "docs" + ], + "output_filters": [ + "head", + "tail", + "grep", + "wc", + "sort", + "uniq", + "cut", + "tr", + "cat", + "less" + ], "build_words": [ "change", "fix", @@ -58,6 +77,7 @@ "without changing", "without modifying", "no changes", + "files you may change: none", "report only", "only report", "do not create" diff --git a/canon/orchestration-tools.json b/canon/orchestration-tools.json new file mode 100644 index 0000000..0dc9343 --- /dev/null +++ b/canon/orchestration-tools.json @@ -0,0 +1,104 @@ +{ + "_about": "Host tool names the orchestration meter needs (sisi/orchestration.py). Per host: `delegation` tools start a worker (where the call carries the model and the brief text, as dotted paths into the tool's input); `exempt` tools are never counted as direct work (the question dialog, planning and to-do tools, messaging tools). Any other tool, including one named nowhere here, counts. `refuse` says how the host's before-tool hook refuses a call: `json-deny` prints the host's permission-deny JSON, `exit-2` exits with status 2 and the reason on standard error, `none` means the meter only counts there. `evidence` says how sure this entry is.", + "claude-code": { + "refuse": "json-deny", + "evidence": "observed live (tools/live_orchestration_check.py)", + "delegation": { + "Task": { + "model": "model", + "brief": "prompt" + }, + "Agent": { + "model": "model", + "brief": "prompt" + } + }, + "exempt": { + "dialog": [ + "AskUserQuestion" + ], + "planning": [ + "TodoWrite", + "EnterPlanMode", + "ExitPlanMode", + "TaskCreate", + "TaskUpdate", + "TaskList", + "TaskGet", + "TaskOutput", + "TaskStop" + ], + "messaging": [ + "SendMessage", + "SendUserMessage", + "PushNotification" + ] + } + }, + "codex": { + "refuse": "exit-2", + "evidence": "from the host's hook documentation; not run live here", + "delegation": {}, + "exempt": { + "dialog": [ + "request_user_input" + ], + "planning": [ + "update_plan" + ], + "messaging": [] + } + }, + "gemini": { + "refuse": "exit-2", + "evidence": "from the host's hook documentation; not run live here", + "delegation": {}, + "exempt": { + "dialog": [ + "ask_user" + ], + "planning": [ + "write_todos" + ], + "messaging": [] + } + }, + "copilot": { + "refuse": "none", + "evidence": "the host's before-tool refusal contract is not confirmed here; counts only", + "delegation": { + "task": { + "model": "model", + "brief": "prompt" + } + }, + "exempt": { + "dialog": [ + "ask_user" + ], + "planning": [ + "update_todo" + ], + "messaging": [] + } + }, + "cursor": { + "refuse": "exit-2", + "evidence": "from the host's hook documentation; not run live here", + "delegation": { + "Task": { + "model": "model", + "brief": "prompt" + } + }, + "exempt": { + "dialog": [ + "AskQuestion" + ], + "planning": [ + "TodoWrite" + ], + "messaging": [] + } + } +} diff --git a/canon/orchestration.md b/canon/orchestration.md index e5e5d75..8c00d4f 100644 --- a/canon/orchestration.md +++ b/canon/orchestration.md @@ -80,6 +80,16 @@ present; nothing here names one. Read on demand: `sisi delegate guide`. - Unavailability is temporary and is never a quality judgement: record it with `sisi workers down`, use the next worker, and try again when due. A rejected result never marks a worker down. +- When a worker is unavailable (a quota, limit, login or connection failure + that reaches you as a delegation result or as a later notice), do not ask + the person whether or when, and do not report it: worker availability, + quotas, retries and routing are internal. Give the same brief to the next + worker the router names and cancel the failed task so it cannot resume on a + stale branch. If every other provider is down, use the host's own + subagents. If nothing at all is usable, do the work yourself. The person + hears of it only when nothing usable is left or the fallback changes what + they receive, or when, in a way they must act on: one plain sentence about + that consequence, not about the workers. ## Keeping the picture current diff --git a/config.default.json b/config.default.json index 128649f..3d65fe1 100644 --- a/config.default.json +++ b/config.default.json @@ -21,5 +21,12 @@ }, "unit": { "stale_hours": 12 + }, + "orchestrate": { + "enabled": true, + "direct_calls": 6, + "direct_chars": 30000, + "extension": 10, + "route_window_min": 15 } } diff --git a/docs/design.md b/docs/design.md index 69b7838..7813bc8 100644 --- a/docs/design.md +++ b/docs/design.md @@ -341,6 +341,64 @@ worker). - `sisi delegate --brief FILE …` still runs a worker through its own CLI when the host has no delegation of its own. +**Enforcement** (`sisi/orchestration.py`, `sisi/fallback.py`; host tool names in `canon/orchestration-tools.json`). +The before- and after-tool hooks run for every tool, not only the shell, and keep a per-session, +per-turn meter in the scratch store (`sessions/.meter.json`, under a file lock; every counted event is +also appended to `orchestration.jsonl`). It meters main threads only: a session the host marks as a subagent, +one whose first prompt opens with the brief template's first line, and one started by `sisi delegate` are +workers and are never counted or refused; neither is anything refused when no usable worker other than the +session's own model exists. Every entry point fails open. + +- **Direct-work budget.** Every tool call that is not a delegation, the question dialog, a planning or to-do + tool, a message or a `sisi` command counts, with the characters of its result. Past `orchestrate.direct_calls` + (6) or `orchestrate.direct_chars` (30000) the next counted call is refused with at most 12 lines: the count, + rule 6, the router's pick for reading and for building (taken from the routing code, with its mechanism + line) and two ways on: delegate with a brief, or `sisi unit direct ""`. A specific reason (a generic + one is refused) extends the turn by `orchestrate.extension` (10) calls and the matching share of characters; + each extension and its reason is stored and shown by `sisi status`. The turn starts again at each prompt (a + host's notice about a background worker is not a prompt) and when the gate lets the turn end. +- **Delegation guard.** A delegation that names no model, or the session's own, is refused with the router's + pick; an allowed one is checked with `brief.check` (advice only) and written to the ledger as a pending run + (worker, project, session, start), completed with minutes and tokens when the result reports them, or, for an + async launch, when the host's completion notice arrives as a prompt. The gate asks once per set of finished, + unjudged runs for the judgements. +- **The router is asked first.** `sisi route` writes a routing decision for the session (kind, difficulty + guess, pick, time). The first delegation with no decision inside `orchestrate.route_window_min` (15) is + refused once; afterwards the pending run carries the kind and difficulty, so `sisi delegate judge ID` needs + 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 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 + host notice is classified (`workers.classify_failure`), the worker's provider (or just the model) is marked + down until the reset time the message names, its pending run is marked `superseded` (never asked to be + judged), and the agent gets at most six lines: the router's next worker for the same kind of work, to fall + back now with the same brief, not to ask and not to report it (worker availability is internal, SPEC 9.7 and + 17), and to cancel the failed task. A question-dialog call right after is refused once; ending the turn with + no fallback started is sent back (twice at most); a final message naming the failed worker or the failure is + sent back once. All state-based. The person hears of it only when nothing usable is left or the outcome or + its timing changes for them. +- **New workers.** A model discovery finds that the previous one did not have is named once at session start + as unproven (low-stakes work first, checked more carefully); never one whose id marks a tier that trains on + its prompts. +- **The record.** The unit record gains an `orchestration` part, and the scorecard's parallelism dimension the + same values, each class `measured`: direct calls and characters, refusals, extensions with reasons, + delegations started, judged and unjudged, and the share of tool calls delegated. `sisi status` prints it for + the unit in progress too. `sisi rule 6` lists what is enforced. +- **Hosts.** Claude Code: the meter can refuse (observed live). Codex, Gemini and Cursor have before-tool + events and are wired for every tool; the refusal is exit status 2 with the reason as the host documents it, + not run live here. Copilot only counts. Hosts with no before-tool hook (Qwen, Pi, OpenCode and the + rulebook-only tools) cannot run the meter; `sisi doctor` says which. + The owner's hand-written orchestrator (`orch.py`, its ledger, and the section of his Claude instructions) is replaced by this. Its ledger is merged into the user store with a row count check, then it is removed. diff --git a/docs/developing.md b/docs/developing.md index eda7956..43c72da 100644 --- a/docs/developing.md +++ b/docs/developing.md @@ -19,6 +19,27 @@ atomically, so a running tool never sees a half-written copy: a process that has keeps running the release it started with. `sisi doctor` shows which copy is live and whether the source folder is ahead of it. +## The live orchestration check + +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 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 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 +time, the session must go on with another worker, never call the question dialog and never mention the +failure in its final message. It costs a few cents and needs the host's login, so it is not part of the unit +suite; synthetic hook input is what let an earlier release ship broken. If the agent ignores a refusal or the +host does not honour it, that is a finding: fix the hook output, do not weaken the assertion. + ## Make a release Run from the clone (a release is made from the running launcher's folder): diff --git a/docs/harnesses.md b/docs/harnesses.md index 3efe1a5..9cd489f 100644 --- a/docs/harnesses.md +++ b/docs/harnesses.md @@ -29,13 +29,33 @@ between each tool's hook JSON and the gate lives in `sisi/hookio.py`; the adapte skills shipped under `canon/skills` into `~/.agents/skills`; `sisi doctor` reports the linked state. Hooks fail open: any error lets the agent finish. Where a tool's hook input has no transcript path, the gate falls back to its pre-attribution behaviour (tree-change based, with no per-session edit attribution). Shell commands are attributed by measurement, not by their text, wherever the tool has confirmed before/after tool events (`sisi watch` takes a stat-only tree snapshot before and after the command and attributes the paths that changed to the session; provably read-only commands skip the pair); tools without confirmed before/after tool events keep the command-text classifier described in [docs/design.md](design.md). +## The orchestration meter, per tool + +The before- and after-tool hooks count the main thread's direct tool calls and refuse past a budget (rule 6, +[design.md](design.md) section 9). `sisi doctor` prints what it can do in each tool: + +| tool | meter | evidence | +|---|---|---| +| Claude Code | counts and refuses every tool (permission-deny output), delegation guard, fallback | observed live (`tools/live_orchestration_check.py`) | +| Codex CLI | counts and can refuse every tool (exit status 2 with the reason) | the host's hook documentation; not run live here | +| Gemini CLI | counts and can refuse every tool (exit status 2) | documentation; not run live | +| Cursor | counts and can refuse every tool (exit status 2) | documentation; not run live | +| GitHub Copilot CLI | only counts: its refusal contract is not confirmed | not run live | +| Qwen, Pi, OpenCode, Muse, Grok, Crush and the rulebook-only tools | cannot run: no before-tool hook is wired | see each section | + +Host tool names (delegation, question dialog, planning, messaging) are data in +`canon/orchestration-tools.json`; a tool named nowhere there still counts. Only Claude Code's delegation tool is +named for the guard and the fallback; elsewhere delegation goes through `sisi delegate`, which is exempt. + ## 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`. The gate also enforces +`Stop`/`SubagentStop` → `sisi gate` (blocking), and `PreToolUse`/`PostToolUse`/`PostToolUseFailure` with no +matcher (every tool) → `sisi watch` (the orchestration meter, and before/after tree measurement for shell +commands) in `~/.claude/settings.json`. An installation from an earlier release (shell-only matchers) is +changed by `sisi install` and by `sisi update`, span-preserving; `sisi uninstall` restores the original bytes. 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. @@ -54,7 +74,7 @@ Rulebook symlink at `~/.codex/AGENTS.md` (or `$CODEX_HOME/AGENTS.md`), plus hook `~/.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 +`PreToolUse`/`PostToolUse` (every tool) → `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 any change to the hook commands (for example after moving the sisi clone). `sisi doctor` cannot verify diff --git a/docs/workers.md b/docs/workers.md index 2927c93..15a129a 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -92,6 +92,27 @@ through to the next choice, and quality is untouched. Poor work is a rejected ju never marks a worker down. No approval- or sandbox-switching flag is passed unless the config allows it per tool (`workers.allow_bypass`). +## Orchestration the hooks enforce + +`sisi route` records the session's routing decision (kind, difficulty guess, pick). A delegation started with +the host's own tool is written to the ledger by the hooks as a pending run with that kind and difficulty, and +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, 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 +message, mark its pending run `superseded` and hand the agent the router's next worker. The agent is told to +fall back at once with the same brief and neither ask the person nor report it. `sisi delegate` itself says +the same when only host-native workers remain. Models discovery finds that it had not seen are named once at +session start as unproven. Settings under `orchestrate`: `direct_calls`, `direct_chars`, `extension`, +`route_window_min`. Mechanics: [design.md](design.md) section 9. + ## Stored, and when facts go stale In the user store: `workers.json` (discovery cache), `delegations.jsonl` (the ledger), diff --git a/sisi/adapters.py b/sisi/adapters.py index 71d952b..048727f 100644 --- a/sisi/adapters.py +++ b/sisi/adapters.py @@ -532,8 +532,8 @@ class Codex(Adapter): "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"}, - "PostToolUse": {"cmd": _cmd("watch", "codex"), "timeout": 60, "sub": "watch", "matcher": "Bash"}, + "PreToolUse": {"cmd": _cmd("watch", "codex"), "timeout": 60, "sub": "watch"}, + "PostToolUse": {"cmd": _cmd("watch", "codex"), "timeout": 60, "sub": "watch"}, } def detect(self): diff --git a/sisi/brief.py b/sisi/brief.py index 6503e67..489d01a 100644 --- a/sisi/brief.py +++ b/sisi/brief.py @@ -171,3 +171,16 @@ def advice(text): out.append("It has numbered items but no commit per item: ask for a commit after each, with a " "\"done / next\" note, so an interruption loses at most one.") return out + + +def check(text): + """Plain lines about a brief that arrives by a host's own delegation tool: what it lacks of the + three required parts (outcome, acceptance, the files the worker may change), then the usual + advice. Always advice for the main agent; a brief is never refused here.""" + lines = [] + missing = missing_required(text) + if missing: + lines.append("the brief has no %s; a worker starts cold, so say %s (`sisi delegate brief` prints the template)" + % (" and no ".join(m.lower() for m in missing), "each of them")) + lines += advice(text) + return lines diff --git a/sisi/cli.py b/sisi/cli.py index d9af30c..c6476c9 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -154,6 +154,8 @@ def cmd_wiring(name, args=()): w = max(len(r["tool"]) for r in rows) for r in rows: line = "%-*s %-9s blocking hook: %-8s %s" % (w, r["tool"], r["status"], r["blocking_hook"][:60], r["detail"]) + if r.get("meter"): + line += " | orchestration meter: " + r["meter"] if r.get("action"): line += " | you need to: " + r["action"] print(line) diff --git a/sisi/deep.py b/sisi/deep.py index b538828..96ba243 100644 --- a/sisi/deep.py +++ b/sisi/deep.py @@ -16,6 +16,17 @@ def _lock_path(project): return os.path.join(paths.state(), "locks", "deep-" + key(project) + ".lock") +def tree_fp(project): + """What deep results are fresh against: the working tree as the work, never sisi's own records. Everything + under .sisi/ (the contract included) is left out, as it is from the fast checks' reuse fingerprint, so + recording a pause or a note does not make a fresh deep result stale.""" + from . import gitutil + try: + return gitutil.fingerprint(project) + except Exception: + return None + + def deep_items(c): return [x for x in c.get("checks", []) + c.get("invariants", []) if x.get("tier") == "deep" and x.get("cmd") and x.get("rung", 3) not in (5, 6)] diff --git a/sisi/fallback.py b/sisi/fallback.py new file mode 100644 index 0000000..f31d456 --- /dev/null +++ b/sisi/fallback.py @@ -0,0 +1,123 @@ +"""Rule 6 when a worker is unavailable: detect it wherever it arrives, record it, hand over the fallback. + +A worker's unavailability reaches a main session as the result of a delegation tool call (the after-tool +hook) or as a later notice that a background or delegated task failed (the prompt hook). Both run the same +failure classifier (workers.classify_failure). Unavailability is never a quality judgement: nothing here +reads a rejected result, and a result that merely mentions a limit in a long report is not a failure. + +What the agent is told, in at most six lines: which worker is out and until when, the router's next pick for the +same kind of work with its mechanism line (a host-native worker when every other provider is down), to fall +back now with the same brief, neither asking the person nor reporting it to them (worker availability is +internal, SPEC 9.7 and 17), and to cancel the failed task so it cannot resume later on a stale branch. When +nothing else is usable it says so and when the earliest worker is due; the person hears of it only if the +outcome or its timing changes for them, in one plain sentence about that consequence. +""" +import re, time + +from . import store, workers + +NOTICE = "" +_FAIL_MARKERS = ("[failed]", "api error", "error:", "failed:", "traceback", "exit code") +_DEFAULT_KIND = ("impl", 2) +# what a report of the failure would call it, by class: the final message must not say these after one (state-based) +_REASON_WORDS = {"limit": ("quota", "rate limit", "usage limit", "429"), "auth": ("logged in", "login", "credentials"), + "missing": ("not connected", "not installed"), "error": ("outage",)} + + +def _tag(text, name): + m = re.search(r"<%s>(.*?)" % (name, name), text or "", re.S) + return m.group(1).strip() if m else None + + +def looks_failed(text, failure_event=False, status=None): + """Is this a failed delegation rather than a finished report that happens to mention a limit?""" + if failure_event or str(status or "").lower() in ("failed", "error", "killed", "cancelled", "stopped"): + return True + head = (text or "").strip()[:200].lower() + return any(k in head for k in _FAIL_MARKERS) + + +def failure_notice(prompt): + """{"text", "use_id", "task_id"} when a prompt is the host's notice that a task failed, else None.""" + t = (prompt or "").lstrip() + if t.startswith(NOTICE): + status = _tag(t, "status") + body = " ".join(x for x in (_tag(t, "summary"), _tag(t, "result")) if x) + if looks_failed(body, status=None if status in (None, "completed") else status): + return {"text": body or t, "use_id": _tag(t, "tool-use-id"), "task_id": _tag(t, "task-id")} + return None + if "[failed]" in t[:300].lower(): + return {"text": t, "use_id": None, "task_id": None} + return None + + +def shell_notice(output): + """A `sisi delegate` run that already recorded a worker as unavailable: (worker, text) from its output.""" + m = re.search(r"(\S+) is unavailable \(([^)]*)\)", output or "") + return (m.group(1), output) if m else None + + +def fmt_time(ts): + return time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(ts)) + + +def fallback_text(info, cwd, own_model): + """At most six lines: what is down, the next worker, the instruction, the cancel line.""" + kind, diff = info.get("kind") or _DEFAULT_KIND[0], info.get("difficulty") or _DEFAULT_KIND[1] + who = info.get("worker") or "a delegated worker" + until = info.get("until") + head = "sisi: %s is unavailable (%s)%s; recorded, and not a judgement of its work." % ( + who, info.get("reason") or "failed", (" until %s" % fmt_time(until)) if until else "") + worker, mech, _n = workers.recommend(kind, diff, cwd, own_model) + cancel = ("Cancel or interrupt the failed task with this host's own means: it may resume when its limit resets " + "and redo work on a stale branch.") + if worker: + return "\n".join([head, + "Next for the same kind of work (%s, difficulty %s): %s (%s)." % (kind, diff, worker, mech), + "Fall back now with the same brief: start it on that worker now and give the person its result. " + "Do not ask the person, and do not report this to them: which worker is out is internal.", cancel]) + due = workers.earliest_due() + return "\n".join([head, + "No other worker is usable now%s." % ((" (earliest due: %s at %s)" % (due[0], fmt_time(due[1]))) if due else ""), + "Do the work yourself with this session's own tools meanwhile; do not ask the person. Tell them " + "only if what they receive, or when, changes in a way they must act on: one plain sentence about " + "that consequence, not about the workers.", cancel]) + + +def handle(m, sid, cwd, text, own_model=None, worker=None, run_id=None, record=True, kind=None, difficulty=None): + """A failure message arrived. Classify it; record the worker down (when it can be identified and `record`); + mark its pending run superseded; remember it in the meter for the question-dialog check; return the fallback + text, or None when the text is not an unavailability. Never raises past the caller's guard.""" + if workers.classify_failure(text) is None: + return None + from . import orchestration + worker = worker or workers.identify_worker(text) + info = {"worker": worker, "ts": time.time(), "kind": kind, "difficulty": difficulty} + run, marked = None, None + if run_id: + run = next((r for r in workers.merged_runs() if r.get("id") == run_id), None) + if run: + info["kind"], info["difficulty"] = run.get("type"), run.get("difficulty") + if worker and record: + marked = workers.mark_unavailable(worker, text) + if marked: + info.update(until=marked["until"], reason="%s: %s" % (marked["reason"], marked["note"][:60])) + elif worker: # `sisi delegate` already recorded it: read the time it stored + due = workers.read_availability().get(str(worker).lower()) or {} + info.update(until=due.get("retry_at"), reason=("%s: %s" % (due.get("reason"), (due.get("note") or "")[:60])) if due else None) + if not info.get("reason"): + reason, note, _ = workers.classify_failure(text) + info["reason"] = "%s: %s" % (reason, note[:60]) + if run_id: + workers.append_record({"kind": "run-end", "run_id": run_id, "ts": round(time.time()), "status": "superseded", + "ended": round(time.time())}) + m["unavail"] = {k: info.get(k) for k in ("worker", "kind", "difficulty", "until", "reason")} + names = set(m.get("unavail_names") or []) + for n in [worker] + list((marked or {}).get("keys") or []): + for part in re.split(r"[/\s]+", str(n or "").lower()): + if len(part) >= 4: + names.add(part) + names.update(("fallback", "fall back", "unavailable") + _REASON_WORDS.get(workers.classify_failure(text)[0], ())) + m["unavail_names"] = sorted(names) + orchestration._event(m, sid, "unavailable", worker=worker, run=run_id) + return fallback_text(info, cwd, own_model) diff --git a/sisi/gate.py b/sisi/gate.py index 67f1c62..9faf020 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -378,7 +378,7 @@ def _decide(payload): if req.get("all_checks") and c is not None and not errs: try: from . import deep as D - ds = D.deep_state(c, project, fp) + ds = D.deep_state(c, project, D.tree_fp(project)) except Exception as e: store.log_error("gate-deep", e) failing = V.blocking(results) @@ -485,14 +485,26 @@ def _close(stop, cwd, c, path, project, profile, note): return stop.allow(cwd, "\n".join(x for x in (note, cyc) if x) or None) +def profile_reason(profile, info, reasons): + """Why this profile applies: the first reason a changed path gives; when no path gave one (nothing changed + yet, or the unit stands on its declared profile), say that the contract declares it, or the floor's reason.""" + real = [r for r in reasons or [] if r and r != risk.NO_PATHS] + if real: + return real[0] + if info.get("declared") == profile: + return "the contract declares the %s profile" % profile + return None + + def _send_back(stop, cwd, c, path, project, profile, info, reasons, miss, failing, results): uid = c["id"] if c else None why = ["%s" % m[0] for m in miss] + ["%s failed" % f["id"] for f in failing] if stop.exhausted(): return _release(stop, cwd, c, path, project, why) lines = ["sisi: this %s change is not ready to hand over (send-back {n})." % profile] - if reasons: - lines[0] = lines[0][:-1] + " because %s." % reasons[0][:160] + because = profile_reason(profile, info, reasons) + if because: + lines[0] = lines[0][:-1] + " because %s." % because[:160] if info.get("refused"): lines.append("The contract declares %r, but the change is %r; add risk.why to lower it on the record." % (info.get("declared"), info.get("floor"))) @@ -509,12 +521,37 @@ def _send_back(stop, cwd, c, path, project, profile, info, reasons, miss, failin return stop.block(assure.fit(lines), uid, project) +def _orchestration_step(payload, action): + """Rule 6 at the end of a turn, main thread only: ask once for the judgement of this session's finished + delegations (a send-back like any other missing item); when the turn really ends, the meter starts over.""" + try: + from . import orchestration, workers + if workers.is_subagent_payload(payload): + return None + cwd = _cwd(payload) + sid = _session_key(payload, cwd) + if store.load_session(sid).get("subagent"): + return None + if action == "allow": + text = (orchestration.fallback_sendback(payload, sid) or orchestration.judgement_sendback(payload, sid) + or orchestration.report_sendback(payload, sid)) + if text: + return "block", text + orchestration.end_turn(sid) + except Exception as e: # the meter must never break the gate + store.log_error("gate-orchestration", e) + return None + + def decide(payload): """The gate's answer: the contract 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 + j = _orchestration_step(payload, action) + if j: + return j try: from . import questions q = questions.sendback(payload) diff --git a/sisi/harvest.py b/sisi/harvest.py index e0622a0..079a7cc 100644 --- a/sisi/harvest.py +++ b/sisi/harvest.py @@ -118,6 +118,10 @@ _PLACEHOLDERS = [re.compile(r"\[Image[^\]]*\]"), re.compile(r"\[File:[^\]]*\]"), _NOT_HUMAN_PREFIX = ("(.*?)", re.S) @@ -152,7 +156,7 @@ def typed_text(d, queued_prompt=None): s = content.strip() if s.startswith("[Request interrupted by user"): return None, 0, True - if s.startswith(_NOT_HUMAN_PREFIX): + if s.startswith(_NOT_HUMAN_PREFIX) or _MACHINE_NOTICE.match(s): return None, 0, False if s.startswith((""\n record a deviation: a waived check does not pass; the unit closes as a deviation and the report must say so\n sisi contract trust | untrust allow / stop allowing this project\'s contract to run commands', - 'unit': ' sisi unit close [--abandon ""]\n archive the unit to .sisi/units/.json with its scorecard; --abandon records why it stopped\n sisi unit pause ""\n record a wait (checks waiting on something, and the retro; never the contract: refused without a valid unit this session holds)\n sisi unit continue\n say this session continues the open unit: prints its goal, age and owed checks; needed again after unit.stale_hours idle\n sisi unit park "" | resume ID\n set the open unit aside, kept under .sisi/parked/ (listed by status and unit list), or bring a parked one back\n sisi unit show [ID] | list print the open unit or an archived record; list this project\'s units', + 'unit': ' sisi unit close [--abandon ""]\n archive the unit to .sisi/units/.json with its scorecard; --abandon records why it stopped\n sisi unit pause ""\n record a wait (checks waiting on something, and the retro; never the contract: refused without a valid unit this session holds)\n sisi unit continue\n say this session continues the open unit: prints its goal, age and owed checks; needed again after unit.stale_hours idle\n sisi unit park "" | resume ID\n set the open unit aside, kept under .sisi/parked/ (listed by status and unit list), or bring a parked one back\n sisi unit direct ""\n say why doing this work yourself is cheaper than delegating it; a specific reason allows more direct calls this turn and is kept with the unit record\n sisi unit show [ID] | list print the open unit or an archived record; list this project\'s units', 'verify': ' sisi verify [--json] run the selected fast checks (five statuses; nothing unrun passes); exit 0 ok, 1 failure, 2 no contract, 3 untrusted\n sisi verify --deep [--background] run the deep (long) checks; --background detaches and returns at once\n sisi verify --all | --state run every check in both tiers; print only the deep-check state (with --json)', 'gate': " sisi gate [--tool NAME] end-of-turn hook (reads hook JSON on stdin; NAME selects the tool's hook shape)", 'tick': ' sisi tick [--tool NAME] session-start hook', @@ -58,7 +58,7 @@ GROUPS = ( )), ("For the agent at work", ( (("contract",), "contract init|check|waive|trust|untrust", "start, validate and bend the unit's contract"), - (("unit",), "unit close|pause|continue|park|resume|show|list", "close, pause, continue, park, resume; look back"), + (("unit",), "unit close|pause|continue|park|resume|direct|show|list", "close, pause, continue, park, resume; look back"), (("risk",), "risk [--json]", "the risk floor of the working-tree change; what it requires"), (("verify",), "verify [--deep|--all|--state] [--json]", "run the contract's checks; nothing unrun passes"), (("retro",), "retro [--finding F ...|--adopt ID]", "the unit's record; record a finding, with its cause and fix"), diff --git a/sisi/hookio.py b/sisi/hookio.py index 496243e..3d7b37e 100644 --- a/sisi/hookio.py +++ b/sisi/hookio.py @@ -150,17 +150,18 @@ def gate_main(tool, args=()): def watch_main(tool, args=()): - """Before/after tool measurement for the other tools. Always exits 0 (fail open).""" + """Before/after tool measurement and the orchestration meter for the other tools. Fail open: any + error exits 0. A refusal is exit status 2 with the reason on standard error, where the tool's + before-tool event documents that contract (canon/orchestration-tools.json `refuse`).""" try: d = _payload(store.read_stdin()) if d is not None: - from . import watch + from . import orchestration, watch norm = normalize(tool, d) - _t, _c, ev, _cwd, _sid = watch.extract(norm) - if "--before" in args or ev in watch.BEFORE_EVENTS: - watch.before(norm) - elif "--after" in args or ev in watch.AFTER_EVENTS: - watch.after(norm) + out = watch.run(norm, args, host=tool) + if out.get("deny") and orchestration.refuse_style(tool) == "exit-2": + sys.stderr.write(out["deny"] + "\n") + return 2 except Exception as e: store.log_error("watch-%s" % tool, e) return 0 @@ -218,7 +219,8 @@ def prompt_main(tool, args=()): 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 "" + fb = P.meter_new_turn(norm.get("session_id"), _os.getcwd(), query) + text = "\n".join(x for x in (fb, "" if not query else P.context_for(query, norm.get("session_id"), norm)) if x) 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) diff --git a/sisi/hookjson.py b/sisi/hookjson.py index 013bc2b..4ce01eb 100644 --- a/sisi/hookjson.py +++ b/sisi/hookjson.py @@ -409,11 +409,39 @@ def _add_nested_event(text, event, s): ours = _nested_ours(text, event, s["sub"]) if ours: want = _nested_entry(s) + text = _fit_group_matcher(text, event, s, ours[0]) + ours = _nested_ours(text, event, s["sub"]) + if not ours: # the entry shared a group with another hook and was moved out: add it in a group of its own + return _add_nested_event(text, event, s) return _update_fields(text, lambda t: _nested_locate(t, event, _nested_ours(t, event, s["sub"])[0])[3], want) _r, hooks = _hooks_node(text) return append_element(text, member(hooks, event)[1], _dump(_nested_group(s))) +def _group_matcher(g): + """(matcher text or None, its value node or None) of a group node.""" + for k, _kn, v in g.members: + if k == "matcher": + return (v.value if v.kind == "str" else None), v + return None, None + + +def _fit_group_matcher(text, event, s, loc): + """Make the group that holds our entry match what the spec wants: no matcher (every tool) when the spec has none, + else exactly its matcher. A group of ours alone is edited in place; one shared with another hook is left as it + is and our entry is moved out of it (the caller adds it back in a group of its own).""" + want = s.get("matcher") or None + _arr, g, hm, _e = _nested_locate(text, event, loc) + have, node = _group_matcher(g) + if (node is None and want is None) or have == want or (want is None and have in ("", "*")): + return text + if len(hm.items) == 1: + if want is None: + return remove_member(text, g, "matcher") + return replace_node(text, node, json.dumps(want)) if node is not None else insert_member(text, g, "matcher", json.dumps(want)) + return _nested_remove_at(text, event, loc) + + def add_nested(text, spec, created_version=None): """Merge nested hook groups into JSON text. spec: {event: {cmd, timeout, sub, matcher?, name?}}.""" text = _seed_version(text, created_version) diff --git a/sisi/lifecycle.py b/sisi/lifecycle.py index 93371be..ff23efe 100644 --- a/sisi/lifecycle.py +++ b/sisi/lifecycle.py @@ -34,21 +34,39 @@ def _union_lines(src, dst): return len(add) +def _copy_tree(src, dst): + """Copy a folder as it is being used by others: a file or folder that disappears during the copy (a git lock + file, a temporary file) is not part of what was backed up, and is not an error.""" + os.makedirs(dst, exist_ok=True) + try: + names = os.listdir(src) + except FileNotFoundError: + return + for n in names: + if n.endswith(".lock") or n == "gc.pid": + continue # lock files are not data; git's background maintenance removes them while we copy + s, d = os.path.join(src, n), os.path.join(dst, n) + try: + if os.path.isdir(s): + _copy_tree(s, d) + else: + shutil.copy2(s, d) + except FileNotFoundError: + continue + + def _copy_into(src, bdir, rel): dst = os.path.join(bdir, rel) os.makedirs(os.path.dirname(dst), exist_ok=True) - if os.path.isdir(src): - try: - # lock files are not data, and git's background maintenance removes them while we copy - shutil.copytree(src, dst, dirs_exist_ok=True, ignore=shutil.ignore_patterns("*.lock", "gc.pid")) - except shutil.Error as e: - # a file that vanished while being copied (git housekeeping in the personal repository) is not a failure - if not all(isinstance(x, tuple) and "No such file or directory" in str(x[2]) for x in e.args[0]): - raise - elif src.endswith(".db"): - _sqlite_copy(src, dst) - else: - shutil.copy2(src, dst) + try: + if os.path.isdir(src): + _copy_tree(src, dst) + elif src.endswith(".db"): + _sqlite_copy(src, dst) + else: + shutil.copy2(src, dst) + except FileNotFoundError: + pass def _sqlite_copy(src, dst): @@ -598,11 +616,27 @@ def post_update(): except pdata.DataError as e: print("sisi update: %s" % e) return 1 + _rewire_existing() from . import cli print("doctor:") return cli.cmd_wiring("doctor") +def _rewire_existing(): + """An installation that exists is brought up to what this version registers (the tool hooks now run for + every tool, not only the shell). Idempotent and span-preserving; nothing happens without an installation.""" + try: + from . import wiring + if not os.path.exists(wiring._mpath()): + return + rc, notes = wiring.install() + for n in notes: + if "hook" in n or rc: + print(n) + except Exception as e: + print("sisi update: re-registering the hooks failed (%r); run `sisi install`" % e) + + # ---- export / import ------------------------------------------------------------------------------ def _tar_filter(ti): parts = ti.name.split("/") diff --git a/sisi/orchestration.py b/sisi/orchestration.py new file mode 100644 index 0000000..f8d51d1 --- /dev/null +++ b/sisi/orchestration.py @@ -0,0 +1,968 @@ +"""Rule 6 as a mechanism: the direct-work meter, the delegation guard and the delegation record. + +The before-tool and after-tool hooks (sisi/watch.py) call in here for every tool. On a main thread: + + * every tool call that is not a delegation, a question dialog, a planning or to-do tool, a message or a + `sisi` command counts as direct work, with the characters of its result; past the budget + (`orchestrate.direct_calls` / `orchestrate.direct_chars`) the next counted call is refused with the + router's recommendation and the two ways on (delegate with a brief, or `sisi unit direct ""`); + * a delegation that names no model, or the session's own model, is refused the same way; one that is + allowed is written to the ledger as a pending run, completed when it returns, and its brief is checked; + * the fourth identical failing shell command with no file changed in between is refused once. + +Only main threads are metered: a session the host marks as a subagent, one whose first prompt opens with the +brief template's line, one started by `sisi delegate` (SISI_WORKER_RUN) is a worker and never refused. Nothing +is refused when no usable worker other than the session's own model exists. Host tool names live in +canon/orchestration-tools.json. Per-session state is in /sessions/.meter.json under a file lock; +every counted event is also appended to /orchestration.jsonl for the unit record. Every entry point +fails open (the caller wraps it): an error here must never hold up the user's tool. +""" +import fcntl, json, os, re, shlex, time + +from . import paths, store + +EVENTS = "orchestration.jsonl" +_HOSTS = {} + + +def cfg(): + c = store.config().get("orchestrate") or {} + + def num(key, default): + try: + return max(0, int(c.get(key, default))) + except (TypeError, ValueError): + return default + return {"enabled": bool(c.get("enabled", True)), "direct_calls": max(1, num("direct_calls", 6)), + "direct_chars": max(1, num("direct_chars", 30000)), "extension": max(1, num("extension", 10)), + "route_window_min": max(1, num("route_window_min", 15))} + + +def hosts(): + if not _HOSTS: # a failed read is not remembered: the next call tries again + try: + with open(paths.canon("orchestration-tools.json"), encoding="utf-8") as f: + d = json.load(f) + _HOSTS.update({k: v for k, v in d.items() if isinstance(v, dict)}) + except (OSError, ValueError): + return {} + return _HOSTS + + +def host_data(host): + return hosts().get(host or "claude-code") or {} + + +def refuse_style(host): + return host_data(host).get("refuse") + + +def meter_note(tool, wired): + """One honest line for `sisi doctor`: what the meter can do in this host, from what its hooks support.""" + hd = host_data(tool) if tool in hosts() else {} + if not hd: + return "cannot run (no before-tool hook is wired for this tool)" + if not wired: + return "not running (this tool's hooks are not wired: `sisi install`)" + style = hd.get("refuse") + how = {"json-deny": "can refuse a call (permission-deny output)", + "exit-2": "can refuse a call (exit status 2 with the reason)"}.get(style, "only counts (cannot refuse)") + return "%s; %s" % (how, hd.get("evidence") or "evidence not stated") + + +# ---------------------------------------------------------------- classifying a call + +def _exempt_names(hd): + out = set() + for names in (hd.get("exempt") or {}).values(): + out.update(str(n).lower() for n in names or []) + return out + + +def _dig(obj, dotted): + for k in str(dotted or "").split("."): + if not isinstance(obj, dict): + return None + obj = obj.get(k) + return obj + + +def delegation_spec(hd, tool): + for name, spec in (hd.get("delegation") or {}).items(): + if str(name).lower() == str(tool or "").lower(): + return spec if isinstance(spec, dict) else {} + return None + + +def _segments(cmd): + """The commands of a shell line, split at the operators outside quotes; None when it cannot be split.""" + try: + lex = shlex.shlex(cmd, posix=True, punctuation_chars=True) + lex.whitespace_split = True + toks = list(lex) + except ValueError: + return None + segs, cur = [], [] + for t in toks: + if t and all(ch in "();&|<>" for ch in t) and not t.startswith(("<", ">")): + if cur: + segs.append(cur) + cur = [] + else: + cur.append(t) + if cur: + segs.append(cur) + return segs + + +# what may stand around a `sisi` command without making the line legwork: trivial output handling +_TRIVIAL = {"echo", "printf", "true", "false", "head", "tail", "grep", "wc", "sort", "uniq", "cut", "tr"} + + +def runs_sisi(cmd): + """True when the shell line is `sisi` itself: at least one `sisi` invocation, and nothing else on the line but + trivial output handling (`; echo "exit=$?"`, `| head -20`). `sisi x && cat src/*` is not.""" + segs = _segments(cmd or "") + if not segs: + return False + found = False + for seg in segs: + toks = [t for t in seg if not re.match(r"^[A-Za-z_]\w*=", t)] + if not toks: + return False + first = toks[0] + if re.match(r"^python[\d.]*$", os.path.basename(first)) and len(toks) > 1: + first = toks[1] + if os.path.basename(first) == "sisi": + found = True + elif os.path.basename(toks[0]) not in _TRIVIAL: + return False + return found + + +def classify(host, tool, inp, cmd): + """"delegation", "exempt" or "direct".""" + hd = host_data(host) + if delegation_spec(hd, tool) is not None: + return "delegation" + if str(tool or "").lower() in _exempt_names(hd): + return "exempt" + from . import watch + if watch.is_shell(tool, cmd) and runs_sisi(cmd): + return "exempt" + return "direct" + + +# ---------------------------------------------------------------- the per-session meter + +def meter_path(sid): + return os.path.join(paths.state(), "sessions", store.safe_id(sid) + ".meter.json") + + +class Meter: + """The session's meter under an exclusive lock; saved on a clean exit.""" + + def __init__(self, sid): + self.sid = sid + self.m = None + + def __enter__(self): + p = meter_path(self.sid) + os.makedirs(os.path.dirname(p), exist_ok=True) + self.f = open(p, "a+", encoding="utf-8") + end = time.time() + 2.0 + while True: + try: + fcntl.flock(self.f, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except OSError: + if time.time() > end: + self.f.close() + raise + time.sleep(0.005) + self.f.seek(0) + try: + m = json.loads(self.f.read() or "{}") + except ValueError: + m = {} + self.m = m if isinstance(m, dict) else {} + self.m.setdefault("sid", self.sid) + for k, v in (("turn", 0), ("calls", 0), ("chars", 0), ("ext", 0), ("refusals", 0), ("prompts", 0)): + self.m.setdefault(k, v) + for k in ("fails", "pending"): + self.m.setdefault(k, {}) + for k in ("ext_log", "judge_asked"): + self.m.setdefault(k, []) + return self.m + + def __exit__(self, et, ev, tb): + try: + if et is None: + self.m["last_ts"] = time.time() + self.f.seek(0) + self.f.truncate() + self.f.write(json.dumps(self.m)) + self.f.flush() + finally: + try: + fcntl.flock(self.f, fcntl.LOCK_UN) + finally: + self.f.close() + return False + + +def _peek(sid): + """The session's meter without the lock and without writing (the contract guard only reads it).""" + try: + with open(meter_path(sid), encoding="utf-8") as f: + m = json.loads(f.read() or "{}") + return m if isinstance(m, dict) else {} + except (OSError, ValueError): + return {} + + +def worker_flag(sid): + """Did this session's first prompt open with the brief template's line (it is a worker)?""" + return bool(_peek(sid).get("worker")) + + +def routed_kind(sid): + """The kind in the session's current routing decision (`sisi route` recorded it, here, in the meter), or + None when there is none or it is older than orchestrate.route_window_min. The one place the decision is read.""" + r = _peek(sid).get("route") + if not isinstance(r, dict): + return None + try: + if time.time() - float(r.get("ts") or 0) > cfg()["route_window_min"] * 60: + return None + except (TypeError, ValueError): + return None + k = r.get("kind") + return k if isinstance(k, str) and k else None + + +def _event(m, sid, ev, **kw): + rec = {"ts": round(time.time(), 3), "session": sid, "project": m.get("project"), "ev": ev} + rec.update(kw) + store.append(EVENTS, rec) + + +def _project(m, cwd): + if m.get("cwd") != cwd or not m.get("project"): + from . import gitutil + m["cwd"] = cwd + m["project"] = gitutil.root(cwd) or cwd + return m["project"] + + +NOTIFICATION = "" + + +def _tag(text, name): + m = re.search(r"<%s>(.*?)" % (name, name), text, re.S) + return m.group(1).strip() if m else None + + +def _pending_for(m, text): + """(key, entry) of the pending delegation a host notice is about, else (None, None).""" + use_id, task_id = _tag(text, "tool-use-id"), _tag(text, "task-id") + key = use_id if use_id in m["pending"] else next( + (k for k, v in m["pending"].items() if task_id and v.get("agent") == task_id), None) + return key, (m["pending"].get(key) if key else None) + + +def _task_done(m, key, ent, text, superseded=False): + """A host's notice that a background worker finished: complete the run it started.""" + from . import workers + m["pending"].pop(key, None) + now = time.time() + tokens = _tag(text, "subagent_tokens") + ms = _tag(text, "duration_ms") + minutes = round(float(ms) / 60000.0, 2) if ms and ms.replace(".", "", 1).isdigit() else round((now - ent["t0"]) / 60.0, 2) + ok = (_tag(text, "status") or "completed") == "completed" + workers.append_record({"kind": "run-end", "run_id": ent["run"], "ts": round(now), "ended": round(now), + "minutes": minutes, "tokens": int(tokens) if tokens and tokens.isdigit() else None, + "tokens_class": "measured" if tokens and tokens.isdigit() else "unavailable", + "model": ent.get("model"), + "status": "superseded" if superseded else ("waiting" if ok else "failed")}) + _event(m, m.get("sid"), "delegation-done", run=ent["run"]) + + +def brief_line(): + from . import brief + return brief.template().splitlines()[0].strip().lower() + + +def _session_is_worker(m, sess): + return bool(m.get("worker") or sess.get("subagent") or os.environ.get("SISI_WORKER_RUN")) + + +def new_turn(sid, cwd=None, prompt=None): + """A prompt reached the session. A human request starts the meter's turn again (the first one that opens + with the brief template's line makes the session a worker for good). A host notice about a background worker + gives no new budget: it completes the run it names, and when it reports an unavailable worker the fallback + is recorded and returned (text for the prompt hook to hand over), or None.""" + from . import fallback + sess = store.load_session(sid) + with Meter(sid) as m: + if cwd: + _project(m, cwd) + text = prompt if isinstance(prompt, str) else "" + is_notice = text.lstrip().startswith(NOTIFICATION) + failed = fallback.failure_notice(text) if text else None + if is_notice or failed: + out = None + key, ent = _pending_for(m, text) if is_notice else (None, None) + if failed and not _session_is_worker(m, sess): + out = fallback.handle(m, sid, cwd or m.get("project") or os.getcwd(), failed["text"], + own_model=_own_model({}, sess, m), worker=(ent or {}).get("worker"), + run_id=(ent or {}).get("run")) + if ent is not None: + _task_done(m, key, ent, text, superseded=bool(out)) + return out + m["turn"] += 1 + m.update(calls=0, chars=0, ext=0, refusals=0, fails={}, ext_log=[], same_model_ok=False, unavail=None) + m["prompts"] += 1 + if m["prompts"] == 1 and text.lstrip()[:200].lower().startswith(brief_line()): + m["worker"] = True + return None + + +def end_turn(sid): + """The turn ended (the gate let the agent finish): counts start again at the next call.""" + with Meter(sid) as m: + m.update(calls=0, chars=0, ext=0, refusals=0, fails={}, ext_log=[], same_model_ok=False, unavail=None, + unavail_names=[], report_asked=False, fallback_asked=0) + + +# ---------------------------------------------------------------- messages + +def _fmt_pick(kind, difficulty, cwd, own_model): + from . import workers + try: + worker, mech, _n = workers.recommend(kind, difficulty, cwd, own_model) + except Exception as e: + store.log_error("orchestration-route", e) + worker, mech = None, None + return worker, mech + + +def _picks(cwd, own_model): + # the router is asked what the work is: reading and searching is routine (difficulty 1), building is ordinary + # (difficulty 2), so a routine read is not sent to the dearest worker + return (_fmt_pick("read", 1, cwd, own_model), _fmt_pick("impl", 2, cwd, own_model)) + + +def _pick_line(label, pick): + worker, mech = pick + return " %s: %s (%s)" % (label, worker, mech) if worker else " %s: no worker is usable now" % label + + +def refusal_text(m, c, picks, why="budget", detail=""): + """At most 12 lines.""" + limit = c["direct_calls"] + m["ext"] * c["extension"] + read, build = picks + if why == "budget": + head = ("sisi: %d direct tool calls this turn (limit %d, %d characters of results). Legwork belongs to a " + "less expensive worker (rule 6)." % (m["calls"], limit, m["chars"])) + else: + head = "sisi: %s. Legwork belongs to a less expensive worker (rule 6)." % detail + lines = [head, "Router for this project:", _pick_line("reading and searching", read), + _pick_line("building", build), "Two ways on:", + " 1. Delegate the rest: `sisi delegate brief` prints the brief to fill in; start the worker as above%s." + % (", naming its model" if why != "budget" else ""), + " 2. Record why doing it directly is cheaper: `sisi unit direct \"\"`%s." + % (" (allows %d more calls this turn)" % c["extension"] if why == "budget" + else " (also allows this same-model delegation)"), + "This call was not run."] + return "\n".join(lines) + + +def route_text(): + from . import unitguard + return ("sisi: ask the router before delegating (rule 6; it also records your difficulty guess). Run " + "`sisi route --kind K --difficulty N` first: K is one of %s; N is 1 routine, 2 ordinary, 3 hard. " + "This delegation was not started; start it again after." % ", ".join(unitguard.ledger_kinds())) + + +def record_route(kind, difficulty, worker, cwd, retry_of=None): + """`sisi route` ran: the session's routing decision (kind, difficulty guess, recommended worker, time). Quiet + when no session can be named.""" + sid = find_session(cwd) + if not sid: + return + with Meter(sid) as m: + m["route"] = {"kind": kind, "difficulty": difficulty, "worker": worker, "ts": time.time(), "retry_of": retry_of} + m["route_asked"] = False + _event(m, sid, "route", kind=kind, difficulty=difficulty, worker=worker) + + +def repeat_text(key, n): + return ("sisi: `%s` has failed %d times in a row and no file has changed since, so running it again will not " + "produce new information (rule 5). Diagnose why it fails, or change the approach; this one repeat is " + "refused once." % (key[:80], n)) + + +# ---------------------------------------------------------------- hook entry points + +_RESP_KEYS = ("tool_response", "toolResponse", "tool_result", "toolResult", "tool_output", "result", "output", "error") + + +def _chars(payload): + n = 0 + for k in _RESP_KEYS: + if k in payload and payload[k] is not None: + stack = [payload[k]] + while stack: + x = stack.pop() + if isinstance(x, str): + n += len(x) + elif isinstance(x, dict): + stack.extend(x.values()) + elif isinstance(x, list): + stack.extend(x) + break + return n + + +def _failed(payload, ev): + if "failure" in str(ev or "").lower(): + return True + resp = None + for k in _RESP_KEYS: + if isinstance(payload.get(k), dict): + resp = payload[k] + break + if resp: + for k in ("exit_code", "exitCode", "returncode", "returnCode", "code"): + v = resp.get(k) + if isinstance(v, int) and not isinstance(v, bool): + return v != 0 + return False + + +def _norm(cmd): + return " ".join((cmd or "").split()) + + +def _is_worker(payload, sess, m): + return bool(m.get("worker") or sess.get("subagent") or store.is_subagent_payload(payload)) + + +def _transcript_model(path): + """The model the main thread last answered with, from the tail of the host's transcript (a session-start + payload need not carry it). None when it cannot be read.""" + try: + path = os.path.expanduser(path) + with open(path, "rb") as f: + f.seek(max(0, os.path.getsize(path) - 200000)) + tail = f.read().decode("utf-8", "replace") + except (OSError, TypeError): + return None + for line in reversed(tail.splitlines()): + if '"assistant"' not in line: + continue + try: + d = json.loads(line) + except ValueError: + continue + msg = d.get("message") if isinstance(d, dict) else None + model = msg.get("model") if isinstance(msg, dict) else None + if isinstance(model, str) and model and not model.startswith("<") and not d.get("isSidechain"): + return model + return None + + +def _own_model(payload, sess, m=None): + v = payload.get("model") + if isinstance(v, str) and v: + return v + if sess.get("model"): + return sess["model"] + if m is not None and m.get("model"): + return m["model"] + tp = payload.get("transcript_path") or sess.get("transcript_path") + model = _transcript_model(tp) if tp else None + if model and m is not None: + m["model"] = model + return model + + +def before(payload, host=None): + """{"deny": text} to refuse the call, {"context": text} for advice, {} otherwise. On a host whose before-tool + hook cannot refuse (canon/orchestration-tools.json), a refusal is recorded as not made and the call goes on.""" + out = _before(payload, host) + if out.get("deny") and refuse_style(host or store.tool() or "claude-code") not in ("json-deny", "exit-2"): + try: + from . import watch + _t, _c, _e, cwd, sid = watch.extract(payload) + with Meter(sid or "cwd-" + cwd) as m: + _event(m, sid or "cwd-" + cwd, "unrefused", why="the host cannot refuse") + except Exception as e: + store.log_error("orchestration-unrefused", e) + return {} + return out + + +def _before(payload, host=None): + c = cfg() + if not c["enabled"]: + return {} + from . import watch + tool, cmd, _ev, cwd, sid = watch.extract(payload) + host = host or store.tool() or "claude-code" + hd = host_data(host) + if not hd or store.is_subagent_payload(payload): + return {} + sid = sid or "cwd-" + cwd + inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {}) + kind = classify(host, tool, inp, cmd) + shell = watch.is_shell(tool, cmd) + if str(tool or "").lower() in {str(n).lower() for n in (hd.get("exempt") or {}).get("dialog") or []}: + return _dialog_guard(payload, host, sid, cwd) + if kind == "exempt" and not shell: + return {} + sess = store.load_session(sid) + with Meter(sid) as m: + if _is_worker(payload, sess, m): + return {} + project = _project(m, cwd) + m["last_tool"] = tool + if shell: + key = _norm(cmd) + e = m["fails"].get(key) + if e and e.get("n", 0) >= 3 and not e.get("refused"): + from . import gitutil + try: + fp = gitutil.fingerprint(cwd) + except Exception: + fp = None + if fp == e.get("fp"): + e["refused"] = True + m["refusals"] += 1 + _event(m, sid, "refusal", why="repeat", tool=tool) + return {"deny": repeat_text(key, e["n"])} + m["fails"].pop(key, None) + if kind == "exempt": + return {} + if kind == "delegation": + return _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd) + limit = c["direct_calls"] + m["ext"] * c["extension"] + chars_limit = c["direct_chars"] * limit / float(c["direct_calls"]) + if m["calls"] >= limit or m["chars"] >= chars_limit: + own = _own_model(payload, sess, m) + picks = _picks(project, own) + if not any(p[0] for p in picks): + m["calls"] += 1 + _event(m, sid, "unrefused", why="no usable worker", tool=tool) + _event(m, sid, "call", tool=tool) + return {} + m["refusals"] += 1 + _event(m, sid, "refusal", why="budget", tool=tool, calls=m["calls"], chars=m["chars"]) + return {"deny": refusal_text(m, c, picks)} + m["calls"] += 1 + _event(m, sid, "call", tool=tool) + return {} + + +def _dialog_guard(payload, host, sid, cwd): + """The question dialog on a main thread, after an unavailability was recorded and before the agent has + fallen back: refused once with the fallback instruction. State, not wording: the question is never read. + Nothing usable to fall back to, a worker session, or a host that cannot refuse: allowed.""" + from . import fallback, workers + if refuse_style(host) not in ("json-deny", "exit-2"): + return {} + sess = store.load_session(sid) + with Meter(sid) as m: + info = m.get("unavail") + if not info or _is_worker(payload, sess, m): + return {} + own = _own_model(payload, sess, m) + project = _project(m, cwd) + worker, _mech, _n = workers.recommend(info.get("kind") or "impl", info.get("difficulty") or 2, project, own) + if worker is None: + return {} + m["unavail"] = None # once: a second question this turn is the agent's own + m["refusals"] += 1 + _event(m, sid, "refusal", why="question-after-unavailable", tool=payload.get("tool_name")) + return {"deny": fallback.fallback_text(info, project, own)} + + +def _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd): + spec = delegation_spec(hd, tool) or {} + model = _dig(inp, spec.get("model", "model")) + model = model.strip() if isinstance(model, str) else "" + text = _dig(inp, spec.get("brief", "prompt")) + own = _own_model(payload, sess, m) + problem = None + if not model: + problem = "this delegation names no model, so the subagent would run on this session's own model%s" \ + % (" (%s)" % own if own else "") + elif own and workers_same(model, own): + problem = "this delegation names this session's own model (%s)" % own + if problem and not m.get("same_model_ok"): + picks = _picks(m.get("project") or cwd, own) + if any(p[0] for p in picks): + m["refusals"] += 1 + _event(m, sid, "refusal", why="delegation-model", tool=tool) + return {"deny": refusal_text(m, c, picks, why="delegation", detail=problem)} + from . import brief, workers + now = time.time() + route = m.get("route") + if route and now - float(route.get("ts") or 0) > c["route_window_min"] * 60: + route = None # a decision from long ago is no decision + if route is None and not m.get("route_asked"): + m["route_asked"] = True # once: the next delegation goes through even without a decision + m["refusals"] += 1 + _event(m, sid, "refusal", why="route", tool=tool) + return {"deny": route_text()} + import uuid + run_id = uuid.uuid4().hex[:8] + worker = model or own or "(inherited)" + against = None + if route and route.get("worker"): + against = not workers.same_model(worker, route["worker"]) + try: + workers.append_record({"kind": "run", "id": run_id, "ts": round(now), + "type": (route or {}).get("kind"), "difficulty": (route or {}).get("difficulty"), + "route_worker": (route or {}).get("worker"), "chosen_against_route": against, + "retry_of": (route or {}).get("retry_of"), "worker": worker, "model": model or own, "tool": workers.host_tool(), "cwd": m.get("project") or cwd, + "session": sid, "started": round(now), "ended": None, "minutes": None, + "status": "pending", "origin": "hook", "tokens": None, "tokens_class": "unavailable"}) + except OSError as e: + store.log_error("orchestration-run", e) + key = payload.get("tool_use_id") if isinstance(payload.get("tool_use_id"), str) else "last" + m["pending"][key] = {"run": run_id, "t0": now, "worker": worker} + m["unavail"] = None # the agent is falling back (or delegating anew): nothing left to refuse a question for + _event(m, sid, "delegation", run=run_id, worker=worker) + known = bool(route and route.get("kind") and route.get("difficulty")) + lines = ["sisi: delegation recorded as run %s%s. When it returns, judge it: `sisi delegate judge %s --outcome " + "accepted|rejected --check read|tests|diffstat|review|none%s`." + % (run_id, (" (%s, difficulty %s%s)" % (route["kind"], route["difficulty"], + "; you chose %s over the router's %s" % (worker, route["worker"]) if against else "")) + if known else "", run_id, "" if known else " --type KIND --difficulty 1|2|3")] + if isinstance(text, str): + lines += ["sisi brief advice: " + a for a in brief.check(text)] + return {"context": "\n".join(lines)} + + +def workers_same(a, b): + from . import workers + return workers.same_model(a, b) + + +def after(payload, host=None): + """Record what a call returned: result characters, a delegation's end, a failing shell command. + {"context": text} may carry a line for the agent.""" + c = cfg() + if not c["enabled"]: + return {} + from . import watch + tool, cmd, ev, cwd, sid = watch.extract(payload) + host = host or store.tool() or "claude-code" + hd = host_data(host) + if not hd or store.is_subagent_payload(payload): + return {} + sid = sid or "cwd-" + cwd + inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {}) + kind = classify(host, tool, inp, cmd) + shell = watch.is_shell(tool, cmd) + if kind == "exempt" and not shell: + return {} + sess = store.load_session(sid) + out = {} + with Meter(sid) as m: + if _is_worker(payload, sess, m): + return {} + _project(m, cwd) + if kind == "delegation": + return _after_delegation(payload, ev, sid, m, sess, cwd) + if shell and re.search(r"\bsisi\b.*\bdelegate\b", cmd or "", re.S): # alone or inside a longer command line + from . import fallback + note = fallback.shell_notice(_flat(payload)) + if note: # `sisi delegate` recorded the worker down itself; hand over the fallback in the same breath + km = re.search(r"--kind[ =](\S+)", cmd or "") + dm = re.search(r"--difficulty[ =]([123])\b", cmd or "") + text = fallback.handle(m, sid, cwd, note[1], own_model=_own_model(payload, sess, m), worker=note[0], record=False, + kind=km.group(1) if km else None, difficulty=int(dm.group(1)) if dm else None) + return {"context": text} if text else {} + if shell: + key = _norm(cmd) + if _failed(payload, ev): + from . import gitutil + try: + fp = gitutil.fingerprint(cwd) + except Exception: + fp = None + e = m["fails"].get(key) + if e and e.get("fp") == fp: + e["n"] = e.get("n", 0) + 1 + else: + m["fails"][key] = {"n": 1, "fp": fp, "refused": False} + else: + m["fails"].pop(key, None) + if kind == "direct": + n = _chars(payload) + m["chars"] += n + _event(m, sid, "chars", tool=tool, chars=n) + return out + + +def _flat(payload): + parts, stack = [], [payload.get(k) for k in _RESP_KEYS if payload.get(k) is not None][:1] + while stack: + x = stack.pop() + if isinstance(x, str): + parts.append(x) + elif isinstance(x, dict): + stack.extend(x.values()) + elif isinstance(x, list): + stack.extend(x) + return "\n".join(parts) + + +def _after_delegation(payload, ev, sid, m, sess=None, cwd=None): + from . import workers + key = payload.get("tool_use_id") if isinstance(payload.get("tool_use_id"), str) else "last" + ent = m["pending"].get(key) + if ent is None and m["pending"]: + key = sorted(m["pending"], key=lambda k: m["pending"][k]["t0"])[-1] + ent = m["pending"][key] + if ent is None: + return {} + now = time.time() + resp = next((payload[k] for k in _RESP_KEYS if payload.get(k) is not None), None) + if isinstance(resp, dict) and (resp.get("isAsync") or resp.get("status") == "async_launched"): + # the worker was only launched: it is finished when the host's notice arrives (new_turn), not now + m["pending"][key] = dict(ent, agent=resp.get("agentId"), model=resp.get("resolvedModel")) + return {} + from . import fallback + text = _flat(payload) + if fallback.looks_failed(text, failure_event="failure" in str(ev or "").lower()): + out = fallback.handle(m, sid, cwd or m.get("project") or os.getcwd(), text, own_model=_own_model(payload, sess or {}, m), + worker=ent.get("worker"), run_id=ent["run"]) + if out: + m["pending"].pop(key, None) + return {"context": out} + tokens, _cost = workers.extract_usage(json.dumps(resp) if resp is not None else "") + minutes = round((now - ent["t0"]) / 60.0, 2) + if isinstance(resp, dict): + ms = resp.get("totalDurationMs", resp.get("total_duration_ms")) + if isinstance(ms, (int, float)) and not isinstance(ms, bool): + minutes = round(ms / 60000.0, 2) + m["pending"].pop(key, None) + failed = "failure" in str(ev or "").lower() + try: + workers.append_record({"kind": "run-end", "run_id": ent["run"], "ts": round(now), "ended": round(now), + "minutes": minutes, "tokens": tokens, + "tokens_class": "measured" if tokens is not None else "unavailable", + "status": "failed" if failed else "waiting"}) + except OSError as e: + store.log_error("orchestration-run-end", e) + return {"context": "sisi: delegation run %s finished (%s min). Judge it: `sisi delegate judge %s --outcome " + "accepted|rejected --check read|tests|diffstat|review|none --type KIND --difficulty 1|2|3`." + % (ent["run"], minutes, ent["run"])} + + +# ---------------------------------------------------------------- `sisi unit direct` + +_FILLER = set("easier easy quick quicker quickly faster fast simpler simple convenient convenience myself directly " + "direct itself rather instead because just efficient efficiently less effort overhead trivial small " + "short like want prefer simply".split()) + + +def reason_is_generic(text): + """The existing generic-text check, plus the filler a lazy reason is made of: it must name something + specific (a number, a file, a particular fact), not only that direct work is easier or faster.""" + from . import learning as L + if L.is_generic(text): + return True + toks = re.findall(r"[a-z0-9_]+", (text or "").lower()) + if any(any(ch.isdigit() for ch in t) for t in toks): + return False + rest = [t for t in toks if len(t) >= 2 and t not in L.STOP and t not in L.GENERIC_WORDS and t not in _FILLER] + return len(rest) < 2 + + +def find_session(cwd): + """The session a `sisi unit direct` belongs to: SISI_SESSION_ID, else the most recently active meter + in this project, else the most recent one of all (within the last ten minutes).""" + sid = os.environ.get("SISI_SESSION_ID") + if sid: + return sid + d = os.path.join(paths.state(), "sessions") + best, any_best = None, None + from . import gitutil + project = gitutil.root(cwd) or cwd + try: + names = [n for n in os.listdir(d) if n.endswith(".meter.json")] + except OSError: + return None + for n in names: + try: + with open(os.path.join(d, n), encoding="utf-8") as f: + mm = json.load(f) + except (OSError, ValueError): + continue + ts = float(mm.get("last_ts") or 0) + sid = mm.get("sid") or n[:-len(".meter.json")] + if mm.get("project") == project and (best is None or ts > best[0]): + best = (ts, sid) + if time.time() - ts < 600 and (any_best is None or ts > any_best[0]): + any_best = (ts, sid) + return (best or any_best or (0, None))[1] + + +def cmd_direct(args, cwd=None): + """`sisi unit direct ""`: record why doing this directly is cheaper; grants an extension.""" + reason = " ".join(args).strip() + if not reason: + print('usage: sisi unit direct ""') + return 1 + if reason_is_generic(reason): + print("sisi: that reason is generic: say what makes direct work cheaper here (which file, how many lines, " + "what a brief would have to carry), not only that it is easier or faster.") + return 1 + cwd = cwd or os.getcwd() + sid = find_session(cwd) + if not sid: + print("sisi: no session is being metered here; nothing to extend (no limit applies).") + return 0 + c = cfg() + with Meter(sid) as m: + if any(e.get("reason") == reason for e in m["ext_log"]): + print("sisi: that same reason was already recorded this turn; say what is different now, or delegate.") + return 1 + m["ext"] += 1 + m["same_model_ok"] = True + m["ext_log"].append({"reason": reason, "ts": store.now(), "calls": c["extension"]}) + _event(m, sid, "extension", reason=reason[:300], calls=c["extension"]) + limit = c["direct_calls"] + m["ext"] * c["extension"] + print("recorded: %d more direct calls allowed this turn (limit now %d, extension %d); the reason is kept with " + "the unit record." % (c["extension"], limit, m["ext"])) + return 0 + + +# ---------------------------------------------------------------- the gate asks for judgements + +def judgement_sendback(payload, sid): + """Text asking for the judgements of this session's finished, unjudged delegations, once per set of + runs; None when there is nothing to ask.""" + from . import workers + runs = [r for r in workers.unjudged_runs() if r.get("session") == sid] + if not runs: + return None + ids = sorted(r["id"] for r in runs) + with Meter(sid) as m: + if m["judge_asked"] == ids: + return None + m["judge_asked"] = ids + lines = ["sisi: %d delegation(s) from this session finished and are not judged yet (rule 6: the record is the " + "routing policy):" % len(runs)] + for r in runs[:6]: + lines.append("- %s: %s%s" % (r["id"], r.get("worker"), (", %s min" % r["minutes"]) if r.get("minutes") is not None else "")) + lines.append("Judge each: `sisi delegate judge ID --outcome accepted|rejected --check read|tests|diffstat|review|none " + "--type KIND --difficulty 1|2|3`, then finish. (Asked once for this set.)") + return "\n".join(lines) + + +FALLBACK_SENDBACKS = 2 # bounded, like every send-back: a session is never trapped + + +def fallback_sendback(payload, sid): + """The turn is ending with an unavailability recorded and no fallback started: sent back (at most twice) with + the fallback instruction, when the router has a worker to name. State, not wording.""" + from . import fallback, workers + sess = store.load_session(sid) + with Meter(sid) as m: + info = m.get("unavail") + if not info or int(m.get("fallback_asked") or 0) >= FALLBACK_SENDBACKS or _session_is_worker(m, sess): + return None + own = _own_model({}, sess, m) + project = m.get("project") or os.getcwd() + worker, _mech, _n = workers.recommend(info.get("kind") or "impl", info.get("difficulty") or 2, project, own) + if worker is None: + return None + m["fallback_asked"] = int(m.get("fallback_asked") or 0) + 1 + text = fallback.fallback_text(info, project, own) + return "sisi: not finished: the failed task has not been given to another worker yet.\n" + text + + +def report_sendback(payload, sid): + """The final message to the person names a worker or provider that was unavailable this turn: sent back once, + because which worker is out is internal (SPEC 9.7, 17). Judged on the names recorded, never on the wording.""" + from . import questions + with Meter(sid) as m: + names = m.get("unavail_names") or [] + if not names or m.get("report_asked"): + return None + sess = store.load_session(sid) + final = payload.get("last_assistant_message") # the host's own copy of the final message, when it sends one + if not isinstance(final, str) or not final: + tp = payload.get("transcript_path") if isinstance(payload.get("transcript_path"), str) else sess.get("transcript_path") + turn = questions._last_turn(tp) if isinstance(tp, str) and tp else None + final = turn[0] if turn else "" + low = final.lower() + hits = [n for n in names if n in low] + if not hits: + return None + m["report_asked"] = True + return ("sisi: your final message mentions a worker, provider or failure that was internal (%s). Do not " + "report it. Say only what the person receives and when, and only if that differs from what they expect; " + "then finish again." % ", ".join(hits[:3])) + + +# ---------------------------------------------------------------- the unit record + +def _inside(project, root): + root = str(root or "").rstrip(os.sep) + return bool(project) and (project == root or str(project).startswith(root + os.sep)) + + +def summary(project, t0, t1): + """Facts about orchestration for one project between two epochs, or None when nothing was metered.""" + from . import workers + evs = [e for e in store.read(EVENTS) if isinstance(e, dict) and _inside(e.get("project"), project) + and isinstance(e.get("ts"), (int, float)) and (t0 is None or e["ts"] >= t0) and e["ts"] <= t1] + if not evs: + return None + calls = sum(1 for e in evs if e["ev"] == "call") + chars = sum(int(e.get("chars") or 0) for e in evs if e["ev"] == "chars") + refusals = [e for e in evs if e["ev"] == "refusal"] + exts = [e for e in evs if e["ev"] == "extension"] + runs = [e["run"] for e in evs if e["ev"] == "delegation"] + records = workers.read_records() + judged = {r.get("run_id") for r in records if r.get("kind") == "attempt"} + done = sum(1 for r in runs if r in judged) + total = calls + len(runs) + return {"direct_calls": calls, "direct_chars": chars, "refusals": len(refusals), + "extensions": len(exts), "extension_reasons": [e.get("reason") for e in exts], + "unrefused": sum(1 for e in evs if e["ev"] == "unrefused"), + "delegations_started": len(runs), "delegations_judged": done, + "delegations_unjudged": len(runs) - done, + "delegated_share": round(len(runs) / float(total), 3) if total else None} + + +def telemetry(project, t0, t1): + """The orchestration part of a unit's telemetry, each value with its class.""" + from .scorecard import val, unavailable + s = summary(project, t0, t1) + keys = ("direct_calls", "direct_chars", "refusals", "extensions", "extension_reasons", "delegations_started", + "delegations_judged", "delegations_unjudged", "delegated_share") + if s is None: + return {k: unavailable() for k in keys} + return {k: (val(s[k], "measured") if s[k] is not None else unavailable()) for k in keys} + + +def status_line(project, t0, t1): + s = summary(project, t0, t1) + if s is None: + return None + share = ("%d%%" % round(s["delegated_share"] * 100)) if s["delegated_share"] is not None else "n/a" + line = ("orchestration (measured): %d direct calls, %d characters read, %d refusals, %d extension(s), " + "%d delegation(s) started (%d judged, %d unjudged), %s of tool calls delegated" + % (s["direct_calls"], s["direct_chars"], s["refusals"], s["extensions"], s["delegations_started"], + s["delegations_judged"], s["delegations_unjudged"], share)) + if s["extension_reasons"]: + line += "; extension reasons: " + " | ".join(str(r) for r in s["extension_reasons"]) + return line diff --git a/sisi/prompt.py b/sisi/prompt.py index 89d9b19..bd4bae9 100644 --- a/sisi/prompt.py +++ b/sisi/prompt.py @@ -82,13 +82,32 @@ def _done_means(recipe): return bullets -def build_context(query, session=None): +def is_request(query, payload=None): + """Did a person type this message? One definition, harvest.typed_text, the rule the delivery timing uses. A + host's notice that a task finished or failed, an automated wake-up, and anything the hook cannot tell is not + a request (False): no recipe is attached to it.""" + try: + from . import harvest + return harvest.typed_text(payload if isinstance(payload, dict) else {}, queued_prompt=query)[0] is not None + except Exception as e: + store.log_error("prompt-request", e) + return False + + +def context_for(query, session=None, payload=None): + """The request-time context for one prompt hook call: recipe and lessons for a person's request, lessons + only for a message a machine sent.""" + return build_context(query, session=session, recipe=is_request(query, payload)) + + +def build_context(query, session=None, recipe=True): """The context to inject for one human request, or "" when nothing strictly matches. Learnings come only from learning.delivery_text (earned scope, framed as information); - no showing is recorded, so nothing is promoted by being printed.""" + no showing is recorded, so nothing is promoted by being printed. `recipe=False` leaves the recipe matcher + out (the message is not a person's request).""" if is_trivial(query): return "" - recipe = _best_recipe(query) + recipe = _best_recipe(query) if recipe else None lesson_text = _L.delivery_text(os.getcwd(), query).strip() lesson_lines = lesson_text.split("\n")[1:] if lesson_text else [] if not recipe and not lesson_lines: @@ -112,6 +131,19 @@ def build_context(query, session=None): return text +def meter_new_turn(session, cwd, query): + """Every prompt the session receives goes to the orchestration meter (a human request starts its turn again; + a host notice that a worker is unavailable returns the fallback to hand over). Returns text or None; never + raises.""" + try: + if session and query: + from . import orchestration + return orchestration.new_turn(session, cwd, query) + except Exception as e: + store.log_error("prompt-meter", e) + return None + + def extract_prompt(payload): """The human's request text from a hook payload, across the tools' documented field names.""" if not isinstance(payload, dict): @@ -131,7 +163,7 @@ def main(args=()): args = list(args) plain = "--plain" in args args = [a for a in args if a != "--plain"] - query, session = None, None + query, session, payload = None, None, None if args: query = " ".join(args) plain = True @@ -150,7 +182,8 @@ def main(args=()): os.chdir(cwd) if not query: return 0 - text = build_context(query, session=session) + fb = meter_new_turn(session, os.getcwd(), query) + text = "\n".join(x for x in (fb, context_for(query, session, payload)) if x) if not text: return 0 if plain: diff --git a/sisi/risk.py b/sisi/risk.py index 5e0c55b..0d6f684 100644 --- a/sisi/risk.py +++ b/sisi/risk.py @@ -223,6 +223,9 @@ def _diff_blocks(diff_text): return out +NO_PATHS = "no changed paths" + + def assess(paths, diff_text=None, extra_patterns=None, patterns=None): """Return (floor_profile, reasons). Adding a path never lowers the floor.""" pats = list(patterns if patterns is not None else _patterns_from(default_table())) @@ -230,7 +233,7 @@ def assess(paths, diff_text=None, extra_patterns=None, patterns=None): pats += [p for p in extra_patterns if isinstance(p, dict) and p.get("profile") in _ORDER] clean = [str(p).replace(os.sep, "/") for p in (paths or []) if str(p).strip()] if not clean: - return "trivial", ["no changed paths"] + return "trivial", [NO_PATHS] best, reasons = "trivial", [] def offer(prof, text): diff --git a/sisi/rulecmd.py b/sisi/rulecmd.py index 63144be..2ef1fff 100644 --- a/sisi/rulecmd.py +++ b/sisi/rulecmd.py @@ -86,51 +86,51 @@ def _own_the_outcome(): def _size_by_risk(): return _say(enforced=["the end-of-turn gate computes the risk floor of the change, takes the profile the contract declares " - "(lowering it needs a reason) and sends the agent back for whatever that profile requires" + "(lowering it needs a reason) and sends the agent back for whatever that profile requires (sisi/gate.py, sisi/risk.py, sisi/assure.py)" if _gate_wired() and _has("risk", "assess", "requirements_for") and _has("assure", "effective_profile", "missing") else None, - "a contract without a declared `risk.profile` is invalid" + "a contract without a declared `risk.profile` is invalid (sisi/contract.py)" if _has("contract", "RISK_PROFILES") and _has("assure", "missing") else None, "the before-tool hook works out the risk floor of the path about to change (with what this session " "already changed) and refuses %s unless a valid unit stands behind it; the floor wins over a lower " - "declared profile without a reason" % _guard_scope() if _guard_scope() else None], - measured=["`sisi risk` prints the floor and what the profile requires, the unit record keeps the profile" + "declared profile without a reason (sisi/unitguard.py, sisi/watch.py)" % _guard_scope() if _guard_scope() else None], + measured=["`sisi risk` prints the floor and what the profile requires, the unit record keeps the profile (sisi/risk.py, sisi/unit.py)" if _has("risk", "assess") else None], judgement=["raising the profile when you know better; lowering it needs a reason"]) def _define_done(): - return _say(enforced=["contract check refuses a check with no command or one that cannot fail (vacuous)" + return _say(enforced=["contract check refuses a check with no command or one that cannot fail (vacuous) (sisi/contract.py)" if _has("contract", "vacuous_reason") else None, "end-of-turn gate sends the agent back when the profile needs a contract and there is none, " - "or when a check lacks what it covers, invariants or the requirement list are missing" + "or when a check lacks what it covers, invariants or the requirement list are missing (sisi/gate.py, sisi/assure.py)" if _gate_wired() and _has("assure", "missing") else None, "%s is refused before it runs unless this session holds a valid unit: opened or continued by it " "(`sisi unit continue`), not stale (`unit.stale_hours`), `sisi contract check` passing with no placeholder, " - "and carrying what its risk profile needs before building" % _guard_scope() + "and carrying what its risk profile needs before building (sisi/unitguard.py, called from sisi/watch.py)" % _guard_scope() if _guard_scope() else None, "`sisi unit pause` is refused without such a unit (a pause defers waiting checks and the retro, never the " - "contract), and a pause silences the gate only for the session holding the unit" + "contract), and a pause silences the gate only for the session holding the unit (sisi/unitguard.py, sisi/unit.py)" if _has("unitguard", "pause_refusal") else None, "the gate never judges a session's changes against a unit the session does not hold: it sends back " - "to continue, park or init" if _gate_wired() and _has("unitguard", "bound_fresh") else None, - "every refusal is kept in the unit record and counted by `sisi status`" + "to continue, park or init (sisi/gate.py)" if _gate_wired() and _has("unitguard", "bound_fresh") else None, + "every refusal is kept in the unit record and counted by `sisi status` (sisi/unitguard.py, sisi/scorecard.py)" if _has("unitguard", "record_refusal") else None], judgement=["the goal in the person's words, one check on the purpose, invariants captured before the first edit"]) def _verify_enough(): - return _say(enforced=["`sisi verify` runs the checks with five statuses (passed, failed, skipped, not-applicable, not-run), nothing unrun passes" + return _say(enforced=["`sisi verify` runs the checks with five statuses (passed, failed, skipped, not-applicable, not-run), nothing unrun passes (sisi/verify.py)" if _has("verify", "STATUSES") else None, - "the end-of-turn gate runs the fast checks and sends the agent back on a failure, with the failing evidence lines" + "the end-of-turn gate runs the fast checks and sends the agent back on a failure, with the failing evidence lines (sisi/gate.py)" if _gate_wired() and _has("assure", "failure_lines") else None, "high-risk profiles need evidence from someone or something other than the author: a check marked " "independent does not count when `by` is empty, the session's own model or a self-reference, and a " - "review counts only from a worker other than the author's model, judged with a check stronger than none" + "review counts only from a worker other than the author's model, judged with a check stronger than none (sisi/assure.py, sisi/unitguard.py)" if _has("assure", "independent_evidence") and _has("unitguard", "is_self_reference") else - ("high-risk profiles need evidence from someone or something other than the author" + ("high-risk profiles need evidence from someone or something other than the author (sisi/assure.py)" if _has("assure", "independent_evidence") else None)], - measured=["a commit or merge with no passing `sisi verify` for the tree gets a notice, never a block" + measured=["a commit or merge with no passing `sisi verify` for the tree gets a notice, never a block (sisi/watch.py)" if _has("watch", "commit_notice") else None], judgement=["choosing the technique, which checks the change can affect, watching a test fail once"]) @@ -142,12 +142,54 @@ def _deliver_fast(): judgement=["parallel work, background checks, handing over early, changing approach when stuck"]) +def _pre_tool_wired(): + try: + from . import wiring + return "PreToolUse" in wiring.hook_cmds() and not wiring.HOOK_MATCHERS.get("PreToolUse") + except Exception: + return False + + def _orchestrate(): - return _say(enforced=["a delegation brief without outcome, acceptance or files it may change is refused (`sisi delegate`)" - if _has("workers", "cmd_delegate") and _has("brief", "missing_required") else None], - measured=["the delegation ledger and `sisi delegate judge`, `sisi route` recommends the worker from that record" - if _has("routing", "choose") and _has("workers", "cmd_delegate") else None], - judgement=["who gets the task, how much to check what comes back, recording the judgement"]) + meter = _pre_tool_wired() and _has("orchestration", "before", "cmd_direct") + return _say(enforced=["a delegation brief without outcome, acceptance or files it may change is refused (`sisi delegate`; sisi/brief.py, sisi/workers.py)" + if _has("workers", "cmd_delegate") and _has("brief", "missing_required") else None, + "the before-tool hook counts the main thread's direct tool calls and result characters for every tool, and " + "refuses the next one past the budget (`orchestrate.direct_calls`, `orchestrate.direct_chars`), naming the router's " + "workers, asked at difficulty 1 for reading and 2 for building; `sisi unit direct \"\"` extends the turn with a specific reason " + "(a generic one is refused) (sisi/orchestration.py)" + if meter else None, + "a delegation that names no model, or the session's own model, is refused with the router's pick; an allowed " + "one has its brief checked and is written to the ledger as a run (sisi/orchestration.py)" + if meter and _has("orchestration", "_before_delegation") else None, + "the end-of-turn gate asks for the judgement of each finished delegation, once per set of runs (sisi/orchestration.py, sisi/gate.py)" + if _gate_wired() and _has("orchestration", "judgement_sendback") else None, + "a shell command that failed three times in a row with no file changed is refused once (rule 5) (sisi/orchestration.py)" + if meter else None, + "an unavailable worker (a limit, quota, login or connection failure arriving as a delegation result or as " + "a later notice) is recorded down with the reset time parsed from the message, the router's next worker " + "is handed over for the same brief; a question-dialog call right after it is refused once, ending the turn with no fallback " + "started is sent back once, and so is a final message that names the unavailable worker (sisi/fallback.py, sisi/orchestration.py)" + if meter and _has("fallback", "handle", "fallback_text") else None, + "a delegation with no `sisi route` decision in the last minutes (`orchestrate.route_window_min`) is refused once; " + "the run keeps the kind (one of the ledger's, else `sisi route` refuses it) and difficulty guess, and a worker other than the router's pick " + "is recorded as an override (sisi/orchestration.py, sisi/workers.py)" + if meter and _has("orchestration", "record_route") else None, + "`sisi route --retry-of ID` keeps the worker with a better brief after a first rejection, then moves to a worker whose " + "evidence is strictly better (sisi/routing.py retry_choice, sisi/workers.py)" + if _has("workers", "retry_context") and _has("routing", "retry_choice") else None, + "the before-tool hook answers one refusal at a time, in a fixed order: workers are exempt, then the contract " + "guard, then the delegation guard, then the direct-work budget (sisi/watch.py)" + if meter and _guard_scope() else None], + measured=["the delegation ledger and `sisi delegate judge`, `sisi route` recommends the worker from that record (sisi/routing.py, sisi/workers.py)" + if _has("routing", "choose") and _has("workers", "cmd_delegate") else None, + "the unit record and `sisi status` show direct calls and characters, refusals, extensions with their reasons, " + "delegations started, judged and unjudged, and the share of tool calls delegated (sisi/orchestration.py, sisi/scorecard.py)" + if _has("orchestration", "telemetry") else None, + "`sisi workers` shows how often the router was overridden and how the overrides turned out; a model discovery " + "has not seen before is named once at session start as unproven (sisi/workers.py)" + if _has("workers", "override_line", "new_worker_line") else None], + judgement=["who gets the task, how much to check what comes back, the quality of a brief"]) def _report_plainly(): diff --git a/sisi/scorecard.py b/sisi/scorecard.py index f2e824a..289b96d 100644 --- a/sisi/scorecard.py +++ b/sisi/scorecard.py @@ -211,6 +211,8 @@ def build_scorecard(c, results, telemetry, delivery_status): "overlapped_delegations": T("overlapped_delegations"), "worker_minutes": T("worker_minutes"), "wall_time_s": T("time_to_validated_completion_s"), + # who did the work: the main thread's own calls against delegated ones (sisi/orchestration.py) + **{"orch_" + k: v for k, v in (tel.get("orchestration") or {}).items()}, }, "human_experience": { "human_messages": T("human_messages"), @@ -373,6 +375,12 @@ def open_units(cwd=None): started, basis = U.start_of(c, p) row = {"id": c["id"], "status": c.get("status", "open"), "age": _age(started), "goal": c.get("goal") or "", "age_basis": basis} + try: + from . import orchestration + t0 = harvest.epoch(started) if isinstance(started, str) else None + row["orchestration"] = orchestration.status_line(project, t0, time.time()) + except Exception as e: + store.log_error("status-orchestration", e) if row["status"] == "paused": pz = next((x for x in reversed(c.get("pauses") or []) if isinstance(x, dict) and not x.get("until")), {}) row["waiting_for"], row["paused_for"] = pz.get("what"), _age(pz.get("since")) @@ -438,6 +446,8 @@ def format_open(rows): lines.append("open %-24s age %s%s %s" % (r["id"], r["age"], _basis_note(r), r["goal"][:80])) if r.get("refusals"): lines.append(" the guard refused %d building step(s) before a valid unit stood behind them" % r["refusals"]) + if r.get("orchestration"): + lines.append(" " + r["orchestration"]) if r.get("lowered"): lines.append(" lowered: " + r["lowered"]) if r.get("unverified"): diff --git a/sisi/store.py b/sisi/store.py index 21f7afe..a08f5ea 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -78,6 +78,19 @@ def tool(): return None +def is_subagent_payload(payload): + """Is this hook call from a worker: started by `sisi delegate`, or marked by the host as a subagent? Kept here + (not in workers.py) so the per-tool hooks need not import the worker code.""" + if os.environ.get("SISI_WORKER_RUN"): + return True + if not isinstance(payload, dict): + return False + if payload.get("agent_id") or payload.get("agentId") or payload.get("agent_transcript_path"): + return True + tp = str(payload.get("transcript_path") or "") + return "/subagents/" in tp or tp.endswith("/subagents") + + def session_id(): return os.environ.get("SISI_SESSION_ID") or None @@ -157,6 +170,7 @@ def stamp(extra): DEFAULTS = {"gate": {"enabled": True, "budget_s": 120, "max_blocks": 3}, "verify": {"default_timeout_s": 60, "fast_limit_s": 60}, "retro": {"required": True}, + "orchestrate": {"enabled": True, "direct_calls": 6, "direct_chars": 30000, "extension": 10, "route_window_min": 15}, "scratch": {"session_max_age_days": 30, "prune_every": 20, "prune_max_delete": 1000, "prune_budget_s": 0.25}} diff --git a/sisi/tick.py b/sisi/tick.py index 7c8dc36..b10587b 100644 --- a/sisi/tick.py +++ b/sisi/tick.py @@ -101,6 +101,15 @@ def main(args=()): store.save_session(sid, sess) except Exception as e: store.log_error("tick-workers", e) + try: + sess3 = rec or store.load_session(sid) + from . import workers as _W3 + if not sess3.get("subagent") and not _W3.is_subagent_payload(payload): + line = _W3.new_worker_line() + if line: + sys.stdout.write(line + "\n") + except Exception as e: + store.log_error("tick-new-workers", e) try: from . import cycle # cycle.due_notice carries both the due-cycle line and the pending-decision line (learning.pending_notice). diff --git a/sisi/unit.py b/sisi/unit.py index 7603beb..3ff41e6 100644 --- a/sisi/unit.py +++ b/sisi/unit.py @@ -356,6 +356,13 @@ def build_telemetry(c, project, results, t0, t1, t0_basis="measured"): tel["time_in_delegations_s"] = val(0, "measured") tel["overlapped_delegations"] = val(0, "measured") + try: + from . import orchestration + tel["orchestration"] = orchestration.telemetry(project, t0, t1) + except Exception as e: # the part is measurement; never lose the record for it + store.log_error("unit-orchestration", e) + tel["orchestration"] = {} + changed = _changed_artifacts(c, project) tel["files_changed"] = val(len(changed["files"]), "measured") if changed else unavailable() tel["lines_changed"] = val(changed["lines"], "measured") if changed else unavailable() @@ -540,6 +547,7 @@ def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None, "approach": c.get("approach"), "plan": c.get("plan") or [], "workers": delegation_rows, + "orchestration": tel.get("orchestration") or {}, "models": models, "budgets": c.get("budgets"), "started": started, "started_basis": basis, "ended": ended, "closed_at": ended, "telemetry": tel, "start_commit": c.get("base_head"), @@ -927,6 +935,9 @@ def cmd_unit(args, cwd=None, out=print): C.save(p, c) out("unit %s paused: %s" % (c.get("id"), what)) return 0 + if sub == "direct": + from . import orchestration + return orchestration.cmd_direct(args[1:], cwd) if sub == "show": uid = args[1] if len(args) > 1 else None if uid is None: @@ -988,5 +999,5 @@ def cmd_unit(args, cwd=None, out=print): out("no units in this project yet") return 0 out("usage: sisi unit close [--abandon \"\"] | pause \"\" | continue | " - "park \"\" | resume ID | show [ID] | list") + "park \"\" | resume ID | direct \"\" | show [ID] | list") return 1 diff --git a/sisi/unitguard.py b/sisi/unitguard.py index eb0cd56..e5c53c0 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("*")] @@ -560,6 +589,10 @@ def _norm_lines(cmd): return "\n".join(out) +UNPARSED = "$unparsed" +_WRITES = re.compile(r"(?:^|[\s;&|(])(?:sed|perl)\b[^;&|\n]*?\s-\w*i\b|(?:^|[\s;&|(])(?:tee|rm|mv|cp|install|ln|touch|dd)\s|[^<>\d&]>>?\s*[^\s&|;)>]") + + def shell_targets(cmd, cwd): """Best-effort paths a shell command writes: redirects, tee, sed/perl -i, cp/mv/install/ln, rm/touch/mkdir, dd of=. What cannot be told from the text (an interpreter, a script) is left to the after-tool snapshot.""" @@ -569,7 +602,9 @@ def shell_targets(cmd, cwd): lex.whitespace_split = True toks = list(lex) except ValueError: - return [] + # the line cannot be split into words (nested quotes, a loop with an embedded script): if it plainly + # writes, say so with a target that is named by nothing, so the guard treats it as ordinary source + return [UNPARSED] if _WRITES.search(cmd or "") else [] segs, cur = [], [] for t in toks: if t in (";", "&", "|", "&&", "||"): @@ -595,7 +630,7 @@ def shell_targets(cmd, cwd): i += 1 words = [w for w in seg if w and not re.fullmatch(r"\d*(>>?|<\||&>>?)", w)] k = 0 - while k < len(words) and (re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", words[k]) or words[k] in ("sudo", "command", "exec", "time", "nice")): + while k < len(words) and (re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", words[k]) or words[k] in ("sudo", "command", "exec", "time", "nice", "do", "then", "else", "!", "{")): k += 1 if k >= len(words): continue @@ -635,7 +670,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): @@ -656,16 +695,20 @@ def _brief_text(payload): return " ".join(str(inp.get(k) or "") for k in ("description", "prompt", "task", "message")).lower() -def routed_kind(sess, payload): - """The kind of work a delegation was routed as (impl, review, search, ...), or None when no routing - decision is recorded for it. The one place that reads the routing record.""" - r = sess.get("route") if isinstance(sess.get("route"), dict) else None - k = r.get("kind") if r else None - return k if isinstance(k, str) and k else None +def routed_kind(sid): + """The kind of work the session's routing decision names (impl, review, search, ...), or None when no + decision is recorded. `sisi route` stores the decision in the orchestration meter; this reads it there.""" + from . import orchestration + return orchestration.routed_kind(sid) -def is_building_delegation(sess, payload): - kind = routed_kind(sess, payload) +def ledger_kinds(): + """The kinds of work the delegation ledger knows (canon/guard.json): building kinds, then the others.""" + return _list("build_kinds") + [k for k in _list("other_kinds") if k not in _list("build_kinds")] + + +def is_building_delegation(sid, payload): + kind = routed_kind(sid) if kind: return kind in _list("build_kinds") text = _brief_text(payload) @@ -743,13 +786,22 @@ def _is_contract_target(rel): return rel.replace(os.sep, "/") == ".sisi/contract.json" -def before(payload): - """True when this call was refused (the refusal is printed in the host's shape and the call must not run).""" +def check(payload): + """The refusal text when this call must not run (no valid unit stands behind it), else None. Fails open: + a tool call is never held up by an error in here. The caller prints it in the host's shape.""" try: return _before(payload) - except Exception as e: # fail open: a tool call is never held up by an error in here + except Exception as e: store.log_error("unitguard-before", e) - return False + return None + + +def before(payload): + """True when this call was refused (the refusal is printed in the host's shape and the call must not run).""" + msg = check(payload) + if msg: + _deny(msg) + return bool(msg) def _before(payload): @@ -757,26 +809,26 @@ def _before(payload): tool, cmd, _ev, cwd, sid = watch.extract(payload) kind = classify(tool, payload, cmd) if kind is None: - return False + return None if not store.config()["gate"].get("enabled", True) or workers.is_subagent_payload(payload): - return False + return None sid = sid or "cwd-" + cwd if kind == "shell": if CLAIM_RE.search(cmd or ""): note_claim(sid, cwd) if watch._may_write(cmd) is False or _is_sisi_command(cmd): - return False + return None sess = store.load_session(sid) if sess.get("subagent"): - return False + return None top = git_top(cwd) if top is None: - return False # nothing to measure outside a repository + return None # nothing to measure outside a repository rels, outside = [], False if kind == "edit": files = attribution._input_files(payload.get("tool_input") if isinstance(payload.get("tool_input"), dict) else {}) if not files: - return False + return None targets = files elif kind == "shell": targets = shell_targets(cmd, cwd) @@ -788,10 +840,10 @@ def _before(payload): outside = True else: rels.append(r) - if kind == "delegate" and not is_building_delegation(sess, payload): - return False + if kind == "delegate" and not is_building_delegation(sid, payload): + return None if kind == "edit" and not rels: - return False # only outside the project + return None # only outside the project c, cpath, project = open_unit(cwd, top) project = project or top if any(_is_contract_target(r) for r in rels): @@ -802,24 +854,31 @@ def _before(payload): if kind != "delegate" and not paths_all: if changed: store.save_session(sid, sess) - return False + return None floor, _reasons = floor_of(paths_all, project) if paths_all else ("trivial", []) + # a write whose target is named by a shell variable or substitution cannot be told from the text (found by the + # live check: `for f in src/*; do sed -i ... "$f"; done`): it is ordinary source until shown otherwise + unresolved = [r for r in rels if kind == "shell" and re.search(r"[$`]", r)] + if unresolved and assure.ORDER[floor] < assure.ORDER["isolated"]: + floor = "isolated" if kind != "delegate" and floor == "trivial": have = sess.setdefault("ug_paths", []) for r in rels: if r not in have: have.append(r) store.save_session(sid, sess) - return False + return None v = verdict(sid, sess, cwd, floor, c, cpath, project) v.setdefault("project", project) if v["state"] == "ok": _cover(sess) store.save_session(sid, sess) touch(project, c, throttle=60.0) - return False + return None if kind == "delegate": what = "delegating this work to a worker" + elif unresolved: + what = "this call would change files its own text does not name (`%s`)" % unresolved[0] else: focus = next((x for x in paths_all if floor_of([x], project)[0] != "trivial"), paths_all[0]) what = ("this call would change `%s`" % focus) if focus in rels else \ @@ -829,8 +888,7 @@ def _before(payload): msg = msg.replace("Then retry the call.", "The contract is where the worker's brief takes its acceptance from. Then retry.") record_refusal(sid, project, what, v, sess, tool) store.save_session(sid, sess) - _deny(msg) - return True + return msg def _guard_contract_write(sid, sess, c, project, cwd, kind): @@ -840,17 +898,16 @@ def _guard_contract_write(sid, sess, c, project, cwd, kind): if c is None: sess["ug_will_bind"] = os.path.realpath(project) store.save_session(sid, sess) - return False + return None state, last = bound_fresh(sess, project, c) if state == "ok": - return False + return None v = {"state": state, "problems": [], "unit": c, "profile": "isolated", "last": last, "project": project} what = "this call would rewrite the contract of unit %s" % c.get("id") msg = assure.fit(["sisi refused: %s, which this session has not opened or continued." % what] + how_on(c, state, last) + ["Then retry the call."], MAX_LINES) record_refusal(sid, project, what, v, sess, "contract-write") - _deny(msg) - return True + return msg def after(payload): diff --git a/sisi/verify.py b/sisi/verify.py index 0d60ec6..ad04460 100644 --- a/sisi/verify.py +++ b/sisi/verify.py @@ -430,12 +430,13 @@ def cmd_verify(args, cwd=None, out=print): out(" - " + e) return 1 fp = tree_fp(project, path) + dfp = deep.tree_fp(project) # deep freshness: the work, never sisi's own records (a pause must not make it stale) as_json = "--json" in args if "--deep" in args and "--all" in args: out("sisi: use either --deep or --all") return 1 if "--state" in args: - ds = deep.deep_state(c, project, fp) + ds = deep.deep_state(c, project, dfp) if as_json: out(json.dumps(deep.public(ds), indent=2)) else: @@ -449,21 +450,21 @@ def cmd_verify(args, cwd=None, out=print): if not deep.deep_items(c): out("sisi: this contract has no deep items") return 0 - started, info = deep.start_background(project, fp) + started, info = deep.start_background(project, dfp) if started: out("deep run started in the background; log: %s" % info) out("check progress with `sisi verify --state`") else: out("a deep run is already running for this project (pid %s, started %s ago, against %s). " "Not starting another." % (info.get("pid"), deep._ago(time.time() - info.get("ts", time.time())), - "the current tree" if info.get("fp") == fp else "an older tree")) + "the current tree" if info.get("fp") == dfp else "an older tree")) return 0 locked = False if "deep" in tiers and deep.deep_items(c): - locked, info = deep.adopt(project, fp) if "--worker" in args else deep.acquire(project, fp) + locked, info = deep.adopt(project, dfp) if "--worker" in args else deep.acquire(project, dfp) if not locked: out("a deep run is already running for this project (pid %s, against %s); not starting another." - % (info.get("pid"), "the current tree" if info.get("fp") == fp else "an older tree")) + % (info.get("pid"), "the current tree" if info.get("fp") == dfp else "an older tree")) tiers = tuple(t for t in tiers if t != "deep") if not tiers: return 0 @@ -473,12 +474,12 @@ def cmd_verify(args, cwd=None, out=print): contract_path=path, run_all="--all" in args) record(c, project, results, fp) if locked: - deep.save_state(project, c["id"], fp, results, [x["id"] for x in deep.deep_items(c)]) + deep.save_state(project, c["id"], dfp, results, [x["id"] for x in deep.deep_items(c)]) finally: if locked: deep.release(project) good = ok(results) - ds = deep.deep_state(c, project, fp) + ds = deep.deep_state(c, project, dfp) saved = time_saved(results) from . import unit as _unit standing = _unit.latest_results(c, _unit._unit_results(c, project, c.get("started"))) diff --git a/sisi/watch.py b/sisi/watch.py index 9e841dc..802b2dd 100644 --- a/sisi/watch.py +++ b/sisi/watch.py @@ -14,11 +14,17 @@ Both hooks fail open: any error is logged and the tool call proceeds. """ import json, os, re, time -from . import gitutil, paths, store +from . import paths, store + + +def _git(): + """gitutil, imported when a measurement needs it: a hook call that only meters (most tools) must stay light.""" + from . import gitutil + return gitutil BEFORE_EVENTS = {"PreToolUse", "BeforeTool", "preToolUse", "beforeShellExecution", "tool_call"} AFTER_EVENTS = {"PostToolUse", "AfterTool", "postToolUse", "afterShellExecution", - "postToolUseFailure", "tool_result"} + "PostToolUseFailure", "postToolUseFailure", "tool_result"} SHELL_TOOLS = ("bash", "shell", "command", "terminal", "exec") @@ -57,8 +63,8 @@ def is_shell(tool, cmd): def _may_write(cmd): - from . import gate - return gate._shell_may_write(cmd) + from . import attribution # the classifier the gate uses (gate._shell_may_write is this function) + return attribution.shell_may_write(cmd) def snap_file(sid, kind): @@ -113,9 +119,8 @@ def note_shell(sess, cmd, payload): its hook payload came from a subagent (an agent id or a subagent transcript path). `sisi retro` reads this from the session record to quarantine what a subagent records; it never trusts the caller's environment. The command text itself is not kept.""" - from . import workers shells = sess.setdefault("shells", []) - shells.append({"retro": "retro" in (cmd or ""), "subagent": bool(workers.is_subagent_payload(payload)), + shells.append({"retro": "retro" in (cmd or ""), "subagent": bool(store.is_subagent_payload(payload)), "ts": time.time()}) del shells[:-8] @@ -173,7 +178,7 @@ def before(payload): store.save_session(sid, sess) if _may_write(cmd) is False: return # provably read-only (incl. sisi's own and git commit): no measurement paid - snap = gitutil.snapshot(cwd) + snap = _git().snapshot(cwd) _save(snap_file(sid, "watch"), {"root": snap["root"], "files": snap["files"], "command": (cmd or "")[:500], "ts": time.time()}) @@ -194,16 +199,16 @@ def after(payload): os.unlink(snap_file(sid, "watch")) except OSError: pass - root = pend.get("root") or gitutil.root(cwd) or cwd - now = gitutil.snapshot(root) - changed = gitutil.snapshot_diff(pend, now) + root = pend.get("root") or _git().root(cwd) or cwd + now = _git().snapshot(root) + changed = _git().snapshot_diff(pend, now) if changed: note_edit(sess, changed, root) store.save_session(sid, sess) def pend_root(sess, cwd): - return gitutil.root(cwd) or sess.get("req_project") or cwd + return _git().root(cwd) or sess.get("req_project") or cwd def consume_pending(sess, sid, cwd): @@ -221,7 +226,7 @@ def consume_pending(sess, sid, cwd): def save_pass_snapshot(sid, cwd): - snap = gitutil.snapshot(cwd) + snap = _git().snapshot(cwd) _save(snap_file(sid, "pass"), snap) return snap @@ -231,7 +236,7 @@ def changed_since_pass(sid, cwd): pend = _load(snap_file(sid, "pass")) if pend is None: return None - return gitutil.snapshot_diff(pend, gitutil.snapshot(cwd)) + return _git().snapshot_diff(pend, _git().snapshot(cwd)) _COMMIT_RE = re.compile(r"(?:^|[;&|(]\s*)(?:\w+=\S+\s+)*git\s+(?:(?:-C|-c)\s+\S+\s+|--[\w-]+\s+)*(?:commit|merge)\b") @@ -256,28 +261,121 @@ def commit_notice(payload): "`sisi verify` first (a notice, not a block)." % c.get("id")) -def main(args=()): +def _read_payload(): try: - from . import gate - payload = gate._read_payload() - _tool, _cmd, ev, _cwd, _sid = extract(payload) - if "--before" in args or ev in BEFORE_EVENTS: - from . import unitguard - if unitguard.before(payload): # refused (rule 3: no valid unit): the call must not run, nothing to measure - return 0 + import sys + if sys.stdin is None or sys.stdin.isatty(): + return {} + d = json.loads(store.read_stdin() or "{}") + return d if isinstance(d, dict) else {} + except Exception: + return {} + + +def meter(payload, after_call, host=None): + """The orchestration meter's answer for one tool call ({"deny": text} / {"context": text} / {}); never + raises: an error inside the meter lets the call through.""" + try: + from . import orchestration + return (orchestration.after if after_call else orchestration.before)(payload, host) + except Exception as e: + store.log_error("watch-meter", e) + return {} + + +def contract_guard(payload): + """The refusal text of rule 3's before-tool guard (no valid unit behind a project change or a build + delegation), or None. Never raises.""" + try: + from . import unitguard + return unitguard.check(payload) + except Exception as e: + store.log_error("watch-unitguard", e) + return None + + +def run(payload, args=(), host=None): + """One before/after hook call for any tool: {"deny": text} (the call must not run) or {"context": text} or {}. + + Before a call, in this order, and the first refusal is the only one the agent sees (a refused call is not + measured or counted): worker and subagent sessions 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 behind it: it comes before + the budget, so an agent told to delegate is not then refused for a contract it was never told about); then + the delegation guard and the direct-work meter (orchestration.before). Every stage fails open.""" + _tool, _cmd, ev, _cwd, sid = extract(payload) + out = {} + if "--before" in args or ev in BEFORE_EVENTS: + if not worker_session(payload, sid, _cwd): + text = contract_guard(payload) + if text: + return {"deny": text} + out = meter(payload, False, host) + if out.get("deny"): + return out + try: before(payload) - try: - line = commit_notice(payload) - if line: - import sys - sys.stdout.write(json.dumps({"systemMessage": line, "hookSpecificOutput": { - "hookEventName": "PreToolUse", "additionalContext": line}}) + "\n") - except Exception as e: - store.log_error("watch-commit-notice", e) - elif "--after" in args or ev in AFTER_EVENTS: + except Exception as e: + store.log_error("watch", e) + try: + line = commit_notice(payload) + if line: + out = dict(out, notice=line) + except Exception as e: + store.log_error("watch-commit-notice", e) + elif "--after" in args or ev in AFTER_EVENTS: + out = meter(payload, True, host) + try: after(payload) + except Exception as e: + store.log_error("watch", e) + try: from . import unitguard unitguard.after(payload) + except Exception as e: + store.log_error("watch-unitguard", e) + return out + + +def worker_session(payload, sid, cwd): + """Is this call from a worker or subagent (the host marks it, `sisi delegate` started it, or its first + prompt opened with the brief template's line)? Workers are exempt from the contract guard and the meter. + False when it cannot be told.""" + try: + if store.is_subagent_payload(payload): + return True + from . import orchestration + sid = sid or "cwd-" + cwd + return bool(store.load_session(sid).get("subagent") or orchestration.worker_flag(sid)) + except Exception as e: + store.log_error("watch-worker", e) + return False + + +def render_claude(out, event): + """The Claude Code hook output for a run() result, or None.""" + if out.get("deny"): + return json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", + "permissionDecisionReason": out["deny"]}}) + ctx = "\n".join(x for x in (out.get("context"), out.get("notice")) if x) + if not ctx: + return None + d = {"hookSpecificOutput": {"hookEventName": event, "additionalContext": ctx}} + if out.get("notice"): + d["systemMessage"] = out["notice"] + return json.dumps(d) + + +def main(args=()): + try: + payload = _read_payload() + _tool, _cmd, ev, _cwd, _sid = extract(payload) + out = run(payload, args) + before_call = "--before" in args or ev in BEFORE_EVENTS + # the host rejects output whose event name is not the event it is answering (found by the live check) + text = render_claude(out, "PreToolUse" if before_call else (ev if ev in AFTER_EVENTS else "PostToolUse")) + if text: + import sys + sys.stdout.write(text + "\n") except Exception as e: # fail open: a tool call must never be held up by measurement store.log_error("watch", e) return 0 diff --git a/sisi/wiring.py b/sisi/wiring.py index 0436521..34c7b01 100644 --- a/sisi/wiring.py +++ b/sisi/wiring.py @@ -229,7 +229,7 @@ def _claude_md_wired(data): # ---- settings.json --------------------------------------------------------- -HOOK_MATCHERS = {"PreToolUse": "Bash", "PostToolUse": "Bash"} +HOOK_MATCHERS = {} # no matcher: the tool hooks run for every tool (the orchestration meter counts all of them) def hook_cmds(): @@ -240,7 +240,8 @@ def hook_cmds(): "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), - "PostToolUse": (watch, 60)} + "PostToolUse": (watch, 60), + "PostToolUseFailure": (watch, 60)} def _claude_spec(): @@ -326,11 +327,15 @@ def _hooks_wired(obj): out = {} for ev, sub, name in (("SessionStart", "tick", "tick"), ("UserPromptSubmit", "prompt", "prompt"), ("Stop", "gate", "gate"), ("SubagentStop", "gate", "subagent"), - ("PreToolUse", "watch", "pre"), ("PostToolUse", "watch", "post")): + ("PreToolUse", "watch", "pre"), ("PostToolUse", "watch", "post"), + ("PostToolUseFailure", "watch", "postfail")): groups = hooks.get(ev) if isinstance(hooks, dict) else None sub, key = sub, name out[key] = False for g in groups if isinstance(groups, list) else []: + if ev in ("PreToolUse", "PostToolUse", "PostToolUseFailure") and isinstance(g, dict) \ + and g.get("matcher") not in (None, "", "*"): + continue # a hook limited to some tools (the shell only, in an older install) does not meter the rest for h in g.get("hooks", []) if isinstance(g, dict) and isinstance(g.get("hooks"), list) else []: inv = hookjson.sisi_invocation(h.get("command")) if isinstance(h, dict) else None if _is_ours(h, sub) and inv and inv[0] == paths.launcher(): @@ -561,7 +566,7 @@ def uninstall(): try: text = data.decode("utf-8") subs = {"SessionStart": "tick", "UserPromptSubmit": "prompt", "Stop": "gate", "SubagentStop": "gate", - "PreToolUse": "watch", "PostToolUse": "watch"} + "PreToolUse": "watch", "PostToolUse": "watch", "PostToolUseFailure": "watch"} orig = _read(os.path.join(_idir(), "backups", ent["backup"])) if ent and ent["backup"] else None drop_hooks, _dv = hookjson.backup_drop_flags( orig.decode("utf-8") if orig is not None else None, None) if orig is not None else (True, False) @@ -606,6 +611,11 @@ def uninstall(): # ---- doctor ---------------------------------------------------------------- +def _meter(pair): + from . import orchestration + return orchestration.meter_note(*pair) + + def doctor(): L = loc() rows = [] @@ -617,10 +627,12 @@ def doctor(): 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] + ("watch-before hook (all tools)", hw["pre"]), ("watch-after hook (all tools)", hw["post"]), + ("watch-failure hook", hw.get("postfail", False))) if not ok] rows.append({"tool": "claude-code", "status": "not wired" if missing else "wired", "detail": ("missing: " + ", ".join(missing)) if missing else "import + tick + prompt + gate registered", "blocking_hook": "yes (Stop)" if hw["gate"] else "no", + "meter": _meter(("claude-code", hw["pre"] and hw["post"] and hw.get("postfail", False))), "rulebook": not missing and _claude_md_wired(cm), "tick": hw["tick"], "enforcement": "blocks", "action": None}) from . import adapters @@ -634,13 +646,14 @@ def doctor(): "sends a follow-up (%s)" % st["via"] if enf == "sends a follow-up" else enf) tool_rows.append({"tool": st["tool"], "status": "wired" if st["wired"] else "not wired", "detail": st["detail"], "blocking_hook": blocking, "rulebook": st["rulebook"], - "tick": st["tick"], "enforcement": enf, "action": st["action"]}) + "tick": st["tick"], "enforcement": enf, "action": st["action"], + "meter": _meter((st["tool"], st["wired"]))}) rows += tool_rows anti = adapters.antigravity_status() if anti["detected"]: rows.append({"tool": "antigravity", "status": "not wired", "detail": anti["detail"], "blocking_hook": "unknown", "rulebook": anti["rulebook"], "tick": False, - "enforcement": "unknown", "action": None}) + "enforcement": "unknown", "action": None, "meter": _meter(("antigravity", False))}) _providers = {"claude-code", "codex", "opencode", "cursor", "pi", "muse", "gemini", "copilot", "qwen", "grok"} wired_names = [n for n in ([r["tool"] for r in tool_rows if r["status"] == "wired"] + (["claude-code"] if rows[0]["status"] == "wired" else [])) if n in _providers] @@ -708,7 +721,8 @@ def doctor_claude(): 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] + ("watch-before hook (all tools)", hw["pre"]), ("watch-after hook (all tools)", hw["post"]), + ("watch-failure hook", hw.get("postfail", False))) if not ok] return ", ".join(missing) diff --git a/sisi/workers.py b/sisi/workers.py index 41cbc13..8a3ff3b 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -107,13 +107,20 @@ AUTH_SIGNATURES = ( "authentication required", "run 'agent login'", 'run "agent login"', "you are not authenticated", "not authenticated", "no credentials", "no codex credentials", "invalid or missing api key", "run 'amp login'", "run codex login", "use /login", - "no models available", "401 unauthorized", "http 401", + "no models available", "401 unauthorized", "http 401", "api error 401", "api error 403", "http 403", + "403 forbidden", "not logged in", "login required", "please log in", "invalid api key", ) LIMIT_SIGNATURES = ( "provider.go-limit", "monthly usage limit reached", "usage limit reached", "usage limit", "rate limit", "you've hit the rate limit", "you've hit your session rate limit", "you've reached your weekly rate limit", "quota exceeded", "insufficient credits", "out of credits", "http 429", '"status":429', '"status": 429', + "api error 429", "error 429", "too many requests", "quota exhausted", "out of quota", "subscription quota", + "insufficient quota", "credit balance", "billing", "payment required", "http 402", +) +MISSING_SIGNATURES = ( + "tool not found", "command not found", "provider not connected", "not connected", "provider not found", + "model not found", "unknown model", ) ERROR_SIGNATURES = ( "http 500", "http 502", "http 503", "http 529", "service unavailable", "bad gateway", @@ -129,18 +136,43 @@ def classify_failure(text, returncode=0): m = re.search(r"retryafterms\D{0,4}(\d+)", low) if m: retry = int(m.group(1)) / 1000.0 + elif "reset" in low: + until = parse_reset(text) + if until is not None: + retry = until - time.time() for sig in AUTH_SIGNATURES: if sig in low: return "auth", "not logged in (%s)" % _phrase(text, sig), retry for sig in LIMIT_SIGNATURES: if sig in low: return "limit", _phrase(text, sig), retry + for sig in MISSING_SIGNATURES: + if sig in low: + return "missing", _phrase(text, sig), retry for sig in ERROR_SIGNATURES: if sig in low: return "error", _phrase(text, sig), retry return None +_ISO_TIME = r"\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?" + + +def parse_reset(text, now=None): + """The epoch second a limit message says the worker is back at (an ISO date-time or date, best after the + word "reset"), or None when it names none or only a past one.""" + now = time.time() if now is None else now + t = text or "" + for pat in (r"reset\w*\s*(?:at|on|in|:)?\s*[:=]?\s*(%s)" % _ISO_TIME, r"(%s)" % _ISO_TIME): + for m in re.finditer(pat, t, re.I): + ts = _parse_time(m.group(1)) + if ts is not None and ts > now: + return ts + if re.search(r"reset", t, re.I) is None: + break # without the word, only the first (keyword) pattern was worth trying + return None + + def _phrase(text, sig, width=110): t = " ".join((text or "").split()) i = t.lower().find(sig) @@ -316,10 +348,62 @@ def discover(force=False, now=None): if not force and cached.get("tools") and now - float(cached.get("checked") or 0) < age: return cached data = {"checked": now, "tools": [_discover_tool(d) for d in DRIVERS]} + if cached.get("tools"): # models the previous discovery did not have wait for the next session start to be named + here = _model_names(data) + kept = [w for w in cached.get("new_unannounced") or [] if w in here] + data["new_unannounced"] = kept + sorted(w for w in here - _model_names(cached) if w not in kept) write_json(discovery_path(), data) return data +def _model_names(disc): + return {_canonical(t["name"], m) for t in disc.get("tools") or [] for m in t.get("models") or [] + if "contributor" not in str(m).lower()} # a tier that trains on its prompts is never offered + + +def new_worker_line(): + """One line naming up to three models discovery found that the previous discovery did not have, once; they + are unproven, so low-stakes work first and a closer look at what they return, until their record is no longer + thin. None when there is nothing new (or it was said already).""" + disc = load_discovery() + records = read_records() + judged = {} + for r in records: + if r.get("kind") == "attempt": + judged[str(r.get("worker") or "").lower()] = judged.get(str(r.get("worker") or "").lower(), 0) + 1 + new = [w for w in disc.get("new_unannounced") or [] + if "contributor" not in w.lower() and judged.get(w.lower(), 0) < routing.MIN_ATTEMPTS] + if not disc.get("new_unannounced"): + return None + disc["new_unannounced"] = [] + write_json(discovery_path(), disc) + if not new: + return None + more = " (and %d more)" % (len(new) - 3) if len(new) > 3 else "" + return ("sisi: new worker model(s) found since the last discovery: %s%s. They are unproven (no judged record): give them " + "low-stakes work first and check what they return one level more carefully, until their record is no longer " + "thin (%d judged attempts)." % (", ".join(new[:3]), more, routing.MIN_ATTEMPTS)) + + +def override_line(records=None): + """How often the router's pick was overridden and how the overrides turned out against the recommendations + that were followed; None when nothing was routed. Under five judged on either side it says too few.""" + records = read_records() if records is None else records + routed = [r for r in merged_runs(records) if r.get("chosen_against_route") is not None] + if not routed: + return None + attempts = [r for r in records if r.get("kind") == "attempt" and r.get("chosen_against_route") is not None] + + def rate(rows): + n = len(rows) + return "too few to say (%d judged, need 5)" % n if n < 5 else "%d%% accepted (%d judged)" % ( + round(100.0 * sum(1 for r in rows if r.get("outcome") == "accepted") / n), n) + over = [r for r in attempts if r["chosen_against_route"]] + followed = [r for r in attempts if not r["chosen_against_route"]] + return ("Router overridden in %d of %d routed delegations. Overrides: %s. Recommendations followed: %s." + % (sum(1 for r in routed if r["chosen_against_route"]), len(routed), rate(over), rate(followed))) + + def mark_discovery_stale(): cached = load_discovery() if cached: @@ -422,6 +506,64 @@ def record_down(keys, reason, note=None, now=None, retry_after_s=None, until_ts= return avail +_MODEL_ONLY = re.compile(r"\bmodel\b.{0,80}(not found|not available|unavailable|not supported|overloaded|does not exist|" + r"deprecated)|(unknown|invalid|unsupported) model", re.I | re.S) + + +def identify_worker(text, candidates=None): + """The one candidate worker a message names (by worker id, model or alias, longest spelling first), or + None when it names none or more than one.""" + low = (text or "").lower() + cands = _cached_candidates()[0] if candidates is None else candidates + found = {} + for c in cands: + names = [c.get("worker"), c.get("model")] + list(c.get("aliases") or []) + hits = [str(n).lower() for n in names if n and len(str(n)) >= 3 and str(n).lower() in low] + if hits: + found[c["worker"]] = max(len(h) for h in hits) + if not found: + return None + best = max(found.values()) + top = [w for w, n in found.items() if n == best] + return top[0] if len(top) == 1 else None + + +def mark_unavailable(worker, text, now=None): + """Record, without being asked, that the worker named failed for a reason that is not about its work + (limit, login, missing, passing error): its provider when the whole provider is out, the single model + when the text shows only the model is. The time it is back is parsed from the message when it gives one, + else the usual widening wait. Returns {"worker", "keys", "reason", "note", "until"} or None when the text + is no such failure. Never a quality judgement.""" + failure = classify_failure(text) + if failure is None or not worker: + return None + reason, note, retry = failure + now = time.time() if now is None else now + cand = resolve_worker(worker, _cached_candidates()[0]) or {"worker": worker, "model": worker, "tool": None} + model = str(cand.get("model") or "") + if _MODEL_ONLY.search(text or ""): + keys = [cand["worker"]] + elif "/" in model: + keys = [cand["worker"], model.split("/", 1)[0]] + elif cand.get("tool") and not cand.get("host_native"): + keys = [cand["worker"], cand["tool"]] + else: + keys = [cand["worker"]] + until = parse_reset(text, now) + avail = record_down(keys, reason, note, now=now, retry_after_s=None if until else retry, until_ts=until) + shown = avail.get(str(keys[-1]).lower()) or {} + return {"worker": cand["worker"], "keys": keys, "reason": reason, "note": note, + "until": until if until is not None else shown.get("retry_at")} + + +def earliest_due(now=None): + """(key, epoch) of the worker or provider due for another try soonest, or None when nothing is down.""" + now = time.time() if now is None else now + rows = [(float(e.get("retry_at") or 0), k) for k, e in read_availability().items() + if isinstance(e, dict) and float(e.get("retry_at") or 0) > now] + return (min(rows)[1], min(rows)[0]) if rows else None + + def clear_down(worker): avail = read_availability() if not avail: @@ -483,10 +625,35 @@ def import_ledger(src, now=None): return before, before + added, added +def merged_runs(records=None): + """The ledger's runs, each with the later `run-end` fact for its id applied (a delegation the + host started: written when it begins, completed when it returns). A run still in flight keeps + status "pending".""" + records = read_records() if records is None else records + ends = {} + for r in records: + if r.get("kind") == "run-end" and r.get("run_id"): + ends[r["run_id"]] = r + out = [] + for r in records: + if r.get("kind") != "run": + continue + end = ends.get(r.get("id")) + if end is not None: + r = dict(r, **{k: v for k, v in end.items() if k not in ("kind", "run_id", "ts") and v is not None}) + out.append(r) + return out + + +NOT_JUDGED_STATUSES = ("pending", "superseded") # in flight, or replaced by a fallback: nothing to judge + + def unjudged_runs(records=None): + """Finished runs with no judgement. A run still in flight (status "pending") is not waiting yet, and one + replaced by a fallback (status "superseded") is never asked for.""" records = read_records() if records is None else records judged = {r.get("run_id") for r in records if r.get("kind") == "attempt" and r.get("run_id")} - return [r for r in records if r.get("kind") == "run" and r.get("id") not in judged] + return [r for r in merged_runs(records) if r.get("id") not in judged and r.get("status") not in NOT_JUDGED_STATUSES] # ---------------------------------------------------------------- candidates @@ -923,6 +1090,41 @@ def mechanism_for(cand, host=None): return "use `sisi delegate` (the host has no delegation of its own for this worker)" +def same_model(a, b): + """Do two spellings name one model? Equal, or one an alias contained in the other's full name + (a short name against a dated id). Neither side may be empty or shorter than three characters.""" + a, b = str(a or "").strip().lower(), str(b or "").strip().lower() + if len(a) < 3 or len(b) < 3: + return False + a, b = a.rsplit("/", 1)[-1], b.rsplit("/", 1)[-1] + return a == b or a in b or b in a + + +def _own_workers(candidates, own_model): + return [c["worker"] for c in candidates + if own_model and any(same_model(own_model, x) for x in + [c.get("worker"), c.get("model")] + list(c.get("aliases") or []))] + + +def recommend(kind, difficulty, cwd=None, own_model=None): + """The router's pick for a kind of task as (worker, mechanism line, usable_count), reading only + the cached discovery and the record, never printing. The session's own model is not offered: + delegating to the same model is what orchestration is meant to avoid. (None, None, 0) when no + other worker is usable.""" + records = read_records() + candidates, _tools = _cached_candidates(records) + candidates, _cold, _x = routable_candidates(candidates, records) + prefs = effective_prefs(kind, difficulty, cwd or os.getcwd()) + candidates, _limited = apply_limits(candidates, prefs) + result = routing.choose(candidates, records, read_availability(), kind, difficulty, now=time.time(), + exclude=_own_workers(candidates, own_model), avoid=prefs["avoid"], prefer=prefs["prefer"], + floors=route_floors()) + choice = result["choice"] + if choice is None: + return None, None, 0 + return choice["worker"], mechanism_for(choice), 1 + + def _pct(ok, n): return ("%d%%" % round(100.0 * ok / n)) if n else "-" @@ -1164,7 +1366,8 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev notes.append("sisi: %s is a host-native worker; start it with the host's own subagent tool " "(`sisi delegate` runs only command-line tools)" % cand["worker"]) return None, None, notes - candidates = [c for c in apply_limits(candidates, prefs)[0] if not c.get("host_native")] + limited = apply_limits(candidates, prefs)[0] + candidates = [c for c in limited if not c.get("host_native")] while True: if cand is None: prefs = effective_prefs(kind, difficulty, cwd) @@ -1173,7 +1376,15 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors()) cand = result["choice"] if cand is None: - notes.append("sisi: no usable worker remains for kind %s at difficulty %s" % (kind, difficulty)) + native = routing.choose([c for c in limited if c.get("host_native")], read_records(), read_availability(), + kind, difficulty, now=time.time(), exclude=tried, + avoid=prefs["avoid"], prefer=prefs["prefer"])["choice"] + if native is not None: # every command-line worker is out: the host's own subagents take it, at once + notes.append("sisi: no command-line worker remains for kind %s at difficulty %s. Fall back now with the " + "same brief: %s (model %s). Do not ask the person and do not report this to them: " + "which worker is out is internal." % (kind, difficulty, mechanism_for(native), native.get("model") or native["worker"])) + else: + notes.append("sisi: no usable worker remains for kind %s at difficulty %s" % (kind, difficulty)) return None, None, notes tried.append(cand["worker"]) if "contributor" in str(cand.get("model") or cand["worker"]).lower(): @@ -1208,7 +1419,8 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev failure = classify_failure(out + "\n" + err, rc) if failure is not None: reason, note, retry = failure - record_down(_down_keys(cand, reason), reason, note, retry_after_s=retry) + until = parse_reset(out + "\n" + err) # the time the message itself names, when it names one + record_down(_down_keys(cand, reason), reason, note, retry_after_s=None if until else retry, until_ts=until) mark_discovery_stale() notes.append("%s is unavailable (%s: %s); trying the next choice" % (cand["worker"], reason, note)) cand = None @@ -1262,14 +1474,7 @@ def _cached_candidates(records=None): def is_subagent_payload(payload): - if os.environ.get("SISI_WORKER_RUN"): - return True - if not isinstance(payload, dict): - return False - if payload.get("agent_id") or payload.get("agentId") or payload.get("agent_transcript_path"): - return True - tp = str(payload.get("transcript_path") or "") - return "/subagents/" in tp or tp.endswith("/subagents") + return store.is_subagent_payload(payload) def _with_facts(lines): @@ -1470,6 +1675,9 @@ def cmd_workers(args=()): print(line) for ln in digest_lines(records): print(ln) + line = override_line(records) + if line: + print(line) return 0 @@ -1489,9 +1697,18 @@ def _down_lines(down, limit=3): return ["down now: %s%s" % ("; ".join(shown), more)] -def _route_setup(args): - kind = _opt(args, "--kind") +def _route_setup(args, derived=None): + kind = _opt(args, "--kind") or (derived or {}).get("kind") + if kind and not derived: + from . import unitguard + known = unitguard.ledger_kinds() + if known and kind not in known: + print("sisi route: kind %r is not one the ledger knows. Kinds: %s (building: %s)." + % (kind, ", ".join(known), ", ".join(unitguard._list("build_kinds"))), file=sys.stderr) + return None difficulty = _opt(args, "--difficulty") + if difficulty is None and derived: + difficulty = derived.get("difficulty") if not kind or difficulty is None: return None try: @@ -1503,10 +1720,76 @@ def _route_setup(args): return kind, difficulty +def retry_context(retry_id, records=None): + """What `sisi route --retry-of ID` needs from the judged record: the attempt (ID is an attempt id, or the + id of a run that was judged), its kind and difficulty, and how many results in the retry chain behind it + were rejected in a row, newest first, with the workers that produced them. None when ID is unknown or + its run is not judged yet.""" + records = read_records() if records is None else records + attempts = {r["id"]: r for r in records if r.get("kind") == "attempt" and r.get("id")} + by_run = {r["run_id"]: r for r in attempts.values() if r.get("run_id")} + a = attempts.get(retry_id) or by_run.get(retry_id) + if a is None: + return None + rejected, seen, cur = [], set(), a + while cur is not None and cur["id"] not in seen: + seen.add(cur["id"]) + if cur.get("outcome") != "rejected": + break + rejected.append(cur.get("worker")) + cur = attempts.get(cur.get("retry_of")) + return {"attempt": a, "kind": a.get("type"), "difficulty": a.get("difficulty"), "rejected": rejected} + + +RETRY_BRIEF_LINE = ("retry: most failures are brief failures. Improve the brief (what was missing, what is known now, " + "the exact failure) and check it with `sisi delegate check`, then give it to this same worker once more.") + + +def _route_retry(args, ctx, kind, difficulty, candidates, records, prefs): + """Print the pick for a retry and return it (or None). The ladder is routing.retry_choice: the same worker + with a better brief after the first rejection, then a worker whose evidence is strictly better, then the + strongest known.""" + rejected = ctx["rejected"] + res = routing.retry_choice(candidates, records, read_availability(), kind, difficulty, rejected[0], len(rejected), + now=time.time(), avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors()) + pick = res["choice"] + if pick is None: + print("no usable worker for kind %s at difficulty %d after a rejection by %s" + % (kind, difficulty, ", ".join(sorted(set(rejected))))) + return None + print(pick["worker"]) + print("mechanism: %s" % mechanism_for(pick)) + if res["step"] == "same": + print(RETRY_BRIEF_LINE) + else: + print("retry after %d rejection(s) by %s: %s" % (len(rejected), ", ".join(sorted(set(rejected))), { + "better": "a worker with strictly better evidence than the rejected one", + "strongest": "nobody has better evidence, so the strongest known usable worker", + "only": "nobody else is usable, so the same worker once more"}[res["step"]])) + return pick + + +def route_decision(kind, difficulty, worker, retry_of=None): + """Write the routing decision for the session this command runs in (see orchestration.record_route).""" + try: + from . import orchestration + orchestration.record_route(kind, difficulty, worker, os.getcwd(), retry_of) + except Exception as e: + store.log_error("route-decision", e) + + def cmd_route(args=()): - setup = _route_setup(args) + retry_id = _opt(args, "--retry-of") + ctx = None + if retry_id: + ctx = retry_context(retry_id) + if ctx is None: + print("sisi route: no judged delegation with id %s (judge the run first: `sisi delegate judge`)" % retry_id, + file=sys.stderr) + return 1 + setup = _route_setup(args, ctx) if setup is None: - print("usage: sisi route --kind K --difficulty 1|2|3 [--review-of WORKER] [--explain]") + print("usage: sisi route --kind K --difficulty 1|2|3 [--review-of WORKER] [--explain] | --retry-of ID") return 1 kind, difficulty = setup records = read_records() @@ -1514,6 +1797,10 @@ def cmd_route(args=()): prefs = effective_prefs(kind, difficulty, os.getcwd()) everyone = candidates candidates, limited = apply_limits(candidates, prefs) + if ctx is not None and ctx["rejected"]: + pick = _route_retry(args, ctx, kind, difficulty, candidates, records, prefs) + route_decision(kind, difficulty, pick["worker"] if pick else None, ctx["attempt"]["id"]) + return 0 if pick else 1 result = routing.choose(candidates, records, read_availability(), kind, difficulty, review_of=_opt(args, "--review-of"), now=time.time(), avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors()) @@ -1521,6 +1808,7 @@ def cmd_route(args=()): by_worker = {c["worker"]: c for c in everyone} down = _down_now(read_availability(), time.time()) if result["choice"] is None: + route_decision(kind, difficulty, None, ctx["attempt"]["id"] if ctx else None) print("no usable worker for kind %s at difficulty %d" % (kind, difficulty)) for line in _down_lines(down): print(line) @@ -1531,6 +1819,7 @@ def cmd_route(args=()): for line in routing.explain_choice(result, kind, difficulty)[1:]: print(line) return 1 + route_decision(kind, difficulty, result["choice"]["worker"], ctx["attempt"]["id"] if ctx else None) print(result["choice"]["worker"]) print("mechanism: %s" % mechanism_for(result["choice"])) for line in _down_lines(down): @@ -1697,7 +1986,7 @@ def _cmd_judge(args): records = read_records() run_id = args[0] if args and not args[0].startswith("--") else None if run_id is not None: - run = next((r for r in records if r.get("kind") == "run" and r.get("id") == run_id), None) + run = next((r for r in merged_runs(records) if r.get("id") == run_id), None) if run is None: print("sisi delegate: no delegation run with id %s" % run_id, file=sys.stderr) return 1 @@ -1708,10 +1997,15 @@ def _cmd_judge(args): "project": os.path.basename(str(run.get("cwd") or "").rstrip("/")) or None, "type": run.get("type"), "difficulty": run.get("difficulty"), "worker": run.get("worker"), "model": run.get("model"), "tool": run.get("tool"), "outcome": outcome, "check": check, - "minutes": None, "tokens": run.get("tokens"), "tokens_class": run.get("tokens_class"), + "minutes": run.get("minutes"), "tokens": run.get("tokens"), "tokens_class": run.get("tokens_class"), "cost": run.get("cost"), "cost_class": run.get("cost_class"), "started": run.get("started"), "ended": run.get("ended"), - "retry_of": run.get("retry_of"), "note": None} + "retry_of": run.get("retry_of"), "note": None, + "route_worker": run.get("route_worker"), "chosen_against_route": run.get("chosen_against_route")} + if _opt(args, "--type") or _opt(args, "--kind"): # a run the host started carries no kind until judged + rec["type"] = _opt(args, "--type") or _opt(args, "--kind") + if _opt(args, "--difficulty") in ("1", "2", "3"): + rec["difficulty"] = int(_opt(args, "--difficulty")) else: worker = _opt(args, "--worker") kind = _opt(args, "--type") or _opt(args, "--kind") @@ -1749,6 +2043,9 @@ def _cmd_judge(args): # it never marks the worker unavailable. clear_down(rec["worker"]) print(rec["id"]) + if rec["outcome"] == "rejected": + print("next: `sisi route --retry-of %s` names the worker for the retry (the same one with a better brief first, " + "a stronger one after a second rejection)" % rec["id"]) return 0 diff --git a/tests/test_adapters.py b/tests/test_adapters.py index b3b810a..726003b 100644 --- a/tests/test_adapters.py +++ b/tests/test_adapters.py @@ -88,7 +88,7 @@ class HookToolTests(AdapterBase): self.assertTrue(any("watch --tool %s" % name in (c or "") for c in cmds), (name, ev, cmds)) if name == "codex": for ev in events: - self.assertTrue(any(g.get("matcher") == "Bash" for g in obj["hooks"][ev])) + self.assertFalse(any(g.get("matcher") for g in obj["hooks"][ev]), "tool hooks cover every tool") self.assertEqual(self.rows()[name]["status"], "wired") wiring.uninstall() diff --git a/tests/test_install_safety.py b/tests/test_install_safety.py index f604835..5416be6 100644 --- a/tests/test_install_safety.py +++ b/tests/test_install_safety.py @@ -1,4 +1,4 @@ -import json, os, random, shutil, stat, subprocess, sys, unittest +import contextlib, io, json, os, random, shutil, stat, subprocess, sys, unittest from unittest import mock from support import * from test_wiring import WiringBase, snapshot @@ -547,3 +547,116 @@ class WidenedPropertyTests(SafetyBase): if __name__ == "__main__": unittest.main() + + +real_cmds = wiring.hook_cmds # the registration as this version makes it, kept before any test patches it + + +class AllToolsHookMigrationTests(SafetyBase): + """Item 7: an installed shell-only configuration becomes all-tool hooks, span-preserving, and uninstall restores + the original bytes (R-7.1-1 / R-6.3-1: the meter must see every tool).""" + + ORIGINAL = (b'{\n "theme": "dark", \n "hooks": {\n "PreToolUse": [\n' + b' {"matcher": "Edit", "hooks": [{"type": "command", "command": "echo mine"}]}\n ]\n },\n' + b' "model": "x"\n}\n') + + def settings(self): + return self.path(".claude/settings.json") + + def install_old_style(self): + """What the previous release wrote: shell-only matchers on the tool hooks and no failure hook.""" + old = {"PreToolUse": "Bash", "PostToolUse": "Bash"} + with mock.patch.object(wiring, "HOOK_MATCHERS", old), \ + mock.patch.object(wiring, "hook_cmds", lambda: {k: v for k, v in real_cmds().items() if k != "PostToolUseFailure"}): + rc, notes = wiring.install() + self.assertEqual(rc, 0, notes) + + def groups(self, ev): + return json.load(open(self.settings()))["hooks"][ev] + + def test_shell_only_install_is_migrated_and_uninstall_restores_the_original_bytes(self): + self.put(".claude/settings.json", self.ORIGINAL) + self.install_old_style() + self.assertTrue(any(g.get("matcher") == "Bash" for g in self.groups("PreToolUse"))) + self.assertNotIn("PostToolUseFailure", json.load(open(self.settings()))["hooks"]) + self.assertIn("watch-failure hook", wiring.doctor_claude()) # doctor says what is missing + rc, notes = wiring.install() # `sisi install` again, with this version + self.assertEqual(rc, 0, notes) + for ev in ("PreToolUse", "PostToolUse", "PostToolUseFailure"): + mine = [g for g in self.groups(ev) if any("watch --tool" in h["command"] for h in g["hooks"])] + self.assertEqual(len(mine), 1, ev) + self.assertFalse(mine[0].get("matcher"), (ev, mine)) # every tool: no matcher + user = [g for g in self.groups("PreToolUse") if g.get("matcher") == "Edit"] + self.assertEqual(user, [{"matcher": "Edit", "hooks": [{"type": "command", "command": "echo mine"}]}]) + self.assertEqual(wiring.doctor_claude(), "") + before = open(self.settings(), "rb").read() + wiring.install() + self.assertEqual(open(self.settings(), "rb").read(), before) # idempotent + wiring.uninstall() + self.assertEqual(open(self.settings(), "rb").read(), self.ORIGINAL) # the original bytes, spelling and all + + def test_a_group_shared_with_a_users_own_hook_is_split_not_widened(self): + """Our entry sharing a Bash-matcher group with a user's hook must not widen the user's hook to every tool.""" + cmd = real_cmds()["PreToolUse"][0] + shared = {"hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": [ + {"type": "command", "command": "echo mine"}, {"type": "command", "command": cmd, "timeout": 60}]}]}} + self.put(".claude/settings.json", json.dumps(shared, indent=2).encode() + b"\n") + wiring.install() + groups = self.groups("PreToolUse") + user = [g for g in groups if any(h["command"] == "echo mine" for h in g["hooks"])] + self.assertEqual(len(user), 1) + self.assertEqual(user[0]["matcher"], "Bash") + self.assertEqual(len(user[0]["hooks"]), 1) + ours = [g for g in groups if any("watch --tool" in h["command"] for h in g["hooks"])] + self.assertEqual(len(ours), 1) + self.assertFalse(ours[0].get("matcher")) + + def test_sisi_update_brings_an_existing_installation_to_all_tool_hooks(self): + self.put(".claude/settings.json", self.ORIGINAL) + self.install_old_style() + from sisi import lifecycle + with contextlib.redirect_stdout(io.StringIO()): + lifecycle._rewire_existing() + self.assertFalse(any(g.get("matcher") == "Bash" for g in self.groups("PreToolUse"))) + self.assertIn("PostToolUseFailure", json.load(open(self.settings()))["hooks"]) + wiring.uninstall() + self.assertEqual(open(self.settings(), "rb").read(), self.ORIGINAL) + + def test_update_without_an_installation_changes_nothing(self): + self.put(".claude/settings.json", self.ORIGINAL) + from sisi import lifecycle + with contextlib.redirect_stdout(io.StringIO()): + lifecycle._rewire_existing() + self.assertEqual(open(self.settings(), "rb").read(), self.ORIGINAL) + + def test_codex_shell_only_hooks_are_widened_too(self): + os.makedirs(self.path(".codex")) + old = {"PreToolUse": {"cmd": "x"}} + spec = adapters.BY_NAME["codex"].spec() + spec_old = {k: dict(v, matcher="Bash") if k in ("PreToolUse", "PostToolUse") else v for k, v in spec.items()} + with mock.patch.object(adapters.Codex, "spec", lambda self: spec_old): + wiring.install() + self.assertTrue(any(g.get("matcher") == "Bash" for g in json.load(open(self.path(".codex/hooks.json")))["hooks"]["PreToolUse"])) + wiring.install() + self.assertFalse(any(g.get("matcher") for g in json.load(open(self.path(".codex/hooks.json")))["hooks"]["PreToolUse"])) + wiring.uninstall() + self.assertFalse(os.path.exists(self.path(".codex/hooks.json"))) + + def test_doctor_says_what_the_meter_can_do_per_tool(self): + from sisi import orchestration + shutil.copy(os.path.join(REPO, "canon", "orchestration-tools.json"), os.path.join(self.repo, "canon")) + orchestration._HOSTS.clear() + self.addCleanup(orchestration._HOSTS.clear) + os.makedirs(self.path(".codex")) + os.makedirs(self.path(".qwen")) + wiring.install() + rows = {r["tool"]: r for r in wiring.doctor()} + self.assertIn("can refuse", rows["claude-code"]["meter"]) + self.assertIn("observed live", rows["claude-code"]["meter"]) + self.assertIn("exit status 2", rows["codex"]["meter"]) + self.assertIn("not run live", rows["codex"]["meter"]) + self.assertIn("cannot run", rows["qwen"]["meter"]) + out = self.sisi("doctor").stdout + self.assertIn("orchestration meter: cannot run", out) + + diff --git a/tests/test_integration.py b/tests/test_integration.py new file mode 100644 index 0000000..206eb48 --- /dev/null +++ b/tests/test_integration.py @@ -0,0 +1,548 @@ +"""The orchestration meter (rule 6) and the contract guard (rule 3) on one tree, and four small fixes. + +One before-tool path with one refusal at a time, in a fixed order; one home for the routing decision; the +unit record, `sisi status`, `sisi rule` and the config carrying both sides; deep results that stay fresh +through a pause; a gate send-back that says why the profile applies; a backup copy that survives a file +vanishing; a prompt hook that attaches no recipe to a machine's message. +""" +import json, os, re, shutil, time, unittest +from unittest import mock +from support import * +import test_meter as TM +import test_unitguard as TG +from sisi import contract as C, gate, lifecycle, orchestration, prompt, routing, rulecmd, store, unit as U, unitguard as G +from sisi import watch, workers + +SRC = TG.SRC +CONTRACT_LINES = 12 + + +class Both(TG.GuardCase): + """A project with the contract guard's fixtures and the meter's seeded workers.""" + + def setUp(self): + super().setUp() + os.makedirs(self.data, exist_ok=True) + TM.seed_workers(self) + self.own = "gamma-top" + self.tick(model=self.own) + + def hook(self, tool, inp, event="PreToolUse", **extra): + """The real before-tool hook; (reason or None, whole stdout).""" + d = dict({"session_id": self.sid, "cwd": self.proj, "hook_event_name": event, "tool_name": tool, + "tool_input": inp}, **extra) + r = self.sisi("watch", "--before", "--tool", "claude-code", stdin=json.dumps(d)) + self.assertEqual(r.returncode, 0, r.stderr) + out = json.loads(r.stdout) if r.stdout.strip() else {} + hs = out.get("hookSpecificOutput") or {} + if hs.get("permissionDecision") == "deny": + reason = hs["permissionDecisionReason"] + self.assertLessEqual(len(reason.splitlines()), CONTRACT_LINES, reason) + return reason + return None + + def read(self, **kw): + return self.hook("Read", {"file_path": os.path.join(self.proj, "README.md")}, **kw) + + def edit(self, rel=SRC, **kw): + return self.hook("Edit", {"file_path": os.path.join(self.proj, rel), "old_string": "a", "new_string": "b"}, **kw) + + def agent(self, prompt_text, model=None, **kw): + inp = {"description": "d", "prompt": prompt_text} + if model: + inp["model"] = model + return self.hook("Agent", inp, **kw) + + def spend_budget(self): + for _ in range(6): + self.assertIsNone(self.read()) + self.assertIn("direct tool calls", self.read()) # the meter now refuses every counted call + + def route(self, *args): + return self.sisi("route", *args, env={"SISI_SESSION_ID": self.sid}) + + def foreign_unit(self, ago_s=3 * 86400, goal="redo the old report"): + c = TG.good_contract(goal=goal, id="old-report") + self.write_contract(c) + self.age_unit(c, ago_s, sid="someone-else") + return C.load(self.contract_path) + + +BUILD_BRIEF = "Outcome: greet by name\nAcceptance: the test passes\nFiles you may change: src/app.py" +READ_BRIEF = "Outcome: list the callers of greet\nAcceptance: a list\nFiles you may change: none" + + +class OneRefusalAtATime(Both): + """Integration point 1.""" + + def test_an_edit_with_no_unit_past_the_budget_is_refused_for_the_contract_only(self): + self.spend_budget() + msg = self.edit() + self.assertIn("sisi contract init", msg) + self.assertNotIn("direct tool calls", msg) + self.assertNotIn("sisi unit direct", msg) + + def test_delegating_a_build_past_the_budget_with_no_model_and_no_unit_is_refused_for_the_contract(self): + self.spend_budget() + for model in (None, self.own): + msg = self.agent(BUILD_BRIEF, model=model) + self.assertIn("sisi contract init", msg) + self.assertIn("acceptance", msg) + self.assertNotIn("names no model", msg) + self.assertNotIn("names this session's own model", msg) + + def test_a_routed_build_is_a_build_whatever_the_brief_says(self): + self.assertEqual(self.route("--kind", "impl", "--difficulty", "2").returncode, 0) + msg = self.agent("Look into the greeting", model="alpha-small") + self.assertIn("sisi contract init", msg) + + def test_a_read_only_delegation_goes_to_the_delegation_guard_then_the_meter(self): + msg = self.agent(READ_BRIEF) # no model, no unit needed + self.assertIn("names no model", msg) + self.assertNotIn("contract", msg) + self.assertEqual(self.route("--kind", "read", "--difficulty", "1").returncode, 0) + self.assertIsNone(self.agent(READ_BRIEF, model="alpha-small")) + + def test_with_a_valid_unit_the_contract_guard_is_silent_and_the_meter_speaks(self): + self.open_unit() + for _ in range(6): + self.assertIsNone(self.read()) + self.assertIn("direct tool calls", self.read()) + # an edit is a counted call too: with the unit valid, the meter refuses it + self.assertIn("direct tool calls", self.edit()) + msg = self.agent(BUILD_BRIEF) + self.assertIn("names no model", msg) + + def test_workers_and_subagents_are_exempt_from_all_of_it(self): + for _ in range(12): + self.assertIsNone(self.read(agent_id="w1")) + self.assertIsNone(self.edit(agent_id="w1")) + self.assertIsNone(self.agent(BUILD_BRIEF, agent_id="w1")) + # a session whose first prompt opens with the brief template's line is a worker too + orchestration.new_turn("wk", self.proj, orchestration.brief_line() + "\nOutcome: x") + d = {"session_id": "wk", "cwd": self.proj, "hook_event_name": "PreToolUse", "tool_name": "Edit", + "tool_input": {"file_path": os.path.join(self.proj, SRC), "old_string": "a", "new_string": "b"}} + r = self.sisi("watch", "--before", "--tool", "claude-code", stdin=json.dumps(d)) + self.assertEqual(r.stdout.strip(), "") + + def test_no_refusal_is_longer_than_twelve_lines_in_any_state(self): + for step in (lambda: None, lambda: self.foreign_unit(), self.spend_budget_quiet): + step() + for text in (self.edit("auth/login.py"), self.agent(BUILD_BRIEF), self.agent(READ_BRIEF), self.read()): + self.assertLessEqual(len((text or "").splitlines()), CONTRACT_LINES) + + def spend_budget_quiet(self): + for _ in range(8): + self.read() + + def test_every_stage_fails_open_on_its_own(self): + self.spend_budget() + with mock.patch.object(G, "check", side_effect=RuntimeError("boom")): + self.assertEqual(watch.contract_guard({"tool_name": "Edit"}), None) + self.assertIn("direct tool calls", self.read()) # the meter still answers + with mock.patch.object(orchestration, "before", side_effect=RuntimeError("boom")): + self.assertEqual(watch.meter({"tool_name": "Read"}, False), {}) + self.assertIn("sisi contract init", self.edit()) # the contract guard still answers + with mock.patch.object(watch, "contract_guard", side_effect=RuntimeError("boom")): + r = self.sisi("watch", "--before", "--tool", "claude-code", stdin=json.dumps( + {"session_id": self.sid, "cwd": self.proj, "hook_event_name": "PreToolUse", "tool_name": "Read", + "tool_input": {"file_path": "/x"}})) + self.assertEqual(r.returncode, 0) + + def test_a_refused_call_is_not_counted_by_the_meter(self): + for _ in range(10): + self.assertIn("sisi contract init", self.edit()) + for _ in range(6): + self.assertIsNone(self.read()) # the ten refused edits used none of the budget + + +class RoutingDecision(Both): + """Integration point 2.""" + + def decision(self): + return orchestration._peek(self.sid).get("route") + + def test_the_guard_reads_the_decision_where_route_stores_it(self): + self.assertIsNone(G.routed_kind(self.sid)) + self.route("--kind", "impl", "--difficulty", "2") + self.assertEqual(self.decision()["kind"], "impl") + self.assertEqual(G.routed_kind(self.sid), "impl") + self.route("--kind", "review", "--difficulty", "2") + self.assertEqual(G.routed_kind(self.sid), "review") + self.assertFalse(G.is_building_delegation(self.sid, {"tool_input": {"prompt": "fix and implement everything"}})) + + def test_a_decision_older_than_the_window_is_no_decision_for_the_guard_too(self): + self.route("--kind", "impl", "--difficulty", "2") + with orchestration.Meter(self.sid) as m: + m["route"]["ts"] -= 3600 + self.assertIsNone(G.routed_kind(self.sid)) + + def test_route_accepts_only_the_ledgers_kinds_and_says_which(self): + r = self.route("--kind", "implementation", "--difficulty", "2") + self.assertNotEqual(r.returncode, 0) + for k in G.ledger_kinds(): + self.assertIn(k, r.stderr) + self.assertIsNone(self.decision()) # the record stays clean + for k in G.ledger_kinds(): + self.assertEqual(self.route("--kind", k, "--difficulty", "1").returncode, 0, k) + self.assertEqual(self.decision()["kind"], k) + + def test_the_guards_build_kinds_are_ledger_kinds(self): + self.assertTrue(set(G._list("build_kinds")) <= set(G.ledger_kinds())) + + def test_the_meters_own_texts_name_only_ledger_kinds(self): + text = orchestration.route_text() + for k in G.ledger_kinds(): + self.assertIn(k, text) + self.assertNotIn("implementation", text) + + +class RetryOf(Both): + """Integration point 3.""" + + def test_the_orchestration_branchs_own_ladder_is_gone(self): + for name in ("stronger_choice",): + self.assertFalse(hasattr(workers, name), name) + + def test_retry_of_asks_the_reworked_routing(self): + att = {"kind": "attempt", "id": "a1", "run_id": None, "ts": 1, "project": "p", "type": "read", "difficulty": 1, + "worker": "alpha-small", "outcome": "rejected", "check": "read"} + workers.append_record(att) + calls = [] + real_choice = routing.retry_choice + + def spy(*a, **kw): + calls.append((a[3:7], kw.get("floors") is not None)) + return real_choice(*a, **kw) + with mock.patch.object(routing, "retry_choice", spy): + r = self.sisi("route", "--retry-of", "a1", env={"SISI_SESSION_ID": self.sid}) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(calls, [(("read", 1, "alpha-small", 1), True)]) + self.assertEqual(r.stdout.splitlines()[0], "alpha-small") # the first retry: the same worker, a better brief + self.assertIn("improve the brief", r.stdout.lower()) + + def test_the_second_rejection_moves_to_strictly_better_evidence(self): + for i, w in enumerate(("alpha-small", "alpha-small")): + workers.append_record({"kind": "attempt", "id": "x%d" % i, "run_id": None, "ts": 2 + i, "project": "p", "type": "read", + "difficulty": 1, "worker": w, "outcome": "rejected", "check": "read", + "retry_of": "x0" if i else None}) + r = self.sisi("route", "--retry-of", "x1", env={"SISI_SESSION_ID": self.sid}) + self.assertEqual(r.stdout.splitlines()[0], "beta-large") + self.assertEqual(G.routed_kind(self.sid), "read") + + +class MeterRouterLines(Both): + """Integration point 4.""" + + def test_reading_is_asked_at_difficulty_one_and_building_at_two(self): + asked = [] + + def fake(kind, difficulty, cwd=None, own_model=None): + asked.append((kind, difficulty)) + return "w-%s" % kind, "mech", 1 + with mock.patch.object(workers, "recommend", fake): + picks = orchestration._picks(self.proj, self.own) + self.assertEqual(asked, [("read", 1), ("impl", 2)]) + self.assertEqual([p[0] for p in picks], ["w-read", "w-impl"]) + + def test_a_routine_read_is_not_sent_to_the_dearest_worker(self): + with open(os.path.join(self.data, "worker-prices.json"), "w") as f: + json.dump({"models": {"alpha-small": {"cost_per_million_tokens": 1}, "beta-large": {"cost_per_million_tokens": 9}}}, f) + read, build = orchestration._picks(self.proj, self.own) + self.assertEqual(read[0], "alpha-small") + self.spend_budget() + text = self.read() + self.assertRegex(text, r"reading and searching: alpha-small") + + def test_the_router_gets_the_floors_of_the_reworked_routing(self): + seen = {} + real = routing.choose + + def spy(*a, **kw): + seen["floors"] = kw.get("floors") + return real(*a, **kw) + with mock.patch.object(routing, "choose", spy): + workers.recommend("impl", 2, self.proj, self.own) + self.assertIsNotNone(seen["floors"]) + + +class UnitRecordAndStatus(Both): + """Integration point 5.""" + + def refused_unit(self): + self.open_unit(TG.good_contract(profile="integration")) # bound, but lacks what its profile needs before building + self.assertIn("Missing", self.edit()) # a guard refusal, kept with the unit + for _ in range(3): + self.read() + orchestration._event({"project": self.proj}, self.sid, "call") # a metered call in the window + + def status_block(self): + out = self.sisi("status").stdout.splitlines() + i = out.index("units in progress:") + block = [] + for ln in out[i + 1:]: + if not ln.strip(): + break + block.append(ln) + return block + + def test_the_record_carries_both_sides_additions(self): + self.refused_unit() + c = C.load(self.contract_path) + rec = U.build_record(c, self.proj, "complete", time.time()) + self.assertGreaterEqual(len(rec["guard_refusals"]), 1) + self.assertIn("direct_calls", rec["orchestration"]) + self.assertGreaterEqual(rec["orchestration"]["direct_calls"]["value"], 1) + self.assertIn("orch_direct_calls", rec["scorecard"]["parallelism"]) + self.assertEqual(U.summary_line(rec)["guard_refusals"], len(rec["guard_refusals"])) + + def test_the_binding_is_what_the_record_and_status_are_about(self): + c = self.open_unit() + rec = U.build_record(c, self.proj, "complete", time.time()) + self.assertEqual(G.author_models(self.proj, c), [self.own]) # the session that opened it, by its model + self.assertEqual(U.build_record(c, self.proj, "complete", time.time())["guard_refusals"], []) + + def test_status_shows_both_within_four_extra_lines(self): + self.open_unit(TG.good_contract(profile="integration")) + before = self.status_block() + self.refused_unit() + after = self.status_block() + self.assertTrue(any("guard refused" in ln for ln in after), after) + self.assertTrue(any("orchestration (measured)" in ln for ln in after), after) + self.assertLessEqual(len(after) - len(before), 4) + + +class RuleStatements(SisiCase): + """Integration point 6.""" + + NEEDS = {"size-by-risk": ("sisi/gate.py", "sisi/risk.py", "sisi/unitguard.py"), + "define-done": ("sisi/contract.py", "sisi/gate.py", "sisi/unitguard.py", "sisi/scorecard.py"), + "verify-enough": ("sisi/verify.py", "sisi/gate.py", "sisi/assure.py"), + "orchestrate": ("sisi/orchestration.py", "sisi/fallback.py", "sisi/routing.py", "sisi/brief.py", "sisi/watch.py")} + + def test_rules_2_3_4_and_6_say_enforced_and_name_where_the_code_lives(self): + for rid, files in self.NEEDS.items(): + text = rulecmd.enforcement_for(rid) + self.assertTrue(text.startswith("enforced:"), rid) + for f in files: + self.assertIn(f, text, (rid, f)) + for f in re.findall(r"sisi/[a-z_]+\.py", text): + self.assertTrue(os.path.isfile(os.path.join(REPO, f)), f) + + def test_the_rule_for_orchestration_has_one_statement_per_mechanism_of_both_sides(self): + text = rulecmd.enforcement_for("orchestrate") + for part in ("direct tool calls", "names no model", "failed three times", "arriving as a delegation result", "`sisi route` decision", + "--retry-of", "one refusal at a time", "judgement of each finished delegation"): + self.assertEqual(text.count(part), 1, part) + self.assertNotIn("stronger", text.split("--retry-of")[1][:200].split(";")[0].replace("strictly", "")) + + +class ConfigDefault(SisiCase): + """Integration point 7.""" + + def test_every_section_of_both_sides_and_valid_json(self): + with open(os.path.join(REPO, "config.default.json")) as f: + cfg = json.load(f) + for section in ("gate", "verify", "retro", "route", "unit", "orchestrate"): + self.assertIn(section, cfg) + self.assertEqual(sorted(cfg["orchestrate"]), ["direct_calls", "direct_chars", "enabled", "extension", "route_window_min"]) + self.assertEqual(sorted(cfg["route"]), ["price_blend_input_parts", "standing_floor"]) + self.assertEqual(cfg["unit"], {"stale_hours": 12}) + self.assertEqual(store.config()["orchestrate"]["direct_calls"], 6) + + +# --------------------------------------------------------------------------- the four fixes + +class DeepStaysFreshThroughAPause(TG.GuardCase): + """Fix A.""" + + def test_a_pause_does_not_make_a_fresh_deep_result_stale(self): + deep = dict(TG.real("slow"), tier="deep", cmd="test -f src/app.py") + c = TG.good_contract(checks=[TG.real("c1"), deep]) + self.open_unit(c) + r = self.sisi("verify", "--deep") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + state = json.loads(self.sisi("verify", "--state", "--json").stdout) + self.assertTrue(state["fresh"], state) + r = self.sisi("unit", "pause", "waiting for the reviewer", env={"SISI_SESSION_ID": self.sid}) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertTrue(C.load(self.contract_path)["pauses"]) # the contract file did change + state = json.loads(self.sisi("verify", "--state", "--json").stdout) + self.assertTrue(state["fresh"], state) + + def test_a_change_to_the_work_still_makes_it_stale(self): + deep = dict(TG.real("slow"), tier="deep", cmd="test -f src/app.py") + self.open_unit(TG.good_contract(checks=[TG.real("c1"), deep])) + self.sisi("verify", "--deep") + self.put(SRC, "def greet():\n return 'yo'\n") + self.assertFalse(json.loads(self.sisi("verify", "--state", "--json").stdout)["fresh"]) + + +class SendBackSaysWhy(TG.GuardCase): + """Fix B.""" + + def test_the_reason_is_the_contract_when_no_path_gave_one(self): + self.assertEqual(gate.profile_reason("integration", {"declared": "integration"}, ["no changed paths"]), + "the contract declares the integration profile") + self.assertEqual(gate.profile_reason("integration", {"declared": "integration"}, ["auth code", "x"]), "auth code") + self.assertIsNone(gate.profile_reason("trivial", {"declared": None}, ["no changed paths"])) + + def test_the_gates_message_does_not_open_with_no_changed_paths(self): + os.environ["SISI_RETRO_REQUIRED"] = "1" + self.addCleanup(lambda: os.environ.__setitem__("SISI_RETRO_REQUIRED", "0")) + self.tick() + self.open_unit(TG.good_contract(profile="integration")) + sess = store.load_session(self.sid) + sess["dirty"] = True + store.save_session(self.sid, sess) + action, msg = gate.decide({"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop", "stop_hook_active": False}) + self.assertEqual(action, "block", msg) + self.assertNotIn("no changed paths", msg) + 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_write_named_by_a_shell_variable_is_ordinary_source(self): + """Found by the live check: `for f in src/*; do sed -i ... "$f"; done` slipped through as a trivial change.""" + msg = self.bash('for f in src/*.py; do sed -i "s/a/b/" "$f"; done') + self.assertIn("sisi contract init", msg) + self.assertIn("does not name", msg) + self.assertLessEqual(len(msg.splitlines()), 12) + self.open_unit() + self.assertIsNone(self.bash('for f in src/*.py; do sed -i "s/a/b/" "$f"; done')) + + def test_a_line_that_cannot_be_split_but_plainly_writes_is_ordinary_source(self): + cmd = ("for i in 01 02; do sed -i \"s/a$i/b/\" src/mod$i.py; done && python3 -c \"\nimport sys\nprint(f'x{1}')\n\" ; " + "git diff | grep '^[-+] ' \"") # an unbalanced quote: no tokenizer reads it + self.assertEqual(G.shell_targets(cmd, self.proj), [G.UNPARSED]) + self.assertIn("sisi contract init", self.bash(cmd)) + self.assertEqual(G.shell_targets('echo "unbalanced; ls', self.proj), []) # nothing plainly writing: left to the snapshot + + 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.""" + + def setUp(self): + super().setUp() + self.src = os.path.join(self.tmp, "src") + for rel in ("a.txt", "b.lock", "sub/c.txt", "sub/d.lock"): + p = os.path.join(self.src, rel) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "w") as f: + f.write(rel) + self.out = os.path.join(self.tmp, "backup") + + def test_a_file_removed_mid_copy_is_left_out(self): + real = shutil.copy2 + + def racy(s, d, *a, **kw): + if s.endswith(".lock"): + os.unlink(s) # gone between the listing and the copy + return real(s, d, *a, **kw) + with mock.patch.object(lifecycle.shutil, "copy2", racy): + lifecycle._copy_into(self.src, self.out, "data") + got = sorted(os.path.relpath(os.path.join(dp, n), self.out) for dp, _d, fs in os.walk(self.out) for n in fs) + self.assertEqual(got, ["data/a.txt", "data/sub/c.txt"]) + + def test_a_folder_removed_mid_copy_is_left_out(self): + real = os.listdir + + def racy(p): + if p.endswith("sub"): + shutil.rmtree(p) + return real(p) + with mock.patch.object(lifecycle.os, "listdir", racy): + lifecycle._copy_into(self.src, self.out, "data") + self.assertTrue(os.path.isfile(os.path.join(self.out, "data", "a.txt"))) + + def test_a_real_error_is_still_an_error(self): + with mock.patch.object(lifecycle.shutil, "copy2", side_effect=PermissionError("no")): + with self.assertRaises(PermissionError): + lifecycle._copy_into(self.src, self.out, "data") + + +class NoRecipeForAMachine(SisiCase): + """Fix D.""" + + def mk(self): + from sisi import learning as L + f = dict(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") + return L.new_record(f["moment"], f["cause"], "correctness", "promote", self.proj, "u-test", change=f["change"], + mechanism="policy", scope="project", expect="caught before delivery", validate="replay")["id"] + + def ask(self, text, tool=None): + args = ["prompt"] + (["--tool", tool] if tool else []) + r = self.sisi(*args, stdin=json.dumps({"prompt": text, "session_id": "s1", "cwd": self.proj})) + self.assertEqual(r.returncode, 0, r.stderr) + return json.loads(r.stdout)["hookSpecificOutput"]["additionalContext"] if r.stdout.strip() else "" + + NOTICES = ('Delegated task "cut a new release and tag it" [completed]: tagged v2 and published the release notes', + 'Delegated task "cut a new release and tag it" [failed]: API error 429, usage limit reached', + '[failed]: cut a new release and tag it, the worker hit a usage limit', + '\ncompleted\ncut a new release and tag it\n', + 'Scheduled wake-up: cut a new release and tag it when the build is green') + + def test_a_person_gets_the_recipe(self): + self.mk() + self.assertIn("recipe `release`", self.ask("cut a new release and tag it")) + + def test_a_machines_notice_gets_no_recipe(self): + self.mk() + for text in self.NOTICES: + with self.subTest(text=text[:40]): + self.assertNotIn("recipe", self.ask(text)) + + def test_learnings_in_scope_still_go_through_for_a_notice(self): + lid = self.mk() + ctx = self.ask('Delegated task "publish the release: check the tag, the manifest version and the changelog" ' + '[completed]: ready to publish') + self.assertIn(lid, ctx) + self.assertNotIn("Done means", ctx) + + def test_the_test_is_the_one_delivery_uses_and_it_defaults_to_no_recipe(self): + from sisi import harvest + for text in self.NOTICES: + self.assertIsNone(harvest.typed_text({}, queued_prompt=text)[0], text) + self.assertTrue(prompt.is_request("cut a new release and tag it")) + with mock.patch.object(harvest, "typed_text", side_effect=RuntimeError("cannot tell")): + self.assertFalse(prompt.is_request("cut a new release and tag it")) + self.assertFalse(prompt.is_request("cut a new release and tag it", {"origin": {"kind": "task-notification"}})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_meter.py b/tests/test_meter.py new file mode 100644 index 0000000..ace6c2f --- /dev/null +++ b/tests/test_meter.py @@ -0,0 +1,1015 @@ +"""The direct-work meter, the delegation guard and the repeat-failure stop (rule 6, SPEC section 7; R-7.1-1, +R-7.2-2, R-6.3-1, R-6.3-3, R-15-4). Every test is written from the side of an agent trying to keep working +directly; hook input is what Claude Code sends, the output is what the host reads.""" +import json, os, subprocess, time, unittest +from unittest import mock +from support import * + +from sisi import orchestration, store, workers + + +def seed_workers(case, names=("alpha-small", "beta-large")): + """A ledger with two usable workers (host-native, judged), the first the cheaper.""" + for i, w in enumerate(names): + for t in ("read", "impl"): + workers.append_record({"kind": "attempt", "id": "%s%s" % (w[:3], t[:2]), "run_id": None, "ts": 1, + "project": "p", "type": t, "difficulty": 1, "worker": w, + "outcome": "accepted", "check": "read"}) + with open(os.path.join(case.data, "worker-prices.json"), "w") as f: + json.dump({"models": {names[0]: {"cost_per_million_tokens": 1}, names[1]: {"cost_per_million_tokens": 9}}}, f) + # a fresh discovery cache (no command-line tool installed): no test ever runs a real tool's model listing + with open(os.path.join(case.data, "workers.json"), "w") as f: + json.dump({"checked": time.time(), "tools": [{"name": "opencode", "installed": False, "models": [], "usable": False}]}, f) + + +class MeterBase(SisiCase): + def setUp(self): + super().setUp() + self.git_init() + os.makedirs(self.data, exist_ok=True) + seed_workers(self) + self.sid = "sess-1" + self.own = "gamma-top" + self.tick() + + def payload(self, ev, tool, inp=None, **kw): + d = {"session_id": self.sid, "cwd": self.proj, "hook_event_name": ev, "tool_name": tool, + "tool_input": inp or {}} + d.update(kw) + return json.dumps(d) + + def tick(self, sid=None, **kw): + d = {"session_id": sid or self.sid, "cwd": self.proj, "hook_event_name": "SessionStart", + "source": "startup", "model": self.own} + d.update(kw) + self.sisi("tick", "--tool", "claude-code", stdin=json.dumps(d)) + + def prompt(self, text="fix the parser and explain each module in the project", sid=None, route=True): + """A prompt reaches the session; by default the agent has also asked `sisi route` (a delegation needs that).""" + r = self.sisi("prompt", "--tool", "claude-code", stdin=json.dumps( + {"session_id": sid or self.sid, "cwd": self.proj, "hook_event_name": "UserPromptSubmit", "prompt": text})) + if route and not text.startswith("") and not text.startswith("[failed]") \ + and not text.startswith("You are a worker"): + self.route(sid=sid) + return r + + def route(self, kind="research", difficulty="1", *extra, sid=None): + return self.sisi("route", "--kind", kind, "--difficulty", difficulty, *extra, + env={"SISI_SESSION_ID": sid or self.sid}) + + def pre(self, tool="Read", inp=None, **kw): + """The decoded hook output of one before-tool call: (denied, reason, whole output).""" + r = self.sisi("watch", "--before", "--tool", "claude-code", + stdin=self.payload("PreToolUse", tool, inp or {"file_path": "/x"}, **kw)) + self.assertEqual(r.returncode, 0) + out = json.loads(r.stdout) if r.stdout.strip() else {} + hs = out.get("hookSpecificOutput") or {} + return hs.get("permissionDecision") == "deny", hs.get("permissionDecisionReason") or hs.get("additionalContext"), out + + def post(self, tool="Read", inp=None, response="x", event="PostToolUse", **kw): + return self.sisi("watch", "--after", "--tool", "claude-code", + stdin=self.payload(event, tool, inp or {"file_path": "/x"}, tool_response=response, **kw)) + + def events(self, ev=None): + rows = store.read(orchestration.EVENTS) + return [r for r in rows if ev is None or r["ev"] == ev] + + def read_n(self, n, tool="Read"): + return [self.pre(tool)[0] for _ in range(n)] + + +class BudgetTests(MeterBase): + def test_fifty_reads_in_one_turn(self): + """R-7.2-2: the seventh counted call is refused, and so is every one after it, with a message of at most + 12 lines that gives the count, rule 6, the router's workers and both ways on.""" + self.prompt() + denied = self.read_n(50) + self.assertEqual(denied[:6], [False] * 6) + self.assertEqual(denied[6:], [True] * 44) + _d, reason, _o = self.pre() + self.assertLessEqual(len(reason.splitlines()), 12) + self.assertIn("6 direct tool calls", reason) + self.assertIn("rule 6", reason) + self.assertIn("alpha-small", reason) # the router's pick, by calling the routing code + self.assertIn("host's own subagent tool", reason) # its mechanism line + self.assertIn("sisi delegate brief", reason) + self.assertIn('sisi unit direct ""', reason) + self.assertEqual(len(self.events("refusal")), 45) + + def test_one_shell_command_printing_twenty_files_trips_the_character_budget(self): + """A single call whose result is huge uses the character budget: the very next counted call is refused.""" + self.prompt() + self.assertFalse(self.pre("Bash", {"command": "cat src/*"})[0]) + self.post("Bash", {"command": "cat src/*"}, response={"stdout": "x" * 31000, "stderr": ""}) + denied, reason, _ = self.pre("Read") + self.assertTrue(denied) + self.assertIn("1 direct tool calls", reason.replace("1 direct tool call ", "1 direct tool calls ")) + self.assertIn("31000 characters", reason) + + def test_a_tool_sisi_has_never_heard_of_counts(self): + """Legwork through a tool named nowhere in the data still counts.""" + self.prompt() + denied = [self.pre("mcp__some__brandnew_tool", {"q": "x"})[0] for _ in range(8)] + self.assertEqual(denied, [False] * 6 + [True] * 2) + + def test_exempt_tools_and_sisi_commands_are_never_counted_or_refused(self): + self.prompt() + self.read_n(6) + for tool in ("AskUserQuestion", "TodoWrite", "EnterPlanMode", "SendMessage"): + self.assertFalse(self.pre(tool, {})[0], tool) + for cmd in ("sisi route --kind research --difficulty 1", 'sisi unit direct "a; b"', "FOO=1 sisi delegate brief", + "python3 /opt/x/bin/sisi status", "sisi status && sisi risk"): + self.assertFalse(self.pre("Bash", {"command": cmd})[0], cmd) + self.assertTrue(self.pre("Read")[0]) + + def test_a_command_that_only_starts_with_sisi_still_counts(self): + """`sisi x && cat everything` is legwork with a sisi command in front.""" + self.prompt() + self.read_n(6) + self.assertTrue(self.pre("Bash", {"command": "sisi status && cat src/*"})[0]) + self.assertTrue(self.pre("Bash", {"command": "echo sisi"})[0]) + self.assertTrue(self.pre("Bash", {"command": "sisi status; cat src/a.py"})[0]) + self.assertTrue(self.pre("Bash", {"command": "sisi status | xargs cat"})[0]) + + def test_trivial_output_handling_around_a_sisi_command_does_not_make_it_legwork(self): + """Found by the live check: `sisi unit direct "..."; echo "exit=$?"` was refused as a counted command, so the + agent could not use either way on.""" + self.prompt() + self.read_n(6) + for cmd in ('sisi unit direct "a specific reason of 40 lines"; echo "exit=$?"', "sisi route --kind test --difficulty 1 --explain 2>&1; echo \"exit=$?\"", + "sisi delegate brief | head -20", "sisi status && echo done"): + self.assertFalse(self.pre("Bash", {"command": cmd})[0], cmd) + + def test_the_turn_resets_at_each_prompt(self): + self.prompt() + self.read_n(7) + self.assertTrue(self.pre()[0]) + self.prompt("now fix the second bug in the parser as well please") + self.assertFalse(self.pre()[0]) + + def test_limits_come_from_config(self): + os.makedirs(self.data, exist_ok=True) + with open(os.path.join(self.data, "config.json"), "w") as f: + json.dump({"orchestrate": {"direct_calls": 2}}, f) + self.prompt() + self.assertEqual(self.read_n(4), [False, False, True, True]) + + def test_a_hook_that_raises_lets_the_call_through(self): + """Fail open: a crash inside the meter never blocks the user's tool.""" + self.prompt() + self.read_n(6) + with mock.patch.object(orchestration, "before", side_effect=RuntimeError("boom")): + denied, _r, out = self.pre() + self.assertFalse(denied) + self.assertEqual(out, {}) + with mock.patch.object(orchestration.Meter, "__enter__", side_effect=OSError("disk")): + self.assertFalse(self.pre()[0]) + + +class ExtensionTests(MeterBase): + def test_a_generic_reason_is_refused_a_specific_one_grants_the_extension(self): + """R-6.3-3: 'because it is easier' is not a reason; a specific one extends the turn by ten calls and is stored.""" + self.prompt() + self.read_n(7) + for generic in ("because it is easier", "faster", "it is simpler and quicker to just do it myself"): + r = self.sisi("unit", "direct", generic) + self.assertEqual(r.returncode, 1, generic) + self.assertIn("generic", r.stdout) + self.assertTrue(self.pre()[0]) + r = self.sisi("unit", "direct", "the fix is one line in parser.py and a brief would be longer than the change") + self.assertEqual(r.returncode, 0, r.stdout) + self.assertEqual(self.read_n(10), [False] * 10) + self.assertTrue(self.pre()[0]) + ext = self.events("extension") + self.assertEqual(len(ext), 1) + self.assertIn("parser.py", ext[0]["reason"]) + + def test_many_extensions_are_each_recorded_and_visible_in_status(self): + """Splitting legwork across the allowed calls and many extensions: nothing hides, every extension and its + reason is stored and `sisi status` shows it for the open unit.""" + self.write_contract(contract([check("c", "true")])) + self.prompt() + for i in range(4): + self.read_n(7 if i == 0 else 11) + r = self.sisi("unit", "direct", "step %d of the parser migration reads src/part%d.py once" % (i, i)) + self.assertEqual(r.returncode, 0, r.stdout) + self.assertEqual(len(self.events("extension")), 4) + out = self.sisi("status").stdout + self.assertIn("4 extension(s)", out) + self.assertIn("src/part3.py", out) + self.assertIn("orchestration (measured)", out) + + def test_the_same_reason_twice_in_a_turn_is_refused(self): + self.prompt() + self.read_n(7) + why = "the fix is one line in parser.py and a brief would be longer" + self.assertEqual(self.sisi("unit", "direct", why).returncode, 0) + self.assertEqual(self.sisi("unit", "direct", why).returncode, 1) + + def test_the_character_budget_grows_with_an_extension(self): + self.prompt() + self.pre("Bash", {"command": "cat a"}) + self.post("Bash", {"command": "cat a"}, response="y" * 31000) + self.assertTrue(self.pre()[0]) + self.sisi("unit", "direct", "the two config files hold 40 lines each, a brief costs more") + self.assertFalse(self.pre()[0]) + + +class WhoIsMeteredTests(MeterBase): + def test_a_host_marked_subagent_call_is_never_counted_or_refused(self): + self.prompt() + self.read_n(7) + denied, _r, _o = self.pre("Read", agent_id="sub-1") + self.assertFalse(denied) + self.assertEqual(self.events("call")[-1]["ev"], "call") + self.assertEqual(len(self.events("call")), 6) # the subagent's call is not in the count + + def test_a_session_started_by_sisi_delegate_is_never_refused(self): + self.prompt() + with mock.patch.dict(os.environ, {"SISI_WORKER_RUN": "1"}): + self.assertEqual(self.read_n(20), [False] * 20) + + def test_a_session_the_host_started_as_a_subagent_is_never_refused(self): + self.tick("sub-sess", agent_id="a1") + self.sid = "sub-sess" + self.prompt() + self.assertEqual(self.read_n(20), [False] * 20) + + def test_a_first_prompt_that_opens_with_the_brief_line_makes_a_worker(self): + """Compared case-insensitively on the first 200 characters.""" + from sisi import brief + line = brief.template().splitlines()[0] + self.prompt(line.upper() + "\n\n## Outcome and scope\nfind the bug") + self.assertEqual(self.read_n(20), [False] * 20) + + def test_a_main_prompt_that_only_mentions_worker_later_is_still_metered(self): + from sisi import brief + line = brief.template().splitlines()[0] + self.prompt("fix the parser, and remember this: " + line + " you are a worker of mine") + self.assertEqual(self.read_n(8), [False] * 6 + [True] * 2) + # nor does a brief line in the second prompt change a session that began as a main thread + self.prompt(line + " again please do this") + self.assertEqual(self.read_n(8), [False] * 6 + [True] * 2) + + def test_no_refusal_when_no_other_worker_is_usable(self): + """Counts and records, never refuses: the ledger knows only the session's own model.""" + os.unlink(workers.ledger_path()) + workers.append_record({"kind": "attempt", "id": "x", "run_id": None, "ts": 1, "project": "p", "type": "research", + "difficulty": 1, "worker": self.own, "outcome": "accepted", "check": "read"}) + self.prompt() + self.assertEqual(self.read_n(10), [False] * 10) + self.assertEqual(len(self.events("call")), 10) + self.assertTrue(self.events("unrefused")) + self.assertEqual(self.events("refusal"), []) + + +class DelegationGuardTests(MeterBase): + def deleg(self, **kw): + inp = {"description": "read the code", "prompt": "Outcome: list what each file does.", "subagent_type": "general-purpose"} + inp.update(kw) + return self.pre("Agent", inp) + + def test_a_delegation_naming_no_model_is_refused_with_the_recommendation(self): + self.prompt() + denied, reason, _ = self.deleg() + self.assertTrue(denied) + self.assertIn("names no model", reason) + self.assertIn("alpha-small", reason) + self.assertIn('sisi unit direct ""', reason) + self.assertLessEqual(len(reason.splitlines()), 12) + + def test_the_same_expensive_model_named_explicitly_is_refused(self): + self.prompt() + denied, reason, _ = self.deleg(model="gamma") # an alias of the session's own model + self.assertTrue(denied) + self.assertIn("own model", reason) + denied, _r, _o = self.deleg(model="gamma-top") + self.assertTrue(denied) + + def test_a_recorded_reason_allows_the_same_model_delegation(self): + self.prompt() + self.assertTrue(self.deleg()[0]) + self.sisi("unit", "direct", "the review must see exactly what this session saw, 3 files") + self.assertFalse(self.deleg()[0]) + + def test_a_delegation_to_another_model_is_allowed_recorded_and_its_brief_advised(self): + self.prompt() + denied, ctx, _ = self.deleg(model="alpha-small", prompt="read the files and tell me what they do") + self.assertFalse(denied) + self.assertIn("recorded as run", ctx) + self.assertIn("no outcome and scope", ctx) # missing parts are advice, never a refusal + runs = [r for r in workers.read_records() if r.get("kind") == "run"] + self.assertEqual(len(runs), 1) + self.assertEqual((runs[0]["worker"], runs[0]["status"], runs[0]["session"]), ("alpha-small", "pending", self.sid)) + + def test_delegations_are_not_counted_as_direct_calls(self): + self.prompt() + for _ in range(10): + self.assertFalse(self.deleg(model="alpha-small")[0]) + self.assertFalse(self.pre()[0]) + + +class DelegationRecordTests(MeterBase): + """Item 4: a host delegation writes itself to the ledger; the gate asks for the judgement once.""" + + def deleg_pre(self, tool_use_id="tu1", model="alpha-small"): + return self.pre("Agent", {"description": "d", "prompt": "Outcome: x\nAcceptance: y\nFiles you may change: none", + "model": model}, tool_use_id=tool_use_id) + + def deleg_post(self, response, tool_use_id="tu1", event="PostToolUse"): + return self.post("Agent", {"description": "d", "prompt": "p", "model": "alpha-small"}, response=response, + event=event, tool_use_id=tool_use_id) + + def stop(self): + r = self.sisi("gate", "--tool", "claude-code", stdin=json.dumps( + {"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop", "stop_hook_active": False})) + return json.loads(r.stdout) if r.stdout.strip() else {} + + def runs(self): + return workers.merged_runs() + + def test_a_synchronous_delegation_is_written_pending_then_completed_with_tokens(self): + self.prompt() + _d, ctx, _ = self.deleg_pre() + run = self.runs()[0] + self.assertIn(run["id"], ctx) # the id is printed + self.assertEqual((run["status"], run["worker"], run["session"]), ("pending", "alpha-small", self.sid)) + self.assertEqual(workers.unjudged_runs(), []) # in flight: nothing to judge yet + self.deleg_post({"status": "completed", "totalTokens": 4321, "totalDurationMs": 90000}) + run = self.runs()[0] + self.assertEqual((run["status"], run["tokens"], run["tokens_class"], run["minutes"]), ("waiting", 4321, "measured", 1.5)) + self.assertEqual([r["id"] for r in workers.unjudged_runs()], [run["id"]]) + r = self.sisi("delegate", "judge", run["id"], "--outcome", "accepted", "--check", "read", + "--type", "research", "--difficulty", "1") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertEqual(workers.unjudged_runs(), []) + att = [x for x in workers.read_records() if x.get("kind") == "attempt" and x.get("run_id") == run["id"]][0] + self.assertEqual((att["type"], att["difficulty"], att["tokens"], att["minutes"]), ("research", 1, 4321, 1.5)) + + def test_an_async_launch_stays_pending_until_the_hosts_notice_arrives(self): + """The host answers an async launch at once; the run is finished only when its notice comes as a prompt.""" + self.prompt() + self.deleg_pre(tool_use_id="toolu_A") + self.read_n(3) + self.deleg_post({"isAsync": True, "status": "async_launched", "agentId": "agent9", "resolvedModel": "alpha-small-2"}, + tool_use_id="toolu_A") + self.assertEqual(self.runs()[0]["status"], "pending") # still running: nothing to judge or ask for + self.assertEqual(workers.unjudged_runs(), []) + note = ("\nagent9\ntoolu_A\n" + "completed\ndone\n7302" + "11612\n") + self.prompt(note) + run = self.runs()[0] + self.assertEqual((run["status"], run["tokens"], run["tokens_class"]), ("waiting", 7302, "measured")) + # a notice is the host reporting, not a new request: it gives no new budget + self.assertEqual(self.read_n(5), [False] * 3 + [True] * 2) + + def test_the_gate_asks_for_the_judgements_once_per_set_of_runs(self): + self.prompt() + self.deleg_pre("t1") + self.deleg_post({"status": "completed"}, "t1") + out = self.stop() + self.assertEqual(out.get("decision"), "block") + self.assertIn("not judged yet", out["reason"]) + rid = self.runs()[0]["id"] + self.assertIn(rid, out["reason"]) + self.assertIn("sisi delegate judge", out["reason"]) + self.assertEqual(self.stop(), {}) # the same set is not asked again + self.deleg_pre("t2") + self.deleg_post({"status": "completed"}, "t2") + out = self.stop() # a new set is + self.assertEqual(out.get("decision"), "block") + for r in self.runs(): + self.sisi("delegate", "judge", r["id"], "--outcome", "accepted", "--check", "read", "--type", "research", "--difficulty", "1") + self.assertEqual(self.stop(), {}) + + def test_another_sessions_runs_are_not_asked_for(self): + workers.append_record({"kind": "run", "id": "other1", "ts": 1, "worker": "alpha-small", "session": "someone-else", + "status": "waiting"}) + self.assertEqual(self.stop(), {}) + + +class RepeatFailureTests(MeterBase): + """Item 5 (R-15-4): the fourth identical failing command with no file changed is refused once.""" + + def fail(self, cmd="make build"): + denied, reason, _ = self.pre("Bash", {"command": cmd}) + if not denied: + self.post("Bash", {"command": cmd}, response=None, event="PostToolUseFailure", error="Exit code 2") + return denied, reason + + def test_the_fourth_identical_attempt_is_refused_once(self): + self.prompt() + self.assertEqual([self.fail()[0] for _ in range(3)], [False] * 3) + denied, reason = self.fail("make build") # whitespace-normalised + self.assertTrue(denied) + self.assertIn("will not produce new information", reason) + self.assertIn("failed 3 times", reason) + self.assertLessEqual(len(reason.splitlines()), 12) + self.assertFalse(self.fail()[0]) # once: the next is let through + self.assertEqual([e["why"] for e in self.events("refusal")], ["repeat"]) + + def test_a_changed_file_between_failures_resets_the_count(self): + self.prompt() + self.fail(); self.fail() + open(os.path.join(self.proj, "fix.txt"), "w").write("a fix") + self.fail() # first failure of the new state + self.assertFalse(self.fail()[0]) + self.assertFalse(self.fail()[0]) + self.assertTrue(self.fail()[0]) + + def test_a_success_in_between_resets_it(self): + self.prompt() + self.fail(); self.fail() + self.post("Bash", {"command": "make build"}, response={"stdout": "ok", "exit_code": 0}) + self.fail(); self.fail() + self.assertFalse(self.fail()[0]) + + def test_another_command_is_not_affected(self): + self.prompt() + for _ in range(3): + self.fail() + self.assertFalse(self.fail("make test")[0]) + + def test_a_new_turn_starts_the_count_again(self): + self.prompt() + for _ in range(3): + self.fail() + self.prompt("the build is still broken, please look at it again now") + self.assertFalse(self.fail()[0]) + + def test_workers_are_not_stopped(self): + self.prompt() + for _ in range(3): + self.fail() + self.assertFalse(self.pre("Bash", {"command": "make build"}, agent_id="a1")[0]) + + +class RecordTests(MeterBase): + """Item 6: the unit record and `sisi status` show orchestration, each value classed measured.""" + + def start_unit(self): + from sisi import contract as C + self.assertEqual(self.sisi("contract", "init", "--goal", "make the thing").returncode, 0) + p = os.path.join(self.proj, ".sisi", "contract.json") + c = C.load(p) + c["checks"] = [check("works", "test -f done.txt")] + C.save(p, c) + + def finish_and_close(self): + open(os.path.join(self.proj, "done.txt"), "w").write("x") + self.assertEqual(self.sisi("verify").returncode, 0) + r = self.sisi("unit", "close") + self.assertEqual(r.returncode, 0, r.stdout) + return json.load(open(os.path.join(self.proj, ".sisi", "units", "proj.json"))) + + def test_the_closed_unit_carries_the_orchestration_part(self): + self.start_unit() + self.prompt() + self.read_n(8) # 6 counted, 2 refused + self.sisi("unit", "direct", "the two config files hold 40 lines each, a brief costs more") + self.read_n(2) + self.pre("Agent", {"description": "d", "prompt": "p", "model": "alpha-small"}, tool_use_id="x1") + rec = self.finish_and_close() + o = rec["orchestration"] + self.assertEqual(o["direct_calls"], {"value": 8, "class": "measured"}) + self.assertEqual(o["refusals"], {"value": 2, "class": "measured"}) + self.assertEqual(o["extensions"], {"value": 1, "class": "measured"}) + self.assertIn("40 lines", o["extension_reasons"]["value"][0]) + self.assertEqual(o["delegations_started"]["value"], 1) + self.assertEqual((o["delegations_judged"]["value"], o["delegations_unjudged"]["value"]), (0, 1)) + self.assertEqual(o["delegated_share"], {"value": 0.111, "class": "measured"}) # 1 of 9 tool calls + self.assertEqual(rec["scorecard"]["parallelism"]["orch_direct_calls"]["class"], "measured") + out = self.sisi("status").stdout + self.assertIn("orch_direct_calls 8 (measured)", out) + self.assertIn("orch_extension_reasons", out) + + def test_status_shows_it_for_the_unit_in_progress(self): + self.start_unit() + self.prompt() + self.read_n(7) + out = self.sisi("status").stdout + self.assertIn("orchestration (measured): 6 direct calls", out) + self.assertIn("1 refusals", out) + + def test_a_unit_with_nothing_metered_says_unavailable_not_zero(self): + self.start_unit() + rec = self.finish_and_close() + self.assertEqual(rec["orchestration"]["direct_calls"]["class"], "unavailable") + + def test_rule_six_is_listed_as_enforced_and_names_the_mechanisms(self): + out = self.sisi("rule").stdout + line = next(l for l in out.splitlines() if "orchestrate" in l) + self.assertIn("enforced", line) + self.assertNotIn("not enforced", line) + detail = self.sisi("rule", "orchestrate").stdout + for phrase in ("direct tool calls", "sisi unit direct", "names no model", "judg", "unavailable worker", + "question-dialog call"): + self.assertIn(phrase, detail) + + +FUTURE = "2036-11-30T05:00:00Z" + + +def future_ts(): + return workers._parse_time(FUTURE) + + +class FallbackTests(MeterBase): + """Item 9 (R-7.2-1, R-7.2-2, R-15-1, R-15-5, R-17-3): a worker's unavailability is recorded and the fallback handed + over where it arrives; the person is not asked.""" + + QUOTA = ("[failed]: API error 429 [request_id=req_011]: Subscription quota exhausted. " + "Your usage window resets at " + FUTURE) + + def setUp(self): + super().setUp() + # one prefixed provider (a command-line tool's model) besides the two host-native workers + with open(os.path.join(self.data, "workers.json"), "w") as f: + json.dump({"checked": time.time(), "tools": [{"name": "opencode", "installed": True, "usable": True, + "models": ["provx/model-1"]}]}, f) + with open(os.path.join(self.data, "worker-prices.json"), "w") as f: + json.dump({"models": {"provx/model-1": {"cost_per_million_tokens": 0.1}, + "alpha-small": {"cost_per_million_tokens": 1}, + "beta-large": {"cost_per_million_tokens": 9}}}, f) + for t in ("read", "impl"): + workers.append_record({"kind": "attempt", "id": "px" + t[:2], "run_id": None, "ts": 1, "project": "p", "type": t, + "difficulty": 1, "worker": "provx/model-1", "outcome": "accepted", "check": "read"}) + + def context(self, r): + out = json.loads(r.stdout) if r.stdout.strip() else {} + return (out.get("hookSpecificOutput") or {}).get("additionalContext") or "" + + def notice(self, text=None, use_id="toolu_Q", task="agentQ", status="failed"): + body = text or self.QUOTA + return ("\n%s\n%s\n%s\n" + "Agent \"read the code\" failed\n%s\n" + % (task, use_id, status, body)) + + def launch(self, model="provx/model-1", use_id="toolu_Q"): + self.pre("Agent", {"description": "read the code", "prompt": "Outcome: x", "model": model}, tool_use_id=use_id) + self.post("Agent", {"description": "d", "prompt": "p", "model": model}, + response={"isAsync": True, "status": "async_launched", "agentId": "agentQ"}, tool_use_id=use_id) + + def down(self): + return workers.read_availability() + + def test_the_quota_notice_through_the_prompt_hook_marks_the_provider_down_and_hands_over_the_fallback(self): + self.prompt() + self.launch() + ctx = self.context(self.prompt(self.notice())) + entry = self.down()["provx"] # the provider, not one model + self.assertEqual((entry["retry_at"], entry["reason"]), (future_ts(), "limit")) + self.assertIn("quota exhausted", entry["note"].lower()) + lines = ctx.splitlines() + self.assertLessEqual(len(lines), 6) + self.assertIn("provx/model-1 is unavailable", ctx) + self.assertIn("2036-11-30 05:00 UTC", ctx) + self.assertIn("alpha-small", ctx) # every prefixed provider is down: host-native + self.assertIn("host's own subagent tool", ctx) + self.assertIn("Do not ask the person, and do not report this to them", ctx) + self.assertNotIn("tell them", ctx.lower()) # worker availability is internal (SPEC 9.7, 17) + self.assertIn("Cancel or interrupt", ctx) + + def test_a_failure_notice_gets_the_fallback_and_no_recipe(self): + """The notice is a machine's message: the recipe matcher does not run on it, the fallback still goes through.""" + self.prompt() + self.launch() + ctx = self.context(self.prompt(self.notice(self.QUOTA + " (task: cut a new release and tag it)"))) + self.assertIn("provx/model-1 is unavailable", ctx) + self.assertNotIn("recipe", ctx) + self.assertNotIn("Done means", ctx) + + def test_the_same_through_a_delegation_tool_result(self): + self.prompt() + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "provx/model-1"}, tool_use_id="t9") + r = self.post("Agent", {"description": "d", "prompt": "p", "model": "provx/model-1"}, response=self.QUOTA, tool_use_id="t9") + ctx = self.context(r) + self.assertEqual(self.down()["provx"]["retry_at"], future_ts()) + self.assertIn("alpha-small", ctx) + self.assertLessEqual(len(ctx.splitlines()), 6) + run = workers.merged_runs()[0] + self.assertEqual(run["status"], "superseded") # never asked to be judged + self.assertEqual(workers.unjudged_runs(), []) + + def test_a_failing_sisi_delegate_run_hands_over_the_fallback_under_the_event_name_the_host_expects(self): + """Found by the live check: the host rejects hook output whose event name is not the event it answers.""" + self.prompt() + out = ("fakeprov/model-1 is unavailable (limit: API error 429: Subscription quota exhausted. Your usage window resets at " + + FUTURE + "); trying the next choice\nsisi: no usable worker remains for kind research at difficulty 1") + r = self.sisi("watch", "--after", "--tool", "claude-code", stdin=self.payload( + "PostToolUseFailure", "Bash", {"command": "sisi delegate --kind research --difficulty 1 --brief b.md"}, + error="Exit code 1\n" + out)) + hs = json.loads(r.stdout)["hookSpecificOutput"] + self.assertEqual(hs["hookEventName"], "PostToolUseFailure") + self.assertIn("Next for the same kind of work (research, difficulty 1)", hs["additionalContext"]) + self.assertIn("Do not ask the person", hs["additionalContext"]) + self.assertEqual(self.down(), {}) # `sisi delegate` recorded it itself; the hook does not do it twice + # the same inside a longer command line (writing the brief and running it in one call) + r = self.sisi("watch", "--after", "--tool", "claude-code", stdin=self.payload( + "PostToolUseFailure", "Bash", {"command": "cat > b.md <<'EOF'\nx\nEOF\nsisi delegate --kind research --difficulty 1 --brief b.md"}, + error="Exit code 1\n" + out)) + self.assertIn("Fall back now", json.loads(r.stdout)["hookSpecificOutput"]["additionalContext"]) + + def test_sisi_delegate_itself_tells_the_agent_to_fall_back_when_only_host_workers_remain(self): + """Found by the live check: a small model stopped at "no usable worker remains"; the command's own output now + carries the instruction, and the reset time in the message is what is recorded.""" + fake = os.path.join(self.tmp, "fakebin") + os.makedirs(fake) + with open(os.path.join(fake, "opencode"), "w") as f: + f.write("#!/bin/sh\necho 'API error 429: Subscription quota exhausted. Your usage window resets at %s' >&2\nexit 1\n" % FUTURE) + os.chmod(os.path.join(fake, "opencode"), 0o755) + brief = os.path.join(self.proj, "brief.md") + with open(brief, "w") as f: + f.write("## Outcome and scope\nlist files\n## Acceptance\none per line\n## Files you may change\nnone\n") + r = self.sisi("delegate", "--kind", "research", "--difficulty", "1", "--brief", brief, + env={"PATH": fake + os.pathsep + os.environ["PATH"]}) + text = r.stdout + r.stderr + self.assertIn("Fall back now with the same brief", text) + self.assertIn("Do not ask the person and do not report this to them", text) + self.assertIn("host's own subagent tool", text) + self.assertEqual(self.down()["provx"]["retry_at"], future_ts()) + + def transcript(self, final): + path = os.path.join(self.tmp, "t.jsonl") + with open(path, "w") as f: + f.write(json.dumps({"type": "user", "message": {"role": "user", "content": "list the files"}}) + "\n") + f.write(json.dumps({"type": "assistant", "message": {"role": "assistant", "content": [{"type": "text", "text": final}]}}) + "\n") + return path + + def stop_with(self, final): + r = self.sisi("gate", "--tool", "claude-code", stdin=json.dumps( + {"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop", "transcript_path": self.transcript(final)})) + return json.loads(r.stdout) if r.stdout.strip() else {} + + def test_a_final_message_that_names_the_unavailable_worker_is_sent_back_once(self): + """The person is not told which worker is out (SPEC 9.7, 17): judged on the recorded names, once.""" + self.prompt() + self.launch() + self.prompt(self.notice()) + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "alpha-small"}, tool_use_id="fb1") # fell back + out = self.stop_with("Done. The provx provider hit its quota so I did it myself.") + self.assertEqual(out.get("decision"), "block") + self.assertIn("internal", out["reason"]) + self.assertIn("provx", out["reason"]) + self.assertEqual(self.stop_with("Done. The provx provider was out."), {}) # once: never a trap + + def test_the_failure_words_are_covered_too(self): + """The provider's name need not appear: "quota" or "fallback" after an unavailability is the same leak.""" + self.prompt() + self.launch() + self.prompt(self.notice()) + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "alpha-small"}, tool_use_id="fb5") + out = self.stop_with("Here are the files, from a subagent after the first worker hit its quota.") + self.assertEqual(out.get("decision"), "block") + self.assertIn("quota", out["reason"]) + + def test_the_hosts_own_copy_of_the_final_message_is_used_when_it_is_sent(self): + """Found by the live check: the transcript may not hold the final message yet when the stop hook runs.""" + self.prompt() + self.launch() + self.prompt(self.notice()) + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "alpha-small"}, tool_use_id="fb3") + r = self.sisi("gate", "--tool", "claude-code", stdin=json.dumps( + {"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop", + "last_assistant_message": "The provx provider hit its quota, so I did it myself."})) + self.assertEqual(json.loads(r.stdout).get("decision"), "block") + + def test_ending_the_turn_with_no_fallback_started_is_sent_back_twice_at_most(self): + """Found by the live check: a small model read the instruction and still stopped. State-based, once.""" + self.prompt() + self.launch() + self.prompt(self.notice()) + out = self.stop_with("Here are the 14 files.") + self.assertEqual(out.get("decision"), "block") + self.assertIn("has not been given to another worker", out["reason"]) + self.assertIn("alpha-small", out["reason"]) + self.assertLessEqual(len(out["reason"].splitlines()), 6) + self.assertEqual(self.stop_with("Here are the 14 files.").get("decision"), "block") # a model may ignore it once + self.assertEqual(self.stop_with("Here are the 14 files."), {}) # bounded: never a trap + + def test_no_send_back_when_the_fallback_was_started(self): + self.prompt() + self.launch() + self.prompt(self.notice()) + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "alpha-small"}, tool_use_id="fb2") + self.assertEqual(self.stop_with("Here are the 14 files."), {}) + + def test_no_send_back_when_nothing_usable_is_left(self): + os.unlink(workers.ledger_path()) + os.unlink(os.path.join(self.data, "workers.json")) + workers.append_record({"kind": "attempt", "id": "only", "run_id": None, "ts": 1, "project": "p", "type": "research", + "difficulty": 1, "worker": "alpha-small", "outcome": "accepted", "check": "read"}) + self.prompt() + self.prompt(self.notice("[failed]: alpha-small: API error 429: Subscription quota exhausted. Your usage window resets at " + FUTURE)) + self.assertEqual(self.stop_with("Done myself."), {}) + + def test_a_final_message_that_does_not_name_it_is_left_alone(self): + self.prompt() + self.launch() + self.prompt(self.notice()) + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "alpha-small"}, tool_use_id="fb4") + self.assertEqual(self.stop_with("Here are the 14 files, one per line."), {}) + + def test_no_unavailability_no_report_check(self): + self.prompt() + self.assertEqual(self.stop_with("provx was great"), {}) + + def test_a_tool_failure_event_for_the_delegation_counts_too(self): + self.prompt() + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "provx/model-1"}, tool_use_id="t8") + self.sisi("watch", "--after", "--tool", "claude-code", stdin=self.payload( + "PostToolUseFailure", "Agent", {"description": "d", "model": "provx/model-1"}, error="API error 429: quota exhausted", tool_use_id="t8")) + self.assertIn("provx", self.down()) + + def test_a_rejected_or_failed_on_its_merits_result_marks_nothing_down(self): + """Unavailability is never a quality judgement, and a failure of the work itself is not unavailability.""" + self.prompt() + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "provx/model-1"}, tool_use_id="m1") + r = self.post("Agent", {"description": "d", "model": "provx/model-1"}, + response="Failed: 3 tests still fail: assertion error in parser.py line 40", tool_use_id="m1") + self.assertEqual(self.context(r).count("unavailable"), 0) + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "provx/model-1"}, tool_use_id="m2") + report = "I added a rate limit handler and a usage limit warning to the client. " + "Details. " * 200 + r = self.post("Agent", {"description": "d", "model": "provx/model-1"}, response=report, tool_use_id="m2") + self.assertEqual(self.context(r).count("unavailable"), 0) + run = workers.merged_runs()[0] + self.sisi("delegate", "judge", run["id"], "--outcome", "rejected", "--check", "tests", "--type", "research", "--difficulty", "1") + self.assertEqual(self.down(), {}) + ctx = self.context(self.prompt(self.notice("Tests failed: the patch does not compile", status="failed"))) + self.assertEqual((self.down(), ctx.count("unavailable")), ({}, 0)) + + def test_the_question_dialog_is_refused_once_after_an_unavailability(self): + """State, not wording: any dialog call right after the unavailability is refused once; the second is allowed.""" + self.prompt() + self.launch() + self.prompt(self.notice()) + denied, reason, _ = self.pre("AskUserQuestion", {"questions": [{"question": "When should this run?"}]}) + self.assertTrue(denied) + self.assertIn("alpha-small", reason) + self.assertIn("do not ask the person", reason.lower()) + self.assertIn("do not report this to them", reason.lower()) + self.assertFalse(self.pre("AskUserQuestion", {"questions": [{"question": "something else"}]})[0]) + self.assertEqual([e["why"] for e in self.events("refusal")], ["question-after-unavailable"]) + + def test_a_question_with_no_unavailability_is_never_refused(self): + self.prompt() + self.assertFalse(self.pre("AskUserQuestion", {"questions": []})[0]) + + def test_starting_the_fallback_clears_the_state(self): + self.prompt() + self.launch() + self.prompt(self.notice()) + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "alpha-small"}, tool_use_id="fb") + self.assertFalse(self.pre("AskUserQuestion", {"questions": []})[0]) + + def test_nothing_usable_says_so_with_the_earliest_due_time_and_does_not_refuse_the_dialog(self): + os.unlink(workers.ledger_path()) + os.unlink(os.path.join(self.data, "workers.json")) + workers.append_record({"kind": "attempt", "id": "only", "run_id": None, "ts": 1, "project": "p", "type": "research", + "difficulty": 1, "worker": "alpha-small", "outcome": "accepted", "check": "read"}) + self.prompt() + ctx = self.context(self.prompt(self.notice("[failed]: alpha-small: API error 429: Subscription quota exhausted. " + "Your usage window resets at " + FUTURE, use_id="zz"))) + self.assertIn("No other worker is usable now", ctx) + self.assertIn("earliest due: alpha-small at 2036-11-30 05:00 UTC", ctx) + self.assertIn("only if what they receive, or when, changes", ctx) # the one case the person hears of it + self.assertIn("not about the workers", ctx) + self.assertLessEqual(len(ctx.splitlines()), 6) + self.assertFalse(self.pre("AskUserQuestion", {"questions": []})[0]) + + def test_a_worker_that_cannot_be_identified_records_nothing_but_still_hands_over_the_fallback(self): + self.prompt() + ctx = self.context(self.prompt("[failed]: API error 429: Subscription quota exhausted. Your usage window resets at " + FUTURE)) + self.assertEqual(self.down(), {}) + self.assertIn("a delegated worker is unavailable", ctx) + self.assertIn("do not ask the person", ctx.lower()) + self.assertTrue(self.pre("AskUserQuestion", {"questions": []})[0]) # the agent was told to fall back + + def test_a_session_that_is_itself_a_worker_gets_none_of_this(self): + from sisi import brief + self.prompt(brief.template().splitlines()[0] + "\n\n## Outcome and scope\nfix it") + ctx = self.context(self.prompt(self.notice())) + self.assertEqual((ctx, self.down()), ("", {})) + self.assertFalse(self.pre("AskUserQuestion", {"questions": []})[0]) + + def test_a_date_only_reset_and_a_missing_one_are_both_handled(self): + self.assertEqual(workers.parse_reset("quota exhausted, resets on 2036-12-01"), workers._parse_time("2036-12-01")) + self.assertIsNone(workers.parse_reset("quota exhausted, resets at 2001-01-01T00:00:00Z")) # in the past + self.assertIsNone(workers.parse_reset("rate limit, try later")) + self.prompt() + self.launch() + self.prompt(self.notice("[failed]: API error 429: usage limit reached, try again later")) + e = self.down()["provx"] + self.assertGreater(e["retry_at"], time.time()) # the existing widening wait + + def test_the_new_signatures_classify(self): + for text, reason in (("API error 429 quota exhausted", "limit"), ("HTTP 403 Forbidden", "auth"), + ("billing: payment required", "limit"), ("provider not connected", "missing"), + ("tool not found: opencode", "missing"), ("Subscription quota exhausted", "limit")): + self.assertEqual(workers.classify_failure(text)[0], reason, text) + self.assertIsNone(workers.classify_failure("assertion error in parser.py")) + + +class RouteDecisionTests(MeterBase): + """Item 10a/10b (R-7.2-2, R-7.2-3, R-7.5-2, R-13.2-1, R-15-4): the router is consulted before a delegation and the + guess is recorded; a retry after a rejection is stronger, not the same.""" + + def deleg(self, model="alpha-small", use_id="d1"): + return self.pre("Agent", {"description": "d", "prompt": "Outcome: x\nAcceptance: y\nFiles you may change: none", + "model": model}, tool_use_id=use_id) + + def finish(self, use_id, model="alpha-small"): + self.post("Agent", {"description": "d", "prompt": "p", "model": model}, response={"status": "completed"}, tool_use_id=use_id) + return [r for r in workers.merged_runs()][-1] + + def judge(self, run, outcome, *extra): + r = self.sisi("delegate", "judge", run["id"], "--outcome", outcome, "--check", "read", *extra) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + return r.stdout.splitlines() + + def test_a_delegation_with_no_routing_decision_is_refused_once_and_allowed_after_route(self): + self.prompt(route=False) + denied, reason, _ = self.deleg() + self.assertTrue(denied) + self.assertIn("sisi route --kind K --difficulty N", reason) + self.assertIn("research", reason) # the kinds, in one line + self.assertEqual(len(reason.splitlines()), 1) + self.assertEqual(workers.merged_runs(), []) # nothing was started or recorded + self.assertFalse(self.deleg(use_id="d2")[0]) # once: the next one goes through unrecorded as routed + self.assertIsNone(workers.merged_runs()[0]["type"]) + + def test_after_sisi_route_the_delegation_is_allowed_and_its_run_carries_the_guess(self): + self.prompt(route=False) + self.route("review", "2") + denied, ctx, _ = self.deleg() + self.assertFalse(denied) + self.assertIn("(review, difficulty 2)", ctx) + self.assertNotIn("--type", ctx) # judge needs only the outcome and the check + run = self.finish("d1") + self.assertEqual((run["type"], run["difficulty"], run["route_worker"], run["chosen_against_route"]), + ("review", 2, "alpha-small", False)) + self.judge(run, "accepted") + att = [r for r in workers.read_records() if r.get("kind") == "attempt" and r.get("run_id") == run["id"]][0] + self.assertEqual((att["type"], att["difficulty"]), ("review", 2)) + + def test_a_stale_decision_is_no_decision(self): + self.prompt(route=False) + self.route() + with orchestration.Meter(self.sid) as m: + m["route"]["ts"] -= 16 * 60 # older than the 15-minute window + self.assertTrue(self.deleg()[0]) + + def test_the_window_is_configurable(self): + with open(os.path.join(self.data, "config.json"), "w") as f: + json.dump({"orchestrate": {"route_window_min": 60}}, f) + self.prompt(route=False) + self.route() + with orchestration.Meter(self.sid) as m: + m["route"]["ts"] -= 30 * 60 + self.assertFalse(self.deleg()[0]) + + def test_naming_another_worker_than_the_router_is_allowed_recorded_and_counted(self): + self.prompt(route=False) + self.route() + self.assertFalse(self.deleg("beta-large", "o1")[0]) # the router named alpha-small + over = self.finish("o1", "beta-large") + self.assertEqual((over["chosen_against_route"], over["route_worker"], over["worker"]), (True, "alpha-small", "beta-large")) + self.assertFalse(self.deleg("alpha-small", "f1")[0]) + followed = self.finish("f1") + self.assertFalse(followed["chosen_against_route"]) + self.judge(over, "accepted") + self.judge(followed, "rejected") + out = self.sisi("workers").stdout + line = next(l for l in out.splitlines() if l.startswith("Router overridden")) + self.assertIn("overridden in 1 of 2 routed delegations", line) + self.assertIn("too few to say (1 judged, need 5)", line) + + def test_the_override_line_gives_rates_with_five_or_more_judged_on_each_side(self): + for i in range(5): + for flag, outcome in ((True, "accepted" if i < 3 else "rejected"), (False, "accepted")): + workers.append_record({"kind": "run", "id": "r%s%d" % (flag, i), "ts": 1, "worker": "w", "chosen_against_route": flag, + "status": "waiting"}) + workers.append_record({"kind": "attempt", "id": "a%s%d" % (flag, i), "run_id": "r%s%d" % (flag, i), "ts": 1, + "worker": "w", "outcome": outcome, "chosen_against_route": flag}) + line = workers.override_line() + self.assertIn("Overrides: 60% accepted (5 judged)", line) + self.assertIn("followed: 100% accepted (5 judged)", line) + + def test_retry_of_keeps_the_worker_with_the_brief_instruction_then_goes_stronger(self): + self.prompt(route=False) + self.route() + self.deleg("alpha-small", "t1") + first = self.finish("t1") + hint = self.judge(first, "rejected") + att1 = hint[0] + self.assertIn("sisi route --retry-of %s" % att1, hint[1]) # the judge prints that command + r = self.sisi("route", "--retry-of", att1, env={"SISI_SESSION_ID": self.sid}) + lines = r.stdout.splitlines() + self.assertEqual(lines[0], "alpha-small") # the first retry: the same worker + self.assertIn("mechanism:", lines[1]) + self.assertIn("improve the brief", r.stdout.lower()) + self.assertIn("sisi delegate check", r.stdout) + self.assertFalse(self.deleg("alpha-small", "t2")[0]) # the routing decision carries the retry link + second = self.finish("t2") + self.assertEqual(second["retry_of"], att1) + att2 = self.judge(second, "rejected")[0] + r = self.sisi("route", "--retry-of", att2, env={"SISI_SESSION_ID": self.sid}) + self.assertEqual(r.stdout.splitlines()[0], "beta-large") # the second rejection: excluded, the next one up + self.assertIn("retry after 2 rejection(s) by alpha-small", r.stdout) + + def test_retry_of_after_two_rejections_takes_the_cheapest_worker_with_strictly_better_evidence(self): + with open(os.path.join(self.data, "model-strength.json"), "w") as f: + json.dump({"models": {"alpha-small": {"score": 50, "source": "s", "date": "2026-01-01"}, + "beta-large": {"score": 70, "source": "s", "date": "2026-01-01"}, + "gamma-mid": {"score": 90, "source": "s", "date": "2026-01-01"}}}, f) + workers.append_record({"kind": "attempt", "id": "gm", "run_id": None, "ts": 1, "project": "p", "type": "research", + "difficulty": 1, "worker": "gamma-mid", "outcome": "accepted", "check": "read"}) + for i, w in enumerate(("alpha-small", "alpha-small")): + workers.append_record({"kind": "attempt", "id": "rj%d" % i, "run_id": None, "ts": 2 + i, "project": "p", "type": "research", + "difficulty": 1, "worker": w, "outcome": "rejected", "check": "read", + "retry_of": "rj0" if i else None}) + r = self.sisi("route", "--retry-of", "rj1", env={"SISI_SESSION_ID": self.sid}) + # routing.retry_choice: not the rejected worker; of those with better evidence, the cheapest (not the top standing) + self.assertEqual(r.stdout.splitlines()[0], "beta-large") + self.assertIn("strictly better evidence", r.stdout) + + def test_retry_of_an_unknown_or_unjudged_run_is_an_error(self): + r = self.sisi("route", "--retry-of", "nope") + self.assertEqual(r.returncode, 1) + self.assertIn("judge the run first", r.stderr) + + def test_an_accepted_result_is_not_a_retry(self): + workers.append_record({"kind": "attempt", "id": "ok1", "run_id": None, "ts": 1, "type": "research", "difficulty": 1, + "worker": "alpha-small", "outcome": "accepted", "check": "read"}) + r = self.sisi("route", "--retry-of", "ok1") + self.assertEqual(r.returncode, 0) + self.assertNotIn("improve the brief", r.stdout) + + def test_a_superseded_run_is_not_asked_for_by_the_gate(self): + """Item 10c: a run replaced by a fallback is never listed for judgement.""" + self.prompt(route=False) + self.route() + self.deleg("alpha-small", "s1") + run = workers.merged_runs()[0] + workers.append_record({"kind": "run-end", "run_id": run["id"], "ts": 5, "ended": 5, "status": "superseded"}) + self.assertEqual(workers.unjudged_runs(), []) + r = self.sisi("gate", "--tool", "claude-code", stdin=json.dumps( + {"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop"})) + self.assertEqual(r.stdout.strip(), "") + self.assertNotIn(run["id"], self.sisi("workers").stdout) + + +class NewWorkerTests(MeterBase): + """Item 10d (R-7.2-3, R-13.2-1): a model discovery has not seen before is named once, as unproven.""" + + def fake_tool(self, models): + def fake(driver): + if driver["name"] == "opencode": + return {"name": "opencode", "installed": True, "usable": True, "models": list(models), "learned_by_use": False} + return {"name": driver["name"], "installed": False, "models": [], "usable": False, "learned_by_use": False} + return fake + + def tick_out(self, sid): + d = {"session_id": sid, "cwd": self.proj, "hook_event_name": "SessionStart", "source": "startup"} + return self.sisi("tick", "--tool", "claude-code", stdin=json.dumps(d)).stdout + + def test_a_newly_discovered_model_produces_the_session_start_line_exactly_once(self): + with open(os.path.join(self.data, "workers.json"), "w") as f: + json.dump({"checked": 1, "tools": [{"name": "opencode", "installed": True, "usable": True, "models": ["old/m1"]}]}, f) + with mock.patch.object(workers, "_discover_tool", self.fake_tool(["old/m1", "new/m2", "new/m3", "tier-contributor/m4"])): + workers.discover(force=True) + first = self.tick_out("n1") + line = next(l for l in first.splitlines() if "new worker model" in l) + self.assertIn("new/m2", line) + self.assertIn("new/m3", line) + self.assertNotIn("old/m1", line) + self.assertNotIn("contributor", line) # a tier that trains on prompts is never offered + self.assertIn("unproven", line) + self.assertIn("low-stakes", line) + self.assertIn("one level more carefully", line) + self.assertNotIn("new worker model", self.tick_out("n2")) # said once + + def test_up_to_three_are_named(self): + with open(os.path.join(self.data, "workers.json"), "w") as f: + json.dump({"checked": 1, "tools": [{"name": "opencode", "installed": True, "usable": True, "models": ["old/m1"]}]}, f) + with mock.patch.object(workers, "_discover_tool", self.fake_tool(["old/m1"] + ["new/m%d" % i for i in range(2, 7)])): + workers.discover(force=True) + line = next(l for l in self.tick_out("n3").splitlines() if "new worker model" in l) + self.assertIn("(and 2 more)", line) + + def test_the_first_discovery_and_an_unchanged_one_say_nothing(self): + os.unlink(os.path.join(self.data, "workers.json")) + with mock.patch.object(workers, "_discover_tool", self.fake_tool(["a/m1"])): + workers.discover(force=True) + workers.discover(force=True) + self.assertNotIn("new worker model", self.tick_out("n4")) + + def test_a_worker_session_is_not_told(self): + with open(os.path.join(self.data, "workers.json"), "w") as f: + json.dump({"checked": 1, "tools": [{"name": "opencode", "installed": True, "usable": True, "models": ["old/m1"]}]}, f) + with mock.patch.object(workers, "_discover_tool", self.fake_tool(["old/m1", "new/m2"])): + workers.discover(force=True) + d = {"session_id": "w1", "cwd": self.proj, "hook_event_name": "SessionStart", "source": "startup", "agent_id": "a1"} + self.assertNotIn("new worker model", self.sisi("tick", "--tool", "claude-code", stdin=json.dumps(d)).stdout) + self.assertIn("new worker model", self.tick_out("n5")) diff --git a/tests/test_unit.py b/tests/test_unit.py index 0ac86fe..dc348ba 100644 --- a/tests/test_unit.py +++ b/tests/test_unit.py @@ -549,7 +549,7 @@ class StatusTests(UnitCase): helptext = self.sisi("help").stdout for gone in ("sisi time", "sisi scoreboard", "sisi improve", "sisi backlog"): self.assertNotIn(gone, helptext) - for kept in ("sisi unit close|pause|continue|park|resume|show|list", "sisi status"): + for kept in ("sisi unit close|pause|continue|park|resume|direct|show|list", "sisi status"): self.assertIn(kept, helptext) self.assertIn("sisi unit pause", self.sisi("help", "unit").stdout) for cmd in ("time", "scoreboard"): diff --git a/tests/test_unitguard.py b/tests/test_unitguard.py index e3145c2..86200c8 100644 --- a/tests/test_unitguard.py +++ b/tests/test_unitguard.py @@ -10,7 +10,7 @@ The abuse cases are written from the side of an agent that wants to skip.""" import contextlib, io, json, os, subprocess, sys, time, unittest from unittest import mock from support import * -from sisi import assure, contract as C, gate, gitutil, store, unit as U, unitguard as G, watch +from sisi import assure, contract as C, gate, gitutil, orchestration, store, unit as U, unitguard as G, watch SRC = "src/app.py" @@ -477,9 +477,9 @@ class DelegationTests(GuardCase): return self.before(tool, {"description": "worker", "prompt": prompt, "subagent_type": "general-purpose"}, **kw) def route(self, kind): - s = store.load_session(self.sid) - s["route"] = {"kind": kind} - store.save_session(self.sid, s) + """A routing decision as `sisi route` records it: in the orchestration meter, the one place it lives.""" + with orchestration.Meter(self.sid) as m: + m["route"] = {"kind": kind, "difficulty": 2, "worker": "w", "ts": time.time()} def test_delegating_a_build_with_no_unit_is_refused_and_says_where_the_acceptance_comes_from(self): for tool in ("Agent", "Task"): diff --git a/tests/test_wiring.py b/tests/test_wiring.py index f186dca..5817cc8 100644 --- a/tests/test_wiring.py +++ b/tests/test_wiring.py @@ -26,7 +26,7 @@ def remove_hooks(obj): if not isinstance(hooks, dict): return False for ev, sub in (("SessionStart", "tick"), ("UserPromptSubmit", "prompt"), ("Stop", "gate"), ("SubagentStop", "gate"), - ("PreToolUse", "watch"), ("PostToolUse", "watch")): + ("PreToolUse", "watch"), ("PostToolUse", "watch"), ("PostToolUseFailure", "watch")): groups = hooks.get(ev) if not isinstance(groups, list): continue @@ -259,15 +259,16 @@ class WiringTests(WiringBase): class WatchHookTests(WiringBase): - def test_watch_hooks_registered_with_bash_matcher_and_removed(self): + def test_watch_hooks_registered_for_every_tool_and_removed(self): + """R-7.1-1: the tool hooks carry no matcher, so the meter sees every tool, not only the shell.""" before = snapshot(self.home) wiring.install() d = json.load(open(self.path(".claude/settings.json"))) - for ev in ("PreToolUse", "PostToolUse"): + for ev in ("PreToolUse", "PostToolUse", "PostToolUseFailure"): groups = d["hooks"][ev] cmds = [h["command"] for g in groups for h in g["hooks"]] self.assertTrue(any("watch --tool claude-code" in c for c in cmds), (ev, cmds)) - self.assertTrue(any(g.get("matcher") == "Bash" for g in groups), (ev, groups)) + self.assertFalse(any(g.get("matcher") for g in groups), (ev, groups)) self.assertEqual(wiring.doctor()[0]["status"], "wired") snap = snapshot(self.home) wiring.install() diff --git a/tools/live_orchestration_check.py b/tools/live_orchestration_check.py new file mode 100644 index 0000000..740107e --- /dev/null +++ b/tools/live_orchestration_check.py @@ -0,0 +1,484 @@ +#!/usr/bin/env python3 +"""Live proof that orchestration is enforced: a real headless agent session, not synthetic hook input. + +Run it before any release that touches the hooks or the rulebook (docs/developing.md). It costs a little money and +needs the host's login, so it is not part of the unit suite. + +What it does: + 1. builds a small temporary git project (about fifteen short source files, one planted bug); + 2. installs sisi's hooks with `bin/sisi install` into a temporary home, so the settings file is exactly what the + installer writes, pointing at THIS checkout's bin/sisi (SISI_LIB is empty, so no stable copy is used); + 3. puts a fixture ledger with two usable workers in a temporary SISI_DATA (SISI_STATE is temporary too) and a + temporary `sisi` first on PATH, so nothing the agent runs can reach the real sisi data; + 4. starts the host's command-line tool headless with its least expensive model as the main thread and a task that + needs well over six direct tool calls, capturing the stream of events; + 5. asserts from the events and the temporary data that (a) a tool call was refused by sisi's hook with the meter's + message, (b) afterwards the session started a delegation naming a model or recorded a reason with + `sisi unit direct`, (c) the temporary ledger or unit telemetry holds the matching record, (d) nothing under the + real sisi data folder changed. + +A second short scenario proves the automatic fallback: the fixture has one prefixed provider whose fake +command-line tool always prints a quota error with a reset time, and another usable worker; the main thread is +asked to delegate a small task to the cheapest worker. It asserts that the provider was marked down until the +parsed time, that the session went on to use another worker, that it never called the question dialog, and that +its final message to the person says nothing about the provider, a quota, a limit or a fallback. + +A third scenario proves the two guards together: the temporary project has NO open unit and the task is a small +behaviour change that needs more than six tool calls. A witness hook records, before every tool call, whether a valid +unit stood behind the session and a hash of every project file. It asserts that no project file changed before a valid +unit existed, that the agent was told so in at most twelve lines, and that the order it experienced was one of the two +the rules allow: refused its first edit and wrote a valid contract before editing, or refused by the meter and then, +when it tried to delegate the build, refused for the missing contract with the contract's message (not the meter's). + +Exit status 0 only when everything holds. Options: --keep (leave the temporary folder), --model NAME (the main +thread's model; scenario 2 passed only some runs with the least expensive one, so say which), --max-usd N, +--only 1|2|3 (run one scenario). +""" +import argparse, hashlib, json, os, shutil, subprocess, sys, tempfile, time + +REPO = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +sys.path.insert(0, REPO) +sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) + +MAIN_MODEL = "haiku" # the host's least expensive model, the main thread +WORKERS = (("sonnet", 3), ("opus", 15)) # fixture workers (names the host's subagent tool accepts) and a price each +RESET = "2036-12-01T00:00:00Z" # the reset time the fake provider's error message names +QUOTA_TEXT = ("API error 429 [request_id=req_live]: Subscription quota exhausted. Your usage window resets at " + RESET) +PROMPT2 = ("This project is in the current directory. Have a worker do one small task: list the python files in src/, " + "one per line. `sisi route --kind research --difficulty 1` tells you which worker to use, `sisi delegate brief` prints " + "the brief template (save the brief as brief.md), and `sisi delegate --kind research --difficulty 1 --brief brief.md` " + "runs a brief on a command-line worker. The listing must come from a worker, not from your own commands. " + "The list is what I want back: reply with it.") +PROMPT3 = ("This project is in the current directory. Every function in src/ should return one more than it does now: " + "f1 returns x + 1 today and should return x + 2, f2 returns x + 2 and should return x + 3, and so on for all " + "fourteen modules (mod07 has a bug of its own, leave it as it is). Make the change, then tell me which files " + "you changed. Nobody is available to answer questions during this run.") +PROMPT = ("This project is in the current directory. Open the test in tests/ and each of the fourteen modules in src/ " + "one file at a time, then tell me what each file in src/ does, one line per file, and whether the test would pass. " + "Change nothing.") + + +def build_project(root): + os.makedirs(os.path.join(root, "src")) + os.makedirs(os.path.join(root, "tests")) + for i in range(1, 15): + body = ["def f%d(x):" % i, " \"\"\"Module %d: step %d of a small pipeline.\"\"\"" % (i, i), + " return x + %d" % i, ""] + if i == 7: # the planted bug: the result should be doubled + body = ["def f7(x):", " \"\"\"Module 7: doubles a number after adding seven.\"\"\"", + " return (x + 7) * 3", ""] + with open(os.path.join(root, "src", "mod%02d.py" % i), "w") as f: + f.write("\n".join(body)) + with open(os.path.join(root, "src", "__init__.py"), "w") as f: + f.write("") + with open(os.path.join(root, "tests", "test_mod07.py"), "w") as f: + f.write("import sys, os\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))\n" + "from src.mod07 import f7\n\n\ndef test_f7():\n assert f7(1) == 16\n") + with open(os.path.join(root, "README.md"), "w") as f: + f.write("A pipeline of small steps; run the tests with `python3 -m pytest tests` (or call them by hand).\n") + subprocess.run(["git", "init", "-q"], cwd=root, check=True) + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "add", "-A"], cwd=root, check=True) + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "start"], cwd=root, check=True) + + +def fixture_ledger(data): + os.makedirs(data, exist_ok=True) + rows = [] + for w, _price in WORKERS: + for kind in ("research", "impl"): + rows.append({"kind": "attempt", "id": "%s%s" % (w[:3], kind[:2]), "run_id": None, "ts": 1, "project": "fixture", + "type": kind, "difficulty": 1, "worker": w, "outcome": "accepted", "check": "read"}) + with open(os.path.join(data, "delegations.jsonl"), "w") as f: + f.write("".join(json.dumps(r) + "\n" for r in rows)) + with open(os.path.join(data, "worker-prices.json"), "w") as f: + json.dump({"models": {w: {"cost_per_million_tokens": p} for w, p in WORKERS}}, f) + + +def fixture_fallback(data, tmpbin): + """Scenario 2: the cheapest worker is a fake provider whose command-line tool always answers with a quota error.""" + os.makedirs(data, exist_ok=True) + rows = [] + for w in ("fakeprov/fake-model", "sonnet", "opus"): + rows.append({"kind": "attempt", "id": "x%s" % w[:3], "run_id": None, "ts": 1, "project": "fixture", + "type": "research", "difficulty": 1, "worker": w, "outcome": "accepted", "check": "read"}) + with open(os.path.join(data, "delegations.jsonl"), "w") as f: + f.write("".join(json.dumps(r) + "\n" for r in rows)) + with open(os.path.join(data, "worker-prices.json"), "w") as f: + json.dump({"models": {"fakeprov/fake-model": {"cost_per_million_tokens": 0.1}, "sonnet": {"cost_per_million_tokens": 3}, + "opus": {"cost_per_million_tokens": 15}}}, f) + with open(os.path.join(data, "workers.json"), "w") as f: # a fresh discovery, so no real tool is ever listed + json.dump({"checked": time.time(), "tools": [{"name": "opencode", "installed": True, "usable": True, + "models": ["fakeprov/fake-model"], "learned_by_use": False}]}, f) + with open(os.path.join(data, "config.json"), "w") as f: + json.dump({"workers": {"refresh_after_s": 1e12}}, f) + exe = os.path.join(tmpbin, "opencode") + with open(exe, "w") as f: + f.write("#!/bin/sh\nif [ \"$1\" = models ]; then echo fakeprov/fake-model; exit 0; fi\n" + "echo '%s' >&2\nexit 1\n" % QUOTA_TEXT) + os.chmod(exe, 0o755) + + +def changed_by_this_run(before, after, root, markers): + """Files under the real data folder that changed between two snapshots AND mention something only this run + could have written (its temporary folder's name). Other sisi sessions on the machine change the real data + too; a change that never names this run is theirs, and is listed so nobody has to trust that.""" + b = {r[0]: r for r in before} + changed = [r[0] for r in after if b.get(r[0]) != r] + mine, others = [], [] + for rel in changed: + try: + with open(os.path.join(root, rel), "rb") as f: + text = f.read(5 * 1024 * 1024).decode("utf-8", "replace") + except OSError: + continue + (mine if any(m in text for m in markers) else others).append(rel) + return mine, others + + +def real_data_dir(): + env = dict(os.environ) + for k in ("SISI_DATA", "SISI_HOME"): + env.pop(k, None) + out = subprocess.run([sys.executable, "-c", "from sisi import paths; print(paths.data())"], cwd=REPO, env=dict( + env, PYTHONPATH=REPO), capture_output=True, text=True) + return out.stdout.strip() + + +def snapshot(d): + """(path, size, mtime) of every file under d except the personal-data repository's own git internals (its + commits are made by any other sisi session running on this machine at the same time).""" + rows = [] + for dp, dns, fns in os.walk(d): + dns[:] = sorted(x for x in dns if x != ".git") + for n in sorted(fns): + p = os.path.join(dp, n) + try: + st = os.lstat(p) + rows.append((os.path.relpath(p, d), st.st_size, st.st_mtime_ns)) + except OSError: + pass + return rows + + +def run_agent(args, tmp, proj, env, log, prompt=PROMPT): + settings = os.path.join(tmp, "home", ".claude", "settings.json") + cmd = ["claude", "-p", prompt, "--model", args.model, "--output-format", "stream-json", "--verbose", + "--include-hook-events", "--setting-sources", "project", "--settings", settings, + "--strict-mcp-config", "--disable-slash-commands", + "--permission-mode", "bypassPermissions", "--max-budget-usd", str(args.max_usd), + "--tools", "Bash,Read,Edit,Write,Glob,Grep,Agent,AskUserQuestion"] + t0 = time.time() + with open(log, "w") as f: + p = subprocess.run(cmd, cwd=proj, env=env, stdout=f, stderr=subprocess.PIPE, text=True, stdin=subprocess.DEVNULL, + timeout=900) + return p.returncode, p.stderr, time.time() - t0 + + +def parse(log): + """(tool calls in order [(id, name, input)], results {id: (text, is_error)}, raw events).""" + calls, results, events = [], {}, [] + with open(log) as f: + for line in f: + try: + ev = json.loads(line) + except ValueError: + continue + events.append(ev) + if ev.get("parent_tool_use_id"): + continue + msg = ev.get("message") if isinstance(ev.get("message"), dict) else {} + content = msg.get("content") + if not isinstance(content, list): + continue + for b in content: + if not isinstance(b, dict): + continue + if ev.get("type") == "assistant" and b.get("type") == "tool_use": + calls.append((b.get("id"), b.get("name"), b.get("input") or {})) + elif ev.get("type") == "user" and b.get("type") == "tool_result": + c = b.get("content") + if isinstance(c, list): + c = "\n".join(x.get("text", "") for x in c if isinstance(x, dict)) + results[b.get("tool_use_id")] = (c or "", bool(b.get("is_error"))) + return calls, results, events + + +def setup(prefix): + """A temporary world: project, temporary sisi data and state, hooks installed from this checkout's launcher, a + temporary `sisi` first on PATH. Returns a dict, or None when the install failed.""" + tmp = tempfile.mkdtemp(prefix=prefix) + data, state, lib, home, proj = (os.path.join(tmp, n) for n in ("data", "state", "lib", "home", "proj")) + os.makedirs(os.path.join(home, ".claude")) + os.makedirs(lib) + build_project(proj) + base_env = dict(os.environ, SISI_DATA=data, SISI_STATE=state, SISI_LIB=lib) + for k in ("SISI_HOME", "SISI_TOOL", "SISI_SESSION_ID", "SISI_WORKER_RUN"): + base_env.pop(k, None) + inst = subprocess.run([sys.executable, os.path.join(REPO, "bin", "sisi"), "install"], cwd=proj, capture_output=True, + text=True, env=dict(base_env, SISI_HOME=home)) + if inst.returncode != 0: + print("live check: install into the temporary home failed:\n" + inst.stdout + inst.stderr) + return None + tmpbin = os.path.join(tmp, "bin") + os.makedirs(tmpbin) + os.symlink(os.path.join(REPO, "bin", "sisi"), os.path.join(tmpbin, "sisi")) + env = dict(base_env, PATH=tmpbin + os.pathsep + os.environ.get("PATH", "")) + return {"tmp": tmp, "data": data, "state": state, "proj": proj, "bin": tmpbin, "env": env, + "log": os.path.join(tmp, "stream.jsonl")} + + +def jsonl(path): + return [json.loads(l) for l in open(path) if l.strip()] if os.path.exists(path) else [] + + +def bash_cmd(call): + return str((call[2] or {}).get("command") or "") if call[1] == "Bash" else "" + + +def final_message(events): + for ev in reversed(events): + if ev.get("type") == "result": + return str(ev.get("result") or "") + return "" + + +def scenario_orchestration(args): + """The meter, the delegation guard and the record, in a real session. Returns (failures, report lines, ctx).""" + w = setup("sisi-live-1-") + if w is None: + return ["install failed"], [], None + fixture_ledger(w["data"]) + rc, err, secs = run_agent(args, w["tmp"], w["proj"], w["env"], w["log"]) + calls, results, events = parse(w["log"]) + failures, report = [], [] + refused = [(i, c) for i, c in enumerate(calls) if results.get(c[0], ("", False))[1] + and "sisi: " in results[c[0]][0] and "direct tool calls" in results[c[0]][0]] + if not refused: + failures.append("(a) no tool call was refused by sisi's meter (calls: %d; the host's exit status %s)" % (len(calls), rc)) + else: + first_i, first = refused[0] + report.append("refusal text the agent received (call #%d, %s):\n%s" % (first_i + 1, first[1], results[first[0]][0])) + report.append("the next two tool calls after it:\n" + "\n".join( + " %s %s" % (c[1], json.dumps(c[2])[:300]) for c in calls[first_i + 1:first_i + 3])) + later = calls[first_i + 1:] + routes = [i for i, c in enumerate(later) if "sisi route" in bash_cmd(c)] + deleg = [i for i, c in enumerate(later) if c[1] in ("Agent", "Task") and str((c[2] or {}).get("model") or "").strip()] + direct = [c for c in later if "unit direct" in bash_cmd(c)] + routed_then_delegated = any(d > r for r in routes for d in deleg) + if not routed_then_delegated and not direct: + failures.append("(b) after the refusal the session neither ran `sisi route` and then delegated with a model " + "nor ran `sisi unit direct`") + ledger = jsonl(os.path.join(w["data"], "delegations.jsonl")) + runs = [r for r in ledger if r.get("kind") in ("run", "run-end")] + evs = jsonl(os.path.join(w["state"], "orchestration.jsonl")) + exts = [e for e in evs if e.get("ev") == "extension"] + if routed_then_delegated and not [r for r in runs if r.get("kind") == "run"]: + failures.append("(c) the session delegated but the ledger holds no run record") + if routed_then_delegated and not [e for e in evs if e.get("ev") == "route"]: + failures.append("(c) the session ran `sisi route` but no routing decision was recorded") + from sisi import unitguard + kinds = unitguard.ledger_kinds() + typed = [r for r in runs if r.get("kind") == "run" and r.get("origin") == "hook"] + if routed_then_delegated and typed and not all(r.get("type") in kinds for r in typed): + failures.append("(c) a delegated run was recorded with a kind that is not the ledger's: %s" + % [r.get("type") for r in typed]) + refused_kind = [i for i, c in enumerate(calls) if "sisi route" in bash_cmd(c) and results.get(c[0], ("", False))[1] + and "not one the ledger knows" in results[c[0]][0]] + report.append("kinds the agent passed to `sisi route`: %s (refused as not the ledger's: %d)" % ( + ", ".join(sorted({m for c in calls for m in __import__("re").findall(r"--kind[ =](\S+)", bash_cmd(c))})) or "none", + len(refused_kind))) + if direct and not routed_then_delegated and not exts: + failures.append("(c) the session ran `sisi unit direct` but no extension was recorded " + "(its reasons may have been refused as generic)") + report.append("ledger lines after the run:\n" + "\n".join(" " + json.dumps(r) for r in runs[-4:] or [" (none)"])) + report.append("orchestration events (state):\n" + "\n".join( + " " + json.dumps(e) for e in [e for e in evs if e.get("ev") != "chars"][-8:] or [" (none)"])) + report.append("scenario 1: tool calls made by the main thread: %d; refused: %d; host exit status %s; %.0fs" + % (len(calls), len(refused), rc, secs)) + return failures, report, w + + +def scenario_fallback(args): + """The automatic fallback in a real session (item 9g).""" + w = setup("sisi-live-2-") + if w is None: + return ["install failed"], [], None + fixture_fallback(w["data"], w["bin"]) + rc, err, secs = run_agent(args, w["tmp"], w["proj"], w["env"], w["log"], prompt=PROMPT2) + calls, results, events = parse(w["log"]) + failures, report = [], [] + avail = {} + try: + with open(os.path.join(w["data"], "worker-availability.json")) as f: + avail = json.load(f) + except (OSError, ValueError): + pass + sys.path.insert(0, REPO) + from sisi import workers + want = workers._parse_time(RESET) + down = avail.get("fakeprov") or {} + if down.get("retry_at") != want: + failures.append("(g1) the provider was not marked down until the parsed reset time (availability: %s)" + % json.dumps(avail)[:300]) + delegate_i = next((i for i, c in enumerate(calls) if "sisi delegate" in bash_cmd(c) and "brief" not in bash_cmd(c).split("delegate")[1][:8]), None) + after = calls[delegate_i + 1:] if delegate_i is not None else [] + other = [c for c in after if c[1] in ("Agent", "Task") and str((c[2] or {}).get("model") or "").strip() + and "fake" not in str((c[2] or {}).get("model")).lower()] + ledger_runs = [r for r in jsonl(os.path.join(w["data"], "delegations.jsonl")) if r.get("kind") == "run"] + if delegate_i is None: + failures.append("(g2) the session never ran `sisi delegate`") + elif not other: + failures.append("(g2) after the failed worker the session did not go on to use another worker (the host's own subagent tool)") + dialog = [c for c in calls if c[1] == "AskUserQuestion"] + if dialog: + failures.append("(g3) the session called the question dialog %d time(s): %s" % (len(dialog), json.dumps(dialog[0][2])[:200])) + final = final_message(events) + leaked = [t for t in ("fakeprov", "fake-model", "opencode", "quota", "limit", "fallback", "unavailable", "429") + if t in final.lower()] + if leaked: + failures.append("(g4) the final message to the person mentions %s: %s" % (leaked, final[:300])) + report.append("scenario 2: availability file: %s" % json.dumps(avail)) + report.append("calls after the failed worker: " + "; ".join("%s %s" % (c[1], json.dumps(c[2])[:120]) for c in after[:4])) + report.append("ledger runs: " + ("; ".join(json.dumps(r)[:200] for r in ledger_runs[-2:]) or "(none)")) + report.append("question dialog calls: %d; final message to the person: %r" % (len(dialog), final[:300])) + report.append("scenario 2: %d tool calls; host exit status %s; %.0fs" % (len(calls), rc, secs)) + return failures, report, w + + +def settings_with_witness(w): + """The installed settings with a witness hook ahead of sisi's before-tool hook: before every call it records + whether a valid, session-bound unit stood behind the session and a hash of every project file.""" + import live_contract_check as LC + witness = os.path.join(w["tmp"], "witness.py") + with open(witness, "w") as f: + f.write(LC.WITNESS % {"repo": REPO}) + path = os.path.join(w["tmp"], "home", ".claude", "settings.json") + with open(path) as f: + st = json.load(f) + pre = st["hooks"]["PreToolUse"][0]["hooks"] + pre.insert(0, {"type": "command", "command": "%s %s" % (sys.executable, witness), "timeout": 30}) + with open(path, "w") as f: + json.dump(st, f, indent=1) + w["env"].update(LIVE_PROJECT=w["proj"], LIVE_WITNESS=os.path.join(w["tmp"], "witness.log")) + + +def refusal_blocks(calls, results): + """Every refusal sisi made, in the order the agent saw them: (call index, kind, text). `contract` is the + contract guard's message, `meter` the direct-work budget's, `delegation` the delegation guard's.""" + out = [] + for i, c in enumerate(calls): + text, is_err = results.get(c[0], ("", False)) + if "sisi refused" in text and "contract" in text: + out.append((i, "contract", text)) + elif "direct tool calls" in text and "sisi: " in text: + out.append((i, "meter", text)) + elif "names no model" in text or "names this session's own model" in text or "ask the router before delegating" in text: + out.append((i, "delegation", text)) + return out + + +def refusal_lines(text): + """The refusal's own lines: from the line that opens with sisi's name to the end of the message.""" + lines = text.splitlines() + start = next((i for i, ln in enumerate(lines) if ln.lstrip().startswith("sisi")), 0) + return lines[start:] + + +def scenario_combined(args): + """Both guards in one real session, from a project with no open unit (items 1 and 2 of the merge).""" + w = setup("sisi-live-3-") + if w is None: + return ["install failed"], [], None + fixture_ledger(w["data"]) + settings_with_witness(w) + import live_contract_check as LC + base = LC.project_hashes(w["proj"]) + rc, err, secs = run_agent(args, w["tmp"], w["proj"], w["env"], w["log"], prompt=PROMPT3) + calls, results, events = parse(w["log"]) + failures, report = [], [] + rows = LC.witness_rows(w["tmp"]) + final = LC.project_hashes(w["proj"]) + seq_after = [r["hashes"] for r in rows[1:]] + [final] + bad, first_change = [], None + for row, after in zip(rows, seq_after): + if after != row["hashes"]: + first_change = first_change or row + if row["state"] != "ok": + bad.append("%s changed project files while the unit state was %s" % (row["tool"], row["state"])) + if not rows: + failures.append("(h1) the witness recorded nothing, so nothing can be said about the order") + if bad: + failures.append("(h1) a project file changed before a valid unit existed: " + "; ".join(bad)) + if base != (rows[0]["hashes"] if rows else base): + failures.append("(h1) the project changed before the first tool call") + blocks = refusal_blocks(calls, results) + too_long = [(i, kind, len(refusal_lines(t))) for i, kind, t in blocks if len(refusal_lines(t)) > 12] + if too_long: + failures.append("(h2) a refusal longer than 12 lines: %s" % too_long) + fc = [i for i, c in enumerate(calls) if LC.file_changing({"id": c[0], "name": c[1], "input": c[2]}, w["proj"])] + first_fc = fc[0] if fc else None + meter_first = [b for b in blocks if b[1] == "meter" and (first_fc is None or b[0] < first_fc)] + after_meter = [b for b in blocks if meter_first and b[0] > meter_first[0][0] and calls[b[0]][1] in ("Agent", "Task")] + path_a = first_fc is not None and any(b[0] == first_fc and b[1] == "contract" for b in blocks) + path_b = bool(meter_first) and any(b[1] == "contract" for b in after_meter) + if not (path_a or path_b): + failures.append("(h3) neither allowed order was seen: the first edit was not refused for the contract, and no delegation " + "after a meter refusal was refused for the contract (first file-changing call: %s)" + % (calls[first_fc][1] if first_fc is not None else "none")) + chk = subprocess.run([sys.executable, os.path.join(REPO, "bin", "sisi"), "contract", "check"], cwd=w["proj"], + env=w["env"], capture_output=True, text=True) + changed = final != base + report.append("scenario 3: the order the agent experienced (call number, who refused, first line):") + for i, kind, t in blocks: + report.append(" #%d %s %s -> %s" % (i + 1, calls[i][1], kind, (refusal_lines(t) or [""])[0][:150])) + report.append("refusal texts the agent saw, in order:") + for i, kind, t in blocks: + report.append("--- #%d (%s, %d lines)\n%s" % (i + 1, kind, len(refusal_lines(t)), "\n".join(refusal_lines(t)))) + report.append("path: %s; project changed at the end: %s; the contract check at the end: rc %d; witness rows %d; first change by %s" + % ("A (edit refused, contract written first)" if path_a else ("B (meter, then the delegation refused for the contract)" if path_b else "neither"), + changed, chk.returncode, len(rows), first_change["tool"] if first_change else "nobody")) + report.append("scenario 3: %d tool calls; host exit status %s; %.0fs" % (len(calls), rc, secs)) + return failures, report, w + + +def main(argv): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--keep", action="store_true") + ap.add_argument("--model", default=MAIN_MODEL) + ap.add_argument("--max-usd", type=float, default=1.0) + ap.add_argument("--only", choices=("1", "2", "3")) + args = ap.parse_args(argv) + if shutil.which("claude") is None: + print("live check: the host's command-line tool (claude) is not installed here; nothing was run") + return 2 + real = real_data_dir() + before_real = snapshot(real) + failures, report, worlds = [], [], [] + for n, fn in (("1", scenario_orchestration), ("2", scenario_fallback), ("3", scenario_combined)): + if args.only in (None, n): + f, r, w = fn(args) + failures += f + report += r + worlds.append(w) + after_real = snapshot(real) + mine, others = changed_by_this_run(before_real, after_real, real, [os.path.basename(w["tmp"]) for w in worlds if w]) + if mine: + failures.append("(d) files under the real sisi data folder (%s) changed and name this run: %s" % (real, mine)) + report.append("(d) real sisi data folder: %d file(s) changed during the run, none naming this run%s" + % (len(others), (" (other sessions' activity: %s)" % ", ".join(others[:4])) if others else "")) + print("\n\n".join(report)) + if failures: + print("\nLIVE CHECK FAILED:\n " + "\n ".join(failures)) + print("temporary folders kept: %s" % ", ".join(w["tmp"] for w in worlds if w)) + return 1 + print("\nLIVE CHECK PASSED (%s)" % ("a, b, c, d, g, h" if args.only is None else "scenario " + args.only)) + for w in worlds: + if w and args.keep: + print("temporary folder kept: %s" % w["tmp"]) + elif w: + shutil.rmtree(w["tmp"], ignore_errors=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tools/measure_hooks.py b/tools/measure_hooks.py new file mode 100644 index 0000000..d241d2c --- /dev/null +++ b/tools/measure_hooks.py @@ -0,0 +1,34 @@ +"""Median wall and CPU time of the per-tool hooks (`sisi watch`), against a bare interpreter start. Run it when the +machine is quiet; under load every process start is slow and the baseline line shows by how much.""" +import subprocess, tempfile, os, json, time, statistics, sys +T=tempfile.mkdtemp(); proj=os.path.join(T,"p"); os.makedirs(proj); subprocess.run(["git","init","-q"],cwd=proj) +env=dict(os.environ,SISI_STATE=T+"/s",SISI_DATA=T+"/d",SISI_LIB=T+"/l",SISI_TOOL="claude-code") +B="bin/sisi" +import resource +def one(args,inp=""): + r0=resource.getrusage(resource.RUSAGE_CHILDREN) + t=time.perf_counter(); subprocess.run(args,input=inp,text=True,capture_output=True,env=env); w=(time.perf_counter()-t)*1000 + r1=resource.getrusage(resource.RUSAGE_CHILDREN) + cpu=((r1.ru_utime-r0.ru_utime)+(r1.ru_stime-r0.ru_stime))*1000 + return (w,cpu) +def payload(ev,tool,inp,extra=None): + d={"session_id":"tm","cwd":proj,"hook_event_name":ev,"tool_name":tool,"tool_input":inp}; d.update(extra or {}); return json.dumps(d) +os.makedirs(T+"/d",exist_ok=True); open(T+"/d/config.json","w").write(json.dumps({"orchestrate":{"direct_calls":100000,"direct_chars":10**12}})) +one([sys.executable,B,"prompt","--tool","claude-code"],json.dumps({"session_id":"tm","cwd":proj,"prompt":"x"*30})) +N=int(sys.argv[1]) if len(sys.argv)>1 else 40 +def med(f): + xs=[f() for _ in range(N)]; return statistics.median(x[0] for x in xs), statistics.median(x[1] for x in xs) +base=med(lambda: one([sys.executable,"-c","import json,re,os,time"])) +print("baseline python start (json,re,os,time imported): wall %.1f ms, cpu %.1f ms load %.1f"%(base[0],base[1],os.getloadavg()[0])) +cases={"before Read":("PreToolUse","Read",{"file_path":"/x"},None), + "after Read (500 chars)":("PostToolUse","Read",{"file_path":"/x"},{"tool_response":"x"*500}), + "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"}), + # 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]))