@jesdi/skills 0.0.99 → 0.0.101

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/package.json +1 -1
  2. package/skills/implement-spec/ARCHITECTURE.md +8 -5
  3. package/skills/implement-spec/README.md +43 -19
  4. package/skills/implement-spec/SKILL.md +2 -0
  5. package/skills/implement-spec/driver.py +136 -30
  6. package/skills/implement-spec/driver_agents.py +13 -0
  7. package/skills/implement-spec/driver_arbiter.py +57 -11
  8. package/skills/implement-spec/driver_decisions.py +186 -49
  9. package/skills/implement-spec/driver_dispute.py +1 -1
  10. package/skills/implement-spec/driver_final.py +232 -242
  11. package/skills/implement-spec/driver_final_gate.py +152 -17
  12. package/skills/implement-spec/driver_gate.py +12 -0
  13. package/skills/implement-spec/driver_legacy.py +15 -2
  14. package/skills/implement-spec/driver_overturn.py +106 -0
  15. package/skills/implement-spec/driver_pr.py +286 -0
  16. package/skills/implement-spec/driver_report.py +9 -4
  17. package/skills/implement-spec/driver_review.py +10 -4
  18. package/skills/implement-spec/driver_run.py +33 -14
  19. package/skills/implement-spec/driver_slots.py +61 -11
  20. package/skills/implement-spec/driver_state.py +30 -16
  21. package/skills/implement-spec/driver_summary.py +10 -3
  22. package/skills/implement-spec/prompts/arbiter.md +8 -4
  23. package/skills/implement-spec/prompts/conflict.md +1 -1
  24. package/skills/implement-spec/prompts/pr-body.md +2 -1
  25. package/skills/implement-spec/recovery.md +4 -4
  26. package/skills/implement-spec/tests/conftest.py +1 -0
  27. package/skills/implement-spec/tests/test_arbiter.py +74 -17
  28. package/skills/implement-spec/tests/test_arbitration.py +1 -1
  29. package/skills/implement-spec/tests/test_decisions.py +30 -6
  30. package/skills/implement-spec/tests/test_driver.py +9 -1
  31. package/skills/implement-spec/tests/test_final.py +20 -3
  32. package/skills/implement-spec/tests/test_final_gate.py +144 -0
  33. package/skills/implement-spec/tests/test_fixloop.py +1 -1
  34. package/skills/implement-spec/tests/test_leave_out.py +203 -0
  35. package/skills/implement-spec/tests/test_legacy.py +25 -0
  36. package/skills/implement-spec/tests/test_lenses.py +6 -4
  37. package/skills/implement-spec/tests/test_overturn.py +362 -0
  38. package/skills/implement-spec/tests/test_scoped.py +6 -5
  39. package/skills/implement-spec/tests/test_ship_draft.py +203 -0
  40. package/skills/implement-spec/tests/test_slots.py +29 -0
  41. package/skills/implement-spec/tests/test_state.py +4 -2
  42. package/skills/implement-spec/tests/test_stops.py +19 -4
  43. package/skills/implement-spec/tests/test_tidy.py +4 -2
  44. package/skills/implement-spec/tests/test_walk.py +1 -0
  45. package/skills-manifest.json +3 -3
@@ -1,18 +1,38 @@
1
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, on another provider than the implementer, with a reason and the cost if it is
3
- wrong. An arbiter that cannot rule leaves the questions to the operator."""
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."""
4
8
  from __future__ import annotations
5
9
 
10
+ import os
11
+
6
12
  import driver_agents
7
13
  import driver_decisions
8
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)
9
23
 
10
24
 
11
25
  def _values(run: Run, asked: list[dict]) -> dict[str, str]:
12
- tip = run.tip()
13
- return {"spec": run.args.spec, "tickets": run.args.tickets, "pr_branch": run.pr, "branch": run.pr,
14
- "start_sha": tip, "ledger": str(OUT / "ledger.md"),
15
- "questions": "".join(f"- {q['id']}: {q['title']}. Evidence: {', '.join(q['evidence'])}\n" for q in asked)}
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")
16
36
 
17
37
 
18
38
  def _why(ruling: dict) -> str:
@@ -23,20 +43,46 @@ def _why(ruling: dict) -> str:
23
43
  def rule(run: Run) -> tuple[dict[str, str], dict[str, str]]:
