@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
@@ -2,7 +2,8 @@
2
2
  ticket, rebase it onto the fetched base tip, gate it, run the final review, let one fix batch land as `fix(NN)`
3
3
  commits with a scoped review, then stop before the push, or push and open the PR. A finding the scoped review leaves
4
4
  open asks `final-finding-open-<n>`: a `retry` runs another batch and scoped review, an `accept` or a `follow-up` ships
5
- the PR with it, as draft when it is critical.
5
+ the PR with it, as draft. A critical or must-fix one asks `final-finding-must-fix-<n>` instead, which only the
6
+ operator ships.
6
7
 
7
8
  `run.final` of state.json is the resume contract (`driver_state._final` makes it with every key):
8
9
  skipped why the end-of-run work did not start
@@ -15,10 +16,16 @@ the PR with it, as draft when it is critical.
15
16
  round the reviews done
16
17
  open the findings the fix batch is due for
17
18
  lenses {lens role: {tip, report}}: the accepted report of each lens of the full review and the tip it covers
18
- batch the tip of the fix batch that the driver validated and named
19
+ batch the tip of the fix batch that the driver validated and named, or of a ticket that merged after the
20
+ rewrite, once an overturn let it run again (landed_after_tidy)
21
+ locked the commit whose locked files the final fixers keep: None for the tidied tip, else the tip that the
22
+ last ticket that merged after the rewrite made
19
23
  phase `blocked` at a stop with questions, until a `retry` answer makes it `pending` again
20
24
  green_gates, pushed, pr
25
+ body the tip the pr-writer's part of the PR body was written for (driver_pr)
21
26
  draft the PR opened as draft
27
+ ship {tip, stops: [{subject, role}]} once a `ship-draft` answer settled (driver._settle): the gated tip
28
+ that the push ships as draft, None when no full gate ran on the branch tip, and the stops it names
22
29
  """
23
30
  from __future__ import annotations
24
31
 
@@ -28,9 +35,9 @@ import re
28
35
  import shlex
29
36
  import shutil
30
37
  import subprocess
31
- import sys
32
38
  from concurrent.futures import ThreadPoolExecutor
33
39
  from pathlib import Path
40
+ from typing import Callable
34
41
 
35
42
  import driver_agents
36
43
  import driver_decisions
@@ -38,56 +45,24 @@ import driver_gate
38
45
  import driver_final_gate
39
46
  import driver_locked
40
47
  import driver_merge
48
+ import driver_pr
41
49
  import driver_review
42
50
  import driver_tidy
43
- from driver_run import FINAL, FINAL_RESUME, OUT, Blocked, Call, Halted, Run, during, ledger
51
+ from driver_run import FINAL, FINAL_RESUME, OUT, Blocked, Call, Halted, Run, during, final_values, ledger
44
52
  from driver_slots import git, head
45
53
  from driver_state import State
46
54
  from driver_tickets import Ticket
47
55
 
48
- # The final review runs through the review-diff skill, which must sit next to this one: `_installed` looks nowhere else.
49
- REVIEW_DIFF = driver_agents.SKILL.parent / "review-diff" / "SKILL.md"
50
56
  SEVERITIES = ("critical", "important", "minor")
51
57
 
52
58
 
53
- def _installed(name: str) -> Path | None:
54
- """The SKILL.md of a skill: next to this skill, else in the skill folder of the Claude home or of the shared
55
- home of Codex and OpenCode. review-diff is only next to this skill."""
56
- claude = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
57
- homes = (REVIEW_DIFF.parent.parent,) if name == REVIEW_DIFF.parent.name else (
58
- driver_agents.SKILL.parent, claude / "skills", Path.home() / ".agents" / "skills")
59
- return next((home / name / "SKILL.md" for home in homes if (home / name / "SKILL.md").is_file()), None)
60
-
61
-
62
- def pr_skill() -> Path | None:
63
- """The SKILL.md of the pr skill, which the PR body follows."""
64
- return _installed("pr")
65
-
66
-
67
59
  def _method(lens: driver_agents.Lens) -> Path | None:
68
60
  """The file `lens` follows, in its skill where that is installed. None when the skill or the file is missing."""
69
- skill = _installed(lens.skill)
61
+ skill = driver_agents.installed(lens.skill)
70
62
  method = skill and skill.parent / lens.method
71
63
  return method if method and method.is_file() else None
72
64
 
73
65
 
74
- def pr_risk_skill() -> Path | None:
75
- """The SKILL.md of the pr-risk skill, which parses and validates the merge-risk block of the PR body."""
76
- return _installed("pr-risk")
77
-
78
-
79
- PR_RISK_INSTALL = "`npx skills add jesdi/general-skills --skill pr-risk`"
80
-
81
-
82
- def _risk_errors(method: Path, body: str) -> str:
83
- """The errors of the merge-risk block of `body` as `pr-risk` names them, or "" when the block is valid."""
84
- checked = OUT / FINAL / "pr-risk-check.md"
85
- checked.write_text(body)
86
- done = subprocess.run([sys.executable, str(method.parent / "merge_risk.py"), "validate", str(checked)],
87
- capture_output=True, text=True)
88
- return (done.stdout + done.stderr).strip() if done.returncode else ""
89
-
90
-
91
66
  def _has_origin() -> bool:
92
67
  return git(".", "remote", "get-url", "origin").returncode == 0
93
68
 
@@ -111,12 +86,12 @@ def precondition_errors(push: bool, base: str | None) -> list[str]:
111
86
  def _push_errors() -> list[str]:
112
87
  """The errors that stop a run that is to push before any agent."""
113
88
  errors = []
114
- if not pr_skill():
89
+ if not driver_pr.pr_skill():
115
90
  errors.append("the pr skill is missing: the PR body follows it; install it with "
116
91
  "`npx skills add mattpocock/skills --skill pr`, or run without --push and --unattended")
117
- if not pr_risk_skill():
92
+ if not driver_pr.pr_risk_skill():
118
93
  errors.append(f"the pr-risk skill is missing: the PR body carries its merge-risk block; install it with "
119
- f"{PR_RISK_INSTALL}, or run without --push and --unattended")
94
+ f"{driver_pr.PR_RISK_INSTALL}, or run without --push and --unattended")
120
95
  if not _has_origin():
121
96
  errors.append("the repository has no origin remote: --unattended and --push push the PR branch to origin; "
122
97
  "add the remote, or run without them to stop before the push")
@@ -132,19 +107,9 @@ def finish_interrupted_move(state: State, pr: str) -> None:
132
107
  git(".", "checkout", "-q", pr)
133
108
 
134
109
 
135
- def _prompt_values(run: Run) -> dict[str, str]:
136
- """The pointers every prompt of the end of run gets. Its agents work in slot 1, the PR worktree."""
137
- return {"spec": run.args.spec, "tickets": run.args.tickets, "pr_branch": run.pr, "branch": run.pr,
138
- "gate": run.args.fast_gate}
139
-
140
-
141
- def _title(finding: dict) -> str:
142
- return f"{finding['title']} ({finding['file']}:{finding['line']})"
143
-
144
-
145
- def _key(finding: dict) -> str:
146
- """A finding as a `finding-open` question names it: its title and file, not its line, which a fix batch moves."""
147
- return f"{finding['title']} ({finding['file']})"
110
+ def due(final: dict, subject: str) -> bool:
111
+ """The last review leaves open the finding a finding question names `subject` (driver_decisions.subject)."""
112
+ return subject in {driver_decisions.subject(finding) for finding in final["open"]}
148
113
 
149
114
 
150
115
  def _last(commits: dict[str, str]) -> str:
@@ -238,7 +203,7 @@ def _rebase_check(run: Run, stop: str, context: dict) -> driver_locked.Locked |
238
203
  return None
239
204
  context["commits"] = [head(".")]
240
205
  recovery = git(".", "rev-parse", run.names.recovery).stdout.strip()
241
- return driver_locked.for_end_of_run(run.state.read()["tickets"], recovery)
206
+ return driver_locked.for_end_of_run(_shipped(run), recovery)
242
207
 
243
208
 
244
209
  def _run_rebase_conflict_agent(run: Run, values: dict) -> str:
@@ -260,7 +225,7 @@ def _resolve_rebase_conflict(run: Run, base: str, onto: str) -> None:
260
225
  """Resolve the rebase in slot 1, with one agent rerun; the final integration gate checks its tip.
