@jesdi/skills 0.0.77 → 0.0.79

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 (74) hide show
  1. package/README.md +3 -2
  2. package/package.json +1 -1
  3. package/skills/implement-spec/ARCHITECTURE.md +102 -54
  4. package/skills/implement-spec/README.md +53 -51
  5. package/skills/implement-spec/SKILL.md +5 -6
  6. package/skills/implement-spec/driver.py +67 -153
  7. package/skills/implement-spec/driver_agents.py +75 -25
  8. package/skills/implement-spec/driver_decisions.py +92 -199
  9. package/skills/implement-spec/driver_dispute.py +189 -0
  10. package/skills/implement-spec/driver_final.py +196 -97
  11. package/skills/implement-spec/driver_fixloop.py +102 -192
  12. package/skills/implement-spec/driver_legacy.py +73 -5
  13. package/skills/implement-spec/driver_locked.py +186 -0
  14. package/skills/implement-spec/driver_merge.py +3 -48
  15. package/skills/implement-spec/driver_report.py +84 -64
  16. package/skills/implement-spec/driver_review.py +12 -119
  17. package/skills/implement-spec/driver_run.py +167 -130
  18. package/skills/implement-spec/driver_state.py +11 -9
  19. package/skills/implement-spec/models.json +0 -2
  20. package/skills/implement-spec/prompts/arbitration.md +34 -0
  21. package/skills/implement-spec/prompts/conflict.md +1 -0
  22. package/skills/implement-spec/prompts/correction.md +7 -4
  23. package/skills/implement-spec/prompts/elsewhere.md +6 -0
  24. package/skills/implement-spec/prompts/final-fixer.md +1 -1
  25. package/skills/implement-spec/prompts/final-lens.md +40 -0
  26. package/skills/implement-spec/prompts/final-reviewer.md +7 -7
  27. package/skills/implement-spec/prompts/fixer.md +2 -2
  28. package/skills/implement-spec/prompts/implementer.md +1 -1
  29. package/skills/implement-spec/prompts/lens-copy.md +1 -0
  30. package/skills/implement-spec/prompts/lens-correctness.md +8 -0
  31. package/skills/implement-spec/prompts/lens-spec.md +2 -0
  32. package/skills/implement-spec/prompts/lens-structure.md +2 -0
  33. package/skills/implement-spec/prompts/rebase-conflict.md +1 -0
  34. package/skills/implement-spec/prompts/rereview.md +0 -1
  35. package/skills/implement-spec/prompts/rerun.md +1 -1
  36. package/skills/implement-spec/prompts/reviewer.md +3 -6
  37. package/skills/implement-spec/prompts/ruled.md +3 -0
  38. package/skills/implement-spec/prompts/test-writer.md +4 -5
  39. package/skills/implement-spec/tests/test_agents.py +23 -22
  40. package/skills/implement-spec/tests/test_amendments.py +6 -48
  41. package/skills/implement-spec/tests/test_arbitration.py +314 -0
  42. package/skills/implement-spec/tests/test_cli.py +3 -3
  43. package/skills/implement-spec/tests/test_decisions.py +251 -374
  44. package/skills/implement-spec/tests/test_driver.py +22 -50
  45. package/skills/implement-spec/tests/test_final.py +45 -77
  46. package/skills/implement-spec/tests/test_fixloop.py +400 -633
  47. package/skills/implement-spec/tests/test_landing.py +23 -126
  48. package/skills/implement-spec/tests/test_lenses.py +217 -0
  49. package/skills/implement-spec/tests/test_merge.py +0 -43
  50. package/skills/implement-spec/tests/test_models.py +50 -1
  51. package/skills/implement-spec/tests/test_report.py +9 -23
  52. package/skills/implement-spec/tests/test_review.py +15 -153
  53. package/skills/implement-spec/tests/test_review_page.py +7 -3
  54. package/skills/implement-spec/tests/test_scoped.py +125 -0
  55. package/skills/implement-spec/tests/test_state.py +8 -3
  56. package/skills/implement-spec/tests/test_stops.py +43 -61
  57. package/skills/implement-spec/tests/test_tidy.py +77 -98
  58. package/skills/implement-spec/tests/test_walk.py +7 -6
  59. package/skills/review-page/SKILL.md +1 -1
  60. package/skills/test-prune/SKILL.md +7 -3
  61. package/skills/test-prune/prune_source.py +48 -0
  62. package/skills/test-prune/prune_strengthen.py +87 -2
  63. package/skills/test-prune/tests/test_prune_strengthen.py +93 -0
  64. package/skills/to-tickets/SKILL.md +1 -1
  65. package/skills-manifest.json +9 -9
  66. package/skills/implement-spec/prompts/corrected.md +0 -3
  67. package/skills/implement-spec/prompts/correctness.md +0 -42
  68. package/skills/implement-spec/prompts/final-scoped.md +0 -1
  69. package/skills/implement-spec/prompts/full-review.md +0 -2
  70. package/skills/implement-spec/prompts/overruled.md +0 -7
  71. package/skills/implement-spec/prompts/rejected.md +0 -1
  72. package/skills/implement-spec/prompts/restored-red.md +0 -3
  73. package/skills/implement-spec/prompts/restored.md +0 -3
  74. package/skills/implement-spec/prompts/stands.md +0 -2
