@jesdi/skills 0.0.98 → 0.0.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/package.json +1 -1
  2. package/skills/implement-spec/ARCHITECTURE.md +10 -5
  3. package/skills/implement-spec/README.md +44 -17
  4. package/skills/implement-spec/SKILL.md +4 -2
  5. package/skills/implement-spec/driver.py +166 -40
  6. package/skills/implement-spec/driver_agents.py +26 -8
  7. package/skills/implement-spec/driver_arbiter.py +89 -0
  8. package/skills/implement-spec/driver_decisions.py +212 -39
  9. package/skills/implement-spec/driver_dispute.py +1 -1
  10. package/skills/implement-spec/driver_final.py +255 -186
  11. package/skills/implement-spec/driver_final_gate.py +1 -1
  12. package/skills/implement-spec/driver_legacy.py +15 -2
  13. package/skills/implement-spec/driver_overturn.py +106 -0
  14. package/skills/implement-spec/driver_pr.py +277 -0
  15. package/skills/implement-spec/driver_report.py +24 -6
  16. package/skills/implement-spec/driver_review.py +10 -4
  17. package/skills/implement-spec/driver_run.py +38 -15
  18. package/skills/implement-spec/driver_slots.py +33 -0
  19. package/skills/implement-spec/driver_state.py +29 -15
  20. package/skills/implement-spec/driver_summary.py +11 -4
  21. package/skills/implement-spec/models.json +2 -1
  22. package/skills/implement-spec/prompts/arbiter.md +38 -0
  23. package/skills/implement-spec/prompts/conflict.md +1 -1
  24. package/skills/implement-spec/prompts/pr-body.md +1 -1
  25. package/skills/implement-spec/recovery.md +4 -4
  26. package/skills/implement-spec/tests/conftest.py +3 -0
  27. package/skills/implement-spec/tests/test_arbiter.py +208 -0
  28. package/skills/implement-spec/tests/test_arbitration.py +1 -1
  29. package/skills/implement-spec/tests/test_cli.py +1 -1
  30. package/skills/implement-spec/tests/test_decisions.py +31 -7
  31. package/skills/implement-spec/tests/test_driver.py +10 -2
  32. package/skills/implement-spec/tests/test_final.py +34 -9
  33. package/skills/implement-spec/tests/test_fixloop.py +2 -2
  34. package/skills/implement-spec/tests/test_leave_out.py +203 -0
  35. package/skills/implement-spec/tests/test_legacy.py +25 -0
  36. package/skills/implement-spec/tests/test_lenses.py +6 -4
  37. package/skills/implement-spec/tests/test_overturn.py +362 -0
  38. package/skills/implement-spec/tests/test_report.py +1 -1
  39. package/skills/implement-spec/tests/test_scoped.py +18 -15
  40. package/skills/implement-spec/tests/test_ship_draft.py +203 -0
  41. package/skills/implement-spec/tests/test_slots.py +29 -0
  42. package/skills/implement-spec/tests/test_state.py +4 -2
  43. package/skills/implement-spec/tests/test_stops.py +21 -5
  44. package/skills/implement-spec/tests/test_tidy.py +7 -5
  45. package/skills-manifest.json +3 -3
@@ -1,7 +1,9 @@
1
1
  """The end of a run, when every ticket is merged and every slot is idle: tidy the PR branch into one commit per
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
- open asks `final-ticket-blocked-<n>`: only a `retry` runs another batch and scoped review.
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. A critical or must-fix one asks `final-finding-must-fix-<n>` instead, which only the
6
+ operator ships.
5
7
 
6
8
  `run.final` of state.json is the resume contract (`driver_state._final` makes it with every key):
7
9
  skipped why the end-of-run work did not start
@@ -14,9 +16,16 @@ open asks `final-ticket-blocked-<n>`: only a `retry` runs another batch and scop
14
16
  round the reviews done
15
17
  open the findings the fix batch is due for
16
18
  lenses {lens role: {tip, report}}: the accepted report of each lens of the full review and the tip it covers
17
- 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
18
23
  phase `blocked` at a stop with questions, until a `retry` answer makes it `pending` again
19
24
  green_gates, pushed, pr
25
+ body the tip the pr-writer's part of the PR body was written for (driver_pr)
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
20
29
  """
21
30
  from __future__ import annotations
22
31
 
@@ -26,9 +35,9 @@ import re
26
35
  import shlex
27
36
  import shutil
28
37
  import subprocess
29
- import sys
30
38
  from concurrent.futures import ThreadPoolExecutor
31
39
  from pathlib import Path
40
+ from typing import Callable
32
41
 
33
42
  import driver_agents
34
43
  import driver_decisions
@@ -36,56 +45,24 @@ import driver_gate
36
45
  import driver_final_gate
37
46
  import driver_locked
38
47
  import driver_merge
48
+ import driver_pr
39
49
  import driver_review
40
50
  import driver_tidy
41
- 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
42
52
  from driver_slots import git, head
43
53
  from driver_state import State
44
54
  from driver_tickets import Ticket
45
55
 
46
- # The final review runs through the review-diff skill, which must sit next to this one: `_installed` looks nowhere else.
47
- REVIEW_DIFF = driver_agents.SKILL.parent / "review-diff" / "SKILL.md"
48
56
  SEVERITIES = ("critical", "important", "minor")
49
57
 
50
58
 
51
- def _installed(name: str) -> Path | None:
52
- """The SKILL.md of a skill: next to this skill, else in the skill folder of the Claude home or of the shared
53
- home of Codex and OpenCode. review-diff is only next to this skill."""
54
- claude = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
55
- homes = (REVIEW_DIFF.parent.parent,) if name == REVIEW_DIFF.parent.name else (
56
- driver_agents.SKILL.parent, claude / "skills", Path.home() / ".agents" / "skills")
57
- return next((home / name / "SKILL.md" for home in homes if (home / name / "SKILL.md").is_file()), None)
58
-
59
-
60
- def pr_skill() -> Path | None:
61
- """The SKILL.md of the pr skill, which the PR body follows."""
62
- return _installed("pr")
63
-
64
-
65
59
  def _method(lens: driver_agents.Lens) -> Path | None:
66
60
  """The file `lens` follows, in its skill where that is installed. None when the skill or the file is missing."""
67
- skill = _installed(lens.skill)
61
+ skill = driver_agents.installed(lens.skill)
68
62
  method = skill and skill.parent / lens.method
69
63
  return method if method and method.is_file() else None
70
64
 
71
65
 
72
- def pr_risk_skill() -> Path | None:
73
- """The SKILL.md of the pr-risk skill, which parses and validates the merge-risk block of the PR body."""
74
- return _installed("pr-risk")
75
-
76
-
77
- PR_RISK_INSTALL = "`npx skills add jesdi/general-skills --skill pr-risk`"
78
-
79
-
80
- def _risk_errors(method: Path, body: str) -> str:
81
- """The errors of the merge-risk block of `body` as `pr-risk` names them, or "" when the block is valid."""
82
- checked = OUT / FINAL / "pr-risk-check.md"
83
- checked.write_text(body)
84
- done = subprocess.run([sys.executable, str(method.parent / "merge_risk.py"), "validate", str(checked)],
85
- capture_output=True, text=True)
86
- return (done.stdout + done.stderr).strip() if done.returncode else ""
87
-
88
-
89
66
  def _has_origin() -> bool:
90
67
  return git(".", "remote", "get-url", "origin").returncode == 0
91
68
 
@@ -109,12 +86,12 @@ def precondition_errors(push: bool, base: str | None) -> list[str]:
109
86
  def _push_errors() -> list[str]:
110
87
  """The errors that stop a run that is to push before any agent."""
111
88
  errors = []
112
- if not pr_skill():
89
+ if not driver_pr.pr_skill():
113
90
  errors.append("the pr skill is missing: the PR body follows it; install it with "
114
91
  "`npx skills add mattpocock/skills --skill pr`, or run without --push and --unattended")
115
- if not pr_risk_skill():
92
+ if not driver_pr.pr_risk_skill():
116
93
  errors.append(f"the pr-risk skill is missing: the PR body carries its merge-risk block; install it with "
117
- f"{PR_RISK_INSTALL}, or run without --push and --unattended")
94
+ f"{driver_pr.PR_RISK_INSTALL}, or run without --push and --unattended")
118
95
  if not _has_origin():
119
96
  errors.append("the repository has no origin remote: --unattended and --push push the PR branch to origin; "
120
97
  "add the remote, or run without them to stop before the push")
@@ -130,14 +107,9 @@ def finish_interrupted_move(state: State, pr: str) -> None:
130
107
  git(".", "checkout", "-q", pr)
131
108
 
132
109
 
133
- def _prompt_values(run: Run) -> dict[str, str]:
134
- """The pointers every prompt of the end of run gets. Its agents work in slot 1, the PR worktree."""
135
- return {"spec": run.args.spec, "tickets": run.args.tickets, "pr_branch": run.pr, "branch": run.pr,
136
- "gate": run.args.fast_gate}
137
-
138
-
139
- def _title(finding: dict) -> str:
140
- return f"{finding['title']} ({finding['file']}:{finding['line']})"
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"]}
141
113
 
142
114
 
143
115
  def _last(commits: dict[str, str]) -> str:
@@ -231,7 +203,7 @@ def _rebase_check(run: Run, stop: str, context: dict) -> driver_locked.Locked |
231
203
  return None
232
204
  context["commits"] = [head(".")]
233
205
  recovery = git(".", "rev-parse", run.names.recovery).stdout.strip()
234
- return driver_locked.for_end_of_run(run.state.read()["tickets"], recovery)
206
+ return driver_locked.for_end_of_run(_shipped(run), recovery)
235
207
 
236
208
 
237
209
  def _run_rebase_conflict_agent(run: Run, values: dict) -> str:
@@ -253,7 +225,7 @@ def _resolve_rebase_conflict(run: Run, base: str, onto: str) -> None:
253
225
  """Resolve the rebase in slot 1, with one agent rerun; the final integration gate checks its tip.
254
226
  No rebase is open afterwards, also when this raises."""
255
227
  files = _files_in_conflict()
256
- 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)}
257
229
  error = _run_rebase_conflict_agent(run, values)
258
230
  if _rebase_is_open():
259
231
  again = _files_in_conflict()
@@ -364,10 +336,10 @@ def _carried_findings() -> str:
364
336
  """Ticket observations and minor findings for the final review, with their evidence files."""
365
337
  lines = []
366
338
  for path in sorted(OUT.glob("[0-9]*/findings-*.json")):
367
- 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())
368
340
  if finding["severity"] == "minor"]
369
341
  for path in sorted(OUT.glob("[0-9]*/observations-*.json")):
370
- 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())]
371
343
  return "\n".join(dict.fromkeys(lines))
372
344
 
373
345
 
@@ -388,34 +360,46 @@ def _settle_review(run: Run, done: int, tip: str, covered: str, found: list[dict
388
360
  for finding in found:
389
361
  ledger(f"Final review round {done + 1}: {finding['severity']} finding of kind {finding['kind']} from "
390
362
  f"{finding['source']} at {finding['file']}:{finding['line']}: {finding['title']}.")
391
- to_fix = [finding for finding in found if finding["severity"] in driver_review.OPEN]
392
- run.state.update(lambda state: state["run"]["final"].update(reviewed=tip, round=done + 1, open=to_fix))
363
+ found_open = [finding for finding in found if finding["severity"] in driver_review.OPEN]
364
+ run.state.update(lambda state: state["run"]["final"].update(reviewed=tip, round=done + 1, open=found_open))
393
365
  ledger(f"Final review round {done + 1}: the range {covered} is reviewed, the reviewed tip is {tip[:7]}, and "
394
- f"{len(to_fix)} critical or important finding{'s are' if len(to_fix) != 1 else ' is'} open.")
395
- if to_fix and done:
396
- # Another batch is the operator's call: one `final-ticket-blocked` question per finding.
397
- titles = [_title(finding) for finding in to_fix]
398
- run.ask(FINAL, "ticket-blocked", [f"a finding open after the scoped review: {title}" for title in titles],
399
- str(file), FINAL_RESUME)
366
+ f"{len(found_open)} critical or important finding{'s are' if len(found_open) != 1 else ' is'} open.")
367
+ if done:
368
+ _ask_open(run, file, found_open)
369
+
370
+
371
+ def _ask_open(run: Run, file: Path, found_open: list[dict]) -> None:
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)
400
377
  raise Blocked(f"the scoped review leaves {len(titles)} finding{'s' * (len(titles) > 1)} open: "
401
378
  + "; ".join(titles))
402
379
 
403
380
 
381
+ def _to_fix(run: Run, found: list[dict]) -> list[dict]:
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)]
386
+
387
+
404
388
  def _review(run: Run, final: dict, tip: str) -> None:
405
389
  """One round of the final review on `tip`: the full review by the three lenses, or after it the scoped one, on
406
390
  the other-provider entry: another provider than the implementer's, and so than the fixer's when it shares
407
391
  the implementer's."""
408
392
  done, folder = final["round"], OUT / FINAL
409
- 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}",
410
394
  "gate": str(driver_gate.record_path(folder, driver_gate.FULL, tip)),
411
395
  "ledger": str(OUT / "ledger.md"), "carried": _carried_findings(), "reviewed": str(final["reviewed"]),
412
- "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"]),
413
397
  "rulings": "\n".join(driver_decisions.rulings(run.state.read()["run"]["questions"])),
414
398
  "findings": str(folder / f"findings-{done - 1}.json")}
415
399
  with during("the final review"):
416
400
  # The full review resolves no must-fix finding: only the scoped review verifies a fix.
417
401
  reviewed, resolved = _scoped(run, values, tip, done) if done else (_lenses(run, values, tip), set())
418
- 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]
419
403
  _settle_review(run, done, tip, values["range"], _round_findings(final, _merged(reviewed), carried))
420
404
 
421
405
 
@@ -531,30 +515,45 @@ def _undo_rejected_batch(run: Run, tip: str) -> str:
531
515
  return ""
532
516
 
533
517
 
534
- def _fixer_call(run: Run, tickets: list[Ticket], final: dict, tip: str, gate_record: str = "") -> Call:
535
- """Build a final fixer call from review findings or the saved integration-gate failure."""
518
+ def _findings_list(run: Run, final: dict) -> str:
519
+ """The lines of the findings a fix batch is due for, for the final fixer's prompt."""
520
+ return "\n".join(f"- {finding['severity']}: {driver_review.title(finding)}"
521
+ for finding in _to_fix(run, final["open"]))
522
+
523
+
524
+ def _fixer_values(run: Run, final: dict, tip: str, gate_record: str) -> dict[str, str]:
525
+ """The prompt values of the final fixer: the review findings, and the saved gate failure for a gate repair."""
536
526
  folder = OUT / FINAL
537
- values = {**_prompt_values(run), "start_sha": tip, "findings": str(folder / f"findings-{final['round'] - 1}.json"),
538
- "locked": " ".join(driver_locked.every(run.state.read()["tickets"])),
539
- "must_fix_list": "\n".join(f"- {_title(finding)}" for finding in final["must_fix"]),
540
- "findings_list": "\n".join(f"- {finding['severity']}: {_title(finding)}" for finding in final["open"])}
541
- name = ""
542
- if gate_record:
543
- values.update(driver_final_gate.pointers(final, gate_record, tip))
544
- name = f"gate-fixer-{final['gate_repairs']}"
545
- tidied = final["tidied"]
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"]),
530
+ "findings_list": _findings_list(run, final)}
531
+ return {**values, **(driver_final_gate.pointers(final, gate_record, tip) if gate_record else {})}
532
+
533
+
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"]],
539
+ "fix": [values["gate_title"]] if gate_record else []}
540
+
541
+
542
+ def _fixer_call(run: Run, final: dict, tip: str, gate_record: str = "") -> Call:
543
+ """Build a final fixer call from review findings or the saved integration-gate failure."""
544
+ values = _fixer_values(run, final, tip, gate_record)
545
+ name = f"gate-fixer-{final['gate_repairs']}" if gate_record else ""
546
+ baseline = final["locked"] or final["tidied"]
546
547
  return Call("fixer", FINAL, ".", values, template="final-gate-fixer" if gate_record else "final-fixer",
547
548
  fix_round=final["round"], name=name,
548
- check={"owners": [ticket.number for ticket in tickets],
549
- "must_fix": [] if gate_record else [_title(finding) for finding in final["must_fix"]],
550
- "fix": [values["gate_title"]] if gate_record else []},
551
- 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))
552
551
 
553
552
 
554
- 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:
555
554
  """Run the fixer on the PR branch in slot 1 and return its report. A rejected batch is undone."""
556
555
  try:
557
- return run.agent(_fixer_call(run, tickets, final, tip, gate_record))
556
+ return run.agent(_fixer_call(run, final, tip, gate_record))
558
557
  except Blocked as blocked:
559
558
  raise Blocked(f"{blocked}{_undo_rejected_batch(run, tip)}") from None
560
559
  except Halted as halted:
@@ -575,130 +574,120 @@ def _name_batch(run: Run, tip: str, report: dict) -> list[str]:
575
574
  return named
576
575
 
577
576
 
578
- 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:
579
578
  """Run one bounded batch and settle its attributed tip before the next full gate."""
580
579
  with during("the fix batch"):
581
- report = _run_fixer(run, tickets, final, tip, gate_record)
580
+ report = _run_fixer(run, final, tip, gate_record)
582
581
  named = _name_batch(run, tip, report)
583
582
  fields = dict(open=[], batch=named[-1] if named else tip)
584
583
  if gate_record:
585
584
  fields.update(gate_repairs=final["gate_repairs"] + 1, gate_failure=None)
586
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`."""
587
591
  subjects = ", ".join(f"{commit[:7]} {driver_tidy.text(commit).splitlines()[0]}" for commit in named)
588
- label = "integration gate" if gate_record else "final review"
589
592
  ledger(f"Fix batch of the {label}: {len(named)} commit{'s' if len(named) != 1 else ''} on {tip[:7]}: "
590
593
  f"{subjects or 'no code change'}.")
591
594
 
592
595
 
593
- def _review_until_reviewed(run: Run, tickets: list[Ticket]) -> None:
594
- """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."""
595
599
  while True:
596
600
  final, tip = run.state.read()["run"]["final"], run.tip()
601
+ if final["ship"]:
602
+ return
597
603
  if final["reviewed"] != tip:
598
604
  _check_review_is_due(run, final, tip)
599
605
  with during("the integration gate"):
600
606
  if record := driver_final_gate.failure(run, tip):
601
- _fix_batch(run, tickets, final, tip, record)
607
+ _fix_batch(run, final, tip, record)
602
608
  continue
603
609
  _review(run, final, tip)
604
- elif final["open"]: # after the full review, or after a `retry` of a finding the scoped review left open
605
- _fix_batch(run, tickets, final, tip)
610
+ elif _to_fix(run, final["open"]): # after the full review, or after a `retry` of a finding left open
611
+ _fix_batch(run, final, tip)
606
612
  else:
607
613
  return
608
614
 
609
615
 
610
- # ---------------------------------------------------------------- the push
611
-
612
- def _name(run: Run) -> str:
613
- """The title of the PR: the first heading of the spec, else the PR branch."""
614
- spec = Path(run.args.spec)
615
- lines = spec.read_text(errors="replace").splitlines() if spec.is_file() else []
616
- return next((line[2:].strip() for line in lines if line.startswith("# ")), run.pr)
617
-
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()
618
655
 
619
- def _review_coverage(final: dict) -> dict[str, str]:
620
- """The first full review may include gate repairs made after tidy; later reviews cover the remaining range."""
621
- full_tip = next((lens["tip"] for lens in final["lenses"].values()), final["tidied"])
622
- return {"full_review": f"{final['onto']}..{full_tip}",
623
- "scoped": f"{full_tip}..{final['reviewed']}" if full_tip != final["reviewed"] else "not needed"}
624
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
625
671
 
626
- def _facts(run: Run, final: dict, tickets: list[Ticket]) -> str:
627
- """The end of the PR body: the ticket-to-commit map, the fix commits, the rulings and the review coverage."""
628
- titles, tip = {ticket.number: ticket.title for ticket in tickets}, final["reviewed"]
629
- fixes = git(".", "log", "--reverse", "--format=- %h %s", f"{final['tidied']}..{tip}").stdout.strip()
630
- rulings = driver_decisions.rulings(run.state.read()["run"]["questions"])
631
- return driver_agents.render("pr-body", {
632
- "map": "\n".join(f"- {number}: {commit[:7]} {titles[number]}" for number, commit in final["commits"].items()),
633
- "fixes": fixes or "None.", "rulings": "\n".join(f"- {ruling}" for ruling in rulings) or "None.",
634
- "tip": tip, **_review_coverage(final),
635
- "providers": _review_providers(run.state.read()["run"]["agents"])})
636
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
637
682
 
638
- # The roles that review code, with their line in the PR body, and the roles that write it.
639
- _REVIEWS = {"reviewer": "Ticket reviews", "final-correctness": "Correctness lens", "final-reviewer": "Scoped review"}
640
- _AUTHORS = ("implementer", "fixer", "conflict")
641
683
 
684
+ # ---------------------------------------------------------------- the push
642
685
 
643
- def _review_providers(agents: list[dict]) -> str:
644
- """One line per reviewing role that ran: the entries it ran on, and whether one of them shares a provider with an
645
- entry that wrote code. It reads the agents that ran, so a preflight fallback of an earlier invocation that a later
646
- one undid is not claimed."""
647
- wrote = {driver_agents.split(agent["entry"])[0] for agent in agents if agent["role"] in _AUTHORS}
648
- lines = []
649
- for role, label in _REVIEWS.items():
650
- if used := sorted({agent["entry"] for agent in agents if agent["role"] == role}):
651
- same = any(driver_agents.split(entry)[0] in wrote for entry in used)
652
- lines.append(f"- {label} ran on: {', '.join(used)}" + (", on a provider that also wrote code" * same))
653
- return "\n".join(lines)
654
-
655
-
656
- def _run_pr_writer(run: Run, tip: str, risk: Path, values: dict) -> str:
657
- """Run the pr-writer, and once more with the errors of its merge-risk block. Returns the body it wrote."""
658
- for round_ in range(2):
659
- with during("the PR body"):
660
- report = run.read_only(FINAL, ".", run.pr, tip,
661
- lambda: run.agent(Call("pr-writer", FINAL, ".", values, fix_round=round_)))
662
- if not (errors := _risk_errors(risk, report["body"])):
663
- return report["body"]
664
- values["risk_errors"] = (f"Your previous body has an invalid merge-risk block. Fix it with the pr-risk "
665
- f"skill; its errors:\n{errors}\n")
666
- raise Blocked(f"the merge-risk block of the PR body is invalid after a second run of the pr-writer: {errors}")
667
-
668
-
669
- def _write_body(run: Run, final: dict, tickets: list[Ticket]) -> Path:
670
- """Write the PR body: what the pr-writer wrote with the method of the pr skill, then the facts of the run. A body
671
- written for the reviewed tip is kept when its merge-risk block still validates, so a PR that failed to open costs
672
- no second agent."""
673
- body, tip = OUT / FINAL / "pr-body.md", final["reviewed"]
674
- method, risk, facts = pr_skill(), pr_risk_skill(), _facts(run, final, tickets)
675
- if final["body"] == tip and body.is_file() and risk and not _risk_errors(risk, body.read_text()):
676
- return body
677
- if not method:
678
- raise Blocked("the pr skill is missing: the PR body follows it; install it with "
679
- "`npx skills add mattpocock/skills --skill pr`")
680
- if not risk:
681
- raise Blocked(f"the pr-risk skill is missing: the PR body carries its merge-risk block; install it with "
682
- f"{PR_RISK_INSTALL}")
683
- values = {**_prompt_values(run), "start_sha": tip, "range": f"{final['onto']}..{tip}",
684
- "gate": str(driver_gate.record_path(OUT / FINAL, driver_gate.FULL, tip)), "pr_skill": str(method),
685
- "pr_risk_skill": str(risk), "risk_errors": "", "facts": facts}
686
- body.write_text(f"{_run_pr_writer(run, tip, risk, values).strip()}\n\n{facts}")
687
- run.state.update(lambda state: state["run"]["final"].update(body=tip))
688
- return body
689
-
690
-
691
- def _open_pr(run: Run, final: dict, tickets: list[Ticket]) -> str:
692
- """Open the PR, ready for review, and return its URL."""
693
- body = _write_body(run, final, tickets)
694
- made = subprocess.run(["gh", "pr", "create", "--base", final["base"], "--head", run.pr, "--title", _name(run),
695
- "--body-file", str(body)], capture_output=True, text=True, stdin=subprocess.DEVNULL)
696
- if made.returncode:
697
- raise Blocked(f"gh pr create failed: {(made.stderr or made.stdout).strip()}")
698
- url = (made.stdout.split() or [""])[-1]
699
- run.state.update(lambda state: state["run"]["final"].update(pr=url))
700
- ledger(f"The PR of {run.pr} into {final['base']} is open: {url}.")
701
- return url
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}
702
691
 
703
692
 
704
693
  def _require_pushable(run: Run, tip: str) -> None:
@@ -709,19 +698,97 @@ def _require_pushable(run: Run, tip: str) -> None:
709
698
  "them, then run with --push again")
710
699
 
711
700
 
712
- def _push(run: Run, final: dict, tickets: list[Ticket]) -> list[str]:
713
- """Push the reviewed tip to origin, once and with no force, then open the PR, once. Returns the lines for the
714
- operator."""
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 ""
705
+
706
+
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)))
711
+
712
+
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"]
720
+
721
+
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"]
754
+
755
+
756
+ def _branch_tip(run: dict) -> str:
757
+ return git(".", "rev-parse", f"refs/heads/{run['pr_branch']}").stdout.strip()
758
+
759
+
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"]
768
+
769
+
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"])
715
774
  tip = final["reviewed"]
716
775
  if tip != run.tip() or tip not in final["green_gates"][driver_gate.FULL]:
717
- raise Blocked(f"the reviewed tip {tip[:7]} is not the tip of {run.pr} with a green full gate record: nothing "
718
- "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)
719
785
  if not final["base"]:
720
786
  raise Blocked(f"the end of run tidied {run.pr} when the repository had no origin remote, so it is on no base "
721
787
  "branch of origin: nothing is pushed")
722
788
  if not shutil.which("gh"):
723
789
  raise Blocked("gh is not on PATH: nothing is pushed")
724
790
  if final["pushed"] != tip:
791
+ driver_pr.require_open(final)
725
792
  _require_pushable(run, tip)
726
793
  # The commit, not the branch name: what leaves the machine is the tip the review covered.
727
794
  sent = git(".", "push", "-q", "origin", f"{tip}:refs/heads/{run.pr}")
@@ -729,8 +796,7 @@ def _push(run: Run, final: dict, tickets: list[Ticket]) -> list[str]:
729
796
  raise Blocked(f"git push origin {run.pr} failed: {sent.stderr.strip()}")
730
797
  run.state.update(lambda state: state["run"]["final"].update(pushed=tip))
731
798
  ledger(f"Pushed {run.pr} at {tip[:7]} to origin.")
732
- url = final["pr"] or _open_pr(run, final, tickets)
733
- 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)}"]
734
800
 
735
801
 
736
802
  def again(argv: list[str]) -> str:
@@ -755,10 +821,13 @@ def _close(run: Run, tickets: list[Ticket]) -> list[str]:
755
821
  return [f"Branch tip: {run.tip()}", f"Reviewed tip: {final['reviewed']}", f"Nothing is pushed. {how}"]
756
822
 
757
823
 
758
- def _unmerged_tickets(state: dict) -> str:
824
+ def _unmerged_tickets(state: dict, tickets: list[Ticket]) -> str:
759
825
  """"" or why the end-of-run work does not start. A ticket that is not merged can still merge after an answer,
760
- and its branch starts from the history as it is: a tidy would rewrite its branch point."""
761
- 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]
762
831
  return f"these tickets are not merged: {', '.join(waiting)}" if waiting else ""
763
832
 
764
833
 
@@ -766,7 +835,7 @@ def run(run: Run, tickets: list[Ticket]) -> tuple[bool, list[str]]:
766
835
  """Do the end of the run, from where state.json says it is. Call it only when no slot runs a ticket.
767
836
  Returns (the end of run is BLOCKED, the lines the operator reads last)."""
768
837
  state = run.state.read()
769
- reason, before = _unmerged_tickets(state), state["run"]["final"]["skipped"]
838
+ reason, before = _unmerged_tickets(state, tickets), state["run"]["final"]["skipped"]
770
839
  run.state.update(lambda new: new["run"]["final"].update(skipped=reason))
771
840
  if reason:
772
841
  if reason != before:
@@ -776,7 +845,7 @@ def run(run: Run, tickets: list[Ticket]) -> tuple[bool, list[str]]:
776
845
  if _parked(state):
777
846
  return False, [] # the driver prints the questions
778
847
  _rewrite_once(run, tickets)
779
- _review_until_reviewed(run, tickets)
848
+ _review_until_reviewed(run)
780
849
  return False, _close(run, tickets)
781
850
  except Blocked as blocked:
782
851
  line = ledger(f"End of run: BLOCKED at {blocked}.")