@jesdi/skills 0.0.99 → 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 (42) hide show
  1. package/package.json +1 -1
  2. package/skills/implement-spec/ARCHITECTURE.md +7 -4
  3. package/skills/implement-spec/README.md +38 -14
  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 +219 -232
  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 +9 -4
  16. package/skills/implement-spec/driver_review.py +10 -4
  17. package/skills/implement-spec/driver_run.py +33 -14
  18. package/skills/implement-spec/driver_slots.py +33 -0
  19. package/skills/implement-spec/driver_state.py +29 -16
  20. package/skills/implement-spec/driver_summary.py +10 -3
  21. package/skills/implement-spec/prompts/arbiter.md +8 -4
  22. package/skills/implement-spec/prompts/conflict.md +1 -1
  23. package/skills/implement-spec/prompts/pr-body.md +1 -1
  24. package/skills/implement-spec/recovery.md +4 -4
  25. package/skills/implement-spec/tests/conftest.py +1 -0
  26. package/skills/implement-spec/tests/test_arbiter.py +74 -17
  27. package/skills/implement-spec/tests/test_arbitration.py +1 -1
  28. package/skills/implement-spec/tests/test_decisions.py +30 -6
  29. package/skills/implement-spec/tests/test_driver.py +9 -1
  30. package/skills/implement-spec/tests/test_final.py +20 -3
  31. package/skills/implement-spec/tests/test_fixloop.py +1 -1
  32. package/skills/implement-spec/tests/test_leave_out.py +203 -0
  33. package/skills/implement-spec/tests/test_legacy.py +25 -0
  34. package/skills/implement-spec/tests/test_lenses.py +6 -4
  35. package/skills/implement-spec/tests/test_overturn.py +362 -0
  36. package/skills/implement-spec/tests/test_scoped.py +6 -5
  37. package/skills/implement-spec/tests/test_ship_draft.py +203 -0
  38. package/skills/implement-spec/tests/test_slots.py +29 -0
  39. package/skills/implement-spec/tests/test_state.py +4 -2
  40. package/skills/implement-spec/tests/test_stops.py +19 -4
  41. package/skills/implement-spec/tests/test_tidy.py +4 -2
  42. package/skills-manifest.json +3 -3
@@ -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,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,
47
- "draft": False}
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}
48
52
 
49
53
 
50
54
  class State:
@@ -107,19 +111,28 @@ def verified(entry: dict, branch: str, pr_branch: str) -> tuple[dict, str]:
107
111
  return {}, ""
108
112
  # The branch of a merged ticket is deleted, so its commits are trusted only while the PR branch has them.
109
113
  where, word = (pr_branch, "in") if phase == "merged" else (branch, "on")
110
- if ancestor(tip, where):
114
+ if ancestor(tip, where) or (phase == "merge" and entry["replayed"] == entry["tip"]):
111
115
  return {}, ""
112
116
  return {"phase": "implement", "tip": entry["test_writer_sha"]}, f"the recorded tip {tip[:7]} is not {word} {where}"
113
117
 
114
118
 
115
119
  def kept(state: dict) -> dict[str, int]:
116
120
  """ticket number -> slot, per ticket stopped mid-role or at an open question, with uncommitted work in the slot."""
117
- found = {}
118
121
  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
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()))
@@ -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,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,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()
@@ -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
 
@@ -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_three_kinds_exist():
458
- assert list(driver_decisions.KINDS) == ["spec-ambiguous", "ticket-blocked", "finding-open"]
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 ")
@@ -15,8 +15,8 @@ Interface choices (ticket 06):
15
15
  - a tidied commit has the subject `feat(NN): <ticket title>` and a body line `Ticket: <ticket file name>`.
16
16
  - the final fixer's `commits` hold `{"sha", "ticket"}` objects, and the driver renames each fixer commit to
17
17
  `fix(NN): <its subject>` before the gate and the scoped review run (no rewrite after a review).
18
- - a finding open after the scoped review: question `final-finding-open-<n>`, options `retry`, `accept` and
19
- `follow-up`.
18
+ - a finding open after the scoped review: question `final-finding-open-<n>`, or `final-finding-must-fix-<n>` for a
19
+ critical or must-fix one, options `retry`, `accept` and `follow-up`.
20
20
  - local stop: stdout lines `Branch tip: <sha>`, `Reviewed tip: <sha>` and the rerun command, which has `--push`.
21
21
  - the PR body lists, per ticket, a line with the ticket number and its commit's first 7 hex, and every ruling line.
