@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
@@ -0,0 +1,362 @@
1
+ """Overturn: after a run, `--answer <question id>=<other option>` on a question the driver or the arbiter answered
2
+ overturns its ruling. The new ruling says which ruling it overturns and who took it, and it takes effect from where the
3
+ run is: an accepted finding gets a fix batch, a left-out ticket runs again, a draft's stop runs again. What lands is
4
+ pushed on top of the open PR, with no force. An overturn that would undo work, or that cannot take effect, exits 3
5
+ before any agent and says why.
6
+
7
+ In process, on the rigs of test_arbiter, test_leave_out and test_ship_draft."""
8
+ import subprocess
9
+
10
+ import pytest
11
+
12
+ import driver_decisions
13
+ import driver_overturn
14
+ import driver_pr
15
+ from test_arbiter import Q, gh, open_after_batch, ruled
16
+ from test_arbitration import AMBIGUOUS, SECOND, disputes, ruling
17
+ from test_final import GH, THREE, final, fixer, fn
18
+ from test_fixloop import Inside as Local
19
+ from test_fixloop import inside # noqa: F401 (the autouse fixture puts the rig's CLIs on PATH)
20
+ from test_lenses import rig_of, stopped
21
+ from test_scoped import ATOMIC
22
+ from test_review import ONE, review
23
+ from test_stops import UNATTENDED, blocked
24
+ from test_tidy import Inside
25
+ from test_tidy import tools # noqa: F401 (tools is an autouse fixture)
26
+ from test_walk import impl, plan, tw
27
+
28
+ AUTONOMOUS = ("--no-ask", "--retries", "0", *UNATTENDED)
29
+
30
+
31
+ def on_top(rig, first):
32
+ """The branch tip holds the first pushed tip: the second push needed no force."""
33
+ return subprocess.run(["git", "merge-base", "--is-ancestor", first, rig.branch()], cwd=rig.repo).returncode == 0
34
+
35
+
36
+ def test_an_accept_overturned_to_retry_gets_a_fix_batch_pushed_on_top_of_the_open_draft(tmp_path):
37
+ rig, steps = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "accept"))])
38
+ assert rig.code == 0 and len(rig.final_calls("fixer")) == 1, rig.out
39
+ first = rig.branch()
40
+ steps["final/fixer"].append(fixer(fn("02"), "write the ledger atomically"))
41
+ steps["final/final-reviewer"].append(final())
42
+ rig.run(steps, *AUTONOMOUS, "--answer", f"{Q}=retry")
43
+ assert rig.code == 0, rig.out
44
+ assert len(rig.final_calls("fixer")) == 2 and len(rig.prs()) == 1, "the open PR is not opened again"
45
+ assert rig.pushes() == [f"refs/heads/feat/csv {first}", f"refs/heads/feat/csv {rig.branch()}"]
46
+ assert on_top(rig, first)
47
+ (q,) = rig.state()["run"]["questions"]
48
+ assert q["answer"] == "retry" and "by" not in q
49
+ line = ("Ruling: final runs again (retry): ledger write not atomic (ledger.py). It overturns the ruling accept of "
50
+ "the arbiter.")
51
+ summary = (rig.repo / ".agent/implement/summary.md").read_text()
52
+ assert rig.led(line) and f"Overturned by the operator:\n- {Q}: {line}" in summary
53
+ assert "Driver decisions, taken without the operator:" not in summary
54
+ (edit,) = gh(rig, ["pr", "edit"])
55
+ assert edit["argv"][2] == "https://github.example/pull/1" and "--ready" not in edit["argv"]
56
+ assert line in edit["body"] and f"Branch tip and reviewed tip: {rig.branch()}" in edit["body"]
57
+ assert edit["body"].startswith(rig.prs()[0]["body"].split("\n\n## Tickets")[0]), "the pr-writer's part stays"
58
+ assert rig.led("The body of the PR https://github.example/pull/1 is written again")
59
+ rig.run(steps, *AUTONOMOUS)
60
+ assert rig.code == 0 and len(gh(rig, ["pr", "edit"])) == 1, "a rerun that changes nothing edits no body"
61
+
62
+
63
+ def test_an_accept_overturned_to_follow_up_files_the_issue_for_the_open_pr(tmp_path):
64
+ rig, steps = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "accept"))])
65
+ assert rig.code == 0 and not gh(rig, ["issue", "create"]), rig.out
66
+ rig.run(steps, *AUTONOMOUS, "--answer", f"{Q}=follow-up")
67
+ assert rig.code == 0, rig.out
68
+ (issue,) = gh(rig, ["issue", "create"])
69
+ assert "It overturns the ruling accept of the arbiter." in issue["body"]
70
+ assert len(rig.prs()) == 1 and len(rig.final_calls("fixer")) == 1
71
+ (edit,) = gh(rig, ["pr", "edit"])
72
+ assert "Follow-up issue: https://github.example/issues/1" in edit["body"]
73
+
74
+
75
+ def test_a_left_out_ticket_overturned_to_retry_runs_again_and_lands_on_top_of_the_open_draft(tmp_path):
76
+ rig = Inside(tmp_path, THREE)
77
+ steps = plan(**{"01/implementer": [blocked(), blocked()]})
78
+ rig.run(steps, *AUTONOMOUS)
79
+ assert rig.code == 0 and len(rig.prs()) == 1, rig.output()
80
+ first = rig.branch()
81
+ steps["01/implementer"].append(impl("01"))
82
+ rig.run(steps, *AUTONOMOUS, "--answer", "01-ticket-blocked-1=retry")
83
+ assert rig.code == 0, rig.output()
84
+ assert {entry["phase"] for entry in rig.state()["tickets"].values()} == {"merged"}
85
+ assert rig.calls("02"), "the ticket the left-out one blocked runs too"
86
+ assert rig.pushes()[-1] == f"refs/heads/feat/csv {rig.branch()}" and on_top(rig, first)
87
+ assert len(rig.prs()) == 1
88
+ assert rig.led("Ruling: 01 runs again (retry)", "It overturns the ruling leave-out of the driver.")
89
+ assert len(rig.final_calls("pr-writer")) == 2, "the pr-writer writes its part again for the tickets that landed"
90
+ (edit,) = gh(rig, ["pr", "edit"])
91
+ assert "- 01: " in edit["body"] and "Left out of the run" not in edit["body"]
92
+
93
+
94
+ def test_a_left_out_ticket_lands_only_its_own_commits_on_the_rewritten_branch(tmp_path):
95
+ rig = Inside(tmp_path, THREE)
96
+ steps = plan(**{"02/implementer": [blocked(), blocked()]})
97
+ rig.run(steps, *AUTONOMOUS)
98
+ assert rig.code == 0 and rig.state()["tickets"]["02"]["phase"] == "blocked", rig.output()
99
+ recovery, first = rig.final()["recovery"], rig.branch()
100
+ steps["02/implementer"].append(impl("02"))
101
+ rig.run(steps, *AUTONOMOUS, "--answer", "02-ticket-blocked-1=retry")
102
+ assert rig.code == 0 and rig.state()["tickets"]["02"]["phase"] == "merged", rig.output()
103
+ assert on_top(rig, first) and not on_top(rig, recovery), "no commit of the history before the tidy comes back"
104
+ assert rig.led("Ticket 02: merged into feat/csv as a fast-forward")
105
+ assert rig.led("Ticket 02: its own work is replayed onto")
106
+
107
+
108
+ def test_a_left_out_ticket_that_lands_after_a_ship_draft_gets_its_tip_reviewed_and_pushed(tmp_path):
109
+ rig = Inside(tmp_path, THREE)
110
+ steps = plan(**{"02/implementer": [blocked(), blocked()], "final/final-structure": [stopped(), stopped()]})
111
+ rig.run(steps, *AUTONOMOUS)
112
+ assert rig.code == 0 and rig.final()["ship"] and len(rig.prs()) == 1, rig.output()
113
+ first = rig.branch()
114
+ steps["02/implementer"].append(impl("02"))
115
+ steps["final/final-structure"].append(final())
116
+ rig.run(steps, *AUTONOMOUS, "--answer", "02-ticket-blocked-1=retry")
117
+ assert rig.code == 0 and rig.state()["tickets"]["02"]["phase"] == "merged", rig.output()
118
+ assert not rig.final()["ship"], "the draft ruling shipped the tip before the ticket landed"
119
+ assert rig.final()["reviewed"] == rig.branch() != first
120
+ assert rig.pushes()[-1] == f"refs/heads/feat/csv {rig.branch()}" and on_top(rig, first)
121
+
122
+
123
+ def test_a_ship_draft_overturned_to_retry_runs_the_failed_lens_again(tmp_path):
124
+ rig = rig_of(tmp_path)
125
+ steps = plan(**{"final/final-structure": [stopped(), stopped()]})
126
+ rig.run(steps, *AUTONOMOUS)
127
+ assert rig.code == 0 and len(rig.prs()) == 1, rig.out
128
+ rig.run(steps, *AUTONOMOUS, "--answer", "final-ticket-blocked-1=retry")
129
+ assert rig.code == 0, rig.out
130
+ assert len(rig.final_calls("final-structure")) == 3 and len(rig.prs()) == 1
131
+ assert rig.final()["reviewed"] == rig.branch()
132
+ assert rig.led("(retry)", "It overturns the ruling ship-draft of the driver.")
133
+ (edit,) = gh(rig, ["pr", "edit"])
134
+ assert "It overturns the ruling ship-draft of the driver." in edit["body"] and "--ready" not in edit["argv"]
135
+ assert rig.final()["draft"] and not gh(rig, ["pr", "ready"]), "the PR stays a draft: the operator readies it"
136
+
137
+
138
+ def test_an_overturn_of_an_answer_of_the_operator_exits_3_before_any_agent(tmp_path):
139
+ rig = rig_of(tmp_path)
140
+ steps = plan(**{"final/final-structure": [stopped(), stopped()]})
141
+ rig.run(steps, "--retries", "0", *UNATTENDED)
142
+ assert rig.code == 2, rig.out
143
+ rig.run(steps, "--answer", "final-ticket-blocked-1=ship-draft", *UNATTENDED)
144
+ assert rig.code == 0, rig.out
145
+ calls = len(rig.calls())
146
+ rig.run(steps, "--answer", "final-ticket-blocked-1=retry", *UNATTENDED)
147
+ assert rig.code == 3 and len(rig.calls()) == calls
148
+ assert ("--answer final-ticket-blocked-1=retry: you answered final-ticket-blocked-1: only a ruling of the driver "
149
+ "or the arbiter is overturned") in rig.out
150
+
151
+
152
+ # ---------------------------------------------------------------- the refusals, on a state.json of their own
153
+
154
+ def q(id, answer, ticket="final", kind="finding-open", stop=1, by="driver", subject="s (f.py)", **more):
155
+ options = {"finding-open": ["retry", "accept", "follow-up"], "finding-must-fix": ["retry", "accept", "follow-up"],
156
+ "ticket-blocked": ["retry", "ship-draft", "edit"],
157
+ "spec-ambiguous": ["keep-test", "correct-test", "leave-out", "edit-spec"]}[kind]
158
+ return {"id": id, "ticket": ticket, "kind": kind, "stop": stop, "answer": answer, "subject": subject,
159
+ "options": [{"id": option} for option in options], **({"by": by} if by else {}), **more}
160
+
161
+
162
+ def state(*questions, open=(), pr=None, phases=None):
163
+ return {"run": {"questions": list(questions),
164
+ "final": {"open": [{"title": t, "file": "f.py"} for t in open], "pr": pr}},
165
+ "tickets": {number: {"phase": phase} for number, phase in (phases or {}).items()}}
166
+
167
+
168
+ @pytest.mark.parametrize("asked, pair, why", [
169
+ (state(), ("zz", "retry"), "there is no question zz"),
170
+ (state(q("a", "accept", by=None)), ("a", "retry"),
171
+ "you answered a: only a ruling of the driver or the arbiter is overturned"),
172
+ (state(q("a", "accept", by="arbiter")), ("a", "nope"), "a offers retry, accept, follow-up"),
173
+ (state(q("a", "accept", by="arbiter")), ("a", "accept"), "a is answered accept already"),
174
+ (state(q("a", "retry", open=["s"])), ("a", "accept"),
175
+ "the retry of the driver ran: its work is on the branch, and an overturn undoes no work"),
176
+ (state(q("a", "retry", kind="finding-must-fix"), open=["s"]), ("a", "accept"),
177
+ "the retry of the driver ran: its work is on the branch, and an overturn undoes no work"),
178
+ (state(q("a", "ship-draft", kind="ticket-blocked")), ("a", "edit"),
179
+ "an overturn takes an option that lets the run go on: edit the spec or the ticket, then overturn a to an option "
180
+ "that runs the work again"),
181
+ (state(q("a", "accept", by="arbiter"), q("b", "retry", stop=2), open=["s"]), ("a", "retry"),
182
+ "a later stop of the end of run asked b: only the newest stop of the end of run is overturned"),
183
+ (state(q("a", "keep-test", ticket="01", kind="spec-ambiguous", by="arbiter"), phases={"01": "merged"}),
184
+ ("a", "correct-test"), "ticket 01 merged since: its work is on the PR branch"),
185
+ (state(q("a", "accept", by="arbiter"), open=["other"]), ("a", "retry"),
186
+ "the last review leaves the finding closed: no fix batch is due for it"),
187
+ (state(q("a", "ship-draft", kind="ticket-blocked", subject="the pr-writer: it reported BLOCKED",
188
+ role="pr-writer"), pr="https://pr"),
189
+ ("a", "retry"), "the PR is open, so the pr-writer does not run again: edit its body on GitHub"),
190
+ ])
191
+ def test_an_overturn_that_cannot_take_effect_is_refused_with_why(asked, pair, why):
192
+ assert driver_overturn.refusals([pair], asked) == [f"--answer {pair[0]}={pair[1]}: {why}"]
193
+
194
+
195
+ @pytest.mark.parametrize("asked, pair", [
196
+ (state(q("a", "accept", by="arbiter"), open=["s"]), ("a", "retry")),
197
+ (state(q("a", "accept", by="arbiter")), ("a", "follow-up")),
198
+ (state(q("a", "leave-out", ticket="01", kind="spec-ambiguous"), phases={"01": "blocked"}), ("a", "correct-test")),
199
+ (state(q("a", "ship-draft", kind="ticket-blocked", subject="the final-spec: x"), pr="https://pr"), ("a", "retry")),
200
+ ])
201
+ def test_an_overturn_that_takes_effect_is_not_refused(asked, pair, monkeypatch):
202
+ monkeypatch.setattr(driver_pr, "state", lambda url: "OPEN")
203
+ assert driver_overturn.refusals([pair], asked) == []
204
+
205
+
206
+ @pytest.mark.parametrize("pair, draft", [
207
+ (("a", "follow-up"), ""),
208
+ (("a", "retry"), ""),
209
+ (None, "a finding ships open: s (f.py:1)"),
210
+ ])
211
+ def test_an_agent_s_ship_overturned_is_the_operator_s_ruling_and_drafts_no_pr(pair, draft):
212
+ questions = [q("a", "accept", by="arbiter", resume={"phase": "final"})]
213
+ final = {"open": [{"title": "s", "file": "f.py", "line": 1}], "ship": None, "gate_preexisting": None}
214
+ if pair:
215
+ driver_decisions.overturn(questions, dict([pair]))
216
+ assert driver_pr._draft(final, questions, [], "tip") == draft
217
+
218
+
219
+ def test_a_body_edit_that_fails_is_made_again_by_the_next_run(tmp_path):
220
+ rig, steps = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "accept"))])
221
+ gh_path = tmp_path / "bin/gh"
222
+ down = 'if sys.argv[1:3] == ["pr", "edit"]:\n sys.exit("gh down")\n'
223
+ gh_path.write_text(GH.replace("log = Path", f"{down}log = Path", 1))
224
+ rig.run(steps, *AUTONOMOUS, "--answer", f"{Q}=follow-up")
225
+ assert rig.code != 0 and "gh pr edit failed: gh down" in rig.out, rig.out
226
+ gh_path.write_text(GH)
227
+ rig.run(steps, *AUTONOMOUS)
228
+ assert rig.code == 0, rig.out
229
+ (edit,) = gh(rig, ["pr", "edit"])
230
+ assert "Follow-up issue: https://github.example/issues/1" in edit["body"]
231
+ assert (rig.repo / ".agent/implement/final/pr-body.md").read_text() == edit["body"]
232
+
233
+
234
+ @pytest.mark.parametrize("shown", ["MERGED", "CLOSED"])
235
+ def test_an_overturn_once_the_pr_is_merged_or_closed_exits_3_before_any_agent(tmp_path, shown):
236
+ rig, steps = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "accept"))])
237
+ (tmp_path / "gh-pr-state").write_text(f"{shown}\n")
238
+ calls = len(rig.calls())
239
+ rig.run(steps, *AUTONOMOUS, "--answer", f"{Q}=retry")
240
+ assert rig.code == 3 and len(rig.calls()) == calls and len(rig.pushes()) == 1
241
+ assert (f"--answer {Q}=retry: the PR https://github.example/pull/1 is {shown.lower()}: an overturn adds work to "
242
+ "an open PR only") in rig.out
243
+
244
+
245
+ @pytest.mark.parametrize("shown", ["MERGED", "CLOSED"])
246
+ def test_an_overturn_stopped_before_its_push_pushes_nothing_once_the_pr_is_merged_or_closed(tmp_path, shown,
247
+ monkeypatch):
248
+ rig, steps = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "accept"))])
249
+ steps["final/fixer"].append(fixer(fn("02"), "write the ledger atomically"))
250
+ steps["final/final-reviewer"].append(final())
251
+ import driver_final
252
+
253
+ def killed(*_, **__):
254
+ raise SystemExit(137)
255
+
256
+ with monkeypatch.context() as patch:
257
+ patch.setattr(driver_final, "_push", killed)
258
+ with pytest.raises(SystemExit):
259
+ rig.run(steps, *AUTONOMOUS, "--answer", f"{Q}=retry")
260
+ (tmp_path / "gh-pr-state").write_text(f"{shown}\n")
261
+ rig.run(steps, *AUTONOMOUS)
262
+ assert rig.code == 1 and len(rig.pushes()) == 1 and not gh(rig, ["pr", "edit"]), rig.out
263
+ assert f"the PR https://github.example/pull/1 is {shown.lower()}: nothing goes out to it" in rig.out
264
+
265
+
266
+ def test_a_final_fixer_after_a_ticket_landed_late_keeps_that_ticket_s_locked_test_as_it_landed(tmp_path):
267
+ rig = Inside(tmp_path, THREE)
268
+ steps = plan(**{"02/implementer": [blocked(), blocked()]})
269
+ rig.run(steps, *AUTONOMOUS)
270
+ assert rig.code == 0 and rig.state()["tickets"]["02"]["phase"] == "blocked", rig.output()
271
+ steps["02/implementer"].append(impl("02"))
272
+ steps["final/fixer"] = [fixer(fn("02"), "repair the gate")]
273
+ rig.gate_conf(full={"subjects": ["feat(02): Quote fields"]}) # red on the commit the late ticket lands as
274
+ rig.run(steps, *AUTONOMOUS, "--answer", "02-ticket-blocked-1=retry")
275
+ assert rig.code == 0, rig.output()
276
+ assert len(rig.final_calls("fixer")) == 1 and rig.led("Fix batch of the integration gate: 1 commit"), rig.ledger()
277
+ assert rig.final()["locked"] == rig.state()["run"]["landed"][-1][1]
278
+ assert "def test_x" in subprocess.run(["git", "show", "feat/csv:tests/test_02.py"], cwd=rig.repo,
279
+ capture_output=True, text=True).stdout
280
+
281
+
282
+ QUOTE = "demo/quote.py"
283
+
284
+
285
+ def conflicted(tmp_path, conflict):
286
+ """Ticket 02 is left out, then overturned to `retry`: its work adds QUOTE, which the base the tidy moved onto
287
+ adds too, so its replay onto the rewritten branch conflicts. `conflict` is the conflict agent's steps."""
288
+ rig = Inside(tmp_path, THREE)
289
+ rig.move_base({QUOTE: "base = 1\n"})
290
+ steps = plan(**{"02/implementer": [blocked(), blocked(), impl("02", QUOTE)], "02/conflict": conflict})
291
+ rig.run(steps, *AUTONOMOUS)
292
+ assert rig.code == 0 and rig.state()["tickets"]["02"]["phase"] == "blocked", rig.output()
293
+ return rig, steps
294
+
295
+
296
+ RESOLVED = {"files": {QUOTE: "base = 1\n" + fn("02")}, "commit": "replay 02",
297
+ "report": {"status": "DONE", "commits": ["$SHA"], "files": [QUOTE], "concerns": []}}
298
+
299
+
300
+ def test_a_replay_that_conflicts_goes_to_the_conflict_agent_and_lands(tmp_path):
301
+ rig, steps = conflicted(tmp_path, [RESOLVED])
302
+ rig.run(steps, *AUTONOMOUS, "--answer", "02-ticket-blocked-1=retry")
303
+ assert rig.code == 0 and rig.state()["tickets"]["02"]["phase"] == "merged", rig.output()
304
+ (agent,) = rig.calls("02", "conflict")
305
+ assert "replayed onto the PR branch after the end of run rewrote it, is open in this worktree" in agent["prompt"]
306
+ shown = subprocess.run(["git", "show", f"feat/csv:{QUOTE}"], cwd=rig.repo, capture_output=True, text=True)
307
+ assert shown.stdout == "base = 1\n" + fn("02")
308
+ assert rig.led("Ticket 02: the conflict agent resolved the merge conflict in demo/quote.py")
309
+
310
+
311
+ def test_a_replay_whose_conflict_agent_stops_leaves_the_slot_clean_and_retry_runs_the_agent_again(tmp_path):
312
+ rig, steps = conflicted(tmp_path, [blocked(), blocked(), RESOLVED])
313
+ rig.run(steps, "--retries", "0", "--answer", "02-ticket-blocked-1=retry", *UNATTENDED)
314
+ assert rig.code == 2, rig.output()
315
+ (question,) = [q for q in rig.state()["run"]["questions"] if q["answer"] is None]
316
+ assert (question["id"], question["role"]) == ("02-ticket-blocked-2", "conflict")
317
+ entry = rig.state()["tickets"]["02"]
318
+ slot = rig.repo if entry["slot"] == 1 else rig.repo / f".agent/worktrees/slot-{entry['slot']}"
319
+ run = lambda *a: subprocess.run(["git", *a], cwd=slot, capture_output=True, text=True).stdout.strip()
320
+ assert run("status", "--porcelain") == "" and not run("rev-parse", "-q", "--verify", "CHERRY_PICK_HEAD")
321
+ assert "02" in run("for-each-ref", "--format=%(refname)", "--points-at", entry["tip"], "refs/heads"), \
322
+ "the ticket branch is back on its tip before the replay"
323
+ rig.run(steps, "--retries", "0", "--answer", "02-ticket-blocked-2=retry", *UNATTENDED)
324
+ assert rig.code == 0 and rig.state()["tickets"]["02"]["phase"] == "merged", rig.output()
325
+ assert len(rig.calls("02", "conflict")) == 3
326
+
327
+
328
+ def test_a_run_killed_in_a_replay_replays_again_and_keeps_the_ticket_s_work(tmp_path, monkeypatch):
329
+ rig, steps = conflicted(tmp_path, [RESOLVED])
330
+ import driver
331
+
332
+ def killed(*_, **__): # the driver dies while the conflict agent works: the ticket branch is on the PR tip
333
+ raise SystemExit(137)
334
+
335
+ with monkeypatch.context() as patch:
336
+ patch.setattr(driver, "_resolve_conflict", killed)
337
+ with pytest.raises(SystemExit):
338
+ rig.run(steps, *AUTONOMOUS, "--answer", "02-ticket-blocked-1=retry")
339
+ entry = rig.state()["tickets"]["02"]
340
+ slot = rig.repo if entry["slot"] == 1 else rig.repo / f".agent/worktrees/slot-{entry['slot']}"
341
+ subprocess.run(["git", "cherry-pick", "--abort"], cwd=slot, check=True) # the driver starts on no open change
342
+ rig.run(steps, *AUTONOMOUS)
343
+ assert rig.code == 0 and rig.state()["tickets"]["02"]["phase"] == "merged", rig.output()
344
+ assert len(rig.calls("02", "implementer")) == 3, "the ticket's work is not thrown away"
345
+ shown = subprocess.run(["git", "show", f"feat/csv:{QUOTE}"], cwd=rig.repo, capture_output=True, text=True)
346
+ assert shown.stdout == "base = 1\n" + fn("02")
347
+
348
+
349
+ def test_a_spec_ambiguous_leave_out_overturned_to_keep_test_runs_the_implementer_again_and_lands(tmp_path):
350
+ rig = Local(tmp_path, {**ONE, **SECOND})
351
+ steps = plan(**{"01/implementer": [disputes(), disputes(), impl("01")], "01/test-writer": [tw("01")],
352
+ "02/implementer": [impl("02", "demo/other.py")],
353
+ "01/reviewer": [ruling("code-wrong", "R3 says double quotes"), review("01")]})
354
+ rig.run(steps, "--no-ask", "--retries", "0")
355
+ assert rig.code == 0, rig.ledger()
356
+ (q,) = [q for q in rig.state()["run"]["questions"] if q["id"] == AMBIGUOUS]
357
+ assert q["answer"] == "leave-out" and rig.state()["tickets"]["02"]["phase"] == "merged"
358
+ rig.run(steps, "--no-ask", "--retries", "0", "--answer", f"{AMBIGUOUS}=keep-test")
359
+ assert rig.code == 0 and rig.state()["tickets"]["01"]["phase"] == "merged", rig.ledger()
360
+ assert len(rig.calls("01", "implementer")) == 3
361
+ assert rig.led("(keep-test)", "It overturns the ruling leave-out of the driver.")
362
+ assert rig.led("Ticket 01: its own work is replayed onto")
@@ -1,6 +1,7 @@
1
1
  """Fewer roles, ticket 04: after the fix batch of the final review, one scoped re-review runs, the `final-reviewer`
2
- role on the other-provider entry of the `final-reviewer` list. A finding it leaves open asks `final-finding-open`:
3
- only a `retry` starts another batch and scoped review; `accept` and `follow-up` ship the PR with it.
2
+ role on the other-provider entry of the `final-reviewer` list. A finding it leaves open asks `final-finding-open`, or
3
+ `final-finding-must-fix` for a critical or must-fix one: only a `retry` starts another batch and scoped review;
4
+ `accept` and `follow-up` ship the PR with it.
4
5
 
5
6
  In process, on the rig of test_tidy and test_lenses."""
6
7
  import json
@@ -28,7 +29,7 @@ def test_the_scoped_review_is_one_agent_on_the_other_provider_over_the_fix_batch
28
29
  assert [(f["title"], f["source"]) for f in findings_file(rig, 1)] == [("Q-ONE", "final-reviewer")]
29
30
 
30
31
 
31
- def test_a_must_fix_the_scoped_review_leaves_out_of_resolved_must_fix_asks_final_finding_open(tmp_path):
32
+ def test_a_must_fix_the_scoped_review_leaves_out_of_resolved_must_fix_asks_final_finding_must_fix(tmp_path):
32
33
  rig = Inside(tmp_path, RISKY, MODELS)
33
34
  escaping = {**finding("quote escaping", file="csv.py", line=30), "basis": "regression"}
34
35
  batch = fixer(fn("02"), "escape quotes", ticket_of="02")
@@ -37,7 +38,7 @@ def test_a_must_fix_the_scoped_review_leaves_out_of_resolved_must_fix_asks_final
37
38
  "final/final-reviewer": [final()], "final/fixer": [batch]}))
38
39
  assert rig.code == 2, rig.out
39
40
  (question,) = decisions(rig)["questions"]
40
- assert question["id"] == Q and "quote escaping (csv.py)" in question["title"]
41
+ assert question["id"] == "final-finding-must-fix-1" and "quote escaping (csv.py)" in question["title"]
41
42
  assert len(rig.final_calls("final-reviewer")) == 1
42
43
 
43
44
 
@@ -87,7 +88,7 @@ def test_with_retries_the_driver_runs_the_one_more_fix_batch_itself_and_pushes_w
87
88
  assert [len(rig.final_calls(role)) for role in LENSES] == [1, 1, 1]
88
89
 
89
90
 
90
- def test_accept_on_an_open_final_finding_ships_it_with_no_fix_batch_and_lists_the_operator_ruling(tmp_path):
91
+ def test_the_operators_accept_on_an_open_final_finding_ships_it_ready_with_no_fix_batch_and_lists_the_ruling(tmp_path):
91
92
  rig, steps = open_after_batch(tmp_path)
92
93
  rig.run(steps, "--answer", f"{Q}=accept", *UNATTENDED)
93
94
  assert rig.code == 0 and rig.pushes() and len(rig.final_calls("fixer")) == 1, rig.out
@@ -0,0 +1,203 @@
1
+ """`ship-draft`: once the driver's retries are spent on an end-of-run stop, a full gate still red after its repair or an
2
+ end-of-run agent that failed twice, the driver pushes the branch tip that a full gate ran on and opens the PR as
3
+ draft, naming the stop. `--ask` (IMPLEMENT_SPEC_ASK=1, which conftest pins) asks the operator instead; a tip no full
4
+ gate ran on, as after a failed rebase conflict agent, still asks.
5
+
6
+ In process, on the rigs of test_tidy and test_lenses."""
7
+ from test_final import RESOLVE, fixer, fn
8
+ from test_fixloop import inside # noqa: F401 (the autouse fixture puts the rig's CLIs on PATH)
9
+ from test_lenses import LENSES, final, rig_of, stopped
10
+ from test_review import RISKY, finding, fix, review
11
+ from test_stops import UNATTENDED, decisions, stage
12
+ from test_tidy import Inside, git, moved, stray
13
+ from test_tidy import tools # noqa: F401 (tools is an autouse fixture)
14
+ from test_walk import plan
15
+
16
+ AUTONOMOUS = ("--no-ask", "--retries", "0", *UNATTENDED)
17
+ FIXER_STOPPED = {"report": {**stopped()["report"], "green": []}}
18
+ DRAFT = {"stage": "implement", "status": "done", "draft": True, "decisions": 1}
19
+
20
+
21
+ def not_reviewed(rig, since):
22
+ """The coverage line's list of the commits after `since` that no review covered."""
23
+ return "not reviewed: " + "; ".join(f"{c['sha'][:7]} {c['subject']}" for c in rig.commits(since))
24
+
25
+
26
+ def test_a_full_gate_red_after_its_repair_ships_the_repaired_tip_as_draft(tmp_path):
27
+ rig = Inside(tmp_path)
28
+ rig.gate_conf(full={'subjects': ['feat(01): Export rows', 'fix(01): first repair']})
29
+ rig.run(plan(**{'final/fixer': [fixer('first\n', 'first repair', ticket_of='01')]}), *AUTONOMOUS)
30
+ assert rig.code == 0, rig.output()
31
+ assert len(rig.final_calls('fixer')) == 1 and not any(rig.final_calls(role) for role in LENSES)
32
+ assert rig.pushes() == [f'refs/heads/feat/csv {rig.branch()}'], 'the tip the red gate ran on, repair included'
33
+ (pr,) = rig.prs()
34
+ assert '--draft' in pr['argv']
35
+ assert 'the full integration gate remains red after its repair' in pr['body']
36
+ assert rig.led('open as a draft: the end of run stopped: the full integration gate remains red after its repair')
37
+ assert rig.led('(ship-draft)') and rig.led('Ruled by the driver, not the operator.')
38
+ assert not_reviewed(rig, rig.final()['onto']) in pr['body'], 'no review ran, so every commit is unreviewed'
39
+ assert stage(rig) == DRAFT
40
+
41
+
42
+ def test_a_lens_that_fails_twice_ships_the_gated_tip_as_draft_naming_the_lens(tmp_path):
43
+ rig = rig_of(tmp_path)
44
+ rig.run(plan(**{"final/final-structure": [stopped(), stopped()]}), *AUTONOMOUS)
45
+ assert rig.code == 0, rig.out
46
+ assert rig.pushes() == [f"refs/heads/feat/csv {rig.final()['tidied']}"]
47
+ (pr,) = rig.prs()
48
+ assert "--draft" in pr["argv"] and "the final-structure: it reported BLOCKED" in pr["body"]
49
+ assert not_reviewed(rig, rig.final()["onto"]) in pr["body"]
50
+ assert not rig.final_calls("fixer")
51
+ assert stage(rig) == DRAFT
52
+
53
+
54
+ def test_a_pr_writer_that_fails_twice_ships_a_draft_with_the_facts_of_the_driver(tmp_path):
55
+ rig = rig_of(tmp_path)
56
+ rig.run(plan(**{"final/pr-writer": [stopped(), stopped()]}), *AUTONOMOUS)
57
+ assert rig.code == 0, rig.out
58
+ assert len(rig.final_calls("pr-writer")) == 2, "no third pr-writer"
59
+ (pr,) = rig.prs()
60
+ assert "--draft" in pr["argv"] and pr["body"].startswith("## Tickets")
61
+ assert "(ship-draft): the pr-writer: report: " in pr["body"]
62
+ assert stage(rig) == DRAFT
63
+
64
+
65
+ def test_a_final_fixer_that_fails_twice_ships_the_reviewed_tip_as_draft(tmp_path):
66
+ rig = rig_of(tmp_path)
67
+ rig.run(plan(**{"final/final-spec": [final(finding("missing --dry-run flag"))],
68
+ "final/fixer": [FIXER_STOPPED] * 2}), *AUTONOMOUS)
69
+ assert rig.code == 0, rig.out
70
+ reviewed = rig.final()["reviewed"]
71
+ assert rig.pushes() == [f"refs/heads/feat/csv {reviewed}"] and rig.branch() == reviewed
72
+ (pr,) = rig.prs()
73
+ assert "--draft" in pr["argv"] and "the fixer: it reported BLOCKED" in pr["body"]
74
+ assert f"Branch tip and reviewed tip: {reviewed}" in pr["body"]
75
+ assert rig.led("a finding ships open: missing --dry-run flag")
76
+ assert stage(rig) == DRAFT
77
+
78
+
79
+ def test_a_scoped_review_that_fails_twice_ships_the_fixed_tip_as_draft_naming_the_unreviewed_fix(tmp_path):
80
+ rig = rig_of(tmp_path)
81
+ rig.run(plan(**{"final/final-spec": [final(finding("missing --dry-run flag"))],
82
+ "final/fixer": [fixer(fn("02"), "add the flag")],
83
+ "final/final-reviewer": [stopped(), stopped()]}), *AUTONOMOUS)
84
+ assert rig.code == 0, rig.out
85
+ reviewed = rig.final()["reviewed"]
86
+ assert rig.pushes() == [f"refs/heads/feat/csv {rig.branch()}"] and rig.branch() != reviewed
87
+ (pr,) = rig.prs()
88
+ assert "--draft" in pr["argv"] and "the final-reviewer: it reported BLOCKED" in pr["body"]
89
+ assert f"reviewed tip: {reviewed}; {not_reviewed(rig, reviewed)}" in pr["body"]
90
+ assert "fix(02): add the flag" in not_reviewed(rig, reviewed)
91
+ assert stage(rig) == DRAFT
92
+
93
+
94
+ def test_a_critical_finding_open_when_the_final_fixer_fails_parks_for_the_operator_who_may_ship_it(tmp_path):
95
+ """No agent ships a critical finding: the driver does not take `ship-draft` itself while one is open."""
96
+ rig = rig_of(tmp_path)
97
+ steps = plan(**{"final/final-correctness": [final(finding("ledger write not atomic", "critical"))],
98
+ "final/fixer": [FIXER_STOPPED] * 2})
99
+ rig.run(steps, *AUTONOMOUS)
100
+ assert rig.code == 2, rig.out
101
+ assert not rig.pushes() and not rig.prs()
102
+ (question,) = decisions(rig)["questions"]
103
+ assert question["id"] == "final-ticket-blocked-1" and "ship-draft" in [o["id"] for o in question["options"]]
104
+ assert not rig.led("(ship-draft)") and rig.final()["ship"] is None
105
+ rig.run(steps, "--answer", "final-ticket-blocked-1=ship-draft", *AUTONOMOUS)
106
+ assert rig.code == 0, rig.out
107
+ assert rig.pushes() == [f"refs/heads/feat/csv {rig.final()['reviewed']}"]
108
+ (pr,) = rig.prs()
109
+ assert "--draft" in pr["argv"] and rig.led("a finding ships open: ledger write not atomic")
110
+ assert not rig.led("Ruled by the driver, not the operator.")
111
+ assert len(rig.final_calls("fixer")) == 2, "the operator's ship-draft runs no more repair"
112
+
113
+
114
+ def test_a_run_stopped_after_the_ruling_pushes_the_recorded_tip_and_refuses_a_branch_that_moved(tmp_path):
115
+ rig = rig_of(tmp_path)
116
+ steps = plan(**{"final/final-structure": [stopped(), stopped()]})
117
+ rig.run(steps, "--no-ask", "--retries", "0")
118
+ shipped = rig.final()["ship"]
119
+ assert rig.code == 0 and not rig.pushes(), rig.out
120
+ assert shipped == {"tip": rig.branch(), "stops": [
121
+ {"subject": "the final-structure: it reported BLOCKED: cannot read the spec", "role": "final-structure"}]}
122
+ stray(rig)
123
+ rig.run(steps, "--push")
124
+ assert rig.code == 1 and not rig.pushes(), rig.out
125
+ assert rig.led(f"feat/csv moved from {shipped['tip'][:7]}, the gated tip that the ship-draft ruling ships")
126
+ git(rig.repo, "reset", "-q", "--hard", shipped["tip"])
127
+ rig.run(steps, "--push")
128
+ assert rig.code == 0 and rig.pushes() == [f"refs/heads/feat/csv {shipped['tip']}"], rig.out
129
+ assert len(rig.final_calls("final-structure")) == 2, "the recorded ruling reviews no more"
130
+
131
+
132
+ def test_a_red_gate_after_the_fix_of_a_critical_finding_parks_for_the_operator_who_may_ship_it(tmp_path):
133
+ """The fix batch clears the open findings before any review verifies the fix: the full gate red after its repair
134
+ leaves the critical finding unverified, so the driver does not take `ship-draft` itself."""
135
+ rig = Inside(tmp_path)
136
+ rig.gate_conf(full={'subjects': ['fix(01): review fix', 'fix(01): gate repair']})
137
+ steps = plan(**{'final/final-correctness': [final(finding('ledger write not atomic', 'critical'))],
138
+ 'final/fixer': [fixer('review\n', 'review fix', ticket_of='01'),
139
+ fixer('gate\n', 'gate repair', ticket_of='01')]})
140
+ rig.run(steps, *AUTONOMOUS)
141
+ assert rig.code == 2, rig.out
142
+ assert not rig.pushes() and not rig.prs()
143
+ assert not rig.final_calls('final-reviewer')
144
+ assert rig.final()['open'] == []
145
+ (question,) = decisions(rig)['questions']
146
+ assert question['id'] == 'final-ticket-blocked-1' and not rig.led('(ship-draft)')
147
+ rig.run(steps, '--answer', 'final-ticket-blocked-1=ship-draft', *AUTONOMOUS)
148
+ assert rig.code == 0, rig.out
149
+ assert rig.pushes() == [f'refs/heads/feat/csv {rig.branch()}'] and len(rig.final_calls('fixer')) == 2
150
+ (pr,) = rig.prs()
151
+ assert '--draft' in pr['argv'] and not rig.led('Ruled by the driver, not the operator.')
152
+
153
+
154
+ def parks_then_ships_on_the_operators_answer(rig, steps):
155
+ """The driver does not take `ship-draft` itself: the stop parks; the operator's `ship-draft` ships a draft."""
156
+ rig.run(steps, *AUTONOMOUS)
157
+ assert rig.code == 2, rig.out
158
+ assert not rig.pushes() and not rig.prs() and not rig.led("(ship-draft)")
159
+ (question,) = decisions(rig)["questions"]
160
+ assert question["id"] == "final-ticket-blocked-1"
161
+ rig.run(steps, "--answer", "final-ticket-blocked-1=ship-draft", *AUTONOMOUS)
162
+ assert rig.code == 0, rig.out
163
+ assert rig.pushes() == [f"refs/heads/feat/csv {rig.branch()}"]
164
+ (pr,) = rig.prs()
165
+ assert "--draft" in pr["argv"] and not rig.led("Ruled by the driver, not the operator.")
166
+
167
+
168
+ def test_a_critical_finding_of_one_lens_when_another_fails_twice_parks_for_the_operator(tmp_path):
169
+ """No review settled, but the accepted report of the correctness lens holds a critical finding."""
170
+ rig = rig_of(tmp_path)
171
+ parks_then_ships_on_the_operators_answer(rig, plan(**{
172
+ "final/final-correctness": [final(finding("ledger write not atomic", "critical"))],
173
+ "final/final-structure": [stopped(), stopped()]}))
174
+ assert rig.final()["round"] == 0
175
+
176
+
177
+ def test_a_carried_must_fix_finding_when_the_first_full_gate_stays_red_parks_for_the_operator(tmp_path):
178
+ """A must-fix finding carried from a ticket that merged at its fix cap is open before any review."""
179
+ rig = rig_of(tmp_path, RISKY)
180
+ rig.gate_conf(full={"subjects": ["feat(02): Quote fields", "fix(02): first repair"]})
181
+ regression = {**finding("QUOTING-REGRESSION"), "basis": "regression"}
182
+ parks_then_ships_on_the_operators_answer(rig, plan(**{
183
+ "02/reviewer": [review("02", [regression])] * 3, "02/fixer": [fix("02", 1), fix("02", 2)],
184
+ "final/fixer": [fixer(fn("02"), "first repair", ticket_of="02")]}))
185
+ assert [item["title"] for item in rig.final()["must_fix"]] == ["QUOTING-REGRESSION"]
186
+ assert not any(rig.final_calls(role) for role in LENSES)
187
+
188
+
189
+ def test_the_operators_ship_draft_with_no_gated_tip_is_refused_and_retry_remains(tmp_path):
190
+ """A failed rebase conflict agent leaves no tip that a full gate ran on: `ship-draft` would record nothing to
191
+ push, so the answer is a usage error and the question stays open."""
192
+ stuck = {"report": {"status": "BLOCKED", "commits": [], "files": [], "concerns": ["both sides are needed"]}}
193
+ resolved = {**RESOLVE, "files": {"demo/cli.py": "def main():\n return 'both'\n"}}
194
+ rig = moved(tmp_path, {"demo/cli.py": "def main():\n return 'base'\n"}, stuck, stuck)
195
+ assert rig.code == 2, rig.out
196
+ steps = plan(**{"final/conflict": [stuck, stuck, resolved]})
197
+ rig.run(steps, "--answer", "final-ticket-blocked-1=ship-draft", *UNATTENDED)
198
+ assert rig.code == 3 and "no full gate ran on" in rig.out and "`retry` remains" in rig.out, rig.out
199
+ (question,) = decisions(rig)["questions"]
200
+ assert question["id"] == "final-ticket-blocked-1" and rig.final()["ship"] is None
201
+ rig.run(steps, "--answer", "final-ticket-blocked-1=retry", *UNATTENDED)
202
+ assert rig.code == 0, rig.out
203
+ assert rig.pushes() == [f"refs/heads/feat/csv {rig.branch()}"] and "--draft" not in rig.prs()[0]["argv"]
@@ -183,3 +183,32 @@ def test_git_without_a_command_still_returns_gits_usage_error(repo):
183
183
  repo()
184
184
  result = driver_slots.git(".")
185
185
  assert result.returncode != 0 and "usage: git" in result.stdout + result.stderr
186
+
187
+
188
+ def test_a_set_aside_never_replaces_an_earlier_patch_and_writes_it_whole_before_the_reset(repo, tmp_path):
189
+ repo()
190
+ assert driver_slots.setup(2, None) == []
191
+ slot = driver_slots.path(2)
192
+ (tmp_path / slot / "wip.txt").write_text("half done\n")
193
+ earlier = tmp_path / "out/left-out.patch"
194
+ earlier.parent.mkdir()
195
+ earlier.write_text("the snapshot of a set-aside whose reset failed\n")
196
+ patch = driver_slots.fresh(earlier)
197
+ assert patch.name == "left-out-2.patch"
198
+ assert driver_slots.set_aside(slot, patch) == ""
199
+ assert "+half done" in patch.read_text() and earlier.read_text().startswith("the snapshot")
200
+ assert sorted(p.name for p in earlier.parent.iterdir()) == ["left-out-2.patch", "left-out.patch"]
201
+ assert driver_slots.git(slot, "status", "--porcelain").stdout == ""
202
+
203
+
204
+ def test_the_arbiter_checkout_is_removed_through_git_alone(repo, tmp_path):
205
+ import driver_arbiter
206
+ repo()
207
+ scratch = tmp_path / driver_arbiter.SCRATCH
208
+ scratch.mkdir(parents=True)
209
+ (scratch / "keep.txt").write_text("not a worktree of the run\n")
210
+ assert driver_arbiter._remove_scratch().startswith(f"cannot remove {driver_arbiter.SCRATCH}: ")
211
+ assert (scratch / "keep.txt").exists()
212
+ (scratch / "keep.txt").unlink()
213
+ scratch.rmdir()
214
+ assert driver_arbiter._remove_scratch() == ""