diff --git a/docs/architecture/01-introduction-and-goals.md b/docs/architecture/01-introduction-and-goals.md index 3134bcc..af56625 100644 --- a/docs/architecture/01-introduction-and-goals.md +++ b/docs/architecture/01-introduction-and-goals.md @@ -46,7 +46,7 @@ What it is not: | 05 | Probe security | Reads each trial with 11 security and 3 data-protection probes | [ch. 8.6.8](08-crosscutting-concepts.md) | | 06 | Judge | Scores each trial blind, three times, on an anchored rubric, and checks every quoted line | [ch. 8.6.6](08-crosscutting-concepts.md), [ch. 8.6.7](08-crosscutting-concepts.md) | | 07 | Check the judge | Builds damaged and improved trees that a working judge must tell apart | [ch. 8.6.7](08-crosscutting-concepts.md) | -| 08 | Report | Pairs trials, computes intervals and verdicts, owes or refuses the escalation, and prints the report | section 1.4, [ch. 8.7](08-crosscutting-concepts.md) | +| 08 | Report | Pairs trials, computes intervals and verdicts, refuses a run past its registered K, and prints the report | section 1.4, [ch. 8.7](08-crosscutting-concepts.md) | | 09 | Archive | Copies a round's raw data to a private store, restores it and checks the figures match | [ADR-019](../decisions/019-archive-before-the-report.md) | | 10 | Reuse | Copies an earlier round's trials into a new run root, with their readings | [ch. 4.2](04-solution-strategy.md) | diff --git a/docs/architecture/02-constraints.md b/docs/architecture/02-constraints.md index 3e39bb2..320ce40 100644 --- a/docs/architecture/02-constraints.md +++ b/docs/architecture/02-constraints.md @@ -24,7 +24,7 @@ setting, not a choice the benchmark made. Chapter 9 records the choices. | - | ---------- | ----------- | | 1 | One owner runs and reads every round | No step may wait for a person, and no person may score. A person in the loop would leak judgement into an arm | | 2 | Rules are registered before the trials they govern | A new hypothesis is committed to its round's registration before its first trial. A check chosen afterwards describes and never decides | -| 3 | K is fixed before a round's first trial: at most 5 after one escalation from 3, or 15 in round 5 | Sampling until an interval clears zero is not possible | +| 3 | K is fixed before a round's first trial, 15 from round 5, and no run goes past it | Sampling until an interval clears zero is not possible | | 4 | `ledger`, a second app, stays sealed | Every round so far measures `tariff`, the development app | | 5 | The templates live in another repository | Every run names a templates source with `--templates` or `BENCHMARK_TEMPLATES`, and reports land in that source's `docs/audits/` | diff --git a/docs/architecture/05-building-block-view.md b/docs/architecture/05-building-block-view.md index 6f9b479..c4c4474 100644 --- a/docs/architecture/05-building-block-view.md +++ b/docs/architecture/05-building-block-view.md @@ -24,7 +24,7 @@ dependency with its keyword. | `security.py` | Seeds each app, signs in its administrator, runs the 11 security and 3 data-protection probes | The scored trees | `security-scores/` | | `judge.py` | Builds a blind bundle per trial, runs the judge CLI against the rubric, checks every quoted line | The scored trees | `judge/` | | `control/control.py` | Builds the rubric control: trees damaged or improved on one row each, from two pinned bases | `base.zip`, `base-2.zip`, `overlay/` | A control root for `judge.py` | -| `report.py` | Pairs trials, computes intervals, verdicts and the escalation, applies withdrawals, prints the report | The run root, the scoring area, `withdrawn.json` | `docs/audits/YYYY-MM-DD-efficacy.md` in the templates source | +| `report.py` | Pairs trials, computes intervals and verdicts, applies withdrawals, prints the report | The run root, the scoring area, `withdrawn.json` | `docs/audits/YYYY-MM-DD-efficacy.md` in the templates source | | `archive.py` | Copies a round's raw data to the private archive, restores it, recomputes the report's figures from both | The run root, the scoring area | The archive clone, `archived.json` | ## 5.2 Inputs @@ -48,7 +48,7 @@ harness and `reuse.py`. | Path | Holds | | ---- | ----- | -| `-/` | A trial's pen, such as `full-2/`: everything the trial owns | +| `-/` | A trial's pen, such as `skills-2/`: everything the trial owns | | `-/-/` | The trial's workspace, inside its pen | | `-/tmp//` | The trial's own temporary directory, inside its pen | | `-.tar` | The frozen workspace, the only copy scoring reads | @@ -86,7 +86,6 @@ Every arm starts from an empty git repository holding `SPEC.md`. All but | Arm | Adds | Budget | Asks | |---|---|---|---| | `none` | nothing: the bare agent | — | the baseline every file is compared with | -| `full` | the file the interview generates, inline | none | do the templates help as shipped | | `short` | one generation from `agents.md`, inline, under a budget | ≤ 40 lines, ≤ 88 characters wide | does a short generated file help | | `hybrid` | the file the interview generates in its hybrid model, with the templates vendored into the workspace | none | does the model the owner's projects use help | | `hand` | a hand-written file | ≤ 40 lines | is the effect the templates, or merely having a file | diff --git a/docs/architecture/06-runtime-view.md b/docs/architecture/06-runtime-view.md index 06da7c1..d53ab61 100644 --- a/docs/architecture/06-runtime-view.md +++ b/docs/architecture/06-runtime-view.md @@ -207,8 +207,8 @@ restoring it, then the report. | 2-3 | The rubric is a JSON Schema, so a score is read by machine. Each primary row has anchors at 1, 3 and 5 in this domain's terms | [ch. 8.6.6](08-crosscutting-concepts.md) | | 4 | Every quoted line is looked up in its bundle. A judge that never opened the code still returns plausible numbers | [ch. 8.6.7](08-crosscutting-concepts.md) | | 5 | Run records, tarballs without their environments, transcripts and every reading go to a fresh directory of `braboj/tariff-runs` | [ADR-019](../decisions/019-archive-before-the-report.md) | -| 6-7 | The archive is restored into a temporary root and the report's table, contrasts, withdrawals, escalation, reach scan and lost trials are computed from both. Any difference fails | [ADR-019](../decisions/019-archive-before-the-report.md) | -| 8 | K paired differences per contrast, a 10,000-resample bootstrap interval at a recorded seed, the registered verdict rule, and whether the one escalation to K = 5 is owed | [ch. 8.1](08-crosscutting-concepts.md) | +| 6-7 | The archive is restored into a temporary root and the report's table, contrasts, withdrawals, blocks, reach scan and lost trials are computed from both. Any difference fails | [ADR-019](../decisions/019-archive-before-the-report.md) | +| 8 | K paired differences per contrast, a 10,000-resample bootstrap interval at a recorded seed, the registered verdict rule, and how many of the registered blocks are in | [ch. 8.1](08-crosscutting-concepts.md) | | 9 | Without the stamp, or once any reading changed since it was written, the report refuses to write under `docs/audits/` | [ADR-019](../decisions/019-archive-before-the-report.md) | | 10 | The finding table first, then the record behind every cell | [ch. 8.7.3](08-crosscutting-concepts.md) | @@ -257,18 +257,12 @@ original time, which the report reads to tell a re-run's sessions from those of the blocked attempt before it. Scoring and judging then run on it as on any root, which is how a later round re-reads an earlier one. -### 6.4.3 The escalation in the report +### 6.4.3 The blocks in the report -The report computes the one escalation to K = 5 of a round registered at -K = 3, so nobody decides it by eye. At K = 3 it names the rows that owe it and -the `--k 5 --from` run that settles it, from the trial the rotated order puts -first in block 4. At K = 5 it reads the first three blocks alone, prints their -verdicts beside the K = 5 ones, and flags an escalation no row owed. - -Round 5 registers K = 15 and no escalation. Its report says how many of the 15 -blocks are in, and calls a run short of them part-run. The harness refuses -`--k` above 5, or above 15 for a run holding a round-5 arm, and the report -refuses a run past it. +A round registers K = 15 and adds no block once results are seen. The report +says how many of the 15 blocks are in, and calls a run short of them part-run, +with none of its verdicts the round's. The harness refuses `--k` above 15, and +the report refuses a run past it. ### 6.4.4 Reusing an earlier round's trials @@ -276,6 +270,5 @@ refuses a run past it. its run record, tarball, transcripts, score, judgings and security reading, marked with where they came from. The earlier round's tool lock comes along, so both rounds are measured with one ruler. Nothing copied is measured again -unless a tool is given `--rescore`, `--rejudge` or `--reread`. Round 2 reused -round 1's `full` and `hand`. Later rounds reuse nothing, because the spec and -the judge changed. +unless a tool is given `--rescore`, `--rejudge` or `--reread`. Round 5d +reuses round 5c's trials, re-scored with it on one hidden suite. diff --git a/docs/architecture/08-crosscutting-concepts.md b/docs/architecture/08-crosscutting-concepts.md index 87db897..e17491f 100644 --- a/docs/architecture/08-crosscutting-concepts.md +++ b/docs/architecture/08-crosscutting-concepts.md @@ -79,7 +79,7 @@ The margins: | 5 | Round 5 holds adherence to one item | 8 pp, one checklist item of 13, as [its registration](../rounds/round-5.md) states | FR-02-05 | | 6 | Few blocks describe | Below K = 6, every interval is called descriptive | FR-02-09 | -### 8.1.3 Trial count and escalation +### 8.1.3 Trial count A round fixes K, the number of blocks, before its first trial. @@ -89,18 +89,15 @@ A round fixes K, the number of blocks, before its first trial. arrangement of three reaches conventional significance. Three trials describe; they do not prove. - Sampling until an interval clears zero is the failure the bound on K - prevents. - -![A round registered at K = 3 runs three blocks. If an escalation is owed it runs blocks 4 and 5 once and reports K = 3 and K = 5 side by side; otherwise it reports at K = 3. A round registered at a larger K, such as 15, runs K blocks and reports the round if all ran, and is part-run with no verdict of its own if not](../diagrams/escalation.png) + prevents. Rounds 1 to 4 were registered at K = 3 with one bounded + escalation to 5; they are retired, and their escalation with them. **Rules** | # | Rule | In practice | Requirement | | - | ---- | ----------- | ----------- | -| 1 | One escalation, under fixed conditions | Owed where a primary's interval contains zero while its mean exceeds the smallest change that matters, in any contrast and either direction; the report computes it | FR-03-01 | -| 2 | Never past K = 5 by escalation | Two more blocks, once; a row still open is reported inconclusive | FR-03-02, FR-03-03 | -| 3 | Or a larger K, sized beforehand | From earlier rounds' per-trial noise; no block added once results are seen. Round 5 registers K = 15 ([13.5](../rounds/round-5.md)) | FR-03-04 | -| 4 | A short run decides nothing | A run short of its K is part-run, and none of its verdicts is the round's | FR-03-05 | +| 1 | K is sized beforehand | From earlier rounds' per-trial noise; no block added once results are seen. Round 5 registers K = 15 ([13.5](../rounds/round-5.md)) | FR-03-04 | +| 2 | A short run decides nothing | A run short of its K is part-run, and none of its verdicts is the round's | FR-03-05 | ### 8.1.4 Failed and lost trials @@ -617,9 +614,12 @@ it, or the bar would move with the results. | # | Rule | In practice | Requirement | | - | ---- | ----------- | ----------- | | 1 | Declared before it is read | In writing, with its direction, before any trial is read for it | — | -| 2 | Printed apart | Its own section, with means and intervals and no verdict | FR-12-08 | -| 3 | Never decides | Never in the verdict vector, a "nothing got worse" claim, or the escalation | FR-12-08 | -| 4 | Fixed for next time | A check worth deciding on is registered before the next run | — | +| 2 | Never decides | Never in the verdict vector or a "nothing got worse" claim | — | +| 3 | Fixed for next time | A check worth deciding on is registered before the next run | — | + +Rounds 1 and 2 read their security checks this way, in a section of their own +with no verdict. From round 3 every check is a probe declared before the run, +so no report prints such a section. ### 8.7.5 Withdrawn metrics and re-scores diff --git a/docs/architecture/09-architecture-decisions.md b/docs/architecture/09-architecture-decisions.md index ce1c31e..b18decc 100644 --- a/docs/architecture/09-architecture-decisions.md +++ b/docs/architecture/09-architecture-decisions.md @@ -57,7 +57,7 @@ report shows first. | Record | Decision | Status | | ------ | -------- | ------ | -| [ADR-003](../decisions/003-k-blocks-and-escalation.md) | A round fixes K before its first trial, 15 from round 5 with no escalation; a round at K = 3 escalates at most to 5 | Accepted | +| [ADR-003](../decisions/003-k-blocks-and-escalation.md) | A round fixes K before its first trial, 15 from round 5, and no run goes past it; the escalation of rounds registered at K = 3 retired with them | Accepted | | [ADR-013](../decisions/013-what-the-report-opens-with.md) | The report opens with the finding table, and keeps the score table only for contrasts between two files | Accepted | | [ADR-015](../decisions/015-contrasts-and-verdicts.md) | A contrast gets a verdict only when both its arms run in the same round | Accepted | diff --git a/docs/architecture/11-risks-and-technical-debt.md b/docs/architecture/11-risks-and-technical-debt.md index 49454e0..714772c 100644 --- a/docs/architecture/11-risks-and-technical-debt.md +++ b/docs/architecture/11-risks-and-technical-debt.md @@ -7,7 +7,7 @@ Each risk names what holds it today. | # | Risk | Held by | Open | | - | ---- | ------- | ---- | -| 1 | Three trials cannot reach significance: 27 distinct resamples, a minimum two-sided p of 0.25 | Below K = 6 every interval is printed as descriptive. Round 5 registers K = 15, sized from rounds 3 and 4's noise | Round 4's escalations are owed and not run. Round 3's cannot run, its raw data lost | +| 1 | Three trials cannot reach significance: 27 distinct resamples, a minimum two-sided p of 0.25 | Below K = 6 every interval is printed as descriptive. Round 5 registers K = 15, sized from rounds 3 and 4's noise | Rounds 1 to 4, registered at K = 3, are retired; the benchmark proper starts with round 6 | | 2 | One app: every effect may be `tariff`'s | `ledger` stays sealed for the final claim | No second app has run | | 3 | One builder agent | | Another agent reading `AGENTS.md` is untested | | 4 | A judge that shares a vendor with the builder may favour the templates' own style | From round 5 the judge is `gpt-6-astra`, another vendor's model than every builder | | diff --git a/docs/architecture/12-glossary.md b/docs/architecture/12-glossary.md index 8840f62..0b2931b 100644 --- a/docs/architecture/12-glossary.md +++ b/docs/architecture/12-glossary.md @@ -19,11 +19,10 @@ under [`docs/rounds/`](../rounds/). | Churn | The files touched and lines changed by the change task, counted from the commit of the copy | | Consistency | How alike an arm's runs come out: the spread of each meter across them, and conventions agreement, the share of checklist items on which every run gives the same verdict | | Context file | A `CLAUDE.md` the agent reads at the start of a session: project facts and house rules | -| Contrast | Two arms compared within each block, such as `full − none`. K paired differences, one interval, one verdict per metric | +| Contrast | Two arms compared within each block, such as `skills − none`. K paired differences, one interval, one verdict per metric | | Control fixture | Trees built from two pinned applications, each damaged or improved on one judge row and each passing the same tests. A primary row counts only if it falls on the damaged trees and rises on the improved | | Cross-check judge | `gpt-6-astra` through `codex exec`, reading a sample of whole blocks. Its scores are never averaged with the rounds' judge. It withholds a verdict only where the two read opposite directions. Dropped from round 5 | | Data-protection probes | Three checks on personal data: a customer's email in the logs, an erased customer still in the database file, one customer's export carrying another's data | -| Escalation | The one step from K = 3 to K = 5, owed when a primary's interval contains zero while its mean exceeds the smallest change that matters. Round 5, which registers K = 15, has none | | Evidence check | Each line the judge quotes, looked up in the bundle it was quoted from. The report prints the share found | | Freeze | Saving a workspace as a tarball and its commit hash, before anything reads it | | Generator | The non-interactive invocation that turns the brief and a chain into an arm's file. Nobody answers its questions | @@ -33,7 +32,7 @@ under [`docs/rounds/`](../rounds/). | Hybrid model | A context file that copies in the rules whose breaking is silent and no tool enforces, and names the rest, with the templates vendored beside it | | Inline model | A context file that copies every adopted rule in | | Judge | The model that scores a blind bundle 1 to 5 per rubric row, with a quoted line as evidence. From round 5 it is `gpt-6-astra` through `codex exec` at effort `high`. Rounds 3 and 4 used `claude-opus-5-5` | -| K | The number of blocks, so the trials per arm, fixed by each round before its first trial: 15 in round 5. A round registered at K = 3 escalates at most to 5 | +| K | The number of blocks, so the trials per arm, fixed by each round before its first trial: 15 in round 5. No run goes past it | | Likely range | The primer's plain name for the bootstrap interval: where the average difference would land if the runs were redone | | Lost probe | A probe the trial kept from running, such as one that needs a sign-in the app refuses. It fails, never drops out of the rate | | Lost trial | A trial the provider ended rather than the agent, recorded as blocked. Re-run once in its place. A second loss stops the run | diff --git a/docs/coverage.md b/docs/coverage.md index cbf3770..b5b707e 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -53,15 +53,12 @@ when: | FR-02-08 | Untestable | No script calls a trim free; a person reading the report applies it, on the held rows the report prints. | | FR-02-09 | Self-test | `report.py` "from six blocks no interval is called descriptive"
`report.py` "a round too small to decide says so in the report and the appendix" | -## 03 Trial count and escalation +## 03 Trial count | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-03-01 | Self-test | `report.py` "a crossing interval with an effect of 0.67 owes it"
`report.py` "an effect of 0.67 the other way owes it"
`report.py` "the same row on C-A owes it"
`report.py` "an effect of exactly 0.5 does not"
`report.py` "an interval clear of zero does not"
`report.py` "an interval not computed does not"
`report.py` "a row outside the primary dimensions does not" | -| FR-03-02 | Self-test | `harness.py` "a K past the escalation's ceiling refuses"
`harness.py` "the escalation runs its blocks from none-4"
`report.py` "an owed escalation's command names a trial the harness takes" | -| FR-03-03 | Self-test | `report.py` "an escalated report prints both vectors"
`report.py` "the report carries the escalation section"
`report.py` "a K = 5 run is judged on its first three blocks"
`report.py` "a K = 3 run is assessed on its own vector"
`report.py` "an open row leaves both inconclusive" | -| FR-03-04 | Self-test | `harness.py` "a round-5 run takes K = 15 and refuses more"
`harness.py` "a round-5d run of hand and short takes K = 15 too" | -| FR-03-05 | Self-test | `report.py` "one trial of the last block leaves the round part-run"
`report.py` "a round 5 run short of its last block says it is provisional"
`report.py` "a round-5 run owes no escalation and names the blocks still owed" | +| FR-03-04 | Self-test | `harness.py` "a round-5 run takes K = 15 and refuses more"
`harness.py` "a K past the registered ceiling refuses"
`harness.py` "a round-5d run of hand and short takes K = 15 too" | +| FR-03-05 | Self-test | `report.py` "one trial of the last block leaves the round part-run"
`report.py` "a round 5 run short of its last block says it is provisional"
`report.py` "a round-5 run short of its K names the blocks still owed" | ## 04 Failed and lost trials @@ -165,12 +162,11 @@ when: | -- | ---- | ---------- | | FR-12-01 | Self-test | `report.py` "a contrast crossing rounds carries no verdict and counts nowhere"
`report.py` "a comparison across rounds reads as not given, not too few runs" | | FR-12-02 | Self-test | `report.py` "a contrast across rounds is unpaired, with a verdict"
`report.py` "a round-5d run reads H4 against a reused `none`, unpaired"
`report.py` "an unpaired contrast leaves out two trials, not blocks" | -| FR-12-03 | Self-test | `report.py` "it prints every declared contrast its arms ran"
`report.py` "a three-arm run prints only its own contrasts"
`report.py` "an earlier round computes no round-5d contrast" | -| FR-12-04 | Self-test | `report.py` "an earlier round rescored prints app code without a verdict"
`report.py` "round 5 reports the files it supersedes without a verdict" | +| FR-12-03 | Self-test | `report.py` "it prints every declared contrast its arms ran"
`report.py` "a three-arm run prints only its own contrasts" | +| FR-12-04 | Self-test | `report.py` "round 5 reports the files it supersedes without a verdict" | | FR-12-05 | Self-test | `report.py` "the report links its appendix, and the appendix the record"
`report.py` "the appendix holds what produced the results, the radar's axes and the verdict vector, and nothing else" | | FR-12-06 | Self-test | `report.py` "the radar draws a panel per arm, with the bare ring, in both themes"
`report.py` "an axis is better minus worse over its rows with a verdict, None without one"
`report.py` "the summary is the radar, one image per theme" | | FR-12-07 | Self-test | `report.py` "the report names each approach and its verdict in plain words"
`report.py` "a better primary and no worse answers Yes"
`report.py` "a worse primary answers Worse"
`report.py` "nothing separated answers No" | -| FR-12-08 | Self-test | `report.py` "the report prints the section"
`report.py` "its row carries no verdict"
`report.py` "its row is not in the verdict vector"
`report.py` "no after-the-results check is a verdict metric" | | FR-12-09 | Self-test | `report.py` "withdrawal blanks every value of the row"
`report.py` "its verdict vector row reads withdrawn"
`report.py` "the withdrawal section names it and why"
`report.py` "a run graded by another revision withdraws nothing"
`report.py` "a metric not withdrawn keeps its verdict" | | FR-12-10 | Self-test | `score.py` "a score on another Python refuses the root"
`report.py` "scores on two Pythons are refused"
`report.py` "a run graded by another revision withdraws nothing" | diff --git a/docs/decisions/003-k-blocks-and-escalation.md b/docs/decisions/003-k-blocks-and-escalation.md index 377b9ac..65c9107 100644 --- a/docs/decisions/003-k-blocks-and-escalation.md +++ b/docs/decisions/003-k-blocks-and-escalation.md @@ -18,9 +18,9 @@ blocks until an effect turns significant is sampling to significance. ## Decision -A round fixes K before its first trial, at K = 15 with no escalation from -round 5, while a round registered at K = 3 escalates at most once, to K = 5, on -an effect in either direction. +A round fixes K before its first trial, at K = 15 from round 5, and no run +goes past it. Rounds 1 to 4, registered at K = 3 with one bounded escalation +to K = 5, are retired, and the escalation with them. ## Rationale @@ -40,7 +40,7 @@ The rules a round's K follows: | # | Rule | In practice | | - | ---- | ----------- | | 1 | K is registered | Fixed by the round's registration before its first trial | -| 2 | Escalation | Only a round registered at K = 3: one step to K = 5, owed by an effect in either direction on any contrast; a row with no interval triggers nothing | +| 2 | No escalation | A run stops at its registered K; the one bounded escalation of a K = 3 round is retired with rounds 1 to 4 | | 3 | Block order | Each block starts one arm later than the last | | 4 | One lettered block | Round 5 runs block A alone; blocks B and C wait for a later round | @@ -51,6 +51,7 @@ What the history of this decision left behind: | Consequence | Effect | | ----------- | ------ | | Round 3 stays at K = 3 | Its K = 5 escalation is recorded as unrunnable, since its run root no longer exists | +| Rounds 1 to 4 are retired | Their `full` arm, their contrasts and the escalation leave the benchmark; each is re-run only from the benchmark at its own commit, and the benchmark proper starts with round 6 | ## History @@ -62,3 +63,4 @@ Every change to this decision, oldest first: | 2026-09-15 | The escalation reads the effect in either direction, on any contrast; a row with no interval triggers nothing | An escalation owed only to a favourable effect would lean toward "better" | — | | 2026-10-15 | Round 3's K = 5 escalation is recorded as unrunnable, and its report stays at K = 3 | The escalation adds blocks 4 and 5 to round 3's root, which no longer exists; re-running the whole round would not reproduce the three blocks its report read | solid-ai-templates#1767 | | 2026-10-27 | Round 5 runs block A alone, at K = 15 with no escalation, each block starting one arm later; adherence is held within 8 pp, and H2 reads the mean over pairs of trials. Blocks B and C wait for a later round | The report's rules, run on round 3's per-trial noise, decide almost nothing at K = 3: H1 is supported in 29 % of rounds when true, and a chance "worse" turns up in 36 %. At K = 15 those are 73 % and 12 %. On round 4's noise, B and C would contradict block A by chance at any affordable K | — | +| 2026-11-04 | Rounds 1 to 4 are retired with their K = 3 design and its escalation; the benchmark proper starts with round 6 | No remaining round reads at K = 3, and an earlier round is re-run from the benchmark at its own commit | #91 | diff --git a/docs/diagrams/escalation.drawio b/docs/diagrams/escalation.drawio deleted file mode 100644 index 2ade409..0000000 --- a/docs/diagrams/escalation.drawio +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/diagrams/escalation.png b/docs/diagrams/escalation.png deleted file mode 100644 index 50ae2f6..0000000 Binary files a/docs/diagrams/escalation.png and /dev/null differ diff --git a/docs/requirements.md b/docs/requirements.md index f5323f2..ecc9e1f 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -55,13 +55,13 @@ | FR-02-08 | The benchmark shall call a trim free only where every metric held. | Report | | FR-02-09 | The benchmark shall call every interval descriptive below K = 6. | Report | -### 03 Trial count and escalation +### 03 Trial count | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-03-01 | The benchmark shall owe an escalation to K = 5 where a primary's interval contains zero while its mean difference exceeds the smallest change that matters, in any contrast and either direction. | Report | -| FR-03-02 | The benchmark shall run an escalation as two more blocks, once, and never past K = 5. | Harness, Report | -| FR-03-03 | The benchmark shall print an escalated round's K = 3 and K = 5 results side by side, and a row still open at K = 5 as inconclusive. | Report | +| FR-03-01 | Removed: the escalation to K = 5 belonged to rounds registered at K = 3, retired with rounds 1 to 4. | - | +| FR-03-02 | Removed: with FR-03-01. | - | +| FR-03-03 | Removed: with FR-03-01. | - | | FR-03-04 | The benchmark shall refuse a block past the K a round registers. | Harness | | FR-03-05 | The benchmark shall call a run short of its registered K part-run, and give none of its verdicts as the round's. | Report | @@ -172,7 +172,7 @@ | FR-12-05 | The benchmark shall write a report, an appendix and a record for each round, each linking the next. | Report | | FR-12-06 | The benchmark shall draw one radar panel per file arm against `none`, in both themes, each axis better minus worse over its rows with a verdict. | Report | | FR-12-07 | The benchmark shall give each approach Yes where a deciding measure is better and none worse, Worse where any is worse, and No where none moved. | Report | -| FR-12-08 | The benchmark shall print a check declared after a run in its own section, with no verdict, outside the verdict vector. | Report | +| FR-12-08 | Removed: rounds 1 and 2's security checks, declared after their runs, were printed apart; from round 3 every check is a probe declared before the run, and those rounds are retired. | - | | FR-12-09 | The benchmark shall blank a withdrawn metric on every run its grader's revision graded, and keep it on the others. | Report | | FR-12-10 | The benchmark shall fix a fault found in its instruments, validate the fix, re-score in full every round that reads the faulty scores, and replace each report with a dated note keeping the verdicts it replaces. | Scorer, Report, Owner | | FR-12-11 | Removed: merged into FR-12-10. | - | diff --git a/docs/rounds/README.md b/docs/rounds/README.md index 9b53deb..19af65f 100644 --- a/docs/rounds/README.md +++ b/docs/rounds/README.md @@ -5,6 +5,13 @@ before its first trial runs. Nothing in a registration changes once a trial of that round has run. The rules every round shares are in [chapter 8](../architecture/08-crosscutting-concepts.md). +Rounds 1 to 5d are the pilot. They shaped the benchmark, and each is re-run +only from the benchmark at its own commit: the current version carries no +arm, contrast or rule that only they used. The benchmark proper starts with +round 6. From there a round is named by a letter for the knob it turns and a +number for how often that knob has been turned, as `A3` for the third round +that moved the arms; the trials inside keep their names, `inline-1`, `none-1`. + | Round | Registered | Asks | | ----- | ---------- | ---- | | [Round 4](round-4.md) | Before its first trial, after round 3 | Does a file supply what a thin spec leaves out, and help a weaker model more | diff --git a/tests/efficacy/archive.py b/tests/efficacy/archive.py index a372645..0f10220 100644 --- a/tests/efficacy/archive.py +++ b/tests/efficacy/archive.py @@ -299,8 +299,7 @@ def figures(root, seed): withdrawn = report.withdrawals(trials) report.withdraw(withdrawn, table, results) return {"table": table, "results": results, "withdrawn": withdrawn, - "escalation": report.assess_escalation(trials, results, seed, - withdrawn, root), + "owed_blocks": report.owed_blocks(trials), "reach": report.reaches(root), "lost": [{key: value for key, value in loss.items() if key != "kept"} @@ -390,7 +389,7 @@ def plant_root(scratch): area = scoring_area(root) started = datetime.datetime(2026, 10, 1, 12, 0, 0) records = [] - for arm, task in (("none", "build"), ("full", "build"), + for arm, task in (("none", "build"), ("hybrid", "build"), ("none", "change")): name = "%s-1" % arm if task == "build" else "change-%s-1" % arm workspace = os.path.join(root, name) @@ -403,17 +402,17 @@ def plant_root(scratch): "started_at": started.isoformat(), "frozen": {"head": "h", "tarball": tarball}}) - # The voided attempt ran in full-1's workspace before its re-run, so its + # The voided attempt ran in hybrid-1's workspace before its re-run, so its # transcript sits in the same folder and is older than the re-run's start. - void_dir = os.path.join(root, "void", "full-1-2026-10-01T11-00-00") + void_dir = os.path.join(root, "void", "hybrid-1-2026-10-01T11-00-00") os.makedirs(void_dir) - records.insert(1, {"arm": "full", "trial": 1, "task": "build", + records.insert(1, {"arm": "hybrid", "trial": 1, "task": "build", "outcome": "blocked", "reason": "planted", "workspace": records[1]["workspace"], "started_at": "2026-10-01T11:00:00", "void": {"dir": void_dir}, "frozen": {"tarball": os.path.join(void_dir, - "full-1.tar")}}) + "hybrid-1.tar")}}) write_run(os.path.join(root, "run-planted.json"), started, records) for record in records: if record["outcome"] != "completed": @@ -435,7 +434,7 @@ def plant_root(scratch): "w", encoding="utf-8") as handle: handle.write('{"token": "planted-secret"}') - for name, arm in (("none-1", "none"), ("full-1", "full")): + for name, arm in (("none-1", "none"), ("hybrid-1", "hybrid")): for kind in READINGS: dump_json(os.path.join(area, kind, "%s.json" % name), {"name": name, "arm": arm, "trial": 1, @@ -487,12 +486,12 @@ def self_test(): len(manifest["transcripts"]) == 4 and not any("credentials" in key for key in files)), ("readings, judgings, map and lock come; bundles do not", - {"scoring/scores/none-1.json", "scoring/security-scores/full-1.json", + {"scoring/scores/none-1.json", "scoring/security-scores/hybrid-1.json", "scoring/scores-change/none-1.json", "scoring/judge/T1.json", "scoring/judge/map.json", "scoring/tool-lock.txt"} <= set(files) and not any("bundle" in key for key in files)), ("a voided directory is kept as a marker", - manifest["voided"] == ["full-1-2026-10-01T11-00-00"] + manifest["voided"] == ["hybrid-1-2026-10-01T11-00-00"] and os.path.isfile(os.path.join(into, "void", manifest["voided"][0], VOID_MARKER))), ("the revisions are recorded", @@ -508,7 +507,7 @@ def self_test(): records[0]["frozen"]["tarball"] == os.path.join(restored, "none-1.tar") and records[1]["void"]["dir"] - == os.path.join(restored, "void", "full-1-2026-10-01T11-00-00") + == os.path.join(restored, "void", "hybrid-1-2026-10-01T11-00-00") and records[0]["workspace"] == os.path.join(root, "none-1")), ("a restored transcript keeps its time", abs(os.path.getmtime(os.path.join(restored, relative)) @@ -520,7 +519,7 @@ def self_test(): # The control: a reading changed in the archive must show in the verify, # or its clean result above proves nothing. changed = os.path.join(scoring_area(into), "security-scores", - "full-1.json") + "hybrid-1.json") before = load_json(changed).get("security_probe_pass_rate") dump_json(changed, dict(load_json(changed), security_probe_pass_rate={"value": 0.5})) @@ -552,7 +551,7 @@ def self_test(): leftovers = [os.path.join(area, "scoring", "none-1", "tree"), os.path.join(area, "scoring", "none-1", "venv"), os.path.join(area, "scoring-change", "none-1", "tree"), - os.path.join(area, "security", "full-1", "venv")] + os.path.join(area, "security", "hybrid-1", "venv")] for folder in leftovers: os.makedirs(folder, exist_ok=True) with io.open(os.path.join(folder, "left.txt"), "w") as handle: diff --git a/tests/efficacy/arms/full/CLAUDE.md b/tests/efficacy/arms/full/CLAUDE.md deleted file mode 100644 index a609310..0000000 --- a/tests/efficacy/arms/full/CLAUDE.md +++ /dev/null @@ -1,391 +0,0 @@ -# CLAUDE.md — tariff - -Project: `tariff` -Owner: Imbra Ltd -Repository: not yet set (add the URL here when the remote exists) -Agent context file: `CLAUDE.md` - -## 1. Project - -`tariff` is a pricing and invoicing web application for Imbra Ltd. It holds a product catalog, discount rules of several kinds, tax jurisdictions and customers, and assembles invoices from them. - -Two actors use it: - -- **The administrator**, the only account, works in a browser. -- **Another program** imports the pricing engine as a library and consumes invoice exports. - -The web application is one caller of the engine. The engine MUST work without the web application present. - -The program's interfaces are the library's own API and the invoice exports. Nothing reaches the network. The store is a local SQLite file. The application runs locally, with no deployment target. - -Customers are people. The store holds their name, email and postal address, and invoices name them. The business is in the EU, so the GDPR applies. A customer may ask for their data to be erased or for a copy of it, and the application MUST be able to do both (section 7). - -## 2. Stack - -| Concern | Choice | -| --- | --- | -| Language | Python 3.12 | -| Web framework | Flask 3, application factory, blueprints | -| Templates | Jinja2 with autoescape, server-rendered | -| Interactivity | HTMX 2.x, vendored under `static/` and never loaded from a CDN | -| Store | SQLite, one local file | -| Packaging | uv, with `pyproject.toml` and a committed `uv.lock` | -| Lint and format | ruff (`ruff check`, `ruff format`) | -| Types | mypy `--strict` | -| Cognitive complexity | complexipy | -| SAST | bandit | -| Tests | pytest with pytest-cov | -| Secrets | gitleaks, in pre-commit and CI | -| Hooks | pre-commit | - -Not adopted, each with a revisit trigger: - -| Candidate | Why not | Revisit when | -| --- | --- | --- | -| Containers, CI/CD deploy stages, IaC, Kubernetes | There is no deployment target. | A deployment target is chosen. | -| Feature flags | Nothing is rolled out progressively. | A second operator or environment exists. | -| Messaging and background jobs | Nothing is asynchronous. | An operation exceeds one request's budget. | -| Alpine.js | HTMX and plain HTML cover current needs. | Client-only state beyond a single toggle appears. | -| Distributed tracing | It is a single local process. | The application is split into more than one process. | -| Mutation testing | The suite is not yet mature. | The engine's suite is stable and its rules carry real money. | - -Declining a candidate needs at most a line in the PR. It needs no ADR or ticket. - -## 3. Project structure - -`README.md` is the single source of truth for the directory tree. This section holds only the placement rules for agents. - -- `src/tariff/engine/` is the pricing engine library. It holds the catalog model, discount rules, tax calculation, invoice assembly, exports and the public API in `__init__.py`. -- `src/tariff/store/` holds SQLite access (repositories, unit of work) and migrations. -- `src/tariff/web/` holds the Flask factory, blueprints per domain, templates and static files. - - Blueprints: `catalog`, `discounts`, `tax`, `customers`, `invoices`, `auth`. - - Partials live in `templates/partials/`. -- `tests/` holds `unit/`, `integration/` and `e2e/`, plus `tests/component/` for route-level tests. -- `examples/` is optional. If created, it needs its own `README.md` and follows section 13. -- `docs/` holds `ONBOARDING.md`, `PLAYBOOK.md`, `dev-journal.md` and `decisions/`. - -### The boundary that must not be crossed - -- `tariff.engine` MUST NOT import `flask`, `werkzeug`, `jinja2`, `tariff.web` or `tariff.store`. The engine depends on nothing but the standard library and its own modules. -- The engine receives data through parameters and protocols (for example a `CatalogReader` protocol) that `store` and `web` implement. This is dependency inversion. -- `tariff.store` MUST NOT import `tariff.web`. -- The web layer depends on both the store and the engine. It calls the engine and never re-implements pricing. - -Check this after committing. Pass condition: it prints the module count, then `layering violations: 0`, and exits zero. - -```bash -py - <<'EOF' -import ast, pathlib - -ROOT = pathlib.Path("src") -FORBIDDEN = ( - ("tariff.engine", "flask"), - ("tariff.engine", "werkzeug"), - ("tariff.engine", "jinja2"), - ("tariff.engine", "tariff.web"), - ("tariff.engine", "tariff.store"), - ("tariff.store", "tariff.web"), -) - -def imported(tree): - names = [] - for node in ast.walk(tree): - if isinstance(node, ast.Import): - names.extend(alias.name for alias in node.names) - elif isinstance(node, ast.ImportFrom) and node.module: - names.append(node.module) - return names - -files = sorted(ROOT.rglob("*.py")) -print("modules inspected: %d" % len(files)) -findings = [] -for path in files: - module = ".".join(path.relative_to(ROOT).with_suffix("").parts) - for name in imported(ast.parse(path.read_text(encoding="utf-8"))): - for importer, banned in FORBIDDEN: - if module.startswith(importer) and ( - name == banned or name.startswith(banned + ".") - ): - findings.append("%s imports %s" % (module, name)) -print("layering violations: %d" % len(findings)) -for finding in findings: - print(" " + finding) -raise SystemExit(1 if findings or not files else 0) -EOF -``` - -A count of zero modules is a failure. It means the enumeration reached nothing. - -## 4. Off-limits paths - -These MUST NOT be modified without a proposal first. The proposal carries a rollback strategy and the tests that would catch a regression. The approval covers that plan, not the area. - -- Auth and session code (`tariff/web/auth/`, session configuration, the password hash and login flow). -- Schema migrations (`tariff/store/migrations/`). Never edit a merged migration. -- `.env*` and anything handling secrets. This includes the secret key and the administrator credential. -- The personal-data erasure and export code (section 7). A defect there is a GDPR defect. -- The public API of `tariff.engine` (`__init__` exports) and the invoice export formats. Both are observable interfaces (section 12). -- CI workflow definitions (`.github/workflows/`), if and when they exist. - -A diff touching one of these paths MUST say so at the top of its summary, naming the path, whether or not it owes a proposal. A diff confined to comments and prose is ordinary work. A `# noqa` or `# nosec` line is executable, and so is one that touches a comment and a step. - -## 5. Commands - -``` -uv sync --locked # install from the lock -uv run flask --app tariff.web run --debug # run locally on 127.0.0.1 -uv run pytest # fast tier: unit + integration -uv run pytest --cov=tariff # with coverage -uv run ruff check src tests # lint -uv run ruff format --check src tests # format check -uv run mypy src tests --strict # types -uv run complexipy src # cognitive complexity -uv run bandit -r src # SAST -pre-commit run --all-files # every hook -``` - -Before every commit, run pytest, mypy, ruff and pre-commit, and read the output. A local run is evidence about one platform. - -## 6. Configuration - -- All configuration comes from environment variables with the `TARIFF_` prefix (for example `TARIFF_DATABASE_PATH`, `TARIFF_SECRET_KEY`, `TARIFF_PORT`). -- `.env.example` is committed with placeholders. `.env` is gitignored. -- One typed `Settings` object is built once in `create_app` and passed explicitly. There are no config globals in engine or service code. -- Required settings that are missing or invalid fail at startup with a message naming the setting. -- The secret key and the administrator credential are required and have no default. -- The engine reads no environment variable. Its configuration (rounding policy, currency) is passed in. -- Bind to `127.0.0.1` by default. The port comes from `TARIFF_PORT`. Binding to another interface needs an explicit setting and an explicit decision. -- Config precedence is default, then file, then environment, then CLI flag. An empty value is an error, not a fallback to the default. - -## 7. Personal data (GDPR) - -Personal data means a customer's name, email and postal address, wherever they appear: the store, invoices, exports, logs, test fixtures and error messages. - -- **Minimise.** Store only the personal fields the product needs. Add a new personal field only with a stated purpose in the PR. -- **Export.** One function in the store layer produces a complete copy of one customer's data (record and invoices naming them) as JSON, in a machine-readable form. It is reachable from the administrator's UI. Tests assert that every personal column in the schema appears in the export, so a newly added column fails the test until it is exported. -- **Erasure.** One function erases or anonymises one customer's personal fields in a single transaction. - - Invoices already issued keep their amounts, tax lines and numbering, but the customer's name and address on them are replaced by a non-identifying placeholder that keeps the invoice referentially intact. - - Whether Imbra's tax or accounting retention duty requires keeping the issued name for a period is a decision for the owner. Until an ADR records it, anonymise and do not hard-delete invoices. - - Tests assert that no personal value survives in any table or export after erasure. This includes free-text fields and any audit or history table. -- **No personal data outside the store.** - - Never log names, emails or addresses. Log customer ids only. - - Error responses do not echo personal data. - - Fixtures and examples use synthetic data only. Never copy a real customer into a test. - - Exports and any file the app writes outside the SQLite file are written only where the administrator asks, and the UI says so. -- **The SQLite file** lives outside the repository (path from `TARIFF_DATABASE_PATH`) and is gitignored. Never commit a database file, dump or backup. Treat every repository as public. -- **Backups** of the file contain personal data. The playbook names where they go and that an erased customer reappears if a pre-erasure backup is restored, so the erasure is re-applied. -- Changing what is collected, how erasure behaves or the export shape is an observable change. It needs an ADR (section 12) and a `CHANGELOG.md` entry. - -## 8. Security - -There is one administrator and no other account. No network access is expected, but the application is still an authenticated web application. - -- **Authentication.** - - The administrator's password is stored hashed with scrypt (Werkzeug `generate_password_hash`) or Argon2. Never store it plain, and never use MD5, SHA-1 or plain SHA-256. - - Compare secrets in constant time. - - Throttle failed logins. - - Login errors say "invalid credentials" and nothing more. - - Every route except the login page and the health endpoint requires the session. Apply the check in one `before_request` guard on the app, not per route, so a new blueprint cannot forget it. -- **Sessions.** Cookies are `HttpOnly`, `SameSite=Lax`, and `Secure` whenever the app is served over HTTPS. The session id is regenerated at login. Sessions expire after 30 minutes idle, and logout invalidates the session server-side. -- **CSRF.** The session is authenticated by a cookie, so every `POST`, `PUT`, `PATCH` and `DELETE` carries a CSRF token (Flask-WTF `CSRFProtect`, never hand-rolled). Every form renders the token. HTMX requests send it through `hx-headers` on ``. `GET` never changes state. -- **Injection and XSS.** Use parameterised queries only. Never build SQL by string interpolation. Jinja autoescape stays on, and never use `| safe` or `Markup` on data that a customer or the administrator typed. -- **Headers.** Set them in one `after_request` hook: a strict `Content-Security-Policy` (no `unsafe-inline`, no `unsafe-eval`, self-hosted scripts only), `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: strict-origin-when-cross-origin`, and a restrictive `Permissions-Policy`. - - Pin static MIME types in code, because `nosniff` makes the server the sole authority. - - Verify script execution in a real browser, not only status codes. - - HSTS applies only if the app is ever served over HTTPS. -- **Errors.** No stack traces, paths or SQL errors reach the browser. Return a generic message, log the detail with a request id, and use RFC 9457 `application/problem+json` for JSON error responses. Debug mode is never on outside local development. -- **Nothing reaches the network.** No CDN, font, analytics or telemetry call, and no outbound HTTP client. Adding one needs an ADR. SSRF rules apply the moment a URL from input is fetched. It is not fetched today. -- **Secrets.** None in source, history, commits, PRs or conversation. An agent MUST NOT read, print or cat `.env`, key or credential files. Check presence with `test -f .env && echo exists`. If a secret is exposed, flag it, name it and recommend rotating it. -- **Dependencies.** Commit `uv.lock` and install with `uv sync --locked`. Refresh the lock deliberately and name what refreshes it. Prefer maintained dependencies, remove unused ones, and check licences before adding one. GPL and AGPL need explicit approval. -- Run bandit and gitleaks (full history in CI) on every change. - -## 9. Architecture and code rules - -### Layers - -The order is route handler, then service function, then repository. Handlers are thin: decode the request, call a service, render or encode the response. No database access in handlers. No HTTP concerns in services. - -### Money and rounding - -- Amounts are `decimal.Decimal` or integer minor units, never `float`. In SQLite store integer minor units, because SQLite has no exact decimal type. -- Currency codes are ISO 4217. Timestamps are stored in UTC. -- The rounding rule (mode and the step at which it applies: per line or per invoice) is one named constant, stated once and covered by tests. -- Never scatter `round()` calls. - -### The engine - -- It is a library. Pricing logic is pure: same inputs give the same output, with no I/O, no clock and no global state. Pass "now" in as a parameter. -- Discount rules of several kinds are a Strategy: one small class per kind behind a common protocol, so adding a kind is adding a class and a registry entry rather than a new branch. -- Rule ordering and stacking (which rules combine, and in what order) is stated in one place, documented, and tested with worked examples. -- Errors the engine raises on purpose derive from one `TariffError` base, each type also deriving from the built-in its site raised before. A test walks every `raise` in the package and fails on one outside the hierarchy. The test also asserts it saw at least one raise. -- No abstract operation declares `*args` or `**kwargs`. -- Prefer free functions for stateless logic. Use a class when it owns state. -- Composition over inheritance, and hierarchies at most two levels deep. -- No AOP or hidden interception. Cross-cutting behaviour is explicit at a visible call site. - -### Public API - -- `tariff.engine` exports its public API from `__init__.py`. Everything else is private. Public functions carry full type hints and Google-style docstrings. -- The API is stable, following semver. Before removing or renaming a public symbol, deprecate it with a comment naming the replacement, and remove it in a follow-up. -- A rename spanning a method and its keyword arguments is deprecated together or not at all. -- Importing `tariff.engine` has no side effects and reads no file or environment. -- A library attaches `logging.NullHandler()` to its own logger and installs no writing handler. The logger is injectable. - -### Store - -- SQLite through one connection factory. Foreign keys on (`PRAGMA foreign_keys = ON`) and WAL where it fits. -- Schema changes go only through versioned migrations, committed and never edited once merged. Each has an `up` and a `down`. -- Multi-step writes run in one transaction that is short and never spans a request. Timeouts are set on connections. No unbounded queries. -- Follow the data-modeling rules: - - snake_case plural table names - - `is_`/`has_` boolean prefixes - - `_id` foreign keys - - a documented maximum length on text columns - - foreign keys defined explicitly with a deliberate cascade choice -- Tests use a real SQLite file or `:memory:`. SQLite is the production engine, so this is not a substitute. - -### HTMX and templates - -- The server owns state. Endpoints return HTML. -- Detect HTMX with the `HX-Request` header. Return the partial for HTMX requests and the full page otherwise. -- Return `204` when nothing changes on screen. Return `422` with the re-rendered form and inline field errors on validation failure. Never redirect to a blank form after a failed `POST`. -- Every HTMX interaction sets `hx-target` and `hx-swap` explicitly. Use `hx-push-url` only on real navigation. -- Use `hx-indicator` and `hx-disabled-elt` on submits so nothing is submitted twice. -- Pages work without JavaScript, and HTMX enhances them. -- Partials are named for what they render (`partials/invoice_lines.html`) and take all data as explicit context. Keep at most two or three OOB targets per response. -- Templates hold conditionals and loops only. No business logic. Keep one template per view and extract repeated markup. -- Accessibility target: WCAG 2.1 AA. Use semantic HTML, labelled fields, `:focus-visible`, and full keyboard operation. - -### Validation and requests - -- Validate at the boundary with a schema (Pydantic or an equivalent), allowlisting rather than blocklisting. Internal code trusts validated data. -- Parse typed query parameters explicitly, so absent, valid and invalid are three distinct states. Invalid means `400`, never a silent default. -- URLs use lowercase hyphenated nouns, plural collections, nested sub-resources, no trailing slash, and camelCase query parameters. -- List views are paginated. - -### General quality - -- DRY, KISS, YAGNI. Every deferral names its revisit trigger. -- Names are the documentation. Functions take a verb, classes a noun, booleans `is_`, `has_` or `can_`. Use no single-letter names except loop counters and `e` in `except`. -- No boolean flag parameters. Use two named functions or an enum. -- Cognitive complexity is at most 15 per function, and nesting at most three levels. Use guard clauses. -- Magic numbers and strings become named constants. A threshold sized from data records its data source. -- No circular dependencies. Shared logic moves to a third module, never a local copy. -- Fail fast at boundaries. Fail loudly rather than fall back to a derived value. -- Every wait on another thread, process or connection is bounded and reports why it gave up. -- No dead code, no commented-out code, no debug `print`, no `pdb`. Debug tooling sits behind a flag. -- A workaround comment naming a rejected mechanism is a prompt to grep the codebase for that mechanism. -- Comments are for intent the code cannot express. Never cite a ticket, PR or ADR number in a code comment. A block comment sits directly above its item, and a trailing comment is only a tool directive. -- Identifiers are ASCII. Files are UTF-8 with LF endings. Commit `.editorconfig` and `.gitattributes` (`* text=auto`). A program that writes text sets its encoding and line ending explicitly at the boundary. -- A destructive operation (delete, truncate, overwrite) acts only on what it can prove it created. Erasure (section 7) deletes by key, never by a broad filter. -- Probe scripts are named `probe_*.py` and deleted before the commit that uses their findings. - -## 10. Testing - -- The fast tier (unit and integration) is the default `pytest` run. The tier follows from the directory, set by one collection hook. The e2e tier is opt-in behind a marker. -- **Unit:** - - Engine logic is tested with pure inputs and no mocks. - - Cover each discount kind, stacking and ordering, each tax jurisdiction, rounding edges, zero and negative quantities, and empty invoices. - - Use worked examples with hand-computed expected totals from the business rules, not values produced by the code under test. - - Use `pytest.mark.parametrize` for data-driven cases. -- **Integration:** real SQLite. Cover repositories, migrations up and down, and the erasure and export functions. -- **Component:** Flask test client per route. Cover success, `400`/`422` validation, `401` or redirect when unauthenticated, `404`, missing CSRF token rejected, and the partial versus full page split on `HX-Request`. -- **Engine boundary:** a test imports `tariff.engine` in a fresh interpreter with Flask blocked (for example a stub that raises on import) and exercises the public API. -- **Export contract:** each invoice export format is asserted against a fixed reference file. A round trip through our own writer and reader proves only self-consistency. -- **GDPR tests:** as in section 7. They assert that erasure and export cover every personal column. -- **Negative assertions** assert their inputs were reached. Assert the count of files, rows or records examined, not only that a set is empty. -- Tests are independent, share no mutable state and set environment variables explicitly per test. A test never touches host state outside the working directory. -- Never skip or weaken a failing test without a documented reason. A change that deletes or loosens an existing test states why. A change that adds tests needs no ceremony. -- Coverage is at least 80% overall and at least 90% of new code. It must not regress. Name the `omit` list, and adding to it is a reviewable decision. -- A test asserting a numeric threshold names what it pins. -- A visual or template change is verified against the rendered page, not the source. -- Verify a fix fires on real data, not only on a synthetic case. - -## 11. Quality gates - -Every category runs at three layers. CI is the backstop and duplicates pre-commit, because hooks can be bypassed. - -| Category | Editor | Pre-commit | CI | -| --- | --- | --- | --- | -| Lint (ruff) | yes | yes | yes | -| Format (ruff format) | yes | yes | yes | -| Types (mypy strict) | yes | yes | yes | -| Secrets (gitleaks) | | yes | yes | -| File hygiene | | yes | | -| SAST (bandit) | | | yes | -| Cognitive complexity (complexipy) | | | yes | -| Tests and coverage | | | yes | -| Layering check (section 3) | | | yes | - -- Thresholds: zero lint, format and type errors, and zero high or critical findings. Coverage is at least 80%. -- Ruff `D` rules use the Google convention, exempt for `tests/**`. Configuration lives only in `pyproject.toml`. -- mypy runs `--strict` from the first commit. Never weaken it globally. Scope an escape for an untyped third-party library to a per-module override with a stated reason. -- Site-local suppressions name the rule (`# noqa: B017`) and are never bare. The reason sits on the line above. -- When a gate is red, fix the source. Never narrow the gate, and never edit the input a check reads to make a finding disappear. Freeze existing instances by name only, never by count. -- A check states what it inspected as well as what it found, and its exit status carries its verdict. -- A skipped check is not a passed check. -- If a repository host enforces branch protection, CI checks are required status checks and bind administrators. -- CI runs the same Python version that `.python-version`, `requires-python` and mypy's `python_version` name (3.12), so every gate validates the runtime that runs the app. - -## 12. Git, documentation and decisions - -### Git - -- Always work on a branch and never commit to `main`. Branch names are `feat/…`, `fix/…`, `chore/…` or `docs/…`. -- Commit messages use conventional prefixes (`feat:`, `fix:`, `chore:`, `docs:`, `refactor:`, `style:`, `test:`), the imperative mood and a subject under 80 characters. When a single-commit branch closes an issue, the subject carries the issue reference. -- PRs are small, with one concern each. Test locally, then read the CI run before calling the change good. Repeat the closing keyword before each issue number, and never write a closing keyword next to a number you only mean to reference. -- Never force-push, including `--force-with-lease`. Merge `main` into a stale branch, then regenerate any derived artifact. -- Regenerate derived artifacts in the same change that edits their source. -- Do not commit build output, `.venv/`, `__pycache__/`, `.mypy_cache/`, `*.db`, `*.sqlite*`, exports containing personal data, or `.env`. Commit the lockfile. `.gitignore` exists from the first commit. -- Before merging, review the diff in priority order: security, correctness, clarity, conventions. Personal-data handling is part of security. -- Tags are annotated `vX.Y.Z` and follow semver. A patch means fixes only, a minor adds compatibly, and a major breaks the API or an export format. - -### Documentation - -- `README.md` follows the nine-section structure: title and summary, features, quick start, usage, project structure, development setup, configuration reference, links, licence last. It is the source of truth for the directory tree. -- `docs/ONBOARDING.md` has six numbered sections in order: prerequisites, first-time setup, verify the setup, key files, project context, daily workflow. -- `docs/PLAYBOOK.md` has five numbered sections in order: git workflow, domain operations (add a discount kind, add a tax jurisdiction, add a personal field, run an erasure or export), quality, maintenance, release and deploy. Release and deploy stays last, and here it means tagging and publishing the library. There is no deployment. -- `docs/dev-journal.md` is required. Session entries run oldest first, with the heading `## YYYY-MM-DD — Short theme`. Each records Tool, Key changes, PRs merged, Issues closed/created, and Lesson. A P0 or P1 fix or an incident adds a post-mortem. -- Update the relevant document before every commit. No document states a count or figure about the tree outside a generated block. -- Rules use RFC 2119 words. Write in the present tense, wrap Markdown at the width declared once in configuration, and write for a reader who lacks context. -- `CHANGELOG.md` follows Keep a Changelog, with an `Unreleased` section maintained by the change that causes each entry. Entries are at most 40 words and say what changed and what a reader must do. A breaking change names the migration. -- **ADRs.** A decision needs an ADR in `docs/decisions/` (`NNN-slug.md`, YAML frontmatter, supersession through the frontmatter only) when it changes something observable without reading the internals. Here that means: - - the engine's public API - - the invoice export formats - - discount stacking and rounding semantics - - what personal data is kept, and how erasure or export behaves - - any new outbound network path - - Tool choices, layout and process end in the PR. An ADR is not edited once merged, except for format-only changes. -- When a document disagrees with the system, establish which is wrong before changing either. -- Adopting shared rules: - - Templates supply candidate conventions, and the project chooses what it adopts. - - A template update creates no compliance work by itself. - - Rules already adopted here stay in force until this project changes them. - - Declining a new candidate needs no ADR or ticket. - -## 13. Examples - -If an `examples/` directory is created, one file shows one pattern or journey, for instance pricing a basket through the library without the web app. - -- The directory has its own `README.md`, and each example appears there as an exact command with real output. -- Examples run offline against the project's own code and synthetic data. -- Examples are excluded from any built package, and CI runs each one after a plain `uv sync`. -- An example that verifies something exits non-zero on failure. - -## 14. Working with the agent - -- **Plan before implementing.** For a feature or a non-trivial change, first give the files to touch, the function signatures, the edge cases and the assumptions. Wait for approval before writing implementation code. Single-line fixes, typos and fully specified changes are exempt. If a constraint invalidates an approved plan, stop and re-surface the options. -- **Verify an issue before implementing it.** Re-read the target for existing coverage, check whether an open PR already closes it, and check for ADRs accepted since it was filed. -- **Verify a finding before reporting it.** Reproduce the defect, or label the finding unverified. A finding from a subagent is a lead, not evidence. -- **Report faithfully.** If tests fail, say so with the output. If a step was skipped, say that. -- **Ask before hard-to-reverse or outward-facing actions.** That includes anything that deletes data, touches the real SQLite file, or sends anything anywhere. Nothing may reach the network. -- **Never use real personal data.** Use synthetic customers in tests, fixtures, examples, docs and conversation. -- **End-of-session audit.** Before ending a session that changed code: - 1. Run the full gate set from section 11. - 2. Run the layering check from section 3. - 3. Confirm the docs and `CHANGELOG.md` reflect the change. - 4. Confirm that no personal data, secret or database file is staged. - 5. State what was and was not verified. - - diff --git a/tests/efficacy/arms/full/generation.json b/tests/efficacy/arms/full/generation.json deleted file mode 100644 index 6595c96..0000000 --- a/tests/efficacy/arms/full/generation.json +++ /dev/null @@ -1,179 +0,0 @@ -{ - "arm": "full", - "output_model": "inline", - "budget": null, - "ref": "v2.90.0", - "commit": "4b1be7d8dec1186cc63d22f01969fc0c93ac822b", - "roots": [ - "stack-flask", - "stack-htmx", - "frontend-ux", - "frontend-quality" - ], - "resolved_files": [ - "templates/base/core/quality.md", - "templates/base/core/git.md", - "templates/base/core/docs.md", - "templates/base/core/readme.md", - "templates/base/core/testing.md", - "templates/base/core/review.md", - "templates/base/core/oop.md", - "templates/base/core/config.md", - "templates/backend/http.md", - "templates/backend/database.md", - "templates/backend/observability.md", - "templates/base/security/security.md", - "templates/base/infra/containers.md", - "templates/backend/quality.md", - "templates/backend/features.md", - "templates/backend/messaging.md", - "templates/base/infra/cicd.md", - "templates/base/security/devsecops.md", - "templates/base/data/data-modeling.md", - "templates/base/data/data-quality.md", - "templates/base/language/python.md", - "templates/base/core/cli.md", - "templates/base/workflow/quality-gates.md", - "templates/base/core/examples.md", - "templates/stack/python-lib.md", - "templates/stack/python-service.md", - "templates/stack/python-flask.md", - "templates/backend/templating.md", - "templates/stack/htmx.md", - "templates/frontend/ux.md", - "templates/frontend/quality.md" - ], - "prompt_chars": 586094, - "model": "claude-sonnet-5", - "effort": "high", - "started_at": "2026-09-26T12:16:08", - "prompt_leak": null, - "prompt_file": "C:/efficacy/gen-r3-full\\arm-full-prompt.txt", - "auth_probe": "ready", - "command": [ - "C:\\Users\\braboj\\AppData\\Roaming\\npm\\claude.CMD", - "-p", - "--output-format", - "json", - "--model", - "claude-sonnet-5", - "--effort", - "high", - "--permission-mode", - "bypassPermissions", - "--setting-sources", - "", - "--settings", - "C:/efficacy/gen-r3-full\\home\\settings.json", - "--strict-mcp-config", - "--disallowed-tools", - "WebSearch", - "WebFetch" - ], - "elapsed_s": 116.7, - "exit_status": 0, - "result": { - "duration_api_ms": 114951, - "stop_reason": "end_turn", - "session_id": "246a25a9-08d1-4f98-9a42-dbdf2315dd22", - "total_cost_usd": 0.94651, - "usage": { - "input_tokens": 2, - "cache_creation_input_tokens": 205647, - "cache_read_input_tokens": 15540, - "output_tokens": 12081, - "output_tokens_details": { - "thinking_tokens": 1679 - }, - "server_tool_use": { - "web_search_requests": 0, - "web_fetch_requests": 0 - }, - "service_tier": "standard", - "cache_creation": { - "ephemeral_1h_input_tokens": 205647, - "ephemeral_5m_input_tokens": 0 - }, - "inference_geo": "not_available", - "iterations": [ - { - "input_tokens": 2, - "output_tokens": 12081, - "cache_read_input_tokens": 15540, - "cache_creation_input_tokens": 205647, - "cache_creation": { - "ephemeral_5m_input_tokens": 0, - "ephemeral_1h_input_tokens": 205647 - }, - "type": "message" - } - ], - "speed": "standard" - }, - "modelUsage": { - "claude-sonnet-5": { - "inputTokens": 2, - "outputTokens": 12081, - "cacheReadInputTokens": 15540, - "cacheCreationInputTokens": 205647, - "webSearchRequests": 0, - "costUSD": 0.94651, - "contextWindow": 1000000, - "maxOutputTokens": 128000, - "thinkingTokens": 1679, - "canonicalModel": "claude-sonnet-5", - "provider": "firstParty", - "costBasis": "list" - } - }, - "permission_denials": [], - "terminal_reason": "completed", - "fast_mode_state": "off", - "fast_mode_disabled_reason": "sdk_opt_in_required", - "subagent_stats": { - "spawned": 0, - "requested": { - "background": 0, - "foreground": 0, - "unset": 0 - }, - "started_in_background": 0, - "max_depth": 0, - "spawned_by_subagents": 0, - "completed": 0, - "failed": 0, - "killed": { - "parent": 0, - "user": 0, - "system": 0 - }, - "refused": { - "depth_limit": 0, - "concurrency_limit": 0, - "budget": 0 - }, - "by_type": {} - }, - "is_error": false, - "num_turns": 1, - "subtype": "success", - "api_error_status": null, - "result": "# CLAUDE.md \u2014 tariff\n\nProject: `tariff`\nOwner: Imbra Ltd\nRepository: not yet set (add the URL here when the remote exists)\nAgent context file: `CLAUDE.md`\n\n## 1. Project\n\n`tariff` is a pricing and invoicing web application for Imbra Ltd. It holds a product catalog, discount rules of several kinds, tax jurisdictions and customers, and assembles invoices from them.\n\nTwo actors use it:\n\n- **The administrator**, the only account, works in a browser.\n- **Another program** imports the pricing engine as a library and consumes invoice exports.\n\nThe web application is one caller of the engine. The engine MUST work without the web application present.\n\nThe program's interfaces are the library's own API and the invoice exports. Nothing reaches the network. The store is a local SQLite file. The application runs locally, with no deployment target.\n\nCustomers are people. The store holds their name, email and postal address, and invoices name them. The business is in the EU, so the GDPR applies. A customer may ask for their data to be erased or for a copy of it, and the application MUST be able to do both (section 7).\n\n## 2. Stack\n\n| Concern | Choice |\n| --- | --- |\n| Language | Python 3.12 |\n| Web framework | Flask 3, application factory, blueprints |\n| Templates | Jinja2 with autoescape, server-rendered |\n| Interactivity | HTMX 2.x, vendored under `static/` and never loaded from a CDN |\n| Store | SQLite, one local file |\n| Packaging | uv, with `pyproject.toml` and a committed `uv.lock` |\n| Lint and format | ruff (`ruff check`, `ruff format`) |\n| Types | mypy `--strict` |\n| Cognitive complexity | complexipy |\n| SAST | bandit |\n| Tests | pytest with pytest-cov |\n| Secrets | gitleaks, in pre-commit and CI |\n| Hooks | pre-commit |\n\nNot adopted, each with a revisit trigger:\n\n| Candidate | Why not | Revisit when |\n| --- | --- | --- |\n| Containers, CI/CD deploy stages, IaC, Kubernetes | There is no deployment target. | A deployment target is chosen. |\n| Feature flags | Nothing is rolled out progressively. | A second operator or environment exists. |\n| Messaging and background jobs | Nothing is asynchronous. | An operation exceeds one request's budget. |\n| Alpine.js | HTMX and plain HTML cover current needs. | Client-only state beyond a single toggle appears. |\n| Distributed tracing | It is a single local process. | The application is split into more than one process. |\n| Mutation testing | The suite is not yet mature. | The engine's suite is stable and its rules carry real money. |\n\nDeclining a candidate needs at most a line in the PR. It needs no ADR or ticket.\n\n## 3. Project structure\n\n`README.md` is the single source of truth for the directory tree. This section holds only the placement rules for agents.\n\n- `src/tariff/engine/` is the pricing engine library. It holds the catalog model, discount rules, tax calculation, invoice assembly, exports and the public API in `__init__.py`.\n- `src/tariff/store/` holds SQLite access (repositories, unit of work) and migrations.\n- `src/tariff/web/` holds the Flask factory, blueprints per domain, templates and static files.\n - Blueprints: `catalog`, `discounts`, `tax`, `customers`, `invoices`, `auth`.\n - Partials live in `templates/partials/`.\n- `tests/` holds `unit/`, `integration/` and `e2e/`, plus `tests/component/` for route-level tests.\n- `examples/` is optional. If created, it needs its own `README.md` and follows section 13.\n- `docs/` holds `ONBOARDING.md`, `PLAYBOOK.md`, `dev-journal.md` and `decisions/`.\n\n### The boundary that must not be crossed\n\n- `tariff.engine` MUST NOT import `flask`, `werkzeug`, `jinja2`, `tariff.web` or `tariff.store`. The engine depends on nothing but the standard library and its own modules.\n- The engine receives data through parameters and protocols (for example a `CatalogReader` protocol) that `store` and `web` implement. This is dependency inversion.\n- `tariff.store` MUST NOT import `tariff.web`.\n- The web layer depends on both the store and the engine. It calls the engine and never re-implements pricing.\n\nCheck this after committing. Pass condition: it prints the module count, then `layering violations: 0`, and exits zero.\n\n```bash\npy - <<'EOF'\nimport ast, pathlib\n\nROOT = pathlib.Path(\"src\")\nFORBIDDEN = (\n (\"tariff.engine\", \"flask\"),\n (\"tariff.engine\", \"werkzeug\"),\n (\"tariff.engine\", \"jinja2\"),\n (\"tariff.engine\", \"tariff.web\"),\n (\"tariff.engine\", \"tariff.store\"),\n (\"tariff.store\", \"tariff.web\"),\n)\n\ndef imported(tree):\n names = []\n for node in ast.walk(tree):\n if isinstance(node, ast.Import):\n names.extend(alias.name for alias in node.names)\n elif isinstance(node, ast.ImportFrom) and node.module:\n names.append(node.module)\n return names\n\nfiles = sorted(ROOT.rglob(\"*.py\"))\nprint(\"modules inspected: %d\" % len(files))\nfindings = []\nfor path in files:\n module = \".\".join(path.relative_to(ROOT).with_suffix(\"\").parts)\n for name in imported(ast.parse(path.read_text(encoding=\"utf-8\"))):\n for importer, banned in FORBIDDEN:\n if module.startswith(importer) and (\n name == banned or name.startswith(banned + \".\")\n ):\n findings.append(\"%s imports %s\" % (module, name))\nprint(\"layering violations: %d\" % len(findings))\nfor finding in findings:\n print(\" \" + finding)\nraise SystemExit(1 if findings or not files else 0)\nEOF\n```\n\nA count of zero modules is a failure. It means the enumeration reached nothing.\n\n## 4. Off-limits paths\n\nThese MUST NOT be modified without a proposal first. The proposal carries a rollback strategy and the tests that would catch a regression. The approval covers that plan, not the area.\n\n- Auth and session code (`tariff/web/auth/`, session configuration, the password hash and login flow).\n- Schema migrations (`tariff/store/migrations/`). Never edit a merged migration.\n- `.env*` and anything handling secrets. This includes the secret key and the administrator credential.\n- The personal-data erasure and export code (section 7). A defect there is a GDPR defect.\n- The public API of `tariff.engine` (`__init__` exports) and the invoice export formats. Both are observable interfaces (section 12).\n- CI workflow definitions (`.github/workflows/`), if and when they exist.\n\nA diff touching one of these paths MUST say so at the top of its summary, naming the path, whether or not it owes a proposal. A diff confined to comments and prose is ordinary work. A `# noqa` or `# nosec` line is executable, and so is one that touches a comment and a step.\n\n## 5. Commands\n\n```\nuv sync --locked # install from the lock\nuv run flask --app tariff.web run --debug # run locally on 127.0.0.1\nuv run pytest # fast tier: unit + integration\nuv run pytest --cov=tariff # with coverage\nuv run ruff check src tests # lint\nuv run ruff format --check src tests # format check\nuv run mypy src tests --strict # types\nuv run complexipy src # cognitive complexity\nuv run bandit -r src # SAST\npre-commit run --all-files # every hook\n```\n\nBefore every commit, run pytest, mypy, ruff and pre-commit, and read the output. A local run is evidence about one platform.\n\n## 6. Configuration\n\n- All configuration comes from environment variables with the `TARIFF_` prefix (for example `TARIFF_DATABASE_PATH`, `TARIFF_SECRET_KEY`, `TARIFF_PORT`).\n- `.env.example` is committed with placeholders. `.env` is gitignored.\n- One typed `Settings` object is built once in `create_app` and passed explicitly. There are no config globals in engine or service code.\n- Required settings that are missing or invalid fail at startup with a message naming the setting.\n- The secret key and the administrator credential are required and have no default.\n- The engine reads no environment variable. Its configuration (rounding policy, currency) is passed in.\n- Bind to `127.0.0.1` by default. The port comes from `TARIFF_PORT`. Binding to another interface needs an explicit setting and an explicit decision.\n- Config precedence is default, then file, then environment, then CLI flag. An empty value is an error, not a fallback to the default.\n\n## 7. Personal data (GDPR)\n\nPersonal data means a customer's name, email and postal address, wherever they appear: the store, invoices, exports, logs, test fixtures and error messages.\n\n- **Minimise.** Store only the personal fields the product needs. Add a new personal field only with a stated purpose in the PR.\n- **Export.** One function in the store layer produces a complete copy of one customer's data (record and invoices naming them) as JSON, in a machine-readable form. It is reachable from the administrator's UI. Tests assert that every personal column in the schema appears in the export, so a newly added column fails the test until it is exported.\n- **Erasure.** One function erases or anonymises one customer's personal fields in a single transaction.\n - Invoices already issued keep their amounts, tax lines and numbering, but the customer's name and address on them are replaced by a non-identifying placeholder that keeps the invoice referentially intact.\n - Whether Imbra's tax or accounting retention duty requires keeping the issued name for a period is a decision for the owner. Until an ADR records it, anonymise and do not hard-delete invoices.\n - Tests assert that no personal value survives in any table or export after erasure. This includes free-text fields and any audit or history table.\n- **No personal data outside the store.**\n - Never log names, emails or addresses. Log customer ids only.\n - Error responses do not echo personal data.\n - Fixtures and examples use synthetic data only. Never copy a real customer into a test.\n - Exports and any file the app writes outside the SQLite file are written only where the administrator asks, and the UI says so.\n- **The SQLite file** lives outside the repository (path from `TARIFF_DATABASE_PATH`) and is gitignored. Never commit a database file, dump or backup. Treat every repository as public.\n- **Backups** of the file contain personal data. The playbook names where they go and that an erased customer reappears if a pre-erasure backup is restored, so the erasure is re-applied.\n- Changing what is collected, how erasure behaves or the export shape is an observable change. It needs an ADR (section 12) and a `CHANGELOG.md` entry.\n\n## 8. Security\n\nThere is one administrator and no other account. No network access is expected, but the application is still an authenticated web application.\n\n- **Authentication.**\n - The administrator's password is stored hashed with scrypt (Werkzeug `generate_password_hash`) or Argon2. Never store it plain, and never use MD5, SHA-1 or plain SHA-256.\n - Compare secrets in constant time.\n - Throttle failed logins.\n - Login errors say \"invalid credentials\" and nothing more.\n - Every route except the login page and the health endpoint requires the session. Apply the check in one `before_request` guard on the app, not per route, so a new blueprint cannot forget it.\n- **Sessions.** Cookies are `HttpOnly`, `SameSite=Lax`, and `Secure` whenever the app is served over HTTPS. The session id is regenerated at login. Sessions expire after 30 minutes idle, and logout invalidates the session server-side.\n- **CSRF.** The session is authenticated by a cookie, so every `POST`, `PUT`, `PATCH` and `DELETE` carries a CSRF token (Flask-WTF `CSRFProtect`, never hand-rolled). Every form renders the token. HTMX requests send it through `hx-headers` on ``. `GET` never changes state.\n- **Injection and XSS.** Use parameterised queries only. Never build SQL by string interpolation. Jinja autoescape stays on, and never use `| safe` or `Markup` on data that a customer or the administrator typed.\n- **Headers.** Set them in one `after_request` hook: a strict `Content-Security-Policy` (no `unsafe-inline`, no `unsafe-eval`, self-hosted scripts only), `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: strict-origin-when-cross-origin`, and a restrictive `Permissions-Policy`.\n - Pin static MIME types in code, because `nosniff` makes the server the sole authority.\n - Verify script execution in a real browser, not only status codes.\n - HSTS applies only if the app is ever served over HTTPS.\n- **Errors.** No stack traces, paths or SQL errors reach the browser. Return a generic message, log the detail with a request id, and use RFC 9457 `application/problem+json` for JSON error responses. Debug mode is never on outside local development.\n- **Nothing reaches the network.** No CDN, font, analytics or telemetry call, and no outbound HTTP client. Adding one needs an ADR. SSRF rules apply the moment a URL from input is fetched. It is not fetched today.\n- **Secrets.** None in source, history, commits, PRs or conversation. An agent MUST NOT read, print or cat `.env`, key or credential files. Check presence with `test -f .env && echo exists`. If a secret is exposed, flag it, name it and recommend rotating it.\n- **Dependencies.** Commit `uv.lock` and install with `uv sync --locked`. Refresh the lock deliberately and name what refreshes it. Prefer maintained dependencies, remove unused ones, and check licences before adding one. GPL and AGPL need explicit approval.\n- Run bandit and gitleaks (full history in CI) on every change.\n\n## 9. Architecture and code rules\n\n### Layers\n\nThe order is route handler, then service function, then repository. Handlers are thin: decode the request, call a service, render or encode the response. No database access in handlers. No HTTP concerns in services.\n\n### Money and rounding\n\n- Amounts are `decimal.Decimal` or integer minor units, never `float`. In SQLite store integer minor units, because SQLite has no exact decimal type.\n- Currency codes are ISO 4217. Timestamps are stored in UTC.\n- The rounding rule (mode and the step at which it applies: per line or per invoice) is one named constant, stated once and covered by tests.\n- Never scatter `round()` calls.\n\n### The engine\n\n- It is a library. Pricing logic is pure: same inputs give the same output, with no I/O, no clock and no global state. Pass \"now\" in as a parameter.\n- Discount rules of several kinds are a Strategy: one small class per kind behind a common protocol, so adding a kind is adding a class and a registry entry rather than a new branch.\n- Rule ordering and stacking (which rules combine, and in what order) is stated in one place, documented, and tested with worked examples.\n- Errors the engine raises on purpose derive from one `TariffError` base, each type also deriving from the built-in its site raised before. A test walks every `raise` in the package and fails on one outside the hierarchy. The test also asserts it saw at least one raise.\n- No abstract operation declares `*args` or `**kwargs`.\n- Prefer free functions for stateless logic. Use a class when it owns state.\n- Composition over inheritance, and hierarchies at most two levels deep.\n- No AOP or hidden interception. Cross-cutting behaviour is explicit at a visible call site.\n\n### Public API\n\n- `tariff.engine` exports its public API from `__init__.py`. Everything else is private. Public functions carry full type hints and Google-style docstrings.\n- The API is stable, following semver. Before removing or renaming a public symbol, deprecate it with a comment naming the replacement, and remove it in a follow-up.\n- A rename spanning a method and its keyword arguments is deprecated together or not at all.\n- Importing `tariff.engine` has no side effects and reads no file or environment.\n- A library attaches `logging.NullHandler()` to its own logger and installs no writing handler. The logger is injectable.\n\n### Store\n\n- SQLite through one connection factory. Foreign keys on (`PRAGMA foreign_keys = ON`) and WAL where it fits.\n- Schema changes go only through versioned migrations, committed and never edited once merged. Each has an `up` and a `down`.\n- Multi-step writes run in one transaction that is short and never spans a request. Timeouts are set on connections. No unbounded queries.\n- Follow the data-modeling rules:\n - snake_case plural table names\n - `is_`/`has_` boolean prefixes\n - `
_id` foreign keys\n - a documented maximum length on text columns\n - foreign keys defined explicitly with a deliberate cascade choice\n- Tests use a real SQLite file or `:memory:`. SQLite is the production engine, so this is not a substitute.\n\n### HTMX and templates\n\n- The server owns state. Endpoints return HTML.\n- Detect HTMX with the `HX-Request` header. Return the partial for HTMX requests and the full page otherwise.\n- Return `204` when nothing changes on screen. Return `422` with the re-rendered form and inline field errors on validation failure. Never redirect to a blank form after a failed `POST`.\n- Every HTMX interaction sets `hx-target` and `hx-swap` explicitly. Use `hx-push-url` only on real navigation.\n- Use `hx-indicator` and `hx-disabled-elt` on submits so nothing is submitted twice.\n- Pages work without JavaScript, and HTMX enhances them.\n- Partials are named for what they render (`partials/invoice_lines.html`) and take all data as explicit context. Keep at most two or three OOB targets per response.\n- Templates hold conditionals and loops only. No business logic. Keep one template per view and extract repeated markup.\n- Accessibility target: WCAG 2.1 AA. Use semantic HTML, labelled fields, `:focus-visible`, and full keyboard operation.\n\n### Validation and requests\n\n- Validate at the boundary with a schema (Pydantic or an equivalent), allowlisting rather than blocklisting. Internal code trusts validated data.\n- Parse typed query parameters explicitly, so absent, valid and invalid are three distinct states. Invalid means `400`, never a silent default.\n- URLs use lowercase hyphenated nouns, plural collections, nested sub-resources, no trailing slash, and camelCase query parameters.\n- List views are paginated.\n\n### General quality\n\n- DRY, KISS, YAGNI. Every deferral names its revisit trigger.\n- Names are the documentation. Functions take a verb, classes a noun, booleans `is_`, `has_` or `can_`. Use no single-letter names except loop counters and `e` in `except`.\n- No boolean flag parameters. Use two named functions or an enum.\n- Cognitive complexity is at most 15 per function, and nesting at most three levels. Use guard clauses.\n- Magic numbers and strings become named constants. A threshold sized from data records its data source.\n- No circular dependencies. Shared logic moves to a third module, never a local copy.\n- Fail fast at boundaries. Fail loudly rather than fall back to a derived value.\n- Every wait on another thread, process or connection is bounded and reports why it gave up.\n- No dead code, no commented-out code, no debug `print`, no `pdb`. Debug tooling sits behind a flag.\n- A workaround comment naming a rejected mechanism is a prompt to grep the codebase for that mechanism.\n- Comments are for intent the code cannot express. Never cite a ticket, PR or ADR number in a code comment. A block comment sits directly above its item, and a trailing comment is only a tool directive.\n- Identifiers are ASCII. Files are UTF-8 with LF endings. Commit `.editorconfig` and `.gitattributes` (`* text=auto`). A program that writes text sets its encoding and line ending explicitly at the boundary.\n- A destructive operation (delete, truncate, overwrite) acts only on what it can prove it created. Erasure (section 7) deletes by key, never by a broad filter.\n- Probe scripts are named `probe_*.py` and deleted before the commit that uses their findings.\n\n## 10. Testing\n\n- The fast tier (unit and integration) is the default `pytest` run. The tier follows from the directory, set by one collection hook. The e2e tier is opt-in behind a marker.\n- **Unit:**\n - Engine logic is tested with pure inputs and no mocks.\n - Cover each discount kind, stacking and ordering, each tax jurisdiction, rounding edges, zero and negative quantities, and empty invoices.\n - Use worked examples with hand-computed expected totals from the business rules, not values produced by the code under test.\n - Use `pytest.mark.parametrize` for data-driven cases.\n- **Integration:** real SQLite. Cover repositories, migrations up and down, and the erasure and export functions.\n- **Component:** Flask test client per route. Cover success, `400`/`422` validation, `401` or redirect when unauthenticated, `404`, missing CSRF token rejected, and the partial versus full page split on `HX-Request`.\n- **Engine boundary:** a test imports `tariff.engine` in a fresh interpreter with Flask blocked (for example a stub that raises on import) and exercises the public API.\n- **Export contract:** each invoice export format is asserted against a fixed reference file. A round trip through our own writer and reader proves only self-consistency.\n- **GDPR tests:** as in section 7. They assert that erasure and export cover every personal column.\n- **Negative assertions** assert their inputs were reached. Assert the count of files, rows or records examined, not only that a set is empty.\n- Tests are independent, share no mutable state and set environment variables explicitly per test. A test never touches host state outside the working directory.\n- Never skip or weaken a failing test without a documented reason. A change that deletes or loosens an existing test states why. A change that adds tests needs no ceremony.\n- Coverage is at least 80% overall and at least 90% of new code. It must not regress. Name the `omit` list, and adding to it is a reviewable decision.\n- A test asserting a numeric threshold names what it pins.\n- A visual or template change is verified against the rendered page, not the source.\n- Verify a fix fires on real data, not only on a synthetic case.\n\n## 11. Quality gates\n\nEvery category runs at three layers. CI is the backstop and duplicates pre-commit, because hooks can be bypassed.\n\n| Category | Editor | Pre-commit | CI |\n| --- | --- | --- | --- |\n| Lint (ruff) | yes | yes | yes |\n| Format (ruff format) | yes | yes | yes |\n| Types (mypy strict) | yes | yes | yes |\n| Secrets (gitleaks) | | yes | yes |\n| File hygiene | | yes | |\n| SAST (bandit) | | | yes |\n| Cognitive complexity (complexipy) | | | yes |\n| Tests and coverage | | | yes |\n| Layering check (section 3) | | | yes |\n\n- Thresholds: zero lint, format and type errors, and zero high or critical findings. Coverage is at least 80%.\n- Ruff `D` rules use the Google convention, exempt for `tests/**`. Configuration lives only in `pyproject.toml`.\n- mypy runs `--strict` from the first commit. Never weaken it globally. Scope an escape for an untyped third-party library to a per-module override with a stated reason.\n- Site-local suppressions name the rule (`# noqa: B017`) and are never bare. The reason sits on the line above.\n- When a gate is red, fix the source. Never narrow the gate, and never edit the input a check reads to make a finding disappear. Freeze existing instances by name only, never by count.\n- A check states what it inspected as well as what it found, and its exit status carries its verdict.\n- A skipped check is not a passed check.\n- If a repository host enforces branch protection, CI checks are required status checks and bind administrators.\n- CI runs the same Python version that `.python-version`, `requires-python` and mypy's `python_version` name (3.12), so every gate validates the runtime that runs the app.\n\n## 12. Git, documentation and decisions\n\n### Git\n\n- Always work on a branch and never commit to `main`. Branch names are `feat/\u2026`, `fix/\u2026`, `chore/\u2026` or `docs/\u2026`.\n- Commit messages use conventional prefixes (`feat:`, `fix:`, `chore:`, `docs:`, `refactor:`, `style:`, `test:`), the imperative mood and a subject under 80 characters. When a single-commit branch closes an issue, the subject carries the issue reference.\n- PRs are small, with one concern each. Test locally, then read the CI run before calling the change good. Repeat the closing keyword before each issue number, and never write a closing keyword next to a number you only mean to reference.\n- Never force-push, including `--force-with-lease`. Merge `main` into a stale branch, then regenerate any derived artifact.\n- Regenerate derived artifacts in the same change that edits their source.\n- Do not commit build output, `.venv/`, `__pycache__/`, `.mypy_cache/`, `*.db`, `*.sqlite*`, exports containing personal data, or `.env`. Commit the lockfile. `.gitignore` exists from the first commit.\n- Before merging, review the diff in priority order: security, correctness, clarity, conventions. Personal-data handling is part of security.\n- Tags are annotated `vX.Y.Z` and follow semver. A patch means fixes only, a minor adds compatibly, and a major breaks the API or an export format.\n\n### Documentation\n\n- `README.md` follows the nine-section structure: title and summary, features, quick start, usage, project structure, development setup, configuration reference, links, licence last. It is the source of truth for the directory tree.\n- `docs/ONBOARDING.md` has six numbered sections in order: prerequisites, first-time setup, verify the setup, key files, project context, daily workflow.\n- `docs/PLAYBOOK.md` has five numbered sections in order: git workflow, domain operations (add a discount kind, add a tax jurisdiction, add a personal field, run an erasure or export), quality, maintenance, release and deploy. Release and deploy stays last, and here it means tagging and publishing the library. There is no deployment.\n- `docs/dev-journal.md` is required. Session entries run oldest first, with the heading `## YYYY-MM-DD \u2014 Short theme`. Each records Tool, Key changes, PRs merged, Issues closed/created, and Lesson. A P0 or P1 fix or an incident adds a post-mortem.\n- Update the relevant document before every commit. No document states a count or figure about the tree outside a generated block.\n- Rules use RFC 2119 words. Write in the present tense, wrap Markdown at the width declared once in configuration, and write for a reader who lacks context.\n- `CHANGELOG.md` follows Keep a Changelog, with an `Unreleased` section maintained by the change that causes each entry. Entries are at most 40 words and say what changed and what a reader must do. A breaking change names the migration.\n- **ADRs.** A decision needs an ADR in `docs/decisions/` (`NNN-slug.md`, YAML frontmatter, supersession through the frontmatter only) when it changes something observable without reading the internals. Here that means:\n - the engine's public API\n - the invoice export formats\n - discount stacking and rounding semantics\n - what personal data is kept, and how erasure or export behaves\n - any new outbound network path\n\n Tool choices, layout and process end in the PR. An ADR is not edited once merged, except for format-only changes.\n- When a document disagrees with the system, establish which is wrong before changing either.\n- Adopting shared rules:\n - Templates supply candidate conventions, and the project chooses what it adopts.\n - A template update creates no compliance work by itself.\n - Rules already adopted here stay in force until this project changes them.\n - Declining a new candidate needs no ADR or ticket.\n\n## 13. Examples\n\nIf an `examples/` directory is created, one file shows one pattern or journey, for instance pricing a basket through the library without the web app.\n\n- The directory has its own `README.md`, and each example appears there as an exact command with real output.\n- Examples run offline against the project's own code and synthetic data.\n- Examples are excluded from any built package, and CI runs each one after a plain `uv sync`.\n- An example that verifies something exits non-zero on failure.\n\n## 14. Working with the agent\n\n- **Plan before implementing.** For a feature or a non-trivial change, first give the files to touch, the function signatures, the edge cases and the assumptions. Wait for approval before writing implementation code. Single-line fixes, typos and fully specified changes are exempt. If a constraint invalidates an approved plan, stop and re-surface the options.\n- **Verify an issue before implementing it.** Re-read the target for existing coverage, check whether an open PR already closes it, and check for ADRs accepted since it was filed.\n- **Verify a finding before reporting it.** Reproduce the defect, or label the finding unverified. A finding from a subagent is a lead, not evidence.\n- **Report faithfully.** If tests fail, say so with the output. If a step was skipped, say that.\n- **Ask before hard-to-reverse or outward-facing actions.** That includes anything that deletes data, touches the real SQLite file, or sends anything anywhere. Nothing may reach the network.\n- **Never use real personal data.** Use synthetic customers in tests, fixtures, examples, docs and conversation.\n- **End-of-session audit.** Before ending a session that changed code:\n 1. Run the full gate set from section 11.\n 2. Run the layering check from section 3.\n 3. Confirm the docs and `CHANGELOG.md` reflect the change.\n 4. Confirm that no personal data, secret or database file is staged.\n 5. State what was and was not verified.\n\n", - "ttft_ms": 22475, - "type": "result", - "duration_ms": 115075, - "uuid": "a0e49f0e-7ebd-4064-bfd7-6afb9a4a04ca", - "ttft_stream_ms": 3370, - "time_to_request_ms": 120, - "first_content_frame_ms": 3371, - "queued_turn_count": 0, - "result_index": 0 - }, - "output_leak": null, - "over_budget": [], - "outcome": "generated", - "output": "C:\\Workspace\\solid-ai-templates\\tests\\efficacy\\arms\\full\\CLAUDE.md", - "output_chars": 29503, - "output_lines": 391, - "output_width": 360 -} \ No newline at end of file diff --git a/tests/efficacy/generate_arm.py b/tests/efficacy/generate_arm.py index 0193924..e3664fa 100644 --- a/tests/efficacy/generate_arm.py +++ b/tests/efficacy/generate_arm.py @@ -48,9 +48,8 @@ # The arms this module makes, each with the directory under `arms/` its file # and record live in, and how it is made: fixed text, a model generation in # one of `agents.md`'s models, or the emitter, and a model arm's budget as -# (lines, width) where it has one. Round 3's `full` and `hand` keep their -# committed files and records; they were made through an interview that no -# longer ships upstream. +# (lines, width) where it has one. `hand` is a person's file, kept verbatim +# with no record, so it is not made here. GENERATED = { "reference": {"dir": "reference", "kind": "fixed"}, "inline": {"dir": "inline", "kind": "model", "model": "inline"}, diff --git a/tests/efficacy/harness.py b/tests/efficacy/harness.py index a251e6c..cb6183c 100644 --- a/tests/efficacy/harness.py +++ b/tests/efficacy/harness.py @@ -67,19 +67,17 @@ BUDGET_USD = 100.0 TIMEOUT_S = 7200 -# K as registered, and the ceiling of the one escalation allowed. No run -# goes past the ceiling, because sampling until an interval clears zero is the -# failure the bound exists to prevent. -K_PRIMARY = 3 -K_CEILING = 5 - -# Round 5 registers its own K instead, with no escalation. Fifteen blocks -# were sized before its first trial from the rounds before it, whose per-trial -# noise left three blocks unable to decide its hypotheses. A run holding one -# of its arms may go that far and no further. +# A round registers its K before its first trial and no run goes past it, +# because sampling until an interval clears zero is the failure the bound +# exists to prevent. Round 5 registers fifteen blocks, sized from the +# per-trial noise of the rounds before it, which left three blocks unable to +# decide its hypotheses. ROUND5_ARMS = ("inline", "reference", "skills") ROUND5_K = 15 +# A run is short unless the registered K is asked for by name. +K_DEFAULT = 3 + # Round 5d runs `hand` and `short` under round 5's design: its K, its spec # at its registered content, against round 5c's arms. ROUND5D_ARMS = ("hand", "short") @@ -128,15 +126,13 @@ SKILLS_INTO = ".claude/skills" # The arms, each a word, and the context file each starts with, relative to -# `arms/`. Arm `none` carries no file: it is the bare agent. The two files -# round 1 ran keep the directories its generation record names. `inline`, -# `reference` and `skills` are round 5's; `hybrid` was regenerated for it, -# and an arm's vendored ref comes from its generation record. `short` was -# made again from round 5's chain, under round 3's budget. +# `arms/`. Arm `none` carries no file: it is the bare agent. `hand` is a +# person's file, kept verbatim. `inline`, `reference` and `skills` are round +# 5's; `hybrid` was regenerated for it, and an arm's vendored ref comes from +# its generation record. `short` was made again from round 5's chain, under a +# 40-line budget. ARMS = { "none": {"label": "no context file", "context": None}, - "full": {"label": "the templates' file, inline", - "context": "full/CLAUDE.md"}, "short": {"label": "the templates' file, inline, 40 lines", "context": "short/CLAUDE.md"}, "hybrid": {"label": "the templates' file, hybrid", @@ -246,7 +242,7 @@ def reach_denials(root, workspace): # Every block any run may hold, so no trial of a long round is left # readable by the trials of its other blocks. names = {trial_name(arm, trial) for arm in ARMS - for trial in range(1, max(K_CEILING, ROUND5_K) + 1)} + for trial in range(1, ROUND5_K + 1)} names |= {"change-" + name for name in names} targets = [repository_root(), scoring_area(root), os.path.join(root, "home"), os.path.join(root, "void")] @@ -1838,22 +1834,11 @@ def order(arms, k): for trial in range(1, k + 1) for place in range(count)] -def k_ceiling(arms): - """The most blocks a run of these arms may hold.""" - return (ROUND5_K if set(arms) & set(ROUND5_ARMS + ROUND5D_ARMS) - else K_CEILING) - - def pending_trials(arms, k, start=None): """The interleaved order, from `start` onwards where one is given.""" - ceiling = k_ceiling(arms) - if ceiling == ROUND5_K: - why = "round 5 registers K = %d and no escalation" % ROUND5_K - else: - why = ("a round escalates once to K = %d and never further" - % K_CEILING) - if not 1 <= k <= ceiling: - raise TrialError("--k %d is outside 1 to %d: %s" % (k, ceiling, why)) + if not 1 <= k <= ROUND5_K: + raise TrialError("--k %d is outside 1 to %d: a round registers its K " + "and runs no block past it" % (k, ROUND5_K)) trials = order(arms, k) if start is None: return trials @@ -2176,14 +2161,13 @@ def resume_checks(): except TrialError: checks.append(("--from an unknown trial refuses", True)) try: - pending_trials(["none", "hybrid"], K_CEILING + 1) - checks.append(("a K past the escalation's ceiling refuses", False)) + pending_trials(["none", "hybrid"], ROUND5_K + 1) + checks.append(("a K past the registered ceiling refuses", False)) except TrialError: - checks.append(("a K past the escalation's ceiling refuses", True)) - first_escalated = trial_name("none", K_PRIMARY + 1) + checks.append(("a K past the registered ceiling refuses", True)) names = [trial_name(*pair) - for pair in pending_trials(arms, K_CEILING, first_escalated)] - checks.append(("the escalation runs its blocks from none-4", + for pair in pending_trials(arms, 5, trial_name("none", 4))] + checks.append(("--from a later block keeps the rotated order", names == ["none-4", "short-4", "hybrid-4", "short-5", "hybrid-5", "none-5"])) @@ -2464,7 +2448,7 @@ def dry_run_checks(): # The thin specification reaches its workspace under the one name the # prompt gives, so the prompt stays a single text across specifications. - thin_workspace, _ = prepare_workspace("full", 1, root, SPECS["thin"]) + thin_workspace, _ = prepare_workspace("inline", 1, root, SPECS["thin"]) with io.open(os.path.join(thin_workspace, "SPEC.md"), "rb") as handle: given = handle.read() with io.open(SPECS["thin"], "rb") as handle: @@ -3248,7 +3232,7 @@ def denied(target): or denied(templates_root(required=False))), ("other trials, their change tasks, home and void are denied", all(denied(os.path.join(root, entry)) - for entry in ("full-1", "none-2", "change-none-1", + for entry in ("inline-1", "none-2", "change-none-1", "change-hand-5", "home", "void"))), ("a round-5 run's last block is denied too", all(denied(os.path.join(root, trial_name(arm, ROUND5_K))) @@ -3269,7 +3253,7 @@ def denied(target): # The command that ended round 4's thin run, and its kin. Each MUST meet a # deny rule; a stop by PID or by port MUST meet none. KILLS = { - "Bash": ['cd "C:/runs/full-1" && powershell -NoProfile -Command ' + "Bash": ['cd "C:/runs/inline-1" && powershell -NoProfile -Command ' '"Get-Process -Name python -ErrorAction SilentlyContinue | ' 'Where-Object { $_.MainWindowTitle -eq \'\' } | ' 'Stop-Process -Force"', @@ -3579,11 +3563,9 @@ def parse_args(argv): "commas, from %s; their order is block 1's. " "Required for a run, so a run names the arms " "it holds" % ",".join(ARMS)) - parser.add_argument("--k", type=int, default=K_PRIMARY, - help="trials per arm (default %d; at most %d, the " - "escalation's ceiling, or %d for a run holding " - "a round-5 arm)" - % (K_PRIMARY, K_CEILING, ROUND5_K)) + parser.add_argument("--k", type=int, default=K_DEFAULT, + help="trials per arm (default %d; at most %d, the K a " + "round registers)" % (K_DEFAULT, ROUND5_K)) parser.add_argument("--cli", help="the Claude CLI file every trial runs, in place " "of `claude` on PATH; its version is recorded " diff --git a/tests/efficacy/judge.py b/tests/efficacy/judge.py index 33acd69..a01463e 100644 --- a/tests/efficacy/judge.py +++ b/tests/efficacy/judge.py @@ -135,7 +135,7 @@ # would have changed what is being judged. MARKERS = ("CLAUDE.md", "AGENTS.md", "GEMINI.md", "solid-ai-templates", "Claude Code", "claude.ai", "CLAUDE", "context file", - "arm none", "arm full", "arm short", + "arm none", "arm short", "arm hybrid", "arm hand", "arm reference", "arm inline", "arm skills", "SKILL.md") @@ -962,14 +962,14 @@ def bundle_checks(scratch): The planted tree is shaped like one scoring leaves behind: the trial's code beside tool caches that hold absolute paths through the scoring area. """ - tree = os.path.join(scratch, "scoring", "full-2", "tree", "full-2") - scored = "/".join((scratch.replace(os.sep, "/"), "scoring", "full-2", "tree", - "full-2", "src")) + tree = os.path.join(scratch, "scoring", "inline-2", "tree", "inline-2") + scored = "/".join((scratch.replace(os.sep, "/"), "scoring", "inline-2", "tree", + "inline-2", "src")) code = os.path.join("src", "app.py") # The trial's name outside a path, where an implementation may use it, # is not a leak. - plant(tree, {code: 'CELL = "full-2"\n', "CLAUDE.md": "# rules\n"}) + plant(tree, {code: 'CELL = "inline-2"\n', "CLAUDE.md": "# rules\n"}) # The skills arm's skills, in both folders they can sit in, name the arm. skills = [os.path.join(".claude", "skills", "review", "SKILL.md"), @@ -1026,15 +1026,15 @@ def bundle_checks(scratch): # The plant landed: the bundle lacked the file and now holds it. checks.append((label, not before and os.path.exists(landed) - and [relative, "full-2", "as a path segment"] in found)) + and [relative, "inline-2", "as a path segment"] in found)) # The scan reads the directories the copy leaves out, because the judge # reads whatever the bundle holds. hidden = os.path.join(".git", "config") plant(bundle, {hidden: "worktree = %s\n" % scored}) checks.append(("a leak in a directory the copy skips is found", - [hidden, "full-2", "as a path segment"] - in surviving_markers(bundle, "full-2"))) + [hidden, "inline-2", "as a path segment"] + in surviving_markers(bundle, "inline-2"))) return checks diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index df58516..4c3a456 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -36,12 +36,10 @@ import archive # noqa: E402 import lib # noqa: E402 from generate_arm import GENERATED, record_path # noqa: E402 -from harness import (ARMS, ARMS_DIR, K_CEILING, K_PRIMARY, # noqa: E402 - PROMPT, ROUND5_ARMS, ROUND5_K, ROUND5_SPEC, - ROUND5D_ARMS, SCORABLE, - TEMPLATES_ENV, VOIDING, - TrialError, canonical, git, k_ceiling, order, reach, - read_transcripts, scoring_area, split_name, +from harness import (ARMS, ARMS_DIR, PROMPT, ROUND5_ARMS, # noqa: E402 + ROUND5_K, ROUND5_SPEC, ROUND5D_ARMS, SCORABLE, + TEMPLATES_ENV, VOIDING, TrialError, canonical, git, + reach, read_transcripts, scoring_area, split_name, templates_root, trial_name) from harness import name_of as trial_of # noqa: E402 @@ -80,16 +78,12 @@ RESAMPLES = 10000 CONFIDENCE = 0.95 -# Every contrast declared before the run, each a treatment arm -# against a baseline. A run -# prints the contrasts whose arms it holds; the rest are computed as not -# computed and left out of every table. full - hand is the one an adopter -# asks: a large full - none beside an equally large hand - none is not a -# result for the templates. short - hand holds length fixed, hybrid - full -# the content, and short - full asks whether length matters at all. -CONTRASTS = (("full", "none"), ("short", "none"), ("hybrid", "none"), - ("hand", "none"), ("full", "hand"), ("short", "hand"), - ("hybrid", "full"), ("short", "full"), +# Every contrast declared before the run, each a treatment arm against a +# baseline. A run prints the contrasts whose arms it holds; the rest are +# computed as not computed and left out of every table. Each file arm reads +# against none, and short - hand holds length fixed. +CONTRASTS = (("short", "none"), ("hybrid", "none"), ("hand", "none"), + ("short", "hand"), # Round 5: each arm against none, the two # hypotheses' contrasts against hybrid, and skills against @@ -103,10 +97,6 @@ ("inline", "hand"), ("hybrid", "hand"), ("reference", "hand"), ("skills", "hand"), ("short", "inline")) -# The contrasts only round 5d declares. Round 2 ran `hybrid` beside `hand` -# and declared no contrast between them, so its report never prints one. -ROUND5D_ONLY = CONTRASTS[-5:] - # Declared before the run. "up" improves upward, "down" # improves downward, "neutral" is reported without a verdict. UP, DOWN, NEUTRAL = "up", "down", "neutral" @@ -175,19 +165,6 @@ # They are still printed, without a verdict, so nothing reads them twice. SUPERSEDED_IN_ROUND5 = ("source_lines", "tracked_files") -# The app-code rows decide from round 5 on. An earlier round rescored by the -# current scorer carries them too, but was registered on source lines and -# files, so it prints them without a verdict and reads as it was reported. -FROM_ROUND5 = ("app_lines", "app_files") - -# The practical thresholds that can owe the one -# escalation to K = 5. Only a primary dimension triggers it, so no other -# metric's threshold is carried here, where something could come to read it. -PRACTICAL = {key: ("0.5 points", 0.5) for key in PRIMARY - if key not in PROBE_RATES} -PRACTICAL.update(security_probe_pass_rate=("9 pp", 0.09), - data_protection_probe_pass_rate=("30 pp", 0.30)) - def path(payload, *keys): """Follow a path through nested dicts, answering None at the first gap.""" @@ -458,32 +435,10 @@ def pattern_count(trial, verdict): def security_value(trial, key): - """A security check's value, or None where it was not taken.""" + """A security reading's value, or None where it was not taken.""" return metric_value({"scores": trial.get("security") or {}}, key) -# Security checks declared after a run and before any trial was read for them. -# Their directions were declared with them. They are kept out of METRICS so no -# verdict, escalation or verdict-vector row can come from a check chosen after -# the results were seen. -POSTHOC = ( - ("security_secret_key", "Hard-coded secret keys", DOWN, - lambda t: security_value(t, "secret_key")), - ("security_debug", "Debug enabled", DOWN, - lambda t: security_value(t, "debug")), - ("security_sql_strings", "SQL assembled from untraced values", DOWN, - lambda t: security_value(t, "sql_strings")), - ("security_vulnerable", "Known vulnerabilities in installed dependencies", - DOWN, lambda t: security_value(t, "vulnerable_dependencies")), - ("security_cookies", "Session cookie flags set, of three", UP, - lambda t: security_value(t, "cookie_flags")), - ("security_headers", "Security headers on /, of four", UP, - lambda t: security_value(t, "security_headers")), - ("security_leaks", "Malformed requests answered with a stack trace, of " - "five", DOWN, lambda t: security_value(t, "error_leakage")), -) - - def change_value(trial, *keys): """A change-task metric's value, or None where it was not measured.""" return metric_value({"scores": trial.get("change") or {}}, *keys) @@ -702,11 +657,7 @@ def is_round5(trials): def is_round5d(trials): """Whether the run holds a round-5d arm, so that round's registration and its verdict rules govern it.""" - - # Rounds 2 and 3 ran `hand` and `short` too, always beside `full`, which - # round 5d never runs, so `full` tells the earlier rounds apart. - arms = {arm_of(name) for name in trials} - return bool(arms & set(ROUND5D_ARMS)) and "full" not in arms + return any(arm_of(name) in ROUND5D_ARMS for name in trials) # The arms round 5 registers. A block is complete only when every one of @@ -739,41 +690,14 @@ def blocks_named(blocks): def margins_of(trials): """The margins a run's contrasts are held against.""" - if is_round5d(trials): - return ROUND5D_MARGINS - return ROUND5_MARGINS if is_round5(trials) else MARGINS - - -def block_start(root, trials, block): - """The first trial of `block` in the order the harness runs it. - - The harness starts each block one arm later than the last, from the - order `--arms` named. The run's records show that order in its first - block; a run without records is read in the arms' declared order. - """ - named = [] - for record in run_records(root) if root else []: - if record.get("task", "build") != "build": - continue - try: - arm, index = split_name(trial_of(record)) - except (TrialError, KeyError, TypeError, ValueError): - continue - if index == 1 and arm not in named: - named.append(arm) - present = {arm_of(name) for name in trials} - arms = ([arm for arm in named if arm in present] - or [arm for arm in ARMS if arm in present]) - return trial_name(*order(arms, block)[len(arms) * (block - 1)]) + return ROUND5D_MARGINS if is_round5d(trials) else ROUND5_MARGINS def active_contrasts(trials): """The declared contrasts whose both arms the run holds, in the declared order.""" present = {arm_of(name) for name in trials} - later = () if is_round5d(trials) else ROUND5D_ONLY - return [pair for pair in CONTRASTS - if set(pair) <= present and pair not in later] + return [pair for pair in CONTRASTS if set(pair) <= present] def contrast_arms(active): @@ -810,14 +734,10 @@ def collect(trials, metrics=METRICS, later_rules=None): """Metric values by metric, arm and trial index, read by round 5d's rules for a round-5d run or where `later_rules` asks for them.""" working_only = is_round5d(trials) if later_rules is None else later_rules - - # Round 5d's rules are round 5's size rows too, so a round read by them - # decides on app code, whichever round it was. - superseded = (SUPERSEDED_IN_ROUND5 if is_round5(trials) or working_only - else FROM_ROUND5) table = {} for key, label, direction, accessor in metrics: - if key in superseded or (working_only and key == "adherence"): + if key in SUPERSEDED_IN_ROUND5 or (working_only + and key == "adherence"): direction = NEUTRAL row = {} for name, trial in sorted(trials.items()): @@ -1100,11 +1020,6 @@ def contrasts(table, seed, crossed=(), margins=None, strict=False, label = "%s-%s" % (treatment, baseline) if only and label not in only: continue - - # Only round 5d declares these, so no earlier round computes - # them, and none can owe an escalation or a finding to one. - if not strict and (treatment, baseline) in ROUND5D_ONLY: - continue left = entry["values"].get(treatment, {}) right = entry["values"].get(baseline, {}) # Round 5d reads a contrast with an earlier round's arm unpaired, @@ -1327,64 +1242,11 @@ def cross_check_section(check): return lines -def escalation_triggers(results): - """The rows that owe the escalation to K = 5, in one set of contrasts. - - A row owes it where a primary dimension's interval contains zero while its - mean paired difference exceeds that dimension's practical threshold. - """ - triggers = [] - for key in PRIMARY: - label, threshold = PRACTICAL[key] - for treatment, baseline in CONTRASTS: - name = "%s-%s" % (treatment, baseline) - contrast = results[key].get(name) - if contrast is None: - continue - low = contrast["interval"].get("low") - high = contrast["interval"].get("high") - if low is None or high is None or not contrast["pairs"]: - continue - - # Read by size in either direction: an escalation owed only to a - # favourable effect would lean the stopping rule toward "better". - effect = statistics.fmean(contrast["pairs"]) - if low <= 0 <= high and abs(effect) > threshold: - triggers.append({"metric": key, "contrast": name, - "mean": round(effect, 4), "low": low, - "high": high, "threshold": label}) - return triggers - - -def assess_escalation(trials, results, seed, withdrawn=None, root=None): - """Whether the escalation to K = 5 is owed, and whether it was run. - - A run past K = 3 is judged on its first three blocks alone, because that is - the vector which had to owe the escalation. Their contrasts are kept, so - the report prints the K = 3 vector beside the K = 5 one, with `withdrawn` - blanked from them as it is from `results`. A round-5 run registers its - own K and no escalation; `root` is read for the order its run took. - """ - k = max((index_of(name) for name in trials), default=0) - if is_round5(trials): - return {"k": k, "state": "registered", "owed": None, "triggers": [], - "owed_blocks": owed_blocks(trials)} - if k < K_PRIMARY: - return {"k": k, "state": "not assessed", "owed": None, "triggers": []} - if k == K_PRIMARY: - triggers = escalation_triggers(results) - return {"k": k, "state": "assessed", "owed": bool(triggers), - "triggers": triggers, - "from": block_start(root, trials, K_PRIMARY + 1)} - first = {name: trial for name, trial in trials.items() - if index_of(name) <= K_PRIMARY} - earlier = contrasts(collect(first), seed) - withdraw(withdrawn or {}, {}, earlier) - triggers = escalation_triggers(earlier) - return {"k": k, - "state": "escalated" if k == K_CEILING else "part-escalated", - "owed": bool(triggers), "triggers": triggers, - "results_k3": earlier} +def blocks_state(trials): + """How far the run has come toward its registered K: the blocks it + holds, and those that still miss a registered arm's trial.""" + return {"k": max((index_of(name) for name in trials), default=0), + "owed_blocks": owed_blocks(trials)} def number(value): @@ -1711,16 +1573,15 @@ def unrecorded_voids(root, sequence, recorded): return lost -def write_report(root, trials, table, results, seed, escalation, - out_dir, posthoc=None, withdrawn=None, cross=None): +def write_report(root, trials, table, results, seed, out_dir, + withdrawn=None, cross=None): """The dated round report, written to `out_dir`. The directory has no default so a shakedown of the writer renders into a scratch directory. A fabricated run must not be able to leave a file among the real audits, where its date alone would read as a result. - `posthoc` is the table and contrasts of the checks declared after the - run, printed in their own section and nowhere else. `withdrawn` maps each - withdrawn metric to its record, already blanked from `table` and `results`. + `withdrawn` maps each withdrawn metric to its record, already blanked + from `table` and `results`. `cross` is the other vendor's judge's reading, already applied to `results`. """ @@ -1769,8 +1630,8 @@ def write_report(root, trials, table, results, seed, escalation, newline="\n") as handle: handle.write(radar_svg(panels, theme)) radar[theme] = image - lines.extend(executive_section(trials, table, results, escalation, - withdrawn or {}, lost, scans, radar)) + lines.extend(executive_section(trials, table, results, withdrawn or {}, + lost, scans, radar)) lines.append("") lines.extend(["## What produced these numbers", ""]) @@ -1794,7 +1655,7 @@ def write_report(root, trials, table, results, seed, escalation, blocks=k)) lines.append("") - lines.extend(escalation_section(escalation)) + lines.extend(blocks_section(trials)) lines.append("") lines.append("## Task success, adherence and cost") @@ -1825,10 +1686,6 @@ def write_report(root, trials, table, results, seed, escalation, blocks=k)) lines.append("") - if posthoc: - lines.extend(posthoc_section(*posthoc, active=active, blocks=k)) - lines.append("") - if is_round5(trials) and not is_round5d(trials): lines.extend(round5_section(trials, table, results)) lines.append("") @@ -1841,13 +1698,11 @@ def write_report(root, trials, table, results, seed, escalation, lines.append("") lines.append("| Metric | %s |" % " | ".join(names)) lines.append("|---|%s" % ("---|" * len(names))) - raw = [(table, METRICS)] + ([(posthoc[0], POSTHOC)] if posthoc else []) - for source, metrics in raw: - for key, label, direction, _ in metrics: - row = source[key]["values"] - cells = [number(row.get(arm_of(name), {}).get(index_of(name))) - for name in names] - lines.append("| %s | %s |" % (label, " | ".join(cells))) + for key, label, direction, _ in METRICS: + row = table[key]["values"] + cells = [number(row.get(arm_of(name), {}).get(index_of(name))) + for name in names] + lines.append("| %s | %s |" % (label, " | ".join(cells))) lines.append("") lines.append("## Trials, and what was measured on them") @@ -1918,15 +1773,15 @@ def write_report(root, trials, table, results, seed, escalation, lines.append("") lines.extend(["## Verdict vector", ""]) - lines.extend(vector_lines(results, active, escalation, k)) + lines.extend(vector_lines(results, active)) lines.append("") os.makedirs(out_dir, exist_ok=True) width = markdown_width() documents = { record: lines, - appendix: appendix_lines(trials, table, results, escalation, k, seed, - generation, report, record), + appendix: appendix_lines(trials, table, results, k, seed, generation, + report, record), report: plain_report_lines(root, trials, table, results, radar, appendix, k)} for document, text in documents.items(): @@ -2072,32 +1927,15 @@ def provenance_lines(trials, names, arms, k, seed, generation): return lines -def vector_lines(results, active, escalation, k): - """The verdict vector: every metric's verdict in every contrast, the - first three blocks' beside them where the run escalated.""" - lines = [] - lines.append("The whole vector, which the summary's scores digest " - "and never replace.") - lines.append("") - - # A run that escalated reports both vectors, so - # each contrast at K = 5 sits beside the same contrast over the first - # three blocks rather than in a second table a reader has to line up. - earlier = escalation.get("results_k3") - header = [] - for treatment, baseline in active: - column = "%s−%s" % (treatment, baseline) - header.extend(["%s, K = %d" % (column, K_PRIMARY), - "%s, K = %d" % (column, k)] if earlier else [column]) +def vector_lines(results, active): + """The verdict vector: every metric's verdict in every contrast.""" + lines = ["The whole vector, which the summary's scores digest and never " + "replace.", ""] + header = ["%s−%s" % pair for pair in active] lines.append("| Metric | %s |" % " | ".join(header)) lines.append("|---|%s" % ("---|" * len(header))) for key, label, direction, _ in METRICS: - cells = [] - for pair in active: - name = "%s-%s" % pair - if earlier: - cells.append(earlier[key][name]["verdict"]) - cells.append(results[key][name]["verdict"]) + cells = [results[key]["%s-%s" % pair]["verdict"] for pair in active] lines.append("| %s | %s |" % (label, " | ".join(cells))) return lines @@ -2112,7 +1950,6 @@ def vector_lines(results, active, escalation, k): "skills": "a root file plus one skill per kind of task", "hand": "a short file a person wrote", "short": "the templates' rules cut down to 40 lines", - "full": "the templates' full file, from an earlier round", } # Each radar axis in plain words, as a sentence names it. @@ -2292,12 +2129,10 @@ def sureness_lines(trials, k): lines.append("- With only %d runs per approach, no difference here can " "be called established. Read every result as a hint." % k) - if is_round5(trials): - owed = owed_blocks(trials) - if owed: - lines.append("- The round is not complete: %s still miss a run, so " - "every answer here is provisional." - % blocks_named(owed)) + owed = owed_blocks(trials) + if owed: + lines.append("- The round is not complete: %s still miss a run, so " + "every answer here is provisional." % blocks_named(owed)) return lines @@ -2392,8 +2227,8 @@ def rerun_lines(lost): return lines -def appendix_lines(trials, table, results, escalation, k, seed, generation, - report, record): +def appendix_lines(trials, table, results, k, seed, generation, report, + record): """The technical appendix: what produced the results, the radar's axes row by row, and the verdict vector.""" names = ordered(trials) @@ -2419,7 +2254,7 @@ def appendix_lines(trials, table, results, escalation, k, seed, generation, blocks=k, legend=False)) lines.append("") lines.extend(["## The verdict vector", ""]) - lines.extend(vector_lines(results, active, escalation, k)) + lines.extend(vector_lines(results, active)) return lines @@ -2461,36 +2296,6 @@ def wrap_prose(lines, width): return wrapped -def posthoc_owed(trials): - """Whether the run's security readings are the post-hoc checks. - - From round 3 the same checks are probes, fixed before the run and read - through the two pass rates, so a run whose readings carry probes has no - post-hoc section: printed, it would call them declared after the run. - """ - readings = [trial["security"] for trial in trials.values() - if trial["security"]] - return bool(readings) and not any("probes" in reading - for reading in readings) - - -def posthoc_section(table, results, active=None, blocks=None): - """The report's lines on the security checks declared after the run.""" - lines = ["## Security, read with checks declared after the results", - "", - "The run's own security checks passed on every trial and " - "separated nothing. These were declared after the run and before " - "any trial was read for them, so each row gives the means and the " - "interval and no verdict, and none of them reaches the verdict " - "vector or the escalation.", - ""] - lines.extend(contrast_table(table, results, - [key for key, _, _, _ in POSTHOC], - verdicts=False, active=active, - blocks=blocks)) - return lines - - def spoken(names): """Names as a sentence lists them: a, b and c.""" return names[0] if len(names) == 1 else "%s and %s" % ( @@ -2522,8 +2327,8 @@ def score(wins, fails): NOT_MEASURED = "not measured" # A run whose hidden-suite pass rate sits under the bare arm's mean by more -# than this is named in the finding table. It is the practical threshold -# registered for task success; nothing else reads it. +# than this is named in the finding table. It is the smallest change that +# matters for task success, as registered; nothing else reads it. SUITE_DIP = 0.05 @@ -2898,17 +2703,18 @@ def boot(install, factory, status): "server error", got == [1.0, 0.0, 0.0, 0.0], got)) # A broken build's task success is left out in round 5d and is zero in - # round 2, which ran `full` beside `hand`. + # a round read by the earlier rules. broken = dict(boot(False, False, None)["scores"], hidden_suite={"value": None, "missing": "no install"}) working = dict(boot(True, True, 302)["scores"], hidden_suite={"value": 0.9}) run = {"hand-1": {"scores": broken}, "short-1": {"scores": working}} later = collect(run) - earlier = collect(dict(run, **{"full-1": {"scores": working}})) + earlier = collect({"none-1": {"scores": broken}, + "inline-1": {"scores": working}}) got = (later["task_success"]["values"]["hand"][1], later["reliability"]["values"]["hand"][1], - earlier["task_success"]["values"]["hand"][1]) + earlier["task_success"]["values"]["none"][1]) checks.append(("round 5d reads task success on working builds only", got == (None, 0.0, 0.0), got)) @@ -3055,14 +2861,14 @@ def judged(score, reused=False): checks.append(("the cross-check reads a contrast across rounds unpaired", got == 1.0, got)) - # The same for an earlier round read post-hoc: round 2's reused `full` + # The same for an earlier round read post-hoc: its reused `inline` # against `none`, read by the later rules. - earlier_ours = {"full-1": judged(3, True), "full-2": judged(3, True), + earlier_ours = {"inline-1": judged(3, True), "inline-2": judged(3, True), "none-3": judged(2)} got = (cross_check(earlier_ours, earlier_ours, seed)["results"][ - "judge_design"]["full-none"]["mean"], + "judge_design"]["inline-none"]["mean"], cross_check(earlier_ours, earlier_ours, seed, True)["results"][ - "judge_design"]["full-none"]["mean"]) + "judge_design"]["inline-none"]["mean"]) checks.append(("an earlier round's cross-check is unpaired post-hoc", got == (None, 1.0), got)) @@ -3095,16 +2901,6 @@ def judged(score, reused=False): checks.append(("round 5d's appendix and radar read round 5d's rows", got and radar_axes({}) == RADAR_AXES, got)) - # An earlier round never computes a contrast only round 5d declares. - earlier_table = {"judge_design": {"label": "x", "direction": UP, - "values": {"hybrid": {1: 4.0, 2: 4.0}, - "hand": {1: 3.0, 2: 3.0}}}} - got = ("hybrid-hand" in contrasts(earlier_table, seed)["judge_design"], - "hybrid-hand" in contrasts(earlier_table, seed, (), None, - True)["judge_design"]) - checks.append(("an earlier round computes no round-5d contrast", - got == (False, True), got)) - def planted(*pairs): return {key: {"x": {"verdict": verdict, "size": size}} for key, (verdict, size) in zip(("a", "b"), pairs)} @@ -3220,15 +3016,15 @@ def rows_for(verdict, reliability="held"): checks.append(("the post-hoc reading takes a cross-check", crossed_ok is True, crossed_ok)) - # A round before round 5 read by the later rules decides on app code, - # while its registered reading keeps source lines and files. + # A round read by the later rules decides on app code and prints source + # lines without a verdict, as round 5 does. sized_run = {trial_name(arm, 1): {"scores": {}} for arm in ("none", - "full")} + "inline")} got = (collect(sized_run, later_rules=True)["app_lines"]["direction"], collect(sized_run, later_rules=True)["source_lines"]["direction"], collect(sized_run)["source_lines"]["direction"]) checks.append(("the later rules read app code in any round", - got == (DOWN, NEUTRAL, DOWN), got)) + got == (DOWN, NEUTRAL, NEUTRAL), got)) scratch = os.path.join(tempfile.gettempdir(), "efficacy-posthoc-rules") shutil.rmtree(scratch, ignore_errors=True) page = write_posthoc_rules(earlier, later_table, later_results, seed, @@ -3314,12 +3110,12 @@ def trial(items): trials["skills-1"]["security"] = {"probes": {"x": {"passed": True}}} trials["skills-2"]["security"] = {"probes": {"x": {"passed": True}}} trials["skills-3"]["security"] = {"probes": {"x": {"passed": None}}} - full = pairwise_agreement(security_sets(trials, "skills")) + alike = pairwise_agreement(security_sets(trials, "skills")) trials["skills-2"]["security"] = {"probes": {"x": {"passed": False}}} none = pairwise_agreement(security_sets(trials, "skills")) checks.append(("security agreement counts two empty sets as agreement " "and leaves out an unmeasured trial", - (full, none) == (1.0, 0.0), (full, none))) + (alike, none) == (1.0, 0.0), (alike, none))) def results(verdict, within): contrast = {"verdict": verdict, "non_inferior": {"within": within}} @@ -3346,7 +3142,7 @@ def results(verdict, within): "change": None, "judge": None, "security": {"probes": {"x": {"passed": True}}}} for arm in ("none", "reference", "inline", "hybrid", "skills") - for index in range(1, K_PRIMARY + 1)} + for index in range(1, 4)} _, _, text = rendered(run, 0, {}) section = text[text.find("## Round 5"):] checks.append(("a five-arm report prints conventions, structure and " @@ -3358,15 +3154,11 @@ def results(verdict, within): "hybrid", "skills")), section[:600])) - # Round 5 registers its K, so a run short of it is part-run and no run - # of it owes the escalation of a K = 3 round. - state = assess_escalation(run, {}, 0)["state"] + # Round 5 registers its K, so a run short of it is part-run. runs = " ".join(text[text.find("## Runs per arm"):][:400].split()) - checks.append(("a round-5 run owes no escalation and names the blocks " - "still owed", state == "registered" - and "## The escalation" not in text - and "blocks %d to %d" % (K_PRIMARY + 1, ROUND5_K) in runs, - (state, runs))) + checks.append(("a round-5 run short of its K names the blocks still owed", + "## The escalation" not in text + and "blocks %d to %d" % (4, ROUND5_K) in runs, runs)) # From six blocks a run's intervals are no longer only descriptions. longer = {trial_name(arm, index): dict(run[trial_name(arm, 1)]) @@ -3388,7 +3180,7 @@ def results(verdict, within): whole = dict(almost, **{trial_name(arm, ROUND5_K): {} for arm in ROUND5_RUN}) got = [owed_blocks(run) for run in (almost, gap, whole)] - named = escalation_section(assess_escalation(almost, {}, 0)) + named = blocks_section(almost) checks.append(("one trial of the last block leaves the round part-run", got == [[ROUND5_K], [7, ROUND5_K], []] and "block %d still misses" % ROUND5_K in "\n".join(named) @@ -3930,8 +3722,8 @@ def radar_panels(table, results, active): return panels -def executive_section(trials, table, results, escalation=None, - withdrawn=None, lost=(), scans=(), radar=None): +def executive_section(trials, table, results, withdrawn=None, lost=(), + scans=(), radar=None): """The report's first sections: the summary, a radar per file arm read against no file where `radar` names its two images, light and dark; then the arms against no file: the finding table, one line per file on @@ -3954,9 +3746,7 @@ def executive_section(trials, table, results, escalation=None, scored = between_files(results, active) if scored: lines.extend(["", scored]) - if escalation is not None: - lines.extend(["", caveats_line(trials, escalation, withdrawn or {}, - lost, scans)]) + lines.extend(["", caveats_line(trials, withdrawn or {}, lost, scans)]) return lines @@ -4049,9 +3839,8 @@ def between_files(results, active): """One line scoring the contrasts between two files, 1 to 10 with the wins and the fails, or None where the run holds none. - The score was declared after round 1's results were seen, and stays - for the pairings the finding table has no column for. It digests the - verdict vector and decides nothing. + A score kept for the pairings the finding table has no column for. It + digests the verdict vector and decides nothing. """ parts = [] for treatment, baseline in active: @@ -4076,22 +3865,17 @@ def between_files(results, active): % "; ".join(parts)) -def caveats_line(trials, escalation, withdrawn, lost, scans): - """One line of what qualifies the run: the escalation, withdrawals, - lost trials, reaches and the judge's check.""" +def caveats_line(trials, withdrawn, lost, scans): + """One line of what qualifies the run: the blocks in, withdrawals, lost + trials, reaches and the judge's check.""" labels = {key: label for key, label, _, _ in METRICS} judged = [trial["judge"] for trial in trials.values() if trial["judge"]] reached = [] for scan in scans: if scan["hits"] and scan["name"] not in reached: reached.append(scan["name"]) - if escalation["state"] == "registered": - runs = ("%d of the %d blocks round 5 registers complete, with no " - "escalation" % (ROUND5_K - len(escalation["owed_blocks"]), - ROUND5_K)) - else: - runs = "escalation to K = %d %s" % (K_CEILING, - escalation_phrase(escalation)) + runs = ("%d of the %d registered blocks complete" + % (ROUND5_K - len(owed_blocks(trials)), ROUND5_K)) caveats = ["%d trials, %d judged" % (len(trials), len(judged)), runs, "withdrawn: %s" % ("; ".join(labels.get(key, key) @@ -4110,22 +3894,6 @@ def caveats_line(trials, escalation, withdrawn, lost, scans): return "Caveats: %s." % "; ".join(caveats) -def escalation_phrase(escalation): - """The escalation's state, as the summary states it.""" - state, owed, k = escalation["state"], escalation["owed"], escalation["k"] - if state == "not assessed": - return "not assessed, the run holding K = %d" % k - if state == "assessed": - return ("owed and not yet run" if owed - else "not owed, so K stays %d" % K_PRIMARY) - if not owed: - return ("run without a trigger, so only the K = %d vector counts" - % K_PRIMARY) - if state == "part-escalated": - return "owed and part-run, at K = %d" % k - return "owed and run to K = %d" % K_CEILING - - def withdrawn_section(withdrawn): """The report's lines on each metric withdrawn from this run, and why.""" labels = {key: label for key, label, _, _ in METRICS} @@ -4146,90 +3914,25 @@ def withdrawn_section(withdrawn): return lines -def thresholds(): - """Each primary's practical threshold in words, a shared one said once.""" - worded = [] - for key in PRIMARY: - label = PRACTICAL[key][0] - if key in PROBE_RATES: - label = "%s for the %s" % (label, SHORT[key]) - if label not in worded: - worded.append(label) - if len(worded) == 1: - return worded[0] - return "%s or %s" % (", ".join(worded[:-1]), worded[-1]) - - -def escalation_section(escalation): - """The report's lines on the one escalation to K = 5 allowed, or on the - K round 5 registers in its place.""" - k = escalation["k"] - if escalation["state"] == "registered": - lines = ["## Runs per arm", - "", - "Fixed before the run: round 5 runs K = %d blocks, sized " - "from the noise of the rounds before it, and allows no " - "escalation." % ROUND5_K, - ""] - owed = escalation["owed_blocks"] - if owed: - lines.append("**Part-run.** A block is complete when every " - "registered arm has its trial in it; %s still %s a " - "trial before any verdict below is the round's." - % (blocks_named(owed), - "misses" if len(owed) == 1 else "miss")) - else: - lines.append("**Complete.** Every registered arm has its trial " - "in all %d blocks." % ROUND5_K) - return lines - lines = ["## The escalation to K = %d" % K_CEILING, +def blocks_section(trials): + """The report's lines on the K the round registers, and how many of its + blocks the run holds.""" + lines = ["## Runs per arm", "", - "Fixed before the run: one escalation is owed where a primary " - "dimension's interval contains zero while its mean paired " - "difference exceeds %s in either direction, on any contrast. " - "K never exceeds %d." % (thresholds(), K_CEILING), + "Fixed before the run: the round runs K = %d blocks, sized from " + "the noise of the rounds before it, and adds none once results " + "are seen." % ROUND5_K, ""] - state, owed = escalation["state"], escalation["owed"] - if state == "not assessed": - lines.append("Not assessed: the run holds K = %d, and the rule reads " - "K = %d." % (k, K_PRIMARY)) - return lines - if state == "assessed" and owed: - lines.append("**Owed.** Run blocks %d to %d with `--k %d --from %s`, " - "then report again. A row still containing zero at K = " - "%d is reported as no improvement shown." - % (K_PRIMARY + 1, K_CEILING, K_CEILING, - escalation["from"], K_CEILING)) - elif state == "assessed": - lines.append("**Not owed.** No primary dimension's row meets the " - "rule, so K stays %d." % K_PRIMARY) - elif not owed: - lines.append("**Run without a trigger.** The first %d blocks owed no " - "escalation, so every block past them was sampled outside " - "the escalation rule. Read the K = %d vector; the K = %d " - "rows are not evidence." % (K_PRIMARY, K_PRIMARY, k)) - elif state == "part-escalated": - lines.append("**Part-run.** The first %d blocks owed it and the run " - "holds K = %d, so block %d is still owed before the K = " - "%d vector is read." % (K_PRIMARY, k, K_CEILING, - K_CEILING)) + owed = owed_blocks(trials) + if owed: + lines.append("**Part-run.** A block is complete when every " + "registered arm has its trial in it; %s still %s a " + "trial before any verdict below is the round's." + % (blocks_named(owed), + "misses" if len(owed) == 1 else "miss")) else: - lines.append("**Run.** The first %d blocks owed it, on the rows " - "below. No further escalation is permitted: a row still " - "containing zero at K = %d is reported as no improvement " - "shown." % (K_PRIMARY, K_CEILING)) - if escalation["triggers"]: - labels = {key: label for key, label, _, _ in METRICS} - lines.append("") - lines.append("| Metric | Contrast | Mean difference | Interval " - "| Threshold |") - lines.append("|---|---|---|---|---|") - for row in escalation["triggers"]: - lines.append("| %s | %s | %s | (%s, %s) | %s |" - % (labels[row["metric"]], - row["contrast"].replace("-", "−"), - number(row["mean"]), number(row["low"]), - number(row["high"]), row["threshold"])) + lines.append("**Complete.** Every registered arm has its trial " + "in all %d blocks." % ROUND5_K) return lines @@ -4495,7 +4198,7 @@ def lost_checks(): def band_checks(seed): """App code's size reads against a band: a rise inside the margin is held, only one wholly past it worse; round 5 reports the rows it - supersedes without a verdict, and an earlier round keeps them.""" + supersedes without a verdict.""" # A margin of 20 lines: the loss side of each interval, for a metric that # improves downward, placed against it. @@ -4523,19 +4226,10 @@ def trial(app, files): results = contrasts(collect(trials), seed, (), ROUND5_MARGINS) app = results["app_lines"]["skills-none"]["verdict"] files = results["tracked_files"]["skills-none"]["verdict"] - earlier = {name.replace("skills", "full"): value - for name, value in trials.items()} - reread = contrasts(collect(earlier), seed) - kept = reread["tracked_files"]["full-none"] - later = reread["app_lines"]["full-none"]["verdict"] checks.extend([ - ("an earlier round rescored prints app code without a verdict", - later == "reported without a verdict", later), ("round 5 reads a 10 % rise in app code as held", app == "held", app), ("round 5 reports the files it supersedes without a verdict", - files == "reported without a verdict", files), - ("an earlier round still reads its files row", kept["verdict"] - == "worse", kept["verdict"])]) + files == "reported without a verdict", files)]) return checks @@ -4741,14 +4435,14 @@ def rescan_checks(): shutil.rmtree(scratch, ignore_errors=True) workspace = os.path.join(scratch, "none-2") os.makedirs(workspace) - os.makedirs(os.path.join(scratch, "full-1")) + os.makedirs(os.path.join(scratch, "inline-1")) folder = "".join(char if char.isalnum() else "-" for char in os.path.abspath(workspace)) projects = os.path.join(scratch, "home", ".claude", "projects", folder) os.makedirs(projects) entry = {"type": "assistant", "message": {"content": [ {"type": "tool_use", "name": "Bash", - "input": {"command": "cat ../full-1/src/tariff/pricing.py"}}]}} + "input": {"command": "cat ../inline-1/src/tariff/pricing.py"}}]}} with io.open(os.path.join(projects, "planted.jsonl"), "w", encoding="utf-8") as handle: handle.write(json.dumps(entry) + "\n") @@ -4769,195 +4463,14 @@ def rescan_checks(): shutil.rmtree(scratch, ignore_errors=True) return [("the planted transcript carries one call", landed), ("its record's clean scan is read again and flagged", - terms == ["../full-1"])] - - -# One row on each side of the escalation rule. The interval is planted beside -# its pairs, so each case turns on the rule rather than on the bootstrap. -ESCALATING = ( - ("a crossing interval with an effect of 0.67 owes it", "judge_design", - "full-none", [2.0, -1.0, 1.0], -1.0, 2.0, True), - ("the same row on C-A owes it", "judge_readability", "hand-none", - [2.0, -1.0, 1.0], -1.0, 2.0, True), - ("an effect of 0.67 the other way owes it", "judge_maintainability", - "full-hand", [-2.0, 1.0, -1.0], -2.0, 1.0, True), - ("an effect of exactly 0.5 does not", "judge_design", "full-none", - [1.5, -1.0, 1.0], -1.0, 1.5, False), - ("an interval clear of zero does not", "judge_design", "full-none", - [1.0, 1.0, 1.0], 1.0, 1.0, False), - ("a row outside the primary dimensions does not", "task_success", "full-none", - [2.0, -1.0, 1.0], -1.0, 2.0, False), - ("an interval not computed does not", "judge_design", "full-none", [2.0], - None, None, False), -) - - -def planted_results(key, name, pairs, low, high): - """Contrasts with one planted row, every other row measured nothing.""" - results = {metric: {"%s-%s" % pair: {"pairs": [], - "interval": {"low": None, - "high": None}} - for pair in CONTRASTS} - for metric, _, _, _ in METRICS} - results[key][name] = {"pairs": pairs, - "interval": {"low": low, "high": high}} - return results - - -def escalation_checks(seed): - """The escalation rule on planted rows, and a planted K = 5 run rendered.""" - checks = [] - for label, key, name, pairs, low, high, expected in ESCALATING: - triggers = escalation_triggers(planted_results(key, name, pairs, low, - high)) - checks.append((label, bool(triggers) == expected, triggers)) - - # An owed escalation names the first trial of block four the way the - # harness spells it, so the printed command runs as written. - three = {trial_name(arm, 1): {} for arm in ("none", "full", "hand")} - owed = "\n".join(escalation_section({ - "k": K_PRIMARY, "state": "assessed", "owed": True, "triggers": [], - "from": block_start(None, three, K_PRIMARY + 1)})) - checks.append(("an owed escalation's command names a trial the harness " - "takes", "--from none-4" in owed and "--from A" not in owed, - owed)) - - # Block four starts one arm later per block after block one: read off - # the run's own first block where its records show it, and off the arms' - # declared order where none do. - five = {trial_name(arm, 1): {} - for arm in ("none", "inline", "hybrid", "reference", "skills")} - root = tempfile.mkdtemp(prefix="efficacy-report-block-start-") - with io.open(os.path.join(root, "run-2026-10-27T00-00-00.json"), "w", - encoding="utf-8") as handle: - json.dump({"trials": [{"arm": arm, "trial": 1} for arm in ( - "none", "inline", "hybrid", "reference", "skills")]}, handle) - got = (block_start(root, five, K_PRIMARY + 1), - block_start(None, five, K_PRIMARY + 1)) - shutil.rmtree(root, ignore_errors=True) - checks.append(("block four starts where the run's own order puts it", - got == ("reference-4", "inline-4"), got)) - - # Five blocks of judged trials. The first three alone must decide the - # escalation, and the report must print their vector beside the fifth's. - design = {"none": [3, 3, 3, 3, 3], "full": [5, 2, 4, 4, 4], - "hand": [3, 3, 3, 3, 3]} - trials = {trial_name(arm, index): { - "scores": {}, "change": None, - "judge": {"answer": {"rubric": {"design": {"score": score}}}}} - for arm, scores in design.items() - for index, score in enumerate(scores, 1)} - table = collect(trials) - results = contrasts(table, seed) - escalation = assess_escalation(trials, results, seed) - earlier = escalation.get("results_k3") or {} - checks.append(("a K = 5 run is judged on its first three blocks", - escalation["state"] == "escalated" - and len(path(earlier, "judge_design", "full-none", "pairs") - or []) == K_PRIMARY - and len(results["judge_design"]["full-none"]["pairs"]) - == K_CEILING, escalation["state"])) - - first = {name: trial for name, trial in trials.items() - if index_of(name) <= K_PRIMARY} - state = assess_escalation(first, contrasts(collect(first), seed), - seed)["state"] - checks.append(("a K = 3 run is assessed on its own vector", - state == "assessed", state)) - - scratch = os.path.join(tempfile.gettempdir(), - "efficacy-report-escalation-self-test") - shutil.rmtree(scratch, ignore_errors=True) - os.makedirs(scratch) - target = write_report(scratch, trials, table, results, seed, - escalation, out_dir=scratch) - with io.open(target[:-len(".md")] + "-record.md", - encoding="utf-8") as handle: - text = handle.read() - shutil.rmtree(scratch, ignore_errors=True) - checks.append(("the report carries the escalation section", - "## The escalation to K = 5" in text, None)) - checks.append(("an escalated report prints both vectors", - "| Metric | full−none, K = 3 | full−none, K = 5 |" in text, - None)) - checks.append(("the judge is checked by its evidence, not a person", - "No person scores the judge." in text - and "holdout" not in text.lower(), None)) - - # The planted report carries prose far over the width, such as the - # escalation rule's paragraph, so the wrap is exercised, not assumed. - width = markdown_width() - long_prose = [line for line in text.splitlines() - if len(line) > width and not line.startswith(("|", "#"))] - checks.append(("no prose line exceeds the declared width", - width == 88 and "exceeds 0.5 points" in text - and not long_prose, long_prose[:2])) - return checks - - -def posthoc_checks(seed): - """Checks declared after a run are printed, and decide nothing.""" - keys = {key for key, _, _, _ in POSTHOC} - checks = [("no after-the-results check is a verdict metric", - not keys & {key for key, _, _, _ in METRICS}, sorted(keys))] - - # Arm full sets every header on every trial and the bare arm sets none, - # so the row would - # read "better" if a verdict were ever computed for it. - headers = {"none": 0, "full": 4, "hand": 2} - trials = {trial_name(arm, index): { - "scores": {}, "change": None, "judge": None, - "security": {"security_headers": {"value": value, "missing": None}}} - for arm, value in headers.items() for index in range(1, K_PRIMARY + 1)} - table = collect(trials) - results = contrasts(table, seed) - posthoc_table = collect(trials, POSTHOC) - posthoc = (posthoc_table, contrasts(posthoc_table, seed)) - checks.append(("the planted row would read better", - posthoc[1]["security_headers"]["full-none"]["verdict"] - == "better", posthoc[1]["security_headers"]["full-none"])) - - # A round-3 reading carries its probes, and its checks were fixed before - # the run, so the section that calls them post-hoc is not printed for it. - probed = {name: dict(trial, security=dict(trial["security"], probes={})) - for name, trial in trials.items()} - checks.append(("a run whose readings carry probes has no post-hoc section", - posthoc_owed(trials) and not posthoc_owed(probed), - (posthoc_owed(trials), posthoc_owed(probed)))) - - scratch = os.path.join(tempfile.gettempdir(), - "efficacy-report-posthoc-self-test") - shutil.rmtree(scratch, ignore_errors=True) - os.makedirs(scratch) - target = write_report(scratch, trials, table, results, seed, - assess_escalation(trials, results, seed), - out_dir=scratch, posthoc=posthoc) - with io.open(target[:-len(".md")] + "-record.md", - encoding="utf-8") as handle: - text = handle.read() - shutil.rmtree(scratch, ignore_errors=True) - - label = "Security headers on /, of four" - heading = "## Security, read with checks declared after the results" - section = text.split(heading)[1].split("\n## ")[0] if heading in text \ - else "" - row = [line for line in section.splitlines() if line.startswith( - "| " + label)] - vector = text.split("## Verdict vector")[-1] - checks.append(("the report prints the section", bool(row), None)) - checks.append(("its row carries no verdict", - bool(row) and not any(word in row[0] for word in - ("better", "worse", "improvement")), - row)) - checks.append(("its row is not in the verdict vector", - label not in vector, None)) - return checks + terms == ["../inline-1"])] def planted_change_run(revision): - """K = 3 change tasks graded at `revision`, arm full ahead on every row.""" - rates = {"none": 0.25, "full": 0.75, "hand": 0.5} - lines = {"none": 300, "full": 200, "hand": 250} + """K = 3 change tasks graded at `revision`, arm skills ahead on every + row.""" + rates = {"none": 0.25, "skills": 0.75, "hybrid": 0.5} + lines = {"none": 300, "skills": 200, "hybrid": 250} def change(arm, index): return {"suite_revision": revision, @@ -4969,21 +4482,20 @@ def change(arm, index): return {trial_name(arm, index): {"scores": {}, "judge": None, "security": None, "change": change(arm, index)} - for arm in rates for index in range(1, K_PRIMARY + 1)} + for arm in rates for index in range(1, 4)} def rendered(trials, seed, withdrawn): """The report a planted run renders, withdrawn metrics blanked first.""" table = collect(trials) results = round_contrasts(trials, table, seed) - before = results["change_success"]["full-none"]["verdict"] + before = results["change_success"]["skills-none"]["verdict"] withdraw(withdrawn, table, results) scratch = os.path.join(tempfile.gettempdir(), "efficacy-report-withdrawal-render") shutil.rmtree(scratch, ignore_errors=True) os.makedirs(scratch) target = write_report(scratch, trials, table, results, seed, - assess_escalation(trials, results, seed, withdrawn), out_dir=scratch, withdrawn=withdrawn) with io.open(target[:-len(".md")] + "-record.md", encoding="utf-8") as handle: @@ -5037,7 +4549,7 @@ def withdrawal_checks(seed): ("the planted row read better before withdrawal", before == "better", before), ("withdrawal blanks every value of the row", - len(values) == 3 * K_PRIMARY + len(values) == 9 and all(value is None for value in values), values), ("its change-task row prints no number or verdict", len(change) == 1 and "withdrawn" in change[0] and not any( @@ -5062,7 +4574,7 @@ def withdrawal_checks(seed): and "## Summary" not in text, None), ("the line between files scores the verdicts, the withdrawn metric " "not among them", - "full − hand 10.0 (1 won, 0 failed)" in finding, finding), + "skills − hybrid 10.0 (1 won, 0 failed)" in finding, finding), ("it names the withdrawal among the caveats", "withdrawn: %s;" % label in finding, None), ]) @@ -5074,7 +4586,7 @@ def withdrawal_checks(seed): and "## Withdrawn measurements" not in text, kept)) finding = finding_of(text) checks.append(("that run's line between files counts the row a win", - "full − hand 10.0 (2 won, 0 failed)" in finding + "skills − hybrid 10.0 (2 won, 0 failed)" in finding and "withdrawn: nothing;" in finding, finding)) # The rule at its ends and in the middle: round 1's templates against no @@ -5117,35 +4629,35 @@ def executive_checks(seed): checks.append((label, got == expected, got)) # The reading sets the longer file's answer beside the shorter's. - lengths = {"full": 400, "hand": 40} + lengths = {"inline": 400, "hand": 40} for label, answers, expected in ( ("a short Yes beside a long No reads length is not quality", - {"full": "No", "hand": "Yes"}, + {"inline": "No", "hand": "Yes"}, "length is not quality — the long file spent the agent's " "attention on conventions, the short one on the code"), ("a long Yes beside a short Worse reads the long file's gain", - {"full": "Yes", "hand": "Worse"}, + {"inline": "Yes", "hand": "Worse"}, "the long file added quality, the short one did not"), ("two Yes answers read long or short", - {"full": "Yes", "hand": "Yes"}, + {"inline": "Yes", "hand": "Yes"}, "a context file adds quality, long or short"), - ("two No answers read neither", {"full": "No", "hand": "No"}, + ("two No answers read neither", {"inline": "No", "hand": "No"}, "neither file added quality"), ("an unmeasured column reads not measured", - {"full": "Not measured", "hand": "Yes"}, NOT_MEASURED)): + {"inline": "Not measured", "hand": "Yes"}, NOT_MEASURED)): got = reading(answers, lengths) checks.append((label, got == expected, got)) # With more than two files the reading names the two it compares; with # two it needs no names, since the columns are the only ones. - four = {"full": 391, "short": 39, "hybrid": 516, "hand": 40} + four = {"inline": 391, "short": 39, "hybrid": 516, "hand": 40} named = compared({arm: "No" for arm in four}, four) checks.append(("a reading over four files names the two it compares", named == ", reading the longest file beside the shortest " "(`hybrid`, `short`)", named)) checks.append(("a reading over two files names none", - compared({"full": "No", "hand": "No"}, lengths) == "", - compared({"full": "No", "hand": "No"}, lengths))) + compared({"inline": "No", "hand": "No"}, lengths) == "", + compared({"inline": "No", "hand": "No"}, lengths))) # An interval over fewer pairs than the round's blocks names its count; # one over every block does not. @@ -5242,38 +4754,38 @@ def executive_checks(seed): # A why-line says, in words, what stands on a record or verdict below: # the run that could not boot, the structure built beyond the task and # the work it took, what the judge read, and the patterns missed. - trials = {"full-1": {"scores": {"boot": {"value": { + trials = {"inline-1": {"scores": {"boot": {"value": { "factory": False, "factory_error": "planted error"}}}}, - "full-2": {"scores": {"boot": {"value": {"factory": True}}}}, + "inline-2": {"scores": {"boot": {"value": {"factory": True}}}}, "none-1": {"scores": {"boot": {"value": {"factory": False}}}}} - got = boot_failures(trials, "full") + got = boot_failures(trials, "inline") checks.append(("boot failures are the arm's own, with the error", got == (["planted error"], 2), got)) - planted = {key: {"full-none": {"mean": 0.0, "verdict": shown}} + planted = {key: {"inline-none": {"mean": 0.0, "verdict": shown}} for key, _, _, _ in METRICS} - planted["tracked_files"]["full-none"]["verdict"] = "worse" - planted["turns"]["full-none"]["verdict"] = "worse" - planted["churn_lines"]["full-none"]["verdict"] = "worse" - planted["patterns_missed"]["full-none"]["verdict"] = "worse" - planted["judge_readability"]["full-none"]["verdict"] = "better" - planted["adherence"]["full-none"]["verdict"] = "better" - got = why_line(trials, planted, "full", "full-none", "No", 400) + planted["tracked_files"]["inline-none"]["verdict"] = "worse" + planted["turns"]["inline-none"]["verdict"] = "worse" + planted["churn_lines"]["inline-none"]["verdict"] = "worse" + planted["patterns_missed"]["inline-none"]["verdict"] = "worse" + planted["judge_readability"]["inline-none"]["verdict"] = "better" + planted["adherence"]["inline-none"]["verdict"] = "better" + got = why_line(trials, planted, "inline", "inline-none", "No", 400) checks.append(("the why-line says what the records and verdicts hold", - got == "**`full`, No.** One run of two left the " + got == "**`inline`, No.** One run of two left the " "app unable to boot (`planted error`). It built more than " "the task asked for: more files, and took more turns to " "do it; the follow-up change had to move through that " "structure too. The judge read its code as more " "readable; it missed more of the patterns the domain " "called for.", got)) - trials["full-1"]["scores"]["boot"]["value"]["factory_error"] = \ + trials["inline-1"]["scores"]["boot"]["value"]["factory_error"] = \ "ModuleNotFoundError(\"No module named 'planted'\")" - planted["judge_readability"]["full-none"]["verdict"] = shown - got = why_line(trials, planted, "full", "full-none", "No", 400) + planted["judge_readability"]["inline-none"]["verdict"] = shown + got = why_line(trials, planted, "inline", "inline-none", "No", 400) checks.append(("a module missing after a clean install is a declared " "dependency, and a win the judge did not give is a tool " "count", - got.startswith("**`full`, No.** One run of two " + got.startswith("**`inline`, No.** One run of two " "declared its dependencies so that a clean " "install left the app unable to boot.") and got.endswith("The judge saw none of it as better " @@ -5314,33 +4826,36 @@ def row_start(arm, verdict): < text.find("## Arms against `none`"), None), ("it has a row per arm, the bare arm first, with the files' lines", 0 < text.find("| `none` | no file | — |") - < text.find(row_start("full", "Not measured")) and context_lines("full") - > context_lines("hand"), prose_of(text, "## Arms against `none`")), + < text.find(row_start("hybrid", "Not measured")) + and context_lines("skills") > context_lines("hybrid"), + prose_of(text, "## Arms against `none`")), ("an unmeasured run answers Not measured in every cell", - row_start("full", "Not measured") + " not measured |" in text - and row_start("hand", "Not measured") + " not measured |" in text - and "Together: not measured. K = %d," % K_PRIMARY in text, + row_start("hybrid", "Not measured") + " not measured |" in text + and row_start("skills", "Not measured") + " not measured |" in text + and "Together: not measured. K = 3," in text, prose_of(text, "## Arms against `none`")), ("each file's why-line sits between the table and the reading", "▲ better and ▼ worse" in text and 0 < text.find("▲ better and ▼ worse") - < text.find("**`full`, Not measured.** Every win is " + < text.find("**`hybrid`, Not measured.** Every win is " "something a tool counts.") - < text.find("**`hand`, Not measured.**") + < text.find("**`skills`, Not measured.**") < text.find("Together:"), prose_of(text, "## Arms against `none`")), ]) - # A round 2 run: five arms, `full` and `hand` reused from round 1, the - # judge's design score constant per arm so each contrast's verdict is - # known. Every declared contrast is printed, one column per file arm, - # and the reused arms and the contrasts crossing rounds are named. - design = {"none": 3, "full": 3, "short": 4, "hybrid": 3, "hand": 4} + # A run reusing an earlier round's trials: five arms, `hybrid` and + # `reference` reused, the judge's design score constant per arm so each + # contrast's verdict is known. Every declared contrast is printed, one + # column per file arm, and the reused arms and the contrasts crossing + # rounds are named. + design = {"none": 3, "inline": 3, "hybrid": 3, "reference": 4, + "skills": 4} trials = {trial_name(arm, index): { "scores": ({"reused_from": {"name": "planted"}} - if arm in ("full", "hand") else {}), + if arm in ("hybrid", "reference") else {}), "change": None, "security": None, "judge": {"answer": {"rubric": {"design": {"score": score}}}}} - for arm, score in design.items() for index in range(1, K_PRIMARY + 1)} + for arm, score in design.items() for index in range(1, 4)} _, _, text = rendered(trials, seed, {}) finding = prose_of(text, "## Arms against `none`") @@ -5350,7 +4865,7 @@ def row_start(arm, verdict): checks.extend([ ("a five-arm run prints one row per arm", all("| `%s` |" % arm in finding - for arm in ("none", "full", "short", "hybrid", "hand")), + for arm in ("none", "inline", "hybrid", "reference", "skills")), finding), ("it prints every declared contrast its arms ran", all("%s − %s" % pair in finding for pair in active_contrasts(trials) @@ -5360,17 +4875,18 @@ def row_start(arm, verdict): .split(" | ")) == len(active_contrasts(trials)) + 1, finding), ("the reused arms and the contrasts crossing rounds are named", - "Reused from an earlier round: full (3 trials) and hand (3 " + "Reused from an earlier round: hybrid (3 trials) and reference (3 " "trials). Pairing them with this round's trials, across days: " - "full − none, hand − none, short − hand, hybrid − full and " - "short − full." - in finding and "reused from an earlier round: full and hand" + "hybrid − none, reference − none and skills − hybrid." + in finding and "reused from an earlier round: hybrid and reference" in finding, finding), ("the reading sets the longest measured file against the shortest", - "Together: length is not quality" in finding + "Together: the long file added quality, the short one did not" + in finding and all(row_start(arm, verdict) in finding for arm, verdict in - (("full", "Not measured"), ("short", "Yes"), - ("hybrid", "No"), ("hand", "Not measured"))), finding), + (("hybrid", "Not measured"), ("inline", "No"), + ("reference", "Not measured"), ("skills", "Yes"))), + finding), ("a trial's repeats are meaned, and one judging means itself", judge_score({"judgings": [ {"answer": {"rubric": {"design": {"score": 4}}}}, @@ -5382,10 +4898,9 @@ def row_start(arm, verdict): "design") == 3, None), ("a contrast crossing rounds carries no verdict and counts nowhere", CROSSING_VERDICT in text - and "short − hand unscored (0 won, 0 failed)" in finding - and "hybrid − full unscored (0 won, 0 failed)" in finding, finding), + and "skills − hybrid unscored (0 won, 0 failed)" in finding, finding), ("a three-arm run prints only its own contrasts", - "| Metric | full−none | hand−none | full−hand |" + "| Metric | hybrid−none | skills−none | skills−hybrid |" in rendered(planted_change_run("r"), seed, {})[2], None), ]) return checks @@ -5396,12 +4911,12 @@ def exclusion_checks(): task takes only its change reading; a reached trial is a lost one.""" def planted(): return {name: {"scores": {"name": name}, "change": {"name": name}} - for name in ("none-1", "full-1", "hand-1")} + for name in ("none-1", "inline-1", "hand-1")} hit = [{"tool": "Bash", "term": "hidden-suite", "call": "planted"}] trials = planted() left_out = exclude_reached(trials, [ - {"name": "full-1", "hits": hit}, + {"name": "inline-1", "hits": hit}, {"name": "hand-1" + CHANGE_TASK, "hits": hit}, {"name": "none-1", "hits": []}, {"name": "short-1", "hits": hit}]) @@ -5411,26 +4926,26 @@ def planted(): with io.open(os.path.join(scratch, "run-planted.json"), "w", encoding="utf-8") as handle: json.dump({"trials": [ - {"arm": "full", "trial": 1, "task": "build", + {"arm": "inline", "trial": 1, "task": "build", "outcome": "reached", "reason": "planted", "started_at": "2026-10-15T10:00:00"}, - {"arm": "full", "trial": 1, "task": "build", + {"arm": "inline", "trial": 1, "task": "build", "outcome": "completed", "started_at": "2026-10-15T11:00:00"}]}, handle) lost = lost_trials(scratch) shutil.rmtree(scratch, ignore_errors=True) return [ ("a reached build trial is left out whole", - "full-1" not in trials and "none-1" in trials, sorted(trials)), + "inline-1" not in trials and "none-1" in trials, sorted(trials)), ("a reached change task takes only its change reading", trials["hand-1"]["change"] is None and trials["hand-1"]["scores"] == {"name": "hand-1"}, trials.get("hand-1")), ("only what was flagged and held is named as left out", - left_out == ["full-1", "hand-1" + CHANGE_TASK], left_out), + left_out == ["inline-1", "hand-1" + CHANGE_TASK], left_out), ("a reached trial is listed among the lost, with its re-run", [(entry["name"], entry["rerun"]) for entry in lost] - == [("full-1", "completed")], lost), + == [("inline-1", "completed")], lost), ] @@ -5445,24 +4960,24 @@ def judged(model, design, readability): return {"scores": {}, "judge": judging, "judgings": [judging], "change": None, "security": None} - # The rounds' judge reads full better on both rows. The other reads full + # The rounds' judge reads inline better on both rows. The other reads full # worse on design and better on readability. ours, theirs = {}, {} - for index, (full_design, other_design, full_reads, other_reads) in \ + for index, (treated_design, other_design, treated_reads, other_reads) in \ enumerate(((4, 2, 4, 4), (4, 2, 5, 4), (5, 1, 4, 5)), 1): ours["none-%d" % index] = judged("ours", 2, 3) - ours["full-%d" % index] = judged("ours", full_design, full_reads) + ours["inline-%d" % index] = judged("ours", treated_design, treated_reads) theirs["none-%d" % index] = judged("theirs", 4, 3) - theirs["full-%d" % index] = judged("theirs", other_design, + theirs["inline-%d" % index] = judged("theirs", other_design, other_reads) results = contrasts(collect(ours), seed) - before = (results["judge_design"]["full-none"]["verdict"], - results["judge_readability"]["full-none"]["verdict"]) + before = (results["judge_design"]["inline-none"]["verdict"], + results["judge_readability"]["inline-none"]["verdict"]) check = cross_check(ours, theirs, seed) withheld = disagree(results, check) text = "\n".join(cross_check_section(check)) - # Only the none trials read: the full-none contrast has no other reading, + # Only the none trials read: the inline-none contrast has no other reading, # so the rounds' judge's verdict stands. unread = contrasts(collect(ours), seed) partial = cross_check(ours, {name: trial for name, trial @@ -5470,15 +4985,15 @@ def judged(model, design, readability): seed) disagree(unread, partial) return [ - ("the planted rounds' judge reads full better on both rows", + ("the planted rounds' judge reads inline better on both rows", before == ("better", "better"), before), ("a direction the other judge reverses loses its verdict", - results["judge_design"]["full-none"]["verdict"] == DISAGREE_VERDICT + results["judge_design"]["inline-none"]["verdict"] == DISAGREE_VERDICT and [entry["metric"] for entry in withheld] == ["judge_design"], - results["judge_design"]["full-none"]["verdict"]), + results["judge_design"]["inline-none"]["verdict"]), ("a direction both judges read keeps its verdict", - results["judge_readability"]["full-none"]["verdict"] == "better", - results["judge_readability"]["full-none"]["verdict"]), + results["judge_readability"]["inline-none"]["verdict"] == "better", + results["judge_readability"]["inline-none"]["verdict"]), ("agreement is counted per row over the trials both read", check["rows"]["judge_design"] == {"trials": 6, "mean_difference": -0.3333, @@ -5486,11 +5001,11 @@ def judged(model, design, readability): and check["rows"]["judge_readability"]["within_one"] == 1.0, check["rows"]), ("the section names the model and the withheld verdict", - "`theirs` read 6 trial(s)" in text and "- design, full-none" in text, + "`theirs` read 6 trial(s)" in text and "- design, inline-none" in text, text[:200]), ("a contrast the other judge did not read keeps its verdict", - unread["judge_design"]["full-none"]["verdict"] == "better", - unread["judge_design"]["full-none"]["verdict"]), + unread["judge_design"]["inline-none"]["verdict"] == "better", + unread["judge_design"]["inline-none"]["verdict"]), ("a root with no judgings yields no cross-check", load_cross_check(os.path.join(HERE, "no-such-root"), ours) == {}, None), @@ -5508,13 +5023,12 @@ def documents_checks(seed): trials = planted_change_run("any-revision") table = collect(trials) results = contrasts(table, seed, crossed_labels(trials)) - results["task_success"]["full-none"]["verdict"] = "worse" + results["task_success"]["skills-none"]["verdict"] = "worse" scratch = os.path.join(tempfile.gettempdir(), "efficacy-report-documents-self-test") shutil.rmtree(scratch, ignore_errors=True) os.makedirs(scratch) target = write_report(scratch, trials, table, results, seed, - assess_escalation(trials, results, seed), out_dir=scratch) stem = target[:-len(".md")] texts = {} @@ -5530,9 +5044,12 @@ def documents_checks(seed): if line.startswith("## ")] return [ ("the report names each approach and its verdict in plain words", - "### `full`" in report and "### `hand`" in report + "### `skills`" in report and "### `hybrid`" in report and "**Verdict: worse**, because of the hidden tests." in report and PLAIN_VERDICT_RULE[:40] in report, report[:400]), + ("the judge is checked by its evidence, not a person", + "No person scores the judge." in texts["-record"] + and "holdout" not in texts["-record"].lower(), None), ("the report links its appendix, and the appendix the record", "-appendix.md)" in report and "-record.md)" in appendix, None), ("the appendix holds what produced the results, the radar's axes " @@ -5547,8 +5064,8 @@ def documents_checks(seed): "appendix", "can be called established" in report and "Every interval below is descriptive." in appendix, None), ("a comparison across rounds reads as not given, not too few runs", - plain_verdict({key: {"full-none": {"verdict": CROSSING_VERDICT}} - for key in ANSWERED}, "full-none", "Not measured") + plain_verdict({key: {"inline-none": {"verdict": CROSSING_VERDICT}} + for key in ANSWERED}, "inline-none", "Not measured") .startswith("**Verdict: not given.**"), None), ("a round 5 run short of its last block says it is provisional", any("block %d still miss a run" % ROUND5_K in line @@ -5564,15 +5081,15 @@ def documents_checks(seed): ("a broken build is named even where reliability reads neutral", any(line.startswith("- Noted, though reliability") for line in plain_arm_lines( - {"full-1": {"scores": {"boot": {"value": { - "factory": False}}}}, "full-2": {"scores": {}}}, + {"inline-1": {"scores": {"boot": {"value": { + "factory": False}}}}, "inline-2": {"scores": {}}}, {"task_success": {"values": {"none": {1: 1.0, 2: 1.0}, - "full": {1: 0.0, 2: 1.0}}}, - "cost_usd": {"values": {"none": {1: 1.0}, "full": {1: 1.0}}}}, - {key: {"full-none": {"verdict": "no improvement shown"}} + "inline": {1: 0.0, 2: 1.0}}}, + "cost_usd": {"values": {"none": {1: 1.0}, "inline": {1: 1.0}}}}, + {key: {"inline-none": {"verdict": "no improvement shown"}} for _, keys in RADAR_AXES for key in keys} - | {key: {"full-none": {"verdict": "no improvement shown"}} - for key in ANSWERED}, "full", 391)), None), + | {key: {"inline-none": {"verdict": "no improvement shown"}} + for key in ANSWERED}, "inline", 391)), None), ("run counts come from the runs scored, a spread where they differ", times({"none": 15, "skills": 12, "hybrid": 15}, ["skills", "hybrid"]) == "between 12 and 15 times" @@ -5581,8 +5098,8 @@ def documents_checks(seed): def self_test(seed): - """Check the verdict rule, the relative margin, the escalation rule, the - withdrawal of a metric and the reach section.""" + """Check the verdict rule, the relative margin, the withdrawal of a + metric and the reach section.""" checks = [] for label, differences, direction, expected in WORKED: interval = bca_interval(list(differences), seed) @@ -5627,8 +5144,8 @@ def self_test(seed): metric_keys = {key for key, _, _, _ in METRICS} worded = {key for key, _ in READS} lacking = sorted(key for key in PRIMARY - if not (key in MARGINS and key in PRACTICAL - and key in SHORT and key in metric_keys + if not (key in MARGINS and key in SHORT + and key in metric_keys and (key in worded or key in PROBE_RATES))) unmatched = sorted(judged.symmetric_difference( key for key in PRIMARY if key not in PROBE_RATES)) @@ -5659,8 +5176,6 @@ def self_test(seed): "seen": {"lines": 1500}}}} got = per_kloc(planted, "complexity", "over_15") checks.append(("a nested count is taken per KLOC", got == 2.0, got)) - checks.extend(escalation_checks(seed)) - checks.extend(posthoc_checks(seed)) checks.extend(withdrawal_checks(seed)) checks.extend(executive_checks(seed)) checks.extend(documents_checks(seed)) @@ -5775,14 +5290,12 @@ def main(argv): print("no trial is left to report once the reached ones are out") return 2 - # A round escalates once, to K = 5, or registers its own K, and goes no - # further, so a run past its ceiling is refused rather than reported as - # though the bound held. + # A round registers its K and goes no further, so a run past it is + # refused rather than reported as though the bound held. k = max(index_of(name) for name in trials) - ceiling = k_ceiling({arm_of(name) for name in trials}) - if k > ceiling: - print("refused: the run holds K = %d, past the ceiling of " - "K = %d" % (k, ceiling)) + if k > ROUND5_K: + print("refused: the run holds K = %d, past the registered K = %d" + % (k, ROUND5_K)) return 2 table = collect(trials) results = round_contrasts(trials, table, options.seed) @@ -5810,24 +5323,15 @@ def main(argv): return 2 check = cross_check(trials, other, options.seed) disagree(results, check) - escalation = assess_escalation(trials, results, options.seed, withdrawn, - options.root) - posthoc = None - if posthoc_owed(trials): - posthoc_table = collect(trials, POSTHOC) - posthoc = (posthoc_table, round_contrasts(trials, posthoc_table, - options.seed)) target = write_report(options.root, trials, table, results, options.seed, - escalation, out_dir, posthoc, withdrawn, check) + out_dir, withdrawn, check) with io.open(os.path.join(scoring_area(options.root), "aggregate.json"), "w", encoding="utf-8") as handle: json.dump({"seed": options.seed, "table": table, "results": results, - "escalation": escalation, + "blocks": blocks_state(trials), "withdrawn": withdrawn, - "cross_check": check, - "posthoc": {"table": posthoc[0], "results": posthoc[1]} - if posthoc else None}, + "cross_check": check}, handle, indent=2, sort_keys=True) print("Report: %s" % target) diff --git a/tests/efficacy/score.py b/tests/efficacy/score.py index c637a4c..bada9d3 100644 --- a/tests/efficacy/score.py +++ b/tests/efficacy/score.py @@ -1650,11 +1650,11 @@ def security_checks(scratch): reading, and leaves a skipped trial's reading alone.""" target = os.path.join(scratch, "security-scores") os.makedirs(target) - for name in ("full-1", "none-1"): + for name in ("inline-1", "none-1"): with io.open(os.path.join(target, "%s.json" % name), "w", encoding="utf-8") as handle: handle.write("{}") - owed = security_owed(target, ["full-1", "hand-1", "none-1"], ["none-1"]) + owed = security_owed(target, ["inline-1", "hand-1", "none-1"], ["none-1"]) return [("a rescored trial is read again, a skipped one only if unread", owed == ["hand-1", "none-1"])]