diff --git a/canon/floors.json b/canon/floors.json deleted file mode 100644 index 46e76cc..0000000 --- a/canon/floors.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "concurrency": 2, - "parsing": 2, - "money": 2, - "state-machine": 2, - "migration": 2 -} diff --git a/canon/risk.json b/canon/risk.json index 126695e..a67ba9d 100644 --- a/canon/risk.json +++ b/canon/risk.json @@ -1,13 +1,13 @@ { "profiles": ["trivial", "isolated", "logic", "integration", "data", "critical", "release"], "requirements": { - "trivial": {"contract": false, "checks": "the diff; a targeted check when one exists", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "only on an anomaly (two send-backs, or a human correction)"}, - "isolated": {"contract": true, "checks": "at least one that is not vacuous", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes"}, - "logic": {"contract": true, "checks": "as isolated, each with covers", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes"}, - "integration": {"contract": true, "checks": "as logic, plus invariants", "requirement_model": true, "risk_note": true, "independent_evidence": false, "retro": "yes"}, - "data": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"}, - "critical": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"}, - "release": {"contract": true, "checks": "every check (--all)", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"} + "trivial": {"contract": false, "checks": "the diff; a targeted check when one exists", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "only on an anomaly (two send-backs, or a human correction)", "min_checks": 0, "covers": false, "invariants": false, "approach": false, "all_checks": false, "retro_when": "anomaly"}, + "isolated": {"contract": true, "checks": "at least one that is not vacuous", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes", "min_checks": 1, "covers": false, "invariants": false, "approach": false, "all_checks": false, "retro_when": "close"}, + "logic": {"contract": true, "checks": "as isolated, each with covers", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes", "min_checks": 1, "covers": true, "invariants": false, "approach": false, "all_checks": false, "retro_when": "close"}, + "integration": {"contract": true, "checks": "as logic, plus invariants", "requirement_model": true, "risk_note": true, "independent_evidence": false, "retro": "yes", "min_checks": 1, "covers": true, "invariants": true, "approach": true, "all_checks": false, "retro_when": "close"}, + "data": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes", "min_checks": 1, "covers": true, "invariants": true, "approach": true, "all_checks": false, "retro_when": "close"}, + "critical": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes", "min_checks": 1, "covers": true, "invariants": true, "approach": true, "all_checks": false, "retro_when": "close"}, + "release": {"contract": true, "checks": "every check (--all)", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes", "min_checks": 1, "covers": true, "invariants": true, "approach": true, "all_checks": true, "retro_when": "close"} }, "patterns": [ {"stage": "code", "glob": "**/*.{py,pyi,pyw,js,mjs,cjs,jsx,ts,tsx,mts,cts,vue,svelte,astro,java,kt,kts,scala,groovy,clj,cljs,go,rs,c,h,cc,cpp,cxx,hpp,hh,hxx,m,mm,cs,fs,vb,swift,dart,rb,php,pl,pm,lua,r,jl,ex,exs,erl,hs,ml,mli,nim,zig,sh,bash,zsh,fish,ps1,bat,cmd,sol,sv,vhd,tcl,awk,asm,sql}", "profile": "isolated", "reason": "source code: never trivial, whatever its name or directory"}, diff --git a/config.default.json b/config.default.json index 8609e99..784dd43 100644 --- a/config.default.json +++ b/config.default.json @@ -2,9 +2,7 @@ "gate": { "enabled": true, "budget_s": 120, - "max_blocks": 3, - "growth_lines": 40, - "growth_files": 3 + "max_blocks": 3 }, "verify": { "default_timeout_s": 60, diff --git a/sisi/assure.py b/sisi/assure.py new file mode 100644 index 0000000..f91828e --- /dev/null +++ b/sisi/assure.py @@ -0,0 +1,175 @@ +"""What a risk profile requires, and what is missing from a unit (target section 3). + +The gate enforces the `requirements` table in canon/risk.json and nothing else. This module reads +that table, looks at the contract and the evidence, and returns the missing items in plain words, +each with the command or field that supplies it. It never decides anything about the tree itself. + +The profile that applies is the floor (what the changed paths say, by sisi/risk.py) unless the +contract declares a higher one. A contract may declare a lower one only by giving `risk.why`: the +unit then runs at the declared profile and is recorded as lowered, with floor, declared profile and +reason kept side by side (`sisi status` shows it). +""" +import os, time + +from . import contract as C, harvest, risk, store + +ORDER = {name: i for i, name in enumerate(risk.PROFILES)} + + +def effective_profile(floor, c): + """(profile, info). `info` = {floor, declared, lowered, why, refused}: `refused` is set when a + contract declared a lower profile without a reason, so the floor was kept.""" + rk = (c.get("risk") if isinstance(c, dict) else None) or {} + declared = rk.get("profile") if rk.get("profile") in ORDER else None + info = {"floor": floor, "declared": declared, "lowered": False, "why": rk.get("why"), "refused": False} + if declared is None or ORDER[declared] >= ORDER[floor]: + return (declared if declared and ORDER[declared] > ORDER[floor] else floor), info + if C.is_placeholder(rk.get("why")): + info["refused"] = True + return floor, info + info["lowered"] = True + return declared, info + + +def is_lowered(floor, declared, why): + """True when a unit declared a profile below its floor and gave a reason (what `sisi status` flags).""" + return bool(floor in ORDER and declared in ORDER and ORDER[declared] < ORDER[floor] + and not C.is_placeholder(why)) + + +def requirements(profile): + return risk.requirements_for(profile) + + +def stronger_technique(c): + """True when some check or invariant uses a technique stronger than example tests: a proof or + model check (rung 1), or properties, fuzzing or a reference comparison (rung 2).""" + items = list((c or {}).get("checks") or []) + list((c or {}).get("invariants") or []) + return any(isinstance(x, dict) and x.get("rung") in (1, 2) for x in items) + + +def _real(items, key): + """Entries of a list whose `key` says something (not empty, not a placeholder).""" + return [x for x in items or [] if isinstance(x, dict) and not C.is_placeholder(x.get(key))] + + +def _passing(r): + return r.get("status") == "passed" or (r.get("status") == "skipped" + and str(r.get("reason") or "").startswith("reused: passed")) + + +def review_evidence(project, c, now=None): + """The accepted review delegations of this project inside the unit's window whose result was + checked by something stronger than `none`. The ledger names a project by its folder name.""" + t0 = harvest.epoch(c["started"]) if isinstance(c.get("started"), str) else None + if t0 is None: + return [] + try: + from . import workers + dg = workers.delegations_for_project(os.path.basename(project.rstrip(os.sep)), t0, + time.time() if now is None else now) + except Exception as e: + store.log_error("assure-delegations", e) + return [] + return [r for r in dg["delegations"] if r.get("type") == "review" and r.get("outcome") == "accepted" + and r.get("check") not in (None, "", "none")] + + +def independent_evidence(project, c, results, now=None): + """What stands behind a unit as independent evidence: a judged review in the ledger, or a + passing check that is marked independent AND says by whom or what it was produced.""" + out = [] + for r in review_evidence(project, c, now): + out.append("review by %s" % (r.get("worker") or "a reviewer")) + named = {x.get("id"): x for x in list(c.get("checks") or []) + list(c.get("invariants") or []) + if isinstance(x, dict) and x.get("independent") is True and not C.is_placeholder(x.get("by"))} + for r in results or []: + if r.get("id") in named and _passing(r): + out.append("check %s by %s" % (r["id"], named[r["id"]]["by"])) + return out + + +def missing(profile, c, project, results=None, errors=None, deep_state=None, now=None): + """[(what is missing, how to supply it)] for this profile. `c` is None when no contract is open. + `errors` are the contract's validation errors. Nothing is asked that the table does not require.""" + req = requirements(profile) + out = [] + if not req.get("contract"): + return out + if c is None: + out.append(("a contract for this %s change" % profile, + "`sisi contract init`, then write at least one check that can fail")) + c = {} + absent = True + else: + absent = False + if errors: + shown = "; ".join(errors[:3]) + ("; and %d more" % (len(errors) - 3) if len(errors) > 3 else "") + out.append(("a valid contract: %s" % shown, "fix it, then `sisi contract check`")) + checks = [x for x in c.get("checks") or [] if isinstance(x, dict)] + if not absent and not errors and int(req.get("min_checks", 0)) > len(checks): + out.append(("at least one check that can fail", 'add it under "checks"')) + if req.get("covers"): + bare = [x.get("id") or "?" for x in checks if C.is_placeholder(x.get("covers"))] + if bare or absent: + out.append(("every check says what it covers" + (" (missing on %s)" % ", ".join(bare) if bare else ""), + '"covers": the failure that check would catch')) + if req.get("invariants") and not _real(c.get("invariants"), "claim"): + out.append(("invariants: what must not get worse", + '"invariants": a command that can fail, e.g. the existing tests')) + if req.get("requirement_model") and not _real(c.get("requirements"), "text"): + out.append(("a requirement list", + '"requirements": entries with "kind", "text" and "decision" (now, architect, defer, ignore)')) + if req.get("risk_note"): + rk = c.get("risk") if isinstance(c.get("risk"), dict) else {} + lacking = [k for k in ("blast_radius", "rollback") if C.is_placeholder(rk.get(k))] + if lacking: + out.append(("a risk note: %s" % " and ".join(lacking), + '"risk": {"blast_radius": what this can break, "rollback": how to undo it}')) + if req.get("approach"): + ap = c.get("approach") if isinstance(c.get("approach"), dict) else {} + if C.is_placeholder(ap.get("chosen")) or C.is_placeholder(ap.get("why")) \ + or not [a for a in ap.get("alternatives") or [] if not C.is_placeholder(a)]: + out.append(("the approach: what you chose, why, and an alternative you rejected", + '"approach": {"chosen", "why", "alternatives": [...]}')) + if req.get("independent_evidence") and not independent_evidence(project, c, results, now): + out.append(("independent evidence that someone or something else checked this", + "a reviewer's judged result (`sisi delegate judge --type review --outcome accepted " + "--check review`), or a passing check with \"independent\": true and \"by\": \"\"")) + if req.get("all_checks") and deep_state is not None and deep_state not in ("fresh-pass", "none"): + out.append(("every check, deep ones included, passing on this tree (release)", + "`sisi verify --deep --background`, then `sisi verify --state`")) + return out + + +# ---------------------------------------------------------------- messages + +MAX_LINES = 25 + + +def fit(lines, limit=MAX_LINES): + """No message to the agent is longer than `limit` lines: over it, the tail is replaced by one line + saying how many were cut. Every line is also kept short.""" + flat = [] + for ln in lines: + for sub in str(ln).split("\n"): + flat.append(sub if len(sub) <= 300 else sub[:297] + "...") + if len(flat) <= limit: + return "\n".join(flat) + return "\n".join(flat[:limit - 1] + ["... (%d more lines; run `sisi verify` for the full output)" + % (len(flat) - limit + 1)]) + + +def failure_lines(results, per_check=4, checks=4): + """A short report of the blocking results: id, status, and the last lines of what they printed.""" + from . import verify as V + out = [] + bad = V.blocking(results) + for r in bad[:checks]: + head = "- %s [%s%s]" % (r["id"], r["status"], (": " + r["reason"]) if r.get("reason") else "") + out.append(head) + tail = [ln for ln in str(r.get("tail") or "").splitlines() if ln.strip()][-per_check:] + out += [" " + ln[:200] for ln in tail] + if len(bad) > checks: + out.append("- and %d more failing" % (len(bad) - checks)) + return out diff --git a/sisi/cli.py b/sisi/cli.py index 399cbcb..d2dd4af 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -168,10 +168,6 @@ def cmd_contract(args): errs = C.validate(c) for e in errs: print(" - " + e) - if not errs: - for f in C.floor_failures(c): - errs.append(f["message"]) - print(" - " + f["message"]) if not errs: for w in C.warnings(c): print("warning: " + w) diff --git a/sisi/contract.py b/sisi/contract.py index eb2f91a..d12b86b 100644 --- a/sisi/contract.py +++ b/sisi/contract.py @@ -1,4 +1,4 @@ -"""Contract file: location, skeleton, validation, floors.""" +"""Contract file: location, skeleton, validation.""" import json, os, re from . import paths, gitutil @@ -108,14 +108,6 @@ def deferred_checks(c): return out -def floors(): - try: - with open(paths.canon("floors.json"), encoding="utf-8") as f: - return {k: int(v) for k, v in json.load(f).items()} - except (OSError, ValueError): - return {} - - def _num(x): return isinstance(x, (int, float)) and not isinstance(x, bool) @@ -124,6 +116,24 @@ def _str(x): return isinstance(x, str) and x.strip() != "" +_PLACEHOLDER_WORDS = {"todo", "tbd", "tba", "fixme", "xxx", "wip", "none", "nothing", "no", "n/a", "na", "nil", + "null", "unknown", "placeholder", "later", "see above", "same", "as above", "not applicable", + "no risk", "no rollback", "none needed", "not needed", "nothing needed", "-", "--", "...", + "?", "yes", "ok", "fine", "tests", "all"} + + +def is_placeholder(x): + """True for text that fills a field without saying anything: empty, `TODO`, `n/a`, `none`, + `tbd`, a bare punctuation mark, or anything that begins with TODO/TBD/FIXME. The gate asks for + a requirement list, a risk note, an approach and a reason; these words do not provide one.""" + if not isinstance(x, str): + return True + t = " ".join(x.lower().split()).strip(" .,:;!-_*") + if len(re.findall(r"[a-z0-9]", t)) < 3 and t not in ("ui",): + return True + return t in _PLACEHOLDER_WORDS or bool(re.match(r"^(todo|tbd|fixme|placeholder|xxx)\b", t)) + + TIERS = ("fast", "deep") @@ -274,6 +284,8 @@ def _check_new_fields(ch, w, errs): for k in ("mandatory", "independent"): if k in ch and not isinstance(ch[k], bool): errs.append("%s: %s must be true or false" % (w, k)) + if "by" in ch and not _str(ch["by"]): + errs.append(w + ": by must name who or what produced the independent evidence") def _validate_new_top(c, ids, errs): @@ -473,16 +485,3 @@ def validate(c): errs.append("questions[%d] needs q and default" % i) _validate_new_top(c, ids, errs) return errs - - -def floor_failures(c, floor_map=None): - """Kinds with a floor where every check of that kind is weaker than the floor.""" - fm = floors() if floor_map is None else floor_map - out = [] - for kind, fl in sorted(fm.items()): - of_kind = [ch for ch in c.get("checks", []) if ch.get("kind") == kind] - if of_kind and not any(ch["rung"] <= fl for ch in of_kind): - out.append({"kind": kind, "floor": fl, - "message": "floor: %s claims need a check at rung %d or stronger; best is rung %d" - % (kind, fl, min(ch["rung"] for ch in of_kind))}) - return out diff --git a/sisi/gate.py b/sisi/gate.py index d684b10..e2f0f97 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -1,8 +1,32 @@ -"""End-of-turn gate. Claude Code Stop hook: JSON on stdin, block = JSON {"decision":"block","reason":...} on stdout, exit 0. -Anything that goes wrong inside sisi allows (fail open) and is logged to the state dir.""" -import hashlib, json, os, re, shlex, sys, time +"""End-of-turn gate (Stop hook): may this agent stop now? JSON on stdin; a send-back is +{"decision":"block","reason":...} on stdout, exit 0. Anything that goes wrong inside sisi allows +(fail open) and is logged to the state dir. -from . import contract as C, deep as D, gitutil, paths, store, trust, verify as V +The flow is target.md section 7, and each stop answers these in order: + + 1. Did THIS session change anything since its last settled stop? If not, the turn ends silently + (a paused unit with no new change, a closed unit, another session's edits: all silent). + 2. What does the change need? The floor comes from the paths changed (sisi/risk.py); the contract + may raise it, and lowers it only with a reason (sisi/assure.py). + 3. Enforce what that profile's row of canon/risk.json requires, and nothing else; run the + selected fast checks (sisi/verify.py). One send-back lists everything missing at once. + 4. All green and the unit still open: close it if the retro is recorded, otherwise offer the two + ways on (the retro, or `sisi unit pause`), once. A trivial change is asked nothing. + +Send-backs are bounded (`gate.max_blocks`); when they run out the unit is released as `unverified` +and says why. A subagent is never sent back and never asked for a retro: its last message is its +report. Who made which edit is attributed in sisi/attribution.py, so a session is never sent back +for another session's work in the same tree. +""" +import hashlib, json, os, sys, time + +from . import assure, attribution, contract as C, gitutil, risk, store, trust, unit as U, verify as V +from .questions import QUESTION_DIALOG_TOOLS, ends_with_question # noqa: F401 (rulecmd and the tests name them here) + +# watch.py asks the gate's shell classifier whether a command may write +_shell_may_write = attribution.shell_may_write + +SENTINELS = ("*shell*", "*shell-unmeasured*", "*subagent*") def _read_payload(): @@ -20,579 +44,236 @@ def _session_key(payload, cwd): return sid if isinstance(sid, str) and sid else "cwd-" + hashlib.sha1(cwd.encode()).hexdigest()[:12] +def _cwd(payload): + c = payload.get("cwd") + return c if isinstance(c, str) and os.path.isdir(c) else os.getcwd() + + def _new_waiver(project, sess): - """Latest waiver for this project made during this session and not yet applied.""" - since, seen, best = sess.get("started") or "", sess.get("waiver_ns", 0), None + """Latest `sisi contract waive` for this project made during this session and not yet applied.""" + since, seen, best = sess.get("started") or sess.get("first_seen") or "", sess.get("waiver_ns", 0), None for w in store.read("waivers"): if w.get("project") == project and w.get("ts", "") >= since and w.get("ns", 0) > seen: best = w return best -class _Ctx: - def __init__(self, sess, sid, cfg, fp): - self.sess, self.sid, self.cfg, self.fp = sess, sid, cfg, fp +# ---------------------------------------------------------------- who changed what + +def _absorb_subagents(sess, sid): + """Edits a subagent reported at its own stop count as this session's edits (hosts that keep the + subagent's transcript elsewhere are covered this way).""" + seen = int(sess.get("sub_seen_ns", 0) or 0) + top = max(seen, 0) + for r in store.read("subagents"): + if r.get("session") != sid or int(r.get("ns", 0)) <= seen: + continue + top = max(top, int(r["ns"])) + if not r.get("edited"): + continue + sess["attr_gen"] = int(sess.get("attr_gen", 0) or 0) + 1 + since = sess.setdefault("attr_since_pass", []) + for f in r.get("files") or []: + if f not in since: + since.append(f) + if not r.get("files") and "*subagent*" not in since: + since.append("*subagent*") + sess["sub_seen_ns"] = top + + +def _note_own_paths(sess, attr, top): + """Record this scan's edited paths (relative to the repository) as edited since the last settled stop.""" + since = sess.setdefault("attr_since_pass", []) + for f in attr.get("files") or []: + rel = f + if os.path.isabs(f) and top: + try: + rel = os.path.relpath(f, top) + except ValueError: + rel = f + if rel not in since: + since.append(rel) + if attr.get("shell_edits") and not sess.get("attr_measured") and "*shell*" not in since: + since.append("*shell*") # a text-classified shell edit: its paths are unknown + + +def _own_changed(sess, sid, cwd, top, attr): + """Paths changed since this session's last settled stop that this session made (or may have made). + Never another session's work: that is what lets two sessions share a tree.""" + changed = None + try: + from . import watch + changed = watch.changed_since_pass(sid, cwd) + except Exception as e: + store.log_error("gate-watch-diff", e) + if changed is None: # no settled snapshot yet: the tree against the session's start + base = set((sess.get("baseline") or {}).get("files") or []) + since = set(sess.get("attr_since_pass") or []) + try: + now = gitutil.measure(cwd, sess.get("head"))["files"] + except Exception: + now = [] + changed = [f for f in now if f not in base or f in since] + changed = [f for f in changed if not f.startswith(".sisi" + os.sep) and not f.startswith(".sisi/")] + since = set(sess.get("attr_since_pass") or []) + if attr is None or attr["unknown"] or any(s in since for s in SENTINELS): + return changed + return [f for f in changed if f in since] + + +def _claims_unit(sess, contract_path): + """This session wrote the open contract itself (`sisi contract init`, or an edit of the file).""" + if not contract_path: + return False + rel = C.REL.replace(os.sep, "/") + mine = [f.replace(os.sep, "/") for f in list(sess.get("attr_files") or []) + list(sess.get("attr_since_pass") or [])] + return any(f == rel or f.endswith("/" + rel) for f in mine) + + +def _diff_text(project, base): + return U._git_diff_text(project, base) + + +# ---------------------------------------------------------------- the stop + +class _Stop: + """One stop: the session record, and the few ways a stop can end.""" + + def __init__(self, sess, sid, cfg, fp, attr): + self.sess, self.sid, self.cfg, self.fp, self.attr = sess, sid, cfg, fp, attr + self.maxb = int(cfg["gate"].get("max_blocks", 3)) def save(self): store.save_session(self.sid, self.sess) - def allow(self, msg=None): - if msg is None: # a clean stop is one of the places the cycle-due counter is checked (no scheduler) - try: - from . import cycle - note = cycle.due_notice(session=self.sid) - if note: - msg = note + " (This turn may end; the cycle is background work, not a send-back.)" - except Exception as e: - store.log_error("gate-cycle-notice", e) - self.sess.update(blocks=0, last_fp=self.fp, last_decision="allow") + def settle(self, cwd): + """This stop leaves nothing pending: the next change is measured from here.""" + s = self.sess + s.update(dirty=False, blocks=0, settled_fp=self.fp, last_fp=self.fp, last_decision="allow", sb_unit=0, + attr_since_pass=[]) + try: + from . import watch + watch.save_pass_snapshot(self.sid, cwd) + except Exception as e: + store.log_error("gate-watch-pass", e) self.save() + + def allow(self, cwd, msg=None, settle=True): + if settle: + self.settle(cwd) + else: + self.sess.update(blocks=0, last_decision="allow") + self.save() return "allow", msg - def block(self, template, contract_id=None, project=None, kind="fast"): - """One path for every kind of block: strikes, 3-strike release as UNVERIFIED.""" - s, maxb = self.sess, int(self.cfg["gate"].get("max_blocks", 3)) - blocks = int(s.get("blocks", 0)) - if blocks >= maxb: - if kind == "retro": - self.allow() - return "allow", ("sisi: no retrospective was recorded after %d reminders, so the gate let this turn end. " - "Run `sisi retro` before you finish if you still can." % maxb) - store.append("results", {"ts": store.now(), "contract": contract_id, "project": project, "check": "gate", - "item": "gate", "kind": None, "rung": None, "status": "unverified", - "duration_s": 0.0, "tool": store.tool(), "session": self.sid}) - _, _ = self.allow() - return "allow", ("sisi: result is UNVERIFIED. The gate has sent this work back %d times and it is still " - "not verified, so it let the turn end. Report the work as unverified." % maxb) - s["req_blocks"] = int(s.get("req_blocks", 0)) + 1 # send-backs during this request, for the delivery row - s.update(blocks=blocks + 1, last_fp=self.fp, last_decision="block", last_msg=template, last_kind=kind, - last_contract=contract_id, last_project=project) + def block(self, text, contract_id, project, counts=True): + s = self.sess + if counts: + s["req_blocks"] = int(s.get("req_blocks", 0)) + 1 # send-backs during this request, for the delivery row + s["blocks"] = int(s.get("blocks", 0)) + 1 + s["sb_unit"] = int(s.get("sb_unit", 0)) + 1 + s.update(last_fp=self.fp, last_decision="block") self.save() - return "block", template.replace("{n}", "%d of %d" % (blocks + 1, maxb)) + return "block", text.replace("{n}", "%d of %d" % (s.get("blocks", 1), self.maxb)) + + def exhausted(self): + return int(self.sess.get("blocks", 0)) >= self.maxb + + def refresh(self, cwd, path): + """The contract file is part of the tree's fingerprint: take it again after the gate edited it.""" + self.fp = gitutil.fingerprint(cwd, [path]) if gitutil.root(cwd) and path else self.fp -# ---------------------------------------------------------------- attribution -# Attribution reads this session's own transcript (Claude-Code-shaped JSONL: assistant records whose -# message.content holds tool_use blocks). Only bytes after the per-session offset stored in the session -# record are read, so a long transcript costs only its new tail; subagent transcripts found under -# /subagents/** are read the same way and count as this session's edits. -# Edit/Write/MultiEdit/NotebookEdit (and any tool whose name says it writes) count, with the file paths -# in their input. Shell (Bash) commands count when they plausibly write: a redirect, tee/dd-of, an -# in-place editor (sed -i, perl -i, awk -i inplace), git apply/checkout/restore/reset/clean/mv/rm, -# patch, cp/mv/rm/touch/mkdir, or any program that is not on the provably read-only list (ls, cat, -# grep, git status/diff/log/..., test runners and interpreters therefore count: they can write). -# Known blind spots: a read-only-looking command that writes through indirection sisi cannot see -# (a script reached by a read-only interpreter flag combination that slips the lists, a daemon, or a -# tool whose transcript shape is not Claude-Code JSONL), and writes made between the last complete -# transcript line and a crash. A missing/unreadable transcript, a corrupt line, or a shell command -# that cannot be tokenised is treated as an edit by this session (fail strict, never fail open here); -# so is an unread tail over 64 MB, which is skipped (offset moved to its end) rather than scanned -# inside the gate's time budget. - -EDIT_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"} -_READONLY_CMDS = {"ls", "cat", "head", "tail", "grep", "egrep", "fgrep", "rg", "ag", "wc", "file", - "stat", "du", "df", "which", "type", "pwd", "date", "env", "printenv", "sort", - "uniq", "cut", "tr", "jq", "yq", "diff", "cmp", "md5sum", "sha1sum", "sha256sum", - "basename", "dirname", "realpath", "readlink", "ps", "top", "free", "uname", - "hostname", "id", "whoami", "less", "more", "man", "help", "history"} -_READONLY_GIT = {"status", "diff", "log", "show", "rev-parse", "ls-files", "ls-tree", "describe", - "blame", "grep", "cat-file", "branch", "tag", "remote", "config", "add", "commit"} -_GH_READ = {("run", "list"), ("run", "view"), ("run", "watch"), ("pr", "list"), ("pr", "view"), - ("pr", "status"), ("pr", "diff"), ("pr", "checks"), ("issue", "list"), ("issue", "view"), - ("issue", "status"), ("repo", "view"), ("repo", "list"), ("release", "list"), - ("release", "view"), ("workflow", "list"), ("workflow", "view"), ("auth", "status")} -_WRITE_WORDS = ("edit", "write", "create", "delete", "move", "rename", "patch", "apply", "insert") -_SHELL_WRITE_RE = re.compile( - r">>?[^=]|\btee\b|\bdd\b[^;&|]*\bof=|\bsed\b[^;&|]*\s-[a-z]*i|\bperl\b[^;&|]*\s-[a-z]*i" - r"|\bawk\b[^;&|]*inplace|\bgit\s+(apply|checkout|restore|reset|clean|mv|rm)\b" - r"|\bpatch\b|\b(cp|mv|rm|touch|mkdir|rmdir|install|ln)\b", re.I) +def _release(stop, cwd, c, path, project, why): + """The send-backs ran out: the turn ends, the unit is released as unverified and says why.""" + why = [w for w in why if w][:4] + store.append("results", {"ts": store.now(), "contract": c["id"] if c else None, "project": project, + "check": "gate", "item": "gate", "kind": None, "rung": None, "status": "unverified", + "reason": "; ".join(why)[:500], "duration_s": 0.0, "tool": store.tool(), + "session": stop.sid}) + if c is not None and path: + try: + c["unverified"] = {"ts": store.now(), "send_backs": stop.maxb, "why": why} + C.save(path, c) + stop.refresh(cwd, path) + except OSError as e: + store.log_error("gate-release", e) + stop.allow(cwd) + return "allow", ("sisi: result is UNVERIFIED. The gate has sent this work back %d times and it is still not " + "verified (%s), so it let the turn end. Report the work as unverified and say what is " + "missing." % (stop.maxb, "; ".join(why) or "see the last message")) -def _shell_may_write(command): - """True: plausibly writes files. False: provably read-only. None: cannot be tokenised.""" - if not isinstance(command, str) or not command.strip(): - return False - if _SHELL_WRITE_RE.search(command): - return True +def _offer_text(c, profile, anomaly): + why = ("every check for unit %s passes" % c["id"]) if not anomaly else \ + ("unit %s passes, and it shows something worth a look (%s)" % (c["id"], anomaly)) + return assure.fit([ + "sisi: %s (%s change). Two ways on, then finish:" % (why, profile), + "- record what you learned: `sisi retro` prints this unit's record; then", + ' `sisi retro --finding "" --cause "" ' + '--impact value|correctness|time|cost|attention --disposition record --limits ""`', + " records it and closes the unit. (`sisi retro --help` shows `promote` and `drop`.)", + '- or, if this work now waits on something (a review, a decision, a deploy):', + ' `sisi unit pause ""`. The turn ends and nothing more is asked until the tree changes.', + ]) + + +def _technique_note(c, profile, sess): + """Once per unit, never blocking: a logic-or-higher change with no check stronger than examples.""" + if c is None or assure.ORDER[profile] < assure.ORDER["logic"] or assure.stronger_technique(c): + return None + if sess.get("technique_noted") == c.get("id"): + return None + sess["technique_noted"] = c.get("id") + return ("Note (not a send-back): no check in this contract uses a technique stronger than example tests " + "(a proof, properties, fuzzing or a comparison with a reference: rung 2 or better). " + "`sisi verifiers for \"\"` ranks the options.") + + +def _anomaly(c, project, sess): + """Why a trivial unit still earns a retro: two send-backs, or a human correction inferred from the transcript.""" + if int(sess.get("sb_unit", 0)) >= 2: + return "the gate sent the agent back %d times" % int(sess["sb_unit"]) try: - lex = shlex.shlex(command, posix=True, punctuation_chars=True) - lex.whitespace_split = True - tokens = list(lex) - except ValueError: - return None - segments, cur = [], [] - for tok in tokens: - if tok in (";", "&", "|", "&&", "||"): - segments.append(cur) - cur = [] - else: - cur.append(tok) - segments.append(cur) - for seg in segments: - i = 0 - while i < len(seg) and (re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", seg[i]) or seg[i] in ("sudo", "command", "exec", "time", "nice")): - i += 1 - if i >= len(seg): - continue - prog = os.path.basename(seg[i]) - rest = seg[i + 1:] - if prog in ("cd", "export", "unset", "set", "alias", "umask", "wait", "jobs", "fg", "bg", - "exit", "return", "break", "continue", "shift", "readonly", "local", "declare", - "typeset", "echo", "printf", "true", "false", ":", "test", "[", "[[", "eval"): - if prog == "eval": - return True - continue - if prog == "find": - if any(a in ("-delete", "-exec", "-execdir", "-ok", "-okdir", "-fls", "-fprint") for a in rest): - return True - continue - if prog == "git": - sub = next((a for a in rest if not a.startswith("-")), "") - if sub == "stash": # only listing a stash leaves the tree alone; push/pop/apply change it - tail = rest[rest.index(sub) + 1:] - if not tail or tail[0] in ("list", "show"): - continue - return True - if sub in _READONLY_GIT and not (sub == "config" and any(not a.startswith("-") for a in rest[rest.index(sub) + 1:])): - continue # add/commit touch .git only, never a working-tree file - return True - if prog == "gh": - pair = tuple(a for a in rest if not a.startswith("-"))[:2] - if pair in _GH_READ: - continue - if pair and pair[0] == "api" and not any(a in ("-X", "--method", "-f", "-F", "--field", "--raw-field") - or a.startswith(("-f", "-F")) for a in rest): - continue - return True - if prog == "sisi": - # sisi writes only personal data and state, never the project — except contract - # init/waive/trust, which do record something about (or in) this project. - if rest and rest[0] == "contract": - if len(rest) > 1 and rest[1] in ("init", "waive", "trust", "untrust"): - return True - continue - continue - if prog in _READONLY_CMDS: - if prog in ("sed", "awk", "jq", "yq") and any("inplace" in a or a.startswith("-i") for a in rest): - return True - continue - return True # interpreters, build/test runners, scripts, anything unlisted: can write - return False - - -def _input_files(inp): - out = [] - if isinstance(inp, dict): - for k in ("file_path", "notebook_path", "path", "filename", "filePath"): - if isinstance(inp.get(k), str) and inp[k]: - out.append(inp[k]) - return out - - -def _parse_transcript_chunk(data, measured=False): - """Parse complete JSONL bytes. Returns (edits, files, writing, corrupt, consumed_bytes, shell_edits). - In measured mode Bash calls are not guessed from their text at all: the before/after tree - measurement (sisi/watch.py) has already attributed whatever they actually changed — except - `sisi contract init/waive/trust`, which record project state outside the measured files.""" - if data.endswith(b"\n") or not data: - consumed, body = len(data), data - else: - cut = data.rfind(b"\n") - tail = data[cut + 1:] - try: - json.loads(tail.decode("utf-8", "replace")) - consumed, body = len(data), data # a complete final line without its newline yet - except ValueError: - consumed, body = cut + 1, data[:cut + 1] # partial line: leave it for the next read - edits, files, writing, corrupt, shell_edits = 0, [], False, 0, 0 - for raw in body.split(b"\n"): - if not raw.strip(): - continue - if len(raw) > 131072 and b"tool_use" not in raw and b"Bash" not in raw: - continue # a huge tool-result line: no tool call hides in it worth parsing - try: - d = json.loads(raw.decode("utf-8", "replace")) - except ValueError: - corrupt += 1 - edits += 1 # an unreadable line may be the edit we cannot see: count it - writing = True - continue - if not isinstance(d, dict): - continue - content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None - for x in content if isinstance(content, list) else []: - if not isinstance(x, dict) or x.get("type") != "tool_use": - continue - name = x.get("name") or "" - inp = x.get("input") if isinstance(x.get("input"), dict) else {} - if name in EDIT_TOOLS or any(w in name.lower() for w in _WRITE_WORDS): - edits += 1 - writing = True - files += _input_files(inp) - elif name in ("Bash", "Shell", "bash", "shell"): - cmd = inp.get("command") if isinstance(inp.get("command"), str) else inp.get("cmd") - if measured: - if isinstance(cmd, str) and re.search(r"\bsisi\s+contract\s+(init|waive|trust|untrust)\b", cmd): - edits += 1 - shell_edits += 1 - writing = True - files.append(".sisi/contract.json") - continue # everything else was measured, not guessed - may = _shell_may_write(cmd) - if may is None: - corrupt += 1 - edits += 1 - shell_edits += 1 - writing = True - elif may: - edits += 1 - shell_edits += 1 - writing = True - return edits, files, writing, corrupt, consumed, shell_edits - - -def _scan_one(sess, store_key, path): - """Advance one transcript's offset in the session record. Returns (edits, files, writing, unknown).""" - offsets = sess.setdefault("attr_sub_offsets", {}) if store_key == "sub" else None - try: - size = os.path.getsize(os.path.expanduser(path)) - except OSError: - return 0, [], False, True, 0 # missing or unreadable: unknown, treated as edited by the caller - if store_key == "sub": - offset = int(offsets.get(path, 0) or 0) - else: - offset = int(sess.get("attr_offset", 0) or 0) - unknown = False - if offset > size: - offset, unknown = 0, True # truncated or replaced: rescan, and do not trust the gap - if size - offset > 64 * 1024 * 1024: - # Too much unread tail to scan inside the gate's budget: skip it and count it as a - # possible edit by this session (strict), rather than guessing it was someone else's. - if store_key == "sub": - offsets[path] = size - else: - sess["attr_offset"] = size - return 1, [], True, True, 0 - edits, files, writing, sh = 0, [], False, 0 - try: - with open(os.path.expanduser(path), "rb") as f: - f.seek(offset) - data = f.read() - except OSError: - return 0, [], False, True, 0 - if data: - e, fl, w, corrupt, consumed, sh = _parse_transcript_chunk(data, measured=bool(sess.get("attr_measured"))) - edits, files, writing = e, fl, w - unknown = unknown or corrupt > 0 - offset += consumed - if store_key == "sub": - offsets[path] = offset - else: - sess["attr_offset"] = offset - return edits, files, writing, unknown, sh - - -def _subagent_transcripts(tp): - """Native subagent transcripts under this session's transcript, Claude Code layout.""" - if not isinstance(tp, str) or not tp.endswith(".jsonl"): - return [] - root = os.path.join(os.path.expanduser(tp)[:-len(".jsonl")], "subagents") - out = [] - for dirpath, dirs, names in os.walk(root): - dirs.sort() - for n in sorted(names): - if n.startswith("agent-") and n.endswith(".jsonl"): - out.append(os.path.join(dirpath, n)) - return out - - -def _update_attribution(sess, tp): - """Refresh this session's edit count from its own (and its native subagents') transcripts. - - Returns {"gen", "writing", "unknown"} or None when no transcript path is known at all - (the caller then falls back to the pre-attribution behaviour). Fails towards edited.""" - if not isinstance(tp, str) or not tp: - return None - if sess.get("attr_tp") != tp: - sess.update(attr_tp=tp, attr_offset=0, attr_gen=0, attr_pass_gen=0, attr_retro_gen=0, - attr_baseline_gen=0, attr_writing=False, attr_files=[], attr_sub_offsets={}) - sess.setdefault("attr_gen", 0) - sess.setdefault("attr_pass_gen", 0) - sess.setdefault("attr_retro_gen", 0) - sess.setdefault("attr_baseline_gen", 0) - unknown = False - total, all_files, shell_total = 0, [], 0 - e, fl, w, unk, sh = _scan_one(sess, "main", tp) - total += e - shell_total += sh - all_files += fl - unknown = unknown or unk - if w: - sess["attr_writing"] = True - for sub in _subagent_transcripts(tp): - e, fl, w, unk, sh = _scan_one(sess, "sub", sub) - total += e - shell_total += sh - all_files += fl - unknown = unknown or unk - if w: - sess["attr_writing"] = True - sess["attr_gen"] = int(sess.get("attr_gen", 0)) + total - if all_files: - have = sess.setdefault("attr_files", []) - for f in all_files: - if f not in have: - have.append(f) - del have[:-500] - if unknown: - sess["attr_writing"] = True - return {"gen": int(sess["attr_gen"]), "writing": bool(sess.get("attr_writing")), "unknown": bool(unknown), - "edits": total, "files": all_files, "shell_edits": shell_total} - - -def _changed_paths(top, cwd, own_files): - """Up to five working-tree paths changed against HEAD that this session did not edit.""" - try: - rels = gitutil.measure(cwd, gitutil.head(cwd))["files"] - except Exception: - return [] - own = set() - for f in own_files or []: - own.add(os.path.normpath(f)) - if top: - try: - own.add(os.path.normpath(os.path.relpath(f, top))) - except ValueError: - pass - out = [] - for r in rels: - if os.path.normpath(r) not in own: - out.append(r) - if len(out) >= 5: - break - return out - - -def _other_sessions(top, cwd, changed, sid, tp): - """Session ids that plausibly made `changed` edits, from session records and sibling transcripts.""" - found = [] - - def note(x): - if x and x != sid and x not in found: - found.append(x) - - def mentions(path, limit=2 * 1024 * 1024): - try: - with open(os.path.expanduser(path), "rb") as f: - f.seek(0, 2) - size = f.tell() - f.seek(max(0, size - limit)) - data = f.read() - except OSError: - return False - return any(os.path.basename(c).encode() in data or c.encode() in data for c in changed) - - try: - names = sorted(os.listdir(os.path.join(paths.state(), "sessions"))) - except OSError: - names = [] - for n in names: - if not n.endswith(".json"): - continue - try: - with open(os.path.join(paths.state(), "sessions", n), encoding="utf-8") as f: - r = json.load(f) - except (OSError, ValueError): - continue - if not isinstance(r, dict): - continue - osid = r.get("session_id") or n[:-5] - if osid == sid: - continue - proj = r.get("req_project") or r.get("cwd") - if top and proj and gitutil.root(proj) not in (top, proj) and os.path.realpath(proj) != os.path.realpath(top): - # a record for another folder says nothing about this tree - if os.path.realpath(proj) != os.path.realpath(cwd): - continue - files = r.get("attr_files") or [] - hit = any(os.path.basename(f) in [os.path.basename(c) for c in changed] or - (top and os.path.normpath(os.path.join(top, c)) == os.path.normpath(f)) for f in files for c in changed) - if hit: - note(osid) - elif isinstance(r.get("transcript_path"), str) and changed and mentions(r["transcript_path"]): - note(osid) - if isinstance(tp, str) and changed: - try: - sibs = sorted(os.listdir(os.path.dirname(os.path.expanduser(tp)) or ".")) - except OSError: - sibs = [] - for n in sibs: - if n.endswith(".jsonl") and os.path.join(os.path.dirname(os.path.expanduser(tp)), n) != os.path.expanduser(tp): - p = os.path.join(os.path.dirname(os.path.expanduser(tp)), n) - if mentions(p): - note(n[:-len(".jsonl")]) - return found[:3] - - -# ---------------------------------------------------------------- rule 5: ask through the dialog -# Tools with a confirmed question dialog whose transcripts sisi can read in Claude-Code shape. -# Codex's request_user_input is behind a flag that is off by default, OpenCode's question tool has -# no readable transcript file here, and the other tools name no dialog at all, so they are exempt. -QUESTION_DIALOG_TOOLS = {"claude-code": ("AskUserQuestion",), "qwen": ("ask_user_question",)} -_RHETORICAL = (r"^who (wouldn'?t|couldn'?t|doesn'?t)\b", r"^what could possibly\b", - r"^(isn'?t|aren'?t) it (obvious|clear)\b") - - -def ends_with_question(text): - """True when a final message ends by asking the reader a question. The rule, exactly: after - removing fenced code blocks, blockquote lines and inline code, the last sentence of the last - paragraph ends with a question mark that is not inside a closing quote (a quoted question), - and the sentence does not start with a known rhetorical form.""" - if not isinstance(text, str) or not text.strip(): - return False - kept, in_fence = [], False - for line in text.split("\n"): - if line.strip().startswith("```"): - in_fence = not in_fence - continue - if in_fence or line.lstrip().startswith(">"): - continue - kept.append(re.sub(r"`[^`]*`", "", line)) - paras = [p.strip() for p in re.split(r"\n\s*\n", "\n".join(kept)) if p.strip()] - if not paras: - return False - para = " ".join(paras[-1].split()) - t = para.rstrip("*_ ") - if t.endswith(('?"', "?\"", "?'", "?’", "?”")): # the question mark sits inside a quotation - return False - t = t.rstrip(')]*_ ') - if not t.endswith("?"): - return False - start = max(t.rfind(".", 0, len(t) - 1), t.rfind("!", 0, len(t) - 1), t.rfind("?", 0, len(t) - 1)) + 1 - sentence = t[start:].strip().lower() - return not any(re.match(p, sentence) for p in _RHETORICAL) - - -def _last_turn(tp): - """(final assistant text, tool names used) after the last message the human typed, from the - transcript tail. None when the turn cannot be bounded (the caller then exempts the turn).""" - try: - size = os.path.getsize(os.path.expanduser(tp)) - with open(os.path.expanduser(tp), "rb") as f: - f.seek(max(0, size - 2 * 1024 * 1024)) - data = f.read() - except OSError: - return None - from . import harvest - recs = [] - for raw in data.split(b"\n"): - if not raw.strip(): - continue - try: - d = json.loads(raw.decode("utf-8", "replace")) - except ValueError: - continue # a cut first line or a corrupt one: it cannot be the turn's evidence either way - if isinstance(d, dict): - recs.append(d) - last_human = -1 - for i, d in enumerate(recs): - if d.get("type") == "user": - try: - if harvest.typed_text(d)[0] is not None: - last_human = i - except Exception: - pass - if last_human < 0: - return None - final, tools = "", set() - for d in recs[last_human + 1:]: - content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None - texts = [] - for x in content if isinstance(content, list) else []: - if not isinstance(x, dict): - continue - if x.get("type") == "tool_use" and isinstance(x.get("name"), str): - tools.add(x["name"]) - elif x.get("type") == "text" and isinstance(x.get("text"), str): - texts.append(x["text"]) - if texts and d.get("type") in ("assistant", None): - final = "\n".join(texts) - return final, tools - - -def _question_sendback(payload): - """('block', reason) when this turn ended by asking in reply text and no question dialog was - used in it; None otherwise. At most once per final message, keyed by its hash in the session - record, so a session can never be trapped. Subagents and dialog-less tools are exempt.""" - tool = store.tool() - dialogs = QUESTION_DIALOG_TOOLS.get(tool or "") - if not dialogs: - return None - if payload.get("agent_id") or payload.get("agent_transcript_path"): - return None # a subagent has no human to ask through a dialog - cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() - sid = _session_key(payload, cwd) - sess = store.load_session(sid) - tp = payload.get("transcript_path") if isinstance(payload.get("transcript_path"), str) else sess.get("transcript_path") - if not isinstance(tp, str) or not tp: - return None - turn = _last_turn(tp) - if not turn: - return None - final, tools = turn - if any(d in tools for d in dialogs) or not ends_with_question(final): - return None - key = hashlib.sha1(final.encode("utf-8", "replace")).hexdigest()[:16] - if sess.get("q_block_key") == key: - return None - sess["q_block_key"] = key - sess["req_blocks"] = int(sess.get("req_blocks", 0)) + 1 - store.save_session(sid, sess) - return "block", ("sisi: you ended by asking the human a question in the text of your reply. Ask it through the " - "tool's question dialog (%s), with options to pick from and the one you recommend marked — or " - "decide it yourself, record the assumption, and finish without the question. " - "(The rule in full: `sisi rule decide-dont-ask`.)" % dialogs[0]) - - -def _measure_work(cwd, base=None): - """Growth of the work itself: sisi's own contract file is not product work and never counts.""" - m = gitutil.measure(cwd, base) - rel = C.REL.replace(os.sep, "/") - if rel in m["files"]: - lines = m["lines"] - try: - with open(os.path.join(gitutil.root(cwd) or cwd, C.REL), "rb") as f: - lines = max(0, lines - (f.read().count(b"\n") or 1)) - except OSError: - pass - return {"lines": lines, "files": [f for f in m["files"] if f != rel]} - return m + from . import harvest + t0 = harvest.epoch(c["started"]) if isinstance(c.get("started"), str) else None + stats = U._transcript_stats(project, t0, time.time()) if t0 is not None else None + if stats and stats.get("corrections"): + return "the human corrected the agent" + except Exception as e: + store.log_error("gate-anomaly", e) + return None def _decide(payload): """Return ('allow', message_or_None) or ('block', reason).""" cfg = store.config() - g = cfg["gate"] - if not g.get("enabled", True): + if not cfg["gate"].get("enabled", True): return "allow", None - cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() + from . import workers + if workers.is_subagent_payload(payload): + return decide_subagent(payload) + cwd = _cwd(payload) sid = _session_key(payload, cwd) 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() - store.save_session(sid, sess) - since = sess.get("started") or sess.get("first_seen") + top = gitutil.root(cwd) path = C.find(cwd) - sess["req_contract"], sess["req_project"] = bool(path), cwd + sess["req_contract"], sess["req_project"] = bool(path), top or cwd if isinstance(payload.get("transcript_path"), str): sess["transcript_path"] = payload["transcript_path"] # `sisi retro` reads the request's start from it tp = sess.get("transcript_path") if isinstance(sess.get("transcript_path"), str) else None + + # 1. what did this session itself change since its last settled stop? try: - attr = _update_attribution(sess, tp) if tp else None + attr = attribution.update(sess, tp) if tp else None except Exception as e: # attribution must never break the gate: fail towards strict, not open store.log_error("gate-attribution", e) - attr = {"gen": int(sess.get("attr_gen", 0) or 0), "writing": True, "unknown": True} + attr = {"gen": int(sess.get("attr_gen", 0) or 0), "writing": True, "unknown": True, "files": []} if attr is not None: try: from . import watch @@ -600,32 +281,21 @@ def _decide(payload): attr["unknown"] = True # a shell command with a before but no after: strict except Exception as e: store.log_error("gate-watch-pending", e) - since_pass = sess.setdefault("attr_since_pass", []) - top0 = gitutil.root(cwd) - for f in attr.get("files") or []: - rel = f - if os.path.isabs(f) and top0: - try: - rel = os.path.relpath(f, top0) - except ValueError: - rel = f - if rel not in since_pass: - since_pass.append(rel) - if attr.get("shell_edits") and not sess.get("attr_measured") and "*shell*" not in since_pass: - since_pass.append("*shell*") # a text-classified shell edit: its paths are unknown - try: - store.save_session(sid, sess) # persist the offset even on an early return below - except Exception: - pass + _absorb_subagents(sess, sid) + _note_own_paths(sess, attr, top) + fp = gitutil.fingerprint(cwd, [path]) if top else None + if attr is not None: + gen = int(sess.get("attr_gen", 0) or 0) + if attr["unknown"] or gen > int(sess.get("seen_gen", 0) or 0): + sess["dirty"] = True + sess["seen_gen"] = gen + elif fp is None or fp != sess.get("settled_fp", sess.get("baseline_fp")): + sess["dirty"] = True # no transcript to read: the tree against its last settled state + stop = _Stop(sess, sid, cfg, fp, attr) + store.save_session(sid, sess) - def _own_since(key): - if attr is None: - return None # no transcript path known: pre-attribution behaviour - return bool(attr["unknown"] or int(sess.get("attr_gen", 0) or 0) > int(sess.get(key, 0) or 0)) - - own_since_pass = _own_since("attr_pass_gen") - own_since_retro = _own_since("attr_retro_gen") - c, errs = None, [] + # the open unit + c, errs, project = None, [], top or cwd if path: project = C.project_dir(path) if not trust.is_trusted(project): @@ -637,295 +307,220 @@ def _decide(payload): try: c = C.load(path) except (OSError, ValueError) as e: - errs = ["cannot read contract: %s" % e] - if c is not None and C.is_unedited_skeleton(c): - path = None # nothing real written yet: behave as if there is no contract + errs, c = ["cannot read contract: %s" % e], {} + if c is not None and c and C.is_unedited_skeleton(c): + c, path = None, None # nothing real written yet: behave as if there is no contract sess["req_contract"] = False - if c is not None and path and c.get("status") == "paused": - from . import unit as _unit - if gitutil.root(cwd) is None or c.get("pause_fp") == gitutil.fingerprint(cwd): - return "allow", None # a recorded wait and no new change: the turn ends with no demands - _unit.resume(c, path) # the tree changed since the pause: the wait is over - if c is not None and path and c.get("status") == "closed": - path = None # the unit is archived; new work stands or falls on its own + elif isinstance(c, dict) and c.get("status") == "closed": + c, path = None, None # the unit is archived; new work stands or falls on its own sess["req_contract"] = False - top = gitutil.root(cwd) - sess["req_project"] = top or (project if path else cwd) - fp = gitutil.fingerprint(cwd, [path]) if top else None - ctx = _Ctx(sess, sid, cfg, fp) + elif isinstance(c, dict) and c.get("status") == "paused": + if not sess.get("dirty") or top is None or c.get("pause_fp") == fp: + return stop.allow(cwd, settle=bool(sess.get("dirty"))) # a recorded wait, no new change + U.resume(c, path) # the tree changed since the pause: the wait is over + stop.refresh(cwd, path) + if not sess.get("dirty"): + return _late_close(stop, cwd, c, path, project) + + # 2. the profile + if top is None: + if c is None: + return stop.allow(cwd) + floor, reasons, own_floor = "isolated", ["not a git repository: the change cannot be measured"], None + else: + own = _own_changed(sess, sid, cwd, top, attr) + own_floor, own_reasons = risk.assess(own, diff_text=_diff_text(project, sess.get("head")), + patterns=risk.load_patterns(project)) + claimed = c is not None and _claims_unit(sess, path) + if own_floor == "trivial" and not claimed and not (c is not None and sess.get("last_unit") == c.get("id")): + return stop.allow(cwd) # documentation and the like, or nothing of this session's: nothing is asked + if c is not None: + files = gitutil.measure(project, c.get("base_head"))["files"] + floor, reasons = risk.assess(files, diff_text=_diff_text(project, c.get("base_head")), + patterns=risk.load_patterns(project)) + floor = max(floor, own_floor, key=lambda p: assure.ORDER[p]) + else: + floor, reasons = own_floor, own_reasons + profile, info = assure.effective_profile(floor, c) + if c is not None: + sess["last_unit"] = c.get("id") + req = assure.requirements(profile) + + # a fresh waiver for a change with no unit: recorded as a deviation, the contract is not demanded + w = _new_waiver(top or project, sess) if c is None else None + if w: + sess["waiver_ns"] = w.get("ns", 0) + return stop.allow(cwd) + + if profile == "trivial" or not req.get("contract"): + return _trivial(stop, cwd, c, path, project, profile) + + # 3. what the profile requires, and the selected fast checks + results, deadline = [], time.time() + float(cfg["gate"].get("budget_s", 120)) + if c is not None and not errs: + errs = C.validate(c) + if c is not None and not errs: + t_run = time.time() + results = V.run(c, project, deadline, cfg["verify"]["default_timeout_s"], tiers=("fast",), contract_path=path) + sess["req_check_s"] = float(sess.get("req_check_s", 0.0)) + (time.time() - t_run) + V.record(c, project, results, fp) ds = None - if path and c is not None and not C.validate(c): + if req.get("all_checks") and c is not None and not errs: try: + from . import deep as D ds = D.deep_state(c, project, fp) except Exception as e: store.log_error("gate-deep", e) - dfail = bool(ds and ds["state"] == "failed" and ds["fresh"]) # deep failure on the current tree - retro_on = bool(cfg.get("retro", {}).get("required", True)) - repo_key = top or (project if path else cwd) + failing = V.blocking(results) + if ds and ds["state"] == "failed" and ds["fresh"]: + failing = failing + [{"id": i["id"], "status": "failed", "reason": "deep", "tail": i["tail"]} for i in ds["failed"]] + miss = assure.missing(profile, c, project, results, errs, ds["state"] if ds else None) - def need_retro(real_work): - """True when real work was done and no retro covers the current tree state yet.""" - if not (retro_on and real_work): - return False - sess["real_work"] = True - from . import retro - if retro.satisfied(repo_key, since, fp): - sess["retro_done"] = True - if attr is not None: - sess["attr_retro_gen"] = int(sess.get("attr_gen", 0) or 0) - return False - return True + if miss or failing: + return _send_back(stop, cwd, c, path, project, profile, info, reasons, miss, failing, results) - _csp = {} + # 4. all green + if c is not None and c.get("unverified"): + c.pop("unverified") # re-verified since the gate released it + C.save(path, c) + stop.refresh(cwd, path) + note = _technique_note(c, profile, sess) + if c is None: # a waived change, or nothing that needs a unit + return stop.allow(cwd, note) + findings = [] + try: + from . import learning + findings = learning.findings_for_unit(project, c["id"]) + except Exception as e: + store.log_error("gate-findings", e) + if findings: + return _close(stop, cwd, c, path, project, profile, note) + if not cfg.get("retro", {}).get("required", True): + return stop.allow(cwd, note) + if sess.get("offered") == [c["id"], fp]: + return stop.allow(cwd, note) # offered once for this state of the tree; not repeated + sess["offered"] = [c["id"], fp] + text = _offer_text(c, profile, None) + return stop.block(text + ("\n" + note if note else ""), c["id"], project, counts=False) - def changed_paths_since_pass(): - if "v" not in _csp: - v = None - if attr is not None: - try: - from . import watch - v = watch.changed_since_pass(sid, cwd) - except Exception as e: - store.log_error("gate-watch-diff", e) - _csp["v"] = v if v is not None else _changed_paths(top, cwd, []) - return _csp["v"] - def own_responsible(): - """This session answers for the failing tree when a path that changed since the last - passing state is attributed to it (edit tool path, or a measured command window), or - when attribution is uncertain. Gen-only fallback when no path differs (e.g. the - contract itself changed, which the stat snapshot does not track).""" - if attr is None: - return True - if attr["unknown"]: - return True - changed = changed_paths_since_pass() - if not changed: - return bool(own_since_pass) - since = set(sess.get("attr_since_pass") or []) - if "*shell*" in since or "*shell-unmeasured*" in since: - return True - return any(p in changed for p in since) +def _trivial(stop, cwd, c, path, project, profile): + """A trivial change asks nothing, unless the unit shows an anomaly: then the retro is asked once.""" + sess = stop.sess + if c is None or not stop.cfg.get("retro", {}).get("required", True): + return stop.allow(cwd) + why = _anomaly(c, project, sess) + if not why: + return stop.allow(cwd) + try: + from . import learning + if learning.findings_for_unit(project, c["id"]): + return _close(stop, cwd, c, path, project, profile, None) + except Exception as e: + store.log_error("gate-findings", e) + if sess.get("offered") == [c["id"], None]: + return stop.allow(cwd) + sess["offered"] = [c["id"], None] + return stop.block(_offer_text(c, profile, why), c["id"], project, counts=False) - def other_allow(failing_text, contract_id=None): - """Someone else's failing tree: allow once per distinct tree state, recorded unverified.""" - if sess.get("other_notice_fp") == fp: - return ctx.allow() - sess["other_notice_fp"] = fp - store.append("results", {"ts": store.now(), "contract": contract_id, "project": project if path else repo_key, - "check": "gate", "item": "gate", "kind": None, "rung": None, - "status": "unverified", "duration_s": 0.0, "tool": store.tool(), "session": sid}) - own_paths = set(sess.get("attr_since_pass") or []) - changed = [p for p in changed_paths_since_pass() if p not in own_paths][:5] \ - or _changed_paths(top, cwd, sess.get("attr_files") or []) - others = _other_sessions(top, cwd, changed, sid, tp) - lines = ["sisi: the contract is NOT satisfied, but this session has not edited files since the " - "checks last passed (or since it started), so this turn may end. Do not report this work " - "as done; the result is recorded as UNVERIFIED. Relay this to the human.", - "Failing checks:\n" + failing_text] - if changed: - lines.append("Files changed in the tree that this session did not edit (likely another " - "session's work in progress): " + ", ".join(changed)) - if others: - lines.append("The changed files appear in the transcript/session record of session(s): " - + ", ".join(others)) - else: - lines.append("Files changed by another session are the likely cause; no other session " - "could be identified from the records available.") - return ctx.allow("\n".join(lines)) - def other_tree_changed(): - """The tree moved since this session's last pass or its start (dirty-vs-HEAD is the - fallback proxy when no start fingerprint was ever recorded for the session).""" - if fp is not None: - if sess.get("attr_pass_fp"): - return fp != sess["attr_pass_fp"] - if sess.get("baseline_fp") is not None: - return fp != sess["baseline_fp"] - if sess.get("last_fp") is not None: - return fp != sess["last_fp"] - return bool(_changed_paths(top, cwd, sess.get("attr_files") or [])) - - w = _new_waiver(top, sess) if (top and not path) else None # a fresh waiver re-opens the decision - # A turn that changed nothing is not punished and not re-checked. - if fp is not None and not w: - if sess.get("last_fp") is not None: - same, last = fp == sess["last_fp"], sess.get("last_decision") - else: - same, last = fp == sess.get("baseline_fp"), "allow" - if same and last == "allow" and not dfail: - return "allow", None - retro_clear = False - if same and last == "block" and sess.get("last_kind") == "retro": - from . import retro - retro_clear = retro.satisfied(repo_key, since, fp) - if same and last == "block" and sess.get("last_msg") and not retro_clear \ - and not (sess.get("last_kind") == "deep" and not dfail): - return ctx.block(sess["last_msg"], sess.get("last_contract"), sess.get("last_project"), - kind=sess.get("last_kind", "fast")) - - if path: - deadline = time.time() + float(g.get("budget_s", 120)) - if c is not None: - errs = C.validate(c) - if errs: - results = [{"item": "contract", "id": "contract", "status": "failed", "kind": None, "rung": None, - "claim": "contract is invalid", "duration_s": 0.0, "tail": "\n".join(errs)}] - else: - t_run = time.time() - results = V.run(c, project, deadline, cfg["verify"]["default_timeout_s"], tiers=("fast",), - reuse=False, contract_path=path) - sess["req_check_s"] = float(sess.get("req_check_s", 0.0)) + (time.time() - t_run) - V.record(c, project, results, fp) - if V.ok(results): - own_before_pass = own_since_pass - responsible_before_pass = own_responsible() if attr is not None else True - other_before_pass = attr is not None and not responsible_before_pass and other_tree_changed() - if attr is not None: - sess["attr_pass_gen"] = int(sess.get("attr_gen", 0) or 0) - sess["attr_pass_fp"] = fp - sess["attr_since_pass"] = [] - try: - from . import watch - watch.save_pass_snapshot(sid, cwd) - except Exception as e: - store.log_error("gate-watch-pass", e) - if dfail: - tails = "\n".join("- deep check %s [%s]:\n%s" % (i["id"], i["status"], "\n".join(" " + l for l in i["tail"].splitlines()[-15:])) - for i in ds["failed"]) - if other_before_pass: - return other_allow(tails[:4000], c["id"] if c else None) - return ctx.block("sisi: the fast checks pass, but the deep checks failed on the current tree " - "(send-back {n}). Fix the work, then re-run them with `sisi verify --deep " - "--background` (see `sisi verify --state`). Do not report this work as done.\n\n%s" - % tails[:4000], c["id"], project, kind="deep") - changed = fp is None or fp != sess.get("baseline_fp") - if need_retro(changed if attr is None else bool(own_since_retro)): - from . import retro - return ctx.block(retro.TEMPLATE, c["id"] if c else None, project, kind="retro") - if ds and ds["state"] != "fresh-pass" and sess.get("deep_notice") != (fp or "nofp"): - sess["deep_notice"] = fp or "nofp" - text = ("sisi: the fast checks pass, but the deep checks are %s (%d item%s). The work is NOT yet " - "verified end to end: report it as not yet done, say that deep checks are pending, and " - "start them with `sisi verify --deep --background` (progress: `sisi verify --state`)." - % (ds["state"], ds["items"], "" if ds["items"] == 1 else "s")) - return ctx.allow({"message": "sisi: deep checks %s; the work is not yet fully verified" % ds["state"], - "context": text}) - return ctx.allow() - if attr is not None and not own_responsible() and other_tree_changed(): - return other_allow(V.failure_report(results), c["id"] if c else None) - msg = ("sisi: the contract at %s is not satisfied (send-back {n}). Fix the work, then run " - "`sisi verify` until it passes. Do not report this work as done.\n\n%s" - % (path, V.failure_report(results))) +def _late_close(stop, cwd, c, path, project): + """This session changed nothing, but a retro was recorded for the open unit it evaluated before: + the unit closes now rather than waiting for the next change.""" + s = stop.sess + if c is not None and path and c.get("status") == "open" and s.get("last_unit") == c.get("id") \ + and not c.get("unverified"): try: - from . import retro - failing = " ".join("%s %s %s" % (r["id"], r.get("kind") or "", r.get("claim") or "") - for r in results if r["status"] in ("failed", "not-run")) - block = retro.lessons_block(failing, "gate", session=sid) - if block: - msg += "\n\n" + block + from . import learning + if learning.findings_for_unit(project, c["id"]): + rec, msg, ok = U.close_unit(c, path, project) + if ok: + stop.refresh(cwd, path) + return stop.allow(cwd, _cycle_note(stop.sid)) except Exception as e: - store.log_error("gate-lessons", e) - return ctx.block(msg, c["id"] if c else None, project) + store.log_error("gate-late-close", e) + return "allow", None - if not top: - return "allow", None - if sess.get("baseline") is None: - sess.update(baseline=_measure_work(cwd), head=gitutil.head(cwd), started=sess.get("started") or store.now()) - sess["baseline_fp"] = fp - if attr is not None: - sess["attr_baseline_gen"] = int(sess.get("attr_gen", 0) or 0) - store.save_session(sid, sess) - return "allow", None - if attr is not None and not _own_since("attr_baseline_gen") and not attr["unknown"]: - return ctx.allow() # this session edited nothing here: no retro, no growth send-back for others' work - # Fix 4: growth is measured from the session start, or from the latest waiver. - if w: - sess["baseline"] = {"lines": w.get("lines", 0), "files": w.get("files", [])} - sess["head"] = w.get("head") - sess["waiver_ns"] = w.get("ns", 0) - sess["blocks"] = 0 - now = _measure_work(cwd, sess.get("head")) - base = sess["baseline"] - dl = max(0, now["lines"] - base["lines"]) - df = len(set(now["files"]) - set(base["files"])) - if not (dl > int(g.get("growth_lines", 40)) or df > int(g.get("growth_files", 3))): - if need_retro(bool(sess.get("waiver_ns")) if attr is None else bool(own_since_retro)): - from . import retro - return ctx.block(retro.TEMPLATE, kind="retro") - return ctx.allow() - return ctx.block("sisi: this session has changed %d lines and %d files since its start and there is no " - "contract (send-back {n}). Write `.sisi/contract.json` (`sisi contract init` makes the " - "skeleton; give it at least one check with a real command), then run `sisi verify`. If " - "the change needs no checks, run `sisi contract waive \"\"` instead." % (dl, df)) + +def _cycle_note(sid): + try: + from . import cycle + note = cycle.due_notice(session=sid) + return note + " (This turn may end; the cycle is background work, not a send-back.)" if note else None + except Exception as e: + store.log_error("gate-cycle-notice", e) + return None + + +def _close(stop, cwd, c, path, project, profile, note): + rec, msg, ok = U.close_unit(c, path, project) + if not ok: # it cannot close as delivered: say why, like any other send-back + return _send_back(stop, cwd, c, path, project, profile, {}, [], [(msg.replace("sisi: ", ""), "")], [], []) + stop.refresh(cwd, path) + cyc = _cycle_note(stop.sid) + return stop.allow(cwd, "\n".join(x for x in (note, cyc) if x) or None) + + +def _send_back(stop, cwd, c, path, project, profile, info, reasons, miss, failing, results): + uid = c["id"] if c else None + why = ["%s" % m[0] for m in miss] + ["%s failed" % f["id"] for f in failing] + if stop.exhausted(): + return _release(stop, cwd, c, path, project, why) + lines = ["sisi: this %s change is not ready to hand over (send-back {n})." % profile] + if reasons: + lines[0] = lines[0][:-1] + " because %s." % reasons[0][:160] + if info.get("refused"): + lines.append("The contract declares %r, but the change is %r; add risk.why to lower it on the record." + % (info.get("declared"), info.get("floor"))) + if miss: + lines.append("Missing:") + lines += ["- %s -> %s" % (a, b) if b else "- %s" % a for a, b in miss] + if failing: + lines.append("Failing checks:") + lines += assure.failure_lines(failing, per_check=3) + lines.append("Fix these, then run `sisi verify`. Do not report this work as done.") + note = _technique_note(c, profile, stop.sess) + if note: + lines.append(note) + return stop.block(assure.fit(lines), uid, project) def decide(payload): - """The gate's answer: the contract/retro decision, then — only on an otherwise-clean stop — + """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 try: - q = _question_sendback(payload) + from . import questions + q = questions.sendback(payload) except Exception as e: # the question check must never break the gate store.log_error("gate-question", e) q = None return q if q else (action, msg) -def subagent_edits(transcript): - """(edited_files, start_ts) from a subagent transcript (JSONL). start_ts is in sisi's timestamp format, or None.""" - edited, start = False, None - with open(os.path.expanduser(transcript), encoding="utf-8", errors="replace") as f: - for line in f: - try: - d = json.loads(line) - except ValueError: - continue - if start is None and isinstance(d.get("timestamp"), str) and len(d["timestamp"]) >= 19: - start = d["timestamp"][:19] + "Z" - content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None - for x in content if isinstance(content, list) else []: - if isinstance(x, dict) and x.get("type") == "tool_use" and x.get("name") in EDIT_TOOLS: - edited = True - if isinstance(x, dict) and x.get("type") == "tool_use" and x.get("name") in ("Bash", "Shell"): - inp = x.get("input") if isinstance(x.get("input"), dict) else {} - if _shell_may_write(inp.get("command")) is not False: - edited = True - return edited, start - - def decide_subagent(payload): - """SubagentStop: only the retro requirement, only when the subagent edited files (read from its transcript).""" - cfg = store.config() - if not cfg.get("retro", {}).get("required", True) or not cfg["gate"].get("enabled", True): - return "allow", None - tp = payload.get("agent_transcript_path") - if not isinstance(tp, str): - return "allow", None # cannot tell whether it changed files: do not block - edited, start = subagent_edits(tp) - if not edited or not start: - return "allow", None - cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() - from . import retro - if retro.satisfied(retro.repo_of(cwd), start, None): - return "allow", None - key = "sub-%s" % (payload.get("agent_id") or "unknown") - sess = store.load_session(key) - blocks, maxb = int(sess.get("blocks", 0)), int(cfg["gate"].get("max_blocks", 3)) - if blocks >= maxb: - return "allow", None - sess["blocks"] = blocks + 1 - store.save_session(key, sess) - return "block", retro.TEMPLATE.replace("{n}", "%d of %d" % (blocks + 1, maxb)) + """SubagentStop: never blocks and never asks for a retro. A subagent's last message is its + report to its parent and stays that. What it observed is recorded for the parent's gate: that + it edited, and which files its edit tools named.""" + try: + tp = payload.get("agent_transcript_path") + if isinstance(tp, str) and tp and isinstance(payload.get("session_id"), str): + edited, files, _start = attribution.observed_edits(tp) + store.append("subagents", {"ts": store.now(), "ns": time.time_ns(), "session": payload["session_id"], + "agent": payload.get("agent_id"), "project": _cwd(payload), + "edited": edited, "files": files}) + except Exception as e: + store.log_error("gate-subagent", e) + return "allow", None def _record_delivery(payload): """The request is delivered: write one delivery row. Never raises, never changes the gate's answer.""" try: from . import delivery - cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() + cwd = _cwd(payload) sid = _session_key(payload, cwd) delivery.record(payload, store.load_session(sid), sid, cwd) except Exception as e: @@ -943,10 +538,6 @@ def main(args=()): _record_delivery(payload) if action == "block": sys.stdout.write(json.dumps({"decision": "block", "reason": msg}) + "\n") - elif isinstance(msg, dict): - # Documented for Stop: hookSpecificOutput.additionalContext reaches the model (and continues the turn once). - sys.stdout.write(json.dumps({"systemMessage": msg["message"], "hookSpecificOutput": { - "hookEventName": "Stop", "additionalContext": msg["context"]}}) + "\n") elif msg: sys.stdout.write(json.dumps({"systemMessage": msg}) + "\n") return 0 diff --git a/sisi/questions.py b/sisi/questions.py new file mode 100644 index 0000000..a18f37e --- /dev/null +++ b/sisi/questions.py @@ -0,0 +1,130 @@ +"""Rule 5 at the end of a turn: a reply that ends by asking the human a question must have asked it +through the tool's question dialog. Sent back at most once per final message, never a subagent.""" +import hashlib, json, os, re + +from . import store + + +def _session_key(payload, cwd): + sid = payload.get("session_id") + return sid if isinstance(sid, str) and sid else "cwd-" + hashlib.sha1(cwd.encode()).hexdigest()[:12] + + +# ---------------------------------------------------------------- rule 5: ask through the dialog +# Tools with a confirmed question dialog whose transcripts sisi can read in Claude-Code shape. +# Codex's request_user_input is behind a flag that is off by default, OpenCode's question tool has +# no readable transcript file here, and the other tools name no dialog at all, so they are exempt. +QUESTION_DIALOG_TOOLS = {"claude-code": ("AskUserQuestion",), "qwen": ("ask_user_question",)} +_RHETORICAL = (r"^who (wouldn'?t|couldn'?t|doesn'?t)\b", r"^what could possibly\b", + r"^(isn'?t|aren'?t) it (obvious|clear)\b") + + +def ends_with_question(text): + """True when a final message ends by asking the reader a question. The rule, exactly: after + removing fenced code blocks, blockquote lines and inline code, the last sentence of the last + paragraph ends with a question mark that is not inside a closing quote (a quoted question), + and the sentence does not start with a known rhetorical form.""" + if not isinstance(text, str) or not text.strip(): + return False + kept, in_fence = [], False + for line in text.split("\n"): + if line.strip().startswith("```"): + in_fence = not in_fence + continue + if in_fence or line.lstrip().startswith(">"): + continue + kept.append(re.sub(r"`[^`]*`", "", line)) + paras = [p.strip() for p in re.split(r"\n\s*\n", "\n".join(kept)) if p.strip()] + if not paras: + return False + para = " ".join(paras[-1].split()) + t = para.rstrip("*_ ") + if t.endswith(('?"', "?\"", "?'", "?’", "?”")): # the question mark sits inside a quotation + return False + t = t.rstrip(')]*_ ') + if not t.endswith("?"): + return False + start = max(t.rfind(".", 0, len(t) - 1), t.rfind("!", 0, len(t) - 1), t.rfind("?", 0, len(t) - 1)) + 1 + sentence = t[start:].strip().lower() + return not any(re.match(p, sentence) for p in _RHETORICAL) + + +def _last_turn(tp): + """(final assistant text, tool names used) after the last message the human typed, from the + transcript tail. None when the turn cannot be bounded (the caller then exempts the turn).""" + try: + size = os.path.getsize(os.path.expanduser(tp)) + with open(os.path.expanduser(tp), "rb") as f: + f.seek(max(0, size - 2 * 1024 * 1024)) + data = f.read() + except OSError: + return None + from . import harvest + recs = [] + for raw in data.split(b"\n"): + if not raw.strip(): + continue + try: + d = json.loads(raw.decode("utf-8", "replace")) + except ValueError: + continue # a cut first line or a corrupt one: it cannot be the turn's evidence either way + if isinstance(d, dict): + recs.append(d) + last_human = -1 + for i, d in enumerate(recs): + if d.get("type") == "user": + try: + if harvest.typed_text(d)[0] is not None: + last_human = i + except Exception: + pass + if last_human < 0: + return None + final, tools = "", set() + for d in recs[last_human + 1:]: + content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None + texts = [] + for x in content if isinstance(content, list) else []: + if not isinstance(x, dict): + continue + if x.get("type") == "tool_use" and isinstance(x.get("name"), str): + tools.add(x["name"]) + elif x.get("type") == "text" and isinstance(x.get("text"), str): + texts.append(x["text"]) + if texts and d.get("type") in ("assistant", None): + final = "\n".join(texts) + return final, tools + + +def sendback(payload): + """('block', reason) when this turn ended by asking in reply text and no question dialog was + used in it; None otherwise. At most once per final message, keyed by its hash in the session + record, so a session can never be trapped. Subagents and dialog-less tools are exempt.""" + tool = store.tool() + dialogs = QUESTION_DIALOG_TOOLS.get(tool or "") + if not dialogs: + return None + if payload.get("agent_id") or payload.get("agent_transcript_path"): + return None # a subagent has no human to ask through a dialog + cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() + sid = _session_key(payload, cwd) + sess = store.load_session(sid) + tp = payload.get("transcript_path") if isinstance(payload.get("transcript_path"), str) else sess.get("transcript_path") + if not isinstance(tp, str) or not tp: + return None + turn = _last_turn(tp) + if not turn: + return None + final, tools = turn + if any(d in tools for d in dialogs) or not ends_with_question(final): + return None + key = hashlib.sha1(final.encode("utf-8", "replace")).hexdigest()[:16] + if sess.get("q_block_key") == key: + return None + sess["q_block_key"] = key + sess["req_blocks"] = int(sess.get("req_blocks", 0)) + 1 + store.save_session(sid, sess) + return "block", ("sisi: you ended by asking the human a question in the text of your reply. Ask it through the " + "tool's question dialog (%s), with options to pick from and the one you recommend marked — or " + "decide it yourself, record the assumption, and finish without the question. " + "(The rule in full: `sisi rule decide-dont-ask`.)" % dialogs[0]) diff --git a/sisi/store.py b/sisi/store.py index 12b2b85..21f7afe 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -5,7 +5,7 @@ from . import paths FILES = {"results": "results.jsonl", "learn": "learn.jsonl", "quarantine": "learn.jsonl", "waivers": "waivers.jsonl", - "deliveries": "deliveries.jsonl", "units": "units.jsonl"} + "deliveries": "deliveries.jsonl", "units": "units.jsonl", "subagents": "subagents.jsonl"} def _migrate_learn(): @@ -154,7 +154,7 @@ def stamp(extra): return rec -DEFAULTS = {"gate": {"enabled": True, "budget_s": 120, "max_blocks": 3, "growth_lines": 40, "growth_files": 3}, +DEFAULTS = {"gate": {"enabled": True, "budget_s": 120, "max_blocks": 3}, "verify": {"default_timeout_s": 60, "fast_limit_s": 60}, "retro": {"required": True}, "scratch": {"session_max_age_days": 30, "prune_every": 20, "prune_max_delete": 1000, diff --git a/sisi/unit.py b/sisi/unit.py index fe68f17..6054eee 100644 --- a/sisi/unit.py +++ b/sisi/unit.py @@ -137,14 +137,14 @@ def _row_epoch(r): def policy_version(project, c): - """Hash of the policies in force: the effective rulebook, the floors and risk tables, + """Hash of the policies in force: the effective rulebook, the risk tables, the enforced checks, and the gate/verify config.""" h = hashlib.sha256() rulebook = paths.generated() if not os.path.exists(rulebook): rulebook = paths.canon("core.md") # named by role, never by path: the same policies hash the same in any clone or project - for role, p in (("rulebook", rulebook), ("floors", paths.canon("floors.json")), + for role, p in (("rulebook", rulebook), ("risk table", paths.canon("risk.json")), ("project risk table", os.path.join(project, ".sisi", "risk.json"))): try: diff --git a/sisi/verifiers.py b/sisi/verifiers.py index 1311df7..9d1bcc4 100644 --- a/sisi/verifiers.py +++ b/sisi/verifiers.py @@ -455,21 +455,12 @@ def cmd_for(args): ranked = [(s + (1.0 if inst[e["path"]] == "yes" else 0.0), e) for s, e in cands] ranked.sort(key=lambda x: (-round(x[0], 1), x[1]["rung"], x[1]["id"])) top = ranked[:8] - fl = None - if "kind" in opts: - fl = C.floors().get(opts["kind"].lower()) - if fl: - print("Floor: %s claims need rung %d or stronger (canon/floors.json). Results marked [floor ok] satisfy it.\n" - % (opts["kind"], fl)) if not top: print("no verifier matches that description; try `sisi verifiers` to browse") _print_lessons(desc, "verifiers-for", loose=True) return 0 for i, (f, e) in enumerate(top, 1): - mark = "" - if fl: - mark = " [floor ok]" if e["rung"] <= fl else " [below floor]" - print("%d. %s rung %s cost %s installed: %s%s%s" % (i, e["id"], e["rung"], e["cost"] or "-", inst[e["path"]], mark, origin_tag(e))) + print("%d. %s rung %s cost %s installed: %s%s" % (i, e["id"], e["rung"], e["cost"] or "-", inst[e["path"]], origin_tag(e))) print(" %s" % (e["answers"] or e["title"])) print("\nsisi verifiers show ID for set-up and a worked example") _print_lessons(desc, "verifiers-for", extra=" ".join(e["id"] for _, e in top[:3]), loose=True, diff --git a/sisi/verify.py b/sisi/verify.py index 5f3c427..edb1627 100644 --- a/sisi/verify.py +++ b/sisi/verify.py @@ -285,11 +285,6 @@ def run(c, project, deadline=None, default_timeout=60, tiers=("fast",), changed= dirty_cache = True if dirty_cache: _save_cache(cache) - for f in (C.floor_failures(c) if "fast" in tiers else []): - res.append({"item": "floor", "tier": "fast", "id": "floor:" + f["kind"], "kind": f["kind"], "rung": None, - "claim": f["message"], "status": "failed", "reason": None, "duration_s": 0.0, - "tail": f["message"], "mandatory": True, "independent": False, "covers": None, - "seen_failing": True, "saved_s": 0.0}) if "fast" in tiers: # enforced lessons ride the same path as floors (personal overlay, trusted commands) try: from . import cycle diff --git a/tests/test_contract.py b/tests/test_contract.py index 5e87b18..302b59b 100644 --- a/tests/test_contract.py +++ b/tests/test_contract.py @@ -40,17 +40,6 @@ class ContractTests(SisiCase): def test_rung_5_6_valid_without_cmd(self): self.assertEqual(C.validate(contract([check("a", "true"), human("h", 5), human("i", 6)])), []) - def test_floors(self): - weak = contract([check("m", "true", rung=3, kind="money")]) - self.assertEqual(len(C.floor_failures(weak)), 1) - self.assertEqual(C.floor_failures(contract([check("m", "true", rung=2, kind="money")])), []) - # one strong check among weak ones satisfies the floor - self.assertEqual(C.floor_failures(contract([check("m", "true", rung=3, kind="money"), - check("n", "true", rung=1, kind="money")])), []) - self.assertEqual(C.floor_failures(contract([check("u", "true", rung=4, kind="ui")])), []) - for k in ("concurrency", "parsing", "money", "state-machine", "migration"): - self.assertEqual(C.floors()[k], 2) - def test_find_stops_at_git_root(self): self.git_init() self.write_contract(contract([check("a", "true")])) diff --git a/tests/test_verifiers.py b/tests/test_verifiers.py index d31525a..c27bc7f 100644 --- a/tests/test_verifiers.py +++ b/tests/test_verifiers.py @@ -161,17 +161,6 @@ class ShowAndChooseTests(LibCase): out = self.sisi("verifiers", "for", "widget").stdout self.assertEqual(len([l for l in out.splitlines() if l[:1].isdigit()]), 8) - def test_for_kind_floor_marking(self): - self.seed() - out = self.sisi("verifiers", "for", "parsing round trip", "--kind", "parsing").stdout - self.assertIn("Floor: parsing claims need rung 2", out) - self.assertIn("[floor ok]", out) - self.put("prove/weakparse.md", vfile("weakparse", rung=4, kinds="parsing", answers="Does parsing look fine?")) - out = self.sisi("verifiers", "for", "parsing looks fine", "--kind", "parsing").stdout - self.assertIn("[below floor]", out) - out = self.sisi("verifiers", "for", "page looks", "--kind", "ui").stdout - self.assertNotIn("Floor:", out) - def test_for_lang_and_kind_filters(self): self.seed() out = self.sisi("verifiers", "for", "random inputs parsing", "--lang", "rust").stdout