@jesdi/skills 0.0.86 → 0.0.87

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jesdi/skills",
3
- "version": "0.0.86",
3
+ "version": "0.0.87",
4
4
  "description": "jesdi's agent skills (content package consumed by @jesdi/skills-cli)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -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`).
@@ -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
 
@@ -150,8 +149,8 @@ The end of run starts only when every ticket is merged and every slot is idle. I
150
149
 
151
150
  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
151
  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.
152
+ 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.
153
+ 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
154
  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
155
  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
156
 
@@ -177,13 +176,26 @@ A repository with no `origin` remote skips only step 2 and step 6. The tidied co
177
176
 
178
177
  `models.json` holds the default list for each role. An entry is `provider/model@effort`; an entry with no provider is `anthropic`.
179
178
 
179
+ 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:
180
+
181
+ 1. the skill's `models.json`;
182
+ 2. the home file `${XDG_CONFIG_HOME:-~/.config}/implement-spec/models.json`, for the operator's subscriptions on every repository;
183
+ 3. the repo file `.implement-spec/models.json` at the root of the PR worktree, committed, for a repository that pins a model;
184
+ 4. the `--models` file of the invocation.
185
+
186
+ 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.
187
+
180
188
  | Provider | CLI | Efforts |
181
189
  |---|---|---|
182
190
  | `anthropic` | `claude -p` | low, medium, high, xhigh, max |
183
- | `openai` | `codex exec` | minimal, low, medium, high, xhigh |
191
+ | `openai` | `codex exec --json` | minimal, low, medium, high, xhigh |
184
192
 
185
193
  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
194
 
195
+ 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.
196
+
197
+ 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.
198
+
187
199
  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
200
 
189
201
  ## Report schema per role
@@ -229,10 +241,10 @@ Answer with `--answer <question id>=<option id>` on the next run, or through the
229
241
  | 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
242
  | 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
243
  | 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. |
244
+ | 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
245
 
234
246
  ## Known limits
235
247
 
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.
248
+ - **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
249
  - **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
250
  - **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
@@ -44,8 +44,8 @@ class Blocked(Exception):
44
44
 
45
45
 
46
46
  class Halted(Exception):
47
- """The CLI of an agent failed with no report, two times: a model the account cannot use, a CLI that is not
48
- signed in. The run starts no other agent and ends with exit 4; the ticket keeps its phase for the next run."""
47
+ """The CLI of an agent failed with no report: a model the account cannot use or has no usage left for, a CLI
48
+ that is not signed in. The run starts no other agent and ends with exit 4; the ticket keeps its phase for the next run."""
49
49
 
50
50
 
51
51
  @contextmanager
@@ -319,11 +319,9 @@ def _ask_blocked(run: Run, call: Call, report: Path, error: str) -> None:
319
319
  run.ask(call.number, "ticket-blocked", [f"the {call.role}: {error}"], str(report), resume)
320
320
 
321
321
 
322
- def _give_up(run: Run, call: Call, report: Path, error: str, failed: str, same: bool) -> NoReturn:
323
- """After the rerun failed too: Halted for a CLI that wrote no report, else Blocked, with a `ticket-blocked`
324
- question when the agent stopped or was rejected."""
325
- if failed:
326
- raise Halted(failed)
322
+ def _give_up(run: Run, call: Call, report: Path, error: str, same: bool) -> NoReturn:
323
+ """After the rerun failed too: Blocked, with a `ticket-blocked` question when the agent stopped or was
324
+ rejected."""
327
325
  if not same:
328
326
  _ask_blocked(run, call, report, error)
329
327
  raise Blocked(error)
@@ -344,13 +342,24 @@ def _first_prompt(template: str, values: dict[str, str], notes: tuple | list, re
344
342
 
345
343
 
346
344
  def _record_attempt(run: Run, role: str, number: str, entry: str, seconds: float, log: Path, error: str) -> None:
347
- cost = driver_agents.cost(log)
348
- used = {"ticket": number, "role": role, "entry": entry, "seconds": round(seconds, 1), "cost": float(cost or 0)}
345
+ tokens = driver_agents.tokens(log)
346
+ cost = driver_agents.cost(log, entry, tokens)
347
+ # cost None: not priced, a codex model with no list price or a CLI that reported none.
348
+ used = {"ticket": number, "role": role, "entry": entry, "seconds": round(seconds, 1), "cost": cost,
349
+ "tokens": tokens}
349
350
  run.state.update(lambda state: state["run"]["agents"].append(used))
350
- spent = f", cost {cost} USD" if cost else ""
351
+ spent = f", cost {cost:g} USD" if cost is not None else _unpriced(tokens)
351
352
  ledger(f"{_owner(number)}: {role} ran on {entry} for {seconds:.1f}s{spent}: {error or 'report accepted'}.")
352
353
 
353
354
 
355
+ def _unpriced(tokens: dict[str, int]) -> str:
356
+ """The ledger words of a codex agent whose model has no list price: its tokens; "" when it has none."""
357
+ if not tokens:
358
+ return ""
359
+ return (f", {tokens['input']} input tokens ({tokens['cached_input']} cached) and {tokens['output']} output tokens, "
360
+ "not priced")
361
+
362
+
354
363
  def _command(run: Run, role: str, entry: str, prompt: str, report: str) -> list[str]:
355
364
  if run.args.runner: # `--runner` is for tests
356
365
  return [run.args.runner, role, prompt, report]
@@ -370,7 +379,7 @@ def _attempts(run: Run, call: Call) -> dict:
370
379
  "template": call.template or role, **call.check}
371
380
  text = _first_prompt(context["template"], values, call.notes, report_in_slot)
372
381
  rerun_on = _rerun_entry(run, role, entry, call.entries)
373
- minutes, error, failed, same = run.args.timeout[role], "", "", True
382
+ minutes, error, same = run.args.timeout[role], "", True
374
383
  for _ in range(2):
375
384
  argv = _command(run, role, entry, os.path.relpath(prompt, slot), report_in_slot)
376
385
  prompt.write_text(text)
@@ -386,10 +395,11 @@ def _attempts(run: Run, call: Call) -> dict:
386
395
  _record_attempt(run, role, number, entry, seconds, log, error)
387
396
  if not error:
388
397
  return json.loads(report.read_text())
389
- failed = _cli_failure(role, entry, code, report, log)
398
+ if failed := _cli_failure(role, entry, code, report, log):
399
+ raise Halted(failed) # the operator changes the config: the run moves to no other entry on its own
390
400
  # The rerun prompt is the first prompt, the rejection, then the same ending again.
391
401
  text += rerun_lines + driver_agents.tail(text, report_in_slot)
392
402
  if code is None:
393
403
  minutes *= 2
394
404
  entry = entry if same else rerun_on
