diff --git a/sisi/scorecard.py b/sisi/scorecard.py index 427a685..fc59b13 100644 --- a/sisi/scorecard.py +++ b/sisi/scorecard.py @@ -5,7 +5,7 @@ Missing data is unavailable with value None: never zero, never good. No single s ever computed or printed. Check statistics and escape candidates (work declared verified that then turned out wrong) live here too: they feed the correctness and intent dimensions. """ -import json, os, re +import json, os, re, time from . import harvest, store @@ -186,6 +186,7 @@ def build_scorecard(c, results, telemetry, delivery_status): "techniques": val(sorted({"rung %s" % x.get("rung") for x in items.values()} | {str(x.get("kind")) for x in items.values() if x.get("kind")}), "measured"), "checks_seen_failing": val(sum(1 for r in latest.values() if r.get("seen_failing")), "measured"), + "stronger_than_examples": val(any(x.get("rung") in (1, 2) for x in items.values()), "measured"), "independent_evidence": val(any(norm_status((latest.get(cid) or {}).get("status")) == "passed" for cid, x in items.items() if x.get("independent")), "measured"), "deviation": val(delivery_status == "deviation", "measured"), @@ -345,8 +346,74 @@ def format_dimension(dim, vals): ("; %d unavailable" % n_un) if n_un else "") -def format_status(units, learning=False, recent=5): +def _age(iso, now=None): + """'3h', '2d', '15m' since an ISO UTC time; '?' when it cannot be read.""" + from . import harvest + t = harvest.epoch(iso) if isinstance(iso, str) else None + if t is None: + return "?" + s = max(0, (time.time() if now is None else now) - t) + return "%dd" % (s // 86400) if s >= 86400 else "%dh" % (s // 3600) if s >= 3600 else "%dm" % (s // 60) + + +def open_units(cwd=None): + """The unit that is open or paused in this project, as display rows. A unit that waits (paused) + says what for and for how long; one that was declared below its floor says so, with the reason.""" + from . import contract as C, unit as U, assure + out = [] + try: + p = C.find(cwd or os.getcwd()) + c = C.load(p) if p else None + except (OSError, ValueError): + return out + if not isinstance(c, dict) or not c.get("id") or c.get("status") == "closed" or C.is_unedited_skeleton(c): + return out + project = C.project_dir(p) + row = {"id": c["id"], "status": c.get("status", "open"), "age": _age(c.get("started")), "goal": c.get("goal") or ""} + if row["status"] == "paused": + pz = next((x for x in reversed(c.get("pauses") or []) if isinstance(x, dict) and not x.get("until")), {}) + row["waiting_for"], row["paused_for"] = pz.get("what"), _age(pz.get("since")) + rk = c.get("risk") or {} + floor, _ = U.risk_floor(c, project) + floor = floor.get("value") if isinstance(floor, dict) else floor + if assure.is_lowered(floor, rk.get("profile"), rk.get("why")): + row["lowered"] = "declared %s below the floor %s: %s" % (rk.get("profile"), floor, rk.get("why")) + if c.get("unverified"): + row["unverified"] = "; ".join(c["unverified"].get("why") or []) + out.append(row) + return out + + +def _lowered_note(u): + rk = u.get("risk") or {} + if not rk.get("lowered"): + return "" + floor = rk.get("floor") + floor = floor.get("value") if isinstance(floor, dict) else floor + return " [lowered: declared %s, floor %s%s]" % (rk.get("declared"), floor, + (": " + str(rk["why"])) if rk.get("why") else "") + + +def format_open(rows): lines = [] + for r in rows: + if r["status"] == "paused": + lines.append("paused %-24s age %s waiting for: %s (for %s)" % (r["id"], r["age"], r.get("waiting_for") or "?", r.get("paused_for"))) + else: + lines.append("open %-24s age %s %s" % (r["id"], r["age"], r["goal"][:80])) + if r.get("lowered"): + lines.append(" lowered: " + r["lowered"]) + if r.get("unverified"): + lines.append(" released unverified by the gate: " + r["unverified"]) + return lines + + +def format_status(units, learning=False, recent=5, opened=()): + lines = [] + if opened: + lines.append("units in progress:") + lines += [" " + ln for ln in format_open(opened)] + lines.append("") if not units: lines.append("sisi status: no closed work units yet. Close one with `sisi unit close`; " "its scorecard will appear here.") @@ -354,8 +421,8 @@ def format_status(units, learning=False, recent=5): lines.append("recent units (newest first, %d closed in all):" % len(units)) for u in list(reversed(units))[:recent]: lines.append("") - lines.append("%s %s [%s] %s" % (u.get("id"), str(u.get("ended") or "")[:10], - u.get("delivery_status"), u.get("goal") or "")) + lines.append("%s %s [%s] %s%s" % (u.get("id"), str(u.get("ended") or "")[:10], + u.get("delivery_status"), u.get("goal") or "", _lowered_note(u))) sc = u.get("scorecard") or {} for dim, vals in sc.items(): lines.append(format_dimension(dim, vals)) @@ -385,8 +452,9 @@ def format_status(units, learning=False, recent=5): def cmd_status(args=(), cwd=None, out=print): units = load_unit_summaries(cwd) + opened = open_units(cwd) if "--json" in args: - out(json.dumps({"units": units, "trends": trends(units)}, indent=2, default=str)) + out(json.dumps({"open": opened, "units": units, "trends": trends(units)}, indent=2, default=str)) return 0 - out(format_status(units, learning="--learning" in args)) + out(format_status(units, learning="--learning" in args, opened=opened)) return 0 diff --git a/sisi/tick.py b/sisi/tick.py index e5fa593..03ed8c0 100644 --- a/sisi/tick.py +++ b/sisi/tick.py @@ -75,8 +75,7 @@ def main(args=()): rec["attr_offset"] = os.path.getsize(os.path.expanduser(payload["transcript_path"])) except OSError: rec["attr_offset"] = 0 - rec.update(attr_gen=0, attr_pass_gen=0, attr_retro_gen=0, attr_baseline_gen=0, - attr_writing=False, attr_files=[], attr_sub_offsets={}) + rec.update(attr_gen=0, seen_gen=0, dirty=False, attr_writing=False, attr_files=[], attr_sub_offsets={}) from . import contract as C, gitutil if gitutil.root(cwd): rec["head"] = gitutil.head(cwd) diff --git a/sisi/unit.py b/sisi/unit.py index 6054eee..41b744a 100644 --- a/sisi/unit.py +++ b/sisi/unit.py @@ -458,6 +458,8 @@ def decide_status(c, rows, abandon=None): return "abandoned", block, unrun if c.get("deviations"): return "deviation", block, unrun + if c.get("unverified"): # the gate released the unit after its send-backs and nothing has verified it since + return "unverified", block, unrun if block: released = any(r.get("check") == "gate" and r.get("status") == "unverified" for r in rows) return ("unverified" if released else None), block, unrun @@ -480,6 +482,8 @@ def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None, unrun = never_run(latest) floor, floor_reasons = risk_floor(c, project) declared = c.get("risk") or {} + from . import assure + floor_name = floor.get("value") if isinstance(floor, dict) else floor rec = { "id": c["id"], "parent": c.get("parent"), "goal": c.get("goal"), "scope": c.get("scope") or {"in": [], "out": []}, @@ -488,7 +492,10 @@ def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None, "checks": c.get("checks") or [], "invariants": c.get("invariants") or [], "risk": {"floor": floor, "floor_reasons": floor_reasons, "declared": declared.get("profile"), "why": declared.get("why"), + "lowered": assure.is_lowered(floor_name, declared.get("profile"), declared.get("why")), "blast_radius": declared.get("blast_radius"), "rollback": declared.get("rollback")}, + "stronger_technique": assure.stronger_technique(c), + "released_unverified": c.get("unverified"), "approach": c.get("approach"), "plan": c.get("plan") or [], "workers": delegation_rows, @@ -521,7 +528,7 @@ def summary_line(rec): floor = (risk.get("floor") or {}).get("value") if isinstance(risk.get("floor"), dict) else risk.get("floor") return {"id": rec["id"], "parent": rec.get("parent"), "project": rec.get("project"), "goal": rec.get("goal"), "delivery_status": rec.get("delivery_status"), - "risk": {"declared": risk.get("declared"), "floor": floor}, + "risk": {"declared": risk.get("declared"), "floor": floor, "lowered": bool(risk.get("lowered"))}, "models": rec.get("models") or [], "policy_version": rec.get("policy_version"), "started": rec.get("started"), "ended": rec.get("ended"), "closed_at": rec.get("closed_at"), "scorecard": rec.get("scorecard")} @@ -637,6 +644,25 @@ def resume(c, contract_path): return True +def verified_for_tree(c, project, contract_path): + """True when the unit's fast checks have a run that passed on exactly the tree as it is now + (what the commit-time notice asks). A run that was skipped or reused counts only if nothing in + it blocks and something passed. False when no run is recorded for this tree.""" + from . import verify as V + fp = V.tree_fp(project, contract_path) + if fp is None: + return True # outside git there is no tree to compare: nothing to say + runs = {} + for r in _unit_results(c, project, c.get("started")): + if r.get("fp") == fp and r.get("tier", "fast") == "fast" and r.get("run") and r.get("item") in ("check", "invariant"): + runs.setdefault(r["run"], []).append(r) + for rows in runs.values(): + if not V.blocking(rows) and any(r.get("status") == "passed" or str(r.get("reason") or "").startswith("reused: passed") + for r in rows): + return True + return False + + def summary_for_retro(project): """What `sisi retro` prints: the open unit's scorecard so far and what stands out in it.""" p = os.path.join(project, C.REL) diff --git a/sisi/watch.py b/sisi/watch.py index eb6d07f..1d86275 100644 --- a/sisi/watch.py +++ b/sisi/watch.py @@ -12,7 +12,7 @@ that errs strict, which is the safe side. A pending before-record with no after killed) is likewise treated as this session having edited, with no known paths (a sentinel). Both hooks fail open: any error is logged and the tool call proceeds. """ -import json, os, time +import json, os, re, time from . import gitutil, paths, store @@ -178,6 +178,28 @@ def changed_since_pass(sid, cwd): return gitutil.snapshot_diff(pend, gitutil.snapshot(cwd)) +_COMMIT_RE = re.compile(r"(?:^|[;&|(]\s*)(?:\w+=\S+\s+)*git\s+(?:(?:-C|-c)\s+\S+\s+|--[\w-]+\s+)*(?:commit|merge)\b") + + +def commit_notice(payload): + """One line, never a block: the command is a `git commit` or `git merge` and the open unit's fast + checks have no passing result for the tree as it is now. None when there is nothing to say.""" + tool, cmd, _ev, cwd, _sid = extract(payload) + if not is_shell(tool, cmd) or not _COMMIT_RE.search(cmd): + return None + from . import contract as C, trust, unit + path = C.find(cwd) + if not path or not trust.is_trusted(C.project_dir(path)): + return None + c = C.load(path) + if not isinstance(c, dict) or c.get("status", "open") != "open" or C.is_unedited_skeleton(c) or C.validate(c): + return None + if unit.verified_for_tree(c, C.project_dir(path), path): + return None + return ("sisi: unit %s has no passing `sisi verify` result for the tree you are about to commit; run " + "`sisi verify` first (a notice, not a block)." % c.get("id")) + + def main(args=()): try: from . import gate @@ -185,6 +207,14 @@ def main(args=()): _tool, _cmd, ev, _cwd, _sid = extract(payload) if "--before" in args or ev in BEFORE_EVENTS: before(payload) + try: + line = commit_notice(payload) + if line: + import sys + sys.stdout.write(json.dumps({"systemMessage": line, "hookSpecificOutput": { + "hookEventName": "PreToolUse", "additionalContext": line}}) + "\n") + except Exception as e: + store.log_error("watch-commit-notice", e) elif "--after" in args or ev in AFTER_EVENTS: after(payload) except Exception as e: # fail open: a tool call must never be held up by measurement