@jesdi/skills 0.0.97 → 0.0.99

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.
@@ -3,15 +3,20 @@
3
3
  A question in state.json `run.questions`; `answer` is None while it is open:
4
4
  {id, title, why, evidence, options: [{id, description}], recommended, ticket, kind, subject, stop, answer,
5
5
  resume: {phase[, tip][, round][, gate_allowance]}, the record fields a `retry` or a `keep-test` sets (`Resume`),
6
- ruling: the ruling sentence, once answered}
6
+ ruling: the ruling sentence, once answered; by: DRIVER or ARBITER when no operator answered it;
7
+ issue: the URL of the follow-up issue the driver filed for a `follow-up` answer}
7
8
  decisions.json: {run: <run.revision>, questions: [the open ones, first six fields], revision: <SHA-256 of the rest>}."""
8
9
  from __future__ import annotations
9
10
 
10
11
  import hashlib
11
12
  import json
13
+ from collections import Counter
12
14
  from typing import NamedTuple
13
15
 
14
16
  PUBLIC = ("id", "title", "why", "evidence", "options", "recommended")
17
+ DRIVER = "driver" # `by` of a question the driver answered itself
18
+ ARBITER = "arbiter" # `by` of a question the arbiter agent answered
19
+ SHIPS = ("accept", "follow-up") # the answers to `finding-open` that ship the PR with the finding open
15
20
  FINAL = "final" # the end of run asks its questions, and has its record and its files, under this name
16
21
 
17
22
 
@@ -70,12 +75,12 @@ KINDS = {
70
75
  "edit-spec": Option(
71
76
  "Keep the ticket BLOCKED, so the spec can be edited to say which reading it means.",
72
77
  "Ruling: {ticket} stays BLOCKED for an edit of the spec (edit-spec): {subject}.", False)}),
73
- # The end of run asks it too, with the ticket `final`: for an agent, or for a finding open after the scoped review.
78
+ # The end of run asks it too, with the ticket `final`: for an agent, or for the integration gate.
74
79
  "ticket-blocked": Kind(
75
- "{owner}: an agent stopped or was rejected, and its rerun too, or a final-review finding or integration gate remains red: {subject}",
80
+ "{owner}: an agent stopped or was rejected, and its rerun too, or the integration gate remains red: {subject}",
76
81
  "An agent ran two times, using the same model for a timeout or moved branch and the next entry otherwise, "
77
- "and stopped or was rejected both times; or the final review left a finding open, or the integration gate "
78
- "stayed red after its repair. {owner} is BLOCKED, each ticket that it blocks waits, and nothing is pushed.",
82
+ "and stopped or was rejected both times; or the integration gate stayed red after its repair. {owner} is "
83
+ "BLOCKED, each ticket that it blocks waits, and nothing is pushed.",
79
84
  "retry",
80
85
  {"retry": Option(
81
86
  "The role runs again on its first entry from the tip the ticket left, with one rerun (the same model "
@@ -86,6 +91,21 @@ KINDS = {
86
91
  "edit": Option(
87
92
  "Keep it BLOCKED, so the spec or the ticket can be edited before more work on it.",
88
93
  "Ruling: {ticket} stays BLOCKED for an edit of the spec or the ticket (edit): {subject}.", False)}),
94
+ # Only the end of run asks it: the subject is the finding's title.
95
+ "finding-open": Kind(
96
+ "End of run: a final-review finding is open after the scoped review: {subject}",
97
+ "The scoped review after the fix batch left this critical or important finding open. Nothing is pushed until "
98
+ "it is ruled on.",
99
+ "retry",
100
+ {"retry": Option(
101
+ "One more fix batch and scoped review.",
102
+ "Ruling: {ticket} runs again (retry): {subject}.", True),
103
+ "accept": Option(
104
+ "Push and open the PR with the finding open and listed in its rulings; a critical one opens it as draft.",
105
+ "Ruling: {ticket} ships with the finding open (accept): {subject}.", True),
106
+ "follow-up": Option(
107
+ "As `accept`, and the driver files the finding as an issue before it opens the PR.",
108
+ "Ruling: {ticket} ships with the finding open, filed as a follow-up issue (follow-up): {subject}.", True)}),
89
109
  }
90
110
 
91
111
 
@@ -136,8 +156,19 @@ def document(run: dict) -> dict:
136
156
 
137
157
 
138
158
  def rulings(questions: list[dict]) -> list[str]:
139
- """The ruling sentence of each answered question, without the note of the operator."""
140
- return [q["ruling"] for q in questions if q["answer"] is not None]
159
+ """The ruling sentence of each answered question, without the note of the operator, with its follow-up issue."""
160
+ return [q["ruling"] + (f" Follow-up issue: {q['issue']}" if q.get("issue") else "")
161
+ for q in questions if q["answer"] is not None]
162
+
163
+
164
+ def waived(questions: list[dict]) -> set[str]:
165
+ """The findings, by subject, that a `finding-open` answer ships with: no fix batch is due for them."""
166
+ return {q["subject"] for q in questions if q["kind"] == "finding-open" and q["answer"] in SHIPS}
167
+
168
+
169
+ def follow_ups(questions: list[dict]) -> list[dict]:
170
+ """The `finding-open` questions answered `follow-up` with no issue filed yet."""
171
+ return [q for q in questions if (q["kind"], q["answer"]) == ("finding-open", "follow-up") and not q.get("issue")]
141
172
 
142
173
 
143
174
  def ruling(q: dict) -> str:
@@ -162,19 +193,55 @@ def _settled(questions: list[dict], ticket: str, stop: int) -> dict:
162
193
  return {name: value for one in fields for name, value in one.items()} if all(fields) else {}
163
194
 
164
195
 
165
- def apply(questions: list[dict], answers: dict) -> tuple[list[str], dict[str, dict]]:
166
- """Answer the open questions in `answers`. Returns (a ruling per answer, ticket or FINAL -> the fields that let its
167
- record go on)."""
196
+ def ruled(questions: list[dict]) -> Counter:
197
+ """ticket (or FINAL) -> the stops of it that the driver ruled on."""
198
+ return Counter(ticket for ticket, _ in {(q["ticket"], q["stop"]) for q in questions if q.get("by") == DRIVER})
199
+
200
+
201
+ def automatic(questions: list[dict], budget: int) -> dict:
202
+ """The answers the driver gives itself: `retry` for each open question that recommends it, while the driver ruled
203
+ on fewer than `budget` stops of its ticket (or of the end of run). No other option is the driver's to take: a
204
+ kind that recommends one still asks the operator."""
205
+ spent = ruled(questions)
206
+ asked = [q for q in questions if q["answer"] is None and q["recommended"] == "retry"]
207
+ return {q["id"]: q["recommended"] for q in asked if spent[q["ticket"]] < budget}
208
+
209
+
210
+ def _answer(q: dict, answers: dict, by: str, why: str) -> str:
211
+ """Answer `q` from `answers` and return its ruling, with the note of the operator."""
212
+ q["answer"], q["by"] = answers[q["id"]], by
213
+ q["ruling"] = ruling(q) + (f" Ruled by the {by}, not the operator{why}." if by else "")
214
+ note = answers.get(f"{q['id']}.note")
215
+ return q["ruling"] + f" Note of the operator: {note}" * bool(note)
216
+
217
+
218
+ def apply(questions: list[dict], answers: dict, by: str = "", why: dict[str, str] | None = None
219
+ ) -> tuple[list[str], dict[str, dict]]:
220
+ """Answer the open questions in `answers`; `by` is DRIVER for the answers of `automatic` and ARBITER for those of
221
+ the arbiter, whose `why` gives the end of the ruling sentence per question. Returns (a ruling per answer, ticket or
222
+ FINAL -> the fields that let its record go on)."""
168
223
  rulings, stops = [], {}
169
224
  for q in questions:
170
225
  if q["answer"] is None and q["id"] in answers:
171
- q["answer"] = answers[q["id"]]
172
- q["ruling"] = ruling(q)
173
- note = answers.get(f"{q['id']}.note")
174
- rulings.append(q["ruling"] + f" Note of the operator: {note}" * bool(note))
226
+ rulings.append(_answer(q, answers, by, (why or {}).get(q["id"], "")))
175
227
  stops[q["ticket"]] = q["stop"]
228
+ return rulings, _moved(questions, stops)
229
+
230
+
231
+ def _moved(questions: list[dict], stops: dict) -> dict[str, dict]:
232
+ """ticket or FINAL -> the fields that let its record go on, for each of `stops` whose answers settle it."""
176
233
  moved = {ticket: _settled(questions, ticket, stop) for ticket, stop in stops.items()}
177
- return rulings, {ticket: fields for ticket, fields in moved.items() if fields}
234
+ return {ticket: fields for ticket, fields in moved.items() if fields}
235
+
236
+
237
+ def without_operator(questions: list[dict]) -> list[dict]:
238
+ """The questions the driver or its arbiter answered, with no operator."""
239
+ return [q for q in questions if q.get("by") in (DRIVER, ARBITER)]
240
+
241
+
242
+ def arbitrated(questions: list[dict]) -> list[dict]:
243
+ """The open questions the arbiter rules on once the driver's retries are spent."""
244
+ return [q for q in questions if q["answer"] is None and q["kind"] == "finding-open"]
178
245
 
