diff --git a/.gitignore b/.gitignore index 463a491..c0deba7 100644 --- a/.gitignore +++ b/.gitignore @@ -6,9 +6,10 @@ __pycache__/ .mypy_cache/ .ruff_cache/ -# sisi run-time state in a project: only the contract is tracked +# sisi run-time state in a project: only the contract and the project's risk table are tracked .sisi/* !.sisi/contract.json +!.sisi/risk.json # scratch for delegated work .agent-work/ diff --git a/.sisi/risk.json b/.sisi/risk.json new file mode 100644 index 0000000..7022b53 --- /dev/null +++ b/.sisi/risk.json @@ -0,0 +1,15 @@ +{ + "patterns": [ + {"glob": ["sisi/hookio.py", "sisi/tick.py", "sisi/prompt.py", "sisi/watch.py", "sisi/gate.py", + "sisi/attribution.py", "sisi/questions.py", "sisi/assure.py", "bin/sisi"], + "profile": "critical", "reason": "sisi's hooks and the end-of-turn gate: they run inside every session and decide when an agent may stop"}, + {"glob": ["sisi/wiring.py", "sisi/lifecycle.py", "sisi/adapters.py"], + "profile": "critical", "reason": "sisi's installer, wiring and tool adapters: they edit other tools' configuration"}, + {"glob": ["sisi/hookjson.py"], + "profile": "critical", "reason": "sisi's JSON editor: it rewrites other tools' settings files in place"}, + {"glob": ["sisi/release.py"], + "profile": "critical", "reason": "sisi's release code: it publishes what users install"}, + {"glob": ["canon/core.md", "canon/risk.json", "sisi/risk.py", "sisi/rulecmd.py", "sisi/overlay.py"], + "profile": "integration", "reason": "sisi's rulebook and risk table: every session and every gate decision reads them"} + ] +} diff --git a/CHANGELOG.md b/CHANGELOG.md index ef82f1a..758dd64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,9 +17,25 @@ All notable changes to this project are recorded here. The format follows - Telemetry with a class on every value, the eight-dimension scorecard, and `sisi status` as the one report (recent units, then trends by project, risk profile, model and policy version). - Scratch pruning of old session state, on a counter at session start. +- The end-of-turn gate is rebuilt on risk profiles (docs/records.md, "The end-of-turn gate"): it + enforces exactly the `requirements` row of `canon/risk.json` for the profile (a contract, checks + with `covers`, invariants, a requirement list, a risk note, an `approach`, independent evidence), + in one send-back that lists everything missing; a retro is asked only when the checks are green and + a unit is open, and a recorded retro closes the unit. A contract may declare a profile below its + floor only with `risk.why`; `sisi status` shows such a unit as lowered and lists open and paused + units with their age. `independent` checks name who or what produced them (`by`). A unit the gate + released after its send-backs is `unverified` and says why. The gate notes, once, when a + logic-or-higher change has no check stronger than example tests. A commit or merge with no passing + `sisi verify` result for the tree prints a one-line notice. This repository's own `.sisi/risk.json` + is tracked. ### Removed +- The gate's line-count thresholds (`gate.growth_lines`, `gate.growth_files`) and + `canon/floors.json` (minimum rungs by self-declared check kind); `C.floors()` and + `C.floor_failures()`; the `[floor ok]` marks of `sisi verifiers for --kind`; the gate's retro demand + on every stop that edited anything and on subagents; its "someone else broke it" notice (a session + is no longer sent back for another session's edits, so there is nothing to explain). - `sisi note` and `sisi propose`: use `sisi retro` or `sisi learn`. Existing notes and proposal files in a personal store are no longer read. - `sisi audit` and the audit module. diff --git a/canon/floors.json b/canon/floors.json deleted file mode 100644 index 46e76cc..0000000 --- a/canon/floors.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "concurrency": 2, - "parsing": 2, - "money": 2, - "state-machine": 2, - "migration": 2 -} diff --git a/canon/risk.json b/canon/risk.json index 37e73c6..1047f62 100644 --- a/canon/risk.json +++ b/canon/risk.json @@ -1,13 +1,13 @@ { "profiles": ["trivial", "isolated", "logic", "integration", "data", "critical", "release"], "requirements": { - "trivial": {"contract": false, "checks": "the diff; a targeted check when one exists", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "only on an anomaly (two send-backs, or a human correction)"}, - "isolated": {"contract": true, "checks": "at least one that is not vacuous", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes"}, - "logic": {"contract": true, "checks": "as isolated, each with covers", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes"}, - "integration": {"contract": true, "checks": "as logic, plus invariants", "requirement_model": true, "risk_note": true, "independent_evidence": false, "retro": "yes"}, - "data": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"}, - "critical": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"}, - "release": {"contract": true, "checks": "every check (--all)", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"} + "trivial": {"contract": false, "checks": "the diff; a targeted check when one exists", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "only on an anomaly (two send-backs, or a human correction)", "min_checks": 0, "covers": false, "invariants": false, "approach": false, "all_checks": false, "retro_when": "anomaly"}, + "isolated": {"contract": true, "checks": "at least one that is not vacuous", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes", "min_checks": 1, "covers": false, "invariants": false, "approach": false, "all_checks": false, "retro_when": "close"}, + "logic": {"contract": true, "checks": "as isolated, each with covers", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes", "min_checks": 1, "covers": true, "invariants": false, "approach": false, "all_checks": false, "retro_when": "close"}, + "integration": {"contract": true, "checks": "as logic, plus invariants", "requirement_model": true, "risk_note": true, "independent_evidence": false, "retro": "yes", "min_checks": 1, "covers": true, "invariants": true, "approach": true, "all_checks": false, "retro_when": "close"}, + "data": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes", "min_checks": 1, "covers": true, "invariants": true, "approach": true, "all_checks": false, "retro_when": "close"}, + "critical": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes", "min_checks": 1, "covers": true, "invariants": true, "approach": true, "all_checks": false, "retro_when": "close"}, + "release": {"contract": true, "checks": "every check (--all)", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes", "min_checks": 1, "covers": true, "invariants": true, "approach": true, "all_checks": true, "retro_when": "close"} }, "patterns": [ {"stage": "code", "glob": "**/*.{py,pyi,pyw,js,mjs,cjs,jsx,ts,tsx,mts,cts,vue,svelte,astro,java,kt,kts,scala,groovy,clj,cljs,go,rs,c,h,cc,cpp,cxx,hpp,hh,hxx,m,mm,cs,fs,vb,swift,dart,rb,php,pl,pm,lua,r,jl,ex,exs,erl,hs,ml,mli,nim,zig,sh,bash,zsh,fish,ps1,bat,cmd,sol,sv,vhd,tcl,awk,asm,sql}", "profile": "isolated", "reason": "source code: never trivial, whatever its name or directory"}, diff --git a/config.default.json b/config.default.json index 8609e99..784dd43 100644 --- a/config.default.json +++ b/config.default.json @@ -2,9 +2,7 @@ "gate": { "enabled": true, "budget_s": 120, - "max_blocks": 3, - "growth_lines": 40, - "growth_files": 3 + "max_blocks": 3 }, "verify": { "default_timeout_s": 60, diff --git a/docs/design.md b/docs/design.md index ae6112e..1ef3c6d 100644 --- a/docs/design.md +++ b/docs/design.md @@ -136,8 +136,10 @@ Claude Code supports a blocking stop hook. The equivalent in OpenCode, Codex and does not exist, verification is meant to run at the next session start and failures to be reported then (that fallback is a design intention, not built). -**Floors.** Some kinds of claim have a minimum rung. Concurrency, parsing, money, state machines and data -migration may not rest on example tests alone. The floors are in `canon/floors.json`. +**What a risk profile requires.** The strength of the evidence follows the risk of the change, not the kind a +check declares for itself: logic and above need every check to say what it covers, integration and above need +invariants, a requirement list, a risk note and an approach, and data, critical and release need independent +evidence. The table is `requirements` in `canon/risk.json`; the gate enforces it and nothing else. **Formal tooling is provisioned.** sisi keeps a verifier library: for each language and kind of claim, the tool, a working template and a worked example (Kani and Verus for Rust, TLA+ or Quint and Alloy for designs, @@ -311,7 +313,7 @@ Built and covered by tests: - The end-of-turn gate (`sisi gate`) and session-start hook (`sisi tick`), wired into Claude Code with a blocking hook; wiring (`sisi install`, `uninstall`, `doctor`) also points Codex and OpenCode at the rulebook, where nothing blocks. -- The rulebook (`canon/core.md`), the minimum-rung floors, the verifier library and the recipes. +- The rulebook (`canon/core.md`), the risk table, the verifier library and the recipes. - Retrospectives and lessons (`sisi retro`, `sisi lessons`), `sisi learn` live at once, time to delivery (`sisi time`). - Choosing the approach as a checked step: the contract design section, `sisi design`, the gate's diff --git a/docs/records.md b/docs/records.md index 3a38183..f182260 100644 --- a/docs/records.md +++ b/docs/records.md @@ -31,6 +31,46 @@ plainly `delivered`. `sisi contract waive` records a deviation; it turns nothing A pause records what the unit waits for. While nothing in the tree changes the gate asks nothing; a change ends the wait. Waiting time is telemetry. +## The end-of-turn gate + +At each stop the gate asks, in order: did **this session** change anything since its last settled +stop (its own edits only, read from its transcript and the before/after shell measurement, never another +session's work in the same tree)? If not, the turn ends silently, as it does for a paused unit with no +new change and for a closed unit. Otherwise it works out the profile and enforces what that profile's +row of `canon/risk.json` requires, and nothing else: + +| Profile | Required | +|---|---| +| trivial | nothing (the retro is asked once only if the unit shows two send-backs or a human correction) | +| isolated | a contract with at least one check that can fail | +| logic | as isolated; every check has `covers` | +| integration | as logic; `invariants`, a `requirements` list (kind, text, decision), `risk.blast_radius` and `risk.rollback`, and an `approach` (chosen, why, an alternative) | +| data, critical | as integration, plus independent evidence | +| release | as data, plus every deep check passing on the tree | + +Independent evidence is an accepted `review` delegation in the ledger for this project inside the unit's +window with a check stronger than `none`, or a passing check with `"independent": true` and a `"by"` +naming who or what produced it. Text such as `TODO`, `n/a` or `none` fills no field. + +The profile is the floor (from the paths changed, see `sisi risk`) unless the contract declares a higher +one. A contract may declare a lower one only with `risk.why`; the unit then runs at the declared profile and +the record keeps floor, declared profile and reason, and `sisi status` shows it as lowered. Without a +reason the floor applies. With no unit open the floor covers the paths this session changed since its last +settled stop. + +One send-back lists everything missing, each with the command or field that supplies it, within 25 lines. +When the checks pass and everything required is present, a unit with recorded retro findings is closed and +the turn ends; otherwise the gate says once, for that state of the tree, the two ways on: `sisi retro` +(which records the findings and so closes the unit) or `sisi unit pause ""`. A pause +ends when the tree changes; `sisi contract init` refuses while a unit is open or paused; `sisi status` +lists open and paused units with their age. Send-backs are bounded (`gate.max_blocks`); when they run out +the gate lets the turn end, the unit's delivery status is `unverified`, the record says why, and the +agent is told to say so in its report. A subagent's stop never blocks and never asks for a retro; what it +observed (that it edited, and which files) is recorded for its parent's gate. When a logic-or-higher unit +has no check stronger than examples (rung 2 or better) the gate says so once, without blocking, and the +record stores whether the unit had one. A `git commit` or `git merge` whose unit has no passing result for the +current tree prints a one-line notice (`sisi verify`) and is never blocked. + ## Verification Five statuses: `passed`, `failed`, `skipped`, `not-applicable`, `not-run`; the last three always diff --git a/docs/spec/conformance.json b/docs/spec/conformance.json index a1d02a3..ef11413 100644 --- a/docs/spec/conformance.json +++ b/docs/spec/conformance.json @@ -506,15 +506,15 @@ { "id": "R-5.1-1", "status": "partial", - "how": "The rung ladder, canon/floors.json and contract invariants ask for stronger evidence than a passing test", - "evidence": "canon/floors.json", + "how": "The rung ladder, the risk table's requirements (canon/risk.json: covers, invariants, independent evidence) and contract invariants ask for stronger evidence than a passing test", + "evidence": "canon/risk.json", "gap": "A check still proves only that a command exited as expected; rung is agent-asserted and correctness kinds are not distinguished in any record." }, { "id": "R-5.1-2", "status": "partial", - "how": "The rung ladder, canon/floors.json and contract invariants ask for stronger evidence than a passing test", - "evidence": "canon/floors.json", + "how": "The rung ladder, the risk table's requirements (canon/risk.json: covers, invariants, independent evidence) and contract invariants ask for stronger evidence than a passing test", + "evidence": "canon/risk.json", "gap": "A check still proves only that a command exited as expected; rung is agent-asserted and correctness kinds are not distinguished in any record." }, { @@ -527,15 +527,15 @@ { "id": "R-5.1-4", "status": "partial", - "how": "The rung ladder, canon/floors.json and contract invariants ask for stronger evidence than a passing test", - "evidence": "canon/floors.json", + "how": "The rung ladder, the risk table's requirements (canon/risk.json: covers, invariants, independent evidence) and contract invariants ask for stronger evidence than a passing test", + "evidence": "canon/risk.json", "gap": "A check still proves only that a command exited as expected; rung is agent-asserted and correctness kinds are not distinguished in any record." }, { "id": "R-5.1-5", "status": "partial", - "how": "The rung ladder, canon/floors.json and contract invariants ask for stronger evidence than a passing test", - "evidence": "canon/floors.json", + "how": "The rung ladder, the risk table's requirements (canon/risk.json: covers, invariants, independent evidence) and contract invariants ask for stronger evidence than a passing test", + "evidence": "canon/risk.json", "gap": "A check still proves only that a command exited as expected; rung is agent-asserted and correctness kinds are not distinguished in any record." }, { @@ -548,8 +548,8 @@ { "id": "R-5.1-7", "status": "partial", - "how": "The rung ladder, canon/floors.json and contract invariants ask for stronger evidence than a passing test", - "evidence": "canon/floors.json", + "how": "The rung ladder, the risk table's requirements (canon/risk.json: covers, invariants, independent evidence) and contract invariants ask for stronger evidence than a passing test", + "evidence": "canon/risk.json", "gap": "A check still proves only that a command exited as expected; rung is agent-asserted and correctness kinds are not distinguished in any record." }, { @@ -597,8 +597,8 @@ { "id": "R-5.3-1", "status": "partial", - "how": "canon/floors.json sets a minimum rung by self-declared check kind and the contract splits fast and deep tiers", - "evidence": "canon/floors.json", + "how": "canon/risk.json sets what each risk profile requires of a contract (checks with covers, invariants, an approach, independent evidence) and the contract splits fast and deep tiers", + "evidence": "canon/risk.json", "gap": "Floors compare the rung label only, so cmd true at rung 1 satisfies a floor, and no impact, likelihood, blast-radius or reversibility assessment selects the depth." }, { @@ -611,57 +611,57 @@ { "id": "R-5.3-3", "status": "partial", - "how": "canon/floors.json sets a minimum rung by self-declared check kind and the contract splits fast and deep tiers", - "evidence": "canon/floors.json", + "how": "canon/risk.json sets what each risk profile requires of a contract (checks with covers, invariants, an approach, independent evidence) and the contract splits fast and deep tiers", + "evidence": "canon/risk.json", "gap": "Floors compare the rung label only, so cmd true at rung 1 satisfies a floor, and no impact, likelihood, blast-radius or reversibility assessment selects the depth." }, { "id": "R-5.3-4", "status": "partial", - "how": "canon/floors.json sets a minimum rung by self-declared check kind and the contract splits fast and deep tiers", - "evidence": "canon/floors.json", + "how": "canon/risk.json sets what each risk profile requires of a contract (checks with covers, invariants, an approach, independent evidence) and the contract splits fast and deep tiers", + "evidence": "canon/risk.json", "gap": "Floors compare the rung label only, so cmd true at rung 1 satisfies a floor, and no impact, likelihood, blast-radius or reversibility assessment selects the depth." }, { "id": "R-5.3-5", "status": "partial", - "how": "canon/floors.json sets a minimum rung by self-declared check kind and the contract splits fast and deep tiers", - "evidence": "canon/floors.json", + "how": "canon/risk.json sets what each risk profile requires of a contract (checks with covers, invariants, an approach, independent evidence) and the contract splits fast and deep tiers", + "evidence": "canon/risk.json", "gap": "Floors compare the rung label only, so cmd true at rung 1 satisfies a floor, and no impact, likelihood, blast-radius or reversibility assessment selects the depth." }, { "id": "R-5.3-6", "status": "partial", - "how": "canon/floors.json sets a minimum rung by self-declared check kind and the contract splits fast and deep tiers", - "evidence": "canon/floors.json", + "how": "canon/risk.json sets what each risk profile requires of a contract (checks with covers, invariants, an approach, independent evidence) and the contract splits fast and deep tiers", + "evidence": "canon/risk.json", "gap": "Floors compare the rung label only, so cmd true at rung 1 satisfies a floor, and no impact, likelihood, blast-radius or reversibility assessment selects the depth." }, { "id": "R-5.3-7", "status": "partial", - "how": "canon/floors.json sets a minimum rung by self-declared check kind and the contract splits fast and deep tiers", - "evidence": "canon/floors.json", + "how": "canon/risk.json sets what each risk profile requires of a contract (checks with covers, invariants, an approach, independent evidence) and the contract splits fast and deep tiers", + "evidence": "canon/risk.json", "gap": "Floors compare the rung label only, so cmd true at rung 1 satisfies a floor, and no impact, likelihood, blast-radius or reversibility assessment selects the depth." }, { "id": "R-5.3-8", "status": "partial", - "how": "canon/floors.json sets a minimum rung by self-declared check kind and the contract splits fast and deep tiers", - "evidence": "canon/floors.json", + "how": "canon/risk.json sets what each risk profile requires of a contract (checks with covers, invariants, an approach, independent evidence) and the contract splits fast and deep tiers", + "evidence": "canon/risk.json", "gap": "Floors compare the rung label only, so cmd true at rung 1 satisfies a floor, and no impact, likelihood, blast-radius or reversibility assessment selects the depth." }, { "id": "R-5.3-9", "status": "partial", - "how": "canon/floors.json sets a minimum rung by self-declared check kind and the contract splits fast and deep tiers", - "evidence": "canon/floors.json", + "how": "canon/risk.json sets what each risk profile requires of a contract (checks with covers, invariants, an approach, independent evidence) and the contract splits fast and deep tiers", + "evidence": "canon/risk.json", "gap": "Floors compare the rung label only, so cmd true at rung 1 satisfies a floor, and no impact, likelihood, blast-radius or reversibility assessment selects the depth." }, { "id": "R-5.3-10", "status": "partial", - "how": "canon/floors.json sets a minimum rung by self-declared check kind and the contract splits fast and deep tiers", - "evidence": "canon/floors.json", + "how": "canon/risk.json sets what each risk profile requires of a contract (checks with covers, invariants, an approach, independent evidence) and the contract splits fast and deep tiers", + "evidence": "canon/risk.json", "gap": "Floors compare the rung label only, so cmd true at rung 1 satisfies a floor, and no impact, likelihood, blast-radius or reversibility assessment selects the depth." }, { diff --git a/docs/target.md b/docs/target.md index add0d22..2041cea 100644 --- a/docs/target.md +++ b/docs/target.md @@ -64,13 +64,17 @@ What a profile requires. The gate enforces exactly this table and nothing else: | trivial | no | the diff; a targeted check when one exists | no | no | no | only on an anomaly (two send-backs, or a human correction) | | isolated | yes | at least one that is not vacuous | no | no | no | yes | | logic | yes | as isolated, each with `covers` | no | no | no | yes | -| integration | yes | as logic, plus invariants | yes | yes | no | yes | +| integration | yes | as logic, plus invariants and an `approach` | yes | yes | no | yes | | data, critical | yes | as integration | yes | yes | yes | yes | | release | yes | every check (`--all`) | yes | yes | yes | yes | -"Requirement model" is the contract's `requirements` list (section 4). "Risk note" is -`risk.blast_radius` and `risk.rollback`. "Independent evidence" is a judged review delegation -in the ledger for this unit, or a passing check marked `"independent": true`. +"Requirement model" is the contract's `requirements` list (section 4); an `approach` is the +contract's `approach` object with `chosen`, `why` and at least one alternative. Text such as `TODO`, +`n/a` or `none` fills no field. The table is held as data in `canon/risk.json` (`requirements`, with +machine keys beside the prose ones) and read by the gate. "Risk note" is +`risk.blast_radius` and `risk.rollback`. "Independent evidence" is an accepted review delegation +in the ledger for this project inside the unit's window with a check stronger than `none`, or a passing check +marked `"independent": true` that names who or what produced it in `"by"`. ## 4. The work unit [10] @@ -175,6 +179,11 @@ At the end of a turn in which the session changed something: (`sisi retro`), which closes the unit; or `sisi unit pause ""`. 5. A paused or closed unit with no new change passes silently. +In this build the retro is offered once for each state of the tree and a trivial change is asked +nothing (unless the unit shows an anomaly); a recorded retro closes the unit. A session is judged only on +its own edits, so another session's work in the same tree never sends it back. The detail is in +docs/records.md, "The end-of-turn gate". + Send-backs stay bounded; when they run out the unit is released as `unverified` and recorded as such. Subagents are never sent back for a retro: a subagent's last message is its report to its parent and must stay that. The question-dialog gate stays as it is. diff --git a/sisi/assure.py b/sisi/assure.py new file mode 100644 index 0000000..26a7e27 --- /dev/null +++ b/sisi/assure.py @@ -0,0 +1,175 @@ +"""What a risk profile requires, and what is missing from a unit (target section 3). + +The gate enforces the `requirements` table in canon/risk.json and nothing else. This module reads +that table, looks at the contract and the evidence, and returns the missing items in plain words, +each with the command or field that supplies it. It never decides anything about the tree itself. + +The profile that applies is the floor (what the changed paths say, by sisi/risk.py) unless the +contract declares a higher one. A contract may declare a lower one only by giving `risk.why`: the +unit then runs at the declared profile and is recorded as lowered, with floor, declared profile and +reason kept side by side (`sisi status` shows it). +""" +import os, time + +from . import contract as C, harvest, risk, store + +ORDER = {name: i for i, name in enumerate(risk.PROFILES)} + + +def effective_profile(floor, c): + """(profile, info). `info` = {floor, declared, lowered, why, refused}: `refused` is set when a + contract declared a lower profile without a reason, so the floor was kept.""" + rk = (c.get("risk") if isinstance(c, dict) else None) or {} + declared = rk.get("profile") if rk.get("profile") in ORDER else None + info = {"floor": floor, "declared": declared, "lowered": False, "why": rk.get("why"), "refused": False} + if declared is None or ORDER[declared] >= ORDER[floor]: + return (declared if declared and ORDER[declared] > ORDER[floor] else floor), info + if C.is_placeholder(rk.get("why")): + info["refused"] = True + return floor, info + info["lowered"] = True + return declared, info + + +def is_lowered(floor, declared, why): + """True when a unit declared a profile below its floor and gave a reason (what `sisi status` flags).""" + return bool(floor in ORDER and declared in ORDER and ORDER[declared] < ORDER[floor] + and not C.is_placeholder(why)) + + +def requirements(profile): + return risk.requirements_for(profile) + + +def stronger_technique(c): + """True when some check or invariant uses a technique stronger than example tests: a proof or + model check (rung 1), or properties, fuzzing or a reference comparison (rung 2).""" + items = list((c or {}).get("checks") or []) + list((c or {}).get("invariants") or []) + return any(isinstance(x, dict) and x.get("rung") in (1, 2) for x in items) + + +def _real(items, key): + """Entries of a list whose `key` says something (not empty, not a placeholder).""" + return [x for x in items or [] if isinstance(x, dict) and not C.is_placeholder(x.get(key))] + + +def _passing(r): + return r.get("status") == "passed" or (r.get("status") == "skipped" + and str(r.get("reason") or "").startswith("reused: passed")) + + +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.""" + t0 = harvest.epoch(c["started"]) if isinstance(c.get("started"), str) else None + if t0 is None: + return [] + try: + from . import workers + dg = workers.delegations_for_project(os.path.basename(project.rstrip(os.sep)), t0, + (time.time() if now is None else now) + 1) # a judgement rounds its time + except Exception as e: + store.log_error("assure-delegations", e) + return [] + 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")] + + +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.""" + out = [] + for r in review_evidence(project, c, now): + out.append("review by %s" % (r.get("worker") or "a reviewer")) + 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"))} + 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"])) + return out + + +def missing(profile, c, project, results=None, errors=None, deep_state=None, now=None): + """[(what is missing, how to supply it)] for this profile. `c` is None when no contract is open. + `errors` are the contract's validation errors. Nothing is asked that the table does not require.""" + req = requirements(profile) + out = [] + if not req.get("contract"): + return out + if c is None: + out.append(("a contract for this %s change" % profile, + "`sisi contract init`, then write at least one check that can fail")) + c = {} + absent = True + else: + absent = False + 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`")) + checks = [x for x in c.get("checks") or [] if isinstance(x, dict)] + if not absent and not errors and int(req.get("min_checks", 0)) > len(checks): + out.append(("at least one check that can fail", 'add it under "checks"')) + if req.get("covers"): + bare = [x.get("id") or "?" for x in checks if C.is_placeholder(x.get("covers"))] + if bare or absent: + out.append(("every check says what it covers" + (" (missing on %s)" % ", ".join(bare) if bare else ""), + '"covers": the failure that check would catch')) + if req.get("invariants") and not _real(c.get("invariants"), "claim"): + out.append(("invariants: what must not get worse", + '"invariants": a command that can fail, e.g. the existing tests')) + if req.get("requirement_model") and not _real(c.get("requirements"), "text"): + out.append(("a requirement list", + '"requirements": entries with "kind", "text" and "decision" (now, architect, defer, ignore)')) + if req.get("risk_note"): + rk = c.get("risk") if isinstance(c.get("risk"), dict) else {} + lacking = [k for k in ("blast_radius", "rollback") if C.is_placeholder(rk.get(k))] + if lacking: + out.append(("a risk note: %s" % " and ".join(lacking), + '"risk": {"blast_radius": what this can break, "rollback": how to undo it}')) + if req.get("approach"): + ap = c.get("approach") if isinstance(c.get("approach"), dict) else {} + if C.is_placeholder(ap.get("chosen")) or C.is_placeholder(ap.get("why")) \ + or not [a for a in ap.get("alternatives") or [] if not C.is_placeholder(a)]: + out.append(("the approach: what you chose, why, and an alternative you rejected", + '"approach": {"chosen", "why", "alternatives": [...]}')) + if req.get("independent_evidence") and not independent_evidence(project, c, results, now): + out.append(("independent evidence that someone or something else checked this", + "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 deep_state is not None and deep_state not in ("fresh-pass", "none"): + out.append(("every check, deep ones included, passing on this tree (release)", + "`sisi verify --deep --background`, then `sisi verify --state`")) + return out + + +# ---------------------------------------------------------------- messages + +MAX_LINES = 25 + + +def fit(lines, limit=MAX_LINES): + """No message to the agent is longer than `limit` lines: over it, the tail is replaced by one line + saying how many were cut. Every line is also kept short.""" + flat = [] + for ln in lines: + for sub in str(ln).split("\n"): + flat.append(sub if len(sub) <= 300 else sub[:297] + "...") + if len(flat) <= limit: + return "\n".join(flat) + return "\n".join(flat[:limit - 1] + ["... (%d more lines; run `sisi verify` for the full output)" + % (len(flat) - limit + 1)]) + + +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.""" + 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] + if len(bad) > checks: + out.append("- and %d more failing" % (len(bad) - checks)) + return out diff --git a/sisi/attribution.py b/sisi/attribution.py new file mode 100644 index 0000000..bd8b878 --- /dev/null +++ b/sisi/attribution.py @@ -0,0 +1,297 @@ +"""Which edits were this session's own. The gate reads this, never another session's work. + +Attribution reads this session's own transcript (Claude-Code-shaped JSONL: assistant records whose +message.content holds tool_use blocks). Only bytes after the per-session offset stored in the session +record are read, so a long transcript costs only its new tail; subagent transcripts found under +/subagents/** are read the same way and count as this session's edits. +Edit/Write/MultiEdit/NotebookEdit (and any tool whose name says it writes) count, with the file paths +in their input. Shell commands are measured by the before/after hooks (sisi/watch.py) where those are +installed; where they are not, a shell command counts when it plausibly writes: a redirect, tee/dd-of, +an in-place editor, git apply/checkout/restore/reset/clean/mv/rm, patch, cp/mv/rm/touch/mkdir, or any +program that is not on the provably read-only list (test runners and interpreters therefore count: +they can write). +Known blind spots: a read-only-looking command that writes through indirection sisi cannot see, a +daemon, a tool whose transcript is not Claude-Code JSONL, and writes made between the last complete +transcript line and a crash. A missing or unreadable transcript, a corrupt line, or a shell command +that cannot be tokenised is treated as an edit by this session (fail strict, never fail open here); +so is an unread tail over 64 MB, which is skipped rather than scanned inside the gate's time budget. +""" +import json, os, re, shlex + +EDIT_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"} +_READONLY_CMDS = {"ls", "cat", "head", "tail", "grep", "egrep", "fgrep", "rg", "ag", "wc", "file", + "stat", "du", "df", "which", "type", "pwd", "date", "env", "printenv", "sort", + "uniq", "cut", "tr", "jq", "yq", "diff", "cmp", "md5sum", "sha1sum", "sha256sum", + "basename", "dirname", "realpath", "readlink", "ps", "top", "free", "uname", + "hostname", "id", "whoami", "less", "more", "man", "help", "history"} +_READONLY_GIT = {"status", "diff", "log", "show", "rev-parse", "ls-files", "ls-tree", "describe", + "blame", "grep", "cat-file", "branch", "tag", "remote", "config", "add", "commit"} +_GH_READ = {("run", "list"), ("run", "view"), ("run", "watch"), ("pr", "list"), ("pr", "view"), + ("pr", "status"), ("pr", "diff"), ("pr", "checks"), ("issue", "list"), ("issue", "view"), + ("issue", "status"), ("repo", "view"), ("repo", "list"), ("release", "list"), + ("release", "view"), ("workflow", "list"), ("workflow", "view"), ("auth", "status")} +_WRITE_WORDS = ("edit", "write", "create", "delete", "move", "rename", "patch", "apply", "insert") +_SHELL_WRITE_RE = re.compile( + r">>?[^=]|\btee\b|\bdd\b[^;&|]*\bof=|\bsed\b[^;&|]*\s-[a-z]*i|\bperl\b[^;&|]*\s-[a-z]*i" + r"|\bawk\b[^;&|]*inplace|\bgit\s+(apply|checkout|restore|reset|clean|mv|rm)\b" + r"|\bpatch\b|\b(cp|mv|rm|touch|mkdir|rmdir|install|ln)\b", re.I) + + +def shell_may_write(command): + """True: plausibly writes files. False: provably read-only. None: cannot be tokenised.""" + if not isinstance(command, str) or not command.strip(): + return False + if _SHELL_WRITE_RE.search(command): + return True + try: + lex = shlex.shlex(command, posix=True, punctuation_chars=True) + lex.whitespace_split = True + tokens = list(lex) + except ValueError: + return None + segments, cur = [], [] + for tok in tokens: + if tok in (";", "&", "|", "&&", "||"): + segments.append(cur) + cur = [] + else: + cur.append(tok) + segments.append(cur) + for seg in segments: + i = 0 + while i < len(seg) and (re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", seg[i]) or seg[i] in ("sudo", "command", "exec", "time", "nice")): + i += 1 + if i >= len(seg): + continue + prog = os.path.basename(seg[i]) + rest = seg[i + 1:] + if prog in ("cd", "export", "unset", "set", "alias", "umask", "wait", "jobs", "fg", "bg", + "exit", "return", "break", "continue", "shift", "readonly", "local", "declare", + "typeset", "echo", "printf", "true", "false", ":", "test", "[", "[[", "eval"): + if prog == "eval": + return True + continue + if prog == "find": + if any(a in ("-delete", "-exec", "-execdir", "-ok", "-okdir", "-fls", "-fprint") for a in rest): + return True + continue + if prog == "git": + sub = next((a for a in rest if not a.startswith("-")), "") + if sub == "stash": # only listing a stash leaves the tree alone; push/pop/apply change it + tail = rest[rest.index(sub) + 1:] + if not tail or tail[0] in ("list", "show"): + continue + return True + if sub in _READONLY_GIT and not (sub == "config" and any(not a.startswith("-") for a in rest[rest.index(sub) + 1:])): + continue # add/commit touch .git only, never a working-tree file + return True + if prog == "gh": + pair = tuple(a for a in rest if not a.startswith("-"))[:2] + if pair in _GH_READ: + continue + if pair and pair[0] == "api" and not any(a in ("-X", "--method", "-f", "-F", "--field", "--raw-field") + or a.startswith(("-f", "-F")) for a in rest): + continue + return True + if prog == "sisi": + # sisi writes only personal data and state, never the project — except contract + # init/waive/trust, which do record something about (or in) this project. + if rest and rest[0] == "contract": + if len(rest) > 1 and rest[1] in ("init", "waive", "trust", "untrust"): + return True + continue + continue + if prog in _READONLY_CMDS: + if prog in ("sed", "awk", "jq", "yq") and any("inplace" in a or a.startswith("-i") for a in rest): + return True + continue + return True # interpreters, build/test runners, scripts, anything unlisted: can write + return False + + +def _input_files(inp): + out = [] + if isinstance(inp, dict): + for k in ("file_path", "notebook_path", "path", "filename", "filePath"): + if isinstance(inp.get(k), str) and inp[k]: + out.append(inp[k]) + return out + + +def parse_chunk(data, measured=False): + """Parse complete JSONL bytes. Returns (edits, files, writing, corrupt, consumed_bytes, shell_edits). + In measured mode Bash calls are not guessed from their text at all: the before/after tree + measurement (sisi/watch.py) has already attributed whatever they actually changed — except + `sisi contract init/waive/trust`, which record project state outside the measured files.""" + if data.endswith(b"\n") or not data: + consumed, body = len(data), data + else: + cut = data.rfind(b"\n") + tail = data[cut + 1:] + try: + json.loads(tail.decode("utf-8", "replace")) + consumed, body = len(data), data # a complete final line without its newline yet + except ValueError: + consumed, body = cut + 1, data[:cut + 1] # partial line: leave it for the next read + edits, files, writing, corrupt, shell_edits = 0, [], False, 0, 0 + for raw in body.split(b"\n"): + if not raw.strip(): + continue + if len(raw) > 131072 and b"tool_use" not in raw and b"Bash" not in raw: + continue # a huge tool-result line: no tool call hides in it worth parsing + try: + d = json.loads(raw.decode("utf-8", "replace")) + except ValueError: + corrupt += 1 + edits += 1 # an unreadable line may be the edit we cannot see: count it + writing = True + continue + if not isinstance(d, dict): + continue + content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None + for x in content if isinstance(content, list) else []: + if not isinstance(x, dict) or x.get("type") != "tool_use": + continue + name = x.get("name") or "" + inp = x.get("input") if isinstance(x.get("input"), dict) else {} + if name in EDIT_TOOLS or any(w in name.lower() for w in _WRITE_WORDS): + edits += 1 + writing = True + files += _input_files(inp) + elif name in ("Bash", "Shell", "bash", "shell"): + cmd = inp.get("command") if isinstance(inp.get("command"), str) else inp.get("cmd") + if measured: + if isinstance(cmd, str) and re.search(r"\bsisi\s+contract\s+(init|waive|trust|untrust)\b", cmd): + edits += 1 + shell_edits += 1 + writing = True + files.append(".sisi/contract.json") + continue # everything else was measured, not guessed + may = shell_may_write(cmd) + if may is None: + corrupt += 1 + edits += 1 + shell_edits += 1 + writing = True + elif may: + edits += 1 + shell_edits += 1 + writing = True + return edits, files, writing, corrupt, consumed, shell_edits + + +def _scan_one(sess, store_key, path): + """Advance one transcript's offset in the session record. Returns (edits, files, writing, unknown).""" + offsets = sess.setdefault("attr_sub_offsets", {}) if store_key == "sub" else None + try: + size = os.path.getsize(os.path.expanduser(path)) + except OSError: + return 0, [], False, True, 0 # missing or unreadable: unknown, treated as edited by the caller + if store_key == "sub": + offset = int(offsets.get(path, 0) or 0) + else: + offset = int(sess.get("attr_offset", 0) or 0) + unknown = False + if offset > size: + offset, unknown = 0, True # truncated or replaced: rescan, and do not trust the gap + if size - offset > 64 * 1024 * 1024: + # Too much unread tail to scan inside the gate's budget: skip it and count it as a + # possible edit by this session (strict), rather than guessing it was someone else's. + if store_key == "sub": + offsets[path] = size + else: + sess["attr_offset"] = size + return 1, [], True, True, 0 + edits, files, writing, sh = 0, [], False, 0 + try: + with open(os.path.expanduser(path), "rb") as f: + f.seek(offset) + data = f.read() + except OSError: + return 0, [], False, True, 0 + if data: + e, fl, w, corrupt, consumed, sh = parse_chunk(data, measured=bool(sess.get("attr_measured"))) + edits, files, writing = e, fl, w + unknown = unknown or corrupt > 0 + offset += consumed + if store_key == "sub": + offsets[path] = offset + else: + sess["attr_offset"] = offset + return edits, files, writing, unknown, sh + + +def subagent_transcripts(tp): + """Native subagent transcripts under this session's transcript, Claude Code layout.""" + if not isinstance(tp, str) or not tp.endswith(".jsonl"): + return [] + root = os.path.join(os.path.expanduser(tp)[:-len(".jsonl")], "subagents") + out = [] + for dirpath, dirs, names in os.walk(root): + dirs.sort() + for n in sorted(names): + if n.startswith("agent-") and n.endswith(".jsonl"): + out.append(os.path.join(dirpath, n)) + return out + + +def update(sess, tp): + """Refresh this session's edit count from its own (and its native subagents') transcripts. + + Returns {"gen", "writing", "unknown", "edits", "files", "shell_edits"} or None when no transcript + path is known at all (the caller then falls back to comparing the tree with its last settled + state). Fails towards edited: `unknown` is true whenever the transcript cannot be trusted.""" + if not isinstance(tp, str) or not tp: + return None + if sess.get("attr_tp") != tp: + sess.update(attr_tp=tp, attr_offset=0, attr_gen=0, attr_writing=False, attr_files=[], attr_sub_offsets={}) + sess.setdefault("attr_gen", 0) + unknown = False + total, all_files, shell_total = 0, [], 0 + for key, path in [("main", tp)] + [("sub", s) for s in subagent_transcripts(tp)]: + e, fl, w, unk, sh = _scan_one(sess, key, path) + total += e + shell_total += sh + all_files += fl + unknown = unknown or unk + if w: + sess["attr_writing"] = True + sess["attr_gen"] = int(sess.get("attr_gen", 0)) + total + if all_files: + have = sess.setdefault("attr_files", []) + for f in all_files: + if f not in have: + have.append(f) + del have[:-500] + if unknown: + sess["attr_writing"] = True + return {"gen": int(sess["attr_gen"]), "writing": bool(sess.get("attr_writing")), "unknown": bool(unknown), + "edits": total, "files": all_files, "shell_edits": shell_total} + + +def observed_edits(transcript): + """(edited, files, start_ts) from a subagent's own transcript: did it write, which files did its + edit tools name, and when did it start (sisi's timestamp format, or None). A shell command that + may write counts as an edit with no known file.""" + edited, files, start = False, [], None + with open(os.path.expanduser(transcript), encoding="utf-8", errors="replace") as f: + for line in f: + try: + d = json.loads(line) + except ValueError: + continue + if not isinstance(d, dict): + continue + if start is None and isinstance(d.get("timestamp"), str) and len(d["timestamp"]) >= 19: + start = d["timestamp"][:19] + "Z" + content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None + for x in content if isinstance(content, list) else []: + if not (isinstance(x, dict) and x.get("type") == "tool_use"): + continue + inp = x.get("input") if isinstance(x.get("input"), dict) else {} + if x.get("name") in EDIT_TOOLS: + edited = True + files += [f for f in _input_files(inp) if f not in files] + elif x.get("name") in ("Bash", "Shell") and shell_may_write(inp.get("command")) is not False: + edited = True + return edited, files[:100], start diff --git a/sisi/cli.py b/sisi/cli.py index b73198b..9e95802 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -175,10 +175,6 @@ def cmd_contract(args): errs = C.validate(c) for e in errs: print(" - " + e) - if not errs: - for f in C.floor_failures(c): - errs.append(f["message"]) - print(" - " + f["message"]) if not errs: for w in C.warnings(c): print("warning: " + w) diff --git a/sisi/contract.py b/sisi/contract.py index eb2f91a..d12b86b 100644 --- a/sisi/contract.py +++ b/sisi/contract.py @@ -1,4 +1,4 @@ -"""Contract file: location, skeleton, validation, floors.""" +"""Contract file: location, skeleton, validation.""" import json, os, re from . import paths, gitutil @@ -108,14 +108,6 @@ def deferred_checks(c): return out -def floors(): - try: - with open(paths.canon("floors.json"), encoding="utf-8") as f: - return {k: int(v) for k, v in json.load(f).items()} - except (OSError, ValueError): - return {} - - def _num(x): return isinstance(x, (int, float)) and not isinstance(x, bool) @@ -124,6 +116,24 @@ def _str(x): return isinstance(x, str) and x.strip() != "" +_PLACEHOLDER_WORDS = {"todo", "tbd", "tba", "fixme", "xxx", "wip", "none", "nothing", "no", "n/a", "na", "nil", + "null", "unknown", "placeholder", "later", "see above", "same", "as above", "not applicable", + "no risk", "no rollback", "none needed", "not needed", "nothing needed", "-", "--", "...", + "?", "yes", "ok", "fine", "tests", "all"} + + +def is_placeholder(x): + """True for text that fills a field without saying anything: empty, `TODO`, `n/a`, `none`, + `tbd`, a bare punctuation mark, or anything that begins with TODO/TBD/FIXME. The gate asks for + a requirement list, a risk note, an approach and a reason; these words do not provide one.""" + if not isinstance(x, str): + return True + t = " ".join(x.lower().split()).strip(" .,:;!-_*") + if len(re.findall(r"[a-z0-9]", t)) < 3 and t not in ("ui",): + return True + return t in _PLACEHOLDER_WORDS or bool(re.match(r"^(todo|tbd|fixme|placeholder|xxx)\b", t)) + + TIERS = ("fast", "deep") @@ -274,6 +284,8 @@ def _check_new_fields(ch, w, errs): for k in ("mandatory", "independent"): if k in ch and not isinstance(ch[k], bool): errs.append("%s: %s must be true or false" % (w, k)) + if "by" in ch and not _str(ch["by"]): + errs.append(w + ": by must name who or what produced the independent evidence") def _validate_new_top(c, ids, errs): @@ -473,16 +485,3 @@ def validate(c): errs.append("questions[%d] needs q and default" % i) _validate_new_top(c, ids, errs) return errs - - -def floor_failures(c, floor_map=None): - """Kinds with a floor where every check of that kind is weaker than the floor.""" - fm = floors() if floor_map is None else floor_map - out = [] - for kind, fl in sorted(fm.items()): - of_kind = [ch for ch in c.get("checks", []) if ch.get("kind") == kind] - if of_kind and not any(ch["rung"] <= fl for ch in of_kind): - out.append({"kind": kind, "floor": fl, - "message": "floor: %s claims need a check at rung %d or stronger; best is rung %d" - % (kind, fl, min(ch["rung"] for ch in of_kind))}) - return out diff --git a/sisi/gate.py b/sisi/gate.py index d684b10..eace829 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -1,8 +1,32 @@ -"""End-of-turn gate. Claude Code Stop hook: JSON on stdin, block = JSON {"decision":"block","reason":...} on stdout, exit 0. -Anything that goes wrong inside sisi allows (fail open) and is logged to the state dir.""" -import hashlib, json, os, re, shlex, sys, time +"""End-of-turn gate (Stop hook): may this agent stop now? JSON on stdin; a send-back is +{"decision":"block","reason":...} on stdout, exit 0. Anything that goes wrong inside sisi allows +(fail open) and is logged to the state dir. -from . import contract as C, deep as D, gitutil, paths, store, trust, verify as V +The flow is target.md section 7, and each stop answers these in order: + + 1. Did THIS session change anything since its last settled stop? If not, the turn ends silently + (a paused unit with no new change, a closed unit, another session's edits: all silent). + 2. What does the change need? The floor comes from the paths changed (sisi/risk.py); the contract + may raise it, and lowers it only with a reason (sisi/assure.py). + 3. Enforce what that profile's row of canon/risk.json requires, and nothing else; run the + selected fast checks (sisi/verify.py). One send-back lists everything missing at once. + 4. All green and the unit still open: close it if the retro is recorded, otherwise offer the two + ways on (the retro, or `sisi unit pause`), once. A trivial change is asked nothing. + +Send-backs are bounded (`gate.max_blocks`); when they run out the unit is released as `unverified` +and says why. A subagent is never sent back and never asked for a retro: its last message is its +report. Who made which edit is attributed in sisi/attribution.py, so a session is never sent back +for another session's work in the same tree. +""" +import hashlib, json, os, sys, time + +from . import assure, attribution, contract as C, gitutil, risk, store, trust, unit as U, verify as V +from .questions import QUESTION_DIALOG_TOOLS, ends_with_question # noqa: F401 (rulecmd and the tests name them here) + +# watch.py asks the gate's shell classifier whether a command may write +_shell_may_write = attribution.shell_may_write + +SENTINELS = ("*shell*", "*shell-unmeasured*", "*subagent*") def _read_payload(): @@ -20,579 +44,237 @@ def _session_key(payload, cwd): return sid if isinstance(sid, str) and sid else "cwd-" + hashlib.sha1(cwd.encode()).hexdigest()[:12] +def _cwd(payload): + c = payload.get("cwd") + return c if isinstance(c, str) and os.path.isdir(c) else os.getcwd() + + def _new_waiver(project, sess): - """Latest waiver for this project made during this session and not yet applied.""" - since, seen, best = sess.get("started") or "", sess.get("waiver_ns", 0), None + """Latest `sisi contract waive` for this project made during this session and not yet applied.""" + since, seen, best = sess.get("started") or sess.get("first_seen") or "", sess.get("waiver_ns", 0), None for w in store.read("waivers"): if w.get("project") == project and w.get("ts", "") >= since and w.get("ns", 0) > seen: best = w return best -class _Ctx: - def __init__(self, sess, sid, cfg, fp): - self.sess, self.sid, self.cfg, self.fp = sess, sid, cfg, fp +# ---------------------------------------------------------------- who changed what + +def _absorb_subagents(sess, sid, top): + """Edits a subagent reported at its own stop count as this session's edits (hosts that keep the + subagent's transcript elsewhere are covered this way).""" + seen = int(sess.get("sub_seen_ns", 0) or 0) + newest = seen + for r in store.read("subagents"): + if r.get("session") != sid or int(r.get("ns", 0)) <= seen: + continue + newest = max(newest, int(r["ns"])) + if not r.get("edited"): + continue + sess["attr_gen"] = int(sess.get("attr_gen", 0) or 0) + 1 + since = sess.setdefault("attr_since_pass", []) + for f in r.get("files") or []: + rel = os.path.relpath(f, top) if top and os.path.isabs(f) else f + if rel not in since: + since.append(rel) + if not r.get("files") and "*subagent*" not in since: + since.append("*subagent*") + sess["sub_seen_ns"] = newest + + +def _note_own_paths(sess, attr, top): + """Record this scan's edited paths (relative to the repository) as edited since the last settled stop.""" + since = sess.setdefault("attr_since_pass", []) + for f in attr.get("files") or []: + rel = f + if os.path.isabs(f) and top: + try: + rel = os.path.relpath(f, top) + except ValueError: + rel = f + if rel not in since: + since.append(rel) + if attr.get("shell_edits") and not sess.get("attr_measured") and "*shell*" not in since: + since.append("*shell*") # a text-classified shell edit: its paths are unknown + + +def _own_changed(sess, sid, cwd, top, attr): + """Paths changed since this session's last settled stop that this session made (or may have made). + Never another session's work: that is what lets two sessions share a tree.""" + changed = None + try: + from . import watch + changed = watch.changed_since_pass(sid, cwd) + except Exception as e: + store.log_error("gate-watch-diff", e) + if changed is None: # no settled snapshot yet: the tree against the session's start + base = set((sess.get("baseline") or {}).get("files") or []) + since = set(sess.get("attr_since_pass") or []) + try: + now = gitutil.measure(cwd, sess.get("head"))["files"] + except Exception: + now = [] + changed = [f for f in now if f not in base or f in since] + changed = [f for f in changed if not f.startswith(".sisi" + os.sep) and not f.startswith(".sisi/")] + since = set(sess.get("attr_since_pass") or []) + if attr is None or attr["unknown"] or any(s in since for s in SENTINELS): + return changed + return [f for f in changed if f in since] + + +def _claims_unit(sess, contract_path): + """This session wrote the open contract itself (`sisi contract init`, or an edit of the file).""" + if not contract_path: + return False + rel = C.REL.replace(os.sep, "/") + mine = [f.replace(os.sep, "/") for f in list(sess.get("attr_files") or []) + list(sess.get("attr_since_pass") or [])] + return any(f == rel or f.endswith("/" + rel) for f in mine) + + +def _diff_text(project, base): + return U._git_diff_text(project, base) + + +# ---------------------------------------------------------------- the stop + +class _Stop: + """One stop: the session record, and the few ways a stop can end.""" + + def __init__(self, sess, sid, cfg, fp, attr): + self.sess, self.sid, self.cfg, self.fp, self.attr = sess, sid, cfg, fp, attr + self.maxb = int(cfg["gate"].get("max_blocks", 3)) def save(self): store.save_session(self.sid, self.sess) - def allow(self, msg=None): - if msg is None: # a clean stop is one of the places the cycle-due counter is checked (no scheduler) - try: - from . import cycle - note = cycle.due_notice(session=self.sid) - if note: - msg = note + " (This turn may end; the cycle is background work, not a send-back.)" - except Exception as e: - store.log_error("gate-cycle-notice", e) - self.sess.update(blocks=0, last_fp=self.fp, last_decision="allow") + def settle(self, cwd): + """This stop leaves nothing pending: the next change is measured from here.""" + s = self.sess + s.update(dirty=False, blocks=0, settled_fp=self.fp, last_fp=self.fp, last_decision="allow", sb_unit=0, + attr_since_pass=[]) + try: + from . import watch + watch.save_pass_snapshot(self.sid, cwd) + except Exception as e: + store.log_error("gate-watch-pass", e) self.save() + + def allow(self, cwd, msg=None, settle=True): + if settle: + self.settle(cwd) + else: + self.sess.update(blocks=0, last_decision="allow") + self.save() return "allow", msg - def block(self, template, contract_id=None, project=None, kind="fast"): - """One path for every kind of block: strikes, 3-strike release as UNVERIFIED.""" - s, maxb = self.sess, int(self.cfg["gate"].get("max_blocks", 3)) - blocks = int(s.get("blocks", 0)) - if blocks >= maxb: - if kind == "retro": - self.allow() - return "allow", ("sisi: no retrospective was recorded after %d reminders, so the gate let this turn end. " - "Run `sisi retro` before you finish if you still can." % maxb) - store.append("results", {"ts": store.now(), "contract": contract_id, "project": project, "check": "gate", - "item": "gate", "kind": None, "rung": None, "status": "unverified", - "duration_s": 0.0, "tool": store.tool(), "session": self.sid}) - _, _ = self.allow() - return "allow", ("sisi: result is UNVERIFIED. The gate has sent this work back %d times and it is still " - "not verified, so it let the turn end. Report the work as unverified." % maxb) - s["req_blocks"] = int(s.get("req_blocks", 0)) + 1 # send-backs during this request, for the delivery row - s.update(blocks=blocks + 1, last_fp=self.fp, last_decision="block", last_msg=template, last_kind=kind, - last_contract=contract_id, last_project=project) + def block(self, text, contract_id, project, counts=True): + s = self.sess + if counts: + s["req_blocks"] = int(s.get("req_blocks", 0)) + 1 # send-backs during this request, for the delivery row + s["blocks"] = int(s.get("blocks", 0)) + 1 + s["sb_unit"] = int(s.get("sb_unit", 0)) + 1 + s.update(last_fp=self.fp, last_decision="block") self.save() - return "block", template.replace("{n}", "%d of %d" % (blocks + 1, maxb)) + return "block", text.replace("{n}", "%d of %d" % (s.get("blocks", 1), self.maxb)) + + def exhausted(self): + return int(self.sess.get("blocks", 0)) >= self.maxb + + def refresh(self, cwd, path): + """The contract file is part of the tree's fingerprint: take it again after the gate edited it.""" + self.fp = gitutil.fingerprint(cwd, [path]) if gitutil.root(cwd) and path else self.fp -# ---------------------------------------------------------------- attribution -# Attribution reads this session's own transcript (Claude-Code-shaped JSONL: assistant records whose -# message.content holds tool_use blocks). Only bytes after the per-session offset stored in the session -# record are read, so a long transcript costs only its new tail; subagent transcripts found under -# /subagents/** are read the same way and count as this session's edits. -# Edit/Write/MultiEdit/NotebookEdit (and any tool whose name says it writes) count, with the file paths -# in their input. Shell (Bash) commands count when they plausibly write: a redirect, tee/dd-of, an -# in-place editor (sed -i, perl -i, awk -i inplace), git apply/checkout/restore/reset/clean/mv/rm, -# patch, cp/mv/rm/touch/mkdir, or any program that is not on the provably read-only list (ls, cat, -# grep, git status/diff/log/..., test runners and interpreters therefore count: they can write). -# Known blind spots: a read-only-looking command that writes through indirection sisi cannot see -# (a script reached by a read-only interpreter flag combination that slips the lists, a daemon, or a -# tool whose transcript shape is not Claude-Code JSONL), and writes made between the last complete -# transcript line and a crash. A missing/unreadable transcript, a corrupt line, or a shell command -# that cannot be tokenised is treated as an edit by this session (fail strict, never fail open here); -# so is an unread tail over 64 MB, which is skipped (offset moved to its end) rather than scanned -# inside the gate's time budget. - -EDIT_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"} -_READONLY_CMDS = {"ls", "cat", "head", "tail", "grep", "egrep", "fgrep", "rg", "ag", "wc", "file", - "stat", "du", "df", "which", "type", "pwd", "date", "env", "printenv", "sort", - "uniq", "cut", "tr", "jq", "yq", "diff", "cmp", "md5sum", "sha1sum", "sha256sum", - "basename", "dirname", "realpath", "readlink", "ps", "top", "free", "uname", - "hostname", "id", "whoami", "less", "more", "man", "help", "history"} -_READONLY_GIT = {"status", "diff", "log", "show", "rev-parse", "ls-files", "ls-tree", "describe", - "blame", "grep", "cat-file", "branch", "tag", "remote", "config", "add", "commit"} -_GH_READ = {("run", "list"), ("run", "view"), ("run", "watch"), ("pr", "list"), ("pr", "view"), - ("pr", "status"), ("pr", "diff"), ("pr", "checks"), ("issue", "list"), ("issue", "view"), - ("issue", "status"), ("repo", "view"), ("repo", "list"), ("release", "list"), - ("release", "view"), ("workflow", "list"), ("workflow", "view"), ("auth", "status")} -_WRITE_WORDS = ("edit", "write", "create", "delete", "move", "rename", "patch", "apply", "insert") -_SHELL_WRITE_RE = re.compile( - r">>?[^=]|\btee\b|\bdd\b[^;&|]*\bof=|\bsed\b[^;&|]*\s-[a-z]*i|\bperl\b[^;&|]*\s-[a-z]*i" - r"|\bawk\b[^;&|]*inplace|\bgit\s+(apply|checkout|restore|reset|clean|mv|rm)\b" - r"|\bpatch\b|\b(cp|mv|rm|touch|mkdir|rmdir|install|ln)\b", re.I) +def _release(stop, cwd, c, path, project, why): + """The send-backs ran out: the turn ends, the unit is released as unverified and says why.""" + why = [w for w in why if w][:4] + store.append("results", {"ts": store.now(), "contract": c["id"] if c else None, "project": project, + "check": "gate", "item": "gate", "kind": None, "rung": None, "status": "unverified", + "reason": "; ".join(why)[:500], "duration_s": 0.0, "tool": store.tool(), + "session": stop.sid}) + if c is not None and path: + try: + c["unverified"] = {"ts": store.now(), "send_backs": stop.maxb, "why": why} + C.save(path, c) + stop.refresh(cwd, path) + except OSError as e: + store.log_error("gate-release", e) + stop.allow(cwd) + return "allow", ("sisi: result is UNVERIFIED. The gate has sent this work back %d times and it is still not " + "verified (%s), so it let the turn end. Report the work as unverified and say what is " + "missing." % (stop.maxb, "; ".join(why) or "see the last message")) -def _shell_may_write(command): - """True: plausibly writes files. False: provably read-only. None: cannot be tokenised.""" - if not isinstance(command, str) or not command.strip(): - return False - if _SHELL_WRITE_RE.search(command): - return True +def _offer_text(c, profile, anomaly): + why = ("every check for unit %s passes" % c["id"]) if not anomaly else \ + ("unit %s passes, and it shows something worth a look (%s)" % (c["id"], anomaly)) + return assure.fit([ + "sisi: %s (%s change). Two ways on, then finish:" % (why, profile), + "- record what you learned: `sisi retro` prints this unit's record; then", + ' `sisi retro --finding "" --cause "" ' + '--impact value|correctness|time|cost|attention --disposition record --limits ""`', + " records it and closes the unit. (`sisi retro --help` shows `promote` and `drop`.)", + '- or, if this work now waits on something (a review, a decision, a deploy):', + ' `sisi unit pause ""`. The turn ends and nothing more is asked until the tree changes.', + ]) + + +def _technique_note(c, profile, sess): + """Once per unit, never blocking: a logic-or-higher change with no check stronger than examples.""" + if c is None or assure.ORDER[profile] < assure.ORDER["logic"] or assure.stronger_technique(c): + return None + if sess.get("technique_noted") == c.get("id"): + return None + sess["technique_noted"] = c.get("id") + return ("Note (not a send-back): no check in this contract uses a technique stronger than example tests " + "(a proof, properties, fuzzing or a comparison with a reference: rung 2 or better). " + "`sisi verifiers for \"\"` ranks the options.") + + +def _anomaly(c, project, sess): + """Why a trivial unit still earns a retro: two send-backs, or a human correction inferred from the transcript.""" + if int(sess.get("sb_unit", 0)) >= 2: + return "the gate sent the agent back %d times" % int(sess["sb_unit"]) try: - lex = shlex.shlex(command, posix=True, punctuation_chars=True) - lex.whitespace_split = True - tokens = list(lex) - except ValueError: - return None - segments, cur = [], [] - for tok in tokens: - if tok in (";", "&", "|", "&&", "||"): - segments.append(cur) - cur = [] - else: - cur.append(tok) - segments.append(cur) - for seg in segments: - i = 0 - while i < len(seg) and (re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", seg[i]) or seg[i] in ("sudo", "command", "exec", "time", "nice")): - i += 1 - if i >= len(seg): - continue - prog = os.path.basename(seg[i]) - rest = seg[i + 1:] - if prog in ("cd", "export", "unset", "set", "alias", "umask", "wait", "jobs", "fg", "bg", - "exit", "return", "break", "continue", "shift", "readonly", "local", "declare", - "typeset", "echo", "printf", "true", "false", ":", "test", "[", "[[", "eval"): - if prog == "eval": - return True - continue - if prog == "find": - if any(a in ("-delete", "-exec", "-execdir", "-ok", "-okdir", "-fls", "-fprint") for a in rest): - return True - continue - if prog == "git": - sub = next((a for a in rest if not a.startswith("-")), "") - if sub == "stash": # only listing a stash leaves the tree alone; push/pop/apply change it - tail = rest[rest.index(sub) + 1:] - if not tail or tail[0] in ("list", "show"): - continue - return True - if sub in _READONLY_GIT and not (sub == "config" and any(not a.startswith("-") for a in rest[rest.index(sub) + 1:])): - continue # add/commit touch .git only, never a working-tree file - return True - if prog == "gh": - pair = tuple(a for a in rest if not a.startswith("-"))[:2] - if pair in _GH_READ: - continue - if pair and pair[0] == "api" and not any(a in ("-X", "--method", "-f", "-F", "--field", "--raw-field") - or a.startswith(("-f", "-F")) for a in rest): - continue - return True - if prog == "sisi": - # sisi writes only personal data and state, never the project — except contract - # init/waive/trust, which do record something about (or in) this project. - if rest and rest[0] == "contract": - if len(rest) > 1 and rest[1] in ("init", "waive", "trust", "untrust"): - return True - continue - continue - if prog in _READONLY_CMDS: - if prog in ("sed", "awk", "jq", "yq") and any("inplace" in a or a.startswith("-i") for a in rest): - return True - continue - return True # interpreters, build/test runners, scripts, anything unlisted: can write - return False - - -def _input_files(inp): - out = [] - if isinstance(inp, dict): - for k in ("file_path", "notebook_path", "path", "filename", "filePath"): - if isinstance(inp.get(k), str) and inp[k]: - out.append(inp[k]) - return out - - -def _parse_transcript_chunk(data, measured=False): - """Parse complete JSONL bytes. Returns (edits, files, writing, corrupt, consumed_bytes, shell_edits). - In measured mode Bash calls are not guessed from their text at all: the before/after tree - measurement (sisi/watch.py) has already attributed whatever they actually changed — except - `sisi contract init/waive/trust`, which record project state outside the measured files.""" - if data.endswith(b"\n") or not data: - consumed, body = len(data), data - else: - cut = data.rfind(b"\n") - tail = data[cut + 1:] - try: - json.loads(tail.decode("utf-8", "replace")) - consumed, body = len(data), data # a complete final line without its newline yet - except ValueError: - consumed, body = cut + 1, data[:cut + 1] # partial line: leave it for the next read - edits, files, writing, corrupt, shell_edits = 0, [], False, 0, 0 - for raw in body.split(b"\n"): - if not raw.strip(): - continue - if len(raw) > 131072 and b"tool_use" not in raw and b"Bash" not in raw: - continue # a huge tool-result line: no tool call hides in it worth parsing - try: - d = json.loads(raw.decode("utf-8", "replace")) - except ValueError: - corrupt += 1 - edits += 1 # an unreadable line may be the edit we cannot see: count it - writing = True - continue - if not isinstance(d, dict): - continue - content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None - for x in content if isinstance(content, list) else []: - if not isinstance(x, dict) or x.get("type") != "tool_use": - continue - name = x.get("name") or "" - inp = x.get("input") if isinstance(x.get("input"), dict) else {} - if name in EDIT_TOOLS or any(w in name.lower() for w in _WRITE_WORDS): - edits += 1 - writing = True - files += _input_files(inp) - elif name in ("Bash", "Shell", "bash", "shell"): - cmd = inp.get("command") if isinstance(inp.get("command"), str) else inp.get("cmd") - if measured: - if isinstance(cmd, str) and re.search(r"\bsisi\s+contract\s+(init|waive|trust|untrust)\b", cmd): - edits += 1 - shell_edits += 1 - writing = True - files.append(".sisi/contract.json") - continue # everything else was measured, not guessed - may = _shell_may_write(cmd) - if may is None: - corrupt += 1 - edits += 1 - shell_edits += 1 - writing = True - elif may: - edits += 1 - shell_edits += 1 - writing = True - return edits, files, writing, corrupt, consumed, shell_edits - - -def _scan_one(sess, store_key, path): - """Advance one transcript's offset in the session record. Returns (edits, files, writing, unknown).""" - offsets = sess.setdefault("attr_sub_offsets", {}) if store_key == "sub" else None - try: - size = os.path.getsize(os.path.expanduser(path)) - except OSError: - return 0, [], False, True, 0 # missing or unreadable: unknown, treated as edited by the caller - if store_key == "sub": - offset = int(offsets.get(path, 0) or 0) - else: - offset = int(sess.get("attr_offset", 0) or 0) - unknown = False - if offset > size: - offset, unknown = 0, True # truncated or replaced: rescan, and do not trust the gap - if size - offset > 64 * 1024 * 1024: - # Too much unread tail to scan inside the gate's budget: skip it and count it as a - # possible edit by this session (strict), rather than guessing it was someone else's. - if store_key == "sub": - offsets[path] = size - else: - sess["attr_offset"] = size - return 1, [], True, True, 0 - edits, files, writing, sh = 0, [], False, 0 - try: - with open(os.path.expanduser(path), "rb") as f: - f.seek(offset) - data = f.read() - except OSError: - return 0, [], False, True, 0 - if data: - e, fl, w, corrupt, consumed, sh = _parse_transcript_chunk(data, measured=bool(sess.get("attr_measured"))) - edits, files, writing = e, fl, w - unknown = unknown or corrupt > 0 - offset += consumed - if store_key == "sub": - offsets[path] = offset - else: - sess["attr_offset"] = offset - return edits, files, writing, unknown, sh - - -def _subagent_transcripts(tp): - """Native subagent transcripts under this session's transcript, Claude Code layout.""" - if not isinstance(tp, str) or not tp.endswith(".jsonl"): - return [] - root = os.path.join(os.path.expanduser(tp)[:-len(".jsonl")], "subagents") - out = [] - for dirpath, dirs, names in os.walk(root): - dirs.sort() - for n in sorted(names): - if n.startswith("agent-") and n.endswith(".jsonl"): - out.append(os.path.join(dirpath, n)) - return out - - -def _update_attribution(sess, tp): - """Refresh this session's edit count from its own (and its native subagents') transcripts. - - Returns {"gen", "writing", "unknown"} or None when no transcript path is known at all - (the caller then falls back to the pre-attribution behaviour). Fails towards edited.""" - if not isinstance(tp, str) or not tp: - return None - if sess.get("attr_tp") != tp: - sess.update(attr_tp=tp, attr_offset=0, attr_gen=0, attr_pass_gen=0, attr_retro_gen=0, - attr_baseline_gen=0, attr_writing=False, attr_files=[], attr_sub_offsets={}) - sess.setdefault("attr_gen", 0) - sess.setdefault("attr_pass_gen", 0) - sess.setdefault("attr_retro_gen", 0) - sess.setdefault("attr_baseline_gen", 0) - unknown = False - total, all_files, shell_total = 0, [], 0 - e, fl, w, unk, sh = _scan_one(sess, "main", tp) - total += e - shell_total += sh - all_files += fl - unknown = unknown or unk - if w: - sess["attr_writing"] = True - for sub in _subagent_transcripts(tp): - e, fl, w, unk, sh = _scan_one(sess, "sub", sub) - total += e - shell_total += sh - all_files += fl - unknown = unknown or unk - if w: - sess["attr_writing"] = True - sess["attr_gen"] = int(sess.get("attr_gen", 0)) + total - if all_files: - have = sess.setdefault("attr_files", []) - for f in all_files: - if f not in have: - have.append(f) - del have[:-500] - if unknown: - sess["attr_writing"] = True - return {"gen": int(sess["attr_gen"]), "writing": bool(sess.get("attr_writing")), "unknown": bool(unknown), - "edits": total, "files": all_files, "shell_edits": shell_total} - - -def _changed_paths(top, cwd, own_files): - """Up to five working-tree paths changed against HEAD that this session did not edit.""" - try: - rels = gitutil.measure(cwd, gitutil.head(cwd))["files"] - except Exception: - return [] - own = set() - for f in own_files or []: - own.add(os.path.normpath(f)) - if top: - try: - own.add(os.path.normpath(os.path.relpath(f, top))) - except ValueError: - pass - out = [] - for r in rels: - if os.path.normpath(r) not in own: - out.append(r) - if len(out) >= 5: - break - return out - - -def _other_sessions(top, cwd, changed, sid, tp): - """Session ids that plausibly made `changed` edits, from session records and sibling transcripts.""" - found = [] - - def note(x): - if x and x != sid and x not in found: - found.append(x) - - def mentions(path, limit=2 * 1024 * 1024): - try: - with open(os.path.expanduser(path), "rb") as f: - f.seek(0, 2) - size = f.tell() - f.seek(max(0, size - limit)) - data = f.read() - except OSError: - return False - return any(os.path.basename(c).encode() in data or c.encode() in data for c in changed) - - try: - names = sorted(os.listdir(os.path.join(paths.state(), "sessions"))) - except OSError: - names = [] - for n in names: - if not n.endswith(".json"): - continue - try: - with open(os.path.join(paths.state(), "sessions", n), encoding="utf-8") as f: - r = json.load(f) - except (OSError, ValueError): - continue - if not isinstance(r, dict): - continue - osid = r.get("session_id") or n[:-5] - if osid == sid: - continue - proj = r.get("req_project") or r.get("cwd") - if top and proj and gitutil.root(proj) not in (top, proj) and os.path.realpath(proj) != os.path.realpath(top): - # a record for another folder says nothing about this tree - if os.path.realpath(proj) != os.path.realpath(cwd): - continue - files = r.get("attr_files") or [] - hit = any(os.path.basename(f) in [os.path.basename(c) for c in changed] or - (top and os.path.normpath(os.path.join(top, c)) == os.path.normpath(f)) for f in files for c in changed) - if hit: - note(osid) - elif isinstance(r.get("transcript_path"), str) and changed and mentions(r["transcript_path"]): - note(osid) - if isinstance(tp, str) and changed: - try: - sibs = sorted(os.listdir(os.path.dirname(os.path.expanduser(tp)) or ".")) - except OSError: - sibs = [] - for n in sibs: - if n.endswith(".jsonl") and os.path.join(os.path.dirname(os.path.expanduser(tp)), n) != os.path.expanduser(tp): - p = os.path.join(os.path.dirname(os.path.expanduser(tp)), n) - if mentions(p): - note(n[:-len(".jsonl")]) - return found[:3] - - -# ---------------------------------------------------------------- rule 5: ask through the dialog -# Tools with a confirmed question dialog whose transcripts sisi can read in Claude-Code shape. -# Codex's request_user_input is behind a flag that is off by default, OpenCode's question tool has -# no readable transcript file here, and the other tools name no dialog at all, so they are exempt. -QUESTION_DIALOG_TOOLS = {"claude-code": ("AskUserQuestion",), "qwen": ("ask_user_question",)} -_RHETORICAL = (r"^who (wouldn'?t|couldn'?t|doesn'?t)\b", r"^what could possibly\b", - r"^(isn'?t|aren'?t) it (obvious|clear)\b") - - -def ends_with_question(text): - """True when a final message ends by asking the reader a question. The rule, exactly: after - removing fenced code blocks, blockquote lines and inline code, the last sentence of the last - paragraph ends with a question mark that is not inside a closing quote (a quoted question), - and the sentence does not start with a known rhetorical form.""" - if not isinstance(text, str) or not text.strip(): - return False - kept, in_fence = [], False - for line in text.split("\n"): - if line.strip().startswith("```"): - in_fence = not in_fence - continue - if in_fence or line.lstrip().startswith(">"): - continue - kept.append(re.sub(r"`[^`]*`", "", line)) - paras = [p.strip() for p in re.split(r"\n\s*\n", "\n".join(kept)) if p.strip()] - if not paras: - return False - para = " ".join(paras[-1].split()) - t = para.rstrip("*_ ") - if t.endswith(('?"', "?\"", "?'", "?’", "?”")): # the question mark sits inside a quotation - return False - t = t.rstrip(')]*_ ') - if not t.endswith("?"): - return False - start = max(t.rfind(".", 0, len(t) - 1), t.rfind("!", 0, len(t) - 1), t.rfind("?", 0, len(t) - 1)) + 1 - sentence = t[start:].strip().lower() - return not any(re.match(p, sentence) for p in _RHETORICAL) - - -def _last_turn(tp): - """(final assistant text, tool names used) after the last message the human typed, from the - transcript tail. None when the turn cannot be bounded (the caller then exempts the turn).""" - try: - size = os.path.getsize(os.path.expanduser(tp)) - with open(os.path.expanduser(tp), "rb") as f: - f.seek(max(0, size - 2 * 1024 * 1024)) - data = f.read() - except OSError: - return None - from . import harvest - recs = [] - for raw in data.split(b"\n"): - if not raw.strip(): - continue - try: - d = json.loads(raw.decode("utf-8", "replace")) - except ValueError: - continue # a cut first line or a corrupt one: it cannot be the turn's evidence either way - if isinstance(d, dict): - recs.append(d) - last_human = -1 - for i, d in enumerate(recs): - if d.get("type") == "user": - try: - if harvest.typed_text(d)[0] is not None: - last_human = i - except Exception: - pass - if last_human < 0: - return None - final, tools = "", set() - for d in recs[last_human + 1:]: - content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None - texts = [] - for x in content if isinstance(content, list) else []: - if not isinstance(x, dict): - continue - if x.get("type") == "tool_use" and isinstance(x.get("name"), str): - tools.add(x["name"]) - elif x.get("type") == "text" and isinstance(x.get("text"), str): - texts.append(x["text"]) - if texts and d.get("type") in ("assistant", None): - final = "\n".join(texts) - return final, tools - - -def _question_sendback(payload): - """('block', reason) when this turn ended by asking in reply text and no question dialog was - used in it; None otherwise. At most once per final message, keyed by its hash in the session - record, so a session can never be trapped. Subagents and dialog-less tools are exempt.""" - tool = store.tool() - dialogs = QUESTION_DIALOG_TOOLS.get(tool or "") - if not dialogs: - return None - if payload.get("agent_id") or payload.get("agent_transcript_path"): - return None # a subagent has no human to ask through a dialog - cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() - sid = _session_key(payload, cwd) - sess = store.load_session(sid) - tp = payload.get("transcript_path") if isinstance(payload.get("transcript_path"), str) else sess.get("transcript_path") - if not isinstance(tp, str) or not tp: - return None - turn = _last_turn(tp) - if not turn: - return None - final, tools = turn - if any(d in tools for d in dialogs) or not ends_with_question(final): - return None - key = hashlib.sha1(final.encode("utf-8", "replace")).hexdigest()[:16] - if sess.get("q_block_key") == key: - return None - sess["q_block_key"] = key - sess["req_blocks"] = int(sess.get("req_blocks", 0)) + 1 - store.save_session(sid, sess) - return "block", ("sisi: you ended by asking the human a question in the text of your reply. Ask it through the " - "tool's question dialog (%s), with options to pick from and the one you recommend marked — or " - "decide it yourself, record the assumption, and finish without the question. " - "(The rule in full: `sisi rule decide-dont-ask`.)" % dialogs[0]) - - -def _measure_work(cwd, base=None): - """Growth of the work itself: sisi's own contract file is not product work and never counts.""" - m = gitutil.measure(cwd, base) - rel = C.REL.replace(os.sep, "/") - if rel in m["files"]: - lines = m["lines"] - try: - with open(os.path.join(gitutil.root(cwd) or cwd, C.REL), "rb") as f: - lines = max(0, lines - (f.read().count(b"\n") or 1)) - except OSError: - pass - return {"lines": lines, "files": [f for f in m["files"] if f != rel]} - return m + from . import harvest + t0 = harvest.epoch(c["started"]) if isinstance(c.get("started"), str) else None + stats = U._transcript_stats(project, t0, time.time()) if t0 is not None else None + if stats and stats.get("corrections"): + return "the human corrected the agent" + except Exception as e: + store.log_error("gate-anomaly", e) + return None def _decide(payload): """Return ('allow', message_or_None) or ('block', reason).""" cfg = store.config() - g = cfg["gate"] - if not g.get("enabled", True): + if not cfg["gate"].get("enabled", True): return "allow", None - cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() + from . import workers + if workers.is_subagent_payload(payload): + return decide_subagent(payload) + cwd = _cwd(payload) sid = _session_key(payload, cwd) os.environ["SISI_SESSION_ID"] = sid sess = store.load_session(sid) + if sess.get("subagent"): + return "allow", None # a session another agent started: its last message is its report to that agent if not (sess.get("started") or sess.get("first_seen")): sess["first_seen"] = store.now() - store.save_session(sid, sess) - since = sess.get("started") or sess.get("first_seen") + top = gitutil.root(cwd) path = C.find(cwd) - sess["req_contract"], sess["req_project"] = bool(path), cwd + sess["req_contract"], sess["req_project"] = bool(path), top or cwd if isinstance(payload.get("transcript_path"), str): sess["transcript_path"] = payload["transcript_path"] # `sisi retro` reads the request's start from it tp = sess.get("transcript_path") if isinstance(sess.get("transcript_path"), str) else None + + # 1. what did this session itself change since its last settled stop? try: - attr = _update_attribution(sess, tp) if tp else None + attr = attribution.update(sess, tp) if tp else None except Exception as e: # attribution must never break the gate: fail towards strict, not open store.log_error("gate-attribution", e) - attr = {"gen": int(sess.get("attr_gen", 0) or 0), "writing": True, "unknown": True} + attr = {"gen": int(sess.get("attr_gen", 0) or 0), "writing": True, "unknown": True, "files": []} if attr is not None: try: from . import watch @@ -600,32 +282,21 @@ def _decide(payload): attr["unknown"] = True # a shell command with a before but no after: strict except Exception as e: store.log_error("gate-watch-pending", e) - since_pass = sess.setdefault("attr_since_pass", []) - top0 = gitutil.root(cwd) - for f in attr.get("files") or []: - rel = f - if os.path.isabs(f) and top0: - try: - rel = os.path.relpath(f, top0) - except ValueError: - rel = f - if rel not in since_pass: - since_pass.append(rel) - if attr.get("shell_edits") and not sess.get("attr_measured") and "*shell*" not in since_pass: - since_pass.append("*shell*") # a text-classified shell edit: its paths are unknown - try: - store.save_session(sid, sess) # persist the offset even on an early return below - except Exception: - pass + _absorb_subagents(sess, sid, top) + _note_own_paths(sess, attr, top) + fp = gitutil.fingerprint(cwd, [path]) if top else None + if attr is not None: + gen = int(sess.get("attr_gen", 0) or 0) + if attr["unknown"] or gen > int(sess.get("seen_gen", 0) or 0): + sess["dirty"] = True + sess["seen_gen"] = gen + elif fp is None or fp != sess.get("settled_fp", sess.get("baseline_fp")): + sess["dirty"] = True # no transcript to read: the tree against its last settled state + stop = _Stop(sess, sid, cfg, fp, attr) + store.save_session(sid, sess) - def _own_since(key): - if attr is None: - return None # no transcript path known: pre-attribution behaviour - return bool(attr["unknown"] or int(sess.get("attr_gen", 0) or 0) > int(sess.get(key, 0) or 0)) - - own_since_pass = _own_since("attr_pass_gen") - own_since_retro = _own_since("attr_retro_gen") - c, errs = None, [] + # the open unit + c, errs, project = None, [], top or cwd if path: project = C.project_dir(path) if not trust.is_trusted(project): @@ -637,295 +308,220 @@ def _decide(payload): try: c = C.load(path) except (OSError, ValueError) as e: - errs = ["cannot read contract: %s" % e] - if c is not None and C.is_unedited_skeleton(c): - path = None # nothing real written yet: behave as if there is no contract + errs, c = ["cannot read contract: %s" % e], {} + if c is not None and c and C.is_unedited_skeleton(c): + c, path = None, None # nothing real written yet: behave as if there is no contract sess["req_contract"] = False - if c is not None and path and c.get("status") == "paused": - from . import unit as _unit - 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": - path = None # the unit is archived; new work stands or falls on its own + elif isinstance(c, dict) and c.get("status") == "closed": + c, path = None, None # the unit is archived; new work stands or falls on its own sess["req_contract"] = False - top = gitutil.root(cwd) - sess["req_project"] = top or (project if path else cwd) - fp = gitutil.fingerprint(cwd, [path]) if top else None - ctx = _Ctx(sess, sid, cfg, fp) + elif isinstance(c, dict) and c.get("status") == "paused": + if not sess.get("dirty") or top is None or c.get("pause_fp") == gitutil.fingerprint(cwd): + return stop.allow(cwd, settle=bool(sess.get("dirty"))) # a recorded wait, no new change + U.resume(c, path) # the tree changed since the pause: the wait is over + stop.refresh(cwd, path) + if not sess.get("dirty"): + return _late_close(stop, cwd, c, path, project) + + # 2. the profile + if top is None: + if c is None: + return stop.allow(cwd) + floor, reasons, own_floor = "isolated", ["not a git repository: the change cannot be measured"], None + else: + own = _own_changed(sess, sid, cwd, top, attr) + own_floor, own_reasons = risk.assess(own, diff_text=_diff_text(project, sess.get("head")), + patterns=risk.load_patterns(project)) + claimed = c is not None and (attr is None or _claims_unit(sess, path)) # no transcript: every change is ours + if own_floor == "trivial" and not claimed and not (c is not None and sess.get("last_unit") == c.get("id")): + return stop.allow(cwd) # documentation and the like, or nothing of this session's: nothing is asked + if c is not None: + files = gitutil.measure(project, c.get("base_head"))["files"] + floor, reasons = risk.assess(files, diff_text=_diff_text(project, c.get("base_head")), + patterns=risk.load_patterns(project)) + floor = max(floor, own_floor, key=lambda p: assure.ORDER[p]) + else: + floor, reasons = own_floor, own_reasons + profile, info = assure.effective_profile(floor, c) + if c is not None: + sess["last_unit"] = c.get("id") + req = assure.requirements(profile) + + # a fresh waiver for a change with no unit: recorded as a deviation, the contract is not demanded + w = _new_waiver(top or project, sess) if c is None else None + if w: + sess["waiver_ns"] = w.get("ns", 0) + return stop.allow(cwd) + + if profile == "trivial" or not req.get("contract"): + return _trivial(stop, cwd, c, path, project, profile) + + # 3. what the profile requires, and the selected fast checks + results, deadline = [], time.time() + float(cfg["gate"].get("budget_s", 120)) + if c is not None and not errs: + errs = C.validate(c) + if c is not None and not errs: + t_run = time.time() + results = V.run(c, project, deadline, cfg["verify"]["default_timeout_s"], tiers=("fast",), contract_path=path) + sess["req_check_s"] = float(sess.get("req_check_s", 0.0)) + (time.time() - t_run) + V.record(c, project, results, fp) ds = None - if path and c is not None and not C.validate(c): + if req.get("all_checks") and c is not None and not errs: try: + from . import deep as D ds = D.deep_state(c, project, fp) except Exception as e: store.log_error("gate-deep", e) - dfail = bool(ds and ds["state"] == "failed" and ds["fresh"]) # deep failure on the current tree - retro_on = bool(cfg.get("retro", {}).get("required", True)) - repo_key = top or (project if path else cwd) + 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"]] + miss = assure.missing(profile, c, project, results, errs, ds["state"] if ds else None) - def need_retro(real_work): - """True when real work was done and no retro covers the current tree state yet.""" - if not (retro_on and real_work): - return False - sess["real_work"] = True - from . import retro - if retro.satisfied(repo_key, since, fp): - sess["retro_done"] = True - if attr is not None: - sess["attr_retro_gen"] = int(sess.get("attr_gen", 0) or 0) - return False - return True + if miss or failing: + return _send_back(stop, cwd, c, path, project, profile, info, reasons, miss, failing, results) - _csp = {} + # 4. all green + if c is not None and c.get("unverified"): + c.pop("unverified") # re-verified since the gate released it + C.save(path, c) + stop.refresh(cwd, path) + note = _technique_note(c, profile, sess) + if c is None: # a waived change, or nothing that needs a unit + return stop.allow(cwd, note) + findings = [] + try: + from . import learning + findings = learning.findings_for_unit(project, c["id"]) + except Exception as e: + store.log_error("gate-findings", e) + if findings: + return _close(stop, cwd, c, path, project, profile, note) + if not cfg.get("retro", {}).get("required", True): + return stop.allow(cwd, note) + if sess.get("offered") == [c["id"], fp]: + return stop.allow(cwd, note) # offered once for this state of the tree; not repeated + sess["offered"] = [c["id"], fp] + text = _offer_text(c, profile, None) + return stop.block(text + ("\n" + note if note else ""), c["id"], project, counts=False) - def changed_paths_since_pass(): - if "v" not in _csp: - v = None - if attr is not None: - try: - from . import watch - v = watch.changed_since_pass(sid, cwd) - except Exception as e: - store.log_error("gate-watch-diff", e) - _csp["v"] = v if v is not None else _changed_paths(top, cwd, []) - return _csp["v"] - def own_responsible(): - """This session answers for the failing tree when a path that changed since the last - passing state is attributed to it (edit tool path, or a measured command window), or - when attribution is uncertain. Gen-only fallback when no path differs (e.g. the - contract itself changed, which the stat snapshot does not track).""" - if attr is None: - return True - if attr["unknown"]: - return True - changed = changed_paths_since_pass() - if not changed: - return bool(own_since_pass) - since = set(sess.get("attr_since_pass") or []) - if "*shell*" in since or "*shell-unmeasured*" in since: - return True - return any(p in changed for p in since) +def _trivial(stop, cwd, c, path, project, profile): + """A trivial change asks nothing, unless the unit shows an anomaly: then the retro is asked once.""" + sess = stop.sess + if c is None or not stop.cfg.get("retro", {}).get("required", True): + return stop.allow(cwd) + why = _anomaly(c, project, sess) + if not why: + return stop.allow(cwd) + try: + from . import learning + if learning.findings_for_unit(project, c["id"]): + return _close(stop, cwd, c, path, project, profile, None) + except Exception as e: + store.log_error("gate-findings", e) + if sess.get("offered") == [c["id"], None]: + return stop.allow(cwd) + sess["offered"] = [c["id"], None] + return stop.block(_offer_text(c, profile, why), c["id"], project, counts=False) - def other_allow(failing_text, contract_id=None): - """Someone else's failing tree: allow once per distinct tree state, recorded unverified.""" - if sess.get("other_notice_fp") == fp: - return ctx.allow() - sess["other_notice_fp"] = fp - store.append("results", {"ts": store.now(), "contract": contract_id, "project": project if path else repo_key, - "check": "gate", "item": "gate", "kind": None, "rung": None, - "status": "unverified", "duration_s": 0.0, "tool": store.tool(), "session": sid}) - own_paths = set(sess.get("attr_since_pass") or []) - changed = [p for p in changed_paths_since_pass() if p not in own_paths][:5] \ - or _changed_paths(top, cwd, sess.get("attr_files") or []) - others = _other_sessions(top, cwd, changed, sid, tp) - lines = ["sisi: the contract is NOT satisfied, but this session has not edited files since the " - "checks last passed (or since it started), so this turn may end. Do not report this work " - "as done; the result is recorded as UNVERIFIED. Relay this to the human.", - "Failing checks:\n" + failing_text] - if changed: - lines.append("Files changed in the tree that this session did not edit (likely another " - "session's work in progress): " + ", ".join(changed)) - if others: - lines.append("The changed files appear in the transcript/session record of session(s): " - + ", ".join(others)) - else: - lines.append("Files changed by another session are the likely cause; no other session " - "could be identified from the records available.") - return ctx.allow("\n".join(lines)) - def other_tree_changed(): - """The tree moved since this session's last pass or its start (dirty-vs-HEAD is the - fallback proxy when no start fingerprint was ever recorded for the session).""" - if fp is not None: - if sess.get("attr_pass_fp"): - return fp != sess["attr_pass_fp"] - if sess.get("baseline_fp") is not None: - return fp != sess["baseline_fp"] - if sess.get("last_fp") is not None: - return fp != sess["last_fp"] - return bool(_changed_paths(top, cwd, sess.get("attr_files") or [])) - - w = _new_waiver(top, sess) if (top and not path) else None # a fresh waiver re-opens the decision - # A turn that changed nothing is not punished and not re-checked. - if fp is not None and not w: - if sess.get("last_fp") is not None: - same, last = fp == sess["last_fp"], sess.get("last_decision") - else: - same, last = fp == sess.get("baseline_fp"), "allow" - if same and last == "allow" and not dfail: - return "allow", None - retro_clear = False - if same and last == "block" and sess.get("last_kind") == "retro": - from . import retro - retro_clear = retro.satisfied(repo_key, since, fp) - if same and last == "block" and sess.get("last_msg") and not retro_clear \ - and not (sess.get("last_kind") == "deep" and not dfail): - return ctx.block(sess["last_msg"], sess.get("last_contract"), sess.get("last_project"), - kind=sess.get("last_kind", "fast")) - - if path: - deadline = time.time() + float(g.get("budget_s", 120)) - if c is not None: - errs = C.validate(c) - if errs: - results = [{"item": "contract", "id": "contract", "status": "failed", "kind": None, "rung": None, - "claim": "contract is invalid", "duration_s": 0.0, "tail": "\n".join(errs)}] - else: - t_run = time.time() - results = V.run(c, project, deadline, cfg["verify"]["default_timeout_s"], tiers=("fast",), - reuse=False, contract_path=path) - sess["req_check_s"] = float(sess.get("req_check_s", 0.0)) + (time.time() - t_run) - V.record(c, project, results, fp) - if V.ok(results): - own_before_pass = own_since_pass - responsible_before_pass = own_responsible() if attr is not None else True - other_before_pass = attr is not None and not responsible_before_pass and other_tree_changed() - if attr is not None: - sess["attr_pass_gen"] = int(sess.get("attr_gen", 0) or 0) - sess["attr_pass_fp"] = fp - sess["attr_since_pass"] = [] - try: - from . import watch - watch.save_pass_snapshot(sid, cwd) - except Exception as e: - store.log_error("gate-watch-pass", e) - if dfail: - tails = "\n".join("- deep check %s [%s]:\n%s" % (i["id"], i["status"], "\n".join(" " + l for l in i["tail"].splitlines()[-15:])) - for i in ds["failed"]) - if other_before_pass: - return other_allow(tails[:4000], c["id"] if c else None) - return ctx.block("sisi: the fast checks pass, but the deep checks failed on the current tree " - "(send-back {n}). Fix the work, then re-run them with `sisi verify --deep " - "--background` (see `sisi verify --state`). Do not report this work as done.\n\n%s" - % tails[:4000], c["id"], project, kind="deep") - changed = fp is None or fp != sess.get("baseline_fp") - if need_retro(changed if attr is None else bool(own_since_retro)): - from . import retro - return ctx.block(retro.TEMPLATE, c["id"] if c else None, project, kind="retro") - if ds and ds["state"] != "fresh-pass" and sess.get("deep_notice") != (fp or "nofp"): - sess["deep_notice"] = fp or "nofp" - text = ("sisi: the fast checks pass, but the deep checks are %s (%d item%s). The work is NOT yet " - "verified end to end: report it as not yet done, say that deep checks are pending, and " - "start them with `sisi verify --deep --background` (progress: `sisi verify --state`)." - % (ds["state"], ds["items"], "" if ds["items"] == 1 else "s")) - return ctx.allow({"message": "sisi: deep checks %s; the work is not yet fully verified" % ds["state"], - "context": text}) - return ctx.allow() - if attr is not None and not own_responsible() and other_tree_changed(): - return other_allow(V.failure_report(results), c["id"] if c else None) - msg = ("sisi: the contract at %s is not satisfied (send-back {n}). Fix the work, then run " - "`sisi verify` until it passes. Do not report this work as done.\n\n%s" - % (path, V.failure_report(results))) +def _late_close(stop, cwd, c, path, project): + """This session changed nothing, but a retro was recorded for the open unit it evaluated before: + the unit closes now rather than waiting for the next change.""" + s = stop.sess + if c is not None and path and c.get("status", "open") == "open" and s.get("last_unit") == c.get("id") \ + and not c.get("unverified"): try: - from . import retro - failing = " ".join("%s %s %s" % (r["id"], r.get("kind") or "", r.get("claim") or "") - for r in results if r["status"] in ("failed", "not-run")) - block = retro.lessons_block(failing, "gate", session=sid) - if block: - msg += "\n\n" + block + from . import learning + if learning.findings_for_unit(project, c["id"]): + rec, msg, ok = U.close_unit(c, path, project) + if ok: + stop.refresh(cwd, path) + return stop.allow(cwd, _cycle_note(stop.sid)) except Exception as e: - store.log_error("gate-lessons", e) - return ctx.block(msg, c["id"] if c else None, project) + store.log_error("gate-late-close", e) + return "allow", None - if not top: - return "allow", None - if sess.get("baseline") is None: - sess.update(baseline=_measure_work(cwd), head=gitutil.head(cwd), started=sess.get("started") or store.now()) - sess["baseline_fp"] = fp - if attr is not None: - sess["attr_baseline_gen"] = int(sess.get("attr_gen", 0) or 0) - store.save_session(sid, sess) - return "allow", None - if attr is not None and not _own_since("attr_baseline_gen") and not attr["unknown"]: - return ctx.allow() # this session edited nothing here: no retro, no growth send-back for others' work - # Fix 4: growth is measured from the session start, or from the latest waiver. - if w: - sess["baseline"] = {"lines": w.get("lines", 0), "files": w.get("files", [])} - sess["head"] = w.get("head") - sess["waiver_ns"] = w.get("ns", 0) - sess["blocks"] = 0 - now = _measure_work(cwd, sess.get("head")) - base = sess["baseline"] - dl = max(0, now["lines"] - base["lines"]) - df = len(set(now["files"]) - set(base["files"])) - if not (dl > int(g.get("growth_lines", 40)) or df > int(g.get("growth_files", 3))): - if need_retro(bool(sess.get("waiver_ns")) if attr is None else bool(own_since_retro)): - from . import retro - return ctx.block(retro.TEMPLATE, kind="retro") - return ctx.allow() - return ctx.block("sisi: this session has changed %d lines and %d files since its start and there is no " - "contract (send-back {n}). Write `.sisi/contract.json` (`sisi contract init` makes the " - "skeleton; give it at least one check with a real command), then run `sisi verify`. If " - "the change needs no checks, run `sisi contract waive \"\"` instead." % (dl, df)) + +def _cycle_note(sid): + try: + from . import cycle + note = cycle.due_notice(session=sid) + return note + " (This turn may end; the cycle is background work, not a send-back.)" if note else None + except Exception as e: + store.log_error("gate-cycle-notice", e) + return None + + +def _close(stop, cwd, c, path, project, profile, note): + rec, msg, ok = U.close_unit(c, path, project) + if not ok: # it cannot close as delivered: say why, like any other send-back + return _send_back(stop, cwd, c, path, project, profile, {}, [], [(msg.replace("sisi: ", ""), "")], [], []) + stop.refresh(cwd, path) + cyc = _cycle_note(stop.sid) + return stop.allow(cwd, "\n".join(x for x in (note, cyc) if x) or None) + + +def _send_back(stop, cwd, c, path, project, profile, info, reasons, miss, failing, results): + uid = c["id"] if c else None + why = ["%s" % m[0] for m in miss] + ["%s failed" % f["id"] for f in failing] + if stop.exhausted(): + return _release(stop, cwd, c, path, project, why) + lines = ["sisi: this %s change is not ready to hand over (send-back {n})." % profile] + if reasons: + lines[0] = lines[0][:-1] + " because %s." % reasons[0][:160] + if info.get("refused"): + lines.append("The contract declares %r, but the change is %r; add risk.why to lower it on the record." + % (info.get("declared"), info.get("floor"))) + if miss: + lines.append("Missing:") + lines += ["- %s -> %s" % (a, b) if b else "- %s" % a for a, b in miss] + if failing: + lines.append("Failing checks:") + lines += assure.failure_lines(failing, per_check=3) + lines.append("Fix these, then run `sisi verify`. Do not report this work as done.") + note = _technique_note(c, profile, stop.sess) + if note: + lines.append(note) + return stop.block(assure.fit(lines), uid, project) def decide(payload): - """The gate's answer: the contract/retro decision, then — only on an otherwise-clean stop — + """The gate's answer: the contract decision, then — only on an otherwise-clean stop — the rule-5 question check, which sends the agent back at most once per final message.""" action, msg = _decide(payload) if action != "allow": return action, msg try: - q = _question_sendback(payload) + from . import questions + q = questions.sendback(payload) except Exception as e: # the question check must never break the gate store.log_error("gate-question", e) q = None return q if q else (action, msg) -def subagent_edits(transcript): - """(edited_files, start_ts) from a subagent transcript (JSONL). start_ts is in sisi's timestamp format, or None.""" - edited, start = False, None - with open(os.path.expanduser(transcript), encoding="utf-8", errors="replace") as f: - for line in f: - try: - d = json.loads(line) - except ValueError: - continue - if start is None and isinstance(d.get("timestamp"), str) and len(d["timestamp"]) >= 19: - start = d["timestamp"][:19] + "Z" - content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None - for x in content if isinstance(content, list) else []: - if isinstance(x, dict) and x.get("type") == "tool_use" and x.get("name") in EDIT_TOOLS: - edited = True - if isinstance(x, dict) and x.get("type") == "tool_use" and x.get("name") in ("Bash", "Shell"): - inp = x.get("input") if isinstance(x.get("input"), dict) else {} - if _shell_may_write(inp.get("command")) is not False: - edited = True - return edited, start - - def decide_subagent(payload): - """SubagentStop: only the retro requirement, only when the subagent edited files (read from its transcript).""" - cfg = store.config() - if not cfg.get("retro", {}).get("required", True) or not cfg["gate"].get("enabled", True): - return "allow", None - tp = payload.get("agent_transcript_path") - if not isinstance(tp, str): - return "allow", None # cannot tell whether it changed files: do not block - edited, start = subagent_edits(tp) - if not edited or not start: - return "allow", None - cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() - from . import retro - if retro.satisfied(retro.repo_of(cwd), start, None): - return "allow", None - key = "sub-%s" % (payload.get("agent_id") or "unknown") - sess = store.load_session(key) - blocks, maxb = int(sess.get("blocks", 0)), int(cfg["gate"].get("max_blocks", 3)) - if blocks >= maxb: - return "allow", None - sess["blocks"] = blocks + 1 - store.save_session(key, sess) - return "block", retro.TEMPLATE.replace("{n}", "%d of %d" % (blocks + 1, maxb)) + """SubagentStop: never blocks and never asks for a retro. A subagent's last message is its + report to its parent and stays that. What it observed is recorded for the parent's gate: that + it edited, and which files its edit tools named.""" + try: + tp = payload.get("agent_transcript_path") + if isinstance(tp, str) and tp and isinstance(payload.get("session_id"), str): + edited, files, _start = attribution.observed_edits(tp) + store.append("subagents", {"ts": store.now(), "ns": time.time_ns(), "session": payload["session_id"], + "agent": payload.get("agent_id"), "project": _cwd(payload), + "edited": edited, "files": files}) + except Exception as e: + store.log_error("gate-subagent", e) + return "allow", None def _record_delivery(payload): """The request is delivered: write one delivery row. Never raises, never changes the gate's answer.""" try: from . import delivery - cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() + cwd = _cwd(payload) sid = _session_key(payload, cwd) delivery.record(payload, store.load_session(sid), sid, cwd) except Exception as e: @@ -943,10 +539,6 @@ def main(args=()): _record_delivery(payload) if action == "block": sys.stdout.write(json.dumps({"decision": "block", "reason": msg}) + "\n") - elif isinstance(msg, dict): - # Documented for Stop: hookSpecificOutput.additionalContext reaches the model (and continues the turn once). - sys.stdout.write(json.dumps({"systemMessage": msg["message"], "hookSpecificOutput": { - "hookEventName": "Stop", "additionalContext": msg["context"]}}) + "\n") elif msg: sys.stdout.write(json.dumps({"systemMessage": msg}) + "\n") return 0 diff --git a/sisi/learning.py b/sisi/learning.py index 2d6bacb..b4272d9 100644 --- a/sisi/learning.py +++ b/sisi/learning.py @@ -34,7 +34,12 @@ GENERIC_WORDS = set(( "improving improvement quality thorough thoroughly review reviewing think thinking plan planning ahead " "going forward all any some general generally just really very much many bit little slightly again once " "ever also too so can could would will may might worse avoid mistakes mistake fine ok okay well everything " - "anything something stuff careless carelessness sloppy rushed hasty lazy diligent diligence").split()) + "anything something stuff careless carelessness sloppy rushed hasty lazy diligent diligence " + # a non-finding says only that nothing stood out ("it went well", "no problems, as expected") + "went go goes gone smooth smoothly expected nicely perfect perfectly success successful successfully " + "finished complete completed happened happen hitch hitches without notable remarkable report reported " + "particular special specific cause causes reason reasons known unknown clear obvious say said " + "passed pass green").split()) class LearningError(Exception): diff --git a/sisi/questions.py b/sisi/questions.py new file mode 100644 index 0000000..a18f37e --- /dev/null +++ b/sisi/questions.py @@ -0,0 +1,130 @@ +"""Rule 5 at the end of a turn: a reply that ends by asking the human a question must have asked it +through the tool's question dialog. Sent back at most once per final message, never a subagent.""" +import hashlib, json, os, re + +from . import store + + +def _session_key(payload, cwd): + sid = payload.get("session_id") + return sid if isinstance(sid, str) and sid else "cwd-" + hashlib.sha1(cwd.encode()).hexdigest()[:12] + + +# ---------------------------------------------------------------- rule 5: ask through the dialog +# Tools with a confirmed question dialog whose transcripts sisi can read in Claude-Code shape. +# Codex's request_user_input is behind a flag that is off by default, OpenCode's question tool has +# no readable transcript file here, and the other tools name no dialog at all, so they are exempt. +QUESTION_DIALOG_TOOLS = {"claude-code": ("AskUserQuestion",), "qwen": ("ask_user_question",)} +_RHETORICAL = (r"^who (wouldn'?t|couldn'?t|doesn'?t)\b", r"^what could possibly\b", + r"^(isn'?t|aren'?t) it (obvious|clear)\b") + + +def ends_with_question(text): + """True when a final message ends by asking the reader a question. The rule, exactly: after + removing fenced code blocks, blockquote lines and inline code, the last sentence of the last + paragraph ends with a question mark that is not inside a closing quote (a quoted question), + and the sentence does not start with a known rhetorical form.""" + if not isinstance(text, str) or not text.strip(): + return False + kept, in_fence = [], False + for line in text.split("\n"): + if line.strip().startswith("```"): + in_fence = not in_fence + continue + if in_fence or line.lstrip().startswith(">"): + continue + kept.append(re.sub(r"`[^`]*`", "", line)) + paras = [p.strip() for p in re.split(r"\n\s*\n", "\n".join(kept)) if p.strip()] + if not paras: + return False + para = " ".join(paras[-1].split()) + t = para.rstrip("*_ ") + if t.endswith(('?"', "?\"", "?'", "?’", "?”")): # the question mark sits inside a quotation + return False + t = t.rstrip(')]*_ ') + if not t.endswith("?"): + return False + start = max(t.rfind(".", 0, len(t) - 1), t.rfind("!", 0, len(t) - 1), t.rfind("?", 0, len(t) - 1)) + 1 + sentence = t[start:].strip().lower() + return not any(re.match(p, sentence) for p in _RHETORICAL) + + +def _last_turn(tp): + """(final assistant text, tool names used) after the last message the human typed, from the + transcript tail. None when the turn cannot be bounded (the caller then exempts the turn).""" + try: + size = os.path.getsize(os.path.expanduser(tp)) + with open(os.path.expanduser(tp), "rb") as f: + f.seek(max(0, size - 2 * 1024 * 1024)) + data = f.read() + except OSError: + return None + from . import harvest + recs = [] + for raw in data.split(b"\n"): + if not raw.strip(): + continue + try: + d = json.loads(raw.decode("utf-8", "replace")) + except ValueError: + continue # a cut first line or a corrupt one: it cannot be the turn's evidence either way + if isinstance(d, dict): + recs.append(d) + last_human = -1 + for i, d in enumerate(recs): + if d.get("type") == "user": + try: + if harvest.typed_text(d)[0] is not None: + last_human = i + except Exception: + pass + if last_human < 0: + return None + final, tools = "", set() + for d in recs[last_human + 1:]: + content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None + texts = [] + for x in content if isinstance(content, list) else []: + if not isinstance(x, dict): + continue + if x.get("type") == "tool_use" and isinstance(x.get("name"), str): + tools.add(x["name"]) + elif x.get("type") == "text" and isinstance(x.get("text"), str): + texts.append(x["text"]) + if texts and d.get("type") in ("assistant", None): + final = "\n".join(texts) + return final, tools + + +def sendback(payload): + """('block', reason) when this turn ended by asking in reply text and no question dialog was + used in it; None otherwise. At most once per final message, keyed by its hash in the session + record, so a session can never be trapped. Subagents and dialog-less tools are exempt.""" + tool = store.tool() + dialogs = QUESTION_DIALOG_TOOLS.get(tool or "") + if not dialogs: + return None + if payload.get("agent_id") or payload.get("agent_transcript_path"): + return None # a subagent has no human to ask through a dialog + cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() + sid = _session_key(payload, cwd) + sess = store.load_session(sid) + tp = payload.get("transcript_path") if isinstance(payload.get("transcript_path"), str) else sess.get("transcript_path") + if not isinstance(tp, str) or not tp: + return None + turn = _last_turn(tp) + if not turn: + return None + final, tools = turn + if any(d in tools for d in dialogs) or not ends_with_question(final): + return None + key = hashlib.sha1(final.encode("utf-8", "replace")).hexdigest()[:16] + if sess.get("q_block_key") == key: + return None + sess["q_block_key"] = key + sess["req_blocks"] = int(sess.get("req_blocks", 0)) + 1 + store.save_session(sid, sess) + return "block", ("sisi: you ended by asking the human a question in the text of your reply. Ask it through the " + "tool's question dialog (%s), with options to pick from and the one you recommend marked — or " + "decide it yourself, record the assumption, and finish without the question. " + "(The rule in full: `sisi rule decide-dont-ask`.)" % dialogs[0]) diff --git a/sisi/scorecard.py b/sisi/scorecard.py index 427a685..fc59b13 100644 --- a/sisi/scorecard.py +++ b/sisi/scorecard.py @@ -5,7 +5,7 @@ Missing data is unavailable with value None: never zero, never good. No single s ever computed or printed. Check statistics and escape candidates (work declared verified that then turned out wrong) live here too: they feed the correctness and intent dimensions. """ -import json, os, re +import json, os, re, time from . import harvest, store @@ -186,6 +186,7 @@ def build_scorecard(c, results, telemetry, delivery_status): "techniques": val(sorted({"rung %s" % x.get("rung") for x in items.values()} | {str(x.get("kind")) for x in items.values() if x.get("kind")}), "measured"), "checks_seen_failing": val(sum(1 for r in latest.values() if r.get("seen_failing")), "measured"), + "stronger_than_examples": val(any(x.get("rung") in (1, 2) for x in items.values()), "measured"), "independent_evidence": val(any(norm_status((latest.get(cid) or {}).get("status")) == "passed" for cid, x in items.items() if x.get("independent")), "measured"), "deviation": val(delivery_status == "deviation", "measured"), @@ -345,8 +346,74 @@ def format_dimension(dim, vals): ("; %d unavailable" % n_un) if n_un else "") -def format_status(units, learning=False, recent=5): +def _age(iso, now=None): + """'3h', '2d', '15m' since an ISO UTC time; '?' when it cannot be read.""" + from . import harvest + t = harvest.epoch(iso) if isinstance(iso, str) else None + if t is None: + return "?" + s = max(0, (time.time() if now is None else now) - t) + return "%dd" % (s // 86400) if s >= 86400 else "%dh" % (s // 3600) if s >= 3600 else "%dm" % (s // 60) + + +def open_units(cwd=None): + """The unit that is open or paused in this project, as display rows. A unit that waits (paused) + says what for and for how long; one that was declared below its floor says so, with the reason.""" + from . import contract as C, unit as U, assure + out = [] + try: + p = C.find(cwd or os.getcwd()) + c = C.load(p) if p else None + except (OSError, ValueError): + return out + if not isinstance(c, dict) or not c.get("id") or c.get("status") == "closed" or C.is_unedited_skeleton(c): + return out + project = C.project_dir(p) + row = {"id": c["id"], "status": c.get("status", "open"), "age": _age(c.get("started")), "goal": c.get("goal") or ""} + if row["status"] == "paused": + pz = next((x for x in reversed(c.get("pauses") or []) if isinstance(x, dict) and not x.get("until")), {}) + row["waiting_for"], row["paused_for"] = pz.get("what"), _age(pz.get("since")) + rk = c.get("risk") or {} + floor, _ = U.risk_floor(c, project) + floor = floor.get("value") if isinstance(floor, dict) else floor + if assure.is_lowered(floor, rk.get("profile"), rk.get("why")): + row["lowered"] = "declared %s below the floor %s: %s" % (rk.get("profile"), floor, rk.get("why")) + if c.get("unverified"): + row["unverified"] = "; ".join(c["unverified"].get("why") or []) + out.append(row) + return out + + +def _lowered_note(u): + rk = u.get("risk") or {} + if not rk.get("lowered"): + return "" + floor = rk.get("floor") + floor = floor.get("value") if isinstance(floor, dict) else floor + return " [lowered: declared %s, floor %s%s]" % (rk.get("declared"), floor, + (": " + str(rk["why"])) if rk.get("why") else "") + + +def format_open(rows): lines = [] + for r in rows: + if r["status"] == "paused": + lines.append("paused %-24s age %s waiting for: %s (for %s)" % (r["id"], r["age"], r.get("waiting_for") or "?", r.get("paused_for"))) + else: + lines.append("open %-24s age %s %s" % (r["id"], r["age"], r["goal"][:80])) + if r.get("lowered"): + lines.append(" lowered: " + r["lowered"]) + if r.get("unverified"): + lines.append(" released unverified by the gate: " + r["unverified"]) + return lines + + +def format_status(units, learning=False, recent=5, opened=()): + lines = [] + if opened: + lines.append("units in progress:") + lines += [" " + ln for ln in format_open(opened)] + lines.append("") if not units: lines.append("sisi status: no closed work units yet. Close one with `sisi unit close`; " "its scorecard will appear here.") @@ -354,8 +421,8 @@ def format_status(units, learning=False, recent=5): lines.append("recent units (newest first, %d closed in all):" % len(units)) for u in list(reversed(units))[:recent]: lines.append("") - lines.append("%s %s [%s] %s" % (u.get("id"), str(u.get("ended") or "")[:10], - u.get("delivery_status"), u.get("goal") or "")) + lines.append("%s %s [%s] %s%s" % (u.get("id"), str(u.get("ended") or "")[:10], + u.get("delivery_status"), u.get("goal") or "", _lowered_note(u))) sc = u.get("scorecard") or {} for dim, vals in sc.items(): lines.append(format_dimension(dim, vals)) @@ -385,8 +452,9 @@ def format_status(units, learning=False, recent=5): def cmd_status(args=(), cwd=None, out=print): units = load_unit_summaries(cwd) + opened = open_units(cwd) if "--json" in args: - out(json.dumps({"units": units, "trends": trends(units)}, indent=2, default=str)) + out(json.dumps({"open": opened, "units": units, "trends": trends(units)}, indent=2, default=str)) return 0 - out(format_status(units, learning="--learning" in args)) + out(format_status(units, learning="--learning" in args, opened=opened)) return 0 diff --git a/sisi/store.py b/sisi/store.py index 12b2b85..21f7afe 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -5,7 +5,7 @@ from . import paths FILES = {"results": "results.jsonl", "learn": "learn.jsonl", "quarantine": "learn.jsonl", "waivers": "waivers.jsonl", - "deliveries": "deliveries.jsonl", "units": "units.jsonl"} + "deliveries": "deliveries.jsonl", "units": "units.jsonl", "subagents": "subagents.jsonl"} def _migrate_learn(): @@ -154,7 +154,7 @@ def stamp(extra): return rec -DEFAULTS = {"gate": {"enabled": True, "budget_s": 120, "max_blocks": 3, "growth_lines": 40, "growth_files": 3}, +DEFAULTS = {"gate": {"enabled": True, "budget_s": 120, "max_blocks": 3}, "verify": {"default_timeout_s": 60, "fast_limit_s": 60}, "retro": {"required": True}, "scratch": {"session_max_age_days": 30, "prune_every": 20, "prune_max_delete": 1000, diff --git a/sisi/tick.py b/sisi/tick.py index e5fa593..03ed8c0 100644 --- a/sisi/tick.py +++ b/sisi/tick.py @@ -75,8 +75,7 @@ def main(args=()): rec["attr_offset"] = os.path.getsize(os.path.expanduser(payload["transcript_path"])) except OSError: rec["attr_offset"] = 0 - rec.update(attr_gen=0, attr_pass_gen=0, attr_retro_gen=0, attr_baseline_gen=0, - attr_writing=False, attr_files=[], attr_sub_offsets={}) + rec.update(attr_gen=0, seen_gen=0, dirty=False, attr_writing=False, attr_files=[], attr_sub_offsets={}) from . import contract as C, gitutil if gitutil.root(cwd): rec["head"] = gitutil.head(cwd) diff --git a/sisi/unit.py b/sisi/unit.py index fe68f17..41b744a 100644 --- a/sisi/unit.py +++ b/sisi/unit.py @@ -137,14 +137,14 @@ def _row_epoch(r): def policy_version(project, c): - """Hash of the policies in force: the effective rulebook, the floors and risk tables, + """Hash of the policies in force: the effective rulebook, the risk tables, the enforced checks, and the gate/verify config.""" h = hashlib.sha256() rulebook = paths.generated() if not os.path.exists(rulebook): rulebook = paths.canon("core.md") # named by role, never by path: the same policies hash the same in any clone or project - for role, p in (("rulebook", rulebook), ("floors", paths.canon("floors.json")), + for role, p in (("rulebook", rulebook), ("risk table", paths.canon("risk.json")), ("project risk table", os.path.join(project, ".sisi", "risk.json"))): try: @@ -458,6 +458,8 @@ def decide_status(c, rows, abandon=None): return "abandoned", block, unrun if c.get("deviations"): return "deviation", block, unrun + if c.get("unverified"): # the gate released the unit after its send-backs and nothing has verified it since + return "unverified", block, unrun if block: released = any(r.get("check") == "gate" and r.get("status") == "unverified" for r in rows) return ("unverified" if released else None), block, unrun @@ -480,6 +482,8 @@ def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None, unrun = never_run(latest) floor, floor_reasons = risk_floor(c, project) declared = c.get("risk") or {} + from . import assure + floor_name = floor.get("value") if isinstance(floor, dict) else floor rec = { "id": c["id"], "parent": c.get("parent"), "goal": c.get("goal"), "scope": c.get("scope") or {"in": [], "out": []}, @@ -488,7 +492,10 @@ def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None, "checks": c.get("checks") or [], "invariants": c.get("invariants") or [], "risk": {"floor": floor, "floor_reasons": floor_reasons, "declared": declared.get("profile"), "why": declared.get("why"), + "lowered": assure.is_lowered(floor_name, declared.get("profile"), declared.get("why")), "blast_radius": declared.get("blast_radius"), "rollback": declared.get("rollback")}, + "stronger_technique": assure.stronger_technique(c), + "released_unverified": c.get("unverified"), "approach": c.get("approach"), "plan": c.get("plan") or [], "workers": delegation_rows, @@ -521,7 +528,7 @@ def summary_line(rec): floor = (risk.get("floor") or {}).get("value") if isinstance(risk.get("floor"), dict) else risk.get("floor") return {"id": rec["id"], "parent": rec.get("parent"), "project": rec.get("project"), "goal": rec.get("goal"), "delivery_status": rec.get("delivery_status"), - "risk": {"declared": risk.get("declared"), "floor": floor}, + "risk": {"declared": risk.get("declared"), "floor": floor, "lowered": bool(risk.get("lowered"))}, "models": rec.get("models") or [], "policy_version": rec.get("policy_version"), "started": rec.get("started"), "ended": rec.get("ended"), "closed_at": rec.get("closed_at"), "scorecard": rec.get("scorecard")} @@ -637,6 +644,25 @@ def resume(c, contract_path): return True +def verified_for_tree(c, project, contract_path): + """True when the unit's fast checks have a run that passed on exactly the tree as it is now + (what the commit-time notice asks). A run that was skipped or reused counts only if nothing in + it blocks and something passed. False when no run is recorded for this tree.""" + from . import verify as V + fp = V.tree_fp(project, contract_path) + if fp is None: + return True # outside git there is no tree to compare: nothing to say + runs = {} + for r in _unit_results(c, project, c.get("started")): + if r.get("fp") == fp and r.get("tier", "fast") == "fast" and r.get("run") and r.get("item") in ("check", "invariant"): + runs.setdefault(r["run"], []).append(r) + for rows in runs.values(): + if not V.blocking(rows) and any(r.get("status") == "passed" or str(r.get("reason") or "").startswith("reused: passed") + for r in rows): + return True + return False + + def summary_for_retro(project): """What `sisi retro` prints: the open unit's scorecard so far and what stands out in it.""" p = os.path.join(project, C.REL) diff --git a/sisi/verifiers.py b/sisi/verifiers.py index 021145e..766697c 100644 --- a/sisi/verifiers.py +++ b/sisi/verifiers.py @@ -433,21 +433,12 @@ def cmd_for(args): ranked = [(s + (1.0 if inst[e["path"]] == "yes" else 0.0), e) for s, e in cands] ranked.sort(key=lambda x: (-round(x[0], 1), x[1]["rung"], x[1]["id"])) top = ranked[:8] - fl = None - if "kind" in opts: - fl = C.floors().get(opts["kind"].lower()) - if fl: - print("Floor: %s claims need rung %d or stronger (canon/floors.json). Results marked [floor ok] satisfy it.\n" - % (opts["kind"], fl)) if not top: print("no verifier matches that description; try `sisi verifiers` to browse") _print_lessons(desc) return 0 for i, (f, e) in enumerate(top, 1): - mark = "" - if fl: - mark = " [floor ok]" if e["rung"] <= fl else " [below floor]" - print("%d. %s rung %s cost %s installed: %s%s%s" % (i, e["id"], e["rung"], e["cost"] or "-", inst[e["path"]], mark, origin_tag(e))) + print("%d. %s rung %s cost %s installed: %s%s" % (i, e["id"], e["rung"], e["cost"] or "-", inst[e["path"]], origin_tag(e))) print(" %s" % (e["answers"] or e["title"])) print("\nsisi verifiers show ID for set-up and a worked example") _print_lessons(desc, extra=" ".join(e["id"] for _, e in top[:3]), targets=tuple(e["id"] for _, e in top)) diff --git a/sisi/verify.py b/sisi/verify.py index 5f3c427..edb1627 100644 --- a/sisi/verify.py +++ b/sisi/verify.py @@ -285,11 +285,6 @@ def run(c, project, deadline=None, default_timeout=60, tiers=("fast",), changed= dirty_cache = True if dirty_cache: _save_cache(cache) - for f in (C.floor_failures(c) if "fast" in tiers else []): - res.append({"item": "floor", "tier": "fast", "id": "floor:" + f["kind"], "kind": f["kind"], "rung": None, - "claim": f["message"], "status": "failed", "reason": None, "duration_s": 0.0, - "tail": f["message"], "mandatory": True, "independent": False, "covers": None, - "seen_failing": True, "saved_s": 0.0}) if "fast" in tiers: # enforced lessons ride the same path as floors (personal overlay, trusted commands) try: from . import cycle diff --git a/sisi/watch.py b/sisi/watch.py index 9a6d1e3..5634941 100644 --- a/sisi/watch.py +++ b/sisi/watch.py @@ -12,7 +12,7 @@ that errs strict, which is the safe side. A pending before-record with no after killed) is likewise treated as this session having edited, with no known paths (a sentinel). Both hooks fail open: any error is logged and the tool call proceeds. """ -import json, os, time +import json, os, re, time from . import gitutil, paths, store @@ -191,6 +191,28 @@ def changed_since_pass(sid, cwd): return gitutil.snapshot_diff(pend, gitutil.snapshot(cwd)) +_COMMIT_RE = re.compile(r"(?:^|[;&|(]\s*)(?:\w+=\S+\s+)*git\s+(?:(?:-C|-c)\s+\S+\s+|--[\w-]+\s+)*(?:commit|merge)\b") + + +def commit_notice(payload): + """One line, never a block: the command is a `git commit` or `git merge` and the open unit's fast + checks have no passing result for the tree as it is now. None when there is nothing to say.""" + tool, cmd, _ev, cwd, _sid = extract(payload) + if not is_shell(tool, cmd) or not _COMMIT_RE.search(cmd): + return None + from . import contract as C, trust, unit + path = C.find(cwd) + if not path or not trust.is_trusted(C.project_dir(path)): + return None + c = C.load(path) + if not isinstance(c, dict) or c.get("status", "open") != "open" or C.is_unedited_skeleton(c) or C.validate(c): + return None + if unit.verified_for_tree(c, C.project_dir(path), path): + return None + return ("sisi: unit %s has no passing `sisi verify` result for the tree you are about to commit; run " + "`sisi verify` first (a notice, not a block)." % c.get("id")) + + def main(args=()): try: from . import gate @@ -198,6 +220,14 @@ def main(args=()): _tool, _cmd, ev, _cwd, _sid = extract(payload) if "--before" in args or ev in BEFORE_EVENTS: before(payload) + try: + line = commit_notice(payload) + if line: + import sys + sys.stdout.write(json.dumps({"systemMessage": line, "hookSpecificOutput": { + "hookEventName": "PreToolUse", "additionalContext": line}}) + "\n") + except Exception as e: + store.log_error("watch-commit-notice", e) elif "--after" in args or ev in AFTER_EVENTS: after(payload) except Exception as e: # fail open: a tool call must never be held up by measurement diff --git a/tests/test_contract.py b/tests/test_contract.py index 5e87b18..302b59b 100644 --- a/tests/test_contract.py +++ b/tests/test_contract.py @@ -40,17 +40,6 @@ class ContractTests(SisiCase): def test_rung_5_6_valid_without_cmd(self): self.assertEqual(C.validate(contract([check("a", "true"), human("h", 5), human("i", 6)])), []) - def test_floors(self): - weak = contract([check("m", "true", rung=3, kind="money")]) - self.assertEqual(len(C.floor_failures(weak)), 1) - self.assertEqual(C.floor_failures(contract([check("m", "true", rung=2, kind="money")])), []) - # one strong check among weak ones satisfies the floor - self.assertEqual(C.floor_failures(contract([check("m", "true", rung=3, kind="money"), - check("n", "true", rung=1, kind="money")])), []) - self.assertEqual(C.floor_failures(contract([check("u", "true", rung=4, kind="ui")])), []) - for k in ("concurrency", "parsing", "money", "state-machine", "migration"): - self.assertEqual(C.floors()[k], 2) - def test_find_stops_at_git_root(self): self.git_init() self.write_contract(contract([check("a", "true")])) diff --git a/tests/test_delivery.py b/tests/test_delivery.py index 9f611bb..e1b7785 100644 --- a/tests/test_delivery.py +++ b/tests/test_delivery.py @@ -169,6 +169,10 @@ class DeliveryRowTests(SisiCase): def test_send_backs_and_check_time_are_counted_for_the_request(self): self.write_contract(contract([check("bad", "sleep 0.3; exit 1")])) + with open(self.tp, "a") as f: # the agent edited a source file this turn + f.write(json.dumps({"type": "assistant", "timestamp": "2026-01-01T00:00:00.000Z", "message": { + "role": "assistant", "content": [{"type": "tool_use", "name": "Edit", + "input": {"file_path": os.path.join(self.proj, "app.py")}}]}}) + "\n") r = self.hook(transcript_path=self.tp) self.assertEqual(json.loads(r.stdout)["decision"], "block") self.assertEqual(self.rows(), []) # a send-back is not a delivery diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 448f8c3..e33f332 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -2,35 +2,161 @@ import json, os, unittest from support import * +def load(path): + with open(path) as f: + return json.load(f) + + +def tool_line(name, inp): + return {"type": "assistant", "timestamp": "2026-01-01T00:00:00.000Z", + "message": {"role": "assistant", "content": [{"type": "tool_use", "name": name, "input": inp}]}} + + class EndToEnd(SisiCase): + """R-5.3-1, R-9-1, R-10.3-1..7, R-15-13, R-17-3, R-17-5, R-17-7: the real hook entry points with + Claude-Code-shaped hook JSON, in a temp home and a temp git project, from install to a closed unit + and a unit the gate had to release as unverified.""" + + def setUp(self): + super().setUp() + os.environ["SISI_RETRO_REQUIRED"] = "1" + self.addCleanup(lambda: os.environ.__setitem__("SISI_RETRO_REQUIRED", "0")) + + def hook(self, event, **extra): + p = dict({"session_id": "e2e", "cwd": self.proj, "transcript_path": self.tp, "hook_event_name": event}, **extra) + return self.sisi("tick" if event == "SessionStart" else "gate", stdin=json.dumps(p)) + + def stop(self): + r = self.hook("Stop", stop_hook_active=False) + self.assertEqual(r.returncode, 0, r.stderr) + if not r.stdout.strip(): + return "allow", None + d = json.loads(r.stdout) + return ("block", d["reason"]) if d.get("decision") == "block" else ("allow", d.get("systemMessage")) + + def agent_writes(self, rel, text, tool="Write"): + p = os.path.join(self.proj, rel) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "a" if tool == "Edit" else "w") as f: + f.write(text) + with open(self.tp, "a") as f: + f.write(json.dumps(tool_line(tool, {"file_path": p})) + "\n") + + def agent_runs(self, command, *argv): + with open(self.tp, "a") as f: + f.write(json.dumps(tool_line("Bash", {"command": command})) + "\n") + return self.sisi(*argv) + + def finding(self, n): + r = self.sisi("retro", "--finding", "`cargo test` run %d took 4 minutes with no fuzz verifier in the project" % n, + "--cause", "the recipe never named a fuzz verifier for parsers", "--impact", "time", + "--disposition", "promote", + "--change", "Add the fuzz verifier to the parser-or-codec recipe Checks, variant %d" % n, + "--mechanism", "verification", "--expect", "parser work gets a fuzz check", + "--validate", "run the recipe checks on a parser change", env={"SISI_SESSION_ID": "e2e"}) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + def test_full_flow(self): for d in (".claude", ".codex", ".config/opencode"): os.makedirs(os.path.join(self.home, d)) with open(os.path.join(self.home, ".claude", "settings.json"), "w") as f: json.dump({"hooks": {"SessionStart": [{"matcher": "*", "hooks": [{"type": "command", "command": "existing"}]}]}}, f) self.git_init() + with open(os.path.join(self.proj, "README.md"), "w") as f: + f.write("# project\n") self.assertEqual(self.sisi("install").returncode, 0) - doc = self.sisi("doctor").stdout - self.assertIn("claude-code wired", doc) - payload = json.dumps({"session_id": "e2e", "cwd": self.proj, "hook_event_name": "SessionStart", "source": "startup"}) - self.assertEqual(self.sisi("tick", stdin=payload).stdout, "") - stop = json.dumps({"session_id": "e2e", "cwd": self.proj, "hook_event_name": "Stop", "stop_hook_active": False}) + self.assertIn("claude-code wired", self.sisi("doctor").stdout) + self.tp = os.path.join(self.tmp, "e2e.jsonl") + with open(self.tp, "w") as f: + f.write(json.dumps({"type": "user", "timestamp": "2026-01-01T00:00:00.000Z", + "message": {"role": "user", "content": "build the feature"}}) + "\n") + self.assertEqual(self.hook("SessionStart", source="startup").stdout, "") - self.write_contract(contract([check("feature", "test -f %s/done.txt" % self.proj, rung=3)])) - r = self.sisi("gate", stdin=stop) - self.assertEqual(r.returncode, 0) - d = json.loads(r.stdout) - self.assertEqual(d["decision"], "block") - self.assertIn("feature", d["reason"]) + # a documentation change: silent, nothing run, nothing asked + self.agent_writes("README.md", "more words\n", "Edit") + self.assertEqual(self.stop(), ("allow", None)) - open(os.path.join(self.proj, "done.txt"), "w").close() - r = self.sisi("gate", stdin=stop) - self.assertEqual((r.returncode, r.stdout), (0, "")) + # a source change with no contract: sent back, with what it needs + self.agent_writes("app.py", "def feature():\n return 1\n") + a, msg = self.stop() + self.assertEqual(a, "block") + self.assertIn("a contract for this isolated change", msg) + self.assertIn("sisi contract init", msg) - self.assertEqual(self.sisi("unit", "close").returncode, 0) + # a contract with a failing check: sent back with the failure + self.agent_runs("sisi contract init --goal 'build the feature'", "contract", "init", "--goal", "build the feature") + c = load(os.path.join(self.proj, ".sisi", "contract.json")) + c["id"] = "feature" + c["checks"] = [{"id": "feature", "claim": "done.flag exists", "kind": "general", "rung": 3, + "cmd": "test -f done.flag", "expect": {"exit": 0}}] + self.agent_writes(os.path.join(".sisi", "contract.json"), json.dumps(c)) + a, msg = self.stop() + self.assertEqual(a, "block") + self.assertIn("feature", msg) + self.assertIn("Failing checks", msg) + + # fixed: the two ways on are offered + self.agent_writes("done.flag", "ok\n") + a, msg = self.stop() + self.assertEqual(a, "block") + self.assertIn("sisi retro", msg) + self.assertIn("sisi unit pause", msg) + + # paused: silent + self.assertEqual(self.agent_runs("sisi unit pause 'the reviewer'", "unit", "pause", "the reviewer").returncode, 0) + self.assertEqual(self.stop(), ("allow", None)) + self.assertIn("paused", self.sisi("status").stdout) + + # a new change ends the wait; everything is green, so the two ways on come again + self.agent_writes("app.py", "# a change\n", "Edit") + a, msg = self.stop() + self.assertEqual(a, "block") + self.assertEqual(load(os.path.join(self.proj, ".sisi", "contract.json"))["status"], "open") + + # the retro is recorded: the unit closes, is archived, and the stop is silent + self.finding(1) + self.assertEqual(self.stop(), ("allow", None)) + rec = load(os.path.join(self.proj, ".sisi", "units", "feature.json")) + self.assertEqual(rec["delivery_status"], "delivered") out = self.sisi("status").stdout self.assertIn("[delivered]", out) self.assertIn("correctness and assurance", out) + + # a migration with no independent evidence: sent back with the list + self.agent_writes("migrations/001_users.sql", "CREATE TABLE users (id integer);\n") + self.agent_runs("sisi contract init --goal 'add users'", "contract", "init", "--goal", "add users") + c = load(os.path.join(self.proj, ".sisi", "contract.json")) + c["id"] = "users" + c["checks"] = [{"id": "schema", "claim": "the migration file is present", "kind": "migration", "rung": 3, + "cmd": "test -f migrations/001_users.sql", "expect": {"exit": 0}, + "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["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)) + a, msg = self.stop() + self.assertEqual(a, "block") + self.assertIn("this data change is not ready to hand over (send-back 1 of 3)", msg) + self.assertIn("independent evidence", msg) + self.assertLessEqual(len(msg.splitlines()), 25) + self.migration_message = msg + + # three send-backs in a row, then released as unverified and recorded + self.assertEqual(self.stop()[0], "block") + self.assertEqual(self.stop()[0], "block") + a, msg = self.stop() + self.assertEqual(a, "allow") + self.assertIn("UNVERIFIED", msg) + rows = [r for r in self.results() if r.get("check") == "gate" and r.get("status") == "unverified"] + self.assertEqual(len(rows), 1) + self.assertIn("independent evidence", rows[0]["reason"]) + self.assertIn("released unverified by the gate", self.sisi("status").stdout) + self.assertEqual(self.sisi("unit", "close").returncode, 0) + rec = load(os.path.join(self.proj, ".sisi", "units", "users.json")) + self.assertEqual(rec["delivery_status"], "unverified") + self.assertEqual(self.sisi("uninstall").returncode, 0) diff --git a/tests/test_gate.py b/tests/test_gate.py index b59d011..baca9b0 100644 --- a/tests/test_gate.py +++ b/tests/test_gate.py @@ -1,111 +1,848 @@ -import io, json, os, random, sys, unittest +"""The end-of-turn gate: risk-set requirements, bounded send-backs, attribution, pauses, subagents. + +Tests cite requirement ids (docs/spec/requirements.json). The property tests run seeded random +sequences of operations against a real git project and check invariants after every stop; scale them +with SISI_TEST_ITERS.""" +import io, json, os, random, subprocess, sys, time, unittest from unittest import mock from support import * -from sisi import gate, store +from sisi import assure, attribution, contract as C, gate, learning, store, unit as U, workers + + +def _tool_line(name, inp): + return {"type": "assistant", "timestamp": "2026-01-01T00:00:00.000Z", + "message": {"role": "assistant", "content": [{"type": "tool_use", "name": name, "input": inp}]}} + + +def _human_line(): + return {"type": "user", "timestamp": "2026-01-01T00:00:00.000Z", + "message": {"role": "user", "content": "do the work please"}} + + +def full(**over): + """A contract that satisfies every requirement of every profile except independent evidence.""" + c = contract([dict(check("works", "test -f ok.txt"), covers="the feature file is missing")], + [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"}, + 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=[]) + c.update(over) + return c class GateBase(SisiCase): sid = "sess-1" + def setUp(self): + super().setUp() + os.environ["SISI_RETRO_REQUIRED"] = "1" # these tests are about the retro: turn it on + self.addCleanup(lambda: os.environ.__setitem__("SISI_RETRO_REQUIRED", "0")) + self.git_init() + self.put("README.md", "# project\n") + self.put("ok.txt", "ready\n") + self.commit_all() + self.tdir = os.path.join(self.tmp, "transcripts") + os.makedirs(self.tdir) + + def put(self, rel, text="x\n", mode="w"): + p = os.path.join(self.proj, rel) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, mode) as f: + f.write(text) + return p + + def commit_all(self, msg="c"): + subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True) + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", msg], cwd=self.proj, check=True) + + def session(self, sid=None): + return Sess(self, sid or self.sid) + def call(self, cwd=None, sid=None, **extra): - """Run the gate in process as the hook would. Returns (action, message).""" + """Run the gate in process as the hook would, with no transcript (every tree change is this session's).""" payload = dict({"session_id": sid or self.sid, "cwd": cwd or self.proj, "hook_event_name": "Stop", "stop_hook_active": False}, **extra) return gate.decide(payload) - def hook(self, payload=None, cwd=None): + def hook(self, payload=None, cwd=None, args=()): """Run the real hook command: JSON stdin, stdout, exit code.""" p = dict({"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop"}, **(payload or {})) - return self.sisi("gate", cwd=cwd, stdin=json.dumps(p)) + return self.sisi("gate", *args, cwd=cwd, stdin=json.dumps(p)) - def set_config(self, **gate_cfg): - os.makedirs(self.state, exist_ok=True) - with open(os.path.join(self.state, "config.json"), "w") as f: - json.dump({"gate": gate_cfg}, f) + def unit_state(self): + c = C.load(os.path.join(self.proj, C.REL)) + c.setdefault("status", "open") + return c + + def archives(self): + d = os.path.join(self.proj, ".sisi", "units") + return sorted(os.listdir(d)) if os.path.isdir(d) else [] + + def record_finding(self, n=1, cwd=None, sid=None): + r = self.sisi("retro", + "--finding", "`cargo test` run %d took 4 minutes with no fuzz verifier in the project" % n, + "--cause", "the recipe never named a fuzz verifier for parsers", + "--impact", "time", "--disposition", "promote", + "--change", "Add the fuzz verifier to the parser-or-codec recipe Checks, variant %d" % n, + "--mechanism", "verification", "--expect", "parser work gets a fuzz check", + "--validate", "run the recipe checks on a parser change", cwd=cwd, + env={"SISI_SESSION_ID": sid or self.sid}) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + def lines(self, msg): + return len(str(msg).splitlines()) -class GateContractTests(GateBase): - def test_pass_allows_with_no_output(self): - self.write_contract(contract([check("ok", "true")])) - r = self.hook() - self.assertEqual((r.returncode, r.stdout), (0, "")) +class Sess: + """One agent session in the test project: a Claude-Code-shaped transcript that records its edits, + the session-start hook, and the stop hook.""" - def test_fail_blocks_with_claude_format(self): - self.write_contract(contract([check("bad", "echo boom-output >&2; exit 1")])) - r = self.hook() - self.assertEqual(r.returncode, 0) + def __init__(self, case, sid): + self.case, self.sid = case, sid + self.tp = os.path.join(case.tdir, sid + ".jsonl") + with open(self.tp, "w") as f: + f.write(json.dumps(_human_line()) + "\n") + case.sisi("tick", stdin=json.dumps({"session_id": sid, "cwd": case.proj, "source": "startup", + "transcript_path": self.tp})) + + def _line(self, name, inp): + with open(self.tp, "a") as f: + f.write(json.dumps(_tool_line(name, inp)) + "\n") + + def edit(self, rel, text="x\n"): + """The agent edits a file with its edit tool.""" + p = self.case.put(rel, text, mode="a") + self._line("Edit", {"file_path": p}) + return p + + def write(self, rel, text): + p = self.case.put(rel, text) + self._line("Write", {"file_path": p}) + return p + + def remove(self, rel): + os.remove(os.path.join(self.case.proj, rel)) + self._line("Bash", {"command": "rm " + rel}) + + def shell(self, command): + self._line("Bash", {"command": command}) + + def contract(self, c): + """The agent writes the contract file (a claim on the unit).""" + self.case.write_contract(c) + self._line("Write", {"file_path": os.path.join(self.case.proj, C.REL)}) + + def stop(self): + """('allow'|'block', message or None) from the real hook entry point.""" + r = self.case.sisi("gate", stdin=json.dumps({"session_id": self.sid, "cwd": self.case.proj, + "hook_event_name": "Stop", "transcript_path": self.tp})) + self.case.assertEqual(r.returncode, 0, r.stderr) + if not r.stdout.strip(): + return "allow", None d = json.loads(r.stdout) - self.assertEqual(d["decision"], "block") - self.assertIn("bad", d["reason"]) - self.assertIn("boom-output", d["reason"]) + return ("block", d["reason"]) if d.get("decision") == "block" else ("allow", d.get("systemMessage")) - def test_timeout_and_floor_block(self): - self.write_contract(contract([check("slow", "sleep 5", timeout_s=0.2)])) - self.assertEqual(self.call()[0], "block") - self.write_contract(contract([check("m", "true", rung=3, kind="money")])) - a, msg = self.call(sid="other") + +# ======================================================================== requirements by profile + +class RequirementTests(GateBase): + """R-5.3-1..11: the gate enforces exactly what the profile's row of canon/risk.json requires.""" + + def test_the_table_is_monotone_in_the_profile(self): + """R-5.3-2: a higher profile never requires less (seeded random contracts).""" + rng = random.Random(7) + keys = ["requirements", "risk", "approach", "invariants"] + for _ in range(40 * ITERS): + c = full() + for k in keys: + if rng.random() < 0.5: + c.pop(k, None) if k != "invariants" else c.update(invariants=[]) + if rng.random() < 0.5: + c["checks"][0].pop("covers") + lows = [assure.missing(p, c, self.proj) for p in ("isolated", "logic", "integration", "data", "critical", "release")] + for a, b in zip(lows, lows[1:]): + self.assertTrue({m[0] for m in a} <= {m[0] for m in b}, (c, a, b)) + + def test_trivial_needs_nothing_and_isolated_needs_a_contract_with_a_check(self): + """R-5.3-4, R-5.3-5.""" + self.assertEqual(assure.missing("trivial", None, self.proj), []) + miss = assure.missing("isolated", None, self.proj) + self.assertEqual(len(miss), 1) + self.assertIn("sisi contract init", miss[0][1]) + self.assertEqual(assure.missing("isolated", contract([check("a", "false")]), self.proj), []) + + 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")]) + miss = assure.missing("logic", c, self.proj) + self.assertEqual(len(miss), 1) + self.assertIn("a", miss[0][0]) + self.assertNotIn("(missing on a, b)", miss[0][0]) + self.assertEqual(assure.missing("logic", full(), self.proj), []) + + 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) + 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) + self.assertEqual(assure.missing("integration", full(), self.proj), []) + + def test_data_critical_and_release_need_independent_evidence(self): + """R-5.3-8, R-5.3-9, R-5.3-10.""" + for p in ("data", "critical", "release"): + miss = assure.missing(p, full(), self.proj) + self.assertEqual(len(miss), 1, p) + self.assertIn("independent", miss[0][0]) + self.assertEqual(assure.missing("integration", full(), self.proj), []) + + def test_the_table_is_data_not_code(self): + """R-5.3-1: a project that edits the table's row changes what the gate asks, with no code change.""" + from sisi import risk + row = risk.requirements_for("logic") + self.assertTrue(row["covers"]) + with mock.patch.object(risk, "requirements_for", return_value=dict(row, covers=False)): + self.assertEqual(assure.missing("logic", contract([check("a", "false")]), self.proj), []) + + def test_a_declared_profile_raises_freely(self): + """R-5.3-1.""" + p, info = assure.effective_profile("isolated", full(risk={"profile": "data"})) + self.assertEqual((p, info["lowered"]), ("data", False)) + + def test_floor_wins_over_a_trivial_declaration_without_a_reason(self): + """R-5.3-1, abuse: declares `trivial` on a migration with no `risk.why`: the floor wins.""" + p, info = assure.effective_profile("data", full(risk={"profile": "trivial"})) + self.assertEqual((p, info["refused"], info["lowered"]), ("data", True, False)) + for why in ("TODO", "n/a", "none", ""): + p, info = assure.effective_profile("data", full(risk={"profile": "trivial", "why": why})) + self.assertEqual(p, "data", why) + + def test_lowering_with_a_reason_is_allowed_recorded_and_visible_in_status(self): + """R-5.3-1, abuse: with a reason the declaration stands; the record keeps floor, declared and reason.""" + c = full(risk={"profile": "trivial", "why": "the migration only adds a comment to a table"}) + p, info = assure.effective_profile("data", c) + self.assertEqual((p, info["lowered"]), ("trivial", True)) + self.git_init_unit = None + self.put("migrations/001_comment.sql", "COMMENT ON TABLE t IS 'x';\n") + self.write_contract(c) + c_path = os.path.join(self.proj, C.REL) + rec = U.build_record(c, self.proj, "delivered", time.time(), rows=[]) + self.assertEqual((rec["risk"]["floor"]["value"], rec["risk"]["declared"], rec["risk"]["lowered"]), + ("data", "trivial", True)) + self.assertEqual(rec["risk"]["why"], "the migration only adds a comment to a table") + out = self.sisi("status").stdout + self.assertIn("lowered: declared trivial below the floor data: the migration only adds a comment", out) + self.assertTrue(os.path.exists(c_path)) + + def test_placeholder_text_is_not_a_requirement_a_risk_note_or_an_approach(self): + """R-5.3-7, abuse: present but empty, or placeholder text, counts as missing.""" + for junk in ("TODO", "n/a", "none", "TBD", "", " ", "-", "ok", "TODO: fill in later"): + c = full(requirements=[{"id": "r1", "kind": "explicit", "text": junk, "decision": "now"}], + risk={"blast_radius": junk, "rollback": junk}, + approach={"chosen": junk, "why": junk, "alternatives": [junk]}) + text = " | ".join(m[0] for m in assure.missing("integration", c, self.proj)) + for piece in ("requirement list", "risk note", "the approach"): + self.assertIn(piece, text, "%r: %s" % (junk, piece)) + self.assertTrue(C.is_placeholder("N/A")) + self.assertFalse(C.is_placeholder("git revert the commit and rerun the migration")) + + def test_an_approach_needs_an_alternative(self): + """R-5.3-7.""" + c = full(approach={"chosen": "write the file directly", "why": "the simplest thing", "alternatives": []}) + self.assertIn("the approach", " ".join(m[0] for m in assure.missing("integration", c, self.proj))) + + def test_independent_flag_without_by_is_not_evidence(self): + """R-5.3-9, abuse: `independent: true` with no `by` (or a placeholder `by`).""" + results = [{"id": "works", "status": "passed"}] + for by in (None, "", "TODO", "n/a"): + ck = dict(check("works", "test -f ok.txt"), covers="the file is missing", independent=True) + if by is not None: + ck["by"] = by + c = full(checks=[ck]) + self.assertEqual(assure.independent_evidence(self.proj, c, results), [], by) + ck = dict(check("works", "test -f ok.txt"), covers="the file is missing", independent=True, + by="the reference parser in tools/ref.py") + c = full(checks=[ck]) + self.assertEqual(len(assure.independent_evidence(self.proj, c, results)), 1) + self.assertEqual(assure.independent_evidence(self.proj, c, [{"id": "works", "status": "failed"}]), []) + self.assertEqual(assure.missing("data", c, self.proj, results), []) + + def judged(self, **over): + row = {"kind": "attempt", "id": "a1", "ts": round(time.time()), "project": os.path.basename(self.proj), + "type": "review", "difficulty": 2, "worker": "reviewer-model", "outcome": "accepted", "check": "read"} + row.update(over) + workers.append_record(row) + + def test_a_judged_review_in_the_window_is_independent_evidence(self): + """R-5.3-9.""" + c = full(started=store.now()) + self.assertEqual(len(assure.missing("data", c, self.proj)), 1) + self.judged() + self.assertEqual(assure.missing("data", c, self.proj), []) + + def test_review_rows_that_do_not_count(self): + """R-5.3-9, abuse: outside the window, another project, rejected, checked with `none`, not a review.""" + c = full(started=store.now()) + for over in ({"ts": round(time.time()) - 7200}, {"project": "some-other-project"}, {"outcome": "rejected"}, + {"check": "none"}, {"check": None}, {"type": "impl"}): + self.judged(**over) + self.assertEqual(assure.review_evidence(self.proj, c), []) + self.assertEqual(len(assure.missing("data", c, self.proj)), 1) + self.judged(check="diffstat") # stronger than none: counts + self.assertEqual(len(assure.review_evidence(self.proj, c)), 1) + + def test_a_technique_stronger_than_examples(self): + """R-5.3-6.""" + self.assertFalse(assure.stronger_technique(contract([check("a", "false", rung=3)]))) + self.assertTrue(assure.stronger_technique(contract([check("a", "false", rung=2)]))) + self.assertTrue(assure.stronger_technique(contract([check("a", "false", rung=4)], [check("i", "false", rung=1)]))) + + +# ======================================================================== the flow + +class FlowTests(GateBase): + def test_a_session_that_changed_nothing_passes_silently(self): + """R-17-3: no change, no check run, no message.""" + self.write_contract(full(checks=[check("bad", "false")])) + s = self.session() + self.assertEqual(s.stop(), ("allow", None)) + self.assertEqual(self.results(), []) + + def test_documentation_only_passes_silently_even_with_a_failing_unit_open(self): + """R-5.3-4, R-17-3.""" + self.write_contract(contract([check("bad", "false")])) + s = self.session() + s.edit("README.md", "more words\n") + self.assertEqual(s.stop(), ("allow", None)) + + def test_a_source_change_without_a_contract_is_sent_back_once_with_the_list(self): + """R-5.3-5, R-17-5.""" + s = self.session() + s.write("app.py", "def f():\n return 1\n") + a, msg = s.stop() self.assertEqual(a, "block") - self.assertIn("floor", msg) + self.assertIn("a contract for this isolated change", msg) + self.assertIn("sisi contract init", msg) + self.assertLessEqual(self.lines(msg), 25) + self.assertEqual(s.stop()[0], "block") # still nothing: sent back again (and counted) - def test_invalid_contract_blocks(self): - self.write_contract({"id": "x"}) - self.assertEqual(self.call()[0], "block") - - def test_budget_makes_unfinished_checks_timeout(self): - self.set_config(budget_s=0.4) - self.write_contract(contract([check("a", "sleep 3", timeout_s=60), check("b", "true")])) - a, msg = self.call() + def test_failing_check_sends_back_then_green_offers_the_two_ways_on(self): + """R-10.3-4, R-10.3-6: failing is sent back with the failure; green offers retro or pause, once.""" + s = self.session() + s.write("app.py", "x = 1\n") + s.contract(contract([check("feature", "test -f done.flag")])) + a, msg = s.stop() self.assertEqual(a, "block") - st = {r["check"]: r["status"] for r in self.results()} - self.assertEqual(st, {"a": "not-run", "b": "not-run"}) # a timed out, b never ran: neither passed + self.assertIn("feature", msg) + self.assertIn("Failing checks", msg) + s.write("done.flag", "ok\n") + a, msg = s.stop() + self.assertEqual(a, "block") + self.assertIn("sisi retro", msg) + self.assertIn("sisi unit pause", msg) + self.assertLessEqual(self.lines(msg), 25) + self.assertEqual(s.stop(), ("allow", None)) # said once: not repeated for the same tree - def test_three_strikes_then_unverified_release_then_reset(self): - self.write_contract(contract([check("bad", "false")])) - self.assertEqual([self.call()[0] for _ in range(3)], ["block"] * 3) - a, msg = self.call() - self.assertEqual(a, "allow") - self.assertIn("UNVERIFIED", msg) - self.assertEqual(self.results()[-1]["status"], "unverified") - out = self.hook() # after release the count restarts: blocks again - self.assertEqual(json.loads(out.stdout)["decision"], "block") + def test_pause_is_silent_and_a_new_change_ends_the_wait(self): + """R-10.3-1, R-14.2-1: abuse: a pause (it names what it waits for, such as an owner's authorization) asks + nothing while the tree is unchanged; a change ends it.""" + s = self.session() + s.write("app.py", "x = 1\n") + s.contract(contract([check("feature", "test -f ok.txt")])) + self.assertEqual(s.stop()[0], "block") # the offer + self.assertEqual(self.sisi("unit", "pause", "the reviewer").returncode, 0) + self.assertEqual(s.stop(), ("allow", None)) + self.assertEqual(self.unit_state()["status"], "paused") + s.edit("app.py", "y = 2\n") + a, msg = s.stop() + self.assertEqual(self.unit_state()["status"], "open") # the wait ended + self.assertEqual(a, "block") + self.assertIn("sisi retro", msg) - def test_unverified_release_is_printed(self): - self.write_contract(contract([check("bad", "false")])) - for _ in range(3): - self.hook() - r = self.hook() - self.assertIn("UNVERIFIED", json.loads(r.stdout)["systemMessage"]) + def test_a_pause_is_never_a_way_to_hide(self): + """R-15-13, abuse: init refuses while a unit is open (or paused); status lists both with their age.""" + s = self.session() + s.write("app.py", "x = 1\n") + s.contract(contract([check("feature", "test -f ok.txt")]) | {"started": store.now()}) + self.sisi("unit", "pause", "waiting for ever") + r = self.sisi("contract", "init") + self.assertEqual(r.returncode, 1) + self.assertIn("still open", r.stdout) + out = self.sisi("status").stdout + self.assertRegex(out, r"paused\s+t\s+age \d+[mhd]\s+waiting for: waiting for ever") + c = self.unit_state() + c["status"] = "open" + C.save(os.path.join(self.proj, C.REL), c) + self.assertRegex(self.sisi("status").stdout, r"open\s+t\s+age \d+[mhd]") - def test_pass_resets_count(self): - self.write_contract(contract([check("c", "test -f %s/ok" % self.tmp)])) - self.call(); self.call() - open(os.path.join(self.tmp, "ok"), "w").close() - self.assertEqual(self.call()[0], "allow") - os.remove(os.path.join(self.tmp, "ok")) - self.assertEqual([self.call()[0] for _ in range(3)], ["block"] * 3) # fresh three strikes + def test_a_recorded_retro_closes_and_archives_the_unit(self): + """R-10.3-5, R-10.3-7.""" + s = self.session() + s.write("app.py", "x = 1\n") + s.contract(contract([check("feature", "test -f ok.txt")])) + self.assertEqual(s.stop()[0], "block") # offer + self.record_finding() + self.assertEqual(s.stop(), ("allow", None)) + self.assertEqual(self.unit_state()["status"], "closed") + self.assertEqual(self.archives(), ["t.json"]) + self.assertEqual(s.stop(), ("allow", None)) - def test_strikes_are_per_session(self): - self.write_contract(contract([check("bad", "false")])) - for _ in range(3): - self.call(sid="a") - self.assertEqual(self.call(sid="b")[0], "block") + def test_a_generic_finding_does_not_close_the_unit(self): + """R-10.3-7, abuse: the learning module refuses it, so the gate has nothing to close on.""" + s = self.session() + s.write("app.py", "x = 1\n") + s.contract(contract([check("feature", "test -f ok.txt")])) + self.assertEqual(s.stop()[0], "block") + r = self.sisi("retro", "--finding", "it went well", "--cause", "no cause", "--impact", "time", + "--disposition", "record", "--limits", "none", env={"SISI_SESSION_ID": self.sid}) + self.assertEqual(learning.findings_for_unit(self.proj, "t"), [], r.stdout) + s.edit("app.py", "y = 2\n") + a, msg = s.stop() + self.assertEqual(a, "block") + self.assertIn("sisi retro", msg) + self.assertEqual(self.unit_state()["status"], "open") + self.assertEqual(self.archives(), []) - def test_stop_hook_active_does_not_bypass(self): - self.write_contract(contract([check("bad", "false")])) - self.assertEqual(self.call(stop_hook_active=True)[0], "block") + def test_a_retro_recorded_after_a_quiet_stop_still_closes_the_unit(self): + """R-10.3-7: the offer was ignored once; the retro is recorded later with no edit.""" + s = self.session() + s.write("app.py", "x = 1\n") + s.contract(contract([check("feature", "test -f ok.txt")])) + s.stop() + self.assertEqual(s.stop(), ("allow", None)) # offered once; not repeated; unit still open + self.assertEqual(self.unit_state()["status"], "open") + self.record_finding() + self.assertEqual(s.stop(), ("allow", None)) + self.assertEqual(self.unit_state()["status"], "closed") + + def test_a_trivial_unit_asks_nothing_unless_it_shows_an_anomaly(self): + """R-5.3-4: nothing is asked for a trivial change; two send-backs make the retro worth asking.""" + self.write_contract(contract([check("feature", "test -f ok.txt")], ) | {"risk": {"profile": "trivial"}}) + s = self.session() + s.contract(contract([check("feature", "test -f ok.txt")]) | {"risk": {"profile": "trivial"}}) + s.edit("README.md", "words\n") + self.assertEqual(s.stop(), ("allow", None)) # quiet + st = store.load_session(self.sid) + st["sb_unit"] = 2 # two send-backs earlier in this unit + store.save_session(self.sid, st) + s.edit("README.md", "more words\n") + a, msg = s.stop() + self.assertEqual(a, "block") + self.assertIn("sisi retro", msg) + self.assertIn("sent the agent back 2 times", msg) + self.assertEqual(s.stop(), ("allow", None)) # asked once + + def test_declaring_trivial_on_a_migration_without_a_reason_does_not_lower_it(self): + """R-5.3-8, abuse: end to end through the gate.""" + s = self.session() + s.write("migrations/001_users.sql", "CREATE TABLE users (id integer);\n") + s.contract(full(risk={"profile": "trivial", "blast_radius": "one table, nothing reads it yet", + "rollback": "drop the table"})) + a, msg = s.stop() + self.assertEqual(a, "block") + self.assertIn("declares 'trivial', but the change is 'data'", msg) + self.assertIn("independent evidence", msg) + + def test_a_migration_with_a_reason_runs_at_the_lowered_profile(self): + """R-5.3-8, abuse.""" + s = self.session() + s.write("migrations/001_users.sql", "COMMENT ON TABLE users IS 'people';\n") + s.contract(full(risk={"profile": "trivial", "why": "a comment on a table changes no data"})) + self.assertEqual(s.stop(), ("allow", None)) # trivial: nothing asked + self.assertIn("lowered", self.sisi("status").stdout) + + def test_removing_a_failing_check_does_not_make_the_unit_read_as_delivered(self): + """R-10.3-3, R-15-6, abuse: the check fails, the agent deletes it, the unit is not plainly delivered.""" + s = self.session() + s.write("app.py", "x = 1\n") + s.contract(contract([check("good", "test -f ok.txt"), check("hard", "test -f never.txt")])) + a, msg = s.stop() + self.assertEqual(a, "block") + self.assertIn("hard", msg) + c = self.unit_state() + c["checks"] = [x for x in c["checks"] if x["id"] != "hard"] + s.contract(c) + self.assertEqual(s.stop()[0], "block") # the offer + self.record_finding() + self.assertEqual(s.stop(), ("allow", None)) + with open(os.path.join(self.proj, ".sisi", "units", "t.json")) as f: + rec = json.load(f) + failed = [r for r in rec["verification"] if r["check"] == "hard" and r["status"] == "failed"] + self.assertTrue(failed) # the failed result is in the record + self.assertNotIn("hard", [x["id"] for x in rec["contract"]["checks"]]) # and so is the removal + + def test_green_technique_note_is_given_once_and_never_blocks(self): + """R-5.3-6: a logic change with no check stronger than examples.""" + s = self.session() + s.write("parser.py", "def parse(s):\n return s.split()\n") + s.contract(full(risk={"profile": "logic", "blast_radius": "the parser only", "rollback": "revert"})) + a, msg = s.stop() + self.assertEqual(a, "block") # the offer, carrying the note + self.assertIn("sisi verifiers for", msg) + s.edit("parser.py", "# more\n") + a, msg = s.stop() + self.assertNotIn("sisi verifiers for", msg or "") # once + rec = U.build_record(self.unit_state(), self.proj, "delivered", time.time(), rows=[]) + self.assertFalse(rec["stronger_technique"]) + + def test_waive_lets_a_change_without_a_contract_end_and_is_a_recorded_deviation(self): + """R-10.3-2: a waiver is a deviation, never a pass.""" + s = self.session() + s.write("app.py", "x = 1\n") + self.assertEqual(s.stop()[0], "block") + self.assertEqual(self.sisi("contract", "waive", "a throwaway script").returncode, 0) + self.assertEqual(s.stop(), ("allow", None)) + self.assertEqual(store.read("waivers")[0]["reason"], "a throwaway script") def test_disabled_allows(self): - self.set_config(enabled=False) self.write_contract(contract([check("bad", "false")])) - self.assertEqual(self.call()[0], "allow") + os.makedirs(self.state, exist_ok=True) + with open(os.path.join(self.state, "config.json"), "w") as f: + json.dump({"gate": {"enabled": False}}, f) + s = self.session() + s.write("app.py", "x = 1\n") + self.assertEqual(s.stop(), ("allow", None)) - def test_contract_found_from_subdir_up_to_git_root(self): - self.git_init() + def test_not_a_git_repo_allows(self): + d = os.path.join(self.tmp, "plain") + os.makedirs(d) + self.assertEqual(self.call(cwd=d), ("allow", None)) + + def test_the_contract_is_found_from_a_subdirectory(self): + self.write_contract(contract([check("bad", "false")]) | {"risk": {"profile": "isolated"}}) + os.makedirs(os.path.join(self.proj, "sub")) + a, msg = self.call(cwd=os.path.join(self.proj, "sub")) + self.assertEqual(a, "block") + self.assertIn("bad", msg) + + def test_a_check_over_the_budget_is_reported_not_passed(self): + """R-15-5: a check that cannot finish in time is not-run, never passed.""" + with open(os.path.join(self.tmp, "cfg"), "w"): + pass + os.makedirs(self.state, exist_ok=True) + with open(os.path.join(self.state, "config.json"), "w") as f: + json.dump({"gate": {"budget_s": 0.4}}, f) + self.write_contract(contract([check("a", "sleep 3", timeout_s=60), check("b", "test -f ok.txt")]) | {"risk": {"profile": "isolated"}}) + a, msg = self.call() + self.assertEqual(a, "block") + self.assertEqual({r["check"]: r["status"] for r in self.results()}, {"a": "not-run", "b": "not-run"}) + + +# ======================================================================== bounded send-backs + +class SendBackTests(GateBase): + def setUp(self): + super().setUp() + self.s = self.session() + self.s.write("migrations/001_users.sql", "CREATE TABLE users (id integer);\n") + self.s.contract(full()) # everything but the independent evidence a migration needs + + def test_the_migration_send_back_lists_what_is_missing_in_plain_words(self): + """R-17-5, R-5.3-8: one message, the missing evidence named with the command that supplies it.""" + a, msg = self.s.stop() + self.assertEqual(a, "block") + self.assertIn("this data change is not ready to hand over (send-back 1 of 3)", msg) + self.assertIn("independent evidence", msg) + self.assertIn("sisi delegate judge", msg) + self.assertIn('"independent": true', msg) + self.assertLessEqual(self.lines(msg), 25) + + def test_without_a_contract_the_whole_list_comes_at_once(self): + """R-17-5: every missing piece in one message, within 25 lines.""" + s = self.session("other") + self.put("src/db/schema.sql", "CREATE TABLE a (id integer);\n") + os.remove(os.path.join(self.proj, C.REL)) + s.edit("src/db/schema.sql", "-- more\n") + a, msg = s.stop() + self.assertEqual(a, "block") + for piece in ("a contract", "covers", "invariants", "a requirement list", "a risk note", "the approach", + "independent evidence"): + self.assertIn(piece, msg) + self.assertLessEqual(self.lines(msg), 25) + + def test_three_send_backs_then_released_as_unverified_and_recorded(self): + """R-10.3-4, R-15-13, R-17-7.""" + acts = [self.s.stop()[0] for _ in range(3)] + self.assertEqual(acts, ["block"] * 3) + a, msg = self.s.stop() + self.assertEqual(a, "allow") + self.assertIn("UNVERIFIED", msg) + self.assertIn("independent evidence", msg) + self.assertIn("Report the work as unverified", msg) + row = [r for r in self.results() if r.get("check") == "gate"][-1] + self.assertEqual(row["status"], "unverified") + self.assertIn("independent evidence", row["reason"]) + c = self.unit_state() + self.assertIn("independent evidence", " ".join(c["unverified"]["why"])) + self.s.stop() + rec = U.build_record(c, self.proj, U.decide_status(c, [])[0], time.time(), rows=[]) + self.assertEqual(rec["delivery_status"], "unverified") + self.assertIn("independent", " ".join(rec["released_unverified"]["why"])) + self.assertIn("released unverified by the gate", self.sisi("status").stdout) + + def test_release_then_a_new_change_counts_afresh(self): + for _ in range(4): + self.s.stop() + self.s.edit("migrations/001_users.sql", "-- touch\n") + self.assertEqual(self.s.stop()[0], "block") + + def test_a_waiver_is_a_deviation_and_never_green(self): + """R-10.3-3: waived units close as `deviation`.""" + self.sisi("contract", "waive", "--check", "works", "the reviewer is on leave") + c = self.unit_state() + self.assertEqual(U.decide_status(c, [])[0], "deviation") + + def test_independent_evidence_through_the_ledger_ends_the_send_backs(self): + """R-5.3-9.""" + self.assertEqual(self.s.stop()[0], "block") + workers.append_record({"kind": "attempt", "id": "r1", "ts": round(time.time()), "project": os.path.basename(self.proj), + "type": "review", "difficulty": 2, "worker": "reviewer-model", + "outcome": "accepted", "check": "read"}) + a, msg = self.s.stop() + self.assertEqual(a, "block") + self.assertIn("sisi retro", msg) # now only the offer remains + self.assertNotIn("independent evidence", msg) + + def test_independent_evidence_through_a_named_passing_check(self): + """R-5.3-9.""" + c = self.unit_state() + c["checks"][0].update(independent=True, by="the reference migration tool") + self.s.contract(c) + a, msg = self.s.stop() + self.assertIn("sisi retro", msg) + + def test_independent_without_by_still_sends_back(self): + """R-5.3-9, abuse through the gate.""" + c = self.unit_state() + c["checks"][0].update(independent=True) + self.s.contract(c) + a, msg = self.s.stop() + self.assertEqual(a, "block") + self.assertIn("independent evidence", msg) + + +# ======================================================================== other sessions, subagents + +class AttributionTests(GateBase): + """R-9-1, R-15-9: two sessions, one folder: the gate judges only this session's own edits.""" + + def test_another_sessions_uncommitted_edits_never_send_this_session_back(self): + """Abuse: B breaks the tree and edits a migration; A made no edit of its own.""" + a, b = self.session("sess-a"), self.session("sess-b") + b.write("migrations/002_orders.sql", "CREATE TABLE orders (id integer);\n") + b.contract(contract([check("c", "false")])) + self.assertEqual(a.stop(), ("allow", None)) + self.assertEqual(self.results(), []) # nothing was even run for A + a.edit("README.md", "my own words\n") # A's own change is documentation + self.assertEqual(a.stop(), ("allow", None)) + + def test_this_sessions_own_source_change_is_judged_on_its_own_paths(self): + a, b = self.session("sess-a"), self.session("sess-b") + b.write("migrations/002_orders.sql", "CREATE TABLE orders (id integer);\n") + a.write("app.py", "x = 1\n") + action, msg = a.stop() + self.assertEqual(action, "block") + self.assertIn("isolated change", msg) # not 'data': B's migration is not A's work + self.assertNotIn("migrations", msg) + + def test_shell_edits_count_and_read_only_shell_does_not(self): + a = self.session("sess-a") + a.shell("ls -la; git status --short; cat README.md") + self.put("app.py", "someone else wrote this\n") + self.assertEqual(a.stop(), ("allow", None)) + a.shell("echo hi > out.py") + self.put("out.py", "hi\n") + self.assertEqual(a.stop()[0], "block") # a command that may write: the change is this session's + + def test_a_missing_or_corrupt_transcript_is_strict(self): + """R-15-5: when the gate cannot tell, the change is the session's.""" + self.put("app.py", "x = 1\n") + for name, body in (("missing.jsonl", None), ("corrupt.jsonl", "not json at all\n{{{\n")): + tp = os.path.join(self.tdir, name) + if body: + with open(tp, "w") as f: + f.write(body) + a, msg = gate.decide({"session_id": "s-" + name, "cwd": self.proj, "transcript_path": tp}) + self.assertEqual(a, "block", name) + + def test_only_the_new_tail_of_the_transcript_is_read(self): + s = self.session("sess-tail") + self.assertEqual(s.stop(), ("allow", None)) + size = os.path.getsize(s.tp) + self.assertEqual(store.load_session("sess-tail")["attr_offset"], size) + with open(s.tp, "a") as f: + f.write(json.dumps({"type": "user", "message": {"role": "user", "content": "x" * 5000}}) + "\n") + s.write("app.py", "x = 1\n") + self.assertEqual(s.stop()[0], "block") + self.assertEqual(store.load_session("sess-tail")["attr_gen"], 1) # counted once, not rescanned + + def test_native_subagent_edits_are_the_parents_edits(self): + """R-9-1: the parent answers for what its subagents wrote.""" + a = self.session("sess-a") + subdir = os.path.join(self.tdir, "sess-a", "subagents") + os.makedirs(subdir) + with open(os.path.join(subdir, "agent-x1.jsonl"), "w") as f: + f.write(json.dumps(_human_line()) + "\n") + f.write(json.dumps(_tool_line("Edit", {"file_path": os.path.join(self.proj, "app.py")})) + "\n") + self.put("app.py", "x = 1\n") + self.assertEqual(a.stop()[0], "block") + + def test_shell_classifier(self): + for cmd in ("sed -i 's/a/b/' f.txt", "echo x > out.txt", "git apply p.diff", "python3 scripts/build.py", + "sisi contract init", "python3 tests/run_parallel.py"): + self.assertTrue(attribution.shell_may_write(cmd), cmd) + for cmd in ("ls -la; git status; cat f.txt", "sisi verify", "grep -rn foo sisi/", "git commit -qm x", + "gh run list", "sisi retro --aim speed --moment m"): + self.assertFalse(attribution.shell_may_write(cmd), cmd) + self.assertIsNone(attribution.shell_may_write("echo 'unterminated")) + self.assertIs(gate._shell_may_write, attribution.shell_may_write) # watch.py reaches it here + + def test_snapshot_ignores_commits_and_gitignored_files(self): + from sisi import gitutil + s0 = gitutil.snapshot(self.proj) + self.put("README.md", "changed\n", mode="a") + self.assertIn("README.md", gitutil.snapshot_diff(s0, gitutil.snapshot(self.proj))) + self.commit_all() + s1 = gitutil.snapshot(self.proj) + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "e"], + cwd=self.proj, check=True) + self.assertEqual(gitutil.snapshot_diff(s1, gitutil.snapshot(self.proj)), []) + self.put(".gitignore", "ignored.txt\n") + s2 = gitutil.snapshot(self.proj) + self.put("ignored.txt", "") + self.assertNotIn("ignored.txt", gitutil.snapshot_diff(s2, gitutil.snapshot(self.proj))) + + +class WatchTests(GateBase): + """R-9-1: measured shell attribution: a command's real effect on the tree, not its text.""" + + def setUp(self): + super().setUp() + self.put("noop.py", "print('nothing written')\n") + self.put("gen.py", "open('generated.py', 'w').write('x = 1\\n')\n") + self.commit_all() + + def watch(self, s, command, during=None, after=True): + s.shell(command) + base = {"session_id": s.sid, "cwd": self.proj, "transcript_path": s.tp, + "tool_name": "Bash", "tool_input": {"command": command}} + r = self.sisi_proc("watch", stdin=json.dumps(dict(base, hook_event_name="PreToolUse"))) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + if during: + during() + if after: + r = self.sisi_proc("watch", stdin=json.dumps(dict(base, hook_event_name="PostToolUse"))) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + def run_in_proj(self, *argv): + return subprocess.run(argv, cwd=self.proj, check=True, capture_output=True, text=True) + + def test_an_orchestrator_that_only_runs_commands_never_edits(self): + a = self.session("orch") + self.assertEqual(a.stop(), ("allow", None)) + for cmd, during in (("python3 noop.py", lambda: self.run_in_proj(sys.executable, "noop.py")), + ("git commit -qm x", lambda: self.run_in_proj("git", "commit", "-q", "--allow-empty", "-m", "x")), + ("gh run list", None)): + self.watch(a, cmd, during=during) + self.assertFalse(store.load_session("orch").get("attr_since_pass")) + self.put("app.py", "another session wrote this\n") + self.assertEqual(a.stop(), ("allow", None)) + + def test_a_command_that_writes_a_project_file_is_an_edit_of_that_path(self): + a = self.session("gen") + self.watch(a, "python3 gen.py", during=lambda: self.run_in_proj(sys.executable, "gen.py")) + self.assertIn("generated.py", store.load_session("gen").get("attr_since_pass", [])) + self.put("app.py", "another session wrote this\n") + action, msg = a.stop() + self.assertEqual(action, "block") + self.assertIn("isolated change", msg) + + def test_a_command_that_writes_only_outside_the_project_is_not_an_edit(self): + a = self.session("out") + outside = os.path.join(self.tmp, "outside.txt") + self.put("gen_out.py", "open(%r, 'w').write('elsewhere\\n')\n" % outside) + self.commit_all() + self.watch(a, "python3 gen_out.py", during=lambda: self.run_in_proj(sys.executable, "gen_out.py")) + self.assertTrue(os.path.exists(outside)) + self.assertFalse(store.load_session("out").get("attr_since_pass")) + self.assertEqual(a.stop(), ("allow", None)) + + def test_a_missing_after_record_is_strict(self): + a = self.session("kill") + self.watch(a, "python3 gen.py", after=False) # killed: no PostToolUse ever arrives + self.put("app.py", "x = 1\n") + self.assertEqual(a.stop()[0], "block") + + def commit_notice(self, command): + return self.sisi_proc("watch", "--before", stdin=json.dumps( + {"session_id": "w", "cwd": self.proj, "hook_event_name": "PreToolUse", "tool_name": "Bash", + "tool_input": {"command": command}})).stdout + + def test_commit_time_notice_when_the_checks_have_not_passed_on_this_tree(self): + """R-5.6-1: said at `git commit`, once per commit, never a block.""" + self.write_contract(contract([check("feature", "test -f ok.txt")])) + out = self.commit_notice("git commit -am wip") + d = json.loads(out) + self.assertIn("sisi verify", d["systemMessage"]) + self.assertEqual(d["hookSpecificOutput"]["additionalContext"], d["systemMessage"]) + self.assertIn("sisi verify", json.loads(self.commit_notice("cd x && git merge main"))["systemMessage"]) + self.assertEqual(self.commit_notice("git status"), "") + self.assertEqual(self.sisi("verify").returncode, 0) + self.assertEqual(self.commit_notice("git commit -am wip"), "") # passed on this very tree + self.put("app.py", "x = 1\n") + self.assertIn("sisi verify", self.commit_notice("git commit -am wip")) # the tree moved on + os.remove(os.path.join(self.proj, C.REL)) + self.assertEqual(self.commit_notice("git commit -am wip"), "") # no unit: nothing to say + + +class SubagentTests(GateBase): + """R-17-7: a subagent's last message is its report to its parent.""" + + def payload(self, **extra): + return dict({"session_id": "parent", "cwd": self.proj, "hook_event_name": "SubagentStop", "agent_id": "ag-1"}, **extra) + + def test_a_subagent_stop_is_never_blocked_and_asks_for_nothing(self): + """Abuse: a subagent that edited source, with a failing contract and no retro.""" self.write_contract(contract([check("bad", "false")])) - sub = os.path.join(self.proj, "x", "y") - os.makedirs(sub) - self.assertEqual(self.call(cwd=sub)[0], "block") + tp = os.path.join(self.tmp, "agent-ag-1.jsonl") + with open(tp, "w") as f: + f.write(json.dumps(_tool_line("Write", {"file_path": os.path.join(self.proj, "app.py")})) + "\n") + self.put("app.py", "x = 1\n") + pl = self.payload(agent_transcript_path=tp) + self.assertEqual(gate.decide_subagent(pl), ("allow", None)) + self.assertEqual(gate.decide(pl), ("allow", None)) # even by the main entry + r = self.sisi("gate", "--subagent", stdin=json.dumps(pl)) + self.assertEqual((r.returncode, r.stdout), (0, "")) + r = self.sisi("gate", stdin=json.dumps(pl)) + self.assertEqual((r.returncode, r.stdout), (0, "")) + self.assertEqual(self.results(), []) + def test_what_the_subagent_observed_reaches_the_parents_gate(self): + """A subagent that wrote makes the parent's next stop a stop after an edit.""" + tp = os.path.join(self.tmp, "agent-ag-1.jsonl") + with open(tp, "w") as f: + f.write(json.dumps(_tool_line("Write", {"file_path": os.path.join(self.proj, "app.py")})) + "\n") + parent = self.session("parent") + self.put("app.py", "x = 1\n") + gate.decide_subagent(self.payload(agent_transcript_path=tp)) + row = store.read("subagents")[0] + self.assertEqual((row["session"], row["edited"]), ("parent", True)) + a, msg = parent.stop() + self.assertEqual(a, "block") + self.assertIn("isolated change", msg) + + def test_a_session_marked_as_a_subagent_is_never_sent_back(self): + self.put("app.py", "x = 1\n") + st = store.load_session("child") or {} + st["subagent"] = True + store.save_session("child", st) + self.assertEqual(self.call(sid="child"), ("allow", None)) + + +# ======================================================================== fail open, trust class GateFailOpenTests(GateBase): def test_internal_error_allows_and_logs(self): @@ -125,10 +862,8 @@ class GateFailOpenTests(GateBase): self.assertEqual((r.returncode, r.stdout), (0, "")) def test_garbage_stdin_allows(self): - r = self.sisi("gate", stdin="not json") - self.assertEqual((r.returncode, r.stdout), (0, "")) - r = self.sisi("gate", stdin="") - self.assertEqual((r.returncode, r.stdout), (0, "")) + self.assertEqual(self.sisi("gate", stdin="not json").stdout, "") + self.assertEqual(self.sisi("gate", stdin="").stdout, "") def test_corrupt_session_and_config_files(self): os.makedirs(os.path.join(self.state, "sessions")) @@ -139,210 +874,29 @@ class GateFailOpenTests(GateBase): self.write_contract(contract([check("bad", "false")])) self.assertEqual(self.hook().returncode, 0) - -class GateNoContractTests(GateBase): - def start(self, sid=None): - self.sisi("tick", stdin=json.dumps({"session_id": sid or self.sid, "cwd": self.proj, "source": "startup"})) - - def grow(self, n_lines=0, n_files=1): - for i in range(n_files): - with open(os.path.join(self.proj, "f%d.txt" % i), "w") as f: - f.write("x\n" * (n_lines // max(n_files, 1) + 1)) - - def test_not_a_git_repo_allows(self): - self.grow(500, 5) - self.assertEqual(self.call()[0], "allow") - - def test_small_change_allows(self): - self.git_init(); self.start() - self.grow(10, 1) - self.assertEqual(self.call()[0], "allow") - - def test_many_files_blocks(self): - self.git_init(); self.start() - self.grow(4, 5) - self.assertEqual(self.call()[0], "block") - - def test_preexisting_dirt_does_not_count(self): - self.git_init() - self.grow(500, 6) - self.start() - self.assertEqual(self.call()[0], "allow") - with open(os.path.join(self.proj, "new.txt"), "w") as f: - f.write("y\n" * 100) - self.assertEqual(self.call()[0], "block") - - def test_committed_growth_still_counts(self): - self.git_init(); self.start() - self.grow(100, 1) - subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True) - subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "c"], cwd=self.proj, check=True) - self.assertEqual(self.call()[0], "block") - - def test_waive_allows_and_records(self): - self.git_init(); self.start() - self.grow(100, 1) - r = self.sisi("contract", "waive", "typo fix") - self.assertEqual(r.returncode, 0) - self.assertEqual(self.call()[0], "allow") - w = store.read("waivers") - self.assertEqual(w[0]["reason"], "typo fix") - self.assertIn("project", w[0]) - - def test_waiver_before_session_does_not_count(self): - self.git_init() - self.sisi("contract", "waive", "old") - w = store.read("waivers") - w[0]["ts"] = "2000-01-01T00:00:00Z" - os.remove(os.path.join(self.state, "waivers.jsonl")) - store.append("waivers", w[0]) - self.start(); self.grow(100, 1) - self.assertEqual(self.call()[0], "block") - - def test_contract_created_after_block_is_enforced(self): - self.git_init(); self.start(); self.grow(100, 1) - self.call() - self.write_contract(contract([check("bad", "false")])) - self.assertEqual(self.call()[0], "block") - - -class GatePropertyTests(GateBase): - """The gate cannot be passed with a failing, timed-out or unrun check short of the 3-strike release.""" - - CMDS = [("true", 0, "passed")] * 3 + [("exit 1", 0, "failed"), ("exit 7", 7, "passed"), ("exit 7", 0, "failed")] \ - + [("sleep 3", 0, "timeout")] * 1 - - def gen(self, rng): - checks, invs, expect_ok = [], [], True - floors = {"money": 2, "parsing": 2, "ui": None} - kinds = {} - for i in range(rng.randint(1, 5)): - kind = rng.choice(["general", "money", "parsing", "ui", "state-machine"]) - if rng.random() < 0.2: - rung = rng.choice([5, 6]) - checks.append(human("h%d" % i, rung, kind)) - kinds.setdefault(kind, []).append(rung) - continue - cmd, exit_, status = rng.choice(self.CMDS) - rung = rng.randint(1, 4) - checks.append(check("c%d" % i, cmd, rung=rung, kind=kind, exit=exit_, timeout_s=0.08)) - kinds.setdefault(kind, []).append(rung) - if status != "passed": - expect_ok = False - for i in range(rng.randint(0, 2)): - cmd, exit_, status = rng.choice(self.CMDS) - invs.append(check("i%d" % i, cmd, exit=exit_, timeout_s=0.08)) - if status != "passed": - expect_ok = False - for kind, rungs in kinds.items(): - if kind in ("money", "parsing", "state-machine") and min(rungs) > 2: - expect_ok = False - if not invs and not any("cmd" in c for c in checks): - expect_ok = False # nothing runnable: the contract is invalid and must not pass - return contract(checks, invs), expect_ok - - def test_generated_contracts(self): - seeds = [0, random.randrange(2**32)] + [random.randrange(2**32) for _ in range(ITERS - 1)] - for seed in seeds: - rng = random.Random(seed) - for n in range(4 * ITERS): - c, expect_ok = self.gen(rng) - sid = "p-%d-%d" % (seed, n) - self.write_contract(c) - with self.subTest(seed=seed, n=n, contract=c): - first = self.call(sid=sid)[0] - self.assertEqual(first, "allow" if expect_ok else "block") - if not expect_ok: - acts = [first] + [self.call(sid=sid)[0] for _ in range(2)] - self.assertEqual(acts, ["block"] * 3) # never passes early - a, msg = self.call(sid=sid) - self.assertEqual(a, "allow") - self.assertIn("UNVERIFIED", msg) - - -class GateUnchangedTreeTests(GateBase): - """Fix 1: a turn that changed nothing is not punished, and not re-checked.""" - - def setUp(self): - super().setUp() - self.git_init() - self.counter = os.path.join(self.tmp, "runs") - - def counting(self, cmd="true"): - return check("c", "echo x >> %s; %s" % (self.counter, cmd)) - - def runs(self): - return len(open(self.counter).read().split()) if os.path.exists(self.counter) else 0 - - def tick(self): - self.sisi("tick", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj, "source": "startup"})) - - def edit(self, text="x"): - with open(os.path.join(self.proj, "work.txt"), "a") as f: - f.write(text + "\n") - - def test_unchanged_since_baseline_allows_without_running(self): - self.write_contract(contract([self.counting("false")])) - self.tick() - self.assertEqual(self.call()[0], "allow") - self.assertEqual(self.runs(), 0) - - def test_unchanged_since_last_allow_not_rerun(self): - self.write_contract(contract([self.counting()])) - self.tick() - self.edit() - self.assertEqual(self.call()[0], "allow") - self.assertEqual(self.runs(), 1) - self.assertEqual(self.call()[0], "allow") - self.assertEqual(self.runs(), 1) - self.edit() # a change runs the checks again - self.call() - self.assertEqual(self.runs(), 2) - - def test_unchanged_after_block_keeps_blocking_and_counts_strikes(self): - self.write_contract(contract([self.counting("false")])) - self.tick() - self.edit() - acts = [self.call() for _ in range(3)] - self.assertEqual([a for a, _ in acts], ["block"] * 3) - self.assertEqual(self.runs(), 1) # only the first call ran the checks - self.assertIn("send-back 2 of 3", acts[1][1]) + def test_an_unreadable_contract_is_reported_not_crashed_on(self): + os.makedirs(os.path.join(self.proj, ".sisi")) + with open(os.path.join(self.proj, C.REL), "w") as f: + f.write("{not json") + from sisi import trust + trust.add(self.proj) + self.put("app.py", "x = 1\n") a, msg = self.call() - self.assertEqual(a, "allow") - self.assertIn("UNVERIFIED", msg) - self.assertEqual(self.call()[0], "allow") # released tree, still unchanged: allowed - - def test_fixing_the_work_reruns(self): - marker = os.path.join(self.proj, "fixed") - self.write_contract(contract([check("c", "test -f %s" % marker)])) - self.tick() - self.edit() - self.assertEqual(self.call()[0], "block") - open(marker, "w").close() - self.assertEqual(self.call()[0], "allow") - - def test_fixing_a_gitignored_contract_reruns(self): - with open(os.path.join(self.proj, ".git", "info", "exclude"), "a") as f: - f.write(".sisi/\n") - self.write_contract(contract([check("c", "false")])) - self.tick() - self.edit() - self.assertEqual(self.call()[0], "block") - self.write_contract(contract([check("c", "true")])) - self.assertEqual(self.call()[0], "allow") + self.assertEqual(a, "block") + self.assertIn("cannot read contract", msg) class GateTrustTests(GateBase): - """Fix 2: a contract that arrived with a clone is never executed without approval.""" + """A contract that arrived with a clone is never executed without approval.""" def setUp(self): super().setUp() self.marker = os.path.join(self.tmp, "ran") - self.write_contract(contract([check("evil", "touch %s; false" % self.marker)]), trusted=False) + self.write_contract(contract([check("evil", "touch %s; false" % self.marker)]) | {"risk": {"profile": "isolated"}}, + trusted=False) def test_gate_allows_with_one_notice_and_runs_nothing(self): r = self.hook() - self.assertEqual(r.returncode, 0) msg = json.loads(r.stdout)["systemMessage"] self.assertIn("untrusted", msg) self.assertIn("sisi contract trust", msg) @@ -352,7 +906,6 @@ class GateTrustTests(GateBase): def test_verify_refuses_with_distinct_exit(self): r = self.sisi("verify") self.assertEqual(r.returncode, 3) - self.assertIn("untrusted", r.stdout) self.assertFalse(os.path.exists(self.marker)) def test_trust_then_untrust(self): @@ -364,574 +917,119 @@ class GateTrustTests(GateBase): self.assertEqual(self.sisi("verify").returncode, 3) self.assertFalse(os.path.exists(self.marker)) - def test_init_trusts_the_project(self): - d = os.path.join(self.tmp, "other") - os.makedirs(d) - self.sisi("contract", "init", cwd=d) - self.assertEqual(self.sisi("verify", cwd=d).returncode, 1) # ran (placeholder fails), not refused - def test_trust_follows_realpath(self): - link = os.path.join(self.tmp, "link") - os.symlink(self.proj, link) - self.sisi("contract", "trust", cwd=link) - self.assertEqual(self.sisi("verify").returncode, 1) +# ======================================================================== seeded sequences +class GateSequenceTests(GateBase): + """Seeded random sequences of operations against a real project; the invariants are checked after + every stop. A failing seed is printed with the operations that led to it.""" -class GateEmptyContractTests(GateBase): - """Fix 3: a contract with nothing runnable must not pass.""" + OPS = ["edit_src", "edit_src", "edit_doc", "break", "fix", "stop", "stop", "retro", "pause", "other_edits", "other_breaks"] - def test_only_human_or_empty_is_invalid_everywhere(self): - for name, c in (("human only", contract([human("h5", 5), human("h6", 6)])), ("empty", contract([]))): - with self.subTest(name): - self.write_contract(c) - r = self.sisi("contract", "check") - self.assertEqual(r.returncode, 1) - self.assertIn("runnable", r.stdout) - self.assertEqual(self.sisi("verify").returncode, 1) - self.assertIn("runnable", self.sisi("verify").stdout) - self.assertEqual(self.call(sid=name)[0], "block") + def run_sequence(self, seed, steps=14): + rng = random.Random(seed) + proj_note = "seed %d" % seed + a = self.session("seq-a-%d" % seed) + b = self.session("seq-b-%d" % seed) + a.write("app.py", "x = 0\n") + a.contract(contract([check("feature", "test -f ok.txt")])) + log, last_action, consecutive_blocks, paused, n_retro = [], None, 0, False, 0 + for step in range(steps): + op = rng.choice(self.OPS) + log.append(op) + if op == "edit_src": + a.edit("app.py", "x = %d\n" % step) + paused = False + elif op == "edit_doc": + a.edit("README.md", "line %d\n" % step) + paused = False + elif op == "break" and os.path.exists(os.path.join(self.proj, "ok.txt")): + a.remove("ok.txt") + paused = False + elif op == "fix": + a.write("ok.txt", "ready\n") + paused = False + elif op == "retro": + n_retro += 1 + self.record_finding(n_retro, sid=a.sid) + elif op == "pause" and self.unit_state().get("status") == "open": + self.sisi("unit", "pause", "waiting for the reviewer %d" % step) + paused = True + elif op == "other_edits": + b.edit("other.py", "y = %d\n" % step) + elif op == "other_breaks": + b.write("migrations/%03d.sql" % step, "CREATE TABLE t%d (id integer);\n" % step) + if op != "stop": + continue + action, msg = a.stop() + where = "%s ops=%s" % (proj_note, log) + self.assertLessEqual(self.lines(msg), 25, where) + ok_now = os.path.exists(os.path.join(self.proj, "ok.txt")) + c = self.unit_state() + if action == "block": + consecutive_blocks += 1 + self.assertLessEqual(consecutive_blocks, 3 + 4, where) # bounded: offers are not counted + else: + consecutive_blocks = 0 + if msg and "UNVERIFIED" in msg: + last_action = "released" + # invariant: a unit is archived only after a retro was recorded for it + if c.get("status") == "closed": + self.assertTrue(learning.findings_for_unit(self.proj, "t"), where) + self.assertEqual(self.archives(), ["t.json"], where) + return + # invariant: no silent pass with a failing check and a source change pending, + # unless the unit is paused with no change since, or the gate released it as unverified + if action == "allow" and msg is None and not ok_now and c.get("status") == "open" \ + and not c.get("unverified"): + st = store.load_session(a.sid) + self.assertFalse(st.get("dirty"), where) # then nothing of this session's was pending + # invariant: a stop right after a silent allow, with nothing in between, is silent again + if action == "allow" and msg is None: + self.assertEqual(a.stop(), ("allow", None), where) - def test_waive_is_the_way_out(self): + def test_seeded_sequences(self): + seeds = [0, 1, 2, random.randrange(2 ** 32)] + [random.randrange(2 ** 32) for _ in range(ITERS - 1)] + for seed in seeds: + with self.subTest(seed=seed): + self.setUp_again() + self.run_sequence(seed) + + def setUp_again(self): + """A clean project and state for the next seed.""" + import shutil + shutil.rmtree(self.proj, ignore_errors=True) + shutil.rmtree(self.state, ignore_errors=True) + shutil.rmtree(self.data, ignore_errors=True) + os.makedirs(self.proj) self.git_init() - self.write_contract(contract([human("h")])) - self.assertEqual(self.call()[0], "block") + self.put("README.md", "# project\n") + self.put("ok.txt", "ready\n") + self.commit_all() - def test_skeleton_is_honest_and_does_not_trap_question_turns(self): - self.git_init() - self.sisi("tick", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj, "source": "startup"})) - r = self.sisi("contract", "init") - self.assertIn("SKELETON", r.stdout) - self.assertIn("real command", r.stdout) - self.assertEqual(self.sisi("verify").returncode, 1) - self.assertEqual(self.call()[0], "allow") # nothing changed but the skeleton itself - with open(os.path.join(self.proj, "big.txt"), "w") as f: - f.write("x\n" * 100) - a, msg = self.call() - self.assertEqual(a, "block") # growth rule applies while the contract is still a skeleton - self.assertIn("contract", msg) - - -class GateGrowthTests(GateBase): - """Fix 4: growth without contract keeps blocking like a failing contract.""" - - def setUp(self): - super().setUp() - self.git_init() - self.sisi("tick", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj, "source": "startup"})) - - def grow(self, name, n): - with open(os.path.join(self.proj, name), "a") as f: - f.write("x\n" * n) - - def test_blocks_up_to_three_then_unverified(self): - self.grow("a.txt", 100) - self.assertEqual([self.call()[0] for _ in range(3)], ["block"] * 3) - a, msg = self.call() - self.assertEqual(a, "allow") - self.assertIn("UNVERIFIED", msg) - self.assertEqual(self.results()[-1]["status"], "unverified") - self.grow("a.txt", 1) # still over the threshold, still no contract: strikes start again - self.assertEqual(self.call()[0], "block") - - def test_contract_ends_it(self): - self.grow("a.txt", 100) - self.assertEqual(self.call()[0], "block") - c = contract([check("c", "true")]) - c["design"] = { - "implies": ["A change this size needs its approach recorded so the next agent can " - "see why it went this way and what was ruled out."], - "provided": [{"what": "git already measures the change in this repository", - "evidence": "command:git"}], - "alternatives": [ - {"name": "keep blocking on growth alone", "cost": "no new code to write at all", - "risk": "a contract can be gamed with checks that prove nothing real"}, - {"name": "ask the human to approve large changes", "cost": "one prompt per change", - "risk": "the human becomes the bottleneck for routine sizeable work"}], - "chosen": {"name": "contract with a checked design section", - "why": "It is the option the owner would pick: the approach is recorded " - "and checked mechanically instead of depending on goodwill."}, - "objections": [], - "challenge": {"by": "a subagent on a different model", - "recorded_at": "2026-01-01T00:00:00Z", - "objections": ["The design section could become ceremony filled with filler text."], - "changes": ["Required evidence that named existing things actually exist."]}} - self.write_contract(c) - self.assertEqual(self.call()[0], "allow") - - def test_waiver_covers_tree_at_that_moment_only(self): - self.grow("a.txt", 100) - self.assertEqual(self.call()[0], "block") - self.assertEqual(self.sisi("contract", "waive", "generated file").returncode, 0) - self.assertEqual(self.call()[0], "allow") - self.grow("a.txt", 10) # small growth after the waiver point - self.assertEqual(self.call()[0], "allow") - self.grow("a.txt", 100) # big growth after the waiver point - self.assertEqual(self.call()[0], "block") - self.sisi("contract", "waive", "again") - self.assertEqual(self.call()[0], "allow") - - -def _tool_line(name, inp): - return {"type": "assistant", "timestamp": "2026-01-01T00:00:00.000Z", - "message": {"role": "assistant", "content": [{"type": "tool_use", "name": name, "input": inp}]}} - - -def _human_line(): - return {"type": "user", "timestamp": "2026-01-01T00:00:00.000Z", - "message": {"role": "user", "content": "do the work please"}} - - -class GateAttributionTests(GateBase): - """Two sessions, one folder: the gate judges only this session's own edits (scenarios a-e).""" - - def setUp(self): - super().setUp() - os.environ["SISI_RETRO_REQUIRED"] = "1" - self.addCleanup(lambda: os.environ.__setitem__("SISI_RETRO_REQUIRED", "0")) - self.git_init() - self.marker = os.path.join(self.proj, "ok") - open(self.marker, "w").close() - with open(os.path.join(self.proj, "work.txt"), "w") as f: - f.write("base\n") - self.write_contract(contract([check("c", "test -f ok")])) - subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True) - subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "base"], - cwd=self.proj, check=True) - self.tdir = os.path.join(self.tmp, "transcripts") - os.makedirs(self.tdir) - - def transcript(self, name, lines=()): - p = os.path.join(self.tdir, name) - with open(p, "w") as f: - f.write(json.dumps(_human_line()) + "\n") - for ln in lines: - f.write(json.dumps(ln) + "\n") - return p - - def append_line(self, path, line): - with open(path, "a") as f: - f.write((line if isinstance(line, str) else json.dumps(line)) + "\n") - - def tick(self, sid, tp=None): - p = {"session_id": sid, "cwd": self.proj, "source": "startup"} - if tp: - p["transcript_path"] = tp - return self.sisi("tick", stdin=json.dumps(p)) - - def gate_proc(self, sid, tp=None): - p = {"session_id": sid, "cwd": self.proj, "hook_event_name": "Stop"} - if tp: - p["transcript_path"] = tp - return self.sisi_proc("gate", stdin=json.dumps(p), env={"SISI_RETRO_REQUIRED": "1"}) - - def edit_work(self, name="work.txt", text="more\n"): - with open(os.path.join(self.proj, name), "a") as f: - f.write(text) - - def gate_unverified(self): - return [r for r in self.results() if r.get("check") == "gate" and r.get("status") == "unverified"] - - def test_a_other_session_breaks_check_allows_once_per_tree_state(self): - ta = self.transcript("sess-a.jsonl") - tb = self.transcript("sess-b.jsonl") - self.tick("sess-a", ta); self.tick("sess-b", tb) - # B edits and breaks the check; A edited nothing at all. - self.append_line(tb, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) - self.edit_work() - os.remove(self.marker) - r = self.gate_proc("sess-a", ta) - self.assertEqual(r.returncode, 0, r.stdout) - msg = json.loads(r.stdout)["systemMessage"] - self.assertIn("NOT satisfied", msg) - self.assertIn("UNVERIFIED", msg) - self.assertIn("work.txt", msg) - self.assertIn("sess-b", msg) # identified from B's sibling transcript / session record - self.assertIn("Do not report this work as done", msg) - self.assertNotIn("Fix the work", msg) - self.assertNotIn("sisi retro", msg) # A did no work: never asked for a retro - self.assertEqual(len(self.gate_unverified()), 1) - # Same tree again: allowed silently, no second note, no second unverified row. - r = self.gate_proc("sess-a", ta) - self.assertEqual((r.returncode, r.stdout), (0, "")) - self.assertEqual(len(self.gate_unverified()), 1) - # The tree moves again: one more note. - self.edit_work(text="even more\n") - r = self.gate_proc("sess-a", ta) - self.assertIn("NOT satisfied", json.loads(r.stdout)["systemMessage"]) - self.assertEqual(len(self.gate_unverified()), 2) - - def test_a_through_another_tools_hook(self): - # The same logic arrives through hookio: codex carries a transcript path, pi/opencode do not. - ta = self.transcript("sess-a.jsonl") - tb = self.transcript("sess-b.jsonl") - self.tick("sess-a", ta); self.tick("sess-b", tb) - self.append_line(tb, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) - self.edit_work() - os.remove(self.marker) - p = {"session_id": "sess-a", "transcript_path": ta, "cwd": self.proj, "hook_event_name": "Stop"} - r = self.sisi("gate", "--tool", "codex", stdin=json.dumps(p)) - self.assertEqual(r.returncode, 0, r.stdout) - self.assertIn("NOT satisfied", json.loads(r.stdout)["systemMessage"]) - p2 = {"session_id": "sess-pi", "cwd": self.proj} # no transcript path: pre-attribution behaviour - r = self.sisi("gate", "--tool", "pi", stdin=json.dumps(p2)) - self.assertEqual(r.returncode, 2) # pi blocks by exit code, as before - self.assertIn("Fix the work", r.stdout) - - def test_b_own_edit_then_other_breaks_is_sent_back(self): - ta = self.transcript("sess-a.jsonl") - tb = self.transcript("sess-b.jsonl") - self.tick("sess-a", ta); self.tick("sess-b", tb) - self.append_line(ta, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) - self.edit_work() - self.append_line(tb, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) - self.edit_work(text="b was here\n") - os.remove(self.marker) - r = self.gate_proc("sess-a", ta) - d = json.loads(r.stdout) - self.assertEqual(d["decision"], "block") - self.assertIn("Fix the work", d["reason"]) - - def test_c_native_subagent_edit_asks_parent_for_retro(self): - ta = self.transcript("sess-a.jsonl") - self.tick("sess-a", ta) - subdir = os.path.join(self.tdir, "sess-a", "subagents") - os.makedirs(subdir) - with open(os.path.join(subdir, "agent-x1.jsonl"), "w") as f: - f.write(json.dumps(_human_line()) + "\n") - f.write(json.dumps(_tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) + "\n") - self.edit_work() - r = self.gate_proc("sess-a", ta) - d = json.loads(r.stdout) - self.assertEqual(d["decision"], "block") - self.assertIn("sisi retro", d["reason"]) - - def test_d_shell_edits_count_and_readonly_shell_does_not(self): - cmds = ["sed -i 's/base/changed/' %s" % os.path.join(self.proj, "work.txt"), - "echo hi > %s" % os.path.join(self.proj, "shell-out.txt"), - "git apply changes.diff"] - for i, cmd in enumerate(cmds): - sid = "shell-%d" % i - tp = self.transcript("%s.jsonl" % sid) - self.tick(sid, tp) - self.append_line(tp, _tool_line("Bash", {"command": cmd})) - self.edit_work(text="shell %d\n" % i) # the file change the command made - r = self.gate_proc(sid, tp) - with self.subTest(cmd=cmd): - d = json.loads(r.stdout) - self.assertEqual(d["decision"], "block") - self.assertIn("sisi retro", d["reason"]) # treated as having edited: retro required - sid = "shell-ro" - tp = self.transcript("shell-ro.jsonl") - self.tick(sid, tp) - self.append_line(tp, _tool_line("Bash", {"command": "ls -la; git status --short; cat work.txt"})) - self.edit_work(text="someone else\n") # tree changed, but not by this session - r = self.gate_proc(sid, tp) - self.assertEqual((r.returncode, r.stdout), (0, "")) # passing check, no retro asked - - def test_e_missing_or_corrupt_transcript_is_strict(self): - tb = self.transcript("sess-b.jsonl") - self.tick("sess-b", tb) - self.edit_work() - os.remove(self.marker) - missing = os.path.join(self.tdir, "no-such.jsonl") - r = self.gate_proc("sess-missing", missing) - self.assertEqual(json.loads(r.stdout)["decision"], "block") # not waved through as another's work - bad = os.path.join(self.tdir, "corrupt.jsonl") - with open(bad, "w") as f: - f.write("not json at all\n{{{\n") - r = self.gate_proc("sess-corrupt", bad) - self.assertEqual(json.loads(r.stdout)["decision"], "block") - # and with the check passing again, a corrupt transcript still counts as edited for the retro - open(self.marker, "w").close() - r = self.gate_proc("sess-corrupt2", bad) - d = json.loads(r.stdout) - self.assertEqual(d["decision"], "block") - self.assertIn("sisi retro", d["reason"]) - - def test_shell_classifier(self): - self.assertTrue(gate._shell_may_write("sed -i 's/a/b/' f.txt")) - self.assertTrue(gate._shell_may_write("echo x > out.txt")) - self.assertTrue(gate._shell_may_write("git apply p.diff")) - self.assertTrue(gate._shell_may_write("python3 scripts/build.py")) - self.assertIsNone(gate._shell_may_write("echo 'unterminated")) - self.assertFalse(gate._shell_may_write("ls -la; git status; cat f.txt")) - self.assertFalse(gate._shell_may_write("sisi verify")) - self.assertFalse(gate._shell_may_write("grep -rn foo sisi/")) - - def test_offset_reads_only_the_new_tail(self): - tp = self.transcript("sess-tail.jsonl") - self.tick("sess-tail", tp) - a, _ = gate.decide({"session_id": "sess-tail", "cwd": self.proj, "transcript_path": tp}) - self.assertEqual(a, "allow") - size = os.path.getsize(tp) - self.assertEqual(store.load_session("sess-tail")["attr_offset"], size) - self.append_line(tp, {"type": "user", "message": {"role": "user", "content": "x" * 5000}}) - self.append_line(tp, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) - self.edit_work() - a, msg = gate.decide({"session_id": "sess-tail", "cwd": self.proj, "transcript_path": tp}) - self.assertEqual(a, "block") # the edit in the new tail was seen, retro is required - self.assertIn("sisi retro", msg) - self.assertEqual(store.load_session("sess-tail")["attr_gen"], 1) # counted once, not rescanned - - -class GateWatchTests(GateBase): - """Measured shell attribution: before/after tree snapshots, not command-text guesses.""" - - def setUp(self): - super().setUp() - os.environ["SISI_RETRO_REQUIRED"] = "1" - self.addCleanup(lambda: os.environ.__setitem__("SISI_RETRO_REQUIRED", "0")) - self.git_init() - self.marker = os.path.join(self.proj, "ok") - open(self.marker, "w").close() - with open(os.path.join(self.proj, "work.txt"), "w") as f: - f.write("base\n") - with open(os.path.join(self.proj, "noop.py"), "w") as f: - f.write("print('nothing written')\n") - with open(os.path.join(self.proj, "gen.py"), "w") as f: - f.write("open('generated.txt', 'w').write('made\\n')\n") - self.write_contract(contract([check("c", "test -f ok")])) - subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True) - subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "base"], - cwd=self.proj, check=True) - self.tdir = os.path.join(self.tmp, "transcripts") - os.makedirs(self.tdir) - - def transcript(self, name): - p = os.path.join(self.tdir, name) - with open(p, "w") as f: - f.write(json.dumps(_human_line()) + "\n") - return p - - def append_line(self, path, line): - with open(path, "a") as f: - f.write(json.dumps(line) + "\n") - - def tick(self, sid, tp): - return self.sisi("tick", stdin=json.dumps({"session_id": sid, "cwd": self.proj, - "source": "startup", "transcript_path": tp})) - - def gate_proc(self, sid, tp=None): - p = {"session_id": sid, "cwd": self.proj, "hook_event_name": "Stop"} - if tp: - p["transcript_path"] = tp - return self.sisi_proc("gate", stdin=json.dumps(p), env={"SISI_RETRO_REQUIRED": "1"}) - - def watch(self, sid, tp, command, during=None, after=True): - """Simulate the Pre/PostToolUse pair around the command's real effect. Returns nothing.""" - self.append_line(tp, _tool_line("Bash", {"command": command})) - base = {"session_id": sid, "cwd": self.proj, "transcript_path": tp, - "tool_name": "Bash", "tool_input": {"command": command}} - r = self.sisi_proc("watch", stdin=json.dumps(dict(base, hook_event_name="PreToolUse")), - env={"SISI_RETRO_REQUIRED": "1"}) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - if during is not None: - during() - if after: - r = self.sisi_proc("watch", stdin=json.dumps(dict(base, hook_event_name="PostToolUse")), - env={"SISI_RETRO_REQUIRED": "1"}) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - - def run_in_proj(self, *argv): - return subprocess.run(argv, cwd=self.proj, check=True, capture_output=True, text=True) - - def test_orchestrator_that_only_runs_commands_is_never_the_editor(self): - ta, tb = self.transcript("orch-a.jsonl"), self.transcript("sess-b.jsonl") - self.tick("orch-a", ta); self.tick("sess-b", tb) - self.assertEqual(self.gate_proc("orch-a", ta).stdout, "") # passing stop: records the pass state - cmds = [("python3 noop.py", lambda: self.run_in_proj(sys.executable, "noop.py")), - ("git commit -qm x", lambda: self.run_in_proj("git", "commit", "-q", "--allow-empty", "-m", "x")), - ("gh run list", None), - ("sisi retro --aim speed --moment m", None), - ("python3 ~/.claude/orchestrator/orch.py log --type impl", None)] - for cmd, during in cmds: - self.watch("orch-a", ta, cmd, during=during) - self.assertFalse(store.load_session("orch-a").get("attr_since_pass")) - # Another session edits and breaks the check. - self.append_line(tb, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) - with open(os.path.join(self.proj, "work.txt"), "a") as f: - f.write("worker edit\n") - os.remove(self.marker) - r = self.gate_proc("orch-a", ta) - msg = json.loads(r.stdout)["systemMessage"] - self.assertIn("NOT satisfied", msg) - self.assertIn("work.txt", msg) - self.assertNotIn("Fix the work", msg) - self.assertNotIn("sisi retro", msg) - self.assertEqual(len([x for x in self.results() if x.get("status") == "unverified"]), 1) - self.assertEqual(self.gate_proc("orch-a", ta).stdout, "") # second stop: silent - - def test_command_that_writes_a_project_file_is_an_edit_of_that_path(self): - tp = self.transcript("gen-a.jsonl") - self.tick("gen-a", tp) - self.assertEqual(self.gate_proc("gen-a", tp).stdout, "") - self.watch("gen-a", tp, "python3 gen.py", during=lambda: self.run_in_proj(sys.executable, "gen.py")) - self.assertIn("generated.txt", store.load_session("gen-a").get("attr_since_pass", [])) - tb = self.transcript("sess-b.jsonl") - self.tick("sess-b", tb) - self.append_line(tb, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) - with open(os.path.join(self.proj, "work.txt"), "a") as f: - f.write("worker edit\n") - os.remove(self.marker) - d = json.loads(self.gate_proc("gen-a", tp).stdout) - self.assertEqual(d["decision"], "block") # a path it is attributed with changed since the pass - self.assertIn("Fix the work", d["reason"]) - open(self.marker, "w").close() # checks pass again, and this session edited: retro required - d = json.loads(self.gate_proc("gen-a", tp).stdout) - self.assertEqual(d["decision"], "block") - self.assertIn("sisi retro", d["reason"]) - - def test_command_that_writes_only_outside_the_project_is_not_an_edit(self): - tp = self.transcript("out-a.jsonl") - self.tick("out-a", tp) - self.assertEqual(self.gate_proc("out-a", tp).stdout, "") - outside = os.path.join(self.tmp, "outside.txt") - gen = os.path.join(self.proj, "gen_out.py") - with open(gen, "w") as f: - f.write("open(%r, 'w').write('elsewhere\\n')\n" % outside) - self.watch("out-a", tp, "python3 gen_out.py", during=lambda: self.run_in_proj(sys.executable, "gen_out.py")) - self.assertTrue(os.path.exists(outside)) - self.assertFalse(store.load_session("out-a").get("attr_since_pass")) - self.assertEqual(self.gate_proc("out-a", tp).stdout, "") # no retro asked - - def test_other_agents_write_inside_the_window_is_attributed_to_this_session(self): - tp = self.transcript("win-a.jsonl") - self.tick("win-a", tp) - self.assertEqual(self.gate_proc("win-a", tp).stdout, "") - - def during(): - with open(os.path.join(self.proj, "work.txt"), "a") as f: - f.write("written by another agent mid-command\n") - os.remove(self.marker) - - self.watch("win-a", tp, "python3 noop.py", during=during) - self.assertIn("work.txt", store.load_session("win-a").get("attr_since_pass", [])) - d = json.loads(self.gate_proc("win-a", tp).stdout) - self.assertEqual(d["decision"], "block") # documented strict error: the window is this session's - self.assertIn("Fix the work", d["reason"]) - - def test_missing_after_record_is_strict(self): - tp = self.transcript("kill-a.jsonl") - self.tick("kill-a", tp) - self.assertEqual(self.gate_proc("kill-a", tp).stdout, "") - self.watch("kill-a", tp, "python3 gen.py", after=False) # killed: no PostToolUse ever arrives - with open(os.path.join(self.proj, "work.txt"), "a") as f: - f.write("worker edit\n") - os.remove(self.marker) - d = json.loads(self.gate_proc("kill-a", tp).stdout) - self.assertEqual(d["decision"], "block") - self.assertIn("Fix the work", d["reason"]) - tp2 = self.transcript("kill-b.jsonl") - self.tick("kill-b", tp2) - open(self.marker, "w").close() # tree passes again - self.watch("kill-b", tp2, "python3 gen.py", after=False) - d = json.loads(self.gate_proc("kill-b", tp2).stdout) - self.assertEqual(d["decision"], "block") - self.assertIn("sisi retro", d["reason"]) # strict for the retro too - - def test_snapshot_and_classifier(self): - from sisi import gitutil - s0 = gitutil.snapshot(self.proj) - with open(os.path.join(self.proj, "work.txt"), "a") as f: - f.write("changed\n") - self.assertIn("work.txt", gitutil.snapshot_diff(s0, gitutil.snapshot(self.proj))) - subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True) - s1 = gitutil.snapshot(self.proj) - subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "c"], - cwd=self.proj, check=True) - self.assertEqual(gitutil.snapshot_diff(s1, gitutil.snapshot(self.proj)), []) # commit: .git only - with open(os.path.join(self.proj, ".gitignore"), "w") as f: - f.write("ignored.txt\n") - s2 = gitutil.snapshot(self.proj) - open(os.path.join(self.proj, "ignored.txt"), "w").close() - self.assertNotIn("ignored.txt", gitutil.snapshot_diff(s2, gitutil.snapshot(self.proj))) - self.assertFalse(gate._shell_may_write("git commit -qm x")) - self.assertFalse(gate._shell_may_write("gh run list")) - self.assertFalse(gate._shell_may_write("sisi retro --aim speed --moment m")) - self.assertFalse(gate._shell_may_write("sisi verify")) - self.assertTrue(gate._shell_may_write("sisi contract init")) - self.assertTrue(gate._shell_may_write("python3 ~/.claude/orchestrator/orch.py log --type impl")) - self.assertTrue(gate._shell_may_write("python3 tests/run_parallel.py")) - - -class GateSingleSessionEquivalenceTests(GateBase): - """(f) One session only: with a transcript that records its own edits, every decision matches - the pre-attribution gate (the same decide() called with no transcript path) on a twin project.""" - - def twin(self, name): - d = os.path.join(self.tmp, name) - os.makedirs(d) - self.git_init(d) - with open(os.path.join(d, "work.txt"), "w") as f: - f.write("base\n") - open(os.path.join(d, "ok"), "w").close() - self.write_contract(contract([check("c", "test -f ok")]), d=d) - return d - - def retro_for(self, proj, sid, n): - r = self.sisi("retro", - "--finding", "`cargo test` twin run %d took 4 minutes with no fuzz verifier in project" % n, - "--cause", "the recipe never named a fuzz verifier for parsers", - "--impact", "time", "--disposition", "promote", - "--change", "Add the fuzz verifier to the parser-or-codec recipe Checks, twin variant %d" % n, - "--mechanism", "verification", "--expect", "parser work gets a fuzz check", - "--validate", "run the recipe checks on a parser change", - cwd=proj, env={"SISI_SESSION_ID": sid}) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - - def test_seeded_sequences_match_the_reference(self): - os.environ["SISI_RETRO_REQUIRED"] = "1" - self.addCleanup(lambda: os.environ.__setitem__("SISI_RETRO_REQUIRED", "0")) - ref_proj, new_proj = self.twin("refproj"), self.twin("newproj") - tp = os.path.join(self.tmp, "twin-new.jsonl") - with open(tp, "w") as f: - f.write(json.dumps(_human_line()) + "\n") - self.sisi("tick", stdin=json.dumps({"session_id": "twin-ref", "cwd": ref_proj, "source": "startup"})) - self.sisi("tick", stdin=json.dumps({"session_id": "twin-new", "cwd": new_proj, "source": "startup", - "transcript_path": tp})) - n_retro = [0] - - def both(fn): - fn(ref_proj) - fn(new_proj) - - def append_both(text): - for p in (ref_proj, new_proj): - with open(os.path.join(p, "work.txt"), "a") as f: - f.write(text) - - def stop_pair(step): - a_ref, m_ref = gate.decide({"session_id": "twin-ref", "cwd": ref_proj}) - a_new, m_new = gate.decide({"session_id": "twin-new", "cwd": new_proj, "transcript_path": tp}) - self.assertEqual(a_new, a_ref, "step %r" % (step,)) - self.assertEqual(("sisi retro" in (m_new or "")), ("sisi retro" in (m_ref or "")), "step %r" % (step,)) - self.assertEqual(("Fix the work" in (m_new or "")), ("Fix the work" in (m_ref or "")), "step %r" % (step,)) - - for seed in (0, 1, 2): - rng = random.Random(seed) - for step in range(12): - op = rng.choice(["edit", "edit", "break", "fix", "verify", "retro"]) - if op == "edit": - append_both("s%d-%d\n" % (seed, step)) - with open(tp, "a") as f: - f.write(json.dumps(_tool_line("Edit", {"file_path": os.path.join(new_proj, "work.txt")})) + "\n") - elif op == "break": - both(lambda p: os.path.exists(os.path.join(p, "ok")) and os.remove(os.path.join(p, "ok"))) - append_both("break\n") - with open(tp, "a") as f: - f.write(json.dumps(_tool_line("Edit", {"file_path": os.path.join(new_proj, "work.txt")})) + "\n") - elif op == "fix": - both(lambda p: open(os.path.join(p, "ok"), "w").close()) - with open(tp, "a") as f: - f.write(json.dumps(_tool_line("Write", {"file_path": os.path.join(new_proj, "ok")})) + "\n") - elif op == "verify": - self.sisi("verify", cwd=ref_proj) - self.sisi("verify", cwd=new_proj) - elif op == "retro": - n_retro[0] += 1 - self.retro_for(ref_proj, "twin-ref", n_retro[0]) - self.retro_for(new_proj, "twin-new", n_retro[0]) - stop_pair((seed, step, op)) + def test_another_sessions_work_never_touches_this_sessions_stops(self): + """R-15-9: for any sequence of B's edits and breakages, A (which does nothing) is never sent back.""" + for seed in range(3 * ITERS): + with self.subTest(seed=seed): + self.setUp_again() + rng = random.Random(seed) + a, b = self.session("a%d" % seed), self.session("b%d" % seed) + self.assertEqual(a.stop(), ("allow", None)) + for step in range(8): + op = rng.choice(["src", "doc", "migration", "break", "contract", "secret"]) + if op == "src": + b.edit("b%d.py" % step, "y = 1\n") + elif op == "doc": + b.edit("README.md", "b %d\n" % step) + elif op == "migration": + b.write("migrations/%03d.sql" % step, "CREATE TABLE x (id integer);\n") + elif op == "break" and os.path.exists(os.path.join(self.proj, "ok.txt")): + b.remove("ok.txt") + elif op == "contract" and not os.path.exists(os.path.join(self.proj, C.REL)): + b.contract(contract([check("c", "false")])) + elif op == "secret": + b.write("config/secrets.env", "PASSWORD=hunter2\n") + self.assertEqual(a.stop(), ("allow", None), "seed %d step %d %s" % (seed, step, op)) if __name__ == "__main__": diff --git a/tests/test_unit.py b/tests/test_unit.py index b4199dd..26d7f1d 100644 --- a/tests/test_unit.py +++ b/tests/test_unit.py @@ -345,7 +345,7 @@ class PauseTests(UnitCase): self.assertEqual(c["pauses"][0]["what"], "the owner's decision") stop = json.dumps({"session_id": "p1", "cwd": self.proj, "hook_event_name": "Stop", "stop_hook_active": False}) self.sisi("tick", stdin=json.dumps({"session_id": "p1", "cwd": self.proj, "hook_event_name": "SessionStart"})) - open(os.path.join(self.proj, "new.txt"), "w").write("x") # a change after the pause + open(os.path.join(self.proj, "new.py"), "w").write("x = 1\n") # a change after the pause self.assertIn("block", self.sisi("gate", stdin=stop).stdout) self.assertEqual(C.load(self.contract_path)["status"], "open") # the wait ended self.assertTrue(C.load(self.contract_path)["pauses"][0]["until"]) diff --git a/tests/test_verifiers.py b/tests/test_verifiers.py index d31525a..c27bc7f 100644 --- a/tests/test_verifiers.py +++ b/tests/test_verifiers.py @@ -161,17 +161,6 @@ class ShowAndChooseTests(LibCase): out = self.sisi("verifiers", "for", "widget").stdout self.assertEqual(len([l for l in out.splitlines() if l[:1].isdigit()]), 8) - def test_for_kind_floor_marking(self): - self.seed() - out = self.sisi("verifiers", "for", "parsing round trip", "--kind", "parsing").stdout - self.assertIn("Floor: parsing claims need rung 2", out) - self.assertIn("[floor ok]", out) - self.put("prove/weakparse.md", vfile("weakparse", rung=4, kinds="parsing", answers="Does parsing look fine?")) - out = self.sisi("verifiers", "for", "parsing looks fine", "--kind", "parsing").stdout - self.assertIn("[below floor]", out) - out = self.sisi("verifiers", "for", "page looks", "--kind", "ui").stdout - self.assertNotIn("Floor:", out) - def test_for_lang_and_kind_filters(self): self.seed() out = self.sisi("verifiers", "for", "random inputs parsing", "--lang", "rust").stdout diff --git a/tests/test_verify.py b/tests/test_verify.py index df438ca..1b84ffc 100644 --- a/tests/test_verify.py +++ b/tests/test_verify.py @@ -45,13 +45,6 @@ class VerifyTests(SisiCase): r = self.run_verify(contract([check("pwd", "pwd", stdout_contains=self.proj)])) self.assertEqual(r.returncode, 0, r.stdout) - def test_floor_fails(self): - r = self.run_verify(contract([check("m", "true", rung=3, kind="money")])) - self.assertEqual(r.returncode, 1) - self.assertIn("floor", r.stdout) - r = self.run_verify(contract([check("m", "true", rung=2, kind="money")])) - self.assertEqual(r.returncode, 0) - def test_no_contract_exit_2(self): self.assertEqual(self.sisi("verify").returncode, 2)