diff --git a/CHANGELOG.md b/CHANGELOG.md index 16e9934..ef82f1a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,18 @@ All notable changes to this project are recorded here. The format follows ## Unreleased +### Added + +- The durable work-unit record: `sisi unit close|pause|show|list`, an archive per unit in the + project, one summary line per unit in the user store, five delivery statuses, the policy + version, start and closing commits. See docs/records.md. +- Verification with five statuses, selection by change (`when_changed`), reuse of results on + identical inputs, `covers`, `mandatory` and `independent` on checks, the `approach` object, and + refusal of checks that cannot fail. `sisi contract waive` records a deviation. +- 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. + ### Removed - `sisi note` and `sisi propose`: use `sisi retro` or `sisi learn`. Existing notes and proposal @@ -17,6 +29,8 @@ All notable changes to this project are recorded here. The format follows - `sisi build-canon` and `sisi canon cost` as public commands; the functions remain for install and other code, and `sisi doctor` now shows the always-loaded size. - `sisi migrate` as a command; `sisi update` performs the migration. +- `sisi time`, `sisi scoreboard` and the old `sisi status` counts; the `awaiting-human` and + `timeout` result statuses (a timeout is `not-run (timed out)`). ### Changed diff --git a/canon/core.md b/canon/core.md index 8e1d0ac..1d0070f 100644 --- a/canon/core.md +++ b/canon/core.md @@ -142,4 +142,4 @@ check first and slow checks in the background while you carry on, never repeatin inputs have not changed, and finding out why a slow step is slow instead of waiting on it. Why: correct work that takes days when hours would do fails the human almost as badly as wrong -work. `sisi time` shows where the time went. +work. `sisi status` shows where the time went. diff --git a/docs/README.md b/docs/README.md index de8162e..656ad88 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,6 +6,7 @@ | [../SPEC.md](../SPEC.md) | read the standard sisi is built and judged against | | [target.md](target.md) | see how sisi meets that standard | | [design.md](design.md) | understand why sisi works the way it does, and what is built versus only designed | +| [records.md](records.md) | know what a closed work unit records, the five verification statuses, telemetry classes and `sisi status` | | [learning.md](learning.md) | how a recorded lesson takes effect, is measured, strengthened, consolidated or withdrawn | | [workers.md](workers.md) | how the agent tools and models on the machine are found, chosen between by measured results, and run | | [personal-data.md](personal-data.md) | know where sisi keeps what it learns, how the overlay works, and what an update touches | diff --git a/docs/records.md b/docs/records.md new file mode 100644 index 0000000..3a38183 --- /dev/null +++ b/docs/records.md @@ -0,0 +1,70 @@ +# Records: the work unit, verification, telemetry and the scorecard + +The open work unit is `.sisi/contract.json`. `sisi contract init` starts one and refuses while +another is open. `sisi unit close` archives it; the commands are `sisi unit close [--abandon +""]`, `sisi unit pause ""`, `sisi unit show [ID]` and +`sisi unit list`. `sisi help` lists them with the rest. + +## The record + +Closing writes `.sisi/units/.json` in the project and one summary line (id, project, +closed time, risk, delivery status, scorecard) to `units.jsonl` in the user store. The archive is +created whole or not at all and is never replaced: closing twice, starting a new unit, abandoning +and a crash between the archive and the reset each leave every earlier record as it was, and a +second `sisi unit close` after a crash completes the close from the archive. An id already taken +by another unit moves the new one to a fresh id. + +It holds the fourteen items of SPEC 10.2, the start and closing commits when the project is a +git repository, the risk floor (from the paths changed since the unit started, by the risk +table) beside the declared profile, the delegations the ledger has for the project in the +unit's window, the retro findings and learnings of the unit, and a hash of the policies in +force (rulebook, risk tables, enforced checks, gate and verify settings; it never contains a +path). Closing offers the unit to the evaluation harness as a benchmark case; a failure there +never stops the close. + +Delivery status is one of `delivered`, `delivered-with-deferred`, `deviation` (a check was +waived), `unverified` (the gate released the unit after its send-backs) and `abandoned`. A unit +with a failing check cannot close as delivered. A mandatory check that never ran to a pass, or +whose `when_changed` glob matches no file, makes the unit `delivered-with-deferred`, never +plainly `delivered`. `sisi contract waive` records a deviation; it turns nothing green. + +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. + +## Verification + +Five statuses: `passed`, `failed`, `skipped`, `not-applicable`, `not-run`; the last three always +carry a reason. A timeout is `not-run (timed out)`; a check a person must judge is `not-run (needs +human)`. A failed check blocks, and so does a mandatory not-run other than a recorded deferral or +needing a human. + +- A check with `when_changed` runs only when a changed path matches (`skipped (not affected by + this change)`); one whose globs match no file is `not-applicable`. `--all` runs everything. +- A check whose command and inputs (the watched files, or the whole tree) are identical to its + last pass is `skipped (reused: passed at ...)`. A failure is never reused. Files git ignores are + not seen by the whole-tree fingerprint. +- `sisi contract check` refuses a command that cannot fail (`true`, `:`, `exit 0`, `echo`, + `test 1 = 1`, any of them in `sh -c`, joined with `;` or `&&`, or after `||`). This is a floor, + not a proof: no analysis finds every constant. +- Every result stores its duration and whether the check has been seen failing in the unit. + `sisi verify` prints the slowest checks and the time saved by selection and reuse. + +## Telemetry and the scorecard + +Every value is `{"value", "class"}` with class `measured`, `inferred`, `estimated` or +`unavailable`; an unavailable value has no value, and is never counted as zero. Tokens by +category and model, question dialogs, human messages and inferred corrections come from the +host's transcript when it has one with usage; cost is estimated only when every model used has a +recorded price. Changed files and lines come from git; delegations from the ledger. + +The scorecard has the eight dimensions of SPEC 13.1. `sisi status` prints recent units with +their scorecards and then trends by project, risk profile, model and policy version, with the +median and 95th percentile and "too few" under five units. It prints no single score. +`sisi status --learning` prints the learning report. + +## Scratch + +Session-state files older than `scratch.session_max_age_days` (30) are removed on the first +session start and every `scratch.prune_every`th (20) after it, with no scheduler. A run is +bounded by `prune_max_delete` files and `prune_budget_s` seconds and the next start continues. A +session is kept while it is the current one or its transcript has been written to within the age. diff --git a/docs/spec/conformance.json b/docs/spec/conformance.json index ca8ad95..a1d02a3 100644 --- a/docs/spec/conformance.json +++ b/docs/spec/conformance.json @@ -694,17 +694,17 @@ }, { "id": "R-5.4-4", - "status": "missing", - "how": "nothing", - "evidence": "", - "gap": "No check records which changed behaviour or failure mode it addresses." + "status": "partial", + "how": "A check may carry `covers`, the failure it would catch; the unit record keeps it", + "evidence": "sisi/contract.py", + "gap": "Optional until a risk profile requires it; nothing yet checks that the stated failure is the one the change could cause." }, { "id": "R-5.4-5", - "status": "missing", - "how": "nothing", - "evidence": "", - "gap": "No field, record, check or command in sisi implements this; at most canon prose gestures at it." + "status": "partial", + "how": "A check's `when_changed` globs name the paths that make it relevant; selection uses them", + "evidence": "sisi/verify.py", + "gap": "Path patterns only: no dependency graph or call analysis." }, { "id": "R-5.4-6", @@ -715,10 +715,10 @@ }, { "id": "R-5.4-7", - "status": "missing", - "how": "nothing", - "evidence": "", - "gap": "No field, record, check or command in sisi implements this; at most canon prose gestures at it." + "status": "partial", + "how": "Every result stores its duration; verify prints the slowest checks and the time saved by selection and reuse", + "evidence": "sisi/verify.py", + "gap": "No estimate before a check has run once; resource cost other than time is not recorded." }, { "id": "R-5.4-8", @@ -729,17 +729,16 @@ }, { "id": "R-5.4-9", - "status": "missing", - "how": "nothing", - "evidence": "", - "gap": "No field, record, check or command in sisi implements this; at most canon prose gestures at it." + "status": "met", + "how": "A check whose command and inputs (the watched files, or the whole tree) match its last pass is skipped as reused, with the time of that pass", + "evidence": "sisi/verify.py" }, { "id": "R-5.4-10", - "status": "missing", - "how": "nothing", - "evidence": "", - "gap": "No field, record, check or command in sisi implements this; at most canon prose gestures at it." + "status": "partial", + "how": "A check kept back by selection records why (not affected by this change); `--all` runs everything", + "evidence": "sisi/verify.py", + "gap": "A mandatory check with no stated reason is still allowed to block; nothing asks for a justification when the contract is written." }, { "id": "R-5.5-1", @@ -750,24 +749,22 @@ }, { "id": "R-5.6-1", - "status": "partial", - "how": "verify records each run result and the gate reports failures and UNVERIFIED releases", - "evidence": "sisi/verify.py:108", - "gap": "Statuses omit skipped, not applicable and not run, budget exhaustion is reported as timeout, and awaiting-human counts as success." + "status": "met", + "how": "Every verification result of the unit is stored in its archived record, with the standing result per check", + "evidence": "sisi/unit.py" }, { "id": "R-5.6-2", - "status": "partial", - "how": "verify records each run result and the gate reports failures and UNVERIFIED releases", - "evidence": "sisi/verify.py:108", - "gap": "Statuses omit skipped, not applicable and not run, budget exhaustion is reported as timeout, and awaiting-human counts as success." + "status": "met", + "how": "Five statuses (passed, failed, skipped, not-applicable, not-run), the last three with a reason; timeouts and human checks are not-run", + "evidence": "sisi/verify.py" }, { "id": "R-5.6-3", "status": "partial", - "how": "verify records each run result and the gate reports failures and UNVERIFIED releases", - "evidence": "sisi/verify.py:108", - "gap": "Statuses omit skipped, not applicable and not run, budget exhaustion is reported as timeout, and awaiting-human counts as success." + "how": "Nothing that did not run is reported as passed: skips and reuse are their own status, vacuous checks are refused, a mandatory check that never ran cannot close the unit as delivered", + "evidence": "sisi/verify.py", + "gap": "A partial proof's scope is not checked against the property claimed." }, { "id": "R-6.1-1", @@ -779,30 +776,29 @@ { "id": "R-6.1-2", "status": "partial", - "how": "delivery.py records request-to-allowed-stop seconds, send-backs and check seconds, summarised as median and p90", - "evidence": "sisi/delivery.py", - "gap": "Time to first useful result is never recorded, and the completion time is time to a gate-accepted stop rather than to user acceptance." + "how": "The unit record holds time to first useful result and time to validated completion, each with its class", + "evidence": "sisi/unit.py", + "gap": "First useful result is the first green run (inferred) or the first allowed stop; it is not a judgement that the increment is useful." }, { "id": "R-6.1-3", - "status": "missing", - "how": "nothing", - "evidence": "", - "gap": "Time to first useful result is never timestamped; only request-to-allowed-stop is recorded." + "status": "partial", + "how": "First allowed stop after the request, or the first green verification, whichever the hooks recorded", + "evidence": "sisi/unit.py", + "gap": "A proxy for a working increment." }, { "id": "R-6.1-4", - "status": "partial", - "how": "delivery.py records request-to-allowed-stop seconds, send-backs and check seconds, summarised as median and p90", - "evidence": "sisi/delivery.py", - "gap": "Time to first useful result is never recorded, and the completion time is time to a gate-accepted stop rather than to user acceptance." + "status": "met", + "how": "Close time minus start time, and a unit closes as delivered only when required verification has passed", + "evidence": "sisi/unit.py" }, { "id": "R-6.1-5", "status": "partial", - "how": "delivery.py records request-to-allowed-stop seconds, send-backs and check seconds, summarised as median and p90", - "evidence": "sisi/delivery.py", - "gap": "Time to first useful result is never recorded, and the completion time is time to a gate-accepted stop rather than to user acceptance." + "how": "Time in checks, in recorded waits (pauses) and in delegations are measured per unit", + "evidence": "sisi/unit.py", + "gap": "Queue and integration time are not measured." }, { "id": "R-6.2-1", @@ -869,17 +865,17 @@ }, { "id": "R-6.4-2", - "status": "missing", - "how": "nothing", - "evidence": "", - "gap": "Nothing reads the diff, dependency graph or history to select relevant checks." + "status": "partial", + "how": "Checks declare the paths they depend on; the changed paths since the unit started select which run", + "evidence": "sisi/verify.py", + "gap": "Declared path patterns, not a dependency graph." }, { "id": "R-6.4-3", - "status": "missing", - "how": "nothing", - "evidence": "", - "gap": "No field, record, check or command in sisi implements this; at most canon prose gestures at it." + "status": "partial", + "how": "A skip records its reason; checks are mandatory by default and may be marked optional", + "evidence": "sisi/verify.py", + "gap": "The reason an expensive suite is expensive is not recorded." }, { "id": "R-6.4-4", @@ -1198,143 +1194,132 @@ }, { "id": "R-10.2-2", - "status": "partial", - "how": "The contract holds an id, goal, checks, invariants, assumptions and questions, and verify appends results by contract id", - "evidence": "sisi/contract.py:57", - "gap": "Most required fields are missing and the pieces live in four unlinked stores: no parent request, risk profile, agents, budgets, times, changed artifacts, deferred checks, delivery status or scorecard in one durable record." + "status": "met", + "how": "The record holds the unit id and its parent request or workstream", + "evidence": "sisi/unit.py" }, { "id": "R-10.2-3", - "status": "partial", - "how": "The contract holds an id, goal, checks, invariants, assumptions and questions, and verify appends results by contract id", - "evidence": "sisi/contract.py:57", - "gap": "Most required fields are missing and the pieces live in four unlinked stores: no parent request, risk profile, agents, budgets, times, changed artifacts, deferred checks, delivery status or scorecard in one durable record." + "status": "met", + "how": "The record holds the goal in the human's words and the scope in and out", + "evidence": "sisi/unit.py" }, { "id": "R-10.2-4", - "status": "missing", - "how": "nothing", - "evidence": "", - "gap": "No field, record, check or command in sisi implements this; at most canon prose gestures at it." + "status": "met", + "how": "The record holds the requirements with their kind and decision", + "evidence": "sisi/unit.py" }, { "id": "R-10.2-5", - "status": "partial", - "how": "The contract holds an id, goal, checks, invariants, assumptions and questions, and verify appends results by contract id", - "evidence": "sisi/contract.py:57", - "gap": "Most required fields are missing and the pieces live in four unlinked stores: no parent request, risk profile, agents, budgets, times, changed artifacts, deferred checks, delivery status or scorecard in one durable record." + "status": "met", + "how": "The record holds the checks and invariants", + "evidence": "sisi/unit.py" }, { "id": "R-10.2-6", - "status": "partial", - "how": "The contract holds an id, goal, checks, invariants, assumptions and questions, and verify appends results by contract id", - "evidence": "sisi/contract.py:57", - "gap": "Most required fields are missing and the pieces live in four unlinked stores: no parent request, risk profile, agents, budgets, times, changed artifacts, deferred checks, delivery status or scorecard in one durable record." + "status": "met", + "how": "The record holds the risk floor computed from the changed paths beside the declared profile, and the policy version in force", + "evidence": "sisi/unit.py" }, { "id": "R-10.2-7", "status": "partial", - "how": "The contract holds an id, goal, checks, invariants, assumptions and questions, and verify appends results by contract id", - "evidence": "sisi/contract.py:57", - "gap": "Most required fields are missing and the pieces live in four unlinked stores: no parent request, risk profile, agents, budgets, times, changed artifacts, deferred checks, delivery status or scorecard in one durable record." + "how": "The record holds the plan and the delegations from the ledger", + "evidence": "sisi/unit.py", + "gap": "Dependencies between units are not recorded." }, { "id": "R-10.2-8", - "status": "missing", - "how": "nothing", - "evidence": "", - "gap": "No field, record, check or command in sisi implements this; at most canon prose gestures at it." + "status": "partial", + "how": "The record holds the models seen in the host transcript and any budget the contract states", + "evidence": "sisi/unit.py", + "gap": "Budgets exist only if the contract sets them; model choice is not recorded when the host exposes no transcript." }, { "id": "R-10.2-9", - "status": "partial", - "how": "The contract holds an id, goal, checks, invariants, assumptions and questions, and verify appends results by contract id", - "evidence": "sisi/contract.py:57", - "gap": "Most required fields are missing and the pieces live in four unlinked stores: no parent request, risk profile, agents, budgets, times, changed artifacts, deferred checks, delivery status or scorecard in one durable record." + "status": "met", + "how": "Start and end times and the telemetry, every value classed", + "evidence": "sisi/unit.py" }, { "id": "R-10.2-10", "status": "partial", - "how": "The contract holds an id, goal, checks, invariants, assumptions and questions, and verify appends results by contract id", - "evidence": "sisi/contract.py:57", - "gap": "Most required fields are missing and the pieces live in four unlinked stores: no parent request, risk profile, agents, budgets, times, changed artifacts, deferred checks, delivery status or scorecard in one durable record." + "how": "Changed files and lines from git, and the start and closing commits", + "evidence": "sisi/unit.py", + "gap": "The implementation summary is written only when the contract carries one." }, { "id": "R-10.2-11", "status": "met", - "how": "verify.record appends every check action and result with contract id, rung, status and duration to the results store", - "evidence": "tests/test_verify.py:25", - "gap": "" + "how": "Every verification action and result is in the record", + "evidence": "sisi/unit.py" }, { "id": "R-10.2-12", - "status": "missing", - "how": "nothing", - "evidence": "", - "gap": "Deferred checks, limitations and unresolved risks have no field and are never gated." + "status": "met", + "how": "Deferred checks, limitations and open risks are fields of the record; a unit with deferred or never-run mandatory checks closes as delivered-with-deferred", + "evidence": "sisi/unit.py" }, { "id": "R-10.2-13", - "status": "partial", - "how": "The contract holds an id, goal, checks, invariants, assumptions and questions, and verify appends results by contract id", - "evidence": "sisi/contract.py:57", - "gap": "Most required fields are missing and the pieces live in four unlinked stores: no parent request, risk profile, agents, budgets, times, changed artifacts, deferred checks, delivery status or scorecard in one durable record." + "status": "met", + "how": "One of delivered, delivered-with-deferred, deviation, unverified, abandoned", + "evidence": "sisi/unit.py" }, { "id": "R-10.2-14", - "status": "missing", - "how": "nothing", - "evidence": "", - "gap": "No per-unit scorecard is produced or stored." + "status": "met", + "how": "The eight-dimension scorecard is stored in the record", + "evidence": "sisi/unit.py" }, { "id": "R-10.2-15", - "status": "partial", - "how": "The contract holds an id, goal, checks, invariants, assumptions and questions, and verify appends results by contract id", - "evidence": "sisi/contract.py:57", - "gap": "Most required fields are missing and the pieces live in four unlinked stores: no parent request, risk profile, agents, budgets, times, changed artifacts, deferred checks, delivery status or scorecard in one durable record." + "status": "met", + "how": "The retro findings recorded for the unit and the learnings it created are stored in the record", + "evidence": "sisi/unit.py" }, { "id": "R-10.3-1", "status": "partial", - "how": "The gate blocks a stop until contract checks pass and a retro is recorded, and labels escapes UNVERIFIED", - "evidence": "sisi/gate.py:52", - "gap": "Acceptance by an authorised party, disclosure of limitations and deferred checks are never asked, and awaiting-human checks count as passing." + "how": "`sisi unit close` archives the unit as delivered only when required verification has passed; a failing unit closes only as deviation, unverified or abandoned", + "evidence": "sisi/unit.py", + "gap": "Acceptance by an authorised party is not asked, and the end-of-turn flow does not yet require a unit to be closed." }, { "id": "R-10.3-2", "status": "partial", - "how": "The gate blocks a stop until contract checks pass and a retro is recorded, and labels escapes UNVERIFIED", - "evidence": "sisi/gate.py:52", - "gap": "Acceptance by an authorised party, disclosure of limitations and deferred checks are never asked, and awaiting-human checks count as passing." + "how": "`sisi unit close` archives the unit as delivered only when required verification has passed; a failing unit closes only as deviation, unverified or abandoned", + "evidence": "sisi/unit.py", + "gap": "Acceptance by an authorised party is not asked, and the end-of-turn flow does not yet require a unit to be closed." }, { "id": "R-10.3-3", "status": "partial", - "how": "The gate blocks a stop until contract checks pass and a retro is recorded, and labels escapes UNVERIFIED", - "evidence": "sisi/gate.py:52", - "gap": "Acceptance by an authorised party, disclosure of limitations and deferred checks are never asked, and awaiting-human checks count as passing." + "how": "`sisi unit close` archives the unit as delivered only when required verification has passed; a failing unit closes only as deviation, unverified or abandoned", + "evidence": "sisi/unit.py", + "gap": "Acceptance by an authorised party is not asked, and the end-of-turn flow does not yet require a unit to be closed." }, { "id": "R-10.3-4", "status": "partial", - "how": "The gate blocks a stop until contract checks pass and a retro is recorded, and labels escapes UNVERIFIED", - "evidence": "sisi/gate.py:52", - "gap": "Acceptance by an authorised party, disclosure of limitations and deferred checks are never asked, and awaiting-human checks count as passing." + "how": "`sisi unit close` archives the unit as delivered only when required verification has passed; a failing unit closes only as deviation, unverified or abandoned", + "evidence": "sisi/unit.py", + "gap": "Acceptance by an authorised party is not asked, and the end-of-turn flow does not yet require a unit to be closed." }, { "id": "R-10.3-5", "status": "partial", - "how": "The gate blocks a stop until contract checks pass and a retro is recorded, and labels escapes UNVERIFIED", - "evidence": "sisi/gate.py:52", - "gap": "Acceptance by an authorised party, disclosure of limitations and deferred checks are never asked, and awaiting-human checks count as passing." + "how": "`sisi unit close` archives the unit as delivered only when required verification has passed; a failing unit closes only as deviation, unverified or abandoned", + "evidence": "sisi/unit.py", + "gap": "Acceptance by an authorised party is not asked, and the end-of-turn flow does not yet require a unit to be closed." }, { "id": "R-10.3-6", "status": "partial", - "how": "The gate blocks a stop until contract checks pass and a retro is recorded, and labels escapes UNVERIFIED", - "evidence": "sisi/gate.py:52", - "gap": "Acceptance by an authorised party, disclosure of limitations and deferred checks are never asked, and awaiting-human checks count as passing." + "how": "`sisi unit close` archives the unit as delivered only when required verification has passed; a failing unit closes only as deviation, unverified or abandoned", + "evidence": "sisi/unit.py", + "gap": "Acceptance by an authorised party is not asked, and the end-of-turn flow does not yet require a unit to be closed." }, { "id": "R-10.3-7", @@ -1346,9 +1331,9 @@ { "id": "R-10.3-8", "status": "partial", - "how": "The gate blocks a stop until contract checks pass and a retro is recorded, and labels escapes UNVERIFIED", - "evidence": "sisi/gate.py:52", - "gap": "Acceptance by an authorised party, disclosure of limitations and deferred checks are never asked, and awaiting-human checks count as passing." + "how": "`sisi unit close` archives the unit as delivered only when required verification has passed; a failing unit closes only as deviation, unverified or abandoned", + "evidence": "sisi/unit.py", + "gap": "Acceptance by an authorised party is not asked, and the end-of-turn flow does not yet require a unit to be closed." }, { "id": "R-11.1-1", @@ -1815,9 +1800,9 @@ { "id": "R-13.1-1", "status": "partial", - "how": "scoreboard.py and improve report corrections, questions, contract share, send-backs and delivery time", - "evidence": "sisi/scoreboard.py", - "gap": "No per-work-unit scorecard exists and none of intent, correctness, cost, human attention or lifecycle quality is measured per unit or aggregated by policy version." + "how": "Each closed unit has a scorecard of the eight dimensions; `sisi status` shows recent units and trends by project, risk profile, model and policy version, with median and 95th percentile and no single score", + "evidence": "sisi/scorecard.py", + "gap": "No trend by task class or by agent." }, { "id": "R-13.2-1", @@ -1940,17 +1925,15 @@ }, { "id": "R-13.4-1", - "status": "partial", - "how": "sisi improve prints an explicit Not measured line for intent fulfilment instead of inventing a number", - "evidence": "sisi/cycle.py:1780", - "gap": "Scores carry no measured, inferred, estimated or unavailable label per dimension, and missing telemetry is not turned into an observability task." + "status": "met", + "how": "Every scorecard value is classed measured, inferred, estimated or unavailable", + "evidence": "sisi/scorecard.py" }, { "id": "R-13.4-2", - "status": "partial", - "how": "sisi improve prints an explicit Not measured line for intent fulfilment instead of inventing a number", - "evidence": "sisi/cycle.py:1780", - "gap": "Scores carry no measured, inferred, estimated or unavailable label per dimension, and missing telemetry is not turned into an observability task." + "status": "met", + "how": "Missing data is unavailable with no value, never zero; cost is estimated only from a recorded price; trends leave unavailable values out", + "evidence": "sisi/scorecard.py" }, { "id": "R-13.4-3", diff --git a/sisi/cli.py b/sisi/cli.py index 63db004..399cbcb 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -5,13 +5,19 @@ HELP = """sisi is still improving A shared rulebook and enforced definitions of done for every AI coding CLI. - sisi contract init [--goal TEXT] create .sisi/contract.json here - sisi contract check validate the contract - sisi contract waive "" record that this change needs no checks + sisi contract init [--goal TEXT] start a work unit: create .sisi/contract.json here (refuses while one is open) + sisi contract check validate the contract (vacuous checks are refused) + sisi contract waive [--check ID] "" + record a deviation: a waived check does not pass; the unit closes as a deviation and the report must say so sisi contract trust | untrust allow / stop allowing this project's contract to run commands - sisi verify [--json] run the fast checks; exit 0 ok, 1 failure, 2 no contract, 3 untrusted + sisi unit close [--abandon ""] + archive the unit to .sisi/units/.json with its scorecard; --abandon records why it stopped + sisi unit pause "" + record a wait; the turn may end with no demands + sisi unit show [ID] | list print the open unit or an archived record; list this project's units + sisi verify [--json] run the selected fast checks (five statuses; nothing unrun passes); exit 0 ok, 1 failure, 2 no contract, 3 untrusted sisi verify --deep [--background] run the deep (long) checks; --background detaches and returns at once - sisi verify --all | --state run both tiers; print only the deep-check state (with --json) + sisi verify --all | --state run every check in both tiers; print only the deep-check state (with --json) sisi gate [--tool NAME] end-of-turn hook (reads hook JSON on stdin; NAME selects the tool's hook shape) sisi tick [--tool NAME] session-start hook sisi prompt [--tool NAME] prompt-submission hook: prints the matching recipe and lessons for the human's request as added context (silent when nothing strictly matches); `sisi prompt ""` tries it by hand @@ -54,8 +60,7 @@ A shared rulebook and enforced definitions of done for every AI coding CLI. its key text) and removes it from the pile sisi oracle print what the human wants: the standing principles from `sisi learn`, live at once (oracle.md in the personal folder) - sisi status verification statistics from the store - sisi time [--json] time from request to verified result: 7 days against the 7 before, slowest checks + sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score) sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json] list ways to know work is correct, by section sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it @@ -107,12 +112,36 @@ def cmd_contract(args): if sub == "init": goal = _pop_opt(args, "--goal") p = os.path.join(os.getcwd(), C.REL) + project = os.getcwd() if os.path.exists(p): - print("sisi: %s already exists" % p) - return 1 + try: + old = C.load(p) + except (OSError, ValueError): + old = None + from . import unit as _U + if not _U.is_closed(old): + print("sisi: %s already exists and the unit %s is still open. Close it first with " + "`sisi unit close`, or record why it stopped with " + "`sisi unit close --abandon \"\"`." % (p, (old or {}).get("id", "?"))) + return 1 + # A closed unit is replaced. Its archive should already exist; if a hand-edited + # contract claims closed with none, archive it now so nothing is ever lost. + if old is not None and old.get("id") and not os.path.exists(_U.archive_path(project, old["id"])): + try: + import time as _t + rec = _U.build_record(old, project, old.get("delivery_status") or "abandoned", _t.time()) + _U.archive_record(rec, project) + if not _U._summary_exists(project, rec["id"]): + store.append("units", _U.summary_line(rec)) + except Exception as e: + store.log_error("contract-init-archive", e) os.makedirs(os.path.dirname(p), exist_ok=True) + skel = C.skeleton(goal) + from . import unit as _U + skel["id"] = _U.fresh_id(skel["id"], project) + skel["base_head"] = gitutil.head(project) with open(p, "w", encoding="utf-8") as f: - json.dump(C.skeleton(goal), f, indent=2) + json.dump(skel, f, indent=2) f.write("\n") trust.add(os.getcwd()) print("created %s as a SKELETON, not a contract yet: replace the placeholder check with a real command " @@ -149,9 +178,11 @@ def cmd_contract(args): print("contract invalid" if errs else "contract ok: %s" % p) return 1 if errs else 0 if sub == "waive": - reason = " ".join(args[1:]).strip() + rest = list(args[1:]) + waived_check = _pop_opt(rest, "--check") + reason = " ".join(rest).strip() if not reason: - print('usage: sisi contract waive ""') + print('usage: sisi contract waive [--check ID] ""') return 1 import time project = gitutil.root(os.getcwd()) or os.getcwd() @@ -159,8 +190,20 @@ def cmd_contract(args): if gitutil.root(os.getcwd()): m = gitutil.measure(os.getcwd()) extra = {"head": gitutil.head(os.getcwd()), "lines": m["lines"], "files": m["files"]} - store.append("waivers", store.stamp(dict({"project": project, "reason": reason, "ns": time.time_ns()}, **extra))) - print("waiver recorded for %s" % project) + store.append("waivers", store.stamp(dict({"project": project, "reason": reason, "check": waived_check, + "ns": time.time_ns()}, **extra))) + cp = C.find(os.getcwd()) + if cp: + try: + c = C.load(cp) + if isinstance(c, dict): + c.setdefault("deviations", []).append( + {"reason": reason, "check": waived_check, "ts": store.now()}) + C.save(cp, c) + except (OSError, ValueError): + pass + print("deviation recorded for %s%s: the unit does not pass; it closes as a deviation " + "and the completion report must say so" % (project, (" (check %s)" % waived_check) if waived_check else "")) return 0 if sub in ("trust", "untrust"): p = C.find(os.getcwd()) @@ -188,94 +231,6 @@ def cmd_oracle(): return 0 -def _status_retro(): - try: - from . import learning as _L - rows = _L.load_learnings() - print("learnings : %d total, %d proposed, %d promoted (`sisi status --learning` for the report)" - % (len(rows), sum(1 for r in rows if r.get("status") == "proposed"), - sum(1 for r in rows if r.get("status") in ("promoted", "monitored")))) - except Exception: - return - - -def _status_contracts(res): - """Per recent contract: latest fast run result and the deep state.""" - from . import contract as C, deep, verify as V - last = {} - for r in res: - if r.get("run") and r.get("item") in ("check", "invariant", "floor"): - k = (r.get("project"), r.get("contract")) - e = last.setdefault(k, {"ts": "", "fast": {}}) - e["ts"] = max(e["ts"], r.get("ts", "")) - if r.get("tier", "fast") == "fast": - e["fast"].setdefault(r["run"], []).append(r["status"]) - if not last: - return - print("recent contracts:") - for (project, cid), e in sorted(last.items(), key=lambda kv: kv[1]["ts"], reverse=True)[:5]: - runs = e["fast"] - fast = "-" - if runs: - # runs are keyed by hex timestamp-pid ids: the largest key is the newest - latest = runs[max(runs, key=lambda k: int(k.split("-")[0], 16))] - fast = "pass" if all(x in ("passed", "awaiting-human") for x in latest) else "fail" - dstate = "n/a" - try: - cp = os.path.join(project, C.REL) - c = C.load(cp) - ds = deep.deep_state(c, project, V.tree_fp(project, cp)) - dstate = ds["state"] if ds else "none" - except Exception: - dstate = "unknown" - print(" %-24s fast: %-5s deep: %s" % (cid, fast, dstate)) - - -def cmd_status(): - from . import store - res = store.read("results") - runs = {} - rungs = {} - for r in res: - if r.get("item") in ("check", "invariant", "floor") and r.get("run"): - runs.setdefault((r.get("project"), r.get("contract"), r["run"]), []).append(r) - if r.get("item") == "check" and r.get("rung"): - rungs[r["rung"]] = rungs.get(r["rung"], 0) + 1 - passed = [k for k, v in runs.items() if all(x["status"] in ("passed", "awaiting-human") for x in v)] - verified = {(k[0], k[1]) for k in passed} - unver = sum(1 for r in res if r.get("status") == "unverified") - waivers = len(store.read("waivers")) - print("contracts verified : %d (of %d seen)" % (len(verified), len({(k[0], k[1]) for k in runs}))) - print("verify runs : %d, pass rate %s" % (len(runs), "%.0f%%" % (100 * len(passed) / len(runs)) if runs else "n/a")) - tot = sum(rungs.values()) - print("checks by rung : " + (", ".join("%d: %.0f%%" % (k, 100 * v / tot) for k, v in sorted(rungs.items())) if tot else "none")) - print("unverified passes : %d" % unver) - print("waivers : %d" % waivers) - try: - from . import overlay - print("always loaded : " + overlay.cost_line()) - except Exception: - pass - try: - from . import delivery - print(delivery.median_line()) - except Exception: - pass - _status_retro() - _status_contracts(res) - from . import verifiers - vs = [e for e in verifiers.load_verifiers() if e["header"]] - by = {} - for e in vs: - k = e["header"].get("verified", "unset") - by[k] = by.get(k, 0) + 1 - print("library : %d verifiers (verified ran %d, docs %d, memory %d%s), %d recipes" - % (len(vs), by.get("ran", 0), by.get("docs", 0), by.get("memory", 0), - "".join(", %s %d" % (k, v) for k, v in sorted(by.items()) if k not in ("ran", "docs", "memory")), - len(verifiers.load_recipes()))) - return 0 - - def cmd_wiring(name, args=()): from . import wiring if name == "install" and "--dry-run" in args: @@ -417,10 +372,11 @@ def main(argv): from . import risk return risk.main(args) if cmd == "status": - return cmd_status() - if cmd == "time": - from . import delivery - return delivery.cmd_time(args) + from . import scorecard + return scorecard.cmd_status(args) + if cmd == "unit": + from . import unit + return unit.cmd_unit(args) if cmd == "verifiers": from . import verifiers return verifiers.main(args) diff --git a/sisi/contract.py b/sisi/contract.py index 4782fbf..eb2f91a 100644 --- a/sisi/contract.py +++ b/sisi/contract.py @@ -36,11 +36,22 @@ def is_unedited_skeleton(c): return False +REQ_KINDS = ("explicit", "implied", "contextual", "anticipated", "experiential") +REQ_DECISIONS = ("now", "architect", "defer", "ignore") +RISK_PROFILES = ("trivial", "isolated", "logic", "integration", "data", "critical", "release") +UNIT_STATUSES = ("open", "paused", "closed") + + def skeleton(goal=None, cwd=None): name = re.sub(r"[^a-z0-9]+", "-", os.path.basename(os.path.abspath(cwd or os.getcwd())).lower()).strip("-") + from . import store as _store return { "id": name or "work", + "parent": None, "goal": goal or "TODO: one sentence describing the outcome", + "scope": {"in": [], "out": []}, + "requirements": [], + "risk": {}, "checks": [{ "id": "c1", "claim": "PLACEHOLDER (fast tier, runs at the end of every turn, 60 s at most): replace with what this check shows to be true", @@ -62,6 +73,14 @@ def skeleton(goal=None, cwd=None): "invariants": [], "assumptions": [], "questions": [], + "deferred": [], + "limitations": [], + "plan": [], + "approach": None, + "status": "open", + "started": _store.now(), + "pauses": [], + "deviations": [], } @@ -70,6 +89,25 @@ def load(path): return json.load(f) +def save(path, c): + tmp = path + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + json.dump(c, f, indent=2) + f.write("\n") + os.replace(tmp, path) + + +def deferred_checks(c): + """{check_id: deferred entry} for deferred entries naming a check, by `check` or exactly by `what`.""" + out = {} + for d in c.get("deferred", []) if isinstance(c, dict) else []: + if isinstance(d, dict): + cid = d.get("check") or d.get("what") + if isinstance(cid, str) and cid: + out[cid] = d + return out + + def floors(): try: with open(paths.canon("floors.json"), encoding="utf-8") as f: @@ -132,6 +170,211 @@ def _expect(e, where, errs): errs.append("%s: unknown expect key %r" % (where, k)) +_TRUE_WORDS = {"true", ":", "/bin/true", "/usr/bin/true"} +_PRINT_WORDS = {"echo", "printf"} +_SHELLS = {"sh", "bash", "dash", "zsh", "/bin/sh", "/bin/bash", "/usr/bin/env"} +_WRAPPERS = {"env", "command", "exec", "time", "nohup", "builtin"} +_TESTERS = {"test", "["} +_OPS = {"&&", "||", ";", "|", "&"} + + +def _lex(s): + import shlex + lx = shlex.shlex(s.replace("\n", " ; "), posix=True, punctuation_chars=True) + lx.whitespace_split = True + lx.commenters = "#" + return list(lx) + + +def _literal(w): + return not any(ch in w for ch in "$`*?[~{}") + + +def _constant_true_simple(words, expect, depth=0): + """True when this one simple command is a constant that exits 0 whatever the project holds.""" + while words and (words[0] in _WRAPPERS or (words[0] == "timeout" and len(words) > 2)): + words = words[2:] if words[0] == "timeout" else words[1:] + if not words: + return False + w0, rest = words[0], words[1:] + if w0 in _TRUE_WORDS: + return True + if w0 == "exit": + return not rest or rest == ["0"] + if w0 in _PRINT_WORDS: + out = " ".join(rest) + want = expect.get("stdout_contains") + return want is None or str(want) in out + if w0 in _TESTERS: + ops = rest[:-1] if w0 == "[" and rest[-1:] == ["]"] else rest + if len(ops) == 3 and ops[1] in ("=", "==", "-eq") and all(_literal(x) for x in (ops[0], ops[2])): + return ops[0] == ops[2] + return False + if w0.rsplit("/", 1)[-1] in _SHELLS and depth < 4: + for i, x in enumerate(rest): + if x.startswith("-") and "c" in x[1:] and not x.startswith("--") and i + 1 < len(rest): + return _constant_true(rest[i + 1], expect, depth + 1) + return False + + +def _split(words, seps): + out, cur = [], [] + for w in words: + if w in seps: + out.append(cur) + cur = [] + else: + cur.append(w) + out.append(cur) + return out + + +def _constant_true(cmd, expect, depth=0): + try: + words = _lex(cmd) + except ValueError: + return False + if not words or any(w.startswith(("<", ">")) or w in ("<<", ">>") for w in words): + return False # a redirection reads or writes something: it can fail + alts = _split(words, {"||"}) + + def chain(ws): + seqs = [q for q in _split(ws, {";", "&&", "&"}) if q] + for seq in seqs: + stages = _split(seq, {"|"}) + if not stages[-1] or not _constant_true_simple(stages[-1], expect, depth): + return False + return bool(seqs) + return chain(alts[0]) or (len(alts) > 1 and chain(alts[-1])) + + +def vacuous_reason(ch): + """Why this check cannot fail, or None. The commands that exit 0 whatever the project + holds: `true`, `:`, `exit 0`, `echo`/`printf` that already prints what is expected, + `test 1 = 1`, any of them inside `sh -c`, joined with `;` or `&&`, or after `||` (so + `anything || true`). A floor, not a proof: no analysis can catch every constant.""" + cmd = ch.get("cmd") + if not isinstance(cmd, str): + return None + expect = ch.get("expect") if isinstance(ch.get("expect"), dict) else {} + if expect.get("exit", 0) != 0: + return None + if not _constant_true(cmd.strip(), expect): + return None + return "vacuous check: %r cannot fail; write a command that can" % cmd.strip() + + +def _check_new_fields(ch, w, errs): + if "covers" in ch and not _str(ch["covers"]): + errs.append(w + ": covers must be a non-empty string") + if "when_changed" in ch: + wc = ch["when_changed"] + if not isinstance(wc, list) or not wc or not all(_str(x) for x in wc): + errs.append(w + ": when_changed must be a non-empty list of path patterns") + 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)) + + +def _validate_new_top(c, ids, errs): + if "parent" in c and c["parent"] is not None and not _str(c["parent"]): + errs.append("parent must be a non-empty string or null") + if "status" in c and c["status"] not in UNIT_STATUSES: + errs.append("status must be one of %s" % ", ".join(UNIT_STATUSES)) + if "started" in c and not _str(c["started"]): + errs.append("started must be a non-empty string") + if "scope" in c: + sc = c["scope"] + if not isinstance(sc, dict): + errs.append("scope must be an object with in/out lists") + else: + for k in sc: + if k not in ("in", "out"): + errs.append("scope: unknown key %r" % k) + for k in ("in", "out"): + if k in sc and (not isinstance(sc[k], list) or not all(isinstance(x, str) for x in sc[k])): + errs.append("scope.%s must be a list of strings" % k) + if "requirements" in c: + rq = c["requirements"] + if not isinstance(rq, list): + errs.append("requirements must be a list") + else: + seen = set() + for i, r in enumerate(rq): + w = "requirements[%d]" % i + if not isinstance(r, dict): + errs.append(w + " must be an object"); continue + if not _str(r.get("id")): + errs.append(w + ".id must be a non-empty string") + elif r["id"] in seen: + errs.append("duplicate requirement id %r" % r["id"]) + else: + seen.add(r["id"]); w = "requirement %r" % r["id"] + if r.get("kind") not in REQ_KINDS: + errs.append("%s: kind must be one of %s" % (w, ", ".join(REQ_KINDS))) + if not _str(r.get("text")): + errs.append(w + ": text must be a non-empty string") + if r.get("decision") not in REQ_DECISIONS: + errs.append("%s: decision must be one of %s" % (w, ", ".join(REQ_DECISIONS))) + if "why" in r and not _str(r["why"]): + errs.append(w + ": why must be a non-empty string") + if "check" in r and r["check"] is not None: + if not _str(r["check"]): + errs.append(w + ": check must be a check id or null") + elif ids and r["check"] not in ids: + errs.append("%s: check %r is not a check or invariant id" % (w, r["check"])) + if "added" in r and not _str(r["added"]): + errs.append(w + ": added must be a non-empty string") + if "risk" in c: + rk = c["risk"] + if not isinstance(rk, dict): + errs.append("risk must be an object") + else: + if "profile" in rk and rk["profile"] not in RISK_PROFILES: + errs.append("risk.profile must be one of %s" % ", ".join(RISK_PROFILES)) + for k in ("why", "blast_radius", "rollback"): + if k in rk and not _str(rk[k]): + errs.append("risk.%s must be a non-empty string" % k) + if "deferred" in c: + df = c["deferred"] + if not isinstance(df, list): + errs.append("deferred must be a list") + else: + for i, d in enumerate(df): + w = "deferred[%d]" % i + if not isinstance(d, dict): + errs.append(w + " must be an object"); continue + for k in ("what", "why", "safe_because"): + if not _str(d.get(k)): + errs.append("%s.%s must be a non-empty string" % (w, k)) + if "check" in d and d["check"] is not None and not _str(d["check"]): + errs.append(w + ": check must be a check id or null") + if "approach" in c and c["approach"] is not None: + ap = c["approach"] + if not isinstance(ap, dict): + errs.append("approach must be an object") + else: + for k in ap: + if k not in ("chosen", "why", "alternatives", "reuses"): + errs.append("approach: unknown key %r" % k) + for k in ("chosen", "why"): + if k in ap and not _str(ap[k]): + errs.append("approach.%s must be a non-empty string" % k) + for k in ("alternatives", "reuses"): + if k in ap and (not isinstance(ap[k], list) or not all(_str(x) for x in ap[k])): + errs.append("approach.%s must be a list of non-empty strings" % k) + if "limitations" in c: + if not isinstance(c["limitations"], list) or not all(isinstance(x, str) for x in c["limitations"]): + errs.append("limitations must be a list of strings") + if "plan" in c: + if not isinstance(c["plan"], list) or not all(isinstance(x, (str, dict)) for x in c["plan"]): + errs.append("plan must be a list of steps (strings or objects)") + if "pauses" in c and not isinstance(c["pauses"], list): + errs.append("pauses must be a list") + if "deviations" in c and not isinstance(c["deviations"], list): + errs.append("deviations must be a list") + + def validate(c): """Return a list of error strings; empty means valid.""" errs = [] @@ -179,6 +422,10 @@ def validate(c): _tier(ch, w, errs) if "serial" in ch and not isinstance(ch["serial"], bool): errs.append(w + ": serial must be true or false") + _check_new_fields(ch, w, errs) + vr = vacuous_reason(ch) + if vr: + errs.append("%s: %s" % (w, vr)) inv = c.get("invariants", []) if not isinstance(inv, list): errs.append("invariants must be a list") @@ -205,6 +452,10 @@ def validate(c): _tier(iv, w, errs) if "serial" in iv and not isinstance(iv["serial"], bool): errs.append(w + ": serial must be true or false") + _check_new_fields(iv, w, errs) + vr = vacuous_reason(iv) + if vr: + errs.append("%s: %s" % (w, vr)) runnable = any(isinstance(x, dict) and x.get("rung") in (1, 2, 3, 4) and x.get("cmd") for x in checks) or \ any(isinstance(x, dict) and x.get("cmd") for x in inv) if checks and not runnable: @@ -220,6 +471,7 @@ def validate(c): for i, x in enumerate(q): if not (isinstance(x, dict) and _str(x.get("q")) and "default" in x): errs.append("questions[%d] needs q and default" % i) + _validate_new_top(c, ids, errs) return errs diff --git a/sisi/deep.py b/sisi/deep.py index a0c6acd..9bbcdfd 100644 --- a/sisi/deep.py +++ b/sisi/deep.py @@ -93,7 +93,7 @@ def save_state(project, contract_id, fp, results, deep_ids): items = [{"id": r["id"], "status": r["status"], "tail": (r.get("tail") or "")[-1500:]} for r in results if r.get("tier") == "deep"] st = {"contract": contract_id, "fp": fp, "epoch": time.time(), "ids": sorted(deep_ids), - "ok": all(i["status"] in ("passed", "awaiting-human") for i in items), "items": items} + "ok": all(i["status"] in ("passed", "skipped", "not-applicable") for i in items), "items": items} p = _state_path(project) os.makedirs(os.path.dirname(p), exist_ok=True) tmp = p + ".tmp%d" % os.getpid() @@ -123,7 +123,7 @@ def deep_state(c, project, fp): st = load_state(project) if st is not None and st.get("ids") == ids: base.update(epoch=st.get("epoch"), fresh=fp is not None and st.get("fp") == fp, - failed=[i for i in st["items"] if i["status"] not in ("passed", "awaiting-human")]) + failed=[i for i in st["items"] if i["status"] in ("failed", "not-run")]) else: st = None if lock: diff --git a/sisi/delivery.py b/sisi/delivery.py index d9168e7..0c75ea4 100644 --- a/sisi/delivery.py +++ b/sisi/delivery.py @@ -1,4 +1,5 @@ -"""Time to delivery: how long from the human's request to a verified stop, recorded by the gate and read by `sisi time`. +"""Time to delivery: how long from the human's request to a verified stop, recorded by the gate +and read back as unit telemetry when a unit closes (see sisi.unit; `sisi status` is the one report). Delivery row (deliveries.jsonl in the state dir): session, project, start, end (ISO UTC), seconds, send_backs (times the gate sent the agent back during this request), check_s (seconds spent running checks during this request), contract @@ -93,143 +94,3 @@ def record(payload, sess, sid, cwd, now=None): except Exception as e: store.log_error("delivery", e) return None - - -# ---------------------------------------------------------------- reading: `sisi time` - -DAY = 86400.0 - - -def median(xs): - s = sorted(xs) - n = len(s) - if not n: - return None - return s[n // 2] if n % 2 else (s[n // 2 - 1] + s[n // 2]) / 2.0 - - -def percentile(xs, p): - """Linear-interpolation percentile (p in 0..100) of a list of numbers; None when empty.""" - s = sorted(xs) - if not s: - return None - k = (len(s) - 1) * p / 100.0 - lo = int(k) - hi = min(lo + 1, len(s) - 1) - return s[lo] + (s[hi] - s[lo]) * (k - lo) - - -def _epoch(ts): - from . import harvest - return harvest.epoch(ts) if isinstance(ts, str) else None - - -def summarize(rows): - secs = [r["seconds"] for r in rows] - tot = sum(secs) - chk = sum(min(r.get("check_s", 0.0), r["seconds"]) for r in rows) - return {"n": len(rows), "median_s": median(secs), "p90_s": percentile(secs, 90), - "check_share": (chk / tot) if tot > 0 else None, - "send_back_deliveries": sum(1 for r in rows if r.get("send_backs", 0) > 0)} - - -def windows(rows, now): - """(last 7 days, the 7 days before) of delivery rows, by their end time.""" - cur, prev = [], [] - for r in rows: - if not (isinstance(r, dict) and isinstance(r.get("seconds"), (int, float))): - continue - t = _epoch(r.get("end") or r.get("ts")) - if t is None: - continue - if now - 7 * DAY <= t <= now: - cur.append(r) - elif now - 14 * DAY <= t < now - 7 * DAY: - prev.append(r) - return cur, prev - - -def slow_checks(results, now, top=5): - """The slowest checks by mean duration over the last 7 days, each with a suggestion.""" - from . import scoreboard - recent = [r for r in results if isinstance(r, dict) and (_epoch(r.get("ts")) or 0) >= now - 7 * DAY] - out = [] - for s in scoreboard.check_stats(recent)["checks"]: - if s.get("timed_runs"): - out.append({"id": s["id"], "mean_s": s["total_s"] / s["timed_runs"], "runs": s["runs"], "tier": s.get("tier", "fast")}) - out.sort(key=lambda x: -x["mean_s"]) - out = out[:top] - for x in out: - if x["mean_s"] < 5: - x["suggestion"] = "quick enough: leave it in the fast tier" - elif x["tier"] == "deep": - x["suggestion"] = "already deep; split it so a quick part can run in the gate" - else: - x["suggestion"] = 'mark as "tier": "deep" if it can wait, or split it into a quick part and a slow part' - return out - - -def report(now=None): - now = time.time() if now is None else now - rows = store.read("deliveries") - cur, prev = windows(rows, now) - by_project = {} - for label, group in (("cur", cur), ("prev", prev)): - for r in group: - by_project.setdefault(r.get("project") or "(unknown)", {"cur": [], "prev": []})[label].append(r) - return {"now": _iso(now), "all": {"last7": summarize(cur), "prev7": summarize(prev)}, - "projects": {p: {"last7": summarize(v["cur"]), "prev7": summarize(v["prev"])} for p, v in sorted(by_project.items())}, - "slowest_checks": slow_checks(store.read("results"), now)} - - -def fmt_s(s): - if s is None: - return "-" - s = int(round(s)) - if s < 60: - return "%ds" % s - if s < 3600: - return "%dm%02ds" % (s // 60, s % 60) - return "%dh%02dm" % (s // 3600, (s % 3600) // 60) - - -def _cell(s): - return "median %s, p90 %s (%d)" % (fmt_s(s["median_s"]), fmt_s(s["p90_s"]), s["n"]) if s["n"] else "none" - - -def median_line(now=None): - """One line for `sisi status`.""" - cur = report(now)["all"]["last7"] - if not cur["n"]: - return "time to delivery : no deliveries recorded in the last 7 days" - return "time to delivery : median %s over the last 7 days (%d deliveries)" % (fmt_s(cur["median_s"]), cur["n"]) - - -def cmd_time(args, out=print): - r = report() - if "--json" in args: - out(json.dumps(r, indent=2)) - return 0 - a = r["all"] - if not a["last7"]["n"] and not a["prev7"]["n"]: - out("sisi time: no deliveries recorded in the last 14 days. The end-of-turn gate records one each time it lets " - "a turn end; check that the gate is installed (`sisi doctor`).") - else: - out("time from the human's request to a verified stop") - out("%-28s %-34s %s" % ("", "last 7 days", "the 7 days before")) - out("%-28s %-34s %s" % ("all projects", _cell(a["last7"]), _cell(a["prev7"]))) - for p, v in r["projects"].items(): - out("%-28s %-34s %s" % (os.path.basename(p.rstrip("/"))[:28] or p, _cell(v["last7"]), _cell(v["prev7"]))) - c = a["last7"] - if c["n"]: - out("") - out("share of that time spent running checks: %s" % ("%.0f%%" % (100 * c["check_share"]) if c["check_share"] is not None else "-")) - out("deliveries that needed a send-back: %d of %d" % (c["send_back_deliveries"], c["n"])) - out("") - if r["slowest_checks"]: - out("slowest checks (mean run time, last 7 days)") - for x in r["slowest_checks"]: - out(" %-30s %8s over %d runs [%s]\n -> %s" % (x["id"][:30], fmt_s(x["mean_s"]), x["runs"], x["tier"], x["suggestion"])) - else: - out("slowest checks: no check runs recorded in the last 7 days") - return 0 diff --git a/sisi/escapes.py b/sisi/escapes.py deleted file mode 100644 index 3e766ea..0000000 --- a/sisi/escapes.py +++ /dev/null @@ -1,89 +0,0 @@ -"""Escape candidates: work declared verified (or finished) that then turned out wrong. Evidence pointers only. - -Kinds - contract-then-correction a contract run passed (every check passed or awaits a human) in a session, and a - correction-like user message came later in that session. - contract-then-fix-session a contract run passed in a session; within 7 days a later main session in the same - repo touched at least one of the same files (by following commits) and opened with a - fix-like request. - premature-done independent of sisi records: an assistant turn ended on a completion claim and the - very next typed user message was correction-like. -Results join to sessions by the `session` field when present, otherwise by time and project: a session whose -window contains the run and whose cwd or repo is inside the run's project. If more than one session fits, the -candidate is marked `ambiguous`. These are candidates for a human or a model to look at, not conclusions. -""" -import json, re - -from . import harvest, store - -WEEK_S = 7 * 86400 -_FIXLIKE = re.compile(r"\b(fix|bug|broken|wrong|regress|revert|fails?|failing|doesn'?t work|not working|error|crash)", re.I) - - -def passed_runs(results): - """[{ts, t, project, contract, session, run}] for runs whose checks all passed.""" - groups = {} - for r in results: - if not isinstance(r, dict) or r.get("check") == "gate": - continue - key = r.get("run") or "%s|%s|%s" % (r.get("ts"), r.get("contract"), r.get("project")) - groups.setdefault(key, []).append(r) - out = [] - for key, rs in groups.items(): - if all(x.get("status") in ("passed", "awaiting-human") for x in rs) and any(x.get("status") == "passed" for x in rs): - t = harvest.epoch(rs[0].get("ts") or "") - if t is not None: - out.append({"ts": rs[0]["ts"], "t": t, "project": rs[0].get("project"), "contract": rs[0].get("contract"), - "session": rs[0].get("session"), "run": key}) - return sorted(out, key=lambda x: x["t"]) - - -def _inside(path, parent): - if not path or not parent: - return False - p, q = path.rstrip("/"), parent.rstrip("/") - return p == q or p.startswith(q + "/") or q.startswith(p + "/") - - -def attribute(run, sessions): - """Sessions (rows) the run can be attributed to: by session id when it names one, else by time and project.""" - if run["session"]: - hit = [s for s in sessions if s["id"] == run["session"]] - if hit: - return hit, False - hit = [s for s in sessions if s["t0"] is not None and s["t0"] <= run["t"] <= (s["t1"] or s["t0"]) + 60 - and (_inside(s["cwd"], run["project"]) or _inside(s["repo_root"], run["project"]))] - return hit, len(hit) > 1 - - -def find(con, results=None): - results = store.read("results") if results is None else results - sessions = [dict(r) for r in con.execute( - "SELECT s.id, s.cwd, s.t0, s.t1, s.first_message, s.machine, g.repo_root, g.files, g.start_kind " - "FROM sessions s LEFT JOIN groundtruth g ON g.session_id=s.id WHERE s.kind='main'")] - out = [] - for run in passed_runs(results): - hit, ambiguous = attribute(run, sessions) - for s in hit: - later = con.execute("SELECT idx, ts, t FROM user_msgs WHERE session_id=? AND correction=1 AND t>? ORDER BY t", - (s["id"], run["t"])).fetchall() - for m in later[:3]: - out.append({"kind": "contract-then-correction", "session": s["id"], "run": run["run"], "contract": run["contract"], - "passed_at": run["ts"], "evidence": {"user_msg_idx": m["idx"], "at": m["ts"]}, "ambiguous": ambiguous}) - files = set(json.loads(s["files"] or "[]")) - if files and s["repo_root"]: - for o in sessions: - if o["id"] == s["id"] or o["repo_root"] != s["repo_root"] or o["machine"] or o["t0"] is None: - continue - if not (run["t"] < o["t0"] <= run["t"] + WEEK_S): - continue - common = files & set(json.loads(o["files"] or "[]")) - if common and _FIXLIKE.search((o["first_message"] or "")[:1500]): - out.append({"kind": "contract-then-fix-session", "session": s["id"], "run": run["run"], - "contract": run["contract"], "passed_at": run["ts"], - "evidence": {"later_session": o["id"], "common_files": sorted(common)[:10]}, - "ambiguous": ambiguous}) - for r in con.execute("SELECT m.session_id, m.idx, m.ts FROM user_msgs m WHERE m.correction=1 AND m.after_completion=1 ORDER BY m.t"): - out.append({"kind": "premature-done", "session": r["session_id"], "evidence": {"user_msg_idx": r["idx"], "at": r["ts"]}, - "ambiguous": False}) - return out diff --git a/sisi/gate.py b/sisi/gate.py index 4ba9c60..d684b10 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -641,6 +641,14 @@ def _decide(payload): if c is not None and C.is_unedited_skeleton(c): path = 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 + 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 @@ -765,7 +773,8 @@ def _decide(payload): "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",)) + 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): @@ -811,7 +820,7 @@ def _decide(payload): 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", "timeout")) + 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 diff --git a/sisi/gitutil.py b/sisi/gitutil.py index eb94eda..4d74067 100644 --- a/sisi/gitutil.py +++ b/sisi/gitutil.py @@ -25,12 +25,19 @@ def head(cwd): return out.strip() if rc == 0 else None +_EXCLUDE = ":(exclude).sisi" # sisi's own records are never part of the work being measured + + +def _is_sisi(rel): + return rel == ".sisi" or rel.startswith(".sisi/") + + def measure(cwd, base=None, max_untracked=200): """Return {'lines': n, 'files': [paths]} for the working tree vs `base` (default HEAD).""" cwd = root(cwd) or cwd base = base or head(cwd) or EMPTY_TREE lines, files = 0, set() - rc, out = _git(cwd, "diff", "--numstat", base, timeout=10) + rc, out = _git(cwd, "diff", "--numstat", base, "--", ".", _EXCLUDE, timeout=10) if rc == 0: for ln in out.splitlines(): parts = ln.split("\t", 2) @@ -44,7 +51,7 @@ def measure(cwd, base=None, max_untracked=200): rc, out = _git(cwd, "ls-files", "--others", "--exclude-standard", timeout=10) if rc == 0: top = cwd - for rel in out.splitlines()[:max_untracked]: + for rel in [r for r in out.splitlines() if not _is_sisi(r)][:max_untracked]: files.add(rel) try: fp = os.path.join(top, rel) @@ -100,13 +107,13 @@ def fingerprint(cwd, extra_files=()): h = hashlib.sha1() base = head(top) or EMPTY_TREE h.update(base.encode()) - p = subprocess.run(["git", "diff", "--no-ext-diff", "--no-textconv", "--no-color", base], cwd=top, - capture_output=True, timeout=10) + p = subprocess.run(["git", "diff", "--no-ext-diff", "--no-textconv", "--no-color", base, "--", ".", _EXCLUDE], + cwd=top, capture_output=True, timeout=10) h.update(b"\0diff\0" + p.stdout) p = subprocess.run(["git", "ls-files", "--others", "--exclude-standard", "-z"], cwd=top, capture_output=True, timeout=10) for rel in p.stdout.split(b"\0")[:2000]: - if not rel: + if not rel or _is_sisi(os.fsdecode(rel)): continue try: st = os.stat(os.path.join(top, os.fsdecode(rel))) diff --git a/sisi/harvest.py b/sisi/harvest.py index 64caca8..a759b08 100644 --- a/sisi/harvest.py +++ b/sisi/harvest.py @@ -226,6 +226,90 @@ def machine_reason(text, origin_kind=None, entrypoint=None): return bool(reasons), ";".join(reasons) +# ---------------------------------------------------------------- transcript usage (telemetry) + +_USAGE_KEYS = (("input", ("input_tokens", "inputTokens")), + ("output", ("output_tokens", "outputTokens")), + ("cache_read", ("cache_read_input_tokens", "cacheReadInputTokens", "cached_input_tokens")), + ("cache_creation", ("cache_creation_input_tokens", "cacheCreationInputTokens"))) +_QUESTION_TOOLS = {"AskUserQuestion", "request_user_input", "ask_user_question"} + + +def transcript_stats(path, t0=None, t1=None): + """Token usage and human-attention counts from one Claude-Code-shaped transcript, or None + when the file cannot be read. `usage` is None when no record carried any usage numbers: + a caller must report tokens as unavailable then, never as zero. Timestamps bound the + window in epoch seconds when given. Streams the file; malformed lines are skipped.""" + try: + f = open(os.path.expanduser(path), "rb") + except (OSError, TypeError): + return None + by_model, by_cat = {}, {} + human, corrections, dialogs, subagents, first = 0, 0, 0, 0, True + with f: + for raw in f: + try: + if b"usage" not in raw and b"user" not in raw and b"tool_use" not in raw \ + and b"queued_command" not in raw: + continue + d = json.loads(raw) + if not isinstance(d, dict): + continue + ts = epoch(d["timestamp"]) if isinstance(d.get("timestamp"), str) else None + outside = ts is not None and ((t0 is not None and ts < t0) or (t1 is not None and ts > t1)) + typ = d.get("type") + if outside and typ != "user": + continue + if typ == "assistant": + m = d.get("message") or {} + u = m.get("usage") if isinstance(m, dict) else None + if isinstance(u, dict): + model = m.get("model") if isinstance(m.get("model"), str) and not m["model"].startswith("<") else "(unknown)" + got = {} + for cat, keys in _USAGE_KEYS: + for k in keys: + if isinstance(u.get(k), (int, float)) and not isinstance(u.get(k), bool): + got[cat] = int(u[k]); break + if got: + slot = by_model.setdefault(model, {}) + for cat, v in got.items(): + by_cat[cat] = by_cat.get(cat, 0) + v + slot[cat] = slot.get(cat, 0) + v + content = m.get("content") if isinstance(m, dict) else None + for b in content if isinstance(content, list) else (): + if isinstance(b, dict) and b.get("type") == "tool_use": + if b.get("name") in _QUESTION_TOOLS: + dialogs += 1 + if b.get("name") in ("Agent", "Task"): + subagents += 1 + elif typ == "user": + text = typed_text(d)[0] + if text is not None: + # the transcript's first typed message is a request, never a correction, + # whether or not it falls inside the window + if not outside: + if not first and is_correction(text): + corrections += 1 + human += 1 + first = False + elif typ == "attachment": + a = d.get("attachment") or {} + if a.get("type") == "queued_command" and a.get("commandMode") == "prompt" and not a.get("isMeta"): + if typed_text(a, queued_prompt=a.get("prompt"))[0] is not None: + human += 1 + except Exception: + continue + for slot in by_model.values(): + slot["total"] = sum(v for k, v in slot.items()) + if by_cat: + by_cat_out = dict(by_cat, total=sum(by_cat.values())) + usage = {"by_category": by_cat_out, "by_model": by_model} + else: + usage = None + return {"usage": usage, "human_messages": human, "corrections": corrections, + "question_dialogs": dialogs, "subagent_runs": subagents} + + # ---------------------------------------------------------------- source interface class Source: diff --git a/sisi/learn_cli.py b/sisi/learn_cli.py index 96d0d5d..9e7c502 100644 --- a/sisi/learn_cli.py +++ b/sisi/learn_cli.py @@ -1,4 +1,4 @@ -"""Commands for the data layer of the learning loop: harvest, tasks, escapes, checks, scoreboard. +"""Commands for the data layer of the learning loop: harvest, tasks, escapes, checks. Usable now as `python3 -m sisi.learn_cli `. The main CLI hooks them in with `learn_cli.register(subparsers)`; each command sets `func(args) -> exit code` on its parser. @@ -69,8 +69,8 @@ def cmd_tasks(args): def cmd_escapes(args): - from . import escapes, harvest - rows = escapes.find(harvest.connect()) + from . import harvest, scorecard + rows = scorecard.escape_candidates(harvest.connect()) if args.json: print(json.dumps(rows)) return 0 @@ -84,37 +84,21 @@ def cmd_escapes(args): def cmd_checks(args): - from . import scoreboard - st = scoreboard.check_stats(store.read("results")) + from . import scorecard + st = scorecard.check_stats(store.read("results")) if args.json: print(json.dumps(st)) return 0 for title, key in (("check", "checks"), ("verifier", "verifiers")): if not st[key]: continue - print("%-40s %5s %5s %5s" % (title, "runs", "fail", "tmo")) + print("%-40s %5s %5s %5s" % (title, "runs", "fail", "not run")) for s in st[key]: - print("%-40s %5d %5d %5d%s" % (s["id"][:40], s["runs"], s["failures"], s["timeouts"], + print("%-40s %5d %5d %5d%s" % (s["id"][:40], s["runs"], s["failures"], s["not_run"], " never seen failing" if s["never_seen_failing"] else "")) return 0 -def cmd_scoreboard(args): - from . import scoreboard - sb = scoreboard.scoreboard(_con()) - if args.json: - print(json.dumps(sb)) - return 0 - cols = ("sessions", "turns_per_session", "corrections_per_100", "questions_per_100", "contract_share", "premature_done_share") - for title, key in (("week", "weeks"), ("repo", "repos")): - print("%-18s %s" % (title, " ".join("%-12s" % c[:12] for c in cols))) - for k, v in sb[key].items(): - print("%-18s %s" % (k[:18], " ".join("%-12s" % ("-" if v[c] is None else v[c]) for c in cols))) - print() - print("tasks:", json.dumps(sb["tasks"])) - return 0 - - def register(subparsers): p = subparsers.add_parser("harvest", help="read agent transcripts into the harvest database (incremental)") p.add_argument("--workers", type=int, default=None) @@ -146,11 +130,6 @@ def register(subparsers): p.add_argument("--json", action="store_true") p.set_defaults(func=cmd_checks) - p = subparsers.add_parser("scoreboard", help="weekly and per-repo trends from harvested sessions") - p.add_argument("--json", action="store_true") - p.set_defaults(func=cmd_scoreboard) - - def main(argv=None): ap = argparse.ArgumentParser(prog="sisi") register(ap.add_subparsers(dest="cmd", required=True)) diff --git a/sisi/scoreboard.py b/sisi/scoreboard.py deleted file mode 100644 index 70234fa..0000000 --- a/sisi/scoreboard.py +++ /dev/null @@ -1,100 +0,0 @@ -"""Check statistics and the scoreboard. - -Check statistics (from results.jsonl): per check id, and per verifier when records carry a `verifier` field: -runs, failures, timeouts. A check with MANY_RUNS or more runs and no failure or timeout is flagged -"never seen failing" (it may be a check that cannot fail). The `gate` pseudo-check is skipped. - -Scoreboard: ISO weeks (Monday start, UTC) and repo, from the harvested main sessions that a human started -(first typed message not machine-written). Trends matter, so every week uses the same definitions: - sessions human-started main sessions whose first message falls in the week - turns_per_session typed user turns per session - corrections_per_100 correction-like typed messages per 100 typed turns (the first message never counts) - questions_per_100 assistant turns that ended on a question with no tool call, plus AskUserQuestion calls, - per 100 typed turns - contract_share share of sessions that used `sisi contract`/`sisi verify` - premature_done_share among sessions with at least one completion claim, the share where a claim was - immediately followed by a correction-like message (a claim can only be "followed" by - a correction if the session went on, so this is not "sessions ending on a claim") -Only weeks and repos with at least one session appear. Completion claims, questions and corrections are -regex heuristics; compare week with week, not with an absolute truth. -""" -import datetime, json, time - -from . import harvest, store, taskset - -MANY_RUNS = 10 - - -def check_stats(results): - by, byv = {}, {} - for r in results: - if not isinstance(r, dict) or not r.get("check") or r.get("check") == "gate": - continue - keys = [("check", r["check"], by)] - if r.get("verifier"): - keys.append(("verifier", r["verifier"], byv)) - for _, k, d in keys: - s = d.setdefault(k, {"runs": 0, "failures": 0, "timeouts": 0, "total_s": 0.0, "timed_runs": 0}) - s["runs"] += 1 - if isinstance(r.get("duration_s"), (int, float)) and not isinstance(r.get("duration_s"), bool): - s["total_s"] += r["duration_s"] # for `sisi time`: which checks cost the most - s["timed_runs"] += 1 - s["tier"] = r.get("tier", "fast") - if r.get("status") == "failed": - s["failures"] += 1 - elif r.get("status") == "timeout": - s["timeouts"] += 1 - def fin(d): - out = [] - for k, s in sorted(d.items()): - s = dict(s, id=k) - s["never_seen_failing"] = s["runs"] >= MANY_RUNS and s["failures"] == 0 and s["timeouts"] == 0 - out.append(s) - return out - return {"checks": fin(by), "verifiers": fin(byv)} - - -def iso_week(t): - d = datetime.datetime.fromtimestamp(t, datetime.timezone.utc).date() - y, w, _ = d.isocalendar() - return "%04d-W%02d" % (y, w) - - -def _blank(): - return {"sessions": 0, "turns": 0, "corrections": 0, "questions": 0, "contract": 0, "claim_sessions": 0, "premature_sessions": 0} - - -def _finish(a): - n, t = a["sessions"], a["turns"] - return {"sessions": n, "turns_per_session": round(t / n, 2) if n else None, - "corrections_per_100": round(100.0 * a["corrections"] / t, 1) if t else None, - "questions_per_100": round(100.0 * a["questions"] / t, 1) if t else None, - "contract_share": round(a["contract"] / n, 3) if n else None, - "premature_done_share": round(a["premature_sessions"] / a["claim_sessions"], 3) if a["claim_sessions"] else None} - - -def _add(a, r): - a["sessions"] += 1 - a["turns"] += r["user_turns"] - a["corrections"] += r["n_corrections"] - a["questions"] += r["n_question_turns"] + r["n_ask"] - a["contract"] += 1 if (r["used_contract"] or r["used_verify"]) else 0 - if r["n_completion_claims"]: - a["claim_sessions"] += 1 - a["premature_sessions"] += 1 if r["n_premature_done"] else 0 - - -def scoreboard(con): - weeks, repos, wr = {}, {}, {} - q = ("SELECT s.t0, s.user_turns, s.n_corrections, s.n_question_turns, s.n_ask, s.used_contract, s.used_verify, " - "s.n_completion_claims, s.n_premature_done, g.repo_root FROM sessions s LEFT JOIN groundtruth g ON g.session_id=s.id " - "WHERE s.kind='main' AND s.machine=0 AND s.t0 IS NOT NULL") - for r in con.execute(q): - repo = (r["repo_root"] or "(no repo)").rstrip("/").rsplit("/", 1)[-1] - week = iso_week(r["t0"]) - for table, key in ((weeks, week), (repos, repo), (wr, (week, repo))): - _add(table.setdefault(key, _blank()), r) - return {"weeks": {k: _finish(v) for k, v in sorted(weeks.items())}, - "repos": {k: _finish(v) for k, v in sorted(repos.items())}, - "week_repo": {"%s %s" % k: _finish(v) for k, v in sorted(wr.items())}, - "tasks": taskset.counts(con)} diff --git a/sisi/scorecard.py b/sisi/scorecard.py new file mode 100644 index 0000000..427a685 --- /dev/null +++ b/sisi/scorecard.py @@ -0,0 +1,392 @@ +"""The per-unit scorecard (eight dimensions, every value classed) and `sisi status`. + +Every scorecard value is {"value": ..., "class": measured|inferred|estimated|unavailable}. +Missing data is unavailable with value None: never zero, never good. No single score is +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 + +from . import harvest, store + +CLASSES = ("measured", "inferred", "estimated", "unavailable") + + +def val(v, cls): + assert cls in CLASSES + return {"value": v, "class": cls} + + +def unavailable(): + return {"value": None, "class": "unavailable"} + + +# ---------------------------------------------------------------- check statistics + +MANY_RUNS = 10 +# rows written by earlier versions: neither of these ever meant a pass +_LEGACY = {"timeout": "not-run", "awaiting-human": "not-run"} + + +def norm_status(s): + return _LEGACY.get(s, s) + + +def check_stats(results): + by, byv = {}, {} + for r in results: + if not isinstance(r, dict) or not r.get("check") or r.get("check") == "gate": + continue + keys = [("check", r["check"], by)] + if r.get("verifier"): + keys.append(("verifier", r["verifier"], byv)) + for _, k, d in keys: + s = d.setdefault(k, {"runs": 0, "failures": 0, "not_run": 0, + "total_s": 0.0, "timed_runs": 0}) + s["runs"] += 1 + if isinstance(r.get("duration_s"), (int, float)) and not isinstance(r.get("duration_s"), bool): + s["total_s"] += r["duration_s"] + s["timed_runs"] += 1 + s["tier"] = r.get("tier", "fast") + st = norm_status(r.get("status")) + if st == "failed": + s["failures"] += 1 + elif st == "not-run": + s["not_run"] += 1 + def fin(d): + out = [] + for k, s in sorted(d.items()): + s = dict(s, id=k) + s["never_seen_failing"] = s["runs"] >= MANY_RUNS and s["failures"] == 0 and s["not_run"] == 0 + out.append(s) + return out + return {"checks": fin(by), "verifiers": fin(byv)} + + +# ---------------------------------------------------------------- escape candidates + +WEEK_S = 7 * 86400 +_FIXLIKE = re.compile(r"\b(fix|bug|broken|wrong|regress|revert|fails?|failing|doesn'?t work|not working|error|crash)", re.I) + + +def passed_runs(results): + """[{ts, t, project, contract, session, run}] for runs with a real pass and no failure. + A run of only skipped/not-run checks is not a pass: nothing that did not run passed.""" + groups = {} + for r in results: + if not isinstance(r, dict) or r.get("check") == "gate": + continue + key = r.get("run") or "%s|%s|%s" % (r.get("ts"), r.get("contract"), r.get("project")) + groups.setdefault(key, []).append(r) + out = [] + for key, rs in groups.items(): + sts = [norm_status(x.get("status")) for x in rs] + if any(s == "passed" for s in sts) and all(s in ("passed", "skipped", "not-applicable") for s in sts): + t = harvest.epoch(rs[0].get("ts") or "") + if t is not None: + out.append({"ts": rs[0]["ts"], "t": t, "project": rs[0].get("project"), "contract": rs[0].get("contract"), + "session": rs[0].get("session"), "run": key}) + return sorted(out, key=lambda x: x["t"]) + + +def _inside(path, parent): + if not path or not parent: + return False + p, q = path.rstrip("/"), parent.rstrip("/") + return p == q or p.startswith(q + "/") or q.startswith(p + "/") + + +def attribute(run, sessions): + if run["session"]: + hit = [s for s in sessions if s["id"] == run["session"]] + if hit: + return hit, False + hit = [s for s in sessions if s["t0"] is not None and s["t0"] <= run["t"] <= (s["t1"] or s["t0"]) + 60 + and (_inside(s["cwd"], run["project"]) or _inside(s["repo_root"], run["project"]))] + return hit, len(hit) > 1 + + +def escape_candidates(con, results=None): + results = store.read("results") if results is None else results + sessions = [dict(r) for r in con.execute( + "SELECT s.id, s.cwd, s.t0, s.t1, s.first_message, s.machine, g.repo_root, g.files, g.start_kind " + "FROM sessions s LEFT JOIN groundtruth g ON g.session_id=s.id WHERE s.kind='main'")] + out = [] + for run in passed_runs(results): + hit, ambiguous = attribute(run, sessions) + for s in hit: + later = con.execute("SELECT idx, ts, t FROM user_msgs WHERE session_id=? AND correction=1 AND t>? ORDER BY t", + (s["id"], run["t"])).fetchall() + for m in later[:3]: + out.append({"kind": "contract-then-correction", "session": s["id"], "run": run["run"], "contract": run["contract"], + "passed_at": run["ts"], "evidence": {"user_msg_idx": m["idx"], "at": m["ts"]}, "ambiguous": ambiguous}) + files = set(json.loads(s["files"] or "[]")) + if files and s["repo_root"]: + for o in sessions: + if o["id"] == s["id"] or o["repo_root"] != s["repo_root"] or o["machine"] or o["t0"] is None: + continue + if not (run["t"] < o["t0"] <= run["t"] + WEEK_S): + continue + common = files & set(json.loads(o["files"] or "[]")) + if common and _FIXLIKE.search((o["first_message"] or "")[:1500]): + out.append({"kind": "contract-then-fix-session", "session": s["id"], "run": run["run"], + "contract": run["contract"], "passed_at": run["ts"], + "evidence": {"later_session": o["id"], "common_files": sorted(common)[:10]}, + "ambiguous": ambiguous}) + for r in con.execute("SELECT m.session_id, m.idx, m.ts FROM user_msgs m WHERE m.correction=1 AND m.after_completion=1 ORDER BY m.t"): + out.append({"kind": "premature-done", "session": r["session_id"], "evidence": {"user_msg_idx": r["idx"], "at": r["ts"]}, + "ambiguous": False}) + return out + + +# ---------------------------------------------------------------- the eight dimensions + +def _latest_by_check(results): + out = {} + for r in results: + if isinstance(r, dict) and (r.get("check") or r.get("id")): + out[r.get("check") or r.get("id")] = r + return out + + +def build_scorecard(c, results, telemetry, delivery_status): + """The scorecard stored in the unit record. `results` are the unit's recorded result rows + (any dicts with check/status/duration_s, store rows or fresh verify results).""" + latest = _latest_by_check(results) + by_status = {} + for r in latest.values(): + by_status[norm_status(r.get("status"))] = by_status.get(norm_status(r.get("status")), 0) + 1 + items = {x.get("id"): x for x in (c.get("checks") or []) + (c.get("invariants") or []) if isinstance(x, dict)} + + reqs = [r for r in (c.get("requirements") or []) if isinstance(r, dict)] + with_check = [r for r in reqs if r.get("check")] + passing = sum(1 for r in with_check + if norm_status((latest.get(r["check"]) or {}).get("status")) == "passed") + first_ts = min((r["ts"] for r in results if isinstance(r, dict) and isinstance(r.get("ts"), str)), default=None) + if first_ts and any(isinstance(r.get("added"), str) for r in reqs): + surprise = val(sum(1 for r in reqs if isinstance(r.get("added"), str) and r["added"] > first_ts), "measured") + else: + surprise = unavailable() + tel = telemetry or {} + def T(key): + return tel.get(key) or unavailable() + tokens = T("tokens_by_category") + total_tokens = val(tokens["value"]["total"], "measured") if tokens["class"] == "measured" \ + and isinstance(tokens.get("value"), dict) else unavailable() + + return { + "intent_fulfilment": { + "requirements_total": val(len(reqs), "measured") if "requirements" in c else unavailable(), + "requirements_with_passing_check": val(passing, "measured") if with_check else unavailable(), + "requirements_added_after_first_verification": surprise, + "human_corrections": T("human_corrections"), + }, + "correctness_and_assurance": { + "results_by_status": val(by_status, "measured"), + "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"), + "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"), + "unverified": val(delivery_status == "unverified", "measured"), + }, + "delivery_velocity": { + "time_to_first_useful_result_s": T("time_to_first_useful_result_s"), + "time_to_validated_completion_s": T("time_to_validated_completion_s"), + "time_in_checks_s": T("time_in_checks_s"), + "time_in_waits_s": T("time_in_waits_s"), + "time_in_delegations_s": T("time_in_delegations_s"), + }, + "resource_efficiency": { + "tokens_by_category": tokens, + "tokens_by_model": T("tokens_by_model"), + "tokens_total": total_tokens, + "cost": T("cost"), + "retries": T("send_backs"), + }, + "parallelism": { + "delegations": T("delegations"), + "overlapped_delegations": T("overlapped_delegations"), + "worker_minutes": T("worker_minutes"), + "wall_time_s": T("time_to_validated_completion_s"), + }, + "human_experience": { + "human_messages": T("human_messages"), + "question_dialogs": T("question_dialogs"), + "human_corrections": T("human_corrections"), + }, + "lifecycle_quality": { + "files_changed": T("files_changed"), + "lines_changed": T("lines_changed"), + "tests_changed_with_code": T("tests_changed_with_code"), + "public_surface_touched": T("public_surface_touched"), + }, + "organizational_improvement": { + "findings": T("retro_findings"), + "learnings_created": T("learnings_created"), + "recurrences": T("recurrences"), + }, + } + + +# ---------------------------------------------------------------- `sisi status` + +def load_unit_summaries(cwd=None): + """Closed-unit summary lines from the user store, merged with this project's archived + records (deduped by project+id; the archive wins). Returns dicts, oldest first.""" + units = {} + for r in store.read("units"): + if isinstance(r, dict) and r.get("id"): + units[(r.get("project"), r["id"])] = r + try: + from . import contract as C + p = C.find(cwd or os.getcwd()) + proj = C.project_dir(p) if p else None + if proj: + d = os.path.join(proj, ".sisi", "units") + for n in sorted(os.listdir(d)) if os.path.isdir(d) else []: + if not n.endswith(".json"): + continue + try: + with open(os.path.join(d, n), encoding="utf-8") as f: + rec = json.load(f) + except (OSError, ValueError): + continue + if isinstance(rec, dict) and rec.get("id"): + units[(rec.get("project") or proj, rec["id"])] = rec + except Exception: + pass + return sorted(units.values(), key=lambda r: str(r.get("ended") or r.get("started") or "")) + + +def _num(v): + x = v.get("value") if isinstance(v, dict) else None + return float(x) if isinstance(x, (int, float)) and not isinstance(x, bool) else None + + +def _metric(unit, *path): + cur = unit.get("scorecard") or {} + for k in path: + cur = cur.get(k) if isinstance(cur, dict) else None + return _num(cur) if cur is not None else None + + +_TREND_METRICS = (("validated completion (s)", ("delivery_velocity", "time_to_validated_completion_s")), + ("first useful result (s)", ("delivery_velocity", "time_to_first_useful_result_s")), + ("time in checks (s)", ("delivery_velocity", "time_in_checks_s")), + ("tokens", ("resource_efficiency", "tokens_total")), + ("human corrections", ("human_experience", "human_corrections")), + ("files changed", ("lifecycle_quality", "files_changed"))) + + +def _pct(xs, p): + s = sorted(xs) + if not s: + return None + k = (len(s) - 1) * p / 100.0 + lo = int(k) + hi = min(lo + 1, len(s) - 1) + return s[lo] + (s[hi] - s[lo]) * (k - lo) + + +def trends(units): + """{segment_kind: {segment: {metric: {n, median, p95} or 'too few'}}} by project, risk + profile, model and policy version. Segments under five units say so; no single score.""" + def seg_of(u, kind): + if kind == "project": + return os.path.basename(str(u.get("project") or "").rstrip("/")) or "(unknown project)" + if kind == "risk profile": + return ((u.get("risk") or {}).get("declared") or (u.get("risk") or {}).get("profile") + or "(none recorded)") + if kind == "model": + models = u.get("models") or [] + return ", ".join(models) if isinstance(models, list) and models else "(no model recorded)" + return str(u.get("policy_version") or "(none recorded)")[:12] + out = {} + for kind in ("project", "risk profile", "model", "policy version"): + groups = {} + for u in units: + groups.setdefault(str(seg_of(u, kind)), []).append(u) + seg_out = {} + for seg, us in sorted(groups.items()): + if len(us) < 5: + seg_out[seg] = "too few" + continue + m = {} + for name, path in _TREND_METRICS: + xs = [x for x in (_metric(u, *path) for u in us) if x is not None] + m[name] = {"n": len(xs), "median": _pct(xs, 50), "p95": _pct(xs, 95)} if xs else "unavailable" + seg_out[seg] = m + out[kind] = seg_out + return out + + +def _fmt_val(v): + if not isinstance(v, dict) or v.get("class") == "unavailable" or v.get("value") is None: + return "unavailable" + x = v["value"] + if isinstance(x, bool): + return "yes" if x else "no" + if isinstance(x, float): + return "%g" % x + if isinstance(x, dict): + return ", ".join("%s=%s" % kv for kv in sorted(x.items(), key=lambda kv: str(kv[0]))) or "-" + if isinstance(x, list): + return ", ".join(str(i) for i in x) or "-" + return str(x) + + +def format_dimension(dim, vals): + shown = ["%s %s (%s)" % (k, _fmt_val(v), v.get("class")) for k, v in vals.items() + if isinstance(v, dict) and v.get("class") != "unavailable"] + n_un = sum(1 for v in vals.values() if isinstance(v, dict) and v.get("class") == "unavailable") + return " %s: %s%s" % (dim.replace("_", " "), "; ".join(shown) or "nothing recorded", + ("; %d unavailable" % n_un) if n_un else "") + + +def format_status(units, learning=False, recent=5): + lines = [] + if not units: + lines.append("sisi status: no closed work units yet. Close one with `sisi unit close`; " + "its scorecard will appear here.") + else: + 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 "")) + sc = u.get("scorecard") or {} + for dim, vals in sc.items(): + lines.append(format_dimension(dim, vals)) + lines.append("") + lines.append("trends (median / p95; segments under five units say 'too few'):") + for kind, segs in trends(units).items(): + lines.append(" by %s:" % kind) + for seg, m in segs.items(): + if m == "too few": + lines.append(" %-28s too few" % seg[:28]) + else: + cells = ["%s %s/%s (n=%d)" % (name, ("%g" % v["median"]) if v != "unavailable" else "unavailable", + ("%g" % v["p95"]) if v != "unavailable" else "-", + v["n"] if v != "unavailable" else 0) + for name, v in m.items()] + lines.append(" %-28s %s" % (seg[:28], "; ".join(cells))) + if learning: + lines.append("") + try: + from . import learning as _L + lines.append(_L.learning_report()) + except Exception as e: + store.log_error("status-learning", e) + lines.append("learning: unavailable (%s)" % e) + return "\n".join(lines) + + +def cmd_status(args=(), cwd=None, out=print): + units = load_unit_summaries(cwd) + if "--json" in args: + out(json.dumps({"units": units, "trends": trends(units)}, indent=2, default=str)) + return 0 + out(format_status(units, learning="--learning" in args)) + return 0 diff --git a/sisi/store.py b/sisi/store.py index 1e214ec..12b2b85 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"} + "deliveries": "deliveries.jsonl", "units": "units.jsonl"} def _migrate_learn(): @@ -82,7 +82,7 @@ def session_id(): return os.environ.get("SISI_SESSION_ID") or None -PERSONAL = ("learn", "quarantine") # what the person told or taught sisi: personal data, the rest is scratch +PERSONAL = ("learn", "quarantine", "units") # what the person told or taught sisi: personal data, the rest is scratch def file_path(name): @@ -156,7 +156,9 @@ def stamp(extra): DEFAULTS = {"gate": {"enabled": True, "budget_s": 120, "max_blocks": 3, "growth_lines": 40, "growth_files": 3}, "verify": {"default_timeout_s": 60, "fast_limit_s": 60}, - "retro": {"required": True}} + "retro": {"required": True}, + "scratch": {"session_max_age_days": 30, "prune_every": 20, "prune_max_delete": 1000, + "prune_budget_s": 0.25}} def config(): @@ -204,6 +206,76 @@ def save_session(sid, rec): os.replace(tmp, p) +def _transcript_alive(session_file, cutoff): + """True when the transcript this session record names was written to since `cutoff`: the + session is still going on in the host even though sisi has not touched its record.""" + try: + with open(session_file, encoding="utf-8") as f: + tp = json.load(f).get("transcript_path") + return isinstance(tp, str) and os.stat(os.path.expanduser(tp)).st_mtime >= cutoff + except (OSError, ValueError, AttributeError): + return False + + +def prune_sessions(now=None, active_ids=(), force=False): + """Remove session-state files older than the configured age. Runs on a counter kept in + scratch (every Nth session start, first run included), never on a scheduler. Bounded: + stops after the configured time budget or deletion count, and a later start continues. + Never deletes the file of a session named active (callers pass the current session's id) + nor of one whose transcript the host has written to within the age. Returns the number + of files removed.""" + cfg = config().get("scratch", {}) + d = os.path.join(paths.state(), "sessions") + counter_file = os.path.join(d, ".prune-counter") + count = 0 + try: + with open(counter_file, encoding="utf-8") as f: + count = int(f.read().strip() or 0) + except (OSError, ValueError): + count = 0 + count += 1 + try: + os.makedirs(d, exist_ok=True) + with open(counter_file, "w", encoding="utf-8") as f: + f.write(str(count)) + except OSError: + pass + every = max(1, int(cfg.get("prune_every", 20))) + if not force and (count - 1) % every != 0: + return 0 # not this start's turn: the first start and every Nth after it sweep + now = time.time() if now is None else now + cutoff = now - float(cfg.get("session_max_age_days", 30)) * 86400 + keep = {safe_id(s) + ".json" for s in active_ids if s} + budget = float(cfg.get("prune_budget_s", 0.25)) + max_delete = int(cfg.get("prune_max_delete", 1000)) + removed, deadline, unfinished = 0, time.time() + budget, False + try: + with os.scandir(d) as it: + for e in it: + if removed >= max_delete or time.time() > deadline: + unfinished = True + break + if not e.name.endswith(".json") or e.name in keep: + continue + try: + if e.is_file(follow_symlinks=False) and e.stat().st_mtime < cutoff: + if _transcript_alive(e.path, cutoff): + continue # the host is still writing this session's transcript + os.unlink(e.path) + removed += 1 + except OSError: + pass + except OSError: + pass + if unfinished: # out of budget with files left: the next start continues the sweep + try: + with open(counter_file, "w", encoding="utf-8") as f: + f.write("0") + except OSError: + pass + return removed + + def log_error(where, exc): try: append("errors.log", {"ts": now(), "where": where, "error": repr(exc)}) diff --git a/sisi/taskset.py b/sisi/taskset.py index 3e7f98c..f7a834a 100644 --- a/sisi/taskset.py +++ b/sisi/taskset.py @@ -299,10 +299,3 @@ def benchmark_cases(con): out.append(case) return out - -def counts(con): - """{kind: {grade: {split: n}}} for the scoreboard.""" - out = {} - for r in con.execute("SELECT kind, COALESCE(grade,'-') g, split, COUNT(*) n FROM tasks GROUP BY 1,2,3"): - out.setdefault(r["kind"], {}).setdefault(r["g"], {})[r["split"]] = r["n"] - return out diff --git a/sisi/tick.py b/sisi/tick.py index 7f70b6d..e5fa593 100644 --- a/sisi/tick.py +++ b/sisi/tick.py @@ -7,21 +7,9 @@ from . import store MAX_AGE_S = 30 * 86400 -def _prune(now=None): - """Delete per-session state files untouched for 30 days.""" - from . import paths - d = os.path.join(paths.state(), "sessions") - cutoff = (now or time.time()) - MAX_AGE_S - try: - with os.scandir(d) as it: - for e in it: - if e.name.endswith(".json") and e.is_file(follow_symlinks=False) and e.stat().st_mtime < cutoff: - try: - os.unlink(e.path) - except OSError: - pass - except OSError: - pass +def _prune(now=None, sid=None): + """Delete old per-session state files, bounded and on a counter (see store.prune_sessions).""" + return store.prune_sessions(now=now, active_ids=(sid,) if sid else ()) def _export_session(sid): @@ -95,7 +83,7 @@ def main(args=()): rec["baseline"] = gitutil.measure(cwd) rec["baseline_fp"] = gitutil.fingerprint(cwd, [C.find(cwd)]) store.save_session(sid, rec) - _prune() + _prune(sid=sid) from . import wiring problem = wiring.quick_problem() if problem: diff --git a/sisi/unit.py b/sisi/unit.py new file mode 100644 index 0000000..fe68f17 --- /dev/null +++ b/sisi/unit.py @@ -0,0 +1,800 @@ +"""The durable work-unit record: close, pause, show, list. + +The open unit is `.sisi/contract.json`. Closing archives the full record to +`.sisi/units/.json` in the project (exclusive create: never overwritten) and appends +one summary line to the user store's `units.jsonl`, then marks the contract closed so a +new unit may replace it. Re-running close after a crash at any step converges without +duplicating or losing a record. +""" +import hashlib, json, os, time + +from . import contract as C, gitutil, harvest, paths, scorecard, store +from .scorecard import unavailable, val + +DELIVERY_STATUSES = ("delivered", "delivered-with-deferred", "deviation", "unverified", "abandoned") # the five of SPEC 10.3 + + +def is_closed(c): + return isinstance(c, dict) and c.get("status") == "closed" + + +def archive_path(project, uid): + return os.path.join(project, ".sisi", "units", "%s.json" % store.safe_id(uid)) + + +def list_archives(project): + d = os.path.join(project, ".sisi", "units") + out = [] + try: + names = sorted(os.listdir(d)) + except OSError: + return out + for n in names: + if n.endswith(".json"): + try: + with open(os.path.join(d, n), encoding="utf-8") as f: + out.append(json.load(f)) + except (OSError, ValueError): + pass + return out + + +def fresh_id(base, project): + """A unit id not already used by an archived or summarised unit in this project.""" + used = {r.get("id") for r in list_archives(project)} + used |= {r.get("id") for r in store.read("units") if isinstance(r, dict) and r.get("project") == project} + if base not in used: + return base + n = 2 + while "%s-%d" % (base, n) in used: + n += 1 + return "%s-%d" % (base, n) + + +# ---------------------------------------------------------------- sources the record draws on + +def _git_diff_text(project, base): + import subprocess + top = gitutil.root(project) + if not top: + return "" + try: + p = subprocess.run(["git", "diff", "--no-ext-diff", base or gitutil.head(top) or gitutil.EMPTY_TREE, + "--", ".", ":(exclude).sisi"], cwd=top, capture_output=True, timeout=10) + return p.stdout.decode("utf-8", "replace")[:200000] + except Exception: + return "" + + +def risk_floor(c, project): + """The risk floor from what changed since the unit started (committed or not), by the + product's and the project's risk table. Unavailable outside a repository.""" + ch = _changed_artifacts(c, project) + if ch is None: + return unavailable(), [] + try: + from . import risk + profile, reasons = risk.assess(ch["files"], diff_text=_git_diff_text(project, c.get("base_head")), + patterns=risk.load_patterns(project)) + return val(profile, "measured"), list(reasons) + except Exception as e: + store.log_error("unit-risk-floor", e) + return unavailable(), [] + + +def retro_findings(c, project): + """The retro findings recorded for this unit (the learning store holds them).""" + try: + from . import learning + return learning.findings_for_unit(project, c.get("id")) + except Exception as e: + store.log_error("unit-findings", e) + return [] + + +def learning_activity(c, project): + """(ids of learnings this unit created, count of recurrences it recorded).""" + try: + from . import learning + pk = learning.project_key(project) + made, rec = [], 0 + for r in learning.load_learnings(): + if r.get("source_unit") == c.get("id") and r.get("origin_project") == pk: + made.append(r.get("id")) + for pv in r.get("provenance") or []: + if isinstance(pv, dict) and pv.get("kind") == "recurrence" \ + and pv.get("unit") == c.get("id") and pv.get("project") == pk: + rec += 1 + return made, rec + except Exception as e: + store.log_error("unit-learnings", e) + return [], None + + +def delegations(project, t0, t1): + """The ledger's attempts for this project inside the unit's window, from the orchestration + record. The ledger names a project by its folder name. None when it cannot be read.""" + if t0 is None: + return None + try: + from . import workers + return workers.delegations_for_project(os.path.basename(project.rstrip(os.sep)), t0, t1) + except Exception as e: + store.log_error("unit-delegations", e) + return None + + +def _row_epoch(r): + for k in ("ts", "t", "started", "ended", "time"): + v = r.get(k) + if isinstance(v, (int, float)) and not isinstance(v, bool): + return float(v) + if isinstance(v, str): + t = harvest.epoch(v) + if t is not None: + return t + return None + + +def policy_version(project, c): + """Hash of the policies in force: the effective rulebook, the floors and 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")), + ("risk table", paths.canon("risk.json")), + ("project risk table", os.path.join(project, ".sisi", "risk.json"))): + try: + with open(p, "rb") as f: + h.update(role.encode() + b"\0" + f.read() + b"\0") + except OSError: + h.update(role.encode() + b"\0missing\0") + try: + from . import cycle + h.update(json.dumps(cycle.load_enforced(), sort_keys=True, default=str).encode()) + except Exception: + h.update(b"\0enforced-unavailable\0") + cfg = store.config() + h.update(json.dumps({k: cfg.get(k) for k in ("gate", "verify")}, sort_keys=True, default=str).encode()) + return h.hexdigest() + + +# ---------------------------------------------------------------- telemetry + +def _unit_results(c, project, t0_iso): + rows = [] + for r in store.read("results"): + if not isinstance(r, dict) or r.get("contract") != c.get("id") or r.get("project") != project: + continue + if t0_iso and isinstance(r.get("ts"), str) and r["ts"] < t0_iso: + continue + rows.append(r) + return rows + + +def _transcript_stats(project, t0, t1): + """Aggregated transcript stats from session records for this project in the window. + Returns None when no readable transcript was found at all.""" + cands = [] + sid = store.session_id() + sids = [sid] if sid else [] + d = os.path.join(paths.state(), "sessions") + try: + names = [n for n in os.listdir(d) if n.endswith(".json")] + except OSError: + names = [] + # newest first, bounded: session files far outside the window cannot belong to the unit + entries = [] + for n in names: + try: + entries.append((os.path.getmtime(os.path.join(d, n)), n)) + except OSError: + pass + entries.sort(reverse=True) + names = [n for m, n in entries if t1 is None or m >= t1 - 7 * 86400][:200] + for n in names: + rec = store.load_session(n[:-5]) + tp, cwd = rec.get("transcript_path"), rec.get("cwd") + if isinstance(tp, str) and isinstance(cwd, str) and (cwd == project or cwd.startswith(project + os.sep)): + cands.append(tp) + if sid: + tp = store.load_session(sid).get("transcript_path") + if isinstance(tp, str) and tp not in cands: + cands.append(tp) + agg = None + for tp in cands: + st = harvest.transcript_stats(tp, t0, t1) + if st is None: + continue + if agg is None: + agg = {"usage": None, "human_messages": 0, "corrections": 0, "question_dialogs": 0, "subagent_runs": 0} + for k in ("human_messages", "corrections", "question_dialogs", "subagent_runs"): + agg[k] += st[k] + if st["usage"]: + if agg["usage"] is None: + agg["usage"] = {"by_category": {}, "by_model": {}} + for cat, v in st["usage"]["by_category"].items(): + if cat != "total": + agg["usage"]["by_category"][cat] = agg["usage"]["by_category"].get(cat, 0) + v + for model, slot in st["usage"]["by_model"].items(): + dst = agg["usage"]["by_model"].setdefault(model, {}) + for cat, v in slot.items(): + if cat != "total": + dst[cat] = dst.get(cat, 0) + v + if agg is not None and agg["usage"]: + agg["usage"]["by_category"]["total"] = sum(agg["usage"]["by_category"].values()) + for slot in agg["usage"]["by_model"].values(): + slot["total"] = sum(slot.values()) + return agg + + +def build_telemetry(c, project, results, t0, t1): + """Every value classed. Sources: deliveries, results, pauses on the contract, the + host transcript where a session record names one, git, and the delegation ledger.""" + tel = {} + tel["time_to_validated_completion_s"] = val(round(t1 - t0, 1), "measured") if t0 is not None else unavailable() + if results: + tel["time_in_checks_s"] = val(round(sum(float(r["duration_s"]) for r in results + if isinstance(r.get("duration_s"), (int, float))), 3), "measured") + else: + tel["time_in_checks_s"] = unavailable() + if isinstance(c.get("pauses"), list): + waits = 0.0 + for p in c["pauses"]: + if not isinstance(p, dict): + continue + a = harvest.epoch(p["since"]) if isinstance(p.get("since"), str) else None + b = harvest.epoch(p["until"]) if isinstance(p.get("until"), str) else t1 + if a is not None and b is not None and b > a: + waits += b - a + tel["time_in_waits_s"] = val(round(waits, 1), "measured") + else: + tel["time_in_waits_s"] = unavailable() + + deliveries = [] + for r in store.read("deliveries"): + if not isinstance(r, dict): + continue + end = harvest.epoch(r["end"]) if isinstance(r.get("end"), str) else None + if end is not None and t0 is not None and t0 <= end <= t1 and \ + (r.get("project") in (project, None) or str(r.get("project", "")).startswith(project)): + deliveries.append((end, r)) + if deliveries: + tel["time_to_first_useful_result_s"] = val(round(min(e for e, _ in deliveries) - t0, 1), "measured") + tel["send_backs"] = val(sum(int(r.get("send_backs", 0)) for _, r in deliveries), "measured") + else: + first_pass = None + runs = {} + for r in results: + runs.setdefault(r.get("run"), []).append(r) + for run_rows in runs.values(): + sts = [scorecard.norm_status(r.get("status")) for r in run_rows] + if any(s == "passed" for s in sts) and all(s in ("passed", "skipped", "not-applicable") for s in sts): + ts = harvest.epoch(run_rows[0]["ts"]) if isinstance(run_rows[0].get("ts"), str) else None + if ts is not None and t0 is not None: + first_pass = ts if first_pass is None else min(first_pass, ts) + tel["time_to_first_useful_result_s"] = val(round(first_pass - t0, 1), "inferred") if first_pass else unavailable() + tel["send_backs"] = unavailable() + + stats = _transcript_stats(project, t0, t1) + if stats is None: + for k in ("human_messages", "question_dialogs", "human_corrections", + "tokens_by_category", "tokens_by_model"): + tel[k] = unavailable() + models = [] + else: + tel["human_messages"] = val(stats["human_messages"], "measured") + tel["question_dialogs"] = val(stats["question_dialogs"], "measured") + tel["human_corrections"] = val(stats["corrections"], "inferred") + if stats["usage"]: + tel["tokens_by_category"] = val(stats["usage"]["by_category"], "measured") + tel["tokens_by_model"] = val(stats["usage"]["by_model"], "measured") + models = sorted(stats["usage"]["by_model"]) + else: # the transcript has no usage numbers: tokens are unavailable, never zero + tel["tokens_by_category"] = unavailable() + tel["tokens_by_model"] = unavailable() + models = [] + tel["cost"] = _estimated_cost(tel.get("tokens_by_model")) + + dg = delegations(project, t0, t1) + if dg is None: + for k in ("delegations", "overlapped_delegations", "worker_minutes", "time_in_delegations_s"): + tel[k] = unavailable() + rows = [] + else: + rows = dg["delegations"] + tel["delegations"] = val(dg["count"], "measured") + if dg["count"]: + tel["worker_minutes"] = val(round(dg["worker_minutes"], 1), "estimated") + tel["time_in_delegations_s"] = val(round(dg["wall_minutes"] * 60, 1), "estimated") + tel["overlapped_delegations"] = val(dg["overlapping_pairs"], "inferred") + else: + tel["worker_minutes"] = val(0, "measured") + tel["time_in_delegations_s"] = val(0, "measured") + tel["overlapped_delegations"] = val(0, "measured") + + changed = _changed_artifacts(c, project) + tel["files_changed"] = val(len(changed["files"]), "measured") if changed else unavailable() + tel["lines_changed"] = val(changed["lines"], "measured") if changed else unavailable() + if changed: + tests = [f for f in changed["files"] if _is_test(f)] + code = [f for f in changed["files"] if not _is_test(f)] + tel["tests_changed_with_code"] = val(bool(tests and code), "inferred") + tel["public_surface_touched"] = val(any(_is_public(f) for f in changed["files"]), "inferred") + else: + tel["tests_changed_with_code"] = unavailable() + tel["public_surface_touched"] = unavailable() + + findings = retro_findings(c, project) + learnings, recurrences = learning_activity(c, project) + tel["retro_findings"] = val(len(findings), "measured") + tel["learnings_created"] = val(len(learnings), "measured") + tel["recurrences"] = val(recurrences, "measured") if recurrences is not None else unavailable() + tel["_models"] = models + tel["_delegation_rows"] = rows + tel["_findings"] = findings + tel["_learnings"] = learnings + tel["_changed"] = changed + return tel + + +def _estimated_cost(tokens_by_model): + """Cost from the recorded price facts (`sisi workers fact`) and the measured tokens per model. + Estimated when every model used has a recorded price; unavailable otherwise, and when + there are no tokens to price. Never a guess at a missing price.""" + if not tokens_by_model or tokens_by_model.get("class") != "measured": + return unavailable() + try: + from . import workers + prices = workers.load_prices() + total = 0.0 + for model, slot in tokens_by_model["value"].items(): + cost = workers.estimate_cost(slot.get("total"), workers._price_for(prices, None, model, model)) + if cost is None: + return unavailable() + total += cost + return val(round(total, 6), "estimated") + except Exception as e: + store.log_error("unit-cost", e) + return unavailable() + + +def _is_test(f): + base = os.path.basename(f) + return base.startswith(("test_", "test-")) or base.endswith(("_test.py", "_test.go", ".test.js", ".spec.js")) \ + or "/tests/" in "/" + f + + +def _is_public(f): + return os.path.basename(f) in ("__init__.py",) or f.endswith(".pyi") or f.startswith(("include/", "public/")) + + +def _changed_artifacts(c, project): + if not gitutil.root(project): + return None + try: + return gitutil.measure(project, c.get("base_head")) + except Exception: + return None + + +# ---------------------------------------------------------------- the record + +def latest_results(c, rows): + """The standing result of every check and invariant of the contract, and of the floor and + enforced items of the latest fast run. A check with no record gets a synthesized `not-run`: + nothing that has no record of running is ever shown as passed. Each entry also says whether + the check ever passed in this unit, ever failed, and was waived.""" + ids = {x["id"] for x in (c.get("checks") or []) + (c.get("invariants") or []) + if isinstance(x, dict) and x.get("id")} + last_fast = None + for r in rows: + if r.get("tier", "fast") == "fast" and r.get("run"): + last_fast = r["run"] + waived = {d.get("check") for d in (c.get("deviations") or []) if isinstance(d, dict) and d.get("check")} + latest, ever_passed, ever_failed = {}, set(), set() + for r in rows: + cid = r.get("check") + if not cid or r.get("item") not in ("check", "invariant", "floor", "enforced"): + continue + if r["item"] in ("floor", "enforced"): + if r.get("run") != last_fast: + continue + elif cid not in ids: + continue # a check since removed from the contract no longer speaks for it + st = scorecard.norm_status(r.get("status")) + if st == "passed": + ever_passed.add(cid) + if st == "failed": + ever_failed.add(cid) + latest[cid] = {"item": r["item"], "id": cid, "status": st, "reason": r.get("reason"), + "duration_s": r.get("duration_s", 0.0), "mandatory": r.get("mandatory", True), + "tier": r.get("tier", "fast"), "ts": r.get("ts")} + for x in (c.get("checks") or []) + (c.get("invariants") or []): + if isinstance(x, dict) and x.get("id") and x["id"] not in latest: + latest[x["id"]] = {"item": "check", "id": x["id"], "status": "not-run", + "reason": "needs human" if x.get("rung") in (5, 6) else "never run", + "duration_s": 0.0, "mandatory": x.get("mandatory", True), + "tier": x.get("tier", "fast"), "ts": None} + out = [] + for cid, r in latest.items(): + r["ever_passed"] = cid in ever_passed + r["seen_failing"] = cid in ever_failed + r["waived"] = cid in waived + out.append(r) + return out + + +def _justified_by_selection(r): + """A check kept back because the change did not touch what it watches, where files it + watches exist. A watch that matches no file at all justifies nothing.""" + return r["status"] == "skipped" and str(r.get("reason") or "").startswith("not affected") + + +def never_run(latest): + """Mandatory checks that never ran to a pass in this unit and that nothing justifies + skipping. A unit with any of these cannot close as plainly delivered.""" + out = [] + for r in latest: + if r["item"] not in ("check", "invariant") or not r.get("mandatory", True): + continue + if r["ever_passed"] or _justified_by_selection(r): + continue + out.append(r) + return out + + +def decide_status(c, rows, abandon=None): + """(delivery status or None, blocking, unrun). None with blocking results means the unit + cannot close as delivered. A waiver or an abandonment is recorded as what it is.""" + from . import verify as V + latest = latest_results(c, rows) + block = V.blocking(latest) + unrun = never_run(latest) + if abandon is not None: + return "abandoned", block, unrun + if c.get("deviations"): + return "deviation", block, unrun + if block: + released = any(r.get("check") == "gate" and r.get("status") == "unverified" for r in rows) + return ("unverified" if released else None), block, unrun + if any(r["status"] == "not-run" for r in latest) or unrun or C.deferred_checks(c): + return "delivered-with-deferred", block, unrun + return "delivered", block, unrun + + +def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None, rows=None): + t0 = harvest.epoch(c["started"]) if isinstance(c.get("started"), str) else None + rows = _unit_results(c, project, c.get("started")) if rows is None else rows + tel = build_telemetry(c, project, rows, t0, ended_epoch) + models = tel.pop("_models") + delegation_rows = tel.pop("_delegation_rows") + changed = tel.pop("_changed") + findings = tel.pop("_findings") + learnings = tel.pop("_learnings") + ended = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(ended_epoch)) + "Z" + latest = latest_results(c, rows) + unrun = never_run(latest) + floor, floor_reasons = risk_floor(c, project) + declared = c.get("risk") or {} + rec = { + "id": c["id"], "parent": c.get("parent"), + "goal": c.get("goal"), "scope": c.get("scope") or {"in": [], "out": []}, + "project": project, + "requirements": c.get("requirements") or [], + "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"), + "blast_radius": declared.get("blast_radius"), "rollback": declared.get("rollback")}, + "approach": c.get("approach"), + "plan": c.get("plan") or [], + "workers": delegation_rows, + "models": models, "budgets": c.get("budgets"), + "started": c.get("started"), "ended": ended, "closed_at": ended, "telemetry": tel, + "start_commit": c.get("base_head"), + "closing_commit": gitutil.head(project) if gitutil.root(project) else None, + "summary": c.get("summary"), + "changed_artifacts": changed if changed is not None else {"files": [], "lines": None}, + "verification": rows, + "final_verification": latest, + "deferred": c.get("deferred") or [], + "deferred_checks": [r["id"] for r in latest if r["status"] == "not-run" + and str(r.get("reason") or "").startswith(("deferred", "needs human"))], + "never_run_mandatory": [{"id": r["id"], "status": r["status"], "reason": r.get("reason")} for r in unrun], + "limitations": c.get("limitations") or [], "open_risks": c.get("open_risks") or [], + "deviations": c.get("deviations") or [], "pauses": c.get("pauses") or [], + "delivery_status": delivery_status, + "abandon_reason": abandon_reason, + "policy_version": policy_version(project, c), + "retro_findings": findings, "learning_ids": learnings, + "contract": c, + } + rec["scorecard"] = scorecard.build_scorecard(c, rows, tel, delivery_status) + return rec + + +def summary_line(rec): + risk = rec.get("risk") or {} + floor = (risk.get("floor") or {}).get("value") if isinstance(risk.get("floor"), dict) else risk.get("floor") + return {"id": rec["id"], "parent": rec.get("parent"), "project": rec.get("project"), + "goal": rec.get("goal"), "delivery_status": rec.get("delivery_status"), + "risk": {"declared": risk.get("declared"), "floor": floor}, + "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")} + + +def _summary_exists(project, uid): + return any(isinstance(r, dict) and r.get("id") == uid and r.get("project") == project + for r in store.read("units")) + + +def archive_record(rec, project): + """Write the archive so that it appears whole or not at all and is never replaced: the + full text goes to a temporary file, which is then hard-linked into place (the link fails + if the archive exists). Returns (path, created). An existing archive stays byte for byte.""" + p = archive_path(project, rec["id"]) + os.makedirs(os.path.dirname(p), exist_ok=True) + tmp = "%s.tmp%d" % (p, os.getpid()) + with open(tmp, "w", encoding="utf-8") as f: + json.dump(rec, f, indent=2, default=str) + f.write("\n") + f.flush() + os.fsync(f.fileno()) + try: + try: + os.link(tmp, p) + except FileExistsError: + return p, False + except OSError: # a filesystem without hard links + try: + fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) + except FileExistsError: + return p, False + with os.fdopen(fd, "w", encoding="utf-8") as f, open(tmp, encoding="utf-8") as src: + f.write(src.read()) + return p, True + finally: + try: + os.unlink(tmp) + except OSError: + pass + + +def _capture_case(rec): + """Offer the closed unit to the evaluation harness as a benchmark case. Never stops a close.""" + try: + from . import evaluate + view = dict(rec) + view["fix_commit"] = rec.get("closing_commit") + view["request"] = rec.get("goal") + evaluate.capture_case(view) + except Exception as e: + store.log_error("unit-capture-case", e) + + +def close_unit(c, contract_path, project, abandon=None, now=None): + """Archive the open unit and mark the contract closed. Returns (record_or_None, message, ok). + Refuses with nothing written when verification blocks and no deviation, gate release or + abandonment accounts for it. Safe to repeat after a crash at any step: an archive that + exists is kept as it stands and the remaining steps are completed.""" + ended_epoch = time.time() if now is None else now + rows = _unit_results(c, project, c.get("started")) # under the id the results were recorded with + path = archive_path(project, c["id"]) + if os.path.exists(path): + try: + with open(path, encoding="utf-8") as f: + old = json.load(f) + except (OSError, ValueError): + old = None + if is_closed(c): + return None, "unit %s is already closed (%s); nothing changed" % (c["id"], path), True + if isinstance(old, dict) and old.get("started") == c.get("started") and old.get("project") == project: + rec, created = old, False # a crash after archiving: complete the close from it + else: + c["id"] = fresh_id(c["id"], project) # another unit owns this id: never overwrite it + path = archive_path(project, c["id"]) + rec = None + else: + rec = None + if rec is None: + status, block, _ = decide_status(c, rows, abandon) + if status is None: + bad = ", ".join("%s (%s%s)" % (r["id"], r["status"], ": " + r["reason"] if r.get("reason") else "") + for r in block) + return None, ("sisi: unit %s cannot close as delivered: %s. Fix and re-run `sisi verify`, " + "record a deviation with `sisi contract waive \"\"`, or close it with " + "`sisi unit close --abandon \"\"`." % (c["id"], bad)), False + rec = build_record(c, project, status, ended_epoch, abandon_reason=abandon, rows=rows) + _, created = archive_record(rec, project) + if created: + _capture_case(rec) + if not _summary_exists(project, rec["id"]): + store.append("units", summary_line(rec)) + c["status"] = "closed" + c["ended"] = rec.get("ended") + c["delivery_status"] = rec.get("delivery_status") + for pz in c.get("pauses") or []: + if isinstance(pz, dict) and not pz.get("until"): + pz["until"] = rec.get("ended") + C.save(contract_path, c) + return rec, "closed unit %s (%s): %s" % (rec["id"], rec.get("delivery_status"), path), True + + +def resume(c, contract_path): + """End a recorded wait: the unit is open again and the wait's length is recorded.""" + if c.get("status") != "paused": + return False + for pz in c.get("pauses") or []: + if isinstance(pz, dict) and not pz.get("until"): + pz["until"] = store.now() + c["status"] = "open" + c.pop("pause_fp", None) + C.save(contract_path, c) + return True + + +def summary_for_retro(project): + """What `sisi retro` prints: the open unit's scorecard so far and what stands out in it.""" + p = os.path.join(project, C.REL) + try: + c = C.load(p) + except (OSError, ValueError): + return "" + if not isinstance(c, dict) or not c.get("id"): + return "" + now = time.time() + rows = _unit_results(c, project, c.get("started")) + latest = latest_results(c, rows) + tel = build_telemetry(c, project, rows, harvest.epoch(c["started"]) if isinstance(c.get("started"), str) else None, now) + for k in [k for k in tel if k.startswith("_")]: + tel.pop(k) + card = scorecard.build_scorecard(c, rows, tel, "open") + lines = ["unit %s (%s): %s" % (c["id"], c.get("status", "open"), c.get("goal") or ""), ""] + for dim, vals in card.items(): + lines.append(scorecard.format_dimension(dim, vals)) + out = [] + seen = [r["id"] for r in latest if r["seen_failing"] and r["status"] == "passed"] + if seen: + out.append("failed and then passed (the evidence is real): %s" % ", ".join(seen)) + failing = [r["id"] for r in latest if r["status"] == "failed"] + if failing: + out.append("still failing: %s" % ", ".join(failing)) + nr = never_run(latest) + if nr: + out.append("mandatory checks that never ran to a pass: %s" % ", ".join(r["id"] for r in nr)) + if c.get("deviations"): + out.append("a deviation was recorded: the unit cannot read as delivered") + hc = (tel.get("human_corrections") or {}).get("value") + if hc: + out.append("%s human correction(s) inferred from the transcript" % hc) + sb = (tel.get("send_backs") or {}).get("value") + if sb: + out.append("the gate sent the agent back %s time(s)" % sb) + unav = sorted(k for k, v in tel.items() if isinstance(v, dict) and v.get("class") == "unavailable") + if unav: + out.append("not measurable here (unavailable): %s" % ", ".join(unav)) + lines += ["", "what stands out:"] + ([" - " + x for x in out] or [" nothing in the record stands out"]) + lines += ["", "record each finding with `sisi retro --finding ... --cause ... --impact ... --disposition ...`; " + "then `sisi unit close` archives the unit."] + return "\n".join(lines) + "\n" + + +# ---------------------------------------------------------------- command + +def _open_contract(cwd, out): + p = C.find(cwd) + if not p: + out("sisi: no contract found (run `sisi contract init`)") + return None, None, None + try: + c = C.load(p) + except (OSError, ValueError) as e: + out("sisi: cannot read %s: %s" % (p, e)) + return None, None, None + return c, p, C.project_dir(p) + + +def cmd_unit(args, cwd=None, out=print): + cwd = cwd or os.getcwd() + sub = args[0] if args else "" + if sub == "close": + abandon = None + rest = list(args[1:]) + if "--abandon" in rest: + i = rest.index("--abandon") + abandon = rest[i + 1] if i + 1 < len(rest) else "" + if not str(abandon).strip(): + out('usage: sisi unit close [--abandon ""]') + return 1 + c, p, project = _open_contract(cwd, out) + if c is None: + return 2 + errs = C.validate(c) + if errs and abandon is None: + out("sisi: invalid contract %s; fix it, or close with --abandon" % p) + for e in errs: + out(" - " + e) + return 1 + rec, msg, ok = close_unit(c, p, project, abandon=abandon) + out(msg) + if rec is not None: + out("delivery status: %s" % rec.get("delivery_status")) + if rec.get("delivery_status") == "deviation": + out("a deviation was recorded; the completion report to the human must say so") + if rec.get("deferred_checks"): + out("deferred checks: %s" % ", ".join(rec["deferred_checks"])) + return 0 if ok else 1 + if sub == "pause": + what = " ".join(args[1:]).strip() + if not what: + out('usage: sisi unit pause ""') + return 1 + c, p, project = _open_contract(cwd, out) + if c is None: + return 2 + if is_closed(c): + out("sisi: unit %s is closed; start a new one with `sisi contract init`" % c.get("id")) + return 1 + pauses = c.setdefault("pauses", []) + open_pause = next((x for x in pauses if isinstance(x, dict) and not x.get("until")), None) + if open_pause is not None: + open_pause["what"] = what + else: + pauses.append({"what": what, "since": store.now(), "until": None}) + c["status"] = "paused" + c["pause_fp"] = gitutil.fingerprint(project) # a change to the tree ends the wait (see gate) + C.save(p, c) + out("unit %s paused: %s" % (c.get("id"), what)) + return 0 + if sub == "show": + uid = args[1] if len(args) > 1 else None + if uid is None: + c, p, project = _open_contract(cwd, out) + if c is None: + return 2 + out(json.dumps(c, indent=2)) + return 0 + p = C.find(cwd) + project = C.project_dir(p) if p else None + if project: + for rec in list_archives(project): + if rec.get("id") == uid: + out(json.dumps(rec, indent=2)) + return 0 + for r in store.read("units"): + if isinstance(r, dict) and r.get("id") == uid: + ap = archive_path(r.get("project") or project or cwd, uid) + if os.path.exists(ap): + with open(ap, encoding="utf-8") as f: + out(json.dumps(json.load(f), indent=2)) + else: + out(json.dumps(r, indent=2)) + return 0 + out("sisi: no unit record with id %r" % uid) + return 1 + if sub == "list": + p = C.find(cwd) + project = C.project_dir(p) if p else (gitutil.root(cwd) or cwd) + c = None + if p: + try: + c = C.load(p) + except (OSError, ValueError): + c = None + rows = [] + if project: + for rec in list_archives(project): + rows.append((rec.get("ended") or "", rec.get("id"), rec.get("delivery_status"), rec.get("goal") or "")) + if c is not None and not is_closed(c): + out("open %-24s %s" % (c.get("id"), c.get("goal") or "")) + for ended, uid, status, goal in sorted(rows, reverse=True): + out("%-8s %-24s %-24s %s" % (str(ended)[:10], uid, status, goal)) + if c is None and not rows: + out("no units in this project yet") + return 0 + out("usage: sisi unit close [--abandon \"\"] | pause \"\" | show [ID] | list") + return 1 diff --git a/sisi/verify.py b/sisi/verify.py index 1b3320c..5f3c427 100644 --- a/sisi/verify.py +++ b/sisi/verify.py @@ -1,9 +1,19 @@ -"""Run a contract: every check and invariant with a cmd, in the project dir, with a timeout.""" -import json, os, signal, subprocess, time +"""Run a contract: every selected check and invariant with a cmd, in the project dir, with a timeout. + +Five statuses only: passed, failed, skipped, not-applicable, not-run. A timeout is +not-run (timed out); a rung 5/6 check is not-run (needs human); a check kept back by +change selection is skipped (not affected by this change), or not-applicable when no +file it watches exists; an identical-inputs pass is skipped (reused: passed at