24
44
  """(question id -> the arbiter's option, question id -> the end of its ruling sentence); both {} when no question
25
45
  is the arbiter's or the arbiter could not rule."""
26
- asked = driver_decisions.arbitrated(run.state.read()["run"]["questions"])
46
+ asked = driver_decisions.arbitrated(run.state.read()["run"]["questions"], run.args.retries)
27
47
  if not asked:
28
48
  return {}, {}
29
49
  entries = driver_agents.preferred_entries(run.models, "arbiter")
30
- call = Call("arbiter", FINAL, ".", _values(run, asked), entry=entries[0], entries=entries, asks=False,
31
- name=f"arbiter-{asked[0]['stop']}", check={"questions": [q["id"] for q in asked]})
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}})
32
53
  try:
33
- report = run.read_only(FINAL, ".", run.pr, call.values["start_sha"], lambda: run.agent(call))
54
+ report = _in_scratch(run, call)
34
55
  except Blocked as blocked:
35
- ledger(f"End of run: the arbiter could not rule, so the operator decides: {blocked}.")
56
+ ledger(f"{driver_decisions.owner(asked[0]['ticket'])}: the arbiter could not rule, so the operator decides: "
57
+ f"{blocked}.")
36
58
  return {}, {}
37
59
  return _answers(report["rulings"], call.check["questions"])
38
60
 
39
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
+
40
86
  def _answers(rulings: list[dict], asked: list[str]) -> tuple[dict[str, str], dict[str, str]]:
41
87
  """The rulings on the questions in `asked`, as `rule` returns them."""
42
88
  rulings = [one for one in rulings if one["question"] in asked]
