@jesdi/skills 0.0.97 → 0.0.99

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.97",
3
+ "version": "0.0.99",
4
4
  "description": "jesdi's agent skills (content package consumed by @jesdi/skills-cli)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -14,6 +14,7 @@ A comment in the code is for a line that looks wrong or removable without it.
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
16
  | `driver_dispute.py` | A disputed locked test: the arbitration, its correction, the once-per-test record, `spec-ambiguous` |
17
+ | `driver_arbiter.py` | The arbiter agent that rules on the open questions the driver's retries leave (`driver_decisions.arbitrated`) |
17
18
  | `driver_final.py` | The end of run: tidy, rebase, gate, final review, one fix batch, push |
18
19
  | `driver_tickets.py`, `driver_graph.py` | Ticket files in, tickets or errors out; which tickets can start now |
19
20
  | `driver_agents.py` | Model entries, the CLI command of each provider, prompt templates, the blocking launch |
@@ -35,8 +36,9 @@ and do not know about the run, except `driver_run.py`, which the deciding module
35
36
  ## Conventions
36
37
 
37
38
  - **A step that cannot go on raises `Blocked`.** The message says why. `with during("the merge"):` puts the step
38
- in front. Only two places catch it for good: `driver._run_ticket` (the ticket becomes BLOCKED) and
39
- `driver_final.run` (the end of run becomes BLOCKED). Another `except Blocked` only cleans up and raises again.
39
+ in front. Only three places catch it for good: `driver._run_ticket` (the ticket becomes BLOCKED),
40
+ `driver_final.run` (the end of run becomes BLOCKED) and `driver_arbiter.rule` (the operator answers the questions
41
+ the arbiter could not rule on). Another `except Blocked` only cleans up and raises again.
40
42
  - **A CLI that fails with no report raises `Halted`**, not `Blocked`: the setup of the run is wrong, not the
41
43
  ticket. `driver._run_ticket` and `driver._work` catch it: the run starts no other agent and ends with exit 4,