179
246
 
180
247
  def text(open_questions: list[dict], answers: str, page: str) -> str:
@@ -1,7 +1,8 @@
1
1
  """The end of a run, when every ticket is merged and every slot is idle: tidy the PR branch into one commit per
2
2
  ticket, rebase it onto the fetched base tip, gate it, run the final review, let one fix batch land as `fix(NN)`
3
3
  commits with a scoped review, then stop before the push, or push and open the PR. A finding the scoped review leaves
4
- open asks `final-ticket-blocked-<n>`: only a `retry` runs another batch and scoped review.
4
+ open asks `final-finding-open-<n>`: a `retry` runs another batch and scoped review, an `accept` or a `follow-up` ships
5
+ the PR with it, as draft when it is critical.
5
6
 
6
7
  `run.final` of state.json is the resume contract (`driver_state._final` makes it with every key):
7
8
  skipped why the end-of-run work did not start
@@ -17,6 +18,7 @@ open asks `final-ticket-blocked-<n>`: only a `retry` runs another batch and scop
17
18
  batch the tip of the fix batch that the driver validated and named
18
19
  phase `blocked` at a stop with questions, until a `retry` answer makes it `pending` again
19
20
  green_gates, pushed, pr
21
+ draft the PR opened as draft
20
22
  """