22
22
  - stage.json at a clean unattended end is `{"stage": "implement", "status": "done"}`.
@@ -35,6 +35,7 @@ from types import SimpleNamespace
35
35
 
36
36
  import pytest
37
37
 
38
+ import driver_final
38
39
  from test_cli import SKILL, git, ticket
39
40
  from test_review import ASTRA, FABLE, HOOKED, ONE, OPUS, Review, finding, gate_rule, no_full_gate, review
40
41
  from test_stops import DONE, UNATTENDED, stage
@@ -89,6 +90,10 @@ if argv[:2] == ["issue", "list"]: # an issue whose body has the searched marker
89
90
  print(next(("https://github.example/issues/1" for row in rows
90
91
  if row["argv"][:2] == ["issue", "create"] and marker in row["body"]), ""))
91
92
  sys.exit(0)
93
+ if argv[:2] == ["pr", "view"]: # the state of the PR: OPEN, unless a test wrote another into gh-pr-state
94
+ state = log.with_name("gh-pr-state")
95
+ print(state.read_text().strip() if state.exists() else "OPEN")
96
+ sys.exit(0)
92
97
  with log.open("a") as out:
93
98
  out.write(json.dumps(dict(argv=argv, body=body)) + "\\n")
94
99
  print("https://github.example/issues/1" if argv[:2] == ["issue", "create"] else "https://github.example/pull/1")
@@ -338,7 +343,7 @@ def test_unresolved_must_fix_asks_and_is_not_published_while_the_operator_is_ask
338
343
 
339
344
  assert rig.code == 2, rig.output()
340
345
  (question,) = rig.state()["run"]["questions"]
341
- assert question["id"] == "final-finding-open-1" and "MERGED-QUOTING-REGRESSION" in question["subject"]
346
+ assert question["id"] == "final-finding-must-fix-1" and "MERGED-QUOTING-REGRESSION" in question["subject"]
342
347
  assert [item["title"] for item in rig.state()["run"]["final"]["open"]] == ["MERGED-QUOTING-REGRESSION"]
343
348
  assert not rig.pushes() and not rig.prs()
344
349
  rig.run(steps)
@@ -675,3 +680,15 @@ def test_final_gate_repair_can_prove_no_code_change_but_still_spends_its_attempt
675
680
  assert [g['exit'] for g in rig.gates('full')] == [1, 0 if transient else 1]
676
681
  assert bool(rig.pushes()) == transient
677
682
  assert len(rig.final_calls('final-spec')) == int(transient)
683
+
684
+
685
+ def test_the_final_review_carries_each_minor_finding_and_observation_of_the_tickets_once(tmp_path, monkeypatch):
686
+ monkeypatch.chdir(tmp_path)
687
+ folder = tmp_path / ".agent/implement/01"
688
+ folder.mkdir(parents=True)
689
+ one = {"title": "t", "file": "a.py", "line": 1}
690
+ (folder / "findings-0.json").write_text(json.dumps([{**one, "severity": "minor"}, {**one, "severity": "important",
691
+ "title": "big"}]))
692
+ (folder / "observations-0.json").write_text(json.dumps([{**one, "title": "seen"}, {**one, "title": "seen"}]))
693
+ assert driver_final._carried_findings() == (f"- .agent/implement/01/findings-0.json: t (a.py:1)\n"
694
+ f"- .agent/implement/01/observations-0.json: seen (a.py:1)")
@@ -156,7 +156,7 @@ def test_a_locked_test_finding_that_comes_back_after_its_correction_asks_spec_am
156
156
  assert rig.code == 2 and rig.state()["tickets"]["01"]["phase"] == "blocked", rig.ledger()
157
157
  assert rig.led("BLOCKED at the review: the spec reads two ways on a locked test: tests/test_01.py::test_x: the "
158
158
  "first reading: STALE: STALE; the second reading: STALE: STALE.")
159
- assert asked(rig) == {AMBIGUOUS_1: ["keep-test", "correct-test", "edit-spec"]}
159
+ assert asked(rig) == {AMBIGUOUS_1: ["keep-test", "correct-test", "leave-out", "edit-spec"]}
160
160
  (question,) = rig.state()["run"]["questions"]
161
161
  assert question["recommended"] == "" and question["evidence"][0] == ".agent/implement/01/spec-ambiguous-1.json"
162
162
  rig.run(steps, "--answer", f"{AMBIGUOUS_1}=correct-test")