agent-bios 0.19.3 → 0.20.0

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 (172) hide show
  1. package/DEPENDENCIES.md +62 -20
  2. package/INSTALL.md +1 -1
  3. package/README.md +16 -21
  4. package/claude/agents/frontier.md +1 -1
  5. package/claude/agents/sweep.md +2 -1
  6. package/claude/agents/workhorse.md +2 -2
  7. package/claude/guides/claude-prompting.md +494 -167
  8. package/claude/guides/cli-multi-model-workflow.md +8 -7
  9. package/claude/guides/gpt-prompting.md +241 -111
  10. package/claude/guides/session-distill-workflow.md +93 -43
  11. package/claude/guides/tooling-gotchas.md +3 -1
  12. package/codex/agents/reviewer.toml +2 -2
  13. package/codex/agents/sweep.toml +1 -1
  14. package/codex/agents/workhorse.toml +2 -2
  15. package/codex/guides/claude-prompting.md +494 -167
  16. package/codex/guides/cli-multi-model-workflow.md +8 -7
  17. package/codex/guides/gpt-prompting.md +241 -111
  18. package/codex/guides/session-distill-workflow.md +93 -43
  19. package/codex/guides/tooling-gotchas.md +3 -1
  20. package/compose/assemble.py +4 -1
  21. package/compose/canary.sh +8 -6
  22. package/compose/host_platform.py +158 -15
  23. package/compose/instructions-state.py +183 -41
  24. package/compose/instructions_app.py +2 -2
  25. package/compose/instructions_install.py +222 -27
  26. package/compose/instructions_session.py +250 -75
  27. package/compose/instructions_setup.py +6 -6
  28. package/compose/instructions_setup_cli.py +2 -36
  29. package/compose/instructions_setup_i18n.py +3 -3
  30. package/compose/instructions_store.py +160 -3
  31. package/compose/instructions_transaction.py +29 -5
  32. package/compose/instructions_ui_runtime.py +2 -2
  33. package/compose/setup/START.md +1 -1
  34. package/docs/advanced-launch.md +4 -0
  35. package/docs/releases/0.19.4.md +99 -0
  36. package/docs/releases/0.20.0.md +102 -0
  37. package/docs/setup.md +4 -4
  38. package/install.sh +54 -20
  39. package/launch/agent-launch.py +171 -22
  40. package/launch/agent-launch.toml +64 -29
  41. package/launch/agent-launch.zsh +104 -13
  42. package/launch/claude_subcommands.py +179 -0
  43. package/launch/provision-venv.sh +1 -1
  44. package/launch/shell_integration.py +7 -1
  45. package/learn/collect-learning.py +60 -9
  46. package/learn/migrate-learnings.py +70 -4
  47. package/learn/redact.py +2 -1
  48. package/package.json +37 -4
  49. package/provenance.json +1 -1
  50. package/session-cost.py +141 -18
  51. package/session-distill/coverage.json +6 -0
  52. package/session-distill/distill.py +2575 -0
  53. package/session-distill/grammar/__init__.py +0 -0
  54. package/session-distill/grammar/owner_lines.py +874 -0
  55. package/session-distill/originators.json +9 -0
  56. package/session-distill/packets/cross_review.md +31 -0
  57. package/session-distill/packets/form.md +86 -0
  58. package/session-distill/packets/judge.md +81 -0
  59. package/session-distill/packets/placement_contract.md +90 -0
  60. package/session-distill/packets/propose.md +124 -0
  61. package/session-distill/packets/read.md +57 -0
  62. package/session-distill/packets/reconsider.md +53 -0
  63. package/session-distill/packets/s7b.md +65 -0
  64. package/session-distill/packets/s9b.md +39 -0
  65. package/session-distill/packets/stitch.md +35 -0
  66. package/session-distill/packets/sweep.md +33 -0
  67. package/session-distill/runlib/__init__.py +0 -0
  68. package/session-distill/runlib/bound.py +1102 -0
  69. package/session-distill/runlib/breaker.py +467 -0
  70. package/session-distill/runlib/census.py +2347 -0
  71. package/session-distill/runlib/claims.py +420 -0
  72. package/session-distill/runlib/controls.py +902 -0
  73. package/session-distill/runlib/coverage.py +881 -0
  74. package/session-distill/runlib/declare.py +888 -0
  75. package/session-distill/runlib/delivery_evidence.py +1145 -0
  76. package/session-distill/runlib/derive.py +812 -0
  77. package/session-distill/runlib/destinations.py +3072 -0
  78. package/session-distill/runlib/dispatch.py +7939 -0
  79. package/session-distill/runlib/drift.py +1077 -0
  80. package/session-distill/runlib/entry.py +401 -0
  81. package/session-distill/runlib/evidence.py +890 -0
  82. package/session-distill/runlib/exposure.py +1162 -0
  83. package/session-distill/runlib/gate.py +2727 -0
  84. package/session-distill/runlib/gitread.py +79 -0
  85. package/session-distill/runlib/inventory.py +19624 -0
  86. package/session-distill/runlib/journal.py +1919 -0
  87. package/session-distill/runlib/ledger.py +3210 -0
  88. package/session-distill/runlib/ledger_compat.py +101 -0
  89. package/session-distill/runlib/ledger_migration.py +190 -0
  90. package/session-distill/runlib/lifecycle_intake.py +693 -0
  91. package/session-distill/runlib/lineage.py +454 -0
  92. package/session-distill/runlib/measures.py +249 -0
  93. package/session-distill/runlib/monitor.py +1180 -0
  94. package/session-distill/runlib/operations.py +522 -0
  95. package/session-distill/runlib/packet.py +838 -0
  96. package/session-distill/runlib/placement.py +1769 -0
  97. package/session-distill/runlib/projection.py +4090 -0
  98. package/session-distill/runlib/ranking.py +740 -0
  99. package/session-distill/runlib/receipts.py +200 -0
  100. package/session-distill/runlib/records.py +1965 -0
  101. package/session-distill/runlib/search.py +249 -0
  102. package/session-distill/runlib/sequencing.py +829 -0
  103. package/session-distill/runlib/sources.py +641 -0
  104. package/session-distill/runlib/stage_adjudicate.py +845 -0
  105. package/session-distill/runlib/stage_apply.py +1378 -0
  106. package/session-distill/runlib/stage_approvals.py +758 -0
  107. package/session-distill/runlib/stage_close.py +1220 -0
  108. package/session-distill/runlib/stage_confirm.py +929 -0
  109. package/session-distill/runlib/stage_delivery.py +3080 -0
  110. package/session-distill/runlib/stage_form.py +2576 -0
  111. package/session-distill/runlib/stage_judge.py +4248 -0
  112. package/session-distill/runlib/stage_propose.py +3307 -0
  113. package/session-distill/runlib/stage_read.py +5179 -0
  114. package/session-distill/runlib/stage_render.py +2739 -0
  115. package/session-distill/runlib/stage_retrieve.py +924 -0
  116. package/session-distill/runlib/stage_review_korean.py +1002 -0
  117. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  118. package/session-distill/runlib/stagelock.py +412 -0
  119. package/session-distill/runlib/stop.py +1061 -0
  120. package/session-distill/runlib/targets.py +809 -0
  121. package/session-distill/runlib/usage.py +280 -0
  122. package/session-distill/runlib/validate.py +319 -0
  123. package/session-distill/runlib/views.py +4327 -0
  124. package/session-distill/schemas/adjudication.schema.json +35 -0
  125. package/session-distill/schemas/approval.schema.json +35 -0
  126. package/session-distill/schemas/census.schema.json +128 -0
  127. package/session-distill/schemas/checks.schema.json +207 -0
  128. package/session-distill/schemas/claim.schema.json +16 -0
  129. package/session-distill/schemas/confirmation.schema.json +24 -0
  130. package/session-distill/schemas/coverage.schema.json +66 -0
  131. package/session-distill/schemas/cross_review.schema.json +24 -0
  132. package/session-distill/schemas/event.schema.json +20 -0
  133. package/session-distill/schemas/evidence.schema.json +20 -0
  134. package/session-distill/schemas/expected_observation.schema.json +18 -0
  135. package/session-distill/schemas/form.schema.json +103 -0
  136. package/session-distill/schemas/intake.schema.json +71 -0
  137. package/session-distill/schemas/inventory.schema.json +872 -0
  138. package/session-distill/schemas/judge.schema.json +77 -0
  139. package/session-distill/schemas/ledger.schema.json +313 -0
  140. package/session-distill/schemas/observation.schema.json +16 -0
  141. package/session-distill/schemas/propose.schema.json +555 -0
  142. package/session-distill/schemas/read.schema.json +76 -0
  143. package/session-distill/schemas/reconsider.schema.json +122 -0
  144. package/session-distill/schemas/run.schema.json +150 -0
  145. package/session-distill/schemas/s7b.schema.json +200 -0
  146. package/session-distill/schemas/s9b.schema.json +28 -0
  147. package/session-distill/schemas/stitch.schema.json +25 -0
  148. package/session-distill/schemas/sweep.schema.json +25 -0
  149. package/session-distill/seats.json +149 -0
  150. package/session-distill/tables/allowed_pairs.json +257 -0
  151. package/session-distill/tables/controls.json +30 -0
  152. package/session-distill/tables/delivery_evidence.json +36 -0
  153. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  154. package/session-distill/tables/destinations.json +684 -0
  155. package/session-distill/tables/drift_layers.json +68 -0
  156. package/session-distill/tables/exposure_rules.json +192 -0
  157. package/session-distill/tables/placement_rules.json +148 -0
  158. package/session-distill/tables/propose_fixtures.json +154 -0
  159. package/session-distill/tables/ranking.json +194 -0
  160. package/session-distill/tables/redundancy.json +10 -0
  161. package/session-distill/tables/structural_rules.json +44 -0
  162. package/session-distill/tables/transition_fixtures.json +398 -0
  163. package/session-distill/tables/transitions.json +69 -0
  164. package/session-distill/tables/unit_outcome.json +67 -0
  165. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  166. package/wrappers/claude-run.sh +481 -33
  167. package/wrappers/claude_hermetic_evidence.py +1423 -0
  168. package/wrappers/codex-helm.sh +44 -13
  169. package/wrappers/codex-run.sh +183 -20
  170. package/wrappers/codex_frame_filter.py +1199 -0
  171. package/wrappers/codex_protocol.py +737 -0
  172. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,845 @@