@@ -3,8 +3,11 @@
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; 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}
6
+ ruling: the ruling sentence, once answered; by: DRIVER or ARBITER when no operator answered it, until the operator
7
+ overturns the ruling (driver_overturn); overturned: who took the ruling the operator overturned;
8
+ issue: the URL of the follow-up issue the driver filed for a `follow-up` answer;
9
+ role: the agent whose stop a `ticket-blocked` question asks about, None for a gate or a landing stop and absent
10
+ from a question of an older driver, which a reader takes as no particular agent}
8
11
  decisions.json: {run: <run.revision>, questions: [the open ones, first six fields], revision: <SHA-256 of the rest>}."""
9
12
  from __future__ import annotations
10
13
 
@@ -13,10 +16,16 @@ import json
13
16
  from collections import Counter
14
17
  from typing import NamedTuple
15
18
 
19
+ from driver_tickets import Ticket
20
+
16
21
  PUBLIC = ("id", "title", "why", "evidence", "options", "recommended")
17
22
  DRIVER = "driver" # `by` of a question the driver answered itself
18
23
  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
24
+ OPERATOR = "operator" # what `ruled_by` says of a question with no `by`
25
+ SHIPS = ("accept", "follow-up") # the answers to a finding question that ship the PR with the finding open
26
+ FINDING_OPEN = "finding-open" # the kind of an important finding: the arbiter may ship it, as draft
27
+ MUST_FIX = "finding-must-fix" # the kind of a critical or must-fix finding: no agent ships it
28
+ FINDINGS = (FINDING_OPEN, MUST_FIX) # the kinds of a final-review finding that the scoped review leaves open
20
29
  FINAL = "final" # the end of run asks its questions, and has its record and its files, under this name
21
30
 
22
31
 
@@ -46,6 +55,15 @@ class Option(NamedTuple):
46
55
  ruling: str
47
56
  resumes: bool # the record goes back to the `resume` of the question
48
57
  fields: dict = {} # what else the record gets when its stop is settled; no field at all keeps it BLOCKED
58
+ final_only: bool = False # only the end of run offers it
59
+ ticket_only: bool = False # only a ticket offers it
60
+
61
+
62
+ LEAVE_OUT = Option(
63
+ "Leave the ticket out of the run, with each ticket it blocks: the merged tickets get the end of run and a draft PR "
64
+ "that names them. The driver takes it once its retries, and the arbiter's, are spent.",
65
+ "Ruling: {ticket} is left out of the run, with each ticket it blocks (leave-out): {subject}.", False,
66
+ ticket_only=True)
49
67
 
50
68
 
51
69
  class Kind(NamedTuple):
@@ -53,6 +71,20 @@ class Kind(NamedTuple):
53
71
  why: str
54
72
  recommended: str # "" for a kind that recommends no option
55
73
  options: dict[str, Option]
74
+ arbiter: tuple[str, ...] = () # the options the arbiter may rule with once the driver's retries are spent; none:
75
+ # the arbiter does not rule on it
76
+
77
+
78
+ FINDING_OPTIONS = { # both finding kinds: they differ only in who may ship the finding (`Kind.arbiter`)
79
+ "retry": Option(
80
+ "One more fix batch and scoped review.",
81
+ "Ruling: {ticket} runs again (retry): {subject}.", True),
82
+ "accept": Option(
83
+ "Push and open the PR as draft, with the finding open and listed in its rulings.",
84
+ "Ruling: {ticket} ships with the finding open (accept): {subject}.", True),
85
+ "follow-up": Option(
86
+ "As `accept`, and the driver files the finding as an issue before it opens the PR.",
87
+ "Ruling: {ticket} ships with the finding open, filed as a follow-up issue (follow-up): {subject}.", True)}
56
88
 
57
89
 
58
90
  KINDS = {
@@ -72,9 +104,11 @@ KINDS = {
72
104
  "again (a fixer after the review of its round); after a review finding, the review runs again.",
73
105
  "Ruling: {ticket} locked test is corrected to the second reading (correct-test): {subject}.", False,
74
106
  {"phase": "test-writer", "note": "correction"}),
107
+ "leave-out": LEAVE_OUT,
75
108
  "edit-spec": Option(
76
109
  "Keep the ticket BLOCKED, so the spec can be edited to say which reading it means.",
77
- "Ruling: {ticket} stays BLOCKED for an edit of the spec (edit-spec): {subject}.", False)}),
110
+ "Ruling: {ticket} stays BLOCKED for an edit of the spec (edit-spec): {subject}.", False)},
111
+ arbiter=("keep-test", "correct-test")),
78
112
  # The end of run asks it too, with the ticket `final`: for an agent, or for the integration gate.
79
113
  "ticket-blocked": Kind(
80
114
  "{owner}: an agent stopped or was rejected, and its rerun too, or the integration gate remains red: {subject}",
@@ -88,27 +122,38 @@ KINDS = {
88
122
  "fix batch and scoped review, and a red integration gate gets one more repair batch from its saved "
89
123
  "log, followed by the full gate and review.",
90
124
  "Ruling: {ticket} runs again (retry): {subject}.", True),
125
+ "ship-draft": Option(
126
+ "Push the branch tip that a full gate ran on, green or red, and open the PR as draft, naming this stop; "
127
+ "the end of run reviews and repairs no more. The driver takes it once its retries are spent.",
128
+ "Ruling: {ticket} ships as a draft PR (ship-draft): {subject}.", True, final_only=True),
129
+ "leave-out": LEAVE_OUT,
91
130
  "edit": Option(
92
131
  "Keep it BLOCKED, so the spec or the ticket can be edited before more work on it.",
93
132
  "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(
133
+ # Only the end of run asks the two finding kinds: the subject is the finding's title and file (`subject`).
134
+ FINDING_OPEN: Kind(
96
135
  "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)}),
136
+ "The scoped review after the fix batch left this important finding open. Nothing is pushed until it is ruled "
137
+ "on.",
138
+ "retry", FINDING_OPTIONS, arbiter=SHIPS),
139
+ MUST_FIX: Kind(
140
+ "End of run: a critical or must-fix finding is open after the scoped review: {subject}",
141
+ "The scoped review after the fix batch left this critical or must-fix finding open, and the driver's own fix "
142
+ "batches are spent. No agent ships it: only you may. Nothing is pushed until it is ruled on.",
143
+ "retry", FINDING_OPTIONS),
109
144
  }
110
145
 
111
146
 
147
+ def finding_kind(finding: dict) -> str:
148
+ """The kind of the question that an open final-review finding asks."""
149
+ return MUST_FIX if finding["severity"] == "critical" or finding.get("must_fix") else FINDING_OPEN
150
+
151
+
152
+ def subject(finding: dict) -> str:
153
+ """A final-review finding as its question names it: its title and file, not its line, which a fix batch moves."""
154
+ return f"{finding['title']} ({finding['file']})"
155
+
156
+
112
157
  def drop_merged(state: dict) -> list[dict]:
113
158
  """Remove the open questions of each merged ticket from `state`: the stop that asked them is over (issue #136).
114
159
  Returns them."""
@@ -121,30 +166,45 @@ def drop_merged(state: dict) -> list[dict]:
121
166
 
122
167
  def question_id(kind: str, ticket: str, asked: list[dict]) -> str:
123
168
  """The id of the next question of `kind` for `ticket`: `<NN>-<kind>-<n>` (`final-<kind>-<n>` for the end of run);
124
- n counts in `asked`, the whole run."""
125
- return f"{ticket}-{kind}-{1 + sum((q['ticket'], q['kind']) == (ticket, kind) for q in asked)}"
169
+ n counts the ids of `asked`, the whole run, so a question whose kind changed (driver_legacy) keeps its id."""
170
+ prefix = f"{ticket}-{kind}-"
171
+ return f"{prefix}{1 + sum(q['id'].startswith(prefix) for q in asked)}"
126
172
 
127
173
 
128
174
  def question(kind: str, ticket: str, subject: str, evidence: list[str], asked: list[dict], stop: int,
129
- resume: Resume) -> dict:
130
- """A new open question."""
175
+ resume: Resume, role: str | None = None) -> dict:
176
+ """A new open question; `role`: the agent whose stop it asks about. A gate or a landing stop has none, nor has a
177
+ question of a driver before it, so a reader takes no role for no particular agent."""
131
178
  made, values = KINDS[kind], {"ticket": ticket, "subject": subject, "owner": owner(ticket)}
