@jesdi/skills 0.0.77 → 0.0.78

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +3 -2
  2. package/package.json +1 -1
  3. package/skills/implement-spec/ARCHITECTURE.md +102 -54
  4. package/skills/implement-spec/README.md +53 -51
  5. package/skills/implement-spec/SKILL.md +5 -6
  6. package/skills/implement-spec/driver.py +67 -153
  7. package/skills/implement-spec/driver_agents.py +75 -25
  8. package/skills/implement-spec/driver_decisions.py +92 -199
  9. package/skills/implement-spec/driver_dispute.py +189 -0
  10. package/skills/implement-spec/driver_final.py +196 -97
  11. package/skills/implement-spec/driver_fixloop.py +102 -192
  12. package/skills/implement-spec/driver_legacy.py +73 -5
  13. package/skills/implement-spec/driver_locked.py +186 -0
  14. package/skills/implement-spec/driver_merge.py +3 -48
  15. package/skills/implement-spec/driver_report.py +84 -64
  16. package/skills/implement-spec/driver_review.py +12 -119
  17. package/skills/implement-spec/driver_run.py +167 -130
  18. package/skills/implement-spec/driver_state.py +11 -9
  19. package/skills/implement-spec/models.json +0 -2
  20. package/skills/implement-spec/prompts/arbitration.md +34 -0
  21. package/skills/implement-spec/prompts/conflict.md +1 -0
  22. package/skills/implement-spec/prompts/correction.md +7 -4
  23. package/skills/implement-spec/prompts/elsewhere.md +6 -0
  24. package/skills/implement-spec/prompts/final-fixer.md +1 -1
  25. package/skills/implement-spec/prompts/final-lens.md +40 -0
  26. package/skills/implement-spec/prompts/final-reviewer.md +7 -7
  27. package/skills/implement-spec/prompts/fixer.md +2 -2
  28. package/skills/implement-spec/prompts/implementer.md +1 -1
  29. package/skills/implement-spec/prompts/lens-copy.md +1 -0
  30. package/skills/implement-spec/prompts/lens-correctness.md +8 -0
  31. package/skills/implement-spec/prompts/lens-spec.md +2 -0
  32. package/skills/implement-spec/prompts/lens-structure.md +2 -0
  33. package/skills/implement-spec/prompts/rebase-conflict.md +1 -0
  34. package/skills/implement-spec/prompts/rereview.md +0 -1
  35. package/skills/implement-spec/prompts/rerun.md +1 -1
  36. package/skills/implement-spec/prompts/reviewer.md +3 -6
  37. package/skills/implement-spec/prompts/ruled.md +3 -0
  38. package/skills/implement-spec/prompts/test-writer.md +4 -5
  39. package/skills/implement-spec/tests/test_agents.py +23 -22
  40. package/skills/implement-spec/tests/test_amendments.py +6 -48
  41. package/skills/implement-spec/tests/test_arbitration.py +314 -0
  42. package/skills/implement-spec/tests/test_cli.py +3 -3
  43. package/skills/implement-spec/tests/test_decisions.py +251 -374
  44. package/skills/implement-spec/tests/test_driver.py +22 -50
  45. package/skills/implement-spec/tests/test_final.py +45 -77
  46. package/skills/implement-spec/tests/test_fixloop.py +400 -633
  47. package/skills/implement-spec/tests/test_landing.py +23 -126
  48. package/skills/implement-spec/tests/test_lenses.py +217 -0
  49. package/skills/implement-spec/tests/test_merge.py +0 -43
  50. package/skills/implement-spec/tests/test_models.py +50 -1
  51. package/skills/implement-spec/tests/test_report.py +9 -23
  52. package/skills/implement-spec/tests/test_review.py +15 -153
  53. package/skills/implement-spec/tests/test_review_page.py +7 -3
  54. package/skills/implement-spec/tests/test_scoped.py +125 -0
  55. package/skills/implement-spec/tests/test_state.py +8 -3
  56. package/skills/implement-spec/tests/test_stops.py +43 -61
  57. package/skills/implement-spec/tests/test_tidy.py +77 -98
  58. package/skills/implement-spec/tests/test_walk.py +7 -6
  59. package/skills/review-page/SKILL.md +1 -1
  60. package/skills/to-tickets/SKILL.md +1 -1
  61. package/skills-manifest.json +7 -7
  62. package/skills/implement-spec/prompts/corrected.md +0 -3
  63. package/skills/implement-spec/prompts/correctness.md +0 -42
  64. package/skills/implement-spec/prompts/final-scoped.md +0 -1
  65. package/skills/implement-spec/prompts/full-review.md +0 -2
  66. package/skills/implement-spec/prompts/overruled.md +0 -7
  67. package/skills/implement-spec/prompts/rejected.md +0 -1
  68. package/skills/implement-spec/prompts/restored-red.md +0 -3
  69. package/skills/implement-spec/prompts/restored.md +0 -3
  70. package/skills/implement-spec/prompts/stands.md +0 -2
@@ -8,28 +8,34 @@ from __future__ import annotations
8
8
  import argparse
9
9
  import json
10
10
  import os
11
- import subprocess
12
11
  import threading
13
12
  import time
14
13
  from contextlib import contextmanager
15
- from dataclasses import dataclass, field
14
+ from dataclasses import dataclass, field, replace
16
15
  from pathlib import Path
17
- from typing import Callable, Iterator, NamedTuple, TypeVar
16
+ from typing import Callable, Iterator, NamedTuple, NoReturn, TypeVar
18
17
 
19
18
  import driver_agents
20
19
  import driver_decisions
21
20
  import driver_gate
