One worker decision used by the contract guard, meter, delegation guard, fallback logic, gate; lazy transcript recognition; opening patterns as data. done: items 1-3 / next: tool list and name words

This commit is contained in:
swaits committed 2026-11-23 16:29:15 -07:00
1 parent 858401d58e
commit 1899f1ae4a
8 files changed
+33 -66

No files matched your search

+5 -9
View File
@@ -251,15 +251,13 @@ def _decide(payload):
cfg = store.config()
if not cfg["gate"].get("enabled", True):
return "allow", None
from . import workers
if workers.is_subagent_payload(payload):
return decide_subagent(payload)
from . import workerid
cwd = _cwd(payload)
sid = _session_key(payload, cwd)
if workerid.session_is_worker(payload, sid, cwd):
return decide_subagent(payload) # a worker's last message is its report to the agent that started it
os.environ["SISI_SESSION_ID"] = sid
sess = store.load_session(sid)
if sess.get("subagent"):
return "allow", None # a session another agent started: its last message is its report to that agent
if not (sess.get("started") or sess.get("first_seen")):
sess["first_seen"] = store.now()
top = gitutil.root(cwd)
@@ -525,12 +523,10 @@ 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
from . import orchestration, workerid
cwd = _cwd(payload)
sid = _session_key(payload, cwd)
if store.load_session(sid).get("subagent"):
if workerid.session_is_worker(payload, sid, cwd):
return None
if action == "allow":
text = (orchestration.fallback_sendback(payload, sid) or orchestration.judgement_sendback(payload, sid)
+14 -30
View File
@@ -19,7 +19,7 @@ fails open (the caller wraps it): an error here must never hold up the user's to
"""
import fcntl, json, os, re, shlex, time
from . import paths, store
from . import paths, store, workerid
EVENTS = "orchestration.jsonl"
_HOSTS = {}
@@ -221,11 +221,6 @@ def _peek(sid):
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."""
@@ -288,15 +283,6 @@ def _task_done(m, key, ent, text, superseded=False):
_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
@@ -313,7 +299,7 @@ def new_turn(sid, cwd=None, prompt=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):
if failed and not workerid.is_worker_session({}, sess, m):
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"))
@@ -323,8 +309,8 @@ def new_turn(sid, cwd=None, prompt=None):
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
if m["prompts"] == 1 and "worker" not in m:
m["worker"] = workerid.opens_as_brief(text)
return None
@@ -445,10 +431,6 @@ 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."""
@@ -512,7 +494,7 @@ def _before(payload, host=None):
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):
if not hd:
return {}
sid = sid or "cwd-" + cwd
inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {})
@@ -522,10 +504,10 @@ def _before(payload, host=None):
return _dialog_guard(payload, host, sid, cwd)
if kind == "exempt" and not shell:
return {}
if workerid.session_is_worker(payload, sid, cwd):
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:
@@ -572,10 +554,12 @@ def _dialog_guard(payload, host, sid, cwd):
from . import fallback, workers
if refuse_style(host) not in ("json-deny", "exit-2"):
return {}
if workerid.session_is_worker(payload, sid, cwd):
return {}
sess = store.load_session(sid)
with Meter(sid) as m:
info = m.get("unavail")
if not info or _is_worker(payload, sess, m):
if not info:
return {}
own = _own_model(payload, sess, m)
project = _project(m, cwd)
@@ -661,7 +645,7 @@ def after(payload, host=None):
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):
if not hd:
return {}
sid = sid or "cwd-" + cwd
inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {})
@@ -669,11 +653,11 @@ def after(payload, host=None):
shell = watch.is_shell(tool, cmd)
if kind == "exempt" and not shell:
return {}
if workerid.session_is_worker(payload, sid, cwd):
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)
@@ -876,7 +860,7 @@ def fallback_sendback(payload, sid):
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):
if not info or int(m.get("fallback_asked") or 0) >= FALLBACK_SENDBACKS or workerid.is_worker_session({}, sess, m):
return None
own = _own_model({}, sess, m)
project = m.get("project") or os.getcwd()
+2 -2
View File
@@ -103,8 +103,8 @@ def main(args=()):
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):
from . import workers as _W3, workerid as _WI
if not _WI.is_worker_session(payload, sess3, {}):
line = _W3.new_worker_line()
if line:
sys.stdout.write(line + "\n")
+5 -5
View File
@@ -805,22 +805,22 @@ def before(payload):
def _before(payload):
from . import attribution, watch, workers
from . import attribution, watch, workerid
tool, cmd, _ev, cwd, sid = watch.extract(payload)
kind = classify(tool, payload, cmd)
if kind is None:
return None
if not store.config()["gate"].get("enabled", True) or workers.is_subagent_payload(payload):
if not store.config()["gate"].get("enabled", True):
return None
sid = sid or "cwd-" + cwd
if workerid.session_is_worker(payload, sid, cwd):
return None
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 None
sess = store.load_session(sid)
if sess.get("subagent"):
return None
top = git_top(cwd)
if top is None:
return None # nothing to measure outside a repository
@@ -933,7 +933,7 @@ def _after(payload):
if c is not None:
bind(sid, proj, c, "wrote")
sess = store.load_session(sid)
if top and classify(tool, payload, cmd) == "shell" and not sess.get("subagent"):
if top and classify(tool, payload, cmd) == "shell":
dirty = _absorb(sess, top) or dirty # a change the before-hook could not see: the next counted call answers for it
if dirty:
store.save_session(sid, sess)
+2 -16
View File
@@ -305,7 +305,8 @@ def run(payload, args=(), host=None):
_tool, _cmd, ev, _cwd, sid = extract(payload)
out = {}
if "--before" in args or ev in BEFORE_EVENTS:
if not worker_session(payload, sid, _cwd):
from . import workerid
if not workerid.session_is_worker(payload, sid, _cwd):
text = contract_guard(payload)
if text:
return {"deny": text}
@@ -336,21 +337,6 @@ def run(payload, args=(), host=None):
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"):
+2 -1
View File
@@ -1488,7 +1488,8 @@ def session_lines(model, payload=None):
a missing number never argues against orchestrating. At most one extra line asks for worker
facts to be researched when they are missing or stale (the caller shows these lines once per
session). Uses only cached discovery and the record."""
if not model or is_subagent_payload(payload or {}):
from . import workerid
if not model or workerid.is_worker_session(payload or {}, {}, None):
return []
records = read_records()
candidates, _tools = _cached_candidates(records)
+2 -2
View File
@@ -11,7 +11,7 @@ from support import *
import test_meter as TM
import test_unitguard as TG
from sisi import contract as C, gate, lifecycle, orchestration, prompt, routing, rulecmd, store, unit as U, unitguard as G
from sisi import watch, workers
from sisi import brief, watch, workers
SRC = TG.SRC
CONTRACT_LINES = 12
@@ -119,7 +119,7 @@ class OneRefusalAtATime(Both):
self.assertIsNone(self.edit(agent_id="w1"))
self.assertIsNone(self.agent(BUILD_BRIEF, agent_id="w1"))
# a session whose first prompt opens with the brief template's line is a worker too
orchestration.new_turn("wk", self.proj, orchestration.brief_line() + "\nOutcome: x")
orchestration.new_turn("wk", self.proj, brief.template().splitlines()[0] + "\nOutcome: x")
d = {"session_id": "wk", "cwd": self.proj, "hook_event_name": "PreToolUse", "tool_name": "Edit",
"tool_input": {"file_path": os.path.join(self.proj, SRC), "old_string": "a", "new_string": "b"}}
r = self.sisi("watch", "--before", "--tool", "claude-code", stdin=json.dumps(d))
+1 -1
View File
@@ -245,7 +245,7 @@ class WhoIsMeteredTests(MeterBase):
def test_a_main_prompt_that_only_mentions_worker_later_is_still_metered(self):
from sisi import brief
line = brief.template().splitlines()[0]
self.prompt("fix the parser, and remember this: " + line + " you are a worker of mine")
self.prompt("fix the parser and explain each module in the project. " * 8 + "remember this: " + line + " you are a worker of mine")
self.assertEqual(self.read_n(8), [False] * 6 + [True] * 2)
# nor does a brief line in the second prompt change a session that began as a main thread
self.prompt(line + " again please do this")