132
179
  return {"id": question_id(kind, ticket, asked), "title": made.title.format(**values),
133
180
  "why": made.why.format(**values),
134
181
  "evidence": evidence, "recommended": made.recommended,
135
- "options": [{"id": name, "description": option.description} for name, option in made.options.items()],
136
- "ticket": ticket, "kind": kind, "subject": subject, "stop": stop, "resume": resume.fields(), "answer": None}
182
+ "options": [{"id": name, "description": option.description} for name, option in made.options.items()
183
+ if _offered(option, ticket)],
184
+ "ticket": ticket, "kind": kind, "subject": subject, "stop": stop, "resume": resume.fields(), "answer": None,
185
+ "role": role}
186
+
137
187
 
188
+ def _offered(option: Option, ticket: str) -> bool:
189
+ """Whether a stop of `ticket` offers `option`: an end-of-run one only at the end of run, a ticket one only for a
190
+ ticket."""
191
+ return not (option.ticket_only if ticket == FINAL else option.final_only)
138
192
 
139
- def stop(run: dict, kind: str, ticket: str, subjects: list[str], evidence: list[str], resume: Resume) -> None:
140
- """Count one stop in `run` and add one open question of `kind` per subject. No subject is no stop."""
141
- run["stops"] += bool(subjects)
142
- for subject in subjects:
143
- run["questions"].append(question(kind, ticket, subject, evidence, run["questions"], run["stops"], resume))
144
193
 
194
+ def stop(run: dict, ticket: str, asked: list[tuple[str, str, str | None]], evidence: list[str], resume: Resume
195
+ ) -> None:
196
+ """Count one stop in `run` and add one open question per (kind, subject, role) of `asked`. Nothing asked is no
197
+ stop."""
198
+ run["stops"] += bool(asked)
199
+ for kind, subject, role in asked:
200
+ run["questions"].append(question(kind, ticket, subject, evidence, run["questions"], run["stops"], resume, role))
145
201
 
146
- def decides(kind: str, subjects: int) -> str:
147
- return f"the operator decides on {subjects} question{'s' * (subjects > 1)} of kind {kind}"
202
+
203
+ def decides(asked: list[tuple[str, str, str | None]]) -> str:
204
+ """What the operator decides on at a stop that asks `asked`, (kind, subject, role) triples."""
205
+ counts = Counter(kind for kind, *_ in asked)
206
+ return "the operator decides on " + " and ".join(
207
+ f"{n} question{'s' * (n > 1)} of kind {kind}" for kind, n in counts.items())
148
208
 
149
209
 
150
210
  def document(run: dict) -> dict:
@@ -161,14 +221,51 @@ def rulings(questions: list[dict]) -> list[str]:
161
221
  for q in questions if q["answer"] is not None]
162
222
 
