@jesdi/skills 0.0.98 → 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.
@@ -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:
@@ -22,13 +22,13 @@ def _rows(run: dict, tickets: dict) -> list[tuple[str, object]]:
22
22
 
23
23
  def _stops(run: dict) -> list[tuple[str, object]]:
24
24
  """The stops that waited for the operator, and a row for those the driver ruled on itself, when it did."""
25
- ruled = sum(driver_decisions.ruled(run.get("questions", [])).values())
25
+ ruled = len({(q["ticket"], q["stop"]) for q in driver_decisions.without_operator(run.get("questions", []))})
26
26
  return [("human stops", run["stops"] - ruled), *([("stops the driver ruled on", ruled)] if ruled else [])]
27
27
 
28
28
 
29
29
  def _decisions(run: dict) -> list[str]:
30
30
  """What the driver decided without the operator, for the end of the summary."""
31
- rulings = [q["ruling"] for q in driver_decisions.by_driver(run.get("questions", []))]
31
+ rulings = driver_decisions.rulings(driver_decisions.without_operator(run.get("questions", [])))
32
32
  return ["", "Driver decisions, taken without the operator:", *(f"- {ruling}" for ruling in rulings)] * bool(rulings)
33
33
 
34
34
 
@@ -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.
@@ -29,6 +29,8 @@ def pr_skill(tmp_path_factory):
29
29
  patch.setenv("XDG_CONFIG_HOME", str(tmp_path_factory.mktemp("config-home")))
30
30
  # The tests of a stop see its question: the driver answers none itself unless a test passes --retries.
31
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")
32
34
  yield home / "skills/pr/SKILL.md"
33
35
 
34
36
 