1
+ #!/usr/bin/env python3
2
+ """S10 adjudicate (plan WP-20 K5; design §10.2; lead decisions E4(b) D-20261111-c48e9a and overlay (a)
3
+ D-20261112-995faf).
4
+
5
+ The owner's `판정` lines, which S10's parse part commits as a parse (`parsed.v<n>.json`, its `adjudications`), resolve
6
+ each disputed judgment of a candidate to a side or to the owner's own value. This part, once per committed parse:
7
+
8
+ 1. recomputes each adjudicated candidate's §6.4 derivation with those values. S6's own input for the candidate
9
+ (`stage_judge.given_from_run`) must still reproduce the outcome S6 stored (ADJUDICATION_BASE_MOVED otherwise);
10
+ each resolved requirement is then set to the chosen value for both judges, and `derive.unit_outcome` derives it
11
+ again. A candidate admitted this way carries the admission `adjudication`, the value S7's `awaiting_r` reads, so a
12
+ core item is awaiting_R and a personal one proceeds (E4(b)); derive's own answer stays beside it (`derived`);
13
+ 2. runs the newly admitted through S7 and S7b in a second pass of the same run: lane L's
14
+ `stage_propose.document(..., only=)` and `stage_review_proposals.document(..., only=)`, never their `run`, which
15
+ refuses a subset (SUBSET_IN_RUN) because it would overwrite the stage's whole output;
16
+ 3. writes, for parsed version n, `adjudicated-derivations.v<n>.json`, and when a candidate was newly admitted
17
+ `adjudicated-proposals.v<n>.json`, and when S7 proposed for any of them `adjudicated-review-s7b.v<n>.json`. Each is
18
+ written once (ADJUDICATED_ALREADY): a candidate is adjudicated in one parse, so its second pass is asked once.
19
+
20
+ S6's derivations.json and S7's proposals.json stay as first written. S9 and S9b declare these outputs as inputs, so
21
+ the shared record checks hold them, and lay them over S6's and S7's in version order (`overlay`): the next review
22
+ version shows each adjudicated candidate as recomputed, and a newly admitted one with its proposal and S7b's review.
23
+
24
+ The second pass's calls are not wired, as S7's and S7b's are not: a newly admitted candidate needs an answer
25
+ (CALL_NOT_WIRED when none is given), and S7b's reviews default to none, each proposal then listed unreviewed.
26
+
27
+ stage_adjudicate.py --self-test
28
+ """
29
+ import copy
30
+ import json
31
+ import pathlib
32
+ import re
33
+ import sys
34
+
35
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
36
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
37
+ from runlib import derive, placement, records, stage_judge, stage_propose, stage_review_proposals # noqa: E402
38
+ from runlib.records import Refused # noqa: E402
39
+
40
+ STAGE, PART = "S10", "adjudicate"
41
+ ADMITTED = "adjudication" # the admission stage_propose.awaiting_r reads for a candidate admitted this way
42
+ REQUIREMENT = "requirement/" # the judgment_ref prefix S10's parse writes (stage_render.disputed_of)
43
+ OUTPUT_NAMES = (r"adjudicated-derivations\.v(\d+)\.json", r"adjudicated-proposals\.v(\d+)\.json",
44
+ r"adjudicated-review-s7b\.v(\d+)\.json")
45
+
46
+
47
+ def outputs_of(version):
48
+ return (f"adjudicated-derivations.v{version}.json", f"adjudicated-proposals.v{version}.json",
49
+ f"adjudicated-review-s7b.v{version}.json")
50
+
51
+
52
+ def committed(run_dir):
53
+ """`{version: parse}` of every committed parse, S10's parse part's `parsed.v<n>.json`."""
54
+ out = {}
55
+ for path in sorted(pathlib.Path(run_dir).glob("parsed.v*.json")):
56
+ m = re.fullmatch(r"parsed\.v(\d+)\.json", path.name)
57
+ if m:
58
+ out[int(m.group(1))] = records.read_json(path)
59
+ return out
60
+
61
+
62
+ def adjudicated_ids(parse):
63
+ return sorted({a["candidate_id"] for a in parse.get("adjudications") or []})
64
+
65
+
66
+ def inputs_of(run_dir, version, parse):
67
+ """The parse, S6's derivations and summary, the S5 and S2 files `given_from_run` reads, and each adjudicated
68
+ candidate's own S6 files, every one through the shared record checks."""
69
+ specs = [{"artifact": f"parsed.v{version}.json", "producer_stage": "S10"},
70
+ {"artifact": stage_judge.DERIVATIONS, "producer_stage": "S6"},
71
+ {"artifact": stage_judge.SUMMARY, "producer_stage": "S6"},
72
+ {"artifact": "checked-candidates.json", "producer_stage": "S5"},
73
+ {"artifact": "checks.json", "producer_stage": "S5"},
74
+ {"artifact": "inventory/current.json", "producer_stage": "S2"}]
75
+ for cid in adjudicated_ids(parse):
76
+ specs += [{"artifact": rel, "producer_stage": "S6"} for rel in stage_judge.given_artifacts(run_dir, cid)]
77
+ return tuple(specs)
78
+
79
+
80
+ def recomputed(cid, given, s6_verdict, current, adjudication, earlier=()):
81
+ """`(verdict, problems)`: the candidate's derivation again, with each requirement the owner resolved set to the
82
+ chosen value for both judges: the values `earlier` adjudications resolved first, then this one's. `s6_verdict` is
83
+ S6's stored verdict, which `given` must reproduce before anything is changed in it; `current` the verdict the
84
+ owner last saw, S6's or an earlier adjudication's, which must still be disputed."""
85
+ problems = []
86
+ if derive.unit_outcome(given, {}, stage_judge.TEST_STATE) != s6_verdict.get("outcome"):
87
+ return None, [f"ADJUDICATION_BASE_MOVED {cid}: S6's own files no longer reproduce the derivation S6 stored, "
88
+ "so the owner's values would be applied to something the owner did not read"]
89
+ before = ((current.get("outcome") or {}).get("admission") or {}).get("admission")
90
+ if before != "disputed":
91
+ return None, [f"ADJUDICATION_NOT_DISPUTED {cid}: it is {before}, so there is no disputed judgment for the "
92
+ "owner's values to settle"]
93
+ names = derive.table()["requirements"]
94
+ held = copy.deepcopy(given)
95
+ for r in earlier:
96
+ for who in held["judges"]:
97
+ held["judges"][who]["requirements"][r["judgment_ref"][len(REQUIREMENT):]] = r["value"]
98
+ resolved = []
99
+ for r in adjudication.get("resolved") or []:
100
+ ref, value = r.get("judgment_ref") or "", (r.get("choice") or {}).get("value")
101
+ name = ref[len(REQUIREMENT):] if ref.startswith(REQUIREMENT) else None
102
+ if name not in names or value not in ("met", "unmet"):
103
+ problems.append(f"ADJUDICATION_UNREADABLE {cid}: {ref!r} = {value!r} is not a requirement and met or unmet")
104
+ continue
105
+ for who in held["judges"]:
106
+ held["judges"][who]["requirements"][name] = value
107
+ resolved.append({"judgment_ref": ref, "side": (r.get("choice") or {}).get("side"), "value": value})
108
+ if problems:
109
+ return None, problems
110
+ outcome = derive.unit_outcome(held, {}, stage_judge.TEST_STATE)
111
+ derived = outcome["admission"]["admission"]
112
+ if derived == "admitted":
113
+ outcome["admission"] = {**outcome["admission"], "admission": ADMITTED, "derived": derived}
114
+ verdict = {**{k: v for k, v in s6_verdict.items() if k not in ("outcome", "requirements")}, "outcome": outcome,
115
+ "requirements": {who: held["judges"][who]["requirements"] for who in held["judges"]},
116
+ "adjudication": {"adjudication_id": adjudication["adjudication_id"], "resolved": resolved,
117
+ "earlier": list(earlier), "before": before, "derived": derived}}
118
+ return verdict, []
119
+
120
+
121
+ def document(version, parse, derivations, candidates, given_of, answers=None, reviews=None, earlier=(), ask=None):
122
+ """`(derivations_doc, proposals_doc, review_doc, problems)` for one committed parse. `given_of(cid)` is S6's input
123
+ for a candidate; `earlier` the adjudicated documents of earlier versions, laid under this one's. `ask` is the
124
+ second pass's supervised calls (`SecondPass`): where the caller hands no answers it asks S7 for the newly
125
+ admitted, and where the caller hands no reviews it asks S7b for what S7 proposed."""
126
+ s6 = (derivations or {}).get("verdicts") or {}
127
+ verdicts = dict(s6)
128
+ for held in earlier:
129
+ verdicts.update((held.get("derivations") or {}).get("verdicts") or {})
130
+ out, problems, rows = {}, [], []
131
+ for adj in sorted(parse.get("adjudications") or [], key=lambda a: a["candidate_id"]):
132
+ cid = adj["candidate_id"]
133
+ if cid in out:
134
+ problems.append(f"ADJUDICATED_TWICE {cid}: one parse holds two adjudications of it")
135
+ continue
136
+ if cid not in verdicts:
137
+ problems.append(f"ADJUDICATION_UNACCOUNTED {cid}: S6 derived no such candidate")
138
+ continue
139
+ try:
140
+ given = given_of(cid)
141
+ except records.RunStopped: # a stopped run stops here too, never read as a missing input
142
+ raise
143
+ except (Refused, OSError, KeyError, ValueError) as exc:
144
+ problems.append(f"ADJUDICATION_BASE_MISSING {cid}: S6's input for it could not be read ({exc})")
145
+ continue
146
+ settled = verdicts[cid].get("adjudication") or {}
147
+ verdict, found = recomputed(cid, given, s6[cid], verdicts[cid], adj,
148
+ list(settled.get("earlier") or []) + list(settled.get("resolved") or []))
149
+ problems += found
150
+ if verdict is not None:
151
+ out[cid] = verdict
152
+ rows.append({"candidate_id": cid, "adjudication_id": adj["adjudication_id"], "before": "disputed",
153
+ "derived": verdict["adjudication"]["derived"],
154
+ "admission": verdict["outcome"]["admission"]["admission"]})
155
+ newly = sorted(cid for cid, v in out.items() if v["outcome"]["admission"]["admission"] == ADMITTED)
156
+ answers, reviews = dict(answers or {}), dict(reviews or {})
157
+ problems += [f"ANSWER_UNASKED {cid}: the second pass asks S7 only for the newly admitted"
158
+ for cid in sorted(set(answers) - set(newly))]
159
+ proposals_doc = review_doc = None
160
+ if newly and not problems:
161
+ merged = {**(derivations or {}), "verdicts": {**verdicts, **out}}
162
+ if not answers and ask is not None:
163
+ answers = ask.answers(newly, merged)
164
+ if not answers:
165
+ problems.append(f"CALL_NOT_WIRED adjudicate: S7's second pass is asked for {', '.join(newly)}, and it was "
166
+ "given neither answers in hand nor a supervisor to ask through (--answers PATH, or "
167
+ "--cells DIR)")
168
+ else:
169
+ proposals_doc = stage_propose.document(merged, candidates, answers, only=newly)
170
+ proposed = [p["candidate_id"] for p in proposals_doc["proposals"]]
171
+ problems += [f"REVIEW_UNASKED {cid}: S7b's second pass reviews only what S7 proposed in it"
172
+ for cid in sorted(set(reviews) - set(proposed))]
173
+ if proposed and not problems:
174
+ if not reviews and ask is not None:
175
+ reviews = ask.reviews(proposals_doc, proposed)
176
+ review_doc = stage_review_proposals.document(proposals_doc, reviews, only=proposed)
177
+ names = outputs_of(version)
178
+ doc = {"stage": STAGE, "part": PART, "version": version, "parse_seq": parse.get("parse_seq"),
179
+ "verdicts": out, "adjudicated": rows, "newly_admitted": newly,
180
+ "second_pass": {"proposals": names[1] if proposals_doc is not None else None,
181
+ "review": names[2] if review_doc is not None else None},
182
+ "counts": {"adjudicated": len(rows), "admitted": len(newly),
183
+ "rejected": sum(1 for r in rows if r["admission"] == "rejected"),
184
+ "still_disputed": sum(1 for r in rows if r["admission"] == "disputed")}}
185
+ return doc, proposals_doc, review_doc, problems
186
+
187
+
188
+ # ---- the second pass's supervised calls (release 1) ---------------------------------------------------------------
189
+ # A parse is adjudicated ONCE, so a second pass that wrote its documents over a call that did not end would fix
190
+ # "no proposal" for that candidate for good. The calls therefore all end accepted or nothing is written
191
+ # (SECOND_PASS_INCOMPLETE): a re-run asks again and reuses every accepted attempt. The seats are S7's and S7b's own
192
+ # models declared for THIS stage, since the dispatcher admits a seat only for the stage that declares it.
193
+ PROPOSE_SEAT_KEY, REVIEW_SEAT_KEY = "S10.propose", "S10.review"
194
+
195
+
196
+ class SecondPass:
197
+ """S7 and S7b asked again for the candidates an adjudication newly admitted, through `supervisor`."""
198
+
199
+ def __init__(self, run_dir, declaration, supervisor, candidates, tranche="calibration"):
200
+ self.run_dir, self.declaration, self.supervisor = pathlib.Path(run_dir), declaration, supervisor
201
+ self.rows = {r["candidate_id"]: r for r in (candidates or {}).get("candidates") or []}
202
+ self.tranche, self.calls = tranche, []
203
+ self.checks = {r["candidate_id"]: r for r in records.read_json(self.run_dir / "checks.json")["candidates"]}
204
+ self.current = {u["unit_id"]: u for u in
205
+ records.read_json(self.run_dir / "inventory" / "current.json")["units"]}
206
+ episode = declaration["budget"]["per_episode"]
207
+ self.caps = {"tokens": episode["tokens"], "compactions": episode["compactions"]}
208
+
209
+ def _seat(self, key):
210
+ seat = ((self.declaration or {}).get("seats") or {}).get(key)
211
+ if not seat:
212
+ raise Refused(f"SEAT_UNDECLARED {key}: the second pass's seat is named by run.json's seats")
213
+ return seat
214
+
215
+ def _item(self, kind, cid):
216
+ import hashlib
217
+ return kind + hashlib.sha256(cid.encode("utf-8")).hexdigest()[:12]
218
+
219
+ def _ask(self, kind, cid, seat, text, schema_bytes, case, cap, check, code):
220
+ from runlib import gate, stage_judge
221
+ limits = stage_judge.limits_of(seat, self.run_dir, self.declaration, self.supervisor.seats_path, case=case,
222
+ output_cap=cap, stage=STAGE)
223
+ out = self.supervisor.item(
224
+ STAGE, self._item(kind, cid), seat, text, json.loads(schema_bytes.decode("utf-8")), case_type=case,
225
+ caps=self.caps, view_window=False, tranche=self.tranche, max_output_tokens=cap, resume=True,
226
+ context_capacity=limits["capacity"], stage_check=check(limits["capacity"]),
227
+ packet_check=lambda built: stage_judge.attempt_problems(built, limits, schema_bytes, STAGE, code=code))
228
+ self.calls.append({"candidate_id": cid, "kind": kind, **stage_judge.call_row(out)})
229
+ return gate.accepted(pathlib.Path(out["accepted"]), judged=True) if out["outcome"] == "accepted" else None
230
+
231
+ def _incomplete(self, who):
232
+ failed = [c for c in self.calls if c["outcome"] != "accepted"]
233
+ if failed:
234
+ raise Refused(f"SECOND_PASS_INCOMPLETE adjudicate: {who}'s call for "
235
+ + ", ".join(f"{c['candidate_id']} ended {c['outcome']}"
236
+ + (f" ({', '.join(c['codes'])})" if c["codes"] else "") for c in failed)
237
+ + "; nothing is written, and a re-run asks again")
238
+
239
+ def answers(self, newly, merged):
240
+ """`{cid: answer}` for every newly admitted candidate, each with its before-states set by code."""
241
+ seat = self._seat(PROPOSE_SEAT_KEY)
242
+ checkout = ((self.declaration or {}).get("destinations") or {}).get("checkout")
243
+ if not checkout or not pathlib.Path(checkout).is_dir():
244
+ raise Refused("CHECKOUT_UNDECLARED S10: an operation's before-state is read from the declared checkout")
245
+ verdicts, out = merged.get("verdicts") or {}, {}
246
+ for cid in newly:
247
+ row = self.rows.get(cid) or {"candidate_id": cid}
248
+ text = stage_propose.payload_for(row, merged, verdicts.get(cid),
249
+ stage_propose.unit_rows(self.checks.get(cid), self.current, checkout),
250
+ None)
251
+ held = self._ask("p", cid, seat, text, stage_propose.schema_bytes(), stage_propose.CASE,
252
+ stage_propose.OUTPUT_CAP,
253
+ lambda capacity, row=row, cid=cid: stage_propose.live_check(
254
+ row, merged, verdicts.get(cid), False, checkout, capacity),
255
+ "PROPOSE_OVER_CAPACITY")
256
+ if held is not None:
257
+ out[cid] = stage_propose.with_before_states(held, checkout)[0]
258
+ self._incomplete("S7")
259
+ return out
260
+
261
+ def reviews(self, proposals_doc, proposed):
262
+ """`{cid: review}` for every proposal the second pass's S7 made."""
263
+ seat = self._seat(REVIEW_SEAT_KEY)
264
+ by_id, out = {p["candidate_id"]: p for p in proposals_doc["proposals"]}, {}
265
+ for cid in proposed:
266
+ text = stage_review_proposals.payload_for(self.rows.get(cid) or {"candidate_id": cid}, by_id[cid],
267
+ stage_propose.unit_rows(self.checks.get(cid), self.current))
268
+ held = self._ask("b", cid, seat, text, stage_review_proposals.schema_bytes(),
269
+ stage_review_proposals.CASE, stage_review_proposals.OUTPUT_CAP,
270
+ lambda capacity, cid=cid: stage_review_proposals.live_check(by_id[cid], capacity),
271
+ "REVIEW_OVER_CAPACITY")
272
+ if held is not None:
273
+ out[cid] = held
274
+ self._incomplete("S7b")
275
+ return out
276
+
277
+
278
+ def run(run_dir, version=None, answers=None, reviews=None, *, supervisor=None, tranche="calibration"):
279
+ """S10's adjudicate part for one committed parse (default: the latest with adjudications), through the shared
280
+ mechanism: nothing is written on refusal, and a parse is adjudicated once (ADJUDICATED_ALREADY). With
281
+ `supervisor`, the second pass's answers and reviews are what its calls return (`SecondPass`)."""
282
+ if supervisor is not None and (answers is not None or reviews is not None):
283
+ raise Refused("INPUT_INVALID adjudicate: answers in hand and a supervisor are two sources for one second pass")
284
+ run_dir = pathlib.Path(run_dir)
285
+ parses = committed(run_dir)
286
+ held = {v: p for v, p in parses.items() if p.get("adjudications")}
287
+ if version is None:
288
+ if not held:
289
+ raise Refused("NOTHING_TO_ADJUDICATE S10: no committed parse holds an adjudication")
290
+ version = max(held, key=lambda v: held[v].get("parse_seq") or 0)
291
+ if version not in parses:
292
+ raise Refused(f"PARSE_ABSENT v{version}: no committed parse of that version")
293
+ if version not in held:
294
+ raise Refused(f"NOTHING_TO_ADJUDICATE v{version}: its parse holds no adjudication")
295
+ names = outputs_of(version)
296
+ part = ((records.stage_records(run_dir).get(STAGE) or {}).get("parts") or {}).get(PART) or {}
297
+ resumed = (run_dir / names[0]).exists()
298
+ if resumed and part.get("status") == "complete" and names[0] in {o["artifact"] for o in part.get("outputs") or []}:
299
+ raise Refused(f"ADJUDICATED_ALREADY v{version}: a parse's adjudications are recomputed once, so a candidate's "
300
+ "second pass is asked once")
301
+ parse = parses[version]
302
+ with records.run_stage(run_dir, STAGE, inputs_of(run_dir, version, parse), part=PART) as stage:
303
+ if resumed: # written before a run was cut short: registered now, never computed or asked again
304
+ for v in versions_written(run_dir):
305
+ for rel in outputs_of(v):
306
+ if (run_dir / rel).is_file():
307
+ stage.output(rel)
308
+ return {"version": version, "resumed": True, **records.read_json(run_dir / names[0])["counts"]}
309
+ earlier = [read_version(run_dir, v) for v in versions_written(run_dir) if v != version]
310
+ derivations = records.read_json(run_dir / stage_judge.DERIVATIONS)
311
+ candidates = records.read_json(run_dir / "checked-candidates.json")
312
+ ask = None
313
+ if supervisor is not None:
314
+ supervisor.interrupted(STAGE)
315
+ ask = SecondPass(run_dir, stage.declaration, supervisor, candidates, tranche)
316
+ doc, proposals_doc, review_doc, problems = document(
317
+ version, parse, derivations, candidates, lambda cid: stage_judge.given_from_run(run_dir, cid),
318
+ answers, reviews, earlier, ask)
319
+ if problems:
320
+ raise Refused("\n".join(problems))
321
+ # the second pass's documents first, so the derivations' document names files that are there
322
+ for rel, held_doc in ((names[1], proposals_doc), (names[2], review_doc)):
323
+ if held_doc is not None:
324
+ records.write_json(run_dir, run_dir / rel, held_doc)
325
+ records.write_json(run_dir, run_dir / names[0], doc)
326
+ for v in versions_written(run_dir):
327
+ for rel in outputs_of(v):
328
+ if (run_dir / rel).is_file():
329
+ stage.output(rel)
330
+ return {"version": version, "resumed": False, **doc["counts"],
331
+ **({"calls": len(ask.calls)} if ask is not None else {})}
332
+
333
+
334
+ def versions_written(run_dir):
335
+ """Every version whose adjudicated derivations are on disk, in order."""
336
+ return sorted(int(m.group(1)) for p in pathlib.Path(run_dir).glob("adjudicated-derivations.v*.json")
337
+ for m in [re.fullmatch(OUTPUT_NAMES[0], p.name)] if m)
338
+
339
+
340
+ def read_version(run_dir, version):
341
+ """`{version, derivations, proposals, review}` of one adjudicated version, its absent parts None."""
342
+ names = outputs_of(version)
343
+ run_dir = pathlib.Path(run_dir)
344
+ return {"version": version,
345
+ **{key: records.read_json(run_dir / rel) if (run_dir / rel).is_file() else None
346
+ for key, rel in zip(("derivations", "proposals", "review"), names)}}
347
+
348
+
349
+ # ---- the overlay S9 and S9b read (overlay decision (a)) -------------------------------------------------------------
350
+
351
+ def adjudicated_inputs(run_dir):
352
+ """S10's adjudicate part's outputs as a later stage's inputs: none when the part never ran; refused when its
353
+ record is not complete (ADJUDICATION_UNSETTLED), since what it would lay over S6 and S7 is not there to read."""
354
+ rec = records.stage_records(pathlib.Path(run_dir)).get(STAGE) or {}
355
+ part = (rec.get("parts") or {}).get(PART)
356
+ if part is None:
357
+ return ()
358
+ if part.get("status") != "complete":
359
+ raise Refused(f"ADJUDICATION_UNSETTLED: S10's adjudicate part is {part.get('status')!r}, so the "
360
+ "recomputed derivations are not there; run it to completion before rendering again")
361
+ names = [o["artifact"] for o in part.get("outputs") or []]
362
+ stray = [n for n in names if not any(re.fullmatch(p, n) for p in OUTPUT_NAMES)]
363
+ if stray:
364
+ raise Refused(f"ADJUDICATION_UNSETTLED: the adjudicate part names {stray}, which it does not write")
365
+ return tuple({"artifact": n, "producer_stage": STAGE} for n in sorted(names))
366
+
367
+
368
+ def read_inputs(run_dir, specs):
369
+ """The adjudicated versions the specs name, in version order."""
370
+ versions = sorted({int(m.group(1)) for s in specs for m in [re.fullmatch(OUTPUT_NAMES[0], s["artifact"])] if m})
371
+ return [read_version(run_dir, v) for v in versions]
372
+
373
+
374
+ def overlay(derivations, proposals, s7b, adjudicated):
375
+ """`(derivations, proposals, s7b, problems)`: S6's derivations, S7's proposals and S7b's review with each
376
+ adjudicated version laid over them in version order. A recomputed verdict replaces S6's; a second-pass proposal,
377
+ return or review replaces whatever S7 or S7b held for that candidate. An entry for a candidate S6 never derived,
378
+ or a second-pass entry for one its version did not newly admit, is refused by name (OVERLAY_UNACCOUNTED)."""
379
+ derivations = copy.deepcopy(derivations or {})
380
+ proposals = copy.deepcopy(proposals or {})
381
+ s7b = copy.deepcopy(s7b or {})
382
+ verdicts = derivations.setdefault("verdicts", {})
383
+ problems = []
384
+ for held in adjudicated:
385
+ dv = held.get("derivations") or {}
386
+ for cid, verdict in sorted((dv.get("verdicts") or {}).items()):
387
+ if cid not in verdicts:
388
+ problems.append(f"OVERLAY_UNACCOUNTED {cid}: v{held['version']}'s adjudication recomputed a candidate "
389
+ "S6 never derived")
390
+ continue
391
+ verdicts[cid] = {**verdict, "adjudication": {**verdict.get("adjudication", {}),
392
+ "version": held["version"]}}
393
+ ids, found = second_pass_ids(held)
394
+ problems += found
395
+ second = held.get("proposals") or {}
396
+ for key in ("proposals", "returned"):
397
+ proposals[key] = [p for p in proposals.get(key) or [] if p["candidate_id"] not in ids] + [
398
+ p for p in second.get(key) or [] if p["candidate_id"] in ids]
399
+ problems += _lay_review(s7b, held, ids)
400
+ return derivations, proposals, s7b, problems
401
+
402
+
403
+ def second_pass_ids(held):
404
+ """`(ids, problems)`: the candidates one adjudicated version's second pass answered and its adjudication newly
405
+ admitted; an answer for any other candidate is refused by name (OVERLAY_UNACCOUNTED)."""
406
+ newly = set(((held.get("derivations") or {}).get("newly_admitted")) or [])
407
+ second = held.get("proposals") or {}
408
+ ids = {p["candidate_id"] for p in second.get("proposals") or []} | {
409
+ r["candidate_id"] for r in second.get("returned") or []}
410
+ problems = [f"OVERLAY_UNACCOUNTED {cid}: v{held['version']}'s second pass answered a candidate its "
411
+ "adjudication did not newly admit" for cid in sorted(ids - newly)]
412
+ return ids & newly, problems
413
+
414
+
415
+ def _lay_review(s7b, held, ids):
416
+ """Lay one adjudicated version's second-pass review over `s7b` in place, for `ids`; the problems, by name."""
417
+ review = held.get("review") or {}
418
+ reviewed = {r["item_id"] for key in ("reviews", "returned", "unreviewed") for r in review.get(key) or []}
419
+ problems = [f"OVERLAY_UNACCOUNTED {cid}: v{held['version']}'s second-pass review answered a proposal "
420
+ "its second pass did not make" for cid in sorted(reviewed - ids)]
421
+ for key in ("reviews", "returned", "unreviewed"):
422
+ s7b[key] = [r for r in s7b.get(key) or [] if r["item_id"] not in ids] + [
423
+ r for r in review.get(key) or [] if r["item_id"] in ids]
424
+ return problems
425
+
426
+
427
+ def overlay_review(s7b, adjudicated):
428
+ """`(s7b, problems)`: S7b's review with each adjudicated version's second-pass review laid over it in version
429
+ order, exactly as `overlay` lays it for S9, for a stage that reads S7b's review and not S6's or S7's documents
430
+ (S10b holds an adopted alternative to the review S9 rendered; Codex WP-20 r1 F5)."""
431
+ s7b = copy.deepcopy(s7b or {})
432
+ problems = []
433
+ for held in adjudicated:
434
+ ids, found = second_pass_ids(held)
435
+ problems += found + _lay_review(s7b, held, ids)
436
+ return s7b, problems
437
+
438
+
439
+ # ---- self-test ------------------------------------------------------------------------------------------------------
440
+
441
+ HERE = pathlib.Path(__file__).resolve().parents[1]
442
+
443
+
444
+ def fx_given(cid, b_marks=None, lineages=3):
445
+ """A synthetic S6 input for one candidate in the shape a release-1 run hands derive (`stage_judge.derivation_input`):
446
+ the current point only, incomplete as the literal policy reads every real one, with two units both judges find
447
+ covering - a redundancy candidate, so its diagnosis is `redundant` and its kind `unclassified`, and `reduce` by a
448
+ merge is the library-changing disposition release 1 can reach (above the bar); every requirement met by A, and by
449
+ B but for `b_marks`; enough lineages to be eligible. No release point: S6 judges none (D-20261111-c4fa71)."""
450
+ names = derive.table()["requirements"]
451
+ covers = {"situation": "yes", "action": "yes", "following": None, "contribution": None}
452
+ point = {"complete": False, "layers": {"catalog": "complete", "native_settings": "unknown"},
453
+ "units": {unit: {"A": dict(covers), "B": dict(covers)} for unit in ("u1", "u2")}}
454
+ return {"candidate": {"candidate_id": cid, "type": "D", "lifecycle": "redundancy_hint"},
455
+ "judges": {who: {"requirements": {n: ((b_marks or {}).get(n, "met") if who == "B" else "met") for n in names},
456
+ "consequence_class": "quality", "no_longer_arises": False} for who in ("A", "B")},
457
+ "points": {"current": point}, "checks_pass": True, "lineages": lineages, "arc_confirmed": False}
458
+
459
+
460
+ def fx_merge(layer="guides", carrier="claude/guides/g.md", **over):
461
+ """An S7 answer reducing fx_given's redundant pair by a merge, carrying release 1's named states."""
462
+ return stage_propose._answered(disposition="reduce", destination={"layer": layer, "carrier": carrier},
463
+ operations=[{"type": "merge", "target": f"{carrier}#one", "units": ["u1", "u2"],
464
+ "before_state_sha256": "c" * 64, "content": "one bullet for both"}],
465
+ unknowns=stage_propose._carry(stage_propose.RELEASE_1), **over)
466
+
467
+
468
+ def fx_verdict(given):
469
+ """S6's stored verdict for `given`, wrapped as stage_judge.derive_stage wraps it."""
470
+ return {"outcome": derive.unit_outcome(given, {}, stage_judge.TEST_STATE),
471
+ "requirements": {who: dict(given["judges"][who]["requirements"]) for who in ("A", "B")},
472
+ "lineages": given["lineages"]}
473
+
474
+
475
+ def fx_adjudication(cid, resolved, ident=None):
476
+ return {"adjudication_id": ident or f"J-{cid}", "candidate_id": cid,
477
+ "resolved": [{"judgment_ref": f"{REQUIREMENT}{name}", "choice": {"side": side, "value": value}}
478
+ for name, side, value in resolved], "rationale": "소유자 메모"}
479
+
480
+
481
+ def self_test():
482
+ """The suite under the release scope `all`: the contract as designed, which release 1 holds closed
483
+ (`placement.scoped`), so the second pass S7 runs for an adjudicated item keeps the path the redesign reopens
484
+ held by its controls."""
485
+ with placement.scoped("all"):
486
+ return _self_test_all()
487
+
488
+
489
+ def _self_test_all():
490
+ """Document-level controls over synthetic disputed candidates first; then the stage end to end on S6's golden run
491
+ with planted disputes: S9 renders them, the owner's 판정 lines are parsed by S10, this part runs, S9 renders again
492
+ and S9b reads the result; then the driver's command as a process."""
493
+ import inspect
494
+ import shutil
495
+ import subprocess
496
+ import tempfile
497
+ failures, ran = [], []
498
+
499
+ def control(name, got, want):
500
+ ran.append(name)
501
+ if not isinstance(got, str):
502
+ raise TypeError(f"CONTROL_GOT_NOT_STR {name}: {type(got).__name__}")
503
+ if want not in got:
504
+ failures.append((name, f"expected {want!r} in {got[:600]!r}"))
505
+
506
+ def equal(name, got, want):
507
+ ran.append(name)
508
+ if got != want:
509
+ failures.append((name, f"expected {want!r}, got {got!r}"[:900]))
510
+
511
+ def clean(name, problems):
512
+ equal(name, list(problems), [])
513
+
514
+ def said(call):
515
+ try:
516
+ return f"returned {call()!r}"[:300]
517
+ except Refused as exc:
518
+ return str(exc)
519
+
520
+ def finish():
521
+ if failures:
522
+ for label, detail in failures:
523
+ print(f"stage_adjudicate --self-test [FAIL] {label}: {detail}", file=sys.stderr)
524
+ print(f"stage_adjudicate --self-test: FAILED ({len(failures)} of {len(ran)} controls)", file=sys.stderr)
525
+ return 1
526
+ print(f"stage_adjudicate --self-test: OK ({len(ran)} controls: the owner's values recompute S6's own input and "
527
+ "nothing else, over a fixture in the shape S6 hands derive; a candidate admitted this way is awaiting_R "
528
+ "when core and proceeds when personal; the second pass through S7's and S7b's document, never their run; "
529
+ "S9 and S9b lay it over S6 and S7 in version order)")
530
+ return 0
531
+
532
+ # ---- the document, over synthetic disputed candidates --------------------------------------------------------
533
+ # the fixture is held to what S6 really builds: derivation_input over two judges' judgments, compared by shape
534
+ first = {who: {"requirements": {n: {"mark": "met"} for n in derive.table()["requirements"]},
535
+ "consequence_class": "quality", "no_longer_arises": {"value": False},
536
+ "units": [{"unit_id": u, "situation": "yes", "action": "yes"} for u in ("u1", "u2")]}
537
+ for who in ("A", "B")}
538
+ real = stage_judge.derivation_input({"candidate_id": "k-shape", "type": "D"}, "redundancy_hint", {}, first, {},
539
+ {"complete": False, "layers": {}})
540
+ fixture = fx_given("k-shape")
541
+ equal("the fixture is the shape S6 hands derive: the current point only, its units and lifecycle as S6 builds them",
542
+ (sorted(fixture["points"]), sorted(fixture), fixture["candidate"]["lifecycle"],
543
+ fixture["points"]["current"]["units"]),
544
+ (sorted(real["points"]), sorted(real), real["candidate"]["lifecycle"], real["points"]["current"]["units"]))
545
+ try:
546
+ read_as = (lambda o: (o["unit_outcomes"], o["candidate_diagnosis"]["release"]["row"], o["kind"]["kind"],
547
+ o["candidate_diagnosis"]["current"]["diagnosis"]))(fx_verdict(fixture)["outcome"])
548
+ except Refused as exc:
549
+ read_as = str(exc)
550
+ equal("and derive reads it as release 1 reads every candidate: no unit outcome, the release point absent, kind "
551
+ "unclassified, the redundant pair's diagnosis",
552
+ read_as, ([], "absent", "unclassified", "redundant"))
553
+ if failures: # every control below is built on this fixture, so one not in S6's shape stops the suite here
554
+ return finish()
555
+ givens = {"k-core": fx_given("k-core", {"bounded": "uncertain"}),
556
+ "k-personal": fx_given("k-personal", {"bounded": "uncertain"}),
557
+ "k-reject": fx_given("k-reject", {"bounded": "uncertain"}),
558
+ "k-two": fx_given("k-two", {"bounded": "uncertain", "positioned": "uncertain"}),
559
+ "k-agreed": fx_given("k-agreed")}
560
+ derivations = {**copy.deepcopy(stage_propose.RELEASE_1), "verdicts": {c: fx_verdict(g) for c, g in givens.items()},
561
+ "not_derived": []}
562
+ candidates = {"candidates": [{"candidate_id": c, "type": "D"} for c in givens]}
563
+ parse = {"version": 1, "parse_seq": 1, "adjudications": [
564
+ fx_adjudication("k-core", [("bounded", "A", "met")]),
565
+ fx_adjudication("k-personal", [("bounded", "own", "met")]),
566
+ fx_adjudication("k-reject", [("bounded", "own", "unmet")]),
567
+ fx_adjudication("k-two", [("bounded", "A", "met")])]}
568
+ answers = {"k-core": fx_merge(requires_R=True), "k-personal": fx_merge("personal", "notes/own.md")}
569
+
570
+ def doc(parse_=None, derivations_=None, answers_=answers, reviews=None, given_of=None, earlier=()):
571
+ return document(1, parse_ or parse, derivations_ or derivations, candidates,
572
+ given_of or (lambda cid: copy.deepcopy(givens[cid])), answers_, reviews, earlier)
573
+ dv, props, review, problems = doc()
574
+ clean("four adjudications recompute with nothing refused", problems)
575
+ admissions = {c: (v["outcome"]["admission"]["admission"], v["adjudication"]["derived"])
576
+ for c, v in dv["verdicts"].items()}
577
+ equal("admitted by the owner's values is admission `adjudication`, derive's own answer beside it; unmet is "
578
+ "rejected; one of two disputes resolved leaves it disputed",
579
+ admissions, {"k-core": ("adjudication", "admitted"), "k-personal": ("adjudication", "admitted"),
580
+ "k-reject": ("rejected", "rejected"), "k-two": ("disputed", "disputed")})
581
+ equal("only the newly admitted go through the second pass, and the counts say what happened",
582
+ (dv["newly_admitted"], (props or {}).get("subset"), dv["counts"]),
583
+ (["k-core", "k-personal"], ["k-core", "k-personal"],
584
+ {"adjudicated": 4, "admitted": 2, "rejected": 1, "still_disputed": 1}))
585
+ marks = dv["verdicts"].get("k-core", {}).get("requirements", {})
586
+ equal("the owner's value is set for both judges on the resolved requirement only, every other mark as S6 had it",
587
+ {who: {n: m for n, m in (marks.get(who) or {}).items() if m != givens["k-core"]["judges"][who]["requirements"][n]}
588
+ for who in ("A", "B")}, {"A": {}, "B": {"bounded": "met"}})
589
+ held = {p["candidate_id"]: (p["awaiting_R"], p["awaiting_R_reason"][:40]) for p in (props or {}).get("proposals") or []}
590
+ equal("E4(b): the core item admitted by adjudication is awaiting_R, and the personal one proceeds",
591
+ (held.get("k-core", (None,))[0], held.get("k-personal", (None,))[0]), (True, False))
592
+ equal("S7b's second pass covers exactly what S7 proposed in it, each named unreviewed without a review",
593
+ ((review or {}).get("subset"), sorted(r["item_id"] for r in (review or {}).get("unreviewed") or [])),
594
+ (["k-core", "k-personal"], ["k-core", "k-personal"]))
595
+ no_r = {**answers, "k-core": fx_merge()}
596
+ _d, props_no_r, _r, _p = doc(answers_=no_r)
597
+ control("a core item admitted by adjudication whose answer does not say requires_R is returned by S7's own rule",
598
+ json.dumps((props_no_r or {}).get("returned") or []), "REQUIRES_R_ABSENT k-core")
599
+ moved = copy.deepcopy(derivations)
600
+ moved["verdicts"]["k-core"]["outcome"]["kind"]["kind"] = "misfire"
601
+ control("an input that no longer reproduces S6's stored derivation is refused by name",
602
+ "\n".join(doc(derivations_=moved)[3]), "ADJUDICATION_BASE_MOVED k-core")
603
+ control("a candidate S6 did not leave disputed is not adjudicated",
604
+ "\n".join(doc(parse_={**parse, "adjudications": [fx_adjudication("k-agreed", [("bounded", "A", "met")])]})[3]),
605
+ "ADJUDICATION_NOT_DISPUTED k-agreed")
606
+ control("a resolved judgment that is no requirement, or no met or unmet, is refused by name",
607
+ "\n".join(doc(parse_={**parse, "adjudications": [fx_adjudication("k-core", [("tone", "A", "met")])]})[3]),
608
+ "ADJUDICATION_UNREADABLE k-core")
609
+ control("an adjudication of a candidate S6 never derived is refused by name",
610
+ "\n".join(doc(parse_={**parse, "adjudications": [fx_adjudication("k-zz", [("bounded", "A", "met")])]})[3]),
611
+ "ADJUDICATION_UNACCOUNTED k-zz")
612
+ control("one parse adjudicating a candidate twice is refused by name",
613
+ "\n".join(doc(parse_={**parse, "adjudications": parse["adjudications"] + [
614
+ fx_adjudication("k-core", [("bounded", "B", "met")], "J-again")]})[3]), "ADJUDICATED_TWICE k-core")
615
+ control("an S6 input that cannot be read is named, not fatal",
616
+ "\n".join(doc(given_of=lambda cid: {}["missing"])[3]), "ADJUDICATION_BASE_MISSING k-core")
617
+ control("an answer for a candidate the second pass did not ask about is refused by name",
618
+ "\n".join(doc(answers_={**answers, "k-reject": answers["k-core"]})[3]), "ANSWER_UNASKED k-reject")
619
+ control("a review for a proposal the second pass did not make is refused by name",
620
+ "\n".join(doc(reviews={"k-reject": {}})[3]), "REVIEW_UNASKED k-reject")
621
+ control("newly admitted candidates with no answers say the call is not wired",
622
+ "\n".join(doc(answers_=None)[3]), "CALL_NOT_WIRED adjudicate: S7's second pass is asked for k-core, k-personal")
623
+ _d, props_none, review_none, problems_none = doc(parse_={**parse, "adjudications": [parse["adjudications"][2]]},
624
+ answers_=None)
625
+ equal("a parse that admits nothing needs no answers and writes no second pass",
626
+ (problems_none, props_none, review_none, _d["second_pass"]), ([], None, None, {"proposals": None, "review": None}))
627
+ later_parse = {"version": 2, "parse_seq": 2, "adjudications": [fx_adjudication("k-two", [("positioned", "A", "met")])]}
628
+ later, _lp, _lr, later_problems = document(2, later_parse, derivations, candidates,
629
+ lambda cid: copy.deepcopy(givens[cid]),
630
+ {"k-two": fx_merge(requires_R=True)}, None,
631
+ [{"version": 1, "derivations": dv}])
632
+ equal("a later parse recomputes over an earlier version's values: the second of two disputes settled, it is "
633
+ "admitted, both values held",
634
+ (later_problems, later["verdicts"].get("k-two", {}).get("outcome", {}).get("admission", {}).get("admission"),
635
+ {n: later["verdicts"].get("k-two", {}).get("requirements", {}).get("B", {}).get(n)
636
+ for n in ("bounded", "positioned")}),
637
+ ([], "adjudication", {"bounded": "met", "positioned": "met"}))
638
+ source = inspect.getsource(sys.modules[__name__])
639
+ equal("the second pass goes through S7's and S7b's document, never their run (which refuses a subset)",
640
+ sorted(set(re.findall(r"stage_(?:propose|review_proposals)\.(document|run)\(", source.split("# ---- self-test")[0]))),
641
+ ["document"])
642
+
643
+ # ---- the overlay S9 and S9b read -----------------------------------------------------------------------------
644
+ s7 = {"proposals": [], "returned": [{"candidate_id": c, "problems": ["ANSWER_ABSENT"]} for c in givens]}
645
+ s7b_doc = {"reviews": [], "returned": [], "unreviewed": []}
646
+ # the second pass's documents as written, or empty ones when a reverted rule left none, so each control below
647
+ # fails by name rather than the suite ending on a missing document
648
+ v1 = {"version": 1, "derivations": dv, "proposals": props or {"proposals": [], "returned": []},
649
+ "review": review or {"reviews": [], "returned": [], "unreviewed": []}}
650
+ laid_dv, laid_props, laid_s7b, laid_problems = overlay(derivations, s7, s7b_doc, [v1])
651
+ clean("the overlay lays version 1 over S6, S7 and S7b with nothing refused", laid_problems)
652
+ equal("a recomputed verdict replaces S6's and names its version; a second-pass proposal replaces S7's return",
653
+ (laid_dv["verdicts"].get("k-core", {}).get("adjudication", {}).get("version"),
654
+ laid_dv["verdicts"]["k-agreed"] == derivations["verdicts"]["k-agreed"],
655
+ sorted(p["candidate_id"] for p in laid_props["proposals"]),
656
+ sorted(r["candidate_id"] for r in laid_props["returned"]),
657
+ sorted(r["item_id"] for r in laid_s7b["unreviewed"])),
658
+ (1, True, ["k-core", "k-personal"], ["k-agreed", "k-reject", "k-two"], ["k-core", "k-personal"]))
659
+ equal("the documents laid over are left as they were", (s7["proposals"], derivations["verdicts"]["k-core"] ==
660
+ fx_verdict(givens["k-core"])), ([], True))
661
+ stray = copy.deepcopy(v1)
662
+ stray["proposals"]["proposals"].append({"candidate_id": "k-reject", "proposal": {}})
663
+ control("a second-pass proposal for a candidate its version did not newly admit is refused by name",
664
+ "\n".join(overlay(derivations, s7, s7b_doc, [stray])[3]), "OVERLAY_UNACCOUNTED k-reject")
665
+ ghost = copy.deepcopy(v1)
666
+ ghost["derivations"]["verdicts"]["k-zz"] = ghost["derivations"]["verdicts"]["k-core"]
667
+ control("a recomputed verdict for a candidate S6 never derived is refused by name",
668
+ "\n".join(overlay(derivations, s7, s7b_doc, [ghost])[3]), "OVERLAY_UNACCOUNTED k-zz")
669
+ loose = copy.deepcopy(v1)
670
+ loose["review"]["unreviewed"].append({"item_id": "k-reject", "why": "x"})
671
+ control("a second-pass review entry for a proposal its version did not make is refused by name",
672
+ "\n".join(overlay(derivations, s7, s7b_doc, [loose])[3]), "OVERLAY_UNACCOUNTED k-reject")
673
+ v2 = {"version": 2, "derivations": {"verdicts": {"k-core": {**dv["verdicts"].get("k-core", {}), "lineages": 9}},
674
+ "newly_admitted": []}, "proposals": None, "review": None}
675
+ equal("versions are laid in order: a later version's verdict wins",
676
+ (lambda d: (d["verdicts"]["k-core"].get("lineages"), d["verdicts"]["k-core"].get("adjudication", {}).get("version")))(
677
+ overlay(derivations, s7, s7b_doc, [v1, v2])[0]), (9, 2))
678
+
679
+ # ---- the stage end to end -------------------------------------------------------------------------------------
680
+ from runlib import declare, stage_approvals, stage_render, stage_retrieve, stage_review_korean
681
+ from grammar import owner_lines
682
+ root = pathlib.Path(tempfile.mkdtemp(prefix="s10a-"))
683
+
684
+ class SectionStopped(Exception):
685
+ pass
686
+ try:
687
+ try:
688
+ run_dir = stage_retrieve.fx_gold(root / "base", stage_retrieve.fx_current(stage_judge.fx_library()))
689
+ declare.amend(run_dir, [("budget.per_stage.S6", 20_000_000)], "S10 adjudicate self-test: the golden run",
690
+ scope=["S5", "S6", "S7", "S7b", "S9", "S9b", "S10"]) # S10 reads what S6 read of S2
691
+ stage_retrieve.run(run_dir, "aa" * 8)
692
+ planner = root / "planner"
693
+ shutil.copytree(run_dir.parent, planner)
694
+ # three of the population's own candidates (the review leaves S5's planted controls out of its rows): a
695
+ # due decision the owner's value admits, made eligible by both judges' consequence class so S7 has an
696
+ # allowed answer, and two formed candidates, one rejected and one left disputed
697
+ pop = records.read_json(run_dir / "population.json")["candidates"]
698
+ picked = ([c["candidate_id"] for c in pop if c["source"] == "due_decision"][:1]
699
+ + sorted(c["candidate_id"] for c in pop if c["source"] == "formed")[:2])
700
+
701
+ def disputing(cid, who, row): # judge B uncertain on one requirement of each
702
+ if cid in picked:
703
+ if cid == picked[0]:
704
+ row["answer"]["consequence_class"] = "security"
705
+ if who == "B":
706
+ row["answer"]["requirements"]["bounded"] = {"mark": "uncertain", "reason": "planted"}
707
+ plan, _p = stage_judge.fx_judge_plan(planner / run_dir.name, root / "plan.json", disputing)
708
+ stage_judge.run(run_dir, stage_judge.supervisor(run_dir, root / "cells", plan))
709
+ stage_propose.run(run_dir, {})
710
+ stage_review_proposals.run(run_dir, {})
711
+ first = stage_render.run(run_dir)
712
+ except Exception as exc: # an upstream stage that breaks fails this section's first control by name
713
+ equal("the golden run renders three disputed candidates", f"GOLDEN_RUN_FAILED {type(exc).__name__}: {exc}"[:300],
714
+ 3)
715
+ raise SectionStopped from exc
716
+ rows1 = {r["item_id"]: r for r in records.read_json(run_dir / "review.v1.json")["rows"]}
717
+ equal("the golden run renders three disputed candidates",
718
+ sum(1 for c in picked if rows1.get(c, {}).get("status") == "disputed"), 3)
719
+ admit, reject, left = picked
720
+ copy_path = run_dir / "decisions.ko.v1.md"
721
+ lines = copy_path.read_text(encoding="utf-8").split("\n")
722
+ for item, decision in ((admit, ["결정: 판정", "메모: A가 맞다", "판정 1: A"]),
723
+ (reject, ["결정: 판정", "메모: 경계가 없다", "판정 1: unmet"])):
724
+ start = next(i for i, x in enumerate(lines) if x.startswith(f"<!-- owner-block review item={item} "))
725
+ end = next(i for i in range(start + 1, len(lines)) if lines[i] == owner_lines.CLOSE)
726
+ lines = lines[:start + 1] + decision + lines[end:]
727
+ copy_path.write_text("\n".join(lines), encoding="utf-8")
728
+ parsed = stage_approvals.run(run_dir, 1)
729
+ equal("S10 parses the owner's two 판정 lines", parsed.get("adjudications"), 2)
730
+ cli_out = root / "cli"
731
+ shutil.copytree(run_dir.parent, cli_out)
732
+ unknowns = [{k: s[k] for k in ("field", "state", "effect")}
733
+ for s in stage_propose.named_states(records.read_json(run_dir / stage_judge.DERIVATIONS))]
734
+ answer = stage_propose._answered(disposition="none", operations=[], unknowns=unknowns,
735
+ destination={"layer": "incubator", "carrier": None})
736
+ control("the newly admitted candidate with no answers says the call is not wired",
737
+ said(lambda: run(run_dir)), f"CALL_NOT_WIRED adjudicate: S7's second pass is asked for {admit}")
738
+ # the second pass by its supervised calls, on a copy: S7's seat and S7b's declared for this stage
739
+ from runlib import declare, placement
740
+ live_out = root / "live"
741
+ shutil.copytree(run_dir.parent, live_out)
742
+ live_run = live_out / run_dir.name
743
+ seats_now = records.declaration_state(live_run, who="S10 self-test")[0]["seats"]
744
+ declare.amend(live_run, [("seats", {**seats_now, PROPOSE_SEAT_KEY: "claude:claude-opus-5-5/high",
745
+ REVIEW_SEAT_KEY: "codex:gpt-6-astra/xhigh"}),
746
+ ("budget.per_stage.S10", 5_000_000)], "the second pass's golden seats and budget")
747
+ s7b_review = {"verdict": "agree",
748
+ "disposition_review": {"holds": True, "reason": "그렇다", "evidence": []},
749
+ "destination_review": {"holds": True, "reason": "그렇다", "evidence": []},
750
+ "merge_findings": None, "faithful_merge": "n/a", "alternative": None,
751
+ "bars": [{"bar": bar, "holds": True, "reason": "충족"} for bar in placement.contract_bars()],
752
+ "notes": "동의한다"}
753
+ plan_path = root / "second-pass-plan.json"
754
+
755
+ def planned(propose, review):
756
+ plan_path.write_text(json.dumps([{"match": ["the proposal S7 made for it"], "answer": review},
757
+ {"match": [json.dumps(admit)], "answer": propose}],
758
+ ensure_ascii=False), encoding="utf-8")
759
+ return stage_judge.supervisor(live_run, root / "live-cells", plan_path)
760
+ control("a second-pass call that does not end accepted writes nothing, so a re-run can ask again",
761
+ said(lambda: run(live_run, supervisor=planned({"disposition": "none"}, s7b_review))),
762
+ "SECOND_PASS_INCOMPLETE adjudicate: S7's call for")
763
+ equal("and the parse is still not adjudicated", (live_run / outputs_of(1)[0]).exists(), False)
764
+ live = run(live_run, supervisor=planned(answer, s7b_review))
765
+ live_review = records.read_json(live_run / outputs_of(1)[2]) if (live_run / outputs_of(1)[2]).is_file() else {}
766
+ equal("with a supervisor the second pass asks S7 for the newly admitted and S7b for what S7 proposed, and "
767
+ "writes both documents",
768
+ (live.get("admitted"), live.get("calls"),
769
+ [p["candidate_id"] for p in records.read_json(live_run / outputs_of(1)[1])["proposals"]],
770
+ [r["item_id"] for r in live_review.get("reviews") or []]),
771
+ (1, 2, [admit], [admit]))
772
+ control("answers in hand and a supervisor are two sources, refused by name",
773
+ said(lambda: run(live_run, answers={admit: answer}, supervisor=planned(answer, s7b_review))),
774
+ "INPUT_INVALID adjudicate")
775
+ out = run(run_dir, answers={admit: answer})
776
+ equal("the adjudicate part recomputes both and admits one", (out["version"], out["adjudicated"],
777
+ out["admitted"], out["rejected"]), (1, 2, 1, 1))
778
+ part = ((records.stage_records(run_dir).get(STAGE) or {}).get("parts") or {}).get(PART) or {}
779
+ equal("its record holds the recomputed derivations and the second pass as its outputs",
780
+ (part.get("status"), sorted(o["artifact"] for o in part.get("outputs") or [])),
781
+ ("complete", sorted(outputs_of(1))))
782
+ control("a parse is adjudicated once", said(lambda: run(run_dir, answers={admit: answer})),
783
+ "ADJUDICATED_ALREADY v1")
784
+ second = stage_render.run(run_dir)
785
+ rows2 = {r["item_id"]: r for r in records.read_json(run_dir / "review.v2.json")["rows"]}
786
+ equal("the next review shows the admitted candidate proposed with its adjudication, the rejected one rejected, "
787
+ "and the undecided one still disputed",
788
+ ((first["version"], second["version"]), rows2.get(admit, {}).get("status"),
789
+ (rows2.get(admit, {}).get("adjudication") or {}).get("adjudication_id") is not None,
790
+ rows2.get(reject, {}).get("status"), rows2.get(left, {}).get("status")),
791
+ ((1, 2), "proposed", True, "rejected", "disputed"))
792
+ text2 = (run_dir / "review.ko.v2.md").read_text(encoding="utf-8")
793
+ control("and says what the owner decided on it", text2, "- 소유자 판정: v1의 결정 J-")
794
+ took = sorted(i["artifact"] for i in records.read_json(run_dir / "stages" / "S9" / "record.json")["inputs"]
795
+ if i["producer_stage"] == STAGE)
796
+ equal("S9's render takes the adjudicate part's outputs as recorded inputs", took,
797
+ sorted(n for n in outputs_of(1) if (run_dir / n).is_file()))
798
+ # S9b over the new version: the admitted row's Korean fails once and is regenerated, which S7's rule accepts
799
+ # only against the recomputed derivation, so the regeneration holds only if S9b read the overlay
800
+ def s9b_verdict(failing=()):
801
+ return {"verdict": "fail" if failing else "pass", "notes": "그대로다",
802
+ "fields": [{"field": f, "faithful": f not in failing, "plain": True, "finding": "f"}
803
+ for f in stage_review_korean.FIELDS]}
804
+ rewritten = {**answer, "reasons": {**answer["reasons"], "what_happened": "다시 쓴 무엇이 있었나"}}
805
+ korean = stage_review_korean.run(run_dir, {admit: s9b_verdict(["what_happened"])}, {admit: rewritten},
806
+ {admit: s9b_verdict()})
807
+ s9b_row = next((r for r in records.read_json(run_dir / "review-s9b.v2.json")["rows"] if r["item_id"] == admit), {})
808
+ s9b_took = sorted(i["artifact"] for i in records.read_json(run_dir / "stages" / "S9b" / "record.json")["inputs"]
809
+ if i["producer_stage"] == STAGE)
810
+ equal("S9b reads the review with the adjudication laid over S6 and S7: the admitted row is regenerated "
811
+ "against its recomputed derivation, and the adjudicate outputs are its recorded inputs",
812
+ (korean["version"], s9b_row.get("regenerated"), s9b_row.get("mark"), s9b_took),
813
+ (2, True, False, sorted(n for n in outputs_of(1) if (run_dir / n).is_file())))
814
+ held_part = records.read_json(records.record_path(run_dir, STAGE))
815
+ broken = copy.deepcopy(held_part)
816
+ broken["parts"][PART]["status"] = "failed"
817
+ records.write_json(run_dir, records.record_path(run_dir, STAGE), broken)
818
+ control("a render over an adjudicate part that is not complete is refused by name",
819
+ said(lambda: stage_render.run(run_dir)), "ADJUDICATION_UNSETTLED")
820
+ records.write_json(run_dir, records.record_path(run_dir, STAGE), held_part)
821
+ (cli_out / "answers.json").write_text(json.dumps({admit: answer}), encoding="utf-8")
822
+ bare = subprocess.run([sys.executable, "-I", str(HERE / "distill.py"), "adjudicate", "--run-id", run_dir.name,
823
+ "--out", str(cli_out)], capture_output=True, text=True, timeout=600)
824
+ control("the driver's `adjudicate` without answers says the call is not wired",
825
+ f"rc={bare.returncode} {bare.stderr[-400:]}", "rc=2 CALL_NOT_WIRED adjudicate")
826
+ done = subprocess.run([sys.executable, "-I", str(HERE / "distill.py"), "adjudicate", "--run-id", run_dir.name,
827
+ "--out", str(cli_out), "--answers", str(cli_out / "answers.json")],
828
+ capture_output=True, text=True, timeout=600)
829
+ control("and with them runs the part as a process", f"rc={done.returncode} {done.stdout}{done.stderr[-400:]}",
830
+ "rc=0 S10 adjudicate: version 1: 2 adjudicated, 1 newly admitted, 1 rejected")
831
+ except SectionStopped:
832
+ pass
833
+ except Exception as exc: # a later break fails this section by name, never the whole suite
834
+ failures.append(("the golden run's section ran to its end", f"{type(exc).__name__}: {exc}"[:600]))
835
+ finally:
836
+ shutil.rmtree(root, ignore_errors=True)
837
+
838
+ return finish()
839
+
840
+
841
+ if __name__ == "__main__":
842
+ if sys.argv[1:] == ["--self-test"]:
843
+ sys.exit(self_test())
844
+ print("usage: stage_adjudicate.py --self-test", file=sys.stderr)
845
+ sys.exit(2)