42
44
  and the ticket keeps its phase for the next run. A cleanup of an `except Blocked` that leaves git as it was (an
@@ -41,6 +41,8 @@ A driver before this change named the ticket branches `ticket/<NN>` and the reco
41
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. |
42
42
  | `--timeout ROLE=MINUTES` | The timeout of one role. Repeatable. The rerun after a timeout gets twice the time. |
43
43
  | `--answer QUESTION=OPTION` | The answer to one open question. Repeatable. The driver writes it to `.agent/implement-answers.json`. |
44
+ | `--retries N` | The stops of one ticket, or of the end of run, that the driver answers itself with the recommended option before it asks the operator. Default: `IMPLEMENT_SPEC_RETRIES`, else 2. `0` asks at the first stop. See "The driver rules first". |
45
+ | `--ask`, `--no-ask` | Once the driver's retries are spent, ask the operator instead of the arbiter agent. Default: on with `IMPLEMENT_SPEC_ASK=1`, else off. See "The driver rules first". |
44
46
  | `--unattended` | Print no question. Write `--stage-json` for the dispatcher, and push without `--push` when the final review has passed. |
45
47
  | `--stage-json FILE` | With `--unattended`: the file that says how the run ended. |
46
48
  | `--push` | Local mode: when the final review has passed, push the PR branch and open the PR. Without it nothing is pushed. |
@@ -50,7 +52,7 @@ A driver before this change named the ticket branches `ticket/<NN>` and the reco
50
52
  | `--only ROLE` | Test only. Run one role (`test-writer`, `implementer` or `reviewer`) on the first ticket, with no gate and no merge. |
51
53
  | `--help`, `-h` | Print the flags and exit. |
52
54
 
53
- Default timeouts in minutes: test-writer 30, implementer 90, reviewer 45, fixer 60, final-reviewer 60, final-spec 60, final-correctness 60, final-structure 60, conflict 30, pr-writer 20.
55
+ Default timeouts in minutes: test-writer 30, implementer 90, reviewer 45, fixer 60, final-reviewer 60, final-spec 60, final-correctness 60, final-structure 60, conflict 30, pr-writer 20, arbiter 30.
54
56
 
55
57
  `run.sh` downloads `uv`, Python 3.13 and `jsonschema` once into `~/.cache/implement-spec`. `IMPLEMENT_SPEC_CACHE_DIR` moves that cache. `IMPLEMENT_SPEC_OFFLINE=1` forbids the download. `run.sh` supports macOS and Linux only, on x86_64 or ARM64, and needs `curl`, `tar` and `sha256sum` or `shasum` for the first download.
56
58
 
@@ -60,7 +62,7 @@ Default timeouts in minutes: test-writer 30, implementer 90, reviewer 45, fixer
60
62
  |---|---|
61
63
  | 0 | Done: every ticket is merged and no question is open. Also the end of a valid `--dry-run`. In local mode without `--push`, nothing is pushed. |
62
64
  | 1 | A ticket is BLOCKED, or the end of run is BLOCKED. The other tickets ran as far as they could. |
63
- | 2 | Parked: a question of kind `spec-ambiguous` or `ticket-blocked` is open. Exit 2 wins over exit 1. |
65
+ | 2 | Parked: a question of kind `spec-ambiguous` is open, or one of kind `ticket-blocked` after the driver's own retries are spent (`--retries`), or one of kind `finding-open` that the arbiter did not rule on (`--ask`, or an arbiter that failed). Exit 2 wins over exit 1. |
64
66
  | 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. |
65
67
  | 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. |
66
68
  | 130 | The operator interrupted the run. The driver stops each agent. The work stays in the slots for the next run. |
@@ -71,7 +73,7 @@ With `--unattended`, the `--stage-json` file holds `{"stage": "implement", "stat
71
73
  |---|---|---|
72
74
  | 2 | `awaiting-review` | `artifact` (the review page), `open_questions` (a count) |
73
75
  | 1 | `blocked` | `blocked` (ticket numbers, and `final` for the end of run) |
74
- | 0, pushed | `done` | none |
76
+ | 0, pushed | `done` | `draft` (the PR opened as draft), `decisions` (the questions the driver or the arbiter ruled on) |
75
77
 
76
78
  ## Layout
77
79
 
@@ -83,13 +85,13 @@ Everything is under `.agent/`, which is never committed.
83
85
  | `<git common directory>/implement-spec/<key>.lock` | An empty file, not in the worktree. The driver that runs holds a kernel file lock on it (`driver_state.py` `lock`). Do not remove it during a run. |
84
86
  | `<git common directory>/implement-spec-worktrees.lock` | Shared by driver processes for `worktree`, `checkout`, `switch` and `branch` commands, so a checkout never reads another driver's half-written registration. Held only during that Git command, never during preparation, agents or gates. Git commands outside the driver do not participate. |
85
87
  | `.agent/implement/ledger.md` | One plain sentence for each event. Only the driver writes it, and it reads no fact from it. |
86
- | `.agent/implement/summary.md` | The result in sentences, and the measurement table: fast gates and full gates, agents, wall time, fix rounds, human stops, cost. |
88
+ | `.agent/implement/summary.md` | The result in sentences, and the measurement table: fast gates and full gates, agents, wall time, fix rounds, human stops, the stops the driver ruled on, cost. Then `Driver decisions, taken without the operator:` with one ruling sentence for each question the driver answered itself. |
87
89
  | `.agent/implement/decisions.json` | The open questions and their `revision`. Written only after a stop. |
88
90
  | `.agent/implement/<NN>/` | One folder for each ticket. |
89
91
  | `.agent/implement/<NN>/<role>-<K>.json`, `.log`, `.prompt.md` | The report, the log and the prompt of one agent. K is the fix round. |
90
92
  | `.agent/implement/<NN>/gate-<tier>-<sha7>.log` | One gate record, `<tier>` is `fast` or `full`: start, tier, commit, status, command, output, exit, the state after the command, end. A command that a signal ended, with the tree clean and HEAD unmoved, did not judge the commit: the driver runs it once more, that run overwrites the record, and the ledger says the gate was killed by the signal and runs again. A signal ended the command when its exit is negative, or when it is 128+N for N in SIGHUP (1), SIGINT (2), SIGKILL (9) or SIGTERM (15): the gate runs in `/bin/sh -c`, and a shell that does not exec the command, as Ubuntu's dash does not, outlives its killed child and exits with 128+N. Any other exit, 142 (128+SIGALRM) among them, is a red record with no second run. A second signal leaves the record red. |
91
93
  | `.agent/implement/<NN>/findings-<K>.json` | The merged findings of the review after fix round K, or the red fast gate of round K. |
92
- | `.agent/implement/final/` | The same files for the end of run, and `pr-body.md`: the pr-writer's body, then the facts of the run. |
94
+ | `.agent/implement/final/` | The same files for the end of run, `pr-writer-body.md` (the pr-writer's body) and `pr-body.md`: that body, then the facts of the run. |
93
95
  | `.agent/implement/pycache/` | Compiled Python of the gate, kept out of the slots. |
94
96
  | `.agent/implement-review.html` | The page with the open questions. |
95
97
  | `.agent/implement-answers.json` | The answers: `{"v": 1, "stage": "implement", "submitted": …, "revision": …, "answers": {…}}`. |
@@ -154,8 +156,8 @@ The end of run starts only when every ticket is merged and every slot is idle. I
154
156
  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; the integrated tip gets the full gate in the next step. 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.
155
157
  3. **Full gate.** A red result saves the exact gate log and sends one repair batch to the final fixer (`prompts/final-gate-fixer.md`). An evidenced no-op is allowed when no code change is needed: it consumes the same repair attempt and reruns the full gate on the unchanged tip. Its commits are attributed to tickets and obey the same locked-file checks as final-review fixes. The driver reruns the full gate on the repaired tip. A second red result asks `final-ticket-blocked` with `retry` or `edit`; retry grants one further repair batch using the saved log. This allowance is independent of completed-ticket rounds and final-review rounds. Only a green integrated tip starts 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.
156
158
  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.
157
- 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`.
158
- 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`.
159
+ 5. Each critical or important finding the scoped review leaves open, a must-fix item too, asks one `final-finding-open-<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 that no answer ships with; `accept` and `follow-up` ship the PR with the finding. A finding once shipped asks no question again in the run. There is no third review unless a `retry` asks for one.
160
+ 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`: as draft when a critical or must-fix finding that a ruling shipped is open, ready for review otherwise, and the ledger says why. Once the pr-writer's body is valid and before it opens the PR, it files each finding answered `follow-up` as an issue with `gh issue create`, and the PR body's rulings and `summary.md` link the issue. The issue body carries a marker of the run and the question; a run that stopped before it kept the URL finds the issue by that marker instead of filing it twice. A local run without `--push` files nothing. 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`.
159
161
 
160
162
  History rules:
161
163
 
@@ -195,7 +197,7 @@ A file that does not exist is skipped. An error in one of them names the file, a
195
197
  | `anthropic` | `claude -p` | low, medium, high, xhigh, max |
196
198
  | `openai` | `codex exec --json` | minimal, low, medium, high, xhigh |
197
199
 
198
- 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.
200
+ 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 `arbiter` list holds the most capable model of each provider; the arbiter runs on its first entry on another provider than the first `implementer` entry. 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.
199
201
 
200
202
  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.
201
203
 
@@ -207,7 +209,7 @@ The defaults need both `claude` and `codex` on PATH. The `openai` defaults name
207
209
 
208
210
  Each agent writes one JSON report. The schema of a role is the `json` block of its prompt template, so the agent reads the text that the driver enforces. `driver_report.py` `validate` checks the report against the schema, against git and against the log of the agent. A field that the schema does not name is ignored.
209
211
 
210
- Every report has `status` (`DONE`, `DONE_WITH_CONCERNS`, `NEEDS_CONTEXT`, `BLOCKED`), `files` and `concerns`. A role that commits also has `commits`. A read-only role (reviewer, final-reviewer, the three lenses, pr-writer) has none: a reviewer reads `commits` as the commits it reviews, and the driver would refuse each of them as not new. The driver checks instead that a read-only role leaves its slot on the tip it got, with a clean tree.
212
+ Every report has `status` (`DONE`, `DONE_WITH_CONCERNS`, `NEEDS_CONTEXT`, `BLOCKED`), `files` and `concerns`. A role that commits also has `commits`. A read-only role (reviewer, final-reviewer, the three lenses, pr-writer, arbiter) has none: a reviewer reads `commits` as the commits it reviews, and the driver would refuse each of them as not new. The driver checks instead that a read-only role leaves its slot on the tip it got, with a clean tree.
211
213
 
212
214
  | Role | Template | More fields | Checks after the schema |
213
215
  |---|---|---|---|
@@ -219,6 +221,7 @@ Every report has `status` (`DONE`, `DONE_WITH_CONCERNS`, `NEEDS_CONTEXT`, `BLOCK
219
221
  | final-spec, final-correctness, final-structure | `prompts/final-lens.md`, with the lines of `prompts/lens-<source>.md` | `findings` | None. |
220
222
  | final-reviewer (the scoped review) | `prompts/final-reviewer.md` | `findings`, `resolved_must_fix` | None. |
221
223
  | pr-writer | `prompts/pr-writer.md` | `body` | None. |
224
+ | arbiter | `prompts/arbiter.md` | `rulings` (`question`, `ruling`: `accept` or `follow-up`, `reason`, `cost`) | One ruling for each open question, its id as the list gives it. |
222
225
  | fixer of the final review | `prompts/final-fixer.md` | `green`; `commits` is a list of (`sha`, `ticket`) | Each new commit on the branch is in `commits`, with a ticket of the run. |
223
226
  | conflict | `prompts/conflict.md`, `prompts/rebase-conflict.md` | none | With DONE: one commit or more. No locked file may change. |
224
227
 
@@ -226,14 +229,19 @@ For each role that commits, every commit in `commits` must be new since the role
226
229
 
227
230
  ## Question kinds
228
231
 
232
+ ### The driver rules first
233
+
234
+ A stop whose question recommends `retry` does not park the run, and neither does an open final finding once the retries are spent. The driver answers it with `retry`, the one option it may take itself, writes the same `Ruling:` sentence an operator's answer writes, ending in `Ruled by the driver, not the operator.`, and goes on in the same process, as the next invocation would after `--answer`. Today that is `retry` for `ticket-blocked`; `spec-ambiguous` recommends no option, so it still asks. The driver rules on at most `--retries` stops (default 2) of one ticket, and as many of the end of run. The next stop of that ticket asks the operator, with exit 2; but a `finding-open` question goes to the **arbiter** (`prompts/arbiter.md`), unless `--ask`. The arbiter is one read-only agent on the first `arbiter` entry on another provider than the first `implementer` entry (else the first `arbiter` entry). It reads each finding's evidence and the ledger and rules `accept` or `follow-up` with a reason and the cost if it is wrong; its ruling ends in `Ruled by the arbiter, not the operator: <reason>. Cost if wrong: <cost>.` An arbiter whose rerun fails too leaves the questions to the operator, with a ledger line. `edit` is not an option of `finding-open`: editing the spec is what the operator does after the run. The operator reads the rulings of the driver and the arbiter where the run ends: in `summary.md` under `Driver decisions, taken without the operator:` and in the PR body with the other rulings. On the box, 23 answers of 23 were `retry` and each waited hours for the operator (jesdi/agent-ops retro, 2026-11-14).
235
+
229
236
  A question is a bounded choice for the operator. `driver_decisions.py` `KINDS` holds each kind with its fixed sentences.
230
237
 
231
238
  | Kind | Question id | Asked when | Run exit | Options |
232
239
  |---|---|---|---|---|
233
240
  | `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`. |
234
- | `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 did too (the same model for a timeout or moved branch, the next entry otherwise); 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. |
241
+ | `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 did too (the same model for a timeout or moved branch, the next entry otherwise); or the integration gate stays red after its repair. The subject names the role and the reason, or the gate. | 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. `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. |
242
+ | `finding-open` | `final-finding-open-<n>` | A critical or important finding, a must-fix one too, is open after the scoped review of the final fix batch: one question per finding, the subject is the finding as `<title> (<file>)`, with no line, so a fix batch that moves it does not ask again; the evidence is its findings file. | 2 | `retry` (recommended): one more fix batch and scoped review. `accept`: the PR ships with the finding open, listed in its rulings; a critical or must-fix one opens it as draft. `follow-up`: as `accept`, and the driver files the finding as an issue before it opens the PR. |
235
243
 
236
- `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`.
244
+ An older run may hold an open `final-ticket-blocked-<n>` question on a finding: it keeps its `retry` and `edit`.
237
245
 
238
246
  `n` counts the questions of that ticket and kind in the run, so an id is never used twice. An open question of a ticket that has merged is dropped, with a ledger line: it leaves `decisions.json` and parks no run.
239
247
 
@@ -20,12 +20,12 @@ has passed. The review rounds adapt superpowers' subagent-driven-development
20
20
  (obra/superpowers, MIT).
21
21
  -->
22
22
 
23
- Run the driver. It makes every choice of the run; you start it and relay its result.
23
+ Run the driver. It makes every choice of the run: it answers its own `retry` questions, and its arbiter agent rules on the final findings its retries leave open. You start it and relay its result and its decisions.
24
24
 
25
25
  1. In the PR worktree, run `sh <skill-dir>/run.sh` with the flags the operator gave, unchanged. `<skill-dir>` is the directory of this file. The driver needs `--gate`, `--fast-gate` and `--spec`: ask the operator for a flag that is missing. A run can take hours: run the command in the background and wait for it to exit.
26
- 2. When it exits, relay `.agent/implement/summary.md` and the exit code: 0 is done, 1 is a BLOCKED ticket, 2 is parked on questions, 3 is invalid input, 4 is stopped by a CLI failure (after the fix, the same command resumes). Relay the lines the driver printed after the summary too. With exit 0 and a PR URL such as `https://github.com/jesdi/demo/pull/61`, tell the operator to start the babysitter: run `/babysit-pr https://github.com/jesdi/demo/pull/61`.
26
+ 2. When it exits, relay `.agent/implement/summary.md`, with its `Driver decisions` list whole, and the exit code: 0 is done, 1 is a BLOCKED ticket, 2 is parked on questions, 3 is invalid input, 4 is stopped by a CLI failure (after the fix, the same command resumes). Relay the lines the driver printed after the summary too. With exit 0 and a PR URL such as `https://github.com/jesdi/demo/pull/61`, tell the operator to start the babysitter: run `/babysit-pr https://github.com/jesdi/demo/pull/61`. When the driver opened the PR as a draft, say so and why: no agent merges a draft, so it waits for the operator's review.
27
27
  3. With exit 2, and with exit 1 when the driver printed questions, show the operator those questions. When the operator answers, run the same command again with one `--answer <question id>=<option id>` for each answer.
28
28
 
29
- Do not answer a question for the operator. Do not edit `.agent/implement/`, the code or the branches during a run.
29
+ Answer no question the driver left open: it has spent its own retries on it. Do not edit `.agent/implement/`, the code or the branches during a run.
30
30
 
31
31
  [README.md](README.md) has each flag, the exit codes, the files of a run and the method.
@@ -2,7 +2,7 @@
2
2
  """implement-spec driver: validate the ticket set and the environment, then walk the ticket graph.
3
3
 
4
4
  sh run.sh --gate COMMAND --fast-gate COMMAND --spec FILE [--tickets DIR] [--models FILE] [--parallel N] [--prepare COMMAND]
5
- [--timeout ROLE=MINUTES] [--answer QUESTION=OPTION] [--unattended [--stage-json FILE]] [--push]
5
+ [--timeout ROLE=MINUTES] [--answer QUESTION=OPTION] [--retries N] [--ask] [--unattended [--stage-json FILE]] [--push]
6
6
  [--base BRANCH] [--dry-run]
7
7
 
8
8
  Run it in the PR worktree. Exit 0 = every ticket merged (and pushed, when unattended), 1 = a ticket or the end of
@@ -23,6 +23,7 @@ from pathlib import Path
23
23
 
24
24
  import driver_agents
25
25
  import driver_answers
26
+ import driver_arbiter
26
27
  import driver_decisions
27
28
  import driver_dispute
28
29
  import driver_final
@@ -439,15 +440,10 @@ def _publish_questions(run: dict) -> str:
439
440
  return ""
440
441
 
441
442
 
442
- def _apply_answers(state: driver_state.State, args) -> list[str]:
443
- """Turn each answer that counts into a ruling and let its ticket go on; [] or the errors that stop the run."""
444
- _drop_merged(state)
445
- run = state.read()["run"]
446
- questions, document = run["questions"], driver_decisions.document(run)
447
- if errors := driver_answers.given(args.answer, document):
448
- return errors
449
- answers, ignored = driver_answers.read(document)
450
- rulings, moved = driver_decisions.apply(questions, answers)
443
+ def _settle(state: driver_state.State, questions: list[dict], answers: dict, ignored: list[str], by: str = "",
444
+ why: dict[str, str] | None = None) -> None:
445
+ """Turn each answer into a ruling and let its ticket go on."""
446
+ rulings, moved = driver_decisions.apply(questions, answers, by, why)
451
447
  # The ledger comes first: a run that stops between the two writes gives a ruling twice, and never an answer
452
448
  # that no ledger line names.
453
449
  for sentence in ignored + rulings:
@@ -459,31 +455,68 @@ def _apply_answers(state: driver_state.State, args) -> list[str]:
459
455
  driver_run.record_of(new, number).update(fields)
460
456
 
461
457
  state.update(change)
458
+
459
+
460
+ def _apply_answers(state: driver_state.State, args) -> list[str]:
461
+ """Turn each answer that counts into a ruling and let its ticket go on; [] or the errors that stop the run."""
462
+ _drop_merged(state)
463
+ run = state.read()["run"]
464
+ questions, document = run["questions"], driver_decisions.document(run)
465
+ if errors := driver_answers.given(args.answer, document):
466
+ return errors
467
+ _settle(state, questions, *driver_answers.read(document))
462
468
  error = _publish_questions(run)
463
469
  return [error] if error else []
464
470
 
465
471
 
472
+ def _rule(run: Run) -> bool:
473
+ """The driver answers each open question that recommends `retry` with it, at most `--retries` stops per ticket and
474
+ for the end of run; then, unless `--ask`, the arbiter rules on the questions that are its own. True: one of them
475
+ ruled, so the run goes on with no operator."""
476
+ questions = run.state.read()["run"]["questions"]
477
+ answers, why, by = driver_decisions.automatic(questions, run.args.retries), {}, driver_decisions.DRIVER
478
+ if not (answers or run.args.ask):
479
+ answers, why = _arbitrate(run)
480
+ by, questions = driver_decisions.ARBITER, run.state.read()["run"]["questions"]
481
+ if answers:
482
+ _settle(run.state, questions, answers, [], by, why)
483
+ print(f"implement-spec: the {by} ruled on {len(answers)} question{'s' * (len(answers) > 1)} and goes on",
484
+ flush=True)
485
+ return bool(answers)
486
+
487
+
488
+ def _arbitrate(run: Run) -> tuple[dict[str, str], dict[str, str]]:
489
+ """The arbiter's answers; none when a CLI failure stops it, which halts the run as it would any agent."""
490
+ try:
491
+ return driver_arbiter.rule(run)
492
+ except Halted as halted:
493
+ _halt(run, "End of run", str(halted))
494
+ return {}, {}
495
+
496
+
466
497
  # ---------------------------------------------------------------- the end of the process
467
498
 
468
- def _write_stage(path: str, code: int, open_questions: int, blocked: list[str]) -> None:
469
- """stage.json tells the dispatcher of an unattended run how the run ended."""
499
+ def _write_stage(path: str, code: int, open_questions: int, blocked: list[str], record: dict) -> None:
500
+ """stage.json tells the dispatcher of an unattended run how the run ended; a done run says whether its PR is a
501
+ draft and how many questions were ruled with no operator."""
470
502
  if code == 2:
471
503
  body = {"status": "awaiting-review", "artifact": str(PAGE), "open_questions": open_questions}
472
504
  elif code == 0:
473
- body = {"status": "done"}
505
+ body = {"status": "done", "draft": record["final"]["draft"],
506
+ "decisions": len(driver_decisions.without_operator(record["questions"]))}
474
507
  else:
475
508
  body = {"status": "blocked", "blocked": blocked}
476
509
  Path(path).parent.mkdir(parents=True, exist_ok=True)
477
510
  Path(path).write_text(json.dumps({"stage": "implement", **body}, indent=1) + "\n")
478
511
 
479
512
 
480
- def _tell(args, code: int, open_questions: list[dict], blocked: list[str], pushed: bool) -> None:
513
+ def _tell(args, code: int, open_questions: list[dict], blocked: list[str], record: dict) -> None:
481
514
  """Print the open questions for the operator, or write stage.json for the dispatcher of an unattended run."""
482
515
  if not args.unattended:
483
516
  print(driver_decisions.text(open_questions, str(driver_answers.FILE), str(PAGE)), end="")
484
- elif args.stage_json and (code or pushed):
517
+ elif args.stage_json and (code or record["final"]["pushed"]):
485
518
  # Exit 0 with nothing pushed is not `done` for the dispatcher: it gets no file.
486
- _write_stage(args.stage_json, code, len(open_questions), blocked)
519
+ _write_stage(args.stage_json, code, len(open_questions), blocked, record)
487
520
 
488
521
 
489
522
  def _halted_exit(halted: list[str], final: dict) -> int:
@@ -508,7 +541,7 @@ def _exit_code(final: dict, args, end_blocked: bool) -> int:
508
541
  blocked.append(FINAL)
509
542
  open_questions = driver_decisions.document(final["run"])["questions"]
510
543
  code = 2 if driver_decisions.parked(final["run"]["questions"]) else int(bool(blocked))
511
- _tell(args, code, open_questions, blocked, bool(final["run"]["final"]["pushed"]))
544
+ _tell(args, code, open_questions, blocked, final["run"])
512
545
  return code
513
546
 
514
547
 
@@ -518,25 +551,42 @@ def _record_skipped(skipped: list[str]) -> None:
518
551
  ledger(sentence)
519
552
 
520
553
 
521
- def _run(tickets: list[Ticket], models: dict[str, list[str]], skipped: list[str], args, kept: dict[str, int],
522
- pr: str) -> int:
523
- state = driver_state.State(STATE)
524
- slots = 1 if args.only else min(args.parallel, len(tickets))
525
- errors = _resume(tickets, state, pr, slots, args, kept)
526
- errors = errors or _apply_answers(state, args)
554
+ def _once(tickets: list[Ticket], run: Run, slots: int) -> tuple[bool, list[str]] | int:
555
+ """Resume, apply the answers and do the work once: what `_work` returns, or exit 3 with each error printed."""
556
+ args = run.args
557
+ errors = _resume(tickets, run.state, run.pr, slots, args, run.kept) or _apply_answers(run.state, args)
527
558
  if errors:
528
559
  print("\n".join(errors))
529
560
  return 3
530
- run = Run(args, models, state, pr, kept)
531
- _record_skipped(skipped)
532
561
  if args.unattended and args.stage_json:
533
562
  Path(args.stage_json).unlink(missing_ok=True) # the file tells how this run ends, never an earlier one
534
563
  try:
535
- end_blocked, lines = _work(tickets, slots, run)
564
+ return _work(tickets, slots, run)
536
565
  except driver_slots.PreparationError as error:
537
566
  print(f"implement-spec: {error}; fix slot preparation and run the same command to resume")
538
567
  return 3
539
- final = state.read()
568
+
569
+
570
+ def _run(tickets: list[Ticket], models: dict[str, list[str]], skipped: list[str], args, kept: dict[str, int],
571
+ pr: str) -> int:
572
+ state = driver_state.State(STATE)
573
+ slots = 1 if args.only else min(args.parallel, len(tickets))
574
+ _record_skipped(skipped)
575
+ while True:
576
+ run = Run(args, models, state, pr, kept)
577
+ done = _once(tickets, run, slots)
578
+ if isinstance(done, int):
579
+ return done
580
+ if run.halted or not _rule(run):
581
+ break
582
+ # The driver's own answer resumes the run as the operator's would on the next invocation.
583
+ args.answer, kept = [], driver_state.kept(state.read())
584
+ return _finish(run, args, *done)
585
+
586
+
587
+ def _finish(run: Run, args, end_blocked: bool, lines: list[str]) -> int:
588
+ """Write and print the summary, and return the exit code."""
589
+ final = run.state.read()
540
590
  summary = driver_summary.render(final)
541
591
  (OUT / "summary.md").write_text(summary)
542
592
  print(summary + "".join(line + "\n" for line in lines), end="")
@@ -583,6 +633,12 @@ def _arguments(argv: list[str] | None) -> argparse.Namespace:
583
633
  parser.add_argument("--answer", action="append", type=driver_answers.pair, default=[],
584
634
  metavar="QUESTION=OPTION", help="the answer to one open question of "
585
635
  f"{DECISIONS}, repeatable; it goes to {driver_answers.FILE}")
636
+ parser.add_argument("--retries", type=int, default=int(os.environ.get("IMPLEMENT_SPEC_RETRIES", 2)), metavar="N",
637
+ help="the stops of one ticket, or of the end of run, that the driver answers itself with the "
638
+ "recommended option before it asks the operator (default: IMPLEMENT_SPEC_RETRIES, else 2)")
639
+ parser.add_argument("--ask", action=argparse.BooleanOptionalAction,
640
+ default=os.environ.get("IMPLEMENT_SPEC_ASK") == "1", help="once the retries are spent, ask "
641
+ "the operator instead of the arbiter agent (default: IMPLEMENT_SPEC_ASK=1, else off)")
586
642
  parser.add_argument("--unattended", action="store_true", help="at a question, print no question: write "
587
643
  "--stage-json for the dispatcher, which gives the answers file to the next run")
588
644
  parser.add_argument("--stage-json", metavar="FILE", help="with --unattended: where the driver writes how a "
@@ -40,7 +40,7 @@ LENSES = {
40
40
  "final-structure": Lens("structure", "deep-quality-review", "SKILL.md", False, False)}
41
41
  # Minutes per role.
42
42
  TIMEOUTS = {"test-writer": 30, "implementer": 90, "reviewer": 45, "fixer": 60, "final-reviewer": 60,
43
- **dict.fromkeys(LENSES, 60), "conflict": 30, "pr-writer": 20}
43
+ **dict.fromkeys(LENSES, 60), "conflict": 30, "pr-writer": 20, "arbiter": 30}
44
44
  PROVIDERS = {"anthropic": ("claude", ("low", "medium", "high", "xhigh", "max")),
45
45
  "openai": ("codex", ("minimal", "low", "medium", "high", "xhigh"))}
46
46
  # USD per million tokens at the API list price; the cached part of the input costs `cached_input`. A
@@ -49,7 +49,7 @@ PRICES = {"gpt-6-astra": {"input": 10.0, "cached_input": 1.0, "output": 50.0},
49
49
  "gpt-6.1-sol": {"input": 2.0, "cached_input": 0.10, "output": 10.0}}
50
50
  # The name of each token count in the agent record, and its key in the `usage` of a codex turn.
51
51
  _USAGE = {"input": "input_tokens", "cached_input": "cached_input_tokens", "output": "output_tokens"}
52
- READ_ONLY = ("reviewer", "final-reviewer", *LENSES, "pr-writer")
52
+ READ_ONLY = ("reviewer", "final-reviewer", *LENSES, "pr-writer", "arbiter")
53
53
  PREFLIGHT = "implement-spec preflight: reply with the word OK. Read no file and run no command.\n"
54
54
  # The time limit of one preflight call: a CLI that gives no answer in this time fails the preflight.
55
55
  PREFLIGHT_MINUTES = 5
@@ -129,22 +129,27 @@ def _is_list(entries: object) -> bool:
129
129
  return isinstance(entries, list) and bool(entries) and all(isinstance(entry, str) for entry in entries)
130
130
 
131
131
 
132
- def other_provider_entries(models: dict[str, list[str]]) -> list[str]:
133
- """The entries of the `final-reviewer` list on another provider than the implementer's first entry: the correctness
134
- lens and the scoped review run and rerun on these when there is one."""
132
+ def other_provider_entries(models: dict[str, list[str]], role: str) -> list[str]:
133
+ """The entries of the `role` list on another provider than the implementer's first entry: the correctness lens and
134
+ the scoped review run and rerun on those of `final-reviewer` when there is one, the arbiter on its own."""
135
135
  own = split(models["implementer"][0])[0]
136
- return [entry for entry in models["final-reviewer"] if split(entry)[0] != own]
136
+ return [entry for entry in models[role] if split(entry)[0] != own]
137
137
 
138
138
 
139
139
  def other_provider_entry(models: dict[str, list[str]]) -> str:
140
140
  """The other-provider entry of the `final-reviewer` list, its first one; "" when there is none."""
141
- return next(iter(other_provider_entries(models)), "")
141
+ return next(iter(other_provider_entries(models, "final-reviewer")), "")
142
142
 
143
143
 
144
144
  def correctness_entries(models: dict[str, list[str]]) -> list[str]:
145
145
  """The entries of the correctness lens and the scoped review: the other-provider ones, or, when the config has none
146
146
  or none passed the preflight, the whole `final-reviewer` list (the ledger and the PR body say so)."""
147
- return other_provider_entries(models) or models["final-reviewer"]
147
+ return preferred_entries(models, "final-reviewer")
148
+
149
+
150
+ def preferred_entries(models: dict[str, list[str]], role: str) -> list[str]:
151
+ """The entries of `role` on another provider than the implementer's first entry, else its whole list."""
152
+ return other_provider_entries(models, role) or models[role]
148
153
 
149
154
 
150
155
  def lens_entries(models: dict[str, list[str]], role: str) -> list[str]:
@@ -251,15 +256,26 @@ def last_message(report: str | Path) -> str:
251
256
  return f"{report}.last"
252
257
 
253
258
 
259
+ def _spoken(log: Path) -> str:
260
+ """The JSON object in the `result` of the last claude stream-json line: a report the agent gave as its answer
261
+ and did not write; "" when there is none."""
262
+ with contextlib.suppress(OSError, ValueError, AttributeError, IndexError):
263
+ said = str(json.loads(log.read_text(errors="replace").splitlines()[-1]).get("result"))
264
+ found = said[said.index("{"):said.rindex("}") + 1]
265
+ json.loads(found)
266
+ return found
267
+ return ""
268
+
269
+
254
270
  def settle_report(report: Path) -> None:
255
- """The report is the one the agent wrote when it parses, else the saved last message, when there is one."""
256
- last = Path(last_message(report))
257
- if not last.exists():
258
- return
271
+ """The report is the one the agent wrote when it parses; else the last message codex saved, or the JSON object a
272
+ claude agent gave as its answer in the log next to the report, when there is one."""
259
273
  with contextlib.suppress(OSError, ValueError):
260
274
  json.loads(report.read_text())
261
275
  return
262
- report.write_text(last.read_text())
276
+ last = Path(last_message(report))
277
+ if said := last.read_text() if last.exists() else _spoken(report.with_suffix(".log")):
278
+ report.write_text(said)
263
279
 
264
280
 
265
281
  def render(name: str, values: dict[str, str]) -> str:
@@ -0,0 +1,43 @@
1
+ """The arbiter: when the driver's own retries are spent, one read-only agent rules on each open question that
2
+ driver_decisions.arbitrated names, on another provider than the implementer, with a reason and the cost if it is
3
+ wrong. An arbiter that cannot rule leaves the questions to the operator."""
4
+ from __future__ import annotations
5
+
6
+ import driver_agents
7
+ import driver_decisions
8
+ from driver_run import FINAL, OUT, Blocked, Call, Run, ledger
9
+
10
+
11
+ def _values(run: Run, asked: list[dict]) -> dict[str, str]:
12
+ tip = run.tip()
13
+ return {"spec": run.args.spec, "tickets": run.args.tickets, "pr_branch": run.pr, "branch": run.pr,
14
+ "start_sha": tip, "ledger": str(OUT / "ledger.md"),
15
+ "questions": "".join(f"- {q['id']}: {q['title']}. Evidence: {', '.join(q['evidence'])}\n" for q in asked)}
16
+
17
+
18
+ def _why(ruling: dict) -> str:
19
+ """The end of the ruling sentence: the reason of the arbiter and the cost if it is wrong."""
20
+ return f": {ruling['reason'].rstrip('.')}. Cost if wrong: {ruling['cost'].rstrip('.')}"
21
+
22
+
23
+ def rule(run: Run) -> tuple[dict[str, str], dict[str, str]]:
24
+ """(question id -> the arbiter's option, question id -> the end of its ruling sentence); both {} when no question
25
+ is the arbiter's or the arbiter could not rule."""
26
+ asked = driver_decisions.arbitrated(run.state.read()["run"]["questions"])
27
+ if not asked:
28
+ return {}, {}
29
+ entries = driver_agents.preferred_entries(run.models, "arbiter")
30
+ call = Call("arbiter", FINAL, ".", _values(run, asked), entry=entries[0], entries=entries, asks=False,
31
+ name=f"arbiter-{asked[0]['stop']}", check={"questions": [q["id"] for q in asked]})
32
+ try:
33
+ report = run.read_only(FINAL, ".", run.pr, call.values["start_sha"], lambda: run.agent(call))
34
+ except Blocked as blocked:
35
+ ledger(f"End of run: the arbiter could not rule, so the operator decides: {blocked}.")
36
+ return {}, {}
37
+ return _answers(report["rulings"], call.check["questions"])
38
+
39
+
40
+ def _answers(rulings: list[dict], asked: list[str]) -> tuple[dict[str, str], dict[str, str]]:
41
+ """The rulings on the questions in `asked`, as `rule` returns them."""
42
+ rulings = [one for one in rulings if one["question"] in asked]
43
+ return {one["question"]: one["ruling"] for one in rulings}, {one["question"]: _why(one) for one in rulings}