261
226
  No rebase is open afterwards, also when this raises."""
262
227
  files = _files_in_conflict()
263
- values = {**_prompt_values(run), "branch": "HEAD", "start_sha": onto, "base": base, "files": " ".join(files)}
228
+ values = {**final_values(run), "branch": "HEAD", "start_sha": onto, "base": base, "files": " ".join(files)}
264
229
  error = _run_rebase_conflict_agent(run, values)
265
230
  if _rebase_is_open():
266
231
  again = _files_in_conflict()
@@ -371,10 +336,10 @@ def _carried_findings() -> str:
371
336
  """Ticket observations and minor findings for the final review, with their evidence files."""
372
337
  lines = []
373
338
  for path in sorted(OUT.glob("[0-9]*/findings-*.json")):
374
- lines += [f"- {path}: {_title(finding)}" for finding in json.loads(path.read_text())
339
+ lines += [f"- {path}: {driver_review.title(finding)}" for finding in json.loads(path.read_text())
375
340
  if finding["severity"] == "minor"]
376
341
  for path in sorted(OUT.glob("[0-9]*/observations-*.json")):
377
- lines += [f"- {path}: {_title(finding)}" for finding in json.loads(path.read_text())]
342
+ lines += [f"- {path}: {driver_review.title(finding)}" for finding in json.loads(path.read_text())]
378
343
  return "\n".join(dict.fromkeys(lines))
379
344
 
380
345
 
@@ -404,18 +369,20 @@ def _settle_review(run: Run, done: int, tip: str, covered: str, found: list[dict
404
369
 
405
370
 
406
371
  def _ask_open(run: Run, file: Path, found_open: list[dict]) -> None:
407
- """After the scoped review, another batch is a ruling: one `finding-open` question per finding that no answer
408
- ships with, and the end of run stops."""
409
- if titles := [_key(finding) for finding in _to_fix(run, found_open)]:
410
- run.ask(FINAL, "finding-open", titles, str(file), FINAL_RESUME)
372
+ """After the scoped review, another batch is a ruling: one question per finding that no answer ships with, of the
373
+ kind of the finding, and the end of run stops."""
374
+ if due := _to_fix(run, found_open):
375
+ titles = [driver_decisions.subject(finding) for finding in due]
376
+ run.ask(FINAL, [*zip(map(driver_decisions.finding_kind, due), titles)], str(file), FINAL_RESUME)
411
377
  raise Blocked(f"the scoped review leaves {len(titles)} finding{'s' * (len(titles) > 1)} open: "
412
378
  + "; ".join(titles))
413
379
 
414
380
 
415
381
  def _to_fix(run: Run, found: list[dict]) -> list[dict]:
416
- """The findings of `found` that a fix batch is due for: those that no `accept` or `follow-up` ships with."""
417
- waived = driver_decisions.waived(run.state.read()["run"]["questions"])
418
- return [finding for finding in found if _key(finding) not in waived]
382
+ """The findings of `found` that a fix batch is due for: those that no `accept` or `follow-up` ships with
383
+ (driver_decisions.waived)."""
384
+ questions = run.state.read()["run"]["questions"]
385
+ return [finding for finding in found if not driver_decisions.waived(questions, finding)]
419
386
 
420
387
 
421
388
  def _review(run: Run, final: dict, tip: str) -> None:
@@ -423,16 +390,16 @@ def _review(run: Run, final: dict, tip: str) -> None:
423
390
  the other-provider entry: another provider than the implementer's, and so than the fixer's when it shares
424
391
  the implementer's."""
