The end-of-turn gate rebuilt on risk profiles; non-findings refused as retro findings

The gate enforces exactly what the profile requires, lists everything missing in
one message, closes a green unit when a finding is recorded, lets a paused unit
stop silently, never blocks a subagent, records a release as unverified, and says
at commit time when the checks have not passed on the tree. Size thresholds and
the floors file are gone. 'It went well' and similar are refused as findings.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-23 12:16:29 -07:00
commit 216f39e8f7
31 files changed
+2383 -1807

No files matched your search

+175
View File
@@ -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) + 1) # a judgement rounds its time
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\": \"<who or what>\""))
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
+297
View File
@@ -0,0 +1,297 @@
"""Which edits were this session's own. The gate reads this, never another session's work.
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
<transcript-without-.jsonl>/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 commands are measured by the before/after hooks (sisi/watch.py) where those are
installed; where they are not, a shell command counts when it plausibly writes: a redirect, tee/dd-of,
an in-place editor, 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 (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
daemon, a tool whose transcript is not Claude-Code JSONL, and writes made between the last complete
transcript line and a crash. A missing or 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 rather than scanned inside the gate's time budget.
"""
import json, os, re, shlex
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 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
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_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_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(sess, tp):
"""Refresh this session's edit count from its own (and its native subagents') transcripts.
Returns {"gen", "writing", "unknown", "edits", "files", "shell_edits"} or None when no transcript
path is known at all (the caller then falls back to comparing the tree with its last settled
state). Fails towards edited: `unknown` is true whenever the transcript cannot be trusted."""
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_writing=False, attr_files=[], attr_sub_offsets={})
sess.setdefault("attr_gen", 0)
unknown = False
total, all_files, shell_total = 0, [], 0
for key, path in [("main", tp)] + [("sub", s) for s in subagent_transcripts(tp)]:
e, fl, w, unk, sh = _scan_one(sess, key, path)
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 observed_edits(transcript):
"""(edited, files, start_ts) from a subagent's own transcript: did it write, which files did its
edit tools name, and when did it start (sisi's timestamp format, or None). A shell command that
may write counts as an edit with no known file."""
edited, files, 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 not isinstance(d, dict):
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 not (isinstance(x, dict) and x.get("type") == "tool_use"):
continue
inp = x.get("input") if isinstance(x.get("input"), dict) else {}
if x.get("name") in EDIT_TOOLS:
edited = True
files += [f for f in _input_files(inp) if f not in files]
elif x.get("name") in ("Bash", "Shell") and shell_may_write(inp.get("command")) is not False:
edited = True
return edited, files[:100], start
-4
View File
@@ -175,10 +175,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)
+21 -22
View File
@@ -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
+412 -820
View File
File diff suppressed because it is too large. Load diff
+6 -1
View File
@@ -34,7 +34,12 @@ GENERIC_WORDS = set((
"improving improvement quality thorough thoroughly review reviewing think thinking plan planning ahead "
"going forward all any some general generally just really very much many bit little slightly again once "
"ever also too so can could would will may might worse avoid mistakes mistake fine ok okay well everything "
"anything something stuff careless carelessness sloppy rushed hasty lazy diligent diligence").split())
"anything something stuff careless carelessness sloppy rushed hasty lazy diligent diligence "
# a non-finding says only that nothing stood out ("it went well", "no problems, as expected")
"went go goes gone smooth smoothly expected nicely perfect perfectly success successful successfully "
"finished complete completed happened happen hitch hitches without notable remarkable report reported "
"particular special specific cause causes reason reasons known unknown clear obvious say said "
"passed pass green").split())
class LearningError(Exception):
+130
View File
@@ -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])
+74 -6
View File
@@ -5,7 +5,7 @@ Missing data is unavailable with value None: never zero, never good. No single s
ever computed or printed. Check statistics and escape candidates (work declared verified
that then turned out wrong) live here too: they feed the correctness and intent dimensions.
"""
import json, os, re
import json, os, re, time
from . import harvest, store
@@ -186,6 +186,7 @@ def build_scorecard(c, results, telemetry, delivery_status):
"techniques": val(sorted({"rung %s" % x.get("rung") for x in items.values()} |
{str(x.get("kind")) for x in items.values() if x.get("kind")}), "measured"),
"checks_seen_failing": val(sum(1 for r in latest.values() if r.get("seen_failing")), "measured"),
"stronger_than_examples": val(any(x.get("rung") in (1, 2) for x in items.values()), "measured"),
"independent_evidence": val(any(norm_status((latest.get(cid) or {}).get("status")) == "passed"
for cid, x in items.items() if x.get("independent")), "measured"),
"deviation": val(delivery_status == "deviation", "measured"),
@@ -345,8 +346,74 @@ def format_dimension(dim, vals):
("; %d unavailable" % n_un) if n_un else "")
def format_status(units, learning=False, recent=5):
def _age(iso, now=None):
"""'3h', '2d', '15m' since an ISO UTC time; '?' when it cannot be read."""
from . import harvest
t = harvest.epoch(iso) if isinstance(iso, str) else None
if t is None:
return "?"
s = max(0, (time.time() if now is None else now) - t)
return "%dd" % (s // 86400) if s >= 86400 else "%dh" % (s // 3600) if s >= 3600 else "%dm" % (s // 60)
def open_units(cwd=None):
"""The unit that is open or paused in this project, as display rows. A unit that waits (paused)
says what for and for how long; one that was declared below its floor says so, with the reason."""
from . import contract as C, unit as U, assure
out = []
try:
p = C.find(cwd or os.getcwd())
c = C.load(p) if p else None
except (OSError, ValueError):
return out
if not isinstance(c, dict) or not c.get("id") or c.get("status") == "closed" or C.is_unedited_skeleton(c):
return out
project = C.project_dir(p)
row = {"id": c["id"], "status": c.get("status", "open"), "age": _age(c.get("started")), "goal": c.get("goal") or ""}
if row["status"] == "paused":
pz = next((x for x in reversed(c.get("pauses") or []) if isinstance(x, dict) and not x.get("until")), {})
row["waiting_for"], row["paused_for"] = pz.get("what"), _age(pz.get("since"))
rk = c.get("risk") or {}
floor, _ = U.risk_floor(c, project)
floor = floor.get("value") if isinstance(floor, dict) else floor
if assure.is_lowered(floor, rk.get("profile"), rk.get("why")):
row["lowered"] = "declared %s below the floor %s: %s" % (rk.get("profile"), floor, rk.get("why"))
if c.get("unverified"):
row["unverified"] = "; ".join(c["unverified"].get("why") or [])
out.append(row)
return out
def _lowered_note(u):
rk = u.get("risk") or {}
if not rk.get("lowered"):
return ""
floor = rk.get("floor")
floor = floor.get("value") if isinstance(floor, dict) else floor
return " [lowered: declared %s, floor %s%s]" % (rk.get("declared"), floor,
(": " + str(rk["why"])) if rk.get("why") else "")
def format_open(rows):
lines = []
for r in rows:
if r["status"] == "paused":
lines.append("paused %-24s age %s waiting for: %s (for %s)" % (r["id"], r["age"], r.get("waiting_for") or "?", r.get("paused_for")))
else:
lines.append("open %-24s age %s %s" % (r["id"], r["age"], r["goal"][:80]))
if r.get("lowered"):
lines.append(" lowered: " + r["lowered"])
if r.get("unverified"):
lines.append(" released unverified by the gate: " + r["unverified"])
return lines
def format_status(units, learning=False, recent=5, opened=()):
lines = []
if opened:
lines.append("units in progress:")
lines += [" " + ln for ln in format_open(opened)]
lines.append("")
if not units:
lines.append("sisi status: no closed work units yet. Close one with `sisi unit close`; "
"its scorecard will appear here.")
@@ -354,8 +421,8 @@ def format_status(units, learning=False, recent=5):
lines.append("recent units (newest first, %d closed in all):" % len(units))
for u in list(reversed(units))[:recent]:
lines.append("")
lines.append("%s %s [%s] %s" % (u.get("id"), str(u.get("ended") or "")[:10],
u.get("delivery_status"), u.get("goal") or ""))
lines.append("%s %s [%s] %s%s" % (u.get("id"), str(u.get("ended") or "")[:10],
u.get("delivery_status"), u.get("goal") or "", _lowered_note(u)))
sc = u.get("scorecard") or {}
for dim, vals in sc.items():
lines.append(format_dimension(dim, vals))
@@ -385,8 +452,9 @@ def format_status(units, learning=False, recent=5):
def cmd_status(args=(), cwd=None, out=print):
units = load_unit_summaries(cwd)
opened = open_units(cwd)
if "--json" in args:
out(json.dumps({"units": units, "trends": trends(units)}, indent=2, default=str))
out(json.dumps({"open": opened, "units": units, "trends": trends(units)}, indent=2, default=str))
return 0
out(format_status(units, learning="--learning" in args))
out(format_status(units, learning="--learning" in args, opened=opened))
return 0
+2 -2
View File
@@ -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,
+1 -2
View File
@@ -75,8 +75,7 @@ def main(args=()):
rec["attr_offset"] = os.path.getsize(os.path.expanduser(payload["transcript_path"]))
except OSError:
rec["attr_offset"] = 0
rec.update(attr_gen=0, attr_pass_gen=0, attr_retro_gen=0, attr_baseline_gen=0,
attr_writing=False, attr_files=[], attr_sub_offsets={})
rec.update(attr_gen=0, seen_gen=0, dirty=False, attr_writing=False, attr_files=[], attr_sub_offsets={})
from . import contract as C, gitutil
if gitutil.root(cwd):
rec["head"] = gitutil.head(cwd)
+29 -3
View File
@@ -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:
@@ -458,6 +458,8 @@ def decide_status(c, rows, abandon=None):
return "abandoned", block, unrun
if c.get("deviations"):
return "deviation", block, unrun
if c.get("unverified"): # the gate released the unit after its send-backs and nothing has verified it since
return "unverified", block, unrun
if block:
released = any(r.get("check") == "gate" and r.get("status") == "unverified" for r in rows)
return ("unverified" if released else None), block, unrun
@@ -480,6 +482,8 @@ def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None,
unrun = never_run(latest)
floor, floor_reasons = risk_floor(c, project)
declared = c.get("risk") or {}
from . import assure
floor_name = floor.get("value") if isinstance(floor, dict) else floor
rec = {
"id": c["id"], "parent": c.get("parent"),
"goal": c.get("goal"), "scope": c.get("scope") or {"in": [], "out": []},
@@ -488,7 +492,10 @@ def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None,
"checks": c.get("checks") or [], "invariants": c.get("invariants") or [],
"risk": {"floor": floor, "floor_reasons": floor_reasons,
"declared": declared.get("profile"), "why": declared.get("why"),
"lowered": assure.is_lowered(floor_name, declared.get("profile"), declared.get("why")),
"blast_radius": declared.get("blast_radius"), "rollback": declared.get("rollback")},
"stronger_technique": assure.stronger_technique(c),
"released_unverified": c.get("unverified"),
"approach": c.get("approach"),
"plan": c.get("plan") or [],
"workers": delegation_rows,
@@ -521,7 +528,7 @@ def summary_line(rec):
floor = (risk.get("floor") or {}).get("value") if isinstance(risk.get("floor"), dict) else risk.get("floor")
return {"id": rec["id"], "parent": rec.get("parent"), "project": rec.get("project"),
"goal": rec.get("goal"), "delivery_status": rec.get("delivery_status"),
"risk": {"declared": risk.get("declared"), "floor": floor},
"risk": {"declared": risk.get("declared"), "floor": floor, "lowered": bool(risk.get("lowered"))},
"models": rec.get("models") or [], "policy_version": rec.get("policy_version"),
"started": rec.get("started"), "ended": rec.get("ended"), "closed_at": rec.get("closed_at"),
"scorecard": rec.get("scorecard")}
@@ -637,6 +644,25 @@ def resume(c, contract_path):
return True
def verified_for_tree(c, project, contract_path):
"""True when the unit's fast checks have a run that passed on exactly the tree as it is now
(what the commit-time notice asks). A run that was skipped or reused counts only if nothing in
it blocks and something passed. False when no run is recorded for this tree."""
from . import verify as V
fp = V.tree_fp(project, contract_path)
if fp is None:
return True # outside git there is no tree to compare: nothing to say
runs = {}
for r in _unit_results(c, project, c.get("started")):
if r.get("fp") == fp and r.get("tier", "fast") == "fast" and r.get("run") and r.get("item") in ("check", "invariant"):
runs.setdefault(r["run"], []).append(r)
for rows in runs.values():
if not V.blocking(rows) and any(r.get("status") == "passed" or str(r.get("reason") or "").startswith("reused: passed")
for r in rows):
return True
return False
def summary_for_retro(project):
"""What `sisi retro` prints: the open unit's scorecard so far and what stands out in it."""
p = os.path.join(project, C.REL)
+1 -10
View File
@@ -433,21 +433,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)
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, extra=" ".join(e["id"] for _, e in top[:3]), targets=tuple(e["id"] for _, e in top))
-5
View File
@@ -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
+31 -1
View File
@@ -12,7 +12,7 @@ that errs strict, which is the safe side. A pending before-record with no after
killed) is likewise treated as this session having edited, with no known paths (a sentinel).
Both hooks fail open: any error is logged and the tool call proceeds.
"""
import json, os, time
import json, os, re, time
from . import gitutil, paths, store
@@ -191,6 +191,28 @@ def changed_since_pass(sid, cwd):
return gitutil.snapshot_diff(pend, gitutil.snapshot(cwd))
_COMMIT_RE = re.compile(r"(?:^|[;&|(]\s*)(?:\w+=\S+\s+)*git\s+(?:(?:-C|-c)\s+\S+\s+|--[\w-]+\s+)*(?:commit|merge)\b")
def commit_notice(payload):
"""One line, never a block: the command is a `git commit` or `git merge` and the open unit's fast
checks have no passing result for the tree as it is now. None when there is nothing to say."""
tool, cmd, _ev, cwd, _sid = extract(payload)
if not is_shell(tool, cmd) or not _COMMIT_RE.search(cmd):
return None
from . import contract as C, trust, unit
path = C.find(cwd)
if not path or not trust.is_trusted(C.project_dir(path)):
return None
c = C.load(path)
if not isinstance(c, dict) or c.get("status", "open") != "open" or C.is_unedited_skeleton(c) or C.validate(c):
return None
if unit.verified_for_tree(c, C.project_dir(path), path):
return None
return ("sisi: unit %s has no passing `sisi verify` result for the tree you are about to commit; run "
"`sisi verify` first (a notice, not a block)." % c.get("id"))
def main(args=()):
try:
from . import gate
@@ -198,6 +220,14 @@ def main(args=()):
_tool, _cmd, ev, _cwd, _sid = extract(payload)
if "--before" in args or ev in BEFORE_EVENTS:
before(payload)
try:
line = commit_notice(payload)
if line:
import sys
sys.stdout.write(json.dumps({"systemMessage": line, "hookSpecificOutput": {
"hookEventName": "PreToolUse", "additionalContext": line}}) + "\n")
except Exception as e:
store.log_error("watch-commit-notice", e)
elif "--after" in args or ev in AFTER_EVENTS:
after(payload)
except Exception as e: # fail open: a tool call must never be held up by measurement