21
23
  from __future__ import annotations
22
24
 
@@ -140,6 +142,11 @@ def _title(finding: dict) -> str:
140
142
  return f"{finding['title']} ({finding['file']}:{finding['line']})"
141
143
 
142
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']})"
148
+
149
+
143
150
  def _last(commits: dict[str, str]) -> str:
144
151
  return list(commits.values())[-1]
145
152
 
@@ -388,19 +395,29 @@ def _settle_review(run: Run, done: int, tip: str, covered: str, found: list[dict
388
395
  for finding in found:
389
396
  ledger(f"Final review round {done + 1}: {finding['severity']} finding of kind {finding['kind']} from "
390
397
  f"{finding['source']} at {finding['file']}:{finding['line']}: {finding['title']}.")
391
- to_fix = [finding for finding in found if finding["severity"] in driver_review.OPEN]
392
- run.state.update(lambda state: state["run"]["final"].update(reviewed=tip, round=done + 1, open=to_fix))
398
+ found_open = [finding for finding in found if finding["severity"] in driver_review.OPEN]
399
+ run.state.update(lambda state: state["run"]["final"].update(reviewed=tip, round=done + 1, open=found_open))
393
400
  ledger(f"Final review round {done + 1}: the range {covered} is reviewed, the reviewed tip is {tip[:7]}, and "
394
- f"{len(to_fix)} critical or important finding{'s are' if len(to_fix) != 1 else ' is'} open.")
395
- if to_fix and done:
396
- # Another batch is the operator's call: one `final-ticket-blocked` question per finding.
397
- titles = [_title(finding) for finding in to_fix]
398
- run.ask(FINAL, "ticket-blocked", [f"a finding open after the scoped review: {title}" for title in titles],
399
- str(file), FINAL_RESUME)
401
+ f"{len(found_open)} critical or important finding{'s are' if len(found_open) != 1 else ' is'} open.")
402
+ if done:
403
+ _ask_open(run, file, found_open)
404
+
405
+
406
+ 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)
400
411
  raise Blocked(f"the scoped review leaves {len(titles)} finding{'s' * (len(titles) > 1)} open: "
401
412
  + "; ".join(titles))
402
413
 
403
414
 
