@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.
- package/package.json +1 -1
- package/skills/implement-spec/ARCHITECTURE.md +10 -5
- package/skills/implement-spec/README.md +44 -17
- package/skills/implement-spec/SKILL.md +4 -2
- package/skills/implement-spec/driver.py +166 -40
- package/skills/implement-spec/driver_agents.py +26 -8
- package/skills/implement-spec/driver_arbiter.py +89 -0
- package/skills/implement-spec/driver_decisions.py +212 -39
- package/skills/implement-spec/driver_dispute.py +1 -1
- package/skills/implement-spec/driver_final.py +255 -186
- package/skills/implement-spec/driver_final_gate.py +1 -1
- package/skills/implement-spec/driver_legacy.py +15 -2
- package/skills/implement-spec/driver_overturn.py +106 -0
- package/skills/implement-spec/driver_pr.py +277 -0
- package/skills/implement-spec/driver_report.py +24 -6
- package/skills/implement-spec/driver_review.py +10 -4
- package/skills/implement-spec/driver_run.py +38 -15
- package/skills/implement-spec/driver_slots.py +33 -0
- package/skills/implement-spec/driver_state.py +29 -15
- package/skills/implement-spec/driver_summary.py +11 -4
- package/skills/implement-spec/models.json +2 -1
- package/skills/implement-spec/prompts/arbiter.md +38 -0
- package/skills/implement-spec/prompts/conflict.md +1 -1
- package/skills/implement-spec/prompts/pr-body.md +1 -1
- package/skills/implement-spec/recovery.md +4 -4
- package/skills/implement-spec/tests/conftest.py +3 -0
- package/skills/implement-spec/tests/test_arbiter.py +208 -0
- package/skills/implement-spec/tests/test_arbitration.py +1 -1
- package/skills/implement-spec/tests/test_cli.py +1 -1
- package/skills/implement-spec/tests/test_decisions.py +31 -7
- package/skills/implement-spec/tests/test_driver.py +10 -2
- package/skills/implement-spec/tests/test_final.py +34 -9
- package/skills/implement-spec/tests/test_fixloop.py +2 -2
- package/skills/implement-spec/tests/test_leave_out.py +203 -0
- package/skills/implement-spec/tests/test_legacy.py +25 -0
- package/skills/implement-spec/tests/test_lenses.py +6 -4
- package/skills/implement-spec/tests/test_overturn.py +362 -0
- package/skills/implement-spec/tests/test_report.py +1 -1
- package/skills/implement-spec/tests/test_scoped.py +18 -15
- package/skills/implement-spec/tests/test_ship_draft.py +203 -0
- package/skills/implement-spec/tests/test_slots.py +29 -0
- package/skills/implement-spec/tests/test_state.py +4 -2
- package/skills/implement-spec/tests/test_stops.py +21 -5
- package/skills/implement-spec/tests/test_tidy.py +7 -5
- package/skills-manifest.json +3 -3
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"""implement-spec driver: validate the ticket set and the environment, then walk the ticket graph.
|
|
3
3
|
|
|
4
4
|
sh run.sh --gate COMMAND --fast-gate COMMAND --spec FILE [--tickets DIR] [--models FILE] [--parallel N] [--prepare COMMAND]
|
|
5
|
-
[--timeout ROLE=MINUTES] [--answer QUESTION=OPTION] [--retries N] [--unattended [--stage-json FILE]] [--push]
|
|
5
|
+
[--timeout ROLE=MINUTES] [--answer QUESTION=OPTION] [--retries N] [--ask] [--unattended [--stage-json FILE]] [--push]
|
|
6
6
|
[--base BRANCH] [--dry-run]
|
|
7
7
|
|
|
8
8
|
Run it in the PR worktree. Exit 0 = every ticket merged (and pushed, when unattended), 1 = a ticket or the end of
|
|
@@ -15,6 +15,7 @@ import argparse
|
|
|
15
15
|
import json
|
|
16
16
|
import os
|
|
17
17
|
import re
|
|
18
|
+
import subprocess
|
|
18
19
|
import sys
|
|
19
20
|
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
|
|
20
21
|
from contextlib import ExitStack
|
|
@@ -23,6 +24,7 @@ from pathlib import Path
|
|
|
23
24
|
|
|
24
25
|
import driver_agents
|
|
25
26
|
import driver_answers
|
|
27
|
+
import driver_arbiter
|
|
26
28
|
import driver_decisions
|
|
27
29
|
import driver_dispute
|
|
28
30
|
import driver_final
|
|
@@ -32,6 +34,7 @@ import driver_graph
|
|
|
32
34
|
import driver_legacy
|
|
33
35
|
import driver_locked
|
|
34
36
|
import driver_merge
|
|
37
|
+
import driver_overturn
|
|
35
38
|
import driver_review_page
|
|
36
39
|
import driver_run
|
|
37
40
|
import driver_slots
|
|
@@ -151,10 +154,18 @@ class _Landing:
|
|
|
151
154
|
commit: str # what the PR branch moves to: `pr_tip` (merged already), `ticket_tip` (fast-forward) or a merge
|
|
152
155
|
|
|
153
156
|
|
|
154
|
-
|
|
155
|
-
|
|
157
|
+
MERGE_OPEN = "The merge of the PR branch into the ticket branch is open in this worktree"
|
|
158
|
+
REPLAY_OPEN = ("The ticket's own work, replayed onto the PR branch after the end of run rewrote it, is open in this "
|
|
159
|
+
"worktree as a cherry-pick")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _resolve_conflict(ticket: Ticket, slot: str, run: Run, tip: str, files: list[str], opened: str = MERGE_OPEN
|
|
163
|
+
) -> str:
|
|
164
|
+
"""Run the conflict agent on the merge (or the replay, driver_final.replay) that is open in the slot. Returns the
|
|
165
|
+
new ticket tip."""
|
|
156
166
|
number = ticket.number
|
|
157
|
-
values = {**_prompt_values(ticket, slot, run), "start_sha": tip, "pr_sha": run.tip(), "files": " ".join(files)
|
|
167
|
+
values = {**_prompt_values(ticket, slot, run), "start_sha": tip, "pr_sha": run.tip(), "files": " ".join(files),
|
|
168
|
+
"opened": opened}
|
|
158
169
|
try:
|
|
159
170
|
with during("the conflict agent"):
|
|
160
171
|
run.agent(Call("conflict", number, slot, values))
|
|
@@ -195,7 +206,7 @@ def _refuse_breach(number: str, run: Run, landing: _Landing) -> None:
|
|
|
195
206
|
|
|
196
207
|
|
|
197
208
|
def _block_landing(number: str, run: Run, tip: str, error: str) -> None:
|
|
198
|
-
run.ask(number, "ticket-blocked",
|
|
209
|
+
run.ask(number, [("ticket-blocked", f"the landing: {error}")], str(STATE),
|
|
199
210
|
retry_point("implementer", tip, 0))
|
|
200
211
|
raise Blocked(error)
|
|
201
212
|
|
|
@@ -212,16 +223,26 @@ def _landing_slot(number: str, slot: str, run: Run, tip: str) -> None:
|
|
|
212
223
|
_block_landing(number, run, tip, f"the landing slot has uncommitted work: {status.stdout.strip()}")
|
|
213
224
|
|
|
214
225
|
|
|
226
|
+
def _restart_replay(slot: str, branch: str, tip: str) -> subprocess.CompletedProcess:
|
|
227
|
+
"""A run stopped in a replay (driver_final.replay) before its tip was recorded: the ticket branch goes back to the
|
|
228
|
+
tip the replay started from, and a cherry-pick left open is dropped, so the replay runs again."""
|
|
229
|
+
git(slot, "cherry-pick", "--quit")
|
|
230
|
+
return git(slot, "checkout", "-q", "-f", "-B", branch, tip)
|
|
231
|
+
|
|
232
|
+
|
|
215
233
|
def _checked_landing(ticket: Ticket, slot: str, run: Run, may_resolve: bool) -> _Landing:
|
|
216
234
|
"""The reviewed commit to land, with locked-file invariants checked. Call it under the merge lock."""
|
|
217
235
|
number = ticket.number
|
|
218
236
|
# An earlier try left the slot on its merge commit.
|
|
219
237
|
branch = run.names.ticket(number)
|
|
220
|
-
|
|
221
|
-
|
|
238
|
+
entry = run.state.ticket(number, phase="merge")
|
|
239
|
+
tip = entry["tip"]
|
|
240
|
+
checkout = _restart_replay(slot, branch, tip) if entry["replayed"] == tip else git(slot, "checkout", "-q", branch)
|
|
222
241
|
if checkout.returncode:
|
|
223
242
|
_block_landing(number, run, tip, f"the landing checkout failed: {checkout.stderr.strip()}")
|
|
224
243
|
_landing_slot(number, slot, run, tip)
|
|
244
|
+
tip = driver_final.replay(ticket, slot, run, tip, lambda start, files: _resolve_conflict(
|
|
245
|
+
ticket, slot, run, start, files, REPLAY_OPEN))
|
|
225
246
|
landing = _merge_commit(ticket, slot, run, tip, may_resolve)
|
|
226
247
|
_landing_slot(number, slot, run, landing.ticket_tip)
|
|
227
248
|
_refuse_breach(number, run, landing)
|
|
@@ -249,6 +270,7 @@ def _record_landing(state: dict, number: str, landing: _Landing) -> None:
|
|
|
249
270
|
state["tickets"][number]["phase"] = "merged"
|
|
250
271
|
earlier = [landed for landed in state["run"]["landed"] if landed[0] != number]
|
|
251
272
|
state["run"]["landed"] = earlier + [[number, pr_tip]]
|
|
273
|
+
driver_final.landed_after_tidy(state, number, pr_tip)
|
|
252
274
|
|
|
253
275
|
|
|
254
276
|
def _merge(ticket: Ticket, slot: str, run: Run) -> None:
|
|
@@ -439,12 +461,32 @@ def _publish_questions(run: dict) -> str:
|
|
|
439
461
|
return ""
|
|
440
462
|
|
|
441
463
|
|
|
442
|
-
def _settle(state: driver_state.State, questions: list[dict], answers: dict, ignored: list[str], by: str = ""
|
|
443
|
-
|
|
444
|
-
|
|
464
|
+
def _settle(state: driver_state.State, questions: list[dict], answers: dict, ignored: list[str], by: str = "",
|
|
465
|
+
why: dict[str, str] | None = None) -> None:
|
|
466
|
+
"""Turn each answer into a ruling and let its ticket go on. A `ship-draft` answer, the operator's or the driver's,
|
|
467
|
+
records once in `run.final.ship` what the end of run ships."""
|
|
468
|
+
rulings, moved = driver_decisions.apply(questions, answers, by, why)
|
|
469
|
+
if ship := driver_final.ship_record(state.read()["run"], [q for q in questions if q["id"] in answers]):
|
|
470
|
+
moved.setdefault(FINAL, {})["ship"] = ship
|
|
471
|
+
_record(state, questions, rulings, moved, ignored)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _overturn(questions: list[dict], answers: dict) -> tuple[list[str], dict[str, dict]]:
|
|
475
|
+
"""Overturn the rulings `answers` names (driver_decisions.overturn). A `ship-draft` ruling overturned clears
|
|
476
|
+
`run.final.ship`, so the end of run goes on from its stop."""
|
|
477
|
+
shipped = {q["id"] for q in questions if q["answer"] == "ship-draft"}
|
|
478
|
+
rulings, moved = driver_decisions.overturn(questions, answers)
|
|
479
|
+
if shipped & answers.keys():
|
|
480
|
+
moved.setdefault(FINAL, {})["ship"] = None
|
|
481
|
+
return rulings, moved
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _record(state: driver_state.State, questions: list[dict], rulings: list[str], moved: dict[str, dict],
|
|
485
|
+
ignored: list[str] | tuple[str, ...] = ()) -> None:
|
|
486
|
+
"""Write the ruling sentences to the ledger, then the questions and the records they let go on to state.json."""
|
|
445
487
|
# The ledger comes first: a run that stops between the two writes gives a ruling twice, and never an answer
|
|
446
488
|
# that no ledger line names.
|
|
447
|
-
for sentence in ignored
|
|
489
|
+
for sentence in [*ignored, *rulings]:
|
|
448
490
|
ledger(sentence)
|
|
449
491
|
|
|
450
492
|
def change(new: dict) -> None:
|
|
@@ -456,50 +498,113 @@ def _settle(state: driver_state.State, questions: list[dict], answers: dict, ign
|
|
|
456
498
|
|
|
457
499
|
|
|
458
500
|
def _apply_answers(state: driver_state.State, args) -> list[str]:
|
|
459
|
-
"""Turn each answer that counts into a ruling and let its ticket go on; [] or the
|
|
501
|
+
"""Turn each answer that counts, and each overturn of a ruling, into a ruling and let its ticket go on; [] or the
|
|
502
|
+
errors that stop the run."""
|
|
460
503
|
_drop_merged(state)
|
|
461
|
-
|
|
504
|
+
whole = state.read()
|
|
505
|
+
run = whole["run"]
|
|
462
506
|
questions, document = run["questions"], driver_decisions.document(run)
|
|
463
|
-
|
|
507
|
+
answers, overturns = driver_overturn.split(args.answer, document)
|
|
508
|
+
if errors := driver_overturn.refusals(overturns, whole) or driver_answers.given(answers, document):
|
|
509
|
+
return errors
|
|
510
|
+
given, ignored = driver_answers.read(document)
|
|
511
|
+
if errors := driver_final.refused_ship(run, {**given, **dict(overturns)}):
|
|
464
512
|
return errors
|
|
465
|
-
|
|
513
|
+
_record(state, questions, *_overturn(questions, dict(overturns)))
|
|
514
|
+
_settle(state, questions, given, ignored)
|
|
466
515
|
error = _publish_questions(run)
|
|
467
516
|
return [error] if error else []
|
|
468
517
|
|
|
469
518
|
|
|
470
|
-
def _rule(
|
|
471
|
-
"""The driver answers each open question that recommends
|
|
472
|
-
|
|
473
|
-
questions
|
|
474
|
-
|
|
519
|
+
def _rule(run: Run, tickets: list[Ticket]) -> bool:
|
|
520
|
+
"""The driver answers each open question that recommends `retry` with it, at most `--retries` stops per ticket and
|
|
521
|
+
for the end of run, and `--must-fix-retries` more stops with a `finding-must-fix` question; then, unless `--ask`,
|
|
522
|
+
the arbiter rules on the open `finding-open` questions and a ticket's `spec-ambiguous` ones, and else the driver
|
|
523
|
+
rules on an end-of-run stop by its draft policy (driver_final.draft_ruling) and answers a ticket's stop
|
|
524
|
+
`leave-out`. True: one of them ruled, so the run goes on with no operator."""
|
|
525
|
+
questions = run.state.read()["run"]["questions"]
|
|
526
|
+
answers = driver_decisions.automatic(questions, run.args.retries, run.args.must_fix_retries)
|
|
527
|
+
_settle_rulings(run, questions, answers, driver_decisions.DRIVER, {})
|
|
528
|
+
if run.args.ask:
|
|
529
|
+
return bool(answers)
|
|
530
|
+
arbitrated, why = _arbitrate(run)
|
|
531
|
+
_settle_rulings(run, run.state.read()["run"]["questions"], arbitrated, driver_decisions.ARBITER, why)
|
|
532
|
+
if answers or arbitrated:
|
|
533
|
+
return True
|
|
534
|
+
drafted = driver_final.draft_ruling(run)
|
|
535
|
+
_settle_rulings(run, run.state.read()["run"]["questions"], drafted, driver_decisions.DRIVER, {})
|
|
536
|
+
return bool(drafted or _leave_out(run, tickets))
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _leave_out(run: Run, tickets: list[Ticket]) -> dict[str, str]:
|
|
540
|
+
"""Answer the open questions of a ticket `leave-out` (driver_decisions.leave_out_answers) and set aside the work of
|
|
541
|
+
each ticket it leaves out. Returns the answers."""
|
|
542
|
+
questions = run.state.read()["run"]["questions"]
|
|
543
|
+
answers = driver_decisions.leave_out_answers(questions, tickets, run.args.retries)
|
|
544
|
+
_settle_rulings(run, questions, answers, driver_decisions.DRIVER, {})
|
|
545
|
+
_set_aside(run, tickets) # an error stops the next pass, which sets aside again
|
|
546
|
+
return answers
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def _set_aside(run: Run, tickets: list[Ticket]) -> list[str]:
|
|
550
|
+
"""Save the uncommitted work that a left-out ticket left in its slot as a patch next to its reports, and take the
|
|
551
|
+
slot off its branch with a clean tree: the other tickets and the end of run get the slot. [] or the errors that
|
|
552
|
+
stop the run: a slot that git cannot clean stays as it is."""
|
|
553
|
+
state, errors = run.state.read(), []
|
|
554
|
+
for number in sorted(driver_decisions.left_out(state["run"]["questions"], tickets)):
|
|
555
|
+
slot, patch = state["tickets"][number]["slot"], driver_slots.fresh(OUT / number / "left-out.patch")
|
|
556
|
+
if not driver_state.holds_work(state, number):
|
|
557
|
+
continue
|
|
558
|
+
if error := driver_slots.set_aside(driver_slots.path(slot), patch):
|
|
559
|
+
errors.append(f"implement-spec: ticket {number} is left out, but its uncommitted work stays in slot "
|
|
560
|
+
f"{slot}: {error}")
|
|
561
|
+
continue
|
|
562
|
+
run.kept.pop(number, None)
|
|
563
|
+
ledger(f"Ticket {number}: left out; its uncommitted work in slot {slot} is saved as {patch}, and the slot is "
|
|
564
|
+
"free.")
|
|
565
|
+
return errors
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _settle_rulings(run: Run, questions: list[dict], answers: dict, by: str, why: dict[str, str]) -> None:
|
|
569
|
+
"""Settle the `answers` that `by`, the driver or the arbiter, gave."""
|
|
475
570
|
if answers:
|
|
476
|
-
_settle(state, questions, answers, [],
|
|
477
|
-
print(f"implement-spec: the
|
|
478
|
-
|
|
479
|
-
|
|
571
|
+
_settle(run.state, questions, answers, [], by, why)
|
|
572
|
+
print(f"implement-spec: the {by} ruled on {len(answers)} question{'s' * (len(answers) > 1)} and goes on",
|
|
573
|
+
flush=True)
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _arbitrate(run: Run) -> tuple[dict[str, str], dict[str, str]]:
|
|
577
|
+
"""The arbiter's answers; none when a CLI failure stops it, which halts the run as it would any agent."""
|
|
578
|
+
try:
|
|
579
|
+
return driver_arbiter.rule(run)
|
|
580
|
+
except Halted as halted:
|
|
581
|
+
_halt(run, "End of run", str(halted))
|
|
582
|
+
return {}, {}
|
|
480
583
|
|
|
481
584
|
|
|
482
585
|
# ---------------------------------------------------------------- the end of the process
|
|
483
586
|
|
|
484
|
-
def _write_stage(path: str, code: int, open_questions: int, blocked: list[str]) -> None:
|
|
485
|
-
"""stage.json tells the dispatcher of an unattended run how the run ended
|
|
587
|
+
def _write_stage(path: str, code: int, open_questions: int, blocked: list[str], record: dict) -> None:
|
|
588
|
+
"""stage.json tells the dispatcher of an unattended run how the run ended; a done run says whether its PR is a
|
|
589
|
+
draft and how many questions were ruled with no operator."""
|
|
486
590
|
if code == 2:
|
|
487
591
|
body = {"status": "awaiting-review", "artifact": str(PAGE), "open_questions": open_questions}
|
|
488
592
|
elif code == 0:
|
|
489
|
-
body = {"status": "done"
|
|
593
|
+
body = {"status": "done", "draft": record["final"]["draft"],
|
|
594
|
+
"decisions": len(driver_decisions.without_operator(record["questions"]))}
|
|
490
595
|
else:
|
|
491
596
|
body = {"status": "blocked", "blocked": blocked}
|
|
492
597
|
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
493
598
|
Path(path).write_text(json.dumps({"stage": "implement", **body}, indent=1) + "\n")
|
|
494
599
|
|
|
495
600
|
|
|
496
|
-
def _tell(args, code: int, open_questions: list[dict], blocked: list[str],
|
|
601
|
+
def _tell(args, code: int, open_questions: list[dict], blocked: list[str], record: dict) -> None:
|
|
497
602
|
"""Print the open questions for the operator, or write stage.json for the dispatcher of an unattended run."""
|
|
498
603
|
if not args.unattended:
|
|
499
604
|
print(driver_decisions.text(open_questions, str(driver_answers.FILE), str(PAGE)), end="")
|
|
500
|
-
elif args.stage_json and (code or pushed):
|
|
605
|
+
elif args.stage_json and (code or record["final"]["pushed"]):
|
|
501
606
|
# Exit 0 with nothing pushed is not `done` for the dispatcher: it gets no file.
|
|
502
|
-
_write_stage(args.stage_json, code, len(open_questions), blocked)
|
|
607
|
+
_write_stage(args.stage_json, code, len(open_questions), blocked, record)
|
|
503
608
|
|
|
504
609
|
|
|
505
610
|
def _halted_exit(halted: list[str], final: dict) -> int:
|
|
@@ -514,17 +619,24 @@ def _halted_exit(halted: list[str], final: dict) -> int:
|
|
|
514
619
|
return 4
|
|
515
620
|
|
|
516
621
|
|
|
517
|
-
def
|
|
622
|
+
def _blocked(final: dict, tickets: list[Ticket], end_blocked: bool) -> list[str]:
|
|
623
|
+
"""The tickets that end the run BLOCKED, with FINAL when the end of run is: no left-out ticket, which the end of
|
|
624
|
+
run ships without."""
|
|
625
|
+
left = driver_decisions.left_out(final["run"]["questions"], tickets)
|
|
626
|
+
blocked = [number for number, entry in final["tickets"].items()
|
|
627
|
+
if entry["phase"] == "blocked" and number not in left]
|
|
628
|
+
return blocked + [FINAL] * end_blocked
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def _exit_code(final: dict, args, tickets: list[Ticket], end_blocked: bool) -> int:
|
|
518
632
|
"""Publish the open questions, tell the operator or the dispatcher, and return the exit code."""
|
|
519
633
|
if error := _publish_questions(final["run"]):
|
|
520
634
|
print(error)
|
|
521
635
|
return 3
|
|
522
|
-
blocked =
|
|
523
|
-
if end_blocked:
|
|
524
|
-
blocked.append(FINAL)
|
|
636
|
+
blocked = _blocked(final, tickets, end_blocked)
|
|
525
637
|
open_questions = driver_decisions.document(final["run"])["questions"]
|
|
526
638
|
code = 2 if driver_decisions.parked(final["run"]["questions"]) else int(bool(blocked))
|
|
527
|
-
_tell(args, code, open_questions, blocked,
|
|
639
|
+
_tell(args, code, open_questions, blocked, final["run"])
|
|
528
640
|
return code
|
|
529
641
|
|
|
530
642
|
|
|
@@ -534,11 +646,16 @@ def _record_skipped(skipped: list[str]) -> None:
|
|
|
534
646
|
ledger(sentence)
|
|
535
647
|
|
|
536
648
|
|
|
649
|
+
def _prepared(tickets: list[Ticket], run: Run, slots: int) -> list[str]:
|
|
650
|
+
"""Resume, apply the answers and set aside the work of each left-out ticket: [] or the errors that stop the run."""
|
|
651
|
+
return (_resume(tickets, run.state, run.pr, slots, run.args, run.kept) or _apply_answers(run.state, run.args)
|
|
652
|
+
or _set_aside(run, tickets))
|
|
653
|
+
|
|
654
|
+
|
|
537
655
|
def _once(tickets: list[Ticket], run: Run, slots: int) -> tuple[bool, list[str]] | int:
|
|
538
656
|
"""Resume, apply the answers and do the work once: what `_work` returns, or exit 3 with each error printed."""
|
|
539
657
|
args = run.args
|
|
540
|
-
errors
|
|
541
|
-
if errors:
|
|
658
|
+
if errors := _prepared(tickets, run, slots):
|
|
542
659
|
print("\n".join(errors))
|
|
543
660
|
return 3
|
|
544
661
|
if args.unattended and args.stage_json:
|
|
@@ -556,11 +673,11 @@ def _run(tickets: list[Ticket], models: dict[str, list[str]], skipped: list[str]
|
|
|
556
673
|
slots = 1 if args.only else min(args.parallel, len(tickets))
|
|
557
674
|
_record_skipped(skipped)
|
|
558
675
|
while True:
|
|
559
|
-
run = Run(args, models, state, pr, kept)
|
|
676
|
+
run = Run(args, models, state, pr, kept, tickets)
|
|
560
677
|
done = _once(tickets, run, slots)
|
|
561
678
|
if isinstance(done, int):
|
|
562
679
|
return done
|
|
563
|
-
if run.halted or not _rule(
|
|
680
|
+
if run.halted or not _rule(run, tickets):
|
|
564
681
|
break
|
|
565
682
|
# The driver's own answer resumes the run as the operator's would on the next invocation.
|
|
566
683
|
args.answer, kept = [], driver_state.kept(state.read())
|
|
@@ -575,7 +692,7 @@ def _finish(run: Run, args, end_blocked: bool, lines: list[str]) -> int:
|
|
|
575
692
|
print(summary + "".join(line + "\n" for line in lines), end="")
|
|
576
693
|
if run.halted:
|
|
577
694
|
return _halted_exit(run.halted, final)
|
|
578
|
-
return _exit_code(final, args, end_blocked)
|
|
695
|
+
return _exit_code(final, args, run.tickets, end_blocked)
|
|
579
696
|
|
|
580
697
|
|
|
581
698
|
# ---------------------------------------------------------------- the command line
|
|
@@ -619,6 +736,15 @@ def _arguments(argv: list[str] | None) -> argparse.Namespace:
|
|
|
619
736
|
parser.add_argument("--retries", type=int, default=int(os.environ.get("IMPLEMENT_SPEC_RETRIES", 2)), metavar="N",
|
|
620
737
|
help="the stops of one ticket, or of the end of run, that the driver answers itself with the "
|
|
621
738
|
"recommended option before it asks the operator (default: IMPLEMENT_SPEC_RETRIES, else 2)")
|
|
739
|
+
parser.add_argument("--must-fix-retries", type=int, metavar="N",
|
|
740
|
+
default=int(os.environ.get("IMPLEMENT_SPEC_MUST_FIX_RETRIES", 2)),
|
|
741
|
+
help="the more fix batches, beyond --retries, that the driver runs itself while a critical or "
|
|
742
|
+
"must-fix finding is open, before it asks the operator (default: "
|
|
743
|
+
"IMPLEMENT_SPEC_MUST_FIX_RETRIES, else 2)")
|
|
744
|
+
parser.add_argument("--ask", action=argparse.BooleanOptionalAction,
|
|
745
|
+
default=os.environ.get("IMPLEMENT_SPEC_ASK") == "1", help="once the retries are spent, ask "
|
|
746
|
+
"the operator instead of the arbiter agent, and instead of the `ship-draft` or `leave-out` of "
|
|
747
|
+
"the driver (default: IMPLEMENT_SPEC_ASK=1, else off)")
|
|
622
748
|
parser.add_argument("--unattended", action="store_true", help="at a question, print no question: write "
|
|
623
749
|
"--stage-json for the dispatcher, which gives the answers file to the next run")
|
|
624
750
|
parser.add_argument("--stage-json", metavar="FILE", help="with --unattended: where the driver writes how a "
|
|
@@ -40,7 +40,7 @@ LENSES = {
|
|
|
40
40
|
"final-structure": Lens("structure", "deep-quality-review", "SKILL.md", False, False)}
|
|
41
41
|
# Minutes per role.
|
|
42
42
|
TIMEOUTS = {"test-writer": 30, "implementer": 90, "reviewer": 45, "fixer": 60, "final-reviewer": 60,
|
|
43
|
-
**dict.fromkeys(LENSES, 60), "conflict": 30, "pr-writer": 20}
|
|
43
|
+
**dict.fromkeys(LENSES, 60), "conflict": 30, "pr-writer": 20, "arbiter": 30}
|
|
44
44
|
PROVIDERS = {"anthropic": ("claude", ("low", "medium", "high", "xhigh", "max")),
|
|
45
45
|
"openai": ("codex", ("minimal", "low", "medium", "high", "xhigh"))}
|
|
46
46
|
# USD per million tokens at the API list price; the cached part of the input costs `cached_input`. A
|
|
@@ -49,7 +49,7 @@ PRICES = {"gpt-6-astra": {"input": 10.0, "cached_input": 1.0, "output": 50.0},
|
|
|
49
49
|
"gpt-6.1-sol": {"input": 2.0, "cached_input": 0.10, "output": 10.0}}
|
|
50
50
|
# The name of each token count in the agent record, and its key in the `usage` of a codex turn.
|
|
51
51
|
_USAGE = {"input": "input_tokens", "cached_input": "cached_input_tokens", "output": "output_tokens"}
|
|
52
|
-
READ_ONLY = ("reviewer", "final-reviewer", *LENSES, "pr-writer")
|
|
52
|
+
READ_ONLY = ("reviewer", "final-reviewer", *LENSES, "pr-writer", "arbiter")
|
|
53
53
|
PREFLIGHT = "implement-spec preflight: reply with the word OK. Read no file and run no command.\n"
|
|
54
54
|
# The time limit of one preflight call: a CLI that gives no answer in this time fails the preflight.
|
|
55
55
|
PREFLIGHT_MINUTES = 5
|
|
@@ -129,22 +129,27 @@ def _is_list(entries: object) -> bool:
|
|
|
129
129
|
return isinstance(entries, list) and bool(entries) and all(isinstance(entry, str) for entry in entries)
|
|
130
130
|
|
|
131
131
|
|
|
132
|
-
def other_provider_entries(models: dict[str, list[str]]) -> list[str]:
|
|
133
|
-
"""The entries of the `
|
|
134
|
-
|
|
132
|
+
def other_provider_entries(models: dict[str, list[str]], role: str) -> list[str]:
|
|
133
|
+
"""The entries of the `role` list on another provider than the implementer's first entry: the correctness lens and
|
|
134
|
+
the scoped review run and rerun on those of `final-reviewer` when there is one, the arbiter on its own."""
|
|
135
135
|
own = split(models["implementer"][0])[0]
|
|
136
|
-
return [entry for entry in models[
|
|
136
|
+
return [entry for entry in models[role] if split(entry)[0] != own]
|
|
137
137
|
|
|
138
138
|
|
|
139
139
|
def other_provider_entry(models: dict[str, list[str]]) -> str:
|
|
140
140
|
"""The other-provider entry of the `final-reviewer` list, its first one; "" when there is none."""
|
|
141
|
-
return next(iter(other_provider_entries(models)), "")
|
|
141
|
+
return next(iter(other_provider_entries(models, "final-reviewer")), "")
|
|
142
142
|
|
|
143
143
|
|
|
144
144
|
def correctness_entries(models: dict[str, list[str]]) -> list[str]:
|
|
145
145
|
"""The entries of the correctness lens and the scoped review: the other-provider ones, or, when the config has none
|
|
146
146
|
or none passed the preflight, the whole `final-reviewer` list (the ledger and the PR body say so)."""
|
|
147
|
-
return
|
|
147
|
+
return preferred_entries(models, "final-reviewer")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def preferred_entries(models: dict[str, list[str]], role: str) -> list[str]:
|
|
151
|
+
"""The entries of `role` on another provider than the implementer's first entry, else its whole list."""
|
|
152
|
+
return other_provider_entries(models, role) or models[role]
|
|
148
153
|
|
|
149
154
|
|
|
150
155
|
def lens_entries(models: dict[str, list[str]], role: str) -> list[str]:
|
|
@@ -355,3 +360,16 @@ def cost(log: Path, entry: str, used: dict[str, int]) -> float | None:
|
|
|
355
360
|
+ used["output"] * price["output"]) / 1e6, 4)
|
|
356
361
|
found = re.findall(r'"total_cost_usd":\s*([0-9.]+)', log.read_text(errors="replace"))
|
|
357
362
|
return float(found[-1]) if found else None
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
# The final review runs through the review-diff skill, which must sit next to this one: `installed` looks nowhere else.
|
|
366
|
+
REVIEW_DIFF = SKILL.parent / "review-diff" / "SKILL.md"
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def installed(name: str) -> Path | None:
|
|
370
|
+
"""The SKILL.md of a skill: next to this skill, else in the skill folder of the Claude home or of the shared
|
|
371
|
+
home of Codex and OpenCode. review-diff is only next to this skill."""
|
|
372
|
+
claude = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
|
|
373
|
+
homes = (REVIEW_DIFF.parent.parent,) if name == REVIEW_DIFF.parent.name else (
|
|
374
|
+
SKILL.parent, claude / "skills", Path.home() / ".agents" / "skills")
|
|
375
|
+
return next((home / name / "SKILL.md" for home in homes if (home / name / "SKILL.md").is_file()), None)
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""The arbiter: when the driver's own retries are spent, one read-only agent rules on each open question that
|
|
2
|
+
driver_decisions.arbitrated names (a final finding, or a ticket's spec-ambiguous question), on another provider than
|
|
3
|
+
the implementer, with a reason and the cost if it is wrong. An arbiter that cannot rule leaves the questions to the
|
|
4
|
+
operator.
|
|
5
|
+
|
|
6
|
+
The arbiter runs in a checkout of its own, SCRATCH, on a detached HEAD at the PR tip: slot 1 may hold the uncommitted
|
|
7
|
+
work of the ticket it rules on, which the restore after a read-only role would wipe."""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
|
|
12
|
+
import driver_agents
|
|
13
|
+
import driver_decisions
|
|
14
|
+
from driver_run import FINAL, OUT, Blocked, Call, Run, ledger
|
|
15
|
+
from driver_slots import git
|
|
16
|
+
|
|
17
|
+
SCRATCH = ".agent/worktrees/arbiter"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _here(path: str) -> str:
|
|
21
|
+
"""`path`, which the PR worktree reads, as the arbiter reads it from SCRATCH. Keeps a `:line` suffix."""
|
|
22
|
+
return os.path.relpath(path, SCRATCH)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _values(run: Run, asked: list[dict]) -> dict[str, str]:
|
|
26
|
+
return {"spec": _here(run.args.spec), "tickets": _here(run.args.tickets), "pr_branch": run.pr, "branch": "",
|
|
27
|
+
"start_sha": run.tip(), "ledger": _here(str(OUT / "ledger.md")),
|
|
28
|
+
"questions": "".join(_line(run, q) for q in asked)}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _line(run: Run, q: dict) -> str:
|
|
32
|
+
"""One question for the arbiter: its options, its evidence, and for a ticket the branch its work is on."""
|
|
33
|
+
branch = f" Ticket branch: {run.names.ticket(q['ticket'])}." if q["ticket"] != FINAL else ""
|
|
34
|
+
return (f"- {q['id']}: {q['title']}. Options: {', '.join(driver_decisions.KINDS[q['kind']].arbiter)}.{branch} "
|
|
35
|
+
f"Evidence: {', '.join(map(_here, q['evidence']))}\n")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _why(ruling: dict) -> str:
|
|
39
|
+
"""The end of the ruling sentence: the reason of the arbiter and the cost if it is wrong."""
|
|
40
|
+
return f": {ruling['reason'].rstrip('.')}. Cost if wrong: {ruling['cost'].rstrip('.')}"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def rule(run: Run) -> tuple[dict[str, str], dict[str, str]]:
|
|
44
|
+
"""(question id -> the arbiter's option, question id -> the end of its ruling sentence); both {} when no question
|
|
45
|
+
is the arbiter's or the arbiter could not rule."""
|
|
46
|
+
asked = driver_decisions.arbitrated(run.state.read()["run"]["questions"], run.args.retries)
|
|
47
|
+
if not asked:
|
|
48
|
+
return {}, {}
|
|
49
|
+
entries = driver_agents.preferred_entries(run.models, "arbiter")
|
|
50
|
+
call = Call("arbiter", FINAL, SCRATCH, _values(run, asked), entry=entries[0], entries=entries, asks=False,
|
|
51
|
+
name=f"arbiter-{asked[0]['stop']}",
|
|
52
|
+
check={"questions": {q["id"]: driver_decisions.KINDS[q["kind"]].arbiter for q in asked}})
|
|
53
|
+
try:
|
|
54
|
+
report = _in_scratch(run, call)
|
|
55
|
+
except Blocked as blocked:
|
|
56
|
+
ledger(f"{driver_decisions.owner(asked[0]['ticket'])}: the arbiter could not rule, so the operator decides: "
|
|
57
|
+
f"{blocked}.")
|
|
58
|
+
return {}, {}
|
|
59
|
+
return _answers(report["rulings"], call.check["questions"])
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _in_scratch(run: Run, call: Call) -> dict:
|
|
63
|
+
"""Run the arbiter in SCRATCH, made for it at its start commit and removed after it."""
|
|
64
|
+
tip = call.values["start_sha"]
|
|
65
|
+
if error := _remove_scratch(): # one that an interrupted run left
|
|
66
|
+
raise Blocked(error)
|
|
67
|
+
added = git(".", "worktree", "add", "-q", "--force", "--detach", SCRATCH, tip)
|
|
68
|
+
if added.returncode:
|
|
69
|
+
raise Blocked(f"cannot create {SCRATCH}: {added.stderr.strip()}")
|
|
70
|
+
try:
|
|
71
|
+
return run.read_only(FINAL, SCRATCH, "", tip, lambda: run.agent(call))
|
|
72
|
+
finally:
|
|
73
|
+
if error := _remove_scratch():
|
|
74
|
+
ledger(f"End of run: {error}.")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _remove_scratch() -> str:
|
|
78
|
+
"""Remove SCRATCH through Git alone, so a locked worktree or a directory that is no worktree there loses nothing.
|
|
79
|
+
"" or why it stays."""
|
|
80
|
+
if not os.path.lexists(SCRATCH):
|
|
81
|
+
return ""
|
|
82
|
+
removed = git(".", "worktree", "remove", "--force", SCRATCH)
|
|
83
|
+
return f"cannot remove {SCRATCH}: {removed.stderr.strip()}" if removed.returncode else ""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _answers(rulings: list[dict], asked: list[str]) -> tuple[dict[str, str], dict[str, str]]:
|
|
87
|
+
"""The rulings on the questions in `asked`, as `rule` returns them."""
|
|
88
|
+
rulings = [one for one in rulings if one["question"] in asked]
|
|
89
|
+
return {one["question"]: one["ruling"] for one in rulings}, {one["question"]: _why(one) for one in rulings}
|