Finish the work-unit record: integrate risk floor, delegations, findings and case capture; scorecard cleanup; pausing; scratch pruning bounds

This commit is contained in:
swaits committed 2026-11-23 11:41:46 -07:00
1 parent 91c954344f
commit 199d49169c
19 files changed
+428 -472

No files matched your search

+1 -1
View File
@@ -142,4 +142,4 @@ check first and slow checks in the background while you carry on, never repeatin
inputs have not changed, and finding out why a slow step is slow instead of waiting on it. inputs have not changed, and finding out why a slow step is slow instead of waiting on it.
Why: correct work that takes days when hours would do fails the human almost as badly as wrong Why: correct work that takes days when hours would do fails the human almost as badly as wrong
work. `sisi time` shows where the time went. work. `sisi status` shows where the time went.
+15
View File
@@ -76,6 +76,7 @@ def skeleton(goal=None, cwd=None):
"deferred": [], "deferred": [],
"limitations": [], "limitations": [],
"plan": [], "plan": [],
"approach": None,
"status": "open", "status": "open",
"started": _store.now(), "started": _store.now(),
"pauses": [], "pauses": [],
@@ -275,6 +276,20 @@ def _validate_new_top(c, ids, errs):
errs.append("%s.%s must be a non-empty string" % (w, 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"]): 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") errs.append(w + ": check must be a check id or null")
if "approach" in c and c["approach"] is not None:
ap = c["approach"]
if not isinstance(ap, dict):
errs.append("approach must be an object")
else:
for k in ap:
if k not in ("chosen", "why", "alternatives", "reuses"):
errs.append("approach: unknown key %r" % k)
for k in ("chosen", "why"):
if k in ap and not _str(ap[k]):
errs.append("approach.%s must be a non-empty string" % k)
for k in ("alternatives", "reuses"):
if k in ap and (not isinstance(ap[k], list) or not all(_str(x) for x in ap[k])):
errs.append("approach.%s must be a list of non-empty strings" % k)
if "limitations" in c: if "limitations" in c:
if not isinstance(c["limitations"], list) or not all(isinstance(x, str) for x in c["limitations"]): 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") errs.append("limitations must be a list of strings")
+1 -101
View File
@@ -1,5 +1,5 @@
"""Time to delivery: how long from the human's request to a verified stop, recorded by the gate """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). and read back as unit telemetry when a unit closes (see sisi.unit; `sisi status` is the one report).
Delivery row (deliveries.jsonl in the state dir): session, project, start, end (ISO UTC), seconds, send_backs (times the Delivery row (deliveries.jsonl in the state dir): session, project, start, end (ISO UTC), seconds, send_backs (times the
gate sent the agent back during this request), check_s (seconds spent running checks during this request), contract gate sent the agent back during this request), check_s (seconds spent running checks during this request), contract
@@ -94,103 +94,3 @@ def record(payload, sess, sid, cwd, now=None):
except Exception as e: except Exception as e:
store.log_error("delivery", e) store.log_error("delivery", e)
return None return None
# ---------------------------------------------------------------- reading (telemetry helpers)
DAY = 86400.0
def median(xs):
s = sorted(xs)
n = len(s)
if not n:
return None
return s[n // 2] if n % 2 else (s[n // 2 - 1] + s[n // 2]) / 2.0
def percentile(xs, p):
"""Linear-interpolation percentile (p in 0..100) of a list of numbers; None when empty."""
s = sorted(xs)
if not s:
return None
k = (len(s) - 1) * p / 100.0
lo = int(k)
hi = min(lo + 1, len(s) - 1)
return s[lo] + (s[hi] - s[lo]) * (k - lo)
def _epoch(ts):
from . import harvest
return harvest.epoch(ts) if isinstance(ts, str) else None
def summarize(rows):
secs = [r["seconds"] for r in rows]
tot = sum(secs)
chk = sum(min(r.get("check_s", 0.0), r["seconds"]) for r in rows)
return {"n": len(rows), "median_s": median(secs), "p90_s": percentile(secs, 90),
"check_share": (chk / tot) if tot > 0 else None,
"send_back_deliveries": sum(1 for r in rows if r.get("send_backs", 0) > 0)}
def windows(rows, now):
"""(last 7 days, the 7 days before) of delivery rows, by their end time."""
cur, prev = [], []
for r in rows:
if not (isinstance(r, dict) and isinstance(r.get("seconds"), (int, float))):
continue
t = _epoch(r.get("end") or r.get("ts"))
if t is None:
continue
if now - 7 * DAY <= t <= now:
cur.append(r)
elif now - 14 * DAY <= t < now - 7 * DAY:
prev.append(r)
return cur, prev
def slow_checks(results, now, top=5):
"""The slowest checks by mean duration over the last 7 days, each with a suggestion."""
from . import 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 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"])
out = out[:top]
for x in out:
if x["mean_s"] < 5:
x["suggestion"] = "quick enough: leave it in the fast tier"
elif x["tier"] == "deep":
x["suggestion"] = "already deep; split it so a quick part can run in the gate"
else:
x["suggestion"] = 'mark as "tier": "deep" if it can wait, or split it into a quick part and a slow part'
return out
def report(now=None):
now = time.time() if now is None else now
rows = store.read("deliveries")
cur, prev = windows(rows, now)
by_project = {}
for label, group in (("cur", cur), ("prev", prev)):
for r in group:
by_project.setdefault(r.get("project") or "(unknown)", {"cur": [], "prev": []})[label].append(r)
return {"now": _iso(now), "all": {"last7": summarize(cur), "prev7": summarize(prev)},
"projects": {p: {"last7": summarize(v["cur"]), "prev7": summarize(v["prev"])} for p, v in sorted(by_project.items())},
"slowest_checks": slow_checks(store.read("results"), now)}
def fmt_s(s):
if s is None:
return "-"
s = int(round(s))
if s < 60:
return "%ds" % s
if s < 3600:
return "%dm%02ds" % (s // 60, s % 60)
return "%dh%02dm" % (s // 3600, (s % 3600) // 60)
-5
View File
@@ -1,5 +0,0 @@
"""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
find = escape_candidates
+5 -3
View File
@@ -641,9 +641,11 @@ def _decide(payload):
if c is not None and C.is_unedited_skeleton(c): if c is not None and C.is_unedited_skeleton(c):
path = None # nothing real written yet: behave as if there is no contract path = None # nothing real written yet: behave as if there is no contract
sess["req_contract"] = False sess["req_contract"] = False
if c is not None and path and c.get("status") == "paused" and \ if c is not None and path and c.get("status") == "paused":
any(isinstance(p, dict) and not p.get("until") for p in (c.get("pauses") or [])): from . import unit as _unit
return "allow", None # a recorded wait: the turn may end with no demands if gitutil.root(cwd) is None or c.get("pause_fp") == gitutil.fingerprint(cwd):
return "allow", None # a recorded wait and no new change: the turn ends with no demands
_unit.resume(c, path) # the tree changed since the pause: the wait is over
if c is not None and path and c.get("status") == "closed": 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 path = None # the unit is archived; new work stands or falls on its own
sess["req_contract"] = False sess["req_contract"] = False
+12 -5
View File
@@ -25,12 +25,19 @@ def head(cwd):
return out.strip() if rc == 0 else None return out.strip() if rc == 0 else None
_EXCLUDE = ":(exclude).sisi" # sisi's own records are never part of the work being measured
def _is_sisi(rel):
return rel == ".sisi" or rel.startswith(".sisi/")
def measure(cwd, base=None, max_untracked=200): def measure(cwd, base=None, max_untracked=200):
"""Return {'lines': n, 'files': [paths]} for the working tree vs `base` (default HEAD).""" """Return {'lines': n, 'files': [paths]} for the working tree vs `base` (default HEAD)."""
cwd = root(cwd) or cwd cwd = root(cwd) or cwd
base = base or head(cwd) or EMPTY_TREE base = base or head(cwd) or EMPTY_TREE
lines, files = 0, set() lines, files = 0, set()
rc, out = _git(cwd, "diff", "--numstat", base, timeout=10) rc, out = _git(cwd, "diff", "--numstat", base, "--", ".", _EXCLUDE, timeout=10)
if rc == 0: if rc == 0:
for ln in out.splitlines(): for ln in out.splitlines():
parts = ln.split("\t", 2) parts = ln.split("\t", 2)
@@ -44,7 +51,7 @@ def measure(cwd, base=None, max_untracked=200):
rc, out = _git(cwd, "ls-files", "--others", "--exclude-standard", timeout=10) rc, out = _git(cwd, "ls-files", "--others", "--exclude-standard", timeout=10)
if rc == 0: if rc == 0:
top = cwd top = cwd
for rel in out.splitlines()[:max_untracked]: for rel in [r for r in out.splitlines() if not _is_sisi(r)][:max_untracked]:
files.add(rel) files.add(rel)
try: try:
fp = os.path.join(top, rel) fp = os.path.join(top, rel)
@@ -100,13 +107,13 @@ def fingerprint(cwd, extra_files=()):
h = hashlib.sha1() h = hashlib.sha1()
base = head(top) or EMPTY_TREE base = head(top) or EMPTY_TREE
h.update(base.encode()) h.update(base.encode())
p = subprocess.run(["git", "diff", "--no-ext-diff", "--no-textconv", "--no-color", base], cwd=top, p = subprocess.run(["git", "diff", "--no-ext-diff", "--no-textconv", "--no-color", base, "--", ".", _EXCLUDE],
capture_output=True, timeout=10) cwd=top, capture_output=True, timeout=10)
h.update(b"\0diff\0" + p.stdout) h.update(b"\0diff\0" + p.stdout)
p = subprocess.run(["git", "ls-files", "--others", "--exclude-standard", "-z"], cwd=top, p = subprocess.run(["git", "ls-files", "--others", "--exclude-standard", "-z"], cwd=top,
capture_output=True, timeout=10) capture_output=True, timeout=10)
for rel in p.stdout.split(b"\0")[:2000]: for rel in p.stdout.split(b"\0")[:2000]:
if not rel: if not rel or _is_sisi(os.fsdecode(rel)):
continue continue
try: try:
st = os.stat(os.path.join(top, os.fsdecode(rel))) st = os.stat(os.path.join(top, os.fsdecode(rel)))
+6 -6
View File
@@ -69,8 +69,8 @@ def cmd_tasks(args):
def cmd_escapes(args): def cmd_escapes(args):
from . import escapes, harvest from . import harvest, scorecard
rows = escapes.find(harvest.connect()) rows = scorecard.escape_candidates(harvest.connect())
if args.json: if args.json:
print(json.dumps(rows)) print(json.dumps(rows))
return 0 return 0
@@ -84,17 +84,17 @@ def cmd_escapes(args):
def cmd_checks(args): def cmd_checks(args):
from . import scoreboard from . import scorecard
st = scoreboard.check_stats(store.read("results")) st = scorecard.check_stats(store.read("results"))
if args.json: if args.json:
print(json.dumps(st)) print(json.dumps(st))
return 0 return 0
for title, key in (("check", "checks"), ("verifier", "verifiers")): for title, key in (("check", "checks"), ("verifier", "verifiers")):
if not st[key]: if not st[key]:
continue continue
print("%-40s %5s %5s %5s" % (title, "runs", "fail", "tmo")) print("%-40s %5s %5s %5s" % (title, "runs", "fail", "not run"))
for s in st[key]: for s in st[key]:
print("%-40s %5d %5d %5d%s" % (s["id"][:40], s["runs"], s["failures"], s["timeouts"], print("%-40s %5d %5d %5d%s" % (s["id"][:40], s["runs"], s["failures"], s["not_run"],
" never seen failing" if s["never_seen_failing"] else "")) " never seen failing" if s["never_seen_failing"] else ""))
return 0 return 0
-10
View File
@@ -1,10 +0,0 @@
"""Compatibility shim: the scoreboard folded into sisi.scorecard (SPEC 13).
`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).
"""
from .scorecard import MANY_RUNS, check_stats, iso_week, session_trends
def scoreboard(con):
return session_trends(con)
+22 -65
View File
@@ -5,7 +5,7 @@ Missing data is unavailable with value None: never zero, never good. No single s
ever computed or printed. Check statistics and escape candidates (work declared verified 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. that then turned out wrong) live here too: they feed the correctness and intent dimensions.
""" """
import datetime, json, os, re, time import json, os, re
from . import harvest, store from . import harvest, store
@@ -24,6 +24,7 @@ def unavailable():
# ---------------------------------------------------------------- check statistics # ---------------------------------------------------------------- check statistics
MANY_RUNS = 10 MANY_RUNS = 10
# rows written by earlier versions: neither of these ever meant a pass
_LEGACY = {"timeout": "not-run", "awaiting-human": "not-run"} _LEGACY = {"timeout": "not-run", "awaiting-human": "not-run"}
@@ -40,7 +41,7 @@ def check_stats(results):
if r.get("verifier"): if r.get("verifier"):
keys.append(("verifier", r["verifier"], byv)) keys.append(("verifier", r["verifier"], byv))
for _, k, d in keys: for _, k, d in keys:
s = d.setdefault(k, {"runs": 0, "failures": 0, "timeouts": 0, "not_run": 0, s = d.setdefault(k, {"runs": 0, "failures": 0, "not_run": 0,
"total_s": 0.0, "timed_runs": 0}) "total_s": 0.0, "timed_runs": 0})
s["runs"] += 1 s["runs"] += 1
if isinstance(r.get("duration_s"), (int, float)) and not isinstance(r.get("duration_s"), bool): if isinstance(r.get("duration_s"), (int, float)) and not isinstance(r.get("duration_s"), bool):
@@ -52,12 +53,11 @@ def check_stats(results):
s["failures"] += 1 s["failures"] += 1
elif st == "not-run": elif st == "not-run":
s["not_run"] += 1 s["not_run"] += 1
s["timeouts"] += 1 # legacy column name, kept for existing readers
def fin(d): def fin(d):
out = [] out = []
for k, s in sorted(d.items()): for k, s in sorted(d.items()):
s = dict(s, id=k) s = dict(s, id=k)
s["never_seen_failing"] = s["runs"] >= MANY_RUNS and s["failures"] == 0 and s["timeouts"] == 0 s["never_seen_failing"] = s["runs"] >= MANY_RUNS and s["failures"] == 0 and s["not_run"] == 0
out.append(s) out.append(s)
return out return out
return {"checks": fin(by), "verifiers": fin(byv)} return {"checks": fin(by), "verifiers": fin(byv)}
@@ -139,55 +139,6 @@ def escape_candidates(con, results=None):
return out 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 # ---------------------------------------------------------------- the eight dimensions
def _latest_by_check(results): def _latest_by_check(results):
@@ -258,7 +209,7 @@ def build_scorecard(c, results, telemetry, delivery_status):
"delegations": T("delegations"), "delegations": T("delegations"),
"overlapped_delegations": T("overlapped_delegations"), "overlapped_delegations": T("overlapped_delegations"),
"worker_minutes": T("worker_minutes"), "worker_minutes": T("worker_minutes"),
"wall_minutes": T("time_to_validated_completion_s"), "wall_time_s": T("time_to_validated_completion_s"),
}, },
"human_experience": { "human_experience": {
"human_messages": T("human_messages"), "human_messages": T("human_messages"),
@@ -351,7 +302,7 @@ def trends(units):
if kind == "model": if kind == "model":
models = u.get("models") or [] models = u.get("models") or []
return ", ".join(models) if isinstance(models, list) and models else "(no model recorded)" return ", ".join(models) if isinstance(models, list) and models else "(no model recorded)"
return u.get("policy_version") or "(none recorded)" return str(u.get("policy_version") or "(none recorded)")[:12]
out = {} out = {}
for kind in ("project", "risk profile", "model", "policy version"): for kind in ("project", "risk profile", "model", "policy version"):
groups = {} groups = {}
@@ -386,7 +337,15 @@ def _fmt_val(v):
return str(x) return str(x)
def format_status(units, learning=False, recent=8): def format_dimension(dim, vals):
shown = ["%s %s (%s)" % (k, _fmt_val(v), v.get("class")) for k, v in vals.items()
if isinstance(v, dict) and v.get("class") != "unavailable"]
n_un = sum(1 for v in vals.values() if isinstance(v, dict) and v.get("class") == "unavailable")
return " %s: %s%s" % (dim.replace("_", " "), "; ".join(shown) or "nothing recorded",
("; %d unavailable" % n_un) if n_un else "")
def format_status(units, learning=False, recent=5):
lines = [] lines = []
if not units: if not units:
lines.append("sisi status: no closed work units yet. Close one with `sisi unit close`; " lines.append("sisi status: no closed work units yet. Close one with `sisi unit close`; "
@@ -399,11 +358,7 @@ def format_status(units, learning=False, recent=8):
u.get("delivery_status"), u.get("goal") or "")) u.get("delivery_status"), u.get("goal") or ""))
sc = u.get("scorecard") or {} sc = u.get("scorecard") or {}
for dim, vals in sc.items(): for dim, vals in sc.items():
shown = ["%s %s (%s)" % (k, _fmt_val(v), v.get("class")) for k, v in vals.items() lines.append(format_dimension(dim, vals))
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("")
lines.append("trends (median / p95; segments under five units say 'too few'):") lines.append("trends (median / p95; segments under five units say 'too few'):")
for kind, segs in trends(units).items(): for kind, segs in trends(units).items():
@@ -417,12 +372,14 @@ def format_status(units, learning=False, recent=8):
v["n"] if v != "unavailable" else 0) v["n"] if v != "unavailable" else 0)
for name, v in m.items()] for name, v in m.items()]
lines.append(" %-28s %s" % (seg[:28], "; ".join(cells))) 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: if learning:
lines.append("") lines.append("")
lines.append("learning: unavailable -- the learning view lands with the retro and cycle " try:
"rebuild; until then `sisi lessons` and `sisi cycle status` hold that record.") from . import learning as _L
lines.append(_L.learning_report())
except Exception as e:
store.log_error("status-learning", e)
lines.append("learning: unavailable (%s)" % e)
return "\n".join(lines) return "\n".join(lines)
+26 -5
View File
@@ -206,12 +206,24 @@ def save_session(sid, rec):
os.replace(tmp, p) os.replace(tmp, p)
def _transcript_alive(session_file, cutoff):
"""True when the transcript this session record names was written to since `cutoff`: the
session is still going on in the host even though sisi has not touched its record."""
try:
with open(session_file, encoding="utf-8") as f:
tp = json.load(f).get("transcript_path")
return isinstance(tp, str) and os.stat(os.path.expanduser(tp)).st_mtime >= cutoff
except (OSError, ValueError, AttributeError):
return False
def prune_sessions(now=None, active_ids=(), force=False): def prune_sessions(now=None, active_ids=(), force=False):
"""Remove session-state files older than the configured age. Runs on a counter kept in """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: 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. 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 Never deletes the file of a session named active (callers pass the current session's id)
current session (callers pass its id). Returns the number of files removed.""" nor of one whose transcript the host has written to within the age. Returns the number
of files removed."""
cfg = config().get("scratch", {}) cfg = config().get("scratch", {})
d = os.path.join(paths.state(), "sessions") d = os.path.join(paths.state(), "sessions")
counter_file = os.path.join(d, ".prune-counter") counter_file = os.path.join(d, ".prune-counter")
@@ -229,29 +241,38 @@ def prune_sessions(now=None, active_ids=(), force=False):
except OSError: except OSError:
pass pass
every = max(1, int(cfg.get("prune_every", 20))) every = max(1, int(cfg.get("prune_every", 20)))
if not force and count % every != 1 % every and count != 1: if not force and (count - 1) % every != 0:
return 0 return 0 # not this start's turn: the first start and every Nth after it sweep
now = time.time() if now is None else now now = time.time() if now is None else now
cutoff = now - float(cfg.get("session_max_age_days", 30)) * 86400 cutoff = now - float(cfg.get("session_max_age_days", 30)) * 86400
keep = {safe_id(s) + ".json" for s in active_ids if s} keep = {safe_id(s) + ".json" for s in active_ids if s}
budget = float(cfg.get("prune_budget_s", 0.25)) budget = float(cfg.get("prune_budget_s", 0.25))
max_delete = int(cfg.get("prune_max_delete", 1000)) max_delete = int(cfg.get("prune_max_delete", 1000))
removed, deadline = 0, time.time() + budget removed, deadline, unfinished = 0, time.time() + budget, False
try: try:
with os.scandir(d) as it: with os.scandir(d) as it:
for e in it: for e in it:
if removed >= max_delete or time.time() > deadline: if removed >= max_delete or time.time() > deadline:
unfinished = True
break break
if not e.name.endswith(".json") or e.name in keep: if not e.name.endswith(".json") or e.name in keep:
continue continue
try: try:
if e.is_file(follow_symlinks=False) and e.stat().st_mtime < cutoff: if e.is_file(follow_symlinks=False) and e.stat().st_mtime < cutoff:
if _transcript_alive(e.path, cutoff):
continue # the host is still writing this session's transcript
os.unlink(e.path) os.unlink(e.path)
removed += 1 removed += 1
except OSError: except OSError:
pass pass
except OSError: except OSError:
pass pass
if unfinished: # out of budget with files left: the next start continues the sweep
try:
with open(counter_file, "w", encoding="utf-8") as f:
f.write("0")
except OSError:
pass
return removed return removed
-7
View File
@@ -299,10 +299,3 @@ def benchmark_cases(con):
out.append(case) out.append(case)
return out return out
def counts(con):
"""{kind: {grade: {split: n}}} for the scoreboard."""
out = {}
for r in con.execute("SELECT kind, COALESCE(grade,'-') g, split, COUNT(*) n FROM tasks GROUP BY 1,2,3"):
out.setdefault(r["kind"], {}).setdefault(r["g"], {})[r["split"]] = r["n"]
return out
+318 -145
View File
@@ -11,7 +11,7 @@ import hashlib, json, os, time
from . import contract as C, gitutil, harvest, paths, scorecard, store from . import contract as C, gitutil, harvest, paths, scorecard, store
from .scorecard import unavailable, val from .scorecard import unavailable, val
DELIVERY_STATUSES = ("delivered", "delivered-with-deferred", "deviation", "unverified", "abandoned") DELIVERY_STATUSES = ("delivered", "delivered-with-deferred", "deviation", "unverified", "abandoned") # the five of SPEC 10.3
def is_closed(c): def is_closed(c):
@@ -51,57 +51,77 @@ def fresh_id(base, project):
return "%s-%d" % (base, n) return "%s-%d" % (base, n)
# ---------------------------------------------------------------- later-wave hooks # ---------------------------------------------------------------- sources the record draws on
# 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 _git_diff_text(project, base):
import subprocess
top = gitutil.root(project)
if not top:
return ""
try:
p = subprocess.run(["git", "diff", "--no-ext-diff", base or gitutil.head(top) or gitutil.EMPTY_TREE,
"--", ".", ":(exclude).sisi"], cwd=top, capture_output=True, timeout=10)
return p.stdout.decode("utf-8", "replace")[:200000]
except Exception:
return ""
def risk_floor(c, project): def risk_floor(c, project):
"""Risk-profile floor from changed paths. Later wave (risk profiles) computes it; a """The risk floor from what changed since the unit started (committed or not), by the
contract already carrying `risk_floor` has that value taken as measured.""" product's and the project's risk table. Unavailable outside a repository."""
if isinstance(c, dict) and c.get("risk_floor"): ch = _changed_artifacts(c, project)
return val(c["risk_floor"], "measured") if ch is None:
return unavailable() return unavailable(), []
try:
from . import risk
profile, reasons = risk.assess(ch["files"], diff_text=_git_diff_text(project, c.get("base_head")),
patterns=risk.load_patterns(project))
return val(profile, "measured"), list(reasons)
except Exception as e:
store.log_error("unit-risk-floor", e)
return unavailable(), []
def retro_findings(c, project): def retro_findings(c, project):
"""Retro findings for this unit. Later wave (learning loop) fills these in.""" """The retro findings recorded for this unit (the learning store holds them)."""
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: try:
with open(p, encoding="utf-8") as f: from . import learning
lines = f.readlines() return learning.findings_for_unit(project, c.get("id"))
except OSError: except Exception as e:
return [], False store.log_error("unit-findings", e)
for line in lines: return []
try:
r = json.loads(line)
except ValueError: def learning_activity(c, project):
continue """(ids of learnings this unit created, count of recurrences it recorded)."""
if not isinstance(r, dict): try:
continue from . import learning
rp = r.get("project") or r.get("cwd") pk = learning.project_key(project)
if rp and os.path.realpath(str(rp)) != os.path.realpath(project) \ made, rec = [], 0
and not str(rp).startswith(project + os.sep): for r in learning.load_learnings():
continue if r.get("source_unit") == c.get("id") and r.get("origin_project") == pk:
t = _row_epoch(r) made.append(r.get("id"))
if t is not None and t0 is not None and not (t0 <= t <= (t1 or t)): for pv in r.get("provenance") or []:
continue if isinstance(pv, dict) and pv.get("kind") == "recurrence" \
rows.append(r) and pv.get("unit") == c.get("id") and pv.get("project") == pk:
return rows, True rec += 1
return made, rec
except Exception as e:
store.log_error("unit-learnings", e)
return [], None
def delegations(project, t0, t1):
"""The ledger's attempts for this project inside the unit's window, from the orchestration
record. The ledger names a project by its folder name. None when it cannot be read."""
if t0 is None:
return None
try:
from . import workers
return workers.delegations_for_project(os.path.basename(project.rstrip(os.sep)), t0, t1)
except Exception as e:
store.log_error("unit-delegations", e)
return None
def _row_epoch(r): def _row_epoch(r):
@@ -123,13 +143,15 @@ def policy_version(project, c):
rulebook = paths.generated() rulebook = paths.generated()
if not os.path.exists(rulebook): if not os.path.exists(rulebook):
rulebook = paths.canon("core.md") rulebook = paths.canon("core.md")
for p in (rulebook, paths.canon("floors.json"), paths.canon("risk.json"), # named by role, never by path: the same policies hash the same in any clone or project
os.path.join(project, ".sisi", "risk.json")): for role, p in (("rulebook", rulebook), ("floors", paths.canon("floors.json")),
("risk table", paths.canon("risk.json")),
("project risk table", os.path.join(project, ".sisi", "risk.json"))):
try: try:
with open(p, "rb") as f: with open(p, "rb") as f:
h.update(p.encode() + b"\0" + f.read() + b"\0") h.update(role.encode() + b"\0" + f.read() + b"\0")
except OSError: except OSError:
h.update(p.encode() + b"\0missing\0") h.update(role.encode() + b"\0missing\0")
try: try:
from . import cycle from . import cycle
h.update(json.dumps(cycle.load_enforced(), sort_keys=True, default=str).encode()) h.update(json.dumps(cycle.load_enforced(), sort_keys=True, default=str).encode())
@@ -277,25 +299,22 @@ def build_telemetry(c, project, results, t0, t1):
models = [] models = []
tel["cost"] = unavailable() # no price facts live here; never estimated from thin air tel["cost"] = unavailable() # no price facts live here; never estimated from thin air
rows, have_ledger = delegations(c, project, t0, t1) dg = delegations(project, t0, t1)
if not have_ledger: if dg is None:
for k in ("delegations", "overlapped_delegations", "worker_minutes", "time_in_delegations_s"): for k in ("delegations", "overlapped_delegations", "worker_minutes", "time_in_delegations_s"):
tel[k] = unavailable() tel[k] = unavailable()
rows = []
else: else:
tel["delegations"] = val(len(rows), "inferred") rows = dg["delegations"]
mins = [float(r["minutes"]) for r in rows if isinstance(r.get("minutes"), (int, float))] tel["delegations"] = val(dg["count"], "measured")
if mins: if dg["count"]:
tel["worker_minutes"] = val(round(sum(mins), 1), "estimated") tel["worker_minutes"] = val(round(dg["worker_minutes"], 1), "estimated")
tel["time_in_delegations_s"] = val(round(sum(mins) * 60, 1), "estimated") tel["time_in_delegations_s"] = val(round(dg["wall_minutes"] * 60, 1), "estimated")
ivs = [(_row_epoch(r), float(r["minutes"]) * 60) for r in rows tel["overlapped_delegations"] = val(dg["overlapping_pairs"], "inferred")
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: else:
tel["worker_minutes"] = unavailable() tel["worker_minutes"] = val(0, "measured")
tel["time_in_delegations_s"] = unavailable() tel["time_in_delegations_s"] = val(0, "measured")
tel["overlapped_delegations"] = unavailable() tel["overlapped_delegations"] = val(0, "measured")
changed = _changed_artifacts(c, project) changed = _changed_artifacts(c, project)
tel["files_changed"] = val(len(changed["files"]), "measured") if changed else unavailable() tel["files_changed"] = val(len(changed["files"]), "measured") if changed else unavailable()
@@ -310,12 +329,14 @@ def build_telemetry(c, project, results, t0, t1):
tel["public_surface_touched"] = unavailable() tel["public_surface_touched"] = unavailable()
findings = retro_findings(c, project) findings = retro_findings(c, project)
learnings = learning_ids(c, project) learnings, recurrences = learning_activity(c, project)
tel["retro_findings"] = val(len(findings), "measured") tel["retro_findings"] = val(len(findings), "measured")
tel["learnings_created"] = val(len(learnings), "measured") tel["learnings_created"] = val(len(learnings), "measured")
tel["recurrences"] = unavailable() tel["recurrences"] = val(recurrences, "measured") if recurrences is not None else unavailable()
tel["_models"] = models tel["_models"] = models
tel["_delegation_rows"] = rows if have_ledger else [] tel["_delegation_rows"] = rows
tel["_findings"] = findings
tel["_learnings"] = learnings
tel["_changed"] = changed tel["_changed"] = changed
return tel return tel
@@ -341,24 +362,87 @@ def _changed_artifacts(c, project):
# ---------------------------------------------------------------- the record # ---------------------------------------------------------------- the record
def _latest_results(c, rows): def latest_results(c, rows):
"""Latest recorded result per check, plus a synthesized not-run for checks never run. """The standing result of every check and invariant of the contract, and of the floor and
Synthesis is only ever not-run: a check with no record did not pass.""" enforced items of the latest fast run. A check with no record gets a synthesized `not-run`:
from . import verify as V nothing that has no record of running is ever shown as passed. Each entry also says whether
latest = {} the check ever passed in this unit, ever failed, and was waived."""
ids = {x["id"] for x in (c.get("checks") or []) + (c.get("invariants") or [])
if isinstance(x, dict) and x.get("id")}
last_fast = None
for r in rows: for r in rows:
if r.get("item") in ("check", "invariant", "floor", "enforced") and r.get("check"): if r.get("tier", "fast") == "fast" and r.get("run"):
latest[r["check"]] = {"item": r.get("item"), "id": r["check"], "status": scorecard.norm_status(r.get("status")), last_fast = r["run"]
"reason": r.get("reason"), "duration_s": r.get("duration_s", 0.0), waived = {d.get("check") for d in (c.get("deviations") or []) if isinstance(d, dict) and d.get("check")}
"mandatory": r.get("mandatory", True), "seen_failing": r.get("seen_failing"), latest, ever_passed, ever_failed = {}, set(), set()
"tier": r.get("tier", "fast"), "tail": ""} for r in rows:
cid = r.get("check")
if not cid or r.get("item") not in ("check", "invariant", "floor", "enforced"):
continue
if r["item"] in ("floor", "enforced"):
if r.get("run") != last_fast:
continue
elif cid not in ids:
continue # a check since removed from the contract no longer speaks for it
st = scorecard.norm_status(r.get("status"))
if st == "passed":
ever_passed.add(cid)
if st == "failed":
ever_failed.add(cid)
latest[cid] = {"item": r["item"], "id": cid, "status": st, "reason": r.get("reason"),
"duration_s": r.get("duration_s", 0.0), "mandatory": r.get("mandatory", True),
"tier": r.get("tier", "fast"), "ts": r.get("ts")}
for x in (c.get("checks") or []) + (c.get("invariants") or []): 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: 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", latest[x["id"]] = {"item": "check", "id": x["id"], "status": "not-run",
"reason": "needs human" if x.get("rung") in (5, 6) else "never run", "reason": "needs human" if x.get("rung") in (5, 6) else "never run",
"duration_s": 0.0, "mandatory": x.get("mandatory", True), "duration_s": 0.0, "mandatory": x.get("mandatory", True),
"seen_failing": False, "tier": x.get("tier", "fast"), "tail": ""} "tier": x.get("tier", "fast"), "ts": None}
return list(latest.values()) out = []
for cid, r in latest.items():
r["ever_passed"] = cid in ever_passed
r["seen_failing"] = cid in ever_failed
r["waived"] = cid in waived
out.append(r)
return out
def _justified_by_selection(r):
"""A check kept back because the change did not touch what it watches, where files it
watches exist. A watch that matches no file at all justifies nothing."""
return r["status"] == "skipped" and str(r.get("reason") or "").startswith("not affected")
def never_run(latest):
"""Mandatory checks that never ran to a pass in this unit and that nothing justifies
skipping. A unit with any of these cannot close as plainly delivered."""
out = []
for r in latest:
if r["item"] not in ("check", "invariant") or not r.get("mandatory", True):
continue
if r["ever_passed"] or _justified_by_selection(r):
continue
out.append(r)
return out
def decide_status(c, rows, abandon=None):
"""(delivery status or None, blocking, unrun). None with blocking results means the unit
cannot close as delivered. A waiver or an abandonment is recorded as what it is."""
from . import verify as V
latest = latest_results(c, rows)
block = V.blocking(latest)
unrun = never_run(latest)
if abandon is not None:
return "abandoned", block, unrun
if c.get("deviations"):
return "deviation", block, unrun
if block:
released = any(r.get("check") == "gate" and r.get("status") == "unverified" for r in rows)
return ("unverified" if released else None), block, unrun
if any(r["status"] == "not-run" for r in latest) or unrun or C.deferred_checks(c):
return "delivered-with-deferred", block, unrun
return "delivered", block, unrun
def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None): def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None):
@@ -368,36 +452,42 @@ def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None):
models = tel.pop("_models") models = tel.pop("_models")
delegation_rows = tel.pop("_delegation_rows") delegation_rows = tel.pop("_delegation_rows")
changed = tel.pop("_changed") changed = tel.pop("_changed")
findings = tel.pop("_findings")
learnings = tel.pop("_learnings")
ended = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(ended_epoch)) + "Z" ended = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(ended_epoch)) + "Z"
latest = _latest_results(c, rows) latest = latest_results(c, rows)
deferred_ids = [r["id"] for r in latest if r["status"] == "not-run" unrun = never_run(latest)
and str(r.get("reason") or "").startswith(("deferred", "needs human"))] floor, floor_reasons = risk_floor(c, project)
declared = c.get("risk") or {}
rec = { rec = {
"id": c["id"], "parent": c.get("parent"), "id": c["id"], "parent": c.get("parent"),
"goal": c.get("goal"), "scope": c.get("scope") or {"in": [], "out": []}, "goal": c.get("goal"), "scope": c.get("scope") or {"in": [], "out": []},
"project": project, "project": project,
"requirements": c.get("requirements") or [], "requirements": c.get("requirements") or [],
"checks": c.get("checks") or [], "invariants": c.get("invariants") or [], "checks": c.get("checks") or [], "invariants": c.get("invariants") or [],
"risk": {"floor": risk_floor(c, project), "risk": {"floor": floor, "floor_reasons": floor_reasons,
"declared": (c.get("risk") or {}).get("profile"), "declared": declared.get("profile"), "why": declared.get("why"),
"why": (c.get("risk") or {}).get("why"), "blast_radius": declared.get("blast_radius"), "rollback": declared.get("rollback")},
"blast_radius": (c.get("risk") or {}).get("blast_radius"), "approach": c.get("approach"),
"rollback": (c.get("risk") or {}).get("rollback")}, "plan": c.get("plan") or [],
"plan": c.get("plan") or [], "dependencies": c.get("dependencies") or [],
"workers": delegation_rows, "workers": delegation_rows,
"models": models, "budgets": c.get("budgets"), "models": models, "budgets": c.get("budgets"),
"started": c.get("started"), "ended": ended, "telemetry": tel, "started": c.get("started"), "ended": ended, "closed_at": ended, "telemetry": tel,
"start_commit": c.get("base_head"),
"closing_commit": gitutil.head(project) if gitutil.root(project) else None,
"changed_artifacts": changed if changed is not None else {"files": [], "lines": None}, "changed_artifacts": changed if changed is not None else {"files": [], "lines": None},
"summary": c.get("summary"),
"verification": rows, "verification": rows,
"deferred": c.get("deferred") or [], "deferred_checks": deferred_ids, "final_verification": latest,
"deferred": c.get("deferred") or [],
"deferred_checks": [r["id"] for r in latest if r["status"] == "not-run"
and str(r.get("reason") or "").startswith(("deferred", "needs human"))],
"never_run_mandatory": [{"id": r["id"], "status": r["status"], "reason": r.get("reason")} for r in unrun],
"limitations": c.get("limitations") or [], "open_risks": c.get("open_risks") or [], "limitations": c.get("limitations") or [], "open_risks": c.get("open_risks") or [],
"deviations": c.get("deviations") or [], "pauses": c.get("pauses") or [], "deviations": c.get("deviations") or [], "pauses": c.get("pauses") or [],
"delivery_status": delivery_status, "delivery_status": delivery_status,
"abandon_reason": abandon_reason, "abandon_reason": abandon_reason,
"policy_version": policy_version(project, c), "policy_version": policy_version(project, c),
"retro_findings": retro_findings(c, project), "retro_findings": findings, "learning_ids": learnings,
"learning_ids": learning_ids(c, project),
"contract": c, "contract": c,
} }
rec["scorecard"] = scorecard.build_scorecard(c, rows, tel, delivery_status) rec["scorecard"] = scorecard.build_scorecard(c, rows, tel, delivery_status)
@@ -405,12 +495,14 @@ def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None):
def summary_line(rec): def summary_line(rec):
risk = rec.get("risk") or {}
floor = (risk.get("floor") or {}).get("value") if isinstance(risk.get("floor"), dict) else risk.get("floor")
return {"id": rec["id"], "parent": rec.get("parent"), "project": rec.get("project"), return {"id": rec["id"], "parent": rec.get("parent"), "project": rec.get("project"),
"goal": rec.get("goal"), "delivery_status": rec.get("delivery_status"), "goal": rec.get("goal"), "delivery_status": rec.get("delivery_status"),
"risk": {"declared": (rec.get("risk") or {}).get("declared"), "risk": {"declared": risk.get("declared"), "floor": floor},
"floor": (rec.get("risk") or {}).get("floor")},
"models": rec.get("models") or [], "policy_version": rec.get("policy_version"), "models": rec.get("models") or [], "policy_version": rec.get("policy_version"),
"started": rec.get("started"), "ended": rec.get("ended"), "scorecard": rec.get("scorecard")} "started": rec.get("started"), "ended": rec.get("ended"), "closed_at": rec.get("closed_at"),
"scorecard": rec.get("scorecard")}
def _summary_exists(project, uid): def _summary_exists(project, uid):
@@ -419,76 +511,156 @@ def _summary_exists(project, uid):
def archive_record(rec, project): def archive_record(rec, project):
"""Write the archive with exclusive create. Returns (path, created). An existing """Write the archive so that it appears whole or not at all and is never replaced: the
archive is left byte-for-byte intact (created=False): records are never overwritten.""" full text goes to a temporary file, which is then hard-linked into place (the link fails
if the archive exists). Returns (path, created). An existing archive stays byte for byte."""
p = archive_path(project, rec["id"]) p = archive_path(project, rec["id"])
os.makedirs(os.path.dirname(p), exist_ok=True) os.makedirs(os.path.dirname(p), exist_ok=True)
try: tmp = "%s.tmp%d" % (p, os.getpid())
fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) with open(tmp, "w", encoding="utf-8") as f:
except FileExistsError: json.dump(rec, f, indent=2, default=str)
return p, False
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(rec, f, indent=2)
f.write("\n") f.write("\n")
return p, True f.flush()
os.fsync(f.fileno())
try:
try:
os.link(tmp, p)
except FileExistsError:
return p, False
except OSError: # a filesystem without hard links
try:
fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
except FileExistsError:
return p, False
with os.fdopen(fd, "w", encoding="utf-8") as f, open(tmp, encoding="utf-8") as src:
f.write(src.read())
return p, True
finally:
try:
os.unlink(tmp)
except OSError:
pass
def _capture_case(rec):
"""Offer the closed unit to the evaluation harness as a benchmark case. Never stops a close."""
try:
from . import evaluate
view = dict(rec)
view["fix_commit"] = rec.get("closing_commit")
view["request"] = rec.get("goal")
evaluate.capture_case(view)
except Exception as e:
store.log_error("unit-capture-case", e)
def close_unit(c, contract_path, project, abandon=None, now=None): def close_unit(c, contract_path, project, abandon=None, now=None):
"""Archive the open unit. Returns (record_or_None, message, ok). """Archive the open unit and mark the contract closed. Returns (record_or_None, message, ok).
Refuses with nothing written when verification blocks and no deviation, deferral Refuses with nothing written when verification blocks and no deviation, gate release or
outcome, gate release or abandonment accounts for it.""" abandonment accounts for it. Safe to repeat after a crash at any step: an archive that
from . import verify as V exists is kept as it stands and the remaining steps are completed."""
ended_epoch = time.time() if now is None else now ended_epoch = time.time() if now is None else now
path = archive_path(project, c["id"]) path = archive_path(project, c["id"])
already = os.path.exists(path) if os.path.exists(path):
if already and is_closed(c): try:
return None, "unit %s is already closed (%s); nothing changed" % (c["id"], path), True with open(path, encoding="utf-8") as f:
rows = _unit_results(c, project, c.get("started")) old = json.load(f)
latest = _latest_results(c, rows) except (OSError, ValueError):
gate_released = any(r.get("check") == "gate" and r.get("status") == "unverified" for r in rows) old = None
if abandon is not None: if is_closed(c):
status = "abandoned" return None, "unit %s is already closed (%s); nothing changed" % (c["id"], path), True
elif c.get("deviations"): if isinstance(old, dict) and old.get("started") == c.get("started") and old.get("project") == project:
status = "deviation" rec, created = old, False # a crash after archiving: complete the close from it
elif V.blocking(latest):
if gate_released:
status = "unverified"
else: else:
c["id"] = fresh_id(c["id"], project) # another unit owns this id: never overwrite it
path = archive_path(project, c["id"])
rec = None
else:
rec = None
if rec is None:
rows = _unit_results(c, project, c.get("started"))
status, block, _ = decide_status(c, rows, abandon)
if status is None:
bad = ", ".join("%s (%s%s)" % (r["id"], r["status"], ": " + r["reason"] if r.get("reason") else "") bad = ", ".join("%s (%s%s)" % (r["id"], r["status"], ": " + r["reason"] if r.get("reason") else "")
for r in V.blocking(latest)) for r in block)
return None, ("sisi: unit %s cannot close as delivered: %s. Fix and re-run `sisi verify`, " return None, ("sisi: unit %s cannot close as delivered: %s. Fix and re-run `sisi verify`, "
"record a deviation with `sisi contract waive \"<reason>\"`, or close it with " "record a deviation with `sisi contract waive \"<reason>\"`, or close it with "
"`sisi unit close --abandon \"<reason>\"`." % (c["id"], bad)), False "`sisi unit close --abandon \"<reason>\"`." % (c["id"], bad)), False
elif any(r["status"] == "not-run" for r in latest) or C.deferred_checks(c): rec = build_record(c, project, status, ended_epoch, abandon_reason=abandon)
status = "delivered-with-deferred" _, created = archive_record(rec, project)
else: if created:
status = "delivered" _capture_case(rec)
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"]): if not _summary_exists(project, rec["id"]):
store.append("units", summary_line(rec)) store.append("units", summary_line(rec))
c["status"] = "closed" c["status"] = "closed"
c["ended"] = rec.get("ended") c["ended"] = rec.get("ended")
c["delivery_status"] = rec.get("delivery_status") c["delivery_status"] = rec.get("delivery_status")
try: for pz in c.get("pauses") or []:
from . import verify as _V if isinstance(pz, dict) and not pz.get("until"):
c["closed_fp"] = _V.tree_fp(project, contract_path) pz["until"] = rec.get("ended")
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) C.save(contract_path, c)
return rec, "closed unit %s (%s): %s" % (rec["id"], rec.get("delivery_status"), path), True return rec, "closed unit %s (%s): %s" % (rec["id"], rec.get("delivery_status"), path), True
def resume(c, contract_path):
"""End a recorded wait: the unit is open again and the wait's length is recorded."""
if c.get("status") != "paused":
return False
for pz in c.get("pauses") or []:
if isinstance(pz, dict) and not pz.get("until"):
pz["until"] = store.now()
c["status"] = "open"
c.pop("pause_fp", None)
C.save(contract_path, c)
return True
def summary_for_retro(project):
"""What `sisi retro` prints: the open unit's scorecard so far and what stands out in it."""
p = os.path.join(project, C.REL)
try:
c = C.load(p)
except (OSError, ValueError):
return ""
if not isinstance(c, dict) or not c.get("id"):
return ""
now = time.time()
rows = _unit_results(c, project, c.get("started"))
latest = latest_results(c, rows)
tel = build_telemetry(c, project, rows, harvest.epoch(c["started"]) if isinstance(c.get("started"), str) else None, now)
for k in [k for k in tel if k.startswith("_")]:
tel.pop(k)
card = scorecard.build_scorecard(c, rows, tel, "open")
lines = ["unit %s (%s): %s" % (c["id"], c.get("status", "open"), c.get("goal") or ""), ""]
for dim, vals in card.items():
lines.append(scorecard.format_dimension(dim, vals))
out = []
seen = [r["id"] for r in latest if r["seen_failing"] and r["status"] == "passed"]
if seen:
out.append("failed and then passed (the evidence is real): %s" % ", ".join(seen))
failing = [r["id"] for r in latest if r["status"] == "failed"]
if failing:
out.append("still failing: %s" % ", ".join(failing))
nr = never_run(latest)
if nr:
out.append("mandatory checks that never ran to a pass: %s" % ", ".join(r["id"] for r in nr))
if c.get("deviations"):
out.append("a deviation was recorded: the unit cannot read as delivered")
hc = (tel.get("human_corrections") or {}).get("value")
if hc:
out.append("%s human correction(s) inferred from the transcript" % hc)
sb = (tel.get("send_backs") or {}).get("value")
if sb:
out.append("the gate sent the agent back %s time(s)" % sb)
unav = sorted(k for k, v in tel.items() if isinstance(v, dict) and v.get("class") == "unavailable")
if unav:
out.append("not measurable here (unavailable): %s" % ", ".join(unav))
lines += ["", "what stands out:"] + ([" - " + x for x in out] or [" nothing in the record stands out"])
lines += ["", "record each finding with `sisi retro --finding ... --cause ... --impact ... --disposition ...`; "
"then `sisi unit close` archives the unit."]
return "\n".join(lines) + "\n"
# ---------------------------------------------------------------- command # ---------------------------------------------------------------- command
def _open_contract(cwd, out): def _open_contract(cwd, out):
@@ -552,6 +724,7 @@ def cmd_unit(args, cwd=None, out=print):
else: else:
pauses.append({"what": what, "since": store.now(), "until": None}) pauses.append({"what": what, "since": store.now(), "until": None})
c["status"] = "paused" c["status"] = "paused"
c["pause_fp"] = gitutil.fingerprint(project) # a change to the tree ends the wait (see gate)
C.save(p, c) C.save(p, c)
out("unit %s paused: %s" % (c.get("id"), what)) out("unit %s paused: %s" % (c.get("id"), what))
return 0 return 0
+18 -4
View File
@@ -149,7 +149,9 @@ def input_fingerprint(c, project, x, files=None, contract_path=None):
h.update(json.dumps([x.get("cmd"), x.get("expect")], sort_keys=True, default=str).encode()) h.update(json.dumps([x.get("cmd"), x.get("expect")], sort_keys=True, default=str).encode())
wc = x.get("when_changed") wc = x.get("when_changed")
if not wc: if not wc:
fp = tree_fp(project, contract_path) # the whole tree, but not the contract file: a pause, a note or a status change in the
# contract cannot change what a command shows, and must not defeat reuse
fp = tree_fp(project, None)
if fp is None: if fp is None:
return None return None
h.update(fp.encode()) h.update(fp.encode())
@@ -293,8 +295,6 @@ def run(c, project, deadline=None, default_timeout=60, tiers=("fast",), changed=
from . import cycle from . import cycle
extra = cycle.enforced_results(c, project, deadline, default_timeout) extra = cycle.enforced_results(c, project, deadline, default_timeout)
for r in extra: for r in extra:
if r.get("status") == "timeout":
r["status"], r["reason"] = "not-run", "timed out"
r.setdefault("reason", None) r.setdefault("reason", None)
r.setdefault("mandatory", True) r.setdefault("mandatory", True)
r.setdefault("seen_failing", r.get("status") == "failed") r.setdefault("seen_failing", r.get("status") == "failed")
@@ -433,9 +433,15 @@ def cmd_verify(args, cwd=None, out=print):
good = ok(results) good = ok(results)
ds = deep.deep_state(c, project, fp) ds = deep.deep_state(c, project, fp)
saved = time_saved(results) saved = time_saved(results)
from . import unit as _unit
standing = _unit.latest_results(c, _unit._unit_results(c, project, c.get("started")))
unproven = [{"id": r["id"], "status": r["status"], "reason": r.get("reason")} for r in _unit.never_run(standing)]
if c.get("status") == "paused":
_unit.resume(c, path) # work resumed: the wait is over
if as_json: if as_json:
out(json.dumps({"contract": c["id"], "project": project, "ok": good, "tiers": list(tiers), "fingerprint": fp, out(json.dumps({"contract": c["id"], "project": project, "ok": good, "tiers": list(tiers), "fingerprint": fp,
"deep_state": deep.public(ds), "time_saved_s": saved, "results": results}, indent=2)) "deep_state": deep.public(ds), "time_saved_s": saved,
"never_run_mandatory": unproven, "results": results}, indent=2))
else: else:
if results: if results:
out(format_table(results)) out(format_table(results))
@@ -445,6 +451,14 @@ def cmd_verify(args, cwd=None, out=print):
waiting = [r["id"] for r in results if r["status"] == "not-run"] waiting = [r["id"] for r in results if r["status"] == "not-run"]
out("\nOK" + ((" (not run: %s)" % ", ".join("%s %s" % (r["id"], r.get("reason") or "") out("\nOK" + ((" (not run: %s)" % ", ".join("%s %s" % (r["id"], r.get("reason") or "")
for r in results if r["status"] == "not-run")) if waiting else "")) for r in results if r["status"] == "not-run")) if waiting else ""))
held_back = [r for r in results if r["status"] in ("skipped", "not-applicable")]
if held_back:
out("did not run (not a pass): " + "; ".join("%s %s (%s)" % (r["id"], r["status"], r.get("reason") or "")
for r in held_back))
if unproven:
out("no evidence yet: mandatory check(s) never ran to a pass: " +
", ".join("%s (%s)" % (u["id"], u["reason"] or u["status"]) for u in unproven) +
"; the unit cannot close as plainly delivered")
slow = sorted((r for r in results if r["duration_s"] > 0), key=lambda r: -r["duration_s"])[:3] slow = sorted((r for r in results if r["duration_s"] > 0), key=lambda r: -r["duration_s"])[:3]
if slow: if slow:
out("slowest checks: " + ", ".join("%s %.1fs" % (r["id"], r["duration_s"]) for r in slow)) out("slowest checks: " + ", ".join("%s %.1fs" % (r["id"], r["duration_s"]) for r in slow))
-90
View File
@@ -222,96 +222,6 @@ class DeliveryRowTests(SisiCase):
per = (time.perf_counter() - t) / 5 per = (time.perf_counter() - t) / 5
self.assertLess(per, 0.25) self.assertLess(per, 0.25)
def ref_percentile(xs, p):
s = sorted(xs)
if len(s) == 1:
return s[0]
pos = (len(s) - 1) * p / 100.0
lo, frac = int(pos // 1), pos - int(pos // 1)
return s[lo] if frac == 0 else s[lo] * (1 - frac) + s[lo + 1] * frac
class TimeCommandTests(SisiCase):
def test_small_known_values(self):
self.assertEqual(delivery.median([5, 1, 3]), 3)
self.assertEqual(delivery.median([4, 1, 3, 2]), 2.5)
self.assertEqual(delivery.percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 90), 9.1)
self.assertEqual(delivery.percentile([7], 90), 7)
self.assertIsNone(delivery.median([]))
self.assertIsNone(delivery.percentile([], 90))
def test_median_and_percentile_property(self):
rnd = random.Random(7)
for _ in range(300 * ITERS):
xs = [rnd.choice([rnd.randint(0, 50), rnd.random() * 1000]) for _ in range(rnd.randint(1, 40))]
half = sorted(xs)
n = len(half)
want_med = half[n // 2] if n % 2 else (half[n // 2 - 1] + half[n // 2]) / 2
self.assertAlmostEqual(delivery.median(xs), want_med)
for p in (0, 50, 90, 100, rnd.randint(0, 100)):
self.assertAlmostEqual(delivery.percentile(xs, p), ref_percentile(xs, p), places=6)
self.assertLessEqual(delivery.percentile(xs, 50), delivery.percentile(xs, 90) + 1e-9)
def add_rows(self, now, spec):
"""spec: list of (days_ago, seconds, project, send_backs, check_s)."""
for d, secs, proj, sb, cs in spec:
end = now - d * 86400
store.append("deliveries", {"ts": delivery._iso(end), "session": "s", "project": proj, "start": delivery._iso(end - secs),
"end": delivery._iso(end), "seconds": secs, "send_backs": sb, "check_s": cs, "contract": True})
def test_report_windows_projects_shares_and_send_backs(self):
now = time.time()
self.add_rows(now, [(1, 100, "/a/alpha", 0, 10), (2, 300, "/a/alpha", 1, 90), (3, 200, "/b/beta", 0, 20),
(9, 400, "/a/alpha", 0, 40), (10, 800, "/b/beta", 2, 80), (20, 5, "/a/alpha", 0, 0)])
r = delivery.report(now)
cur, prev = r["all"]["last7"], r["all"]["prev7"]
self.assertEqual((cur["n"], cur["median_s"], prev["n"], prev["median_s"]), (3, 200, 2, 600))
self.assertAlmostEqual(cur["check_share"], 120 / 600)
self.assertEqual(cur["send_back_deliveries"], 1)
self.assertEqual(r["projects"]["/a/alpha"]["last7"]["median_s"], 200)
self.assertEqual(r["projects"]["/b/beta"]["prev7"]["n"], 1)
out = []
delivery.cmd_time([], out=out.append)
text = "\n".join(out)
self.assertIn("median 3m20s", text)
self.assertIn("1 of 3", text)
self.assertIn("alpha", text)
js = []
delivery.cmd_time(["--json"], out=js.append)
self.assertEqual(json.loads(js[0])["all"]["last7"]["n"], 3)
def test_windows_agree_with_a_simple_reference(self):
rnd = random.Random(11)
now = time.time()
for _ in range(30 * ITERS):
rows = [{"end": delivery._iso(now - rnd.random() * 20 * 86400), "seconds": rnd.random() * 500} for _ in range(rnd.randint(0, 30))]
cur, prev = delivery.windows(rows, now)
ref_cur = [r for r in rows if now - 7 * 86400 <= harvest.epoch(r["end"]) <= now]
ref_prev = [r for r in rows if now - 14 * 86400 <= harvest.epoch(r["end"]) < now - 7 * 86400]
self.assertEqual((sorted(map(id, cur)), sorted(map(id, prev))), (sorted(map(id, ref_cur)), sorted(map(id, ref_prev))))
def test_no_data_is_said_plainly(self):
r = self.sisi("time")
self.assertEqual(r.returncode, 0)
self.assertIn("no deliveries recorded", r.stdout)
self.assertIn("no deliveries recorded in the last 7 days", self.sisi("status").stdout)
self.assertEqual(json.loads(self.sisi("time", "--json").stdout)["all"]["last7"]["n"], 0)
def test_status_shows_the_seven_day_median_and_slow_checks_get_advice(self):
now = time.time()
self.add_rows(now, [(1, 120, "/p", 0, 5), (2, 60, "/p", 0, 5), (3, 600, "/p", 0, 5)])
self.assertIn("median 2m00s over the last 7 days (3 deliveries)", self.sisi("status").stdout)
for dur in (50, 70):
store.append("results", {"ts": store.now(), "check": "slow-one", "status": "passed", "duration_s": dur, "tier": "fast"})
store.append("results", {"ts": store.now(), "check": "quick", "status": "passed", "duration_s": 0.5, "tier": "fast"})
store.append("results", {"ts": store.now(), "check": "mutation", "status": "passed", "duration_s": 300, "tier": "deep"})
slow = delivery.report(now)["slowest_checks"]
self.assertEqual([x["id"] for x in slow], ["mutation", "slow-one", "quick"])
self.assertAlmostEqual(slow[1]["mean_s"], 60)
self.assertIn('"tier": "deep"', slow[1]["suggestion"])
self.assertIn("split", slow[0]["suggestion"])
class ParallelVerifyTests(SisiCase): class ParallelVerifyTests(SisiCase):
def strip(self, results): def strip(self, results):
return [{k: r[k] for k in ("item", "id", "status", "kind", "rung", "tier")} for r in results] return [{k: r[k] for k in ("item", "id", "status", "kind", "rung", "tier")} for r in results]
+3 -2
View File
@@ -27,9 +27,10 @@ class EndToEnd(SisiCase):
r = self.sisi("gate", stdin=stop) r = self.sisi("gate", stdin=stop)
self.assertEqual((r.returncode, r.stdout), (0, "")) self.assertEqual((r.returncode, r.stdout), (0, ""))
self.assertEqual(self.sisi("unit", "close").returncode, 0)
out = self.sisi("status").stdout out = self.sisi("status").stdout
self.assertIn("contracts verified : 1", out) self.assertIn("[delivered]", out)
self.assertIn("3: 100%", out) self.assertIn("correctness and assurance", out)
self.assertEqual(self.sisi("uninstall").returncode, 0) self.assertEqual(self.sisi("uninstall").returncode, 0)
+1 -1
View File
@@ -57,7 +57,7 @@ class GateContractTests(GateBase):
a, msg = self.call() a, msg = self.call()
self.assertEqual(a, "block") self.assertEqual(a, "block")
st = {r["check"]: r["status"] for r in self.results()} st = {r["check"]: r["status"] for r in self.results()}
self.assertEqual(st, {"a": "timeout", "b": "timeout"}) # b never ran: counts as timeout self.assertEqual(st, {"a": "not-run", "b": "not-run"}) # a timed out, b never ran: neither passed
def test_three_strikes_then_unverified_release_then_reset(self): def test_three_strikes_then_unverified_release_then_reset(self):
self.write_contract(contract([check("bad", "false")])) self.write_contract(contract([check("bad", "false")]))
-1
View File
@@ -247,7 +247,6 @@ class OverlayTests(PersonalCase):
self.assertIn("rulebook %d lines" % lines, out) self.assertIn("rulebook %d lines" % lines, out)
self.assertIn("%d characters" % len(self.generated()), out) self.assertIn("%d characters" % len(self.generated()), out)
self.assertNotIn("lessons block", out) # no lesson list is loaded at session start self.assertNotIn("lessons block", out) # no lesson list is loaded at session start
self.assertIn("rulebook %d lines" % lines, self.ok("status").stdout)
def test_core_md_rules_have_unique_ids_and_the_budget_holds(self): def test_core_md_rules_have_unique_ids_and_the_budget_holds(self):
text = open(os.path.join(REPO, "canon", "core.md")).read() text = open(os.path.join(REPO, "canon", "core.md")).read()
-12
View File
@@ -106,18 +106,6 @@ class StoreTests(SisiCase):
[t.start() for t in ts]; [t.join() for t in ts] [t.start() for t in ts]; [t.join() for t in ts]
self.assertEqual(len(self.read("learn.jsonl")), 300) self.assertEqual(len(self.read("learn.jsonl")), 300)
def test_status(self):
self.write_contract(contract([check("a", "true", rung=2), check("b", "true", rung=3), human("h")]))
self.sisi("verify")
self.write_contract(contract([check("a", "false", rung=2)]))
self.sisi("verify")
self.sisi("contract", "waive", "tiny")
out = self.sisi("status").stdout
self.assertIn("contracts verified : 1", out)
self.assertIn("pass rate 50%", out)
self.assertIn("waivers : 1", out)
self.assertIn("unverified passes : 0", out)
class HelpTests(SisiCase): class HelpTests(SisiCase):
def test_help_and_unknown(self): def test_help_and_unknown(self):
-9
View File
@@ -311,15 +311,6 @@ class LintCrossCheckTests(LibCase):
self.assertIn("short.md: 30" if False else "verified: memory", r.stdout) self.assertIn("short.md: 30" if False else "verified: memory", r.stdout)
self.assertIn("warning(s)", r.stdout) self.assertIn("warning(s)", r.stdout)
def test_status_shows_library_size(self):
self.put("prove/a.md", vfile("a", extra="verified: ran\n"))
self.put("prove/b.md", vfile("b", extra="verified: memory\n"))
self.put("prove/c.md", vfile("c", extra="verified: docs\n"))
self.put("prove/d.md", vfile("d", extra="verified: docs\n"))
self.put("r.md", dfile("r"), self.ddir)
out = self.sisi("status").stdout
self.assertIn("4 verifiers (verified ran 1, docs 2, memory 1), 1 recipes", out)
class CoreMdTests(SisiCase): class CoreMdTests(SisiCase):
def test_help_lists_new_commands(self): def test_help_lists_new_commands(self):