22
- import driver_merge
21
+ import driver_locked
23
22
  import driver_report
24
23
  import driver_review
25
24
  import driver_slots
26
25
  import driver_state
26
+ from driver_decisions import FINAL, Resume
27
27
  from driver_names import Names
28
- from driver_slots import git, names
28
+ from driver_slots import git
29
29
 
30
30
  OUT = Path(".agent/implement")
31
- FINAL = "final" # the end of run has its reports and gate records under this name, as a ticket has under its number
31
+ FINAL_RESUME = Resume("pending") # a `retry` of the end of run: it goes on from where its state is
32
32
  _LEDGER = threading.Lock()
33
+ _ASKS = threading.Lock() # the lenses of the final review run at the same time
34
+ STOPS = ("BLOCKED", "NEEDS_CONTEXT")
35
+ _COMMITS = ("test-writer", "implementer", "fixer") # the ticket agents whose commits are the ticket's work
36
+ # The phase that runs a ticket agent again: the fixer's round runs again after a review of the tip it left.
37
+ _RETRY = {"test-writer": "test-writer", "implementer": "implement", "reviewer": "review", "fixer": "review",
38
+ "conflict": "merge"}
33
39
  T = TypeVar("T")
34
40
 
35
41
 
@@ -37,14 +43,6 @@ class Blocked(Exception):
37
43
  """A ticket, or the end of run, cannot go on. The message says why."""
38
44
 
39
45
 
40
- class Stopped(Blocked):
41
- """An agent's accepted report says BLOCKED or NEEDS_CONTEXT. `report` is that report."""
42
-
43
- def __init__(self, why: str, report: dict):
44
- super().__init__(why)
45
- self.report = report
46
-
47
-
48
46
  class Halted(Exception):
49
47
  """The CLI of an agent failed with no report, two times: a model the account cannot use, a CLI that is not
50
48
  signed in. The run starts no other agent and ends with exit 4; the ticket keeps its phase for the next run."""
@@ -69,21 +67,47 @@ def ledger(sentence: str) -> int:
69
67
  return sum(1 for _ in file)
70
68
 
71
69
 
72
- def _owner(number: str) -> str:
73
- return "End of run" if number == FINAL else f"Ticket {number}"
70
+ _owner = driver_decisions.owner
74
71
 
75
72
 
76
- def _gate_record(state: dict, number: str) -> dict:
77
- """The record of state.json that holds the green gates of `number`."""
73
+ def record_of(state: dict, number: str) -> dict:
74
+ """The record of `number` in state.json: its ticket record, or `run.final` for the end of run. Each has its
75
+ `phase`, which an answer sets, and its `green_gates`."""
78
76
  return state["run"]["final"] if number == FINAL else state["tickets"][number]
79
77
 
80
78
 
79
+ @dataclass(frozen=True)
80
+ class Call:
81
+ """One agent of a ticket or of the end of run, as `Run.agent` runs it with its one rerun."""
82
+ role: str
83
+ number: str # the ticket, or FINAL
84
+ slot: str
85
+ values: dict[str, str] # the pointers of its prompt
86
+ notes: tuple | list = () # templates whose lines the first prompt gets after the role's own
87
+ entry: str = "" # the model entry, when it is not the first of the role's list
88
+ entries: list[str] | None = None # the list `entry` is from, when it is not the role's
89
+ fix_round: int = 0 # the K of the files `<role>-<K>.json`, `.log` and `.prompt.md`
90
+ check: dict = field(default_factory=dict) # more context for the report validation (driver_report.validate)
91
+ template: str = "" # the prompt and schema, when it is not the one named after the role
92
+ alone: Callable[[], bool] = lambda: True # whether no other agent works in the slot now
93
+ detached: bool = False # the agent works on a detached HEAD
94
+ name: str = "" # the name of its files, when it is not `<role>-<fix_round>`
95
+ # The role that a `retry` of its `ticket-blocked` question runs again from the start commit, when the agent runs
96
+ # for that role (an arbitration, a correction): its own work is not kept.
97
+ retry: str = ""
98
+ # A BLOCKED report that disputes a locked test is accepted, not a stop: `driver_dispute.agent` settles it.
99
+ may_dispute: bool = False
100
+ # Reads the locked-file check of its report when the agent ends, given the validation context, to which it may add
101
+ # (driver_report.validate); by default that of a ticket agent.
102
+ locked: Callable[[dict], driver_locked.Locked | None] | None = None
103
+
104
+
81
105
  class Ask(NamedTuple):
82
- """The questions a ticket thread wants the operator to answer when its ticket blocks."""
106
+ """The questions a ticket thread, or the end of run, wants the operator to answer when it blocks."""
83
107
  kind: str
84
108
  subjects: list[str] # one question per subject
85
109
  report: str # the evidence
86
- fields: dict # what the ticket record gets with the stop
110
+ resume: Resume # the record gets its tip and round with the stop, and all of it with a `retry` or a `keep-test`
87
111
 
88
112
 
89
113
  @dataclass
@@ -104,42 +128,46 @@ class Run:
104
128
  def tip(self) -> str:
105
129
  return git(".", "rev-parse", f"refs/heads/{self.pr}").stdout.strip()
106
130
 
