@jesdi/skills 0.0.86 → 0.0.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/package.json +1 -1
  2. package/skills/implement-spec/ARCHITECTURE.md +33 -14
  3. package/skills/implement-spec/README.md +30 -15
  4. package/skills/implement-spec/SKILL.md +1 -1
  5. package/skills/implement-spec/driver.py +3 -2
  6. package/skills/implement-spec/driver_agents.py +93 -32
  7. package/skills/implement-spec/driver_decisions.py +3 -2
  8. package/skills/implement-spec/driver_dispute.py +82 -57
  9. package/skills/implement-spec/driver_fixloop.py +18 -21
  10. package/skills/implement-spec/driver_legacy.py +31 -2
  11. package/skills/implement-spec/driver_report.py +13 -3
  12. package/skills/implement-spec/driver_run.py +23 -13
  13. package/skills/implement-spec/driver_state.py +9 -8
  14. package/skills/implement-spec/driver_summary.py +8 -1
  15. package/skills/implement-spec/prompts/correction.md +1 -0
  16. package/skills/implement-spec/prompts/reviewer.md +3 -3
  17. package/skills/implement-spec/prompts/ruled.md +1 -1
  18. package/skills/implement-spec/tests/conftest.py +2 -0
  19. package/skills/implement-spec/tests/test_agents.py +56 -5
  20. package/skills/implement-spec/tests/test_arbitration.py +104 -11
  21. package/skills/implement-spec/tests/test_decisions.py +7 -5
  22. package/skills/implement-spec/tests/test_driver.py +2 -1
  23. package/skills/implement-spec/tests/test_fixloop.py +3 -3
  24. package/skills/implement-spec/tests/test_legacy.py +27 -0
  25. package/skills/implement-spec/tests/test_lenses.py +10 -5
  26. package/skills/implement-spec/tests/test_models.py +74 -0
  27. package/skills/implement-spec/tests/test_state.py +1 -1
  28. package/skills/implement-spec/tests/test_summary.py +8 -0
  29. package/skills/test-weigh-in/dashboard.html +70 -17
  30. package/skills/test-weigh-in/tests/browser_driver.py +46 -5
  31. package/skills/test-weigh-in/tests/layout_page.py +7 -3
  32. package/skills/test-weigh-in/tests/overlap_page.py +3 -0
  33. package/skills/test-weigh-in/tests/rules_fixture.py +1 -1
  34. package/skills/test-weigh-in/tests/test_coverage_run.py +5 -1
  35. package/skills/test-weigh-in/tests/test_dashboard_layout.py +50 -9
  36. package/skills/test-weigh-in/tests/test_score.py +53 -2
  37. package/skills/test-weigh-in/weigh.py +2 -2
  38. package/skills/test-weigh-in/weigh_coverage.py +22 -2
  39. package/skills/test-weigh-in/weigh_dashboard.py +51 -10
  40. package/skills/test-weigh-in/weigh_score.py +6 -3
  41. package/skills/test-weigh-in/weigh_smells.py +3 -2
  42. package/skills-manifest.json +3 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jesdi/skills",
3
- "version": "0.0.86",
3
+ "version": "0.0.88",
4
4
  "description": "jesdi's agent skills (content package consumed by @jesdi/skills-cli)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -13,7 +13,7 @@ A comment in the code is for a line that looks wrong or removable without it.
13
13
  | `driver.py` | The command line, the checks before the first agent, the walk of the ticket graph, one ticket from its phase to merged or blocked, the landing on the PR branch, the exit code |
14
14
  | `driver_run.py` | `Run` (what all ticket threads share), one agent with its one rerun, the gate call, the ledger, `Blocked` |
15
15
  | `driver_fixloop.py` | A gated ticket tip in, a reviewed tip out: review, test-writer correction, fix rounds |
16
- | `driver_dispute.py` | A disputed locked test: the arbitration, its correction, the once-per-file record, `spec-ambiguous` |
16
+ | `driver_dispute.py` | A disputed locked test: the arbitration, its correction, the once-per-test record, `spec-ambiguous` |
17
17
  | `driver_final.py` | The end of run: tidy, rebase, gate, final review, one fix batch, push |
18
18
  | `driver_tickets.py`, `driver_graph.py` | Ticket files in, tickets or errors out; which tickets can start now |
19
19
  | `driver_agents.py` | Model entries, the CLI command of each provider, prompt templates, the blocking launch |
@@ -142,8 +142,14 @@ and do not know about the run, except `driver_run.py`, which the deciding module
142
142
  - Fix rounds stop at 2, and round 2 goes to the next implementer entry.
143
143
  - A ticket review runs one agent, the reviewer. Its prompt carries the ticket's Risk line as one more criterion
144
144
  (`driver._risk`), so a risk that the diff does not handle is an unmet criterion under the usual round and cap rules.
145
- - A `--models` file may name only the roles of the skill's `models.json` (`driver_agents.load_models`): a removed
146
- role (`correctness`, `explorer`) or an unknown one stops the run before the preflight.
145
+ - `driver_agents.load_models` puts the provider config files (`config_files`: the home file, then the repo file
146
+ `.implement-spec/models.json`) and then the `--models` file on top of the skill's `models.json`, each replacing
147
+ whole role lists. Each may name only the roles of the skill's `models.json`: a removed role (`correctness`,
148
+ `explorer`) or an unknown one stops the run before the preflight, and the error names the file.
149
+ - `driver_agents.command` runs a `codex` agent with `--json`, and one of a role that commits with
150
+ `--sandbox danger-full-access`, since `workspace-write` keeps `.git` read-only. `driver_agents.cost` prices a
151
+ `codex` agent from the token usage of its log at `PRICES`; `driver_run._record_attempt` keeps the tokens in the
152
+ agent record.
147
153
  - The preflight asks every entry of every list on each invocation and returns the lists without the entries that
148
154
  failed. A role keeps going on what is left, so a provider out of credits stops no run; a role with no entry left
149
155
  exits 3. Round 2 stays on the only implementer entry left (`driver_fixloop.entry`), and the ledger says it
@@ -154,9 +160,10 @@ and do not know about the run, except `driver_run.py`, which the deciding module
154
160
  provider. Its lines are `prompts/lens-<source>.md`, with `prompts/lens-copy.md` as `{copy}`. The entry, the
155
161
  prompt values (`driver_final._lens_values`), the precondition errors and the source tags read it, and `TIMEOUTS` and
156
162
  `READ_ONLY` take its roles. `driver_agents.lens_entries` takes the entries from `final-reviewer`, and
157
- `correctness_entries` keeps a lens, its rerun too, on another provider than the first implementer entry;
158
- `load_models` refuses a list with none. When the preflight (`driver_agents.preflight`) leaves none, because each
159
- such entry failed it, the lens falls back to the `final-reviewer` entries that are left. The ledger says so, and the
163
+ `correctness_entries` keeps a lens, its rerun too, on another provider than the first implementer entry when the
164
+ lists have one: it is a preference, not a check. When the config has none, or the preflight
165
+ (`driver_agents.preflight`) leaves none because each such entry failed it, the lens falls back to the
166
+ `final-reviewer` entries that are left. The ledger says so, and the
160
167
  PR body's Review coverage (`driver_final._review_providers`) names the entries each review ran on, read from
161
168
  `run.agents`, so a fallback that a later invocation undid is not claimed. `driver_final._run_lenses` runs them at the same time in slot 1 inside one
162
169
  `Run.read_only`, so a lens that changes the slot makes all three run again. A lens that stops or is rejected
@@ -167,7 +174,7 @@ and do not know about the run, except `driver_run.py`, which the deciding module
167
174
  findings of the scoped review get the source `final-reviewer`; a findings file of an older driver, with no
168
175
  `source`, is read only by the scoped review agent. The lens reports go to
169
176
  `run.final.lenses` only once `Run.read_only` returns, so a report of a slot that a lens changed is never kept.
170
- - The scoped review after the fix batch is one `final-reviewer` agent on `other_provider_entries`, never the three
177
+ - The scoped review after the fix batch is one `final-reviewer` agent on `correctness_entries`, never the three
171
178
  lenses again. Each finding it leaves open asks one `final-ticket-blocked` question (`driver_final._settle_review`);
172
179
  only a `retry` runs another fix batch and scoped review, and `edit` keeps the end of run BLOCKED
173
180
  (`driver_final._parked`).
@@ -180,18 +187,30 @@ and do not know about the run, except `driver_run.py`, which the deciding module
180
187
  second correction could not close it.
181
188
  - Every test-writer correction, after a `test-wrong` ruling, a review finding or a `correct-test` answer, is one
182
189
  `driver_dispute.correct`: it runs the test-writer on the findings it is given, makes its commit the baseline,
183
- keeps the reading of each file it corrected in `corrected` (none after an answer) and logs one line per finding.
190
+ keeps the reading of each locked test it corrected in `corrected` (none after an answer) and logs one line per
191
+ finding.
184
192
  The callers differ only by the findings and the readings they pass.
185
193
  - No test-writer correction runs after round 2 (`driver_fixloop._act_on`): a red gate or an unmet criterion blocks
186
194
  the ticket. Other open findings go to the final must-fix list when the gate is green. A correction at the cap
187
195
  would add locked tests that no fix round could make green.
188
- - A locked file is arbitrated once and corrected once per ticket. The ticket record keeps them in `disputes` and
189
- `corrected`, keyed by the file (the part of a test id before `::`, resolved against the ticket's `locked` by
190
- `driver_report._locked_file`), so a renamed or parametrized test cannot dodge the rule. Only `driver_dispute._settle`
191
- and `driver_dispute.correct` write them; no answer does, so no answer resets them. A second dispute or a second
196
+ - A locked test is arbitrated once and corrected once per ticket. The ticket record keeps them in `disputes` and
197
+ `corrected`, by the `key` of each `driver_report.Dispute`, worked out once where it comes in. A dispute's key is
198
+ `driver_report.test_key`: `<locked file>::<test>`, the file resolved against the ticket's `locked` by
199
+ `driver_report._locked_file`, a parametrized case as its test. A review finding's key is
200
+ `driver_dispute.requested`: the test it names in `test`; the file for a `fixture` finding that names none; else
201
+ `<file>::+<title>`, a test to add. A per-file key made the operator rule on every second test of a file, and on
202
+ every missing test a review asked for, and answer `correct-test` each time. Only `driver_dispute._settle` and
203
+ `driver_dispute.correct` write them; no answer does, so no answer resets them. A second dispute or a second
192
204
  correction asks `spec-ambiguous` (`driver_dispute.ambiguous`); its evidence file is the findings file a
193
- `correct-test` correction reads (`driver_dispute.correct_as_answered`), and its files are the ones `keep-test` closes for later
194
- reviews (`driver_dispute.kept_files`, `driver_fixloop._still_to_correct`).
205
+ `correct-test` correction reads (`driver_dispute.correct_as_answered`), and its `key`s are the ones `keep-test`
206
+ closes for later reviews (`driver_dispute.kept`, `driver_fixloop._still_to_correct`).
207
+ - A renamed or added test has a new key, so the per-key rule alone does not bound the arbitrations and the review
208
+ corrections of a ticket, and a review correction does not advance the round. The ticket's `settled` counts them,
209
+ in the same `state.json` write as the record it counts (`_settle`'s `settle`, `correct`'s `settles`), so a resume
210
+ neither counts one twice nor drops one. `driver_dispute.admit` is the one gate before a settlement: a key already
211
+ in the record, or `settled` at `driver_dispute.SETTLEMENTS` (3), asks `spec-ambiguous`, so each further one costs
212
+ an answer. `driver_legacy._per_test` moves a schema 4 record, and the evidence of the ticket's questions, to the
213
+ new keys and seeds `settled`, so the live code knows one key shape.
195
214
  - `driver_run._attempts` treats a stop (BLOCKED or NEEDS_CONTEXT, not a dispute of a locked test) of any agent
196
215
  as a rejected attempt: the rerun runs on the next entry of the role's list (`_rerun_entry`; the ticket fixer's list
197
216
  is the implementer's), with the concerns or the driver's error in its prompt. A second stop or rejection asks a
@@ -16,12 +16,11 @@ Before any agent starts, the driver checks these. Each failed check prints one l
16
16
 
17
17
  - `.agent/` is gitignored and the worktree has no uncommitted change.
18
18
  - Each ticket file `NN-name.md` has a title, a **Blocked by** line and a **Seam** line, and the graph has no cycle (`driver_tickets.py`). A ticket needs one criterion or more, unless its Seam is `none — refactor`. A ticket needs a **Touches** line when the set has more than one ticket. The [to-tickets skill](../to-tickets/SKILL.md) has the line format.
19
- - The `--models` file names only roles of the skill's `models.json`. A `correctness` or `explorer` key is a role that was removed: the error says so, and that the key should be deleted from the file.
19
+ - Each provider config file (see Models) and the `--models` file name only roles of the skill's `models.json`. A `correctness` or `explorer` key is a role that was removed: the error says so, names the file, and says that the key should be deleted from it.
20
20
  - Each model entry is valid, and the CLI of the first entry of each role is on PATH.
21
- - The `final-reviewer` list has an entry on another provider than the first `implementer` entry: the correctness lens of the final review and the scoped review run on it. The error names the list and the implementer entry.
22
21
  - The `review-diff` skill is installed next to this one, with its `spec.md` and `correctness.md`, and the `deep-quality-review` skill is next to this one, in `${CLAUDE_CONFIG_DIR:-~/.claude}/skills` or in `~/.agents/skills`: the lenses of the final review follow them. One error per lens names its skill and its missing file.
23
22
  - With `--push`, `--unattended` or `--base`, the repository has an `origin` remote.
24
- - Each model entry of every list answers one short test prompt (the preflight), on each invocation. An entry that fails (a model the account cannot use or has no credits for, a CLI that is not signed in) is skipped for that invocation: each role that lists it goes on with its next entry, and one ledger sentence names the entry and the error. Only a role with no entry left stops the run, with one line naming each entry and its error. When no `final-reviewer` entry on another provider is left, the correctness lens and the scoped review run on the `final-reviewer` entries that are left, on the implementer's provider, and one more sentence says so. The driver prints these sentences and writes them to the ledger. The PR body's Review coverage names the entries that the ticket reviews, the correctness lens and the scoped review ran on, from the agents that ran, and flags an entry on a provider that also wrote code. `--dry-run` skips the preflight.
23
+ - Each model entry of every list answers one short test prompt (the preflight), on each invocation. An entry that fails (a model the account cannot use or has no credits for, a CLI that is not signed in) is skipped for that invocation: each role that lists it goes on with its next entry, and one ledger sentence names the entry and the error. Only a role with no entry left stops the run, with one line naming each entry and its error. When no `final-reviewer` entry on another provider than the first `implementer` entry is left, or the config has none, the correctness lens and the scoped review run on the `final-reviewer` entries that are left, on the implementer's provider, and one more sentence says so. The driver prints these sentences and writes them to the ledger. The PR body's Review coverage names the entries that the ticket reviews, the correctness lens and the scoped review ran on, from the agents that ran, and flags an entry on a provider that also wrote code. `--dry-run` skips the preflight.
25
24
 
26
25
  A run that stopped is continued with the same command. `state.json` is the only input of a resume.
27
26
 
@@ -37,7 +36,7 @@ A driver before this change named the ticket branches `ticket/<NN>` and the reco
37
36
  | `--fast-gate COMMAND` | Required. The fast gate: the ticket's locked tests, lint and types, as one shell line. The driver runs it on each candidate (the tip an implementer, a fixer or a test-writer correction made) before its review, with `IMPLEMENT_SPEC_BASE` set to the PR branch and `IMPLEMENT_SPEC_LOCKED` set to the space-separated locked file paths it checks: the ticket's locked files. Another ticket's locked files are not in a candidate's list. A green record is settled per tier and commit, whatever the list was: a commit is fast gated in one context. The implementer, the fixers and the final fixer run it on their own work: their prompts name this command and the same locked list, and for the final fixer the list is every merged ticket's locked files. No agent prompt names the `--gate` command. What it checks is the operator's choice. |
38
37
  | `--spec FILE` | Required without `--dry-run`. The spec file the prompts point at. Its first heading is the PR title. |
39
38
  | `--tickets DIR` | The directory of the ticket files. Default: `.agent/tickets`. |
40
- | `--models FILE` | A JSON file with one ordered list of `provider/model@effort` for each role. A role in this file replaces the list of that role in `models.json`. |
39
+ | `--models FILE` | A JSON file with one ordered list of `provider/model@effort` for each role. A role in this file replaces the list of that role in `models.json` and in the provider config files (see Models). |
41
40
  | `--parallel N` | The number of tickets in flight at once. Default: 2. |
42
41
  | `--prepare COMMAND` | A shell command that the driver runs once in each new slot 2..N, in `.agent/worktrees/slot-K/`. Use it to install or link the dependencies. |
43
42
  | `--timeout ROLE=MINUTES` | The timeout of one role. Repeatable. The rerun after a timeout gets twice the time. |
@@ -63,7 +62,7 @@ Default timeouts in minutes: test-writer 30, implementer 90, reviewer 45, fixer
63
62
  | 1 | A ticket is BLOCKED, or the end of run is BLOCKED. The other tickets ran as far as they could. |
64
63
  | 2 | Parked: a question of kind `spec-ambiguous` or `ticket-blocked` is open. Exit 2 wins over exit 1. |
65
64
  | 3 | Invalid input or a failed precondition: a usage error, a ticket error, a model error, an uncommitted change, a slot that cannot be made, another driver that runs on the same PR branch, an open question of a kind this driver no longer has (see "Resume"). No agent starts. The one exception: a review page that cannot be written gives exit 3 at the end of a run, after agents ran. |
66
- | 4 | Stopped: the CLI of an agent failed two times and wrote no report (for example, the account cannot use the model). The driver starts no other agent and lets the running agents end. No ticket is BLOCKED by it: fix the CLI or the model entry, then run the same command again to resume. |
65
+ | 4 | Stopped: the CLI of an agent failed and wrote no report (for example, the account cannot use the model, or its usage ran out). The agent gets no rerun on another entry: the driver starts no other agent and lets the running agents end. No ticket is BLOCKED by it: fix the CLI, or move the role to another entry in a provider config file (see Models), then run the same command again to resume. The preflight of that run skips an entry that still fails. |
67
66
  | 130 | The operator interrupted the run. The driver stops each agent. The work stays in the slots for the next run. |
68
67
 
69
68
  With `--unattended`, the `--stage-json` file holds `{"stage": "implement", "status": …}`:
@@ -115,7 +114,7 @@ Rules for each agent:
115
114
 
116
115
  - A call blocks until the agent ends. The driver does not poll.
117
116
  - An agent stops only the processes it started and their child processes, by PID, and never kills a process it did not start, nor uses `pkill`, `killall` or a `kill` by name or pattern: other slots and sessions share the machine. A process it did not start that blocks it goes into its concerns.
118
- - An agent gets one rerun: after a rejected report, after a timeout, or after it left the ticket branch. The rerun prompt is the first prompt plus the reason. A ticket agent (test-writer, implementer, reviewer, fixer, conflict) whose report is rejected, or that reports `BLOCKED` or `NEEDS_CONTEXT`, reruns on the next entry of its model list, wrapping to the first (a list of one entry reruns on that entry); the reason is the driver's error or the agent's concerns. An agent of the end of run (a lens, the scoped final-reviewer, the final fixer, the rebase conflict agent, the pr-writer) does the same; the correctness lens and the scoped review rerun only on `final-reviewer` entries on another provider than the first `implementer` entry. After a timeout or a moved branch, the rerun is on the same entry.
117
+ - An agent gets one rerun: after a rejected report, after a timeout, or after it left the ticket branch. A CLI that exits with an error and writes no report gets none: the run ends with exit 4. The rerun prompt is the first prompt plus the reason. A ticket agent (test-writer, implementer, reviewer, fixer, conflict) whose report is rejected, or that reports `BLOCKED` or `NEEDS_CONTEXT`, reruns on the next entry of its model list, wrapping to the first (a list of one entry reruns on that entry); the reason is the driver's error or the agent's concerns. An agent of the end of run (a lens, the scoped final-reviewer, the final fixer, the rebase conflict agent, the pr-writer) does the same; the correctness lens and the scoped review rerun only on `final-reviewer` entries on another provider than the first `implementer` entry, when the lists have one. After a timeout or a moved branch, the rerun is on the same entry.
119
118
  - A ticket agent whose rerun stops or is rejected too blocks the ticket with a `ticket-blocked` question; an agent of the end of run blocks the end of run with a `final-ticket-blocked-<n>` question. An implementer or a fixer that disputes a locked test (see Disputed locked tests) gets no rerun: the reviewer arbitrates. Nothing left to change is no stop: the implementer and the fixer report it as DONE with no commit.
120
119
  - A BLOCKED ticket stops the tickets that it blocks. All other tickets run on.
121
120
 
@@ -123,7 +122,7 @@ Rules for each agent:
123
122
 
124
123
  | Finding | What the driver does |
125
124
  |---|---|
126
- | kind `fixture`, any severity; kind `test`, `critical` or `important`, on a locked file of the ticket; or any kind, `critical` or `important`, on a locked file of another ticket | One test-writer correction, outside the fix rounds. The fixer may not edit a locked file, so a fix round cannot close a `test` finding there. Only a test-writer may change a locked file of another ticket, and it lists the file in `locked`: a ticket whose Touches line names such a file gets its change this way, where a fixer's change would be rejected (issue #116). The corrected files are the new locked versions, and the next review is a full review. A finding that the correction reports in `not_addressed` (it needs a production change first) becomes a finding of kind `code`, with the reason as its evidence, and goes to a fix round at once; the ledger says it was not corrected. A locked file is corrected at most once per ticket, by a review finding or after a `test-wrong` ruling: a finding that needs a second correction of it asks `spec-ambiguous`, with the finding as the second reading. A correction that is rejected twice asks `ticket-blocked`, whose `retry` reviews the tip again. No correction runs after round 2. |
125
+ | kind `fixture`, any severity; kind `test`, `critical` or `important`, on a locked file of the ticket; or any kind, `critical` or `important`, on a locked file of another ticket | One test-writer correction, outside the fix rounds. The fixer may not edit a locked file, so a fix round cannot close a `test` finding there. Only a test-writer may change a locked file of another ticket, and it lists the file in `locked`: a ticket whose Touches line names such a file gets its change this way, where a fixer's change would be rejected (issue #116). The corrected files are the new locked versions, and the next review is a full review. A finding that the correction reports in `not_addressed` (it needs a production change first) becomes a finding of kind `code`, with the reason as its evidence, and goes to a fix round at once; the ledger says it was not corrected. A finding names the locked test it corrects in `test` (`<locked file>::<test>`), or leaves `test` out when it asks for a test that is missing. The driver keys it by that test; a `fixture` finding that names no test by its file; a missing test by its file and title. Each key is corrected at most once per ticket, by a review finding or after a `test-wrong` ruling: a finding that needs a second correction of the same key asks `spec-ambiguous`, with the finding as the second reading. A finding on another test of a corrected file, or one that asks for another missing test, gets its correction with no question (see Disputed locked tests for the bound). A correction that is rejected twice asks `ticket-blocked`, whose `retry` reviews the tip again. No correction runs after round 2. |
127
126
  | `critical` or `important` | One fix round. |
128
127
  | `minor` | It stays in the ledger and in the findings file. Each lens of the final review gets the list. |
129
128
 
@@ -133,7 +132,9 @@ An implementer or a fixer that finds a locked test contradicting the spec or the
133
132
 
134
133
  The **arbitration** is the reviewer on its entry with `prompts/arbitration.md`: the ticket, the spec, the disputed tests and the dispute report. It is read-only, counts as a `reviewer` agent in `summary.md`, and is not a fix round. Its report `arbitration-<n>.json` gives per disputed test the `requirement` it checks, a `ruling` and a `reason`. On `test-wrong`, one test-writer correction (`correction-<n>.json`) runs with the ruling as a finding of kind `ruling` (`ruled-<n>.json`), then the role that disputed runs again on the corrected tests: the implementer, or the fixer of the same round. On `code-wrong`, that role runs again with the ruling in its prompt (`prompts/ruled.md`) and makes the test green. The review after a correction is a full review.
135
134
 
136
- A locked file is arbitrated once and corrected once per ticket, keyed by the file, so a renamed or parametrized test of a ruled file is the same test. `state.json` keeps the ruling in the ticket's `disputes` and the correction in its `corrected`; no answer changes them. A second dispute on a ruled file, or a `test-wrong` ruling on a file corrected before, asks one `spec-ambiguous` question naming the test, the requirement and the two readings.
135
+ A locked test is arbitrated once and corrected once per ticket, keyed by `<locked file>::<test>`, so a parametrized case (`test_x[a]`) is its test and another test of a ruled or corrected file is a first dispute or a first correction. `state.json` keeps the ruling in the ticket's `disputes` and the correction in its `corrected`; no answer changes them. A second dispute on a ruled test, or a `test-wrong` ruling or a review finding on a test corrected before, asks one `spec-ambiguous` question naming the test, the requirement and the two readings.
136
+
137
+ A renamed test, or a test a correction added, has a new key, so a count bounds the rest: the ticket's `settled` counts its arbitrations and its review corrections (a `test-wrong` ruling and its correction count once), in the same write of `state.json` as their record. Once it is 3, the next dispute or review correction asks `spec-ambiguous` instead, with the count as the first reading. A correction after a `correct-test` answer does not count.
137
138
 
138
139
  A fix round has three steps: the **fixer** (`prompts/fixer.md`) makes the fast gate green on its final commit, as the implementer does; the driver runs the fast gate on the new tip; a re-review reads the range of the fix. A fixer whose findings need no change, for example because a test-writer correction before it already resolved them, makes no commit and gives in `concerns` a reason for each finding; the round still counts, and the re-review of the same tip checks each reason.
139
140
 
@@ -150,8 +151,8 @@ The end of run starts only when every ticket is merged and every slot is idle. I
150
151
 
151
152
  1. **Tidy.** The driver saves the PR tip in `refs/implement-spec/<key>/recovery`. It then makes one commit for each ticket, in merge order, named `feat(NN): <title>`. Each commit holds the tests, the implementation and the fixes of its ticket. The tree of the new tip must equal the tree of the old tip, or the branch stays as it was.
152
153
  2. **Rebase** onto the fetched tip of the `--base` branch, or without it of the default branch of `origin`. A conflict goes to the conflict agent (`prompts/rebase-conflict.md`) once, and the rebased tip gets the full gate. When the agent leaves the rebase open with no conflict, the driver goes on with it, then checks the rebased tip, in place of the commits the report names: a report whose rebased tip changes a locked file of any ticket from the recovery point is rejected, and the rerun fixes that tip with `git commit --amend`. When git cannot go on at the stop the agent resolved (a resolved file it did not stage), the report is rejected with git's error and the agent reruns. A second conflict leaves the branch at its recovery point.
153
- 3. **Full gate**, then the **final review**: three agents at the same time in slot 1, one for each lens of the `review-diff` method, on the whole range, each with the one lens prompt `prompts/final-lens.md` and its own method lines in it. `final-spec` follows review-diff's `spec.md` with the run's spec; `final-correctness` has review-diff's `correctness.md` inlined, reads files from git at the reviewed tip and runs no tests; `final-structure` follows the `deep-quality-review` skill. `final-spec` and `final-structure` run on the first `final-reviewer` entry, `final-correctness` on the first `final-reviewer` entry on another provider than the first `implementer` entry. Each reads the driver's full gate record of the reviewed tip as its gate evidence and runs no gate. Each gets ticket observations, minor findings, the must-fix list and the rulings of the operator, writes its own report and never sees another's. The driver merges their findings into one `findings-0.json`: each finding has a `source` (`spec`, `correctness` or `structure`), and two findings with the same file, line and title are one, the more severe one, or on a tie the earlier one in the order spec, correctness, structure. The ledger line of each finding names its source. A lens that stops or is rejected runs once more on the next entry; when the rerun stops or is rejected too, the round stops once the other lenses have ended, no fix batch runs, and the end of run asks `final-ticket-blocked-<n>`. The driver keeps each accepted lens report with the tip it covers (`run.final.lenses`): the next review of that tip runs only the lenses with no kept report, and a review of another tip runs all three. A lens that changes the slot makes all three run again.
154
- 4. **Fix batch.** Critical and important findings, including every must-fix item, go to one fixer (`prompts/final-fixer.md`), which makes the fast gate green on its final commit, with every merged ticket's locked files in `IMPLEMENT_SPEC_LOCKED`. A report whose commits change a locked file of any ticket from the tidied tip is rejected naming the file, so the fixer runs once more on its next `fixer` entry. The driver names each of its commits `fix(NN): …` from the ticket in the report. Then the full gate, then one scoped review of those commits: the **final-reviewer** (`prompts/final-reviewer.md`), one agent on the entry of `final-correctness`, so on another provider than the first `implementer` entry. It reads the merged findings, checks that each critical and important one is fixed and that the fix commits break nothing else, and lists each must-fix item it verified in `resolved_must_fix`; a must-fix item it leaves out stays open. The driver runs no fast gate at the end of the run.
154
+ 3. **Full gate**, then the **final review**: three agents at the same time in slot 1, one for each lens of the `review-diff` method, on the whole range, each with the one lens prompt `prompts/final-lens.md` and its own method lines in it. `final-spec` follows review-diff's `spec.md` with the run's spec; `final-correctness` has review-diff's `correctness.md` inlined, reads files from git at the reviewed tip and runs no tests; `final-structure` follows the `deep-quality-review` skill. `final-spec` and `final-structure` run on the first `final-reviewer` entry, `final-correctness` on the first `final-reviewer` entry on another provider than the first `implementer` entry, or on the first `final-reviewer` entry when there is none. Each reads the driver's full gate record of the reviewed tip as its gate evidence and runs no gate. Each gets ticket observations, minor findings, the must-fix list and the rulings of the operator, writes its own report and never sees another's. The driver merges their findings into one `findings-0.json`: each finding has a `source` (`spec`, `correctness` or `structure`), and two findings with the same file, line and title are one, the more severe one, or on a tie the earlier one in the order spec, correctness, structure. The ledger line of each finding names its source. A lens that stops or is rejected runs once more on the next entry; when the rerun stops or is rejected too, the round stops once the other lenses have ended, no fix batch runs, and the end of run asks `final-ticket-blocked-<n>`. The driver keeps each accepted lens report with the tip it covers (`run.final.lenses`): the next review of that tip runs only the lenses with no kept report, and a review of another tip runs all three. A lens that changes the slot makes all three run again.
155
+ 4. **Fix batch.** Critical and important findings, including every must-fix item, go to one fixer (`prompts/final-fixer.md`), which makes the fast gate green on its final commit, with every merged ticket's locked files in `IMPLEMENT_SPEC_LOCKED`. A report whose commits change a locked file of any ticket from the tidied tip is rejected naming the file, so the fixer runs once more on its next `fixer` entry. The driver names each of its commits `fix(NN): …` from the ticket in the report. Then the full gate, then one scoped review of those commits: the **final-reviewer** (`prompts/final-reviewer.md`), one agent on the entry of `final-correctness`, so on another provider than the first `implementer` entry when the lists have one. It reads the merged findings, checks that each critical and important one is fixed and that the fix commits break nothing else, and lists each must-fix item it verified in `resolved_must_fix`; a must-fix item it leaves out stays open. The driver runs no fast gate at the end of the run.
155
156
  5. Each critical or important finding the scoped review leaves open, a must-fix item too, asks one `final-ticket-blocked-<n>` question, and nothing is pushed while one is open. `retry` runs one more fix batch and one more scoped review on the open findings; `edit` keeps the end of run BLOCKED. There is no third review unless the operator answers `retry`.
156
157
  6. **Push.** With `--push` or `--unattended`, the driver pushes the reviewed tip once, with no force, and opens the PR into the branch of step 2 with `gh`, ready for review. The **pr-writer** (`prompts/pr-writer.md`) writes the body with the method of the `pr` skill; the driver puts the facts of the run after it: the ticket-to-commit map, the fix commits, the rulings and the review coverage (`prompts/pr-body.md`). The body carries the merge-risk block of the `pr-risk` skill under `## Merge Danger`, above the facts; the driver validates it, runs the pr-writer once more with the errors when it is invalid, and blocks the run, opening no PR, when the second body is invalid too. A push stops before any agent when no `pr` skill or no `pr-risk` skill is next to this skill, in `${CLAUDE_CONFIG_DIR:-~/.claude}/skills` or in `~/.agents/skills`. Without them it prints the two tips and the command to run again with `--push`.
157
158
 
@@ -170,6 +171,7 @@ A repository with no `origin` remote skips only step 2 and step 6. The tidied co
170
171
  - A ticket whose recorded tip is not on its branch goes back to `implement`, from the test-writer commit. A merged ticket whose tip is not in the PR branch does the same.
171
172
  - A red full gate at landing moves the ticket to `fix`, advances its round and records the red commit in `landing`, in one write of `state.json`. A resumed run starts that round's fixer and does not gate the red commit again; the fixer's report clears `landing`.
172
173
  - A `state.json` before `schema` 4 can hold questions of kinds this driver no longer has (`finding`, `locked-test`, `locked-test-again`, `review-stopped`, `review-rejected`, `implementer-stopped`, `fixer-stopped`, `merged-locked-file`, `final-finding`). An open one ends the run with exit 3 before any agent, naming each such question: answer it with the driver version that asked it, or start the run again. An answered one keeps the ruling sentence the older driver wrote, in the ledger and in the PR body (`driver_legacy.py` keeps those sentences; only a kind or an answer it does not know gets `Ruling: <NN> <kind> (<answer>): <subject>.`). Every answered question keeps its ruling sentence in `state.json`.
174
+ - A `state.json` before `schema` 5 keys `disputes` and `corrected` by the locked file. The resume moves each record to the test it names; a review correction that named only its file stays under the file, the key of a `fixture` finding that names no test. Each finding in the evidence of the ticket's `spec-ambiguous` questions gets the key of its file's record, so a `keep-test` answered before now keeps that test, not the whole file. `settled` starts at one per record that is not the correction of a ruling: an arbitration of two files counts two, so the cap comes no later than it would.
173
175
  - A run of an older driver that stopped after its first final review round goes on to its fix batch and the scoped review with its `findings-0.json`, whose findings have no `source`; the findings of the scoped review have the source `final-reviewer`. A run that stopped inside that round runs the three lenses.
174
176
  - A slot with the uncommitted work of an interrupted role stays as it is. The role runs there again and is told so.
175
177
 
@@ -177,13 +179,26 @@ A repository with no `origin` remote skips only step 2 and step 6. The tidied co
177
179
 
178
180
  `models.json` holds the default list for each role. An entry is `provider/model@effort`; an entry with no provider is `anthropic`.
179
181
 
182
+ Two provider config files, in the same shape, change the lists without a flag, so the operator can move any role to another provider, for example when a subscription's usage runs out. The lists apply in this order, and each one replaces the whole list of each role it names:
183
+
184
+ 1. the skill's `models.json`;
185
+ 2. the home file `${XDG_CONFIG_HOME:-~/.config}/implement-spec/models.json`, for the operator's subscriptions on every repository;
186
+ 3. the repo file `.implement-spec/models.json` at the root of the PR worktree, committed, for a repository that pins a model;
187
+ 4. the `--models` file of the invocation.
188
+
189
+ A file that does not exist is skipped. An error in one of them names the file, and the run ends with exit 3 before the preflight.
190
+
180
191
  | Provider | CLI | Efforts |
181
192
  |---|---|---|
182
193
  | `anthropic` | `claude -p` | low, medium, high, xhigh, max |
183
- | `openai` | `codex exec` | minimal, low, medium, high, xhigh |
194
+ | `openai` | `codex exec --json` | minimal, low, medium, high, xhigh |
184
195
 
