Records: the durable work-unit record, five verification statuses with selection and reuse, telemetry with honest classes, the scorecard and sisi status, scratch pruning

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-23 11:50:29 -07:00
commit 563cac426a
31 files changed
+3132 -783

No files matched your search

+62 -106
View File
@@ -5,13 +5,19 @@ HELP = """sisi is still improving
A shared rulebook and enforced definitions of done for every AI coding CLI.
sisi contract init [--goal TEXT] create .sisi/contract.json here
sisi contract check validate the contract
sisi contract waive "<reason>" record that this change needs no checks
sisi contract init [--goal TEXT] start a work unit: create .sisi/contract.json here (refuses while one is open)
sisi contract check validate the contract (vacuous checks are refused)
sisi contract waive [--check ID] "<reason>"
record a deviation: a waived check does not pass; the unit closes as a deviation and the report must say so
sisi contract trust | untrust allow / stop allowing this project's contract to run commands
sisi verify [--json] run the fast checks; exit 0 ok, 1 failure, 2 no contract, 3 untrusted
sisi unit close [--abandon "<reason>"]
archive the unit to .sisi/units/<id>.json with its scorecard; --abandon records why it stopped
sisi unit pause "<what it waits for>"
record a wait; the turn may end with no demands
sisi unit show [ID] | list print the open unit or an archived record; list this project's units
sisi verify [--json] run the selected fast checks (five statuses; nothing unrun passes); exit 0 ok, 1 failure, 2 no contract, 3 untrusted
sisi verify --deep [--background] run the deep (long) checks; --background detaches and returns at once
sisi verify --all | --state run both tiers; print only the deep-check state (with --json)
sisi verify --all | --state run every check in both tiers; print only the deep-check state (with --json)
sisi gate [--tool NAME] end-of-turn hook (reads hook JSON on stdin; NAME selects the tool's hook shape)
sisi tick [--tool NAME] session-start hook
sisi prompt [--tool NAME] prompt-submission hook: prints the matching recipe and lessons for the human's request as added context (silent when nothing strictly matches); `sisi prompt "<request>"` tries it by hand
@@ -54,8 +60,7 @@ A shared rulebook and enforced definitions of done for every AI coding CLI.
its key text) and removes it from the pile
sisi oracle print what the human wants: the standing principles from
`sisi learn`, live at once (oracle.md in the personal folder)
sisi status verification statistics from the store
sisi time [--json] time from request to verified result: 7 days against the 7 before, slowest checks
sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score)
sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]
list ways to know work is correct, by section
sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it
@@ -107,12 +112,36 @@ def cmd_contract(args):
if sub == "init":
goal = _pop_opt(args, "--goal")
p = os.path.join(os.getcwd(), C.REL)
project = os.getcwd()
if os.path.exists(p):
print("sisi: %s already exists" % p)
return 1
try:
old = C.load(p)
except (OSError, ValueError):
old = None
from . import unit as _U
if not _U.is_closed(old):
print("sisi: %s already exists and the unit %s is still open. Close it first with "
"`sisi unit close`, or record why it stopped with "
"`sisi unit close --abandon \"<reason>\"`." % (p, (old or {}).get("id", "?")))
return 1
# A closed unit is replaced. Its archive should already exist; if a hand-edited
# contract claims closed with none, archive it now so nothing is ever lost.
if old is not None and old.get("id") and not os.path.exists(_U.archive_path(project, old["id"])):
try:
import time as _t
rec = _U.build_record(old, project, old.get("delivery_status") or "abandoned", _t.time())
_U.archive_record(rec, project)
if not _U._summary_exists(project, rec["id"]):
store.append("units", _U.summary_line(rec))
except Exception as e:
store.log_error("contract-init-archive", e)
os.makedirs(os.path.dirname(p), exist_ok=True)
skel = C.skeleton(goal)
from . import unit as _U
skel["id"] = _U.fresh_id(skel["id"], project)
skel["base_head"] = gitutil.head(project)
with open(p, "w", encoding="utf-8") as f:
json.dump(C.skeleton(goal), f, indent=2)
json.dump(skel, f, indent=2)
f.write("\n")
trust.add(os.getcwd())
print("created %s as a SKELETON, not a contract yet: replace the placeholder check with a real command "
@@ -149,9 +178,11 @@ def cmd_contract(args):
print("contract invalid" if errs else "contract ok: %s" % p)
return 1 if errs else 0
if sub == "waive":
reason = " ".join(args[1:]).strip()
rest = list(args[1:])
waived_check = _pop_opt(rest, "--check")
reason = " ".join(rest).strip()
if not reason:
print('usage: sisi contract waive "<reason>"')
print('usage: sisi contract waive [--check ID] "<reason>"')
return 1
import time
project = gitutil.root(os.getcwd()) or os.getcwd()
@@ -159,8 +190,20 @@ def cmd_contract(args):
if gitutil.root(os.getcwd()):
m = gitutil.measure(os.getcwd())
extra = {"head": gitutil.head(os.getcwd()), "lines": m["lines"], "files": m["files"]}
store.append("waivers", store.stamp(dict({"project": project, "reason": reason, "ns": time.time_ns()}, **extra)))
print("waiver recorded for %s" % project)
store.append("waivers", store.stamp(dict({"project": project, "reason": reason, "check": waived_check,
"ns": time.time_ns()}, **extra)))
cp = C.find(os.getcwd())
if cp:
try:
c = C.load(cp)
if isinstance(c, dict):
c.setdefault("deviations", []).append(
{"reason": reason, "check": waived_check, "ts": store.now()})
C.save(cp, c)
except (OSError, ValueError):
pass
print("deviation recorded for %s%s: the unit does not pass; it closes as a deviation "
"and the completion report must say so" % (project, (" (check %s)" % waived_check) if waived_check else ""))
return 0
if sub in ("trust", "untrust"):
p = C.find(os.getcwd())
@@ -188,94 +231,6 @@ def cmd_oracle():
return 0
def _status_retro():
try:
from . import learning as _L
rows = _L.load_learnings()
print("learnings : %d total, %d proposed, %d promoted (`sisi status --learning` for the report)"
% (len(rows), sum(1 for r in rows if r.get("status") == "proposed"),
sum(1 for r in rows if r.get("status") in ("promoted", "monitored"))))
except Exception:
return
def _status_contracts(res):
"""Per recent contract: latest fast run result and the deep state."""
from . import contract as C, deep, verify as V
last = {}
for r in res:
if r.get("run") and r.get("item") in ("check", "invariant", "floor"):
k = (r.get("project"), r.get("contract"))
e = last.setdefault(k, {"ts": "", "fast": {}})
e["ts"] = max(e["ts"], r.get("ts", ""))
if r.get("tier", "fast") == "fast":
e["fast"].setdefault(r["run"], []).append(r["status"])
if not last:
return
print("recent contracts:")
for (project, cid), e in sorted(last.items(), key=lambda kv: kv[1]["ts"], reverse=True)[:5]:
runs = e["fast"]
fast = "-"
if runs:
# runs are keyed by hex timestamp-pid ids: the largest key is the newest
latest = runs[max(runs, key=lambda k: int(k.split("-")[0], 16))]
fast = "pass" if all(x in ("passed", "awaiting-human") for x in latest) else "fail"
dstate = "n/a"
try:
cp = os.path.join(project, C.REL)
c = C.load(cp)
ds = deep.deep_state(c, project, V.tree_fp(project, cp))
dstate = ds["state"] if ds else "none"
except Exception:
dstate = "unknown"
print(" %-24s fast: %-5s deep: %s" % (cid, fast, dstate))
def cmd_status():
from . import store
res = store.read("results")
runs = {}
rungs = {}
for r in res:
if r.get("item") in ("check", "invariant", "floor") and r.get("run"):
runs.setdefault((r.get("project"), r.get("contract"), r["run"]), []).append(r)
if r.get("item") == "check" and r.get("rung"):
rungs[r["rung"]] = rungs.get(r["rung"], 0) + 1
passed = [k for k, v in runs.items() if all(x["status"] in ("passed", "awaiting-human") for x in v)]
verified = {(k[0], k[1]) for k in passed}
unver = sum(1 for r in res if r.get("status") == "unverified")
waivers = len(store.read("waivers"))
print("contracts verified : %d (of %d seen)" % (len(verified), len({(k[0], k[1]) for k in runs})))
print("verify runs : %d, pass rate %s" % (len(runs), "%.0f%%" % (100 * len(passed) / len(runs)) if runs else "n/a"))
tot = sum(rungs.values())
print("checks by rung : " + (", ".join("%d: %.0f%%" % (k, 100 * v / tot) for k, v in sorted(rungs.items())) if tot else "none"))
print("unverified passes : %d" % unver)
print("waivers : %d" % waivers)
try:
from . import overlay
print("always loaded : " + overlay.cost_line())
except Exception:
pass
try:
from . import delivery
print(delivery.median_line())
except Exception:
pass
_status_retro()
_status_contracts(res)
from . import verifiers
vs = [e for e in verifiers.load_verifiers() if e["header"]]
by = {}
for e in vs:
k = e["header"].get("verified", "unset")
by[k] = by.get(k, 0) + 1
print("library : %d verifiers (verified ran %d, docs %d, memory %d%s), %d recipes"
% (len(vs), by.get("ran", 0), by.get("docs", 0), by.get("memory", 0),
"".join(", %s %d" % (k, v) for k, v in sorted(by.items()) if k not in ("ran", "docs", "memory")),
len(verifiers.load_recipes())))
return 0
def cmd_wiring(name, args=()):
from . import wiring
if name == "install" and "--dry-run" in args:
@@ -417,10 +372,11 @@ def main(argv):
from . import risk
return risk.main(args)
if cmd == "status":
return cmd_status()
if cmd == "time":
from . import delivery
return delivery.cmd_time(args)
from . import scorecard
return scorecard.cmd_status(args)
if cmd == "unit":
from . import unit
return unit.cmd_unit(args)
if cmd == "verifiers":
from . import verifiers
return verifiers.main(args)
+252
View File
@@ -36,11 +36,22 @@ def is_unedited_skeleton(c):
return False
REQ_KINDS = ("explicit", "implied", "contextual", "anticipated", "experiential")
REQ_DECISIONS = ("now", "architect", "defer", "ignore")
RISK_PROFILES = ("trivial", "isolated", "logic", "integration", "data", "critical", "release")
UNIT_STATUSES = ("open", "paused", "closed")
def skeleton(goal=None, cwd=None):
name = re.sub(r"[^a-z0-9]+", "-", os.path.basename(os.path.abspath(cwd or os.getcwd())).lower()).strip("-")
from . import store as _store
return {
"id": name or "work",
"parent": None,
"goal": goal or "TODO: one sentence describing the outcome",
"scope": {"in": [], "out": []},
"requirements": [],
"risk": {},
"checks": [{
"id": "c1",
"claim": "PLACEHOLDER (fast tier, runs at the end of every turn, 60 s at most): replace with what this check shows to be true",
@@ -62,6 +73,14 @@ def skeleton(goal=None, cwd=None):
"invariants": [],
"assumptions": [],
"questions": [],
"deferred": [],
"limitations": [],
"plan": [],
"approach": None,
"status": "open",
"started": _store.now(),
"pauses": [],
"deviations": [],
}
@@ -70,6 +89,25 @@ def load(path):
return json.load(f)
def save(path, c):
tmp = path + ".tmp%d" % os.getpid()
with open(tmp, "w", encoding="utf-8") as f:
json.dump(c, f, indent=2)
f.write("\n")
os.replace(tmp, path)
def deferred_checks(c):
"""{check_id: deferred entry} for deferred entries naming a check, by `check` or exactly by `what`."""
out = {}
for d in c.get("deferred", []) if isinstance(c, dict) else []:
if isinstance(d, dict):
cid = d.get("check") or d.get("what")
if isinstance(cid, str) and cid:
out[cid] = d
return out
def floors():
try:
with open(paths.canon("floors.json"), encoding="utf-8") as f:
@@ -132,6 +170,211 @@ def _expect(e, where, errs):
errs.append("%s: unknown expect key %r" % (where, k))
_TRUE_WORDS = {"true", ":", "/bin/true", "/usr/bin/true"}
_PRINT_WORDS = {"echo", "printf"}
_SHELLS = {"sh", "bash", "dash", "zsh", "/bin/sh", "/bin/bash", "/usr/bin/env"}
_WRAPPERS = {"env", "command", "exec", "time", "nohup", "builtin"}
_TESTERS = {"test", "["}
_OPS = {"&&", "||", ";", "|", "&"}
def _lex(s):
import shlex
lx = shlex.shlex(s.replace("\n", " ; "), posix=True, punctuation_chars=True)
lx.whitespace_split = True
lx.commenters = "#"
return list(lx)
def _literal(w):
return not any(ch in w for ch in "$`*?[~{}")
def _constant_true_simple(words, expect, depth=0):
"""True when this one simple command is a constant that exits 0 whatever the project holds."""
while words and (words[0] in _WRAPPERS or (words[0] == "timeout" and len(words) > 2)):
words = words[2:] if words[0] == "timeout" else words[1:]
if not words:
return False
w0, rest = words[0], words[1:]
if w0 in _TRUE_WORDS:
return True
if w0 == "exit":
return not rest or rest == ["0"]
if w0 in _PRINT_WORDS:
out = " ".join(rest)
want = expect.get("stdout_contains")
return want is None or str(want) in out
if w0 in _TESTERS:
ops = rest[:-1] if w0 == "[" and rest[-1:] == ["]"] else rest
if len(ops) == 3 and ops[1] in ("=", "==", "-eq") and all(_literal(x) for x in (ops[0], ops[2])):
return ops[0] == ops[2]
return False
if w0.rsplit("/", 1)[-1] in _SHELLS and depth < 4:
for i, x in enumerate(rest):
if x.startswith("-") and "c" in x[1:] and not x.startswith("--") and i + 1 < len(rest):
return _constant_true(rest[i + 1], expect, depth + 1)
return False
def _split(words, seps):
out, cur = [], []
for w in words:
if w in seps:
out.append(cur)
cur = []
else:
cur.append(w)
out.append(cur)
return out
def _constant_true(cmd, expect, depth=0):
try:
words = _lex(cmd)
except ValueError:
return False
if not words or any(w.startswith(("<", ">")) or w in ("<<", ">>") for w in words):
return False # a redirection reads or writes something: it can fail
alts = _split(words, {"||"})
def chain(ws):
seqs = [q for q in _split(ws, {";", "&&", "&"}) if q]
for seq in seqs:
stages = _split(seq, {"|"})
if not stages[-1] or not _constant_true_simple(stages[-1], expect, depth):
return False
return bool(seqs)
return chain(alts[0]) or (len(alts) > 1 and chain(alts[-1]))
def vacuous_reason(ch):
"""Why this check cannot fail, or None. The commands that exit 0 whatever the project
holds: `true`, `:`, `exit 0`, `echo`/`printf` that already prints what is expected,
`test 1 = 1`, any of them inside `sh -c`, joined with `;` or `&&`, or after `||` (so
`anything || true`). A floor, not a proof: no analysis can catch every constant."""
cmd = ch.get("cmd")
if not isinstance(cmd, str):
return None
expect = ch.get("expect") if isinstance(ch.get("expect"), dict) else {}
if expect.get("exit", 0) != 0:
return None
if not _constant_true(cmd.strip(), expect):
return None
return "vacuous check: %r cannot fail; write a command that can" % cmd.strip()
def _check_new_fields(ch, w, errs):
if "covers" in ch and not _str(ch["covers"]):
errs.append(w + ": covers must be a non-empty string")
if "when_changed" in ch:
wc = ch["when_changed"]
if not isinstance(wc, list) or not wc or not all(_str(x) for x in wc):
errs.append(w + ": when_changed must be a non-empty list of path patterns")
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))
def _validate_new_top(c, ids, errs):
if "parent" in c and c["parent"] is not None and not _str(c["parent"]):
errs.append("parent must be a non-empty string or null")
if "status" in c and c["status"] not in UNIT_STATUSES:
errs.append("status must be one of %s" % ", ".join(UNIT_STATUSES))
if "started" in c and not _str(c["started"]):
errs.append("started must be a non-empty string")
if "scope" in c:
sc = c["scope"]
if not isinstance(sc, dict):
errs.append("scope must be an object with in/out lists")
else:
for k in sc:
if k not in ("in", "out"):
errs.append("scope: unknown key %r" % k)
for k in ("in", "out"):
if k in sc and (not isinstance(sc[k], list) or not all(isinstance(x, str) for x in sc[k])):
errs.append("scope.%s must be a list of strings" % k)
if "requirements" in c:
rq = c["requirements"]
if not isinstance(rq, list):
errs.append("requirements must be a list")
else:
seen = set()
for i, r in enumerate(rq):
w = "requirements[%d]" % i
if not isinstance(r, dict):
errs.append(w + " must be an object"); continue
if not _str(r.get("id")):
errs.append(w + ".id must be a non-empty string")
elif r["id"] in seen:
errs.append("duplicate requirement id %r" % r["id"])
else:
seen.add(r["id"]); w = "requirement %r" % r["id"]
if r.get("kind") not in REQ_KINDS:
errs.append("%s: kind must be one of %s" % (w, ", ".join(REQ_KINDS)))
if not _str(r.get("text")):
errs.append(w + ": text must be a non-empty string")
if r.get("decision") not in REQ_DECISIONS:
errs.append("%s: decision must be one of %s" % (w, ", ".join(REQ_DECISIONS)))
if "why" in r and not _str(r["why"]):
errs.append(w + ": why must be a non-empty string")
if "check" in r and r["check"] is not None:
if not _str(r["check"]):
errs.append(w + ": check must be a check id or null")
elif ids and r["check"] not in ids:
errs.append("%s: check %r is not a check or invariant id" % (w, r["check"]))
if "added" in r and not _str(r["added"]):
errs.append(w + ": added must be a non-empty string")
if "risk" in c:
rk = c["risk"]
if not isinstance(rk, dict):
errs.append("risk must be an object")
else:
if "profile" in rk and rk["profile"] not in RISK_PROFILES:
errs.append("risk.profile must be one of %s" % ", ".join(RISK_PROFILES))
for k in ("why", "blast_radius", "rollback"):
if k in rk and not _str(rk[k]):
errs.append("risk.%s must be a non-empty string" % k)
if "deferred" in c:
df = c["deferred"]
if not isinstance(df, list):
errs.append("deferred must be a list")
else:
for i, d in enumerate(df):
w = "deferred[%d]" % i
if not isinstance(d, dict):
errs.append(w + " must be an object"); continue
for k in ("what", "why", "safe_because"):
if not _str(d.get(k)):
errs.append("%s.%s must be a non-empty string" % (w, k))
if "check" in d and d["check"] is not None and not _str(d["check"]):
errs.append(w + ": check must be a check id or null")
if "approach" in c and c["approach"] is not None:
ap = c["approach"]
if not isinstance(ap, dict):
errs.append("approach must be an object")
else:
for k in ap:
if k not in ("chosen", "why", "alternatives", "reuses"):
errs.append("approach: unknown key %r" % k)
for k in ("chosen", "why"):
if k in ap and not _str(ap[k]):
errs.append("approach.%s must be a non-empty string" % k)
for k in ("alternatives", "reuses"):
if k in ap and (not isinstance(ap[k], list) or not all(_str(x) for x in ap[k])):
errs.append("approach.%s must be a list of non-empty strings" % k)
if "limitations" in c:
if not isinstance(c["limitations"], list) or not all(isinstance(x, str) for x in c["limitations"]):
errs.append("limitations must be a list of strings")
if "plan" in c:
if not isinstance(c["plan"], list) or not all(isinstance(x, (str, dict)) for x in c["plan"]):
errs.append("plan must be a list of steps (strings or objects)")
if "pauses" in c and not isinstance(c["pauses"], list):
errs.append("pauses must be a list")
if "deviations" in c and not isinstance(c["deviations"], list):
errs.append("deviations must be a list")
def validate(c):
"""Return a list of error strings; empty means valid."""
errs = []
@@ -179,6 +422,10 @@ def validate(c):
_tier(ch, w, errs)
if "serial" in ch and not isinstance(ch["serial"], bool):
errs.append(w + ": serial must be true or false")
_check_new_fields(ch, w, errs)
vr = vacuous_reason(ch)
if vr:
errs.append("%s: %s" % (w, vr))
inv = c.get("invariants", [])
if not isinstance(inv, list):
errs.append("invariants must be a list")
@@ -205,6 +452,10 @@ def validate(c):
_tier(iv, w, errs)
if "serial" in iv and not isinstance(iv["serial"], bool):
errs.append(w + ": serial must be true or false")
_check_new_fields(iv, w, errs)
vr = vacuous_reason(iv)
if vr:
errs.append("%s: %s" % (w, vr))
runnable = any(isinstance(x, dict) and x.get("rung") in (1, 2, 3, 4) and x.get("cmd") for x in checks) or \
any(isinstance(x, dict) and x.get("cmd") for x in inv)
if checks and not runnable:
@@ -220,6 +471,7 @@ def validate(c):
for i, x in enumerate(q):
if not (isinstance(x, dict) and _str(x.get("q")) and "default" in x):
errs.append("questions[%d] needs q and default" % i)
_validate_new_top(c, ids, errs)
return errs
+2 -2
View File
@@ -93,7 +93,7 @@ def save_state(project, contract_id, fp, results, deep_ids):
items = [{"id": r["id"], "status": r["status"], "tail": (r.get("tail") or "")[-1500:]}
for r in results if r.get("tier") == "deep"]
st = {"contract": contract_id, "fp": fp, "epoch": time.time(), "ids": sorted(deep_ids),
"ok": all(i["status"] in ("passed", "awaiting-human") for i in items), "items": items}
"ok": all(i["status"] in ("passed", "skipped", "not-applicable") for i in items), "items": items}
p = _state_path(project)
os.makedirs(os.path.dirname(p), exist_ok=True)
tmp = p + ".tmp%d" % os.getpid()
@@ -123,7 +123,7 @@ def deep_state(c, project, fp):
st = load_state(project)
if st is not None and st.get("ids") == ids:
base.update(epoch=st.get("epoch"), fresh=fp is not None and st.get("fp") == fp,
failed=[i for i in st["items"] if i["status"] not in ("passed", "awaiting-human")])
failed=[i for i in st["items"] if i["status"] in ("failed", "not-run")])
else:
st = None
if lock:
+2 -141
View File
@@ -1,4 +1,5 @@
"""Time to delivery: how long from the human's request to a verified stop, recorded by the gate and read by `sisi time`.
"""Time to delivery: how long from the human's request to a verified stop, recorded by the gate
and read back as unit telemetry when a unit closes (see sisi.unit; `sisi status` is the one report).
Delivery row (deliveries.jsonl in the state dir): session, project, start, end (ISO UTC), seconds, send_backs (times the
gate sent the agent back during this request), check_s (seconds spent running checks during this request), contract
@@ -93,143 +94,3 @@ def record(payload, sess, sid, cwd, now=None):
except Exception as e:
store.log_error("delivery", e)
return None
# ---------------------------------------------------------------- reading: `sisi time`
DAY = 86400.0
def median(xs):
s = sorted(xs)
n = len(s)
if not n:
return None
return s[n // 2] if n % 2 else (s[n // 2 - 1] + s[n // 2]) / 2.0
def percentile(xs, p):
"""Linear-interpolation percentile (p in 0..100) of a list of numbers; None when empty."""
s = sorted(xs)
if not s:
return None
k = (len(s) - 1) * p / 100.0
lo = int(k)
hi = min(lo + 1, len(s) - 1)
return s[lo] + (s[hi] - s[lo]) * (k - lo)
def _epoch(ts):
from . import harvest
return harvest.epoch(ts) if isinstance(ts, str) else None
def summarize(rows):
secs = [r["seconds"] for r in rows]
tot = sum(secs)
chk = sum(min(r.get("check_s", 0.0), r["seconds"]) for r in rows)
return {"n": len(rows), "median_s": median(secs), "p90_s": percentile(secs, 90),
"check_share": (chk / tot) if tot > 0 else None,
"send_back_deliveries": sum(1 for r in rows if r.get("send_backs", 0) > 0)}
def windows(rows, now):
"""(last 7 days, the 7 days before) of delivery rows, by their end time."""
cur, prev = [], []
for r in rows:
if not (isinstance(r, dict) and isinstance(r.get("seconds"), (int, float))):
continue
t = _epoch(r.get("end") or r.get("ts"))
if t is None:
continue
if now - 7 * DAY <= t <= now:
cur.append(r)
elif now - 14 * DAY <= t < now - 7 * DAY:
prev.append(r)
return cur, prev
def slow_checks(results, now, top=5):
"""The slowest checks by mean duration over the last 7 days, each with a suggestion."""
from . import scoreboard
recent = [r for r in results if isinstance(r, dict) and (_epoch(r.get("ts")) or 0) >= now - 7 * DAY]
out = []
for s in scoreboard.check_stats(recent)["checks"]:
if s.get("timed_runs"):
out.append({"id": s["id"], "mean_s": s["total_s"] / s["timed_runs"], "runs": s["runs"], "tier": s.get("tier", "fast")})
out.sort(key=lambda x: -x["mean_s"])
out = out[:top]
for x in out:
if x["mean_s"] < 5:
x["suggestion"] = "quick enough: leave it in the fast tier"
elif x["tier"] == "deep":
x["suggestion"] = "already deep; split it so a quick part can run in the gate"
else:
x["suggestion"] = 'mark as "tier": "deep" if it can wait, or split it into a quick part and a slow part'
return out
def report(now=None):
now = time.time() if now is None else now
rows = store.read("deliveries")
cur, prev = windows(rows, now)
by_project = {}
for label, group in (("cur", cur), ("prev", prev)):
for r in group:
by_project.setdefault(r.get("project") or "(unknown)", {"cur": [], "prev": []})[label].append(r)
return {"now": _iso(now), "all": {"last7": summarize(cur), "prev7": summarize(prev)},
"projects": {p: {"last7": summarize(v["cur"]), "prev7": summarize(v["prev"])} for p, v in sorted(by_project.items())},
"slowest_checks": slow_checks(store.read("results"), now)}
def fmt_s(s):
if s is None:
return "-"
s = int(round(s))
if s < 60:
return "%ds" % s
if s < 3600:
return "%dm%02ds" % (s // 60, s % 60)
return "%dh%02dm" % (s // 3600, (s % 3600) // 60)
def _cell(s):
return "median %s, p90 %s (%d)" % (fmt_s(s["median_s"]), fmt_s(s["p90_s"]), s["n"]) if s["n"] else "none"
def median_line(now=None):
"""One line for `sisi status`."""
cur = report(now)["all"]["last7"]
if not cur["n"]:
return "time to delivery : no deliveries recorded in the last 7 days"
return "time to delivery : median %s over the last 7 days (%d deliveries)" % (fmt_s(cur["median_s"]), cur["n"])
def cmd_time(args, out=print):
r = report()
if "--json" in args:
out(json.dumps(r, indent=2))
return 0
a = r["all"]
if not a["last7"]["n"] and not a["prev7"]["n"]:
out("sisi time: no deliveries recorded in the last 14 days. The end-of-turn gate records one each time it lets "
"a turn end; check that the gate is installed (`sisi doctor`).")
else:
out("time from the human's request to a verified stop")
out("%-28s %-34s %s" % ("", "last 7 days", "the 7 days before"))
out("%-28s %-34s %s" % ("all projects", _cell(a["last7"]), _cell(a["prev7"])))
for p, v in r["projects"].items():
out("%-28s %-34s %s" % (os.path.basename(p.rstrip("/"))[:28] or p, _cell(v["last7"]), _cell(v["prev7"])))
c = a["last7"]
if c["n"]:
out("")
out("share of that time spent running checks: %s" % ("%.0f%%" % (100 * c["check_share"]) if c["check_share"] is not None else "-"))
out("deliveries that needed a send-back: %d of %d" % (c["send_back_deliveries"], c["n"]))
out("")
if r["slowest_checks"]:
out("slowest checks (mean run time, last 7 days)")
for x in r["slowest_checks"]:
out(" %-30s %8s over %d runs [%s]\n -> %s" % (x["id"][:30], fmt_s(x["mean_s"]), x["runs"], x["tier"], x["suggestion"]))
else:
out("slowest checks: no check runs recorded in the last 7 days")
return 0
-89
View File
@@ -1,89 +0,0 @@
"""Escape candidates: work declared verified (or finished) that then turned out wrong. Evidence pointers only.
Kinds
contract-then-correction a contract run passed (every check passed or awaits a human) in a session, and a
correction-like user message came later in that session.
contract-then-fix-session a contract run passed in a session; within 7 days a later main session in the same
repo touched at least one of the same files (by following commits) and opened with a
fix-like request.
premature-done independent of sisi records: an assistant turn ended on a completion claim and the
very next typed user message was correction-like.
Results join to sessions by the `session` field when present, otherwise by time and project: a session whose
window contains the run and whose cwd or repo is inside the run's project. If more than one session fits, the
candidate is marked `ambiguous`. These are candidates for a human or a model to look at, not conclusions.
"""
import json, re
from . import harvest, store
WEEK_S = 7 * 86400
_FIXLIKE = re.compile(r"\b(fix|bug|broken|wrong|regress|revert|fails?|failing|doesn'?t work|not working|error|crash)", re.I)
def passed_runs(results):
"""[{ts, t, project, contract, session, run}] for runs whose checks all passed."""
groups = {}
for r in results:
if not isinstance(r, dict) or r.get("check") == "gate":
continue
key = r.get("run") or "%s|%s|%s" % (r.get("ts"), r.get("contract"), r.get("project"))
groups.setdefault(key, []).append(r)
out = []
for key, rs in groups.items():
if all(x.get("status") in ("passed", "awaiting-human") for x in rs) and any(x.get("status") == "passed" for x in rs):
t = harvest.epoch(rs[0].get("ts") or "")
if t is not None:
out.append({"ts": rs[0]["ts"], "t": t, "project": rs[0].get("project"), "contract": rs[0].get("contract"),
"session": rs[0].get("session"), "run": key})
return sorted(out, key=lambda x: x["t"])
def _inside(path, parent):
if not path or not parent:
return False
p, q = path.rstrip("/"), parent.rstrip("/")
return p == q or p.startswith(q + "/") or q.startswith(p + "/")
def attribute(run, sessions):
"""Sessions (rows) the run can be attributed to: by session id when it names one, else by time and project."""
if run["session"]:
hit = [s for s in sessions if s["id"] == run["session"]]
if hit:
return hit, False
hit = [s for s in sessions if s["t0"] is not None and s["t0"] <= run["t"] <= (s["t1"] or s["t0"]) + 60
and (_inside(s["cwd"], run["project"]) or _inside(s["repo_root"], run["project"]))]
return hit, len(hit) > 1
def find(con, results=None):
results = store.read("results") if results is None else results
sessions = [dict(r) for r in con.execute(
"SELECT s.id, s.cwd, s.t0, s.t1, s.first_message, s.machine, g.repo_root, g.files, g.start_kind "
"FROM sessions s LEFT JOIN groundtruth g ON g.session_id=s.id WHERE s.kind='main'")]
out = []
for run in passed_runs(results):
hit, ambiguous = attribute(run, sessions)
for s in hit:
later = con.execute("SELECT idx, ts, t FROM user_msgs WHERE session_id=? AND correction=1 AND t>? ORDER BY t",
(s["id"], run["t"])).fetchall()
for m in later[:3]:
out.append({"kind": "contract-then-correction", "session": s["id"], "run": run["run"], "contract": run["contract"],
"passed_at": run["ts"], "evidence": {"user_msg_idx": m["idx"], "at": m["ts"]}, "ambiguous": ambiguous})
files = set(json.loads(s["files"] or "[]"))
if files and s["repo_root"]:
for o in sessions:
if o["id"] == s["id"] or o["repo_root"] != s["repo_root"] or o["machine"] or o["t0"] is None:
continue
if not (run["t"] < o["t0"] <= run["t"] + WEEK_S):
continue
common = files & set(json.loads(o["files"] or "[]"))
if common and _FIXLIKE.search((o["first_message"] or "")[:1500]):
out.append({"kind": "contract-then-fix-session", "session": s["id"], "run": run["run"],
"contract": run["contract"], "passed_at": run["ts"],
"evidence": {"later_session": o["id"], "common_files": sorted(common)[:10]},
"ambiguous": ambiguous})
for r in con.execute("SELECT m.session_id, m.idx, m.ts FROM user_msgs m WHERE m.correction=1 AND m.after_completion=1 ORDER BY m.t"):
out.append({"kind": "premature-done", "session": r["session_id"], "evidence": {"user_msg_idx": r["idx"], "at": r["ts"]},
"ambiguous": False})
return out
+11 -2
View File
@@ -641,6 +641,14 @@ def _decide(payload):
if c is not None and C.is_unedited_skeleton(c):
path = 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
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
@@ -765,7 +773,8 @@ def _decide(payload):
"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",))
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):
@@ -811,7 +820,7 @@ def _decide(payload):
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", "timeout"))
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
+12 -5
View File
@@ -25,12 +25,19 @@ def head(cwd):
return out.strip() if rc == 0 else None
_EXCLUDE = ":(exclude).sisi" # sisi's own records are never part of the work being measured
def _is_sisi(rel):
return rel == ".sisi" or rel.startswith(".sisi/")
def measure(cwd, base=None, max_untracked=200):
"""Return {'lines': n, 'files': [paths]} for the working tree vs `base` (default HEAD)."""
cwd = root(cwd) or cwd
base = base or head(cwd) or EMPTY_TREE
lines, files = 0, set()
rc, out = _git(cwd, "diff", "--numstat", base, timeout=10)
rc, out = _git(cwd, "diff", "--numstat", base, "--", ".", _EXCLUDE, timeout=10)
if rc == 0:
for ln in out.splitlines():
parts = ln.split("\t", 2)
@@ -44,7 +51,7 @@ def measure(cwd, base=None, max_untracked=200):
rc, out = _git(cwd, "ls-files", "--others", "--exclude-standard", timeout=10)
if rc == 0:
top = cwd
for rel in out.splitlines()[:max_untracked]:
for rel in [r for r in out.splitlines() if not _is_sisi(r)][:max_untracked]:
files.add(rel)
try:
fp = os.path.join(top, rel)
@@ -100,13 +107,13 @@ def fingerprint(cwd, extra_files=()):
h = hashlib.sha1()
base = head(top) or EMPTY_TREE
h.update(base.encode())
p = subprocess.run(["git", "diff", "--no-ext-diff", "--no-textconv", "--no-color", base], cwd=top,
capture_output=True, timeout=10)
p = subprocess.run(["git", "diff", "--no-ext-diff", "--no-textconv", "--no-color", base, "--", ".", _EXCLUDE],
cwd=top, capture_output=True, timeout=10)
h.update(b"\0diff\0" + p.stdout)
p = subprocess.run(["git", "ls-files", "--others", "--exclude-standard", "-z"], cwd=top,
capture_output=True, timeout=10)
for rel in p.stdout.split(b"\0")[:2000]:
if not rel:
if not rel or _is_sisi(os.fsdecode(rel)):
continue
try:
st = os.stat(os.path.join(top, os.fsdecode(rel)))
+84
View File
@@ -226,6 +226,90 @@ def machine_reason(text, origin_kind=None, entrypoint=None):
return bool(reasons), ";".join(reasons)
# ---------------------------------------------------------------- transcript usage (telemetry)
_USAGE_KEYS = (("input", ("input_tokens", "inputTokens")),
("output", ("output_tokens", "outputTokens")),
("cache_read", ("cache_read_input_tokens", "cacheReadInputTokens", "cached_input_tokens")),
("cache_creation", ("cache_creation_input_tokens", "cacheCreationInputTokens")))
_QUESTION_TOOLS = {"AskUserQuestion", "request_user_input", "ask_user_question"}
def transcript_stats(path, t0=None, t1=None):
"""Token usage and human-attention counts from one Claude-Code-shaped transcript, or None
when the file cannot be read. `usage` is None when no record carried any usage numbers:
a caller must report tokens as unavailable then, never as zero. Timestamps bound the
window in epoch seconds when given. Streams the file; malformed lines are skipped."""
try:
f = open(os.path.expanduser(path), "rb")
except (OSError, TypeError):
return None
by_model, by_cat = {}, {}
human, corrections, dialogs, subagents, first = 0, 0, 0, 0, True
with f:
for raw in f:
try:
if b"usage" not in raw and b"user" not in raw and b"tool_use" not in raw \
and b"queued_command" not in raw:
continue
d = json.loads(raw)
if not isinstance(d, dict):
continue
ts = epoch(d["timestamp"]) if isinstance(d.get("timestamp"), str) else None
outside = ts is not None and ((t0 is not None and ts < t0) or (t1 is not None and ts > t1))
typ = d.get("type")
if outside and typ != "user":
continue
if typ == "assistant":
m = d.get("message") or {}
u = m.get("usage") if isinstance(m, dict) else None
if isinstance(u, dict):
model = m.get("model") if isinstance(m.get("model"), str) and not m["model"].startswith("<") else "(unknown)"
got = {}
for cat, keys in _USAGE_KEYS:
for k in keys:
if isinstance(u.get(k), (int, float)) and not isinstance(u.get(k), bool):
got[cat] = int(u[k]); break
if got:
slot = by_model.setdefault(model, {})
for cat, v in got.items():
by_cat[cat] = by_cat.get(cat, 0) + v
slot[cat] = slot.get(cat, 0) + v
content = m.get("content") if isinstance(m, dict) else None
for b in content if isinstance(content, list) else ():
if isinstance(b, dict) and b.get("type") == "tool_use":
if b.get("name") in _QUESTION_TOOLS:
dialogs += 1
if b.get("name") in ("Agent", "Task"):
subagents += 1
elif typ == "user":
text = typed_text(d)[0]
if text is not None:
# the transcript's first typed message is a request, never a correction,
# whether or not it falls inside the window
if not outside:
if not first and is_correction(text):
corrections += 1
human += 1
first = False
elif typ == "attachment":
a = d.get("attachment") or {}
if a.get("type") == "queued_command" and a.get("commandMode") == "prompt" and not a.get("isMeta"):
if typed_text(a, queued_prompt=a.get("prompt"))[0] is not None:
human += 1
except Exception:
continue
for slot in by_model.values():
slot["total"] = sum(v for k, v in slot.items())
if by_cat:
by_cat_out = dict(by_cat, total=sum(by_cat.values()))
usage = {"by_category": by_cat_out, "by_model": by_model}
else:
usage = None
return {"usage": usage, "human_messages": human, "corrections": corrections,
"question_dialogs": dialogs, "subagent_runs": subagents}
# ---------------------------------------------------------------- source interface
class Source:
+7 -28
View File
@@ -1,4 +1,4 @@
"""Commands for the data layer of the learning loop: harvest, tasks, escapes, checks, scoreboard.
"""Commands for the data layer of the learning loop: harvest, tasks, escapes, checks.
Usable now as `python3 -m sisi.learn_cli <cmd>`. The main CLI hooks them in with
`learn_cli.register(subparsers)`; each command sets `func(args) -> exit code` on its parser.
@@ -69,8 +69,8 @@ def cmd_tasks(args):
def cmd_escapes(args):
from . import escapes, harvest
rows = escapes.find(harvest.connect())
from . import harvest, scorecard
rows = scorecard.escape_candidates(harvest.connect())
if args.json:
print(json.dumps(rows))
return 0
@@ -84,37 +84,21 @@ def cmd_escapes(args):
def cmd_checks(args):
from . import scoreboard
st = scoreboard.check_stats(store.read("results"))
from . import scorecard
st = scorecard.check_stats(store.read("results"))
if args.json:
print(json.dumps(st))
return 0
for title, key in (("check", "checks"), ("verifier", "verifiers")):
if not st[key]:
continue
print("%-40s %5s %5s %5s" % (title, "runs", "fail", "tmo"))
print("%-40s %5s %5s %5s" % (title, "runs", "fail", "not run"))
for s in st[key]:
print("%-40s %5d %5d %5d%s" % (s["id"][:40], s["runs"], s["failures"], s["timeouts"],
print("%-40s %5d %5d %5d%s" % (s["id"][:40], s["runs"], s["failures"], s["not_run"],
" never seen failing" if s["never_seen_failing"] else ""))
return 0
def cmd_scoreboard(args):
from . import scoreboard
sb = scoreboard.scoreboard(_con())
if args.json:
print(json.dumps(sb))
return 0
cols = ("sessions", "turns_per_session", "corrections_per_100", "questions_per_100", "contract_share", "premature_done_share")
for title, key in (("week", "weeks"), ("repo", "repos")):
print("%-18s %s" % (title, " ".join("%-12s" % c[:12] for c in cols)))
for k, v in sb[key].items():
print("%-18s %s" % (k[:18], " ".join("%-12s" % ("-" if v[c] is None else v[c]) for c in cols)))
print()
print("tasks:", json.dumps(sb["tasks"]))
return 0
def register(subparsers):
p = subparsers.add_parser("harvest", help="read agent transcripts into the harvest database (incremental)")
p.add_argument("--workers", type=int, default=None)
@@ -146,11 +130,6 @@ def register(subparsers):
p.add_argument("--json", action="store_true")
p.set_defaults(func=cmd_checks)
p = subparsers.add_parser("scoreboard", help="weekly and per-repo trends from harvested sessions")
p.add_argument("--json", action="store_true")
p.set_defaults(func=cmd_scoreboard)
def main(argv=None):
ap = argparse.ArgumentParser(prog="sisi")
register(ap.add_subparsers(dest="cmd", required=True))
-100
View File
@@ -1,100 +0,0 @@
"""Check statistics and the scoreboard.
Check statistics (from results.jsonl): per check id, and per verifier when records carry a `verifier` field:
runs, failures, timeouts. A check with MANY_RUNS or more runs and no failure or timeout is flagged
"never seen failing" (it may be a check that cannot fail). The `gate` pseudo-check is skipped.
Scoreboard: ISO weeks (Monday start, UTC) and repo, from the harvested main sessions that a human started
(first typed message not machine-written). Trends matter, so every week uses the same definitions:
sessions human-started main sessions whose first message falls in the week
turns_per_session typed user turns per session
corrections_per_100 correction-like typed messages per 100 typed turns (the first message never counts)
questions_per_100 assistant turns that ended on a question with no tool call, plus AskUserQuestion calls,
per 100 typed turns
contract_share share of sessions that used `sisi contract`/`sisi verify`
premature_done_share among sessions with at least one completion claim, the share where a claim was
immediately followed by a correction-like message (a claim can only be "followed" by
a correction if the session went on, so this is not "sessions ending on a claim")
Only weeks and repos with at least one session appear. Completion claims, questions and corrections are
regex heuristics; compare week with week, not with an absolute truth.
"""
import datetime, json, time
from . import harvest, store, taskset
MANY_RUNS = 10
def check_stats(results):
by, byv = {}, {}
for r in results:
if not isinstance(r, dict) or not r.get("check") or r.get("check") == "gate":
continue
keys = [("check", r["check"], by)]
if r.get("verifier"):
keys.append(("verifier", r["verifier"], byv))
for _, k, d in keys:
s = d.setdefault(k, {"runs": 0, "failures": 0, "timeouts": 0, "total_s": 0.0, "timed_runs": 0})
s["runs"] += 1
if isinstance(r.get("duration_s"), (int, float)) and not isinstance(r.get("duration_s"), bool):
s["total_s"] += r["duration_s"] # for `sisi time`: which checks cost the most
s["timed_runs"] += 1
s["tier"] = r.get("tier", "fast")
if r.get("status") == "failed":
s["failures"] += 1
elif r.get("status") == "timeout":
s["timeouts"] += 1
def fin(d):
out = []
for k, s in sorted(d.items()):
s = dict(s, id=k)
s["never_seen_failing"] = s["runs"] >= MANY_RUNS and s["failures"] == 0 and s["timeouts"] == 0
out.append(s)
return out
return {"checks": fin(by), "verifiers": fin(byv)}
def iso_week(t):
d = datetime.datetime.fromtimestamp(t, datetime.timezone.utc).date()
y, w, _ = d.isocalendar()
return "%04d-W%02d" % (y, w)
def _blank():
return {"sessions": 0, "turns": 0, "corrections": 0, "questions": 0, "contract": 0, "claim_sessions": 0, "premature_sessions": 0}
def _finish(a):
n, t = a["sessions"], a["turns"]
return {"sessions": n, "turns_per_session": round(t / n, 2) if n else None,
"corrections_per_100": round(100.0 * a["corrections"] / t, 1) if t else None,
"questions_per_100": round(100.0 * a["questions"] / t, 1) if t else None,
"contract_share": round(a["contract"] / n, 3) if n else None,
"premature_done_share": round(a["premature_sessions"] / a["claim_sessions"], 3) if a["claim_sessions"] else None}
def _add(a, r):
a["sessions"] += 1
a["turns"] += r["user_turns"]
a["corrections"] += r["n_corrections"]
a["questions"] += r["n_question_turns"] + r["n_ask"]
a["contract"] += 1 if (r["used_contract"] or r["used_verify"]) else 0
if r["n_completion_claims"]:
a["claim_sessions"] += 1
a["premature_sessions"] += 1 if r["n_premature_done"] else 0
def scoreboard(con):
weeks, repos, wr = {}, {}, {}
q = ("SELECT s.t0, s.user_turns, s.n_corrections, s.n_question_turns, s.n_ask, s.used_contract, s.used_verify, "
"s.n_completion_claims, s.n_premature_done, g.repo_root FROM sessions s LEFT JOIN groundtruth g ON g.session_id=s.id "
"WHERE s.kind='main' AND s.machine=0 AND s.t0 IS NOT NULL")
for r in con.execute(q):
repo = (r["repo_root"] or "(no repo)").rstrip("/").rsplit("/", 1)[-1]
week = iso_week(r["t0"])
for table, key in ((weeks, week), (repos, repo), (wr, (week, repo))):
_add(table.setdefault(key, _blank()), r)
return {"weeks": {k: _finish(v) for k, v in sorted(weeks.items())},
"repos": {k: _finish(v) for k, v in sorted(repos.items())},
"week_repo": {"%s %s" % k: _finish(v) for k, v in sorted(wr.items())},
"tasks": taskset.counts(con)}
+392
View File
@@ -0,0 +1,392 @@
"""The per-unit scorecard (eight dimensions, every value classed) and `sisi status`.
Every scorecard value is {"value": ..., "class": measured|inferred|estimated|unavailable}.
Missing data is unavailable with value None: never zero, never good. No single score is
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
from . import harvest, store
CLASSES = ("measured", "inferred", "estimated", "unavailable")
def val(v, cls):
assert cls in CLASSES
return {"value": v, "class": cls}
def unavailable():
return {"value": None, "class": "unavailable"}
# ---------------------------------------------------------------- check statistics
MANY_RUNS = 10
# rows written by earlier versions: neither of these ever meant a pass
_LEGACY = {"timeout": "not-run", "awaiting-human": "not-run"}
def norm_status(s):
return _LEGACY.get(s, s)
def check_stats(results):
by, byv = {}, {}
for r in results:
if not isinstance(r, dict) or not r.get("check") or r.get("check") == "gate":
continue
keys = [("check", r["check"], by)]
if r.get("verifier"):
keys.append(("verifier", r["verifier"], byv))
for _, k, d in keys:
s = d.setdefault(k, {"runs": 0, "failures": 0, "not_run": 0,
"total_s": 0.0, "timed_runs": 0})
s["runs"] += 1
if isinstance(r.get("duration_s"), (int, float)) and not isinstance(r.get("duration_s"), bool):
s["total_s"] += r["duration_s"]
s["timed_runs"] += 1
s["tier"] = r.get("tier", "fast")
st = norm_status(r.get("status"))
if st == "failed":
s["failures"] += 1
elif st == "not-run":
s["not_run"] += 1
def fin(d):
out = []
for k, s in sorted(d.items()):
s = dict(s, id=k)
s["never_seen_failing"] = s["runs"] >= MANY_RUNS and s["failures"] == 0 and s["not_run"] == 0
out.append(s)
return out
return {"checks": fin(by), "verifiers": fin(byv)}
# ---------------------------------------------------------------- escape candidates
WEEK_S = 7 * 86400
_FIXLIKE = re.compile(r"\b(fix|bug|broken|wrong|regress|revert|fails?|failing|doesn'?t work|not working|error|crash)", re.I)
def passed_runs(results):
"""[{ts, t, project, contract, session, run}] for runs with a real pass and no failure.
A run of only skipped/not-run checks is not a pass: nothing that did not run passed."""
groups = {}
for r in results:
if not isinstance(r, dict) or r.get("check") == "gate":
continue
key = r.get("run") or "%s|%s|%s" % (r.get("ts"), r.get("contract"), r.get("project"))
groups.setdefault(key, []).append(r)
out = []
for key, rs in groups.items():
sts = [norm_status(x.get("status")) for x in rs]
if any(s == "passed" for s in sts) and all(s in ("passed", "skipped", "not-applicable") for s in sts):
t = harvest.epoch(rs[0].get("ts") or "")
if t is not None:
out.append({"ts": rs[0]["ts"], "t": t, "project": rs[0].get("project"), "contract": rs[0].get("contract"),
"session": rs[0].get("session"), "run": key})
return sorted(out, key=lambda x: x["t"])
def _inside(path, parent):
if not path or not parent:
return False
p, q = path.rstrip("/"), parent.rstrip("/")
return p == q or p.startswith(q + "/") or q.startswith(p + "/")
def attribute(run, sessions):
if run["session"]:
hit = [s for s in sessions if s["id"] == run["session"]]
if hit:
return hit, False
hit = [s for s in sessions if s["t0"] is not None and s["t0"] <= run["t"] <= (s["t1"] or s["t0"]) + 60
and (_inside(s["cwd"], run["project"]) or _inside(s["repo_root"], run["project"]))]
return hit, len(hit) > 1
def escape_candidates(con, results=None):
results = store.read("results") if results is None else results
sessions = [dict(r) for r in con.execute(
"SELECT s.id, s.cwd, s.t0, s.t1, s.first_message, s.machine, g.repo_root, g.files, g.start_kind "
"FROM sessions s LEFT JOIN groundtruth g ON g.session_id=s.id WHERE s.kind='main'")]
out = []
for run in passed_runs(results):
hit, ambiguous = attribute(run, sessions)
for s in hit:
later = con.execute("SELECT idx, ts, t FROM user_msgs WHERE session_id=? AND correction=1 AND t>? ORDER BY t",
(s["id"], run["t"])).fetchall()
for m in later[:3]:
out.append({"kind": "contract-then-correction", "session": s["id"], "run": run["run"], "contract": run["contract"],
"passed_at": run["ts"], "evidence": {"user_msg_idx": m["idx"], "at": m["ts"]}, "ambiguous": ambiguous})
files = set(json.loads(s["files"] or "[]"))
if files and s["repo_root"]:
for o in sessions:
if o["id"] == s["id"] or o["repo_root"] != s["repo_root"] or o["machine"] or o["t0"] is None:
continue
if not (run["t"] < o["t0"] <= run["t"] + WEEK_S):
continue
common = files & set(json.loads(o["files"] or "[]"))
if common and _FIXLIKE.search((o["first_message"] or "")[:1500]):
out.append({"kind": "contract-then-fix-session", "session": s["id"], "run": run["run"],
"contract": run["contract"], "passed_at": run["ts"],
"evidence": {"later_session": o["id"], "common_files": sorted(common)[:10]},
"ambiguous": ambiguous})
for r in con.execute("SELECT m.session_id, m.idx, m.ts FROM user_msgs m WHERE m.correction=1 AND m.after_completion=1 ORDER BY m.t"):
out.append({"kind": "premature-done", "session": r["session_id"], "evidence": {"user_msg_idx": r["idx"], "at": r["ts"]},
"ambiguous": False})
return out
# ---------------------------------------------------------------- the eight dimensions
def _latest_by_check(results):
out = {}
for r in results:
if isinstance(r, dict) and (r.get("check") or r.get("id")):
out[r.get("check") or r.get("id")] = r
return out
def build_scorecard(c, results, telemetry, delivery_status):
"""The scorecard stored in the unit record. `results` are the unit's recorded result rows
(any dicts with check/status/duration_s, store rows or fresh verify results)."""
latest = _latest_by_check(results)
by_status = {}
for r in latest.values():
by_status[norm_status(r.get("status"))] = by_status.get(norm_status(r.get("status")), 0) + 1
items = {x.get("id"): x for x in (c.get("checks") or []) + (c.get("invariants") or []) if isinstance(x, dict)}
reqs = [r for r in (c.get("requirements") or []) if isinstance(r, dict)]
with_check = [r for r in reqs if r.get("check")]
passing = sum(1 for r in with_check
if norm_status((latest.get(r["check"]) or {}).get("status")) == "passed")
first_ts = min((r["ts"] for r in results if isinstance(r, dict) and isinstance(r.get("ts"), str)), default=None)
if first_ts and any(isinstance(r.get("added"), str) for r in reqs):
surprise = val(sum(1 for r in reqs if isinstance(r.get("added"), str) and r["added"] > first_ts), "measured")
else:
surprise = unavailable()
tel = telemetry or {}
def T(key):
return tel.get(key) or unavailable()
tokens = T("tokens_by_category")
total_tokens = val(tokens["value"]["total"], "measured") if tokens["class"] == "measured" \
and isinstance(tokens.get("value"), dict) else unavailable()
return {
"intent_fulfilment": {
"requirements_total": val(len(reqs), "measured") if "requirements" in c else unavailable(),
"requirements_with_passing_check": val(passing, "measured") if with_check else unavailable(),
"requirements_added_after_first_verification": surprise,
"human_corrections": T("human_corrections"),
},
"correctness_and_assurance": {
"results_by_status": val(by_status, "measured"),
"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"),
"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"),
"unverified": val(delivery_status == "unverified", "measured"),
},
"delivery_velocity": {
"time_to_first_useful_result_s": T("time_to_first_useful_result_s"),
"time_to_validated_completion_s": T("time_to_validated_completion_s"),
"time_in_checks_s": T("time_in_checks_s"),
"time_in_waits_s": T("time_in_waits_s"),
"time_in_delegations_s": T("time_in_delegations_s"),
},
"resource_efficiency": {
"tokens_by_category": tokens,
"tokens_by_model": T("tokens_by_model"),
"tokens_total": total_tokens,
"cost": T("cost"),
"retries": T("send_backs"),
},
"parallelism": {
"delegations": T("delegations"),
"overlapped_delegations": T("overlapped_delegations"),
"worker_minutes": T("worker_minutes"),
"wall_time_s": T("time_to_validated_completion_s"),
},
"human_experience": {
"human_messages": T("human_messages"),
"question_dialogs": T("question_dialogs"),
"human_corrections": T("human_corrections"),
},
"lifecycle_quality": {
"files_changed": T("files_changed"),
"lines_changed": T("lines_changed"),
"tests_changed_with_code": T("tests_changed_with_code"),
"public_surface_touched": T("public_surface_touched"),
},
"organizational_improvement": {
"findings": T("retro_findings"),
"learnings_created": T("learnings_created"),
"recurrences": T("recurrences"),
},
}
# ---------------------------------------------------------------- `sisi status`
def load_unit_summaries(cwd=None):
"""Closed-unit summary lines from the user store, merged with this project's archived
records (deduped by project+id; the archive wins). Returns dicts, oldest first."""
units = {}
for r in store.read("units"):
if isinstance(r, dict) and r.get("id"):
units[(r.get("project"), r["id"])] = r
try:
from . import contract as C
p = C.find(cwd or os.getcwd())
proj = C.project_dir(p) if p else None
if proj:
d = os.path.join(proj, ".sisi", "units")
for n in sorted(os.listdir(d)) if os.path.isdir(d) else []:
if not n.endswith(".json"):
continue
try:
with open(os.path.join(d, n), encoding="utf-8") as f:
rec = json.load(f)
except (OSError, ValueError):
continue
if isinstance(rec, dict) and rec.get("id"):
units[(rec.get("project") or proj, rec["id"])] = rec
except Exception:
pass
return sorted(units.values(), key=lambda r: str(r.get("ended") or r.get("started") or ""))
def _num(v):
x = v.get("value") if isinstance(v, dict) else None
return float(x) if isinstance(x, (int, float)) and not isinstance(x, bool) else None
def _metric(unit, *path):
cur = unit.get("scorecard") or {}
for k in path:
cur = cur.get(k) if isinstance(cur, dict) else None
return _num(cur) if cur is not None else None
_TREND_METRICS = (("validated completion (s)", ("delivery_velocity", "time_to_validated_completion_s")),
("first useful result (s)", ("delivery_velocity", "time_to_first_useful_result_s")),
("time in checks (s)", ("delivery_velocity", "time_in_checks_s")),
("tokens", ("resource_efficiency", "tokens_total")),
("human corrections", ("human_experience", "human_corrections")),
("files changed", ("lifecycle_quality", "files_changed")))
def _pct(xs, p):
s = sorted(xs)
if not s:
return None
k = (len(s) - 1) * p / 100.0
lo = int(k)
hi = min(lo + 1, len(s) - 1)
return s[lo] + (s[hi] - s[lo]) * (k - lo)
def trends(units):
"""{segment_kind: {segment: {metric: {n, median, p95} or 'too few'}}} by project, risk
profile, model and policy version. Segments under five units say so; no single score."""
def seg_of(u, kind):
if kind == "project":
return os.path.basename(str(u.get("project") or "").rstrip("/")) or "(unknown project)"
if kind == "risk profile":
return ((u.get("risk") or {}).get("declared") or (u.get("risk") or {}).get("profile")
or "(none recorded)")
if kind == "model":
models = u.get("models") or []
return ", ".join(models) if isinstance(models, list) and models else "(no model recorded)"
return str(u.get("policy_version") or "(none recorded)")[:12]
out = {}
for kind in ("project", "risk profile", "model", "policy version"):
groups = {}
for u in units:
groups.setdefault(str(seg_of(u, kind)), []).append(u)
seg_out = {}
for seg, us in sorted(groups.items()):
if len(us) < 5:
seg_out[seg] = "too few"
continue
m = {}
for name, path in _TREND_METRICS:
xs = [x for x in (_metric(u, *path) for u in us) if x is not None]
m[name] = {"n": len(xs), "median": _pct(xs, 50), "p95": _pct(xs, 95)} if xs else "unavailable"
seg_out[seg] = m
out[kind] = seg_out
return out
def _fmt_val(v):
if not isinstance(v, dict) or v.get("class") == "unavailable" or v.get("value") is None:
return "unavailable"
x = v["value"]
if isinstance(x, bool):
return "yes" if x else "no"
if isinstance(x, float):
return "%g" % x
if isinstance(x, dict):
return ", ".join("%s=%s" % kv for kv in sorted(x.items(), key=lambda kv: str(kv[0]))) or "-"
if isinstance(x, list):
return ", ".join(str(i) for i in x) or "-"
return str(x)
def format_dimension(dim, vals):
shown = ["%s %s (%s)" % (k, _fmt_val(v), v.get("class")) for k, v in vals.items()
if isinstance(v, dict) and v.get("class") != "unavailable"]
n_un = sum(1 for v in vals.values() if isinstance(v, dict) and v.get("class") == "unavailable")
return " %s: %s%s" % (dim.replace("_", " "), "; ".join(shown) or "nothing recorded",
("; %d unavailable" % n_un) if n_un else "")
def format_status(units, learning=False, recent=5):
lines = []
if not units:
lines.append("sisi status: no closed work units yet. Close one with `sisi unit close`; "
"its scorecard will appear here.")
else:
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 ""))
sc = u.get("scorecard") or {}
for dim, vals in sc.items():
lines.append(format_dimension(dim, vals))
lines.append("")
lines.append("trends (median / p95; segments under five units say 'too few'):")
for kind, segs in trends(units).items():
lines.append(" by %s:" % kind)
for seg, m in segs.items():
if m == "too few":
lines.append(" %-28s too few" % seg[:28])
else:
cells = ["%s %s/%s (n=%d)" % (name, ("%g" % v["median"]) if v != "unavailable" else "unavailable",
("%g" % v["p95"]) if v != "unavailable" else "-",
v["n"] if v != "unavailable" else 0)
for name, v in m.items()]
lines.append(" %-28s %s" % (seg[:28], "; ".join(cells)))
if learning:
lines.append("")
try:
from . import learning as _L
lines.append(_L.learning_report())
except Exception as e:
store.log_error("status-learning", e)
lines.append("learning: unavailable (%s)" % e)
return "\n".join(lines)
def cmd_status(args=(), cwd=None, out=print):
units = load_unit_summaries(cwd)
if "--json" in args:
out(json.dumps({"units": units, "trends": trends(units)}, indent=2, default=str))
return 0
out(format_status(units, learning="--learning" in args))
return 0
+75 -3
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"}
"deliveries": "deliveries.jsonl", "units": "units.jsonl"}
def _migrate_learn():
@@ -82,7 +82,7 @@ def session_id():
return os.environ.get("SISI_SESSION_ID") or None
PERSONAL = ("learn", "quarantine") # what the person told or taught sisi: personal data, the rest is scratch
PERSONAL = ("learn", "quarantine", "units") # what the person told or taught sisi: personal data, the rest is scratch
def file_path(name):
@@ -156,7 +156,9 @@ def stamp(extra):
DEFAULTS = {"gate": {"enabled": True, "budget_s": 120, "max_blocks": 3, "growth_lines": 40, "growth_files": 3},
"verify": {"default_timeout_s": 60, "fast_limit_s": 60},
"retro": {"required": True}}
"retro": {"required": True},
"scratch": {"session_max_age_days": 30, "prune_every": 20, "prune_max_delete": 1000,
"prune_budget_s": 0.25}}
def config():
@@ -204,6 +206,76 @@ def save_session(sid, rec):
os.replace(tmp, p)
def _transcript_alive(session_file, cutoff):
"""True when the transcript this session record names was written to since `cutoff`: the
session is still going on in the host even though sisi has not touched its record."""
try:
with open(session_file, encoding="utf-8") as f:
tp = json.load(f).get("transcript_path")
return isinstance(tp, str) and os.stat(os.path.expanduser(tp)).st_mtime >= cutoff
except (OSError, ValueError, AttributeError):
return False
def prune_sessions(now=None, active_ids=(), force=False):
"""Remove session-state files older than the configured age. Runs on a counter kept in
scratch (every Nth session start, first run included), never on a scheduler. Bounded:
stops after the configured time budget or deletion count, and a later start continues.
Never deletes the file of a session named active (callers pass the current session's id)
nor of one whose transcript the host has written to within the age. Returns the number
of files removed."""
cfg = config().get("scratch", {})
d = os.path.join(paths.state(), "sessions")
counter_file = os.path.join(d, ".prune-counter")
count = 0
try:
with open(counter_file, encoding="utf-8") as f:
count = int(f.read().strip() or 0)
except (OSError, ValueError):
count = 0
count += 1
try:
os.makedirs(d, exist_ok=True)
with open(counter_file, "w", encoding="utf-8") as f:
f.write(str(count))
except OSError:
pass
every = max(1, int(cfg.get("prune_every", 20)))
if not force and (count - 1) % every != 0:
return 0 # not this start's turn: the first start and every Nth after it sweep
now = time.time() if now is None else now
cutoff = now - float(cfg.get("session_max_age_days", 30)) * 86400
keep = {safe_id(s) + ".json" for s in active_ids if s}
budget = float(cfg.get("prune_budget_s", 0.25))
max_delete = int(cfg.get("prune_max_delete", 1000))
removed, deadline, unfinished = 0, time.time() + budget, False
try:
with os.scandir(d) as it:
for e in it:
if removed >= max_delete or time.time() > deadline:
unfinished = True
break
if not e.name.endswith(".json") or e.name in keep:
continue
try:
if e.is_file(follow_symlinks=False) and e.stat().st_mtime < cutoff:
if _transcript_alive(e.path, cutoff):
continue # the host is still writing this session's transcript
os.unlink(e.path)
removed += 1
except OSError:
pass
except OSError:
pass
if unfinished: # out of budget with files left: the next start continues the sweep
try:
with open(counter_file, "w", encoding="utf-8") as f:
f.write("0")
except OSError:
pass
return removed
def log_error(where, exc):
try:
append("errors.log", {"ts": now(), "where": where, "error": repr(exc)})
-7
View File
@@ -299,10 +299,3 @@ def benchmark_cases(con):
out.append(case)
return out
def counts(con):
"""{kind: {grade: {split: n}}} for the scoreboard."""
out = {}
for r in con.execute("SELECT kind, COALESCE(grade,'-') g, split, COUNT(*) n FROM tasks GROUP BY 1,2,3"):
out.setdefault(r["kind"], {}).setdefault(r["g"], {})[r["split"]] = r["n"]
return out
+4 -16
View File
@@ -7,21 +7,9 @@ from . import store
MAX_AGE_S = 30 * 86400
def _prune(now=None):
"""Delete per-session state files untouched for 30 days."""
from . import paths
d = os.path.join(paths.state(), "sessions")
cutoff = (now or time.time()) - MAX_AGE_S
try:
with os.scandir(d) as it:
for e in it:
if e.name.endswith(".json") and e.is_file(follow_symlinks=False) and e.stat().st_mtime < cutoff:
try:
os.unlink(e.path)
except OSError:
pass
except OSError:
pass
def _prune(now=None, sid=None):
"""Delete old per-session state files, bounded and on a counter (see store.prune_sessions)."""
return store.prune_sessions(now=now, active_ids=(sid,) if sid else ())
def _export_session(sid):
@@ -95,7 +83,7 @@ def main(args=()):
rec["baseline"] = gitutil.measure(cwd)
rec["baseline_fp"] = gitutil.fingerprint(cwd, [C.find(cwd)])
store.save_session(sid, rec)
_prune()
_prune(sid=sid)
from . import wiring
problem = wiring.quick_problem()
if problem:
+800
View File
@@ -0,0 +1,800 @@
"""The durable work-unit record: close, pause, show, list.
The open unit is `.sisi/contract.json`. Closing archives the full record to
`.sisi/units/<id>.json` in the project (exclusive create: never overwritten) and appends
one summary line to the user store's `units.jsonl`, then marks the contract closed so a
new unit may replace it. Re-running close after a crash at any step converges without
duplicating or losing a record.
"""
import hashlib, json, os, time
from . import contract as C, gitutil, harvest, paths, scorecard, store
from .scorecard import unavailable, val
DELIVERY_STATUSES = ("delivered", "delivered-with-deferred", "deviation", "unverified", "abandoned") # the five of SPEC 10.3
def is_closed(c):
return isinstance(c, dict) and c.get("status") == "closed"
def archive_path(project, uid):
return os.path.join(project, ".sisi", "units", "%s.json" % store.safe_id(uid))
def list_archives(project):
d = os.path.join(project, ".sisi", "units")
out = []
try:
names = sorted(os.listdir(d))
except OSError:
return out
for n in names:
if n.endswith(".json"):
try:
with open(os.path.join(d, n), encoding="utf-8") as f:
out.append(json.load(f))
except (OSError, ValueError):
pass
return out
def fresh_id(base, project):
"""A unit id not already used by an archived or summarised unit in this project."""
used = {r.get("id") for r in list_archives(project)}
used |= {r.get("id") for r in store.read("units") if isinstance(r, dict) and r.get("project") == project}
if base not in used:
return base
n = 2
while "%s-%d" % (base, n) in used:
n += 1
return "%s-%d" % (base, n)
# ---------------------------------------------------------------- sources the record draws on
def _git_diff_text(project, base):
import subprocess
top = gitutil.root(project)
if not top:
return ""
try:
p = subprocess.run(["git", "diff", "--no-ext-diff", base or gitutil.head(top) or gitutil.EMPTY_TREE,
"--", ".", ":(exclude).sisi"], cwd=top, capture_output=True, timeout=10)
return p.stdout.decode("utf-8", "replace")[:200000]
except Exception:
return ""
def risk_floor(c, project):
"""The risk floor from what changed since the unit started (committed or not), by the
product's and the project's risk table. Unavailable outside a repository."""
ch = _changed_artifacts(c, project)
if ch is None:
return unavailable(), []
try:
from . import risk
profile, reasons = risk.assess(ch["files"], diff_text=_git_diff_text(project, c.get("base_head")),
patterns=risk.load_patterns(project))
return val(profile, "measured"), list(reasons)
except Exception as e:
store.log_error("unit-risk-floor", e)
return unavailable(), []
def retro_findings(c, project):
"""The retro findings recorded for this unit (the learning store holds them)."""
try:
from . import learning
return learning.findings_for_unit(project, c.get("id"))
except Exception as e:
store.log_error("unit-findings", e)
return []
def learning_activity(c, project):
"""(ids of learnings this unit created, count of recurrences it recorded)."""
try:
from . import learning
pk = learning.project_key(project)
made, rec = [], 0
for r in learning.load_learnings():
if r.get("source_unit") == c.get("id") and r.get("origin_project") == pk:
made.append(r.get("id"))
for pv in r.get("provenance") or []:
if isinstance(pv, dict) and pv.get("kind") == "recurrence" \
and pv.get("unit") == c.get("id") and pv.get("project") == pk:
rec += 1
return made, rec
except Exception as e:
store.log_error("unit-learnings", e)
return [], None
def delegations(project, t0, t1):
"""The ledger's attempts for this project inside the unit's window, from the orchestration
record. The ledger names a project by its folder name. None when it cannot be read."""
if t0 is None:
return None
try:
from . import workers
return workers.delegations_for_project(os.path.basename(project.rstrip(os.sep)), t0, t1)
except Exception as e:
store.log_error("unit-delegations", e)
return None
def _row_epoch(r):
for k in ("ts", "t", "started", "ended", "time"):
v = r.get(k)
if isinstance(v, (int, float)) and not isinstance(v, bool):
return float(v)
if isinstance(v, str):
t = harvest.epoch(v)
if t is not None:
return t
return None
def policy_version(project, c):
"""Hash of the policies in force: the effective rulebook, the floors and 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")),
("risk table", paths.canon("risk.json")),
("project risk table", os.path.join(project, ".sisi", "risk.json"))):
try:
with open(p, "rb") as f:
h.update(role.encode() + b"\0" + f.read() + b"\0")
except OSError:
h.update(role.encode() + b"\0missing\0")
try:
from . import cycle
h.update(json.dumps(cycle.load_enforced(), sort_keys=True, default=str).encode())
except Exception:
h.update(b"\0enforced-unavailable\0")
cfg = store.config()
h.update(json.dumps({k: cfg.get(k) for k in ("gate", "verify")}, sort_keys=True, default=str).encode())
return h.hexdigest()
# ---------------------------------------------------------------- telemetry
def _unit_results(c, project, t0_iso):
rows = []
for r in store.read("results"):
if not isinstance(r, dict) or r.get("contract") != c.get("id") or r.get("project") != project:
continue
if t0_iso and isinstance(r.get("ts"), str) and r["ts"] < t0_iso:
continue
rows.append(r)
return rows
def _transcript_stats(project, t0, t1):
"""Aggregated transcript stats from session records for this project in the window.
Returns None when no readable transcript was found at all."""
cands = []
sid = store.session_id()
sids = [sid] if sid else []
d = os.path.join(paths.state(), "sessions")
try:
names = [n for n in os.listdir(d) if n.endswith(".json")]
except OSError:
names = []
# newest first, bounded: session files far outside the window cannot belong to the unit
entries = []
for n in names:
try:
entries.append((os.path.getmtime(os.path.join(d, n)), n))
except OSError:
pass
entries.sort(reverse=True)
names = [n for m, n in entries if t1 is None or m >= t1 - 7 * 86400][:200]
for n in names:
rec = store.load_session(n[:-5])
tp, cwd = rec.get("transcript_path"), rec.get("cwd")
if isinstance(tp, str) and isinstance(cwd, str) and (cwd == project or cwd.startswith(project + os.sep)):
cands.append(tp)
if sid:
tp = store.load_session(sid).get("transcript_path")
if isinstance(tp, str) and tp not in cands:
cands.append(tp)
agg = None
for tp in cands:
st = harvest.transcript_stats(tp, t0, t1)
if st is None:
continue
if agg is None:
agg = {"usage": None, "human_messages": 0, "corrections": 0, "question_dialogs": 0, "subagent_runs": 0}
for k in ("human_messages", "corrections", "question_dialogs", "subagent_runs"):
agg[k] += st[k]
if st["usage"]:
if agg["usage"] is None:
agg["usage"] = {"by_category": {}, "by_model": {}}
for cat, v in st["usage"]["by_category"].items():
if cat != "total":
agg["usage"]["by_category"][cat] = agg["usage"]["by_category"].get(cat, 0) + v
for model, slot in st["usage"]["by_model"].items():
dst = agg["usage"]["by_model"].setdefault(model, {})
for cat, v in slot.items():
if cat != "total":
dst[cat] = dst.get(cat, 0) + v
if agg is not None and agg["usage"]:
agg["usage"]["by_category"]["total"] = sum(agg["usage"]["by_category"].values())
for slot in agg["usage"]["by_model"].values():
slot["total"] = sum(slot.values())
return agg
def build_telemetry(c, project, results, t0, t1):
"""Every value classed. Sources: deliveries, results, pauses on the contract, the
host transcript where a session record names one, git, and the delegation ledger."""
tel = {}
tel["time_to_validated_completion_s"] = val(round(t1 - t0, 1), "measured") if t0 is not None else unavailable()
if results:
tel["time_in_checks_s"] = val(round(sum(float(r["duration_s"]) for r in results
if isinstance(r.get("duration_s"), (int, float))), 3), "measured")
else:
tel["time_in_checks_s"] = unavailable()
if isinstance(c.get("pauses"), list):
waits = 0.0
for p in c["pauses"]:
if not isinstance(p, dict):
continue
a = harvest.epoch(p["since"]) if isinstance(p.get("since"), str) else None
b = harvest.epoch(p["until"]) if isinstance(p.get("until"), str) else t1
if a is not None and b is not None and b > a:
waits += b - a
tel["time_in_waits_s"] = val(round(waits, 1), "measured")
else:
tel["time_in_waits_s"] = unavailable()
deliveries = []
for r in store.read("deliveries"):
if not isinstance(r, dict):
continue
end = harvest.epoch(r["end"]) if isinstance(r.get("end"), str) else None
if end is not None and t0 is not None and t0 <= end <= t1 and \
(r.get("project") in (project, None) or str(r.get("project", "")).startswith(project)):
deliveries.append((end, r))
if deliveries:
tel["time_to_first_useful_result_s"] = val(round(min(e for e, _ in deliveries) - t0, 1), "measured")
tel["send_backs"] = val(sum(int(r.get("send_backs", 0)) for _, r in deliveries), "measured")
else:
first_pass = None
runs = {}
for r in results:
runs.setdefault(r.get("run"), []).append(r)
for run_rows in runs.values():
sts = [scorecard.norm_status(r.get("status")) for r in run_rows]
if any(s == "passed" for s in sts) and all(s in ("passed", "skipped", "not-applicable") for s in sts):
ts = harvest.epoch(run_rows[0]["ts"]) if isinstance(run_rows[0].get("ts"), str) else None
if ts is not None and t0 is not None:
first_pass = ts if first_pass is None else min(first_pass, ts)
tel["time_to_first_useful_result_s"] = val(round(first_pass - t0, 1), "inferred") if first_pass else unavailable()
tel["send_backs"] = unavailable()
stats = _transcript_stats(project, t0, t1)
if stats is None:
for k in ("human_messages", "question_dialogs", "human_corrections",
"tokens_by_category", "tokens_by_model"):
tel[k] = unavailable()
models = []
else:
tel["human_messages"] = val(stats["human_messages"], "measured")
tel["question_dialogs"] = val(stats["question_dialogs"], "measured")
tel["human_corrections"] = val(stats["corrections"], "inferred")
if stats["usage"]:
tel["tokens_by_category"] = val(stats["usage"]["by_category"], "measured")
tel["tokens_by_model"] = val(stats["usage"]["by_model"], "measured")
models = sorted(stats["usage"]["by_model"])
else: # the transcript has no usage numbers: tokens are unavailable, never zero
tel["tokens_by_category"] = unavailable()
tel["tokens_by_model"] = unavailable()
models = []
tel["cost"] = _estimated_cost(tel.get("tokens_by_model"))
dg = delegations(project, t0, t1)
if dg is None:
for k in ("delegations", "overlapped_delegations", "worker_minutes", "time_in_delegations_s"):
tel[k] = unavailable()
rows = []
else:
rows = dg["delegations"]
tel["delegations"] = val(dg["count"], "measured")
if dg["count"]:
tel["worker_minutes"] = val(round(dg["worker_minutes"], 1), "estimated")
tel["time_in_delegations_s"] = val(round(dg["wall_minutes"] * 60, 1), "estimated")
tel["overlapped_delegations"] = val(dg["overlapping_pairs"], "inferred")
else:
tel["worker_minutes"] = val(0, "measured")
tel["time_in_delegations_s"] = val(0, "measured")
tel["overlapped_delegations"] = val(0, "measured")
changed = _changed_artifacts(c, project)
tel["files_changed"] = val(len(changed["files"]), "measured") if changed else unavailable()
tel["lines_changed"] = val(changed["lines"], "measured") if changed else unavailable()
if changed:
tests = [f for f in changed["files"] if _is_test(f)]
code = [f for f in changed["files"] if not _is_test(f)]
tel["tests_changed_with_code"] = val(bool(tests and code), "inferred")
tel["public_surface_touched"] = val(any(_is_public(f) for f in changed["files"]), "inferred")
else:
tel["tests_changed_with_code"] = unavailable()
tel["public_surface_touched"] = unavailable()
findings = retro_findings(c, project)
learnings, recurrences = learning_activity(c, project)
tel["retro_findings"] = val(len(findings), "measured")
tel["learnings_created"] = val(len(learnings), "measured")
tel["recurrences"] = val(recurrences, "measured") if recurrences is not None else unavailable()
tel["_models"] = models
tel["_delegation_rows"] = rows
tel["_findings"] = findings
tel["_learnings"] = learnings
tel["_changed"] = changed
return tel
def _estimated_cost(tokens_by_model):
"""Cost from the recorded price facts (`sisi workers fact`) and the measured tokens per model.
Estimated when every model used has a recorded price; unavailable otherwise, and when
there are no tokens to price. Never a guess at a missing price."""
if not tokens_by_model or tokens_by_model.get("class") != "measured":
return unavailable()
try:
from . import workers
prices = workers.load_prices()
total = 0.0
for model, slot in tokens_by_model["value"].items():
cost = workers.estimate_cost(slot.get("total"), workers._price_for(prices, None, model, model))
if cost is None:
return unavailable()
total += cost
return val(round(total, 6), "estimated")
except Exception as e:
store.log_error("unit-cost", e)
return unavailable()
def _is_test(f):
base = os.path.basename(f)
return base.startswith(("test_", "test-")) or base.endswith(("_test.py", "_test.go", ".test.js", ".spec.js")) \
or "/tests/" in "/" + f
def _is_public(f):
return os.path.basename(f) in ("__init__.py",) or f.endswith(".pyi") or f.startswith(("include/", "public/"))
def _changed_artifacts(c, project):
if not gitutil.root(project):
return None
try:
return gitutil.measure(project, c.get("base_head"))
except Exception:
return None
# ---------------------------------------------------------------- the record
def latest_results(c, rows):
"""The standing result of every check and invariant of the contract, and of the floor and
enforced items of the latest fast run. A check with no record gets a synthesized `not-run`:
nothing that has no record of running is ever shown as passed. Each entry also says whether
the check ever passed in this unit, ever failed, and was waived."""
ids = {x["id"] for x in (c.get("checks") or []) + (c.get("invariants") or [])
if isinstance(x, dict) and x.get("id")}
last_fast = None
for r in rows:
if r.get("tier", "fast") == "fast" and r.get("run"):
last_fast = r["run"]
waived = {d.get("check") for d in (c.get("deviations") or []) if isinstance(d, dict) and d.get("check")}
latest, ever_passed, ever_failed = {}, set(), set()
for r in rows:
cid = r.get("check")
if not cid or r.get("item") not in ("check", "invariant", "floor", "enforced"):
continue
if r["item"] in ("floor", "enforced"):
if r.get("run") != last_fast:
continue
elif cid not in ids:
continue # a check since removed from the contract no longer speaks for it
st = scorecard.norm_status(r.get("status"))
if st == "passed":
ever_passed.add(cid)
if st == "failed":
ever_failed.add(cid)
latest[cid] = {"item": r["item"], "id": cid, "status": st, "reason": r.get("reason"),
"duration_s": r.get("duration_s", 0.0), "mandatory": r.get("mandatory", True),
"tier": r.get("tier", "fast"), "ts": r.get("ts")}
for x in (c.get("checks") or []) + (c.get("invariants") or []):
if isinstance(x, dict) and x.get("id") and x["id"] not in latest:
latest[x["id"]] = {"item": "check", "id": x["id"], "status": "not-run",
"reason": "needs human" if x.get("rung") in (5, 6) else "never run",
"duration_s": 0.0, "mandatory": x.get("mandatory", True),
"tier": x.get("tier", "fast"), "ts": None}
out = []
for cid, r in latest.items():
r["ever_passed"] = cid in ever_passed
r["seen_failing"] = cid in ever_failed
r["waived"] = cid in waived
out.append(r)
return out
def _justified_by_selection(r):
"""A check kept back because the change did not touch what it watches, where files it
watches exist. A watch that matches no file at all justifies nothing."""
return r["status"] == "skipped" and str(r.get("reason") or "").startswith("not affected")
def never_run(latest):
"""Mandatory checks that never ran to a pass in this unit and that nothing justifies
skipping. A unit with any of these cannot close as plainly delivered."""
out = []
for r in latest:
if r["item"] not in ("check", "invariant") or not r.get("mandatory", True):
continue
if r["ever_passed"] or _justified_by_selection(r):
continue
out.append(r)
return out
def decide_status(c, rows, abandon=None):
"""(delivery status or None, blocking, unrun). None with blocking results means the unit
cannot close as delivered. A waiver or an abandonment is recorded as what it is."""
from . import verify as V
latest = latest_results(c, rows)
block = V.blocking(latest)
unrun = never_run(latest)
if abandon is not None:
return "abandoned", block, unrun
if c.get("deviations"):
return "deviation", 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
if any(r["status"] == "not-run" for r in latest) or unrun or C.deferred_checks(c):
return "delivered-with-deferred", block, unrun
return "delivered", block, unrun
def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None, rows=None):
t0 = harvest.epoch(c["started"]) if isinstance(c.get("started"), str) else None
rows = _unit_results(c, project, c.get("started")) if rows is None else rows
tel = build_telemetry(c, project, rows, t0, ended_epoch)
models = tel.pop("_models")
delegation_rows = tel.pop("_delegation_rows")
changed = tel.pop("_changed")
findings = tel.pop("_findings")
learnings = tel.pop("_learnings")
ended = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(ended_epoch)) + "Z"
latest = latest_results(c, rows)
unrun = never_run(latest)
floor, floor_reasons = risk_floor(c, project)
declared = c.get("risk") or {}
rec = {
"id": c["id"], "parent": c.get("parent"),
"goal": c.get("goal"), "scope": c.get("scope") or {"in": [], "out": []},
"project": project,
"requirements": c.get("requirements") or [],
"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"),
"blast_radius": declared.get("blast_radius"), "rollback": declared.get("rollback")},
"approach": c.get("approach"),
"plan": c.get("plan") or [],
"workers": delegation_rows,
"models": models, "budgets": c.get("budgets"),
"started": c.get("started"), "ended": ended, "closed_at": ended, "telemetry": tel,
"start_commit": c.get("base_head"),
"closing_commit": gitutil.head(project) if gitutil.root(project) else None,
"summary": c.get("summary"),
"changed_artifacts": changed if changed is not None else {"files": [], "lines": None},
"verification": rows,
"final_verification": latest,
"deferred": c.get("deferred") or [],
"deferred_checks": [r["id"] for r in latest if r["status"] == "not-run"
and str(r.get("reason") or "").startswith(("deferred", "needs human"))],
"never_run_mandatory": [{"id": r["id"], "status": r["status"], "reason": r.get("reason")} for r in unrun],
"limitations": c.get("limitations") or [], "open_risks": c.get("open_risks") or [],
"deviations": c.get("deviations") or [], "pauses": c.get("pauses") or [],
"delivery_status": delivery_status,
"abandon_reason": abandon_reason,
"policy_version": policy_version(project, c),
"retro_findings": findings, "learning_ids": learnings,
"contract": c,
}
rec["scorecard"] = scorecard.build_scorecard(c, rows, tel, delivery_status)
return rec
def summary_line(rec):
risk = rec.get("risk") or {}
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},
"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")}
def _summary_exists(project, uid):
return any(isinstance(r, dict) and r.get("id") == uid and r.get("project") == project
for r in store.read("units"))
def archive_record(rec, project):
"""Write the archive so that it appears whole or not at all and is never replaced: the
full text goes to a temporary file, which is then hard-linked into place (the link fails
if the archive exists). Returns (path, created). An existing archive stays byte for byte."""
p = archive_path(project, rec["id"])
os.makedirs(os.path.dirname(p), exist_ok=True)
tmp = "%s.tmp%d" % (p, os.getpid())
with open(tmp, "w", encoding="utf-8") as f:
json.dump(rec, f, indent=2, default=str)
f.write("\n")
f.flush()
os.fsync(f.fileno())
try:
try:
os.link(tmp, p)
except FileExistsError:
return p, False
except OSError: # a filesystem without hard links
try:
fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
except FileExistsError:
return p, False
with os.fdopen(fd, "w", encoding="utf-8") as f, open(tmp, encoding="utf-8") as src:
f.write(src.read())
return p, True
finally:
try:
os.unlink(tmp)
except OSError:
pass
def _capture_case(rec):
"""Offer the closed unit to the evaluation harness as a benchmark case. Never stops a close."""
try:
from . import evaluate
view = dict(rec)
view["fix_commit"] = rec.get("closing_commit")
view["request"] = rec.get("goal")
evaluate.capture_case(view)
except Exception as e:
store.log_error("unit-capture-case", e)
def close_unit(c, contract_path, project, abandon=None, now=None):
"""Archive the open unit and mark the contract closed. Returns (record_or_None, message, ok).
Refuses with nothing written when verification blocks and no deviation, gate release or
abandonment accounts for it. Safe to repeat after a crash at any step: an archive that
exists is kept as it stands and the remaining steps are completed."""
ended_epoch = time.time() if now is None else now
rows = _unit_results(c, project, c.get("started")) # under the id the results were recorded with
path = archive_path(project, c["id"])
if os.path.exists(path):
try:
with open(path, encoding="utf-8") as f:
old = json.load(f)
except (OSError, ValueError):
old = None
if is_closed(c):
return None, "unit %s is already closed (%s); nothing changed" % (c["id"], path), True
if isinstance(old, dict) and old.get("started") == c.get("started") and old.get("project") == project:
rec, created = old, False # a crash after archiving: complete the close from it
else:
c["id"] = fresh_id(c["id"], project) # another unit owns this id: never overwrite it
path = archive_path(project, c["id"])
rec = None
else:
rec = None
if rec is None:
status, block, _ = decide_status(c, rows, abandon)
if status is None:
bad = ", ".join("%s (%s%s)" % (r["id"], r["status"], ": " + r["reason"] if r.get("reason") else "")
for r in block)
return None, ("sisi: unit %s cannot close as delivered: %s. Fix and re-run `sisi verify`, "
"record a deviation with `sisi contract waive \"<reason>\"`, or close it with "
"`sisi unit close --abandon \"<reason>\"`." % (c["id"], bad)), False
rec = build_record(c, project, status, ended_epoch, abandon_reason=abandon, rows=rows)
_, created = archive_record(rec, project)
if created:
_capture_case(rec)
if not _summary_exists(project, rec["id"]):
store.append("units", summary_line(rec))
c["status"] = "closed"
c["ended"] = rec.get("ended")
c["delivery_status"] = rec.get("delivery_status")
for pz in c.get("pauses") or []:
if isinstance(pz, dict) and not pz.get("until"):
pz["until"] = rec.get("ended")
C.save(contract_path, c)
return rec, "closed unit %s (%s): %s" % (rec["id"], rec.get("delivery_status"), path), True
def resume(c, contract_path):
"""End a recorded wait: the unit is open again and the wait's length is recorded."""
if c.get("status") != "paused":
return False
for pz in c.get("pauses") or []:
if isinstance(pz, dict) and not pz.get("until"):
pz["until"] = store.now()
c["status"] = "open"
c.pop("pause_fp", None)
C.save(contract_path, c)
return True
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)
try:
c = C.load(p)
except (OSError, ValueError):
return ""
if not isinstance(c, dict) or not c.get("id"):
return ""
now = time.time()
rows = _unit_results(c, project, c.get("started"))
latest = latest_results(c, rows)
tel = build_telemetry(c, project, rows, harvest.epoch(c["started"]) if isinstance(c.get("started"), str) else None, now)
for k in [k for k in tel if k.startswith("_")]:
tel.pop(k)
card = scorecard.build_scorecard(c, rows, tel, "open")
lines = ["unit %s (%s): %s" % (c["id"], c.get("status", "open"), c.get("goal") or ""), ""]
for dim, vals in card.items():
lines.append(scorecard.format_dimension(dim, vals))
out = []
seen = [r["id"] for r in latest if r["seen_failing"] and r["status"] == "passed"]
if seen:
out.append("failed and then passed (the evidence is real): %s" % ", ".join(seen))
failing = [r["id"] for r in latest if r["status"] == "failed"]
if failing:
out.append("still failing: %s" % ", ".join(failing))
nr = never_run(latest)
if nr:
out.append("mandatory checks that never ran to a pass: %s" % ", ".join(r["id"] for r in nr))
if c.get("deviations"):
out.append("a deviation was recorded: the unit cannot read as delivered")
hc = (tel.get("human_corrections") or {}).get("value")
if hc:
out.append("%s human correction(s) inferred from the transcript" % hc)
sb = (tel.get("send_backs") or {}).get("value")
if sb:
out.append("the gate sent the agent back %s time(s)" % sb)
unav = sorted(k for k, v in tel.items() if isinstance(v, dict) and v.get("class") == "unavailable")
if unav:
out.append("not measurable here (unavailable): %s" % ", ".join(unav))
lines += ["", "what stands out:"] + ([" - " + x for x in out] or [" nothing in the record stands out"])
lines += ["", "record each finding with `sisi retro --finding ... --cause ... --impact ... --disposition ...`; "
"then `sisi unit close` archives the unit."]
return "\n".join(lines) + "\n"
# ---------------------------------------------------------------- command
def _open_contract(cwd, out):
p = C.find(cwd)
if not p:
out("sisi: no contract found (run `sisi contract init`)")
return None, None, None
try:
c = C.load(p)
except (OSError, ValueError) as e:
out("sisi: cannot read %s: %s" % (p, e))
return None, None, None
return c, p, C.project_dir(p)
def cmd_unit(args, cwd=None, out=print):
cwd = cwd or os.getcwd()
sub = args[0] if args else ""
if sub == "close":
abandon = None
rest = list(args[1:])
if "--abandon" in rest:
i = rest.index("--abandon")
abandon = rest[i + 1] if i + 1 < len(rest) else ""
if not str(abandon).strip():
out('usage: sisi unit close [--abandon "<reason>"]')
return 1
c, p, project = _open_contract(cwd, out)
if c is None:
return 2
errs = C.validate(c)
if errs and abandon is None:
out("sisi: invalid contract %s; fix it, or close with --abandon" % p)
for e in errs:
out(" - " + e)
return 1
rec, msg, ok = close_unit(c, p, project, abandon=abandon)
out(msg)
if rec is not None:
out("delivery status: %s" % rec.get("delivery_status"))
if rec.get("delivery_status") == "deviation":
out("a deviation was recorded; the completion report to the human must say so")
if rec.get("deferred_checks"):
out("deferred checks: %s" % ", ".join(rec["deferred_checks"]))
return 0 if ok else 1
if sub == "pause":
what = " ".join(args[1:]).strip()
if not what:
out('usage: sisi unit pause "<what it waits for>"')
return 1
c, p, project = _open_contract(cwd, out)
if c is None:
return 2
if is_closed(c):
out("sisi: unit %s is closed; start a new one with `sisi contract init`" % c.get("id"))
return 1
pauses = c.setdefault("pauses", [])
open_pause = next((x for x in pauses if isinstance(x, dict) and not x.get("until")), None)
if open_pause is not None:
open_pause["what"] = what
else:
pauses.append({"what": what, "since": store.now(), "until": None})
c["status"] = "paused"
c["pause_fp"] = gitutil.fingerprint(project) # a change to the tree ends the wait (see gate)
C.save(p, c)
out("unit %s paused: %s" % (c.get("id"), what))
return 0
if sub == "show":
uid = args[1] if len(args) > 1 else None
if uid is None:
c, p, project = _open_contract(cwd, out)
if c is None:
return 2
out(json.dumps(c, indent=2))
return 0
p = C.find(cwd)
project = C.project_dir(p) if p else None
if project:
for rec in list_archives(project):
if rec.get("id") == uid:
out(json.dumps(rec, indent=2))
return 0
for r in store.read("units"):
if isinstance(r, dict) and r.get("id") == uid:
ap = archive_path(r.get("project") or project or cwd, uid)
if os.path.exists(ap):
with open(ap, encoding="utf-8") as f:
out(json.dumps(json.load(f), indent=2))
else:
out(json.dumps(r, indent=2))
return 0
out("sisi: no unit record with id %r" % uid)
return 1
if sub == "list":
p = C.find(cwd)
project = C.project_dir(p) if p else (gitutil.root(cwd) or cwd)
c = None
if p:
try:
c = C.load(p)
except (OSError, ValueError):
c = None
rows = []
if project:
for rec in list_archives(project):
rows.append((rec.get("ended") or "", rec.get("id"), rec.get("delivery_status"), rec.get("goal") or ""))
if c is not None and not is_closed(c):
out("open %-24s %s" % (c.get("id"), c.get("goal") or ""))
for ended, uid, status, goal in sorted(rows, reverse=True):
out("%-8s %-24s %-24s %s" % (str(ended)[:10], uid, status, goal))
if c is None and not rows:
out("no units in this project yet")
return 0
out("usage: sisi unit close [--abandon \"<reason>\"] | pause \"<what it waits for>\" | show [ID] | list")
return 1
+275 -25
View File
@@ -1,9 +1,19 @@
"""Run a contract: every check and invariant with a cmd, in the project dir, with a timeout."""
import json, os, signal, subprocess, time
"""Run a contract: every selected check and invariant with a cmd, in the project dir, with a timeout.
Five statuses only: passed, failed, skipped, not-applicable, not-run. A timeout is
not-run (timed out); a rung 5/6 check is not-run (needs human); a check kept back by
change selection is skipped (not affected by this change), or not-applicable when no
file it watches exists; an identical-inputs pass is skipped (reused: passed at <time>).
Nothing that did not run is ever reported as passed, on any path.
"""
import hashlib, json, os, signal, subprocess, time
from fnmatch import fnmatch
from pathlib import PurePosixPath
from . import contract as C, store
TAIL = 1500
STATUSES = ("passed", "failed", "skipped", "not-applicable", "not-run")
def _tail(s):
@@ -12,10 +22,10 @@ def _tail(s):
def run_cmd(cmd, cwd, timeout, expect):
"""Return (status, duration, tail). status: passed/failed/timeout."""
"""Return (status, duration, tail). status: passed/failed/not-run (a timeout never ran to a verdict)."""
t0 = time.time()
if timeout <= 0:
return "timeout", 0.0, "not run: time budget exhausted"
return "not-run", 0.0, "not run: time budget exhausted"
try:
p = subprocess.Popen(cmd, shell=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.DEVNULL, start_new_session=True)
@@ -32,7 +42,7 @@ def run_cmd(cmd, cwd, timeout, expect):
p.communicate(timeout=5)
except Exception:
pass
return "timeout", time.time() - t0, "timed out after %gs" % timeout
return "not-run", time.time() - t0, "timed out after %gs" % timeout
dur = time.time() - t0
o, e = out.decode("utf-8", "replace"), err.decode("utf-8", "replace")
tail = _tail(o + ("\n" if o and e else "") + e)
@@ -54,31 +64,205 @@ def tree_fp(project, contract_path):
return None
def match_path(path, pattern):
p = str(path).replace(os.sep, "/")
pat = str(pattern).replace(os.sep, "/")
if fnmatch(p, pat) or fnmatch(p, pat.rstrip("/") + "/*"):
return True
try:
return PurePosixPath(p).match(pat)
except ValueError:
return False
def project_files(project, limit=5000):
"""Relative paths in the project (git-tracked plus untracked, else a walk). Bounded."""
from . import gitutil
if gitutil.root(project):
try:
rc, out = gitutil._git(project, "ls-files", "-c", "-o", "--exclude-standard", "-z", timeout=10)
if rc == 0:
return [r for r in out.split("\0") if r][:limit]
except Exception:
pass
out = []
for dirpath, dirs, names in os.walk(project):
dirs[:] = [d for d in dirs if d != ".git"]
for n in names:
out.append(os.path.relpath(os.path.join(dirpath, n), project))
if len(out) >= limit:
return out
return out
def changed_paths(c, project):
"""Paths changed since the unit started (its base_head), or in the working tree vs HEAD.
None when it cannot be known: the caller then runs everything."""
from . import gitutil
if not gitutil.root(project):
return None
try:
return gitutil.measure(project, c.get("base_head"))["files"]
except Exception:
return None
# ---------------------------------------------------------------- reuse cache
def _cache_path():
from . import paths
return os.path.join(paths.state(), "verify-cache.json")
def _load_cache():
try:
with open(_cache_path(), encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except (OSError, ValueError):
return {}
def _save_cache(cache):
try:
p = _cache_path()
os.makedirs(os.path.dirname(p), exist_ok=True)
tmp = p + ".tmp%d" % os.getpid()
with open(tmp, "w", encoding="utf-8") as f:
json.dump(cache, f)
os.replace(tmp, p)
except OSError:
pass
def _cache_key(c, project, x):
raw = json.dumps([os.path.realpath(project), c.get("id"), x.get("id"), x.get("cmd"),
x.get("expect")], sort_keys=True, default=str)
return hashlib.sha1(raw.encode()).hexdigest()
def input_fingerprint(c, project, x, files=None, contract_path=None):
"""Hash of everything a check's verdict may depend on: its command and expectation, plus
the contents of the files its when_changed watches, or the whole tree when it has none.
None when it cannot be computed safely: no reuse then, the check runs."""
h = hashlib.sha256()
h.update(json.dumps([x.get("cmd"), x.get("expect")], sort_keys=True, default=str).encode())
wc = x.get("when_changed")
if not wc:
# the whole tree, but not the contract file: a pause, a note or a status change in the
# contract cannot change what a command shows, and must not defeat reuse
fp = tree_fp(project, None)
if fp is None:
return None
h.update(fp.encode())
return h.hexdigest()
files = project_files(project) if files is None else files
matched = sorted(f for f in files if any(match_path(f, p) for p in wc))
if len(matched) > 2000:
return None
for rel in matched:
try:
full = os.path.join(project, rel)
if os.path.getsize(full) > 10 * 1024 * 1024:
return None
with open(full, "rb") as fh:
h.update(rel.encode() + b"\0" + hashlib.sha256(fh.read()).digest())
except OSError:
h.update(rel.encode() + b"\0gone")
return h.hexdigest()
def _history(c, project):
"""Past results for this contract+project: seen-failing per check, last duration per check."""
seen_fail, last_dur = {}, {}
try:
rows = store.read("results")
except Exception:
rows = []
started = c.get("started")
for r in rows:
if not isinstance(r, dict) or r.get("contract") != c.get("id") or r.get("project") != project:
continue
if started and isinstance(r.get("ts"), str) and r["ts"] < started:
continue
if r.get("status") == "failed":
seen_fail[r.get("check")] = True
if isinstance(r.get("duration_s"), (int, float)):
last_dur[r.get("check")] = float(r["duration_s"])
return seen_fail, last_dur
MAX_PARALLEL = 4
def _run_item(item, x, tier, project, deadline, default_timeout):
r = {"item": item, "id": x["id"], "kind": x.get("kind"), "rung": x.get("rung"), "claim": x.get("claim"),
"tier": tier}
"tier": tier, "mandatory": x.get("mandatory", True), "independent": bool(x.get("independent", False)),
"covers": x.get("covers"), "reason": None, "saved_s": 0.0}
if x.get("rung") in (5, 6):
r.update(status="awaiting-human", duration_s=0.0, tail="")
r.update(status="not-run", reason="needs human", duration_s=0.0, tail="")
else:
to = float(x.get("timeout_s", default_timeout))
if deadline is not None:
to = min(to, deadline - time.time())
st, dur, tail = run_cmd(x["cmd"], project, to, x.get("expect", {"exit": 0}))
r.update(status=st, duration_s=round(dur, 3), tail=tail)
reason = None
if st == "not-run":
reason = "timed out" if tail.startswith("timed out") else tail.removeprefix("not run: ")
r.update(status=st, reason=reason, duration_s=round(dur, 3), tail=tail)
return r
def run(c, project, deadline=None, default_timeout=60, tiers=("fast",)):
"""Run the items of the given tiers. Returns list of result dicts (with 'tail'), in contract order.
deadline is a time.time() value. With top-level "parallel": true in the contract, fast-tier items run together
(at most MAX_PARALLEL at a time), except items marked "serial": true, which run alone afterwards."""
def _not_run_result(base_item, x, tier, status, reason, saved=0.0):
return {"item": base_item, "id": x["id"], "kind": x.get("kind"), "rung": x.get("rung"),
"claim": x.get("claim"), "tier": tier, "mandatory": x.get("mandatory", True),
"independent": bool(x.get("independent", False)), "covers": x.get("covers"),
"status": status, "reason": reason, "duration_s": 0.0, "tail": "", "saved_s": round(saved, 3)}
def run(c, project, deadline=None, default_timeout=60, tiers=("fast",), changed=None, reuse=True,
contract_path=None, run_all=False):
"""Run the items of the given tiers, with change selection and identical-input reuse.
Returns result dicts in contract order. `changed=None` means unknown: run everything.
A skipped or not-applicable result is recorded with its reason; it is never a pass."""
items = [("check", x) for x in c["checks"]] + [("invariant", x) for x in c.get("invariants", [])]
items = [(item, x, x.get("tier", "fast")) for item, x in items if x.get("tier", "fast") in tiers]
deferred = C.deferred_checks(c)
seen_fail, last_dur = _history(c, project)
cache = _load_cache() if reuse and not run_all else {}
files = None
if changed is None and not run_all:
changed = changed_paths(c, project)
res = [None] * len(items)
par = [i for i, (_, x, tier) in enumerate(items) if c.get("parallel") is True and tier == "fast" and not x.get("serial")]
fps = {}
for i, (item, x, tier) in enumerate(items):
if x["id"] in deferred:
res[i] = _not_run_result(item, x, tier, "not-run", "deferred: %s" % deferred[x["id"]].get("why", ""))
continue
if x.get("rung") in (5, 6):
continue # decided in _run_item: not-run (needs human)
wc = x.get("when_changed")
if wc and not run_all and changed is not None:
if files is None:
files = project_files(project)
if not any(match_path(f, p) for f in files for p in wc):
res[i] = _not_run_result(item, x, tier, "not-applicable",
"no file matches when_changed", last_dur.get(x["id"], 0.0))
continue
if not any(match_path(f, p) for f in changed for p in wc):
res[i] = _not_run_result(item, x, tier, "skipped",
"not affected by this change", last_dur.get(x["id"], 0.0))
continue
if reuse and not run_all:
fp = input_fingerprint(c, project, x, files, contract_path)
fps[i] = fp
hit = cache.get(_cache_key(c, project, x)) if fp else None
if hit and hit.get("fp") == fp and hit.get("status") == "passed":
res[i] = _not_run_result(item, x, tier, "skipped",
"reused: passed at %s" % hit.get("ts"), hit.get("duration_s", 0.0))
continue
par = [i for i, (_, x, tier) in enumerate(items)
if res[i] is None and c.get("parallel") is True and tier == "fast" and not x.get("serial")]
if len(par) > 1:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=MAX_PARALLEL) as ex:
@@ -89,50 +273,93 @@ def run(c, project, deadline=None, default_timeout=60, tiers=("fast",)):
for i, (item, x, tier) in enumerate(items):
if res[i] is None:
res[i] = _run_item(item, x, tier, project, deadline, default_timeout)
dirty_cache = False
for i, (item, x, tier) in enumerate(items):
r = res[i]
r["seen_failing"] = bool(seen_fail.get(x["id"])) or r["status"] == "failed"
if r["status"] == "passed" and reuse and not run_all:
fp = fps.get(i) or input_fingerprint(c, project, x, files, contract_path)
if fp:
cache[_cache_key(c, project, x)] = {"fp": fp, "status": "passed", "ts": store.now(),
"duration_s": r["duration_s"]}
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", "duration_s": 0.0, "tail": f["message"]})
"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
res += cycle.enforced_results(c, project, deadline, default_timeout)
extra = cycle.enforced_results(c, project, deadline, default_timeout)
for r in extra:
r.setdefault("reason", None)
r.setdefault("mandatory", True)
r.setdefault("seen_failing", r.get("status") == "failed")
res += extra
except Exception as e:
store.log_error("enforced", e)
return res
def blocking(results):
"""Results that block delivery: any failure, or a mandatory not-run for a reason other
than a recorded deferral or needing a human."""
out = []
for r in results:
if r["status"] == "failed":
out.append(r)
elif r["status"] == "not-run" and r.get("mandatory", True):
reason = r.get("reason") or ""
if not (reason.startswith("deferred") or reason == "needs human"):
out.append(r)
return out
def ok(results):
return all(r["status"] in ("passed", "awaiting-human") for r in results)
return not blocking(results)
def record(c, project, results, fp=None):
run_id = "%x-%d" % (time.time_ns(), os.getpid())
for r in results:
store.append("results", {"ts": store.now(), "contract": c["id"], "project": project,
"check": r["id"], "item": r["item"], "kind": r["kind"], "rung": r["rung"],
"status": r["status"], "duration_s": r["duration_s"],
"check": r["id"], "item": r["item"], "kind": r.get("kind"), "rung": r.get("rung"),
"status": r["status"], "reason": r.get("reason"), "duration_s": r["duration_s"],
"seen_failing": bool(r.get("seen_failing")), "mandatory": r.get("mandatory", True),
"independent": bool(r.get("independent", False)), "covers": r.get("covers"),
"tool": store.tool(), "session": store.session_id(), "run": run_id,
"tier": r.get("tier", "fast"), "fp": fp})
return run_id
def format_table(results):
rows = [("ID", "KIND", "RUNG", "TIER", "STATUS", "SECS")]
for r in results:
rows.append((r["id"], r["kind"] or "-", str(r["rung"] or "-"), r.get("tier", "fast"), r["status"], "%.1f" % r["duration_s"]))
st = r["status"] + ((" (%s)" % r["reason"]) if r.get("reason") else "")
rows.append((r["id"], r["kind"] or "-", str(r["rung"] or "-"), r.get("tier", "fast"), st, "%.1f" % r["duration_s"]))
w = [max(len(row[i]) for row in rows) for i in range(6)]
return "\n".join(" ".join(v.ljust(w[i]) for i, v in enumerate(row)).rstrip() for row in rows)
def failure_report(results, limit=4000):
parts = []
bad = {id(r) for r in blocking(results)} | {id(r) for r in results if r["status"] == "failed"}
for r in results:
if r["status"] in ("failed", "timeout"):
parts.append("- %s %s [%s]: %s\n%s" % (r["item"], r["id"], r["status"], r.get("claim") or "",
if id(r) in bad:
label = r["status"] + ((": " + r["reason"]) if r.get("reason") else "")
parts.append("- %s %s [%s]: %s\n%s" % (r["item"], r["id"], label, r.get("claim") or "",
"\n".join(" " + l for l in (r["tail"] or "").splitlines()[-15:])))
s = "\n".join(parts)
return s if len(s) <= limit else s[:limit] + "\n... (truncated)"
def time_saved(results):
return round(sum(r.get("saved_s", 0.0) for r in results if r["status"] in ("skipped", "not-applicable")), 3)
def cmd_verify(args, cwd=None, out=print):
from . import deep, trust
cwd = cwd or os.getcwd()
@@ -195,7 +422,8 @@ def cmd_verify(args, cwd=None, out=print):
return 0
cfg = store.config()
try:
results = run(c, project, default_timeout=cfg["verify"]["default_timeout_s"], tiers=tiers)
results = run(c, project, default_timeout=cfg["verify"]["default_timeout_s"], tiers=tiers,
contract_path=path, run_all="--all" in args)
record(c, project, results, fp)
if locked:
deep.save_state(project, c["id"], fp, results, [x["id"] for x in deep.deep_items(c)])
@@ -204,17 +432,39 @@ def cmd_verify(args, cwd=None, out=print):
deep.release(project)
good = ok(results)
ds = deep.deep_state(c, project, fp)
saved = time_saved(results)
from . import unit as _unit
standing = _unit.latest_results(c, _unit._unit_results(c, project, c.get("started")))
unproven = [{"id": r["id"], "status": r["status"], "reason": r.get("reason")}
for r in _unit.never_run(standing) if r["status"] != "failed"] # failures are reported as failures
if c.get("status") == "paused":
_unit.resume(c, path) # work resumed: the wait is over
if as_json:
out(json.dumps({"contract": c["id"], "project": project, "ok": good, "tiers": list(tiers), "fingerprint": fp,
"deep_state": deep.public(ds), "results": results}, indent=2))
"deep_state": deep.public(ds), "time_saved_s": saved,
"never_run_mandatory": unproven, "results": results}, indent=2))
else:
if results:
out(format_table(results))
if not good:
out("\nFAILED:\n" + failure_report(results))
else:
waiting = [r["id"] for r in results if r["status"] == "awaiting-human"]
out("\nOK" + (" (awaiting human: %s)" % ", ".join(waiting) if waiting else ""))
waiting = [r["id"] for r in results if r["status"] == "not-run"]
out("\nOK" + ((" (not run: %s)" % ", ".join("%s %s" % (r["id"], r.get("reason") or "")
for r in results if r["status"] == "not-run")) if waiting else ""))
held_back = [r for r in results if r["status"] in ("skipped", "not-applicable")]
if held_back:
out("did not run (not a pass): " + "; ".join("%s %s (%s)" % (r["id"], r["status"], r.get("reason") or "")
for r in held_back))
if unproven:
out("no evidence yet: mandatory check(s) never ran to a pass: " +
", ".join("%s (%s)" % (u["id"], u["reason"] or u["status"]) for u in unproven) +
"; the unit cannot close as plainly delivered")
slow = sorted((r for r in results if r["duration_s"] > 0), key=lambda r: -r["duration_s"])[:3]
if slow:
out("slowest checks: " + ", ".join("%s %.1fs" % (r["id"], r["duration_s"]) for r in slow))
if saved:
out("time saved by selection and reuse: %.1fs" % saved)
for w in C.warnings(c):
out("warning: " + w)
if ds: