@jesdi/skills 0.0.98 → 0.0.100

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 +10 -5
  3. package/skills/implement-spec/README.md +44 -17
  4. package/skills/implement-spec/SKILL.md +4 -2
  5. package/skills/implement-spec/driver.py +166 -40
  6. package/skills/implement-spec/driver_agents.py +26 -8
  7. package/skills/implement-spec/driver_arbiter.py +89 -0
  8. package/skills/implement-spec/driver_decisions.py +212 -39
  9. package/skills/implement-spec/driver_dispute.py +1 -1
  10. package/skills/implement-spec/driver_final.py +255 -186
  11. package/skills/implement-spec/driver_final_gate.py +1 -1
  12. package/skills/implement-spec/driver_legacy.py +15 -2
  13. package/skills/implement-spec/driver_overturn.py +106 -0
  14. package/skills/implement-spec/driver_pr.py +277 -0
  15. package/skills/implement-spec/driver_report.py +24 -6
  16. package/skills/implement-spec/driver_review.py +10 -4
  17. package/skills/implement-spec/driver_run.py +38 -15
  18. package/skills/implement-spec/driver_slots.py +33 -0
  19. package/skills/implement-spec/driver_state.py +29 -15
  20. package/skills/implement-spec/driver_summary.py +11 -4
  21. package/skills/implement-spec/models.json +2 -1
  22. package/skills/implement-spec/prompts/arbiter.md +38 -0
  23. package/skills/implement-spec/prompts/conflict.md +1 -1
  24. package/skills/implement-spec/prompts/pr-body.md +1 -1
  25. package/skills/implement-spec/recovery.md +4 -4
  26. package/skills/implement-spec/tests/conftest.py +3 -0
  27. package/skills/implement-spec/tests/test_arbiter.py +208 -0
  28. package/skills/implement-spec/tests/test_arbitration.py +1 -1
  29. package/skills/implement-spec/tests/test_cli.py +1 -1
  30. package/skills/implement-spec/tests/test_decisions.py +31 -7
  31. package/skills/implement-spec/tests/test_driver.py +10 -2
  32. package/skills/implement-spec/tests/test_final.py +34 -9
  33. package/skills/implement-spec/tests/test_fixloop.py +2 -2
  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_report.py +1 -1
  39. package/skills/implement-spec/tests/test_scoped.py +18 -15
  40. package/skills/implement-spec/tests/test_ship_draft.py +203 -0
  41. package/skills/implement-spec/tests/test_slots.py +29 -0
  42. package/skills/implement-spec/tests/test_state.py +4 -2
  43. package/skills/implement-spec/tests/test_stops.py +21 -5
  44. package/skills/implement-spec/tests/test_tidy.py +7 -5
  45. package/skills-manifest.json +3 -3
@@ -108,3 +108,36 @@ def release(slot: str) -> bool:
108
108
  if status.returncode or status.stdout.strip():
109
109
  return False
110
110
  return git(slot, "checkout", "-q", "--detach").returncode == 0
111
+
112
+
113
+ def fresh(patch: Path) -> Path:
114
+ """`patch`, or `<stem>-<n><suffix>` for the first n from 2 that names no file: a snapshot never replaces one that
115
+ an earlier, partly failed set-aside wrote."""
116
+ n, free = 1, patch
117
+ while free.exists():
118
+ n += 1
119
+ free = patch.with_name(f"{patch.stem}-{n}{patch.suffix}")
120
+ return free
121
+
122
+
123
+ def set_aside(slot: str, patch: Path) -> str:
124
+ """Save the uncommitted work of the slot, untracked files too, as a binary patch on its HEAD at `patch`, then take
125
+ the slot off its branch with a clean tree; ignored files stay. "" or the error: until the whole patch is at
126
+ `patch`, the work stays where it is."""
127
+ patch.parent.mkdir(parents=True, exist_ok=True)
128
+ partial = patch.with_name(f"{patch.name}.partial")
129
+ if error := _steps(slot, ("add", "-A"), ("diff", "--cached", "--binary", f"--output={partial.resolve()}", "HEAD")):
130
+ return error
131
+ partial.replace(patch)
132
+ if error := _steps(slot, ("reset", "-q", "--hard"), ("clean", "-q", "-fd")):
133
+ return error
134
+ return "" if release(slot) else f"{slot} could not be taken off its branch"
135
+
136
+
137
+ def _steps(slot: str, *steps: tuple[str, ...]) -> str:
138
+ """Run the git `steps` in `slot` in order. "" or the error of the first that fails, which stops the rest."""
139
+ for step in steps:
140
+ done = git(slot, *step)
141
+ if done.returncode:
142
+ return f"git {step[0]} failed in {slot}: {done.stderr.strip()}"
143
+ 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,14 +39,16 @@ 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}
50
+ "locked": None, "gate_repairs": 0, "gate_allowance": 1, "gate_failure": None, "green_gates": tiers(),
51
+ "pushed": None, "body": None, "pr": None, "draft": False, "ship": None}
47
52
 
