Merge t3/enforce-orchestration-meter into spec-reconciliation: one before-tool path (worker exempt, contract guard, delegation guard, meter), routing decision read from the meter, retry-of on routing.retry_choice, ledger kind names. done: merge / next: tests on the merged tree, record parts

This commit is contained in:
swaits committed 2026-11-23 15:10:44 -07:00
commit c5df3068ce
36 files changed
+3567 -118

No files matched your search

+7 -3
View File
@@ -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.
+7
View File
@@ -28,6 +28,13 @@
"tests",
"debug"
],
"other_kinds": [
"read",
"search",
"research",
"review",
"docs"
],
"build_words": [
"change",
"fix",
+104
View File
@@ -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": []
}
}
}
+10
View File
@@ -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
+7
View File
@@ -21,5 +21,12 @@
},
"unit": {
"stale_hours": 12
},
"orchestrate": {
"enabled": true,
"direct_calls": 6,
"direct_chars": 30000,
"extension": 10,
"route_window_min": 15
}
}
+52
View File
@@ -336,6 +336,58 @@ 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/<id>.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 "<reason>"`. 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 moves to a stronger one (judged record, else benchmark standing, else host-native) after a
second.
- **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.
+17
View File
@@ -19,6 +19,23 @@ 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 two small temporary
projects, with the hooks from this checkout and a temporary `SISI_DATA` and `SISI_STATE` (the real sisi data is
never read or written; the script asserts that it did not change). Scenario 1 asserts that the meter refused a
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):
+23 -3
View File
@@ -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
+17
View File
@@ -92,6 +92,23 @@ 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, a stronger one after a second rejection.
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),
+2 -2
View File
@@ -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):
+13
View File
@@ -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
+2
View File
@@ -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)
+123
View File
@@ -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 = "<task-notification>"
_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>(.*?)</%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)
+25
View File
@@ -509,12 +509,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)
+2 -2
View File
@@ -6,7 +6,7 @@ command is printed by `sisi help COMMAND` and `sisi COMMAND --help`.
LONG = {
'contract': ' sisi contract init [--goal TEXT] start a work unit: create .sisi/contract.json here (refuses while one is open)\n sisi contract check validate the contract (vacuous checks are refused)\n sisi contract waive [--check ID] "<reason>"\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 "<reason>"]\n archive the unit to .sisi/units/<id>.json with its scorecard; --abandon records why it stopped\n sisi unit pause "<what it waits for>"\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 "<why>" | 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 "<reason>"]\n archive the unit to .sisi/units/<id>.json with its scorecard; --abandon records why it stopped\n sisi unit pause "<what it waits for>"\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 "<why>" | 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 "<reason>"\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"),
+11 -8
View File
@@ -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,9 @@ 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 or P._is_notice(query)) else
P.build_context(query, session=norm.get("session_id"))) 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)
+28
View File
@@ -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)
+16
View File
@@ -534,11 +534,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("/")
+968
View File
@@ -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 "<reason>"`);
* 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 <state>/sessions/<id>.meter.json under a file lock;
every counted event is also appended to <state>/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 = "<task-notification>"
def _tag(text, name):
m = re.search(r"<%s>(.*?)</%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 \"<reason>\"`%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 "<reason>"`: record why doing this directly is cheaper; grants an extension."""
reason = " ".join(args).strip()
if not reason:
print('usage: sisi unit direct "<why doing this directly is cheaper than delegating it>"')
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
+20 -1
View File
@@ -112,6 +112,24 @@ 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 _is_notice(query):
from . import orchestration
return query.lstrip().startswith(orchestration.NOTIFICATION)
def extract_prompt(payload):
"""The human's request text from a hook payload, across the tools' documented field names."""
if not isinstance(payload, dict):
@@ -150,7 +168,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, "" if _is_notice(query) else build_context(query, session=session)) if x)
if not text:
return 0
if plain:
+40 -3
View File
@@ -142,12 +142,49 @@ 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():
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`)"
if _has("workers", "cmd_delegate") and _has("brief", "missing_required") else None],
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; `sisi unit direct \"<reason>\"` extends the turn with a specific reason (a generic one is refused)"
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"
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"
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)"
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"
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 and difficulty guess, and a worker other than the router's pick is recorded as an override"
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 and moves to a stronger "
"one after a second"
if _has("workers", "retry_context", "stronger_choice") 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"])
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"
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"
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():
+10
View File
@@ -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"):
+14
View File
@@ -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}}
+9
View File
@@ -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).
+12 -1
View File
@@ -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 \"<reason>\"] | pause \"<what it waits for>\" | continue | "
"park \"<why>\" | resume ID | show [ID] | list")
"park \"<why>\" | resume ID | direct \"<reason>\" | show [ID] | list")
return 1
+41 -30
View File
@@ -656,16 +656,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 +747,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 +770,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 +801,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,7 +815,7 @@ 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", [])
if kind != "delegate" and floor == "trivial":
have = sess.setdefault("ug_paths", [])
@@ -810,14 +823,14 @@ def _before(payload):
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"
else:
@@ -829,8 +842,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 +852,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):
+128 -30
View File
@@ -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]
@@ -130,7 +135,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()})
@@ -151,16 +156,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):
@@ -178,7 +183,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
@@ -188,7 +193,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")
@@ -213,28 +218,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
+22 -8
View File
@@ -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)
+317 -20
View File
@@ -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
+1 -1
View File
@@ -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()
+114 -1
View File
@@ -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)
+1005
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -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"):
+5 -4
View File
@@ -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()
+363
View File
@@ -0,0 +1,363 @@
#!/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.
Exit status 0 only when everything holds. Options: --keep (leave the temporary folder), --model NAME, --max-usd N,
--only 1|2 (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)
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.")
PROMPT = ("This project is in the current directory. Find and fix the bug (a test in tests/ fails), then tell me "
"what each file in src/ does, one line per file.")
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", "implementation"):
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")
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 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"))
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)):
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 (a, b, c, d, g)")
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:]))
+31
View File
@@ -0,0 +1,31 @@
"""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"})}
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]))