395
- _give_up(run, call, report, error, failed, same)
405
+ _give_up(run, call, report, error, same)
@@ -1,6 +1,6 @@
1
1
  """state.json, the resume contract: one lock, every write a read-modify-write, published by rename.
2
2
 
3
- {"run": {revision, pr_branch, schema, gates: {fast, full}, stops, agents: [{ticket, role, entry, seconds, cost}], questions, start,
3
+ {"run": {revision, pr_branch, schema, gates: {fast, full}, stops, agents: [{ticket, role, entry, seconds, cost, tokens}], questions, start,
4
4
  landed: [[ticket, the PR tip its merge made]], final},
5
5
  "tickets": {"NN": {phase, round, tip, test_writer_sha, locked, green_gates, slot, note,
6
6
  landing, disputes, corrected}}}
@@ -15,7 +15,14 @@ def _rows(run: dict, tickets: dict) -> list[tuple[str, object]]:
15
15
  *((f"wall time, {role}", f"{total:.1f} s") for role, total in seconds.items()),
16
16
  ("fix rounds per ticket", rounds),
17
17
  ("human stops", run["stops"]),
18
- ("cost", f"{sum(agent['cost'] for agent in run['agents']):.2f} USD")]
18
+ *_cost(run["agents"])]
19
+
20
+
21
+ def _cost(agents: list[dict]) -> list[tuple[str, object]]:
22
+ """The cost row, and a row that counts the agents with no price (cost None), which the cost leaves out."""
23
+ unpriced = sum(agent["cost"] is None for agent in agents)
24
+ return [("cost", f"{sum(agent['cost'] or 0 for agent in agents):.2f} USD"),
25
+ *([("agents not priced", unpriced)] if unpriced else [])]
19
26
 
20
27
 
21
28
  def _end(run: dict) -> list[str]:
@@ -25,6 +25,8 @@ def pr_skill(tmp_path_factory):
25
25
  (home / "skills/pr/SKILL.md").write_text("---\nname: pr\n---\n")
26
26
  with pytest.MonkeyPatch.context() as patch:
27
27
  patch.setenv("CLAUDE_CONFIG_DIR", str(home))
28
+ # No test reads the operator's own provider config (driver_agents.load_models).
29
+ patch.setenv("XDG_CONFIG_HOME", str(tmp_path_factory.mktemp("config-home")))
28
30
  yield home / "skills/pr/SKILL.md"
29
31
 
30
32
 
@@ -192,14 +192,16 @@ def test_help_lists_the_timeout_flag_and_default_minutes():
192
192
 
193
193
 
194
194
  @pytest.mark.parametrize("entry", ["openai/gpt-sol@medium"])
195
- def test_openai_implementer_launches_codex_exec_in_workspace_write(env, entry):
195
+ def test_openai_implementer_launches_codex_exec_with_full_access_so_it_can_commit(env, entry):
196
+ # workspace-write keeps .git read-only, even with --add-dir on the git directory: git commit fails there.
196
197
  w = World(env, refactor=True, implementer=[entry, entry]) # the rerun after no report is on the next entry
197
198
  w.run(runner=False)
198
199
  argv = launches(w.tmp, "codex")[0]
199
200
  assert argv[0] == "exec" and "--ephemeral" not in argv
200
201
  assert value_after(argv, "--model", "-m") == "gpt-sol"
201
202
  assert any("model_reasoning_effort" in a and "medium" in a for a in argv)
202
- assert value_after(argv, "--sandbox", "-s") == "workspace-write"
203
+ assert value_after(argv, "--sandbox", "-s") == "danger-full-access"
204
+ assert "--json" in argv, "the log carries the token usage that prices the run"
203
205
  assert not launches(w.tmp, "claude")
204
206
 
205
207
 
@@ -210,6 +212,7 @@ def test_the_reviewer_launches_codex_exec_read_only(env):
210
212
  assert argv[0] == "exec" and "--ephemeral" not in argv
211
213
  assert value_after(argv, "--sandbox", "-s") == "read-only"
212
214
  assert value_after(argv, "--model", "-m") == "gpt-sol"
215
+ assert "--json" in argv
213
216
 
214
217
 
215
218
  @pytest.mark.parametrize("writes", ["file", "message"])
@@ -339,16 +342,18 @@ def test_a_model_the_account_cannot_use_is_skipped_and_its_roles_go_on_with_thei
339
342
 
340
343
 
341
344
  def test_a_cli_that_fails_with_no_report_stops_the_run_with_exit_4_and_the_same_command_resumes(env):
345
+ """Stop and ask: the first CLI failure stops the run, with no rerun on another entry of the list."""
342
346
  w = World(env, refactor=True)
343
- plan = {"implementer": [{"stderr": REFUSED + "\n", "exit": 1}] * 2 + [impl()]}
347
+ plan = {"implementer": [{"stderr": REFUSED + "\n", "exit": 1}, impl()]}
344
348
  proc = w.run(plan)
349
+ assert len(w.calls("implementer")) == 1, "no rerun after a CLI failure"
345
350
  assert proc.returncode == 4, proc.stdout + proc.stderr
346
- assert f"implement-spec: the run stopped: the implementer on openai/gpt-sol@medium exited 1 with no " \
351
+ assert f"implement-spec: the run stopped: the implementer on anthropic/claude-opus-5@medium exited 1 with no " \
347
352
  f"report: {REFUSED}" in proc.stdout.splitlines(), proc.stdout
348
353
  assert "BLOCKED" not in w.ledger() and "Ticket 01: the run stops and the phase stays for the next run: the implementer" in w.ledger()
349
354
  assert json.loads((w.repo / ".agent/implement/state.json").read_text())["tickets"]["01"]["phase"] == "implement"
350
355
  ok(w.run(plan))
351
- assert len(w.calls("implementer")) == 3
356
+ assert len(w.calls("implementer")) == 2
352
357
 
353
358
 
354
359
  def test_finished_status_reruns_the_implementer_once_with_the_error_appended(env):
@@ -452,3 +457,49 @@ def test_log_next_to_report_and_ledger_records_role_entry_duration_and_cost(env)
452
457
  assert "OUT-MARK" in log and "ERR-MARK" in log and (folder / "implementer-0.json").exists()
453
458
  (line,) = [l for l in w.ledger().splitlines() if "implementer" in l and "claude-opus-5@medium" in l]
454
459
  assert re.search(r"\d+(\.\d+)?s\b", line) and "0.4242" in line, line
460
+
461
+
462
+ def turn(used, cached, out):
463
+ return json.dumps({"type": "turn.completed", "usage": {"input_tokens": used, "cached_input_tokens": cached,
464
+ "output_tokens": out, "reasoning_output_tokens": 0}})
465
+
466
+
467
+ def test_a_codex_agent_is_priced_from_its_token_usage_at_the_list_price_of_its_model(env):
468
+ astra = "openai/gpt-6-astra@medium"
469
+ w = World(env, refactor=True, implementer=[astra])
470
+ # Two turns: 1.2M input of which 0.4M cached, 10k output. At 10 / 1 / 50 USD per million: 8 + 0.4 + 0.5.
471
+ ok(w.run({"implementer": [impl(stdout=turn(700_000, 300_000, 4_000) + "\n" + turn(500_000, 100_000, 6_000) + "\n")]}))
472
+ (line,) = [l for l in w.ledger().splitlines() if "implementer ran on" in l]
473
+ assert f"implementer ran on {astra} for " in line and ", cost 8.9 USD: report accepted." in line, line
474
+ (agent,) = [a for a in json.loads((w.repo / ".agent/implement/state.json").read_text())["run"]["agents"]
475
+ if a["role"] == "implementer"]
476
+ assert agent["cost"] == 8.9
477
+ assert agent["tokens"] == {"input": 1_200_000, "cached_input": 400_000, "output": 10_000}
478
+
479
+
480
+ def test_a_codex_model_with_no_list_price_keeps_its_tokens_and_the_ledger_says_it_is_not_priced(env):
481
+ w = World(env, refactor=True, implementer=["openai/gpt-sol@medium"])
482
+ ok(w.run({"implementer": [impl(stdout=turn(1_000, 200, 30) + "\n")]}))
483
+ (line,) = [l for l in w.ledger().splitlines() if "implementer ran on" in l]
484
+ assert ", 1000 input tokens (200 cached) and 30 output tokens, not priced: report accepted." in line, line
485
+ (agent,) = [a for a in json.loads((w.repo / ".agent/implement/state.json").read_text())["run"]["agents"]
486
+ if a["role"] == "implementer"]
487
+ assert agent["cost"] is None and agent["tokens"] == {"input": 1_000, "cached_input": 200, "output": 30}
488
+
489
+
490
+ @pytest.mark.parametrize("line", ['{"type": "error", "message": "You\'ve hit your usage limit."}',
491
+ '{"type": "turn.failed", "error": {"message": "You\'ve hit your usage limit."}}'])
492
+ def test_the_last_words_of_a_codex_json_log_are_its_error_message(tmp_path, line):
493
+ sys.path.insert(0, str(SKILL))
494
+ import driver_agents
495
+ log = tmp_path / "agent.log"
496
+ log.write_text('{"type": "thread.started"}\n' + line + "\n")
497
+ assert driver_agents.last_words(log) == "You've hit your usage limit."
498
+
499
+
500
+ def test_a_turn_with_no_usage_counts_no_token(tmp_path):
501
+ sys.path.insert(0, str(SKILL))
502
+ import driver_agents
503
+ log = tmp_path / "agent.log"
504
+ log.write_text('{"type": "turn.completed"}\n' + turn(10, 4, 2) + "\n")
505
+ assert driver_agents.tokens(log) == {"input": 10, "cached_input": 4, "output": 2}
@@ -149,7 +149,9 @@ def test_the_summary_keeps_its_table_and_counts_an_arbitration_as_a_reviewer_age
149
149
  rows = (rig.repo / ".agent/implement/summary.md").read_text().split("| Measure | Value |\n|---|---|\n")[1]
150
150
  names = re.findall(r"^\| (.+?) \|", rows, re.M)
151
151
  assert {f"wall time, {role}" for role in ("test-writer", "implementer", "reviewer", "fixer")} < set(names), rows
152
- assert names[-3:] == ["fix rounds per ticket", "human stops", "cost"] and rows.endswith(" USD |\n"), rows
152
+ # Most fake agents report no cost, so they are counted as not priced.
153
+ assert names[-4:] == ["fix rounds per ticket", "human stops", "cost", "agents not priced"], rows
154
+ assert re.search(r"^\| cost \| \d+\.\d\d USD \|$", rows, re.M), rows
153
155
  for row in ("| fast gates run | 2 |", "| full gates run | 1 |", "| agents, reviewer on anthropic/claude-opus-5@medium | 3 |",
154
156
  "| fix rounds per ticket | 01: 1, 02: 0 |", "| human stops | 1 |"):
155
157
  assert row in rows, rows
@@ -343,7 +343,8 @@ def test_a_timeout_for_an_unknown_role_is_a_usage_error(repo):
343
343
 
344
344
  def test_command_lines_per_provider():
345
345
  assert driver_agents.command("implementer", "openai/gpt-sol@high", "r.json") == [
346
- "codex", "exec", "--model", "gpt-sol", "-c", 'model_reasoning_effort="high"', "--sandbox", "workspace-write"]
346
+ "codex", "exec", "--json", "--model", "gpt-sol", "-c", 'model_reasoning_effort="high"', "--sandbox",
347
+ "danger-full-access"]
347
348
  assert driver_agents.command("reviewer", "openai/gpt-sol@high", "r.json")[-4:] == [
348
349
  "--sandbox", "read-only", "-o", "r.json.last"]
349
350
  assert driver_agents.command("reviewer", "opus@low", "r.json")[:6] == [
@@ -109,12 +109,17 @@ def test_the_review_coverage_names_only_what_ran_so_an_undone_fallback_is_not_cl
109
109
 
110
110
  # ---------------------------------------------------------------- input validation
111
111
 
112
- def test_a_final_reviewer_list_with_no_entry_on_another_provider_exits_3_before_any_agent(tmp_path):
112
+ def test_a_final_reviewer_list_with_no_entry_on_another_provider_runs_every_review_on_it_and_says_so(
113
+ tmp_path, monkeypatch):
114
+ """Another provider for correctness is a preference: a config on one provider runs, and the ledger says so."""
115
+ monkeypatch.setattr(driver, "_preflight", lambda args, models: driver._checked(models))
116
+ monkeypatch.setattr(driver_agents, "_failures", lambda entries: {})
113
117
  rig = rig_of(tmp_path, models={"implementer": [SONNET], "final-reviewer": [OPUS]}).run(plan())
114
- assert rig.code == 3 and not rig.calls(), rig.out
115
- assert rig.out == (f"final-reviewer: no entry of its list ({OPUS}) is on another provider than the implementer's "
116
- f"first entry {SONNET}; its other-provider entry serves the correctness lens of the final "
117
- "review and the scoped review, which never run on the implementer's provider\n")
118
+ assert rig.code == 0, rig.out
119
+ said = (f"No final-reviewer entry is on another provider than {SONNET}: the correctness lens and the scoped review "
120
+ f"run on {OPUS}, the implementer's provider.")
121
+ assert rig.out.splitlines()[0] == said and rig.ledger()[0] == said
122
+ assert rig.led("End of run: final-correctness ran on", OPUS)
118
123
 
119
124
 
120
125
  def test_without_the_deep_quality_review_skill_the_run_exits_3_before_any_agent(tmp_path, monkeypatch):
@@ -5,6 +5,7 @@ skill's models.json does not define stops the run before the preflight and befor
5
5
  import json
6
6
  import re
7
7
  import subprocess
8
+ import sys
8
9
 
9
10
  import pytest
10
11
 
@@ -94,3 +95,76 @@ def test_only_correctness_exits_3_as_an_unknown_role(env, tmp_path):
94
95
  def test_the_skill_has_no_correctness_or_explorer_role():
95
96
  assert not {"correctness", "explorer"} & models().keys()
96
97
  assert not (SKILL / "prompts/correctness.md").exists()
98
+
99
+
100
+ # ---------------------------------------------------------------- the provider config files
101
+
102
+ OPUS, ASTRA, SOL = "claude-opus-5-5@medium", "openai/gpt-6-astra@medium", "openai/gpt-6.1-sol@medium"
103
+
104
+
105
+ @pytest.fixture
106
+ def layers(tmp_path, monkeypatch):
107
+ """A home config folder and a worktree; returns a writer of (the home file, the repo file)."""
108
+ sys.path.insert(0, str(SKILL))
109
+ import driver_agents
110
+ monkeypatch.setattr(driver_agents.shutil, "which", lambda cli: cli)
111
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config"))
112
+ monkeypatch.chdir(tmp_path)
113
+ home, repo = tmp_path / "config/implement-spec/models.json", tmp_path / ".implement-spec/models.json"
114
+
115
+ def write(path, roles):
116
+ path.parent.mkdir(parents=True, exist_ok=True)
117
+ path.write_text(json.dumps(roles))
118
+ return path
119
+ return driver_agents, lambda roles: write(home, roles), lambda roles: write(repo, roles), tmp_path
120
+
121
+
122
+ def test_the_home_file_replaces_the_lists_it_names_and_keeps_the_rest(layers):
123
+ driver_agents, home, _, _ = layers
124
+ home({"reviewer": [OPUS]})
125
+ loaded, errors = driver_agents.load_models(None)
126
+ assert errors == [] and loaded["reviewer"] == [OPUS] and loaded["implementer"] == models()["implementer"]
127
+
128
+
129
+ def test_the_repo_file_wins_over_the_home_file_and_the_models_flag_wins_over_both(layers):
130
+ driver_agents, home, repo, tmp = layers
131
+ home({"reviewer": [OPUS], "fixer": [OPUS]})
132
+ repo({"reviewer": [ASTRA]})
133
+ loaded, errors = driver_agents.load_models(None)
134
+ assert errors == [] and loaded["reviewer"] == [ASTRA] and loaded["fixer"] == [OPUS]
135
+ flag = tmp / "flag.json"
136
+ flag.write_text(json.dumps({"reviewer": [SOL]}))
137
+ loaded, errors = driver_agents.load_models(str(flag))
138
+ assert errors == [] and loaded["reviewer"] == [SOL] and loaded["fixer"] == [OPUS]
139
+
140
+
141
+ def test_an_error_in_a_config_file_names_that_file(layers):
142
+ driver_agents, home, repo, tmp = layers
143
+ home({"correctness": [OPUS]})
144
+ repo({"planner": [OPUS]})
145
+ _, errors = driver_agents.load_models(None)
146
+ assert errors[0] == f"correctness: the role was removed; delete its key from {tmp}/config/implement-spec/models.json"
147
+ assert errors[1].startswith("planner: unknown role (known: ") and errors[1].endswith(
148
+ "); delete its key from .implement-spec/models.json"), errors
149
+ (tmp / ".implement-spec/models.json").write_text("{not json")
150
+ _, errors = driver_agents.load_models(None)
151
+ assert errors[1].startswith(".implement-spec/models.json: JSONDecodeError("), errors
152
+
153
+
154
+ def test_a_removed_role_in_the_repo_file_exits_3_naming_the_file_before_the_preflight(env, tmp_path):
155
+ repo = make_repo(tmp_path / "demo", three())
156
+ (repo / ".implement-spec").mkdir()
157
+ (repo / ".implement-spec/models.json").write_text(json.dumps({"correctness": [ASTRA]}))
158
+ proc = drive(env, repo, *RUNS)
159
+ assert proc.returncode == 3, proc.stdout + proc.stderr
160
+ assert ("correctness: the role was removed; delete its key from .implement-spec/models.json"
161
+ in proc.stdout.splitlines()), proc.stdout
162
+ assert not (tmp_path / "launched").exists(), "no preflight and no agent"
163
+
164
+
165
+ @pytest.mark.parametrize("content", ['{"reviewer": "openai/gpt-6-astra@medium"}', '{"reviewer": [1]}', "[]"])
166
+ def test_a_config_file_of_the_wrong_shape_is_an_error_naming_the_file(layers, content):
167
+ driver_agents, _, repo, _ = layers
168
+ repo({}).write_text(content)
169
+ _, errors = driver_agents.load_models(None)
170
+ assert len(errors) == 1 and errors[0].startswith(".implement-spec/models.json: "), errors
@@ -27,3 +27,11 @@ Ticket 03 is not merged: its phase is blocked.
27
27
  | human stops | 1 |
28
28
  | cost | 1.75 USD |
29
29
  """