415
+ 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]
419
+
420
+
404
421
  def _review(run: Run, final: dict, tip: str) -> None:
405
422
  """One round of the final review on `tip`: the full review by the three lenses, or after it the scoped one, on
406
423
  the other-provider entry: another provider than the implementer's, and so than the fixer's when it shares
@@ -531,23 +548,37 @@ def _undo_rejected_batch(run: Run, tip: str) -> str:
531
548
  return ""
532
549
 
533
550
 
534
- def _fixer_call(run: Run, tickets: list[Ticket], final: dict, tip: str, gate_record: str = "") -> Call:
535
- """Build a final fixer call from review findings or the saved integration-gate failure."""
551
+ def _findings_list(run: Run, final: dict) -> str:
552
+ """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"]))
554
+
555
+
556
+ def _fixer_values(run: Run, final: dict, tip: str, gate_record: str) -> dict[str, str]:
557
+ """The prompt values of the final fixer: the review findings, and the saved gate failure for a gate repair."""
536
558
  folder = OUT / FINAL
537
559
  values = {**_prompt_values(run), "start_sha": tip, "findings": str(folder / f"findings-{final['round'] - 1}.json"),
538
560
  "locked": " ".join(driver_locked.every(run.state.read()["tickets"])),
539
561
  "must_fix_list": "\n".join(f"- {_title(finding)}" for finding in final["must_fix"]),
540
- "findings_list": "\n".join(f"- {finding['severity']}: {_title(finding)}" for finding in final["open"])}
541
- name = ""
542
- if gate_record:
543
- values.update(driver_final_gate.pointers(final, gate_record, tip))
544
- name = f"gate-fixer-{final['gate_repairs']}"
562
+ "findings_list": _findings_list(run, final)}
563
+ return {**values, **(driver_final_gate.pointers(final, gate_record, tip) if gate_record else {})}
564
+
565
+
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 []}
572
+
573
+
574
+ def _fixer_call(run: Run, tickets: list[Ticket], final: dict, tip: str, gate_record: str = "") -> Call:
575
+ """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 ""
545
578
  tidied = final["tidied"]
546
579
  return Call("fixer", FINAL, ".", values, template="final-gate-fixer" if gate_record else "final-fixer",
547
580
  fix_round=final["round"], name=name,
548
- check={"owners": [ticket.number for ticket in tickets],
549
- "must_fix": [] if gate_record else [_title(finding) for finding in final["must_fix"]],
550
- "fix": [values["gate_title"]] if gate_record else []},
581
+ check=_fixer_check(tickets, final, values, gate_record),
551
582
  locked=lambda _: driver_locked.for_end_of_run(run.state.read()["tickets"], tidied))
552
583
 
553
584
 
@@ -601,7 +632,7 @@ def _review_until_reviewed(run: Run, tickets: list[Ticket]) -> None:
601
632
  _fix_batch(run, tickets, final, tip, record)
602
633
  continue
603
634
  _review(run, final, tip)
604
- elif final["open"]: # after the full review, or after a `retry` of a finding the scoped review left open
635
+ elif _to_fix(run, final["open"]): # after the full review, or after a `retry` of a finding left open
605
636
  _fix_batch(run, tickets, final, tip)
606
637
  else:
607
638
  return
@@ -666,38 +697,89 @@ def _run_pr_writer(run: Run, tip: str, risk: Path, values: dict) -> str:
666
697
  raise Blocked(f"the merge-risk block of the PR body is invalid after a second run of the pr-writer: {errors}")
667
698
 
668
699
 
669
- def _write_body(run: Run, final: dict, tickets: list[Ticket]) -> Path:
670
- """Write the PR body: what the pr-writer wrote with the method of the pr skill, then the facts of the run. A body
671
- written for the reviewed tip is kept when its merge-risk block still validates, so a PR that failed to open costs
672
- no second agent."""
673
- body, tip = OUT / FINAL / "pr-body.md", final["reviewed"]
674
- method, risk, facts = pr_skill(), pr_risk_skill(), _facts(run, final, tickets)
675
- if final["body"] == tip and body.is_file() and risk and not _risk_errors(risk, body.read_text()):
676
- return body
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()
677
704
  if not method:
678
705
  raise Blocked("the pr skill is missing: the PR body follows it; install it with "
679
706
  "`npx skills add mattpocock/skills --skill pr`")
680
707
  if not risk:
681
708
  raise Blocked(f"the pr-risk skill is missing: the PR body carries its merge-risk block; install it with "
682
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)
683
723
  values = {**_prompt_values(run), "start_sha": tip, "range": f"{final['onto']}..{tip}",
684
724
  "gate": str(driver_gate.record_path(OUT / FINAL, driver_gate.FULL, tip)), "pr_skill": str(method),
685
725
  "pr_risk_skill": str(risk), "risk_errors": "", "facts": facts}
686
- body.write_text(f"{_run_pr_writer(run, tip, risk, values).strip()}\n\n{facts}")
726
+ body.write_text(_run_pr_writer(run, tip, risk, values).strip() + "\n")
687
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]
737
+
738
+
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 ""
744
+
745
+
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"))
758
+
759
+ def record(state: dict, ruled: str = q["id"], issue: str = url) -> None:
760
+ next(one for one in state["run"]["questions"] if one["id"] == ruled)["issue"] = issue
761
+
762
+ run.state.update(record)
763
+ ledger(f"End of run: the follow-up {q['subject']} is filed as {url}.")
764
+
765
+
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)}")
688
773
  return body
689
774
 
690
775
 
691
776
  def _open_pr(run: Run, final: dict, tickets: list[Ticket]) -> str:
692
- """Open the PR, ready for review, and return its URL."""
693
- body = _write_body(run, final, tickets)
694
- made = subprocess.run(["gh", "pr", "create", "--base", final["base"], "--head", run.pr, "--title", _name(run),
695
- "--body-file", str(body)], capture_output=True, text=True, stdin=subprocess.DEVNULL)
696
- if made.returncode:
697
- raise Blocked(f"gh pr create failed: {(made.stderr or made.stdout).strip()}")
698
- url = (made.stdout.split() or [""])[-1]
699
- run.state.update(lambda state: state["run"]["final"].update(pr=url))
700
- ledger(f"The PR of {run.pr} into {final['base']} is open: {url}.")
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}.")
701
783
  return url
702
784
 
703
785
 
@@ -203,16 +203,31 @@ 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."""
213
+ given = {ruling.get("question") for ruling in report.get("rulings", [])}
214
+ return [f"rulings: no ruling on {question}: give one ruling per open question, its id as the list gives it"
215
+ for question in context.get("questions", []) if question not in given]
216
+
217
+
211
218
  def locked_files(listed: list[str]) -> list[str]:
