diff --git a/sisi/cli.py b/sisi/cli.py index 63db004..399cbcb 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -5,13 +5,19 @@ HELP = """sisi is still improving A shared rulebook and enforced definitions of done for every AI coding CLI. - sisi contract init [--goal TEXT] create .sisi/contract.json here - sisi contract check validate the contract - sisi contract waive "" record that this change needs no checks + sisi contract init [--goal TEXT] start a work unit: create .sisi/contract.json here (refuses while one is open) + sisi contract check validate the contract (vacuous checks are refused) + sisi contract waive [--check ID] "" + record a deviation: a waived check does not pass; the unit closes as a deviation and the report must say so sisi contract trust | untrust allow / stop allowing this project's contract to run commands - sisi verify [--json] run the fast checks; exit 0 ok, 1 failure, 2 no contract, 3 untrusted + sisi unit close [--abandon ""] + archive the unit to .sisi/units/.json with its scorecard; --abandon records why it stopped + sisi unit pause "" + record a wait; the turn may end with no demands + sisi unit show [ID] | list print the open unit or an archived record; list this project's units + sisi verify [--json] run the selected fast checks (five statuses; nothing unrun passes); exit 0 ok, 1 failure, 2 no contract, 3 untrusted sisi verify --deep [--background] run the deep (long) checks; --background detaches and returns at once - sisi verify --all | --state run both tiers; print only the deep-check state (with --json) + sisi verify --all | --state run every check in both tiers; print only the deep-check state (with --json) sisi gate [--tool NAME] end-of-turn hook (reads hook JSON on stdin; NAME selects the tool's hook shape) sisi tick [--tool NAME] session-start hook sisi prompt [--tool NAME] prompt-submission hook: prints the matching recipe and lessons for the human's request as added context (silent when nothing strictly matches); `sisi prompt ""` tries it by hand @@ -54,8 +60,7 @@ A shared rulebook and enforced definitions of done for every AI coding CLI. its key text) and removes it from the pile sisi oracle print what the human wants: the standing principles from `sisi learn`, live at once (oracle.md in the personal folder) - sisi status verification statistics from the store - sisi time [--json] time from request to verified result: 7 days against the 7 before, slowest checks + sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score) sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json] list ways to know work is correct, by section sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it @@ -107,12 +112,36 @@ def cmd_contract(args): if sub == "init": goal = _pop_opt(args, "--goal") p = os.path.join(os.getcwd(), C.REL) + project = os.getcwd() if os.path.exists(p): - print("sisi: %s already exists" % p) - return 1 + try: + old = C.load(p) + except (OSError, ValueError): + old = None + from . import unit as _U + if not _U.is_closed(old): + print("sisi: %s already exists and the unit %s is still open. Close it first with " + "`sisi unit close`, or record why it stopped with " + "`sisi unit close --abandon \"\"`." % (p, (old or {}).get("id", "?"))) + return 1 + # A closed unit is replaced. Its archive should already exist; if a hand-edited + # contract claims closed with none, archive it now so nothing is ever lost. + if old is not None and old.get("id") and not os.path.exists(_U.archive_path(project, old["id"])): + try: + import time as _t + rec = _U.build_record(old, project, old.get("delivery_status") or "abandoned", _t.time()) + _U.archive_record(rec, project) + if not _U._summary_exists(project, rec["id"]): + store.append("units", _U.summary_line(rec)) + except Exception as e: + store.log_error("contract-init-archive", e) os.makedirs(os.path.dirname(p), exist_ok=True) + skel = C.skeleton(goal) + from . import unit as _U + skel["id"] = _U.fresh_id(skel["id"], project) + skel["base_head"] = gitutil.head(project) with open(p, "w", encoding="utf-8") as f: - json.dump(C.skeleton(goal), f, indent=2) + json.dump(skel, f, indent=2) f.write("\n") trust.add(os.getcwd()) print("created %s as a SKELETON, not a contract yet: replace the placeholder check with a real command " @@ -149,9 +178,11 @@ def cmd_contract(args): print("contract invalid" if errs else "contract ok: %s" % p) return 1 if errs else 0 if sub == "waive": - reason = " ".join(args[1:]).strip() + rest = list(args[1:]) + waived_check = _pop_opt(rest, "--check") + reason = " ".join(rest).strip() if not reason: - print('usage: sisi contract waive ""') + print('usage: sisi contract waive [--check ID] ""') return 1 import time project = gitutil.root(os.getcwd()) or os.getcwd() @@ -159,8 +190,20 @@ def cmd_contract(args): if gitutil.root(os.getcwd()): m = gitutil.measure(os.getcwd()) extra = {"head": gitutil.head(os.getcwd()), "lines": m["lines"], "files": m["files"]} - store.append("waivers", store.stamp(dict({"project": project, "reason": reason, "ns": time.time_ns()}, **extra))) - print("waiver recorded for %s" % project) + store.append("waivers", store.stamp(dict({"project": project, "reason": reason, "check": waived_check, + "ns": time.time_ns()}, **extra))) + cp = C.find(os.getcwd()) + if cp: + try: + c = C.load(cp) + if isinstance(c, dict): + c.setdefault("deviations", []).append( + {"reason": reason, "check": waived_check, "ts": store.now()}) + C.save(cp, c) + except (OSError, ValueError): + pass + print("deviation recorded for %s%s: the unit does not pass; it closes as a deviation " + "and the completion report must say so" % (project, (" (check %s)" % waived_check) if waived_check else "")) return 0 if sub in ("trust", "untrust"): p = C.find(os.getcwd()) @@ -188,94 +231,6 @@ def cmd_oracle(): return 0 -def _status_retro(): - try: - from . import learning as _L - rows = _L.load_learnings() - print("learnings : %d total, %d proposed, %d promoted (`sisi status --learning` for the report)" - % (len(rows), sum(1 for r in rows if r.get("status") == "proposed"), - sum(1 for r in rows if r.get("status") in ("promoted", "monitored")))) - except Exception: - return - - -def _status_contracts(res): - """Per recent contract: latest fast run result and the deep state.""" - from . import contract as C, deep, verify as V - last = {} - for r in res: - if r.get("run") and r.get("item") in ("check", "invariant", "floor"): - k = (r.get("project"), r.get("contract")) - e = last.setdefault(k, {"ts": "", "fast": {}}) - e["ts"] = max(e["ts"], r.get("ts", "")) - if r.get("tier", "fast") == "fast": - e["fast"].setdefault(r["run"], []).append(r["status"]) - if not last: - return - print("recent contracts:") - for (project, cid), e in sorted(last.items(), key=lambda kv: kv[1]["ts"], reverse=True)[:5]: - runs = e["fast"] - fast = "-" - if runs: - # runs are keyed by hex timestamp-pid ids: the largest key is the newest - latest = runs[max(runs, key=lambda k: int(k.split("-")[0], 16))] - fast = "pass" if all(x in ("passed", "awaiting-human") for x in latest) else "fail" - dstate = "n/a" - try: - cp = os.path.join(project, C.REL) - c = C.load(cp) - ds = deep.deep_state(c, project, V.tree_fp(project, cp)) - dstate = ds["state"] if ds else "none" - except Exception: - dstate = "unknown" - print(" %-24s fast: %-5s deep: %s" % (cid, fast, dstate)) - - -def cmd_status(): - from . import store - res = store.read("results") - runs = {} - rungs = {} - for r in res: - if r.get("item") in ("check", "invariant", "floor") and r.get("run"): - runs.setdefault((r.get("project"), r.get("contract"), r["run"]), []).append(r) - if r.get("item") == "check" and r.get("rung"): - rungs[r["rung"]] = rungs.get(r["rung"], 0) + 1 - passed = [k for k, v in runs.items() if all(x["status"] in ("passed", "awaiting-human") for x in v)] - verified = {(k[0], k[1]) for k in passed} - unver = sum(1 for r in res if r.get("status") == "unverified") - waivers = len(store.read("waivers")) - print("contracts verified : %d (of %d seen)" % (len(verified), len({(k[0], k[1]) for k in runs}))) - print("verify runs : %d, pass rate %s" % (len(runs), "%.0f%%" % (100 * len(passed) / len(runs)) if runs else "n/a")) - tot = sum(rungs.values()) - print("checks by rung : " + (", ".join("%d: %.0f%%" % (k, 100 * v / tot) for k, v in sorted(rungs.items())) if tot else "none")) - print("unverified passes : %d" % unver) - print("waivers : %d" % waivers) - try: - from . import overlay - print("always loaded : " + overlay.cost_line()) - except Exception: - pass - try: - from . import delivery - print(delivery.median_line()) - except Exception: - pass - _status_retro() - _status_contracts(res) - from . import verifiers - vs = [e for e in verifiers.load_verifiers() if e["header"]] - by = {} - for e in vs: - k = e["header"].get("verified", "unset") - by[k] = by.get(k, 0) + 1 - print("library : %d verifiers (verified ran %d, docs %d, memory %d%s), %d recipes" - % (len(vs), by.get("ran", 0), by.get("docs", 0), by.get("memory", 0), - "".join(", %s %d" % (k, v) for k, v in sorted(by.items()) if k not in ("ran", "docs", "memory")), - len(verifiers.load_recipes()))) - return 0 - - def cmd_wiring(name, args=()): from . import wiring if name == "install" and "--dry-run" in args: @@ -417,10 +372,11 @@ def main(argv): from . import risk return risk.main(args) if cmd == "status": - return cmd_status() - if cmd == "time": - from . import delivery - return delivery.cmd_time(args) + from . import scorecard + return scorecard.cmd_status(args) + if cmd == "unit": + from . import unit + return unit.cmd_unit(args) if cmd == "verifiers": from . import verifiers return verifiers.main(args) diff --git a/sisi/contract.py b/sisi/contract.py index 4782fbf..be402ab 100644 --- a/sisi/contract.py +++ b/sisi/contract.py @@ -36,11 +36,22 @@ def is_unedited_skeleton(c): return False +REQ_KINDS = ("explicit", "implied", "contextual", "anticipated", "experiential") +REQ_DECISIONS = ("now", "architect", "defer", "ignore") +RISK_PROFILES = ("trivial", "isolated", "logic", "integration", "data", "critical", "release") +UNIT_STATUSES = ("open", "paused", "closed") + + def skeleton(goal=None, cwd=None): name = re.sub(r"[^a-z0-9]+", "-", os.path.basename(os.path.abspath(cwd or os.getcwd())).lower()).strip("-") + from . import store as _store return { "id": name or "work", + "parent": None, "goal": goal or "TODO: one sentence describing the outcome", + "scope": {"in": [], "out": []}, + "requirements": [], + "risk": {}, "checks": [{ "id": "c1", "claim": "PLACEHOLDER (fast tier, runs at the end of every turn, 60 s at most): replace with what this check shows to be true", @@ -62,6 +73,13 @@ def skeleton(goal=None, cwd=None): "invariants": [], "assumptions": [], "questions": [], + "deferred": [], + "limitations": [], + "plan": [], + "status": "open", + "started": _store.now(), + "pauses": [], + "deviations": [], } @@ -70,6 +88,25 @@ def load(path): return json.load(f) +def save(path, c): + tmp = path + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + json.dump(c, f, indent=2) + f.write("\n") + os.replace(tmp, path) + + +def deferred_checks(c): + """{check_id: deferred entry} for deferred entries naming a check, by `check` or exactly by `what`.""" + out = {} + for d in c.get("deferred", []) if isinstance(c, dict) else []: + if isinstance(d, dict): + cid = d.get("check") or d.get("what") + if isinstance(cid, str) and cid: + out[cid] = d + return out + + def floors(): try: with open(paths.canon("floors.json"), encoding="utf-8") as f: @@ -132,6 +169,124 @@ def _expect(e, where, errs): 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): """Return a list of error strings; empty means valid.""" errs = [] @@ -179,6 +334,10 @@ def validate(c): _tier(ch, w, errs) if "serial" in ch and not isinstance(ch["serial"], bool): errs.append(w + ": serial must be true or false") + _check_new_fields(ch, w, errs) + vr = vacuous_reason(ch) + if vr: + errs.append("%s: %s" % (w, vr)) inv = c.get("invariants", []) if not isinstance(inv, list): errs.append("invariants must be a list") @@ -205,6 +364,10 @@ def validate(c): _tier(iv, w, errs) if "serial" in iv and not isinstance(iv["serial"], bool): errs.append(w + ": serial must be true or false") + _check_new_fields(iv, w, errs) + vr = vacuous_reason(iv) + if vr: + errs.append("%s: %s" % (w, vr)) runnable = any(isinstance(x, dict) and x.get("rung") in (1, 2, 3, 4) and x.get("cmd") for x in checks) or \ any(isinstance(x, dict) and x.get("cmd") for x in inv) if checks and not runnable: @@ -220,6 +383,7 @@ def validate(c): for i, x in enumerate(q): if not (isinstance(x, dict) and _str(x.get("q")) and "default" in x): errs.append("questions[%d] needs q and default" % i) + _validate_new_top(c, ids, errs) return errs diff --git a/sisi/deep.py b/sisi/deep.py index a0c6acd..9bbcdfd 100644 --- a/sisi/deep.py +++ b/sisi/deep.py @@ -93,7 +93,7 @@ def save_state(project, contract_id, fp, results, deep_ids): items = [{"id": r["id"], "status": r["status"], "tail": (r.get("tail") or "")[-1500:]} for r in results if r.get("tier") == "deep"] st = {"contract": contract_id, "fp": fp, "epoch": time.time(), "ids": sorted(deep_ids), - "ok": all(i["status"] in ("passed", "awaiting-human") for i in items), "items": items} + "ok": all(i["status"] in ("passed", "skipped", "not-applicable") for i in items), "items": items} p = _state_path(project) os.makedirs(os.path.dirname(p), exist_ok=True) tmp = p + ".tmp%d" % os.getpid() @@ -123,7 +123,7 @@ def deep_state(c, project, fp): st = load_state(project) if st is not None and st.get("ids") == ids: base.update(epoch=st.get("epoch"), fresh=fp is not None and st.get("fp") == fp, - failed=[i for i in st["items"] if i["status"] not in ("passed", "awaiting-human")]) + failed=[i for i in st["items"] if i["status"] in ("failed", "not-run")]) else: st = None if lock: diff --git a/sisi/delivery.py b/sisi/delivery.py index d9168e7..bf6c7e9 100644 --- a/sisi/delivery.py +++ b/sisi/delivery.py @@ -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 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 -# ---------------------------------------------------------------- reading: `sisi time` +# ---------------------------------------------------------------- reading (telemetry helpers) DAY = 86400.0 @@ -151,10 +152,10 @@ def windows(rows, now): def slow_checks(results, now, top=5): """The slowest checks by mean duration over the last 7 days, each with a suggestion.""" - from . import scoreboard + from . import scorecard recent = [r for r in results if isinstance(r, dict) and (_epoch(r.get("ts")) or 0) >= now - 7 * DAY] out = [] - for s in scoreboard.check_stats(recent)["checks"]: + for s in scorecard.check_stats(recent)["checks"]: if s.get("timed_runs"): out.append({"id": s["id"], "mean_s": s["total_s"] / s["timed_runs"], "runs": s["runs"], "tier": s.get("tier", "fast")}) out.sort(key=lambda x: -x["mean_s"]) @@ -193,43 +194,3 @@ def fmt_s(s): 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 diff --git a/sisi/escapes.py b/sisi/escapes.py index 3e766ea..0b57564 100644 --- a/sisi/escapes.py +++ b/sisi/escapes.py @@ -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 - 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 +find = escape_candidates diff --git a/sisi/gate.py b/sisi/gate.py index 4ba9c60..8ae2742 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -641,6 +641,12 @@ def _decide(payload): if c is not None and C.is_unedited_skeleton(c): path = None # nothing real written yet: behave as if there is no contract sess["req_contract"] = False + if c is not None and path and c.get("status") == "paused" 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) sess["req_project"] = top or (project if path else cwd) 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)}] else: t_run = time.time() - results = V.run(c, project, deadline, cfg["verify"]["default_timeout_s"], tiers=("fast",)) + results = V.run(c, project, deadline, cfg["verify"]["default_timeout_s"], tiers=("fast",), + reuse=False, contract_path=path) sess["req_check_s"] = float(sess.get("req_check_s", 0.0)) + (time.time() - t_run) V.record(c, project, results, fp) if V.ok(results): @@ -811,7 +818,7 @@ def _decide(payload): try: from . import retro failing = " ".join("%s %s %s" % (r["id"], r.get("kind") or "", r.get("claim") or "") - for r in results if r["status"] in ("failed", "timeout")) + for r in results if r["status"] in ("failed", "not-run")) block = retro.lessons_block(failing, "gate", session=sid) if block: msg += "\n\n" + block diff --git a/sisi/harvest.py b/sisi/harvest.py index 64caca8..52fc3ca 100644 --- a/sisi/harvest.py +++ b/sisi/harvest.py @@ -226,6 +226,86 @@ def machine_reason(text, origin_kind=None, entrypoint=None): return bool(reasons), ";".join(reasons) +# ---------------------------------------------------------------- transcript usage (telemetry) + +_USAGE_KEYS = (("input", ("input_tokens", "inputTokens")), + ("output", ("output_tokens", "outputTokens")), + ("cache_read", ("cache_read_input_tokens", "cacheReadInputTokens", "cached_input_tokens")), + ("cache_creation", ("cache_creation_input_tokens", "cacheCreationInputTokens"))) +_QUESTION_TOOLS = {"AskUserQuestion", "request_user_input", "ask_user_question"} + + +def transcript_stats(path, t0=None, t1=None): + """Token usage and human-attention counts from one Claude-Code-shaped transcript, or None + when the file cannot be read. `usage` is None when no record carried any usage numbers: + a caller must report tokens as unavailable then, never as zero. Timestamps bound the + window in epoch seconds when given. Streams the file; malformed lines are skipped.""" + try: + f = open(os.path.expanduser(path), "rb") + except (OSError, TypeError): + return None + by_model, by_cat = {}, {} + human, corrections, dialogs, subagents, first = 0, 0, 0, 0, True + with f: + for raw in f: + try: + if b"usage" not in raw and b"user" not in raw and b"tool_use" not in raw \ + and b"queued_command" not in raw: + continue + d = json.loads(raw) + if not isinstance(d, dict): + continue + ts = epoch(d["timestamp"]) if isinstance(d.get("timestamp"), str) else None + 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 class Source: diff --git a/sisi/learn_cli.py b/sisi/learn_cli.py index 96d0d5d..576861d 100644 --- a/sisi/learn_cli.py +++ b/sisi/learn_cli.py @@ -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 `. The main CLI hooks them in with `learn_cli.register(subparsers)`; each command sets `func(args) -> exit code` on its parser. @@ -99,22 +99,6 @@ def cmd_checks(args): return 0 -def cmd_scoreboard(args): - from . import scoreboard - sb = scoreboard.scoreboard(_con()) - if args.json: - print(json.dumps(sb)) - return 0 - cols = ("sessions", "turns_per_session", "corrections_per_100", "questions_per_100", "contract_share", "premature_done_share") - for title, key in (("week", "weeks"), ("repo", "repos")): - print("%-18s %s" % (title, " ".join("%-12s" % c[:12] for c in cols))) - for k, v in sb[key].items(): - print("%-18s %s" % (k[:18], " ".join("%-12s" % ("-" if v[c] is None else v[c]) for c in cols))) - print() - print("tasks:", json.dumps(sb["tasks"])) - return 0 - - def register(subparsers): p = subparsers.add_parser("harvest", help="read agent transcripts into the harvest database (incremental)") p.add_argument("--workers", type=int, default=None) @@ -146,11 +130,6 @@ def register(subparsers): p.add_argument("--json", action="store_true") p.set_defaults(func=cmd_checks) - p = subparsers.add_parser("scoreboard", help="weekly and per-repo trends from harvested sessions") - p.add_argument("--json", action="store_true") - p.set_defaults(func=cmd_scoreboard) - - def main(argv=None): ap = argparse.ArgumentParser(prog="sisi") register(ap.add_subparsers(dest="cmd", required=True)) diff --git a/sisi/scoreboard.py b/sisi/scoreboard.py index 70234fa..b0c3541 100644 --- a/sisi/scoreboard.py +++ b/sisi/scoreboard.py @@ -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: -runs, failures, timeouts. A check with MANY_RUNS or more runs and no failure or timeout is flagged -"never seen failing" (it may be a check that cannot fail). The `gate` pseudo-check is skipped. - -Scoreboard: ISO weeks (Monday start, UTC) and repo, from the harvested main sessions that a human started -(first typed message not machine-written). Trends matter, so every week uses the same definitions: - sessions human-started main sessions whose first message falls in the week - turns_per_session typed user turns per session - corrections_per_100 correction-like typed messages per 100 typed turns (the first message never counts) - questions_per_100 assistant turns that ended on a question with no tool call, plus AskUserQuestion calls, - per 100 typed turns - contract_share share of sessions that used `sisi contract`/`sisi verify` - premature_done_share among sessions with at least one completion claim, the share where a claim was - immediately followed by a correction-like message (a claim can only be "followed" by - a correction if the session went on, so this is not "sessions ending on a claim") -Only weeks and repos with at least one session appear. Completion claims, questions and corrections are -regex heuristics; compare week with week, not with an absolute truth. +`sisi status` is the one report now; the `sisi scoreboard` command is gone. These +names stay only for internal callers not yet migrated (learn_cli's checks command). """ -import datetime, json, time - -from . import harvest, store, taskset - -MANY_RUNS = 10 - - -def check_stats(results): - by, byv = {}, {} - for r in results: - if not isinstance(r, dict) or not r.get("check") or r.get("check") == "gate": - continue - keys = [("check", r["check"], by)] - if r.get("verifier"): - keys.append(("verifier", r["verifier"], byv)) - for _, k, d in keys: - s = d.setdefault(k, {"runs": 0, "failures": 0, "timeouts": 0, "total_s": 0.0, "timed_runs": 0}) - s["runs"] += 1 - if isinstance(r.get("duration_s"), (int, float)) and not isinstance(r.get("duration_s"), bool): - s["total_s"] += r["duration_s"] # for `sisi time`: which checks cost the most - s["timed_runs"] += 1 - s["tier"] = r.get("tier", "fast") - if r.get("status") == "failed": - s["failures"] += 1 - elif r.get("status") == "timeout": - s["timeouts"] += 1 - def fin(d): - out = [] - for k, s in sorted(d.items()): - s = dict(s, id=k) - s["never_seen_failing"] = s["runs"] >= MANY_RUNS and s["failures"] == 0 and s["timeouts"] == 0 - out.append(s) - return out - return {"checks": fin(by), "verifiers": fin(byv)} - - -def iso_week(t): - d = datetime.datetime.fromtimestamp(t, datetime.timezone.utc).date() - y, w, _ = d.isocalendar() - return "%04d-W%02d" % (y, w) - - -def _blank(): - return {"sessions": 0, "turns": 0, "corrections": 0, "questions": 0, "contract": 0, "claim_sessions": 0, "premature_sessions": 0} - - -def _finish(a): - n, t = a["sessions"], a["turns"] - return {"sessions": n, "turns_per_session": round(t / n, 2) if n else None, - "corrections_per_100": round(100.0 * a["corrections"] / t, 1) if t else None, - "questions_per_100": round(100.0 * a["questions"] / t, 1) if t else None, - "contract_share": round(a["contract"] / n, 3) if n else None, - "premature_done_share": round(a["premature_sessions"] / a["claim_sessions"], 3) if a["claim_sessions"] else None} - - -def _add(a, r): - a["sessions"] += 1 - a["turns"] += r["user_turns"] - a["corrections"] += r["n_corrections"] - a["questions"] += r["n_question_turns"] + r["n_ask"] - a["contract"] += 1 if (r["used_contract"] or r["used_verify"]) else 0 - if r["n_completion_claims"]: - a["claim_sessions"] += 1 - a["premature_sessions"] += 1 if r["n_premature_done"] else 0 +from .scorecard import MANY_RUNS, check_stats, iso_week, session_trends def scoreboard(con): - weeks, repos, wr = {}, {}, {} - q = ("SELECT s.t0, s.user_turns, s.n_corrections, s.n_question_turns, s.n_ask, s.used_contract, s.used_verify, " - "s.n_completion_claims, s.n_premature_done, g.repo_root FROM sessions s LEFT JOIN groundtruth g ON g.session_id=s.id " - "WHERE s.kind='main' AND s.machine=0 AND s.t0 IS NOT NULL") - for r in con.execute(q): - repo = (r["repo_root"] or "(no repo)").rstrip("/").rsplit("/", 1)[-1] - week = iso_week(r["t0"]) - for table, key in ((weeks, week), (repos, repo), (wr, (week, repo))): - _add(table.setdefault(key, _blank()), r) - return {"weeks": {k: _finish(v) for k, v in sorted(weeks.items())}, - "repos": {k: _finish(v) for k, v in sorted(repos.items())}, - "week_repo": {"%s %s" % k: _finish(v) for k, v in sorted(wr.items())}, - "tasks": taskset.counts(con)} + return session_trends(con) diff --git a/sisi/scorecard.py b/sisi/scorecard.py new file mode 100644 index 0000000..ba1590a --- /dev/null +++ b/sisi/scorecard.py @@ -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 diff --git a/sisi/store.py b/sisi/store.py index 1e214ec..2a10558 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -5,7 +5,7 @@ from . import paths FILES = {"results": "results.jsonl", "learn": "learn.jsonl", "quarantine": "learn.jsonl", "waivers": "waivers.jsonl", - "deliveries": "deliveries.jsonl"} + "deliveries": "deliveries.jsonl", "units": "units.jsonl"} def _migrate_learn(): @@ -82,7 +82,7 @@ def session_id(): return os.environ.get("SISI_SESSION_ID") or None -PERSONAL = ("learn", "quarantine") # what the person told or taught sisi: personal data, the rest is scratch +PERSONAL = ("learn", "quarantine", "units") # what the person told or taught sisi: personal data, the rest is scratch def file_path(name): @@ -156,7 +156,9 @@ def stamp(extra): DEFAULTS = {"gate": {"enabled": True, "budget_s": 120, "max_blocks": 3, "growth_lines": 40, "growth_files": 3}, "verify": {"default_timeout_s": 60, "fast_limit_s": 60}, - "retro": {"required": True}} + "retro": {"required": True}, + "scratch": {"session_max_age_days": 30, "prune_every": 20, "prune_max_delete": 1000, + "prune_budget_s": 0.25}} def config(): @@ -204,6 +206,55 @@ def save_session(sid, rec): 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): try: append("errors.log", {"ts": now(), "where": where, "error": repr(exc)}) diff --git a/sisi/tick.py b/sisi/tick.py index 7f70b6d..e5fa593 100644 --- a/sisi/tick.py +++ b/sisi/tick.py @@ -7,21 +7,9 @@ from . import store MAX_AGE_S = 30 * 86400 -def _prune(now=None): - """Delete per-session state files untouched for 30 days.""" - from . import paths - d = os.path.join(paths.state(), "sessions") - cutoff = (now or time.time()) - MAX_AGE_S - try: - with os.scandir(d) as it: - for e in it: - if e.name.endswith(".json") and e.is_file(follow_symlinks=False) and e.stat().st_mtime < cutoff: - try: - os.unlink(e.path) - except OSError: - pass - except OSError: - pass +def _prune(now=None, sid=None): + """Delete old per-session state files, bounded and on a counter (see store.prune_sessions).""" + return store.prune_sessions(now=now, active_ids=(sid,) if sid else ()) def _export_session(sid): @@ -95,7 +83,7 @@ def main(args=()): rec["baseline"] = gitutil.measure(cwd) rec["baseline_fp"] = gitutil.fingerprint(cwd, [C.find(cwd)]) store.save_session(sid, rec) - _prune() + _prune(sid=sid) from . import wiring problem = wiring.quick_problem() if problem: diff --git a/sisi/unit.py b/sisi/unit.py new file mode 100644 index 0000000..77f6649 --- /dev/null +++ b/sisi/unit.py @@ -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/.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 \"\"`, or close it with " + "`sisi unit close --abandon \"\"`." % (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 ""]') + 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 ""') + 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 \"\"] | pause \"\" | show [ID] | list") + return 1 diff --git a/sisi/verify.py b/sisi/verify.py index 1b3320c..a5455c3 100644 --- a/sisi/verify.py +++ b/sisi/verify.py @@ -1,9 +1,19 @@ -"""Run a contract: every check and invariant with a cmd, in the project dir, with a timeout.""" -import json, os, signal, subprocess, time +"""Run a contract: every selected check and invariant with a cmd, in the project dir, with a timeout. + +Five statuses only: passed, failed, skipped, not-applicable, not-run. A timeout is +not-run (timed out); a rung 5/6 check is not-run (needs human); a check kept back by +change selection is skipped (not affected by this change), or not-applicable when no +file it watches exists; an identical-inputs pass is skipped (reused: passed at