30
+
31
+
32
+ def test_an_agent_with_no_price_is_counted_apart_from_the_cost():
33
+ agents = [{"role": "reviewer", "entry": "openai/gpt-x@low", "seconds": 1, "cost": None},
34
+ {"role": "implementer", "entry": "opus@medium", "seconds": 1, "cost": 0.5}]
35
+ state = {"run": {"pr_branch": "feat/csv", "gates": {"fast": 0, "full": 0}, "stops": 0, "final": driver_state._final(),
36
+ "agents": agents}, "tickets": {}}
37
+ assert driver_summary.render(state).endswith("| cost | 0.50 USD |\n| agents not priced | 1 |\n")
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-11-05T12:22:43.116Z",
3
+ "generatedAt": "2026-11-05T18:12:03.162Z",
4
4
  "skills": [
5
5
  {
6
6
  "name": "agents-wayfinder",
@@ -58,8 +58,8 @@
58
58
  },
59
59
  {
60
60
  "name": "implement-spec",
61
- "version": "0.1.50",
62
- "hash": "sha256-2b88ad4bcc572280fd6d023ad925e7644fae72483c4827c032362724d14cfa3d",
61
+ "version": "0.1.51",
62
+ "hash": "sha256-3ae7ce51a5d74ddd7161016275ff329636448471711b21fcdd742d345f181828",
63
63
  "description": "Implement a specification in code."
64
64
  },
65
65
  {