@@ -0,0 +1,151 @@
1
+ """The arbiter: when the driver's own retries are spent on a finding the scoped review leaves open, one read-only
2
+ agent on another provider than the implementer rules `accept` or `follow-up` on it, and the PR opens: draft when a
3
+ critical finding stays open, ready otherwise. `--ask` (IMPLEMENT_SPEC_ASK=1, which conftest pins) asks the operator
4
+ instead.
5
+
6
+ In process, on the rig of test_scoped."""
7
+ import json
8
+
9
+ from test_final import GH, final, fixer, fn, risk_body, writer
10
+ from test_fixloop import inside # noqa: F401 (the autouse fixture puts the rig's CLIs on PATH)
11
+ from test_lenses import ASTRA, MODELS, OPUS, rig_of
12
+ from test_review import RISKY, fix, finding, review
13
+ from test_scoped import ATOMIC
14
+ from test_tidy import Inside
15
+ from test_stops import UNATTENDED, decisions, stage
16
+ from test_tidy import tools # noqa: F401 (tools is an autouse fixture)
17
+ from test_walk import plan
18
+
19
+ Q = "final-finding-open-1"
20
+ LEAK = finding("token logged in clear", severity="critical", file="auth.py", line=7)
21
+ ARBITER = {**MODELS, "arbiter": [OPUS, ASTRA]} # the implementer is on anthropic, so the arbiter runs on ASTRA
22
+
23
+
24
+ def ruled(*rulings):
25
+ """An arbiter step: one (question, ruling) pair per open question."""
26
+ return {"report": {"status": "DONE", "files": [], "concerns": [], "rulings": [
27
+ {"question": question, "ruling": ruling, "reason": f"why {ruling}", "cost": f"cost of {ruling}"}
28
+ for question, ruling in rulings]}}
29
+
30
+
31
+ def open_after_batch(tmp_path, found=ATOMIC, arbiter=(), *extra, **more):
32
+ """The scoped review after the one fix batch leaves `found` open, with no retry left for the driver."""
33
+ rig = rig_of(tmp_path, models=ARBITER)
34
+ steps = plan(**{"final/final-spec": [final(found)], "final/final-reviewer": [final(found)],
35
+ "final/fixer": [fixer(fn("02"), "fix it")], "final/arbiter": list(arbiter), **more})
36
+ return rig.run(steps, "--no-ask", "--retries", "0", *UNATTENDED, *extra), steps
37
+
38
+
39
+ def gh(rig, verb):
40
+ rows = [json.loads(line) for line in rig.gh_log.read_text().splitlines()] if rig.gh_log.exists() else []
41
+ return [row for row in rows if row["argv"][:2] == verb]
42
+
43
+
44
+ def test_the_arbiter_accepts_an_important_finding_and_the_pr_opens_ready_with_its_ruling(tmp_path):
45
+ rig, _ = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "accept"))])
46
+ assert rig.code == 0 and rig.pushes(), rig.out
47
+ (arbiter,) = rig.final_calls("arbiter")
48
+ assert Q in arbiter["prompt"] and "findings-1.json" in arbiter["prompt"]
49
+ assert rig.led(f"End of run: arbiter ran on {ASTRA}")
50
+ (pr,) = rig.prs()
51
+ assert "--draft" not in pr["argv"]
52
+ line = ("Ruling: final ships with the finding open (accept): ledger write not atomic (ledger.py). Ruled by "
53
+ "the arbiter, not the operator: why accept. Cost if wrong: cost of accept.")
54
+ assert f"- {line}" in pr["body"] and line in (rig.repo / ".agent/implement/summary.md").read_text()
55
+ assert stage(rig) == {"stage": "implement", "status": "done", "draft": False, "decisions": 1}
56
+ assert len(rig.final_calls("fixer")) == 1, "an accepted finding gets no fix batch"
57
+
58
+
59
+ def test_an_accepted_critical_finding_opens_the_pr_as_draft(tmp_path):
60
+ rig, _ = open_after_batch(tmp_path, LEAK, [ruled(("final-finding-open-1", "accept"))])
61
+ assert rig.code == 0, rig.out
62
+ (pr,) = rig.prs()
63
+ assert "--draft" in pr["argv"] and stage(rig)["draft"] is True
64
+ assert rig.led("The PR of feat/csv into main is open as a draft: a critical or must-fix finding is open")
65
+
66
+
67
+ def test_a_follow_up_is_filed_as_an_issue_before_the_pr_and_the_pr_body_links_it(tmp_path):
68
+ rig, steps = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "follow-up"))])
69
+ assert rig.code == 0, rig.out
70
+ (issue,) = gh(rig, ["issue", "create"])
71
+ assert issue["argv"][2:4] == ["--title", "ledger write not atomic (ledger.py)"]
72
+ assert "feat/csv" in issue["body"] and "why follow-up" in issue["body"]
73
+ (pr,) = rig.prs()
74
+ assert "(follow-up): ledger write not atomic (ledger.py)." in pr["body"]
75
+ assert "Follow-up issue: https://github.example/issues/1" in pr["body"]
76
+ assert "Follow-up issue: https://github.example/issues/1" in (rig.repo / ".agent/implement/summary.md").read_text()
77
+ rig.run(steps, "--no-ask", *UNATTENDED)
78
+ assert len(gh(rig, ["issue", "create"])) == 1, "a rerun files no second issue"
79
+
80
+
81
+ def test_a_local_run_without_push_files_no_issue(tmp_path):
82
+ rig = rig_of(tmp_path)
83
+ rig.run(plan(**{"final/final-spec": [final(ATOMIC)], "final/final-reviewer": [final(ATOMIC)],
84
+ "final/fixer": [fixer(fn("02"), "fix it")], "final/arbiter": [ruled((Q, "follow-up"))]}),
85
+ "--no-ask")
86
+ assert rig.code == 0 and not gh(rig, ["issue", "create"]) and not rig.prs(), rig.out
87
+ assert "(follow-up)" in (rig.repo / ".agent/implement/summary.md").read_text()
88
+
89
+
90
+ def test_the_arbiter_rules_only_after_the_retries_of_the_driver(tmp_path):
91
+ rig = rig_of(tmp_path)
92
+ steps = plan(**{"final/final-spec": [final(ATOMIC)], "final/final-reviewer": [final(ATOMIC), final(ATOMIC)],
93
+ "final/fixer": [fixer(fn("02"), "fix it"), fixer(fn("02"), "fix it again")],
94
+ "final/arbiter": [ruled(("final-finding-open-2", "accept"))]})
95
+ rig.run(steps, "--no-ask", "--retries", "1", *UNATTENDED)
96
+ assert rig.code == 0, rig.out
97
+ assert len(rig.final_calls("fixer")) == 2 and len(rig.final_calls("arbiter")) == 1
98
+ assert rig.led("Ruling: final runs again (retry)") and rig.led("Ruled by the arbiter")
99
+
100
+
101
+ def test_an_arbiter_that_fails_twice_leaves_the_question_to_the_operator(tmp_path):
102
+ rig, _ = open_after_batch(tmp_path, ATOMIC, [{"report": {"status": "DONE"}}] * 2)
103
+ assert rig.code == 2 and not rig.pushes(), rig.out
104
+ assert len(rig.final_calls("arbiter")) == 2
105
+ (question,) = decisions(rig)["questions"]
106
+ assert question["id"] == Q
107
+ assert rig.led("End of run: the arbiter could not rule, so the operator decides")
108
+
109
+
110
+ def test_an_arbiter_report_that_skips_a_question_is_rejected(tmp_path):
111
+ rig, _ = open_after_batch(tmp_path, ATOMIC, [ruled(), ruled((Q, "accept"))])
112
+ assert rig.code == 0, rig.out
113
+ first, _ = rig.led("End of run: arbiter ran on")
114
+ assert f"no ruling on {Q}" in first
115
+
116
+
117
+ def test_an_issue_filed_before_its_url_was_kept_is_found_again_and_not_filed_twice(tmp_path):
118
+ rig = rig_of(tmp_path, models=ARBITER)
119
+ gh_path = tmp_path / "bin/gh"
120
+ gh_path.write_text(GH.replace('log = Path', 'if sys.argv[1:3] == ["pr", "create"]:\n sys.exit("gh down")\nlog = Path', 1))
121
+ steps = plan(**{"final/final-spec": [final(ATOMIC)], "final/final-reviewer": [final(ATOMIC)],
122
+ "final/fixer": [fixer(fn("02"), "fix it")], "final/arbiter": [ruled((Q, "follow-up"))]})
123
+ rig.run(steps, "--no-ask", "--retries", "0", *UNATTENDED)
124
+ assert rig.code != 0 and len(gh(rig, ["issue", "create"])) == 1 and not rig.prs(), rig.out
125
+ state = rig.state() # as a run that stopped before state.json kept the URL leaves it
126
+ del next(q for q in state["run"]["questions"] if q["id"] == Q)["issue"]
127
+ (rig.repo / ".agent/implement/state.json").write_text(json.dumps(state))
128
+ gh_path.write_text(GH)
129
+ rig.run(steps, "--no-ask", *UNATTENDED)
130
+ assert rig.code == 0 and len(gh(rig, ["issue", "create"])) == 1, rig.out
131
+ (pr,) = rig.prs()
132
+ assert "Follow-up issue: https://github.example/issues/1" in pr["body"]
133
+
134
+
135
+ def test_a_pr_body_that_stays_invalid_files_no_follow_up_issue(tmp_path):
136
+ invalid = writer(risk_body("styles"))
137
+ rig, _ = open_after_batch(tmp_path, ATOMIC, [ruled((Q, "follow-up"))], **{"final/pr-writer": [invalid, invalid]})
138
+ assert rig.code != 0 and not gh(rig, ["issue", "create"]) and not rig.prs(), rig.out
139
+
140
+
141
+ def test_an_accepted_must_fix_finding_opens_the_pr_as_draft(tmp_path):
142
+ rig = Inside(tmp_path, RISKY, {**ARBITER})
143
+ escaping = {**finding("quote escaping", file="csv.py", line=30), "basis": "regression"}
144
+ batch = fixer(fn("02"), "escape quotes", ticket_of="02")
145
+ batch["report"]["addressed_must_fix"] = ["quote escaping (csv.py:30)"]
146
+ rig.run(plan(**{"02/reviewer": [review("02", [escaping])] * 3, "02/fixer": [fix("02", 1), fix("02", 2)],
147
+ "final/final-reviewer": [final()], "final/fixer": [batch],
148
+ "final/arbiter": [ruled((Q, "accept"))]}), "--no-ask", "--retries", "0", *UNATTENDED)
149
+ assert rig.code == 0, rig.out
150
+ (pr,) = rig.prs()
151
+ assert "--draft" in pr["argv"] and rig.led("open as a draft: a critical or must-fix finding is open: quote escaping")
@@ -13,7 +13,7 @@ RUN = SKILL / "run.sh"
13
13
  GIT = ["git", "-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false"]
14
14
  TOOLS = ("sh", "uname", "dirname", "readlink", "git", "env", "mktemp", "curl", "tar", "gzip", "mv", "rm", "mkdir",
15
15
  "sha256sum", "shasum", "cat", "chmod", "ln", "date", "basename")
16
- ROLES = ("test-writer", "implementer", "reviewer", "fixer", "final-reviewer", "conflict", "pr-writer")
16
+ ROLES = ("test-writer", "implementer", "reviewer", "fixer", "final-reviewer", "conflict", "pr-writer", "arbiter")
17
17
  NONE = "None (can start immediately)"
18
18
 
19
19
 
@@ -182,7 +182,7 @@ def test_unattended_writes_the_stage_file_and_prints_no_question(tmp_path, capsy
182
182
  assert stage(rig) == {"stage": "implement", "status": "awaiting-review", "artifact": PAGE, "open_questions": 1}
183
183
  write_answers(rig, {Q1: "retry"})
184
184
  rig.run(steps(blocked(), blocked(), impl("01")), *UNATTENDED)
185
- assert rig.code == 0 and stage(rig) == {"stage": "implement", "status": "done"}, "no stage file of the earlier run stays"
185
+ assert rig.code == 0 and stage(rig) == {"stage": "implement", "status": "done", "draft": False, "decisions": 0}, "no stage file of the earlier run stays"
186
186
  assert "feat: 01 rows" in rig.pr_subjects()
187
187
 
188
188
 
@@ -454,8 +454,8 @@ def test_the_rerun_of_fix_round_2_wraps_to_the_first_implementer_entry(tmp_path)
454
454
  assert entries(rig, "01", "fixer") == [SONNET, OPUS_5_5, SONNET]
455
455
 
456
456
 
457
- def test_only_two_kinds_exist():
458
- assert list(driver_decisions.KINDS) == ["spec-ambiguous", "ticket-blocked"]
457
+ def test_only_three_kinds_exist():
458
+ assert list(driver_decisions.KINDS) == ["spec-ambiguous", "ticket-blocked", "finding-open"]
459
459
 
460
460
 
461
461
  # ---------------------------------------------------------------- a test-writer report; a question of a merged ticket
@@ -1032,7 +1032,7 @@ def test_the_preflight_asks_each_entry_once_and_drops_each_entry_whose_cli_fails
1032
1032
  models["implementer"][1] = "openai/gpt-6.1-sol@medium"
1033
1033
  models["final-reviewer"] = ["openai/gpt-astra@medium", "claude-opus-5-5@medium"]
1034
1034
  kept, errors, skipped = driver_agents.preflight(models)
1035
- assert errors == [] and len((bin_dir / "asked").read_text().splitlines()) == 5
1035
+ assert errors == [] and len((bin_dir / "asked").read_text().splitlines()) == 7
1036
1036
  assert kept["implementer"] == ["claude-sonnet-5-5@medium"] and kept["final-reviewer"] == ["claude-opus-5-5@medium"]
1037
1037
  assert kept["test-writer"] == ["claude-sonnet-5-5@medium"] and kept["reviewer"] == models["reviewer"]
1038
1038
  assert skipped == [