diff --git a/sisi/assure.py b/sisi/assure.py index 97d4abe..410b0d0 100644 --- a/sisi/assure.py +++ b/sisi/assure.py @@ -60,7 +60,8 @@ def _passing(r): def review_evidence(project, c, now=None): """The accepted review delegations of this project inside the unit's window whose result was - checked by something stronger than `none`. The ledger names a project by its folder name.""" + checked by something stronger than `none`, and whose worker is not the author's own model (nobody + is their own independent evidence). The ledger names a project by its folder name.""" t0 = harvest.epoch(c["started"]) if isinstance(c.get("started"), str) else None if t0 is None: return [] @@ -71,18 +72,32 @@ def review_evidence(project, c, now=None): except Exception as e: store.log_error("assure-delegations", e) return [] + from . import unitguard + models = unitguard.authors(project, c) return [r for r in dg["delegations"] if r.get("type") == "review" and r.get("outcome") == "accepted" - and r.get("check") not in (None, "", "none")] + and r.get("check") not in (None, "", "none") + and not any(unitguard.same_model(r.get("worker"), m) for m in models)] + + +def self_declared(project, c): + """Checks that call themselves independent but whose `by` is empty or is the author: [(id, by)].""" + from . import unitguard + models = unitguard.authors(project, c) + return [(x.get("id"), x.get("by")) for x in list(c.get("checks") or []) + list(c.get("invariants") or []) + if isinstance(x, dict) and x.get("independent") is True + and unitguard.is_self_reference(x.get("by"), models)] def independent_evidence(project, c, results, now=None): - """What stands behind a unit as independent evidence: a judged review in the ledger, or a - passing check that is marked independent AND says by whom or what it was produced.""" + """What stands behind a unit as independent evidence: a judged review in the ledger by a worker other than the + author, or a passing check that is marked independent AND says by whom or what it was produced (not the author).""" out = [] for r in review_evidence(project, c, now): out.append("review by %s" % (r.get("worker") or "a reviewer")) + refused = {i for i, _ in self_declared(project, c)} named = {x.get("id"): x for x in list(c.get("checks") or []) + list(c.get("invariants") or []) - if isinstance(x, dict) and x.get("independent") is True and not C.is_placeholder(x.get("by"))} + if isinstance(x, dict) and x.get("independent") is True and not C.is_placeholder(x.get("by")) + and x.get("id") not in refused} for r in results or []: if r.get("id") in named and _passing(r): out.append("check %s by %s" % (r["id"], named[r["id"]]["by"])) @@ -140,7 +155,9 @@ def missing(profile, c, project, results=None, errors=None, deep_state=None, now out.append(("the approach: what you chose, why, and an alternative you rejected", '"approach": {"chosen", "why", "alternatives": [...]}')) if req.get("independent_evidence") and not before_build and not independent_evidence(project, c, results, now): - out.append(("independent evidence that someone or something else checked this", + own = self_declared(project, c) + said = (" (not counted, `by` is the author: %s)" % ", ".join("%s by %r" % (i, b) for i, b in own[:3])) if own else "" + out.append(("independent evidence that someone or something else checked this" + said, "a reviewer's judged result (`sisi delegate judge --type review --outcome accepted " "--check review`), or a passing check with \"independent\": true and \"by\": \"\"")) if req.get("all_checks") and not before_build and deep_state is not None and deep_state not in ("fresh-pass", "none"): diff --git a/sisi/rulecmd.py b/sisi/rulecmd.py index 84dc316..63144be 100644 --- a/sisi/rulecmd.py +++ b/sisi/rulecmd.py @@ -62,6 +62,21 @@ def _dialog_names(): return "the question dialog" +def _guard_scope(): + """What the before-tool guard covers where it is registered: every file-changing tool and shell write, or + only shell commands (a Bash-only matcher). None when it is not registered or not present.""" + try: + from . import wiring + m = wiring.HOOK_MATCHERS.get("PreToolUse") + except Exception: + return None + if not _has("unitguard", "before", "after"): + return None + if m in (None, "", "*") or any(t in str(m) for t in ("Edit", "Write")): + return "a file-changing call (edit tools, shell writes) or a build delegation" + return "a shell write (this host's hook is registered for shell commands only)" + + def _own_the_outcome(): return _say(enforced=["ending a reply on a question instead of the question dialog (%s) is sent back by the end-of-turn gate" % _dialog_names() if _has("questions", "ends_with_question", "sendback", "QUESTION_DIALOG_TOOLS") @@ -75,7 +90,10 @@ def _size_by_risk(): if _gate_wired() and _has("risk", "assess", "requirements_for") and _has("assure", "effective_profile", "missing") else None, "a contract without a declared `risk.profile` is invalid" - if _has("contract", "RISK_PROFILES") and _has("assure", "missing") else None], + if _has("contract", "RISK_PROFILES") and _has("assure", "missing") else None, + "the before-tool hook works out the risk floor of the path about to change (with what this session " + "already changed) and refuses %s unless a valid unit stands behind it; the floor wins over a lower " + "declared profile without a reason" % _guard_scope() if _guard_scope() else None], measured=["`sisi risk` prints the floor and what the profile requires, the unit record keeps the profile" if _has("risk", "assess") else None], judgement=["raising the profile when you know better; lowering it needs a reason"]) @@ -86,7 +104,18 @@ def _define_done(): if _has("contract", "vacuous_reason") else None, "end-of-turn gate sends the agent back when the profile needs a contract and there is none, " "or when a check lacks what it covers, invariants or the requirement list are missing" - if _gate_wired() and _has("assure", "missing") else None], + if _gate_wired() and _has("assure", "missing") else None, + "%s is refused before it runs unless this session holds a valid unit: opened or continued by it " + "(`sisi unit continue`), not stale (`unit.stale_hours`), `sisi contract check` passing with no placeholder, " + "and carrying what its risk profile needs before building" % _guard_scope() + if _guard_scope() else None, + "`sisi unit pause` is refused without such a unit (a pause defers waiting checks and the retro, never the " + "contract), and a pause silences the gate only for the session holding the unit" + if _has("unitguard", "pause_refusal") else None, + "the gate never judges a session's changes against a unit the session does not hold: it sends back " + "to continue, park or init" if _gate_wired() and _has("unitguard", "bound_fresh") else None, + "every refusal is kept in the unit record and counted by `sisi status`" + if _has("unitguard", "record_refusal") else None], judgement=["the goal in the person's words, one check on the purpose, invariants captured before the first edit"]) @@ -95,8 +124,12 @@ def _verify_enough(): if _has("verify", "STATUSES") else None, "the end-of-turn gate runs the fast checks and sends the agent back on a failure, with the failing evidence lines" if _gate_wired() and _has("assure", "failure_lines") else None, - "high-risk profiles need evidence from someone or something other than the author" - if _has("assure", "independent_evidence") else None], + "high-risk profiles need evidence from someone or something other than the author: a check marked " + "independent does not count when `by` is empty, the session's own model or a self-reference, and a " + "review counts only from a worker other than the author's model, judged with a check stronger than none" + if _has("assure", "independent_evidence") and _has("unitguard", "is_self_reference") else + ("high-risk profiles need evidence from someone or something other than the author" + if _has("assure", "independent_evidence") else None)], measured=["a commit or merge with no passing `sisi verify` for the tree gets a notice, never a block" if _has("watch", "commit_notice") else None], judgement=["choosing the technique, which checks the change can affect, watching a test fail once"]) diff --git a/sisi/scorecard.py b/sisi/scorecard.py index 2e77eb9..9e429b0 100644 --- a/sisi/scorecard.py +++ b/sisi/scorecard.py @@ -460,6 +460,10 @@ def format_status(units, learning=False, recent=5, opened=()): lines.append("") 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))) + n_ref = u.get("guard_refusals") + n_ref = len(n_ref) if isinstance(n_ref, list) else (n_ref or 0) + if n_ref: + lines.append(" the guard refused %d building step(s) before a valid unit stood behind them" % n_ref) sc = u.get("scorecard") or {} for dim, vals in sc.items(): lines.append(format_dimension(dim, vals)) diff --git a/sisi/unit.py b/sisi/unit.py index 7049e1f..e09cb15 100644 --- a/sisi/unit.py +++ b/sisi/unit.py @@ -554,6 +554,7 @@ def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None, "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 [], "deviations": c.get("deviations") or [], "pauses": c.get("pauses") or [], + "guard_refusals": _guard_refusals(c, project), "delivery_status": delivery_status, "abandon_reason": abandon_reason, "policy_version": policy_version(project, c), @@ -564,12 +565,24 @@ def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None, return rec +def _guard_refusals(c, project): + """Every refusal the before-tool guard made for this unit (what, when): rule 3 as a mechanism.""" + try: + from . import unitguard + return [{k: r.get(k) for k in ("ts", "what", "state", "tool", "session")} + for r in unitguard.refusals_for(project, c.get("id"), c.get("started"))] + except Exception as e: + store.log_error("unit-refusals", e) + return [] + + 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"), "goal": rec.get("goal"), "delivery_status": rec.get("delivery_status"), "risk": {"declared": risk.get("declared"), "floor": floor, "lowered": bool(risk.get("lowered"))}, + "guard_refusals": len(rec.get("guard_refusals") or []), "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")} diff --git a/sisi/unitguard.py b/sisi/unitguard.py index fb178f4..802422e 100644 --- a/sisi/unitguard.py +++ b/sisi/unitguard.py @@ -136,6 +136,45 @@ def author_models(project, c): return [m for m in _load(_act_path(unit_key(project, c))).get("models", []) if isinstance(m, str)] +def is_self_reference(by, models=()): + """True when `by` (who or what produced independent evidence) is the author: a self-reference such as "me" or + "my own review" (the list is data), or a name of the session's own model.""" + text = " ".join(str(by or "").lower().split()) + if not text: + return True + words = set(re.findall(r"[a-z0-9']+", text)) + for ref in _list("self_refs"): + ref = ref.lower() + if (ref in words) if " " not in ref else re.search(r"\b" + re.escape(ref) + r"\b", text): + return True + return any(m and (m.lower() in text or text in m.lower()) for m in models) + + +def same_model(worker, model): + """Is this ledger worker the session's own model? Compares the model part of `provider/model` names.""" + if not worker or not model: + return False + w, m = str(worker).lower(), str(model).lower() + tail = lambda x: x.rsplit("/", 1)[-1].rsplit(":", 1)[-1] + return w == m or tail(w) == tail(m) or m in w or w in m + + +def current_model(): + """The model of the session running this command (the gate and the shell export its id), or None.""" + sid = store.session_id() + m = store.load_session(sid).get("model") if sid else None + return m if isinstance(m, str) and m else None + + +def authors(project, c): + """Models that wrote this unit's work: those of the sessions bound to it, and of the session asking.""" + out = list(author_models(project, c)) + cur = current_model() + if cur and cur not in out: + out.append(cur) + return out + + def bind(sid, project, c, how): """This session now works on this unit: it opened it, continued it or resumed it.""" sess = store.load_session(sid) diff --git a/tests/test_unitguard.py b/tests/test_unitguard.py index 6ccc2cf..e3145c2 100644 --- a/tests/test_unitguard.py +++ b/tests/test_unitguard.py @@ -678,5 +678,114 @@ class GateUnitTests(GuardCase): self.assertIn("c1", msg) +class IndependenceTests(GuardCase): + """Item 6: nobody is their own independent evidence (R-13.3-4).""" + + def data_unit(self, by, independent=True, model="model-a"): + self.tick(model=model) + ch = dict(real("review"), independent=independent) + if by is not None: + ch["by"] = by + c = full_contract(risk={"profile": "data", "blast_radius": "the stored rows", "rollback": "restore backup"}) + c["checks"] = [real("c1"), ch] + self.write_contract(c) + c = C.load(self.contract_path) + G.bind(self.sid, self.proj, c, "init") + return c + + def counted(self, c): + res = [{"id": "review", "status": "passed"}] + return assure.independent_evidence(self.proj, c, res) + + def test_a_self_reference_in_by_is_not_independent_evidence(self): + for by in ("my own review", "me", "myself", "self", "I checked it", "the author", "this session", "own", "", " ", None): + c = self.data_unit(by) + self.assertEqual(self.counted(c), [], repr(by)) + + def test_the_sessions_own_model_named_in_by_is_not_independent(self): + c = self.data_unit("model-a re-reading its own diff", model="model-a") + self.assertEqual(self.counted(c), []) + + def test_something_else_named_in_by_counts_when_the_check_passes(self): + c = self.data_unit("a separate reviewer agent running model-b", model="model-a") + self.assertEqual(len(self.counted(c)), 1) + self.assertEqual(self.counted(c)[0], "check review by a separate reviewer agent running model-b") + + def test_a_failing_or_unmarked_check_does_not_count_either(self): + c = self.data_unit("a separate reviewer agent") + self.assertEqual(assure.independent_evidence(self.proj, c, [{"id": "review", "status": "failed"}]), []) + c = self.data_unit("a separate reviewer agent", independent=False) + self.assertEqual(self.counted(c), []) + + def test_the_missing_list_says_why_the_claim_was_not_counted(self): + c = self.data_unit("my own review") + miss = assure.missing("data", c, self.proj, [{"id": "review", "status": "passed"}], C.validate(c)) + (what, how), = [m for m in miss if "independent" in m[0]] + self.assertIn("review by 'my own review'", what) + self.assertIn("by", how) + + def ledger(self, **row): + base = {"type": "review", "outcome": "accepted", "check": "tests", "worker": "model-b"} + return mock.patch("sisi.workers.delegations_for_project", return_value={"delegations": [dict(base, **row)]}) + + def test_a_review_by_the_sessions_own_model_does_not_count_and_another_workers_does(self): + c = self.data_unit("a separate reviewer agent", independent=False) + with self.ledger(worker="model-a"): + self.assertEqual(assure.independent_evidence(self.proj, c, []), []) + with self.ledger(worker="provider/model-a"): + self.assertEqual(assure.independent_evidence(self.proj, c, []), []) + with self.ledger(worker="model-b"): + self.assertEqual(assure.independent_evidence(self.proj, c, []), ["review by model-b"]) + + def test_a_review_judged_with_no_check_or_not_accepted_does_not_count(self): + c = self.data_unit("x", independent=False) + for row in ({"check": "none"}, {"check": None}, {"outcome": "rejected"}, {"type": "impl"}): + with self.ledger(**row): + self.assertEqual(assure.independent_evidence(self.proj, c, []), [], row) + + def test_the_gate_still_sends_back_a_data_unit_whose_only_evidence_is_the_author(self): + os.environ["SISI_RETRO_REQUIRED"] = "1" + self.addCleanup(lambda: os.environ.__setitem__("SISI_RETRO_REQUIRED", "0")) + self.data_unit("my own review") + self.put("db/schema.sql", "create table t (id integer);\n") + self.put("db/schema.sql", "create table t (id integer);\n") + a, msg = gate.decide({"session_id": "me", "cwd": self.proj, "hook_event_name": "Stop"}) + self.assertEqual(a, "block") + self.assertIn("independent evidence", msg) + + +class RecordTests(GuardCase): + """Item 6: every refusal is kept in the unit record, and `sisi status` counts them (R-10.2-1).""" + + def test_the_closed_units_record_holds_each_refusal_with_what_and_when(self): + c = self.open_unit(good_contract(checks=[dict(real("c1"), cmd="true")])) # invalid: building is refused + self.edit() + self.edit() + self.assertIn("2 building step", self.sisi("status").stdout) + c = C.load(self.contract_path) + c["checks"] = [real("c1")] + C.save(self.contract_path, c) + self.assertEqual(self.sisi("verify", env={"SISI_SESSION_ID": "me"}).returncode, 0) + r = self.sisi("unit", "close", env={"SISI_SESSION_ID": "me"}) + self.assertEqual(r.returncode, 0, r.stdout) + with open(os.path.join(self.proj, ".sisi", "units", "work.json")) as f: + rec = json.load(f) + self.assertEqual(len(rec["guard_refusals"]), 2) + self.assertEqual(rec["guard_refusals"][0]["state"], "invalid") + self.assertIn("src/app.py", rec["guard_refusals"][0]["what"]) + self.assertTrue(rec["guard_refusals"][0]["ts"]) + self.assertIn("the guard refused 2 building step", self.sisi("status").stdout) + + def test_the_rule_listing_shows_rules_two_and_three_as_enforced_with_these_mechanisms(self): + for n in ("2", "3"): + out = self.sisi("rule", n).stdout + self.assertIn("enforced:", out) + self.assertIn("before-tool hook", out) if n == "2" else self.assertIn("sisi unit continue", out) + three = self.sisi("rule", "3").stdout + for part in ("`sisi unit pause` is refused", "never judges a session's changes", "every refusal is kept"): + self.assertIn(part, three) + self.assertIn("review counts only from a worker other than the author", self.sisi("rule", "4").stdout) + + if __name__ == "__main__": unittest.main()