From c8aef3dc23b8050dd3c1bc2fca3299545871cce3 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 12:20:40 -0700 Subject: [PATCH 1/8] Item 1: contract must state risk.profile; init writes the floor; gate lists it. done 1 / next 2 (routing adjustments reader) --- sisi/assure.py | 5 +++++ sisi/cli.py | 2 +- sisi/contract.py | 30 +++++++++++++++++------------- tests/support.py | 4 ++-- tests/test_contract.py | 33 +++++++++++++++++++++++++++++++++ tests/test_e2e.py | 2 +- tests/test_gate.py | 14 ++++++++++++-- tests/test_verification.py | 2 +- 8 files changed, 72 insertions(+), 20 deletions(-) diff --git a/sisi/assure.py b/sisi/assure.py index 26a7e27..f63eade 100644 --- a/sisi/assure.py +++ b/sisi/assure.py @@ -103,6 +103,11 @@ def missing(profile, c, project, results=None, errors=None, deep_state=None, now absent = True else: absent = False + rk = c.get("risk") if isinstance(c.get("risk"), dict) else {} + if not absent and rk.get("profile") not in C.RISK_PROFILES: + out.append(("a declared risk profile (your own judgement of the change)", + '"risk": {"profile": %s}; `sisi risk` shows the floor' % "|".join(C.RISK_PROFILES))) + errors = [e for e in errors or [] if "risk.profile" not in e and not e.startswith("risk must be")] if errors: shown = "; ".join(errors[:3]) + ("; and %d more" % (len(errors) - 3) if len(errors) > 3 else "") out.append(("a valid contract: %s" % shown, "fix it, then `sisi contract check`")) diff --git a/sisi/cli.py b/sisi/cli.py index 9e95802..b46d5ff 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -143,7 +143,7 @@ def cmd_contract(args): except Exception as e: store.log_error("contract-init-archive", e) os.makedirs(os.path.dirname(p), exist_ok=True) - skel = C.skeleton(goal) + skel = C.skeleton(goal, project) from . import unit as _U skel["id"] = _U.fresh_id(skel["id"], project) skel["base_head"] = gitutil.head(project) diff --git a/sisi/contract.py b/sisi/contract.py index d12b86b..1db3d9c 100644 --- a/sisi/contract.py +++ b/sisi/contract.py @@ -39,19 +39,24 @@ def is_unedited_skeleton(c): REQ_KINDS = ("explicit", "implied", "contextual", "anticipated", "experiential") REQ_DECISIONS = ("now", "architect", "defer", "ignore") RISK_PROFILES = ("trivial", "isolated", "logic", "integration", "data", "critical", "release") +RISK_HINT = ("one of %s, your own judgement of the change; `sisi risk` shows the floor worked out from paths" + % ", ".join(RISK_PROFILES)) 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 + """A new contract. `risk.profile` starts at the floor of the current change; the agent judges it from there.""" + cwd = cwd or os.getcwd() + name = re.sub(r"[^a-z0-9]+", "-", os.path.basename(os.path.abspath(cwd)).lower()).strip("-") + from . import store as _store, risk as _risk + floor = _risk.floor_for_working_tree(cwd)[0] return { "id": name or "work", "parent": None, "goal": goal or "TODO: one sentence describing the outcome", "scope": {"in": [], "out": []}, "requirements": [], - "risk": {}, + "risk": {"profile": floor}, "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", @@ -337,16 +342,15 @@ def _validate_new_top(c, ids, errs): 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) + rk = c.get("risk") + if not isinstance(rk, dict): + errs.append("risk must be an object that states its profile: " + RISK_HINT) + else: + if rk.get("profile") not in RISK_PROFILES: + errs.append("risk.profile is required: " + RISK_HINT) + 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): diff --git a/tests/support.py b/tests/support.py index 232e169..46352f4 100644 --- a/tests/support.py +++ b/tests/support.py @@ -126,8 +126,8 @@ def human(id, rung=5, kind="general"): def contract(checks, invariants=()): - return {"id": "t", "goal": "g", "checks": list(checks), "invariants": list(invariants), - "assumptions": [], "questions": []} + return {"id": "t", "goal": "g", "risk": {"profile": "isolated"}, "checks": list(checks), + "invariants": list(invariants), "assumptions": [], "questions": []} def skip_timing_if_busy(case): diff --git a/tests/test_contract.py b/tests/test_contract.py index 302b59b..d60dc23 100644 --- a/tests/test_contract.py +++ b/tests/test_contract.py @@ -4,6 +4,39 @@ from sisi import contract as C class ContractTests(SisiCase): + def test_the_contract_must_state_its_risk_profile(self): + """R-5.3-1: `risk.profile` is the agent's own judgement and is required; init writes the floor as its start.""" + good = contract([check("a", "true")]) + for name, risk in (("missing", None), ("empty object", {}), ("unknown", {"profile": "huge"})): + with self.subTest(name): + c = dict(good) + c.pop("risk") + if risk is not None: + c["risk"] = risk + errs = C.validate(c) + self.assertTrue(any("risk" in e and "sisi risk" in e and "integration" in e and "release" in e + for e in errs), errs) + self.assertEqual(C.validate(good), []) + self.git_init() + self.assertEqual(self.sisi("contract", "init").returncode, 0) + c = C.load(os.path.join(self.proj, ".sisi", "contract.json")) + self.assertIn(c["risk"]["profile"], C.RISK_PROFILES) + with open(os.path.join(self.proj, "migrations_001.sql"), "w") as f: + f.write("alter table t add column c int;\n") + os.remove(os.path.join(self.proj, ".sisi", "contract.json")) + self.assertEqual(self.sisi("contract", "init").returncode, 0) + floor = self.sisi("risk", "--json") + import json as _j + self.assertEqual(C.load(os.path.join(self.proj, ".sisi", "contract.json"))["risk"]["profile"], + _j.loads(floor.stdout)["floor"]) + self.assertNotEqual(_j.loads(floor.stdout)["floor"], "trivial") + c = C.load(os.path.join(self.proj, ".sisi", "contract.json")) + c["risk"] = {} + C.save(os.path.join(self.proj, ".sisi", "contract.json"), c) + r = self.sisi("contract", "check") + self.assertEqual(r.returncode, 1) + self.assertIn("risk.profile", r.stdout) + def test_skeleton_is_valid_but_fails(self): c = C.skeleton("goal") self.assertEqual(C.validate(c), []) diff --git a/tests/test_e2e.py b/tests/test_e2e.py index e33f332..040c196 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -132,7 +132,7 @@ class EndToEnd(SisiCase): "covers": "the migration is deleted"}] c["invariants"] = [{"id": "readme", "claim": "the readme stays", "cmd": "test -f README.md", "expect": {"exit": 0}}] c["requirements"] = [{"id": "r1", "kind": "explicit", "text": "a users table exists", "decision": "now"}] - c["risk"] = {"blast_radius": "one new table; nothing reads it yet", "rollback": "drop the table"} + c["risk"] = {"profile": "data", "blast_radius": "one new table; nothing reads it yet", "rollback": "drop the table"} c["approach"] = {"chosen": "a plain SQL migration", "why": "the project already uses them", "alternatives": ["an ORM auto-migration: hides the schema"]} self.agent_writes(os.path.join(".sisi", "contract.json"), json.dumps(c)) diff --git a/tests/test_gate.py b/tests/test_gate.py index baca9b0..1956429 100644 --- a/tests/test_gate.py +++ b/tests/test_gate.py @@ -25,7 +25,7 @@ def full(**over): [dict(check("keeps", "test -f README.md"), covers="the readme is deleted")]) c.update(id="t", goal="make the feature work", requirements=[{"id": "r1", "kind": "explicit", "text": "ok.txt exists when the feature is done", "decision": "now"}], - risk={"blast_radius": "only the feature file; nothing else reads it", "rollback": "git revert the commit"}, + risk={"profile": "isolated", "blast_radius": "only the feature file; nothing else reads it", "rollback": "git revert the commit"}, approach={"chosen": "write the file directly", "why": "the simplest thing that works", "alternatives": ["generate it from a template: more moving parts"]}, started=store.now(), status="open", pauses=[], deviations=[]) @@ -174,6 +174,16 @@ class RequirementTests(GateBase): self.assertIn("sisi contract init", miss[0][1]) self.assertEqual(assure.missing("isolated", contract([check("a", "false")]), self.proj), []) + def test_a_contract_without_a_risk_profile_is_missing_one_in_the_gates_list(self): + """R-5.3-1: the declared profile is on the "what is missing" list, once, with the field that supplies it.""" + c = full() + c["risk"] = {"blast_radius": "x" * 20, "rollback": "git revert"} + miss = assure.missing("isolated", c, self.proj, errors=C.validate(c)) + self.assertEqual(len(miss), 1, miss) + self.assertIn("risk profile", miss[0][0]) + self.assertIn('"profile"', miss[0][1]) + self.assertEqual(assure.missing("isolated", full(), self.proj, errors=C.validate(full())), []) + def test_logic_needs_covers_on_every_check(self): """R-5.3-6.""" c = contract([check("a", "false"), dict(check("b", "false"), covers="the parser drops a line")]) @@ -185,7 +195,7 @@ class RequirementTests(GateBase): def test_integration_needs_invariants_requirements_a_risk_note_and_an_approach(self): """R-5.3-7: each missing piece is named, with the field that supplies it.""" - c = full(invariants=[], requirements=[], risk={}, approach=None) + c = full(invariants=[], requirements=[], risk={"profile": "isolated"}, approach=None) text = " | ".join("%s -> %s" % m for m in assure.missing("integration", c, self.proj)) for field in ('"invariants"', '"requirements"', '"risk"', '"approach"'): self.assertIn(field, text) diff --git a/tests/test_verification.py b/tests/test_verification.py index d3c9092..355e546 100644 --- a/tests/test_verification.py +++ b/tests/test_verification.py @@ -264,7 +264,7 @@ class NothingUnrunIsEverPassedTests(SisiCase): if wc: x["when_changed"] = wc return x - c = {"id": "t", "goal": "g", "assumptions": [], "questions": [], "invariants": [], + c = {"id": "t", "goal": "g", "risk": {"profile": "isolated"}, "assumptions": [], "questions": [], "invariants": [], "checks": [mk("a", "f_a", None, True), mk("b", "f_b", ["f_b*"], True), mk("c", "f_c", ["nothing/**"], True), mk("d", "f_d", None, False)]} self.write_contract(c, d) From 23a7cc7aec448818d83028d8f33f254864371bc6 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 12:21:15 -0700 Subject: [PATCH 2/8] Item 2: sisi route and delegation honour learned routing adjustments. done 2 / next 3 (failed-check evidence) --- sisi/workers.py | 19 +++++++++++++++++-- tests/test_learning_loop.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/sisi/workers.py b/sisi/workers.py index 49810a4..4b81cc5 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -656,6 +656,21 @@ def load_prefs(): return out +def effective_prefs(kind, difficulty, project): + """The user's avoid/prefer patterns plus the routing adjustments a learning cycle wrote that apply in + this project for this kind (and difficulty, when the adjustment names one). A learned entry carries + its learning id as its reason, so `sisi route --explain` shows where it came from.""" + from . import cycle + prefs = load_prefs() + for a in cycle.routing_adjustments(project): + if a.get("kind") != kind or a.get("difficulty") not in (None, difficulty): + continue + for key in ("avoid", "prefer"): + if a.get(key): + prefs[key].append({"pattern": str(a[key]), "why": "learning %s" % a.get("learning")}) + return prefs + + def _fact_dates(): dates = [] prices = load_prices() @@ -994,9 +1009,9 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev timeout = DEFAULT_RUN_TIMEOUT_S tried = [] cand = explicit - prefs = load_prefs() while True: if cand is None: + prefs = effective_prefs(kind, difficulty, cwd) result = routing.choose(candidates, read_records(), read_availability(), kind, difficulty, review_of=review_of, now=time.time(), exclude=tried, avoid=prefs["avoid"], prefer=prefs["prefer"]) @@ -1303,7 +1318,7 @@ def cmd_route(args=()): kind, difficulty = setup records = read_records() candidates, cold, excluded = routable_candidates(build_candidates(), records) - prefs = load_prefs() + prefs = effective_prefs(kind, difficulty, os.getcwd()) result = routing.choose(candidates, records, read_availability(), kind, difficulty, review_of=_opt(args, "--review-of"), now=time.time(), avoid=prefs["avoid"], prefer=prefs["prefer"]) diff --git a/tests/test_learning_loop.py b/tests/test_learning_loop.py index f78f806..0b5e179 100644 --- a/tests/test_learning_loop.py +++ b/tests/test_learning_loop.py @@ -542,6 +542,34 @@ class Mechanisms(Base): self.assertEqual(len(cycle.routing_adjustments(self.proj)), 1) self.assertEqual(cycle.routing_adjustments(self.other_project()), []) + def test_a_promoted_routing_adjustment_changes_sisi_route_for_its_project_only(self): + """R-11.1-7, R-7.1-1: the reader of routing-adjustments.json is `sisi route`: a cycle's avoid entry + moves the choice in its own project, names its learning in --explain, and leaves another project alone.""" + bindir = os.path.join(self.tmp, "bin") + os.makedirs(bindir) + tool = os.path.join(bindir, "muse") + with open(tool, "w") as f: + f.write('#!/bin/sh\nif [ "$1 $2" = "exec --list-models" ]; then echo beta-1; echo beta-2; fi\nexit 0\n') + os.chmod(tool, 0o755) + env = {"PATH": bindir} + for m, price in (("beta-1", "1"), ("beta-2", "2")): + r = self.sisi("workers", "fact", "muse/" + m, "--price", price, "--source", "fixture", env=env) + self.assertEqual(r.returncode, 0, r.stderr) + other = self.other_project() + route = ("route", "--kind", "impl", "--difficulty", "2", "--explain") + before, before_other = self.sisi(*route, env=env), self.sisi(*route, cwd=other, env=env) + self.assertEqual(before.stdout.splitlines()[0], "muse/beta-1", before.stdout) + self.assertEqual(before_other.stdout, before.stdout) + self.propose() + self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "routing", + "kind": "impl", "avoid": "beta-1"}]).returncode, 0) + after, after_other = self.sisi(*route, env=env), self.sisi(*route, cwd=other, env=env) + self.assertEqual(after.stdout.splitlines()[0], "muse/beta-2", after.stdout) + self.assertIn("learning L-0001", after.stdout) + self.assertEqual(after_other.stdout, before_other.stdout) + unrelated = self.sisi("route", "--kind", "review", "--difficulty", "2", env=env) + self.assertEqual(unrelated.stdout.splitlines()[0], "muse/beta-1") + def test_earned_scope_widens_what_a_cycle_may_apply(self): """R-11.6-2: once a learning has earned scope (two units, two projects) its risk adjustment reaches both projects and a rule it motivates needs no approval for reach alone.""" From ed018a364c1d58c0c2079f2a64d710411b11749a Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 12:22:51 -0700 Subject: [PATCH 3/8] Item 3: failed checks keep their evidence lines (verify, gate, unit record). done 3 / next 4 (dead code and seams) --- sisi/assure.py | 14 ++++++-- sisi/cycle.py | 4 +-- sisi/deep.py | 3 +- sisi/gate.py | 3 +- sisi/unit.py | 2 +- sisi/verify.py | 84 +++++++++++++++++++++++++++++++++++--------- tests/test_gate.py | 10 ++++++ tests/test_verify.py | 58 ++++++++++++++++++++++++++++++ 8 files changed, 154 insertions(+), 24 deletions(-) diff --git a/sisi/assure.py b/sisi/assure.py index f63eade..3016626 100644 --- a/sisi/assure.py +++ b/sisi/assure.py @@ -165,16 +165,24 @@ def fit(lines, limit=MAX_LINES): % (len(flat) - limit + 1)]) +def shown_lines(r, evidence_lines, tail_lines): + """The lines to show for one result: the evidence that identifies the failure first, then the last + lines of its output that the evidence did not already include.""" + ev = [ln for ln in str(r.get("evidence") or "").splitlines() if ln.strip()][:evidence_lines] + tail = [ln for ln in str(r.get("tail") or "").splitlines() if ln.strip() and ln not in ev][-tail_lines:] + return ev + tail + + def failure_lines(results, per_check=4, checks=4): - """A short report of the blocking results: id, status, and the last lines of what they printed.""" + """A short report of the blocking results: id, status, the lines that identify each failure, then + the last lines of what it printed.""" from . import verify as V out = [] bad = V.blocking(results) for r in bad[:checks]: head = "- %s [%s%s]" % (r["id"], r["status"], (": " + r["reason"]) if r.get("reason") else "") out.append(head) - tail = [ln for ln in str(r.get("tail") or "").splitlines() if ln.strip()][-per_check:] - out += [" " + ln[:200] for ln in tail] + out += [" " + ln[:200] for ln in shown_lines(r, per_check, 1)] if len(bad) > checks: out.append("- and %d more failing" % (len(bad) - checks)) return out diff --git a/sisi/cycle.py b/sisi/cycle.py index c59b88d..75f144b 100644 --- a/sisi/cycle.py +++ b/sisi/cycle.py @@ -183,8 +183,8 @@ def enforced_results(c, project, deadline=None, default_timeout=60): to = float(e.get("timeout_s") or default_timeout) if deadline is not None: to = min(to, deadline - time.time()) - st, dur, tail = V.run_cmd(e["cmd"], project, to, e.get("expect") or {"exit": 0}) - out.append(dict(base, status=st, duration_s=round(dur, 3), tail=tail, + st, dur, tail, ev = V.run_cmd(e["cmd"], project, to, e.get("expect") or {"exit": 0}) + out.append(dict(base, status=st, duration_s=round(dur, 3), tail=tail, evidence=ev, claim="enforced learning %s: %s" % (lid, e["cmd"]))) return out diff --git a/sisi/deep.py b/sisi/deep.py index 9bbcdfd..b538828 100644 --- a/sisi/deep.py +++ b/sisi/deep.py @@ -90,7 +90,8 @@ def release(project): def save_state(project, contract_id, fp, results, deep_ids): - items = [{"id": r["id"], "status": r["status"], "tail": (r.get("tail") or "")[-1500:]} + items = [{"id": r["id"], "status": r["status"], "tail": (r.get("tail") or "")[-1500:], + "evidence": r.get("evidence") or ""} 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", "skipped", "not-applicable") for i in items), "items": items} diff --git a/sisi/gate.py b/sisi/gate.py index eace829..34ca584 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -374,7 +374,8 @@ def _decide(payload): store.log_error("gate-deep", e) failing = V.blocking(results) if ds and ds["state"] == "failed" and ds["fresh"]: - failing = failing + [{"id": i["id"], "status": "failed", "reason": "deep", "tail": i["tail"]} for i in ds["failed"]] + failing = failing + [{"id": i["id"], "status": "failed", "reason": "deep", "tail": i["tail"], + "evidence": i.get("evidence") or ""} for i in ds["failed"]] miss = assure.missing(profile, c, project, results, errs, ds["state"] if ds else None) if miss or failing: diff --git a/sisi/unit.py b/sisi/unit.py index 41b744a..976b2a0 100644 --- a/sisi/unit.py +++ b/sisi/unit.py @@ -412,7 +412,7 @@ def latest_results(c, rows): 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")} + "tier": r.get("tier", "fast"), "ts": r.get("ts"), "evidence": r.get("evidence") 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: latest[x["id"]] = {"item": "check", "id": x["id"], "status": "not-run", diff --git a/sisi/verify.py b/sisi/verify.py index edb1627..0d60ec6 100644 --- a/sisi/verify.py +++ b/sisi/verify.py @@ -6,7 +6,7 @@ change selection is skipped (not affected by this change), or not-applicable whe file it watches exists; an identical-inputs pass is skipped (reused: passed at