212
219
  """The files of a `locked` list: a test node id `<file>::<test>` names its file. In order, each file once."""
213
220
  return list(dict.fromkeys(entry.partition("::")[0] for entry in listed))
214
221
 
215
222
 
223
+ def _own_fields(report: dict, rules: dict) -> dict:
224
+ """The schema types only the role's own fields: any other field of the report is dropped."""
225
+ report = {name: value for name, value in report.items() if name in rules["properties"]}
226
+ if "locked" in report:
227
+ report["locked"] = locked_files(report["locked"])
228
+ return report
229
+
230
+
216
231
  def validate(role: str, path: str, context: dict) -> list[str]:
217
232
  try:
218
233
  report = json.loads(Path(path).read_text())
@@ -222,12 +237,10 @@ def validate(role: str, path: str, context: dict) -> list[str]:
222
237
  found = sorted(jsonschema.Draft202012Validator(rules).iter_errors(report), key=lambda e: str(list(e.path)))
223
238
  if found:
224
239
  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"])
240
+ report = _own_fields(report, rules)
229
241
  return (_rejected_errors(report, context) + _space_errors(report) + _commit_errors(report, context)
230
242
  + _owner_errors(report, context) + _must_fix_errors(report, context)
231
243
  + _unchanged_errors(role, report, context) + _correction_errors(report, context)
232
244
  + driver_locked.errors(role, report, context) + _red_errors(report, context)
233
- + _dispute_errors(role, report, context) + _ruling_errors(report, context))
245
+ + _dispute_errors(role, report, context) + _ruling_errors(report, context)
246
+ + _arbiter_errors(report, context))
@@ -95,6 +95,9 @@ class Call:
95
95
  # The role that a `retry` of its `ticket-blocked` question runs again from the start commit, when the agent runs
96
96
  # for that role (an arbitration, a correction): its own work is not kept.
97
97
  retry: str = ""
