Records: the durable work-unit record, five verification statuses with selection and reuse, telemetry with honest classes, the scorecard and sisi status, scratch pruning

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-23 11:50:29 -07:00
commit 563cac426a
31 files changed
+3132 -783

No files matched your search

+14
View File
@@ -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
+1 -1
View File
@@ -142,4 +142,4 @@ check first and slow checks in the background while you carry on, never repeatin
inputs have not changed, and finding out why a slow step is slow instead of waiting on it.
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.
+1
View File
@@ -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 |
+70
View File
@@ -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
"<reason>"]`, `sisi unit pause "<what it waits for>"`, `sisi unit show [ID]` and
`sisi unit list`. `sisi help` lists them with the rest.
## The record
Closing writes `.sisi/units/<id>.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.
+121 -138
View File
@@ -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",
+62 -106
View File
@@ -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 "<reason>" 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] "<reason>"
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 "<reason>"]
archive the unit to .sisi/units/<id>.json with its scorecard; --abandon records why it stopped
sisi unit pause "<what it waits for>"
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 "<request>"` 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 \"<reason>\"`." % (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 "<reason>"')
print('usage: sisi contract waive [--check ID] "<reason>"')
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)
+252
View File
@@ -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
+2 -2
View File
@@ -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:
+2 -141
View File
@@ -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
-89
View File
@@ -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
+11 -2
View File
@@ -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
+12 -5
View File
@@ -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)))
+84
View File
@@ -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:
+7 -28
View File
@@ -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 <cmd>`. 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))
-100
View File
@@ -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)}
+392
View File
@@ -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
+75 -3
View File
@@ -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)})
-7
View File
@@ -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
+4 -16
View File
@@ -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:
+800
View File
@@ -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/<id>.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 \"<reason>\"`, or close it with "
"`sisi unit close --abandon \"<reason>\"`." % (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 "<reason>"]')
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 "<what it waits for>"')
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 \"<reason>\"] | pause \"<what it waits for>\" | show [ID] | list")
return 1
+275 -25
View File
@@ -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 <time>).
Nothing that did not run is ever reported as passed, on any path.
"""
import hashlib, json, os, signal, subprocess, time
from fnmatch import fnmatch
from pathlib import PurePosixPath
from . import contract as C, store
TAIL = 1500
STATUSES = ("passed", "failed", "skipped", "not-applicable", "not-run")
def _tail(s):
@@ -12,10 +22,10 @@ def _tail(s):
def run_cmd(cmd, cwd, timeout, expect):
"""Return (status, duration, tail). status: passed/failed/timeout."""
"""Return (status, duration, tail). status: passed/failed/not-run (a timeout never ran to a verdict)."""
t0 = time.time()
if timeout <= 0:
return "timeout", 0.0, "not run: time budget exhausted"
return "not-run", 0.0, "not run: time budget exhausted"
try:
p = subprocess.Popen(cmd, shell=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.DEVNULL, start_new_session=True)
@@ -32,7 +42,7 @@ def run_cmd(cmd, cwd, timeout, expect):
p.communicate(timeout=5)
except Exception:
pass
return "timeout", time.time() - t0, "timed out after %gs" % timeout
return "not-run", time.time() - t0, "timed out after %gs" % timeout
dur = time.time() - t0
o, e = out.decode("utf-8", "replace"), err.decode("utf-8", "replace")
tail = _tail(o + ("\n" if o and e else "") + e)
@@ -54,31 +64,205 @@ def tree_fp(project, contract_path):
return None
def match_path(path, pattern):
p = str(path).replace(os.sep, "/")
pat = str(pattern).replace(os.sep, "/")
if fnmatch(p, pat) or fnmatch(p, pat.rstrip("/") + "/*"):
return True
try:
return PurePosixPath(p).match(pat)
except ValueError:
return False
def project_files(project, limit=5000):
"""Relative paths in the project (git-tracked plus untracked, else a walk). Bounded."""
from . import gitutil
if gitutil.root(project):
try:
rc, out = gitutil._git(project, "ls-files", "-c", "-o", "--exclude-standard", "-z", timeout=10)
if rc == 0:
return [r for r in out.split("\0") if r][:limit]
except Exception:
pass
out = []
for dirpath, dirs, names in os.walk(project):
dirs[:] = [d for d in dirs if d != ".git"]
for n in names:
out.append(os.path.relpath(os.path.join(dirpath, n), project))
if len(out) >= limit:
return out
return out
def changed_paths(c, project):
"""Paths changed since the unit started (its base_head), or in the working tree vs HEAD.
None when it cannot be known: the caller then runs everything."""
from . import gitutil
if not gitutil.root(project):
return None
try:
return gitutil.measure(project, c.get("base_head"))["files"]
except Exception:
return None
# ---------------------------------------------------------------- reuse cache
def _cache_path():
from . import paths
return os.path.join(paths.state(), "verify-cache.json")
def _load_cache():
try:
with open(_cache_path(), encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except (OSError, ValueError):
return {}
def _save_cache(cache):
try:
p = _cache_path()
os.makedirs(os.path.dirname(p), exist_ok=True)
tmp = p + ".tmp%d" % os.getpid()
with open(tmp, "w", encoding="utf-8") as f:
json.dump(cache, f)
os.replace(tmp, p)
except OSError:
pass
def _cache_key(c, project, x):
raw = json.dumps([os.path.realpath(project), c.get("id"), x.get("id"), x.get("cmd"),
x.get("expect")], sort_keys=True, default=str)
return hashlib.sha1(raw.encode()).hexdigest()
def input_fingerprint(c, project, x, files=None, contract_path=None):
"""Hash of everything a check's verdict may depend on: its command and expectation, plus
the contents of the files its when_changed watches, or the whole tree when it has none.
None when it cannot be computed safely: no reuse then, the check runs."""
h = hashlib.sha256()
h.update(json.dumps([x.get("cmd"), x.get("expect")], sort_keys=True, default=str).encode())
wc = x.get("when_changed")
if not wc:
# the whole tree, but not the contract file: a pause, a note or a status change in the
# contract cannot change what a command shows, and must not defeat reuse
fp = tree_fp(project, None)
if fp is None:
return None
h.update(fp.encode())
return h.hexdigest()
files = project_files(project) if files is None else files
matched = sorted(f for f in files if any(match_path(f, p) for p in wc))
if len(matched) > 2000:
return None
for rel in matched:
try:
full = os.path.join(project, rel)
if os.path.getsize(full) > 10 * 1024 * 1024:
return None
with open(full, "rb") as fh:
h.update(rel.encode() + b"\0" + hashlib.sha256(fh.read()).digest())
except OSError:
h.update(rel.encode() + b"\0gone")
return h.hexdigest()
def _history(c, project):
"""Past results for this contract+project: seen-failing per check, last duration per check."""
seen_fail, last_dur = {}, {}
try:
rows = store.read("results")
except Exception:
rows = []
started = c.get("started")
for r in rows:
if not isinstance(r, dict) or r.get("contract") != c.get("id") or r.get("project") != project:
continue
if started and isinstance(r.get("ts"), str) and r["ts"] < started:
continue
if r.get("status") == "failed":
seen_fail[r.get("check")] = True
if isinstance(r.get("duration_s"), (int, float)):
last_dur[r.get("check")] = float(r["duration_s"])
return seen_fail, last_dur
MAX_PARALLEL = 4
def _run_item(item, x, tier, project, deadline, default_timeout):
r = {"item": item, "id": x["id"], "kind": x.get("kind"), "rung": x.get("rung"), "claim": x.get("claim"),
"tier": tier}
"tier": tier, "mandatory": x.get("mandatory", True), "independent": bool(x.get("independent", False)),
"covers": x.get("covers"), "reason": None, "saved_s": 0.0}
if x.get("rung") in (5, 6):
r.update(status="awaiting-human", duration_s=0.0, tail="")
r.update(status="not-run", reason="needs human", duration_s=0.0, tail="")
else:
to = float(x.get("timeout_s", default_timeout))
if deadline is not None:
to = min(to, deadline - time.time())
st, dur, tail = run_cmd(x["cmd"], project, to, x.get("expect", {"exit": 0}))
r.update(status=st, duration_s=round(dur, 3), tail=tail)
reason = None
if st == "not-run":
reason = "timed out" if tail.startswith("timed out") else tail.removeprefix("not run: ")
r.update(status=st, reason=reason, duration_s=round(dur, 3), tail=tail)
return r
def run(c, project, deadline=None, default_timeout=60, tiers=("fast",)):
"""Run the items of the given tiers. Returns list of result dicts (with 'tail'), in contract order.
deadline is a time.time() value. With top-level "parallel": true in the contract, fast-tier items run together
(at most MAX_PARALLEL at a time), except items marked "serial": true, which run alone afterwards."""
def _not_run_result(base_item, x, tier, status, reason, saved=0.0):
return {"item": base_item, "id": x["id"], "kind": x.get("kind"), "rung": x.get("rung"),
"claim": x.get("claim"), "tier": tier, "mandatory": x.get("mandatory", True),
"independent": bool(x.get("independent", False)), "covers": x.get("covers"),
"status": status, "reason": reason, "duration_s": 0.0, "tail": "", "saved_s": round(saved, 3)}
def run(c, project, deadline=None, default_timeout=60, tiers=("fast",), changed=None, reuse=True,
contract_path=None, run_all=False):
"""Run the items of the given tiers, with change selection and identical-input reuse.
Returns result dicts in contract order. `changed=None` means unknown: run everything.
A skipped or not-applicable result is recorded with its reason; it is never a pass."""
items = [("check", x) for x in c["checks"]] + [("invariant", x) for x in c.get("invariants", [])]
items = [(item, x, x.get("tier", "fast")) for item, x in items if x.get("tier", "fast") in tiers]
deferred = C.deferred_checks(c)
seen_fail, last_dur = _history(c, project)
cache = _load_cache() if reuse and not run_all else {}
files = None
if changed is None and not run_all:
changed = changed_paths(c, project)
res = [None] * len(items)
par = [i for i, (_, x, tier) in enumerate(items) if c.get("parallel") is True and tier == "fast" and not x.get("serial")]
fps = {}
for i, (item, x, tier) in enumerate(items):
if x["id"] in deferred:
res[i] = _not_run_result(item, x, tier, "not-run", "deferred: %s" % deferred[x["id"]].get("why", ""))
continue
if x.get("rung") in (5, 6):
continue # decided in _run_item: not-run (needs human)
wc = x.get("when_changed")
if wc and not run_all and changed is not None:
if files is None:
files = project_files(project)
if not any(match_path(f, p) for f in files for p in wc):
res[i] = _not_run_result(item, x, tier, "not-applicable",
"no file matches when_changed", last_dur.get(x["id"], 0.0))
continue
if not any(match_path(f, p) for f in changed for p in wc):
res[i] = _not_run_result(item, x, tier, "skipped",
"not affected by this change", last_dur.get(x["id"], 0.0))
continue
if reuse and not run_all:
fp = input_fingerprint(c, project, x, files, contract_path)
fps[i] = fp
hit = cache.get(_cache_key(c, project, x)) if fp else None
if hit and hit.get("fp") == fp and hit.get("status") == "passed":
res[i] = _not_run_result(item, x, tier, "skipped",
"reused: passed at %s" % hit.get("ts"), hit.get("duration_s", 0.0))
continue
par = [i for i, (_, x, tier) in enumerate(items)
if res[i] is None and c.get("parallel") is True and tier == "fast" and not x.get("serial")]
if len(par) > 1:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=MAX_PARALLEL) as ex:
@@ -89,50 +273,93 @@ def run(c, project, deadline=None, default_timeout=60, tiers=("fast",)):
for i, (item, x, tier) in enumerate(items):
if res[i] is None:
res[i] = _run_item(item, x, tier, project, deadline, default_timeout)
dirty_cache = False
for i, (item, x, tier) in enumerate(items):
r = res[i]
r["seen_failing"] = bool(seen_fail.get(x["id"])) or r["status"] == "failed"
if r["status"] == "passed" and reuse and not run_all:
fp = fps.get(i) or input_fingerprint(c, project, x, files, contract_path)
if fp:
cache[_cache_key(c, project, x)] = {"fp": fp, "status": "passed", "ts": store.now(),
"duration_s": r["duration_s"]}
dirty_cache = True
if dirty_cache:
_save_cache(cache)
for f in (C.floor_failures(c) if "fast" in tiers else []):
res.append({"item": "floor", "tier": "fast", "id": "floor:" + f["kind"], "kind": f["kind"], "rung": None,
"claim": f["message"], "status": "failed", "duration_s": 0.0, "tail": f["message"]})
"claim": f["message"], "status": "failed", "reason": None, "duration_s": 0.0,
"tail": f["message"], "mandatory": True, "independent": False, "covers": None,
"seen_failing": True, "saved_s": 0.0})
if "fast" in tiers: # enforced lessons ride the same path as floors (personal overlay, trusted commands)
try:
from . import cycle
res += cycle.enforced_results(c, project, deadline, default_timeout)
extra = cycle.enforced_results(c, project, deadline, default_timeout)
for r in extra:
r.setdefault("reason", None)
r.setdefault("mandatory", True)
r.setdefault("seen_failing", r.get("status") == "failed")
res += extra
except Exception as e:
store.log_error("enforced", e)
return res
def blocking(results):
"""Results that block delivery: any failure, or a mandatory not-run for a reason other
than a recorded deferral or needing a human."""
out = []
for r in results:
if r["status"] == "failed":
out.append(r)
elif r["status"] == "not-run" and r.get("mandatory", True):
reason = r.get("reason") or ""
if not (reason.startswith("deferred") or reason == "needs human"):
out.append(r)
return out
def ok(results):
return all(r["status"] in ("passed", "awaiting-human") for r in results)
return not blocking(results)
def record(c, project, results, fp=None):
run_id = "%x-%d" % (time.time_ns(), os.getpid())
for r in results:
store.append("results", {"ts": store.now(), "contract": c["id"], "project": project,
"check": r["id"], "item": r["item"], "kind": r["kind"], "rung": r["rung"],
"status": r["status"], "duration_s": r["duration_s"],
"check": r["id"], "item": r["item"], "kind": r.get("kind"), "rung": r.get("rung"),
"status": r["status"], "reason": r.get("reason"), "duration_s": r["duration_s"],
"seen_failing": bool(r.get("seen_failing")), "mandatory": r.get("mandatory", True),
"independent": bool(r.get("independent", False)), "covers": r.get("covers"),
"tool": store.tool(), "session": store.session_id(), "run": run_id,
"tier": r.get("tier", "fast"), "fp": fp})
return run_id
def format_table(results):
rows = [("ID", "KIND", "RUNG", "TIER", "STATUS", "SECS")]
for r in results:
rows.append((r["id"], r["kind"] or "-", str(r["rung"] or "-"), r.get("tier", "fast"), r["status"], "%.1f" % r["duration_s"]))
st = r["status"] + ((" (%s)" % r["reason"]) if r.get("reason") else "")
rows.append((r["id"], r["kind"] or "-", str(r["rung"] or "-"), r.get("tier", "fast"), st, "%.1f" % r["duration_s"]))
w = [max(len(row[i]) for row in rows) for i in range(6)]
return "\n".join(" ".join(v.ljust(w[i]) for i, v in enumerate(row)).rstrip() for row in rows)
def failure_report(results, limit=4000):
parts = []
bad = {id(r) for r in blocking(results)} | {id(r) for r in results if r["status"] == "failed"}
for r in results:
if r["status"] in ("failed", "timeout"):
parts.append("- %s %s [%s]: %s\n%s" % (r["item"], r["id"], r["status"], r.get("claim") or "",
if id(r) in bad:
label = r["status"] + ((": " + r["reason"]) if r.get("reason") else "")
parts.append("- %s %s [%s]: %s\n%s" % (r["item"], r["id"], label, r.get("claim") or "",
"\n".join(" " + l for l in (r["tail"] or "").splitlines()[-15:])))
s = "\n".join(parts)
return s if len(s) <= limit else s[:limit] + "\n... (truncated)"
def time_saved(results):
return round(sum(r.get("saved_s", 0.0) for r in results if r["status"] in ("skipped", "not-applicable")), 3)
def cmd_verify(args, cwd=None, out=print):
from . import deep, trust
cwd = cwd or os.getcwd()
@@ -195,7 +422,8 @@ def cmd_verify(args, cwd=None, out=print):
return 0
cfg = store.config()
try:
results = run(c, project, default_timeout=cfg["verify"]["default_timeout_s"], tiers=tiers)
results = run(c, project, default_timeout=cfg["verify"]["default_timeout_s"], tiers=tiers,
contract_path=path, run_all="--all" in args)
record(c, project, results, fp)
if locked:
deep.save_state(project, c["id"], fp, results, [x["id"] for x in deep.deep_items(c)])
@@ -204,17 +432,39 @@ def cmd_verify(args, cwd=None, out=print):
deep.release(project)
good = ok(results)
ds = deep.deep_state(c, project, fp)
saved = time_saved(results)
from . import unit as _unit
standing = _unit.latest_results(c, _unit._unit_results(c, project, c.get("started")))
unproven = [{"id": r["id"], "status": r["status"], "reason": r.get("reason")}
for r in _unit.never_run(standing) if r["status"] != "failed"] # failures are reported as failures
if c.get("status") == "paused":
_unit.resume(c, path) # work resumed: the wait is over
if as_json:
out(json.dumps({"contract": c["id"], "project": project, "ok": good, "tiers": list(tiers), "fingerprint": fp,
"deep_state": deep.public(ds), "results": results}, indent=2))
"deep_state": deep.public(ds), "time_saved_s": saved,
"never_run_mandatory": unproven, "results": results}, indent=2))
else:
if results:
out(format_table(results))
if not good:
out("\nFAILED:\n" + failure_report(results))
else:
waiting = [r["id"] for r in results if r["status"] == "awaiting-human"]
out("\nOK" + (" (awaiting human: %s)" % ", ".join(waiting) if waiting else ""))
waiting = [r["id"] for r in results if r["status"] == "not-run"]
out("\nOK" + ((" (not run: %s)" % ", ".join("%s %s" % (r["id"], r.get("reason") or "")
for r in results if r["status"] == "not-run")) if waiting else ""))
held_back = [r for r in results if r["status"] in ("skipped", "not-applicable")]
if held_back:
out("did not run (not a pass): " + "; ".join("%s %s (%s)" % (r["id"], r["status"], r.get("reason") or "")
for r in held_back))
if unproven:
out("no evidence yet: mandatory check(s) never ran to a pass: " +
", ".join("%s (%s)" % (u["id"], u["reason"] or u["status"]) for u in unproven) +
"; the unit cannot close as plainly delivered")
slow = sorted((r for r in results if r["duration_s"] > 0), key=lambda r: -r["duration_s"])[:3]
if slow:
out("slowest checks: " + ", ".join("%s %.1fs" % (r["id"], r["duration_s"]) for r in slow))
if saved:
out("time saved by selection and reuse: %.1fs" % saved)
for w in C.warnings(c):
out("warning: " + w)
if ds:
+2
View File
@@ -115,6 +115,8 @@ class SisiCase(unittest.TestCase):
def check(id, cmd, rung=3, kind="general", exit=0, timeout_s=10, **expect):
if cmd == "true": # a passing check that can fail (bare `true` is vacuous and refused)
cmd = "test -f .sisi/contract.json"
return {"id": id, "claim": "claim " + id, "kind": kind, "rung": rung, "cmd": cmd,
"expect": dict({"exit": exit}, **expect), "timeout_s": timeout_s}
-90
View File
@@ -222,96 +222,6 @@ class DeliveryRowTests(SisiCase):
per = (time.perf_counter() - t) / 5
self.assertLess(per, 0.25)
def ref_percentile(xs, p):
s = sorted(xs)
if len(s) == 1:
return s[0]
pos = (len(s) - 1) * p / 100.0
lo, frac = int(pos // 1), pos - int(pos // 1)
return s[lo] if frac == 0 else s[lo] * (1 - frac) + s[lo + 1] * frac
class TimeCommandTests(SisiCase):
def test_small_known_values(self):
self.assertEqual(delivery.median([5, 1, 3]), 3)
self.assertEqual(delivery.median([4, 1, 3, 2]), 2.5)
self.assertEqual(delivery.percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 90), 9.1)
self.assertEqual(delivery.percentile([7], 90), 7)
self.assertIsNone(delivery.median([]))
self.assertIsNone(delivery.percentile([], 90))
def test_median_and_percentile_property(self):
rnd = random.Random(7)
for _ in range(300 * ITERS):
xs = [rnd.choice([rnd.randint(0, 50), rnd.random() * 1000]) for _ in range(rnd.randint(1, 40))]
half = sorted(xs)
n = len(half)
want_med = half[n // 2] if n % 2 else (half[n // 2 - 1] + half[n // 2]) / 2
self.assertAlmostEqual(delivery.median(xs), want_med)
for p in (0, 50, 90, 100, rnd.randint(0, 100)):
self.assertAlmostEqual(delivery.percentile(xs, p), ref_percentile(xs, p), places=6)
self.assertLessEqual(delivery.percentile(xs, 50), delivery.percentile(xs, 90) + 1e-9)
def add_rows(self, now, spec):
"""spec: list of (days_ago, seconds, project, send_backs, check_s)."""
for d, secs, proj, sb, cs in spec:
end = now - d * 86400
store.append("deliveries", {"ts": delivery._iso(end), "session": "s", "project": proj, "start": delivery._iso(end - secs),
"end": delivery._iso(end), "seconds": secs, "send_backs": sb, "check_s": cs, "contract": True})
def test_report_windows_projects_shares_and_send_backs(self):
now = time.time()
self.add_rows(now, [(1, 100, "/a/alpha", 0, 10), (2, 300, "/a/alpha", 1, 90), (3, 200, "/b/beta", 0, 20),
(9, 400, "/a/alpha", 0, 40), (10, 800, "/b/beta", 2, 80), (20, 5, "/a/alpha", 0, 0)])
r = delivery.report(now)
cur, prev = r["all"]["last7"], r["all"]["prev7"]
self.assertEqual((cur["n"], cur["median_s"], prev["n"], prev["median_s"]), (3, 200, 2, 600))
self.assertAlmostEqual(cur["check_share"], 120 / 600)
self.assertEqual(cur["send_back_deliveries"], 1)
self.assertEqual(r["projects"]["/a/alpha"]["last7"]["median_s"], 200)
self.assertEqual(r["projects"]["/b/beta"]["prev7"]["n"], 1)
out = []
delivery.cmd_time([], out=out.append)
text = "\n".join(out)
self.assertIn("median 3m20s", text)
self.assertIn("1 of 3", text)
self.assertIn("alpha", text)
js = []
delivery.cmd_time(["--json"], out=js.append)
self.assertEqual(json.loads(js[0])["all"]["last7"]["n"], 3)
def test_windows_agree_with_a_simple_reference(self):
rnd = random.Random(11)
now = time.time()
for _ in range(30 * ITERS):
rows = [{"end": delivery._iso(now - rnd.random() * 20 * 86400), "seconds": rnd.random() * 500} for _ in range(rnd.randint(0, 30))]
cur, prev = delivery.windows(rows, now)
ref_cur = [r for r in rows if now - 7 * 86400 <= harvest.epoch(r["end"]) <= now]
ref_prev = [r for r in rows if now - 14 * 86400 <= harvest.epoch(r["end"]) < now - 7 * 86400]
self.assertEqual((sorted(map(id, cur)), sorted(map(id, prev))), (sorted(map(id, ref_cur)), sorted(map(id, ref_prev))))
def test_no_data_is_said_plainly(self):
r = self.sisi("time")
self.assertEqual(r.returncode, 0)
self.assertIn("no deliveries recorded", r.stdout)
self.assertIn("no deliveries recorded in the last 7 days", self.sisi("status").stdout)
self.assertEqual(json.loads(self.sisi("time", "--json").stdout)["all"]["last7"]["n"], 0)
def test_status_shows_the_seven_day_median_and_slow_checks_get_advice(self):
now = time.time()
self.add_rows(now, [(1, 120, "/p", 0, 5), (2, 60, "/p", 0, 5), (3, 600, "/p", 0, 5)])
self.assertIn("median 2m00s over the last 7 days (3 deliveries)", self.sisi("status").stdout)
for dur in (50, 70):
store.append("results", {"ts": store.now(), "check": "slow-one", "status": "passed", "duration_s": dur, "tier": "fast"})
store.append("results", {"ts": store.now(), "check": "quick", "status": "passed", "duration_s": 0.5, "tier": "fast"})
store.append("results", {"ts": store.now(), "check": "mutation", "status": "passed", "duration_s": 300, "tier": "deep"})
slow = delivery.report(now)["slowest_checks"]
self.assertEqual([x["id"] for x in slow], ["mutation", "slow-one", "quick"])
self.assertAlmostEqual(slow[1]["mean_s"], 60)
self.assertIn('"tier": "deep"', slow[1]["suggestion"])
self.assertIn("split", slow[0]["suggestion"])
class ParallelVerifyTests(SisiCase):
def strip(self, results):
return [{k: r[k] for k in ("item", "id", "status", "kind", "rung", "tier")} for r in results]
+3 -2
View File
@@ -27,9 +27,10 @@ class EndToEnd(SisiCase):
r = self.sisi("gate", stdin=stop)
self.assertEqual((r.returncode, r.stdout), (0, ""))
self.assertEqual(self.sisi("unit", "close").returncode, 0)
out = self.sisi("status").stdout
self.assertIn("contracts verified : 1", out)
self.assertIn("3: 100%", out)
self.assertIn("[delivered]", out)
self.assertIn("correctness and assurance", out)
self.assertEqual(self.sisi("uninstall").returncode, 0)
+1 -1
View File
@@ -57,7 +57,7 @@ class GateContractTests(GateBase):
a, msg = self.call()
self.assertEqual(a, "block")
st = {r["check"]: r["status"] for r in self.results()}
self.assertEqual(st, {"a": "timeout", "b": "timeout"}) # b never ran: counts as timeout
self.assertEqual(st, {"a": "not-run", "b": "not-run"}) # a timed out, b never ran: neither passed
def test_three_strikes_then_unverified_release_then_reset(self):
self.write_contract(contract([check("bad", "false")]))
-1
View File
@@ -247,7 +247,6 @@ class OverlayTests(PersonalCase):
self.assertIn("rulebook %d lines" % lines, out)
self.assertIn("%d characters" % len(self.generated()), out)
self.assertNotIn("lessons block", out) # no lesson list is loaded at session start
self.assertIn("rulebook %d lines" % lines, self.ok("status").stdout)
def test_core_md_rules_have_unique_ids_and_the_budget_holds(self):
text = open(os.path.join(REPO, "canon", "core.md")).read()
-12
View File
@@ -106,18 +106,6 @@ class StoreTests(SisiCase):
[t.start() for t in ts]; [t.join() for t in ts]
self.assertEqual(len(self.read("learn.jsonl")), 300)
def test_status(self):
self.write_contract(contract([check("a", "true", rung=2), check("b", "true", rung=3), human("h")]))
self.sisi("verify")
self.write_contract(contract([check("a", "false", rung=2)]))
self.sisi("verify")
self.sisi("contract", "waive", "tiny")
out = self.sisi("status").stdout
self.assertIn("contracts verified : 1", out)
self.assertIn("pass rate 50%", out)
self.assertIn("waivers : 1", out)
self.assertIn("unverified passes : 0", out)
class HelpTests(SisiCase):
def test_help_and_unknown(self):
+593
View File
@@ -0,0 +1,593 @@
"""The work-unit record (SPEC 10), telemetry and the scorecard (SPEC 6.1, 13), `sisi status`, and
scratch pruning (docs/target.md sections 2, 4, 6)."""
import json, os, subprocess, time, unittest
from unittest import mock
from support import *
from sisi import contract as C, harvest, scorecard, store, unit as U, workers
SCORE_DIMENSIONS = ("intent_fulfilment", "correctness_and_assurance", "delivery_velocity", "resource_efficiency",
"parallelism", "human_experience", "lifecycle_quality", "organizational_improvement")
def real(id, cmd, **kw):
return dict(check(id, cmd), **kw)
class UnitCase(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
self.contract_path = os.path.join(self.proj, ".sisi", "contract.json")
def start(self, checks=None, **fields):
r = self.sisi("contract", "init", "--goal", "make the thing")
self.assertEqual(r.returncode, 0, r.stdout)
c = C.load(self.contract_path)
c["checks"] = checks or [real("works", "test -f done.txt")]
c.update(fields)
C.save(self.contract_path, c)
return c
def finish_green(self):
open(os.path.join(self.proj, "done.txt"), "w").write("x")
r = self.sisi("verify")
self.assertEqual(r.returncode, 0, r.stdout)
def archive(self, uid):
return json.load(open(os.path.join(self.proj, ".sisi", "units", "%s.json" % uid)))
def commit_all(self, msg="c"):
subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True)
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", msg], cwd=self.proj, check=True)
class RecordTests(UnitCase):
def test_close_archives_all_fourteen_items(self):
"""R-10.2-1, R-10.2-2, R-10.2-3, R-10.2-4, R-10.2-5, R-10.2-6, R-10.2-7, R-10.2-8, R-10.2-9,
R-10.2-10, R-10.2-11, R-10.2-12, R-10.2-13, R-10.2-14, R-10.2-15: the archived record carries
every item of SPEC 10.2, and a summary line goes to the user store."""
self.start(parent="request-9", scope={"in": ["app"], "out": ["docs"]}, plan=["write it", "check it"],
requirements=[{"id": "q1", "kind": "explicit", "text": "it works", "decision": "now", "check": "works"}],
risk={"profile": "isolated"}, limitations=["only tested here"],
deferred=[{"what": "perf run", "why": "slow", "safe_because": "no hot path"}])
self.finish_green()
r = self.sisi("unit", "close")
self.assertEqual(r.returncode, 0, r.stdout)
rec = self.archive("proj")
for key in ("id", "parent", "goal", "scope", "requirements", "checks", "invariants", "risk", "plan",
"workers", "models", "budgets", "started", "ended", "telemetry", "changed_artifacts",
"verification", "deferred", "limitations", "delivery_status", "scorecard", "retro_findings",
"learning_ids", "policy_version", "start_commit", "closing_commit"):
self.assertIn(key, rec, key)
self.assertEqual(rec["parent"], "request-9")
self.assertEqual(rec["risk"]["declared"], "isolated")
self.assertIn("floor", rec["risk"])
self.assertTrue(rec["policy_version"] and rec["start_commit"])
self.assertEqual(rec["closing_commit"], rec["start_commit"]) # nothing committed in this unit
self.assertEqual(rec["delivery_status"], "delivered-with-deferred") # the contract defers something
self.assertEqual(set(rec["scorecard"]), set(SCORE_DIMENSIONS))
lines = store.read("units")
self.assertEqual(len(lines), 1)
for key in ("id", "project", "closed_at", "risk", "delivery_status", "scorecard"):
self.assertIn(key, lines[0], key)
def test_policy_version_is_stable_and_follows_the_policies(self):
"""R-10.2-6: the hash does not depend on the project's path and changes when its risk table does."""
c = {"id": "x"}
a = U.policy_version(self.proj, c)
self.assertEqual(a, U.policy_version(self.proj, c))
os.makedirs(os.path.join(self.proj, ".sisi"), exist_ok=True)
with open(os.path.join(self.proj, ".sisi", "risk.json"), "w") as f:
json.dump({"patterns": []}, f)
self.assertNotEqual(a, U.policy_version(self.proj, c))
other = os.path.join(self.tmp, "elsewhere")
os.makedirs(other)
self.assertEqual(U.policy_version(other, c), a)
def test_start_and_closing_commits_and_changed_artifacts(self):
"""R-10.2-10: the start commit, the closing commit and the changed files come from git."""
self.start()
base = json.load(open(self.contract_path))["base_head"]
open(os.path.join(self.proj, "done.txt"), "w").write("x\n")
self.commit_all("work")
self.assertEqual(self.sisi("verify").returncode, 0)
self.sisi("unit", "close")
rec = self.archive("proj")
self.assertEqual(rec["start_commit"], base)
self.assertNotEqual(rec["closing_commit"], base)
self.assertIn("done.txt", rec["changed_artifacts"]["files"])
self.assertNotIn(".sisi/units/proj.json", rec["changed_artifacts"]["files"])
def test_risk_floor_is_stored_beside_the_declared_profile(self):
"""R-10.2-6: the floor comes from the changed paths; the declared profile is kept as declared."""
self.start(risk={"profile": "trivial", "why": "docs"})
os.makedirs(os.path.join(self.proj, "auth"))
open(os.path.join(self.proj, "auth", "password_reset.py"), "w").write("secret = 1\n")
open(os.path.join(self.proj, "done.txt"), "w").write("x")
self.assertEqual(self.sisi("verify").returncode, 0)
self.sisi("unit", "close")
risk = self.archive("proj")["risk"]
self.assertEqual(risk["declared"], "trivial")
self.assertEqual(risk["floor"]["class"], "measured")
self.assertNotEqual(risk["floor"]["value"], "trivial") # authorization paths raise the floor
def test_findings_and_delegations_come_from_their_stores(self):
"""R-10.2-7, R-10.2-15: the record holds the retro findings recorded for the unit and the
delegations the ledger has for the project in its window."""
self.start()
self.finish_green()
r = self.sisi("retro", "--finding", "the check failed once because done.txt did not exist yet",
"--cause", "the file was created after the first run, not before", "--impact", "time",
"--disposition", "record", "--limits", "only for tasks that create files")
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
now = time.time()
for i, (start, minutes) in enumerate(((now - 600, 8), (now - 500, 5))):
workers.append_record({"kind": "attempt", "id": "d%d" % i, "ts": int(now), "project": "proj",
"type": "impl", "difficulty": 1, "worker": "w", "outcome": "accepted",
"check": "tests", "minutes": minutes, "started": start, "ended": start + minutes * 60})
workers.append_record({"kind": "attempt", "id": "z", "ts": int(now), "project": "elsewhere", "worker": "w"})
self.sisi("unit", "close")
rec = self.archive("proj")
self.assertEqual(len(rec["retro_findings"]), 1)
self.assertEqual(rec["telemetry"]["retro_findings"], {"value": 1, "class": "measured"})
self.assertEqual(len(rec["workers"]), 2)
par = rec["scorecard"]["parallelism"]
self.assertEqual(par["delegations"]["value"], 2)
self.assertEqual(par["overlapped_delegations"]["value"], 1) # the two ran at the same time
self.assertEqual(par["worker_minutes"]["class"], "estimated")
def test_the_closed_unit_is_offered_to_the_evaluation_harness(self):
"""R-13.3-3: a close calls the harness's capture, and a failure there never stops the close."""
self.start()
self.finish_green()
with mock.patch("sisi.evaluate.capture_case") as cap:
self.assertEqual(self.sisi("unit", "close").returncode, 0)
cap.assert_called_once()
view = cap.call_args[0][0]
self.assertEqual((view["id"], view["delivery_status"]), ("proj", "delivered"))
self.assertTrue(view["start_commit"])
self.sisi("contract", "init")
self.finish_green_again()
with mock.patch("sisi.evaluate.capture_case", side_effect=RuntimeError("harness down")):
self.assertEqual(self.sisi("unit", "close").returncode, 0)
self.assertEqual({r["id"] for r in store.read("units")}, {"proj", "proj-2"})
def finish_green_again(self):
c = C.load(self.contract_path)
c["checks"] = [real("again", "test -f done.txt")]
C.save(self.contract_path, c)
self.assertEqual(self.sisi("verify").returncode, 0)
def test_a_real_benchmark_case_is_stored_for_a_repository_unit(self):
"""R-13.3-3: a unit with a start commit and a command check becomes a stored case."""
from sisi import evaluate
self.start()
self.finish_green()
self.sisi("unit", "close")
self.assertIsNotNone(evaluate.get_case("case-proj"))
class DeliveryStatusTests(UnitCase):
def test_deferred_and_human_checks_close_as_delivered_with_deferred(self):
"""R-10.3-4, R-10.3-5: a check that needs a person is not-run (needs human) and does not
block; the unit says so in its delivery status and lists it."""
self.start(checks=[real("works", "test -f done.txt"), human("eyes", 5)])
self.finish_green()
self.sisi("unit", "close")
rec = self.archive("proj")
self.assertEqual(rec["delivery_status"], "delivered-with-deferred")
self.assertEqual(rec["deferred_checks"], ["eyes"])
def test_a_failing_check_refuses_a_close_as_delivered(self):
"""R-10.3-4: required verification must have passed."""
self.start()
r = self.sisi("unit", "close")
self.assertEqual(r.returncode, 1)
self.assertIn("cannot close as delivered", r.stdout)
self.assertFalse(os.path.exists(os.path.join(self.proj, ".sisi", "units")))
self.assertEqual(store.read("units"), [])
def test_gate_release_after_send_backs_closes_as_unverified(self):
"""R-10.3-5: a unit the gate released with failures standing is `unverified`."""
self.start()
self.sisi("verify")
store.append("results", {"ts": store.now(), "contract": "proj", "project": self.proj, "check": "gate",
"item": "gate", "status": "unverified", "duration_s": 0.0})
self.assertEqual(self.sisi("unit", "close").returncode, 0)
self.assertEqual(self.archive("proj")["delivery_status"], "unverified")
def test_abandon_records_the_reason_and_needs_one(self):
"""R-10.3-8: a unit may be stopped; the disposition and reason are recorded."""
self.start()
self.assertEqual(self.sisi("unit", "close", "--abandon").returncode, 1)
self.assertEqual(self.sisi("unit", "close", "--abandon", "premise disproven").returncode, 0)
rec = self.archive("proj")
self.assertEqual((rec["delivery_status"], rec["abandon_reason"]), ("abandoned", "premise disproven"))
def test_only_the_five_delivery_statuses_exist(self):
"""R-10.2-13."""
self.assertEqual(set(U.DELIVERY_STATUSES),
{"delivered", "delivered-with-deferred", "deviation", "unverified", "abandoned"})
class NeverLostTests(UnitCase):
def test_contract_init_refuses_an_open_unit_and_replaces_a_closed_one(self):
"""R-10.2-1, R-10.3-1: `sisi contract init` on an open unit refuses and names the abandon
command; on a closed unit it starts a new one and the old record stays."""
self.start()
before = open(self.contract_path).read()
r = self.sisi("contract", "init")
self.assertEqual(r.returncode, 1)
self.assertIn('sisi unit close --abandon "<reason>"', r.stdout)
self.assertEqual(open(self.contract_path).read(), before)
self.finish_green()
self.sisi("unit", "close")
old = open(os.path.join(self.proj, ".sisi", "units", "proj.json"), "rb").read()
self.assertEqual(self.sisi("contract", "init").returncode, 0)
c = C.load(self.contract_path)
self.assertEqual((c["id"], c["status"]), ("proj-2", "open"))
self.assertEqual(open(os.path.join(self.proj, ".sisi", "units", "proj.json"), "rb").read(), old)
def test_closing_twice_changes_nothing(self):
"""R-10.2-1: a record is never overwritten or duplicated."""
self.start()
self.finish_green()
self.sisi("unit", "close")
p = os.path.join(self.proj, ".sisi", "units", "proj.json")
old, lines = open(p, "rb").read(), open(os.path.join(self.data, "units.jsonl")).read()
r = self.sisi("unit", "close")
self.assertEqual(r.returncode, 0)
self.assertIn("already closed", r.stdout)
self.assertEqual(open(p, "rb").read(), old)
self.assertEqual(open(os.path.join(self.data, "units.jsonl")).read(), lines)
def test_abandoning_then_starting_again_keeps_every_record(self):
"""R-10.2-1."""
for n in range(3):
self.start()
self.assertEqual(self.sisi("unit", "close", "--abandon", "try %d" % n).returncode, 0)
names = sorted(os.listdir(os.path.join(self.proj, ".sisi", "units")))
self.assertEqual(names, ["proj-2.json", "proj-3.json", "proj.json"])
self.assertEqual(len(store.read("units")), 3)
def test_a_crash_between_archive_and_reset_loses_nothing_and_converges(self):
"""R-10.2-1: the archive written, the summary line and the contract reset not: closing again
keeps the archive byte for byte, adds the missing summary once and marks the contract closed."""
c = self.start()
self.finish_green()
c = C.load(self.contract_path)
rec = U.build_record(c, self.proj, "delivered", time.time())
path, created = U.archive_record(rec, self.proj)
self.assertTrue(created)
before = open(path, "rb").read()
self.assertEqual(store.read("units"), [])
self.assertEqual(self.sisi("contract", "init").returncode, 1) # still open: refused
self.assertEqual(self.sisi("unit", "close").returncode, 0)
self.assertEqual(open(path, "rb").read(), before)
self.assertEqual(len(store.read("units")), 1)
self.assertEqual(C.load(self.contract_path)["status"], "closed")
self.sisi("unit", "close")
self.assertEqual(len(store.read("units")), 1)
def test_an_archive_that_belongs_to_another_unit_is_never_overwritten(self):
"""R-10.2-1: a hand-made id collision moves the new unit to a fresh id."""
self.start()
self.finish_green()
os.makedirs(os.path.join(self.proj, ".sisi", "units"))
p = os.path.join(self.proj, ".sisi", "units", "proj.json")
with open(p, "w") as f:
json.dump({"id": "proj", "started": "2001-01-01T00:00:00Z", "project": self.proj}, f)
before = open(p, "rb").read()
r = self.sisi("unit", "close")
self.assertEqual(r.returncode, 0, r.stdout)
self.assertEqual(open(p, "rb").read(), before)
self.assertTrue(os.path.exists(os.path.join(self.proj, ".sisi", "units", "proj-2.json")))
def test_archive_record_never_replaces_an_existing_archive(self):
"""R-10.2-1: two writers racing for one id: the first record stays, byte for byte."""
path, created = U.archive_record({"id": "u", "v": 1}, self.proj)
self.assertTrue(created)
first = open(path, "rb").read()
path2, created2 = U.archive_record({"id": "u", "v": 2}, self.proj)
self.assertFalse(created2)
self.assertEqual(open(path, "rb").read(), first)
self.assertEqual([n for n in os.listdir(os.path.dirname(path)) if ".tmp" in n], [])
def test_an_interrupted_write_leaves_no_partial_archive(self):
"""R-10.2-1: the archive appears whole or not at all."""
self.start()
self.finish_green()
with mock.patch("os.fsync", side_effect=OSError("disk gone")):
with self.assertRaises(OSError):
U.archive_record({"id": "proj"}, self.proj)
self.assertEqual([n for n in os.listdir(os.path.join(self.proj, ".sisi", "units")) if n == "proj.json"], [])
def test_show_and_list(self):
"""R-10.2-1: `sisi unit show [ID]` and `sisi unit list`."""
self.start()
self.assertIn('"id": "proj"', self.sisi("unit", "show").stdout) # the open unit
self.assertIn("open", self.sisi("unit", "list").stdout)
self.finish_green()
self.sisi("unit", "close")
self.assertEqual(json.loads(self.sisi("unit", "show", "proj").stdout)["delivery_status"], "delivered")
self.assertIn("delivered", self.sisi("unit", "list").stdout)
self.assertEqual(self.sisi("unit", "show", "nope").returncode, 1)
class PauseTests(UnitCase):
def test_pause_lets_the_turn_end_and_a_change_ends_the_wait(self):
"""R-6.1-5: a pause is recorded, the gate makes no demands while nothing changes, a new change
ends the wait, and the wait is telemetry."""
self.start()
self.assertEqual(self.sisi("unit", "pause", "").returncode, 1)
self.assertEqual(self.sisi("unit", "pause", "the owner's decision").returncode, 0)
c = C.load(self.contract_path)
self.assertEqual(c["status"], "paused")
self.assertEqual(c["pauses"][0]["what"], "the owner's decision")
stop = json.dumps({"session_id": "p1", "cwd": self.proj, "hook_event_name": "Stop", "stop_hook_active": False})
self.sisi("tick", stdin=json.dumps({"session_id": "p1", "cwd": self.proj, "hook_event_name": "SessionStart"}))
open(os.path.join(self.proj, "new.txt"), "w").write("x") # a change after the pause
self.assertIn("block", self.sisi("gate", stdin=stop).stdout)
self.assertEqual(C.load(self.contract_path)["status"], "open") # the wait ended
self.assertTrue(C.load(self.contract_path)["pauses"][0]["until"])
self.finish_green()
self.sisi("unit", "close")
wait = self.archive("proj")["telemetry"]["time_in_waits_s"]
self.assertEqual(wait["class"], "measured")
def test_a_paused_unit_with_no_change_passes_silently(self):
"""R-6.1-5."""
self.start()
self.sisi("unit", "pause", "waiting for a review")
stop = json.dumps({"session_id": "p2", "cwd": self.proj, "hook_event_name": "Stop", "stop_hook_active": False})
self.sisi("tick", stdin=json.dumps({"session_id": "p2", "cwd": self.proj, "hook_event_name": "SessionStart"}))
r = self.sisi("gate", stdin=stop)
self.assertEqual((r.returncode, r.stdout.strip()), (0, ""))
class TelemetryHonestyTests(UnitCase):
def transcript(self, with_usage, model="model-one"):
now = store.now()
assistant = {"model": model, "content": [{"type": "tool_use", "name": "AskUserQuestion", "input": {}}]}
if with_usage:
assistant["usage"] = {"input_tokens": 1000, "output_tokens": 500}
lines = [{"type": "user", "timestamp": now, "message": {"role": "user", "content": "please build the thing"}},
{"type": "assistant", "timestamp": now, "message": assistant},
{"type": "user", "timestamp": now, "message": {"role": "user", "content": "no, that is wrong"}}]
tp = os.path.join(self.tmp, "t.jsonl")
with open(tp, "w") as f:
f.write("\n".join(json.dumps(x) for x in lines) + "\n")
store.save_session("s-tel", {"cwd": self.proj, "transcript_path": tp, "started": store.now()})
return tp
def close_and_load(self):
self.finish_green()
self.assertEqual(self.sisi("unit", "close").returncode, 0)
return self.archive("proj")["telemetry"]
def test_without_a_transcript_nothing_is_measured_and_nothing_is_zero(self):
"""R-13.4-1, R-13.4-2: no transcript: tokens, cost, messages and dialogs are unavailable, with
no value, never 0 and never measured."""
self.start()
tel = self.close_and_load()
for k in ("tokens_by_category", "tokens_by_model", "cost", "human_messages", "question_dialogs",
"human_corrections"):
self.assertEqual(tel[k], {"value": None, "class": "unavailable"}, k)
def test_a_transcript_without_usage_gives_no_tokens_and_no_cost(self):
"""R-13.4-2: the host wrote a transcript but no usage numbers: the human counts are measured,
and no token or cost figure may be shown as measured."""
self.start()
self.transcript(with_usage=False)
tel = self.close_and_load()
self.assertEqual(tel["human_messages"], {"value": 2, "class": "measured"})
self.assertEqual(tel["question_dialogs"], {"value": 1, "class": "measured"})
self.assertEqual(tel["human_corrections"]["class"], "inferred")
self.assertEqual(tel["human_corrections"]["value"], 1)
for k in ("tokens_by_category", "tokens_by_model", "cost"):
self.assertEqual(tel[k]["class"], "unavailable", k)
self.assertIsNone(tel[k]["value"], k)
def test_with_usage_tokens_are_measured_by_category_and_model_and_cost_needs_a_price(self):
"""R-13.3-2, R-13.4-1: usage in the transcript is measured by category and by model; a cost
is only ever estimated, and only from a recorded price."""
self.start()
self.transcript(with_usage=True)
tel = self.close_and_load()
self.assertEqual(tel["tokens_by_category"]["class"], "measured")
self.assertEqual(tel["tokens_by_category"]["value"]["input"], 1000)
self.assertEqual(tel["tokens_by_model"]["value"]["model-one"]["output"], 500)
self.assertEqual(tel["cost"], {"value": None, "class": "unavailable"}) # no price recorded
self.sisi("contract", "init")
self.finish_green_again()
with open(os.path.join(self.data, "worker-prices.json"), "w") as f:
json.dump({"models": {"model-one": {"cost_per_million_tokens": 2.0, "source": "test", "date": "2026-01-01"}}}, f)
self.sisi("unit", "close")
cost = self.archive("proj-2")["telemetry"]["cost"]
self.assertEqual(cost["class"], "estimated")
self.assertAlmostEqual(cost["value"], 0.003)
def finish_green_again(self):
c = C.load(self.contract_path)
c["checks"] = [real("again", "test -f done.txt")]
C.save(self.contract_path, c)
self.assertEqual(self.sisi("verify").returncode, 0)
def test_every_scorecard_value_carries_a_class_and_unavailable_has_no_value(self):
"""R-13.1-1, R-13.4-1: the eight dimensions, each leaf classed; nothing missing reads as a number."""
self.start()
self.close_and_load()
card = self.archive("proj")["scorecard"]
self.assertEqual(list(card), list(SCORE_DIMENSIONS))
for dim, vals in card.items():
for k, v in vals.items():
self.assertIn(v["class"], ("measured", "inferred", "estimated", "unavailable"), "%s.%s" % (dim, k))
if v["class"] == "unavailable":
self.assertIsNone(v["value"], "%s.%s" % (dim, k))
def test_first_useful_result_and_completion_time_are_recorded(self):
"""R-6.1-2, R-6.1-3, R-6.1-4: time to first useful result (first green run) and to validated completion."""
self.start()
tel = self.close_and_load()
self.assertEqual(tel["time_to_validated_completion_s"]["class"], "measured")
self.assertEqual(tel["time_to_first_useful_result_s"]["class"], "inferred")
self.assertEqual(tel["time_in_checks_s"]["class"], "measured")
self.assertEqual(tel["files_changed"]["class"], "measured")
def test_a_window_start_does_not_turn_a_first_in_window_message_into_a_non_correction(self):
"""R-6.1-2: only the transcript's own first message is exempt from correction counting."""
tp = os.path.join(self.tmp, "w.jsonl")
rows = [("2026-01-01T00:00:00Z", "start the work"), ("2026-01-01T01:00:00Z", "no, that is wrong")]
with open(tp, "w") as f:
for ts, text in rows:
f.write(json.dumps({"type": "user", "timestamp": ts, "message": {"content": text}}) + "\n")
st = harvest.transcript_stats(tp, harvest.epoch("2026-01-01T00:30:00Z"), harvest.epoch("2026-01-01T02:00:00Z"))
self.assertEqual((st["human_messages"], st["corrections"]), (1, 1))
self.assertIsNone(st["usage"])
class StatusTests(UnitCase):
def line(self, i, project="/w/alpha", risk="logic", model="m1", policy="p1", secs=10.0):
return {"id": "u%d" % i, "project": project, "goal": "g%d" % i, "delivery_status": "delivered",
"risk": {"declared": risk, "floor": risk}, "models": [model], "policy_version": policy,
"started": "2026-01-01T00:00:00Z", "ended": "2026-01-0%dT00:00:00Z" % (1 + i % 8),
"scorecard": {"delivery_velocity": {"time_to_validated_completion_s": {"value": secs, "class": "measured"}}}}
def test_trends_say_too_few_under_five_and_report_median_and_p95_from_five(self):
"""R-13.1-1, R-13.5-1: trends by project, risk profile, model and policy version; no
percentile from fewer than five units; no single score."""
for i, s in enumerate((10, 20, 30, 40, 100)):
store.append("units", self.line(i, secs=s))
store.append("units", self.line(9, project="/w/beta", risk="data", model="m2", policy="p2"))
out = self.sisi("status").stdout
self.assertIn("by project", out)
self.assertRegex(out, r"alpha\s+validated completion \(s\) 30/88 \(n=5\)")
self.assertRegex(out, r"beta\s+too few")
for kind in ("by risk profile", "by model", "by policy version"):
self.assertIn(kind, out)
self.assertRegex(out, r"data\s+too few")
self.assertNotRegex(out.lower(), r"overall score|total score|score:")
def test_unavailable_is_not_counted_as_a_number_in_trends(self):
"""R-13.4-2: a unit with no timing leaves the median to the units that have one."""
rows = [self.line(i, secs=s) for i, s in enumerate((10, 20, 30, 40, 50))]
rows[0]["scorecard"]["delivery_velocity"]["time_to_validated_completion_s"] = {"value": None, "class": "unavailable"}
t = scorecard.trends(rows)["project"]["alpha"]["validated completion (s)"]
self.assertEqual((t["n"], t["median"]), (4, 35.0))
def test_status_with_no_units_says_so(self):
"""R-13.4-3."""
out = self.sisi("status").stdout
self.assertIn("no closed work units yet", out)
def test_status_json_and_learning_view(self):
"""R-13.1-1: `--json` is machine-readable; `--learning` prints the learning report."""
store.append("units", self.line(1))
d = json.loads(self.sisi("status", "--json").stdout)
self.assertEqual(d["units"][0]["id"], "u1")
out = self.sisi("status", "--learning").stdout
self.assertIn("Learning loop", out)
def test_retired_reporters_are_gone_and_the_new_commands_are_listed(self):
"""R-13.1-1: `sisi time`, `sisi scoreboard` and `sisi improve` no longer exist."""
helptext = self.sisi("help").stdout
for gone in ("sisi time", "sisi scoreboard", "sisi improve", "sisi backlog"):
self.assertNotIn(gone, helptext)
for kept in ("sisi unit close", "sisi unit pause", "sisi unit show", "sisi status"):
self.assertIn(kept, helptext)
for cmd in ("time", "scoreboard"):
self.assertNotEqual(self.sisi(cmd).returncode, 0, cmd)
def test_status_after_a_real_close_shows_the_unit_with_its_scorecard(self):
"""R-13.1-1."""
self.start()
self.finish_green()
self.sisi("unit", "close")
out = self.sisi("status").stdout
self.assertIn("[delivered]", out)
for dim in SCORE_DIMENSIONS:
self.assertIn(dim.replace("_", " "), out)
def test_retro_with_no_arguments_prints_the_units_scorecard_and_what_stands_out(self):
"""R-10.3-7: `sisi retro` is grounded in the record."""
self.start()
self.sisi("verify") # fails: done.txt missing
open(os.path.join(self.proj, "done.txt"), "w").write("x")
self.sisi("verify")
out = self.sisi("retro").stdout
self.assertIn("what stands out", out)
self.assertIn("failed and then passed", out)
self.assertIn("correctness and assurance", out)
class PruneTests(SisiCase):
def make(self, name, age_days, transcript_age_days=None):
p = os.path.join(self.state, "sessions", name + ".json")
os.makedirs(os.path.dirname(p), exist_ok=True)
rec = {"cwd": self.proj}
if transcript_age_days is not None:
tp = os.path.join(self.tmp, name + ".jsonl")
open(tp, "w").write("{}\n")
os.utime(tp, (time.time() - transcript_age_days * 86400,) * 2)
rec["transcript_path"] = tp
with open(p, "w") as f:
json.dump(rec, f)
os.utime(p, (time.time() - age_days * 86400,) * 2)
return p
def test_old_sessions_go_on_the_first_start_and_every_nth_after(self):
"""R-12.1-1: pruning runs from a counter at session start, with no scheduler."""
old, new = self.make("old", 60), self.make("new", 1)
self.assertEqual(store.prune_sessions(), 1) # the first start sweeps
self.assertFalse(os.path.exists(old))
self.assertTrue(os.path.exists(new))
again = self.make("old2", 60)
for _ in range(store.DEFAULTS["scratch"]["prune_every"] - 1):
self.assertEqual(store.prune_sessions(), 0) # not their turn
self.assertTrue(os.path.exists(again))
self.assertEqual(store.prune_sessions(), 1) # the Nth start
self.assertFalse(os.path.exists(again))
def test_the_age_is_configurable(self):
"""R-12.1-1."""
keep = self.make("a", 10)
os.makedirs(os.path.join(self.home, ".config", "sisi"), exist_ok=True)
with mock.patch.object(store, "config", return_value=dict(store.DEFAULTS, scratch=dict(store.DEFAULTS["scratch"], session_max_age_days=5))):
self.assertEqual(store.prune_sessions(), 1)
self.assertFalse(os.path.exists(keep))
def test_an_active_session_is_never_touched(self):
"""R-12.1-1: the named current session, and one whose transcript the host is still writing."""
cur, live, dead = self.make("cur", 90), self.make("live", 90, transcript_age_days=1), self.make("dead", 90, transcript_age_days=90)
self.assertEqual(store.prune_sessions(active_ids=("cur",)), 1)
self.assertTrue(os.path.exists(cur) and os.path.exists(live))
self.assertFalse(os.path.exists(dead))
def test_a_run_is_bounded_and_the_next_start_continues(self):
"""R-12.1-1: at most prune_max_delete files per run; the sweep resumes at the next start."""
paths_ = [self.make("s%d" % i, 90) for i in range(7)]
cfg = dict(store.DEFAULTS, scratch=dict(store.DEFAULTS["scratch"], prune_max_delete=3))
with mock.patch.object(store, "config", return_value=cfg):
self.assertEqual(store.prune_sessions(), 3)
self.assertEqual(store.prune_sessions(), 3) # the very next start goes on
self.assertEqual(store.prune_sessions(), 1)
self.assertEqual([p for p in paths_ if os.path.exists(p)], [])
def test_the_time_budget_bounds_a_run(self):
"""R-12.1-1."""
for i in range(5):
self.make("t%d" % i, 90)
cfg = dict(store.DEFAULTS, scratch=dict(store.DEFAULTS["scratch"], prune_budget_s=0.0))
with mock.patch.object(store, "config", return_value=cfg):
self.assertEqual(store.prune_sessions(), 0)
def test_session_start_runs_the_prune(self):
"""R-12.1-1: `sisi tick` prunes during normal use."""
old = self.make("ancient", 90)
self.sisi("tick", stdin=json.dumps({"session_id": "now1", "cwd": self.proj, "hook_event_name": "SessionStart"}))
self.assertFalse(os.path.exists(old))
self.assertTrue(os.path.exists(os.path.join(self.state, "sessions", "now1.json")))
if __name__ == "__main__":
unittest.main()
+338
View File
@@ -0,0 +1,338 @@
"""The verification record (SPEC 5.4-5.6, 6.4): five statuses, refusal of checks that cannot fail,
selection by change, reuse on identical inputs, and the rule that nothing that did not run is
ever reported, stored or summarised as passed."""
import json, os, random, subprocess, unittest
from support import *
from sisi import contract as C, unit as U, verify as V
def real(id, cmd, **kw):
return dict(check(id, cmd), **kw)
class VacuousChecksTests(SisiCase):
def refused(self, cmd, **extra):
c = contract([dict({"id": "v", "claim": "c", "kind": "general", "rung": 3, "cmd": cmd,
"expect": {"exit": 0}}, **extra)])
return [e for e in C.validate(c) if "vacuous" in e]
def test_vacuous_variants_are_refused(self):
"""R-5.6-3: a check that cannot fail shows nothing, so a contract holding one is invalid."""
for cmd in ("true", ":", "exit 0", "echo ok", "test 1 = 1", "sh -c true", "bash -c 'exit 0'",
"[ 1 = 1 ]", "/bin/true", "true && true", "pytest || true", "make test || :",
"exit 0 # fine", "env true", "echo ok;", "sh -c \"sh -c ':'\"", "printf done"):
self.assertTrue(self.refused(cmd), cmd)
def test_commands_that_can_fail_are_accepted(self):
for cmd in ("false", "test -f x", "pytest", "grep -q x f", "echo ok > out.txt", "true && false",
"sh -c 'test -f x'", "test 1 = 2", "python3 -c 'print(1)'", "cd src && make"):
self.assertFalse(self.refused(cmd), cmd)
self.assertFalse(self.refused("echo hi", expect={"exit": 0, "stdout_contains": "zzz"}))
def test_an_echo_that_already_prints_what_it_expects_is_vacuous(self):
"""R-5.6-3: stdout_contains against a literal echo is a constant."""
self.assertTrue(self.refused("echo hello", expect={"exit": 0, "stdout_contains": "hello"}))
def test_vacuous_check_blocks_contract_check_and_verify(self):
"""R-5.6-3: `sisi contract check` and `sisi verify` both refuse, and nothing is recorded as passed."""
self.write_contract(contract([dict(check("v", "x"), cmd="sh -c true")]))
self.assertEqual(self.sisi("contract", "check").returncode, 1)
r = self.sisi("verify")
self.assertEqual(r.returncode, 1)
self.assertIn("vacuous", r.stdout)
self.assertEqual([x for x in self.results() if x["status"] == "passed"], [])
def test_invariants_are_held_to_the_same_rule(self):
"""R-5.6-3."""
c = contract([real("ok", "test -f .sisi/contract.json")], [real("inv", "exit 0")])
self.assertTrue([e for e in C.validate(c) if "vacuous" in e])
class NewFieldsTests(SisiCase):
def test_new_optional_fields_validate(self):
"""R-10.2-1: the unit's optional fields are validated by `sisi contract check`."""
c = contract([real("a", "test -f x", covers="x missing", when_changed=["src/**"], mandatory=True,
independent=False)])
c.update(parent="req-1", scope={"in": ["a"], "out": ["b"]}, deferred=[{"what": "w", "why": "y", "safe_because": "s"}],
limitations=["l"], plan=["step"], risk={"profile": "logic", "why": "money"},
requirements=[{"id": "q1", "kind": "explicit", "text": "t", "decision": "now", "check": "a"}],
approach={"chosen": "c", "why": "w", "alternatives": ["x"], "reuses": ["y"]})
self.assertEqual(C.validate(c), [])
bad = json.loads(json.dumps(c))
bad["checks"][0]["when_changed"] = []
bad["checks"][0]["mandatory"] = "yes"
bad["risk"]["profile"] = "huge"
bad["requirements"][0]["check"] = "nope"
bad["approach"] = {"chosen": 3, "bogus": 1}
bad["scope"] = {"in": "x"}
errs = " | ".join(C.validate(bad))
for part in ("when_changed", "mandatory", "risk.profile", "nope", "approach.chosen", "unknown key 'bogus'", "scope.in"):
self.assertIn(part, errs)
class SelectionAndReuseTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
def run_verify(self, c):
self.write_contract(c)
return self.sisi("verify", "--json")
def rows(self, r):
return {x["id"]: x for x in json.loads(r.stdout)["results"]}
def test_when_changed_selects_by_change(self):
"""R-6.4-1, R-6.4-2, R-5.4-10: a check runs only when a changed path matches; otherwise it is
skipped with the reason recorded, never reported as passed."""
os.makedirs(os.path.join(self.proj, "src"))
open(os.path.join(self.proj, "src", "a.py"), "w").write("x=1\n")
subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True)
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "src"], cwd=self.proj, check=True)
c = contract([real("src", "test -f src/a.py", when_changed=["src/**"]), real("always", "test -f src/a.py")])
rows = self.rows(self.run_verify(c))
self.assertEqual(rows["src"]["status"], "skipped")
self.assertIn("not affected", rows["src"]["reason"])
self.assertEqual(rows["always"]["status"], "passed")
open(os.path.join(self.proj, "src", "a.py"), "w").write("x=2\n")
rows = self.rows(self.sisi("verify", "--json"))
self.assertEqual(rows["src"]["status"], "passed")
def test_a_watch_that_matches_nothing_is_not_applicable_and_not_a_pass(self):
"""R-5.6-2: not-applicable is its own status with a reason."""
c = contract([real("w", "test -f nope", when_changed=["nothing/**"]), real("a", "test -f .sisi/contract.json")])
rows = self.rows(self.run_verify(c))
self.assertEqual(rows["w"]["status"], "not-applicable")
self.assertIn("no file matches", rows["w"]["reason"])
def test_all_runs_everything(self):
"""R-6.4-3: --all overrides selection."""
os.makedirs(os.path.join(self.proj, "src"))
open(os.path.join(self.proj, "src", "a.py"), "w").write("x=1\n")
c = contract([real("src", "test -f src/a.py", when_changed=["src/**"])])
self.git_commit_all()
self.write_contract(c)
self.assertEqual(self.rows(self.sisi("verify", "--json"))["src"]["status"], "skipped")
self.assertEqual(self.rows(self.sisi("verify", "--all", "--json"))["src"]["status"], "passed")
def git_commit_all(self):
subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True)
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "x"], cwd=self.proj, check=True)
def test_reuse_on_identical_inputs_and_not_after_a_change(self):
"""R-5.4-9: an identical tree reuses the last pass (skipped, never passed); any change to
the tree, or to the check's command, runs it again."""
open(os.path.join(self.proj, "f.txt"), "w").write("1")
c = contract([real("a", "test -f f.txt")])
first = self.rows(self.run_verify(c))["a"]
self.assertEqual(first["status"], "passed")
again = self.rows(self.sisi("verify", "--json"))["a"]
self.assertEqual(again["status"], "skipped")
self.assertTrue(again["reason"].startswith("reused: passed at"))
open(os.path.join(self.proj, "f.txt"), "w").write("22")
self.assertEqual(self.rows(self.sisi("verify", "--json"))["a"]["status"], "passed")
c["checks"][0]["cmd"] = "test -f f.txt && test -s f.txt"
self.assertEqual(self.rows(self.run_verify(c))["a"]["status"], "passed") # new command: not reused
def test_a_change_inside_when_changed_is_never_hidden_by_reuse(self):
"""R-5.4-9: reuse keys on the contents of the watched files."""
open(os.path.join(self.proj, "w.txt"), "w").write("good")
c = contract([real("w", "grep -q good w.txt", when_changed=["w.txt"])])
self.assertEqual(self.rows(self.run_verify(c))["w"]["status"], "passed")
open(os.path.join(self.proj, "w.txt"), "w").write("bad")
r = self.sisi("verify", "--json")
self.assertEqual(self.rows(r)["w"]["status"], "failed")
self.assertEqual(r.returncode, 1)
def test_a_failure_is_never_reused(self):
"""R-5.6-3."""
c = contract([real("f", "test -f missing.txt")])
self.assertEqual(self.rows(self.run_verify(c))["f"]["status"], "failed")
self.assertEqual(self.rows(self.sisi("verify", "--json"))["f"]["status"], "failed")
def test_seen_failing_duration_and_time_saved_are_recorded(self):
"""R-5.4-7, R-5.6-1: every result stores its duration and whether the check was seen failing;
`sisi verify` prints the slowest checks and the time saved."""
c = contract([real("a", "test -f f.txt")])
self.write_contract(c)
self.sisi("verify") # fails: f.txt missing
open(os.path.join(self.proj, "f.txt"), "w").write("1")
r = self.sisi("verify", "--json")
a = self.rows(r)["a"]
self.assertTrue(a["seen_failing"])
self.assertIn("duration_s", a)
r = self.sisi("verify")
self.assertIn("time saved by selection and reuse", r.stdout)
self.assertIn("slowest checks", self.sisi("verify", "--all").stdout)
self.assertTrue(all("duration_s" in x for x in self.results()))
def test_text_output_never_presents_a_skip_as_a_pass(self):
"""R-5.6-3."""
c = contract([real("w", "test -f nope", when_changed=["nothing/**"])])
self.write_contract(c)
out = self.sisi("verify").stdout
self.assertIn("did not run (not a pass)", out)
self.assertIn("no evidence yet", out)
class WaiverTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
def test_a_waiver_turns_nothing_green_and_the_unit_reads_deviation_everywhere(self):
"""R-10.3-3, R-13.4-2: a waiver records a deviation; the failing check still fails, and the
unit's status is `deviation` in the record, the summary line, the status report and the list."""
self.write_contract(contract([real("f", "test -f missing.txt")]))
self.assertEqual(self.sisi("verify").returncode, 1)
self.assertEqual(self.sisi("contract", "waive", "--check", "f", "not worth it").returncode, 0)
self.assertEqual(self.sisi("verify").returncode, 1) # still failing
r = self.sisi("unit", "close")
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn("deviation", r.stdout)
self.assertIn("must say so", r.stdout)
rec = json.loads(self.sisi("unit", "show", "t").stdout)
self.assertEqual(rec["delivery_status"], "deviation")
self.assertEqual(rec["deviations"][0]["reason"], "not worth it")
self.assertTrue(rec["scorecard"]["correctness_and_assurance"]["deviation"]["value"])
self.assertEqual([r["delivery_status"] for r in store_units()], ["deviation"])
self.assertIn("[deviation]", self.sisi("status").stdout)
self.assertIn("deviation", self.sisi("unit", "list").stdout)
self.assertNotIn("delivered", rec["delivery_status"])
def store_units():
from sisi import store
return store.read("units")
class NeverRunMandatoryTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
def test_a_mandatory_check_that_never_ran_cannot_close_as_delivered(self):
"""R-5.6-3, R-6.4-3: a `when_changed` glob that matches nothing used to skip a mandatory check
for ever must not let the unit close as plainly delivered."""
self.write_contract(contract([real("real", "test -f .sisi/contract.json"),
real("ghost", "test -f nope", when_changed=["nothing/**"])]))
r = self.sisi("verify")
self.assertEqual(r.returncode, 0) # not blocking...
self.assertIn("no evidence yet", r.stdout) # ...but said plainly
self.sisi("unit", "close")
rec = json.loads(self.sisi("unit", "show", "t").stdout)
self.assertEqual(rec["delivery_status"], "delivered-with-deferred")
self.assertEqual([x["id"] for x in rec["never_run_mandatory"]], ["ghost"])
def test_an_optional_check_may_be_kept_back(self):
"""R-6.4-3: optional confidence-building checks are distinguished from mandatory ones."""
self.write_contract(contract([real("real", "test -f .sisi/contract.json"),
real("opt", "test -f nope", when_changed=["nothing/**"], mandatory=False)]))
self.sisi("verify")
self.sisi("unit", "close")
self.assertEqual(json.loads(self.sisi("unit", "show", "t").stdout)["delivery_status"], "delivered")
def test_a_mandatory_check_not_affected_by_the_change_is_a_justified_skip(self):
"""R-5.4-10: selection with the reason recorded is the documented justification."""
os.makedirs(os.path.join(self.proj, "src"))
open(os.path.join(self.proj, "src", "a"), "w").write("1")
subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True)
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "s"], cwd=self.proj, check=True)
open(os.path.join(self.proj, "other.txt"), "w").write("1")
self.write_contract(contract([real("real", "test -f other.txt"), real("src", "test -f src/a", when_changed=["src/**"])]))
self.sisi("verify")
self.sisi("unit", "close")
self.assertEqual(json.loads(self.sisi("unit", "show", "t").stdout)["delivery_status"], "delivered")
class NothingUnrunIsEverPassedTests(SisiCase):
"""A seeded property test: random tree changes, verify runs and closes, against an oracle that
knows, from an external log, which commands actually ran. Nothing that did not run to a pass on a
tree where it holds may appear as passed in any result, in the stored rows or in the scorecard."""
FILES = ("f_a", "f_b", "f_b2", "f_c", "f_d", "g")
def build(self, n):
d = os.path.join(self.tmp, "p%d" % n)
os.makedirs(d)
self.git_init(d)
log = os.path.join(self.tmp, "log%d" % n)
def mk(id, f, wc, mandatory):
x = {"id": id, "claim": "claim " + id, "kind": "general", "rung": 3, "timeout_s": 10,
"cmd": "echo %s >> %s; test -f %s" % (id, log, f), "expect": {"exit": 0}, "mandatory": mandatory}
if wc:
x["when_changed"] = wc
return x
c = {"id": "t", "goal": "g", "assumptions": [], "questions": [], "invariants": [],
"checks": [mk("a", "f_a", None, True), mk("b", "f_b", ["f_b*"], True),
mk("c", "f_c", ["nothing/**"], True), mk("d", "f_d", None, False)]}
self.write_contract(c, d)
return d, log, {"a": "f_a", "b": "f_b", "c": "f_c", "d": "f_d"}
def logged(self, log):
try:
return open(log).read().split()
except OSError:
return []
def run_sequence(self, rng, n):
d, log, file_of = self.build(n)
steps = rng.choice([8, 12, 16])
for _ in range(steps):
op = rng.choice(["touch", "touch", "rm", "verify", "verify", "all", "close"])
if op in ("touch", "rm"):
p = os.path.join(d, rng.choice(self.FILES))
if op == "touch":
open(p, "w").write(str(rng.random()))
elif os.path.exists(p):
os.remove(p)
continue
if op in ("verify", "all"):
before_rows, before_log = len(self.results()), len(self.logged(log))
r = self.sisi("verify", *(["--all"] if op == "all" else []), "--json", cwd=d)
ran = set(self.logged(log)[before_log:])
new = [x for x in self.results()[before_rows:] if x.get("item") == "check"]
self.assertEqual({x["check"] for x in new}, set(file_of))
for x in new:
exists = os.path.exists(os.path.join(d, file_of[x["check"]]))
if x["status"] == "passed":
self.assertIn(x["check"], ran, "passed without running")
self.assertTrue(exists, "passed where the check cannot hold")
if x["check"] in ran:
self.assertEqual(x["status"], "passed" if exists else "failed")
else:
self.assertIn(x["status"], ("skipped", "not-applicable", "not-run"))
if str(x.get("reason")).startswith("reused"):
self.assertTrue(exists, "reused a pass on a tree where the check fails")
self.assertTrue(x.get("reason"), "a status other than passed or failed carries a reason")
self.assertEqual(r.returncode == 0, not any(x["status"] == "failed" for x in new))
else:
r = self.sisi("unit", "close", cwd=d)
path = os.path.join(d, ".sisi", "units", "t.json")
if r.returncode == 0:
rec = json.load(open(path))
latest = {x["id"]: x for x in rec["final_verification"]}
passed_now = sorted(i for i, x in latest.items() if x["status"] == "passed")
card = rec["scorecard"]["correctness_and_assurance"]["results_by_status"]["value"]
self.assertEqual(card.get("passed", 0), len(passed_now))
if rec["delivery_status"] == "delivered":
for cid in ("a", "b", "c"): # mandatory checks
ever = any(x["check"] == cid and x["status"] == "passed" for x in rec["verification"])
just = latest[cid]["status"] == "skipped" and "not affected" in (latest[cid]["reason"] or "")
self.assertTrue(ever or just, "delivered with %s never run to a pass" % cid)
self.assertNotEqual(latest[cid]["status"], "failed")
return
else:
self.assertFalse(os.path.exists(path))
def test_property_over_generated_sequences(self):
"""R-5.6-2, R-5.6-3: nothing that did not run is ever reported, stored or summarised as passed."""
seeds = [1, random.randrange(2 ** 32)] + [random.randrange(2 ** 32) for _ in range(ITERS)]
for n, seed in enumerate(seeds):
with self.subTest(seed=seed):
self.run_sequence(random.Random(seed), n)
if __name__ == "__main__":
unittest.main()
-9
View File
@@ -311,15 +311,6 @@ class LintCrossCheckTests(LibCase):
self.assertIn("short.md: 30" if False else "verified: memory", r.stdout)
self.assertIn("warning(s)", r.stdout)
def test_status_shows_library_size(self):
self.put("prove/a.md", vfile("a", extra="verified: ran\n"))
self.put("prove/b.md", vfile("b", extra="verified: memory\n"))
self.put("prove/c.md", vfile("c", extra="verified: docs\n"))
self.put("prove/d.md", vfile("d", extra="verified: docs\n"))
self.put("r.md", dfile("r"), self.ddir)
out = self.sisi("status").stdout
self.assertIn("4 verifiers (verified ran 1, docs 2, memory 1), 1 recipes", out)
class CoreMdTests(SisiCase):
def test_help_lists_new_commands(self):
+10 -5
View File
@@ -11,16 +11,21 @@ class VerifyTests(SisiCase):
return {r["check"]: r["status"] for r in self.results()}
def test_statuses(self):
# R-5.6-2, R-5.6-3: five statuses only. A timeout is not-run (timed out) and a
# human check is not-run (needs human): neither is ever reported as passed.
c = contract([check("ok", "true"), check("bad", "exit 3"), check("slow", "sleep 5", timeout_s=0.3),
check("out", "echo hello", stdout_contains="hello"), check("out2", "echo hi", stdout_contains="zzz"),
check("out", "python3 -c \"print('hello')\"", stdout_contains="hello"), check("out2", "echo hi", stdout_contains="zzz"),
check("code", "exit 3", exit=3), human("h5", 5), human("h6", 6)],
[check("inv", "true")])
r = self.run_verify(c)
self.assertEqual(r.returncode, 1)
self.assertEqual(self.statuses(), {"ok": "passed", "bad": "failed", "slow": "timeout", "out": "passed",
"out2": "failed", "code": "passed", "h5": "awaiting-human",
"h6": "awaiting-human", "inv": "passed"})
self.assertIn("awaiting-human", r.stdout)
self.assertEqual(self.statuses(), {"ok": "passed", "bad": "failed", "slow": "not-run", "out": "passed",
"out2": "failed", "code": "passed", "h5": "not-run",
"h6": "not-run", "inv": "passed"})
self.assertIn("not-run (needs human)", r.stdout)
self.assertIn("not-run (timed out)", r.stdout)
reasons = {x["check"]: x.get("reason") for x in self.results()}
self.assertEqual((reasons["slow"], reasons["h5"]), ("timed out", "needs human"))
def test_all_good_exit_zero_and_record_fields(self):
r = self.run_verify(contract([check("ok", "true"), human("h")]))