@@ -1,6 +1,7 @@
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
- commits with a scoped review, then stop before the push, or push and open the PR.
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
5
 
5
6
  `run.final` of state.json is the resume contract (`driver_state._final` makes it with every key):
6
7
  skipped why the end-of-run work did not start
@@ -11,7 +12,9 @@ commits with a scoped review, then stop before the push, or push and open the PR
11
12
  reviewed the last tip a review covered
12
13
  round the reviews done
13
14
  open the findings the fix batch is due for
15
+ lenses {lens role: {tip, report}}: the accepted report of each lens of the full review and the tip it covers
14
16
  batch the tip of the fix batch that the driver validated and named
17
+ phase `blocked` at a stop with questions, until a `retry` answer makes it `pending` again
15
18
  green_gates, pushed, pr
16
19
  """
17
20
  from __future__ import annotations
@@ -23,30 +26,32 @@ import shlex
23
26
  import shutil
24
27
  import subprocess
25
28
  import sys
29
+ from concurrent.futures import ThreadPoolExecutor
26
30
  from pathlib import Path
27
31
 
28
32
  import driver_agents
29
33
  import driver_decisions
30
34
  import driver_gate
35
+ import driver_locked
31
36
  import driver_merge
32
37
  import driver_review
33
38
  import driver_tidy
34
- from driver_run import FINAL, OUT, Blocked, Halted, Run, during, ledger
39
+ from driver_run import FINAL, FINAL_RESUME, OUT, Blocked, Call, Halted, Run, during, ledger
35
40
  from driver_slots import git, head
36
41
  from driver_state import State
37
42
  from driver_tickets import Ticket
38
43
 
39
- KIND = "final-finding"
40
- ROUNDS = 2 # the full review and the scoped one after the fix batch
41
- # The final review runs through the review-diff skill, which is installed next to this one.
44
+ # The final review runs through the review-diff skill, which must sit next to this one: `_installed` looks nowhere else.
42
45
  REVIEW_DIFF = driver_agents.SKILL.parent / "review-diff" / "SKILL.md"
46
+ SEVERITIES = ("critical", "important", "minor")
43
47
 
44
48
 
45
49
  def _installed(name: str) -> Path | None:
46
50
  """The SKILL.md of a skill: next to this skill, else in the skill folder of the Claude home or of the shared
47
- home of Codex and OpenCode."""
51
+ home of Codex and OpenCode. review-diff is only next to this skill."""
48
52
  claude = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
49
- homes = (driver_agents.SKILL.parent, claude / "skills", Path.home() / ".agents" / "skills")
53
+ homes = (REVIEW_DIFF.parent.parent,) if name == REVIEW_DIFF.parent.name else (
54
+ driver_agents.SKILL.parent, claude / "skills", Path.home() / ".agents" / "skills")
50
55
  return next((home / name / "SKILL.md" for home in homes if (home / name / "SKILL.md").is_file()), None)
51
56
 
52
57
 
@@ -55,6 +60,13 @@ def pr_skill() -> Path | None:
55
60
  return _installed("pr")
56
61
 
57
62
 
63
+ def _method(lens: driver_agents.Lens) -> Path | None:
64
+ """The file `lens` follows, in its skill where that is installed. None when the skill or the file is missing."""
65
+ skill = _installed(lens.skill)
66
+ method = skill and skill.parent / lens.method
67
+ return method if method and method.is_file() else None
68
+
69
+
58
70
  def pr_risk_skill() -> Path | None:
59
71
  """The SKILL.md of the pr-risk skill, which parses and validates the merge-risk block of the PR body."""
60
72
  return _installed("pr-risk")
@@ -76,24 +88,34 @@ def _has_origin() -> bool:
76
88
  return git(".", "remote", "get-url", "origin").returncode == 0
77
89
 
78
90
 
91
+ def _method_errors() -> list[str]:
92
+ """One error per lens of the final review whose method is missing."""
93
+ return [f"the {lens.skill} skill is missing its {lens.method}: the {lens.source} lens of the final review follows "
94
+ f"it; install it next to implement-spec with `npx skills add jesdi/general-skills --skill {lens.skill}`"
95
+ for lens in driver_agents.LENSES.values() if not _method(lens)]
96
+
97
+
79
98
  def precondition_errors(push: bool, base: str | None) -> list[str]:
80
99
  """[] or the errors that stop the run before any agent."""
100
+ errors = _method_errors() + (_push_errors() if push else [])
101
+ if base and not _has_origin():
102
+ errors.append(f"--base {base} names a branch of origin, and the repository has no origin remote; "
103
+ "add the remote, or run without --base")
104
+ return errors
105
+
106
+
107
+ def _push_errors() -> list[str]:
108
+ """The errors that stop a run that is to push before any agent."""
81
109
  errors = []
82
- if not REVIEW_DIFF.exists():
83
- errors.append(f"{REVIEW_DIFF} is missing: the final review runs through it; install the review-diff skill "
84
- "next to implement-spec")
85
- if push and not pr_skill():
110
+ if not pr_skill():
86
111
  errors.append("the pr skill is missing: the PR body follows it; install it with "
87
112
  "`npx skills add mattpocock/skills --skill pr`, or run without --push and --unattended")
88
- if push and not pr_risk_skill():
113
+ if not pr_risk_skill():
89
114
  errors.append(f"the pr-risk skill is missing: the PR body carries its merge-risk block; install it with "
90
115
  f"{PR_RISK_INSTALL}, or run without --push and --unattended")
91
- if push and not _has_origin():
116
+ if not _has_origin():
92
117
  errors.append("the repository has no origin remote: --unattended and --push push the PR branch to origin; "
93
118
  "add the remote, or run without them to stop before the push")
94
- if base and not _has_origin():
95
- errors.append(f"--base {base} names a branch of origin, and the repository has no origin remote; "
96
- "add the remote, or run without --base")
97
119
  return errors
98
120
 
99
121
 
@@ -116,10 +138,6 @@ def _title(finding: dict) -> str:
116
138
  return f"{finding['title']} ({finding['file']}:{finding['line']})"
117
139
 
118
140
 
119
- def _locked_files(run: Run) -> list[str]:
120
- return sorted({path for entry in run.state.read()["tickets"].values() for path in entry["locked"]})
121
-
122
-
123
141
  def _last(commits: dict[str, str]) -> str:
124
142
  return list(commits.values())[-1]
125
143
 
@@ -174,6 +192,7 @@ def _keep_published_history(run: Run, tip: str, base: str, onto: str) -> None:
174
192
 
175
193
 
176
194
  def _rebase_is_open() -> bool:
195
+ """A rebase is open in slot 1."""
177
196
  return any(Path(git(".", "rev-parse", "--git-path", name).stdout.strip()).exists()
178
197
  for name in ("rebase-merge", "rebase-apply"))
179
198
 
@@ -182,35 +201,59 @@ def _files_in_conflict() -> list[str]:
182
201
  return git(".", "diff", "--name-only", "--diff-filter=U").stdout.split()
183
202
 
184
203
 