98
+ # An agent whose rerun stops or is rejected too asks `ticket-blocked`; one that does not only raises Blocked: the
99
+ # arbiter, whose failure leaves its questions to the operator.
100
+ asks: bool = True
98
101
  # A BLOCKED report that disputes a locked test is accepted, not a stop: `driver_dispute.agent` settles it.
99
102
  may_dispute: bool = False
100
103
  # Reads the locked-file check of its report when the agent ends, given the validation context, to which it may add
@@ -321,7 +324,8 @@ def _ask_blocked(run: Run, call: Call, report: Path, error: str) -> None:
321
324
 
322
325
  def _give_up(run: Run, call: Call, report: Path, error: str) -> NoReturn:
323
326
  """Every exhausted rerun asks before another attempt, including timeouts and moved branches."""
324
- _ask_blocked(run, call, report, error)
327
+ if call.asks:
328
+ _ask_blocked(run, call, report, error)
325
329
  raise Blocked(error)
326
330
 
327
331
 
@@ -43,7 +43,8 @@ def _final() -> dict:
43
43
  """The end-of-run record before it starts. Every key is here, so a reader uses [] and a wrong name fails."""
44
44
  return {"skipped": "", "phase": "pending", "recovery": None, "tidied": None, "onto": None, "base": None,
45
45
  "commits": {}, "reviewed": None, "round": 0, "open": [], "must_fix": [], "lenses": {}, "batch": None,
46
- "gate_repairs": 0, "gate_allowance": 1, "gate_failure": None, "green_gates": tiers(), "pushed": None, "body": None, "pr": None}
46
+ "gate_repairs": 0, "gate_allowance": 1, "gate_failure": None, "green_gates": tiers(), "pushed": None, "body": None, "pr": None,
47
+ "draft": False}
47
48
 
48
49
 
49
50
  class State:
@@ -3,6 +3,8 @@ from __future__ import annotations
3
3
 
4
4
  from collections import Counter, defaultdict
5
5
 
6
+ import driver_decisions
7
+
6
8
 
7
9
  def _rows(run: dict, tickets: dict) -> list[tuple[str, object]]:
8
10
  agents = Counter((agent["role"], agent["entry"]) for agent in run["agents"])
@@ -14,10 +16,22 @@ def _rows(run: dict, tickets: dict) -> list[tuple[str, object]]:
14
16
  *((f"agents, {role} on {entry}", number) for (role, entry), number in agents.items()),
15
17
  *((f"wall time, {role}", f"{total:.1f} s") for role, total in seconds.items()),
16
18
  ("fix rounds per ticket", rounds),
17
- ("human stops", run["stops"]),
19
+ *_stops(run),
18
20
  *_cost(run["agents"])]
19
21
 
20
22
 
23
+ def _stops(run: dict) -> list[tuple[str, object]]:
24
+ """The stops that waited for the operator, and a row for those the driver ruled on itself, when it did."""
25
+ ruled = len({(q["ticket"], q["stop"]) for q in driver_decisions.without_operator(run.get("questions", []))})
26
+ return [("human stops", run["stops"] - ruled), *([("stops the driver ruled on", ruled)] if ruled else [])]
27
+
28
+
29
+ def _decisions(run: dict) -> list[str]:
30
+ """What the driver decided without the operator, for the end of the summary."""
31
+ rulings = driver_decisions.rulings(driver_decisions.without_operator(run.get("questions", [])))
32
+ return ["", "Driver decisions, taken without the operator:", *(f"- {ruling}" for ruling in rulings)] * bool(rulings)
33
+
34
+
21
35
  def _cost(agents: list[dict]) -> list[tuple[str, object]]:
22
36
  """The cost row, and a row that counts the agents with no price (cost None), which the cost leaves out."""
23
37
  unpriced = sum(agent["cost"] is None for agent in agents)
@@ -44,4 +58,4 @@ def render(state: dict) -> str:
44
58
  lines += [f"Ticket {number} is not merged: its phase is {entry['phase']}."
45
59
  for number, entry in tickets.items() if entry["phase"] != "merged"] + _end(run)
46
60
  table = ["| Measure | Value |", "|---|---|"] + [f"| {name} | {value} |" for name, value in _rows(run, tickets)]