48
53
 
49
54
  class State:
@@ -106,19 +111,28 @@ def verified(entry: dict, branch: str, pr_branch: str) -> tuple[dict, str]:
106
111
  return {}, ""
107
112
  # The branch of a merged ticket is deleted, so its commits are trusted only while the PR branch has them.
108
113
  where, word = (pr_branch, "in") if phase == "merged" else (branch, "on")
109
- if ancestor(tip, where):
114
+ if ancestor(tip, where) or (phase == "merge" and entry["replayed"] == entry["tip"]):
110
115
  return {}, ""
111
116
  return {"phase": "implement", "tip": entry["test_writer_sha"]}, f"the recorded tip {tip[:7]} is not {word} {where}"
112
117
 
113
118
 
114
119
  def kept(state: dict) -> dict[str, int]:
115
120
  """ticket number -> slot, per ticket stopped mid-role or at an open question, with uncommitted work in the slot."""
116
- found = {}
117
121
  asking = {question["ticket"] for question in state.get("run", {}).get("questions", []) if question["answer"] is None}
118
- for number, entry in state.get("tickets", {}).items():
119
- if (entry["phase"] in ("test-writer", "implement") or number in asking) and entry["slot"]:
120
- slot = path(entry["slot"])
121
- on = on_branch(slot)
122
- if on == Names(state["run"]["pr_branch"]).ticket(number) and git(slot, "status", "--porcelain").stdout.strip():
123
- found[number] = entry["slot"]
124
- return found
122
+ return {number: entry["slot"] for number, entry in state.get("tickets", {}).items()
123
+ if _stopped(entry, number in asking) and holds_work(state, number)}
124
+
125
+
126
+ def _stopped(entry: dict, asking: bool) -> bool:
127
+ """The ticket stopped mid-role, or at an open question when `asking`."""
128
+ return entry["phase"] in ("test-writer", "implement") or asking
129
+
130
+
131
+ def holds_work(state: dict, number: str) -> bool:
132
+ """Whether the slot of ticket `number` holds its uncommitted work: the slot is on its ticket branch, and dirty."""
133
+ entry = state["tickets"][number]
134
+ if not entry["slot"]:
135
+ return False
136
+ slot = path(entry["slot"])
137
+ return (on_branch(slot) == Names(state["run"]["pr_branch"]).ticket(number)
138
+ and bool(git(slot, "status", "--porcelain").stdout.strip()))
@@ -22,14 +22,21 @@ def _rows(run: dict, tickets: dict) -> list[tuple[str, object]]:
22
22
 
23
23
  def _stops(run: dict) -> list[tuple[str, object]]:
24
24
  """The stops that waited for the operator, and a row for those the driver ruled on itself, when it did."""
