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