@jesdi/skills 0.0.99 → 0.0.101

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 (45) hide show
  1. package/package.json +1 -1
  2. package/skills/implement-spec/ARCHITECTURE.md +8 -5
  3. package/skills/implement-spec/README.md +43 -19
  4. package/skills/implement-spec/SKILL.md +2 -0
  5. package/skills/implement-spec/driver.py +136 -30
  6. package/skills/implement-spec/driver_agents.py +13 -0
  7. package/skills/implement-spec/driver_arbiter.py +57 -11
  8. package/skills/implement-spec/driver_decisions.py +186 -49
  9. package/skills/implement-spec/driver_dispute.py +1 -1
  10. package/skills/implement-spec/driver_final.py +232 -242
  11. package/skills/implement-spec/driver_final_gate.py +152 -17
  12. package/skills/implement-spec/driver_gate.py +12 -0
  13. package/skills/implement-spec/driver_legacy.py +15 -2
  14. package/skills/implement-spec/driver_overturn.py +106 -0
  15. package/skills/implement-spec/driver_pr.py +286 -0
  16. package/skills/implement-spec/driver_report.py +9 -4
  17. package/skills/implement-spec/driver_review.py +10 -4
  18. package/skills/implement-spec/driver_run.py +33 -14
  19. package/skills/implement-spec/driver_slots.py +61 -11
  20. package/skills/implement-spec/driver_state.py +30 -16
  21. package/skills/implement-spec/driver_summary.py +10 -3
  22. package/skills/implement-spec/prompts/arbiter.md +8 -4
  23. package/skills/implement-spec/prompts/conflict.md +1 -1
  24. package/skills/implement-spec/prompts/pr-body.md +2 -1
  25. package/skills/implement-spec/recovery.md +4 -4
  26. package/skills/implement-spec/tests/conftest.py +1 -0
  27. package/skills/implement-spec/tests/test_arbiter.py +74 -17
  28. package/skills/implement-spec/tests/test_arbitration.py +1 -1
  29. package/skills/implement-spec/tests/test_decisions.py +30 -6
  30. package/skills/implement-spec/tests/test_driver.py +9 -1
  31. package/skills/implement-spec/tests/test_final.py +20 -3
  32. package/skills/implement-spec/tests/test_final_gate.py +144 -0
  33. package/skills/implement-spec/tests/test_fixloop.py +1 -1
  34. package/skills/implement-spec/tests/test_leave_out.py +203 -0
  35. package/skills/implement-spec/tests/test_legacy.py +25 -0
  36. package/skills/implement-spec/tests/test_lenses.py +6 -4
  37. package/skills/implement-spec/tests/test_overturn.py +362 -0
  38. package/skills/implement-spec/tests/test_scoped.py +6 -5
  39. package/skills/implement-spec/tests/test_ship_draft.py +203 -0
  40. package/skills/implement-spec/tests/test_slots.py +29 -0
  41. package/skills/implement-spec/tests/test_state.py +4 -2
  42. package/skills/implement-spec/tests/test_stops.py +19 -4
  43. package/skills/implement-spec/tests/test_tidy.py +4 -2
  44. package/skills/implement-spec/tests/test_walk.py +1 -0
  45. package/skills-manifest.json +3 -3
@@ -209,10 +209,15 @@ def _ruling_errors(report: dict, context: dict) -> list[str]:
209
209
 
210
210
 
211
211
  def _arbiter_errors(report: dict, context: dict) -> list[str]:
212
- """The arbiter rules on each open question."""
213
- given = {ruling.get("question") for ruling in report.get("rulings", [])}
214
- return [f"rulings: no ruling on {question}: give one ruling per open question, its id as the list gives it"
215
- for question in context.get("questions", []) if question not in given]
212
+ """The arbiter rules on each open question, with an option that the question offers it."""
213
+ given = {ruling.get("question"): ruling.get("ruling") for ruling in report.get("rulings", [])}
214
+ errors = []
215
+ for question, options in context.get("questions", {}).items():
216
+ if question not in given:
217
+ errors.append(f"rulings: no ruling on {question}: give one ruling per open question, its id as the list gives it")
218
+ elif given[question] not in options:
219
+ errors.append(f"rulings: {question} takes {' or '.join(options)}, not {given[question]}")
220
+ return errors
216
221
 
217
222
 
218
223
  def locked_files(listed: list[str]) -> list[str]:
@@ -14,6 +14,11 @@ from driver_slots import git, head, on_branch
14
14
  OPEN = ("critical", "important") # the severities that start a fix round
15
15
 
16
16
 
17
+ def title(finding: dict) -> str:
18
+ """A finding as a line names it: `<title> (<file>:<line>)`."""
19
+ return f"{finding['title']} ({finding['file']}:{finding['line']})"
20
+
21
+
17
22
  def _corrected(finding: dict, locked: list[str], protected: list[str]) -> bool:
18
23
  """Whether a correction, not a fixer, takes the finding: see `route`."""
19
24
  return finding["kind"] == "fixture" or finding["severity"] in OPEN and (
@@ -30,14 +35,15 @@ def route(findings: list[dict], locked: list[str], protected: list[str]) -> tupl
30
35
 
31
36
 
32
37
  def restore(slot: str, branch: str, tip: str) -> None:
33
- """Put the slot back on `branch` at `tip` with a clean tree. Only for a read-only role: its edits, commits and
34
- untracked files go. Ignored files stay."""
35
- git(slot, "checkout", "-q", "-f", "-B", branch, tip)
38
+ """Put the slot back on `branch` ("": a detached HEAD) at `tip` with a clean tree. Only for a read-only role: its
39
+ edits, commits and untracked files go. Ignored files stay."""
40
+ git(slot, "checkout", "-q", "-f", *(["-B", branch] if branch else ["--detach"]), tip)
36
41
  git(slot, "clean", "-q", "-fd")
37
42
 
38
43
 
39
44
  def disturbed(slot: str, branch: str, tip: str) -> str:
40
- """"" when the slot is still on `branch` at `tip` with a clean tree, else what the read-only agents left."""
45
+ """"" when the slot is still on `branch` ("": a detached HEAD) at `tip` with a clean tree, else what the read-only
46
+ agents left."""
41
47
  if on_branch(slot) != branch or head(slot) != tip:
42
48
  return f"the slot is no longer on {branch} at {tip[:7]}"
43
49
  left = [line[3:] for line in git(slot, "status", "--porcelain").stdout.splitlines()]
@@ -26,6 +26,7 @@ import driver_state
26
26
  from driver_decisions import FINAL, Resume
27
27
  from driver_names import Names
28
28
  from driver_slots import git
29
+ from driver_tickets import Ticket
29
30
 
30
31
  OUT = Path(".agent/implement")
31
32
  FINAL_RESUME = Resume("pending") # a `retry` of the end of run: it goes on from where its state is
@@ -107,8 +108,7 @@ class Call:
107
108
 
108
109
  class Ask(NamedTuple):
109
110
  """The questions a ticket thread, or the end of run, wants the operator to answer when it blocks."""
110
- kind: str
111
- subjects: list[str] # one question per subject
111
+ asked: list[tuple[str, str, str | None]] # one question per (kind, subject), with the role that stopped
112
112
  report: str # the evidence
113
113
  resume: Resume # the record gets its tip and round with the stop, and all of it with a `retry` or a `keep-test`
114
114
 
@@ -120,6 +120,7 @@ class Run:
120
120
  state: driver_state.State
121
121
  pr: str # the PR branch
122
122
  kept: dict[str, int] # ticket number -> the slot that holds its uncommitted work from an earlier run
123
+ tickets: list[Ticket] = field(default_factory=list) # every ticket of the run
123
124
  merging: threading.Lock = field(default_factory=threading.Lock) # held for one landing: merges are serial
124
125
  asks: dict[str, Ask] = field(default_factory=dict) # ticket number -> its pending stop
125
126
  halted: list[str] = field(default_factory=list) # why the run starts no other agent; [] while it goes on
@@ -131,12 +132,15 @@ class Run:
131
132
  def tip(self) -> str:
132
133
  return git(".", "rev-parse", f"refs/heads/{self.pr}").stdout.strip()
133
134
 
134
- def ask(self, number: str, kind: str, subjects: list[str], report: str, resume: Resume) -> None:
135
- """The questions of `number`'s stop. The end of run adds those of each lens that stopped to one stop."""
135
+ def ask(self, number: str, asked: list[tuple[str, str]], report: str, resume: Resume,
136
+ role: str | None = None) -> None:
137
+ """The questions of `number`'s stop, one per (kind, subject) of `asked`; `role`: the agent that stopped, for a
138
+ `ticket-blocked` one. The end of run adds those of each lens that stopped, or of each finding, to one stop."""
139
+ asked = [(kind, subject, role) for kind, subject in asked]
136
140
  with _ASKS:
137
141
  if earlier := self.asks.get(number):
138
- subjects = earlier.subjects + subjects
139
- self.asks[number] = Ask(kind, subjects, report, resume)
142
+ asked = earlier.asked + asked
143
+ self.asks[number] = Ask(asked, report, resume)
140
144
 
141
145
  def block(self, number: str, line: int) -> None:
142
146
  """Make the record of `number` BLOCKED and add the questions it asked for, in one write of state.json. The
@@ -148,12 +152,12 @@ class Run:
148
152
  if ask:
149
153
  held.update(ask.resume.checkpoint())
150
154
  evidence = [ask.report, f"{OUT / 'ledger.md'}:{line}"]
151
- driver_decisions.stop(state["run"], ask.kind, number, ask.subjects, evidence, ask.resume)
155
+ driver_decisions.stop(state["run"], number, ask.asked, evidence, ask.resume)
152
156
  held["phase"] = "blocked"
153
157
 
154
158
  self.state.update(change)
155
- if ask and ask.subjects:
156
- ledger(f"{_owner(number)}: {driver_decisions.decides(ask.kind, len(ask.subjects))} in "
159
+ if ask and ask.asked:
160
+ ledger(f"{_owner(number)}: {driver_decisions.decides(ask.asked)} in "
157
161
  f"{OUT / 'decisions.json'}.")
158
162
 
159
163
  def agent(self, call: Call) -> dict:
@@ -236,13 +240,22 @@ def _restore_if_changed(number: str, slot: str, branch: str, tip: str, config: d
236
240
  driver_review.restore(slot, branch, tip)
237
241
  left = "; ".join(filter(None, (changed, moved)))
238
242
  if left:
239
- where = ("slot 1" if number == FINAL else "the slot") + f" to {tip[:7]}"
240
- restored = " and ".join(filter(None, ("the shared git config" if changed else "", where if moved else "")))
241
- again = f" and runs {'the final review' if number == FINAL else 'the review'} again" if runs_again else ""
242
- ledger(f"{_owner(number)}: a read-only role broke its rule: {left}; the driver restored {restored}{again}.")
243
+ ledger(f"{_owner(number)}: a read-only role broke its rule: {left}; the driver restored "
244
+ f"{_restored(number, slot, tip, changed, moved)}{_again(number, runs_again)}.")
243
245
  return left
244
246
 
245
247
 
248
+ def _restored(number: str, slot: str, tip: str, changed: str, moved: str) -> str:
249
+ """What the driver restored after a read-only role: the shared git config, the slot, or both."""
250
+ where = ("slot 1" if slot == "." and number == FINAL else "the slot") + f" to {tip[:7]}"
251
+ return " and ".join(filter(None, ("the shared git config" if changed else "", where if moved else "")))
252
+
253
+
254
+ def _again(number: str, runs_again: bool) -> str:
255
+ """The tail of the restore ledger line when the review runs again after it."""
256
+ return f" and runs {'the final review' if number == FINAL else 'the review'} again" if runs_again else ""
257
+
258
+
246
259
  def _reset_if_moved(slot: str, branch: str, tip: str) -> str:
247
260
  """After an agent: "" when the slot is on `branch` and still holds `tip`; else reset it and say what was wrong."""
248
261
  head = driver_slots.on_branch(slot)
@@ -319,7 +332,7 @@ def _ask_blocked(run: Run, call: Call, report: Path, error: str) -> None:
319
332
  its state is."""
320
333
  tip = call.values["start_sha"] if call.retry else driver_slots.head(call.slot)
321
334
  resume = FINAL_RESUME if call.number == FINAL else retry_point(call.retry or call.role, tip, call.fix_round)
322
- run.ask(call.number, "ticket-blocked", [f"the {call.role}: {error}"], str(report), resume)
335
+ run.ask(call.number, [("ticket-blocked", f"the {call.role}: {error}")], str(report), resume, call.role)
323
336
 
324
337
 
325
338
  def _give_up(run: Run, call: Call, report: Path, error: str) -> NoReturn:
@@ -406,3 +419,9 @@ def _attempts(run: Run, call: Call) -> dict:
406
419
  minutes *= 2
407
420
  entry = entry if same else rerun_on
408
421
  _give_up(run, call, report, error)
422
+
423
+
424
+ def final_values(run: Run) -> dict[str, str]:
425
+ """The pointers every prompt of the end of run gets. Its agents work in slot 1, the PR worktree."""
426
+ return {"spec": run.args.spec, "tickets": run.args.tickets, "pr_branch": run.pr, "branch": run.pr,
427
+ "gate": run.args.fast_gate}
@@ -1,4 +1,5 @@
1
- """Slots: the worktrees agents run in. Slot 1 is the PR worktree, slots 2..N live under .agent/worktrees/.
1
+ """Slots: the worktrees agents run in. Slot 1 is the PR worktree, slots 2..N live under .agent/worktrees/, and so
2
+ does BASE_SLOT, of the end of run's full gate on the base commit (driver_final_gate).
2
3
 
3
4
  Every path is relative to the PR worktree, which is the driver's working directory for the whole run.
4
5
  """
@@ -55,6 +56,9 @@ def path(number: int) -> str:
55
56
  return "." if number == 1 else f".agent/worktrees/slot-{number}"
56
57
 
57
58
 
59
+ BASE_SLOT = ".agent/worktrees/slot-base" # the end of run's full gate on the base commit (driver_final_gate)
60
+
61
+
58
62
  def _owned_checkout(slot: str) -> bool:
59
63
  """An existing slot must be this repository's checkout at exactly the assigned path."""
60
64
  common = git(slot, "rev-parse", "--path-format=absolute", "--git-common-dir")
@@ -68,25 +72,38 @@ def _owned_checkout(slot: str) -> bool:
68
72
 
69
73
  def create(number: int, prepare: str | None, keep: bool = False, *, start: str = "HEAD") -> str:
70
74
  """Make and prepare slot 2..N once, or reuse it off any branch (`keep`: as it is). Returns "" or the error."""
71
- slot = path(number)
75
+ return make(path(number), f"slot {number}", prepare, keep, start=start)
76
+
77
+
78
+ def make(slot: str, name: str, prepare: str | None, keep: bool = False, *, start: str = "HEAD") -> str:
79
+ """Make and prepare the worktree `slot` once, or reuse it off any branch (`keep`: as it is). Returns "" or the
80
+ error, which starts with `name`."""
72
81
  if Path(slot, ".git").exists():
73
- if not _owned_checkout(slot):
74
- return f"slot {number}: {slot} is not a healthy checkout of this repository; inspect it before retrying"
75
- if not (keep or release(slot)):
76
- return f"slot {number}: {slot} could not be released: inspect its Git state and uncommitted changes"
77
- return ""
82
+ return _reuse(name, slot, keep)
78
83
  # One force recovers this missing slot registration only; a locked registration still fails.
79
84
  # Never prune: another session may mount the shared metadata without its sibling checkouts.
80
85
  added = git(".", "worktree", "add", "-q", "--force", "--detach", slot, start)
81
86
  if added.returncode:
82
- return f"slot {number}: cannot create {slot}: {added.stderr.strip()}"
83
- if not prepare:
84
- return ""
87
+ return f"{name}: cannot create {slot}: {added.stderr.strip()}"
88
+ return _prepare(name, slot, prepare) if prepare else ""
89
+
90
+
91
+ def _reuse(name: str, slot: str, keep: bool) -> str:
92
+ """"" when the existing `slot` is this repository's and, unless `keep`, off any branch; else the error."""
93
+ if not _owned_checkout(slot):
94
+ return f"{name}: {slot} is not a healthy checkout of this repository; inspect it before retrying"
95
+ if not (keep or release(slot)):
96
+ return f"{name}: {slot} could not be released: inspect its Git state and uncommitted changes"
97
+ return ""
98
+
99
+
100
+ def _prepare(name: str, slot: str, prepare: str) -> str:
101
+ """Run `prepare` in the new `slot`; on a failure remove the slot and return the error."""
85
102
  done = subprocess.run(prepare, shell=True, cwd=slot, capture_output=True, text=True, stdin=subprocess.DEVNULL)
86
103
  if done.returncode:
87
104
  # An unprepared slot must not look ready to the next run.
88
105
  git(".", "worktree", "remove", "--force", slot)
89
- return (f"slot {number}: --prepare `{prepare}` exited {done.returncode} in {slot}: "
106
+ return (f"{name}: --prepare `{prepare}` exited {done.returncode} in {slot}: "
90
107
  f"{(done.stderr or done.stdout).strip()}")
91
108
  return ""
92
109
 
@@ -108,3 +125,36 @@ def release(slot: str) -> bool:
108
125
  if status.returncode or status.stdout.strip():
109
126
  return False
110
127
  return git(slot, "checkout", "-q", "--detach").returncode == 0
128
+
129
+
130
+ def fresh(patch: Path) -> Path:
131
+ """`patch`, or `<stem>-<n><suffix>` for the first n from 2 that names no file: a snapshot never replaces one that
132
+ an earlier, partly failed set-aside wrote."""
133
+ n, free = 1, patch
134
+ while free.exists():
135
+ n += 1
136
+ free = patch.with_name(f"{patch.stem}-{n}{patch.suffix}")
137
+ return free
138
+
139
+
140
+ def set_aside(slot: str, patch: Path) -> str:
141
+ """Save the uncommitted work of the slot, untracked files too, as a binary patch on its HEAD at `patch`, then take
142
+ the slot off its branch with a clean tree; ignored files stay. "" or the error: until the whole patch is at
143
+ `patch`, the work stays where it is."""
144
+ patch.parent.mkdir(parents=True, exist_ok=True)
145
+ partial = patch.with_name(f"{patch.name}.partial")
146
+ if error := _steps(slot, ("add", "-A"), ("diff", "--cached", "--binary", f"--output={partial.resolve()}", "HEAD")):
147
+ return error
148
+ partial.replace(patch)
149
+ if error := _steps(slot, ("reset", "-q", "--hard"), ("clean", "-q", "-fd")):
150
+ return error
151
+ return "" if release(slot) else f"{slot} could not be taken off its branch"
152
+
153
+
154
+ def _steps(slot: str, *steps: tuple[str, ...]) -> str:
155
+ """Run the git `steps` in `slot` in order. "" or the error of the first that fails, which stops the rest."""
156
+ for step in steps:
157
+ done = git(slot, *step)
158
+ if done.returncode:
159
+ return f"git {step[0]} failed in {slot}: {done.stderr.strip()}"
160
+ return ""
@@ -3,14 +3,16 @@
3
3
  {"run": {revision, pr_branch, schema, gates: {fast, full}, stops, agents: [{ticket, role, entry, seconds, cost, tokens}], questions, start,
4
4
  landed: [[ticket, the PR tip its merge made]], final},
5
5
  "tickets": {"NN": {phase, round, tip, test_writer_sha, locked, green_gates, slot, note,
6
- landing, disputes, corrected, settled}}}
6
+ landing, disputes, corrected, settled, replayed}}}
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 a legacy commit whose full gate was red at the landing while the fixer of the round it started has
10
10
  not reported, else None. disputes is {<locked file>::<test>: {test, requirement, ruling, reason}}, the reviewer's
11
11
  ruling on the test; corrected is {<locked file>::<test>: {test, requirement, reason}}, the reading of its one
12
12
  correction. A locked test has at most one of each per ticket. settled counts the arbitrations and review corrections
13
- of the ticket's locked tests. No answer writes the three."""
13
+ of the ticket's locked tests. No answer writes the three. replayed is the ticket tip that a replay onto the rewritten
14
+ PR branch started from (driver_final.replay): while it is the recorded tip, the ticket branch may be elsewhere, and the
15
+ landing puts it back there."""
14
16
  from __future__ import annotations
15
17
 
16
18
  import fcntl
@@ -24,8 +26,9 @@ from typing import IO
24
26
  from driver_names import Names
25
27
  from driver_slots import ancestor, git, on_branch, path
26
28
 
27
- SCHEMA = 5 # the version of this contract; 2: the names of driver_names, 3: gate tiers, 4: the two question kinds and
28
- # the ruling kept on an answered question, 5: disputes and corrected per locked test. A run of an older driver has none.
29
+ SCHEMA = 6 # the version of this contract; 2: the names of driver_names, 3: gate tiers, 4: the two question kinds and
30
+ # the ruling kept on an answered question, 5: disputes and corrected per locked test, 6: the `finding-must-fix` kind.
31
+ # A run of an older driver has none.
29
32
  PHASES = ("pending", "test-writer", "implement", "gate", "review", "fix", "merge", "merged", "blocked")
30
33
 
31
34
 
@@ -36,15 +39,17 @@ def tiers() -> dict:
36
39
 
37
40
  def _ticket() -> dict:
38
41
  return {"phase": "pending", "round": 0, "tip": None, "test_writer_sha": None, "locked": [], "green_gates": tiers(),
39
- "slot": None, "note": "", "landing": None, "disputes": {}, "corrected": {}, "settled": 0}
42
+ "slot": None, "note": "", "landing": None, "disputes": {}, "corrected": {}, "settled": 0,
43
+ "replayed": None}
40
44
 
41
45
 
42
46
  def _final() -> dict:
43
47
  """The end-of-run record before it starts. Every key is here, so a reader uses [] and a wrong name fails."""
44
48
  return {"skipped": "", "phase": "pending", "recovery": None, "tidied": None, "onto": None, "base": None,
45
49
  "commits": {}, "reviewed": None, "round": 0, "open": [], "must_fix": [], "lenses": {}, "batch": None,
46
- "gate_repairs": 0, "gate_allowance": 1, "gate_failure": None, "green_gates": tiers(), "pushed": None, "body": None, "pr": None,
47
- "draft": False}
50
+ "locked": None, "gate_repairs": 0, "gate_allowance": 1, "gate_failure": None, "base_gate": None,
51
+ "gate_preexisting": None, "green_gates": tiers(), "pushed": None, "body": None, "pr": None, "draft": False,
52
+ "ship": None}
48
53
 
49
54
 
50
55
  class State:
@@ -107,19 +112,28 @@ def verified(entry: dict, branch: str, pr_branch: str) -> tuple[dict, str]:
107
112
  return {}, ""
108
113
  # The branch of a merged ticket is deleted, so its commits are trusted only while the PR branch has them.
109
114
  where, word = (pr_branch, "in") if phase == "merged" else (branch, "on")
110
- if ancestor(tip, where):
115
+ if ancestor(tip, where) or (phase == "merge" and entry["replayed"] == entry["tip"]):
111
116
  return {}, ""
112
117
  return {"phase": "implement", "tip": entry["test_writer_sha"]}, f"the recorded tip {tip[:7]} is not {word} {where}"
113
118
 
114
119
 
115
120
  def kept(state: dict) -> dict[str, int]:
116
121
  """ticket number -> slot, per ticket stopped mid-role or at an open question, with uncommitted work in the slot."""
117
- found = {}
118
122
  asking = {question["ticket"] for question in state.get("run", {}).get("questions", []) if question["answer"] is None}
119
- for number, entry in state.get("tickets", {}).items():
120
- if (entry["phase"] in ("test-writer", "implement") or number in asking) and entry["slot"]:
121
- slot = path(entry["slot"])
122
- on = on_branch(slot)
123
- if on == Names(state["run"]["pr_branch"]).ticket(number) and git(slot, "status", "--porcelain").stdout.strip():
124
- found[number] = entry["slot"]
125
- return found
123
+ return {number: entry["slot"] for number, entry in state.get("tickets", {}).items()
124
+ if _stopped(entry, number in asking) and holds_work(state, number)}
125
+
126
+
127
+ def _stopped(entry: dict, asking: bool) -> bool:
128
+ """The ticket stopped mid-role, or at an open question when `asking`."""
129
+ return entry["phase"] in ("test-writer", "implement") or asking
130
+
131
+
132
+ def holds_work(state: dict, number: str) -> bool:
133
+ """Whether the slot of ticket `number` holds its uncommitted work: the slot is on its ticket branch, and dirty."""
134
+ entry = state["tickets"][number]
135
+ if not entry["slot"]:
136
+ return False
137
+ slot = path(entry["slot"])
138
+ return (on_branch(slot) == Names(state["run"]["pr_branch"]).ticket(number)
139
+ and bool(git(slot, "status", "--porcelain").stdout.strip()))
@@ -27,9 +27,16 @@ def _stops(run: dict) -> list[tuple[str, object]]:
27
27
 
28
28
 
29
29
  def _decisions(run: dict) -> list[str]:
30
- """What the driver decided without the operator, for the end of the summary."""
31
- rulings = driver_decisions.rulings(driver_decisions.without_operator(run.get("questions", [])))
32
- return ["", "Driver decisions, taken without the operator:", *(f"- {ruling}" for ruling in rulings)] * bool(rulings)
30
+ """What the driver decided without the operator, for the end of the summary, then the rulings the operator
31
+ overturned, each as the operator's ruling that overturns it, with the question id the operator names."""
32
+ questions = run.get("questions", [])
33
+ return [*_listed("Driver decisions, taken without the operator:", driver_decisions.without_operator(questions)),
34
+ *_listed("Overturned by the operator:", driver_decisions.overturned(questions))]
35
+
36
+
37
+ def _listed(heading: str, questions: list[dict]) -> list[str]:
38
+ rulings = [f"- {q['id']}: {ruling}" for q, ruling in zip(questions, driver_decisions.rulings(questions))]
39
+ return ["", heading, *rulings] * bool(rulings)
33
40
 
34
41
 
35
42
  def _cost(agents: list[dict]) -> list[tuple[str, object]]:
@@ -5,12 +5,16 @@ Tickets: {tickets}
5
5
  PR branch: {pr_branch}, at commit {start_sha}
6
6
  Ledger of the run, one sentence per event: {ledger}
7
7
 
8
- The run is out of retries. Each question below is a finding that the scoped review left open after the last fix batch. No operator is asked: your ruling decides whether the PR ships with it.
8
+ The run is out of retries. No operator is asked: your ruling decides each question below. Rule only with the options the question lists.
9
9
  {questions}
10
- Read each finding in its evidence file, the code it points at, and what the ledger says about the fix batches that tried it. Then rule on each question.
10
+ A finding question is a finding that the scoped review left open after the last fix batch. Read the finding in its evidence file, the code it points at, and what the ledger says about the fix batches that tried it.
11
11
  `accept`: the PR ships with the finding open and listed in its rulings. Take it when the finding is wrong, already handled, or too small to hold the PR.
12
12
  `follow-up`: the PR ships, and the driver files the finding as an issue. Take it when the finding is real and worth a change of its own.
13
- A critical finding, or a must-fix one carried from a ticket that merged at its fix cap, opens the PR as draft whichever you rule; say so in the cost when it matters.
13
+ Each finding here is important, not critical and not must-fix: no agent ships those, so they never come to you. The PR opens as draft whichever you rule, so the operator reviews it before it merges.
14
+ A spec-ambiguous question is a locked test that the spec supports two ways. Its evidence file names the test, the requirement and the two readings. Read the requirement in the spec, and the test with `git show <ticket branch>:<file>`.
15
+ `keep-test`: the test stands, and the role that disputed it makes it green. Take it when the first reading, the test as it is, is the better reading of the spec.
16
+ `correct-test`: the test-writer corrects the test to the second reading. Take it when the second reading is the better one.
17
+ Editing the spec is not yours: when neither reading holds, rule the one that costs the least to undo, and say so in the cost.
14
18
  In `question`, copy the question id as the list gives it. In `reason`, say why, so that the operator can check your ruling from it alone. In `cost`, say what goes wrong if your ruling is wrong.
15
19
  Do not commit, do not change a file and do not dispatch subagents. Leave the tree as you found it.
16
20
 
@@ -24,7 +28,7 @@ Write one JSON report at {report}. When your sandbox is read-only, give the JSON
24
28
  "status": {"enum": ["DONE", "DONE_WITH_CONCERNS", "NEEDS_CONTEXT", "BLOCKED"]},
25
29
  "files": {"type": "array", "items": {"type": "string"}},
26
30
  "concerns": {"type": "array", "items": {"type": "string"}},
27
- "rulings": {"type": "array", "items": {"type": "object", "required": ["question", "ruling", "reason", "cost"], "properties": {"question": {"type": "string", "minLength": 1}, "ruling": {"enum": ["accept", "follow-up"]}, "reason": {"type": "string", "minLength": 1}, "cost": {"type": "string", "minLength": 1}}}}
31
+ "rulings": {"type": "array", "items": {"type": "object", "required": ["question", "ruling", "reason", "cost"], "properties": {"question": {"type": "string", "minLength": 1}, "ruling": {"enum": ["accept", "follow-up", "keep-test", "correct-test"]}, "reason": {"type": "string", "minLength": 1}, "cost": {"type": "string", "minLength": 1}}}}
28
32
  }
29
33
  }
30
34
  ```
@@ -6,7 +6,7 @@ Branch: {branch}, at commit {start_sha}
6
6
  PR branch: {pr_branch}, at commit {pr_sha}
7
7
  Files in conflict: {files}
8
8
 
9
- The merge of the PR branch into the ticket branch is open in this worktree and it has conflicts in those files.
9
+ {opened} 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
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.
12
12
  Run the targeted tests of the files you resolved. The driver runs the gate on your commit.
@@ -14,7 +14,8 @@ One commit per ticket, in merge order:
14
14
 
15
15
  ## Review coverage
16
16
 
17
- - Branch tip and reviewed tip: {tip}
17
+ - {tips}
18
18
  - Full review: {full_review}
19
19
  - Scoped review after the fix batch: {scoped}
20
20
  {providers}
21
+ {gate}
@@ -4,7 +4,7 @@ Use this only when an older run stopped after two implementer attempts and left
4
4
 
5
5
  Stop the driver and prevent the dispatcher from resuming it during recovery. In the PR worktree, preserve any dirty files with a binary patch and exact file copies outside tracked paths. Do not reset the checkout or overwrite locked tests. Keep the branch and driver records; recovery adds a question, not a passing gate.
6
6
 
7
- Read the ticket's ledger and reports. Confirm that the implementer stopped before any accepted implementation and that its recorded tip is still the test-writer commit. The command below accepts only that narrow checkpoint: schema 5, round zero, no gate results, no prior question for this ticket, two recorded implementer attempts, and an intact test-writer commit on the ticket branch. Other phases, uncertain evidence, or prior operator decisions require investigation; do not guess a phase or delete state to start over.
7
+ Read the ticket's ledger and reports. Confirm that the implementer stopped before any accepted implementation and that its recorded tip is still the test-writer commit. The command below accepts only that narrow checkpoint: schema 5 or 6, round zero, no gate results, no prior question for this ticket, two recorded implementer attempts, and an intact test-writer commit on the ticket branch. Other phases, uncertain evidence, or prior operator decisions require investigation; do not guess a phase or delete state to start over.
8
8
 
9
9
  Run the following from the PR worktree, replacing the skill path, ticket number and full verified test-writer SHA. It takes the driver's locks, backs up state, records a question through the existing helper and leaves the ticket BLOCKED. No checkout, branch or gate is changed.
10
10
 
@@ -35,7 +35,7 @@ with held:
35
35
  entry = data['tickets'][number]
36
36
  attempts = [a['role'] for a in data['run']['agents'] if a['ticket'] == number]
37
37
  branch = driver_names.Names(pr).ticket(number)
38
- valid = (data['run']['schema'] == 5 and entry['phase'] == 'blocked'
38
+ valid = (data['run']['schema'] in (5, 6) and entry['phase'] == 'blocked'
39
39
  and entry['round'] == 0 and entry['tip'] == entry['test_writer_sha'] == tip
40
40
  and entry['locked'] and not any(entry['green_gates'].values())
41
41
  and not any(q['ticket'] == number for q in data['run']['questions'])
@@ -47,8 +47,8 @@ with held:
47
47
  with backup.open('xb') as out:
48
48
  out.write(before)
49
49
  def recover(current):
50
- driver_decisions.stop(current['run'], 'ticket-blocked', number,
51
- ['Operator verified the repaired environment and pre-implementation checkpoint.'],
50
+ driver_decisions.stop(current['run'], number, [('ticket-blocked',
51
+ 'Operator verified the repaired environment and pre-implementation checkpoint.', None)],
52
52
  ['.agent/implement/ledger.md'], driver_decisions.Resume('implement', tip))
53
53
  updated = state.update(recover)
54
54
  question = updated['run']['questions'][-1]['id']
@@ -29,6 +29,7 @@ def pr_skill(tmp_path_factory):
29
29
  patch.setenv("XDG_CONFIG_HOME", str(tmp_path_factory.mktemp("config-home")))
30
30
  # The tests of a stop see its question: the driver answers none itself unless a test passes --retries.
31
31
  patch.setenv("IMPLEMENT_SPEC_RETRIES", "0")
32
+ patch.setenv("IMPLEMENT_SPEC_MUST_FIX_RETRIES", "0")
32
33
  # and no arbiter rules in their place, unless a test passes --no-ask.
33
34
  patch.setenv("IMPLEMENT_SPEC_ASK", "1")
34
35
  yield home / "skills/pr/SKILL.md"
@@ -1,7 +1,8 @@
1
1
  """The arbiter: when the driver's own retries are spent on a finding the scoped review leaves open, one read-only
2
- agent on another provider than the implementer rules `accept` or `follow-up` on it, and the PR opens: draft when a
3
- critical finding stays open, ready otherwise. `--ask` (IMPLEMENT_SPEC_ASK=1, which conftest pins) asks the operator
4
- instead.
2
+ agent on another provider than the implementer rules `accept` or `follow-up` on it, and the PR opens as draft. A
3
+ critical or must-fix finding asks `finding-must-fix`, never the arbiter's: the driver runs `--must-fix-retries` more fix
4
+ batches on it, then asks the operator. `--ask` (IMPLEMENT_SPEC_ASK=1, which conftest pins) asks the operator instead
5
+ of the arbiter.
5
6
 
6
7
  In process, on the rig of test_scoped."""
7
8
  import json
@@ -17,6 +18,7 @@ from test_tidy import tools # noqa: F401 (tools is an autouse fixture)
17
18
  from test_walk import plan
18
19
 
19
20
  Q = "final-finding-open-1"
21
+ MUST_FIX = "final-finding-must-fix-1"
20
22
  LEAK = finding("token logged in clear", severity="critical", file="auth.py", line=7)
21
23
  ARBITER = {**MODELS, "arbiter": [OPUS, ASTRA]} # the implementer is on anthropic, so the arbiter runs on ASTRA
22
24
 
@@ -41,27 +43,82 @@ def gh(rig, verb):
41
43
  return [row for row in rows if row["argv"][:2] == verb]
42
44
 
43
45
 
44
- def test_the_arbiter_accepts_an_important_finding_and_the_pr_opens_ready_with_its_ruling(tmp_path):
46
+ def test_the_arbiter_accepts_an_important_finding_and_the_pr_opens_as_draft_with_its_ruling(tmp_path):
45
47
  rig, _ = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "accept"))])
46
48
  assert rig.code == 0 and rig.pushes(), rig.out
47
49
  (arbiter,) = rig.final_calls("arbiter")
48
50
  assert Q in arbiter["prompt"] and "findings-1.json" in arbiter["prompt"]
49
51
  assert rig.led(f"End of run: arbiter ran on {ASTRA}")
50
52
  (pr,) = rig.prs()
51
- assert "--draft" not in pr["argv"]
53
+ assert "--draft" in pr["argv"]
54
+ assert rig.led("The PR of feat/csv into main is open as a draft: a finding ships open: ledger write not atomic")
52
55
  line = ("Ruling: final ships with the finding open (accept): ledger write not atomic (ledger.py). Ruled by "
53
56
  "the arbiter, not the operator: why accept. Cost if wrong: cost of accept.")
54
57
  assert f"- {line}" in pr["body"] and line in (rig.repo / ".agent/implement/summary.md").read_text()
55
- assert stage(rig) == {"stage": "implement", "status": "done", "draft": False, "decisions": 1}
58
+ assert stage(rig) == {"stage": "implement", "status": "done", "draft": True, "decisions": 1}
56
59
  assert len(rig.final_calls("fixer")) == 1, "an accepted finding gets no fix batch"
57
60
 
58
61
 
59
- def test_an_accepted_critical_finding_opens_the_pr_as_draft(tmp_path):
60
- rig, _ = open_after_batch(tmp_path, LEAK, [ruled(("final-finding-open-1", "accept"))])
61
- assert rig.code == 0, rig.out
62
+ def test_a_critical_finding_is_not_the_arbiters_and_parks_once_the_must_fix_retries_are_spent(tmp_path):
63
+ rig, _ = open_after_batch(tmp_path, LEAK, [], "--must-fix-retries", "0")
64
+ assert rig.code == 2 and not rig.pushes() and not rig.final_calls("arbiter"), rig.out
65
+ (question,) = decisions(rig)["questions"]
66
+ assert question["id"] == MUST_FIX and "only you may" in question["why"]
67
+
68
+
69
+ def test_an_open_question_of_a_schema_5_run_on_a_critical_finding_becomes_must_fix_and_the_arbiter_never_rules(
70
+ tmp_path):
71
+ """A run resumed from before the `finding-must-fix` kind asked `finding-open` on a critical finding: it becomes
72
+ `finding-must-fix` with its id, so the arbiter, whose turn it would be, never rules on it."""
73
+ rig, steps = open_after_batch(tmp_path, LEAK, [], "--must-fix-retries", "0")
74
+ state = rig.state() # as the driver of schema 5 left it
75
+ (question,) = state["run"]["questions"]
76
+ question.update(kind="finding-open", id=Q)
77
+ state["run"]["schema"] = 5
78
+ (rig.repo / ".agent/implement/state.json").write_text(json.dumps(state))
79
+ steps["final/arbiter"] = [ruled((Q, "accept"))]
80
+ rig.run(steps, "--no-ask", "--retries", "0", "--must-fix-retries", "0", *UNATTENDED)
81
+ assert rig.code == 2 and not rig.pushes() and not rig.final_calls("arbiter"), rig.out
82
+ (question,) = rig.state()["run"]["questions"]
83
+ assert (question["id"], question["kind"], question["answer"]) == (Q, "finding-must-fix", None)
84
+
85
+
86
+ def test_a_critical_finding_gets_the_must_fix_retries_of_the_driver_after_its_own(tmp_path):
87
+ rig, _ = open_after_batch(tmp_path, LEAK, [], "--must-fix-retries", "1", **{
88
+ "final/final-reviewer": [final(LEAK), final()],
89
+ "final/fixer": [fixer(fn("02"), "fix it"), fixer(fn("02"), "fix it again")]})
90
+ assert rig.code == 0 and not rig.final_calls("arbiter"), rig.out
91
+ assert len(rig.final_calls("fixer")) == 2 and rig.led("Ruling: final runs again (retry)")
62
92
  (pr,) = rig.prs()
63
- assert "--draft" in pr["argv"] and stage(rig)["draft"] is True
64
- assert rig.led("The PR of feat/csv into main is open as a draft: a critical or must-fix finding is open")
93
+ assert "--draft" not in pr["argv"] and stage(rig)["draft"] is False
94
+
95
+
96
+ def test_the_arbiter_rules_on_the_important_finding_of_a_stop_and_leaves_the_critical_one_to_the_operator(tmp_path):
97
+ both = [final(LEAK, ATOMIC)]
98
+ rig, _ = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "accept"))], "--must-fix-retries", "0",
99
+ **{"final/final-spec": both, "final/final-reviewer": both})
100
+ assert rig.code == 2 and not rig.pushes(), rig.out
101
+ (arbiter,) = rig.final_calls("arbiter")
102
+ assert Q in arbiter["prompt"] and MUST_FIX not in arbiter["prompt"]
103
+ assert [q["id"] for q in decisions(rig)["questions"]] == [MUST_FIX]
104
+ assert rig.led("End of run: the operator decides on 1 question of kind finding-must-fix and 1 question of kind "
105
+ "finding-open")
106
+
107
+
108
+ def test_an_important_finding_the_arbiter_accepted_that_turns_critical_asks_the_operator(tmp_path):
109
+ """The arbiter ships the important finding while the critical one gets another batch; the next scoped review rates
110
+ the first critical: the arbiter's waiver no longer covers it, so it asks `finding-must-fix` and nothing is
111
+ pushed."""
112
+ both = [final(LEAK, ATOMIC)]
113
+ rig, _ = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "accept"))], "--must-fix-retries", "1", **{
114
+ "final/final-spec": both, "final/final-reviewer": [*both, final({**ATOMIC, "severity": "critical"})],
115
+ "final/fixer": [fixer(fn("02"), "fix it"), fixer(fn("02"), "fix the leak")]})
116
+ assert rig.code == 2 and not rig.pushes(), rig.out
117
+ assert len(rig.final_calls("fixer")) == 2 and len(rig.final_calls("arbiter")) == 1
118
+ (question,) = decisions(rig)["questions"]
119
+ assert (question["id"], question["title"]) == ("final-finding-must-fix-2", "End of run: a critical or must-fix "
120
+ "finding is open after the scoped review: ledger write not atomic "
121
+ "(ledger.py)")
65
122
 
66
123
 
67
124
  def test_a_follow_up_is_filed_as_an_issue_before_the_pr_and_the_pr_body_links_it(tmp_path):
@@ -138,14 +195,14 @@ def test_a_pr_body_that_stays_invalid_files_no_follow_up_issue(tmp_path):
138
195
  assert rig.code != 0 and not gh(rig, ["issue", "create"]) and not rig.prs(), rig.out
139
196
 
140
197
 
141
- def test_an_accepted_must_fix_finding_opens_the_pr_as_draft(tmp_path):
198
+ def test_a_must_fix_finding_is_not_the_arbiters_and_parks_once_the_must_fix_retries_are_spent(tmp_path):
142
199
  rig = Inside(tmp_path, RISKY, {**ARBITER})
143
200
  escaping = {**finding("quote escaping", file="csv.py", line=30), "basis": "regression"}
144
201
  batch = fixer(fn("02"), "escape quotes", ticket_of="02")
145
202
  batch["report"]["addressed_must_fix"] = ["quote escaping (csv.py:30)"]
146
203
  rig.run(plan(**{"02/reviewer": [review("02", [escaping])] * 3, "02/fixer": [fix("02", 1), fix("02", 2)],
147
- "final/final-reviewer": [final()], "final/fixer": [batch],
148
- "final/arbiter": [ruled((Q, "accept"))]}), "--no-ask", "--retries", "0", *UNATTENDED)
149
- assert rig.code == 0, rig.out
150
- (pr,) = rig.prs()
151
- assert "--draft" in pr["argv"] and rig.led("open as a draft: a critical or must-fix finding is open: quote escaping")
204
+ "final/final-reviewer": [final()], "final/fixer": [batch], "final/arbiter": [ruled((Q, "accept"))]}),
205
+ "--no-ask", "--retries", "0", "--must-fix-retries", "0", *UNATTENDED)
206
+ assert rig.code == 2 and not rig.pushes() and not rig.final_calls("arbiter"), rig.out
207
+ (question,) = decisions(rig)["questions"]
208
+ assert question["id"] == MUST_FIX and "quote escaping (csv.py)" in question["title"]
@@ -173,7 +173,7 @@ def test_a_second_dispute_on_the_same_test_asks_spec_ambiguous_with_both_reading
173
173
  assert len(arbitrations(rig)) == 1, "no second arbitration"
174
174
  (question,) = asked(rig)
175
175
  assert question["id"] == AMBIGUOUS and question["recommended"] == ""
176
- assert [option["id"] for option in question["options"]] == ["keep-test", "correct-test", "edit-spec"]
176
+ assert [option["id"] for option in question["options"]] == ["keep-test", "correct-test", "leave-out", "edit-spec"]
177
177
  for part in (second, "R3", "R3 says double quotes", "the example in R3 uses '"):
178
178
  assert part in question["subject"], part
179
179
  page = (rig.repo / ".agent/implement-review.html").read_text()