425
392
  done, folder = final["round"], OUT / FINAL
426
- values = {**_prompt_values(run), "start_sha": tip, "range": f"{final['reviewed'] or final['onto']}..{tip}",
393
+ values = {**final_values(run), "start_sha": tip, "range": f"{final['reviewed'] or final['onto']}..{tip}",
427
394
  "gate": str(driver_gate.record_path(folder, driver_gate.FULL, tip)),
428
395
  "ledger": str(OUT / "ledger.md"), "carried": _carried_findings(), "reviewed": str(final["reviewed"]),
429
- "must_fix_list": "\n".join(f"- {_title(finding)}" for finding in final["must_fix"]),
396
+ "must_fix_list": "\n".join(f"- {driver_review.title(finding)}" for finding in final["must_fix"]),
430
397
  "rulings": "\n".join(driver_decisions.rulings(run.state.read()["run"]["questions"])),
431
398
  "findings": str(folder / f"findings-{done - 1}.json")}
432
399
  with during("the final review"):
433
400
  # The full review resolves no must-fix finding: only the scoped review verifies a fix.
434
401
  reviewed, resolved = _scoped(run, values, tip, done) if done else (_lenses(run, values, tip), set())
435
- carried = [finding for finding in final["must_fix"] if _title(finding) not in resolved]
402
+ carried = [finding for finding in final["must_fix"] if driver_review.title(finding) not in resolved]
436
403
  _settle_review(run, done, tip, values["range"], _round_findings(final, _merged(reviewed), carried))
437
404
 
438
405
 
@@ -550,42 +517,43 @@ def _undo_rejected_batch(run: Run, tip: str) -> str:
550
517
 
551
518
  def _findings_list(run: Run, final: dict) -> str:
552
519
  """The lines of the findings a fix batch is due for, for the final fixer's prompt."""
553
- return "\n".join(f"- {finding['severity']}: {_title(finding)}" for finding in _to_fix(run, final["open"]))
520
+ return "\n".join(f"- {finding['severity']}: {driver_review.title(finding)}"
521
+ for finding in _to_fix(run, final["open"]))
554
522
 
555
523
 
556
524
  def _fixer_values(run: Run, final: dict, tip: str, gate_record: str) -> dict[str, str]:
557
525
  """The prompt values of the final fixer: the review findings, and the saved gate failure for a gate repair."""
558
526
  folder = OUT / FINAL
559
- values = {**_prompt_values(run), "start_sha": tip, "findings": str(folder / f"findings-{final['round'] - 1}.json"),
560
- "locked": " ".join(driver_locked.every(run.state.read()["tickets"])),
561
- "must_fix_list": "\n".join(f"- {_title(finding)}" for finding in final["must_fix"]),
527
+ values = {**final_values(run), "start_sha": tip, "findings": str(folder / f"findings-{final['round'] - 1}.json"),
528
+ "locked": " ".join(driver_locked.every(_shipped(run))),
529
+ "must_fix_list": "\n".join(f"- {driver_review.title(finding)}" for finding in final["must_fix"]),
562
530
  "findings_list": _findings_list(run, final)}
563
531
  return {**values, **(driver_final_gate.pointers(final, gate_record, tip) if gate_record else {})}
564
532
 
565
533
 
566
- def _fixer_check(tickets: list[Ticket], final: dict, values: dict[str, str], gate_record: str) -> dict:
567
- """What the final fixer's report is checked against: a gate repair fixes the gate, a review batch the must-fix
568
- findings."""
569
- return {"owners": [ticket.number for ticket in tickets],
570
- "must_fix": [] if gate_record else [_title(finding) for finding in final["must_fix"]],
534
+ def _fixer_check(owners: list[str], final: dict, values: dict[str, str], gate_record: str) -> dict:
535
+ """What the final fixer's report is checked against: a commit of a merged ticket in `owners`, a gate repair that
536
+ fixes the gate, a review batch that fixes the must-fix findings."""
537
+ return {"owners": owners,
538
+ "must_fix": [] if gate_record else [driver_review.title(finding) for finding in final["must_fix"]],
571
539
  "fix": [values["gate_title"]] if gate_record else []}
572
540
 
573
541
 
574
- def _fixer_call(run: Run, tickets: list[Ticket], final: dict, tip: str, gate_record: str = "") -> Call:
542
+ def _fixer_call(run: Run, final: dict, tip: str, gate_record: str = "") -> Call:
575
543
  """Build a final fixer call from review findings or the saved integration-gate failure."""
576
544
  values = _fixer_values(run, final, tip, gate_record)
577
545
  name = f"gate-fixer-{final['gate_repairs']}" if gate_record else ""
578
- tidied = final["tidied"]
546
+ baseline = final["locked"] or final["tidied"]
579
547
  return Call("fixer", FINAL, ".", values, template="final-gate-fixer" if gate_record else "final-fixer",
580
548
  fix_round=final["round"], name=name,
581
- check=_fixer_check(tickets, final, values, gate_record),
582
- locked=lambda _: driver_locked.for_end_of_run(run.state.read()["tickets"], tidied))
549
+ check=_fixer_check(list(_shipped(run)), final, values, gate_record),
550
+ locked=lambda _: driver_locked.for_end_of_run(_shipped(run), baseline))
583
551
 
584
552
 
585
- def _run_fixer(run: Run, tickets: list[Ticket], final: dict, tip: str, gate_record: str = "") -> dict:
553
+ def _run_fixer(run: Run, final: dict, tip: str, gate_record: str = "") -> dict:
586
554
  """Run the fixer on the PR branch in slot 1 and return its report. A rejected batch is undone."""
587
555
  try:
588
- return run.agent(_fixer_call(run, tickets, final, tip, gate_record))
556
+ return run.agent(_fixer_call(run, final, tip, gate_record))
589
557
  except Blocked as blocked:
590
558
  raise Blocked(f"{blocked}{_undo_rejected_batch(run, tip)}") from None
591
559
  except Halted as halted:
@@ -606,204 +574,221 @@ def _name_batch(run: Run, tip: str, report: dict) -> list[str]:
606
574
  return named
607
575
 
608
576
 
609
- def _fix_batch(run: Run, tickets: list[Ticket], final: dict, tip: str, gate_record: str = "") -> None:
577
+ def _fix_batch(run: Run, final: dict, tip: str, gate_record: str = "") -> None:
610
578
  """Run one bounded batch and settle its attributed tip before the next full gate."""
611
579
  with during("the fix batch"):
612
- report = _run_fixer(run, tickets, final, tip, gate_record)
580
+ report = _run_fixer(run, final, tip, gate_record)
613
581
  named = _name_batch(run, tip, report)
614
582
  fields = dict(open=[], batch=named[-1] if named else tip)
615
583
  if gate_record:
616
584
  fields.update(gate_repairs=final["gate_repairs"] + 1, gate_failure=None)
617
585
  run.state.update(lambda state: state["run"]["final"].update(fields))
586
+ _led_batch("integration gate" if gate_record else "final review", tip, named)
587
+
588
+
589
+ def _led_batch(label: str, tip: str, named: list[str]) -> None:
590
+ """The ledger sentence of a fix batch of the `label` on `tip` that made the commits `named`."""
618
591
  subjects = ", ".join(f"{commit[:7]} {driver_tidy.text(commit).splitlines()[0]}" for commit in named)
619
- label = "integration gate" if gate_record else "final review"
620
592
  ledger(f"Fix batch of the {label}: {len(named)} commit{'s' if len(named) != 1 else ''} on {tip[:7]}: "
621
593
  f"{subjects or 'no code change'}.")
622
594
 
623
595
 
624
- def _review_until_reviewed(run: Run, tickets: list[Ticket]) -> None:
625
- """Gate and review the tip, and run the fix batch, until the tip is the reviewed tip."""
596
+ def _review_until_reviewed(run: Run) -> None:
597
+ """Gate and review the tip, and run the fix batch, until the tip is the reviewed tip, or until a `ship-draft`
598
+ ruling ships the tip as it is."""
626
599
  while True:
627
600
  final, tip = run.state.read()["run"]["final"], run.tip()
601
+ if final["ship"]:
602
+ return
628
603
  if final["reviewed"] != tip:
629
604
  _check_review_is_due(run, final, tip)
630
605
  with during("the integration gate"):
631
606
  if record := driver_final_gate.failure(run, tip):
632
- _fix_batch(run, tickets, final, tip, record)
607
+ _fix_batch(run, final, tip, record)
633
608
  continue
634
609
  _review(run, final, tip)
635
610
  elif _to_fix(run, final["open"]): # after the full review, or after a `retry` of a finding left open
636
- _fix_batch(run, tickets, final, tip)
611
+ _fix_batch(run, final, tip)
637
612
  else:
638
613
  return
639
614
 
640
615
 
641
- # ---------------------------------------------------------------- the push
616
+ # ---------------------------------------------------------------- a ticket that lands after the tidy
617
+
618
+ def replay(ticket: Ticket, slot: str, run: Run, tip: str, resolve: Callable[[str, list[str]], str]) -> str:
619
+ """A ticket that lands after the rewrite of the end of run, as an overturned `leave-out` does, lands as one commit
620
+ of its own work on the PR tip, as the tidy makes one: the change from where its branch leaves the history before
621
+ the rewrite (the recovery point) to its tip. The PR gets no second copy of the commits the tidy rewrote. Until
622
+ the replay is the recorded tip, `tip` is recorded as `replayed`: a run stopped in between replays again from it
623
+ (driver._restart_replay). A
624
+ conflict is open in the slot as a cherry-pick for `resolve`, the conflict agent of the ticket (from the PR tip, the
625
+ files in conflict), whose stop leaves the slot on `tip` and whose `retry` runs it again. Returns the ticket tip;
626
+ the slot is on it. A branch built on the PR tip as it stands carries no rewritten history and lands as it is: its
627
+ work can be the very commit of the history before the rewrite (the same change in the same second), where the
628
+ fork from the recovery point is the ticket tip itself and the replay would land nothing."""
629
+ final, pr_tip = run.state.read()["run"]["final"], run.tip()
630
+ if not final["recovery"] or driver_merge.ancestor(final["tidied"], tip) or driver_merge.ancestor(pr_tip, tip):
631
+ return tip
632
+ number, branch = ticket.number, run.names.ticket(ticket.number)
633
+ run.state.ticket(number, replayed=tip)
634
+ fork = git(".", "merge-base", final["recovery"], tip).stdout.strip()
635
+ tree = git(".", "merge-tree", "--write-tree", "--no-messages", f"--merge-base={fork}", pr_tip, tip)
636
+ if tree.returncode == 0:
637
+ own = _commit_of(tree.stdout.strip(), pr_tip, ticket, tip)
638
+ git(slot, "checkout", "-q", "-f", "-B", branch, own)
639
+ else:
640
+ work = _commit_of(f"{tip}^{{tree}}", fork, ticket, tip)
641
+ git(slot, "checkout", "-q", "-f", "-B", branch, pr_tip)
642
+ own = _replay_conflict(slot, branch, work, tip, lambda files: resolve(pr_tip, files))
643
+ run.state.ticket(number, tip=own)
644
+ ledger(f"Ticket {number}: its own work is replayed onto {run.pr} at {pr_tip[:7]}, after the rewrite of the end "
645
+ f"of run, as {own[:7]}.")
646
+ return own
647
+
648
+
649
+ def _commit_of(tree: str, parent: str, ticket: Ticket, tip: str) -> str:
650
+ """The commit of `tree` on `parent` with the message the tidy gives `ticket`."""
651
+ made = driver_merge.commit_tree([tree, "-p", parent], driver_tidy.message(ticket), driver_merge.identity(tip))
652
+ if made.returncode:
653
+ raise Blocked(f"git commit-tree failed: {made.stderr.strip()}")
654
+ return made.stdout.strip()
642
655
 
643
- def _name(run: Run) -> str:
644
- """The title of the PR: the first heading of the spec, else the PR branch."""
645
- spec = Path(run.args.spec)
646
- lines = spec.read_text(errors="replace").splitlines() if spec.is_file() else []
647
- return next((line[2:].strip() for line in lines if line.startswith("# ")), run.pr)
648
656
 
657
+ def _replay_conflict(slot: str, branch: str, work: str, tip: str, resolve: Callable[[list[str]], str]) -> str:
658
+ """Cherry-pick `work`, the ticket's own work on its fork from the recovery point, onto the PR tip the slot is on,
659
+ and let `resolve` finish it. When it stops, the slot is back on `tip`."""
660
+ env = {**os.environ, **driver_merge.identity(tip, slot)}
661
+ subprocess.run(["git", "-C", slot, "cherry-pick", work], capture_output=True, env=env)
662
+ files = git(slot, "diff", "--name-only", "--diff-filter=U").stdout.splitlines()
663
+ try:
664
+ if not files:
665
+ raise Blocked(f"the replay of {branch} onto the rewritten PR branch failed with no file in conflict")
666
+ return resolve(files)
667
+ except (Blocked, Halted):
668
+ git(slot, "cherry-pick", "--abort")
669
+ git(slot, "checkout", "-q", "-f", "-B", branch, tip)
670
+ raise
649
671
 
650
- def _review_coverage(final: dict) -> dict[str, str]:
651
- """The first full review may include gate repairs made after tidy; later reviews cover the remaining range."""
652
- full_tip = next((lens["tip"] for lens in final["lenses"].values()), final["tidied"])
653
- return {"full_review": f"{final['onto']}..{full_tip}",
654
- "scoped": f"{full_tip}..{final['reviewed']}" if full_tip != final["reviewed"] else "not needed"}
655
672
 
673
+ def landed_after_tidy(state: dict, number: str, pr_tip: str) -> None:
674
+ """Record ticket `number`, which merged at `pr_tip` after the rewrite, as an overturned `leave-out` does: the end of
675
+ run reviews that tip (`batch`), the final fixers keep every ticket's locked files as it has them (`locked`), the
676
+ ticket map names its commit, and the pr-writer writes its part of the PR body again (`body`). A `ship-draft` ruling
677
+ shipped the tip before it (`ship`): the new tip is gated and reviewed before it is pushed."""
678
+ final = state["run"]["final"]
679
+ if final["tidied"]:
680
+ final.update(batch=pr_tip, locked=pr_tip, body=None, ship=None)
681
+ final["commits"][number] = pr_tip
656
682
 
657
- def _facts(run: Run, final: dict, tickets: list[Ticket]) -> str:
658
- """The end of the PR body: the ticket-to-commit map, the fix commits, the rulings and the review coverage."""
659
- titles, tip = {ticket.number: ticket.title for ticket in tickets}, final["reviewed"]
660
- fixes = git(".", "log", "--reverse", "--format=- %h %s", f"{final['tidied']}..{tip}").stdout.strip()
661
- rulings = driver_decisions.rulings(run.state.read()["run"]["questions"])
662
- return driver_agents.render("pr-body", {
663
- "map": "\n".join(f"- {number}: {commit[:7]} {titles[number]}" for number, commit in final["commits"].items()),
664
- "fixes": fixes or "None.", "rulings": "\n".join(f"- {ruling}" for ruling in rulings) or "None.",
665
- "tip": tip, **_review_coverage(final),
666
- "providers": _review_providers(run.state.read()["run"]["agents"])})
667
683
 
684
+ # ---------------------------------------------------------------- the push
668
685
 
669
- # The roles that review code, with their line in the PR body, and the roles that write it.
670
- _REVIEWS = {"reviewer": "Ticket reviews", "final-correctness": "Correctness lens", "final-reviewer": "Scoped review"}
671
- _AUTHORS = ("implementer", "fixer", "conflict")
686
+ def _shipped(run: Run) -> dict:
687
+ """The records of the tickets the end of run ships, every one but the left-out ones: its to own and lock. Each of
688
+ them is merged, as the end of run starts only then."""
689
+ left = set(driver_pr.left_out(run))
690
+ return {number: entry for number, entry in run.state.read()["tickets"].items() if number not in left}
672
691
 
673
692
 
674
- def _review_providers(agents: list[dict]) -> str:
675
- """One line per reviewing role that ran: the entries it ran on, and whether one of them shares a provider with an
676
- entry that wrote code. It reads the agents that ran, so a preflight fallback of an earlier invocation that a later
677
- one undid is not claimed."""
678
- wrote = {driver_agents.split(agent["entry"])[0] for agent in agents if agent["role"] in _AUTHORS}
679
- lines = []
680
- for role, label in _REVIEWS.items():
681
- if used := sorted({agent["entry"] for agent in agents if agent["role"] == role}):
682
- same = any(driver_agents.split(entry)[0] in wrote for entry in used)
683
- lines.append(f"- {label} ran on: {', '.join(used)}" + (", on a provider that also wrote code" * same))
684
- return "\n".join(lines)
685
-
686
-
687
- def _run_pr_writer(run: Run, tip: str, risk: Path, values: dict) -> str:
688
- """Run the pr-writer, and once more with the errors of its merge-risk block. Returns the body it wrote."""
689
- for round_ in range(2):
690
- with during("the PR body"):
691
- report = run.read_only(FINAL, ".", run.pr, tip,
692
- lambda: run.agent(Call("pr-writer", FINAL, ".", values, fix_round=round_)))
693
- if not (errors := _risk_errors(risk, report["body"])):
694
- return report["body"]
695
- values["risk_errors"] = (f"Your previous body has an invalid merge-risk block. Fix it with the pr-risk "
696
- f"skill; its errors:\n{errors}\n")
697
- raise Blocked(f"the merge-risk block of the PR body is invalid after a second run of the pr-writer: {errors}")
698
-
699
-
700
- def _body_skills() -> tuple[Path, Path]:
701
- """The `pr` skill the body follows and the `pr-risk` skill its merge-risk block follows; Blocked when one is
702
- missing."""
703
- method, risk = pr_skill(), pr_risk_skill()
704
- if not method:
705
- raise Blocked("the pr skill is missing: the PR body follows it; install it with "
706
- "`npx skills add mattpocock/skills --skill pr`")
707
- if not risk:
708
- raise Blocked(f"the pr-risk skill is missing: the PR body carries its merge-risk block; install it with "
709
- f"{PR_RISK_INSTALL}")
710
- return method, risk
711
-
712
-
713
- def _writer_body(run: Run, final: dict, tickets: list[Ticket]) -> str:
714
- """What the pr-writer wrote with the method of the pr skill, its merge-risk block validated. A body written for
715
- the reviewed tip is kept when its merge-risk block still validates, so a PR that failed to open costs no second
716
- agent."""
717
- body, tip = OUT / FINAL / "pr-writer-body.md", final["reviewed"]
718
- risk = pr_risk_skill()
719
- if final["body"] == tip and body.is_file() and risk and not _risk_errors(risk, body.read_text()):
720
- return body.read_text()
721
- method, risk = _body_skills()
722
- facts = _facts(run, final, tickets)
723
- values = {**_prompt_values(run), "start_sha": tip, "range": f"{final['onto']}..{tip}",
724
- "gate": str(driver_gate.record_path(OUT / FINAL, driver_gate.FULL, tip)), "pr_skill": str(method),
725
- "pr_risk_skill": str(risk), "risk_errors": "", "facts": facts}
726
- body.write_text(_run_pr_writer(run, tip, risk, values).strip() + "\n")
727
- run.state.update(lambda state: state["run"]["final"].update(body=tip))
728
- return body.read_text()
729
-
730
-
731
- def _gh(argv: list[str], what: str) -> str:
732
- """Run `gh` and return the URL it prints last."""
733
- made = subprocess.run(["gh", *argv], capture_output=True, text=True, stdin=subprocess.DEVNULL)
734
- if made.returncode:
735
- raise Blocked(f"gh {what} failed: {(made.stderr or made.stdout).strip()}")
736
- return (made.stdout.split() or [""])[-1]
693
+ def _require_pushable(run: Run, tip: str) -> None:
694
+ """Block the push when a commit that origin lacks has no good signature with commit.gpgsign on, or has a
695
+ Co-authored-by trailer."""
696
+ if bad := driver_merge.unpushable(tip):
697
+ raise Blocked(f"commits of {run.pr} may not be pushed: {'; '.join(bad)}: nothing is pushed; sign or reword "
698
+ "them, then run with --push again")
737
699
 
738
700
 
739
- def _draft(final: dict) -> str:
740
- """Why the PR opens as draft; "" for a PR ready for review. A finding still open was shipped by a ruling, and no
741
- ruling settles a must-fix one."""
742
- held = [_title(finding) for finding in final["open"] if finding["severity"] == "critical" or finding.get("must_fix")]
743
- return f"a critical or must-fix finding is open: {'; '.join(held)}" if held else ""
701
+ def _gated(final: dict, tip: str) -> str:
702
+ """`tip` when a full gate ran on it, green or red; "" otherwise."""
703
+ red = (final["gate_failure"] or {}).get("tip") == tip
704
+ return tip if red or tip in final["green_gates"][driver_gate.FULL] else ""
744
705
 
745
706
 
746
- def _file_follow_ups(run: Run) -> None:
747
- """File each finding ruled `follow-up` as an issue, once: the PR body then links it. The issue carries a marker
748
- of the run and the question, so a run that stopped after `gh` filed it and before state.json kept its URL finds it
749
- again instead of filing it twice."""
750
- state = run.state.read()["run"]
751
- for q in driver_decisions.follow_ups(state["questions"]):
752
- marker = f"implement-spec follow-up {state['revision']}/{q['id']}"
753
- body = (f"A finding the final review of {run.pr} left open, shipped with its PR by this ruling:\n\n"
754
- f"{q['ruling']}\n\nEvidence: {q['evidence'][0]}\n\n{marker}\n")
755
- url = (_gh(["issue", "list", "--state", "all", "--search", f'"{marker}" in:body', "--json", "url", "--jq",
756
- ".[].url"], "issue list")
757
- or _gh(["issue", "create", "--title", q["subject"], "--body", body], "issue create"))
707
+ def _must_fix_open(run: Run, final: dict) -> bool:
708
+ """A critical or must-fix finding is open that no ruling of the operator ships with (driver_decisions.waived)."""
709
+ return any(driver_decisions.finding_kind(finding) == driver_decisions.MUST_FIX
710
+ for finding in _to_fix(run, _unverified(final)))
758
711
 
759
- def record(state: dict, ruled: str = q["id"], issue: str = url) -> None:
760
- next(one for one in state["run"]["questions"] if one["id"] == ruled)["issue"] = issue
761
712
 
762
- run.state.update(record)
763
- ledger(f"End of run: the follow-up {q['subject']} is filed as {url}.")
713
+ def _unverified(final: dict) -> list[dict]:
714
+ """The findings that no review has verified fixed. After a settled review, its findings file: a fix batch clears
715
+ `open` before any review verifies its fix, and only the next settled review replaces the file. Before one, the
716
+ findings of the lens reports accepted so far and the must-fix findings carried from the tickets."""
717
+ if final["round"]:
718
+ return json.loads((OUT / FINAL / f"findings-{final['round'] - 1}.json").read_text())
719
+ return [finding for one in final["lenses"].values() for finding in one["report"]["findings"]] + final["must_fix"]
764
720
 
765
721
 
766
- def _write_body(run: Run, final: dict, tickets: list[Ticket]) -> Path:
767
- """Write the PR body: the pr-writer's, then the facts of the run. The follow-up issues are filed once the
768
- pr-writer's body is valid, so a run that cannot open its PR files none, and the facts link them."""
769
- writer = _writer_body(run, final, tickets)
770
- _file_follow_ups(run)
771
- body = OUT / FINAL / "pr-body.md"
772
- body.write_text(f"{writer.strip()}\n\n{_facts(run, final, tickets)}")
773
- return body
722
+ def draft_ruling(run: Run) -> dict[str, str]:
723
+ """The driver's end-of-run draft policy, once its retries are spent and unless --ask: `ship-draft` for each open
724
+ end-of-run `ticket-blocked` question, when a full gate ran on the branch tip and no critical or must-fix finding
725
+ is open: no agent ships one. Else {}, and the stop parks for the operator, who may still answer `ship-draft`."""
726
+ state = run.state.read()["run"]
727
+ final = state["final"]
728
+ stops = [q["id"] for q in state["questions"]
729
+ if (q["answer"], q["kind"], q["ticket"]) == (None, "ticket-blocked", FINAL)]
730
+ if not stops or not _gated(final, run.tip()) or _must_fix_open(run, final):
731
+ return {}
732
+ return dict.fromkeys(stops, "ship-draft")
733
+
734
+
735
+ def ship_record(run: dict, answered: list[dict]) -> dict | None:
736
+ """What a `ship-draft` answer among the `answered` questions ships, for `run.final.ship`: the tip of the PR
737
+ branch when a full gate ran on it, green or red (else None, and the push refuses), and each stop with the role
738
+ that stopped. None with no such answer. The end of run reviews no more, and the push reads only this record."""
739
+ stops = [{"subject": q["subject"], "role": q.get("role")} for q in answered if q["answer"] == "ship-draft"]
740
+ if not stops:
741
+ return None
742
+ return {"tip": _gated(run["final"], _branch_tip(run)) or None, "stops": stops}
743
+
744
+
745
+ def refused_ship(run: dict, answers: dict[str, str]) -> list[str]:
746
+ """Why each `ship-draft` among the operator's `answers` is refused: no full gate ran on the tip of the PR branch,
747
+ as after a failed rebase conflict agent, so there is no tip to ship. The question stays open."""
748
+ tip = _branch_tip(run) if "ship-draft" in answers.values() else ""
749
+ if not tip or _gated(run["final"], tip):
750
+ return []
751
+ return [f"--answer {question}=ship-draft: no full gate ran on {tip[:7]}, the tip of {run['pr_branch']}, so there "
752
+ "is no gated tip to ship; the question stays open, and `retry` remains"
753
+ for question, option in answers.items() if option == "ship-draft"]
774
754
 
775
755
 
776
- def _open_pr(run: Run, final: dict, tickets: list[Ticket]) -> str:
777
- """Open the PR, ready for review or as draft, and return its URL."""
778
- body, draft = _write_body(run, final, tickets), _draft(final)
779
- url = _gh(["pr", "create", "--base", final["base"], "--head", run.pr, "--title", _name(run), "--body-file",
780
- str(body), *["--draft"] * bool(draft)], "pr create")
781
- run.state.update(lambda state: state["run"]["final"].update(pr=url, draft=bool(draft)))
782
- ledger(f"The PR of {run.pr} into {final['base']} is open{f' as a draft: {draft}' * bool(draft)}: {url}.")
783
- return url
756
+ def _branch_tip(run: dict) -> str:
757
+ return git(".", "rev-parse", f"refs/heads/{run['pr_branch']}").stdout.strip()
784
758
 
785
759
 
786
- def _require_pushable(run: Run, tip: str) -> None:
787
- """Block the push when a commit that origin lacks has no good signature with commit.gpgsign on, or has a
788
- Co-authored-by trailer."""
789
- if bad := driver_merge.unpushable(tip):
790
- raise Blocked(f"commits of {run.pr} may not be pushed: {'; '.join(bad)}: nothing is pushed; sign or reword "
791
- "them, then run with --push again")
760
+ def _shipped_tip(run: Run, ship: dict) -> str:
761
+ """The tip that the `ship-draft` ruling recorded, while the PR branch is still at it."""
762
+ if not ship["tip"]:
763
+ raise Blocked(f"the ship-draft ruling found no full gate run on the tip of {run.pr}: nothing is pushed")
764
+ if ship["tip"] != run.tip():
765
+ raise Blocked(f"{run.pr} moved from {ship['tip'][:7]}, the gated tip that the ship-draft ruling ships, to "
766
+ f"{run.tip()[:7]}: nothing is pushed")
767
+ return ship["tip"]
792
768
 
793
769
 
794
- def _push(run: Run, final: dict, tickets: list[Ticket]) -> list[str]:
795
- """Push the reviewed tip to origin, once and with no force, then open the PR, once. Returns the lines for the
796
- operator."""
770
+ def _pushable_tip(run: Run, final: dict) -> str:
771
+ """The tip to push: the reviewed tip with a green full gate, or the tip that a `ship-draft` ruling recorded."""
772
+ if final["ship"]:
773
+ return _shipped_tip(run, final["ship"])
797
774
  tip = final["reviewed"]
798
775
  if tip != run.tip() or tip not in final["green_gates"][driver_gate.FULL]:
799
- raise Blocked(f"the reviewed tip {tip[:7]} is not the tip of {run.pr} with a green full gate record: nothing "
800
- "is pushed")
776
+ raise Blocked(f"the reviewed tip {str(tip)[:7]} is not the tip of {run.pr} with a green full gate record: "
777
+ "nothing is pushed")
778
+ return tip
779
+
780
+
781
+ def _push(run: Run, final: dict, tickets: list[Ticket]) -> list[str]:
782
+ """Push the reviewed tip, or the gated tip of a draft, to origin, once and with no force, then open the PR, once.
783
+ Returns the lines for the operator."""
784
+ tip = _pushable_tip(run, final)
801
785
  if not final["base"]:
802
786
  raise Blocked(f"the end of run tidied {run.pr} when the repository had no origin remote, so it is on no base "
803
787
  "branch of origin: nothing is pushed")
804
788
  if not shutil.which("gh"):
805
789
  raise Blocked("gh is not on PATH: nothing is pushed")
806
790
  if final["pushed"] != tip:
791
+ driver_pr.require_open(final)
807
792
  _require_pushable(run, tip)
808
793
  # The commit, not the branch name: what leaves the machine is the tip the review covered.
809
794
  sent = git(".", "push", "-q", "origin", f"{tip}:refs/heads/{run.pr}")
@@ -811,8 +796,7 @@ def _push(run: Run, final: dict, tickets: list[Ticket]) -> list[str]:
811
796
  raise Blocked(f"git push origin {run.pr} failed: {sent.stderr.strip()}")
812
797
  run.state.update(lambda state: state["run"]["final"].update(pushed=tip))
813
798
  ledger(f"Pushed {run.pr} at {tip[:7]} to origin.")
814
- url = final["pr"] or _open_pr(run, final, tickets)
815
- return [f"Pushed {run.pr} at {tip} to origin.", f"PR: {url}"]
799
+ return [f"Pushed {run.pr} at {tip} to origin.", f"PR: {driver_pr.pr(run, final, tickets, tip)}"]
816
800
 
817
801
 
818
802
  def again(argv: list[str]) -> str:
@@ -837,10 +821,13 @@ def _close(run: Run, tickets: list[Ticket]) -> list[str]:
837
821
  return [f"Branch tip: {run.tip()}", f"Reviewed tip: {final['reviewed']}", f"Nothing is pushed. {how}"]
838
822
 
839
823
 
840
- def _unmerged_tickets(state: dict) -> str:
824
+ def _unmerged_tickets(state: dict, tickets: list[Ticket]) -> str:
841
825
  """"" or why the end-of-run work does not start. A ticket that is not merged can still merge after an answer,
842
- and its branch starts from the history as it is: a tidy would rewrite its branch point."""
843
- waiting = [number for number, entry in state["tickets"].items() if entry["phase"] != "merged"]
826
+ and its branch starts from the history as it is: a tidy would rewrite its branch point. A left-out ticket, and
827
+ each ticket it blocks, does not count: no answer in this run merges it."""
828
+ left = driver_decisions.left_out(state["run"]["questions"], tickets)
829
+ waiting = [number for number, entry in state["tickets"].items()
830
+ if entry["phase"] != "merged" and number not in left]
844
831
  return f"these tickets are not merged: {', '.join(waiting)}" if waiting else ""
845
832
 
846
833
 
@@ -848,7 +835,7 @@ def run(run: Run, tickets: list[Ticket]) -> tuple[bool, list[str]]:
848
835
  """Do the end of the run, from where state.json says it is. Call it only when no slot runs a ticket.
849
836
  Returns (the end of run is BLOCKED, the lines the operator reads last)."""
850
837
  state = run.state.read()
851
- reason, before = _unmerged_tickets(state), state["run"]["final"]["skipped"]
838
+ reason, before = _unmerged_tickets(state, tickets), state["run"]["final"]["skipped"]
852
839
  run.state.update(lambda new: new["run"]["final"].update(skipped=reason))
853
840
  if reason:
854
841
  if reason != before:
@@ -858,7 +845,7 @@ def run(run: Run, tickets: list[Ticket]) -> tuple[bool, list[str]]:
858
845
  if _parked(state):
859
846
  return False, [] # the driver prints the questions
860
847
  _rewrite_once(run, tickets)
861
- _review_until_reviewed(run, tickets)
848
+ _review_until_reviewed(run)
862
849
  return False, _close(run, tickets)
863
850
  except Blocked as blocked:
864
851
  line = ledger(f"End of run: BLOCKED at {blocked}.")