163
223
 
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}
224
+ def waived(questions: list[dict], finding: dict) -> bool:
225
+ """An answer to a question on `finding` ships it: no fix batch is due. A finding that is critical or must-fix now
226
+ is shipped only by the operator's answer, not by the driver's or the arbiter's (`by`) to it as an important one."""
227
+ by = {ruled_by(q) for q in questions if _ships(q, subject(finding))}
228
+ return OPERATOR in by if finding_kind(finding) == MUST_FIX else bool(by)
229
+
230
+
231
+ def agent_shipped(questions: list[dict], finding: dict) -> bool:
232
+ """The driver or the arbiter (`by`), not the operator, answered a question on `finding` with an option that ships it."""
233
+ return any(ruled_by(q) != OPERATOR for q in questions if _ships(q, subject(finding)))
234
+
235
+
236
+ def _ships(q: dict, named: str) -> bool:
237
+ """`q` is a finding question on the subject `named`, answered with an option that ships it."""
238
+ return q["kind"] in FINDINGS and q["answer"] in SHIPS and q["subject"] == named
239
+
240
+
241
+ def left_out(questions: list[dict], tickets: list[Ticket]) -> set[str]:
242
+ """The tickets left out of the run: each one answered `leave-out`, and each ticket it blocks, directly or through
243
+ another. The others are the tickets the end of run ships."""
244
+ out = {q["ticket"] for q in questions if q["answer"] == "leave-out"}
245
+ for _ in tickets: # a chain of blockers is at most as long as the list
246
+ out |= {ticket.number for ticket in tickets if out.intersection(ticket.blocked_by)}
247
+ return out
248
+
249
+
250
+ def leave_out_answers(questions: list[dict], tickets: list[Ticket], retries: int) -> dict[str, str]:
251
+ """`leave-out` for each open question of a ticket that neither the driver's `retry` (`automatic`, while it ruled on
252
+ fewer than `retries` stops of the ticket) nor the arbiter rules on; none when the tickets left out would be all of
253
+ them: a run with no merged ticket ships nothing, so its stop asks the operator."""
254
+ spent, theirs = ruled(questions), {q["id"] for q in arbitrated(questions, retries)}
255
+ answers = {q["id"]: "leave-out" for q in questions if _unruled(q, spent, retries, theirs)}
256
+ after = [{**q, "answer": answers.get(q["id"], q["answer"])} for q in questions]
257
+ return answers if len(left_out(after, tickets)) < len(tickets) else {}
258
+
259
+
260
+ def _unruled(q: dict, spent: Counter, retries: int, theirs: set[str]) -> bool:
261
+ """`q` is an open question of a ticket that neither the driver's `retry` (`_due`) nor the arbiter (its id in
262
+ `theirs`) answers."""
263
+ return q["answer"] is None and q["ticket"] != FINAL and not _due(q, spent, retries) and q["id"] not in theirs
167
264
 
168
265
 
169
266
  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")]
267
+ """The finding questions answered `follow-up` with no issue filed yet."""
268
+ return [q for q in questions if q["kind"] in FINDINGS and q["answer"] == "follow-up" and not q.get("issue")]
172
269
 
173
270
 
174
271
  def ruling(q: dict) -> str:
@@ -193,18 +290,26 @@ def _settled(questions: list[dict], ticket: str, stop: int) -> dict:
193
290
  return {name: value for one in fields for name, value in one.items()} if all(fields) else {}
194
291
 
195
292
 
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})
293
+ def ruled(questions: list[dict], by: str = DRIVER) -> Counter:
294
+ """ticket (or FINAL) -> the stops of it that `by`, the driver or the arbiter, ruled on."""
295
+ return Counter(ticket for ticket, _ in {(q["ticket"], q["stop"]) for q in questions if ruled_by(q) == by})
199
296
 
200
297
 
201
- def automatic(questions: list[dict], budget: int) -> dict:
298
+ def automatic(questions: list[dict], retries: int, must_fix_retries: int) -> dict:
202
299
  """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}
300
+ on fewer than `retries` stops of its ticket (or of the end of run). A `finding-must-fix` question counts only the
301
+ stops with one that the driver ruled, up to `retries + must_fix_retries`: that many fix batches run while a
302
+ critical or must-fix finding is open, whatever else stopped the end of run. No other option is the driver's to
303
+ take: a kind that recommends one still asks the operator."""
304
+ every = (ruled(questions), retries)
305
+ scopes = {MUST_FIX: (ruled([q for q in questions if q["kind"] == MUST_FIX]), retries + must_fix_retries)}
306
+ return {q["id"]: "retry" for q in questions if _due(q, *scopes.get(q["kind"], every))}
307
+
308
+
309
+ def _due(q: dict, spent: Counter, budget: int) -> bool:
310
+ """`q` is open, recommends `retry`, and the driver ruled on fewer than `budget` stops of its ticket, as `spent`
311
+ counts them."""
312
+ return q["answer"] is None and q["recommended"] == "retry" and spent[q["ticket"]] < budget
208
313
 