185
- def _run_rebase_conflict_agent(run: Run, env: dict, values: dict) -> str:
186
- """Run the conflict agent on the open rebase and continue the rebase it resolved. Returns "" or why it blocked."""
204
+ def _stop() -> str:
205
+ """The commit the open rebase stopped at; "" when none."""
206
+ return git(".", "rev-parse", "-q", "--verify", "REBASE_HEAD").stdout.strip()
207
+
208
+
209
+ def _rebase_check(run: Run, stop: str, context: dict) -> driver_locked.Locked | None:
210
+ """The locked-file check of the rebase conflict agent when it ends: every ticket's locked files as the recovery
211
+ point has them. The driver goes on with a rebase that the agent left open, so the check reads the rebased tip, and
212
+ the report is checked on that tip in place of its `commits`, which may name HEAD before the driver's commit. A
213
+ rebase that git cannot go on with at `stop`, the stop the agent was given, rejects a done report with git's error;
214
+ one that stopped again at a later conflict has no tip to check (None), and the driver aborts it."""
215
+ if _rebase_is_open():
216
+ env = {**os.environ, **driver_merge.identity("HEAD")}
217
+ done = subprocess.run(["git", "-c", "core.editor=true", "rebase", "--continue"], capture_output=True,
218
+ text=True, env=env)
219
+ if done.returncode and _stop() == stop:
220
+ why = (done.stderr or done.stdout).strip() # git names an unstaged resolution on stdout
221
+ context["rejected"] = [f"git rebase --continue failed at the stop you resolved: {why}"]
222
+ return None
223
+ if _rebase_is_open():
224
+ return None
225
+ context["commits"] = [head(".")]
226
+ recovery = git(".", "rev-parse", run.names.recovery).stdout.strip()
227
+ return driver_locked.for_end_of_run(run.state.read()["tickets"], recovery)
228
+
229
+
230
+ def _run_rebase_conflict_agent(run: Run, values: dict) -> str:
231
+ """Run the conflict agent on the open rebase; the driver goes on with the rebase after it, and its report is
232
+ rejected while the rebased tip changes a locked file. Returns "" or why it blocked."""
233
+ stop = _stop()
187
234
  try:
188
- run.agent("conflict", FINAL, ".", values, template="rebase-conflict", detached=True)
235
+ run.agent(Call("conflict", FINAL, ".", values, template="rebase-conflict", detached=True,
236
+ locked=lambda context: _rebase_check(run, stop, context)))
189
237
  except Blocked as blocked:
190
238
  return str(blocked)
191
239
  except Halted:
192
240
  git(".", "rebase", "--abort")
193
241
  raise
194
- if _rebase_is_open(): # the agent resolved the files and did not go on
195
- subprocess.run(["git", "-c", "core.editor=true", "rebase", "--continue"], capture_output=True, env=env)
196
242
  return ""
197
243
 
198
244
 
199
- def _resolve_rebase_conflict(run: Run, env: dict, base: str, onto: str) -> None:
200
- """Run the conflict agent, once, on the rebase that is open in slot 1, then gate the rebased tip. No rebase is
201
- open afterwards, also when this raises."""
245
+ def _resolve_rebase_conflict(run: Run, base: str, onto: str) -> None:
246
+ """Run the conflict agent, with its one rerun, on the rebase that is open in slot 1, then gate the rebased tip.
247
+ No rebase is open afterwards, also when this raises."""
202
248
  files = _files_in_conflict()
203
249
  values = {**_prompt_values(run), "branch": "HEAD", "start_sha": onto, "base": base, "files": " ".join(files)}
204
- error = _run_rebase_conflict_agent(run, env, values)
250
+ error = _run_rebase_conflict_agent(run, values)
205
251
  if _rebase_is_open():
206
252
  again = _files_in_conflict()
207
253
  git(".", "rebase", "--abort")
208
254
  raise Blocked(f"the conflict agent: {error}" if error else
209
255
  f"the rebase onto {base} conflicts a second time, in {', '.join(again)}")
210
- # The resolution may not change a locked test: each one is as the recovery point has it.
211
- before = git(".", "rev-parse", run.names.recovery).stdout.strip()
212
- changed = driver_review.locked_changes(".", before, _locked_files(run))
213
- if error := error or "; ".join(finding["title"] for finding in changed):
256
+ if error:
214
257
  raise Blocked(f"the conflict agent: {error}")
215
258
  ledger(f"Rebase: the conflict agent resolved the conflict with {base} in {', '.join(files)} at {head('.')[:7]}.")
216
259
  with during("the gate after the rebase"):
@@ -223,7 +266,7 @@ def _rebase(run: Run, tip: str, base: str, onto: str) -> None:
223
266
  git(".", "checkout", "-q", "--detach", tip)
224
267
  done = subprocess.run(["git", "-c", "core.editor=true", "rebase", onto], capture_output=True, text=True, env=env)
225
268
  if _rebase_is_open():
226
- _resolve_rebase_conflict(run, env, base, onto)
269
+ _resolve_rebase_conflict(run, base, onto)
227
270
  elif done.returncode:
228
271
  raise Blocked(f"git rebase: {done.stderr.strip()}")
229
272
 
@@ -325,27 +368,12 @@ def _carried_findings() -> str:
325
368
 
326
369
  def _check_review_is_due(run: Run, final: dict, tip: str) -> None:
327
370
  """Only a tip the driver made gets a review: the tidied tip, then the tip of the validated fix batch."""
328
- if final["round"] >= ROUNDS:
329
- raise Blocked(f"the two review rounds are done and the tip {tip[:7]} of {run.pr} is not the reviewed tip "
330
- f"{final['reviewed'][:7]}")
331
371
  made = final["batch"] or final["tidied"]
332
372
  if tip != made:
333
373
  raise Blocked(f"the tip {tip[:7]} of {run.pr} is not a tip the driver made: only {made[:7]} gets a review, "
334
374
  f"so the run goes on when {run.pr} is at {made[:7]} again")
335
375
 
336
376
 
337
- def _record_review(state: dict, tip: str, to_fix: list[dict], evidence: list[str]) -> None:
338
- """The first review starts the batch; unresolved must-fix items cannot become accept questions."""
339
- record, final = state["run"], state["run"]["final"]
340
- first_round = final["round"] == 0
341
- final.update(reviewed=tip, round=final["round"] + 1,
342
- open=to_fix if first_round else [finding for finding in to_fix if finding.get("must_fix")])
343
- if not first_round:
344
- other = [finding for finding in to_fix if not finding.get("must_fix")]
345
- if other:
346
- driver_decisions.stop(record, KIND, "", [_title(finding) for finding in other], evidence)
347
-
348
-
349
377
  def _settle_review(run: Run, done: int, tip: str, covered: str, found: list[dict]) -> None:
350
378
  """An accepted review of the range `covered`, after `done` earlier rounds: its findings go to their file, the
351
379
  ledger and state.json."""