107
- def ask(self, number: str, kind: str, subjects: list[str], report: str, **fields) -> None:
108
- self.asks[number] = Ask(kind, subjects, report, fields)
109
-
110
- def agent(self, role: str, number: str, slot: str, values: dict[str, str], **options) -> dict:
111
- """Run one role and return its accepted report. `options` are those of `_attempts`."""
112
- if role == "test-writer":
113
- # Its report may change a locked file of a merged ticket only when it lists the file.
114
- merged = driver_merge.protected(self.state.read()["tickets"], number)
115
- options["check"] = {**(options.get("check") or {}), "merged": merged, "pr": self.tip()}
116
- values = {**values, "protected": " ".join(merged) or "none"}
117
- if options["check"].get("correction"):
118
- options["notes"] = [*options.get("notes", ()), "corrected"]
119
- report = _attempts(self, role, number, slot, values, **options)
120
- if role == "test-writer":
131
+ def ask(self, number: str, kind: str, subjects: list[str], report: str, resume: Resume) -> None:
132
+ """The questions of `number`'s stop. The end of run adds those of each lens that stopped to one stop."""
133
+ with _ASKS:
134
+ if earlier := self.asks.get(number):
135
+ subjects = earlier.subjects + subjects
136
+ self.asks[number] = Ask(kind, subjects, report, resume)
137
+
138
+ def block(self, number: str, line: int) -> None:
139
+ """Make the record of `number` BLOCKED and add the questions it asked for, in one write of state.json. The
140
+ ledger line `line` says why."""
141
+ ask = self.asks.pop(number, None)
142
+
143
+ def change(state: dict) -> None:
144
+ held = record_of(state, number)
145
+ if ask:
146
+ held.update(ask.resume.fields())
147
+ evidence = [ask.report, f"{OUT / 'ledger.md'}:{line}"]
148
+ driver_decisions.stop(state["run"], ask.kind, number, ask.subjects, evidence, ask.resume)
149
+ held["phase"] = "blocked"
150
+
151
+ self.state.update(change)
152
+ if ask and ask.subjects:
153
+ ledger(f"{_owner(number)}: {driver_decisions.decides(ask.kind, len(ask.subjects))} in "
154
+ f"{OUT / 'decisions.json'}.")
155
+
156
+ def agent(self, call: Call) -> dict:
157
+ """Run one agent and return its accepted report."""
158
+ if call.role == "test-writer":
159
+ others = driver_locked.others(self.state.read()["tickets"], call.number)
160
+ call = replace(call, values={**call.values, "protected": " ".join(others) or "none"})
161
+ report = _attempts(self, call)
162
+ if call.role == "test-writer":
121
163
  report["locked"] = driver_report.locked_files(report["locked"]) # as validate read it
122
- if report.get("status") in ("BLOCKED", "NEEDS_CONTEXT"):
123
- concerns = "; ".join(report["concerns"]) or "no concern given"
124
- why = f"the {role} reported {report['status']}: {concerns}"
125
- if number != FINAL:
126
- self._ask_stop(role, number, slot, report, why, options.get("fix_round", 0))
127
- raise Stopped(why, report)
128
164
  return report
129
165
 
130
- def _ask_stop(self, role: str, number: str, slot: str, report: dict, why: str, fix_round: int) -> None:
131
- """The question of a stopped implementer or fixer: `locked-test` when it says a locked test contradicts the
132
- spec, else `<role>-stopped` (issue #123). Its commits stay: after the ruling the ticket goes on from them."""
133
- if role not in ("implementer", "fixer"):
134
- return
135
- evidence, tip = str(OUT / number / f"{role}-{fix_round}.json"), driver_slots.head(slot)
136
- if subject := driver_decisions.contradicted(role, report):
137
- self.ask(number, "locked-test", [subject], evidence, tip=tip)
138
- elif role == "implementer":
139
- self.ask(number, "implementer-stopped", [why], evidence, tip=tip)
140
- else:
141
- # The round that stopped does not count: `retry` reviews the tip and runs that round again.
142
- self.ask(number, "fixer-stopped", [why], evidence, tip=tip, round=fix_round - 1)
166
+ def locked(self, call: Call, context: dict) -> driver_locked.Locked | None:
167
+ """The locked-file check of the report of `call`, read when the agent ends."""
168
+ if call.locked:
169
+ return call.locked(context)
170
+ return driver_locked.for_ticket(self.state.read()["tickets"], call.role, call.number, f"refs/heads/{self.pr}")
143
171
 
144
172
  def read_only(self, number: str, slot: str, branch: str, tip: str, review: Callable[[], T]) -> T:
145
173
  """Run `review` (read-only agents) and return its result. A review that changes the slot runs once more."""
@@ -164,17 +192,17 @@ class Run:
164
192
  if record := self.red_gate(number, slot, commit, tier):
165
193
  raise Blocked(f"the {tier} gate is red on {commit[:7]}, record {record}")
166
194
 
167
- def red_gate(self, number: str, slot: str, commit: str, tier: str, restored: list[str] | tuple = ()) -> str:
195
+ def red_gate(self, number: str, slot: str, commit: str, tier: str) -> str:
168
196
  """`gate`, for a caller that acts on a red gate: returns its record, or "" when the gate is green. The fast gate
169
- checks the ticket's locked files and the `restored` ones, as the state holds them now."""
197
+ checks the ticket's locked files, as the state holds them now."""
170
198
  state = self.state.read()
171
- if commit in _gate_record(state, number)["green_gates"][tier]:
199
+ if commit in record_of(state, number)["green_gates"][tier]:
172
200
  return ""
173
201
  at = driver_slots.head(slot)
174
202
  if at != commit:
175
203
  raise Blocked(f"the slot is at {at[:7]}, not at {commit[:7]}: the {tier} gate did not run")
176
204
  command = self.args.fast_gate if tier == driver_gate.FAST else self.args.gate
177
- locked = list(dict.fromkeys([*state["tickets"][number]["locked"], *restored])) if tier == driver_gate.FAST else []
205
+ locked = state["tickets"][number]["locked"] if tier == driver_gate.FAST else []
178
206
  green, record, killed = driver_gate.run(command, tier, slot, OUT / number, self.pr, locked)
179
207
  for sentence in killed:
180
208
  ledger(f"{_owner(number)}: {sentence}.")
@@ -182,7 +210,7 @@ class Run:
182
210
  def count(state: dict) -> None:
183
211
  state["run"]["gates"][tier] += 1
184
212
  if green:
185
- _gate_record(state, number)["green_gates"][tier].append(commit)
213
+ record_of(state, number)["green_gates"][tier].append(commit)
186
214
 
187
215
  self.state.update(count)
188
216
  if not green:
@@ -190,43 +218,6 @@ class Run:
190
218
  ledger(f"{_owner(number)}: the {tier} gate is green on {commit[:7]}, record {record}.")
191
219
  return ""
192
220
 
193
- def restore_locked_files(self, number: str, slot: str) -> list[str]:
194
- """Before a test-writer correction: put each locked file the implementer changed back to its locked
195
- version in one commit of the driver, so the correction starts from the locked versions on a clean index and
196
- its commit carries no change of the implementer. Other work in the tree stays. Returns the paths."""
197
- tickets = self.state.read()["tickets"]
198
- paths = (driver_review.restore_locked(slot, tickets[number])
199
- + driver_merge.restore(slot, self.tip(), driver_merge.protected(tickets, number)))
200
- self._commit_restored(number, slot, paths, "implement-spec: restore the locked files before the correction")
201
- for path in paths:
202
- ledger(f"Ticket {number}: {path} was not the locked version at the correction: the driver restored it in "
203
- "a commit, so the correction starts from the locked version.")
204
- return paths
205
-
206
- def restore_merged_files(self, number: str, slot: str, paths: list[str]) -> list[str]:
207
- """Before a landing, by a `restore` ruling: put each of `paths` that is a locked file of a merged ticket and
208
- that the ticket changed back to the version of the PR branch, in one commit of the driver. Returns those."""
209
- protected = driver_merge.protected(self.state.read()["tickets"], number)
210
- restored = driver_merge.restore(slot, self.tip(), [path for path in paths if path in protected])
211
- self._commit_restored(number, slot, restored,
212
- "implement-spec: restore the locked files of merged tickets before the landing")
213
- for path in restored:
214
- ledger(f"Ticket {number}: by the ruling (restore), the driver put back {path}, a locked file of a merged "
215
- "ticket, at the version of the PR branch in a commit before the landing.")
216
- return restored
217
-
218
- def _commit_restored(self, number: str, slot: str, paths: list[str], words: str) -> None:
219
- """Commit the restored `paths` in the slot as a commit of the driver, and make it the ticket tip."""
220
- # A path whose change was never committed is back at HEAD already, and `git commit -- <path>` refuses it.
221
- changed = names(git(slot, "diff", "--name-only", "-z", "HEAD", "--", *paths).stdout) if paths else []
222
- if not changed:
223
- return
224
- made = subprocess.run(["git", "-C", slot, "commit", "-q", "--no-verify", "-m", words, "--", *changed],
225
- capture_output=True, text=True, env={**os.environ, **driver_merge.identity("HEAD", slot)})
226
- if made.returncode:
227
- raise Blocked(f"the driver cannot commit the restored locked files: {made.stderr.strip()}")
228
- self.state.ticket(number, tip=driver_slots.head(slot))
229
-
230
221
 
231
222
  def _restore_if_changed(number: str, slot: str, branch: str, tip: str, config: driver_review.Config,
232
223
  runs_again: bool) -> str:
@@ -276,18 +267,72 @@ def _timeout_lines(role: str, minutes: float, context: dict, alone: Callable[[],
276
267
  return driver_agents.render("timeout-shared", values)
277
268
 
278
269
 
279
- def _rejection(role: str, code: int | None, minutes: float, report: Path, context: dict, alone: Callable[[], bool],
280
- detached: bool) -> tuple[str, str]:
281
- """(why the attempt is rejected, the lines the rerun prompt gets); ("", ...) when the report is accepted."""
282
- branch, tip = context["branch"], context["start"]
270
+ def _stop(call: Call, report: Path) -> str:
271
+ """Why the valid report of an agent is a stop: BLOCKED or NEEDS_CONTEXT, and no dispute of an agent that may
272
+ dispute; else ""."""
273
+ accepted = json.loads(report.read_text())
274
+ if accepted["status"] not in STOPS or (call.may_dispute and driver_report.disputes(call.role, accepted, [])):
275
+ return ""
276
+ return f"it reported {accepted['status']}: {'; '.join(accepted['concerns']) or 'no concern given'}"
277
+
278
+
279
+ def _rejection(call: Call, code: int | None, minutes: float, report: Path, context: dict) -> tuple[str, str, bool]:
280
+ """(why the attempt is rejected, the lines the rerun prompt gets, whether the rerun stays on the same entry);
281
+ ("", ...) when the report is accepted. A stop is rejected too."""
282
+ role, branch, tip = call.role, context["branch"], context["start"]
283
283
  # Read-only agents share a slot, and a rebase is on a detached HEAD: there the driver has no branch to reset.
284
- owns_branch = role not in driver_agents.READ_ONLY and not detached
284
+ owns_branch = role not in driver_agents.READ_ONLY and not call.detached
285
285
  if owns_branch and (moved := _reset_if_moved(context["repo"], branch, tip)):
286
- return moved, driver_agents.render("moved", {"branch": branch, "tip": tip})
286
+ return moved, driver_agents.render("moved", {"branch": branch, "tip": tip}), True
287
287
  if code is None:
288
- return f"timed out after {minutes:g} minutes", _timeout_lines(role, minutes, context, alone)
289
- error = "; ".join(driver_report.validate(context["template"], str(report), context))
290
- return error, driver_agents.render("rerun", {"error": error})
288
+ return f"timed out after {minutes:g} minutes", _timeout_lines(role, minutes, context, call.alone), True
289
+ error = "; ".join(driver_report.validate(context["template"], str(report), context)) or _stop(call, report)
290
+ return error, driver_agents.render("rerun", {"error": error}), False
291
+
292
+
293
+ def _rerun_entry(run: Run, role: str, entry: str, entries: list[str] | None) -> str:
294
+ """The entry of the rerun after a stop or a rejection: the next one of the list, wrapping to the first."""
295
+ entries = entries or run.models[role]
296
+ return entries[(entries.index(entry) + 1) % len(entries)]
297
+
298
+
299
+ def _cli_failure(role: str, entry: str, code: int | None, report: Path, log: Path) -> str:
300
+ """Why the run setup is wrong, when the CLI exited with an error and no report: it did not do the role; else ""."""
301
+ if code in (None, 0) or report.exists():
302
+ return ""
303
+ return f"the {role} on {entry} exited {code} with no report: {driver_agents.last_words(log)}"
304
+
305
+
306
+ def retry_point(role: str, tip: str, fix_round: int) -> Resume:
307
+ """Where a `retry` takes a ticket to run `role` again: a role that commits goes on from `tip`, and the round of a
308
+ fixer does not count."""
309
+ return Resume(_RETRY[role], tip if role in _COMMITS else None, fix_round - 1 if role == "fixer" else None)
310
+
311
+
312
+ def _ask_blocked(run: Run, call: Call, report: Path, error: str) -> None:
313
+ """The `ticket-blocked` question of an agent whose rerun stopped or was rejected too. Its `retry` takes the ticket
314
+ back to the phase that runs the role again, from the tip the agent left; an agent that ran for another role
315
+ (`call.retry`) leaves no work, so that role runs again from the agent's start. The end of run goes on from where
316
+ its state is."""
317
+ tip = call.values["start_sha"] if call.retry else driver_slots.head(call.slot)
318
+ resume = FINAL_RESUME if call.number == FINAL else retry_point(call.retry or call.role, tip, call.fix_round)
319
+ run.ask(call.number, "ticket-blocked", [f"the {call.role}: {error}"], str(report), resume)
320
+
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)
327
+ if not same:
328
+ _ask_blocked(run, call, report, error)
329
+ raise Blocked(error)
330
+
331
+
332
+ def _files(folder: Path, role: str, fix_round: int, name: str) -> tuple[Path, Path, Path]:
333
+ """The report, log and prompt of an agent: `<name>.*`, by default `<role>-<fix_round>.*`."""
334
+ name = name or f"{role}-{fix_round}"
335
+ return folder / f"{name}.json", folder / f"{name}.log", folder / f"{name}.prompt.md"
291
336
 
292
337
 
293
338
  def _first_prompt(template: str, values: dict[str, str], notes: tuple | list, report: str) -> str:
@@ -312,29 +357,22 @@ def _command(run: Run, role: str, entry: str, prompt: str, report: str) -> list[
312
357
  return driver_agents.command(role, entry, report)
313
358
 
314
359
 
315
- def _attempts(run: Run, role: str, number: str, slot: str, values: dict[str, str], notes: tuple | list = (),
316
- entry: str = "", fix_round: int = 0, check: dict | None = None, template: str = "",
317
- alone: Callable[[], bool] = lambda: True, detached: bool = False) -> dict:
318
- """Run one role in its slot, with at most one rerun, and return the accepted report.
319
-
320
- notes templates whose lines the first prompt gets after the role's own
321
- entry the model entry, when it is not the first of the role's list
322
- fix_round the K of the files `<role>-<K>.json`, `.log` and `.prompt.md`
323
- check more context for the report validation (driver_report.validate)
324
- template the prompt and schema, when it is not the one named after the role
325
- alone whether no other agent works in the slot now
326
- detached the agent works on a detached HEAD
327
- """
328
- folder, entry = OUT / number, entry or run.models[role][0]
360
+ def _attempts(run: Run, call: Call) -> dict:
361
+ """Run one agent in its slot, with at most one rerun, and return the accepted report. An agent that stops or is
362
+ rejected reruns on the next entry of its list; a timeout or a moved branch reruns on the same entry. An agent whose
363
+ rerun stops or is rejected too asks `ticket-blocked`."""
364
+ role, number, slot, values = call.role, call.number, call.slot, call.values
365
+ folder, entry = OUT / number, call.entry or run.models[role][0]
329
366
  folder.mkdir(parents=True, exist_ok=True)
330
- report, log, prompt = (folder / f"{role}-{fix_round}{suffix}" for suffix in (".json", ".log", ".prompt.md"))
367
+ report, log, prompt = _files(folder, role, call.fix_round, call.name)
331
368
  report_in_slot = os.path.relpath(report, slot) # the agent works in its slot
332
369
  context = {"repo": slot, "branch": values["branch"], "start": values["start_sha"], "log": str(log),
333
- "template": template or role, **(check or {})}
334
- argv = _command(run, role, entry, os.path.relpath(prompt, slot), report_in_slot)
335
- text = _first_prompt(context["template"], values, notes, report_in_slot)
336
- minutes, error, failed = run.args.timeout[role], "", ""
370
+ "template": call.template or role, **call.check}
371
+ text = _first_prompt(context["template"], values, call.notes, report_in_slot)
372
+ rerun_on = _rerun_entry(run, role, entry, call.entries)
373
+ minutes, error, failed, same = run.args.timeout[role], "", "", True
337
374
  for _ in range(2):
375
+ argv = _command(run, role, entry, os.path.relpath(prompt, slot), report_in_slot)
338
376
  prompt.write_text(text)
339
377
  report.unlink(missing_ok=True)
340
378
  Path(driver_agents.last_message(report)).unlink(missing_ok=True)
@@ -342,17 +380,16 @@ def _attempts(run: Run, role: str, number: str, slot: str, values: dict[str, str
342
380
  code = driver_agents.launch(argv, prompt, log, minutes * 60, slot)
343
381
  seconds = time.monotonic() - start
344
382
  driver_agents.settle_report(report)
345
- error, rerun_lines = _rejection(role, code, minutes, report, context, alone, detached)
383
+ checked = {**context} # what the check of the agent's end adds holds for this attempt only
384
+ checked["locked"] = run.locked(call, checked)
385
+ error, rerun_lines, same = _rejection(call, code, minutes, report, checked)
346
386
  _record_attempt(run, role, number, entry, seconds, log, error)
347
387
  if not error:
348
388
  return json.loads(report.read_text())
349
- # A CLI that exits with an error and no report did not do the role: the run setup is wrong, not the ticket.
350
- failed = "" if code in (None, 0) or report.exists() else (
351
- f"the {role} on {entry} exited {code} with no report: {driver_agents.last_words(log)}")
389
+ failed = _cli_failure(role, entry, code, report, log)
352
390
  # The rerun prompt is the first prompt, the rejection, then the same ending again.
353
391
  text += rerun_lines + driver_agents.tail(text, report_in_slot)
354
392
  if code is None:
355
393
  minutes *= 2
356
- if failed:
357
- raise Halted(failed)
358
- raise Blocked(error)
394
+ entry = entry if same else rerun_on
395
+ _give_up(run, call, report, error, failed, same)
@@ -2,12 +2,14 @@
2
2
 
3
3
  {"run": {revision, pr_branch, schema, gates: {fast, full}, stops, agents: [{ticket, role, entry, seconds, cost}], questions, start,
4
4
  landed: [[ticket, the PR tip its merge made]], final},
5
- "tickets": {"NN": {phase, round, tip, test_writer_sha, locked, fixtures, green_gates, slot, note, held, rejected,
6
- landing}}}
5
+ "tickets": {"NN": {phase, round, tip, test_writer_sha, locked, green_gates, slot, note,
6
+ landing, disputes, corrected}}}
7
7
 
8
8
  green_gates is {"fast": [commit], "full": [commit]}, in a ticket and in run.final: a fast green never stands in for a
9
9
  full one. landing is the commit whose full gate was red at the landing while the fixer of the round it started has
10
- not reported, else None."""
10
+ not reported, else None. disputes is {locked file: {test, requirement, ruling, reason}}, the reviewer's ruling on
11
+ the file; corrected is {locked file: {test, requirement, reason}}, the reading of its one correction. A locked file has
12
+ at most one of each per ticket, and no answer writes them."""
11
13
  from __future__ import annotations
12
14
 
13
15
  import fcntl
@@ -21,7 +23,8 @@ from typing import IO
21
23
  from driver_names import Names
22
24
  from driver_slots import ancestor, git, on_branch, path
23
25
 
24
- SCHEMA = 3 # the version of this contract; 2: the names of driver_names, 3: gate tiers. A run of an older driver has none.
26
+ SCHEMA = 4 # the version of this contract; 2: the names of driver_names, 3: gate tiers, 4: the two question kinds and
27
+ # the ruling kept on an answered question. A run of an older driver has none.
25
28
  PHASES = ("pending", "test-writer", "implement", "gate", "review", "fix", "merge", "merged", "blocked")
26
29
 
27
30
 
@@ -32,15 +35,14 @@ def tiers() -> dict:
32
35
 
33
36
  def _ticket() -> dict:
34
37
  return {"phase": "pending", "round": 0, "tip": None, "test_writer_sha": None, "locked": [], "green_gates": tiers(),
35
- "slot": None, "note": "", "held": {}, "rejected": {},
36
- "fixtures": [], "landing": None}
38
+ "slot": None, "note": "", "landing": None, "disputes": {}, "corrected": {}}
37
39
 
38
40
 
39
41
  def _final() -> dict:
40
42
  """The end-of-run record before it starts. Every key is here, so a reader uses [] and a wrong name fails."""
41
- return {"skipped": "", "recovery": None, "tidied": None, "onto": None, "base": None, "commits": {},
42
- "reviewed": None, "round": 0, "open": [], "must_fix": [], "batch": None, "green_gates": tiers(), "pushed": None, "body": None,
43
- "pr": None}
43
+ return {"skipped": "", "phase": "pending", "recovery": None, "tidied": None, "onto": None, "base": None,
44
+ "commits": {}, "reviewed": None, "round": 0, "open": [], "must_fix": [], "lenses": {}, "batch": None,
45
+ "green_gates": tiers(), "pushed": None, "body": None, "pr": None}
44
46
 
45
47
 
46
48
  class State:
@@ -1,9 +1,7 @@
1
1
  {
2
- "explorer": ["claude-sonnet-5-5@medium"],
3
2
  "test-writer": ["claude-sonnet-5-5@medium", "openai/gpt-6.1-sol@medium"],
4
3
  "implementer": ["claude-sonnet-5-5@medium", "claude-opus-5-5@medium"],
5
4
  "reviewer": ["openai/gpt-6-astra@medium", "claude-opus-5-5@medium"],
6
- "correctness": ["openai/gpt-6-astra@medium", "claude-opus-5-5@medium"],
7
5
  "fixer": ["claude-opus-5-5@medium"],
8
6
  "final-reviewer": ["openai/gpt-6-astra@medium", "claude-opus-5-5@medium"],
9
7
  "conflict": ["claude-opus-5-5@medium"],
@@ -0,0 +1,34 @@
1
+ # Arbitration
2
+
3
+ Spec: {spec}
4
+ Ticket: {ticket}
5
+ Branch: {branch}, at commit {start_sha}
6
+ Locked files: {locked}
7
+ Report of the {role} that disputes them: {dispute_report}
8
+
9
+ The {role} reports that these locked tests contradict the spec or the ticket:
10
+ {disputed}
11
+ Rule on each of them. Read the test, the requirement of the spec or the criterion of the ticket that it checks, and the concern of the {role}.
12
+ `test-wrong`: the test asserts what the spec and the ticket do not say. The test-writer corrects it to your reason, then the {role} runs again.
13
+ `code-wrong`: the test asserts what the spec and the ticket say. The {role} runs again with your reason and makes the test green.
14
+ In `test`, copy the test id as the list gives it. In `requirement`, name the requirement or the criterion that the test checks. In `reason`, say what it requires, so that the next agent can act on your reason alone.
15
+ Do not commit, do not change a file and do not dispatch subagents. Leave the tree as you found it.
16
+
17
+ Write one JSON report at {report}. When your sandbox is read-only, give the JSON as your whole final message and the driver saves it there. The report matches this schema:
18
+
19
+ ```json
20
+ {
21
+ "type": "object",
22
+ "required": ["status", "files", "concerns", "rulings"],
23
+ "properties": {
24
+ "status": {"enum": ["DONE", "DONE_WITH_CONCERNS", "NEEDS_CONTEXT", "BLOCKED"]},
25
+ "files": {"type": "array", "items": {"type": "string"}},
26
+ "concerns": {"type": "array", "items": {"type": "string"}},
27
+ "rulings": {"type": "array", "minItems": 1, "items": {"type": "object", "required": ["test", "requirement", "ruling", "reason"], "properties": {"test": {"type": "string", "minLength": 1}, "requirement": {"type": "string", "minLength": 1}, "ruling": {"enum": ["test-wrong", "code-wrong"]}, "reason": {"type": "string", "minLength": 1}}}}
28
+ }
29
+ }
30
+ ```
31
+
32
+ Run git as plain `git` in this worktree, and leave the git config as it is: all worktrees read one shared config, and one key written there, such as a `core.worktree`, breaks git in each of them. So never set GIT_DIR or GIT_WORK_TREE, and never write with `git config`.
33
+ Stop only processes you started and their child processes, by PID (for example the PID of a job you put in the background, or its process group). Never kill a process you did not start, and never use `pkill`, `killall` or a `kill` by name or pattern: other slots and sessions share the machine. If a process you did not start blocks you, report it in your concerns and do not kill it.
34
+ Never run `git stash`, never reset, and never check out another branch: worktrees share one stash and one ref store.
@@ -8,6 +8,7 @@ Files in conflict: {files}
8
8
 
9
9
  The merge of the PR branch into the ticket branch is open in this worktree and it has conflicts in those files.
10
10
  Resolve each conflict so that the behavior of both sides holds: the spec and the ticket say what each side is for. Change nothing that the resolution does not need.
11
+ Leave each locked test file as one side of the merge has it: the driver rejects a report whose commits change a locked file.
11
12
  Run the targeted tests of the files you resolved. The driver runs the gate on your commit.
12
13
  Finish the merge with `git commit` on the checked-out ticket branch. Do not abort the merge and do not dispatch subagents.
13
14
  In `files`, give each file you resolved.
@@ -1,8 +1,11 @@
1
1
 
2
- This call is a correction of the locked tests, not a new test set. Read in {findings} each finding of kind `fixture`, each critical or important finding of kind `test` on a locked file, and each critical or important finding on a locked file of a merged ticket ({protected}).
2
+ This call is a correction of the locked tests, not a new test set. Read in {findings} each finding of kind `ruling`, each finding of kind `fixture`, each critical or important finding of kind `test` on a locked file, and each critical or important finding on a locked file of another ticket ({protected}).
3
+ A `ruling` finding: a ruling says that a locked test contradicts the spec, and its `evidence` gives the reading of the spec that the test must assert. Change what the test asserts to that reading.
3
4
  A `fixture` finding: a locked test encodes a stale path, format, fixture layout or setup detail. Correct only that detail and keep what each test asserts.
4
5
  A `test` finding: a locked test is too weak, for example it stays green when the production line it protects is broken. Make the test assert the behavior of its criterion so that it fails on that break. Do not remove an assertion.
5
- A finding on a locked file of a merged ticket, of any kind: only this correction may change that file. When the ticket must change it, as one that its Touches line names, make the change, keep what each test of the merged ticket asserts, and list the file in `locked`.
6
- For this you may read the implementation.
6
+ A finding on a locked file of another ticket, of any kind: only this correction may change that file. When the ticket must change it, as one that its Touches line names, make the change, keep what each test of the other ticket asserts, and list the file in `locked`.
7
+ For this you may read the implementation. Keep each test that no finding names as it is, and commit only the test files you correct.
7
8
  When a finding needs a production change first, so that no correct test can be green, leave the test as it is and add the finding to `not_addressed`: `finding` is its `title` as the findings file gives it, `reason` is the production change it needs. The driver sends it to the fixer as a finding of kind `code`. A correction whose findings are all in `not_addressed` may report DONE with no commit.
8
- The implementation exists, so a corrected test is green: for `red`, break the production line that the test protects, run the test, print its failing output, then revert the edit. In `locked`, list each test file you corrected: test file paths only, not test node ids. Unlike `mutations[].test` of the reviewer, `locked` takes no `::<test name>`.
9
+ When this correction adds a requirement, update each shared fake or fixture that other locked tests use, so that those tests satisfy the requirement too. List each file you change in `locked`: test file paths only, not test node ids.
10
+ A corrected test that fails because the behavior is missing: run it, print that failing output, and give its failure line in `red`. A corrected test that is green, because the implementation is there: break the production line that the test protects, run the test, print its failing output, give that line in `red`, and revert the edit.
11
+ Then run each whole file of `locked` and each locked test of merged tickets. In `concerns`, name each red test and why it is expected to be red, or write that all are green.
@@ -0,0 +1,6 @@
1
+
2
+ The test-writer of this ticket changed locked files of other tickets. Judge each change against the spec: a change that the spec does not support is a critical `fixture` finding on that file. The diff since the merge base with the PR branch:
3
+
4
+ ```diff
5
+ {elsewhere}
6
+ ```
@@ -12,7 +12,7 @@ Must-fix findings carried from ticket reviews:
12
12
 
13
13
  Fix each finding in the list as one batch, in one commit or in several. List every must-fix item you addressed in `addressed_must_fix` exactly as shown in the must-fix list, including its file and line; an omitted item rejects the batch. Leave the minor findings of the findings file.
14
14
  Each commit belongs to one ticket: the ticket whose criterion or code the commit changes. A fix for two tickets is two commits.
15
- Never edit a locked file: each one stays as it is at {start_sha}, and a locked file that differs is a critical finding of the next review.
15
+ Never edit a locked file: each one stays as it is at {start_sha}, and the driver rejects a report whose commits change one.
16
16
  Use targeted tests while you work.
17
17
  Before you report DONE or DONE_WITH_CONCERNS, make the fast gate green on your final commit: run `{gate}` with IMPLEMENT_SPEC_BASE={pr_branch} and IMPLEMENT_SPEC_LOCKED='{locked}' (the locked files above) in the environment, then fix, commit, and run it again until it passes. The driver runs its full gate on that commit, and a scoped review reads your commits.
18
18
  Commit your work on the checked-out PR branch and change no commit that is on it now. Do not dispatch subagents.
@@ -0,0 +1,40 @@
1
+ # Final review: {lens} lens
2
+
3
+ Spec: {spec}
4
+ Tickets: {tickets}
5
+ PR branch: {pr_branch}, at commit {start_sha}
6
+ Range: {range}
7
+ Gate record of the driver for {start_sha}: {gate}
8
+ Ledger of the run, one sentence per event: {ledger}
9
+ Deferred observations and minor findings from ticket reviews, each with its evidence file:
10
+ {carried}
11
+ Must-fix findings carried from tickets that merged at the cap:
12
+ {must_fix_list}
13
+ Rulings of the operator:
14
+ {rulings}
15
+
16
+ {method}
17
+ The gate is done: the driver ran the full gate on {start_sha}, and its record is the gate evidence of your review. Do not run a gate yourself.
18
+ Two other reviewers review the same range at the same time, each for its own question; you never see their reports, and they never see yours.
19
+ Decide for each carried observation whether it is still true at {start_sha} and in your question; report each one that is, with the severity it has now. Report each must-fix finding that is in your question and still open at {start_sha}, with its title, file and line as the must-fix list shows them: it stays open until the fix batch addresses it and the scoped review verifies it. A ruling does not settle a must-fix finding.
20
+ Give each finding a severity (critical, important or minor), the file and line, a title, the evidence, and a kind: `code`, `test`, or `fixture`.
21
+ Do not commit and do not dispatch subagents. Leave the branch and the tree as you found them.
22
+
23
+ Write one JSON report at {report}. When your sandbox is read-only, give the JSON as your whole final message and the driver saves it there. The report matches this schema:
24
+
25
+ ```json
26
+ {
27
+ "type": "object",
28
+ "required": ["status", "files", "concerns", "findings"],
29
+ "properties": {
30
+ "status": {"enum": ["DONE", "DONE_WITH_CONCERNS", "NEEDS_CONTEXT", "BLOCKED"]},
31
+ "files": {"type": "array", "items": {"type": "string"}},
32
+ "concerns": {"type": "array", "items": {"type": "string"}},
33
+ "findings": {"type": "array", "items": {"type": "object", "required": ["severity", "file", "line", "title", "evidence", "kind"], "properties": {"severity": {"enum": ["critical", "important", "minor"]}, "file": {"type": "string"}, "line": {"type": "integer"}, "title": {"type": "string", "minLength": 1}, "evidence": {"type": "string", "minLength": 1}, "kind": {"enum": ["code", "fixture", "test"]}}}}
34
+ }
35
+ }
36
+ ```
37
+
38
+ Run git as plain `git` in this worktree, and leave the git config as it is: all worktrees read one shared config, and one key written there, such as a `core.worktree`, breaks git in each of them. So never set GIT_DIR or GIT_WORK_TREE, and never write with `git config`.
39
+ Stop only processes you started and their child processes, by PID (for example the PID of a job you put in the background, or its process group). Never kill a process you did not start, and never use `pkill`, `killall` or a `kill` by name or pattern: other slots and sessions share the machine. If a process you did not start blocks you, report it in your concerns and do not kill it.
40
+ Never run `git stash`, never reset, and never check out another branch: worktrees share one stash and one ref store.