@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
@@ -25,7 +25,7 @@ def failure(run: Run, tip: str) -> str:
25
25
  run.state.update(lambda s: s['run']['final'].update(gate_failure=dict(tip=tip, record=record)))
26
26
  if final['gate_repairs'] >= final['gate_allowance']:
27
27
  subject = f'{RETRY_SUBJECT}: {tip[:7]}; read {record}'
28
- run.ask(FINAL, 'ticket-blocked', [subject], record, FINAL_RESUME._replace(
28
+ run.ask(FINAL, [('ticket-blocked', subject)], record, FINAL_RESUME._replace(
29
29
  gate_allowance=final['gate_repairs'] + 1))
30
30
  raise Blocked(subject)
31
31
  return record
@@ -5,7 +5,8 @@ Every run of a newer driver holds `lock` (driver._hold), so a newer and an older
5
5
  at the same time. The driver calls `resume` once, after the locks and before any check reads a ref: a run with no
6
6
  `schema` in state.json gets the new names of its refs; a run before schema 3 gets its gates as the full tier; a run
7
7
  before schema 4 keeps the ruling of each answered question, and one with an open question of a removed kind stops;
8
- a run before schema 5 gets its rulings and corrections keyed by their test.
8
+ a run before schema 5 gets its rulings and corrections keyed by their test; a run before schema 6 gets each open
9
+ `finding-open` question on a critical or must-fix finding as a `finding-must-fix` one, so no arbiter ships it.
9
10
  ponytail: delete this module, tests/test_legacy.py and its one line in driver._hold and in driver._start_errors
10
11
  once no older driver is left.
11
12
  """
@@ -169,9 +170,20 @@ def _all_per_test(state: dict) -> None:
169
170
  _per_test(entry, [path for path in asked if path.exists()])
170
171
 
171
172
 
173
+ def _must_fix(run: dict) -> None:
174
+ """Schema 6: an open `finding-open` question on a critical or must-fix finding of the last review becomes a
175
+ `finding-must-fix` one. It keeps its id and the fields decisions.json shows, and both kinds offer the same options,
176
+ so decisions.json keeps its revision and an answer given to it still counts."""
177
+ must_fix = {driver_decisions.subject(one) for one in run.get("final", {}).get("open", [])
178
+ if driver_decisions.finding_kind(one) == driver_decisions.MUST_FIX}
179
+ for q in run.get("questions", []):
180
+ if (q["answer"], q["kind"]) == (None, driver_decisions.FINDING_OPEN) and q["subject"] in must_fix:
181
+ q["kind"] = driver_decisions.MUST_FIX
182
+
183
+
172
184
  def _upgraded(state: dict) -> None:
173
185
  """Schema 3: every gate of an older driver was the full gate, so its greens and its count are of the full tier.
174
- Schema 4: an answered question keeps its ruling sentence. Schema 5: see `_per_test`."""
186
+ Schema 4: an answered question keeps its ruling sentence. Schema 5: see `_per_test`. Schema 6: see `_must_fix`."""
175
187
  run = state["run"]
176
188
  for q in run.get("questions", []):
177
189
  if q["answer"] is not None:
@@ -180,6 +192,7 @@ def _upgraded(state: dict) -> None:
180
192
  if isinstance(record.get("green_gates"), list):
181
193
  record["green_gates"] = {**driver_state.tiers(), "full": record["green_gates"]}
182
194
  _all_per_test(state)
195
+ _must_fix(run)
183
196
  if isinstance(run.get("gates"), int):
184
197
  run["gates"] = {"fast": 0, "full": run["gates"]}
185
198
  run["schema"] = driver_state.SCHEMA
@@ -0,0 +1,106 @@
1
+ """Overturn a ruling after the run: `--answer <question id>=<other option>` on a question the driver or the arbiter
2
+ answered with no operator. The overturn takes effect as an answer to that question would, from where the run is: an
3
+ accepted finding gets a fix batch, a left-out ticket runs again, an end-of-run stop shipped as draft runs again. The
4
+ work it adds lands on top of the PR branch, so the push needs no force. It never undoes work, so an overturn that
5
+ would is refused, as is one that cannot take effect. No agent ships a `finding-must-fix` finding, so the only ruling of
6
+ one to overturn is the driver's `retry`, whose work ran: an overturn never ships it but by the operator's own answer."""
7
+ from __future__ import annotations
8
+
9
+ import driver_final
10
+ import driver_pr
11
+ from driver_decisions import FINAL, FINDINGS, OPERATOR, ruled_by
12
+
13
+ EDITS = ("edit", "edit-spec") # they keep a stop BLOCKED; an overturn lets the run go on
14
+
15
+
16
+ def split(pairs: list[tuple[str, str]], document: dict) -> tuple[list[tuple[str, str]], list[tuple[str, str]]]:
17
+ """(the `--answer` pairs of an open question of `document`, the overturns: every other pair)."""
18
+ open_ids = {q["id"] for q in document["questions"]}
19
+ return [pair for pair in pairs if pair[0] in open_ids], [pair for pair in pairs if pair[0] not in open_ids]
20
+
21
+
22
+ def refusals(pairs: list[tuple[str, str]], state: dict) -> list[str]:
23
+ """The usage error of each overturn in `pairs` that state.json `state` refuses."""
24
+ asked = {q["id"]: q for q in state["run"]["questions"]}
25
+ return [f"--answer {question}={option}: {why}" for question, option in pairs
26
+ if (why := _refusal(asked.get(question), question, option, state))]
27
+
28
+
29
+ def _refusal(q: dict | None, question: str, option: str, state: dict) -> str:
30
+ """Why the overturn of `question` to `option` is refused; "" when it takes effect."""
31
+ if q is None:
32
+ return f"there is no question {question}"
33
+ return next((why for check in _CHECKS if (why := check(q, option, state))), "")
34
+
35
+
36
+ def _operators(q: dict, option: str, state: dict) -> str:
37
+ if ruled_by(q) == OPERATOR:
38
+ return f"you answered {q['id']}: only a ruling of the driver or the arbiter is overturned"
39
+ return ""
40
+
41
+
42
+ def _offered(q: dict, option: str, state: dict) -> str:
43
+ offered = [o["id"] for o in q["options"]]
44
+ if option not in offered:
45
+ return f"{q['id']} offers {', '.join(offered)}"
46
+ return f"{q['id']} is answered {option} already" if option == q["answer"] else ""
47
+
48
+
49
+ def _ran(q: dict, option: str, state: dict) -> str:
50
+ """A `retry` or a `correct-test` started work that is on the branch now."""
51
+ if q["answer"] in ("retry", "correct-test"):
52
+ return f"the {q['answer']} of the {q['by']} ran: its work is on the branch, and an overturn undoes no work"
53
+ return ""
54
+
55
+
56
+ def _edits(q: dict, option: str, state: dict) -> str:
57
+ if option in EDITS:
58
+ return (f"an overturn takes an option that lets the run go on: edit the spec or the ticket, then overturn "
59
+ f"{q['id']} to an option that runs the work again")
60
+ return ""
61
+
62
+
63
+ def _owner(ticket: str) -> str:
64
+ return "the end of run" if ticket == FINAL else f"ticket {ticket}"
65
+
66
+
67
+ def _later(q: dict, option: str, state: dict) -> str:
68
+ """Only the newest stop of a ticket, or of the end of run, is where the run is."""
69
+ later = [other["id"] for other in state["run"]["questions"]
70
+ if other["ticket"] == q["ticket"] and other["stop"] > q["stop"]]
71
+ if later:
72
+ owner = _owner(q["ticket"])
73
+ return f"a later stop of {owner} asked {later[-1]}: only the newest stop of {owner} is overturned"
74
+ return ""
75
+
76
+
77
+ def _merged(q: dict, option: str, state: dict) -> str:
78
+ if state["tickets"].get(q["ticket"], {}).get("phase") == "merged":
79
+ return f"ticket {q['ticket']} merged since: its work is on the PR branch"
80
+ return ""
81
+
82
+
83
+ def _closed(q: dict, option: str, state: dict) -> str:
84
+ """A `retry` of a finding needs it open after the last review: the fix batch is due for the open findings."""
85
+ if q["kind"] in FINDINGS and option == "retry" and not driver_final.due(state["run"]["final"], q["subject"]):
86
+ return "the last review leaves the finding closed: no fix batch is due for it"
87
+ return ""
88
+
89
+
90
+ def _written(q: dict, option: str, state: dict) -> str:
91
+ """The pr-writer runs only before the PR opens."""
92
+ if q.get("role") == "pr-writer" and state["run"]["final"]["pr"]:
93
+ return "the PR is open, so the pr-writer does not run again: edit its body on GitHub"
94
+ return ""
95
+
96
+
97
+ def _gone(q: dict, option: str, state: dict) -> str:
98
+ """The work of an overturn goes onto the open PR: a merged or closed one takes none. Last, as it asks gh."""
99
+ url = state["run"]["final"]["pr"]
100
+ shown = driver_pr.state(url) if url else "OPEN"
101
+ if shown == "OPEN":
102
+ return ""
103
+ return f"the PR {url} is {shown.lower() or 'not readable with gh'}: an overturn adds work to an open PR only"
104
+
105
+
106
+ _CHECKS = (_operators, _offered, _ran, _edits, _later, _merged, _closed, _written, _gone)
@@ -0,0 +1,277 @@
1
+ """The PR of the end of run: its body, the pr-writer's part and the facts of the driver, and its opening with `gh`,
2
+ once. Once it is open, a push only adds commits to it, and its body follows what an overturn changed: the facts each
3
+ time, the pr-writer's part when a ticket landed after the tidy (driver_final.landed_after_tidy clears `final.body`).
4
+
5
+ `run.final` of state.json (driver_final) keeps what this module needs: `body`, the tip the pr-writer's part was written
6
+ for, None until it is and again once a ticket lands after the tidy; `pr`, its URL; `draft`."""
7
+ from __future__ import annotations
8
+
9
+ import subprocess
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ import driver_agents
14
+ import driver_decisions
15
+ import driver_gate
16
+ from driver_review import title
17
+ from driver_run import FINAL, OUT, Blocked, Call, Run, during, final_values, ledger
18
+ from driver_slots import git
19
+ from driver_tickets import Ticket
20
+
21
+ BODY, WRITER = OUT / FINAL / "pr-body.md", OUT / FINAL / "pr-writer-body.md"
22
+
23
+
24
+ def pr_skill() -> Path | None:
25
+ """The SKILL.md of the pr skill, which the PR body follows."""
26
+ return driver_agents.installed("pr")
27
+
28
+
29
+ def pr_risk_skill() -> Path | None:
30
+ """The SKILL.md of the pr-risk skill, which parses and validates the merge-risk block of the PR body."""
31
+ return driver_agents.installed("pr-risk")
32
+
33
+
34
+ PR_RISK_INSTALL = "`npx skills add jesdi/general-skills --skill pr-risk`"
35
+
36
+
37
+ def _risk_errors(method: Path, body: str) -> str:
38
+ """The errors of the merge-risk block of `body` as `pr-risk` names them, or "" when the block is valid."""
39
+ checked = OUT / FINAL / "pr-risk-check.md"
40
+ checked.write_text(body)
41
+ done = subprocess.run([sys.executable, str(method.parent / "merge_risk.py"), "validate", str(checked)],
42
+ capture_output=True, text=True)
43
+ return (done.stdout + done.stderr).strip() if done.returncode else ""
44
+
45
+
46
+ def left_out(run: Run) -> list[str]:
47
+ """The tickets left out of the run (driver_decisions.left_out), which the end of run ships without."""
48
+ return sorted(driver_decisions.left_out(run.state.read()["run"]["questions"], run.tickets))
49
+
50
+
51
+ def _name(run: Run) -> str:
52
+ """The title of the PR: the first heading of the spec, else the PR branch."""
53
+ spec = Path(run.args.spec)
54
+ lines = spec.read_text(errors="replace").splitlines() if spec.is_file() else []
55
+ return next((line[2:].strip() for line in lines if line.startswith("# ")), run.pr)
56
+
57
+
58
+ def _coverage(final: dict, tip: str) -> dict[str, str]:
59
+ """The review coverage of the pushed tip `tip` in the PR body: the tips and the commits after the reviewed tip
60
+ that no review covered; the full review, which may include gate repairs made after tidy; the scoped review of the
61
+ remaining range. A draft shipped before any review was settled has neither review."""
62
+ reviewed = final["reviewed"]
63
+ full_tip = next(iter(final["lenses"].values()), {"tip": final["tidied"]})["tip"]
64
+ fields = {"tips": f"Branch tip and reviewed tip: {tip}", "full_review": f"{final['onto']}..{full_tip}",
65
+ "scoped": f"{full_tip}..{reviewed}" if full_tip != reviewed else "not needed"}
66
+ if not reviewed:
67
+ fields.update(full_review="not run", scoped="not run")
68
+ if tip != reviewed:
69
+ since = f"{reviewed or final['onto']}..{tip}"
70
+ unreviewed = git(".", "log", "--reverse", "--format=%h %s", since).stdout.strip().splitlines()
71
+ fields["tips"] = f"Branch tip: {tip}; reviewed tip: {reviewed or 'none'}; not reviewed: {'; '.join(unreviewed)}"
72
+ return fields
73
+
74
+
75
+ def _ticket_map(final: dict, titles: dict[str, str], left: list[str]) -> str:
76
+ """The ticket-to-commit map, then the tickets `left` out of the run."""
77
+ out = "; ".join(f"{number} {titles[number]}" for number in left)
78
+ return ("\n".join(f"- {number}: {commit[:7]} {titles[number]}" for number, commit in final["commits"].items())
79
+ + f"\n\nLeft out of the run, so not in this PR: {out}." * bool(left))
80
+
81
+
82
+ def _facts(run: Run, final: dict, tickets: list[Ticket], tip: str) -> str:
83
+ """The end of the PR body for the pushed tip `tip`: the ticket-to-commit map, the fix commits, the rulings and the
84
+ review coverage."""
85
+ titles = {ticket.number: ticket.title for ticket in tickets}
86
+ fixes = git(".", "log", "--reverse", "--format=- %h %s", f"{final['tidied']}..{tip}").stdout.strip()
87
+ rulings = driver_decisions.rulings(run.state.read()["run"]["questions"])
88
+ return driver_agents.render("pr-body", {
89
+ "map": _ticket_map(final, titles, left_out(run)),
90
+ "fixes": fixes or "None.", "rulings": "\n".join(f"- {ruling}" for ruling in rulings) or "None.",
91
+ **_coverage(final, tip),
92
+ "providers": _review_providers(run.state.read()["run"]["agents"])})
93
+
94
+
95
+ # The roles that review code, with their line in the PR body, and the roles that write it.
96
+ _REVIEWS = {"reviewer": "Ticket reviews", "final-correctness": "Correctness lens", "final-reviewer": "Scoped review"}
97
+ _AUTHORS = ("implementer", "fixer", "conflict")
98
+
99
+
100
+ def _review_providers(agents: list[dict]) -> str:
101
+ """One line per reviewing role that ran: the entries it ran on, and whether one of them shares a provider with an
102
+ entry that wrote code. It reads the agents that ran, so a preflight fallback of an earlier invocation that a later
103
+ one undid is not claimed."""
104
+ wrote = {driver_agents.split(entry)[0] for entry in _entries(agents, _AUTHORS)}
105
+ lines = []
106
+ for role, label in _REVIEWS.items():
107
+ if used := _entries(agents, (role,)):
108
+ same = any(driver_agents.split(entry)[0] in wrote for entry in used)
109
+ lines.append(f"- {label} ran on: {', '.join(used)}" + (", on a provider that also wrote code" * same))
110
+ return "\n".join(lines)
111
+
112
+
113
+ def _entries(agents: list[dict], roles: tuple[str, ...]) -> list[str]:
114
+ """The entries that the agents of `roles` ran on."""
115
+ return sorted({agent["entry"] for agent in agents if agent["role"] in roles})
116
+
117
+
118
+ def _run_pr_writer(run: Run, tip: str, risk: Path, values: dict) -> str:
119
+ """Run the pr-writer, and once more with the errors of its merge-risk block. Returns the body it wrote."""
120
+ for round_ in range(2):
121
+ with during("the PR body"):
122
+ report = run.read_only(FINAL, ".", run.pr, tip,
123
+ lambda: run.agent(Call("pr-writer", FINAL, ".", values, fix_round=round_)))
124
+ if not (errors := _risk_errors(risk, report["body"])):
125
+ return report["body"]
126
+ values["risk_errors"] = (f"Your previous body has an invalid merge-risk block. Fix it with the pr-risk "
127
+ f"skill; its errors:\n{errors}\n")
128
+ raise Blocked(f"the merge-risk block of the PR body is invalid after a second run of the pr-writer: {errors}")
129
+
130
+
131
+ def _body_skills() -> tuple[Path, Path]:
132
+ """The `pr` skill the body follows and the `pr-risk` skill its merge-risk block follows; Blocked when one is
133
+ missing."""
134
+ method, risk = pr_skill(), pr_risk_skill()
135
+ if not method:
136
+ raise Blocked("the pr skill is missing: the PR body follows it; install it with "
137
+ "`npx skills add mattpocock/skills --skill pr`")
138
+ if not risk:
139
+ raise Blocked(f"the pr-risk skill is missing: the PR body carries its merge-risk block; install it with "
140
+ f"{PR_RISK_INSTALL}")
141
+ return method, risk
142
+
143
+
144
+ def _writer_body(run: Run, final: dict, tickets: list[Ticket], tip: str) -> str:
145
+ """What the pr-writer wrote for the pushed tip `tip` with the method of the pr skill, its merge-risk block
146
+ validated. A body written for that tip is kept when its merge-risk block still validates, so a PR that failed to
147
+ open costs no second agent; once the PR is open, a body written for any tip is kept, until a ticket lands after
148
+ the tidy and its work is in no word of it."""
149
+ if kept := _kept(final, tip):
150
+ return kept
151
+ method, risk = _body_skills()
152
+ values = {**final_values(run), "start_sha": tip, "range": f"{final['onto']}..{tip}",
153
+ "gate": str(driver_gate.record_path(OUT / FINAL, driver_gate.FULL, tip)), "pr_skill": str(method),
154
+ "pr_risk_skill": str(risk), "risk_errors": "", "facts": _facts(run, final, tickets, tip)}
155
+ WRITER.write_text(_run_pr_writer(run, tip, risk, values).strip() + "\n")
156
+ run.state.update(lambda state: state["run"]["final"].update(body=tip))
157
+ return WRITER.read_text()
158
+
159
+
160
+ def _kept(final: dict, tip: str) -> str:
161
+ """The body the pr-writer wrote that `_writer_body` keeps, when its merge-risk block still validates; "" else."""
162
+ risk = pr_risk_skill()
163
+ if not (_written(final, tip) and WRITER.is_file() and risk):
164
+ return ""
165
+ body = WRITER.read_text()
166
+ return "" if _risk_errors(risk, body) else body
167
+
168
+
169
+ def _written(final: dict, tip: str) -> bool:
170
+ """The pr-writer's body is for `tip`, or, once the PR is open, for any tip since no ticket landed after the tidy."""
171
+ return final["body"] == tip or bool(final["pr"] and final["body"])
172
+
173
+
174
+ def _gh(argv: list[str], what: str) -> str:
175
+ """Run `gh` and return the URL it prints last."""
176
+ made = subprocess.run(["gh", *argv], capture_output=True, text=True, stdin=subprocess.DEVNULL)
177
+ if made.returncode:
178
+ raise Blocked(f"gh {what} failed: {(made.stderr or made.stdout).strip()}")
179
+ return (made.stdout.split() or [""])[-1]
180
+
181
+
182
+ def _draft(final: dict, questions: list[dict], left: list[str]) -> str:
183
+ """Why the PR opens as draft; "" for a PR ready for review: the end-of-run stops that a `ship-draft` ruling ships
184
+ with, the tickets `left` out, and the findings still open that the draft or an agent's ruling ships."""
185
+ reasons = []
186
+ if final["ship"]:
187
+ reasons.append(f"the end of run stopped: {'; '.join(stop['subject'] for stop in final['ship']['stops'])}")
188
+ if left:
189
+ reasons.append(f"tickets are left out of the run: {', '.join(left)}")
190
+ if shipped := _shipped_open(final, questions):
191
+ reasons.append(f"a finding ships open: {'; '.join(shipped)}")
192
+ return "; ".join(reasons)
193
+
194
+
195
+ def _shipped_open(final: dict, questions: list[dict]) -> list[str]:
196
+ """The titles of the findings still open that make a draft: all of them under a `ship-draft` ruling, else those an
197
+ agent's ruling shipped; the operator's own `accept` or `follow-up` keeps the PR ready."""
198
+ ship = final["ship"]
199
+ return [title(one) for one in final["open"] if ship or driver_decisions.agent_shipped(questions, one)]
200
+
201
+
202
+ def _file_follow_ups(run: Run) -> None:
203
+ """File each finding ruled `follow-up` as an issue, once: the PR body then links it. The issue carries a marker
204
+ of the run and the question, so a run that stopped after `gh` filed it and before state.json kept its URL finds it
205
+ again instead of filing it twice."""
206
+ state = run.state.read()["run"]
207
+ for q in driver_decisions.follow_ups(state["questions"]):
208
+ marker = f"implement-spec follow-up {state['revision']}/{q['id']}"
209
+ body = (f"A finding the final review of {run.pr} left open, shipped with its PR by this ruling:\n\n"
210
+ f"{q['ruling']}\n\nEvidence: {q['evidence'][0]}\n\n{marker}\n")
211
+ url = (_gh(["issue", "list", "--state", "all", "--search", f'"{marker}" in:body', "--json", "url", "--jq",
212
+ ".[].url"], "issue list")
213
+ or _gh(["issue", "create", "--title", q["subject"], "--body", body], "issue create"))
214
+
215
+ def record(state: dict, ruled: str = q["id"], issue: str = url) -> None:
216
+ next(one for one in state["run"]["questions"] if one["id"] == ruled)["issue"] = issue
217
+
218
+ run.state.update(record)
219
+ ledger(f"End of run: the follow-up {q['subject']} is filed as {url}.")
220
+
221
+
222
+ def _body(run: Run, final: dict, tickets: list[Ticket], tip: str) -> str:
223
+ """The PR body for the pushed tip `tip`: the pr-writer's part, then the facts of the run; only the facts when the
224
+ pr-writer is an end-of-run stop that a `ship-draft` ruling ships. The follow-up issues are filed once the
225
+ pr-writer's part is valid, so a run that cannot open its PR files none, and the facts link them."""
226
+ stops = final["ship"]["stops"] if final["ship"] else []
227
+ writer = "" if any(stop["role"] == "pr-writer" for stop in stops) else _writer_body(run, final, tickets, tip)
228
+ _file_follow_ups(run)
229
+ return "\n\n".join(filter(None, [writer.strip(), _facts(run, final, tickets, tip)]))
230
+
231
+
232
+ def _open(run: Run, final: dict, tickets: list[Ticket], tip: str) -> str:
233
+ """Open the PR of the pushed tip `tip`, ready for review or as draft, and return its URL."""
234
+ BODY.write_text(_body(run, final, tickets, tip))
235
+ draft = _draft(final, run.state.read()["run"]["questions"], left_out(run))
236
+ url = _gh(["pr", "create", "--base", final["base"], "--head", run.pr, "--title", _name(run), "--body-file",
237
+ str(BODY), *["--draft"] * bool(draft)], "pr create")
238
+ run.state.update(lambda state: state["run"]["final"].update(pr=url, draft=bool(draft)))
239
+ ledger(f"The PR of {run.pr} into {final['base']} is open{f' as a draft: {draft}' * bool(draft)}: {url}.")
240
+ return url
241
+
242
+
243
+ def _refresh(run: Run, final: dict, tickets: list[Ticket], tip: str) -> None:
244
+ """Write the body of the open PR again once what it says changed: an overturn's work, its ruling, its follow-up
245
+ issue, a ticket that landed after the tidy. The draft state stays. BODY is the body GitHub has: the new one
246
+ replaces it only once `gh pr edit` took it, so a failed edit is tried again by the next run."""
247
+ text = _body(run, final, tickets, tip)
248
+ if BODY.is_file() and BODY.read_text() == text:
249
+ return
250
+ require_open(final)
251
+ pending = BODY.with_name("pr-body.pending.md")
252
+ pending.write_text(text)
253
+ _gh(["pr", "edit", final["pr"], "--body-file", str(pending)], "pr edit")
254
+ pending.replace(BODY)
255
+ ledger(f"The body of the PR {final['pr']} is written again with the facts of the run at {tip[:7]}.")
256
+
257
+
258
+ def pr(run: Run, final: dict, tickets: list[Ticket], tip: str) -> str:
259
+ """The URL of the PR of the pushed tip `tip`: open it, once; once it is open, its body follows the run."""
260
+ if not final["pr"]:
261
+ return _open(run, final, tickets, tip)
262
+ _refresh(run, final, tickets, tip)
263
+ return final["pr"]
264
+
265
+
266
+ def require_open(final: dict) -> None:
267
+ """Once the PR is open, a push or a body goes out only while it is open: a run of an overturn that stopped may
268
+ resume after the PR was merged or closed."""
269
+ if final["pr"] and (shown := state(final["pr"])) != "OPEN":
270
+ raise Blocked(f"the PR {final['pr']} is {shown.lower() or 'not readable with gh'}: nothing goes out to it")
271
+
272
+
273
+ def state(url: str) -> str:
274
+ """The state of the PR at `url` as gh gives it: OPEN, MERGED or CLOSED; "" when gh cannot tell."""
275
+ shown = subprocess.run(["gh", "pr", "view", url, "--json", "state", "--jq", ".state"], capture_output=True,
276
+ text=True, stdin=subprocess.DEVNULL)
277
+ return shown.stdout.strip() if shown.returncode == 0 else ""
@@ -203,16 +203,36 @@ def _dispute_errors(role: str, report: dict, context: dict) -> list[str]:
203
203
 
204
204
  def _ruling_errors(report: dict, context: dict) -> list[str]:
205
205
  """An arbitration rules on each disputed test."""
206
- given = {ruling["test"] for ruling in report.get("rulings", [])}
206
+ given = {ruling.get("test") for ruling in report.get("rulings", [])}
207
207
  return [f"rulings: no ruling on {test}: give one ruling per disputed test, its id as the list gives it"
208
208
  for test in context.get("disputed", []) if test not in given]
209
209
 
210
210
 
211
+ def _arbiter_errors(report: dict, context: dict) -> list[str]:
212
+ """The arbiter rules on each open question, with an option that the question offers it."""
213
+ given = {ruling.get("question"): ruling.get("ruling") for ruling in report.get("rulings", [])}
214
+ errors = []
215
+ for question, options in context.get("questions", {}).items():
216
+ if question not in given:
217
+ errors.append(f"rulings: no ruling on {question}: give one ruling per open question, its id as the list gives it")
218
+ elif given[question] not in options:
219
+ errors.append(f"rulings: {question} takes {' or '.join(options)}, not {given[question]}")
220
+ return errors
221
+
222
+
211
223
  def locked_files(listed: list[str]) -> list[str]:
212
224
  """The files of a `locked` list: a test node id `<file>::<test>` names its file. In order, each file once."""
213
225
  return list(dict.fromkeys(entry.partition("::")[0] for entry in listed))
214
226
 
215
227
 
228
+ def _own_fields(report: dict, rules: dict) -> dict:
229
+ """The schema types only the role's own fields: any other field of the report is dropped."""
230
+ report = {name: value for name, value in report.items() if name in rules["properties"]}
231
+ if "locked" in report:
232
+ report["locked"] = locked_files(report["locked"])
233
+ return report
234
+
235
+
216
236
  def validate(role: str, path: str, context: dict) -> list[str]:
217
237
  try:
218
238
  report = json.loads(Path(path).read_text())
@@ -222,12 +242,10 @@ def validate(role: str, path: str, context: dict) -> list[str]:
222
242
  found = sorted(jsonschema.Draft202012Validator(rules).iter_errors(report), key=lambda e: str(list(e.path)))
223
243
  if found:
224
244
  return [f"{'.'.join(map(str, e.path)) or 'report'}: {e.message}" for e in found]
225
- # The schema types only the role's own fields: any other field of the report is dropped.
226
- report = {name: value for name, value in report.items() if name in rules["properties"]}
227
- if "locked" in report:
228
- report["locked"] = locked_files(report["locked"])
245
+ report = _own_fields(report, rules)
229
246
  return (_rejected_errors(report, context) + _space_errors(report) + _commit_errors(report, context)
230
247
  + _owner_errors(report, context) + _must_fix_errors(report, context)
231
248
  + _unchanged_errors(role, report, context) + _correction_errors(report, context)
232
249
  + driver_locked.errors(role, report, context) + _red_errors(report, context)
233
- + _dispute_errors(role, report, context) + _ruling_errors(report, context))
250
+ + _dispute_errors(role, report, context) + _ruling_errors(report, context)
251
+ + _arbiter_errors(report, context))
@@ -14,6 +14,11 @@ from driver_slots import git, head, on_branch
14
14
  OPEN = ("critical", "important") # the severities that start a fix round
15
15
 
16
16
 
17
+ def title(finding: dict) -> str:
18
+ """A finding as a line names it: `<title> (<file>:<line>)`."""
19
+ return f"{finding['title']} ({finding['file']}:{finding['line']})"
20
+
21
+
17
22
  def _corrected(finding: dict, locked: list[str], protected: list[str]) -> bool:
18
23
  """Whether a correction, not a fixer, takes the finding: see `route`."""
19
24
  return finding["kind"] == "fixture" or finding["severity"] in OPEN and (
@@ -30,14 +35,15 @@ def route(findings: list[dict], locked: list[str], protected: list[str]) -> tupl
30
35
 
31
36
 
32
37
  def restore(slot: str, branch: str, tip: str) -> None:
33
- """Put the slot back on `branch` at `tip` with a clean tree. Only for a read-only role: its edits, commits and
34
- untracked files go. Ignored files stay."""
35
- git(slot, "checkout", "-q", "-f", "-B", branch, tip)
38
+ """Put the slot back on `branch` ("": a detached HEAD) at `tip` with a clean tree. Only for a read-only role: its
39
+ edits, commits and untracked files go. Ignored files stay."""
40
+ git(slot, "checkout", "-q", "-f", *(["-B", branch] if branch else ["--detach"]), tip)
36
41
  git(slot, "clean", "-q", "-fd")
37
42
 
38
43
 
39
44
  def disturbed(slot: str, branch: str, tip: str) -> str:
40
- """"" when the slot is still on `branch` at `tip` with a clean tree, else what the read-only agents left."""
45
+ """"" when the slot is still on `branch` ("": a detached HEAD) at `tip` with a clean tree, else what the read-only
46
+ agents left."""
41
47
  if on_branch(slot) != branch or head(slot) != tip:
42
48
  return f"the slot is no longer on {branch} at {tip[:7]}"
43
49
  left = [line[3:] for line in git(slot, "status", "--porcelain").stdout.splitlines()]
@@ -26,6 +26,7 @@ import driver_state
26
26
  from driver_decisions import FINAL, Resume
27
27
  from driver_names import Names
28
28
  from driver_slots import git
29
+ from driver_tickets import Ticket
29
30
 
30
31
  OUT = Path(".agent/implement")
31
32
  FINAL_RESUME = Resume("pending") # a `retry` of the end of run: it goes on from where its state is
@@ -95,6 +96,9 @@ class Call:
95
96
  # The role that a `retry` of its `ticket-blocked` question runs again from the start commit, when the agent runs
96
97
  # for that role (an arbitration, a correction): its own work is not kept.
97
98
  retry: str = ""
99
+ # An agent whose rerun stops or is rejected too asks `ticket-blocked`; one that does not only raises Blocked: the
100
+ # arbiter, whose failure leaves its questions to the operator.
101
+ asks: bool = True
98
102
  # A BLOCKED report that disputes a locked test is accepted, not a stop: `driver_dispute.agent` settles it.
99
103
  may_dispute: bool = False
100
104
  # Reads the locked-file check of its report when the agent ends, given the validation context, to which it may add
@@ -104,8 +108,7 @@ class Call:
104
108
 
105
109
  class Ask(NamedTuple):
106
110
  """The questions a ticket thread, or the end of run, wants the operator to answer when it blocks."""
107
- kind: str
108
- subjects: list[str] # one question per subject
111
+ asked: list[tuple[str, str, str | None]] # one question per (kind, subject), with the role that stopped
109
112
  report: str # the evidence
110
113
  resume: Resume # the record gets its tip and round with the stop, and all of it with a `retry` or a `keep-test`
111
114
 
@@ -117,6 +120,7 @@ class Run:
117
120
  state: driver_state.State
118
121
  pr: str # the PR branch
119
122
  kept: dict[str, int] # ticket number -> the slot that holds its uncommitted work from an earlier run
123
+ tickets: list[Ticket] = field(default_factory=list) # every ticket of the run
120
124
  merging: threading.Lock = field(default_factory=threading.Lock) # held for one landing: merges are serial
121
125
  asks: dict[str, Ask] = field(default_factory=dict) # ticket number -> its pending stop
122
126
  halted: list[str] = field(default_factory=list) # why the run starts no other agent; [] while it goes on
@@ -128,12 +132,15 @@ class Run:
128
132
  def tip(self) -> str:
129
133
  return git(".", "rev-parse", f"refs/heads/{self.pr}").stdout.strip()
130
134
 
131
- def ask(self, number: str, kind: str, subjects: list[str], report: str, resume: Resume) -> None:
132
- """The questions of `number`'s stop. The end of run adds those of each lens that stopped to one stop."""
135
+ def ask(self, number: str, asked: list[tuple[str, str]], report: str, resume: Resume,
136
+ role: str | None = None) -> None:
137
+ """The questions of `number`'s stop, one per (kind, subject) of `asked`; `role`: the agent that stopped, for a
138
+ `ticket-blocked` one. The end of run adds those of each lens that stopped, or of each finding, to one stop."""
139
+ asked = [(kind, subject, role) for kind, subject in asked]
133
140
  with _ASKS:
134
141
  if earlier := self.asks.get(number):
135
- subjects = earlier.subjects + subjects
136
- self.asks[number] = Ask(kind, subjects, report, resume)
142
+ asked = earlier.asked + asked
143
+ self.asks[number] = Ask(asked, report, resume)
137
144
 
138
145
  def block(self, number: str, line: int) -> None:
139
146
  """Make the record of `number` BLOCKED and add the questions it asked for, in one write of state.json. The
@@ -145,12 +152,12 @@ class Run:
145
152
  if ask:
146
153
  held.update(ask.resume.checkpoint())
147
154
  evidence = [ask.report, f"{OUT / 'ledger.md'}:{line}"]
148
- driver_decisions.stop(state["run"], ask.kind, number, ask.subjects, evidence, ask.resume)
155
+ driver_decisions.stop(state["run"], number, ask.asked, evidence, ask.resume)
149
156
  held["phase"] = "blocked"
150
157
 
151
158
  self.state.update(change)
152
- if ask and ask.subjects:
153
- ledger(f"{_owner(number)}: {driver_decisions.decides(ask.kind, len(ask.subjects))} in "
159
+ if ask and ask.asked:
160
+ ledger(f"{_owner(number)}: {driver_decisions.decides(ask.asked)} in "
154
161
  f"{OUT / 'decisions.json'}.")
155
162
 
156
163
  def agent(self, call: Call) -> dict:
@@ -233,13 +240,22 @@ def _restore_if_changed(number: str, slot: str, branch: str, tip: str, config: d
233
240
  driver_review.restore(slot, branch, tip)
234
241
  left = "; ".join(filter(None, (changed, moved)))
235
242
  if left:
236
- where = ("slot 1" if number == FINAL else "the slot") + f" to {tip[:7]}"
237
- restored = " and ".join(filter(None, ("the shared git config" if changed else "", where if moved else "")))
238
- again = f" and runs {'the final review' if number == FINAL else 'the review'} again" if runs_again else ""
239
- ledger(f"{_owner(number)}: a read-only role broke its rule: {left}; the driver restored {restored}{again}.")
243
+ ledger(f"{_owner(number)}: a read-only role broke its rule: {left}; the driver restored "
244
+ f"{_restored(number, slot, tip, changed, moved)}{_again(number, runs_again)}.")
240
245
  return left
241
246
 
242
247
 
248
+ def _restored(number: str, slot: str, tip: str, changed: str, moved: str) -> str:
249
+ """What the driver restored after a read-only role: the shared git config, the slot, or both."""
250
+ where = ("slot 1" if slot == "." and number == FINAL else "the slot") + f" to {tip[:7]}"
251
+ return " and ".join(filter(None, ("the shared git config" if changed else "", where if moved else "")))
252
+
253
+
254
+ def _again(number: str, runs_again: bool) -> str:
255
+ """The tail of the restore ledger line when the review runs again after it."""
256
+ return f" and runs {'the final review' if number == FINAL else 'the review'} again" if runs_again else ""
257
+
258
+
243
259
  def _reset_if_moved(slot: str, branch: str, tip: str) -> str:
244
260
  """After an agent: "" when the slot is on `branch` and still holds `tip`; else reset it and say what was wrong."""
245
261
  head = driver_slots.on_branch(slot)
@@ -316,12 +332,13 @@ def _ask_blocked(run: Run, call: Call, report: Path, error: str) -> None:
316
332
  its state is."""
317
333
  tip = call.values["start_sha"] if call.retry else driver_slots.head(call.slot)
318
334
  resume = FINAL_RESUME if call.number == FINAL else retry_point(call.retry or call.role, tip, call.fix_round)
319
- run.ask(call.number, "ticket-blocked", [f"the {call.role}: {error}"], str(report), resume)
335
+ run.ask(call.number, [("ticket-blocked", f"the {call.role}: {error}")], str(report), resume, call.role)
320
336
 
321
337
 
322
338
  def _give_up(run: Run, call: Call, report: Path, error: str) -> NoReturn:
323
339
  """Every exhausted rerun asks before another attempt, including timeouts and moved branches."""
324
- _ask_blocked(run, call, report, error)
340
+ if call.asks:
341
+ _ask_blocked(run, call, report, error)
325
342
  raise Blocked(error)
326
343
 
327
344
 
@@ -402,3 +419,9 @@ def _attempts(run: Run, call: Call) -> dict:
402
419
  minutes *= 2
403
420
  entry = entry if same else rerun_on
404
421
  _give_up(run, call, report, error)
422
+
423
+
424
+ def final_values(run: Run) -> dict[str, str]:
425
+ """The pointers every prompt of the end of run gets. Its agents work in slot 1, the PR worktree."""
426
+ return {"spec": run.args.spec, "tickets": run.args.tickets, "pr_branch": run.pr, "branch": run.pr,
427
+ "gate": run.args.fast_gate}