185
196
  The driver uses the first entry of a role; the rerun of an agent that stopped or was rejected uses the next entry (round 2's fixer wraps to the first `implementer` entry). The fixer of a ticket runs on the `implementer` list; the `fixer` list is only for the fix batch of the final review. Round 2 uses the second implementer entry, which the model list must supply. The three lenses of the final review have no list of their own: they run on `final-reviewer` entries, and a `--models` file that names a lens is refused as an unknown role.
186
197
 
198
+ A `codex` agent of a role that commits (test-writer, implementer, fixer, conflict) runs with `--sandbox danger-full-access`: `workspace-write` keeps `.git` read-only, even with the git directory as an `--add-dir` or a `sandbox_workspace_write.writable_roots` entry (Codex 0.166.0), so `git commit` fails there. A read-only role runs with `--sandbox read-only`. So any role can run on either provider. Another provider than the first `implementer` entry for the correctness lens and the scoped review is a preference: a config whose `final-reviewer` list has no such entry runs, with one ledger sentence, and the PR body's Review coverage flags each review on a provider that also wrote code.
199
+
200
+ Cost: a `claude` agent's cost is the `total_cost_usd` its CLI reports. A `codex` agent's log holds its token usage per turn, and the driver prices the summed tokens at the list price of its model (`driver_agents.PRICES`, USD per million input, cached input and output tokens). Each agent record in `state.json` keeps its `tokens`, so a run can be priced again. An agent with no price (a `codex` model that is not in `PRICES`, or a `claude` CLI that reported no cost) has `cost` null: the summary's cost leaves it out and its `agents not priced` row counts it, and the ledger line of a `codex` one gives its tokens and says that it is not priced.
201
+
187
202
  The defaults need both `claude` and `codex` on PATH. The `openai` defaults name the full Codex model names (`gpt-6-astra`, `gpt-6.1-sol`), because a Codex CLI that is signed in with a ChatGPT account does not accept the short aliases. Read "Known limits" before you use them as they are.
188
203
 
189
204
  ## Report schema per role
@@ -196,7 +211,7 @@ Every report has `status` (`DONE`, `DONE_WITH_CONCERNS`, `NEEDS_CONTEXT`, `BLOCK
196
211
  |---|---|---|---|
197
212
  | test-writer | `prompts/test-writer.md` | `locked` (test file paths), `red` (`test`, `line`) | The driver reads a test node id `<file>::<test>` in `locked` as its file. With DONE: one commit, one locked file and one red line or more. A correction's test can be green on the implementer's code, so its red line comes from a production edit that the correction makes and reverts. No locked path contains whitespace, since `IMPLEMENT_SPEC_LOCKED` separates the paths by spaces. Each locked path is in a commit that the role made and is a file at the tip: a correction that deletes a locked file leaves it out of `locked`. Each `line` is in the log. A locked file of another ticket whose test-writer has run, merged or not, that the role changed is in `locked`. A correction changes only the files that it lists in `locked`. Each `not_addressed[].finding` is the title of a finding of the correction (the driver logs its reason); a DONE correction with each of its findings there needs no commit. |
198
213
  | implementer | `prompts/implementer.md` | `green` | With DONE and no commit: no new commit on the branch, no uncommitted change, and a concern that says why the start needs no change. The driver then gates and reviews the start commit. With BLOCKED, a dispute names a locked file of the ticket and leaves no uncommitted change (also for the fixer). |
199
- | reviewer | `prompts/reviewer.md` | `findings` (`severity`, `file`, `line`, `title`, `evidence`, `kind`) | None. |
214
+ | reviewer | `prompts/reviewer.md` | `findings` (`severity`, `file`, `line`, `title`, `evidence`, `kind`, and `test` for a `fixture` or `test` finding on a locked test that exists) | None. |
200
215
  | reviewer, arbitrating | `prompts/arbitration.md` | `rulings` (`test`, `requirement`, `ruling`: `test-wrong` or `code-wrong`, `reason`) | One ruling for each disputed test, its id as the dispute gives it. |
201
216
  | fixer | `prompts/fixer.md` | `green`, `ticket` | With DONE and no commit: no new commit on the branch, no uncommitted change, a gate that is green on the start, and a concern that names each finding of the round. |
202
217
  | final-spec, final-correctness, final-structure | `prompts/final-lens.md`, with the lines of `prompts/lens-<source>.md` | `findings` | None. |
@@ -213,7 +228,7 @@ A question is a bounded choice for the operator. `driver_decisions.py` `KINDS` h
213
228
 
214
229
  | Kind | Question id | Asked when | Run exit | Options |
215
230
  |---|---|---|---|---|
216
- | `spec-ambiguous` | `<NN>-spec-ambiguous-<n>` | A second dispute on a locked file that the reviewer ruled on in the ticket, or a second correction needed for a locked file of the ticket (a `test-wrong` ruling or a review finding on a file corrected before). The subject names the test, the requirement and the two readings; the evidence is `spec-ambiguous-<n>.json`. | 2 | No option is recommended. `keep-test`: the role that disputed runs again against the test; after a review finding, the ticket resumes from the review and findings on that file are closed. `correct-test`: one more correction, to the second reading, then the role that disputed runs again (the fixer of the same round after the review of its round); after a review finding, the review runs again. `edit-spec`: the ticket stays BLOCKED, with the ruling in the ledger. None of them changes the ticket's `disputes` or `corrected`. |
231
+ | `spec-ambiguous` | `<NN>-spec-ambiguous-<n>` | A second dispute on a locked test that the reviewer ruled on in the ticket, or a second correction needed for a locked test of the ticket (a `test-wrong` ruling or a review finding on a test corrected before); or a dispute or a review correction after the ticket's locked tests were settled 3 times. Another test of the same file, or another missing test that a review finding asks for, is no second correction. The subject names the test, the requirement and the two readings; the evidence is `spec-ambiguous-<n>.json`. | 2 | No option is recommended. `keep-test`: the role that disputed runs again against the test; after a review finding, the ticket resumes from the review and later findings with the same key are closed: on that test, a `fixture` finding on that file that names no test, or the same missing test. `correct-test`: one more correction, to the second reading, then the role that disputed runs again (the fixer of the same round after the review of its round); after a review finding, the review runs again. `edit-spec`: the ticket stays BLOCKED, with the ruling in the ledger. None of them changes the ticket's `disputes` or `corrected`. |
217
232
  | `ticket-blocked` | `<NN>-ticket-blocked-<n>`, `final-ticket-blocked-<n>` | A ticket agent (test-writer, implementer, reviewer, fixer, conflict) or an agent of the end of run stopped with `BLOCKED` or `NEEDS_CONTEXT` or was rejected, and its rerun on the next entry of its list did too; or a finding is open after the scoped review of the final fix batch (one question per finding). The subject names the role and the reason, or the finding. | 2 | `retry` (recommended): the role runs again on its first entry from the tip the ticket left, with its one rerun; for a fixer, the round that stopped does not count: the driver gates and reviews the tip, and a fixer runs that round again on the review's findings. An arbitration or a correction runs for another role, so its work is not kept: after a dispute, the role that disputed runs again from the tip before them; after a review correction, the driver reviews that tip again. For the end of run, the stopped agent runs again from where the end of run is; for an open finding, one more fix batch and scoped review run. `edit`: the ticket, or the end of run, stays BLOCKED, with the ruling in the ledger, so the spec or the ticket can be edited. |
218
233
 
219
234
  `final-finding` (fix or accept a finding open after the second round of the final review) became a `ticket-blocked` question of the end of run, id `final-ticket-blocked-<n>`: whether one more batch runs is the operator's call, and nothing ships with an open finding, so there is no `accept`.
@@ -229,10 +244,10 @@ Answer with `--answer <question id>=<option id>` on the next run, or through the
229
244
  | Demonstrated red plus green for locked tests | `driver_report.py` `_red_errors`: each red line of a test-writer report (and of a correction) must be in its log. `driver_gate.py` `run`, called from `driver_run.py` `Run.gate` and `driver_fixloop.py` `_gate`: the fast gate gets the ticket's locked files in `IMPLEMENT_SPEC_LOCKED` and must be green on the candidate before its review. |
230
245
  | Locked files changed only by the test-writer | `driver_locked.py` `errors`, one diff check after the implementer, a fixer, the ticket conflict agent, the final fixer and the rebase conflict agent report (the baseline from `for_ticket`, or at the end of run `for_end_of_run`): the ticket's own locked files against its last test-writer commit, every other ticket's against the merge base of the branch and the PR tip, at the end of run every ticket's against the tidied tip (for the rebase conflict agent, the recovery point). A changed file rejects the report. `driver.py` `_refuse_breach` (with `driver_locked.py` `landing_errors`), under the merge lock: the commit that would land against every other ticket's locked files as the PR tip has it; a changed file blocks the ticket with one `ticket-blocked` question. `driver_locked.py` `_unlisted_errors`: a test-writer that changes another ticket's locked file must list it in `locked`, and the reviewer gets its diff (`prompts/elsewhere.md`) to judge against the spec. |
231
246
  | The full gate at landing and at the end of run | `driver.py` `_checked_landing`: the full gate runs on the commit that would land, a fast-forward as well as a merge commit, before the PR branch moves to it. `driver_final.py` `_review_until_reviewed` runs it after the tidy and after each fix batch. |
232
- | The ticket reviewer and the final correctness lens (and the scoped review) on another provider than the implementer | `models.json`: the `reviewer` list starts on another provider than the `implementer` list, which a `--models` file can change. `driver_agents.py` `other_provider_entries`: the correctness lens and the scoped review run and rerun only on `final-reviewer` entries of another provider than the first `implementer` entry; `load_models` refuses a list with no such entry before any agent. When the preflight finds no such entry usable (a provider out of credits), `correctness_entries` falls back to the `final-reviewer` entries that are left, and the ledger says so. When the reviewer's other-provider entry is skipped, its next entry may share the implementer's provider. The PR body's Review coverage names the entries each review ran on and flags one on a provider that also wrote code. |
247
+ | The ticket reviewer and the final correctness lens (and the scoped review) on another provider than the implementer | `models.json`: the `reviewer` list starts on another provider than the `implementer` list, which a `--models` file can change. `driver_agents.py` `other_provider_entries`: the correctness lens and the scoped review run and rerun on `final-reviewer` entries of another provider than the first `implementer` entry, when the lists have one. When the config has none, or the preflight finds none usable (a provider out of credits), `correctness_entries` falls back to the `final-reviewer` entries that are left, and the ledger says so. When the reviewer's other-provider entry is skipped, its next entry may share the implementer's provider. The PR body's Review coverage names the entries each review ran on and flags one on a provider that also wrote code. |
233
248
 
234
249
  ## Known limits
235
250
 
236
- - **A `codex` agent cannot commit.** A role that commits (test-writer, implementer, fixer, conflict) on an `openai` entry runs with `--sandbox workspace-write`, and that sandbox cannot run `git commit`. If a custom `--models` file assigns such an entry to a committing role, replace it with an entry whose CLI can commit in the ticket worktree.
251
+ - **A `codex` agent that commits has full access.** `--sandbox danger-full-access` lets it write outside its slot, as a `claude` agent can. The driver's checks after each role (the locked files, the branch, the slot and the git config of a read-only role, the signatures before a push) see the slot and the repository, not the rest of the disk.
237
252
  - **A ticket that is not merged stops the end of run.** While one ticket is BLOCKED, there is no tidy and no final review of the merged tickets.
238
253
  - **A published PR branch keeps its history.** See "End of run".
@@ -15,7 +15,7 @@ locked acceptance tests at the ticket's Seam; a review before each merge by one
15
15
  reviewer, with the ticket's Risk line as one more criterion; at most 2 fix rounds
16
16
  with escalation at round 2; one gate record per trusted commit, run by the driver;
17
17
  tickets that touch the same function run in sequence; a gate on each merge commit; one commit per ticket before the
18
- final review; a final review by the three lenses of review-diff, with correctness on another provider; no push and no PR until every ticket is merged and the final review
18
+ final review; a final review by the three lenses of review-diff, with correctness on another provider when the config has one; no push and no PR until every ticket is merged and the final review
19
19
  has passed. The review rounds adapt superpowers' subagent-driven-development
20
20
  (obra/superpowers, MIT).
21
21
  -->
@@ -475,8 +475,9 @@ def _halted_exit(halted: list[str], final: dict) -> int:
475
475
  """Exit 4 after a CLI failure: no ticket is BLOCKED by it, and the same command resumes the run."""
476
476
  for why in halted:
477
477
  print(f"implement-spec: the run stopped: {why}")
478
- print("implement-spec: fix the CLI or the model entry (--models FILE), then run the same command again to "
479
- "resume; no ticket is BLOCKED by this.")
478
+ print("implement-spec: fix the CLI, or move the role to another model entry in a provider config file (the "
479
+ "home or the repo models.json, or --models FILE), then run the same command again to resume; no ticket is "
480
+ "BLOCKED by this.")
480
481
  if error := _publish_questions(final["run"]):
481
482
  print(error)
482
483
  return 4
@@ -43,6 +43,12 @@ TIMEOUTS = {"test-writer": 30, "implementer": 90, "reviewer": 45, "fixer": 60, "
43
43
  **dict.fromkeys(LENSES, 60), "conflict": 30, "pr-writer": 20}
44
44
  PROVIDERS = {"anthropic": ("claude", ("low", "medium", "high", "xhigh", "max")),
45
45
  "openai": ("codex", ("minimal", "low", "medium", "high", "xhigh"))}
46
+ # USD per million tokens at the API list price; the cached part of the input costs `cached_input`. A
47
+ # codex model that is not here keeps its tokens, and the ledger says it is not priced. Update when a price changes.
48
+ PRICES = {"gpt-6-astra": {"input": 10.0, "cached_input": 1.0, "output": 50.0},
49
+ "gpt-6.1-sol": {"input": 2.0, "cached_input": 0.10, "output": 10.0}}
50
+ # The name of each token count in the agent record, and its key in the `usage` of a codex turn.
51
+ _USAGE = {"input": "input_tokens", "cached_input": "cached_input_tokens", "output": "output_tokens"}
46
52
  READ_ONLY = ("reviewer", "final-reviewer", *LENSES, "pr-writer")
47
53
  PREFLIGHT = "implement-spec preflight: reply with the word OK. Read no file and run no command.\n"
48
54
  # The time limit of one preflight call: a CLI that gives no answer in this time fails the preflight.
@@ -75,28 +81,59 @@ def _entry_error(role: str, entry: str, first: bool) -> str | None:
75
81
  REMOVED = ("correctness", "explorer")
76
82
 
77
83
 
78
- def _role_errors(given: dict, known: dict) -> list[str]:
79
- """One error per role of the --models file that the skill's models.json does not define."""
80
- return [f"{role}: the role was removed; delete its key from the --models file" if role in REMOVED else
81
- f"{role}: unknown role (known: {', '.join(known)})" for role in given if role not in known]
84
+ def _role_errors(given: dict, known: dict, label: str) -> list[str]:
85
+ """One error per role of the config file `label` that the skill's models.json does not define."""
86
+ return [f"{role}: the role was removed; delete its key from {label}" if role in REMOVED else
87
+ f"{role}: unknown role (known: {', '.join(known)}); delete its key from {label}"
88
+ for role in given if role not in known]
89
+
90
+
91
+ # The provider config files, in the order they apply; the --models file applies after them. The repo file is read
92
+ # from the worktree the driver runs in.
93
+ REPO_CONFIG = Path(".implement-spec/models.json")
94
+
95
+
96
+ def config_files() -> list[Path]:
97
+ """The provider config files that exist: the home file, then the repo file, which wins."""
98
+ home = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "implement-spec/models.json"
99
+ return [path for path in (home, REPO_CONFIG) if path.is_file()]
82
100
 
83
101
 
84
102
  def load_models(path: str | None) -> tuple[dict[str, list[str]], list[str]]:
85
- """The skill's default lists with the roles of `path` on top, and every role and entry error."""
86
- defaults = json.loads((SKILL / "models.json").read_text())
103
+ """The skill's default lists, then the roles of each config file and of the --models file `path` on top, each
104
+ replacing whole lists, and every role and entry error."""
105
+ models = json.loads((SKILL / "models.json").read_text())
106
+ # (the file, how a role error names it, the prefix of its other errors)
107
+ layers = [(file, str(file), str(file)) for file in config_files()]
108
+ layers += [(Path(path), "the --models file", f"--models {path}")] if path else []
109
+ errors = [error for layer in layers for error in _layer(models, *layer)]
110
+ return ({}, errors) if errors else (models, _entry_errors(models))
111
+
112
+
113
+ def _layer(models: dict[str, list[str]], file: Path, label: str, prefix: str) -> list[str]:
114
+ """Put the roles of one config file on top of `models`; its errors, or []."""
87
115
  try:
88
- given = json.loads(Path(path).read_text()) if path else {}
89
- models = {**defaults, **given} # a list is a TypeError
90
- if unknown := _role_errors(given, defaults):
91
- return {}, unknown
92
- return models, _entry_errors(models)
93
- except (OSError, ValueError, AttributeError, LookupError, TypeError) as exc:
94
- return {}, [f"--models {path}: {exc!r}"]
116
+ given = json.loads(file.read_text())
117
+ except (OSError, ValueError) as exc:
118
+ return [f"{prefix}: {exc!r}"]
119
+ if not isinstance(given, dict):
120
+ return [f"{prefix}: a JSON object of role names is required"]
121
+ if unknown := _role_errors(given, models, label):
122
+ return unknown
123
+ if wrong := [role for role, entries in given.items() if not _is_list(entries)]:
124
+ return [f"{prefix}: {', '.join(wrong)}: a role needs a non-empty list of model entries"]
125
+ models.update(given)
126
+ return []
127
+
128
+
129
+ def _is_list(entries: object) -> bool:
130
+ """True for a non-empty list of strings: the shape of one role's model entries."""
131
+ return isinstance(entries, list) and bool(entries) and all(isinstance(entry, str) for entry in entries)
95
132
 
96
133
 
97
134
  def other_provider_entries(models: dict[str, list[str]]) -> list[str]:
98
135
  """The entries of the `final-reviewer` list on another provider than the implementer's first entry: the correctness
99
- lens and the scoped review run and rerun only on these."""
136
+ lens and the scoped review run and rerun on these when there is one."""
100
137
  own = split(models["implementer"][0])[0]
101
138
  return [entry for entry in models["final-reviewer"] if split(entry)[0] != own]
102
139
 
@@ -107,8 +144,8 @@ def other_provider_entry(models: dict[str, list[str]]) -> str:
107
144
 
108
145
 
109
146
  def correctness_entries(models: dict[str, list[str]]) -> list[str]:
110
- """The entries of the correctness lens and the scoped review: the other-provider ones, or, when none passed the
111
- preflight, the whole `final-reviewer` list, so a provider out of credits stops no run (the PR body says so)."""
147
+ """The entries of the correctness lens and the scoped review: the other-provider ones, or, when the config has none
148
+ or none passed the preflight, the whole `final-reviewer` list (the ledger and the PR body say so)."""
112
149
  return other_provider_entries(models) or models["final-reviewer"]
113
150
 
114
151
 
@@ -119,17 +156,12 @@ def lens_entries(models: dict[str, list[str]], role: str) -> list[str]:
119
156
 
120
157
  def _entry_errors(models: dict[str, list[str]]) -> list[str]:
121
158
  """Every entry error of the merged lists."""
122
- # The entries whose CLI must be on PATH; entries[0]: an empty list is an error.
159
+ # The entries whose CLI must be on PATH; `_layer` gave each role a non-empty list.
123
160
  first = {(role, entries[0]) for role, entries in models.items()} | {
124
161
  ("final-reviewer", other_provider_entry(models))}
125
162
  found = [_entry_error(role, entry, (role, entry) in first) for role, entries in models.items() for entry in entries]
126
163
  if len(models["implementer"]) < 2:
127
164
  found.append("implementer: a second implementer model entry is required for fix round 2")
128
- if not other_provider_entry(models):
129
- found.append(f"final-reviewer: no entry of its list ({', '.join(models['final-reviewer'])}) is on another "
130
- f"provider than the implementer's first entry {models['implementer'][0]}; its other-provider "
131
- "entry serves the correctness lens of the final review and the scoped review, which never run on "
132
- "the implementer's provider")
133
165
  return [error for error in found if error]
134
166
 
135
167
 
@@ -176,20 +208,26 @@ def _skipped(models: dict[str, list[str]], kept: dict[str, list[str]], failed: d
176
208
  skipped = [f"Model entry {entry} is skipped for this invocation: {why.rstrip('.')}; each role that lists it "
177
209
  f"goes on with its next entry ({', '.join(role for role in models if entry in models[role])})."
178
210
  for entry, why in failed.items()]
179
- if other_provider_entry(models) and not other_provider_entry(kept):
180
- skipped.append(f"No final-reviewer entry on another provider than {kept['implementer'][0]} passed the "
181
- f"preflight: the correctness lens and the scoped review run on "
211
+ if not other_provider_entry(kept):
212
+ # Another provider for correctness is a preference: a config with none runs, and says so.
213
+ other = f"on another provider than {kept['implementer'][0]}"
214
+ why = f"{other} passed the preflight" if other_provider_entry(models) else f"is {other}"
215
+ skipped.append(f"No final-reviewer entry {why}: the correctness lens and the scoped review run on "
182
216
  f"{', '.join(kept['final-reviewer'])}, the implementer's provider.")
183
217
  return skipped
184
218
 
185
219
 
186
220
  def last_words(log: Path) -> str:
187
- """The last line of an agent log, or the `result` of the last stream-json line: the error a failed CLI gave."""
221
+ """The last line of an agent log, or the `result` of the last claude stream-json line or the error `message` of
222
+ the last codex --json line: the error a failed CLI gave."""
188
223
  lines = [line for line in log.read_text(errors="replace").splitlines() if line.strip()] if log.exists() else []
189
224
  if not lines:
190
225
  return "no output"
191
226
  with contextlib.suppress(ValueError, AttributeError):
192
- return str(json.loads(lines[-1]).get("result") or lines[-1])[-500:]
227
+ event = json.loads(lines[-1])
228
+ error = event.get("error")
229
+ return str(event.get("result") or event.get("message") or (isinstance(error, dict) and error.get("message"))
230
+ or lines[-1])[-500:]
193
231
  return lines[-1][-500:]
194
232
 
195
233
 
@@ -199,9 +237,12 @@ def command(role: str, entry: str, report: str) -> list[str]:
199
237
  if provider == "openai":
200
238
  # No --ephemeral: the rollout on disk is the trace. A read-only agent may not write its report, so -o saves
201
239
  # the last message next to it; settle_report picks one. -o on the report itself overwrites a written report.
240
+ # A role that commits needs full access: workspace-write keeps .git read-only, even as an --add-dir or a
241
+ # sandbox_workspace_write.writable_roots entry (codex 0.166.0).
202
242
  tail = ["--sandbox", "read-only", "-o", last_message(report)] if role in READ_ONLY else [
203
- "--sandbox", "workspace-write"]
204
- return ["codex", "exec", "--model", model, "-c", f'model_reasoning_effort="{effort}"', *tail]
243
+ "--sandbox", "danger-full-access"]
244
+ # --json: the log carries the token usage of each turn, which prices the run.
245
+ return ["codex", "exec", "--json", "--model", model, "-c", f'model_reasoning_effort="{effort}"', *tail]
205
246
  # stream-json keeps tool output in the log and ends with a result that has total_cost_usd.
206
247
  return ["claude", "-p", "--model", model, "--effort", effort, "--permission-mode", "auto",
207
248
  "--output-format", "stream-json", "--verbose"]
@@ -281,7 +322,27 @@ def stop() -> None:
281
322
  _kill(group)
282
323
 
283
324
 
284
- def cost(log: Path) -> str | None:
285
- """The dollar cost the CLI reported; None for codex, which reports tokens only."""
325
+ def tokens(log: Path) -> dict[str, int]:
326
+ """The tokens a codex agent used, summed over the turns of its --json log; {} for a log with no turn."""
327
+ used: dict[str, int] = {}
328
+ for line in log.read_text(errors="replace").splitlines():
329
+ with contextlib.suppress(ValueError, AttributeError, TypeError):
330
+ event = json.loads(line)
331
+ if event.get("type") == "turn.completed":
332
+ for name, key in _USAGE.items():
333
+ used[name] = used.get(name, 0) + int((event.get("usage") or {}).get(key, 0))
334
+ return used
335
+
336
+
337
+ def cost(log: Path, entry: str, used: dict[str, int]) -> float | None:
338
+ """The dollar cost of an agent: the one the claude CLI reported, or the tokens `used` of a codex agent at the list
339
+ price of its model; None when there is neither."""
340
+ provider, model, _ = split(entry)
341
+ if provider == "openai":
342
+ if not used or not (price := PRICES.get(model)):
343
+ return None
344
+ uncached = used["input"] - used["cached_input"]
345
+ return round((uncached * price["input"] + used["cached_input"] * price["cached_input"]
346
+ + used["output"] * price["output"]) / 1e6, 4)
286
347
  found = re.findall(r'"total_cost_usd":\s*([0-9.]+)', log.read_text(errors="replace"))
287
- return found[-1] if found else None
348
+ return float(found[-1]) if found else None
@@ -49,8 +49,9 @@ KINDS = {
49
49
  "spec-ambiguous": Kind(
50
50
  "Ticket {ticket}: the spec reads two ways on a locked test: {subject}",
51
51
  "This locked test was ruled on or corrected once in ticket {ticket}, and a second dispute or a second "
52
- "correction needs it again: the spec supports both readings. Ticket {ticket} is BLOCKED and each ticket that "
53
- "it blocks waits.",
52
+ "correction needs it again: the spec supports both readings. Or the locked tests of ticket {ticket} were "
53
+ "arbitrated or corrected so often that the driver asks before one more: the first reading says so. Ticket "
54
+ "{ticket} is BLOCKED and each ticket that it blocks waits.",
54
55
  "",
55
56
  {"keep-test": Option(
56
57
  "The test stands as it is. The role that disputed it runs again and makes it green; a review finding that "