47
- return "\n".join(lines + ["", *table]) + "\n"
61
+ return "\n".join(lines + ["", *table] + _decisions(run)) + "\n"
@@ -5,5 +5,6 @@
5
5
  "fixer": ["claude-opus-5-5@medium"],
6
6
  "final-reviewer": ["openai/gpt-6-astra@medium", "claude-opus-5-5@medium"],
7
7
  "conflict": ["claude-opus-5-5@medium"],
8
- "pr-writer": ["claude-opus-5-5@medium"]
8
+ "pr-writer": ["claude-opus-5-5@medium"],
9
+ "arbiter": ["openai/gpt-6-astra@xhigh", "claude-opus-5-5@xhigh"]
9
10
  }
@@ -0,0 +1,34 @@
1
+ # Arbiter
2
+
3
+ Spec: {spec}
4
+ Tickets: {tickets}
5
+ PR branch: {pr_branch}, at commit {start_sha}
6
+ Ledger of the run, one sentence per event: {ledger}
7
+
8
+ The run is out of retries. Each question below is a finding that the scoped review left open after the last fix batch. No operator is asked: your ruling decides whether the PR ships with it.
9
+ {questions}
10
+ Read each finding in its evidence file, the code it points at, and what the ledger says about the fix batches that tried it. Then rule on each question.
11
+ `accept`: the PR ships with the finding open and listed in its rulings. Take it when the finding is wrong, already handled, or too small to hold the PR.
12
+ `follow-up`: the PR ships, and the driver files the finding as an issue. Take it when the finding is real and worth a change of its own.
13
+ A critical finding, or a must-fix one carried from a ticket that merged at its fix cap, opens the PR as draft whichever you rule; say so in the cost when it matters.
14
+ In `question`, copy the question id as the list gives it. In `reason`, say why, so that the operator can check your ruling from it alone. In `cost`, say what goes wrong if your ruling is wrong.
15
+ Do not commit, do not change a file and do not dispatch subagents. Leave the tree as you found it.
16
+
17
+ Write one JSON report at {report}. When your sandbox is read-only, give the JSON as your whole final message and the driver saves it there. The report matches this schema:
18
+
19
+ ```json
20
+ {
21
+ "type": "object",
22
+ "required": ["status", "files", "concerns", "rulings"],
23
+ "properties": {
24
+ "status": {"enum": ["DONE", "DONE_WITH_CONCERNS", "NEEDS_CONTEXT", "BLOCKED"]},
25
+ "files": {"type": "array", "items": {"type": "string"}},
26
+ "concerns": {"type": "array", "items": {"type": "string"}},
27
+ "rulings": {"type": "array", "items": {"type": "object", "required": ["question", "ruling", "reason", "cost"], "properties": {"question": {"type": "string", "minLength": 1}, "ruling": {"enum": ["accept", "follow-up"]}, "reason": {"type": "string", "minLength": 1}, "cost": {"type": "string", "minLength": 1}}}}
28
+ }
29
+ }
30
+ ```
31
+
32
+ Run git as plain `git` in this worktree, and leave the git config as it is: all worktrees read one shared config, and one key written there, such as a `core.worktree`, breaks git in each of them. So never set GIT_DIR or GIT_WORK_TREE, and never write with `git config`.
33
+ Stop only processes you started and their child processes, by PID (for example the PID of a job you put in the background, or its process group). Never kill a process you did not start, and never use `pkill`, `killall` or a `kill` by name or pattern: other slots and sessions share the machine. If a process you did not start blocks you, report it in your concerns and do not kill it.
34
+ Never run `git stash`, never reset, and never check out another branch: worktrees share one stash and one ref store.
@@ -27,6 +27,10 @@ def pr_skill(tmp_path_factory):
27
27
  patch.setenv("CLAUDE_CONFIG_DIR", str(home))
28
28
  # No test reads the operator's own provider config (driver_agents.load_models).
29
29
  patch.setenv("XDG_CONFIG_HOME", str(tmp_path_factory.mktemp("config-home")))
30
+ # The tests of a stop see its question: the driver answers none itself unless a test passes --retries.
31
+ patch.setenv("IMPLEMENT_SPEC_RETRIES", "0")
32
+ # and no arbiter rules in their place, unless a test passes --no-ask.
33
+ patch.setenv("IMPLEMENT_SPEC_ASK", "1")
30
34
  yield home / "skills/pr/SKILL.md"
31
35
 
32
36