WIP (worker interrupted by a usage limit): work-unit record, verification vocabulary, scorecard; tests being updated

This commit is contained in:
swaits committed 2026-11-23 11:35:23 -07:00
1 parent 29d239ca3b
commit 91c954344f
16 files changed
+1701 -407

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. 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 init [--goal TEXT] start a work unit: create .sisi/contract.json here (refuses while one is open)
sisi contract check validate the contract sisi contract check validate the contract (vacuous checks are refused)
sisi contract waive "<reason>" record that this change needs no checks 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 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 --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 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 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 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 its key text) and removes it from the pile
sisi oracle print what the human wants: the standing principles from sisi oracle print what the human wants: the standing principles from
`sisi learn`, live at once (oracle.md in the personal folder) `sisi learn`, live at once (oracle.md in the personal folder)
sisi status verification statistics from the store 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 time [--json] time from request to verified result: 7 days against the 7 before, slowest checks
sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json] sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]
list ways to know work is correct, by section 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 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": if sub == "init":
goal = _pop_opt(args, "--goal") goal = _pop_opt(args, "--goal")
p = os.path.join(os.getcwd(), C.REL) p = os.path.join(os.getcwd(), C.REL)
project = os.getcwd()
if os.path.exists(p): if os.path.exists(p):
print("sisi: %s already exists" % p) try:
return 1 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) 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: 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") f.write("\n")
trust.add(os.getcwd()) trust.add(os.getcwd())
print("created %s as a SKELETON, not a contract yet: replace the placeholder check with a real command " 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) print("contract invalid" if errs else "contract ok: %s" % p)
return 1 if errs else 0 return 1 if errs else 0
if sub == "waive": 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: if not reason:
print('usage: sisi contract waive "<reason>"') print('usage: sisi contract waive [--check ID] "<reason>"')
return 1 return 1
import time import time
project = gitutil.root(os.getcwd()) or os.getcwd() project = gitutil.root(os.getcwd()) or os.getcwd()
@@ -159,8 +190,20 @@ def cmd_contract(args):
if gitutil.root(os.getcwd()): if gitutil.root(os.getcwd()):
m = gitutil.measure(os.getcwd()) m = gitutil.measure(os.getcwd())
extra = {"head": gitutil.head(os.getcwd()), "lines": m["lines"], "files": m["files"]} 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))) store.append("waivers", store.stamp(dict({"project": project, "reason": reason, "check": waived_check,
print("waiver recorded for %s" % project) "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 return 0
if sub in ("trust", "untrust"): if sub in ("trust", "untrust"):
p = C.find(os.getcwd()) p = C.find(os.getcwd())
@@ -188,94 +231,6 @@ def cmd_oracle():
return 0 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=()): def cmd_wiring(name, args=()):
from . import wiring from . import wiring
if name == "install" and "--dry-run" in args: if name == "install" and "--dry-run" in args:
@@ -417,10 +372,11 @@ def main(argv):
from . import risk from . import risk
return risk.main(args) return risk.main(args)
if cmd == "status": if cmd == "status":
return cmd_status() from . import scorecard
if cmd == "time": return scorecard.cmd_status(args)
from . import delivery if cmd == "unit":
return delivery.cmd_time(args) from . import unit
return unit.cmd_unit(args)
if cmd == "verifiers": if cmd == "verifiers":
from . import verifiers from . import verifiers
return verifiers.main(args) return verifiers.main(args)
+164
View File
@@ -36,11 +36,22 @@ def is_unedited_skeleton(c):
return False 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): 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("-") 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 { return {
"id": name or "work", "id": name or "work",
"parent": None,
"goal": goal or "TODO: one sentence describing the outcome", "goal": goal or "TODO: one sentence describing the outcome",
"scope": {"in": [], "out": []},
"requirements": [],
"risk": {},
"checks": [{ "checks": [{
"id": "c1", "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", "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,13 @@ def skeleton(goal=None, cwd=None):
"invariants": [], "invariants": [],
"assumptions": [], "assumptions": [],
"questions": [], "questions": [],
"deferred": [],
"limitations": [],
"plan": [],
"status": "open",
"started": _store.now(),
"pauses": [],
"deviations": [],
} }
@@ -70,6 +88,25 @@ def load(path):
return json.load(f) 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(): def floors():
try: try:
with open(paths.canon("floors.json"), encoding="utf-8") as f: with open(paths.canon("floors.json"), encoding="utf-8") as f:
@@ -132,6 +169,124 @@ def _expect(e, where, errs):
errs.append("%s: unknown expect key %r" % (where, k)) errs.append("%s: unknown expect key %r" % (where, k))
_VACUOUS_RE = re.compile(r"^(?:true|:|exit\s+0|echo(?:\s[^|&;<>]*)?)\s*;?$")
def vacuous_reason(ch):
"""Why this check cannot fail, or None. Only whole-command constant forms count:
`true`, `:`, `exit 0`, a bare `echo` (with no stdout expectation). A compound
command, a redirection, or an expect the constant does not satisfy can fail."""
cmd = ch.get("cmd")
if not isinstance(cmd, str):
return None
s = cmd.strip()
if not _VACUOUS_RE.match(s):
return None
expect = ch.get("expect") if isinstance(ch.get("expect"), dict) else {}
if expect.get("exit", 0) != 0:
return None
if s.startswith("echo") and expect.get("stdout_contains") is not None:
return None
return "vacuous check: %r cannot fail; write a command that can" % s
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 "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): def validate(c):
"""Return a list of error strings; empty means valid.""" """Return a list of error strings; empty means valid."""
errs = [] errs = []
@@ -179,6 +334,10 @@ def validate(c):
_tier(ch, w, errs) _tier(ch, w, errs)
if "serial" in ch and not isinstance(ch["serial"], bool): if "serial" in ch and not isinstance(ch["serial"], bool):
errs.append(w + ": serial must be true or false") 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", []) inv = c.get("invariants", [])
if not isinstance(inv, list): if not isinstance(inv, list):
errs.append("invariants must be a list") errs.append("invariants must be a list")
@@ -205,6 +364,10 @@ def validate(c):
_tier(iv, w, errs) _tier(iv, w, errs)
if "serial" in iv and not isinstance(iv["serial"], bool): if "serial" in iv and not isinstance(iv["serial"], bool):
errs.append(w + ": serial must be true or false") 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 \ 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) any(isinstance(x, dict) and x.get("cmd") for x in inv)
if checks and not runnable: if checks and not runnable:
@@ -220,6 +383,7 @@ def validate(c):
for i, x in enumerate(q): for i, x in enumerate(q):
if not (isinstance(x, dict) and _str(x.get("q")) and "default" in x): if not (isinstance(x, dict) and _str(x.get("q")) and "default" in x):
errs.append("questions[%d] needs q and default" % i) errs.append("questions[%d] needs q and default" % i)
_validate_new_top(c, ids, errs)
return 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:]} items = [{"id": r["id"], "status": r["status"], "tail": (r.get("tail") or "")[-1500:]}
for r in results if r.get("tier") == "deep"] for r in results if r.get("tier") == "deep"]
st = {"contract": contract_id, "fp": fp, "epoch": time.time(), "ids": sorted(deep_ids), 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) p = _state_path(project)
os.makedirs(os.path.dirname(p), exist_ok=True) os.makedirs(os.path.dirname(p), exist_ok=True)
tmp = p + ".tmp%d" % os.getpid() tmp = p + ".tmp%d" % os.getpid()
@@ -123,7 +123,7 @@ def deep_state(c, project, fp):
st = load_state(project) st = load_state(project)
if st is not None and st.get("ids") == ids: 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, 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: else:
st = None st = None
if lock: if lock:
+5 -44
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 (`sisi status` reports it; the old `sisi time` command is gone).
Delivery row (deliveries.jsonl in the state dir): session, project, start, end (ISO UTC), seconds, send_backs (times the 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 gate sent the agent back during this request), check_s (seconds spent running checks during this request), contract
@@ -95,7 +96,7 @@ def record(payload, sess, sid, cwd, now=None):
return None return None
# ---------------------------------------------------------------- reading: `sisi time` # ---------------------------------------------------------------- reading (telemetry helpers)
DAY = 86400.0 DAY = 86400.0
@@ -151,10 +152,10 @@ def windows(rows, now):
def slow_checks(results, now, top=5): def slow_checks(results, now, top=5):
"""The slowest checks by mean duration over the last 7 days, each with a suggestion.""" """The slowest checks by mean duration over the last 7 days, each with a suggestion."""
from . import scoreboard from . import scorecard
recent = [r for r in results if isinstance(r, dict) and (_epoch(r.get("ts")) or 0) >= now - 7 * DAY] recent = [r for r in results if isinstance(r, dict) and (_epoch(r.get("ts")) or 0) >= now - 7 * DAY]
out = [] out = []
for s in scoreboard.check_stats(recent)["checks"]: for s in scorecard.check_stats(recent)["checks"]:
if s.get("timed_runs"): 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.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.sort(key=lambda x: -x["mean_s"])
@@ -193,43 +194,3 @@ def fmt_s(s):
return "%dh%02dm" % (s // 3600, (s % 3600) // 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
+4 -88
View File
@@ -1,89 +1,5 @@
"""Escape candidates: work declared verified (or finished) that then turned out wrong. Evidence pointers only. """Compatibility shim: escape candidates folded into sisi.scorecard, where they feed the
intent and correctness dimensions. These names stay for learn_cli's escapes command."""
from .scorecard import WEEK_S, attribute, escape_candidates, passed_runs
Kinds find = escape_candidates
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
+9 -2
View File
@@ -641,6 +641,12 @@ def _decide(payload):
if c is not None and C.is_unedited_skeleton(c): if c is not None and C.is_unedited_skeleton(c):
path = None # nothing real written yet: behave as if there is no contract path = None # nothing real written yet: behave as if there is no contract
sess["req_contract"] = False sess["req_contract"] = False
if c is not None and path and c.get("status") == "paused" and \
any(isinstance(p, dict) and not p.get("until") for p in (c.get("pauses") or [])):
return "allow", None # a recorded wait: the turn may end with no demands
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) top = gitutil.root(cwd)
sess["req_project"] = top or (project if path else cwd) sess["req_project"] = top or (project if path else cwd)
fp = gitutil.fingerprint(cwd, [path]) if top else None fp = gitutil.fingerprint(cwd, [path]) if top else None
@@ -765,7 +771,8 @@ def _decide(payload):
"claim": "contract is invalid", "duration_s": 0.0, "tail": "\n".join(errs)}] "claim": "contract is invalid", "duration_s": 0.0, "tail": "\n".join(errs)}]
else: else:
t_run = time.time() 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) sess["req_check_s"] = float(sess.get("req_check_s", 0.0)) + (time.time() - t_run)
V.record(c, project, results, fp) V.record(c, project, results, fp)
if V.ok(results): if V.ok(results):
@@ -811,7 +818,7 @@ def _decide(payload):
try: try:
from . import retro from . import retro
failing = " ".join("%s %s %s" % (r["id"], r.get("kind") or "", r.get("claim") or "") 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) block = retro.lessons_block(failing, "gate", session=sid)
if block: if block:
msg += "\n\n" + block msg += "\n\n" + block
+80
View File
@@ -226,6 +226,86 @@ def machine_reason(text, origin_kind=None, entrypoint=None):
return bool(reasons), ";".join(reasons) 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
if ts is not None and ((t0 is not None and ts < t0) or (t1 is not None and ts > t1)):
continue
typ = d.get("type")
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:
if not first and is_correction(text):
corrections += 1
first = False
human += 1
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 # ---------------------------------------------------------------- source interface
class Source: class Source:
+1 -22
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 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. `learn_cli.register(subparsers)`; each command sets `func(args) -> exit code` on its parser.
@@ -99,22 +99,6 @@ def cmd_checks(args):
return 0 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): def register(subparsers):
p = subparsers.add_parser("harvest", help="read agent transcripts into the harvest database (incremental)") p = subparsers.add_parser("harvest", help="read agent transcripts into the harvest database (incremental)")
p.add_argument("--workers", type=int, default=None) p.add_argument("--workers", type=int, default=None)
@@ -146,11 +130,6 @@ def register(subparsers):
p.add_argument("--json", action="store_true") p.add_argument("--json", action="store_true")
p.set_defaults(func=cmd_checks) 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): def main(argv=None):
ap = argparse.ArgumentParser(prog="sisi") ap = argparse.ArgumentParser(prog="sisi")
register(ap.add_subparsers(dest="cmd", required=True)) register(ap.add_subparsers(dest="cmd", required=True))
+5 -95
View File
@@ -1,100 +1,10 @@
"""Check statistics and the scoreboard. """Compatibility shim: the scoreboard folded into sisi.scorecard (SPEC 13).
Check statistics (from results.jsonl): per check id, and per verifier when records carry a `verifier` field: `sisi status` is the one report now; the `sisi scoreboard` command is gone. These
runs, failures, timeouts. A check with MANY_RUNS or more runs and no failure or timeout is flagged names stay only for internal callers not yet migrated (learn_cli's checks command).
"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 .scorecard import MANY_RUNS, check_stats, iso_week, session_trends
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): def scoreboard(con):
weeks, repos, wr = {}, {}, {} return session_trends(con)
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)}
+435
View File
@@ -0,0 +1,435 @@
"""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 datetime, json, os, re, time
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
_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, "timeouts": 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
s["timeouts"] += 1 # legacy column name, kept for existing readers
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)}
# ---------------------------------------------------------------- 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
# ---------------------------------------------------------------- session trends (weekly)
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 session_trends(con):
from . import taskset
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)}
# ---------------------------------------------------------------- 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_minutes": 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 u.get("policy_version") or "(none recorded)"
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_status(units, learning=False, recent=8):
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():
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")
lines.append(" %s: %s%s" % (dim.replace("_", " "), "; ".join(shown) or "nothing recorded",
("; %d unavailable" % n_un) if n_un else ""))
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)))
# The learning view (`sisi status --learning`: per promoted learning, units since,
# recurrences, realization rate) plugs in here with the learning-loop wave.
if learning:
lines.append("")
lines.append("learning: unavailable -- the learning view lands with the retro and cycle "
"rebuild; until then `sisi lessons` and `sisi cycle status` hold that record.")
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
+54 -3
View File
@@ -5,7 +5,7 @@ from . import paths
FILES = {"results": "results.jsonl", FILES = {"results": "results.jsonl",
"learn": "learn.jsonl", "quarantine": "learn.jsonl", "waivers": "waivers.jsonl", "learn": "learn.jsonl", "quarantine": "learn.jsonl", "waivers": "waivers.jsonl",
"deliveries": "deliveries.jsonl"} "deliveries": "deliveries.jsonl", "units": "units.jsonl"}
def _migrate_learn(): def _migrate_learn():
@@ -82,7 +82,7 @@ def session_id():
return os.environ.get("SISI_SESSION_ID") or None 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): 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}, 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}, "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(): def config():
@@ -204,6 +206,55 @@ def save_session(sid, rec):
os.replace(tmp, p) os.replace(tmp, p)
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, nor the file just written for the
current session (callers pass its id). 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 % every != 1 % every and count != 1:
return 0
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 = 0, time.time() + budget
try:
with os.scandir(d) as it:
for e in it:
if removed >= max_delete or time.time() > deadline:
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:
os.unlink(e.path)
removed += 1
except OSError:
pass
except OSError:
pass
return removed
def log_error(where, exc): def log_error(where, exc):
try: try:
append("errors.log", {"ts": now(), "where": where, "error": repr(exc)}) append("errors.log", {"ts": now(), "where": where, "error": repr(exc)})
+4 -16
View File
@@ -7,21 +7,9 @@ from . import store
MAX_AGE_S = 30 * 86400 MAX_AGE_S = 30 * 86400
def _prune(now=None): def _prune(now=None, sid=None):
"""Delete per-session state files untouched for 30 days.""" """Delete old per-session state files, bounded and on a counter (see store.prune_sessions)."""
from . import paths return store.prune_sessions(now=now, active_ids=(sid,) if sid else ())
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 _export_session(sid): def _export_session(sid):
@@ -95,7 +83,7 @@ def main(args=()):
rec["baseline"] = gitutil.measure(cwd) rec["baseline"] = gitutil.measure(cwd)
rec["baseline_fp"] = gitutil.fingerprint(cwd, [C.find(cwd)]) rec["baseline_fp"] = gitutil.fingerprint(cwd, [C.find(cwd)])
store.save_session(sid, rec) store.save_session(sid, rec)
_prune() _prune(sid=sid)
from . import wiring from . import wiring
problem = wiring.quick_problem() problem = wiring.quick_problem()
if problem: if problem:
+605
View File
@@ -0,0 +1,605 @@
"""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")
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)
# ---------------------------------------------------------------- later-wave hooks
# Each of these is the one small function a later wave calls or replaces. Until then the
# record carries an honest empty or unavailable value for what they will supply.
def risk_floor(c, project):
"""Risk-profile floor from changed paths. Later wave (risk profiles) computes it; a
contract already carrying `risk_floor` has that value taken as measured."""
if isinstance(c, dict) and c.get("risk_floor"):
return val(c["risk_floor"], "measured")
return unavailable()
def retro_findings(c, project):
"""Retro findings for this unit. Later wave (learning loop) fills these in."""
return list(c.get("retro_findings") or []) if isinstance(c, dict) else []
def learning_ids(c, project):
"""Learning records this unit created. Later wave (learning loop) fills these in."""
return list(c.get("learning_ids") or []) if isinstance(c, dict) else []
def delegations(c, project, t0, t1):
"""Delegation ledger rows (user store `delegations.jsonl`) inside the unit's window.
Rows naming another project are dropped; rows naming none are taken by time alone.
Returns (rows, found_the_ledger)."""
p = paths.data_file("delegations.jsonl")
if not os.path.exists(p):
return [], False
rows = []
try:
with open(p, encoding="utf-8") as f:
lines = f.readlines()
except OSError:
return [], False
for line in lines:
try:
r = json.loads(line)
except ValueError:
continue
if not isinstance(r, dict):
continue
rp = r.get("project") or r.get("cwd")
if rp and os.path.realpath(str(rp)) != os.path.realpath(project) \
and not str(rp).startswith(project + os.sep):
continue
t = _row_epoch(r)
if t is not None and t0 is not None and not (t0 <= t <= (t1 or t)):
continue
rows.append(r)
return rows, True
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")
for p in (rulebook, paths.canon("floors.json"), paths.canon("risk.json"),
os.path.join(project, ".sisi", "risk.json")):
try:
with open(p, "rb") as f:
h.update(p.encode() + b"\0" + f.read() + b"\0")
except OSError:
h.update(p.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"] = unavailable() # no price facts live here; never estimated from thin air
rows, have_ledger = delegations(c, project, t0, t1)
if not have_ledger:
for k in ("delegations", "overlapped_delegations", "worker_minutes", "time_in_delegations_s"):
tel[k] = unavailable()
else:
tel["delegations"] = val(len(rows), "inferred")
mins = [float(r["minutes"]) for r in rows if isinstance(r.get("minutes"), (int, float))]
if mins:
tel["worker_minutes"] = val(round(sum(mins), 1), "estimated")
tel["time_in_delegations_s"] = val(round(sum(mins) * 60, 1), "estimated")
ivs = [(_row_epoch(r), float(r["minutes"]) * 60) for r in rows
if _row_epoch(r) is not None and isinstance(r.get("minutes"), (int, float))]
over = sum(1 for i in range(len(ivs)) for j in range(i + 1, len(ivs))
if ivs[i][0] < ivs[j][0] + ivs[j][1] and ivs[j][0] < ivs[i][0] + ivs[i][1])
tel["overlapped_delegations"] = val(over, "inferred")
else:
tel["worker_minutes"] = unavailable()
tel["time_in_delegations_s"] = unavailable()
tel["overlapped_delegations"] = unavailable()
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 = learning_ids(c, project)
tel["retro_findings"] = val(len(findings), "measured")
tel["learnings_created"] = val(len(learnings), "measured")
tel["recurrences"] = unavailable()
tel["_models"] = models
tel["_delegation_rows"] = rows if have_ledger else []
tel["_changed"] = changed
return tel
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):
"""Latest recorded result per check, plus a synthesized not-run for checks never run.
Synthesis is only ever not-run: a check with no record did not pass."""
from . import verify as V
latest = {}
for r in rows:
if r.get("item") in ("check", "invariant", "floor", "enforced") and r.get("check"):
latest[r["check"]] = {"item": r.get("item"), "id": r["check"], "status": scorecard.norm_status(r.get("status")),
"reason": r.get("reason"), "duration_s": r.get("duration_s", 0.0),
"mandatory": r.get("mandatory", True), "seen_failing": r.get("seen_failing"),
"tier": r.get("tier", "fast"), "tail": ""}
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),
"seen_failing": False, "tier": x.get("tier", "fast"), "tail": ""}
return list(latest.values())
def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None):
t0 = harvest.epoch(c["started"]) if isinstance(c.get("started"), str) else None
rows = _unit_results(c, project, c.get("started"))
tel = build_telemetry(c, project, rows, t0, ended_epoch)
models = tel.pop("_models")
delegation_rows = tel.pop("_delegation_rows")
changed = tel.pop("_changed")
ended = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(ended_epoch)) + "Z"
latest = _latest_results(c, rows)
deferred_ids = [r["id"] for r in latest if r["status"] == "not-run"
and str(r.get("reason") or "").startswith(("deferred", "needs human"))]
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": risk_floor(c, project),
"declared": (c.get("risk") or {}).get("profile"),
"why": (c.get("risk") or {}).get("why"),
"blast_radius": (c.get("risk") or {}).get("blast_radius"),
"rollback": (c.get("risk") or {}).get("rollback")},
"plan": c.get("plan") or [], "dependencies": c.get("dependencies") or [],
"workers": delegation_rows,
"models": models, "budgets": c.get("budgets"),
"started": c.get("started"), "ended": ended, "telemetry": tel,
"changed_artifacts": changed if changed is not None else {"files": [], "lines": None},
"summary": c.get("summary"),
"verification": rows,
"deferred": c.get("deferred") or [], "deferred_checks": deferred_ids,
"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": retro_findings(c, project),
"learning_ids": learning_ids(c, project),
"contract": c,
}
rec["scorecard"] = scorecard.build_scorecard(c, rows, tel, delivery_status)
return rec
def summary_line(rec):
return {"id": rec["id"], "parent": rec.get("parent"), "project": rec.get("project"),
"goal": rec.get("goal"), "delivery_status": rec.get("delivery_status"),
"risk": {"declared": (rec.get("risk") or {}).get("declared"),
"floor": (rec.get("risk") or {}).get("floor")},
"models": rec.get("models") or [], "policy_version": rec.get("policy_version"),
"started": rec.get("started"), "ended": rec.get("ended"), "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 with exclusive create. Returns (path, created). An existing
archive is left byte-for-byte intact (created=False): records are never overwritten."""
p = archive_path(project, rec["id"])
os.makedirs(os.path.dirname(p), exist_ok=True)
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:
json.dump(rec, f, indent=2)
f.write("\n")
return p, True
def close_unit(c, contract_path, project, abandon=None, now=None):
"""Archive the open unit. Returns (record_or_None, message, ok).
Refuses with nothing written when verification blocks and no deviation, deferral
outcome, gate release or abandonment accounts for it."""
from . import verify as V
ended_epoch = time.time() if now is None else now
path = archive_path(project, c["id"])
already = os.path.exists(path)
if already and is_closed(c):
return None, "unit %s is already closed (%s); nothing changed" % (c["id"], path), True
rows = _unit_results(c, project, c.get("started"))
latest = _latest_results(c, rows)
gate_released = any(r.get("check") == "gate" and r.get("status") == "unverified" for r in rows)
if abandon is not None:
status = "abandoned"
elif c.get("deviations"):
status = "deviation"
elif V.blocking(latest):
if gate_released:
status = "unverified"
else:
bad = ", ".join("%s (%s%s)" % (r["id"], r["status"], ": " + r["reason"] if r.get("reason") else "")
for r in V.blocking(latest))
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
elif any(r["status"] == "not-run" for r in latest) or C.deferred_checks(c):
status = "delivered-with-deferred"
else:
status = "delivered"
rec = build_record(c, project, status, ended_epoch, abandon_reason=abandon)
_, created = archive_record(rec, project)
if not created:
# a crash after archiving: keep the archived record exactly as it stands
try:
with open(path, encoding="utf-8") as f:
rec = json.load(f)
except (OSError, ValueError):
pass
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")
try:
from . import verify as _V
c["closed_fp"] = _V.tree_fp(project, contract_path)
except Exception:
c["closed_fp"] = None
for p in c.get("pauses") or []:
if isinstance(p, dict) and not p.get("until"):
p["until"] = rec.get("ended")
C.save(contract_path, c)
return rec, "closed unit %s (%s): %s" % (rec["id"], rec.get("delivery_status"), path), True
# ---------------------------------------------------------------- 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.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
+260 -25
View File
@@ -1,9 +1,19 @@
"""Run a contract: every check and invariant with a cmd, in the project dir, with a timeout.""" """Run a contract: every selected check and invariant with a cmd, in the project dir, with a timeout.
import json, os, signal, subprocess, time
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 from . import contract as C, store
TAIL = 1500 TAIL = 1500
STATUSES = ("passed", "failed", "skipped", "not-applicable", "not-run")
def _tail(s): def _tail(s):
@@ -12,10 +22,10 @@ def _tail(s):
def run_cmd(cmd, cwd, timeout, expect): 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() t0 = time.time()
if timeout <= 0: if timeout <= 0:
return "timeout", 0.0, "not run: time budget exhausted" return "not-run", 0.0, "not run: time budget exhausted"
try: try:
p = subprocess.Popen(cmd, shell=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, p = subprocess.Popen(cmd, shell=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.DEVNULL, start_new_session=True) stdin=subprocess.DEVNULL, start_new_session=True)
@@ -32,7 +42,7 @@ def run_cmd(cmd, cwd, timeout, expect):
p.communicate(timeout=5) p.communicate(timeout=5)
except Exception: except Exception:
pass 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 dur = time.time() - t0
o, e = out.decode("utf-8", "replace"), err.decode("utf-8", "replace") o, e = out.decode("utf-8", "replace"), err.decode("utf-8", "replace")
tail = _tail(o + ("\n" if o and e else "") + e) tail = _tail(o + ("\n" if o and e else "") + e)
@@ -54,31 +64,203 @@ def tree_fp(project, contract_path):
return None 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:
fp = tree_fp(project, contract_path)
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 MAX_PARALLEL = 4
def _run_item(item, x, tier, project, deadline, default_timeout): 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"), 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): 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: else:
to = float(x.get("timeout_s", default_timeout)) to = float(x.get("timeout_s", default_timeout))
if deadline is not None: if deadline is not None:
to = min(to, deadline - time.time()) to = min(to, deadline - time.time())
st, dur, tail = run_cmd(x["cmd"], project, to, x.get("expect", {"exit": 0})) 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 return r
def run(c, project, deadline=None, default_timeout=60, tiers=("fast",)): def _not_run_result(base_item, x, tier, status, reason, saved=0.0):
"""Run the items of the given tiers. Returns list of result dicts (with 'tail'), in contract order. return {"item": base_item, "id": x["id"], "kind": x.get("kind"), "rung": x.get("rung"),
deadline is a time.time() value. With top-level "parallel": true in the contract, fast-tier items run together "claim": x.get("claim"), "tier": tier, "mandatory": x.get("mandatory", True),
(at most MAX_PARALLEL at a time), except items marked "serial": true, which run alone afterwards.""" "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 = [("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] 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) 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: if len(par) > 1:
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=MAX_PARALLEL) as ex: with ThreadPoolExecutor(max_workers=MAX_PARALLEL) as ex:
@@ -89,50 +271,95 @@ def run(c, project, deadline=None, default_timeout=60, tiers=("fast",)):
for i, (item, x, tier) in enumerate(items): for i, (item, x, tier) in enumerate(items):
if res[i] is None: if res[i] is None:
res[i] = _run_item(item, x, tier, project, deadline, default_timeout) 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 []): 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, 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) if "fast" in tiers: # enforced lessons ride the same path as floors (personal overlay, trusted commands)
try: try:
from . import cycle 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:
if r.get("status") == "timeout":
r["status"], r["reason"] = "not-run", "timed out"
r.setdefault("reason", None)
r.setdefault("mandatory", True)
r.setdefault("seen_failing", r.get("status") == "failed")
res += extra
except Exception as e: except Exception as e:
store.log_error("enforced", e) store.log_error("enforced", e)
return res 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): 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): def record(c, project, results, fp=None):
run_id = "%x-%d" % (time.time_ns(), os.getpid()) run_id = "%x-%d" % (time.time_ns(), os.getpid())
for r in results: for r in results:
store.append("results", {"ts": store.now(), "contract": c["id"], "project": project, store.append("results", {"ts": store.now(), "contract": c["id"], "project": project,
"check": r["id"], "item": r["item"], "kind": r["kind"], "rung": r["rung"], "check": r["id"], "item": r["item"], "kind": r.get("kind"), "rung": r.get("rung"),
"status": r["status"], "duration_s": r["duration_s"], "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, "tool": store.tool(), "session": store.session_id(), "run": run_id,
"tier": r.get("tier", "fast"), "fp": fp}) "tier": r.get("tier", "fast"), "fp": fp})
return run_id
def format_table(results): def format_table(results):
rows = [("ID", "KIND", "RUNG", "TIER", "STATUS", "SECS")] rows = [("ID", "KIND", "RUNG", "TIER", "STATUS", "SECS")]
for r in results: 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)] 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) 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): def failure_report(results, limit=4000):
parts = [] parts = []
bad = {id(r) for r in blocking(results)} | {id(r) for r in results if r["status"] == "failed"}
for r in results: for r in results:
if r["status"] in ("failed", "timeout"): if id(r) in bad:
parts.append("- %s %s [%s]: %s\n%s" % (r["item"], r["id"], r["status"], r.get("claim") or "", 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:]))) "\n".join(" " + l for l in (r["tail"] or "").splitlines()[-15:])))
s = "\n".join(parts) s = "\n".join(parts)
return s if len(s) <= limit else s[:limit] + "\n... (truncated)" 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): def cmd_verify(args, cwd=None, out=print):
from . import deep, trust from . import deep, trust
cwd = cwd or os.getcwd() cwd = cwd or os.getcwd()
@@ -195,7 +422,8 @@ def cmd_verify(args, cwd=None, out=print):
return 0 return 0
cfg = store.config() cfg = store.config()
try: 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) record(c, project, results, fp)
if locked: if locked:
deep.save_state(project, c["id"], fp, results, [x["id"] for x in deep.deep_items(c)]) deep.save_state(project, c["id"], fp, results, [x["id"] for x in deep.deep_items(c)])
@@ -204,17 +432,24 @@ def cmd_verify(args, cwd=None, out=print):
deep.release(project) deep.release(project)
good = ok(results) good = ok(results)
ds = deep.deep_state(c, project, fp) ds = deep.deep_state(c, project, fp)
saved = time_saved(results)
if as_json: if as_json:
out(json.dumps({"contract": c["id"], "project": project, "ok": good, "tiers": list(tiers), "fingerprint": fp, 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, "results": results}, indent=2))
else: else:
if results: if results:
out(format_table(results)) out(format_table(results))
if not good: if not good:
out("\nFAILED:\n" + failure_report(results)) out("\nFAILED:\n" + failure_report(results))
else: else:
waiting = [r["id"] for r in results if r["status"] == "awaiting-human"] waiting = [r["id"] for r in results if r["status"] == "not-run"]
out("\nOK" + (" (awaiting human: %s)" % ", ".join(waiting) if waiting else "")) 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 ""))
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): for w in C.warnings(c):
out("warning: " + w) out("warning: " + w)
if ds: if ds:
+2
View File
@@ -115,6 +115,8 @@ class SisiCase(unittest.TestCase):
def check(id, cmd, rung=3, kind="general", exit=0, timeout_s=10, **expect): def check(id, cmd, rung=3, kind="general", exit=0, timeout_s=10, **expect):
if cmd == "true": # a passing check that can fail (bare `true` is vacuous and refused)
cmd = "test -f .sisi/contract.json"
return {"id": id, "claim": "claim " + id, "kind": kind, "rung": rung, "cmd": cmd, return {"id": id, "claim": "claim " + id, "kind": kind, "rung": rung, "cmd": cmd,
"expect": dict({"exit": exit}, **expect), "timeout_s": timeout_s} "expect": dict({"exit": exit}, **expect), "timeout_s": timeout_s}
+9 -4
View File
@@ -11,16 +11,21 @@ class VerifyTests(SisiCase):
return {r["check"]: r["status"] for r in self.results()} return {r["check"]: r["status"] for r in self.results()}
def test_statuses(self): def test_statuses(self):
# R-5.6-2, R-5.6-3: five statuses only. A timeout is not-run (timed out) and a
# human check is not-run (needs human): neither is ever reported as passed.
c = contract([check("ok", "true"), check("bad", "exit 3"), check("slow", "sleep 5", timeout_s=0.3), c = contract([check("ok", "true"), check("bad", "exit 3"), check("slow", "sleep 5", timeout_s=0.3),
check("out", "echo hello", stdout_contains="hello"), check("out2", "echo hi", stdout_contains="zzz"), check("out", "echo hello", stdout_contains="hello"), check("out2", "echo hi", stdout_contains="zzz"),
check("code", "exit 3", exit=3), human("h5", 5), human("h6", 6)], check("code", "exit 3", exit=3), human("h5", 5), human("h6", 6)],
[check("inv", "true")]) [check("inv", "true")])
r = self.run_verify(c) r = self.run_verify(c)
self.assertEqual(r.returncode, 1) self.assertEqual(r.returncode, 1)
self.assertEqual(self.statuses(), {"ok": "passed", "bad": "failed", "slow": "timeout", "out": "passed", self.assertEqual(self.statuses(), {"ok": "passed", "bad": "failed", "slow": "not-run", "out": "passed",
"out2": "failed", "code": "passed", "h5": "awaiting-human", "out2": "failed", "code": "passed", "h5": "not-run",
"h6": "awaiting-human", "inv": "passed"}) "h6": "not-run", "inv": "passed"})
self.assertIn("awaiting-human", r.stdout) self.assertIn("not-run (needs human)", r.stdout)
self.assertIn("not-run (timed out)", r.stdout)
reasons = {x["check"]: x.get("reason") for x in self.results()}
self.assertEqual((reasons["slow"], reasons["h5"]), ("timed out", "needs human"))
def test_all_good_exit_zero_and_record_fields(self): def test_all_good_exit_zero_and_record_fields(self):
r = self.run_verify(contract([check("ok", "true"), human("h")])) r = self.run_verify(contract([check("ok", "true"), human("h")]))