@@ -353,50 +381,115 @@ def _settle_review(run: Run, done: int, tip: str, covered: str, found: list[dict
353
381
  file = folder / f"findings-{done}.json"
354
382
  file.write_text(json.dumps(found, indent=1) + "\n")
355
383
  for finding in found:
356
- ledger(f"Final review round {done + 1}: {finding['severity']} finding of kind {finding['kind']} at "
357
- f"{finding['file']}:{finding['line']}: {finding['title']}.")
384
+ ledger(f"Final review round {done + 1}: {finding['severity']} finding of kind {finding['kind']} from "
385
+ f"{finding['source']} at {finding['file']}:{finding['line']}: {finding['title']}.")
358
386
  to_fix = [finding for finding in found if finding["severity"] in driver_review.OPEN]
359
- evidence = [str(file), str(folder / f"final-reviewer-{done}.json")]
360
- run.state.update(lambda state: _record_review(state, tip, to_fix, evidence))
387
+ run.state.update(lambda state: state["run"]["final"].update(reviewed=tip, round=done + 1, open=to_fix))
361
388
  ledger(f"Final review round {done + 1}: the range {covered} is reviewed, the reviewed tip is {tip[:7]}, and "
362
389
  f"{len(to_fix)} critical or important finding{'s are' if len(to_fix) != 1 else ' is'} open.")
363
390
  if to_fix and done:
364
- questions = len([finding for finding in to_fix if not finding.get("must_fix")])
365
- if questions:
366
- ledger(f"End of run: {driver_decisions.decides(KIND, questions)} in {OUT / 'decisions.json'}: a third "
367
- "review round is never started.")
368
- required = len(to_fix) - questions
369
- if required:
370
- ledger(f"End of run: {required} required must-fix finding{'s remain' if required != 1 else ' remains'} "
371
- "open after the final fix batch; the run is blocked.")
391
+ # Another batch is the operator's call: one `final-ticket-blocked` question per finding.
392
+ titles = [_title(finding) for finding in to_fix]
393
+ run.ask(FINAL, "ticket-blocked", [f"a finding open after the scoped review: {title}" for title in titles],
394
+ str(file), FINAL_RESUME)
395
+ raise Blocked(f"the scoped review leaves {len(titles)} finding{'s' * (len(titles) > 1)} open: "
396
+ + "; ".join(titles))
372
397
 
373
398
 
374
399
  def _review(run: Run, final: dict, tip: str) -> None:
375
- """One round of the final review on `tip`: the full review, or after it the scoped one."""
400
+ """One round of the final review on `tip`: the full review by the three lenses, or after it the scoped one, on
401
+ the other-provider entry: another provider than the implementer's, and so than the fixer's when it shares
402
+ the implementer's."""
376
403
  done, folder = final["round"], OUT / FINAL
377
404
  values = {**_prompt_values(run), "start_sha": tip, "range": f"{final['reviewed'] or final['onto']}..{tip}",
378
- "gate": str(driver_gate.record_path(folder, driver_gate.FULL, tip)), "review_diff": str(REVIEW_DIFF),
405
+ "gate": str(driver_gate.record_path(folder, driver_gate.FULL, tip)),
379
406
  "ledger": str(OUT / "ledger.md"), "carried": _carried_findings(), "reviewed": str(final["reviewed"]),
380
407
  "must_fix_list": "\n".join(f"- {_title(finding)}" for finding in final["must_fix"]),
381
408
  "rulings": "\n".join(driver_decisions.rulings(run.state.read()["run"]["questions"])),
382
409
  "findings": str(folder / f"findings-{done - 1}.json")}
383
- # A locked file that differs from the tidied tip is a critical finding. The driver made that tip, and since
384
- # the tickets' own checks only the conflict agent of the rebase ran, which has the same check.
385
- found = driver_review.locked_changes(".", final["tidied"], _locked_files(run))
386
410
  with during("the final review"):
387
- report = run.read_only(FINAL, ".", run.pr, tip, lambda: run.agent(
388
- "final-reviewer", FINAL, ".", values, notes=["final-scoped"] if done else [], fix_round=done))
389
- _settle_review(run, done, tip, values["range"], _round_findings(final, found + report["findings"],
390
- _carried_must_fix(final, done, report)))
391
-
392
-
393
- def _carried_must_fix(final: dict, done: int, report: dict) -> list[dict]:
394
- """The must-fix findings that stay open after the round: all of them after the full review, else those the
395
- scoped review did not resolve."""
396
- if not done:
397
- return final["must_fix"]
398
- resolved = set(report.get("resolved_must_fix", []))
399
- return [finding for finding in final["must_fix"] if _title(finding) not in resolved]
411
+ # The full review resolves no must-fix finding: only the scoped review verifies a fix.
412
+ reviewed, resolved = _scoped(run, values, tip, done) if done else (_lenses(run, values, tip), set())
413
+ carried = [finding for finding in final["must_fix"] if _title(finding) not in resolved]
414
+ _settle_review(run, done, tip, values["range"], _round_findings(final, _merged(reviewed), carried))
415
+
416
+
417
+ def _scoped(run: Run, values: dict[str, str], tip: str, done: int) -> tuple[list[dict], set[str]]:
418
+ """The scoped review after the fix batch, one `final-reviewer`. Returns (its findings, each with the source
419
+ `final-reviewer`; the titles of the must-fix findings it resolved)."""
420
+ entries = driver_agents.other_provider_entries(run.models)
421
+ report = run.read_only(FINAL, ".", run.pr, tip, lambda: run.agent(Call(
422
+ "final-reviewer", FINAL, ".", values, entry=entries[0], entries=entries, fix_round=done)))
423
+ return ([{**finding, "source": "final-reviewer"} for finding in report["findings"]],
424
+ set(report.get("resolved_must_fix", [])))
425
+
426
+
427
+ def _lenses(run: Run, values: dict[str, str], tip: str) -> list[dict]:
428
+ """The full review: the three lenses at the same time in slot 1, inside one read-only check. Returns their
429
+ findings, each with the source of its lens. A lens with an accepted report for `tip` does not run again, unless
430
+ a lens changed the slot: then all three run again. The accepted reports are kept only once the slot is as the
431
+ review found it."""
432
+ values = {role: _lens_values(lens, values) for role, lens in driver_agents.LENSES.items()}
433
+ lenses = run.state.read()["run"]["final"]["lenses"]
434
+ kept = {role: one["report"] for role, one in lenses.items() if one["tip"] == tip}
435
+ # The first run keeps the reports; the second, after a lens changed the slot, keeps none.
436
+ passes = iter((kept, {}))
437
+ reports, errors = run.read_only(FINAL, ".", run.pr, tip, lambda: _run_lenses(run, values, next(passes)))
438
+ run.state.update(lambda state: state["run"]["final"]["lenses"].update(
439
+ {role: {"tip": tip, "report": report} for role, report in reports.items()}))
440
+ if errors:
441
+ raise Blocked("; ".join(errors))
442
+ return [{**finding, "source": lens.source} for role, lens in driver_agents.LENSES.items()
443
+ for finding in reports[role]["findings"]]
444
+
445
+
446
+ def _lens_values(lens: driver_agents.Lens, values: dict[str, str]) -> dict[str, str]:
447
+ """The prompt values of `lens`: those of the review, its name and its lines of the shared lens prompt. Its method
448
+ file is read only when its lines inline it."""
449
+ path = _method(lens)
450
+ # A lens that may run tests runs them on a copy: the other lenses work in the same worktree.
451
+ slots = {**values, "path": str(path), "copy": driver_agents.render("lens-copy", values),
452
+ **({"text": path.read_text()} if lens.inline else {})}
453
+ # The shared prompt puts the lines on their own lines.
454
+ return {**values, "lens": lens.source, "method": driver_agents.render(f"lens-{lens.source}", slots).rstrip("\n")}
455
+
456
+
457
+ def _run_lenses(run: Run, values: dict[str, dict[str, str]],
458
+ kept: dict[str, dict]) -> tuple[dict[str, dict], list[str]]:
459
+ """Run each lens with no report in `kept` at the same time, each with its `values`. Returns (the report of each lens that has one, why
460
+ each lens that stopped or whose report was rejected twice stops the round)."""
461
+ due = [role for role in driver_agents.LENSES if role not in kept]
462
+ running, reports, errors, halted = list(due), dict(kept), {}, []
463
+ run.asks.pop(FINAL, None) # a pass that a lens changed the slot in asks nothing
464
+
465
+ def call(role: str) -> None:
466
+ entries = driver_agents.lens_entries(run.models, role)
467
+ try:
468
+ reports[role] = run.agent(Call(role, FINAL, ".", values[role], entry=entries[0], entries=entries,
469
+ template="final-lens", alone=lambda: len(running) == 1))
470
+ except Blocked as blocked: # it stopped or was rejected two times
471
+ errors[role] = f"the {role}: {blocked}"
472
+ except Halted as failed:
473
+ halted.append(failed)
474
+ finally:
475
+ running.remove(role)
476
+
477
+ with ThreadPoolExecutor(len(due) or 1) as pool:
478
+ list(pool.map(call, due))
479
+ if halted:
480
+ raise halted[0]
481
+ return reports, [errors[role] for role in driver_agents.LENSES if role in errors]
482
+
483
+
484
+ def _merged(reviewed: list[dict]) -> list[dict]:
485
+ """The `reviewed` findings with each (file, line, title) once: the more severe finding stays, a tie keeps the
486
+ earlier one."""
487
+ kept: dict[tuple, dict] = {}
488
+ for finding in reviewed:
489
+ key = (finding["file"], finding["line"], finding["title"])
490
+ if key not in kept or SEVERITIES.index(finding["severity"]) < SEVERITIES.index(kept[key]["severity"]):
491
+ kept[key] = finding
492
+ return list(kept.values())
400
493
 
401
494
 
402
495
  def _round_findings(final: dict, found: list[dict], carried: list[dict]) -> list[dict]:
@@ -437,13 +530,15 @@ def _run_fixer(run: Run, tickets: list[Ticket], final: dict, tip: str) -> dict:
437
530
  """Run the fixer on the PR branch in slot 1 and return its report. A rejected batch is undone."""
438
531
  folder = OUT / FINAL
439
532
  values = {**_prompt_values(run), "start_sha": tip, "findings": str(folder / f"findings-{final['round'] - 1}.json"),
440
- "locked": " ".join(_locked_files(run)),
533
+ "locked": " ".join(driver_locked.every(run.state.read()["tickets"])),
441
534
  "must_fix_list": "\n".join(f"- {_title(finding)}" for finding in final["must_fix"]),
442
535
  "findings_list": "\n".join(f"- {finding['severity']}: {_title(finding)}" for finding in final["open"])}
536
+ tidied = final["tidied"]
443
537
  try:
444
- return run.agent("fixer", FINAL, ".", values, template="final-fixer", fix_round=final["round"],
445
- check={"owners": [ticket.number for ticket in tickets],
446
- "must_fix": [_title(finding) for finding in final["must_fix"]]})
538
+ return run.agent(Call("fixer", FINAL, ".", values, template="final-fixer", fix_round=final["round"],
539
+ check={"owners": [ticket.number for ticket in tickets],
540
+ "must_fix": [_title(finding) for finding in final["must_fix"]]},
541
+ locked=lambda _: driver_locked.for_end_of_run(run.state.read()["tickets"], tidied)))
447
542
  except Blocked as blocked:
448
543
  raise Blocked(f"{blocked}{_undo_rejected_batch(run, tip)}") from None
449
544
  except Halted as halted:
@@ -477,10 +572,7 @@ def _review_until_reviewed(run: Run, tickets: list[Ticket]) -> None:
477
572
  with during("the gate"):
478
573
  run.gate(FINAL, ".", tip, driver_gate.FULL)
479
574
  _review(run, final, tip)
480
- elif final["open"]:
481
- if final["round"] >= ROUNDS:
482
- raise Blocked("the final review still has unresolved must-fix findings: " +
483
- "; ".join(_title(finding) for finding in final["open"]))
575
+ elif final["open"]: # after the full review, or after a `retry` of a finding the scoped review left open
484
576
  _fix_batch(run, tickets, final, tip)
485
577
  else:
486
578
  return
@@ -512,7 +604,7 @@ def _run_pr_writer(run: Run, tip: str, risk: Path, values: dict) -> str:
512
604
  for round_ in range(2):
513
605
  with during("the PR body"):
514
606
  report = run.read_only(FINAL, ".", run.pr, tip,
515
- lambda: run.agent("pr-writer", FINAL, ".", values, fix_round=round_))
607
+ lambda: run.agent(Call("pr-writer", FINAL, ".", values, fix_round=round_)))
516
608
  if not (errors := _risk_errors(risk, report["body"])):
517
609
  return report["body"]
518
610
  values["risk_errors"] = (f"Your previous body has an invalid merge-risk block. Fix it with the pr-risk "
@@ -598,14 +690,7 @@ def again(argv: list[str]) -> str:
598
690
 
599
691
  def _close(run: Run, tickets: list[Ticket]) -> list[str]:
600
692
  """The tip is reviewed and its gate is green: push when the run may. Returns the lines for the operator."""
601
- record = run.state.read()["run"]
602
- answers = [question["answer"] for question in record["questions"] if question["kind"] == KIND]
603
- if None in answers:
604
- return [] # parked: the driver prints the questions
605
- if kept := answers.count("fix"):
606
- raise Blocked(f"the operator keeps {kept} finding{'s' if kept > 1 else ''} of the final review open (fix): "
607
- "nothing is pushed")
608
- final = record["final"]
693
+ final = run.state.read()["run"]["final"]
609
694
  if run.args.push or run.args.unattended:
610
695
  return _push(run, final, tickets)
611
696
  if final["base"]:
@@ -633,9 +718,23 @@ def run(run: Run, tickets: list[Ticket]) -> tuple[bool, list[str]]:
633
718
  ledger(f"End-of-run work skipped: {reason}.")
634
719
  return False, []
635
720
  try:
721
+ if _parked(state):
722
+ return False, [] # the driver prints the questions
636
723
  _rewrite_once(run, tickets)
637
724
  _review_until_reviewed(run, tickets)
638
725
  return False, _close(run, tickets)
639
726
  except Blocked as blocked:
640
- ledger(f"End of run: BLOCKED at {blocked}.")
727
+ line = ledger(f"End of run: BLOCKED at {blocked}.")
728
+ if FINAL in run.asks: # with no question, the end of run is not recorded BLOCKED: the next run tries again
729
+ run.block(FINAL, line)
641
730
  return True, [f"End of run: BLOCKED at {blocked}"]
731
+
732
+
733
+ def _parked(state: dict) -> bool:
734
+ """True while the end of run is BLOCKED at a question that is open. Raises Blocked when it is BLOCKED with every
735
+ question answered, so by an `edit`: nothing runs and nothing is pushed."""
736
+ if state["run"]["final"]["phase"] != "blocked":
737
+ return False
738
+ if any(q["ticket"] == FINAL and q["answer"] is None for q in state["run"]["questions"]):
739
+ return True
740
+ raise Blocked("the operator keeps the end of run BLOCKED for an edit (edit): nothing is pushed")