209
314
 
210
315
  def _answer(q: dict, answers: dict, by: str, why: str) -> str:
@@ -228,20 +333,52 @@ def apply(questions: list[dict], answers: dict, by: str = "", why: dict[str, str
228
333
  return rulings, _moved(questions, stops)
229
334
 
230
335
 
336
+ def overturn(questions: list[dict], answers: dict) -> tuple[list[str], dict[str, dict]]:
337
+ """Overturn the rulings of the driver or the arbiter that `answers` names with the operator's answer: the new
338
+ ruling names the one it overturns and who took it. Returns what `apply` returns."""
339
+ rulings, stops = [], {}
340
+ for q in questions:
341
+ if q["id"] in answers:
342
+ was, q["overturned"] = q["answer"], q.pop("by")
343
+ q["answer"] = answers[q["id"]]
344
+ q["ruling"] = f"{ruling(q)} It overturns the ruling {was} of the {q['overturned']}."
345
+ rulings.append(q["ruling"])
346
+ stops[q["ticket"]] = q["stop"]
347
+ return rulings, _moved(questions, stops)
348
+
349
+
231
350
  def _moved(questions: list[dict], stops: dict) -> dict[str, dict]:
232
351
  """ticket or FINAL -> the fields that let its record go on, for each of `stops` whose answers settle it."""
233
352
  moved = {ticket: _settled(questions, ticket, stop) for ticket, stop in stops.items()}
234
353
  return {ticket: fields for ticket, fields in moved.items() if fields}
235
354
 
236
355
 
356
+ def ruled_by(q: dict) -> str:
357
+ """Who took the ruling `q` has now: DRIVER, ARBITER, or OPERATOR for an answer of the operator, an overturn
358
+ included, and for an open question."""
359
+ return q.get("by") or OPERATOR
360
+
361
+
237
362
  def without_operator(questions: list[dict]) -> list[dict]:
238
363
  """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)]
364
+ return [q for q in questions if ruled_by(q) != OPERATOR]
365
+
366
+
367
+ def overturned(questions: list[dict]) -> list[dict]:
368
+ """The questions whose ruling of the driver or the arbiter the operator overturned."""
369
+ return [q for q in questions if q.get("overturned")]
370
+
371
+
372
+ def arbitrated(questions: list[dict], budget: int) -> list[dict]:
373
+ """The open questions the arbiter rules on once the driver's retries are spent, of a `Kind.arbiter` kind (no
374
+ `finding-must-fix`): a ticket's only while the arbiter ruled on fewer than `budget` stops of it."""
375
+ spent = ruled(questions, ARBITER)
376
+ return [q for q in questions if q["answer"] is None and _arbiters(q, spent[q["ticket"]], budget)]
240
377
 
241
378
 
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"]
379
+ def _arbiters(q: dict, spent: int, budget: int) -> bool:
380
+ """Whether the arbiter rules on `q` when it ruled on `spent` stops of its ticket."""
381
+ return bool(KINDS[q["kind"]].arbiter) and (q["ticket"] == FINAL or spent < budget)
245
382
 
246
383
 
247
384
  def text(open_questions: list[dict], answers: str, page: str) -> str:
@@ -70,7 +70,7 @@ def ambiguous(run: Run, number: str, readings: list[Reading], resume: Resume) ->
70
70
  _ruling_findings(path, [(one.found, subject, f"correct the test to the second reading: {one.found.reason}")
71
71
  for one, subject in zip(readings, subjects)])
72
72
  subject = "; ".join(subjects)
73
- run.ask(number, "spec-ambiguous", [subject], str(path), resume)
73
+ run.ask(number, [("spec-ambiguous", subject)], str(path), resume)
74
74
  raise Blocked(f"the spec reads two ways on a locked test: {subject}")
75
75
 
76
76