25
- ruled = sum(driver_decisions.ruled(run.get("questions", [])).values())
25
+ ruled = len({(q["ticket"], q["stop"]) for q in driver_decisions.without_operator(run.get("questions", []))})
26
26
  return [("human stops", run["stops"] - ruled), *([("stops the driver ruled on", ruled)] if ruled else [])]
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 = [q["ruling"] for q in driver_decisions.by_driver(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,5 +5,6 @@
5
5
  "fixer": ["claude-opus-5-5@medium"],
6
6
  "final-reviewer": ["openai/gpt-6-astra@medium", "claude-opus-5-5@medium"],
7
7
  "conflict": ["claude-opus-5-5@medium"],
8
- "pr-writer": ["claude-opus-5-5@medium"]
8
+ "pr-writer": ["claude-opus-5-5@medium"],
9
+ "arbiter": ["openai/gpt-6-astra@xhigh", "claude-opus-5-5@xhigh"]
9
10
  }
@@ -0,0 +1,38 @@
1
+ # Arbiter
2
+
3
+ Spec: {spec}
4
+ Tickets: {tickets}
5
+ PR branch: {pr_branch}, at commit {start_sha}
6
+ Ledger of the run, one sentence per event: {ledger}
7
+
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
+ {questions}
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
+ `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
+ `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
+ 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.
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.
19
+ Do not commit, do not change a file and do not dispatch subagents. Leave the tree as you found it.
20
+
21
+ 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:
22
+
23
+ ```json
24
+ {
25
+ "type": "object",
26
+ "required": ["status", "files", "concerns", "rulings"],
27
+ "properties": {
28
+ "status": {"enum": ["DONE", "DONE_WITH_CONCERNS", "NEEDS_CONTEXT", "BLOCKED"]},
29
+ "files": {"type": "array", "items": {"type": "string"}},
30
+ "concerns": {"type": "array", "items": {"type": "string"}},
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}}}}
32
+ }
33
+ }
34
+ ```
35
+
36
+ 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`.
37
+ 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.
38
+ Never run `git stash`, never reset, and never check out another branch: worktrees share one stash and one ref store.
@@ -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,7 @@ 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}
@@ -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,9 @@ 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")
33
+ # and no arbiter rules in their place, unless a test passes --no-ask.
34
+ patch.setenv("IMPLEMENT_SPEC_ASK", "1")
32
35
  yield home / "skills/pr/SKILL.md"
33
36
 
34
37
 
@@ -0,0 +1,208 @@
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 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.
6
+
7
+ In process, on the rig of test_scoped."""
8
+ import json
9
+
10
+ from test_final import GH, final, fixer, fn, risk_body, writer
11
+ from test_fixloop import inside # noqa: F401 (the autouse fixture puts the rig's CLIs on PATH)
12
+ from test_lenses import ASTRA, MODELS, OPUS, rig_of
13
+ from test_review import RISKY, fix, finding, review
14
+ from test_scoped import ATOMIC
15
+ from test_tidy import Inside
16
+ from test_stops import UNATTENDED, decisions, stage
17
+ from test_tidy import tools # noqa: F401 (tools is an autouse fixture)
18
+ from test_walk import plan
19
+
20
+ Q = "final-finding-open-1"
21
+ MUST_FIX = "final-finding-must-fix-1"
22
+ LEAK = finding("token logged in clear", severity="critical", file="auth.py", line=7)
23
+ ARBITER = {**MODELS, "arbiter": [OPUS, ASTRA]} # the implementer is on anthropic, so the arbiter runs on ASTRA
24
+
25
+
26
+ def ruled(*rulings):
27
+ """An arbiter step: one (question, ruling) pair per open question."""
28
+ return {"report": {"status": "DONE", "files": [], "concerns": [], "rulings": [
29
+ {"question": question, "ruling": ruling, "reason": f"why {ruling}", "cost": f"cost of {ruling}"}
30
+ for question, ruling in rulings]}}
31
+
32
+
33
+ def open_after_batch(tmp_path, found=ATOMIC, arbiter=(), *extra, **more):
34
+ """The scoped review after the one fix batch leaves `found` open, with no retry left for the driver."""
35
+ rig = rig_of(tmp_path, models=ARBITER)
36
+ steps = plan(**{"final/final-spec": [final(found)], "final/final-reviewer": [final(found)],
37
+ "final/fixer": [fixer(fn("02"), "fix it")], "final/arbiter": list(arbiter), **more})
38
+ return rig.run(steps, "--no-ask", "--retries", "0", *UNATTENDED, *extra), steps
39
+
40
+
41
+ def gh(rig, verb):
42
+ rows = [json.loads(line) for line in rig.gh_log.read_text().splitlines()] if rig.gh_log.exists() else []
43
+ return [row for row in rows if row["argv"][:2] == verb]
44
+
45
+
46
+ def test_the_arbiter_accepts_an_important_finding_and_the_pr_opens_as_draft_with_its_ruling(tmp_path):
47
+ rig, _ = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "accept"))])
48
+ assert rig.code == 0 and rig.pushes(), rig.out
49
+ (arbiter,) = rig.final_calls("arbiter")
50
+ assert Q in arbiter["prompt"] and "findings-1.json" in arbiter["prompt"]
51
+ assert rig.led(f"End of run: arbiter ran on {ASTRA}")
52
+ (pr,) = rig.prs()
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")
55
+ line = ("Ruling: final ships with the finding open (accept): ledger write not atomic (ledger.py). Ruled by "
56
+ "the arbiter, not the operator: why accept. Cost if wrong: cost of accept.")
57
+ assert f"- {line}" in pr["body"] and line in (rig.repo / ".agent/implement/summary.md").read_text()
58
+ assert stage(rig) == {"stage": "implement", "status": "done", "draft": True, "decisions": 1}
59
+ assert len(rig.final_calls("fixer")) == 1, "an accepted finding gets no fix batch"
60
+
61
+
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)")
92
+ (pr,) = rig.prs()
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)")
122
+
123
+
124
+ def test_a_follow_up_is_filed_as_an_issue_before_the_pr_and_the_pr_body_links_it(tmp_path):
125
+ rig, steps = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "follow-up"))])
126
+ assert rig.code == 0, rig.out
127
+ (issue,) = gh(rig, ["issue", "create"])
128
+ assert issue["argv"][2:4] == ["--title", "ledger write not atomic (ledger.py)"]
129
+ assert "feat/csv" in issue["body"] and "why follow-up" in issue["body"]
130
+ (pr,) = rig.prs()
131
+ assert "(follow-up): ledger write not atomic (ledger.py)." in pr["body"]
132
+ assert "Follow-up issue: https://github.example/issues/1" in pr["body"]
133
+ assert "Follow-up issue: https://github.example/issues/1" in (rig.repo / ".agent/implement/summary.md").read_text()
134
+ rig.run(steps, "--no-ask", *UNATTENDED)
135
+ assert len(gh(rig, ["issue", "create"])) == 1, "a rerun files no second issue"
136
+
137
+
138
+ def test_a_local_run_without_push_files_no_issue(tmp_path):
139
+ rig = rig_of(tmp_path)
140
+ rig.run(plan(**{"final/final-spec": [final(ATOMIC)], "final/final-reviewer": [final(ATOMIC)],
141
+ "final/fixer": [fixer(fn("02"), "fix it")], "final/arbiter": [ruled((Q, "follow-up"))]}),
142
+ "--no-ask")
143
+ assert rig.code == 0 and not gh(rig, ["issue", "create"]) and not rig.prs(), rig.out
144
+ assert "(follow-up)" in (rig.repo / ".agent/implement/summary.md").read_text()
145
+
146
+
147
+ def test_the_arbiter_rules_only_after_the_retries_of_the_driver(tmp_path):
148
+ rig = rig_of(tmp_path)
149
+ steps = plan(**{"final/final-spec": [final(ATOMIC)], "final/final-reviewer": [final(ATOMIC), final(ATOMIC)],
150
+ "final/fixer": [fixer(fn("02"), "fix it"), fixer(fn("02"), "fix it again")],
151
+ "final/arbiter": [ruled(("final-finding-open-2", "accept"))]})
152
+ rig.run(steps, "--no-ask", "--retries", "1", *UNATTENDED)
153
+ assert rig.code == 0, rig.out
154
+ assert len(rig.final_calls("fixer")) == 2 and len(rig.final_calls("arbiter")) == 1
155
+ assert rig.led("Ruling: final runs again (retry)") and rig.led("Ruled by the arbiter")
156
+
157
+
158
+ def test_an_arbiter_that_fails_twice_leaves_the_question_to_the_operator(tmp_path):
159
+ rig, _ = open_after_batch(tmp_path, ATOMIC, [{"report": {"status": "DONE"}}] * 2)
160
+ assert rig.code == 2 and not rig.pushes(), rig.out
161
+ assert len(rig.final_calls("arbiter")) == 2
162
+ (question,) = decisions(rig)["questions"]
163
+ assert question["id"] == Q
164
+ assert rig.led("End of run: the arbiter could not rule, so the operator decides")
165
+
166
+
167
+ def test_an_arbiter_report_that_skips_a_question_is_rejected(tmp_path):
168
+ rig, _ = open_after_batch(tmp_path, ATOMIC, [ruled(), ruled((Q, "accept"))])
169
+ assert rig.code == 0, rig.out
170
+ first, _ = rig.led("End of run: arbiter ran on")
171
+ assert f"no ruling on {Q}" in first
172
+
173
+
174
+ def test_an_issue_filed_before_its_url_was_kept_is_found_again_and_not_filed_twice(tmp_path):
175
+ rig = rig_of(tmp_path, models=ARBITER)
176
+ gh_path = tmp_path / "bin/gh"
177
+ gh_path.write_text(GH.replace('log = Path', 'if sys.argv[1:3] == ["pr", "create"]:\n sys.exit("gh down")\nlog = Path', 1))
178
+ steps = plan(**{"final/final-spec": [final(ATOMIC)], "final/final-reviewer": [final(ATOMIC)],
179
+ "final/fixer": [fixer(fn("02"), "fix it")], "final/arbiter": [ruled((Q, "follow-up"))]})
180
+ rig.run(steps, "--no-ask", "--retries", "0", *UNATTENDED)
181
+ assert rig.code != 0 and len(gh(rig, ["issue", "create"])) == 1 and not rig.prs(), rig.out
182
+ state = rig.state() # as a run that stopped before state.json kept the URL leaves it
183
+ del next(q for q in state["run"]["questions"] if q["id"] == Q)["issue"]
184
+ (rig.repo / ".agent/implement/state.json").write_text(json.dumps(state))
185
+ gh_path.write_text(GH)
186
+ rig.run(steps, "--no-ask", *UNATTENDED)
187
+ assert rig.code == 0 and len(gh(rig, ["issue", "create"])) == 1, rig.out
188
+ (pr,) = rig.prs()
189
+ assert "Follow-up issue: https://github.example/issues/1" in pr["body"]
190
+
191
+
192
+ def test_a_pr_body_that_stays_invalid_files_no_follow_up_issue(tmp_path):
193
+ invalid = writer(risk_body("styles"))
194
+ rig, _ = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "follow-up"))], **{"final/pr-writer": [invalid, invalid]})
195
+ assert rig.code != 0 and not gh(rig, ["issue", "create"]) and not rig.prs(), rig.out
196
+
197
+
198
+ def test_a_must_fix_finding_is_not_the_arbiters_and_parks_once_the_must_fix_retries_are_spent(tmp_path):
199
+ rig = Inside(tmp_path, RISKY, {**ARBITER})
200
+ escaping = {**finding("quote escaping", file="csv.py", line=30), "basis": "regression"}
201
+ batch = fixer(fn("02"), "escape quotes", ticket_of="02")
202
+ batch["report"]["addressed_must_fix"] = ["quote escaping (csv.py:30)"]
203
+ rig.run(plan(**{"02/reviewer": [review("02", [escaping])] * 3, "02/fixer": [fix("02", 1), fix("02", 2)],
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()
@@ -13,7 +13,7 @@ RUN = SKILL / "run.sh"
13
13
  GIT = ["git", "-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false"]
14
14
  TOOLS = ("sh", "uname", "dirname", "readlink", "git", "env", "mktemp", "curl", "tar", "gzip", "mv", "rm", "mkdir",
15
15
  "sha256sum", "shasum", "cat", "chmod", "ln", "date", "basename")
16
- ROLES = ("test-writer", "implementer", "reviewer", "fixer", "final-reviewer", "conflict", "pr-writer")
16
+ ROLES = ("test-writer", "implementer", "reviewer", "fixer", "final-reviewer", "conflict", "pr-writer", "arbiter")
17
17
  NONE = "None (can start immediately)"
18
18
 
19
19
 
@@ -59,7 +59,7 @@ def test_a_stop_prints_the_question_and_an_answer_is_applied_once(tmp_path, caps
59
59
 
60
60
  # The question is closed: its answer cannot be given again, and the old answers file is history.
61
61
  rig.run({}, "--answer", f"{Q1}=edit")
62
- assert rig.code == 3 and f"--answer {Q1}=edit: no open question {Q1}" in capsys.readouterr().out
62
+ assert rig.code == 3 and f"--answer {Q1}=edit: you answered {Q1}: only a ruling of the driver" in capsys.readouterr().out
63
63
  rig.run({})
64
64
  assert rig.code == 0 and not rig.led("ignored") and len(rig.led("Ruling")) == 1
65
65
 
@@ -67,7 +67,7 @@ def test_a_stop_prints_the_question_and_an_answer_is_applied_once(tmp_path, caps
67
67
  def test_an_answer_with_an_option_the_question_does_not_offer_exits_3(tmp_path, capsys):
68
68
  rig = stopped(tmp_path)
69
69
  rig.run(steps(blocked(), blocked(), impl("01")), "--answer", f"{Q1}=nope")
70
- assert rig.code == 3 and f"--answer {Q1}=nope: {Q1} offers retry, edit" in capsys.readouterr().out
70
+ assert rig.code == 3 and f"--answer {Q1}=nope: {Q1} offers retry, leave-out, edit" in capsys.readouterr().out
71
71
  assert not (rig.repo / driver_answers.FILE).exists()
72
72
 
73
73
 
@@ -182,7 +182,7 @@ def test_unattended_writes_the_stage_file_and_prints_no_question(tmp_path, capsy
182
182
  assert stage(rig) == {"stage": "implement", "status": "awaiting-review", "artifact": PAGE, "open_questions": 1}
183
183
  write_answers(rig, {Q1: "retry"})
184
184
  rig.run(steps(blocked(), blocked(), impl("01")), *UNATTENDED)
185
- assert rig.code == 0 and stage(rig) == {"stage": "implement", "status": "done"}, "no stage file of the earlier run stays"
185
+ assert rig.code == 0 and stage(rig) == {"stage": "implement", "status": "done", "draft": False, "decisions": 0}, "no stage file of the earlier run stays"
186
186
  assert "feat: 01 rows" in rig.pr_subjects()
187
187
 
188
188
 
@@ -305,7 +305,7 @@ def test_each_answer_is_checked_on_its_own_and_a_note_goes_with_its_question(one
305
305
  "The answer for 02-spec-ambiguous-1.note in .agent/implement-answers.json is ignored: there is "
306
306
  "no open question 02-spec-ambiguous-1."]
307
307
  found, (ignored,) = answers(one, answers={Q1: ["retry"], f"{Q1}.note": 5})
308
- assert found == {} and ignored.endswith("the question offers retry, edit.")
308
+ assert found == {} and ignored.endswith("the question offers retry, leave-out, edit.")
309
309
 
310
310
 
311
311
  def test_no_open_question_or_no_file_reads_nothing_and_given_writes_only_valid_answers(one):
@@ -383,7 +383,7 @@ def test_a_second_stop_blocks_the_ticket_with_one_ticket_blocked_question(tmp_pa
383
383
  assert rig.code == 2 and rig.state()["tickets"]["01"]["phase"] == "blocked", rig.ledger()
384
384
  (question,) = rig.state()["run"]["questions"]
385
385
  assert (question["id"], question["kind"], question["recommended"]) == (TB1, "ticket-blocked", "retry")
386
- assert [o["id"] for o in question["options"]] == ["retry", "edit"]
386
+ assert [o["id"] for o in question["options"]] == ["retry", "leave-out", "edit"]
387
387
  assert "implementer" in question["subject"] and NO_ACCESS in question["subject"]
388
388
  assert question["evidence"][0] == ".agent/implement/01/implementer-0.json"
389
389
  assert entries(rig, "01", "implementer") == [SONNET, OPUS_5_5]
@@ -454,8 +454,32 @@ def test_the_rerun_of_fix_round_2_wraps_to_the_first_implementer_entry(tmp_path)
454
454
  assert entries(rig, "01", "fixer") == [SONNET, OPUS_5_5, SONNET]
455
455
 
456
456
 
457
- def test_only_two_kinds_exist():
458
- assert list(driver_decisions.KINDS) == ["spec-ambiguous", "ticket-blocked"]
457
+ def test_only_four_kinds_exist():
458
+ assert list(driver_decisions.KINDS) == ["spec-ambiguous", "ticket-blocked", "finding-open", "finding-must-fix"]
459
+
460
+
461
+ def test_a_must_fix_finding_asks_its_own_kind_whose_ships_are_the_operators_only():
462
+ """No agent ships a critical or must-fix finding: it asks `finding-must-fix`, not the arbiter's `finding-open`."""
463
+ must_fix = driver_decisions.KINDS["finding-must-fix"]
464
+ assert list(must_fix.options) == ["retry", "accept", "follow-up"] and must_fix.recommended == "retry"
465
+ assert must_fix.options is driver_decisions.KINDS["finding-open"].options and "only you may" in must_fix.why
466
+ assert [q["kind"] for q in driver_decisions.arbitrated([
467
+ {"answer": None, "kind": kind, "ticket": "final", "stop": 1} for kind in driver_decisions.KINDS], 2)] == [
468
+ "spec-ambiguous", "finding-open"]
469
+ assert "critical" not in driver_decisions.KINDS["finding-open"].why
470
+ kind = driver_decisions.finding_kind
471
+ assert [kind({"severity": "critical"}), kind({"severity": "important", "must_fix": True}),
472
+ kind({"severity": "important"})] == ["finding-must-fix", "finding-must-fix", "finding-open"]
473
+
474
+
475
+ def test_one_stop_asks_questions_of_two_kinds_and_the_ledger_names_both():
476
+ run = {"stops": 0, "questions": []}
477
+ asked = [("finding-must-fix", "leak (auth.py)", None), ("finding-open", "slow (db.py)", None)]
478
+ driver_decisions.stop(run, "final", asked, ["findings-1.json"], driver_decisions.Resume("final"))
479
+ assert [(q["id"], q["stop"]) for q in run["questions"]] == [("final-finding-must-fix-1", 1),
480
+ ("final-finding-open-1", 1)]
481
+ assert driver_decisions.decides(asked) == ("the operator decides on 1 question of kind finding-must-fix and "
482
+ "1 question of kind finding-open")
459
483
 
460
484
 
461
485
  # ---------------------------------------------------------------- a test-writer report; a question of a merged ticket
@@ -962,12 +962,20 @@ def test_a_gate_that_changes_the_tree_or_moves_head_is_red(repo, tmp_path, capsy
962
962
  assert "by-the-gate" not in out_of("git", "log", "--format=%s", "feat/x")
963
963
 
964
964
 
965
- def test_a_merged_ticket_whose_commits_left_the_pr_branch_is_not_merged_on_a_rerun(repo, tmp_path, capsys):
965
+ @pytest.mark.parametrize("rerun_date", ["2026-01-01T00:00:00Z", "2026-01-01T00:00:09Z"])
966
+ def test_a_merged_ticket_whose_commits_left_the_pr_branch_is_not_merged_on_a_rerun(repo, tmp_path, capsys, monkeypatch,
967
+ rerun_date):
968
+ """With the first `rerun_date`, the rerun's implementer makes the very commit of the first run (same work, same
969
+ second, as on a fast machine): the recovery point of the tidy is then the ticket tip, and it still lands."""
966
970
  repo(t01=ticket("01", **REFACTOR))
967
971
  base = out_of("git", "rev-parse", "HEAD")
972
+ for name in ("GIT_AUTHOR_DATE", "GIT_COMMITTER_DATE"):
973
+ monkeypatch.setenv(name, "2026-01-01T00:00:00Z")
968
974
  assert walk(tmp_path, capsys, WORK + REPORT)[0] == 0
969
975
  tip = out_of("git", "rev-parse", "--short=7", "HEAD")
970
976
  subprocess.run(["git", "reset", "-q", "--hard", base], check=True) # the operator dropped the ticket's commits
977
+ for name in ("GIT_AUTHOR_DATE", "GIT_COMMITTER_DATE"):
978
+ monkeypatch.setenv(name, rerun_date)
971
979
  code, ledger, out = walk(tmp_path, capsys, WORK + REPORT)
972
980
  assert f"Ticket 01: returned to implement from the PR tip: the recorded tip {tip} is not in feat/x." in ledger
973
981
  assert ledger[-1].startswith("Ticket 01: merged into feat/x as a fast-forward at ")
@@ -1032,7 +1040,7 @@ def test_the_preflight_asks_each_entry_once_and_drops_each_entry_whose_cli_fails
1032
1040
  models["implementer"][1] = "openai/gpt-6.1-sol@medium"
1033
1041
  models["final-reviewer"] = ["openai/gpt-astra@medium", "claude-opus-5-5@medium"]
1034
1042
  kept, errors, skipped = driver_agents.preflight(models)
1035
- assert errors == [] and len((bin_dir / "asked").read_text().splitlines()) == 5
1043
+ assert errors == [] and len((bin_dir / "asked").read_text().splitlines()) == 7
1036
1044
  assert kept["implementer"] == ["claude-sonnet-5-5@medium"] and kept["final-reviewer"] == ["claude-opus-5-5@medium"]
1037
1045
  assert kept["test-writer"] == ["claude-sonnet-5-5@medium"] and kept["reviewer"] == models["reviewer"]
1038
1046
  assert skipped == [