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.
- package/DEPENDENCIES.md +62 -20
- package/INSTALL.md +1 -1
- package/README.md +16 -21
- package/claude/agents/frontier.md +1 -1
- package/claude/agents/sweep.md +2 -1
- package/claude/agents/workhorse.md +2 -2
- package/claude/guides/claude-prompting.md +494 -167
- package/claude/guides/cli-multi-model-workflow.md +8 -7
- package/claude/guides/gpt-prompting.md +241 -111
- package/claude/guides/session-distill-workflow.md +93 -43
- package/claude/guides/tooling-gotchas.md +3 -1
- package/codex/agents/reviewer.toml +2 -2
- package/codex/agents/sweep.toml +1 -1
- package/codex/agents/workhorse.toml +2 -2
- package/codex/guides/claude-prompting.md +494 -167
- package/codex/guides/cli-multi-model-workflow.md +8 -7
- package/codex/guides/gpt-prompting.md +241 -111
- package/codex/guides/session-distill-workflow.md +93 -43
- package/codex/guides/tooling-gotchas.md +3 -1
- package/compose/assemble.py +4 -1
- package/compose/canary.sh +8 -6
- package/compose/host_platform.py +158 -15
- package/compose/instructions-state.py +183 -41
- package/compose/instructions_app.py +2 -2
- package/compose/instructions_install.py +222 -27
- package/compose/instructions_session.py +250 -75
- package/compose/instructions_setup.py +6 -6
- package/compose/instructions_setup_cli.py +2 -36
- package/compose/instructions_setup_i18n.py +3 -3
- package/compose/instructions_store.py +160 -3
- package/compose/instructions_transaction.py +29 -5
- package/compose/instructions_ui_runtime.py +2 -2
- package/compose/setup/START.md +1 -1
- package/docs/advanced-launch.md +4 -0
- package/docs/releases/0.19.4.md +99 -0
- package/docs/releases/0.20.0.md +102 -0
- package/docs/setup.md +4 -4
- package/install.sh +54 -20
- package/launch/agent-launch.py +171 -22
- package/launch/agent-launch.toml +64 -29
- package/launch/agent-launch.zsh +104 -13
- package/launch/claude_subcommands.py +179 -0
- package/launch/provision-venv.sh +1 -1
- package/launch/shell_integration.py +7 -1
- package/learn/collect-learning.py +60 -9
- package/learn/migrate-learnings.py +70 -4
- package/learn/redact.py +2 -1
- package/package.json +37 -4
- package/provenance.json +1 -1
- package/session-cost.py +141 -18
- package/session-distill/coverage.json +6 -0
- package/session-distill/distill.py +2575 -0
- package/session-distill/grammar/__init__.py +0 -0
- package/session-distill/grammar/owner_lines.py +874 -0
- package/session-distill/originators.json +9 -0
- package/session-distill/packets/cross_review.md +31 -0
- package/session-distill/packets/form.md +86 -0
- package/session-distill/packets/judge.md +81 -0
- package/session-distill/packets/placement_contract.md +90 -0
- package/session-distill/packets/propose.md +124 -0
- package/session-distill/packets/read.md +57 -0
- package/session-distill/packets/reconsider.md +53 -0
- package/session-distill/packets/s7b.md +65 -0
- package/session-distill/packets/s9b.md +39 -0
- package/session-distill/packets/stitch.md +35 -0
- package/session-distill/packets/sweep.md +33 -0
- package/session-distill/runlib/__init__.py +0 -0
- package/session-distill/runlib/bound.py +1102 -0
- package/session-distill/runlib/breaker.py +467 -0
- package/session-distill/runlib/census.py +2347 -0
- package/session-distill/runlib/claims.py +420 -0
- package/session-distill/runlib/controls.py +902 -0
- package/session-distill/runlib/coverage.py +881 -0
- package/session-distill/runlib/declare.py +888 -0
- package/session-distill/runlib/delivery_evidence.py +1145 -0
- package/session-distill/runlib/derive.py +812 -0
- package/session-distill/runlib/destinations.py +3072 -0
- package/session-distill/runlib/dispatch.py +7939 -0
- package/session-distill/runlib/drift.py +1077 -0
- package/session-distill/runlib/entry.py +401 -0
- package/session-distill/runlib/evidence.py +890 -0
- package/session-distill/runlib/exposure.py +1162 -0
- package/session-distill/runlib/gate.py +2727 -0
- package/session-distill/runlib/gitread.py +79 -0
- package/session-distill/runlib/inventory.py +19624 -0
- package/session-distill/runlib/journal.py +1919 -0
- package/session-distill/runlib/ledger.py +3210 -0
- package/session-distill/runlib/ledger_compat.py +101 -0
- package/session-distill/runlib/ledger_migration.py +190 -0
- package/session-distill/runlib/lifecycle_intake.py +693 -0
- package/session-distill/runlib/lineage.py +454 -0
- package/session-distill/runlib/measures.py +249 -0
- package/session-distill/runlib/monitor.py +1180 -0
- package/session-distill/runlib/operations.py +522 -0
- package/session-distill/runlib/packet.py +838 -0
- package/session-distill/runlib/placement.py +1769 -0
- package/session-distill/runlib/projection.py +4090 -0
- package/session-distill/runlib/ranking.py +740 -0
- package/session-distill/runlib/receipts.py +200 -0
- package/session-distill/runlib/records.py +1965 -0
- package/session-distill/runlib/search.py +249 -0
- package/session-distill/runlib/sequencing.py +829 -0
- package/session-distill/runlib/sources.py +641 -0
- package/session-distill/runlib/stage_adjudicate.py +845 -0
- package/session-distill/runlib/stage_apply.py +1378 -0
- package/session-distill/runlib/stage_approvals.py +758 -0
- package/session-distill/runlib/stage_close.py +1220 -0
- package/session-distill/runlib/stage_confirm.py +929 -0
- package/session-distill/runlib/stage_delivery.py +3080 -0
- package/session-distill/runlib/stage_form.py +2576 -0
- package/session-distill/runlib/stage_judge.py +4248 -0
- package/session-distill/runlib/stage_propose.py +3307 -0
- package/session-distill/runlib/stage_read.py +5179 -0
- package/session-distill/runlib/stage_render.py +2739 -0
- package/session-distill/runlib/stage_retrieve.py +924 -0
- package/session-distill/runlib/stage_review_korean.py +1002 -0
- package/session-distill/runlib/stage_review_proposals.py +1292 -0
- package/session-distill/runlib/stagelock.py +412 -0
- package/session-distill/runlib/stop.py +1061 -0
- package/session-distill/runlib/targets.py +809 -0
- package/session-distill/runlib/usage.py +280 -0
- package/session-distill/runlib/validate.py +319 -0
- package/session-distill/runlib/views.py +4327 -0
- package/session-distill/schemas/adjudication.schema.json +35 -0
- package/session-distill/schemas/approval.schema.json +35 -0
- package/session-distill/schemas/census.schema.json +128 -0
- package/session-distill/schemas/checks.schema.json +207 -0
- package/session-distill/schemas/claim.schema.json +16 -0
- package/session-distill/schemas/confirmation.schema.json +24 -0
- package/session-distill/schemas/coverage.schema.json +66 -0
- package/session-distill/schemas/cross_review.schema.json +24 -0
- package/session-distill/schemas/event.schema.json +20 -0
- package/session-distill/schemas/evidence.schema.json +20 -0
- package/session-distill/schemas/expected_observation.schema.json +18 -0
- package/session-distill/schemas/form.schema.json +103 -0
- package/session-distill/schemas/intake.schema.json +71 -0
- package/session-distill/schemas/inventory.schema.json +872 -0
- package/session-distill/schemas/judge.schema.json +77 -0
- package/session-distill/schemas/ledger.schema.json +313 -0
- package/session-distill/schemas/observation.schema.json +16 -0
- package/session-distill/schemas/propose.schema.json +555 -0
- package/session-distill/schemas/read.schema.json +76 -0
- package/session-distill/schemas/reconsider.schema.json +122 -0
- package/session-distill/schemas/run.schema.json +150 -0
- package/session-distill/schemas/s7b.schema.json +200 -0
- package/session-distill/schemas/s9b.schema.json +28 -0
- package/session-distill/schemas/stitch.schema.json +25 -0
- package/session-distill/schemas/sweep.schema.json +25 -0
- package/session-distill/seats.json +149 -0
- package/session-distill/tables/allowed_pairs.json +257 -0
- package/session-distill/tables/controls.json +30 -0
- package/session-distill/tables/delivery_evidence.json +36 -0
- package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
- package/session-distill/tables/destinations.json +684 -0
- package/session-distill/tables/drift_layers.json +68 -0
- package/session-distill/tables/exposure_rules.json +192 -0
- package/session-distill/tables/placement_rules.json +148 -0
- package/session-distill/tables/propose_fixtures.json +154 -0
- package/session-distill/tables/ranking.json +194 -0
- package/session-distill/tables/redundancy.json +10 -0
- package/session-distill/tables/structural_rules.json +44 -0
- package/session-distill/tables/transition_fixtures.json +398 -0
- package/session-distill/tables/transitions.json +69 -0
- package/session-distill/tables/unit_outcome.json +67 -0
- package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
- package/wrappers/claude-run.sh +481 -33
- package/wrappers/claude_hermetic_evidence.py +1423 -0
- package/wrappers/codex-helm.sh +44 -13
- package/wrappers/codex-run.sh +183 -20
- package/wrappers/codex_frame_filter.py +1199 -0
- package/wrappers/codex_protocol.py +737 -0
- package/wrappers/jsonl_lines.py +65 -0
|
@@ -0,0 +1,4248 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""S6 (plan WP-11): the judges A and B over S5's population, held to design §6.2.
|
|
3
|
+
|
|
4
|
+
This module holds the contract a judgment is held to, which no packet shape changes:
|
|
5
|
+
|
|
6
|
+
- the judgment schema (`schemas/judge.schema.json`) against §6.2's judged fields, both ways
|
|
7
|
+
(`contract_problems`, CONTRACT_DRIFT): every field §6.2 names is a field of the schema, and every field of the
|
|
8
|
+
schema is one §6.2 names or one this module declares with its reason (EXTRA_FIELDS);
|
|
9
|
+
- the reuse key (lead decision D12, D-20261111-f174ea): one key per (candidate, unit, seat), the hash of exactly §6.2's components
|
|
10
|
+
(`unit_key`, `key_components`), the component list held against the design's (`key_problems`);
|
|
11
|
+
- one judgment payload for both judges (N#1): PACKET_DIVERGENCE when the payloads two seats were sent differ
|
|
12
|
+
(`divergence`), RECEIPT_STALE when two calls' receipts carry one packet hash, since a receipt serves one call
|
|
13
|
+
(`receipt_problems`);
|
|
14
|
+
- the answer a judge returns, checked against the packet it answered (`answer_problems`): every unit judged once,
|
|
15
|
+
a quote exactly where a match is yes (D14, D-20261111-1aa1b3) and a span of that unit's text, every matching unit's following and
|
|
16
|
+
contribution, every ledger entry's relation, labels the packet shows;
|
|
17
|
+
- the consequence classes, owned by the schema's enum (lead decision D11, D-20261111-f3d39c), which the derivations' promotion row reads
|
|
18
|
+
(`classes`).
|
|
19
|
+
|
|
20
|
+
The judgment packet (plan WP-11 J1b2, lead decision on J0's numbers: shape a1_min) is built by code from what the stores
|
|
21
|
+
hold, one per candidate and the same for both judges (`JudgeLabels`, `payload`, `packets/judge.md`): the candidate as
|
|
22
|
+
S5's population records it, its events, claims and quotes; the units S5 retrieved for it, each with its text, its
|
|
23
|
+
heading, the lines that enclose it (inventory `edges.direct`, in full) and the files it mentions (`edges.reached`, by
|
|
24
|
+
their headings and counts); the ledger entries S5 retrieved. Every stored id is turned into a label of the packet's
|
|
25
|
+
own, so no store's naming reaches a judge. A planted control's packet has a natural one's blocks, rows and fields
|
|
26
|
+
(`packet_markers`, F27). `distill.py judge --dry` builds every packet of the judged population and measures it per
|
|
27
|
+
seat (`run`).
|
|
28
|
+
|
|
29
|
+
The calls (plan WP-11 J2): `distill.py judge --cells DIR` sends every judged candidate to Judge A and Judge B through
|
|
30
|
+
the dispatcher, each judge an item of its own with the candidate's one payload (N#1). Each answer is held to its packet
|
|
31
|
+
by the stage (`check`) and kept in the stores' ids (`judgments/<item>/<A|B>.json`); the receipts carry the payload S6
|
|
32
|
+
built and one packet each (`stage_receipts`); a call whose capture shows an undeclared instruction is failed by the
|
|
33
|
+
gate whatever it answered (done-when 5). A re-run reuses every accepted attempt and calls only the rest; another run
|
|
34
|
+
reuses nothing, and one judge's attempt never answers the other's item (done-when 4's decidable halves; the reuse map and
|
|
35
|
+
the later reference point's call are deferred, D-20261111-c4fa71).
|
|
36
|
+
|
|
37
|
+
The absence sweeps (plan WP-11 J3a, design §6.2, done-when 6) follow the judgments in the same run. At a reference
|
|
38
|
+
point the absence policy reads as incomplete every absence is `unknown` and nothing is swept. Otherwise every judged
|
|
39
|
+
candidate no unit matches by both judges (`absent_candidates`) has its remaining units - the units S5 indexes less the
|
|
40
|
+
ones retrieved for it - cut into shards, several candidates to a group (`shard_plan`, `shard_problems`, run.json's
|
|
41
|
+
`sweeps`), each shard sent to the Claude-side and the OpenAI-side sweep with one payload bound to the inventory's hash,
|
|
42
|
+
and each answer held to exactly the pairs its packet lists (`sweep_problems`). `--dry` reports the sweep's upper bound:
|
|
43
|
+
every judged candidate as a gap over the catalog layer (`upper_bound`).
|
|
44
|
+
|
|
45
|
+
Judge B then reviews every absence claim the sweeps judged whole (plan WP-11 J3b, done-when 3, F10): its packet
|
|
46
|
+
carries every unit either sweep flagged and fifty units both found unrelated, drawn from the run id, each with both
|
|
47
|
+
sweeps' marks and reasons (`cross_stage`); the kept review is held to what the sweep results build
|
|
48
|
+
(`cross_review_problems`: CROSS_REVIEW_INCOMPLETE, CROSS_REVIEW_STALE). Every unit either sweep flagged or Judge B
|
|
49
|
+
marked a match returns to both judges in one judgment packet (plan WP-11 J3c, `reconsider_stage`); the claim is then
|
|
50
|
+
diagnosed again by derive, a disagreement making it disputed, and a judge's missing reconsideration is
|
|
51
|
+
RECONSIDERATION_MISSING.
|
|
52
|
+
|
|
53
|
+
stage_judge.py --self-test
|
|
54
|
+
"""
|
|
55
|
+
import collections
|
|
56
|
+
import hashlib
|
|
57
|
+
import json
|
|
58
|
+
import math
|
|
59
|
+
import os
|
|
60
|
+
import pathlib
|
|
61
|
+
import re
|
|
62
|
+
import shutil
|
|
63
|
+
import sys
|
|
64
|
+
import tempfile
|
|
65
|
+
|
|
66
|
+
if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
|
|
67
|
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
68
|
+
from runlib import bound, controls, derive, gate, lifecycle_intake, packet, records, stage_form, stage_retrieve, validate # noqa: E402
|
|
69
|
+
from runlib.records import Refused # noqa: E402
|
|
70
|
+
|
|
71
|
+
HERE = pathlib.Path(__file__).resolve().parents[1]
|
|
72
|
+
STAGE = "S6"
|
|
73
|
+
TEMPLATE = "judge"
|
|
74
|
+
SCHEMA_PATH = HERE / "schemas" / "judge.schema.json"
|
|
75
|
+
SEATS = ("A", "B")
|
|
76
|
+
REQUIREMENTS = ("observed_event", "consequence", "causal_support", "recognizable_in_advance", "actionable", "bounded",
|
|
77
|
+
"positioned", "audience")
|
|
78
|
+
|
|
79
|
+
# Design §6.2, the judges' paragraph, as written: what both judges return per unit and per candidate. Each phrase is
|
|
80
|
+
# mapped to the schema paths that hold it; `contract_problems` holds the map against the schema both ways.
|
|
81
|
+
DESIGN_6_2_UNIT = {
|
|
82
|
+
"situation match": ("units[].situation",),
|
|
83
|
+
"action match": ("units[].action",),
|
|
84
|
+
"reason": ("units[].reason",),
|
|
85
|
+
"quoting the unit": ("units[].quote",),
|
|
86
|
+
}
|
|
87
|
+
DESIGN_6_2_CANDIDATE = {
|
|
88
|
+
"each admission requirement `met | unmet | uncertain` with reason": ("requirements.*.mark", "requirements.*.reason"),
|
|
89
|
+
"for each matching unit, its following (`followed | not_followed | unknown`)": ("matching_units[].following",),
|
|
90
|
+
"its contribution to the outcome (`helped | harmed | neutral | unknown`)": ("matching_units[].contribution",),
|
|
91
|
+
"each with evidence ids": ("matching_units[].following_evidence_ids", "matching_units[].contribution_evidence_ids"),
|
|
92
|
+
"the consequence class": ("consequence_class",),
|
|
93
|
+
"the relation to each retrieved ledger entry (recurrence, revision, contradiction, relation to a retired entry, "
|
|
94
|
+
"or none)": ("ledger_relations[].relation",),
|
|
95
|
+
}
|
|
96
|
+
# Fields of the schema §6.2's paragraph does not name, each with the reason it is there.
|
|
97
|
+
EXTRA_FIELDS = {
|
|
98
|
+
"units[].unit": "the packet's label of the unit judged, turned back into its stored id by code",
|
|
99
|
+
"matching_units[].unit": "the label of the matching unit the following and contribution are of",
|
|
100
|
+
"ledger_relations[].entry": "the packet's label of the ledger entry related",
|
|
101
|
+
"ledger_relations[].reason": "the reason the relation is given, as every other judged field has one",
|
|
102
|
+
"no_longer_arises.value": "§6.4 obsolete: both judges find that the situation no longer arises",
|
|
103
|
+
"no_longer_arises.reason": "§6.4 obsolete: the reason for that finding",
|
|
104
|
+
"no_longer_arises.evidence_ids": "§6.4 obsolete: 'a lifecycle candidate with evidence that the situation no "
|
|
105
|
+
"longer arises'",
|
|
106
|
+
}
|
|
107
|
+
# Design §6.2's reuse key, as written: "the key is the hash of the packet itself — candidate version with its claim
|
|
108
|
+
# and evidence versions, unit text, heading path, the enclosing guide's or router line's trigger, enclosing
|
|
109
|
+
# exceptions, the operative units it references, layer, scope, prompt and schema versions, and seat".
|
|
110
|
+
DESIGN_6_2_KEY = ("candidate version", "claim versions", "evidence versions", "unit text", "heading path",
|
|
111
|
+
"the enclosing guide's or router line's trigger", "enclosing exceptions",
|
|
112
|
+
"the operative units it references", "layer", "scope", "prompt version", "schema version", "seat")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def schema():
|
|
116
|
+
return json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def schema_paths(spec, defs, prefix=""):
|
|
120
|
+
"""Every leaf of a schema node as a dotted path, an array's items as `[]` and an object's named properties by
|
|
121
|
+
name, `*` for properties sharing one shape (the requirements), `$ref` resolved."""
|
|
122
|
+
if not isinstance(spec, dict):
|
|
123
|
+
return []
|
|
124
|
+
if "$ref" in spec:
|
|
125
|
+
return schema_paths(defs[spec["$ref"].rsplit("/", 1)[-1]], defs, prefix)
|
|
126
|
+
if spec.get("type") == "array":
|
|
127
|
+
items = spec.get("items") or {}
|
|
128
|
+
while isinstance(items, dict) and "$ref" in items:
|
|
129
|
+
items = defs[items["$ref"].rsplit("/", 1)[-1]]
|
|
130
|
+
if not (isinstance(items, dict) and items.get("type") == "object"):
|
|
131
|
+
return [prefix] # a list of scalars is one field: its values, not their positions, are judged
|
|
132
|
+
return schema_paths(items, defs, prefix + "[]")
|
|
133
|
+
props = spec.get("properties")
|
|
134
|
+
if spec.get("type") == "object" and props:
|
|
135
|
+
if set(props) == set(REQUIREMENTS):
|
|
136
|
+
shapes = {json.dumps(v, sort_keys=True) for v in props.values()}
|
|
137
|
+
if len(shapes) == 1:
|
|
138
|
+
return schema_paths(next(iter(props.values())), defs, f"{prefix}.*" if prefix else "*")
|
|
139
|
+
out = []
|
|
140
|
+
for name, member in props.items():
|
|
141
|
+
out += schema_paths(member, defs, f"{prefix}.{name}" if prefix else name)
|
|
142
|
+
return out
|
|
143
|
+
return [prefix]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def contract_problems(held=None):
|
|
147
|
+
"""Plan WP-11 done-when 8, the schema's half: CONTRACT_DRIFT for a field §6.2 names that the schema does not hold,
|
|
148
|
+
and for a schema field neither §6.2 names nor EXTRA_FIELDS declares."""
|
|
149
|
+
held = held or schema()
|
|
150
|
+
defs = held.get("$defs") or {}
|
|
151
|
+
paths = set(schema_paths(held, defs))
|
|
152
|
+
named = {p for table in (DESIGN_6_2_UNIT, DESIGN_6_2_CANDIDATE) for ps in table.values() for p in ps}
|
|
153
|
+
problems = [f"CONTRACT_DRIFT judge.schema.json: §6.2 names '{phrase}' and the schema holds no {p}"
|
|
154
|
+
for table in (DESIGN_6_2_UNIT, DESIGN_6_2_CANDIDATE) for phrase, ps in table.items() for p in ps
|
|
155
|
+
if p not in paths]
|
|
156
|
+
problems += [f"CONTRACT_DRIFT judge.schema.json: {p} is a field §6.2 does not name and no reason declares"
|
|
157
|
+
for p in sorted(paths - named - set(EXTRA_FIELDS))]
|
|
158
|
+
problems += [f"CONTRACT_DRIFT stage_judge.EXTRA_FIELDS: {p} declares a field the schema does not hold"
|
|
159
|
+
for p in sorted(set(EXTRA_FIELDS) - paths)]
|
|
160
|
+
return problems
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def classes(held=None):
|
|
164
|
+
"""The consequence classes (lead decision D11): the schema's enum is their one owner."""
|
|
165
|
+
held = held or schema()
|
|
166
|
+
return tuple(held["$defs"]["consequence_class"]["enum"])
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# ---- which candidates are judged ------------------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
# the sources S5's population names - S4's formed candidates and the lifecycle intake's (stage_form.INTAKE_SOURCES) -
|
|
172
|
+
# which are the keys of run.json's judged scope (held against the schema by the self-test)
|
|
173
|
+
SOURCES = ("formed",) + tuple(stage_form.INTAKE_SOURCES)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def check_failures(rows):
|
|
177
|
+
"""`{candidate id: codes}` of the candidates S5's checks failed (a quote that does not verify, a session problem):
|
|
178
|
+
they are not judged, and stand rejected by check failure (lead, WP-11 stage 0)."""
|
|
179
|
+
out = {}
|
|
180
|
+
for row in rows:
|
|
181
|
+
codes = sorted({p.split()[0] for p in (row.get("quote_problems") or []) + (row.get("session_problems") or [])})
|
|
182
|
+
if row.get("quote_ok") is False or row.get("session_problems"):
|
|
183
|
+
out[row["candidate_id"]] = codes
|
|
184
|
+
return out
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def judged_of(candidates, declaration, run_id, failed=()):
|
|
188
|
+
"""`(judged ids, left out)` (plan WP-11, lead decision on J0's numbers). Of the candidates S5's checks passed, a
|
|
189
|
+
source run.json's `judge.candidate_kinds` maps to `all` is judged whole, one mapped to n by a sample of n drawn by
|
|
190
|
+
code from the run id (the first n by the hash of run id and candidate id), one the map leaves out not at all; with
|
|
191
|
+
no map every candidate is judged. `left out` names every candidate not judged, by source:
|
|
192
|
+
`{source: {count, of, why}}`. A source S6 does not know is SOURCE_UNDECLARED."""
|
|
193
|
+
kinds = ((declaration or {}).get("judge") or {}).get("candidate_kinds")
|
|
194
|
+
by = {}
|
|
195
|
+
for k in candidates:
|
|
196
|
+
if k["candidate_id"] not in failed:
|
|
197
|
+
by.setdefault(k["source"], []).append(k["candidate_id"])
|
|
198
|
+
unknown = sorted(set(by) - set(SOURCES))
|
|
199
|
+
if unknown:
|
|
200
|
+
raise Refused(f"SOURCE_UNDECLARED {unknown}: S5's population names a source S6's judged scope has no key for "
|
|
201
|
+
f"({list(SOURCES)})")
|
|
202
|
+
judged, left = [], {}
|
|
203
|
+
for source in SOURCES:
|
|
204
|
+
ids = sorted(by.get(source, []))
|
|
205
|
+
scope = "all" if kinds is None else kinds.get(source)
|
|
206
|
+
if scope == "all":
|
|
207
|
+
judged += ids
|
|
208
|
+
continue
|
|
209
|
+
if scope is None:
|
|
210
|
+
keep, why = [], "the declaration's judge.candidate_kinds leaves this source out"
|
|
211
|
+
else:
|
|
212
|
+
keep = sorted(ids, key=lambda i: hashlib.sha256(f"{run_id}\x00{i}".encode("utf-8")).hexdigest())[:scope]
|
|
213
|
+
why = f"a sample of {scope} drawn from the run id"
|
|
214
|
+
judged += keep
|
|
215
|
+
if len(keep) < len(ids):
|
|
216
|
+
left[source] = {"count": len(ids) - len(keep), "of": len(ids), "why": why}
|
|
217
|
+
return sorted(judged), left
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
# ---- the reuse key --------------------------------------------------------------------------------------------
|
|
221
|
+
|
|
222
|
+
def sha256_json(value):
|
|
223
|
+
return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
|
224
|
+
.encode("utf-8")).hexdigest()
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def key_components(candidate, claims, quotes, unit, trigger, exceptions, references, prompt_sha256, schema_sha256, seat):
|
|
228
|
+
"""§6.2's components of one (candidate, unit, seat) judgment, by the design's own names: the candidate record, its
|
|
229
|
+
claims and its quotes as the packet shows them, the unit's text, heading and layer and scope, the units that enclose
|
|
230
|
+
it as its trigger (frontmatter and router lines) and its exceptions (the headings and conditions above it), the
|
|
231
|
+
operative units it references (by id and the hash of their text), the template's and the schema's hashes, the seat.
|
|
232
|
+
`unit` is `{unit_id, text, heading, layer, scope}`; `trigger`, `exceptions` and `references` lists of
|
|
233
|
+
`{unit_id, text}`."""
|
|
234
|
+
return {
|
|
235
|
+
"candidate version": sha256_json(candidate),
|
|
236
|
+
"claim versions": sha256_json(claims),
|
|
237
|
+
"evidence versions": sha256_json(quotes),
|
|
238
|
+
"unit text": hashlib.sha256(unit["text"].encode("utf-8")).hexdigest(),
|
|
239
|
+
"heading path": unit["heading"],
|
|
240
|
+
"the enclosing guide's or router line's trigger": sha256_json(sorted((u["unit_id"], u["text"]) for u in trigger)),
|
|
241
|
+
"enclosing exceptions": sha256_json(sorted((u["unit_id"], u["text"]) for u in exceptions)),
|
|
242
|
+
"the operative units it references": sha256_json(sorted((u["unit_id"], hashlib.sha256(u["text"].encode("utf-8"))
|
|
243
|
+
.hexdigest()) for u in references)),
|
|
244
|
+
"layer": unit["layer"],
|
|
245
|
+
"scope": unit.get("scope"),
|
|
246
|
+
"prompt version": prompt_sha256,
|
|
247
|
+
"schema version": schema_sha256,
|
|
248
|
+
"seat": seat,
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def unit_key(components):
|
|
253
|
+
"""The reuse key (D12): the hash of exactly §6.2's components, refused by name when it is handed any other set."""
|
|
254
|
+
problems = key_problems(tuple(components))
|
|
255
|
+
if problems:
|
|
256
|
+
raise Refused("\n".join(problems))
|
|
257
|
+
return sha256_json(components)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def key_problems(names):
|
|
261
|
+
"""Plan WP-11 done-when 8, the key's half: CONTRACT_DRIFT when the key's components are not §6.2's."""
|
|
262
|
+
missing, extra = [n for n in DESIGN_6_2_KEY if n not in names], [n for n in names if n not in DESIGN_6_2_KEY]
|
|
263
|
+
return ([f"CONTRACT_DRIFT reuse key: §6.2's component '{n}' is not in the key" for n in missing]
|
|
264
|
+
+ [f"CONTRACT_DRIFT reuse key: '{n}' is not a component §6.2 names" for n in extra])
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
# ---- one payload, one receipt per call ------------------------------------------------------------------------
|
|
268
|
+
|
|
269
|
+
def divergence(payloads):
|
|
270
|
+
"""N#1: both judges are sent one judgment payload. `payloads` maps a seat to the payload text it was sent;
|
|
271
|
+
PACKET_DIVERGENCE names the first line where two differ."""
|
|
272
|
+
seats = sorted(payloads)
|
|
273
|
+
out = []
|
|
274
|
+
for other in seats[1:]:
|
|
275
|
+
a, b = payloads[seats[0]].splitlines(), payloads[other].splitlines()
|
|
276
|
+
if a == b and payloads[seats[0]] == payloads[other]:
|
|
277
|
+
continue
|
|
278
|
+
line = next((n for n, (x, y) in enumerate(zip(a, b), 1) if x != y), min(len(a), len(b)) + 1)
|
|
279
|
+
out.append(f"PACKET_DIVERGENCE {seats[0]} {other}: the payloads differ from line {line}; both judges are sent "
|
|
280
|
+
"one judgment payload, and a seat's envelope is the only part of a packet that is its own")
|
|
281
|
+
return out
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def receipt_problems(receipts):
|
|
285
|
+
"""A receipt serves one call: RECEIPT_STALE when two receipts carry one `packet_sha256`, and PACKET_DIVERGENCE when
|
|
286
|
+
the receipts of one judgment's seats carry different `evidence.payload_sha256`. `receipts` maps a call id to
|
|
287
|
+
`(seat, receipt)`, the seats of one judgment."""
|
|
288
|
+
out, by_packet, payloads = [], {}, {}
|
|
289
|
+
for call_id, (seat, receipt) in sorted(receipts.items()):
|
|
290
|
+
digest = receipt.get("packet_sha256")
|
|
291
|
+
if digest in by_packet:
|
|
292
|
+
out.append(f"RECEIPT_STALE {call_id}: its receipt carries the packet hash {str(digest)[:12]} of "
|
|
293
|
+
f"{by_packet[digest]}; a receipt serves one call")
|
|
294
|
+
by_packet.setdefault(digest, call_id)
|
|
295
|
+
payloads.setdefault((receipt.get("evidence") or {}).get("payload_sha256"), []).append(f"{seat}:{call_id}")
|
|
296
|
+
if len(payloads) > 1:
|
|
297
|
+
out.append("PACKET_DIVERGENCE receipts: the judges' receipts carry "
|
|
298
|
+
+ ", ".join(f"{str(p)[:12]} ({', '.join(c)})" for p, c in sorted(payloads.items(), key=str))
|
|
299
|
+
+ "; both judges are sent one judgment payload")
|
|
300
|
+
return out
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
# ---- the answer against its packet ----------------------------------------------------------------------------
|
|
304
|
+
|
|
305
|
+
def answer_problems(shown, answer, first=True, reconsider=False):
|
|
306
|
+
"""What a schema-valid answer gets wrong against the packet it answered, each by name. `shown` is
|
|
307
|
+
`{units: {label: text}, quotes: [labels], entries: [labels]}`; `first` is the candidate's first call, which also
|
|
308
|
+
judges its requirements, class, matching units and ledger relations (D12), while a later reference point's call
|
|
309
|
+
judges its units only. `reconsider` is a reconsideration (J3c), which judges its returned units and their matching
|
|
310
|
+
units and no candidate-level field (FIELD_UNEXPECTED)."""
|
|
311
|
+
out = []
|
|
312
|
+
units = shown["units"]
|
|
313
|
+
seen = {}
|
|
314
|
+
for n, row in enumerate(answer.get("units") or []):
|
|
315
|
+
label = row["unit"]
|
|
316
|
+
where = f"units[{n}] {label}"
|
|
317
|
+
if label not in units:
|
|
318
|
+
out.append(f"UNKNOWN_LABEL {where}: this packet shows no unit so labelled")
|
|
319
|
+
continue
|
|
320
|
+
if label in seen:
|
|
321
|
+
out.append(f"UNIT_JUDGED_TWICE {where}: judged at units[{seen[label]}] already")
|
|
322
|
+
continue
|
|
323
|
+
seen[label] = n
|
|
324
|
+
matched = "yes" in (row["situation"], row["action"])
|
|
325
|
+
if matched and not row["quote"]:
|
|
326
|
+
out.append(f"QUOTE_MISSING {where}: a match is yes and no words of the unit show it (D14)")
|
|
327
|
+
elif not matched and row["quote"]:
|
|
328
|
+
out.append(f"QUOTE_UNEXPECTED {where}: neither match is yes, and a quote is given only where one is (D14)")
|
|
329
|
+
elif matched and row["quote"] not in units[label]:
|
|
330
|
+
out.append(f"QUOTE_NOT_IN_UNIT {where}: the quote is not a span of the unit's text")
|
|
331
|
+
out += [f"UNIT_UNJUDGED {label}: the packet shows it and the answer does not judge it"
|
|
332
|
+
for label in units if label not in seen]
|
|
333
|
+
if not first:
|
|
334
|
+
for field in ("matching_units", "ledger_relations"):
|
|
335
|
+
if answer.get(field):
|
|
336
|
+
out.append(f"FIELD_UNEXPECTED {field}: a later reference point's call judges its units only (D12)")
|
|
337
|
+
return out
|
|
338
|
+
if reconsider:
|
|
339
|
+
out += [f"FIELD_UNEXPECTED {field}: a reconsideration judges its returned units only (design §6.2)"
|
|
340
|
+
for field in RECONSIDER_REFUSED if field in answer]
|
|
341
|
+
matching = {label for label, n in seen.items()
|
|
342
|
+
if "yes" in (answer["units"][n]["situation"], answer["units"][n]["action"])}
|
|
343
|
+
given = {}
|
|
344
|
+
quotes = set(shown.get("quotes") or ())
|
|
345
|
+
for n, row in enumerate(answer.get("matching_units") or []):
|
|
346
|
+
where = f"matching_units[{n}] {row['unit']}"
|
|
347
|
+
if row["unit"] not in matching:
|
|
348
|
+
out.append(f"MATCHING_UNIT_UNEXPECTED {where}: the unit is not one this answer finds matching")
|
|
349
|
+
elif row["unit"] in given:
|
|
350
|
+
out.append(f"MATCHING_UNIT_TWICE {where}")
|
|
351
|
+
given.setdefault(row["unit"], n)
|
|
352
|
+
out += [f"UNKNOWN_LABEL {where}: this packet shows no quote {q!r}"
|
|
353
|
+
for q in row["following_evidence_ids"] + row["contribution_evidence_ids"] if q not in quotes]
|
|
354
|
+
out += [f"MATCHING_UNIT_MISSING {label}: a matching unit's following and contribution are judged (§6.2)"
|
|
355
|
+
for label in sorted(matching - set(given))]
|
|
356
|
+
out += [f"UNKNOWN_LABEL no_longer_arises: this packet shows no quote {q!r}"
|
|
357
|
+
for q in (answer.get("no_longer_arises") or {}).get("evidence_ids") or [] if q not in quotes]
|
|
358
|
+
entries = list(shown.get("entries") or ())
|
|
359
|
+
related = {}
|
|
360
|
+
for n, row in enumerate(answer.get("ledger_relations") or []):
|
|
361
|
+
if row["entry"] not in entries:
|
|
362
|
+
out.append(f"UNKNOWN_LABEL ledger_relations[{n}] {row['entry']}: this packet shows no entry so labelled")
|
|
363
|
+
elif row["entry"] in related:
|
|
364
|
+
out.append(f"ENTRY_JUDGED_TWICE ledger_relations[{n}] {row['entry']}")
|
|
365
|
+
related.setdefault(row["entry"], n)
|
|
366
|
+
out += [f"ENTRY_UNJUDGED {e}: the packet shows the entry and the answer gives no relation to it"
|
|
367
|
+
for e in entries if e not in related]
|
|
368
|
+
return out
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
# ---- the judgment packet --------------------------------------------------------------------------------------
|
|
372
|
+
|
|
373
|
+
CASE = "judge" # the judgment call's class (dispatch.class_key)
|
|
374
|
+
SEAT_KEYS = {"A": "S6.A", "B": "S6.B"}
|
|
375
|
+
# lead, on J0's numbers (2026-11-11): above the about 11.7k tokens J0 measured for 112 units with D14's quotes;
|
|
376
|
+
# re-derived when retrieval.per_layer changes
|
|
377
|
+
OUTPUT_CAP = 20_000
|
|
378
|
+
OUTPUT_CAP_BASIS = "J0 (2026-11-11): about 11.7k output tokens at 112 units with D14's quotes; re-derived when K changes"
|
|
379
|
+
INPUTS = ({"artifact": "checks.json", "producer_stage": "S5"},
|
|
380
|
+
{"artifact": "checked-candidates.json", "producer_stage": "S5"},
|
|
381
|
+
{"artifact": "read-results.json", "producer_stage": "S3"},
|
|
382
|
+
{"artifact": "read.json", "producer_stage": "S3"},
|
|
383
|
+
{"artifact": "observations/resolutions.json", "producer_stage": "S3"},
|
|
384
|
+
{"artifact": "census.json", "producer_stage": "S1"},
|
|
385
|
+
{"artifact": "coverage.json", "producer_stage": "S1"},
|
|
386
|
+
{"artifact": "views.json", "producer_stage": "S2"},
|
|
387
|
+
{"artifact": "inventory/current.json", "producer_stage": "S2"})
|
|
388
|
+
DRY_RECORD = "judgments/dry.json"
|
|
389
|
+
# the template's blocks, by the field that fills each and the tag that encloses it
|
|
390
|
+
BLOCKS = {"candidate": "candidate", "claims": "claims", "units": "units", "context": "context", "entries": "ledger_entries"}
|
|
391
|
+
# what the candidate block leaves out of a candidate's record: its ids (shown as labels elsewhere or not at all) and the
|
|
392
|
+
# lifecycle record, which it shows without the candidate's own id and source
|
|
393
|
+
CANDIDATE_HIDDEN = ("candidate_id", "label", "event_ids", "sessions", "lifecycle")
|
|
394
|
+
# what a lifecycle candidate carries for the stages after S6 and never shows a model: the decision a due decision
|
|
395
|
+
# resolves, `<entry id>@<run>` (design §7.1), which names a stored entry and run and is the hidden candidate id's own
|
|
396
|
+
# tail (Codex WP-11 r2 #3); the judges are shown the entry it is about (its label), its status and its expiry
|
|
397
|
+
LIFECYCLE_INTERNAL = ("resolves",)
|
|
398
|
+
CLUSTER_PREFIX = "g_cluster:" # a placed cluster's id (lifecycle_intake): the prefix and the unit its entries share
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def item_of(candidate_id):
|
|
402
|
+
"""A candidate's item name in its calls: opaque, as a call directory's name must be whatever the id holds."""
|
|
403
|
+
return "j" + hashlib.sha256(candidate_id.encode("utf-8")).hexdigest()[:12]
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
class JudgeLabels:
|
|
407
|
+
"""What one judgment packet labels, in the order it lists them: the candidate's events v1, ... and their sessions
|
|
408
|
+
s1, ...; the claims c1, ... its events and admission name; their quotes q1, ... and its events' origin quotes; the
|
|
409
|
+
units S5 retrieved n1, ... in S5's order; the lines enclosing them that S5 did not retrieve x1, ...; the ledger
|
|
410
|
+
entries S5 retrieved e1, .... The labels follow from what the packet lists, so a retry's packet shows the same ones
|
|
411
|
+
and nothing stores them.
|
|
412
|
+
|
|
413
|
+
`candidate` is a member of S5's population, `row` its checks.json row, `units` current.json's units by id (each
|
|
414
|
+
with the `edges` S2's inventory publishes: EDGES_ABSENT otherwise), `entries` the ledger's by id, `subject_of`
|
|
415
|
+
`stage_form.subject(run)`, `evidence` the evidence records by id (S3's stores and S5's population's). A quote the
|
|
416
|
+
candidate cites that is neither one of its claims' nor one of its events' origins is shown with the candidate
|
|
417
|
+
(`quotes`), from its record. A reference the stores do not hold is RECORD_INTEGRITY."""
|
|
418
|
+
|
|
419
|
+
def __init__(self, candidate, row, units, entries, subject_of, evidence):
|
|
420
|
+
cid = candidate["candidate_id"]
|
|
421
|
+
self.candidate, self.unit_store, self.entry_store = candidate, units, entries
|
|
422
|
+
self.subject_of, self.evidence_store = subject_of, evidence # what `returned_labels` builds from
|
|
423
|
+
events = {e["id"]: e for e in subject_of["events"]}
|
|
424
|
+
missing = [e for e in candidate.get("event_ids") or [] if e not in events]
|
|
425
|
+
if missing:
|
|
426
|
+
raise Refused(f"RECORD_INTEGRITY S6 packet {cid}: events no S3 store holds: {missing[:5]}")
|
|
427
|
+
self.event_rows = [events[e] for e in candidate.get("event_ids") or []]
|
|
428
|
+
self.events = {f"v{n}": ev["id"] for n, ev in enumerate(self.event_rows, 1)}
|
|
429
|
+
sessions = list(dict.fromkeys([ev["session"] for ev in self.event_rows] + list(candidate.get("sessions") or [])))
|
|
430
|
+
self.sessions = {f"s{n}": s for n, s in enumerate(sessions, 1)}
|
|
431
|
+
claims, admission = subject_of["claims"], candidate.get("admission") or {}
|
|
432
|
+
named = list(dict.fromkeys([c for ev in self.event_rows for c in [*ev["claim_ids"], *ev["outcome_claim_ids"]]]
|
|
433
|
+
+ [c for req in admission.values() for c in req.get("claim_ids") or []]
|
|
434
|
+
+ list((candidate.get("tension") or {}).get("instance_claim_ids") or [])))
|
|
435
|
+
missing = [c for c in named if c not in claims]
|
|
436
|
+
if missing:
|
|
437
|
+
raise Refused(f"RECORD_INTEGRITY S6 packet {cid}: claims no S3 store holds: {missing[:5]}")
|
|
438
|
+
self.claim_rows = {c: claims[c] for c in named}
|
|
439
|
+
self.claims = {f"c{n}": c for n, c in enumerate(named, 1)}
|
|
440
|
+
quotes = list(dict.fromkeys([q["evidence_id"] for c in named for q in claims[c]["quotes"]]
|
|
441
|
+
+ [o["evidence_id"] for ev in self.event_rows for o in ev.get("origin", [])
|
|
442
|
+
if o.get("evidence_id")]))
|
|
443
|
+
# a quote the admission cites beyond its claims and its own events' origins: S4 may cite any quote its packet
|
|
444
|
+
# showed, another event's origin among them
|
|
445
|
+
self.cited = [q for q in dict.fromkeys(q for req in admission.values() for q in req.get("evidence_ids") or [])
|
|
446
|
+
if q not in quotes]
|
|
447
|
+
missing = [q for q in self.cited if q not in evidence]
|
|
448
|
+
if missing:
|
|
449
|
+
raise Refused(f"RECORD_INTEGRITY S6 packet {cid}: its admission cites quotes no evidence record holds: "
|
|
450
|
+
f"{missing[:5]}")
|
|
451
|
+
self.evidence = {q: evidence[q] for q in self.cited}
|
|
452
|
+
self.quotes = {f"q{n}": q for n, q in enumerate(quotes + self.cited, 1)}
|
|
453
|
+
self.unit_rows = list(row["retrieved_units"])
|
|
454
|
+
self.units = {f"n{n}": r["unit_id"] for n, r in enumerate(self.unit_rows, 1)}
|
|
455
|
+
of_unit = {v: k for k, v in self.units.items()}
|
|
456
|
+
enclosing = []
|
|
457
|
+
for r in self.unit_rows:
|
|
458
|
+
unit = units.get(r["unit_id"])
|
|
459
|
+
if unit is None:
|
|
460
|
+
raise Refused(f"RECORD_INTEGRITY S6 packet {cid}: S5 retrieved {r['unit_id']}, which current.json "
|
|
461
|
+
"does not hold")
|
|
462
|
+
if not isinstance(unit.get("edges"), dict):
|
|
463
|
+
raise Refused(f"EDGES_ABSENT S6 packet {cid}: current.json's unit {r['unit_id']} carries no edges; S2's "
|
|
464
|
+
"inventory part is run again so every unit carries them (D-20261111-92d81a)")
|
|
465
|
+
enclosing += [d for d in unit["edges"]["direct"] if d != r["unit_id"] and d not in of_unit]
|
|
466
|
+
enclosing = list(dict.fromkeys(enclosing))
|
|
467
|
+
missing = [d for d in enclosing if d not in units]
|
|
468
|
+
if missing:
|
|
469
|
+
raise Refused(f"RECORD_INTEGRITY S6 packet {cid}: an edge names units current.json does not hold: {missing[:5]}")
|
|
470
|
+
self.context = {f"x{n}": d for n, d in enumerate(enclosing, 1)}
|
|
471
|
+
self.entry_rows = list(row["ledger_entries"])
|
|
472
|
+
missing = [r["entry_id"] for r in self.entry_rows if r["entry_id"] not in entries]
|
|
473
|
+
if missing:
|
|
474
|
+
raise Refused(f"RECORD_INTEGRITY S6 packet {cid}: S5 retrieved ledger entries the ledger does not hold: "
|
|
475
|
+
f"{missing[:5]}")
|
|
476
|
+
self.entries = {f"e{n}": r["entry_id"] for n, r in enumerate(self.entry_rows, 1)}
|
|
477
|
+
self.label_of = {stored: label for table in (self.events, self.sessions, self.claims, self.quotes, self.units,
|
|
478
|
+
self.context, self.entries) for label, stored in table.items()}
|
|
479
|
+
|
|
480
|
+
def relabel(self, value):
|
|
481
|
+
"""`value` with every string that is a stored id this packet labels turned into its label. A type G candidate's
|
|
482
|
+
tension names its cluster by the cluster's own id, `g_cluster:<the unit its entries are placed at>`
|
|
483
|
+
(lifecycle_intake), which is shown as that unit's label."""
|
|
484
|
+
if isinstance(value, dict):
|
|
485
|
+
return {k: self.relabel(v) for k, v in value.items()}
|
|
486
|
+
if isinstance(value, list):
|
|
487
|
+
return [self.relabel(v) for v in value]
|
|
488
|
+
if isinstance(value, str) and value.startswith(CLUSTER_PREFIX) and value[len(CLUSTER_PREFIX):] in self.label_of:
|
|
489
|
+
return self.label_of[value[len(CLUSTER_PREFIX):]]
|
|
490
|
+
return self.label_of.get(value, value) if isinstance(value, str) else value
|
|
491
|
+
|
|
492
|
+
def candidate_text(self):
|
|
493
|
+
k = self.candidate
|
|
494
|
+
view = {key: k[key] for key in sorted(k) if key not in CANDIDATE_HIDDEN}
|
|
495
|
+
life = k.get("lifecycle")
|
|
496
|
+
view["lifecycle"] = {key: v for key, v in sorted(life.items())
|
|
497
|
+
if key not in ("candidate_id", "source") + LIFECYCLE_INTERNAL} \
|
|
498
|
+
if isinstance(life, dict) else None
|
|
499
|
+
view["sessions"] = list(k.get("sessions") or [])
|
|
500
|
+
view["quotes"] = [{"evidence_id": q, **stage_form.quote_row({"record": self.evidence[q].get("line"),
|
|
501
|
+
"window_role": self.evidence[q]["window_role"],
|
|
502
|
+
"text": self.evidence[q]["redacted_text"]})}
|
|
503
|
+
for q in self.cited]
|
|
504
|
+
view["events"] = [{"event_id": ev["id"], "session": ev["session"], "kind": ev["kind"],
|
|
505
|
+
"description": ev["description"],
|
|
506
|
+
**({"origin": [{**({"evidence_id": o["evidence_id"]} if o.get("evidence_id") else {"citable": False}),
|
|
507
|
+
"record": o["record"], "window_role": "origin", "text": o["text"],
|
|
508
|
+
**({"cut": True} if o.get("cut") else {})} for o in ev["origin"]]}
|
|
509
|
+
if "origin" in ev else {}),
|
|
510
|
+
"claims": list(ev["claim_ids"]), "outcome_claims": list(ev["outcome_claim_ids"])}
|
|
511
|
+
for ev in self.event_rows]
|
|
512
|
+
return json.dumps(self.relabel(view), ensure_ascii=False, sort_keys=True)
|
|
513
|
+
|
|
514
|
+
def claims_text(self):
|
|
515
|
+
if not self.claims:
|
|
516
|
+
return "none"
|
|
517
|
+
return "\n".join(json.dumps(self.relabel({
|
|
518
|
+
"claim_id": ident, "fact": c["fact"], "interpretation": c["interpretation"], "uncertainty": c["uncertainty"],
|
|
519
|
+
"quotes": [{"evidence_id": q["evidence_id"], **stage_form.quote_row(q)} for q in c["quotes"]]}),
|
|
520
|
+
ensure_ascii=False) for ident, c in self.claim_rows.items())
|
|
521
|
+
|
|
522
|
+
def units_text(self):
|
|
523
|
+
if not self.units:
|
|
524
|
+
return "none"
|
|
525
|
+
shown = set(self.units.values()) | set(self.context.values())
|
|
526
|
+
rows = []
|
|
527
|
+
for r in self.unit_rows:
|
|
528
|
+
unit = self.unit_store[r["unit_id"]]
|
|
529
|
+
edges = unit["edges"]
|
|
530
|
+
mentions = {}
|
|
531
|
+
for ref in edges["reached"]:
|
|
532
|
+
target = self.unit_store.get(ref)
|
|
533
|
+
if target is not None:
|
|
534
|
+
held = mentions.setdefault(target.get("path") or "", {"headings": set(), "units": 0})
|
|
535
|
+
held["headings"].add(target.get("heading") or "")
|
|
536
|
+
held["units"] += 1
|
|
537
|
+
rows.append(json.dumps(self.relabel({
|
|
538
|
+
"unit_id": r["unit_id"], "layer": unit["layer"], "path": unit.get("path"), "heading": unit.get("heading") or "",
|
|
539
|
+
"text": unit["text"], "named": bool(r.get("named")),
|
|
540
|
+
"context": [d for d in edges["direct"] if d != r["unit_id"]],
|
|
541
|
+
"mentions": [{"path": path, "headings": sorted(m["headings"]), "units": m["units"]}
|
|
542
|
+
for path, m in sorted(mentions.items())],
|
|
543
|
+
"shown": sorted(ref for ref in edges["reached"] if ref in shown),
|
|
544
|
+
"unresolved_mentions": sum(1 for ref in edges["reached"] if ref not in self.unit_store)}),
|
|
545
|
+
ensure_ascii=False))
|
|
546
|
+
return "\n".join(rows)
|
|
547
|
+
|
|
548
|
+
def context_text(self):
|
|
549
|
+
if not self.context:
|
|
550
|
+
return "none"
|
|
551
|
+
return "\n".join(json.dumps(self.relabel({
|
|
552
|
+
"context_id": ident, "path": self.unit_store[ident].get("path"),
|
|
553
|
+
"heading": self.unit_store[ident].get("heading") or "", "block": self.unit_store[ident].get("block"),
|
|
554
|
+
"text": self.unit_store[ident]["text"]}), ensure_ascii=False) for ident in self.context.values())
|
|
555
|
+
|
|
556
|
+
def entries_text(self):
|
|
557
|
+
if not self.entries:
|
|
558
|
+
return "none"
|
|
559
|
+
return "\n".join(json.dumps(self.relabel({
|
|
560
|
+
"entry_id": r["entry_id"], "status": r.get("status"), "named": bool(r.get("named")),
|
|
561
|
+
"text": lifecycle_intake.entry_text(self.entry_store[r["entry_id"]])}), ensure_ascii=False)
|
|
562
|
+
for r in self.entry_rows)
|
|
563
|
+
|
|
564
|
+
def shown(self):
|
|
565
|
+
"""What `answer_problems` holds an answer to: the units by label with their text, the quote and entry labels."""
|
|
566
|
+
return {"units": {label: self.unit_store[i]["text"] for label, i in self.units.items()},
|
|
567
|
+
"quotes": list(self.quotes), "entries": list(self.entries)}
|
|
568
|
+
|
|
569
|
+
def resolve(self, answer):
|
|
570
|
+
"""An accepted answer read back in the stores' ids: units and matching units by unit id, quotes by evidence id,
|
|
571
|
+
ledger relations by entry id. Only an answer `answer_problems` passed reaches here, so every label is one this
|
|
572
|
+
packet shows."""
|
|
573
|
+
def quoted(ids):
|
|
574
|
+
return [self.quotes[q] for q in ids]
|
|
575
|
+
later = answer.get("no_longer_arises") or {}
|
|
576
|
+
held = {} if "requirements" not in answer else { # a reconsideration carries its units only (J3c)
|
|
577
|
+
"requirements": answer["requirements"], "consequence_class": answer["consequence_class"],
|
|
578
|
+
"no_longer_arises": {**later, "evidence_ids": quoted(later.get("evidence_ids") or [])}}
|
|
579
|
+
return {**held,
|
|
580
|
+
"units": [{"unit_id": self.units[r["unit"]], **{k: r[k] for k in ("situation", "action", "reason", "quote")}}
|
|
581
|
+
for r in answer["units"]],
|
|
582
|
+
"matching_units": [{"unit_id": self.units[r["unit"]], "following": r["following"],
|
|
583
|
+
"following_evidence_ids": quoted(r["following_evidence_ids"]),
|
|
584
|
+
"contribution": r["contribution"],
|
|
585
|
+
"contribution_evidence_ids": quoted(r["contribution_evidence_ids"])}
|
|
586
|
+
for r in answer["matching_units"]],
|
|
587
|
+
**({} if "ledger_relations" not in answer else {"ledger_relations": [
|
|
588
|
+
{"entry_id": self.entries[r["entry"]], "relation": r["relation"], "reason": r["reason"]}
|
|
589
|
+
for r in answer["ledger_relations"]]})}
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def payload(labels):
|
|
593
|
+
"""The judgment payload both judges are sent (N#1): `packets/judge.md` with its five blocks filled."""
|
|
594
|
+
return packet.render(TEMPLATE, {"candidate": labels.candidate_text(), "claims": labels.claims_text(),
|
|
595
|
+
"units": labels.units_text(), "context": labels.context_text(),
|
|
596
|
+
"entries": labels.entries_text()})
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def blocks_of(text):
|
|
600
|
+
"""`(frame, {field: rows})` of a payload: each block's JSON rows, and the text outside the blocks."""
|
|
601
|
+
rows, frame = {}, text
|
|
602
|
+
for field, tag in BLOCKS.items():
|
|
603
|
+
found = re.search(f"<{tag}>\n(.*?)\n</{tag}>", frame, re.S)
|
|
604
|
+
if found is None:
|
|
605
|
+
raise Refused(f"PACKET_INVALID S6: the payload holds no <{tag}> block")
|
|
606
|
+
body = found.group(1)
|
|
607
|
+
rows[field] = [] if body == "none" else [json.loads(line) for line in body.splitlines()]
|
|
608
|
+
frame = frame[:found.start(1)] + f"<{field}>" + frame[found.end(1):]
|
|
609
|
+
return frame, rows
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def packet_markers(control_text, natural_text):
|
|
613
|
+
"""F27 over two payloads: FRAME_DIFFERS when the text outside the blocks differs, and every MARKER_FIELD and
|
|
614
|
+
MARKER_TYPE `controls.marker_problems` finds between their blocks' rows."""
|
|
615
|
+
(c_frame, c_rows), (n_frame, n_rows) = blocks_of(control_text), blocks_of(natural_text)
|
|
616
|
+
out = [] if c_frame == n_frame else ["FRAME_DIFFERS: the text outside the blocks is not the natural packet's"]
|
|
617
|
+
for field in BLOCKS:
|
|
618
|
+
out += controls.marker_problems(c_rows[field], n_rows[field], f"/{field}")
|
|
619
|
+
return out
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
def seats_of(declaration):
|
|
623
|
+
"""`{A, B}`: the judges' seats as run.json declares them (`seats.S6.A`, `seats.S6.B`), SEAT_UNDECLARED otherwise."""
|
|
624
|
+
held = (declaration or {}).get("seats") or {}
|
|
625
|
+
missing = [key for key in SEAT_KEYS.values() if not held.get(key)]
|
|
626
|
+
if missing:
|
|
627
|
+
raise Refused(f"SEAT_UNDECLARED {missing}: S6's judges are seated by run.json, {list(SEAT_KEYS.values())}")
|
|
628
|
+
return {who: held[key] for who, key in SEAT_KEYS.items()}
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def limits_of(seat, run_dir, declaration, seats_path=None, case=CASE, output_cap=OUTPUT_CAP, stage=STAGE):
|
|
632
|
+
"""What one judgment call of `seat` is held to: the seat's context capacity and the host's measured hermetic
|
|
633
|
+
allowance from seats.json (`gate.seat_capacity`), the run's density for this class of call and the host's retry
|
|
634
|
+
share (`dispatch.measured_density`, `retry_share`), the output cap. What is not measured is named in `unmeasured`
|
|
635
|
+
(ALLOWANCE_UNMEASURED, CAPACITY_UNDECLARED; lead decision D13: the first live call of a seat measures it)."""
|
|
636
|
+
from runlib import dispatch
|
|
637
|
+
path = gate.SEATS if seats_path is None else pathlib.Path(seats_path)
|
|
638
|
+
host = seat.partition(":")[0]
|
|
639
|
+
entry = (gate.seats(path).get("hosts") or {}).get(host) or {}
|
|
640
|
+
slot = (entry.get("host_allowance") or {}).get("hermetic") or {}
|
|
641
|
+
allowance = slot.get("allowance_tokens") if slot.get("measured") is True else None
|
|
642
|
+
capacity, basis = gate.seat_capacity(seat, entry.get("version"), path=path)
|
|
643
|
+
density = dispatch.measured_density(run_dir, seat, stage, case, (declaration or {}).get("density"))
|
|
644
|
+
retry = dispatch.retry_share(run_dir, host, (declaration or {}).get("retry"))
|
|
645
|
+
unmeasured = ([] if isinstance(allowance, int) else
|
|
646
|
+
[f"ALLOWANCE_UNMEASURED {seat}: seats.json holds no measured hermetic allowance for {host}"]) \
|
|
647
|
+
+ ([] if capacity is not None else [f"CAPACITY_UNDECLARED {seat}: {basis}"])
|
|
648
|
+
return {"seat": seat, "capacity": capacity, "capacity_basis": basis, "allowance": allowance,
|
|
649
|
+
"bytes_per_token": density["bytes_per_token"], "density_basis": density["basis"],
|
|
650
|
+
"retry_margin": retry["margin"], "retries": retry["count"], "output_cap": output_cap, "unmeasured": unmeasured}
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def at_most_of(size, limits):
|
|
654
|
+
"""Input tokens at most of a judgment call of `size` driver bytes under `limits` (`dispatch.input_at_most`), or None
|
|
655
|
+
for a seat whose allowance or capacity is not measured."""
|
|
656
|
+
from runlib import dispatch
|
|
657
|
+
if limits["unmeasured"]:
|
|
658
|
+
return None
|
|
659
|
+
return dispatch.input_at_most(size, {"bytes_per_token": limits["bytes_per_token"]}, limits["allowance"],
|
|
660
|
+
limits["output_cap"], limits["retry_margin"], limits["retries"])[1]
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
def beyond_capacity(size, limits):
|
|
664
|
+
"""Whether a call of `size` driver bytes, with room for its one retry's correction (S4's rule, stage_read's
|
|
665
|
+
CORRECTION_ROOM) and the output cap, exceeds the seat's capacity; None when it cannot be told."""
|
|
666
|
+
from runlib import stage_read
|
|
667
|
+
at_most = at_most_of(size + stage_read.CORRECTION_ROOM, limits)
|
|
668
|
+
return None if at_most is None else at_most + limits["output_cap"] > limits["capacity"]
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def measure(run_id, who, limits, text, schema_bytes, item):
|
|
672
|
+
"""`(driver bytes, input tokens at most or None, over the seat's capacity)` of one judge's packet."""
|
|
673
|
+
built = packet.build(f"{run_id}-{STAGE}-{item}-{who}-a1", STAGE, limits["seat"], text, schema_bytes)
|
|
674
|
+
size = bound.driver_bytes(built, schema_bytes)[0]
|
|
675
|
+
return size, at_most_of(size, limits), beyond_capacity(size, limits)
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def build(run_dir, declaration, seats_path=None):
|
|
679
|
+
"""`(summary, packets)` of S6 dry over a run (plan WP-11 J1b2), under the declaration its stage was admitted against:
|
|
680
|
+
the candidates it judges (`check_failures`, `judged_of`), each one's packet and its measure per judge. `packets` maps
|
|
681
|
+
a judged candidate to `(labels, payload)`."""
|
|
682
|
+
run_dir = pathlib.Path(run_dir)
|
|
683
|
+
run_id = run_dir.resolve().name
|
|
684
|
+
seats = seats_of(declaration)
|
|
685
|
+
checks = records.read_json(run_dir / "checks.json")
|
|
686
|
+
population = records.read_json(run_dir / "checked-candidates.json")
|
|
687
|
+
units = {u["unit_id"]: u for u in records.read_json(run_dir / "inventory" / "current.json")["units"]}
|
|
688
|
+
ledger, _read = lifecycle_intake.ledger_of(declaration)
|
|
689
|
+
entries = {e["id"]: e for e in ledger["entries"]}
|
|
690
|
+
subject_of = stage_form.subject(run_dir)
|
|
691
|
+
names = [t["name"] for t in records.read_json(run_dir / "views.json")["transcripts"]]
|
|
692
|
+
evidence = {**stage_retrieve.stored_evidence(run_dir, names), **(population.get("evidence") or {})}
|
|
693
|
+
rows = {r["candidate_id"]: r for r in checks["candidates"]}
|
|
694
|
+
by_id = {k["candidate_id"]: k for k in population["candidates"]}
|
|
695
|
+
if set(rows) != set(by_id):
|
|
696
|
+
raise Refused(f"SET_MISMATCH S6: checks.json and checked-candidates.json name different candidates "
|
|
697
|
+
f"({len(set(rows) ^ set(by_id))} apart)")
|
|
698
|
+
failed = check_failures(checks["candidates"])
|
|
699
|
+
judged, left = judged_of(population["candidates"], declaration, run_id, failed)
|
|
700
|
+
schema_bytes = packet.schema_bytes(schema())
|
|
701
|
+
limits = {who: limits_of(seat, run_dir, declaration, seats_path) for who, seat in seats.items()}
|
|
702
|
+
out, over, packets = [], {who: [] for who in seats}, {}
|
|
703
|
+
for cid in judged:
|
|
704
|
+
labels = JudgeLabels(by_id[cid], rows[cid], units, entries, subject_of, evidence)
|
|
705
|
+
text, item = payload(labels), item_of(cid)
|
|
706
|
+
packets[cid] = (labels, text)
|
|
707
|
+
sizes = {who: measure(run_id, who, limits[who], text, schema_bytes, item) for who in seats}
|
|
708
|
+
for who, (_size, _at_most, beyond) in sizes.items():
|
|
709
|
+
if beyond:
|
|
710
|
+
over[who].append(cid)
|
|
711
|
+
out.append({"candidate_id": cid, "item": item, "source": by_id[cid]["source"], "units": len(labels.units),
|
|
712
|
+
"named_units": sum(1 for r in labels.unit_rows if r.get("named")), "context": len(labels.context),
|
|
713
|
+
"entries": len(labels.entries), "claims": len(labels.claims), "quotes": len(labels.quotes),
|
|
714
|
+
"payload_bytes": len(text.encode("utf-8")),
|
|
715
|
+
"payload_sha256": packet.sha256_bytes(text.encode("utf-8")),
|
|
716
|
+
"driver_bytes": {who: v[0] for who, v in sizes.items()},
|
|
717
|
+
"input_at_most": {who: v[1] for who, v in sizes.items()}})
|
|
718
|
+
totals = {"calls": len(out) * len(seats), "payload_bytes": sum(r["payload_bytes"] for r in out),
|
|
719
|
+
"driver_bytes": {who: sum(r["driver_bytes"][who] for r in out) for who in seats},
|
|
720
|
+
"input_at_most": {who: (None if limits[who]["unmeasured"] else sum(r["input_at_most"][who] for r in out))
|
|
721
|
+
for who in seats},
|
|
722
|
+
"output_at_most": len(out) * len(seats) * OUTPUT_CAP}
|
|
723
|
+
summary = {"stage": STAGE, "declaration_seq": declaration["declaration_seq"], "dry": True,
|
|
724
|
+
"population": {"candidates": len(by_id), "judged": len(judged), "check_failed": failed, "left_out": left},
|
|
725
|
+
"seats": seats, "limits": limits, "output_cap": OUTPUT_CAP, "output_cap_basis": OUTPUT_CAP_BASIS,
|
|
726
|
+
"template_sha256": packet.sha256_bytes(packet.template_text(TEMPLATE).encode("utf-8")),
|
|
727
|
+
"schema_sha256": packet.sha256_bytes(schema_bytes), "packets": out, "totals": totals,
|
|
728
|
+
"over_capacity": over,
|
|
729
|
+
"budget": {"per_stage": ((declaration.get("budget") or {}).get("per_stage") or {}).get(STAGE)}}
|
|
730
|
+
return summary, packets
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
# ---- the absence sweeps (plan WP-11 J3a, design §6.2) ----------------------------------------------------------
|
|
734
|
+
|
|
735
|
+
SWEEP_TEMPLATE = "sweep"
|
|
736
|
+
SWEEP_SCHEMA_PATH = HERE / "schemas" / "sweep.schema.json"
|
|
737
|
+
SWEEP_CASE = "sweep" # a sweep call's class (dispatch.class_key)
|
|
738
|
+
SWEEP_SEAT_KEYS = {"a": "S6.sweep_a", "b": "S6.sweep_b"} # lead decision E1: the Claude side and the OpenAI side
|
|
739
|
+
SWEEP_DEFAULTS = {"shard_units": 100, "candidates_per_shard": 5, "output_cap": 20_000} # lead decision E2
|
|
740
|
+
# the density the dry upper bound reports tokens at: S4's declared one, at which J0 measured C2's packets (lead, J2a)
|
|
741
|
+
J0_DENSITY = 2.27
|
|
742
|
+
J0_DENSITY_BASIS = "S4's declared density, at which J0 measured C2's judgment packets (2026-11-11)"
|
|
743
|
+
UPPER_BOUND_LAYER = "catalog" # lead, on J2a: the bound's remaining units are the catalog layer's
|
|
744
|
+
UPPER_BOUND_BASIS = ("every judged candidate taken as a gap, its remaining units the catalog layer's indexed units less "
|
|
745
|
+
"the ones S5 retrieved for it: a bound, not a count of gap candidates, which exist only after judging")
|
|
746
|
+
# what a lifecycle candidate's record names by id, shown to a sweep by the named texts instead (`sweep_view`)
|
|
747
|
+
LIFECYCLE_NAMED = ("candidate_id", "source", "target_entry", "entries", "target_unit", "target_units", "members")
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def sweep_schema():
|
|
751
|
+
return json.loads(SWEEP_SCHEMA_PATH.read_text(encoding="utf-8"))
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def sweeps_of(declaration):
|
|
755
|
+
"""`(sizes, basis)`: the sweep sizes run.json declares (`sweeps.shard_units`, `candidates_per_shard`, `output_cap`),
|
|
756
|
+
each absent one S6's own (SWEEP_DEFAULTS), and which each came from."""
|
|
757
|
+
held = (declaration or {}).get("sweeps") or {}
|
|
758
|
+
return ({k: held.get(k, v) for k, v in SWEEP_DEFAULTS.items()},
|
|
759
|
+
{k: "declared" if k in held else "default" for k in SWEEP_DEFAULTS})
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def sweep_seats(declaration):
|
|
763
|
+
"""`{a, b}`: the sweeps' seats as run.json declares them (`seats.S6.sweep_a`, `seats.S6.sweep_b`), SEAT_UNDECLARED
|
|
764
|
+
otherwise."""
|
|
765
|
+
held = (declaration or {}).get("seats") or {}
|
|
766
|
+
missing = [key for key in SWEEP_SEAT_KEYS.values() if not held.get(key)]
|
|
767
|
+
if missing:
|
|
768
|
+
raise Refused(f"SEAT_UNDECLARED {missing}: S6's sweeps are seated by run.json, {list(SWEEP_SEAT_KEYS.values())}")
|
|
769
|
+
return {side: held[key] for side, key in SWEEP_SEAT_KEYS.items()}
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
def sweep_layers(absence_doc):
|
|
773
|
+
"""The layers an absence sweep covers: every indexed layer under the `literal` policy, which reads the reference
|
|
774
|
+
point's own flag, or the layers a `scoped` policy lists (`derive.absence`)."""
|
|
775
|
+
if (absence_doc or {}).get("policy") == "scoped":
|
|
776
|
+
return list(derive.table()["absence_completeness"]["layers"])
|
|
777
|
+
return None
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
def absent_candidates(judged, judgments, sources):
|
|
781
|
+
"""`(absent, not judged by both)`: the judged candidates whose diagnosis at the current reference point, from both
|
|
782
|
+
judges' units as derive reads them (`agreed`, `unit_diagnosis`, `candidate_diagnosis` at a complete point), is
|
|
783
|
+
`gap` - an absence claim, which the sweep checks. A candidate either judge did not judge is not swept."""
|
|
784
|
+
absent, not_both = [], []
|
|
785
|
+
for cid in judged:
|
|
786
|
+
held = judgments.get(cid) or {}
|
|
787
|
+
if set(held) != set(SEAT_KEYS):
|
|
788
|
+
not_both.append(cid)
|
|
789
|
+
continue
|
|
790
|
+
diagnosis, _row = derive.candidate_diagnosis(unit_diagnoses(held), True, lifecycle_of(sources[cid]))
|
|
791
|
+
if diagnosis == "gap":
|
|
792
|
+
absent.append(cid)
|
|
793
|
+
return absent, not_both
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
def lifecycle_of(source):
|
|
797
|
+
"""The lifecycle `derive.candidate_diagnosis` reads a candidate under: none for a formed one, its source otherwise."""
|
|
798
|
+
return None if source == "formed" else source
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def unit_diagnoses(held):
|
|
802
|
+
"""`{unit id: diagnosis, or (disputed, [A's, B's])}` over both judges' judgments `{A: ..., B: ...}` of one packet,
|
|
803
|
+
as derive reads them (`agreed`, `unit_diagnosis`)."""
|
|
804
|
+
a, b = ({u["unit_id"]: u for u in held[who]["units"]} for who in ("A", "B"))
|
|
805
|
+
units = {}
|
|
806
|
+
for uid in a:
|
|
807
|
+
pair = (a[uid], b.get(uid) or {})
|
|
808
|
+
values = [derive.agreed(pair[0].get(f), pair[1].get(f)) for f in ("situation", "action")]
|
|
809
|
+
diagnosis = derive.unit_diagnosis(*values)
|
|
810
|
+
units[uid] = (diagnosis, [derive.unit_diagnosis(x["situation"], x["action"]) for x in pair]) \
|
|
811
|
+
if diagnosis == derive.DISPUTED else diagnosis
|
|
812
|
+
return units
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
def remaining_of(index, retrieved, layers):
|
|
816
|
+
"""A candidate's remaining units: the units S5 indexes (one per text in each layer, `UnitIndex`) in `layers` (None:
|
|
817
|
+
every layer), less the ones retrieved for it, a copy counted as the unit that stands for it."""
|
|
818
|
+
taken = {index.rep_of.get(u, u) for u in retrieved}
|
|
819
|
+
return sorted(rep for rep in index.copies if (layers is None or index.layer_of[rep] in layers) and rep not in taken)
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
def shard_plan(remaining, candidates_per_shard, shard_units):
|
|
823
|
+
"""The sweep's groups and shards (lead decisions E2, E3): the candidates `candidates_per_shard` at a time in id
|
|
824
|
+
order, and each group's remaining units, the union of its candidates', `shard_units` at a time in unit id order; a
|
|
825
|
+
shard names for each candidate the units of it that are that candidate's remaining ones, and a candidate with none
|
|
826
|
+
in a shard is not in it."""
|
|
827
|
+
ids, groups = sorted(remaining), []
|
|
828
|
+
for g, start in enumerate(range(0, len(ids), candidates_per_shard), 1):
|
|
829
|
+
members = ids[start:start + candidates_per_shard]
|
|
830
|
+
union = sorted(set().union(*(remaining[c] for c in members)))
|
|
831
|
+
shards = []
|
|
832
|
+
for n, at in enumerate(range(0, len(union), shard_units), 1):
|
|
833
|
+
inside = set(union[at:at + shard_units])
|
|
834
|
+
pairs = {c: [u for u in remaining[c] if u in inside] for c in members}
|
|
835
|
+
shards.append({"shard": f"s{n:03d}", "units": union[at:at + shard_units],
|
|
836
|
+
"pairs": {c: us for c, us in pairs.items() if us}})
|
|
837
|
+
groups.append({"group": f"g{g:03d}", "candidates": members, "shards": shards})
|
|
838
|
+
return groups
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
def shard_problems(groups, remaining):
|
|
842
|
+
"""Done-when 6's set accounting: every candidate in exactly one group, and each of its remaining units in exactly
|
|
843
|
+
one shard of that group and nothing else (SET_MISMATCH)."""
|
|
844
|
+
out, seen = [], collections.Counter(c for g in groups for c in g["candidates"])
|
|
845
|
+
if set(seen) != set(remaining) or any(n > 1 for n in seen.values()):
|
|
846
|
+
out.append(f"SET_MISMATCH sweep groups: {sorted(set(remaining) - set(seen))[:3]} in none, "
|
|
847
|
+
f"{sorted(c for c, n in seen.items() if n > 1)[:3]} in more than one")
|
|
848
|
+
for g in groups:
|
|
849
|
+
for c in g["candidates"]:
|
|
850
|
+
got = collections.Counter(u for sh in g["shards"] for u in sh["pairs"].get(c, []))
|
|
851
|
+
want = set(remaining.get(c, []))
|
|
852
|
+
twice, missing, extra = (sorted(u for u, n in got.items() if n > 1), sorted(want - set(got)),
|
|
853
|
+
sorted(set(got) - want))
|
|
854
|
+
if twice or missing or extra:
|
|
855
|
+
out.append(f"SET_MISMATCH sweep {g['group']} {c}: remaining units in no shard {missing[:3]}, in two "
|
|
856
|
+
f"{twice[:3]}, not remaining {extra[:3]}")
|
|
857
|
+
return out
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def sweep_view(candidate, entries, units):
|
|
861
|
+
"""What a sweep is shown of a candidate: a formed one's lesson, type, situation, action and exception; a lifecycle
|
|
862
|
+
one's record without its ids, with the texts of the ledger entries and units it names. A name the stores do not hold
|
|
863
|
+
is counted, as S5 counts a named unit it does not hold (`retrieve_units`' absent): an inventory taken again since
|
|
864
|
+
the intake can drop a unit a hint named."""
|
|
865
|
+
if candidate["source"] == "formed":
|
|
866
|
+
return {k: candidate.get(k) for k in ("lesson", "type", "situation", "action", "exception")}
|
|
867
|
+
life = candidate.get("lifecycle") or {}
|
|
868
|
+
named_entries = stage_retrieve.as_list(life.get("target_entry")) + stage_retrieve.as_list(life.get("entries"))
|
|
869
|
+
named_units = stage_retrieve.as_list(life.get("target_unit")) + stage_retrieve.as_list(life.get("target_units"))
|
|
870
|
+
return {"source": candidate["source"],
|
|
871
|
+
**{k: v for k, v in sorted(life.items()) if k not in LIFECYCLE_NAMED + LIFECYCLE_INTERNAL},
|
|
872
|
+
"entry_texts": [lifecycle_intake.entry_text(entries[i]) for i in named_entries if i in entries],
|
|
873
|
+
"unit_texts": [units[u]["text"] for u in named_units if u in units],
|
|
874
|
+
"names_not_held": sum(1 for i in named_entries if i not in entries) + sum(1 for u in named_units if u not in units)}
|
|
875
|
+
|
|
876
|
+
|
|
877
|
+
class SweepLabels:
|
|
878
|
+
"""What one sweep packet labels: its candidates k1, ... in id order and its units n1, ... in the shard's order, and
|
|
879
|
+
the pairs it lists - each candidate with the units of the shard that are its remaining ones (E3)."""
|
|
880
|
+
|
|
881
|
+
def __init__(self, shard, candidates, units, entries):
|
|
882
|
+
self.shard, self.unit_store, self.entry_store = shard, units, entries
|
|
883
|
+
self.candidates = {f"k{n}": cid for n, cid in enumerate(sorted(shard["pairs"]), 1)}
|
|
884
|
+
self.units = {f"n{n}": uid for n, uid in enumerate(shard["units"], 1)}
|
|
885
|
+
of_unit = {uid: label for label, uid in self.units.items()}
|
|
886
|
+
self.listed = {(k, of_unit[u]) for k, cid in self.candidates.items() for u in shard["pairs"][cid]}
|
|
887
|
+
self.views = {k: sweep_view(candidates[cid], entries, units) for k, cid in self.candidates.items()}
|
|
888
|
+
|
|
889
|
+
def candidates_text(self):
|
|
890
|
+
of_unit = {uid: label for label, uid in self.units.items()}
|
|
891
|
+
return "\n".join(json.dumps({"candidate": k, **self.views[k],
|
|
892
|
+
"units": [of_unit[u] for u in self.shard["pairs"][cid]]}, ensure_ascii=False)
|
|
893
|
+
for k, cid in self.candidates.items())
|
|
894
|
+
|
|
895
|
+
def units_text(self):
|
|
896
|
+
return "\n".join(json.dumps({"unit": label, "layer": self.unit_store[uid]["layer"],
|
|
897
|
+
"path": self.unit_store[uid].get("path"),
|
|
898
|
+
"heading": self.unit_store[uid].get("heading") or "",
|
|
899
|
+
"text": self.unit_store[uid]["text"]}, ensure_ascii=False)
|
|
900
|
+
for label, uid in self.units.items())
|
|
901
|
+
|
|
902
|
+
def resolve(self, answer):
|
|
903
|
+
"""An accepted sweep answer in the stores' ids."""
|
|
904
|
+
return [{"candidate_id": self.candidates[r["candidate"]], "unit_id": self.units[r["unit"]],
|
|
905
|
+
**{k: r[k] for k in ("situation", "action", "reason")}} for r in answer["pairs"]]
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def sweep_payload(labels, inventory_sha256):
|
|
909
|
+
"""One shard's sweep payload, the same for both sweeps (N#1), bound to the inventory it was cut from: the
|
|
910
|
+
inventory's hash is in the payload, so a moved inventory is a new payload and no earlier attempt answers it."""
|
|
911
|
+
return packet.render(SWEEP_TEMPLATE, {"candidates": labels.candidates_text(), "units": labels.units_text(),
|
|
912
|
+
"inventory": f"sha256:{inventory_sha256}"})
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
def sweep_problems(labels, answer):
|
|
916
|
+
"""What a schema-valid sweep answer gets wrong against its packet: every listed pair judged exactly once
|
|
917
|
+
(SWEEP_PAIR_MISSING, SWEEP_PAIR_TWICE) and no other (SWEEP_PAIR_UNLISTED, E3), by labels the packet shows
|
|
918
|
+
(UNKNOWN_LABEL)."""
|
|
919
|
+
out, seen = [], {}
|
|
920
|
+
for n, row in enumerate(answer.get("pairs") or []):
|
|
921
|
+
pair, where = (row["candidate"], row["unit"]), f"pairs[{n}] {row['candidate']} {row['unit']}"
|
|
922
|
+
if pair[0] not in labels.candidates or pair[1] not in labels.units:
|
|
923
|
+
out.append(f"UNKNOWN_LABEL {where}: this packet shows no such candidate or unit")
|
|
924
|
+
elif pair not in labels.listed:
|
|
925
|
+
out.append(f"SWEEP_PAIR_UNLISTED {where}: the packet does not list this unit for this candidate (E3)")
|
|
926
|
+
elif pair in seen:
|
|
927
|
+
out.append(f"SWEEP_PAIR_TWICE {where}: judged at pairs[{seen[pair]}] already")
|
|
928
|
+
else:
|
|
929
|
+
seen[pair] = n
|
|
930
|
+
out += [f"SWEEP_PAIR_MISSING {k} {u}: the packet lists it and the answer does not judge it"
|
|
931
|
+
for k, u in sorted(labels.listed - set(seen))]
|
|
932
|
+
return out
|
|
933
|
+
|
|
934
|
+
|
|
935
|
+
def sweep_check(labels):
|
|
936
|
+
"""The stage's check of a sweep attempt, as `Supervisor.item(stage_check=)` asks it."""
|
|
937
|
+
from runlib import stage_read
|
|
938
|
+
|
|
939
|
+
def judged(call_dir):
|
|
940
|
+
return sweep_problems(labels, stage_read.answer_of(call_dir))
|
|
941
|
+
return judged
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
def sweep_rel(group, shard, side):
|
|
945
|
+
return f"sweeps/{group}/{shard}/{side}.json"
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
def kept_sweep(run_dir, rel, inventory_sha256):
|
|
949
|
+
"""A kept sweep result, refused by name when it was cut from another inventory than the one S6 reads now
|
|
950
|
+
(SWEEP_INVENTORY_MOVED, done-when 6)."""
|
|
951
|
+
held = records.read_json(pathlib.Path(run_dir) / rel)
|
|
952
|
+
if held.get("inventory_sha256") != inventory_sha256:
|
|
953
|
+
raise Refused(f"SWEEP_INVENTORY_MOVED {rel}: cut from inventory {str(held.get('inventory_sha256'))[:12]}, and S6 "
|
|
954
|
+
f"reads {inventory_sha256[:12]}; its shard is swept again")
|
|
955
|
+
return held
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
def sweep_context(run_dir, declaration):
|
|
959
|
+
"""What a sweep plan reads: S5's checks and population, S2's current units, the ledger's entries and S5's index."""
|
|
960
|
+
checks = records.read_json(run_dir / "checks.json")
|
|
961
|
+
population = records.read_json(run_dir / "checked-candidates.json")
|
|
962
|
+
units = records.read_json(run_dir / "inventory" / "current.json")["units"]
|
|
963
|
+
ledger, _read = lifecycle_intake.ledger_of(declaration)
|
|
964
|
+
return {"checks": checks, "by_id": {k["candidate_id"]: k for k in population["candidates"]},
|
|
965
|
+
"rows": {r["candidate_id"]: r for r in checks["candidates"]}, "units": {u["unit_id"]: u for u in units},
|
|
966
|
+
"entries": {e["id"]: e for e in ledger["entries"]}, "index": stage_retrieve.UnitIndex(units)}
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def sweep_packets(context, groups, inventory_sha256):
|
|
970
|
+
"""`[(group, shard, labels, payload)]` of every shard with a pair to judge."""
|
|
971
|
+
out = []
|
|
972
|
+
for g in groups:
|
|
973
|
+
for sh in g["shards"]:
|
|
974
|
+
if sh["pairs"]:
|
|
975
|
+
labels = SweepLabels(sh, context["by_id"], context["units"], context["entries"])
|
|
976
|
+
out.append((g["group"], sh["shard"], labels, sweep_payload(labels, inventory_sha256)))
|
|
977
|
+
return out
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
def upper_bound(run_dir, declaration, judged, seats_path=None):
|
|
981
|
+
"""The sweep's work at its largest (lead, on J2a), for a dry run: every judged candidate as a gap, its remaining
|
|
982
|
+
units the catalog layer's indexed units less its retrieved ones. Groups, shards, packets, payload and driver bytes,
|
|
983
|
+
input tokens at J0's density and output at the cap - counts only, labelled as the bound."""
|
|
984
|
+
context = sweep_context(run_dir, declaration)
|
|
985
|
+
sizes, basis = sweeps_of(declaration)
|
|
986
|
+
seats = sweep_seats(declaration)
|
|
987
|
+
remaining = {cid: remaining_of(context["index"], [r["unit_id"] for r in context["rows"][cid]["retrieved_units"]],
|
|
988
|
+
[UPPER_BOUND_LAYER]) for cid in judged}
|
|
989
|
+
groups = shard_plan(remaining, sizes["candidates_per_shard"], sizes["shard_units"])
|
|
990
|
+
inventory = packet.sha256_bytes((run_dir / "inventory" / "current.json").read_bytes())
|
|
991
|
+
schema_bytes = packet.schema_bytes(sweep_schema())
|
|
992
|
+
payload_bytes, driver = 0, {side: 0 for side in seats}
|
|
993
|
+
built = sweep_packets(context, groups, inventory)
|
|
994
|
+
for group, shard, _labels, text in built:
|
|
995
|
+
payload_bytes += len(text.encode("utf-8"))
|
|
996
|
+
for side, seat in seats.items():
|
|
997
|
+
item = f"sweep-{group}-{shard}-{side}"
|
|
998
|
+
made = packet.build(f"{run_dir.resolve().name}-{STAGE}-{item}-a1", STAGE, seat, text, schema_bytes)
|
|
999
|
+
driver[side] += bound.driver_bytes(made, schema_bytes)[0]
|
|
1000
|
+
calls = len(built) * len(seats)
|
|
1001
|
+
return {"basis": UPPER_BOUND_BASIS, "layer": UPPER_BOUND_LAYER, "sizes": sizes, "sizes_basis": basis, "seats": seats,
|
|
1002
|
+
"candidates": len(remaining), "remaining_units": sum(len(v) for v in remaining.values()),
|
|
1003
|
+
"groups": len(groups), "shards": sum(len(g["shards"]) for g in groups), "packets": calls,
|
|
1004
|
+
"pairs": sum(len(us) for _g, _s, labels, _t in built for us in labels.shard["pairs"].values()),
|
|
1005
|
+
"payload_bytes": payload_bytes, "driver_bytes": driver,
|
|
1006
|
+
"input_tokens_at_j0_density": {side: int(math.ceil(v / J0_DENSITY)) for side, v in driver.items()},
|
|
1007
|
+
"density": J0_DENSITY, "density_basis": J0_DENSITY_BASIS, "output_tokens_at_most": calls * sizes["output_cap"]}
|
|
1008
|
+
|
|
1009
|
+
|
|
1010
|
+
def absence_claims(judged, absent, not_both, sources, absence, layers):
|
|
1011
|
+
"""The judges' absence claims, counted whether or not they are swept: the candidates both judges judged whose agreed
|
|
1012
|
+
unit diagnoses touch no covering row (`absent_candidates`), by name and per candidate kind beside the number of that
|
|
1013
|
+
kind judged by both, with the reference point's state and every layer's status. Under the literal policy no
|
|
1014
|
+
reference point is complete while a layer has no producer, so nothing is swept, and this count is the measured share
|
|
1015
|
+
the lead's D-20261111-eaa2a8 names as the condition for reopening the scoped policy; it costs no call."""
|
|
1016
|
+
both = [cid for cid in judged if cid not in set(not_both)]
|
|
1017
|
+
kinds = sorted({sources[cid] for cid in judged})
|
|
1018
|
+
return {"count": len(absent), "candidates": sorted(absent), "judged_by_both": len(both),
|
|
1019
|
+
"by_kind": {kind: {"claims": sum(1 for cid in absent if sources[cid] == kind),
|
|
1020
|
+
"judged_by_both": sum(1 for cid in both if sources[cid] == kind)} for kind in kinds},
|
|
1021
|
+
"not_judged_by_both": sorted(not_both), "swept": absence.get("complete") is True,
|
|
1022
|
+
"reference": {"point": "current", "policy": absence.get("policy"),
|
|
1023
|
+
"complete": absence.get("complete") is True, "layers": dict(sorted(layers.items()))}}
|
|
1024
|
+
|
|
1025
|
+
|
|
1026
|
+
def sweep_stage(run_dir, stage, supervisor, declaration, judged, judgments, sources, caps, tranche):
|
|
1027
|
+
"""The absence sweeps over S6's judgments (plan WP-11 J3a, done-when 6): the judges' absence claims are counted
|
|
1028
|
+
first (`absence_claims`), at every reference point; at one the absence policy reads as incomplete, every absence is
|
|
1029
|
+
`unknown` and nothing is swept; otherwise each absence claim's remaining units are cut into shards (`shard_plan`,
|
|
1030
|
+
held to `shard_problems`), and each shard is sent to both sweeps with one payload bound to the inventory hash, each
|
|
1031
|
+
answer checked (`sweep_problems`) and kept under sweeps/<group>/<shard>/<a|b>.json. Returns the summary's `sweeps`
|
|
1032
|
+
section and the sweeps' receipts. `absent` names the claims a sweep stands behind, so it stays empty where none
|
|
1033
|
+
runs: a derivation waits for the sweeps of every candidate it lists."""
|
|
1034
|
+
checks = records.read_json(run_dir / "checks.json")
|
|
1035
|
+
absence = checks.get("absence") or {}
|
|
1036
|
+
sizes, basis = sweeps_of(declaration)
|
|
1037
|
+
section = {"reference": "current", "policy": absence.get("policy"), "complete": absence.get("complete") is True,
|
|
1038
|
+
"unknown_layers": absence.get("unknown_layers") or [], "sizes": sizes, "sizes_basis": basis,
|
|
1039
|
+
# the compiled text's would-be units S2 withheld and S5 summed (WP-11b X r1 (i)), carried to the report
|
|
1040
|
+
"withheld": absence.get("withheld"),
|
|
1041
|
+
"absent": [], "not_judged_by_both": [], "groups": [], "calls": []}
|
|
1042
|
+
absent, not_both = absent_candidates(judged, judgments, sources)
|
|
1043
|
+
statuses = current_point(records.read_json(run_dir / "inventory" / "current.json"))["layers"]
|
|
1044
|
+
section["claims"] = absence_claims(judged, absent, not_both, sources, absence, statuses)
|
|
1045
|
+
if not section["complete"]:
|
|
1046
|
+
section["why"] = ("absence unknown: the reference point is incomplete under the " + str(absence.get("policy"))
|
|
1047
|
+
+ " policy, so no absence claim stands and nothing is swept")
|
|
1048
|
+
return section, []
|
|
1049
|
+
seats = sweep_seats(declaration)
|
|
1050
|
+
context = sweep_context(run_dir, declaration)
|
|
1051
|
+
layers = sweep_layers(absence)
|
|
1052
|
+
remaining = {cid: remaining_of(context["index"], [r["unit_id"] for r in context["rows"][cid]["retrieved_units"]],
|
|
1053
|
+
layers) for cid in absent}
|
|
1054
|
+
groups = shard_plan(remaining, sizes["candidates_per_shard"], sizes["shard_units"])
|
|
1055
|
+
problems = shard_problems(groups, remaining)
|
|
1056
|
+
if problems:
|
|
1057
|
+
raise Refused("\n".join(problems))
|
|
1058
|
+
inventory = packet.sha256_bytes((run_dir / "inventory" / "current.json").read_bytes())
|
|
1059
|
+
held_schema = sweep_schema()
|
|
1060
|
+
schema_bytes = packet.schema_bytes(held_schema)
|
|
1061
|
+
receipts = []
|
|
1062
|
+
section.update(absent=absent, not_judged_by_both=not_both, layers=layers, inventory_sha256=inventory,
|
|
1063
|
+
groups=[{"group": g["group"], "candidates": g["candidates"],
|
|
1064
|
+
"shards": [{"shard": sh["shard"], "units": len(sh["units"]),
|
|
1065
|
+
"pairs": sum(len(us) for us in sh["pairs"].values())} for sh in g["shards"]]}
|
|
1066
|
+
for g in groups])
|
|
1067
|
+
limits = {side: limits_of(seat, run_dir, declaration, supervisor.seats_path, case=SWEEP_CASE,
|
|
1068
|
+
output_cap=sizes["output_cap"]) for side, seat in seats.items()}
|
|
1069
|
+
built = sweep_packets(context, groups, inventory)
|
|
1070
|
+
over_capacity(run_dir.resolve().name, [(f"sweep-{group}-{shard}-{side}", side, seat, text)
|
|
1071
|
+
for group, shard, _labels, text in built for side, seat in seats.items()],
|
|
1072
|
+
limits, schema_bytes, "SWEEP_OVER_CAPACITY", "the run declares a smaller sweeps.shard_units")
|
|
1073
|
+
# All or none (C3, lead's option (가)): the plan's claims, each call's input at most and its output cap, against
|
|
1074
|
+
# what S6 has left after the judgments. A sweep set that stops part-way leaves its claims waiting on sweeps that
|
|
1075
|
+
# never land; none sent leaves them unknown, by this name.
|
|
1076
|
+
need, unmeasured = 0, []
|
|
1077
|
+
for group, shard, _labels, text in built:
|
|
1078
|
+
for side, seat in seats.items():
|
|
1079
|
+
made = packet.build(f"{run_dir.resolve().name}-{STAGE}-sweep-{group}-{shard}-{side}-a1", STAGE, seat, text,
|
|
1080
|
+
schema_bytes)
|
|
1081
|
+
at_most = at_most_of(bound.driver_bytes(made, schema_bytes)[0], limits[side])
|
|
1082
|
+
if at_most is None:
|
|
1083
|
+
unmeasured.append(side)
|
|
1084
|
+
continue
|
|
1085
|
+
need += at_most + sizes["output_cap"]
|
|
1086
|
+
left = supervisor.remaining(STAGE)
|
|
1087
|
+
if not unmeasured and need > left:
|
|
1088
|
+
# the claims stay listed, so the derivation names them by this reason and does not read an unswept gap
|
|
1089
|
+
section.update(absent=absent, not_judged_by_both=not_both, layers=layers, inventory_sha256=inventory,
|
|
1090
|
+
run=False, plan={"calls": len(built) * len(seats), "claims_at_most": need, "left": left},
|
|
1091
|
+
why=f"SWEEPS_NOT_RUN budget: the plan's {len(built) * len(seats)} calls claim {need} at most and "
|
|
1092
|
+
f"S6 has {left} left, so no sweep is sent and every absence claim stays unknown")
|
|
1093
|
+
return section, []
|
|
1094
|
+
for group, shard, labels, text in built:
|
|
1095
|
+
payload_sha256 = packet.sha256_bytes(text.encode("utf-8"))
|
|
1096
|
+
row = {"group": group, "shard": shard, "seats": {}}
|
|
1097
|
+
for side, seat in seats.items():
|
|
1098
|
+
out = supervisor.item(STAGE, f"sweep-{group}-{shard}-{side}", seat, text, held_schema, case_type=SWEEP_CASE,
|
|
1099
|
+
caps=caps, view_window=False, tranche=tranche, max_output_tokens=sizes["output_cap"],
|
|
1100
|
+
stage_check=sweep_check(labels), resume=True,
|
|
1101
|
+
context_capacity=limits[side]["capacity"],
|
|
1102
|
+
packet_check=lambda made, bounds=limits[side], side=side: attempt_problems(
|
|
1103
|
+
made, bounds, schema_bytes, f"sweep {side}", "SWEEP_OVER_CAPACITY"))
|
|
1104
|
+
held = call_row(out)
|
|
1105
|
+
if out["outcome"] == "accepted":
|
|
1106
|
+
call_dir = pathlib.Path(out["accepted"])
|
|
1107
|
+
call_id = records.read_json(call_dir / "call.json")["call_id"]
|
|
1108
|
+
receipt = records.read_json(call_dir / "receipt.json")
|
|
1109
|
+
rel = sweep_rel(group, shard, side)
|
|
1110
|
+
records.write_json(run_dir, run_dir / rel, {
|
|
1111
|
+
"group": group, "shard": shard, "side": side, "seat": seat, "call_id": call_id,
|
|
1112
|
+
"inventory_sha256": inventory, "payload_sha256": payload_sha256,
|
|
1113
|
+
"packet_sha256": receipt.get("packet_sha256"),
|
|
1114
|
+
"pairs": labels.resolve(gate.accepted(call_dir, judged=True))})
|
|
1115
|
+
stage.output(rel)
|
|
1116
|
+
receipts.append((f"sweep/{group}/{shard}", seat, call_id, receipt, payload_sha256,
|
|
1117
|
+
corrected_sha256(call_dir, text)))
|
|
1118
|
+
held.update(call_id=call_id, result=rel)
|
|
1119
|
+
row["seats"][side] = held
|
|
1120
|
+
section["calls"].append(row)
|
|
1121
|
+
return section, receipts
|
|
1122
|
+
|
|
1123
|
+
|
|
1124
|
+
# ---- Judge B's cross-review of an absence claim (plan WP-11 J3b, done-when 3, F10) --------------------------------
|
|
1125
|
+
|
|
1126
|
+
CROSS_TEMPLATE = "cross_review"
|
|
1127
|
+
CROSS_SCHEMA_PATH = HERE / "schemas" / "cross_review.schema.json"
|
|
1128
|
+
CROSS_CASE = "cross_review" # a cross-review call's class (dispatch.class_key)
|
|
1129
|
+
NEGATIVES = 50 # design §6.2: fifty negatives, drawn by code from the run id
|
|
1130
|
+
|
|
1131
|
+
|
|
1132
|
+
def cross_schema():
|
|
1133
|
+
return json.loads(CROSS_SCHEMA_PATH.read_text(encoding="utf-8"))
|
|
1134
|
+
|
|
1135
|
+
|
|
1136
|
+
def sweep_marks(results):
|
|
1137
|
+
"""`{candidate id: {unit id: {side: {situation, action, reason}}}}` over kept sweep results (`kept_sweep`)."""
|
|
1138
|
+
marks = {}
|
|
1139
|
+
for held in results:
|
|
1140
|
+
for pair in held["pairs"]:
|
|
1141
|
+
marks.setdefault(pair["candidate_id"], {}).setdefault(pair["unit_id"], {})[held["side"]] = {
|
|
1142
|
+
k: pair[k] for k in ("situation", "action", "reason")}
|
|
1143
|
+
return marks
|
|
1144
|
+
|
|
1145
|
+
|
|
1146
|
+
def flags_of(marks):
|
|
1147
|
+
"""The units either sweep marked as a partial match - a situation or an action yes - in unit id order."""
|
|
1148
|
+
return sorted(u for u, sides in marks.items() if any("yes" in (m["situation"], m["action"]) for m in sides.values()))
|
|
1149
|
+
|
|
1150
|
+
|
|
1151
|
+
def negatives_of(marks, seed, cid, n=NEGATIVES):
|
|
1152
|
+
"""`n` of the units both sweeps marked as no match, drawn by code: the first by sha256 of the seed (the run id),
|
|
1153
|
+
the candidate and the unit. Fewer when fewer are there."""
|
|
1154
|
+
both_no = [u for u, sides in marks.items() if len(sides) == len(SWEEP_SEAT_KEYS)
|
|
1155
|
+
and all(m["situation"] == m["action"] == "no" for m in sides.values())]
|
|
1156
|
+
return sorted(both_no, key=lambda u: hashlib.sha256(f"{seed}\x00{cid}\x00{u}".encode("utf-8")).hexdigest())[:n]
|
|
1157
|
+
|
|
1158
|
+
|
|
1159
|
+
class CrossLabels:
|
|
1160
|
+
"""One cross-review packet's labels: the candidate k1, and its flagged and sampled units n1, ... in unit id order,
|
|
1161
|
+
each with both sweeps' marks."""
|
|
1162
|
+
|
|
1163
|
+
def __init__(self, candidate, marks, flags, negatives, units, entries):
|
|
1164
|
+
self.candidate, self.marks, self.unit_store = candidate, marks, units
|
|
1165
|
+
self.flags, self.negatives = list(flags), list(negatives)
|
|
1166
|
+
self.units = {f"n{n}": u for n, u in enumerate(sorted(set(flags) | set(negatives)), 1)}
|
|
1167
|
+
self.view = sweep_view(candidate, entries, units)
|
|
1168
|
+
|
|
1169
|
+
def candidate_text(self):
|
|
1170
|
+
return json.dumps({"candidate": "k1", **self.view}, ensure_ascii=False)
|
|
1171
|
+
|
|
1172
|
+
def units_text(self):
|
|
1173
|
+
return "\n".join(json.dumps({"unit": label, "layer": self.unit_store[uid]["layer"],
|
|
1174
|
+
"path": self.unit_store[uid].get("path"),
|
|
1175
|
+
"heading": self.unit_store[uid].get("heading") or "",
|
|
1176
|
+
"text": self.unit_store[uid]["text"],
|
|
1177
|
+
"sweeps": {side: self.marks[uid][side] for side in sorted(self.marks[uid])}},
|
|
1178
|
+
ensure_ascii=False) for label, uid in self.units.items())
|
|
1179
|
+
|
|
1180
|
+
def resolve(self, answer):
|
|
1181
|
+
return [{"unit_id": self.units[r["unit"]], **{k: r[k] for k in ("situation", "action", "reason")}}
|
|
1182
|
+
for r in answer["verdicts"]]
|
|
1183
|
+
|
|
1184
|
+
|
|
1185
|
+
def cross_payload(labels):
|
|
1186
|
+
"""One absence claim's cross-review payload (`packets/cross_review.md`)."""
|
|
1187
|
+
return packet.render(CROSS_TEMPLATE, {"candidate": labels.candidate_text(), "units": labels.units_text()})
|
|
1188
|
+
|
|
1189
|
+
|
|
1190
|
+
def cross_problems(labels, answer):
|
|
1191
|
+
"""What a schema-valid cross-review gets wrong against its packet: every unit shown judged exactly once
|
|
1192
|
+
(CROSS_UNIT_MISSING, CROSS_UNIT_TWICE), by a label the packet shows (UNKNOWN_LABEL)."""
|
|
1193
|
+
out, seen = [], {}
|
|
1194
|
+
for n, row in enumerate(answer.get("verdicts") or []):
|
|
1195
|
+
where = f"verdicts[{n}] {row['unit']}"
|
|
1196
|
+
if row["unit"] not in labels.units:
|
|
1197
|
+
out.append(f"UNKNOWN_LABEL {where}: this packet shows no unit so labelled")
|
|
1198
|
+
elif row["unit"] in seen:
|
|
1199
|
+
out.append(f"CROSS_UNIT_TWICE {where}: judged at verdicts[{seen[row['unit']]}] already")
|
|
1200
|
+
else:
|
|
1201
|
+
seen[row["unit"]] = n
|
|
1202
|
+
out += [f"CROSS_UNIT_MISSING {label}: the packet shows it and the review does not judge it"
|
|
1203
|
+
for label in labels.units if label not in seen]
|
|
1204
|
+
return out
|
|
1205
|
+
|
|
1206
|
+
|
|
1207
|
+
def cross_check(labels):
|
|
1208
|
+
"""The stage's check of a cross-review attempt, as `Supervisor.item(stage_check=)` asks it."""
|
|
1209
|
+
from runlib import stage_read
|
|
1210
|
+
|
|
1211
|
+
def judged(call_dir):
|
|
1212
|
+
return cross_problems(labels, stage_read.answer_of(call_dir))
|
|
1213
|
+
return judged
|
|
1214
|
+
|
|
1215
|
+
|
|
1216
|
+
def cross_rel(item):
|
|
1217
|
+
return f"cross_review/{item}.json"
|
|
1218
|
+
|
|
1219
|
+
|
|
1220
|
+
def cross_review_problems(record, flags, negatives, payload_sha256):
|
|
1221
|
+
"""Done-when 3 over a kept cross-review against what the sweep results give now: every partial flag either sweep
|
|
1222
|
+
raised and the drawn negatives in it (CROSS_REVIEW_INCOMPLETE), and its payload the one those results build
|
|
1223
|
+
(CROSS_REVIEW_STALE: a sweep's mark or reason changed after the review was sent)."""
|
|
1224
|
+
cid = record.get("candidate_id")
|
|
1225
|
+
out = []
|
|
1226
|
+
missing = sorted(set(flags) - set(record.get("partial_flags") or []))
|
|
1227
|
+
if missing:
|
|
1228
|
+
out.append(f"CROSS_REVIEW_INCOMPLETE {cid}: partial flags no review carries {missing[:5]}")
|
|
1229
|
+
if list(record.get("seeded_negatives") or []) != list(negatives):
|
|
1230
|
+
out.append(f"CROSS_REVIEW_INCOMPLETE {cid}: its {len(record.get('seeded_negatives') or [])} negatives are not the "
|
|
1231
|
+
f"{len(negatives)} drawn from the run id")
|
|
1232
|
+
if record.get("payload_sha256") != payload_sha256:
|
|
1233
|
+
out.append(f"CROSS_REVIEW_STALE {cid}: its payload {str(record.get('payload_sha256'))[:12]} is not the one the "
|
|
1234
|
+
f"sweep results build now ({payload_sha256[:12]})")
|
|
1235
|
+
return out
|
|
1236
|
+
|
|
1237
|
+
|
|
1238
|
+
def cross_stage(run_dir, stage, supervisor, declaration, swept, item_of_cid, caps, tranche):
|
|
1239
|
+
"""Judge B's cross-review of every absence claim the sweeps judged whole (plan WP-11 J3b, done-when 3): its packet
|
|
1240
|
+
carries every unit either sweep flagged and NEGATIVES units both marked as none, drawn from the run id, each with both
|
|
1241
|
+
sweeps' marks and reasons; the review judges each unit once (`cross_problems`) and is kept under
|
|
1242
|
+
cross_review/<item>.json, held to what the sweep results give (`cross_review_problems`). A claim whose sweeps did not
|
|
1243
|
+
all finish is not reviewed, and is named. Returns the summary's `cross_review` section and the calls' receipts."""
|
|
1244
|
+
section = {"seat": None, "reviewed": [], "exhausted": [], "not_reviewed": [], "calls": [], "negatives": NEGATIVES}
|
|
1245
|
+
if not swept.get("complete") or not swept.get("absent"):
|
|
1246
|
+
section["why"] = "no absence claim was swept" if swept.get("complete") else swept.get("why")
|
|
1247
|
+
return section, []
|
|
1248
|
+
seat = seats_of(declaration)["B"]
|
|
1249
|
+
section["seat"] = seat
|
|
1250
|
+
context = sweep_context(run_dir, declaration)
|
|
1251
|
+
inventory = swept["inventory_sha256"]
|
|
1252
|
+
results, finished = [], {}
|
|
1253
|
+
for row in swept["calls"]:
|
|
1254
|
+
for side, held in row["seats"].items():
|
|
1255
|
+
if held["outcome"] == "accepted":
|
|
1256
|
+
results.append(kept_sweep(run_dir, held["result"], inventory))
|
|
1257
|
+
marks = sweep_marks(results)
|
|
1258
|
+
run_id = run_dir.resolve().name
|
|
1259
|
+
held_schema = cross_schema()
|
|
1260
|
+
receipts = []
|
|
1261
|
+
todo = []
|
|
1262
|
+
for g in swept["groups"]:
|
|
1263
|
+
for cid in g["candidates"]:
|
|
1264
|
+
mine = marks.get(cid) or {}
|
|
1265
|
+
whole = [u for u, sides in mine.items() if len(sides) == len(SWEEP_SEAT_KEYS)]
|
|
1266
|
+
shards = [r for r in swept["calls"] if r["group"] == g["group"]]
|
|
1267
|
+
if any(h["outcome"] != "accepted" for r in shards for h in r["seats"].values()) or len(whole) != len(mine):
|
|
1268
|
+
section["not_reviewed"].append({"candidate_id": cid, "why": "a sweep of its group did not finish"})
|
|
1269
|
+
continue
|
|
1270
|
+
flags, negatives = flags_of(mine), negatives_of(mine, run_id, cid)
|
|
1271
|
+
if not mine:
|
|
1272
|
+
# nothing remained to sweep: S5 retrieved every unit the policy reads for this claim, so the judges' own
|
|
1273
|
+
# judgments are the exhaustive check, and there is nothing to review or reconsider (Codex WP-11 r1 #4:
|
|
1274
|
+
# such a claim was named not_reviewed, never reconsidered, and so never derived)
|
|
1275
|
+
section["exhausted"].append(cid)
|
|
1276
|
+
continue
|
|
1277
|
+
labels = CrossLabels(context["by_id"][cid], mine, flags, negatives, context["units"], context["entries"])
|
|
1278
|
+
todo.append((cid, flags, negatives, labels, cross_payload(labels)))
|
|
1279
|
+
# every cross-review packet is held to Judge B's capacity before the first is sent (Codex WP-11 r1 #3)
|
|
1280
|
+
schema_bytes = packet.schema_bytes(held_schema)
|
|
1281
|
+
limits = limits_of(seat, run_dir, declaration, supervisor.seats_path, case=CROSS_CASE)
|
|
1282
|
+
over_capacity(run_id, [(f"{item_of_cid(cid)}-X", "B", seat, text) for cid, _f, _n, _l, text in todo], {"B": limits},
|
|
1283
|
+
schema_bytes, "CROSS_OVER_CAPACITY", "a claim with this many flagged units is reviewed by a seat with "
|
|
1284
|
+
"more context")
|
|
1285
|
+
for cid, flags, negatives, labels, text in todo:
|
|
1286
|
+
payload_sha256 = packet.sha256_bytes(text.encode("utf-8"))
|
|
1287
|
+
item = f"{item_of_cid(cid)}-X"
|
|
1288
|
+
out = supervisor.item(STAGE, item, seat, text, held_schema, case_type=CROSS_CASE, caps=caps,
|
|
1289
|
+
view_window=False, tranche=tranche, max_output_tokens=OUTPUT_CAP,
|
|
1290
|
+
stage_check=cross_check(labels), resume=True, context_capacity=limits["capacity"],
|
|
1291
|
+
packet_check=lambda made: attempt_problems(made, limits, schema_bytes, "B",
|
|
1292
|
+
"CROSS_OVER_CAPACITY"))
|
|
1293
|
+
held = call_row(out)
|
|
1294
|
+
if out["outcome"] == "accepted":
|
|
1295
|
+
call_dir = pathlib.Path(out["accepted"])
|
|
1296
|
+
call_id = records.read_json(call_dir / "call.json")["call_id"]
|
|
1297
|
+
receipt = records.read_json(call_dir / "receipt.json")
|
|
1298
|
+
rel = cross_rel(item_of_cid(cid))
|
|
1299
|
+
record = {"candidate_id": cid, "seat": seat, "call_id": call_id, "inventory_sha256": inventory,
|
|
1300
|
+
"seed": run_id, "payload_sha256": payload_sha256, "packet_sha256": receipt.get("packet_sha256"),
|
|
1301
|
+
"partial_flags": flags, "seeded_negatives": negatives,
|
|
1302
|
+
"verdicts": labels.resolve(gate.accepted(call_dir, judged=True))}
|
|
1303
|
+
problems = cross_review_problems(record, flags, negatives, payload_sha256)
|
|
1304
|
+
if problems:
|
|
1305
|
+
raise Refused("\n".join(problems))
|
|
1306
|
+
records.write_json(run_dir, run_dir / rel, record)
|
|
1307
|
+
stage.output(rel)
|
|
1308
|
+
receipts.append((f"cross/{cid}", seat, call_id, receipt, payload_sha256, corrected_sha256(call_dir, text)))
|
|
1309
|
+
held.update(call_id=call_id, result=rel)
|
|
1310
|
+
section["reviewed"].append(cid)
|
|
1311
|
+
section["calls"].append({"candidate_id": cid, "flags": len(flags), "negatives": len(negatives), **held})
|
|
1312
|
+
return section, receipts
|
|
1313
|
+
|
|
1314
|
+
|
|
1315
|
+
# ---- the reconsiderations (plan WP-11 J3c, done-when 3, design §6.2) ----------------------------------------------
|
|
1316
|
+
|
|
1317
|
+
RECONSIDER = "R" # a reconsideration's item is `<item>-R<judge>`
|
|
1318
|
+
RECONSIDER_TEMPLATE = "reconsider"
|
|
1319
|
+
RECONSIDER_SCHEMA_PATH = HERE / "schemas" / "reconsider.schema.json"
|
|
1320
|
+
RECONSIDER_CASE = "reconsider" # a reconsideration call's class (dispatch.class_key)
|
|
1321
|
+
RECONSIDER_FIELDS = ("units", "matching_units")
|
|
1322
|
+
# what a reconsideration does not answer: the candidate was judged by its first call, and admission reads that one
|
|
1323
|
+
RECONSIDER_REFUSED = ("requirements", "consequence_class", "no_longer_arises", "ledger_relations")
|
|
1324
|
+
RECONSIDER_COMMENT = ("design §6.2: a unit either sweep or Judge B flagged returns to both judges; plan WP-11 J3c. The "
|
|
1325
|
+
"judge schema's `units` and `matching_units` and the definitions they reach, nothing else: the "
|
|
1326
|
+
"candidate is not judged again. Projected from judge.schema.json (stage_judge.reconsider_projection), "
|
|
1327
|
+
"and held equal to it by stage_judge's self-test.")
|
|
1328
|
+
|
|
1329
|
+
|
|
1330
|
+
def reconsider_schema():
|
|
1331
|
+
return json.loads(RECONSIDER_SCHEMA_PATH.read_text(encoding="utf-8"))
|
|
1332
|
+
|
|
1333
|
+
|
|
1334
|
+
def reconsider_projection(held=None):
|
|
1335
|
+
"""What `schemas/reconsider.schema.json` must be: the judge schema's `units` and `matching_units` with the
|
|
1336
|
+
definitions they reach, closed, and no candidate-level field."""
|
|
1337
|
+
judge = held if held is not None else schema()
|
|
1338
|
+
defs = judge.get("$defs") or {}
|
|
1339
|
+
keep, todo = set(), [judge["properties"][f] for f in RECONSIDER_FIELDS]
|
|
1340
|
+
while todo:
|
|
1341
|
+
node = todo.pop()
|
|
1342
|
+
if isinstance(node, dict):
|
|
1343
|
+
ref = node.get("$ref")
|
|
1344
|
+
if isinstance(ref, str) and ref.startswith("#/$defs/") and ref.split("/")[-1] not in keep:
|
|
1345
|
+
keep.add(ref.split("/")[-1])
|
|
1346
|
+
todo.append(defs[ref.split("/")[-1]])
|
|
1347
|
+
todo += list(node.values())
|
|
1348
|
+
elif isinstance(node, list):
|
|
1349
|
+
todo += node
|
|
1350
|
+
return {"$schema": judge.get("$schema"), "$comment": RECONSIDER_COMMENT, "title": "S6 reconsideration",
|
|
1351
|
+
"type": "object", "additionalProperties": False, "required": list(RECONSIDER_FIELDS),
|
|
1352
|
+
"properties": {f: judge["properties"][f] for f in RECONSIDER_FIELDS},
|
|
1353
|
+
"$defs": {k: defs[k] for k in sorted(keep)}}
|
|
1354
|
+
|
|
1355
|
+
|
|
1356
|
+
def reconsider_payload(labels):
|
|
1357
|
+
"""A reconsideration's payload both judges are sent (N#1): `packets/reconsider.md` with the candidate, its claims,
|
|
1358
|
+
the returned units and their context."""
|
|
1359
|
+
return packet.render(RECONSIDER_TEMPLATE, {"candidate": labels.candidate_text(), "claims": labels.claims_text(),
|
|
1360
|
+
"units": labels.units_text(), "context": labels.context_text()})
|
|
1361
|
+
|
|
1362
|
+
|
|
1363
|
+
def reconsideration_rel(item, who):
|
|
1364
|
+
"""Where one judge's reconsideration of a candidate is kept (plan WP-11: `reconsiderations/<candidate>/{A,B}.json`)."""
|
|
1365
|
+
return f"reconsiderations/{item}/{who}.json"
|
|
1366
|
+
|
|
1367
|
+
|
|
1368
|
+
def returned_of(record):
|
|
1369
|
+
"""The units a kept cross-review returns to both judges (design §6.2): every flag either sweep raised and every
|
|
1370
|
+
unit Judge B marked a match, in unit id order."""
|
|
1371
|
+
return sorted(set(record.get("partial_flags") or [])
|
|
1372
|
+
| {v["unit_id"] for v in record.get("verdicts") or [] if "yes" in (v["situation"], v["action"])})
|
|
1373
|
+
|
|
1374
|
+
|
|
1375
|
+
def returned_labels(labels, unit_ids):
|
|
1376
|
+
"""The judgment packet's labels for a reconsideration: the same candidate, claims and quotes, the returned units in
|
|
1377
|
+
place of the retrieved ones, and no ledger entry, since the candidate's first judgment related every one S5
|
|
1378
|
+
retrieved. A unit or ledger entry the candidate's own fields name (a lifecycle candidate's entries and targets, a
|
|
1379
|
+
type G tension's cluster) that this packet does not show is labelled o1, ...: a reference, never judged here, and
|
|
1380
|
+
never shown by its stored id (Codex WP-11 r1 #5: dropping the entries and the retrieved units left those ids raw)."""
|
|
1381
|
+
held = JudgeLabels(labels.candidate, {"retrieved_units": [{"unit_id": u} for u in unit_ids], "ledger_entries": []},
|
|
1382
|
+
labels.unit_store, labels.entry_store, labels.subject_of, labels.evidence_store)
|
|
1383
|
+
named = []
|
|
1384
|
+
|
|
1385
|
+
def walk(value):
|
|
1386
|
+
if isinstance(value, dict):
|
|
1387
|
+
for v in value.values():
|
|
1388
|
+
walk(v)
|
|
1389
|
+
elif isinstance(value, list):
|
|
1390
|
+
for v in value:
|
|
1391
|
+
walk(v)
|
|
1392
|
+
elif isinstance(value, str):
|
|
1393
|
+
target = value[len(CLUSTER_PREFIX):] if value.startswith(CLUSTER_PREFIX) else value
|
|
1394
|
+
if (target in held.unit_store or target in held.entry_store) and target not in held.label_of:
|
|
1395
|
+
named.append(target)
|
|
1396
|
+
walk({key: v for key, v in held.candidate.items() if key not in ("candidate_id", "label", "event_ids", "sessions")})
|
|
1397
|
+
held.references = {f"o{n}": stored for n, stored in enumerate(dict.fromkeys(named), 1)}
|
|
1398
|
+
held.label_of.update({stored: label for label, stored in held.references.items()})
|
|
1399
|
+
return held
|
|
1400
|
+
|
|
1401
|
+
|
|
1402
|
+
def reconsideration_problems(cid, returned, held):
|
|
1403
|
+
"""Done-when 3: every returned unit reconsidered by both judges. RECONSIDERATION_MISSING for a judge with no
|
|
1404
|
+
accepted reconsideration, or one that judges other units than the cross-review returned."""
|
|
1405
|
+
out = []
|
|
1406
|
+
for who in SEAT_KEYS:
|
|
1407
|
+
judgment = held.get(who)
|
|
1408
|
+
if judgment is None:
|
|
1409
|
+
out.append(f"RECONSIDERATION_MISSING {cid} {who}: the {len(returned)} units its cross-review returned have no "
|
|
1410
|
+
f"accepted reconsideration by Judge {who}")
|
|
1411
|
+
continue
|
|
1412
|
+
judged = sorted(u["unit_id"] for u in judgment.get("units") or [])
|
|
1413
|
+
if judged != sorted(returned):
|
|
1414
|
+
out.append(f"RECONSIDERATION_MISSING {cid} {who}: Judge {who}'s reconsideration judges {len(judged)} units "
|
|
1415
|
+
f"and its cross-review returned {len(returned)}; not judged {sorted(set(returned) - set(judged))[:5]}")
|
|
1416
|
+
return out
|
|
1417
|
+
|
|
1418
|
+
|
|
1419
|
+
def reconsidered_diagnosis(original, held, lifecycle):
|
|
1420
|
+
"""`(diagnosis, row id)` of an absence claim once both judges reconsidered the returned units: derive's candidate
|
|
1421
|
+
diagnosis at a complete reference point over the units of its first judgments and the reconsidered ones. A unit
|
|
1422
|
+
both now find matching contradicts the claim; one they disagree on that could reach a row before the gap makes it
|
|
1423
|
+
`unknown` by `disputed` (O4)."""
|
|
1424
|
+
units = unit_diagnoses(original)
|
|
1425
|
+
if held:
|
|
1426
|
+
units.update(unit_diagnoses(held))
|
|
1427
|
+
return derive.candidate_diagnosis(units, True, lifecycle)
|
|
1428
|
+
|
|
1429
|
+
|
|
1430
|
+
def reconsider_stage(run_dir, stage, supervisor, declaration, summary, packets, judgments, crossed, caps, tranche):
|
|
1431
|
+
"""Both judges' reconsideration of every absence claim Judge B reviewed (plan WP-11 J3c, done-when 3): the returned
|
|
1432
|
+
units (`returned_of`) go to Judge A and Judge B in one packet (`reconsider_payload`, N#1) asking for those units and
|
|
1433
|
+
their matching units only (`reconsider_schema`; `check` refuses a candidate-level field by FIELD_UNEXPECTED), kept
|
|
1434
|
+
under reconsiderations/<item>/<A|B>.json, and the claim is diagnosed again
|
|
1435
|
+
(`reconsidered_diagnosis`). A claim nothing returned keeps its gap without a call; one missing a judge's
|
|
1436
|
+
reconsideration is named (`reconsideration_problems`) and not diagnosed. Returns the summary's `reconsiderations`
|
|
1437
|
+
section, the calls' receipts, and `{candidate id: {A, B}}` of the reconsiderations it accepted, which derive_stage
|
|
1438
|
+
reads in place of their files."""
|
|
1439
|
+
section = {"reconsidered": [], "not_reconsidered": [], "missing": [], "calls": []}
|
|
1440
|
+
accepted = {} # the judgments of every claim reconsidered here, which derive_stage reads in place of the files
|
|
1441
|
+
held_schema = reconsider_schema()
|
|
1442
|
+
schema_bytes = packet.schema_bytes(held_schema)
|
|
1443
|
+
limits = {}
|
|
1444
|
+
sources = {r["candidate_id"]: r["source"] for r in summary["packets"]}
|
|
1445
|
+
receipts = []
|
|
1446
|
+
for cid in crossed.get("exhausted") or []: # nothing remained to sweep, so nothing returns: its gap stands as judged
|
|
1447
|
+
diagnosis, row_id = reconsidered_diagnosis(judgments[cid], {}, lifecycle_of(sources[cid]))
|
|
1448
|
+
section["reconsidered"].append({"candidate_id": cid, "returned": 0, "diagnosis": diagnosis, "row": row_id,
|
|
1449
|
+
"exhausted": True})
|
|
1450
|
+
for cid in crossed.get("reviewed") or []:
|
|
1451
|
+
item = item_of(cid)
|
|
1452
|
+
returned = returned_of(records.read_json(run_dir / cross_rel(item)))
|
|
1453
|
+
lifecycle = lifecycle_of(sources[cid])
|
|
1454
|
+
if not returned:
|
|
1455
|
+
diagnosis, row_id = reconsidered_diagnosis(judgments[cid], {}, lifecycle)
|
|
1456
|
+
section["reconsidered"].append({"candidate_id": cid, "returned": 0, "diagnosis": diagnosis, "row": row_id})
|
|
1457
|
+
continue
|
|
1458
|
+
labels = returned_labels(packets[cid][0], returned)
|
|
1459
|
+
text = reconsider_payload(labels)
|
|
1460
|
+
payload_sha256 = packet.sha256_bytes(text.encode("utf-8"))
|
|
1461
|
+
row, held = {"candidate_id": cid, "item": item, "returned": len(returned), "seats": {}}, {}
|
|
1462
|
+
for who, seat in summary["seats"].items():
|
|
1463
|
+
if who not in limits:
|
|
1464
|
+
limits[who] = limits_of(seat, run_dir, declaration, supervisor.seats_path, case=RECONSIDER_CASE)
|
|
1465
|
+
bounds = limits[who]
|
|
1466
|
+
out = supervisor.item(STAGE, f"{item}-{RECONSIDER}{who}", seat, text, held_schema, case_type=RECONSIDER_CASE,
|
|
1467
|
+
caps=caps, view_window=False, tranche=tranche, max_output_tokens=OUTPUT_CAP,
|
|
1468
|
+
stage_check=check(labels, bounds["capacity"], reconsider=True), resume=True,
|
|
1469
|
+
context_capacity=bounds["capacity"],
|
|
1470
|
+
packet_check=lambda built, bounds=bounds, who=who: attempt_problems(
|
|
1471
|
+
built, bounds, schema_bytes, who))
|
|
1472
|
+
call = call_row(out)
|
|
1473
|
+
if out["outcome"] == "accepted":
|
|
1474
|
+
call_dir = pathlib.Path(out["accepted"])
|
|
1475
|
+
call_id = records.read_json(call_dir / "call.json")["call_id"]
|
|
1476
|
+
receipt = records.read_json(call_dir / "receipt.json")
|
|
1477
|
+
rel = reconsideration_rel(item, who)
|
|
1478
|
+
held[who] = labels.resolve(gate.accepted(call_dir, judged=True))
|
|
1479
|
+
records.write_json(run_dir, run_dir / rel, {
|
|
1480
|
+
"candidate_id": cid, "item": item, "judge": who, "seat": seat, "call_id": call_id,
|
|
1481
|
+
"payload_sha256": payload_sha256, "packet_sha256": receipt.get("packet_sha256"),
|
|
1482
|
+
"returned": returned, "judgment": held[who]})
|
|
1483
|
+
stage.output(rel)
|
|
1484
|
+
receipts.append((f"reconsider/{cid}", seat, call_id, receipt, payload_sha256,
|
|
1485
|
+
corrected_sha256(call_dir, text)))
|
|
1486
|
+
call.update(call_id=call_id, reconsideration=rel)
|
|
1487
|
+
row["seats"][who] = call
|
|
1488
|
+
section["calls"].append(row)
|
|
1489
|
+
problems = reconsideration_problems(cid, returned, held)
|
|
1490
|
+
if problems:
|
|
1491
|
+
section["missing"] += problems
|
|
1492
|
+
section["not_reconsidered"].append({"candidate_id": cid, "why": "RECONSIDERATION_MISSING"})
|
|
1493
|
+
continue
|
|
1494
|
+
diagnosis, row_id = reconsidered_diagnosis(judgments[cid], held, lifecycle)
|
|
1495
|
+
section["reconsidered"].append({"candidate_id": cid, "returned": len(returned), "diagnosis": diagnosis,
|
|
1496
|
+
"row": row_id})
|
|
1497
|
+
accepted[cid] = held
|
|
1498
|
+
return section, receipts, accepted
|
|
1499
|
+
|
|
1500
|
+
|
|
1501
|
+
# ---- the derivations (plan WP-11 J4a, design §4's S6 row, §6.4) -------------------------------------------------
|
|
1502
|
+
|
|
1503
|
+
DERIVATIONS = "judgments/derivations.json"
|
|
1504
|
+
TEST_STATE = "untested: s8_deferred" # release 1 runs no S8 (D-20261111-818391)
|
|
1505
|
+
DELIVERY_WAITING = "delivery_assembly_waiting" # lead decision D3: S5b assembles it, and S6 does not read it yet
|
|
1506
|
+
UNIT_OUTCOMES_NONE = ("unit outcomes are read at the release reference point (design §6.4), and S6 judges the current "
|
|
1507
|
+
"point only until S5 retrieves at a release point (D-20261111-c4fa71): S7 receives no unit outcome in "
|
|
1508
|
+
"release 1")
|
|
1509
|
+
ARC_UNDETERMINED = ("an arc retrospective the owner confirms in the review (design §7.4) is the only producer, and the "
|
|
1510
|
+
"review comes after S6; derive is given arc_confirmed false, so a type G candidate is eligible by "
|
|
1511
|
+
"its lineage count alone (D-20261111-f122c0)")
|
|
1512
|
+
|
|
1513
|
+
|
|
1514
|
+
G_TYPES = tuple(next(r for r in derive.table()["promotion"] if r["id"] == "type_g")["types"])
|
|
1515
|
+
|
|
1516
|
+
|
|
1517
|
+
def marks_of(judgment):
|
|
1518
|
+
"""A judgment's requirement marks as derive reads them: `{requirement: mark}`."""
|
|
1519
|
+
return {name: held["mark"] for name, held in (judgment.get("requirements") or {}).items()}
|
|
1520
|
+
|
|
1521
|
+
|
|
1522
|
+
def judged_units(held):
|
|
1523
|
+
"""`{unit id: {A: {situation, action, following, contribution}, B: ...}}` over both judges' judgments of one packet:
|
|
1524
|
+
a matching unit's following and contribution from its `matching_units` row, None for a unit that does not match."""
|
|
1525
|
+
out = {}
|
|
1526
|
+
for who, judgment in held.items():
|
|
1527
|
+
matching = {m["unit_id"]: m for m in judgment.get("matching_units") or []}
|
|
1528
|
+
for u in judgment["units"]:
|
|
1529
|
+
m = matching.get(u["unit_id"]) or {}
|
|
1530
|
+
out.setdefault(u["unit_id"], {})[who] = {"situation": u["situation"], "action": u["action"],
|
|
1531
|
+
"following": m.get("following"), "contribution": m.get("contribution")}
|
|
1532
|
+
return out
|
|
1533
|
+
|
|
1534
|
+
|
|
1535
|
+
def current_point(current):
|
|
1536
|
+
"""The current reference point as derive reads one: S2's completeness flag and its layers' statuses."""
|
|
1537
|
+
return {"complete": (current.get("reference") or {}).get("complete") is True,
|
|
1538
|
+
"layers": {row["layer"]: row["status"] for row in current.get("layers") or []}}
|
|
1539
|
+
|
|
1540
|
+
|
|
1541
|
+
def derivation_input(candidate, source, row, first, again, point):
|
|
1542
|
+
"""`derive.unit_outcome`'s judgment for one candidate: its type and lifecycle, both judges' requirement marks,
|
|
1543
|
+
class and no_longer_arises from their first judgments, the current point's units - the ones S5 retrieved and the
|
|
1544
|
+
ones reconsidered (`again`, may be empty) - S5's checks passed (it was judged), and its counted lineages. No release
|
|
1545
|
+
point: S6 judges the current one only until S5 retrieves at a release point (D-20261111-c4fa71). No arc
|
|
1546
|
+
confirmation has a producer in S6, so it is False."""
|
|
1547
|
+
units = judged_units(first)
|
|
1548
|
+
units.update(judged_units(again) if again else {})
|
|
1549
|
+
return {"candidate": {"candidate_id": candidate["candidate_id"], "type": candidate.get("type"),
|
|
1550
|
+
"lifecycle": lifecycle_of(source)},
|
|
1551
|
+
"judges": {who: {"requirements": marks_of(first[who]), "consequence_class": first[who].get("consequence_class"),
|
|
1552
|
+
"no_longer_arises": (first[who].get("no_longer_arises") or {}).get("value") is True}
|
|
1553
|
+
for who in SEAT_KEYS},
|
|
1554
|
+
"points": {"current": {**point, "units": units}},
|
|
1555
|
+
"checks_pass": True, "lineages": (row.get("recurrence") or {}).get("count", 0),
|
|
1556
|
+
"arc_confirmed": False} # undetermined, not false: ARC_UNDETERMINED
|
|
1557
|
+
|
|
1558
|
+
|
|
1559
|
+
def derivation_given(candidate, source, check_row, first, point, again):
|
|
1560
|
+
"""`derive.unit_outcome`'s input for one candidate both judges judged: `derivation_input` over their first
|
|
1561
|
+
judgments and their reconsiderations of it (`{A, B}`, or {} when none was accepted). The one place it is assembled:
|
|
1562
|
+
S6's `derive_stage` passes what this invocation accepted, held in memory, and S10's adjudication passes what
|
|
1563
|
+
`given_from_run` read from disk and verified, so a recomputation with the owner's values reads exactly what S6 read
|
|
1564
|
+
(Codex WP-11 r2 #2: the live derivation read the files too, and trusted any file whose call id matched)."""
|
|
1565
|
+
return derivation_input(candidate, source, check_row, first, again, point)
|
|
1566
|
+
|
|
1567
|
+
|
|
1568
|
+
def produced(run_dir):
|
|
1569
|
+
"""`read(rel)`: one of S6's outputs read only when S6's own stage record registered it with exactly these bytes;
|
|
1570
|
+
OUTPUT_UNRECORDED otherwise. A summary or a judgment edited after S6 wrote it - or edited to agree with another - is
|
|
1571
|
+
not what S6 produced (Codex WP-11 r2 #2)."""
|
|
1572
|
+
run_dir = pathlib.Path(run_dir)
|
|
1573
|
+
record = records.read_json(records.record_path(run_dir, STAGE))
|
|
1574
|
+
held = {o["artifact"]: o["sha256"] for o in record.get("outputs") or []}
|
|
1575
|
+
|
|
1576
|
+
def read(rel):
|
|
1577
|
+
path = run_dir / rel
|
|
1578
|
+
if rel not in held or not path.is_file() or records.sha256_file(path) != held[rel]:
|
|
1579
|
+
raise Refused(f"OUTPUT_UNRECORDED S6 {rel}: S6's stage record registers "
|
|
1580
|
+
f"{'no such output' if rel not in held else 'other bytes'} for it")
|
|
1581
|
+
return records.read_json(path)
|
|
1582
|
+
return read
|
|
1583
|
+
|
|
1584
|
+
|
|
1585
|
+
def identity_problems(code, record, want):
|
|
1586
|
+
"""`code` lines for every field of `record` that is not `want`'s (candidate, judge, item, seat, call, returned)."""
|
|
1587
|
+
return [f"{code} {want['candidate_id']} {want['judge']}: its {field} is {str(record.get(field))[:60]!r}, and the call "
|
|
1588
|
+
f"S6 accepted gives {str(value)[:60]!r}" for field, value in want.items() if record.get(field) != value]
|
|
1589
|
+
|
|
1590
|
+
|
|
1591
|
+
def call_problems(code, run_dir, candidate_id, who, record, item):
|
|
1592
|
+
"""The call a kept record names, held to that call's own records: a call of this run for `item` (its id is
|
|
1593
|
+
`<run>-S6-<item>-a<n>`), whose call.json names that id and item and the record's seat and payload, whose receipt
|
|
1594
|
+
names the record's packet, which the gate accepts and no stage check refused."""
|
|
1595
|
+
run_dir = pathlib.Path(run_dir)
|
|
1596
|
+
call_id = str(record.get("call_id") or "")
|
|
1597
|
+
prefix = f"{run_dir.resolve().name}-{STAGE}-{item}-a"
|
|
1598
|
+
if not (call_id.startswith(prefix) and call_id[len(prefix):].isdigit()):
|
|
1599
|
+
return [f"{code} {candidate_id} {who}: the call {call_id[:60]!r} is not one of this run's for {item}"]
|
|
1600
|
+
call_dir = run_dir / "calls" / call_id
|
|
1601
|
+
if not (call_dir / "call.json").is_file():
|
|
1602
|
+
return [f"{code} {candidate_id} {who}: the call {call_id} has no call record"]
|
|
1603
|
+
call = records.read_json(call_dir / "call.json")
|
|
1604
|
+
receipt = records.read_json(call_dir / "receipt.json") if (call_dir / "receipt.json").is_file() else {}
|
|
1605
|
+
out = [f"{code} {candidate_id} {who}: the call record of {call_id} gives {field} {str(got)[:40]!r}"
|
|
1606
|
+
for field, got, want in (("call_id", call.get("call_id"), call_id), ("item", call.get("item"), item),
|
|
1607
|
+
("seat", call.get("seat"), record.get("seat")),
|
|
1608
|
+
("payload_sha256", call.get("payload_sha256"), record.get("payload_sha256")),
|
|
1609
|
+
("packet_sha256", receipt.get("packet_sha256"), record.get("packet_sha256")))
|
|
1610
|
+
if got != want]
|
|
1611
|
+
checked = call_dir / gate.STAGE_CHECK
|
|
1612
|
+
if not gate.accept(call_dir)["ok"] or (checked.is_file() and records.read_json(checked).get("failures")):
|
|
1613
|
+
out.append(f"{code} {candidate_id} {who}: the call {call_id} is not one the gate and the stage check accepted")
|
|
1614
|
+
return out
|
|
1615
|
+
|
|
1616
|
+
|
|
1617
|
+
def judgments_from_disk(run_dir, candidate_id, read, summary):
|
|
1618
|
+
"""Both judges' first judgments of `candidate_id` as S6 wrote and registered them, each held to the call S6's summary
|
|
1619
|
+
accepted for that judge: its candidate, judge, item, seat, call id and the payload S6 built for the candidate, and
|
|
1620
|
+
that call's own records (`call_problems`) - JUDGMENT_STALE otherwise."""
|
|
1621
|
+
run_dir, item = pathlib.Path(run_dir), item_of(candidate_id)
|
|
1622
|
+
calls = next((r for r in summary.get("calls") or [] if r["candidate_id"] == candidate_id), {})
|
|
1623
|
+
built = next((r.get("payload_sha256") for r in summary.get("packets") or [] if r["candidate_id"] == candidate_id),
|
|
1624
|
+
None)
|
|
1625
|
+
first, problems = {}, []
|
|
1626
|
+
for who in SEAT_KEYS:
|
|
1627
|
+
record = read(judgment_rel(item, who))
|
|
1628
|
+
accepted = ((calls.get("seats") or {}).get(who) or {}).get("call_id")
|
|
1629
|
+
found = identity_problems("JUDGMENT_STALE", record, {
|
|
1630
|
+
"candidate_id": candidate_id, "judge": who, "item": item, "seat": summary["seats"][who],
|
|
1631
|
+
"call_id": accepted, "payload_sha256": built})
|
|
1632
|
+
problems += found or call_problems("JUDGMENT_STALE", run_dir, candidate_id, who, record, f"{item}-{who}")
|
|
1633
|
+
first[who] = record.get("judgment")
|
|
1634
|
+
if problems:
|
|
1635
|
+
raise Refused("\n".join(problems))
|
|
1636
|
+
return first
|
|
1637
|
+
|
|
1638
|
+
|
|
1639
|
+
def returned_from_disk(run_dir, candidate_id, read, summary):
|
|
1640
|
+
"""The units `candidate_id`'s cross-review returned, read from the cross-review S6 wrote and registered, held to the
|
|
1641
|
+
call S6's summary accepted for it and that call's records (RECONSIDERATION_STALE); [] when it was not reviewed."""
|
|
1642
|
+
run_dir, item = pathlib.Path(run_dir), item_of(candidate_id)
|
|
1643
|
+
crossed = summary.get("cross_review") or {}
|
|
1644
|
+
if candidate_id not in (crossed.get("reviewed") or []):
|
|
1645
|
+
return []
|
|
1646
|
+
record = read(cross_rel(item))
|
|
1647
|
+
accepted = next((r.get("call_id") for r in crossed.get("calls") or [] if r["candidate_id"] == candidate_id), None)
|
|
1648
|
+
found = identity_problems("RECONSIDERATION_STALE", {**record, "judge": "X"}, {
|
|
1649
|
+
"candidate_id": candidate_id, "judge": "X", "seat": crossed.get("seat"), "call_id": accepted})
|
|
1650
|
+
found = found or call_problems("RECONSIDERATION_STALE", run_dir, candidate_id, "X", record, f"{item}-X")
|
|
1651
|
+
if found:
|
|
1652
|
+
raise Refused("\n".join(found))
|
|
1653
|
+
return returned_of(record)
|
|
1654
|
+
|
|
1655
|
+
|
|
1656
|
+
def reconsiderations_from_disk(run_dir, candidate_id, read, summary):
|
|
1657
|
+
"""Both judges' reconsiderations of `candidate_id` as S6 wrote and registered them, `{A, B}`; {} when its
|
|
1658
|
+
cross-review returned nothing. What was returned is read from the cross-review (`returned_from_disk`), not from a
|
|
1659
|
+
count; the summary must say the candidate was reconsidered with that many, and each file must carry that candidate,
|
|
1660
|
+
judge, item, seat, returned set and the call the summary accepted, and agree with that call's records
|
|
1661
|
+
(RECONSIDERATION_STALE)."""
|
|
1662
|
+
run_dir, item = pathlib.Path(run_dir), item_of(candidate_id)
|
|
1663
|
+
returned = returned_from_disk(run_dir, candidate_id, read, summary)
|
|
1664
|
+
if not returned:
|
|
1665
|
+
return {}
|
|
1666
|
+
again = summary.get("reconsiderations") or {}
|
|
1667
|
+
done = next((r for r in again.get("reconsidered") or [] if r["candidate_id"] == candidate_id), None)
|
|
1668
|
+
if done is None or done.get("returned") != len(returned):
|
|
1669
|
+
raise Refused(f"RECONSIDERATION_STALE {candidate_id}: its cross-review returned {len(returned)} units, and S6's "
|
|
1670
|
+
f"summary records {'no reconsideration' if done is None else done.get('returned')}")
|
|
1671
|
+
row = next((r for r in again.get("calls") or [] if r["candidate_id"] == candidate_id), {})
|
|
1672
|
+
held, problems = {}, []
|
|
1673
|
+
for who in SEAT_KEYS:
|
|
1674
|
+
record = read(reconsideration_rel(item, who))
|
|
1675
|
+
accepted = ((row.get("seats") or {}).get(who) or {}).get("call_id")
|
|
1676
|
+
found = identity_problems("RECONSIDERATION_STALE", record, {
|
|
1677
|
+
"candidate_id": candidate_id, "judge": who, "item": item, "seat": summary["seats"][who],
|
|
1678
|
+
"call_id": accepted, "returned": returned})
|
|
1679
|
+
problems += found or call_problems("RECONSIDERATION_STALE", run_dir, candidate_id, who, record,
|
|
1680
|
+
f"{item}-{RECONSIDER}{who}")
|
|
1681
|
+
held[who] = record.get("judgment")
|
|
1682
|
+
if problems:
|
|
1683
|
+
raise Refused("\n".join(problems))
|
|
1684
|
+
return held
|
|
1685
|
+
|
|
1686
|
+
|
|
1687
|
+
def given_artifacts(run_dir, candidate_id):
|
|
1688
|
+
"""The per-candidate S6 outputs `given_from_run` reads: both judges' judgments, their cross-review when it has one,
|
|
1689
|
+
and their reconsiderations when it returned units. A caller declares them as inputs so the shared record checks
|
|
1690
|
+
hold them to S6's record too."""
|
|
1691
|
+
item = item_of(candidate_id)
|
|
1692
|
+
read = produced(run_dir)
|
|
1693
|
+
summary = read(SUMMARY)
|
|
1694
|
+
crossed = candidate_id in ((summary.get("cross_review") or {}).get("reviewed") or [])
|
|
1695
|
+
returned = returned_from_disk(run_dir, candidate_id, read, summary)
|
|
1696
|
+
return ([judgment_rel(item, who) for who in SEAT_KEYS] + ([cross_rel(item)] if crossed else [])
|
|
1697
|
+
+ ([reconsideration_rel(item, who) for who in SEAT_KEYS] if returned else []))
|
|
1698
|
+
|
|
1699
|
+
|
|
1700
|
+
GIVEN_INPUTS = ("checked-candidates.json", "checks.json", "inventory/current.json") # with SUMMARY and DERIVATIONS
|
|
1701
|
+
|
|
1702
|
+
|
|
1703
|
+
def given_from_run(run_dir, candidate_id):
|
|
1704
|
+
"""`derivation_given` for one candidate from what S6 left on disk, read only as S6's stage record registered it
|
|
1705
|
+
(`produced`): the candidate (S5's checked-candidates.json), its S5 row (checks.json), its source (S6's summary), the
|
|
1706
|
+
current point (S2's inventory/current.json), both judges' first judgments (`judgments_from_disk`) and their
|
|
1707
|
+
reconsiderations (`reconsiderations_from_disk`)."""
|
|
1708
|
+
run_dir = pathlib.Path(run_dir)
|
|
1709
|
+
read = produced(run_dir)
|
|
1710
|
+
summary = read(SUMMARY)
|
|
1711
|
+
population = {k["candidate_id"]: k for k in records.read_json(run_dir / "checked-candidates.json")["candidates"]}
|
|
1712
|
+
rows = {r["candidate_id"]: r for r in records.read_json(run_dir / "checks.json")["candidates"]}
|
|
1713
|
+
sources = {r["candidate_id"]: r["source"] for r in summary["packets"]}
|
|
1714
|
+
point = current_point(records.read_json(run_dir / "inventory" / "current.json"))
|
|
1715
|
+
first = judgments_from_disk(run_dir, candidate_id, read, summary)
|
|
1716
|
+
again = reconsiderations_from_disk(run_dir, candidate_id, read, summary)
|
|
1717
|
+
return derivation_given(population[candidate_id], sources[candidate_id], rows[candidate_id], first, point, again)
|
|
1718
|
+
|
|
1719
|
+
|
|
1720
|
+
def derive_stage(run_dir, summary, judgments, swept, again, reconsidered=None):
|
|
1721
|
+
"""The derivations of every candidate both judges judged (design §4's S6 row: code derives diagnosis, delivery
|
|
1722
|
+
state, kind, admission and promotion eligibility; §6.4 through `derive.unit_outcome`). An absence claim whose sweeps,
|
|
1723
|
+
cross-review and reconsiderations did not all finish is not derived and is named, since its gap is not checked; so
|
|
1724
|
+
is a candidate a judge did not judge. Delivery is not read (lead decision D3): every (session, unit) pair a unit
|
|
1725
|
+
outcome would need is counted as DELIVERY_WAITING. Returns the document `judgments/derivations.json` holds, its
|
|
1726
|
+
`verdicts` in the shape `controls.evaluate` reads."""
|
|
1727
|
+
population = {k["candidate_id"]: k for k in records.read_json(run_dir / "checked-candidates.json")["candidates"]}
|
|
1728
|
+
rows = {r["candidate_id"]: r for r in records.read_json(run_dir / "checks.json")["candidates"]}
|
|
1729
|
+
point = current_point(records.read_json(run_dir / "inventory" / "current.json"))
|
|
1730
|
+
sources = {r["candidate_id"]: r["source"] for r in summary["packets"]}
|
|
1731
|
+
finished = {r["candidate_id"] for r in again.get("reconsidered") or []}
|
|
1732
|
+
verdicts, not_derived, waiting = {}, [], 0
|
|
1733
|
+
for cid in sorted(sources):
|
|
1734
|
+
first = judgments.get(cid) or {}
|
|
1735
|
+
if set(first) != set(SEAT_KEYS):
|
|
1736
|
+
not_derived.append({"candidate_id": cid, "why": "a judge's call did not finish"})
|
|
1737
|
+
continue
|
|
1738
|
+
if cid in (swept.get("absent") or []) and cid not in finished:
|
|
1739
|
+
not_derived.append({"candidate_id": cid, "why": swept["why"] if swept.get("run") is False else
|
|
1740
|
+
"its absence claim's sweeps, cross-review and reconsiderations did not all finish"})
|
|
1741
|
+
continue
|
|
1742
|
+
given = derivation_given(population[cid], sources[cid], rows[cid], first, point, (reconsidered or {}).get(cid, {}))
|
|
1743
|
+
outcome = derive.unit_outcome(given, {}, TEST_STATE)
|
|
1744
|
+
matched = [u for u, d in (outcome["unit_diagnosis"].get("current") or {}).items() if d != "no match"]
|
|
1745
|
+
waiting += len(population[cid].get("sessions") or []) * len(matched)
|
|
1746
|
+
verdicts[cid] = {"outcome": outcome, "requirements": {who: given["judges"][who]["requirements"] for who in SEAT_KEYS},
|
|
1747
|
+
"lineages": given["lineages"],
|
|
1748
|
+
**({"arc_confirmation": "undetermined"} if given["candidate"]["type"] in G_TYPES else {})}
|
|
1749
|
+
tally = collections.Counter
|
|
1750
|
+
g_rows = [v for v in verdicts.values() if "arc_confirmation" in v]
|
|
1751
|
+
bar = next(r for r in derive.table()["promotion"] if r["id"] == "type_g")["independent_lineages_at_least"]
|
|
1752
|
+
return {"stage": STAGE, "test": TEST_STATE, "points": {"release": "absent (D-20261111-c4fa71)", "current": point},
|
|
1753
|
+
"unit_outcomes": {"state": "none", "candidates": len(verdicts), "why": UNIT_OUTCOMES_NONE},
|
|
1754
|
+
"arc_confirmation": {"state": "undetermined", "passed_as": False, "g_candidates": len(g_rows),
|
|
1755
|
+
"g_below_lineage_bar": sum(1 for v in g_rows if v["lineages"] < bar),
|
|
1756
|
+
"lineage_bar": bar, "why": ARC_UNDETERMINED},
|
|
1757
|
+
"delivery": {"state": DELIVERY_WAITING, "pairs": waiting,
|
|
1758
|
+
"why": "S5b assembles delivery evidence (lead decision D3); S6 reads it once a wiring commit "
|
|
1759
|
+
"makes it S6's input"},
|
|
1760
|
+
"verdicts": verdicts, "not_derived": not_derived,
|
|
1761
|
+
"counts": {"derived": len(verdicts), "not_derived": len(not_derived),
|
|
1762
|
+
"admission": dict(tally(v["outcome"]["admission"]["admission"] for v in verdicts.values())),
|
|
1763
|
+
"kind": dict(tally(v["outcome"]["kind"]["kind"] for v in verdicts.values())),
|
|
1764
|
+
"current": dict(tally(v["outcome"]["candidate_diagnosis"]["current"]["diagnosis"]
|
|
1765
|
+
for v in verdicts.values())),
|
|
1766
|
+
"eligible": sum(1 for v in verdicts.values() if v["outcome"]["eligible"]["eligible"])}}
|
|
1767
|
+
|
|
1768
|
+
|
|
1769
|
+
# ---- design §3.2's gate controls (plan WP-11 J4b, lead decision D5) -----------------------------------------------
|
|
1770
|
+
|
|
1771
|
+
GATE_VERDICTS = "judgments/gate-verdicts.json"
|
|
1772
|
+
GATE_PLANTS = "judgments/gate-controls"
|
|
1773
|
+
# the judge whose accepted call each control is planted on: the host whose failure it is (tables/controls.json `design`)
|
|
1774
|
+
GATE_HOSTS = {"truncated_output": "A", "aborted_stream": "B", "incomplete_frame": "B", "refusal": "A",
|
|
1775
|
+
"nonzero_exit": "A", "stale_receipt": "A", "mismatched_result_hash": "A", "inherited_profile": "B",
|
|
1776
|
+
"contaminated_working_directory": "A", "unattested_model": "A"}
|
|
1777
|
+
GATE_UNSEALED = ("stale_receipt", "mismatched_result_hash") # the receipt is the defect, so it is not sealed again
|
|
1778
|
+
PLANTED_TEXT = "Planted by S6's gate control: an instruction no manifest declares.\n"
|
|
1779
|
+
|
|
1780
|
+
|
|
1781
|
+
def edit_json(path, edit):
|
|
1782
|
+
held = json.loads(path.read_text(encoding="utf-8"))
|
|
1783
|
+
edit(held)
|
|
1784
|
+
path.write_text(json.dumps(held, ensure_ascii=False), encoding="utf-8")
|
|
1785
|
+
|
|
1786
|
+
|
|
1787
|
+
def edit_frames(path, edit):
|
|
1788
|
+
recs = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
|
|
1789
|
+
path.write_text("".join(json.dumps(r) + "\n" for r in edit(recs)), encoding="utf-8")
|
|
1790
|
+
|
|
1791
|
+
|
|
1792
|
+
def contaminated_context(host):
|
|
1793
|
+
"""The effective context a contaminated working directory leaves (design §3.2): an instruction file in the working
|
|
1794
|
+
directory, one in its parent and one in the configuration home, a memory file and a skill, none declared."""
|
|
1795
|
+
cwd = pathlib.PurePosixPath(host.get("cwd") or "/cell/work")
|
|
1796
|
+
digest = hashlib.sha256(PLANTED_TEXT.encode("utf-8")).hexdigest()
|
|
1797
|
+
rows = [("Project", cwd / "CLAUDE.md"), ("Project", cwd.parent / "CLAUDE.md"),
|
|
1798
|
+
("User", cwd.parent / "config" / "CLAUDE.md"), ("AutoMem", cwd.parent / "memory" / "MEMORY.md")]
|
|
1799
|
+
held = dict(host.get("context") or {})
|
|
1800
|
+
return {**held, "instructions": list(held.get("instructions") or []) + [
|
|
1801
|
+
{"kind": kind, "path": str(path), "sha256": digest} for kind, path in rows],
|
|
1802
|
+
"skills": sorted(set(held.get("skills") or []) | {"planted-gate-skill"})}
|
|
1803
|
+
|
|
1804
|
+
|
|
1805
|
+
def plant(kind, call_dir, other):
|
|
1806
|
+
"""Plant one §3.2 gate control into a copy of an accepted call (`call_dir`); `other` is the other judge's accepted
|
|
1807
|
+
call, whose receipt a stale receipt is."""
|
|
1808
|
+
host, result, frames = call_dir / "capture" / "host.json", call_dir / "result.json", call_dir / "capture" / "frames.jsonl"
|
|
1809
|
+
if kind == "truncated_output":
|
|
1810
|
+
edit_json(host, lambda h: h["assistant"][-1].update(stop_reason="max_tokens"))
|
|
1811
|
+
elif kind == "refusal":
|
|
1812
|
+
edit_json(host, lambda h: h["assistant"][-1].update(stop_reason="refusal"))
|
|
1813
|
+
edit_json(result, lambda r: r.update(stop_reason="refusal"))
|
|
1814
|
+
elif kind == "aborted_stream":
|
|
1815
|
+
edit_frames(frames, lambda recs: [r for r in recs if r.get("type") != "response.completed"])
|
|
1816
|
+
elif kind == "incomplete_frame":
|
|
1817
|
+
last = lambda recs: [r for r in recs if r.get("type") == "response.completed"][-1]
|
|
1818
|
+
edit_frames(frames, lambda recs: [dict(r, type="response.incomplete", response=dict(
|
|
1819
|
+
r.get("response") or {}, incomplete_details={"reason": "max_output_tokens"})) if r is last(recs) else r
|
|
1820
|
+
for r in recs])
|
|
1821
|
+
elif kind == "nonzero_exit":
|
|
1822
|
+
edit_json(call_dir / "call.json", lambda c: c.update(exit_status=1))
|
|
1823
|
+
elif kind == "stale_receipt":
|
|
1824
|
+
shutil.copyfile(other / "receipt.json", call_dir / "receipt.json")
|
|
1825
|
+
elif kind == "mismatched_result_hash":
|
|
1826
|
+
result.write_bytes(result.read_bytes() + b"\n")
|
|
1827
|
+
elif kind == "inherited_profile":
|
|
1828
|
+
edit_json(host, lambda h: h.update(profile="inherited"))
|
|
1829
|
+
elif kind == "contaminated_working_directory":
|
|
1830
|
+
edit_json(host, lambda h: h.update(context=contaminated_context(h)))
|
|
1831
|
+
elif kind == "unattested_model":
|
|
1832
|
+
edit_json(host, lambda h: h["assistant"][-1].update(model="claude-haiku-5-5"))
|
|
1833
|
+
else:
|
|
1834
|
+
raise Refused(f"GATE_CONTROL_UNKNOWN {kind}: S6 plants {sorted(GATE_HOSTS)}")
|
|
1835
|
+
if kind not in GATE_UNSEALED:
|
|
1836
|
+
seal(call_dir)
|
|
1837
|
+
|
|
1838
|
+
|
|
1839
|
+
def seal(call_dir):
|
|
1840
|
+
"""The planted call's receipt made again from the directory, as the dispatcher's is (`gate.receipt_evidence` and
|
|
1841
|
+
the hashes the gate recomputes), so the planted defect is the only one the gate finds."""
|
|
1842
|
+
c = gate.Call(call_dir)
|
|
1843
|
+
edit_json(call_dir / "receipt.json", lambda r: r.update(
|
|
1844
|
+
packet_sha256=hashlib.sha256(c.packet).hexdigest(), result_sha256=hashlib.sha256(c.result_bytes).hexdigest(),
|
|
1845
|
+
exit_status=c.call.get("exit_status"),
|
|
1846
|
+
evidence={k: "" if v is None else v for k, v in gate.receipt_evidence(call_dir).items()}))
|
|
1847
|
+
|
|
1848
|
+
|
|
1849
|
+
def verdict_of(call_dir):
|
|
1850
|
+
held = gate.accept(call_dir)
|
|
1851
|
+
return {"ok": held["ok"], "codes": held["codes"], "failures": held["failures"], "call_id": held["call_id"]}
|
|
1852
|
+
|
|
1853
|
+
|
|
1854
|
+
def gate_stage(run_dir, calls):
|
|
1855
|
+
"""Design §3.2's ten gate controls (D5): one accepted Judge A call and one accepted Judge B call - the first
|
|
1856
|
+
candidate both judges' calls were accepted for - are copied under judgments/gate-controls/<kind>/, each control
|
|
1857
|
+
planted on its own host's copy, and the gate judges every copy; the originals are the clean counterparts. Returns
|
|
1858
|
+
the document `judgments/gate-verdicts.json` holds: `gate_verdicts` in the shape `controls.evaluate` reads."""
|
|
1859
|
+
rows = [r for r in calls if all(h["outcome"] == "accepted" for h in r["seats"].values())]
|
|
1860
|
+
out = {"stage": STAGE, "source": None, "gate_verdicts": {}}
|
|
1861
|
+
planted_root = run_dir / GATE_PLANTS
|
|
1862
|
+
if planted_root.is_dir():
|
|
1863
|
+
shutil.rmtree(planted_root)
|
|
1864
|
+
if not rows:
|
|
1865
|
+
out["why"] = "no candidate has both judges' calls accepted, so no call is copied"
|
|
1866
|
+
return out
|
|
1867
|
+
source = {who: run_dir / "calls" / rows[0]["seats"][who]["call_id"] for who in SEAT_KEYS}
|
|
1868
|
+
out["source"] = {who: d.name for who, d in source.items()}
|
|
1869
|
+
clean = {who: verdict_of(d) for who, d in source.items()}
|
|
1870
|
+
for kind in [row["kind"] for row in controls.table()["gate"]]:
|
|
1871
|
+
who = GATE_HOSTS.get(kind)
|
|
1872
|
+
if who is None:
|
|
1873
|
+
raise Refused(f"GATE_CONTROL_UNKNOWN {kind}: tables/controls.json names a gate control S6 has no host for")
|
|
1874
|
+
copy = planted_root / kind / source[who].name
|
|
1875
|
+
shutil.copytree(source[who], copy)
|
|
1876
|
+
plant(kind, copy, source["B" if who == "A" else "A"])
|
|
1877
|
+
out["gate_verdicts"][kind] = {"host": who, "planted": {**verdict_of(copy), "at": str(copy.relative_to(run_dir))},
|
|
1878
|
+
"clean": clean[who]}
|
|
1879
|
+
return out
|
|
1880
|
+
|
|
1881
|
+
|
|
1882
|
+
# ---- the calls ------------------------------------------------------------------------------------------------
|
|
1883
|
+
|
|
1884
|
+
SUMMARY = "judgments/judge.json"
|
|
1885
|
+
OUTCOMES = ("accepted", "failed", "not_done", "deferred", "budget_stopped")
|
|
1886
|
+
|
|
1887
|
+
|
|
1888
|
+
def judgment_rel(item, who):
|
|
1889
|
+
"""Where one judge's judgment of a candidate is kept: under the candidate's item name, since a candidate id may hold
|
|
1890
|
+
any character (`item_of`)."""
|
|
1891
|
+
return f"judgments/{item}/{who}.json"
|
|
1892
|
+
|
|
1893
|
+
|
|
1894
|
+
def check(labels, capacity, reconsider=False):
|
|
1895
|
+
"""The stage's check of a judgment call's attempts, as `Supervisor.item(stage_check=)` asks it: the capacity the
|
|
1896
|
+
call was admitted against is the one its record carries (CAPACITY_UNRECORDED, S4's rule), and the answer judges the
|
|
1897
|
+
packet it was sent (`answer_problems`, a candidate's first call)."""
|
|
1898
|
+
from runlib import stage_read
|
|
1899
|
+
shown = labels.shown()
|
|
1900
|
+
|
|
1901
|
+
def judged(call_dir):
|
|
1902
|
+
held = ((records.read_json(pathlib.Path(call_dir) / "call.json").get("bound")) or {}).get("context_capacity")
|
|
1903
|
+
if held != capacity:
|
|
1904
|
+
raise Refused(f"CAPACITY_UNRECORDED {pathlib.Path(call_dir).name}: its call record carries the capacity "
|
|
1905
|
+
f"{held!r}, and S6 was admitted against {capacity!r}")
|
|
1906
|
+
return answer_problems(shown, stage_read.answer_of(call_dir), first=True, reconsider=reconsider)
|
|
1907
|
+
return judged
|
|
1908
|
+
|
|
1909
|
+
|
|
1910
|
+
def attempt_problems(built, limits, schema_bytes, who, code="JUDGE_OVER_CAPACITY"):
|
|
1911
|
+
"""The bound on one attempt's packet as `Supervisor.item(packet_check=)` asks it, built under the call id its
|
|
1912
|
+
reservation gave it and, on a retry, carrying its correction: `code` (JUDGE_OVER_CAPACITY for a judgment, and the
|
|
1913
|
+
sweep's and the cross-review's own) when it and the output cap exceed the seat's capacity. A seat whose capacity is
|
|
1914
|
+
not measured is not bounded here (D13)."""
|
|
1915
|
+
from runlib import stage_read
|
|
1916
|
+
size = bound.driver_bytes(built, schema_bytes)[0]
|
|
1917
|
+
beyond = beyond_capacity(max(size - stage_read.CORRECTION_ROOM, 0), limits)
|
|
1918
|
+
return [f"{code} {who}: this attempt's packet of {size} driver bytes with the output cap exceeds the "
|
|
1919
|
+
f"seat's capacity {limits['capacity']}"] if beyond else []
|
|
1920
|
+
|
|
1921
|
+
|
|
1922
|
+
def over_capacity(run_id, built, limits, schema_bytes, code, advice):
|
|
1923
|
+
"""Before any call of a kind is made: every packet of `built` (`[(item, side, seat, text)]`) whose first attempt,
|
|
1924
|
+
with room for its retry's correction and the output cap, exceeds its seat's capacity (`limits[side]`), refused by
|
|
1925
|
+
`code` naming them and what the run can change. Codex WP-11 r1 #3: the sweeps and the cross-review were sent with
|
|
1926
|
+
no capacity bound at all, and a shard's unit count does not bound its bytes."""
|
|
1927
|
+
over = []
|
|
1928
|
+
for item, side, seat, text in built:
|
|
1929
|
+
made = packet.build(f"{run_id}-{STAGE}-{item}-a1", STAGE, seat, text, schema_bytes)
|
|
1930
|
+
size = bound.driver_bytes(made, schema_bytes)[0]
|
|
1931
|
+
if beyond_capacity(size, limits[side]):
|
|
1932
|
+
over.append(f"{item} ({size} driver bytes, {seat} capacity {limits[side]['capacity']})")
|
|
1933
|
+
if over:
|
|
1934
|
+
raise Refused(f"{code} S6: {len(over)} packets exceed their seat's capacity with the output cap and a retry's "
|
|
1935
|
+
f"correction ({'; '.join(over[:3])}); {advice}")
|
|
1936
|
+
|
|
1937
|
+
|
|
1938
|
+
ATTEMPT = re.compile(r"(?P<item>.+-a)(?P<n>[1-9][0-9]*)")
|
|
1939
|
+
|
|
1940
|
+
|
|
1941
|
+
def due_correction(call_dir):
|
|
1942
|
+
"""The exact correction dispatch sent with the attempt in `call_dir` when it was the one corrective retry, or None.
|
|
1943
|
+
|
|
1944
|
+
Supervisor.item retries a failed attempt once, sending the payload, a newline and `gate.correction` of what the
|
|
1945
|
+
failed attempt was told: the stage's check when the gate accepted it (its `gate.STAGE_CHECK` record), the gate's
|
|
1946
|
+
own verdict otherwise. So the predecessor is the latest earlier attempt of the same item with a call directory
|
|
1947
|
+
(a reservation that was released keeps its number, so the numbers can skip), it must have been sent the payload
|
|
1948
|
+
alone and not been accepted, and the correction is rebuilt from its own records here, byte for byte. Codex WP-11 r2
|
|
1949
|
+
#1: a frame alone admitted an invented diagnostic, two corrections, and a correction on a first attempt."""
|
|
1950
|
+
call_dir = pathlib.Path(call_dir)
|
|
1951
|
+
held = gate.Call(call_dir)
|
|
1952
|
+
found = ATTEMPT.fullmatch(str(held.call.get("call_id") or ""))
|
|
1953
|
+
if found is None or found["item"] + found["n"] != call_dir.name:
|
|
1954
|
+
return None
|
|
1955
|
+
earlier = sorted((int(d.name[len(found["item"]):]), d) for d in call_dir.parent.glob(f"{found['item']}*")
|
|
1956
|
+
if d.name[len(found["item"]):].isdigit() and int(d.name[len(found["item"]):]) < int(found["n"])
|
|
1957
|
+
and (d / "call.json").is_file())
|
|
1958
|
+
if not earlier:
|
|
1959
|
+
return None
|
|
1960
|
+
before = earlier[-1][1]
|
|
1961
|
+
prior = gate.Call(before)
|
|
1962
|
+
if prior.call.get("payload_sha256") != held.call.get("payload_sha256") or prior.packet is None \
|
|
1963
|
+
or packet.sha256_bytes(packet.split(prior.packet)[1] or b"") != held.call.get("payload_sha256"):
|
|
1964
|
+
return None
|
|
1965
|
+
verdict = gate.accept(before)
|
|
1966
|
+
if verdict["ok"]:
|
|
1967
|
+
checked = before / gate.STAGE_CHECK
|
|
1968
|
+
failures = (records.read_json(checked).get("failures") or []) if checked.is_file() else []
|
|
1969
|
+
if not failures:
|
|
1970
|
+
return None # the predecessor was accepted, so nothing was retried after it
|
|
1971
|
+
verdict = {"failures": failures}
|
|
1972
|
+
return gate.correction(verdict)
|
|
1973
|
+
|
|
1974
|
+
|
|
1975
|
+
def corrected_sha256(call_dir, text):
|
|
1976
|
+
"""The payload hash the receipt of the attempt in `call_dir` is due to carry when that attempt was the one corrective
|
|
1977
|
+
retry of `text`: the hash of `text`, a newline and `due_correction(call_dir)`, when that whole payload is exactly
|
|
1978
|
+
what the attempt was sent and the call says it was made for `text`; None otherwise, so a receipt is then held to the
|
|
1979
|
+
payload S6 built and nothing else (Codex WP-11 r1 #1, r2 #1)."""
|
|
1980
|
+
held = gate.Call(call_dir)
|
|
1981
|
+
sent = packet.split(held.packet)[1] if held.packet is not None else None
|
|
1982
|
+
base = text.encode("utf-8")
|
|
1983
|
+
if sent is None or held.call.get("payload_sha256") != packet.sha256_bytes(base):
|
|
1984
|
+
return None
|
|
1985
|
+
correction = due_correction(call_dir)
|
|
1986
|
+
if correction is None:
|
|
1987
|
+
return None
|
|
1988
|
+
expected = base + b"\n" + correction.encode("utf-8")
|
|
1989
|
+
return packet.sha256_bytes(sent) if sent == expected else None
|
|
1990
|
+
|
|
1991
|
+
|
|
1992
|
+
def stage_receipts(calls):
|
|
1993
|
+
"""N#1 over the accepted calls: each candidate's two receipts carry the payload S6 built for it and one payload hash
|
|
1994
|
+
between them (PACKET_DIVERGENCE), and no two receipts of the stage one packet hash (RECEIPT_STALE). `calls` are
|
|
1995
|
+
`(candidate id, seat, call id, receipt, payload sha256[, corrected sha256])`: an attempt that was the corrective
|
|
1996
|
+
retry of that payload (`corrected_sha256`) carries its correction's hash, and is held to that one and read as the
|
|
1997
|
+
payload S6 built when the seats are compared, because the correction is the gate's answer to that seat's own
|
|
1998
|
+
attempt and not a second judgment payload."""
|
|
1999
|
+
out, by_candidate = [], {}
|
|
2000
|
+
for cid, seat, call_id, receipt, built, *rest in calls:
|
|
2001
|
+
corrected = rest[0] if rest else None
|
|
2002
|
+
got = (receipt.get("evidence") or {}).get("payload_sha256")
|
|
2003
|
+
if corrected is not None and got == corrected:
|
|
2004
|
+
receipt = {**receipt, "evidence": {**(receipt.get("evidence") or {}), "payload_sha256": built}}
|
|
2005
|
+
elif got != built:
|
|
2006
|
+
out.append(f"PACKET_DIVERGENCE {call_id}: its receipt carries the payload hash {str(got)[:12]}, and S6 built "
|
|
2007
|
+
f"{str(built)[:12]} for {cid}")
|
|
2008
|
+
by_candidate.setdefault(cid, {})[call_id] = (seat, receipt)
|
|
2009
|
+
for held in by_candidate.values():
|
|
2010
|
+
out += [p for p in receipt_problems(held) if not p.startswith("RECEIPT_STALE")]
|
|
2011
|
+
out += [p for p in receipt_problems({c: (s, r) for _cid, s, c, r, _b, *_rest in calls}) if p.startswith("RECEIPT_STALE")]
|
|
2012
|
+
return out
|
|
2013
|
+
|
|
2014
|
+
|
|
2015
|
+
RECEIPT_KINDS = ("sweep", "cross", "reconsider") # a receipt key's prefix; any other key is a judgment's candidate id
|
|
2016
|
+
|
|
2017
|
+
|
|
2018
|
+
def receipt_counts(calls):
|
|
2019
|
+
"""How many receipts of each kind `stage_receipts` was given: `{judge, sweep, cross, reconsider}`. It cannot see a
|
|
2020
|
+
receipt missing from its list, so the run records what it held to N#1 and a control compares that with the calls
|
|
2021
|
+
accepted."""
|
|
2022
|
+
kinds = collections.Counter(key.split("/", 1)[0] if key.split("/", 1)[0] in RECEIPT_KINDS else "judge"
|
|
2023
|
+
for key, *_rest in calls)
|
|
2024
|
+
return {kind: kinds.get(kind, 0) for kind in ("judge",) + RECEIPT_KINDS}
|
|
2025
|
+
|
|
2026
|
+
|
|
2027
|
+
# S6's golden host: dispatch's (FAKE_HOST) for both hosts, with what its Codex branch does not do
|
|
2028
|
+
JUDGE_HOST = r'''
|
|
2029
|
+
"""S6's golden host. It runs dispatch's golden host (FAKE_HOST) and adds two things: a Codex call is answered from the
|
|
2030
|
+
plan, as FAKE_HOST's Claude branch answers one; and a plan row's `context` names a replayed capture (WP-03's planted
|
|
2031
|
+
working directories) whose effective context replaces the one the host reports. A row `auto: sweep` answers a sweep
|
|
2032
|
+
packet from the packet itself: every pair it lists, a partial match (situation yes) where the unit's text holds the
|
|
2033
|
+
row's `partial_where`, its first pair left out with `drop_first`; `auto: cross` answers a cross-review the same way,
|
|
2034
|
+
every unit it shows, and with `flag_first_negative` marks the first unit both sweeps found unrelated a match; `auto:
|
|
2035
|
+
reconsider` answers a reconsideration from itself: every unit it returns, the first a match with `yes_first`, and the
|
|
2036
|
+
row's `extra` fields added. argv: fake-host host mode spec-json."""
|
|
2037
|
+
import json, os, pathlib, subprocess, sys
|
|
2038
|
+
fake, host, mode, spec = sys.argv[1], sys.argv[2], sys.argv[3], json.loads(sys.argv[4])
|
|
2039
|
+
packet = sys.stdin.buffer.read()
|
|
2040
|
+
text = packet.decode("utf-8")
|
|
2041
|
+
call_id = text.splitlines()[0].split(": ", 1)[1]
|
|
2042
|
+
plan = json.loads(pathlib.Path(spec["answers"]).read_text())
|
|
2043
|
+
row = next((r for r in plan if all(t in text for t in r["match"])), None)
|
|
2044
|
+
def block(tag):
|
|
2045
|
+
body = text.split("<" + tag + ">\n", 1)[1].split("\n</" + tag + ">", 1)[0]
|
|
2046
|
+
return [json.loads(line) for line in body.splitlines()]
|
|
2047
|
+
if row is not None and row.get("auto") == "sweep": # every pair the packet lists, a partial match where the text says
|
|
2048
|
+
units = {u["unit"]: u["text"] for u in block("units")}
|
|
2049
|
+
flagged = lambda u: bool(row.get("partial_where")) and row["partial_where"] in units[u]
|
|
2050
|
+
pairs = [{"candidate": c["candidate"], "unit": u, "situation": "yes" if flagged(u) else "no", "action": "no",
|
|
2051
|
+
"reason": "a partial match" if flagged(u) else "unrelated"} for c in block("candidates") for u in c["units"]]
|
|
2052
|
+
row = {**row, "answer": {"pairs": pairs[1:] if row.get("drop_first") else pairs}}
|
|
2053
|
+
if row is not None and row.get("auto") == "cross": # every unit shown, a match where the text says or on the first negative
|
|
2054
|
+
shown = block("units")
|
|
2055
|
+
first_negative = next((u["unit"] for u in shown if all(m["situation"] == m["action"] == "no"
|
|
2056
|
+
for m in u["sweeps"].values())), None) \
|
|
2057
|
+
if row.get("flag_first_negative") else None
|
|
2058
|
+
flagged = lambda u: (bool(row.get("partial_where")) and row["partial_where"] in u["text"]) or u["unit"] == first_negative
|
|
2059
|
+
row = {**row, "answer": {"verdicts": [{"unit": u["unit"], "situation": "yes" if flagged(u) else "no",
|
|
2060
|
+
"action": "no", "reason": "a match" if flagged(u) else "unrelated"}
|
|
2061
|
+
for u in shown][(1 if row.get("drop_first") else 0):]}}
|
|
2062
|
+
def rows_of(tag):
|
|
2063
|
+
body = text.split("<" + tag + ">\n", 1)[1].split("\n</" + tag + ">", 1)[0]
|
|
2064
|
+
return [] if body.strip() == "none" else [json.loads(line) for line in body.splitlines()]
|
|
2065
|
+
if row is not None and row.get("auto") == "reconsider": # every returned unit, the first a match with yes_first
|
|
2066
|
+
units, quotes = rows_of("units"), [q["evidence_id"] for c in rows_of("claims") for q in c.get("quotes", [])][:1]
|
|
2067
|
+
yes = [u["unit_id"] for u in units][:1] if row.get("yes_first") else []
|
|
2068
|
+
row = {**row, "answer": {"units": [
|
|
2069
|
+
{"unit": u["unit_id"], "situation": "yes" if u["unit_id"] in yes else "no",
|
|
2070
|
+
"action": "yes" if u["unit_id"] in yes else "no", "reason": "one line",
|
|
2071
|
+
"quote": u["text"][:12] if u["unit_id"] in yes else ""} for u in units],
|
|
2072
|
+
"matching_units": [{"unit": u, "following": "followed", "following_evidence_ids": quotes, "contribution": "helped",
|
|
2073
|
+
"contribution_evidence_ids": quotes} for u in yes], **(row.get("extra") or {})}}
|
|
2074
|
+
if row is not None and row.get("auto") in ("sweep", "cross", "reconsider"):
|
|
2075
|
+
held = pathlib.Path(os.environ["DISTILL_CELL"]) / "judge-host-plan.json"
|
|
2076
|
+
held.write_text(json.dumps([{"match": row["match"], "answer": row["answer"]}]))
|
|
2077
|
+
spec = {**spec, "answers": str(held)}
|
|
2078
|
+
done = subprocess.run([sys.executable, fake, host, mode, json.dumps(spec)], input=packet, stdout=subprocess.PIPE)
|
|
2079
|
+
if row is not None and row.get("context") and done.returncode == 0:
|
|
2080
|
+
capture = pathlib.Path(os.environ["REVIEW_CAPTURE_DIR"]) / "host.json"
|
|
2081
|
+
held = json.loads(capture.read_text())
|
|
2082
|
+
held["context"] = json.loads(pathlib.Path(row["context"]).read_text())["context"]
|
|
2083
|
+
capture.write_text(json.dumps(held))
|
|
2084
|
+
out = done.stdout
|
|
2085
|
+
if host == "codex" and done.returncode == 0:
|
|
2086
|
+
out = json.dumps(row["answer"] if row is not None else {"unplanned": True}).replace("<CALL-ID>", call_id).encode()
|
|
2087
|
+
sys.stdout.buffer.write(out)
|
|
2088
|
+
sys.exit(done.returncode)
|
|
2089
|
+
'''
|
|
2090
|
+
|
|
2091
|
+
|
|
2092
|
+
def supervisor(run_dir, cells, plan=None, seats_path=None):
|
|
2093
|
+
"""The supervisor S6's calls go through, their cells under `cells` (made mode 700). Live, the pinned runners: Judge
|
|
2094
|
+
A's token reaches claude-run only as CLAUDE_RUN_TOKEN_FILE in this process's environment - a path never read here,
|
|
2095
|
+
refused by name before anything is reserved when it is not set (TOKEN_FILE_UNSET). With `plan`, a golden host's plan
|
|
2096
|
+
(`[{match, answer, context?}]`, `JUDGE_HOST`), realization golden: the host answers from the plan and starts no model,
|
|
2097
|
+
and the dispatcher refuses that runner under any other realization."""
|
|
2098
|
+
from runlib import dispatch
|
|
2099
|
+
if plan is None and not os.environ.get("CLAUDE_RUN_TOKEN_FILE"):
|
|
2100
|
+
raise Refused("TOKEN_FILE_UNSET S6: a live judgment call's token reaches claude-run only as "
|
|
2101
|
+
"CLAUDE_RUN_TOKEN_FILE, and this environment does not set it")
|
|
2102
|
+
cells = pathlib.Path(cells)
|
|
2103
|
+
cells.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
2104
|
+
if plan is None:
|
|
2105
|
+
return dispatch.Supervisor(run_dir, cell_root=cells, realization="live", seats_path=seats_path)
|
|
2106
|
+
fake, host, plan = cells / "fake_host.py", cells / "judge_host.py", pathlib.Path(plan).resolve()
|
|
2107
|
+
fake.write_text(dispatch.FAKE_HOST, encoding="utf-8")
|
|
2108
|
+
host.write_text(JUDGE_HOST, encoding="utf-8")
|
|
2109
|
+
sup = dispatch.Supervisor(run_dir, cell_root=cells, realization="golden", seats_path=seats_path)
|
|
2110
|
+
sup.runner = lambda h, spec: [sys.executable, str(host), str(fake), h, "clean", json.dumps({**spec, "answers": str(plan)})]
|
|
2111
|
+
return sup
|
|
2112
|
+
|
|
2113
|
+
|
|
2114
|
+
def call_row(out):
|
|
2115
|
+
"""What S6 records of one judge's item: its outcome and codes, its attempts with what the stage's check said of
|
|
2116
|
+
each, whether an earlier accepted attempt answered it (`reused`), and why when it was not done."""
|
|
2117
|
+
from runlib import stage_read
|
|
2118
|
+
return {"outcome": out["outcome"], "codes": out.get("codes", []), "attempts": stage_read.attempts_of(out),
|
|
2119
|
+
"reused": out.get("reused"), "not_reused": out.get("not_reused", []),
|
|
2120
|
+
**({"why": out["why"]} if out.get("why") else {})}
|
|
2121
|
+
|
|
2122
|
+
|
|
2123
|
+
def run(run_dir, supervisor=None, *, dry=False, seats_path=None, tranche="calibration"):
|
|
2124
|
+
"""`_run`, with the expected verdicts' file S5 wrote sealed for as long as it runs (`controls.sealed`): any module
|
|
2125
|
+
that opens it, by its name, a glob, a computed name or a link, is refused CONTROLS_READ (Codex WP-10 X r1 #7)."""
|
|
2126
|
+
with controls.sealed(run_dir, STAGE):
|
|
2127
|
+
return _run(run_dir, supervisor, dry=dry, seats_path=seats_path, tranche=tranche)
|
|
2128
|
+
|
|
2129
|
+
|
|
2130
|
+
def _run(run_dir, supervisor=None, *, dry=False, seats_path=None, tranche="calibration"):
|
|
2131
|
+
"""S6 over S5's population (plan WP-11): admitted against its inputs, it builds and measures every judgment packet
|
|
2132
|
+
(`build`); dry, it writes `judgments/dry.json` and leaves the record `partial`. Otherwise every judged candidate is
|
|
2133
|
+
sent to Judge A and Judge B through `supervisor`, each an item of its own, with the same payload; each answer is
|
|
2134
|
+
checked by the stage (`check`) and kept in the stores' ids (`judgments/<item>/<A|B>.json`), the receipts are held to
|
|
2135
|
+
one payload per candidate and one packet per receipt (`stage_receipts`), and `judgments/judge.json` says what each
|
|
2136
|
+
call did. A call that ends other than accepted leaves the record `partial`; a re-run reuses each accepted attempt
|
|
2137
|
+
(dispatch's resume) and calls only the rest. The calls run in a calibration tranche by default: a seat whose host
|
|
2138
|
+
allowance is not measured (D13: Judge B's) is dispatched only in one. `seats_path` is the dry measure's seats file;
|
|
2139
|
+
a run with calls reads its supervisor's. Without a supervisor and not dry, JUDGE_UNSUPERVISED."""
|
|
2140
|
+
from runlib import dispatch
|
|
2141
|
+
if not dry and supervisor is None:
|
|
2142
|
+
raise Refused("JUDGE_UNSUPERVISED S6: a judgment call goes through a supervisor; without one, run it dry (--dry)")
|
|
2143
|
+
run_dir = pathlib.Path(run_dir)
|
|
2144
|
+
with records.run_stage(run_dir, STAGE, INPUTS) as stage:
|
|
2145
|
+
declaration = stage.declaration
|
|
2146
|
+
# the stage's lock is held, so a reservation of S6 still open is a dead run's: closed before any reuse
|
|
2147
|
+
interrupted = [] if dry else supervisor.interrupted(STAGE)
|
|
2148
|
+
summary, packets = build(run_dir, declaration, seats_path if dry else supervisor.seats_path)
|
|
2149
|
+
if dry:
|
|
2150
|
+
summary["sweep_upper_bound"] = upper_bound(run_dir, declaration, sorted(packets), seats_path)
|
|
2151
|
+
records.write_json(run_dir, run_dir / DRY_RECORD, summary)
|
|
2152
|
+
stage.output(DRY_RECORD)
|
|
2153
|
+
stage.record["status"] = "partial"
|
|
2154
|
+
return summary
|
|
2155
|
+
over = {who: ids for who, ids in summary["over_capacity"].items() if ids}
|
|
2156
|
+
if over:
|
|
2157
|
+
raise Refused("JUDGE_OVER_CAPACITY S6: " + "; ".join(
|
|
2158
|
+
f"{len(ids)} packets exceed Judge {who}'s capacity {summary['limits'][who]['capacity']} with the output "
|
|
2159
|
+
f"cap and a retry's correction ({ids[:3]})" for who, ids in sorted(over.items()))
|
|
2160
|
+
+ "; the run narrows retrieval.per_layer or seats a judge with more context")
|
|
2161
|
+
episode = declaration["budget"]["per_episode"]
|
|
2162
|
+
caps = {"tokens": episode["tokens"], "compactions": episode["compactions"]}
|
|
2163
|
+
held_schema = schema()
|
|
2164
|
+
schema_bytes = packet.schema_bytes(held_schema)
|
|
2165
|
+
calls, receipts, judgments = [], [], {}
|
|
2166
|
+
for measured in summary["packets"]:
|
|
2167
|
+
cid, item = measured["candidate_id"], measured["item"]
|
|
2168
|
+
labels, text = packets[cid]
|
|
2169
|
+
row = {"candidate_id": cid, "item": item, "source": measured["source"], "seats": {}}
|
|
2170
|
+
for who, seat in summary["seats"].items():
|
|
2171
|
+
limits = summary["limits"][who]
|
|
2172
|
+
out = supervisor.item(STAGE, f"{item}-{who}", seat, text, held_schema, case_type=CASE, caps=caps,
|
|
2173
|
+
view_window=False, tranche=tranche, max_output_tokens=OUTPUT_CAP,
|
|
2174
|
+
stage_check=check(labels, limits["capacity"]), resume=True,
|
|
2175
|
+
context_capacity=limits["capacity"],
|
|
2176
|
+
packet_check=lambda built, limits=limits, who=who: attempt_problems(
|
|
2177
|
+
built, limits, schema_bytes, who))
|
|
2178
|
+
held = call_row(out)
|
|
2179
|
+
if out["outcome"] == "accepted":
|
|
2180
|
+
call_dir = pathlib.Path(out["accepted"])
|
|
2181
|
+
call_id = records.read_json(call_dir / "call.json")["call_id"]
|
|
2182
|
+
receipt = records.read_json(call_dir / "receipt.json")
|
|
2183
|
+
rel = judgment_rel(item, who)
|
|
2184
|
+
judgment = labels.resolve(gate.accepted(call_dir, judged=True))
|
|
2185
|
+
judgments.setdefault(cid, {})[who] = judgment
|
|
2186
|
+
records.write_json(run_dir, run_dir / rel, {
|
|
2187
|
+
"candidate_id": cid, "item": item, "judge": who, "seat": seat, "call_id": call_id,
|
|
2188
|
+
"payload_sha256": measured["payload_sha256"], "packet_sha256": receipt.get("packet_sha256"),
|
|
2189
|
+
"judgment": judgment})
|
|
2190
|
+
stage.output(rel)
|
|
2191
|
+
receipts.append((cid, seat, call_id, receipt, measured["payload_sha256"],
|
|
2192
|
+
corrected_sha256(call_dir, text)))
|
|
2193
|
+
held.update(call_id=call_id, judgment=rel)
|
|
2194
|
+
row["seats"][who] = held
|
|
2195
|
+
calls.append(row)
|
|
2196
|
+
sources = {r["candidate_id"]: r["source"] for r in summary["packets"]}
|
|
2197
|
+
swept, sweep_receipts = sweep_stage(run_dir, stage, supervisor, declaration, sorted(packets), judgments, sources,
|
|
2198
|
+
caps, tranche)
|
|
2199
|
+
crossed, cross_receipts = cross_stage(run_dir, stage, supervisor, declaration, swept, item_of, caps, tranche)
|
|
2200
|
+
again, again_receipts, reconsidered = reconsider_stage(run_dir, stage, supervisor, declaration, summary, packets,
|
|
2201
|
+
judgments, crossed, caps, tranche)
|
|
2202
|
+
held_receipts = receipts + sweep_receipts + cross_receipts + again_receipts
|
|
2203
|
+
problems = stage_receipts(held_receipts)
|
|
2204
|
+
if problems:
|
|
2205
|
+
raise Refused("\n".join(problems))
|
|
2206
|
+
derived = derive_stage(run_dir, summary, judgments, swept, again, reconsidered)
|
|
2207
|
+
records.write_json(run_dir, run_dir / DERIVATIONS, derived)
|
|
2208
|
+
stage.output(DERIVATIONS)
|
|
2209
|
+
gated = gate_stage(run_dir, calls)
|
|
2210
|
+
records.write_json(run_dir, run_dir / GATE_VERDICTS, gated)
|
|
2211
|
+
stage.output(GATE_VERDICTS)
|
|
2212
|
+
outcomes = [held["outcome"] for row in calls for held in row["seats"].values()]
|
|
2213
|
+
swept_outcomes = [held["outcome"] for row in swept["calls"] for held in row["seats"].values()]
|
|
2214
|
+
swept["counts"] = {**{o: swept_outcomes.count(o) for o in OUTCOMES},
|
|
2215
|
+
"reused": sum(1 for row in swept["calls"] for held in row["seats"].values() if held["reused"])}
|
|
2216
|
+
crossed_outcomes = [row["outcome"] for row in crossed["calls"]]
|
|
2217
|
+
crossed["counts"] = {**{o: crossed_outcomes.count(o) for o in OUTCOMES},
|
|
2218
|
+
"reused": sum(1 for row in crossed["calls"] if row["reused"])}
|
|
2219
|
+
again_outcomes = [held["outcome"] for row in again["calls"] for held in row["seats"].values()]
|
|
2220
|
+
again["counts"] = {**{o: again_outcomes.count(o) for o in OUTCOMES},
|
|
2221
|
+
"reused": sum(1 for row in again["calls"] for held in row["seats"].values() if held["reused"])}
|
|
2222
|
+
summary.update(dry=False, calls=calls, sweeps=swept, cross_review=crossed, reconsiderations=again,
|
|
2223
|
+
receipts_checked=receipt_counts(held_receipts),
|
|
2224
|
+
gate_controls={"file": GATE_VERDICTS, "source": gated["source"],
|
|
2225
|
+
"planted": len(gated["gate_verdicts"]),
|
|
2226
|
+
"planted_rejected": sorted(k for k, v in gated["gate_verdicts"].items()
|
|
2227
|
+
if v["planted"]["ok"] is False),
|
|
2228
|
+
"clean_accepted": all(v["clean"]["ok"] for v in gated["gate_verdicts"].values()),
|
|
2229
|
+
**({"why": gated["why"]} if "why" in gated else {})},
|
|
2230
|
+
derivations={"file": DERIVATIONS, "counts": derived["counts"], "delivery": derived["delivery"],
|
|
2231
|
+
"unit_outcomes": derived["unit_outcomes"],
|
|
2232
|
+
"arc_confirmation": derived["arc_confirmation"]},
|
|
2233
|
+
interrupted=interrupted, tranche=tranche,
|
|
2234
|
+
counts={**{o: outcomes.count(o) for o in OUTCOMES},
|
|
2235
|
+
"reused": sum(1 for row in calls for held in row["seats"].values() if held["reused"]),
|
|
2236
|
+
"judged_by_both": sum(1 for row in calls
|
|
2237
|
+
if all(h["outcome"] == "accepted" for h in row["seats"].values()))},
|
|
2238
|
+
density_table=dispatch.measured_table(run_dir))
|
|
2239
|
+
records.write_json(run_dir, run_dir / SUMMARY, summary)
|
|
2240
|
+
stage.output(SUMMARY)
|
|
2241
|
+
if any(o != "accepted" for o in outcomes + swept_outcomes + crossed_outcomes + again_outcomes) \
|
|
2242
|
+
or crossed["not_reviewed"] or again["missing"]:
|
|
2243
|
+
stage.record["status"] = "partial"
|
|
2244
|
+
return summary
|
|
2245
|
+
|
|
2246
|
+
|
|
2247
|
+
def report_lines(summary):
|
|
2248
|
+
"""What the driver prints of S6: counts, sizes and codes, never a candidate's, a unit's or a quote's text."""
|
|
2249
|
+
pop, tot = summary["population"], summary["totals"]
|
|
2250
|
+
left = "; ".join(f"{s} {v['count']} of {v['of']} ({v['why']})" for s, v in pop["left_out"].items()) or "none"
|
|
2251
|
+
lines = [f"S6 judge{' (dry)' if summary['dry'] else ''}: declaration_seq {summary['declaration_seq']}; {pop['judged']} of {pop['candidates']} "
|
|
2252
|
+
f"candidates judged; {len(pop['check_failed'])} rejected by S5's checks; left out: {left}",
|
|
2253
|
+
f"packets: {tot['payload_bytes']} payload bytes over {len(summary['packets'])} candidates, "
|
|
2254
|
+
f"{tot['calls']} calls; output at most {tot['output_at_most']} tokens at the cap {summary['output_cap']}"]
|
|
2255
|
+
for who, lim in summary["limits"].items():
|
|
2256
|
+
at_most = tot["input_at_most"][who]
|
|
2257
|
+
lines.append(f"judge {who} ({lim['seat']}): {tot['driver_bytes'][who]} driver bytes; input at most "
|
|
2258
|
+
+ (f"{at_most} tokens at {lim['bytes_per_token']} bytes a token ({lim['density_basis']}); "
|
|
2259
|
+
f"{len(summary['over_capacity'][who])} packets over its capacity {lim['capacity']}"
|
|
2260
|
+
if at_most is not None else "not computed: " + "; ".join(c.split(":")[0] for c in lim["unmeasured"])))
|
|
2261
|
+
lines.append(f"budget: per_stage S6 {summary['budget']['per_stage']}")
|
|
2262
|
+
if not summary["dry"]:
|
|
2263
|
+
counts = summary["counts"]
|
|
2264
|
+
lines.append(f"calls ({summary['tranche']} tranche): " + ", ".join(f"{o} {counts[o]}" for o in OUTCOMES)
|
|
2265
|
+
+ f"; {counts['reused']} answered by an earlier accepted attempt; {counts['judged_by_both']} of "
|
|
2266
|
+
f"{len(summary['calls'])} candidates judged by both")
|
|
2267
|
+
failed = sorted({c for row in summary["calls"] for held in row["seats"].values() if held["outcome"] != "accepted"
|
|
2268
|
+
for c in held["codes"]})
|
|
2269
|
+
if failed:
|
|
2270
|
+
lines.append(f"codes of the calls not accepted: {', '.join(failed)}")
|
|
2271
|
+
if summary["interrupted"]:
|
|
2272
|
+
lines.append(f"interrupted reservations closed: {len(summary['interrupted'])}")
|
|
2273
|
+
sw = summary["sweeps"]
|
|
2274
|
+
cl = sw.get("claims") or {}
|
|
2275
|
+
lines.append(f"absence claims ({'swept' if cl.get('swept') else 'not swept'}): {cl.get('count')} of "
|
|
2276
|
+
f"{cl.get('judged_by_both')} candidates judged by both - "
|
|
2277
|
+
+ ", ".join(f"{k} {v['claims']} of {v['judged_by_both']}" for k, v in (cl.get("by_kind") or {}).items())
|
|
2278
|
+
+ "; current point " + ("complete" if (cl.get("reference") or {}).get("complete") else "incomplete")
|
|
2279
|
+
+ f" under the {(cl.get('reference') or {}).get('policy')} policy, layers "
|
|
2280
|
+
+ ", ".join(f"{k}={v}" for k, v in ((cl.get("reference") or {}).get("layers") or {}).items()))
|
|
2281
|
+
held = sw.get("withheld") or {}
|
|
2282
|
+
lines.append(f"compiled text at the current point: {held.get('units', 0)} would-be units withheld, "
|
|
2283
|
+
f"{held.get('unmatched', 0)} matching no published unit, so not judgeable here")
|
|
2284
|
+
if not sw["complete"] or sw.get("run") is False: # an incomplete point, or a plan S6 has no room for
|
|
2285
|
+
lines.append(f"sweeps: none - {sw['why']}")
|
|
2286
|
+
else:
|
|
2287
|
+
c = sw["counts"]
|
|
2288
|
+
lines.append(f"sweeps ({sw['policy']} policy): {len(sw['absent'])} absence claims in {len(sw['groups'])} groups, "
|
|
2289
|
+
f"{sum(len(g['shards']) for g in sw['groups'])} shards; calls " + ", ".join(f"{o} {c[o]}" for o in OUTCOMES)
|
|
2290
|
+
+ f"; {c['reused']} answered by an earlier accepted attempt; {len(sw['not_judged_by_both'])} "
|
|
2291
|
+
"candidates not swept because a judge did not judge them")
|
|
2292
|
+
cr = summary["cross_review"]
|
|
2293
|
+
lines.append(f"cross-review by Judge B: {len(cr['reviewed'])} absence claims reviewed, "
|
|
2294
|
+
f"{len(cr.get('exhausted') or [])} with nothing left to sweep, {len(cr['not_reviewed'])} "
|
|
2295
|
+
f"not; calls " + ", ".join(f"{o} {cr['counts'][o]}" for o in OUTCOMES))
|
|
2296
|
+
dv = summary["derivations"]["counts"]
|
|
2297
|
+
lines.append(f"derivations: {dv['derived']} candidates derived, {dv['not_derived']} not; admission "
|
|
2298
|
+
+ ", ".join(f"{k} {n}" for k, n in sorted(dv["admission"].items())) + "; current diagnosis "
|
|
2299
|
+
+ ", ".join(f"{k} {n}" for k, n in sorted(dv["current"].items())) + f"; {dv['eligible']} eligible; "
|
|
2300
|
+
f"{summary['derivations']['delivery']['pairs']} (session, unit) pairs {DELIVERY_WAITING}; no unit "
|
|
2301
|
+
f"outcome for {summary['derivations']['unit_outcomes']['candidates']} candidates (release not "
|
|
2302
|
+
f"judged); arc confirmation undetermined for {summary['derivations']['arc_confirmation']['g_candidates']} "
|
|
2303
|
+
"type G candidates")
|
|
2304
|
+
gc = summary["gate_controls"]
|
|
2305
|
+
lines.append(f"gate controls: {gc['planted']} planted on copies of accepted calls, {len(gc['planted_rejected'])} "
|
|
2306
|
+
f"rejected by the gate; clean counterparts accepted: {gc['clean_accepted']}")
|
|
2307
|
+
rc = summary["reconsiderations"]
|
|
2308
|
+
after = collections.Counter(r["diagnosis"] for r in rc["reconsidered"])
|
|
2309
|
+
lines.append(f"reconsidered by both judges: {len(rc['reconsidered'])} absence claims (" + ", ".join(
|
|
2310
|
+
f"{d} {n}" for d, n in sorted(after.items())) + f"), {len(rc['not_reconsidered'])} missing a "
|
|
2311
|
+
"reconsideration; calls " + ", ".join(f"{o} {rc['counts'][o]}" for o in OUTCOMES))
|
|
2312
|
+
else:
|
|
2313
|
+
b = summary["sweep_upper_bound"]
|
|
2314
|
+
lines.append(f"sweep upper bound ({b['basis']}): {b['groups']} groups, {b['shards']} shards, {b['packets']} calls, "
|
|
2315
|
+
f"{b['pairs']} pairs, {b['payload_bytes']} payload bytes; input "
|
|
2316
|
+
+ ", ".join(f"{side} {n}" for side, n in b["input_tokens_at_j0_density"].items())
|
|
2317
|
+
+ f" tokens at {b['density']} bytes a token; output at most {b['output_tokens_at_most']} tokens")
|
|
2318
|
+
return lines
|
|
2319
|
+
|
|
2320
|
+
|
|
2321
|
+
# ---- the self-test --------------------------------------------------------------------------------------------
|
|
2322
|
+
|
|
2323
|
+
def fx_answer(units=("n1", "n2"), yes=("n1",), entries=("e1",)):
|
|
2324
|
+
"""A schema-valid first-call answer over `units`, matching on `yes`."""
|
|
2325
|
+
return {"requirements": {r: {"mark": "met", "reason": "shown"} for r in REQUIREMENTS},
|
|
2326
|
+
"consequence_class": "quality", "no_longer_arises": {"value": False, "reason": "", "evidence_ids": []},
|
|
2327
|
+
"units": [{"unit": u, "situation": "yes" if u in yes else "no", "action": "yes" if u in yes else "no",
|
|
2328
|
+
"reason": "one line", "quote": "Feed the zebra" if u in yes else ""} for u in units],
|
|
2329
|
+
"matching_units": [{"unit": u, "following": "followed", "following_evidence_ids": ["q1"],
|
|
2330
|
+
"contribution": "helped", "contribution_evidence_ids": ["q1"]} for u in yes],
|
|
2331
|
+
"ledger_relations": [{"entry": e, "relation": "none", "reason": "unrelated"} for e in entries]}
|
|
2332
|
+
|
|
2333
|
+
|
|
2334
|
+
WIDE_TOPICS = ("release", "budget", "review", "schema", "ledger", "window")
|
|
2335
|
+
|
|
2336
|
+
|
|
2337
|
+
def fx_library(wide=0):
|
|
2338
|
+
"""S5's fixture library with what S2's inventory now publishes of each unit (D-20261111-92d81a): its heading, its
|
|
2339
|
+
block and its edges. One unit is enclosed by a frontmatter line of its file (a reference unit S5 does not index), and
|
|
2340
|
+
reaches a unit of another file and an unresolved mention. `wide` adds that many catalog units, each its own text, so
|
|
2341
|
+
an absence claim has more than NEGATIVES units both sweeps find unrelated (J3b)."""
|
|
2342
|
+
front = lifecycle_intake.fx_unit("u-front", "description: when a push reaches a shared remote", cls="reference",
|
|
2343
|
+
path="claude/guides/u-push.md")
|
|
2344
|
+
extra = [lifecycle_intake.fx_unit(f"u-wide-{n:03d}", f"Note step {n} of the {WIDE_TOPICS[n % len(WIDE_TOPICS)]} "
|
|
2345
|
+
"routine in its dated log.") for n in range(1, wide + 1)]
|
|
2346
|
+
units = [dict(u) for u in lifecycle_intake.FX_LIBRARY] + [front] + extra
|
|
2347
|
+
for n, unit in enumerate(units, 1): # a path of its own, so a unit's id is never a spelling of its path
|
|
2348
|
+
if unit["path"] == f"claude/guides/{unit['unit_id']}.md":
|
|
2349
|
+
unit["path"] = f"claude/guides/guide-{n}.md"
|
|
2350
|
+
front["path"] = next(u["path"] for u in units if u["unit_id"] == "u-push")
|
|
2351
|
+
for n, unit in enumerate(units, 1):
|
|
2352
|
+
unit.setdefault("heading", f"Guide {n} > Rule")
|
|
2353
|
+
unit["block"] = "frontmatter" if unit is front else "list-item"
|
|
2354
|
+
unit["edges"] = {"direct": [unit["unit_id"]], "reached": []}
|
|
2355
|
+
push = next(u for u in units if u["unit_id"] == "u-push")
|
|
2356
|
+
push["edges"] = {"direct": sorted(["u-push", "u-front"]), "reached": sorted(["u-tests", "k-" + "a" * 24])}
|
|
2357
|
+
return units
|
|
2358
|
+
|
|
2359
|
+
|
|
2360
|
+
def fx_seats(root, capacity_a=None, name="seats.json", capacities=None, codex_allowance=None):
|
|
2361
|
+
"""A seats file as D13 leaves the judges' seats until their first live calls: seats.json's own, with Judge A's
|
|
2362
|
+
capacity and Claude's allowance measured and Judge B's host allowance and seat capacity not; `capacity_a` replaces
|
|
2363
|
+
Judge A's capacity. `capacities` (`{seat: tokens}`) declares a capacity for other seats at their host's version, and
|
|
2364
|
+
`codex_allowance` measures the Codex host's, so a sweep's or a cross-review's seat can be bounded in a control."""
|
|
2365
|
+
held = json.loads(gate.SEATS.read_text(encoding="utf-8"))
|
|
2366
|
+
if capacity_a is not None:
|
|
2367
|
+
held["seat_capacity"]["claude:claude-opus-5-5/high"]["context_capacity"] = capacity_a
|
|
2368
|
+
held["hosts"]["codex"]["host_allowance"] = {"hermetic": {"allowance_tokens": None, "measured": False,
|
|
2369
|
+
"basis": "unmeasured: D13"}}
|
|
2370
|
+
# every Codex seat's capacity, declared since from the pinned binary's catalogue: the fixture is D13's state
|
|
2371
|
+
for seat in [seat for seat in held["seat_capacity"] if seat.startswith("codex:")]:
|
|
2372
|
+
held["seat_capacity"].pop(seat)
|
|
2373
|
+
for seat, tokens in (capacities or {}).items():
|
|
2374
|
+
held["seat_capacity"][seat] = {"context_capacity": tokens, "basis": "planted by a control",
|
|
2375
|
+
"host_version": held["hosts"][seat.partition(":")[0]]["version"]}
|
|
2376
|
+
if codex_allowance is not None:
|
|
2377
|
+
held["hosts"]["codex"]["host_allowance"] = {"hermetic": {"allowance_tokens": codex_allowance, "measured": True,
|
|
2378
|
+
"basis": "planted by a control"}}
|
|
2379
|
+
path = pathlib.Path(root) / name
|
|
2380
|
+
path.write_text(json.dumps(held), encoding="utf-8")
|
|
2381
|
+
return path
|
|
2382
|
+
|
|
2383
|
+
|
|
2384
|
+
def fx_judge_answer(labels):
|
|
2385
|
+
"""A schema-valid first-call answer to one packet, in its labels: every unit judged, the first one matching with a
|
|
2386
|
+
span of its text, its following and contribution shown by the packet's first quote, every ledger entry related."""
|
|
2387
|
+
units = list(labels.units)
|
|
2388
|
+
answer = fx_answer(units=tuple(units), yes=tuple(units[:1]), entries=tuple(labels.entries))
|
|
2389
|
+
quote = list(labels.quotes)[:1]
|
|
2390
|
+
for row in answer["units"]:
|
|
2391
|
+
if row["quote"]:
|
|
2392
|
+
row["quote"] = labels.unit_store[labels.units[row["unit"]]]["text"][:12]
|
|
2393
|
+
for row in answer["matching_units"]:
|
|
2394
|
+
row["following_evidence_ids"], row["contribution_evidence_ids"] = list(quote), list(quote)
|
|
2395
|
+
return answer
|
|
2396
|
+
|
|
2397
|
+
|
|
2398
|
+
def fx_judge_plan(run_dir, path, edit=None):
|
|
2399
|
+
"""The golden hosts' plan for S6 over a run S5 completed: one row per (candidate, judge), matched by the judge's seat
|
|
2400
|
+
and the candidate's whole payload, answering it (`fx_judge_answer`); `edit(candidate id, judge, row)` plants a
|
|
2401
|
+
defect in a row. The packets are built under an S6 admission of `run_dir`, so the plan is made on a copy of the run
|
|
2402
|
+
it answers. `(path, {candidate id: (labels, payload)})`."""
|
|
2403
|
+
with records.run_stage(run_dir, STAGE, INPUTS) as stage:
|
|
2404
|
+
summary, packets = build(run_dir, stage.declaration)
|
|
2405
|
+
stage.record["status"] = "partial"
|
|
2406
|
+
rows = []
|
|
2407
|
+
for cid, (labels, text) in sorted(packets.items()):
|
|
2408
|
+
for who, seat in summary["seats"].items():
|
|
2409
|
+
row = {"match": [f"SEAT: {seat}", text], "answer": fx_judge_answer(labels)}
|
|
2410
|
+
if edit is not None:
|
|
2411
|
+
edit(cid, who, row)
|
|
2412
|
+
rows.append(row)
|
|
2413
|
+
pathlib.Path(path).write_text(json.dumps(rows), encoding="utf-8")
|
|
2414
|
+
return path, packets
|
|
2415
|
+
|
|
2416
|
+
|
|
2417
|
+
def self_test():
|
|
2418
|
+
failures, ran = [], []
|
|
2419
|
+
|
|
2420
|
+
def control(name, condition, detail=""):
|
|
2421
|
+
ran.append(name)
|
|
2422
|
+
if not condition:
|
|
2423
|
+
failures.append(f"{name}: {detail}")
|
|
2424
|
+
|
|
2425
|
+
def named(name, lines, code):
|
|
2426
|
+
control(name, any(line.startswith(code) for line in lines), f"expected {code} in {lines[:3]}")
|
|
2427
|
+
|
|
2428
|
+
def refusal(action):
|
|
2429
|
+
try:
|
|
2430
|
+
action()
|
|
2431
|
+
except Refused as exc:
|
|
2432
|
+
return str(exc)
|
|
2433
|
+
except Exception as exc: # noqa: BLE001 - reported by the control that reads it
|
|
2434
|
+
return f"RAISED {exc!r}"
|
|
2435
|
+
return ""
|
|
2436
|
+
|
|
2437
|
+
def guarded(action, default):
|
|
2438
|
+
try:
|
|
2439
|
+
return action()
|
|
2440
|
+
except Exception as exc: # noqa: BLE001 - reported by the control that reads the default
|
|
2441
|
+
return default(exc) if callable(default) else default
|
|
2442
|
+
|
|
2443
|
+
held = schema()
|
|
2444
|
+
# ---- done-when 8: the schema's fields are §6.2's, both ways --------------------------------------------------
|
|
2445
|
+
control("the judgment schema compiles under the schema policy", not refusal(lambda: validate.compile_schema(held)),
|
|
2446
|
+
refusal(lambda: validate.compile_schema(held)))
|
|
2447
|
+
control("done-when 8: the judgment schema's per-unit and per-candidate fields are §6.2's", not contract_problems(held),
|
|
2448
|
+
f"{contract_problems(held)}")
|
|
2449
|
+
# each plant tolerates a schema that already lacks what it removes, so a mutation of the schema itself fails the
|
|
2450
|
+
# control above by name instead of ending the suite here (Codex WP-11 r1 #6)
|
|
2451
|
+
dropped = json.loads(json.dumps(held))
|
|
2452
|
+
dropped["$defs"]["unit_judgment"]["properties"].pop("quote", None)
|
|
2453
|
+
dropped["$defs"]["unit_judgment"]["required"] = [f for f in dropped["$defs"]["unit_judgment"]["required"]
|
|
2454
|
+
if f != "quote"]
|
|
2455
|
+
named("control: a §6.2 field dropped from the schema is CONTRACT_DRIFT", contract_problems(dropped), "CONTRACT_DRIFT")
|
|
2456
|
+
added = json.loads(json.dumps(held))
|
|
2457
|
+
added["$defs"]["unit_judgment"]["properties"]["confidence"] = {"type": "string"}
|
|
2458
|
+
named("control: a schema field §6.2 does not name and no reason declares is CONTRACT_DRIFT",
|
|
2459
|
+
contract_problems(added), "CONTRACT_DRIFT")
|
|
2460
|
+
gone = json.loads(json.dumps(held))
|
|
2461
|
+
gone["properties"].pop("no_longer_arises", None)
|
|
2462
|
+
gone["required"] = [f for f in gone["required"] if f != "no_longer_arises"]
|
|
2463
|
+
named("control: a declared extra field the schema no longer holds is CONTRACT_DRIFT", contract_problems(gone),
|
|
2464
|
+
"CONTRACT_DRIFT stage_judge.EXTRA_FIELDS")
|
|
2465
|
+
control("the schema's paths are read through its references (the requirements and the units are reached)",
|
|
2466
|
+
{"requirements.*.mark", "units[].quote", "matching_units[].contribution"} <= set(schema_paths(held, held["$defs"])),
|
|
2467
|
+
f"{sorted(schema_paths(held, held['$defs']))}")
|
|
2468
|
+
control("D11: the schema's enum holds §7.5's six consequence classes", classes(held) == (
|
|
2469
|
+
"irreversible", "security", "verification-corrupting", "cost", "quality", "none"), f"{classes(held)}")
|
|
2470
|
+
answer = fx_answer()
|
|
2471
|
+
control("a first-call answer of the fixture is schema-valid",
|
|
2472
|
+
not validate.violations(validate.compile_schema(held), answer), f"{validate.violations(validate.compile_schema(held), answer)}")
|
|
2473
|
+
|
|
2474
|
+
# ---- the reuse key -----------------------------------------------------------------------------------------
|
|
2475
|
+
unit = {"unit_id": "u-0000000000000001", "text": "Feed the zebra at noon.", "heading": "Zoo > Feeding",
|
|
2476
|
+
"layer": "catalog", "scope": None}
|
|
2477
|
+
base = dict(candidate={"candidate_id": "k-1", "lesson": "feed on time"}, claims=[{"claim_id": "c1"}],
|
|
2478
|
+
quotes=[{"evidence_id": "q1", "text": "fed late"}], unit=unit,
|
|
2479
|
+
trigger=[{"unit_id": "u-f", "text": "description: feeding"}], exceptions=[{"unit_id": "u-h", "text": "## Feeding"}],
|
|
2480
|
+
references=[{"unit_id": "u-r", "text": "The keeper's rota."}], prompt_sha256="p" * 64, schema_sha256="s" * 64,
|
|
2481
|
+
seat="claude:claude-opus-5-5/high")
|
|
2482
|
+
parts = key_components(**base)
|
|
2483
|
+
control("done-when 8: the reuse key's component list is §6.2's", not key_problems(tuple(parts)), f"{key_problems(tuple(parts))}")
|
|
2484
|
+
named("control: a component missing from the key is CONTRACT_DRIFT",
|
|
2485
|
+
key_problems(tuple(k for k in parts if k != "seat")), "CONTRACT_DRIFT")
|
|
2486
|
+
said = refusal(lambda: unit_key({**parts, "attempt": 1}))
|
|
2487
|
+
control("control: a key handed a component §6.2 does not name is refused by name", said.startswith("CONTRACT_DRIFT"), said)
|
|
2488
|
+
key = unit_key(parts)
|
|
2489
|
+
control("the same components give the same key", unit_key(key_components(**base)) == key)
|
|
2490
|
+
for name, change in (("the seat", {"seat": "codex:gpt-6-astra/xhigh"}),
|
|
2491
|
+
("one byte of the unit's text", {"unit": {**unit, "text": unit["text"][:-1] + "!"}}),
|
|
2492
|
+
("the heading path", {"unit": {**unit, "heading": "Zoo"}}),
|
|
2493
|
+
("an enclosing exception", {"exceptions": [{"unit_id": "u-h", "text": "## Feeding, except Sundays"}]}),
|
|
2494
|
+
("a referenced unit's text", {"references": [{"unit_id": "u-r", "text": "The keeper's new rota."}]}),
|
|
2495
|
+
("the candidate", {"candidate": {"candidate_id": "k-1", "lesson": "feed earlier"}}),
|
|
2496
|
+
("a quote", {"quotes": [{"evidence_id": "q1", "text": "fed later"}]}),
|
|
2497
|
+
("the prompt", {"prompt_sha256": "q" * 64})):
|
|
2498
|
+
control(f"D12: {name} changed gives another key", unit_key(key_components(**{**base, **change})) != key)
|
|
2499
|
+
|
|
2500
|
+
# ---- one payload for both seats; one receipt per call ------------------------------------------------------
|
|
2501
|
+
sample = "line one\nline two\n"
|
|
2502
|
+
control("the same payload to both seats is no divergence", not divergence({"A": sample, "B": sample}))
|
|
2503
|
+
named("done-when 1 control: a seat-specific line injected into one payload is PACKET_DIVERGENCE",
|
|
2504
|
+
divergence({"A": sample, "B": sample + "You are Judge B.\n"}), "PACKET_DIVERGENCE")
|
|
2505
|
+
built = {seat: packet.build(f"r1-S6-k1-{seat}-a1", STAGE, s, sample, None)
|
|
2506
|
+
for seat, s in (("A", "claude:claude-opus-5-5/high"), ("B", "codex:gpt-6-astra/xhigh"))}
|
|
2507
|
+
hashes = {seat: (packet.sha256_bytes(b), packet.payload_sha256(b)) for seat, b in built.items()}
|
|
2508
|
+
control("done-when 1: the two seats' packets share the payload hash and each packet hash is its own",
|
|
2509
|
+
hashes["A"][1] == hashes["B"][1] and hashes["A"][0] != hashes["B"][0], f"{hashes}")
|
|
2510
|
+
|
|
2511
|
+
def receipt(seat):
|
|
2512
|
+
return {"packet_sha256": hashes[seat][0], "evidence": {"payload_sha256": hashes[seat][1]}}
|
|
2513
|
+
|
|
2514
|
+
control("the two seats' receipts of one judgment pass", not receipt_problems(
|
|
2515
|
+
{"c-A": ("A", receipt("A")), "c-B": ("B", receipt("B"))}))
|
|
2516
|
+
named("done-when 1 control: two receipts carrying one packet hash are RECEIPT_STALE",
|
|
2517
|
+
receipt_problems({"c-A": ("A", receipt("A")), "c-A2": ("A", receipt("A"))}), "RECEIPT_STALE")
|
|
2518
|
+
named("control: the seats' receipts carrying different payload hashes are PACKET_DIVERGENCE",
|
|
2519
|
+
receipt_problems({"c-A": ("A", receipt("A")),
|
|
2520
|
+
"c-B": ("B", {**receipt("B"), "evidence": {"payload_sha256": "0" * 64}})}), "PACKET_DIVERGENCE")
|
|
2521
|
+
|
|
2522
|
+
# ---- the answer against its packet -------------------------------------------------------------------------
|
|
2523
|
+
shown = {"units": {"n1": "Feed the zebra at noon.", "n2": "Wash the bucket."}, "quotes": ["q1"], "entries": ["e1"]}
|
|
2524
|
+
control("a first-call answer that judges every unit and entry passes", not answer_problems(shown, answer),
|
|
2525
|
+
f"{answer_problems(shown, answer)}")
|
|
2526
|
+
|
|
2527
|
+
def edited(change):
|
|
2528
|
+
a = json.loads(json.dumps(answer))
|
|
2529
|
+
change(a)
|
|
2530
|
+
return answer_problems(shown, a)
|
|
2531
|
+
|
|
2532
|
+
for name, change, code in (
|
|
2533
|
+
("a unit left unjudged", lambda a: a["units"].pop(), "UNIT_UNJUDGED"),
|
|
2534
|
+
("a unit judged twice", lambda a: a["units"].append(dict(a["units"][1])), "UNIT_JUDGED_TWICE"),
|
|
2535
|
+
("a unit the packet does not show", lambda a: a["units"].append({**a["units"][1], "unit": "n9"}), "UNKNOWN_LABEL"),
|
|
2536
|
+
("a yes without its quote", lambda a: a["units"][0].update(quote=""), "QUOTE_MISSING"),
|
|
2537
|
+
("a quote where both matches are no", lambda a: a["units"][1].update(quote="Wash"), "QUOTE_UNEXPECTED"),
|
|
2538
|
+
("a quote that is not a span of its unit", lambda a: a["units"][0].update(quote="Feed the lion"), "QUOTE_NOT_IN_UNIT"),
|
|
2539
|
+
("a matching unit without its following and contribution", lambda a: a["matching_units"].clear(),
|
|
2540
|
+
"MATCHING_UNIT_MISSING"),
|
|
2541
|
+
("a following given for a unit that does not match", lambda a: a["matching_units"].append(
|
|
2542
|
+
{**a["matching_units"][0], "unit": "n2"}), "MATCHING_UNIT_UNEXPECTED"),
|
|
2543
|
+
("evidence the packet does not show", lambda a: a["matching_units"][0].update(following_evidence_ids=["q7"]),
|
|
2544
|
+
"UNKNOWN_LABEL"),
|
|
2545
|
+
("a matching unit's following given twice", lambda a: a["matching_units"].append(dict(a["matching_units"][0])),
|
|
2546
|
+
"MATCHING_UNIT_TWICE"),
|
|
2547
|
+
("no-longer-arises evidence the packet does not show",
|
|
2548
|
+
lambda a: a["no_longer_arises"].update(evidence_ids=["q8"]), "UNKNOWN_LABEL no_longer_arises"),
|
|
2549
|
+
("a relation to an entry the packet does not show",
|
|
2550
|
+
lambda a: a["ledger_relations"].append({**a["ledger_relations"][0], "entry": "e9"}), "UNKNOWN_LABEL ledger_relations"),
|
|
2551
|
+
("a ledger entry with no relation", lambda a: a["ledger_relations"].clear(), "ENTRY_UNJUDGED"),
|
|
2552
|
+
("a ledger entry related twice", lambda a: a["ledger_relations"].append(dict(a["ledger_relations"][0])),
|
|
2553
|
+
"ENTRY_JUDGED_TWICE")):
|
|
2554
|
+
named(f"control: {name} is refused by name", edited(change), code)
|
|
2555
|
+
later = {"units": answer["units"], "matching_units": [], "ledger_relations": []}
|
|
2556
|
+
control("a later reference point's answer that judges its units only passes",
|
|
2557
|
+
not answer_problems(shown, later, first=False), f"{answer_problems(shown, later, first=False)}")
|
|
2558
|
+
named("control: a later call's answer that judges a ledger entry is refused (D12)",
|
|
2559
|
+
answer_problems(shown, {**later, "ledger_relations": answer["ledger_relations"]}, first=False), "FIELD_UNEXPECTED")
|
|
2560
|
+
|
|
2561
|
+
# ---- which candidates are judged ----------------------------------------------------------------------------
|
|
2562
|
+
pop = ([{"candidate_id": f"k-f{n}", "source": "formed"} for n in range(3)]
|
|
2563
|
+
+ [{"candidate_id": f"k-l{n:02d}", "source": "legacy"} for n in range(12)]
|
|
2564
|
+
+ [{"candidate_id": "k-g0", "source": "g_cluster"}] + [{"candidate_id": f"k-r{n}", "source": "redundancy_hint"} for n in range(4)])
|
|
2565
|
+
every, none_left = judged_of(pop, {}, "r1")
|
|
2566
|
+
control("with no judged scope declared every candidate is judged and none is left out",
|
|
2567
|
+
every == sorted(k["candidate_id"] for k in pop) and none_left == {}, f"{none_left}")
|
|
2568
|
+
scoped = {"judge": {"candidate_kinds": {"formed": "all", "legacy": 3, "redundancy_hint": 0}}}
|
|
2569
|
+
picked, left = judged_of(pop, scoped, "r1")
|
|
2570
|
+
control("a declared scope judges all the formed, a sample of the legacy, and names every source it leaves out with "
|
|
2571
|
+
"its count and why", sum(i.startswith("k-f") for i in picked) == 3 and sum(i.startswith("k-l") for i in picked) == 3
|
|
2572
|
+
and not any(i.startswith(("k-g", "k-r")) for i in picked)
|
|
2573
|
+
and left == {"legacy": {"count": 9, "of": 12, "why": "a sample of 3 drawn from the run id"},
|
|
2574
|
+
"g_cluster": {"count": 1, "of": 1, "why": "the declaration's judge.candidate_kinds leaves this source out"},
|
|
2575
|
+
"redundancy_hint": {"count": 4, "of": 4, "why": "a sample of 0 drawn from the run id"}}, f"{left}")
|
|
2576
|
+
control("the sample is drawn from the run id: the same id draws the same, another id another",
|
|
2577
|
+
judged_of(pop, scoped, "r1")[0] == picked and judged_of(pop, scoped, "r2")[0] != picked)
|
|
2578
|
+
rows = [{"candidate_id": "k-f0", "quote_ok": False, "quote_problems": ["QUOTE_MISMATCH q-1"], "session_problems": []},
|
|
2579
|
+
{"candidate_id": "k-f1", "quote_ok": True, "quote_problems": [], "session_problems": ["SESSION_UNKNOWN s-9"]},
|
|
2580
|
+
{"candidate_id": "k-f2", "quote_ok": None, "quote_problems": [], "session_problems": []}]
|
|
2581
|
+
failed = check_failures(rows)
|
|
2582
|
+
control("S5's check failures are named with their codes and not judged",
|
|
2583
|
+
failed == {"k-f0": ["QUOTE_MISMATCH"], "k-f1": ["SESSION_UNKNOWN"]}
|
|
2584
|
+
and judged_of(pop, {}, "r1", failed)[0] == sorted(set(every) - {"k-f0", "k-f1"}), f"{failed}")
|
|
2585
|
+
said = refusal(lambda: judged_of(pop + [{"candidate_id": "k-x", "source": "planted"}], {}, "r1"))
|
|
2586
|
+
control("control: a source the judged scope has no key for is refused by name", said.startswith("SOURCE_UNDECLARED"), said)
|
|
2587
|
+
|
|
2588
|
+
# ---- the packet and the dry stage over a golden run through S5 ------------------------------------------------
|
|
2589
|
+
control("the judge template is one packet.TEMPLATES lists, and its placeholders are the five blocks",
|
|
2590
|
+
TEMPLATE in packet.TEMPLATES and guarded(lambda: packet.template_fields(TEMPLATE), []) == sorted(BLOCKS),
|
|
2591
|
+
f"{packet.TEMPLATES}")
|
|
2592
|
+
control("the sweep template is one packet.TEMPLATES lists, and its placeholders are the candidates, the inventory and "
|
|
2593
|
+
"the units", SWEEP_TEMPLATE in packet.TEMPLATES
|
|
2594
|
+
and guarded(lambda: packet.template_fields(SWEEP_TEMPLATE), []) == ["candidates", "inventory", "units"],
|
|
2595
|
+
f"{packet.TEMPLATES}")
|
|
2596
|
+
control("the cross-review template is one packet.TEMPLATES lists, and its placeholders are the candidate and the units",
|
|
2597
|
+
CROSS_TEMPLATE in packet.TEMPLATES and guarded(lambda: packet.template_fields(CROSS_TEMPLATE), []) == ["candidate", "units"],
|
|
2598
|
+
f"{packet.TEMPLATES}")
|
|
2599
|
+
control("the reconsideration template is one packet.TEMPLATES lists, and its placeholders are the candidate, its "
|
|
2600
|
+
"claims, the context and the units", RECONSIDER_TEMPLATE in packet.TEMPLATES
|
|
2601
|
+
and guarded(lambda: packet.template_fields(RECONSIDER_TEMPLATE), []) == ["candidate", "claims", "context", "units"],
|
|
2602
|
+
f"{packet.TEMPLATES}")
|
|
2603
|
+
# ---- the reconsideration's shape (J3c): units and matching units only ------------------------------------------
|
|
2604
|
+
held_rs, projected = guarded(reconsider_schema, {}), guarded(reconsider_projection, None)
|
|
2605
|
+
control("J3c: reconsider.schema.json is the judge schema's units and matching units with the definitions they reach, "
|
|
2606
|
+
"closed, and nothing else", held_rs == projected and projected is not None
|
|
2607
|
+
and sorted(held_rs.get("properties", {})) == sorted(RECONSIDER_FIELDS)
|
|
2608
|
+
and held_rs.get("additionalProperties") is False and held_rs.get("required") == list(RECONSIDER_FIELDS))
|
|
2609
|
+
drifted = json.loads(json.dumps(schema()))
|
|
2610
|
+
drifted["$defs"]["unit_judgment"].setdefault("properties", {})["confidence"] = {"type": "string"}
|
|
2611
|
+
control("control: a field added to the judge schema's unit judgment makes the reconsideration schema stale",
|
|
2612
|
+
guarded(lambda: reconsider_projection(drifted), None) != held_rs)
|
|
2613
|
+
control("control: a candidate-level field added to reconsider.schema.json is not its projection",
|
|
2614
|
+
{**held_rs, "properties": {**held_rs.get("properties", {}), "requirements": schema()["properties"]["requirements"]}}
|
|
2615
|
+
!= projected)
|
|
2616
|
+
sample_r = {"units": [{"unit": "n1", "situation": "no", "action": "no", "reason": "one line", "quote": ""}],
|
|
2617
|
+
"matching_units": []}
|
|
2618
|
+
rs_validator = guarded(lambda: validate.compile_schema(held_rs), None)
|
|
2619
|
+
control("J3c: the reconsideration schema takes a units-only answer and refuses one carrying a candidate-level field",
|
|
2620
|
+
rs_validator is not None and not validate.violations(rs_validator, sample_r)
|
|
2621
|
+
and all(validate.violations(rs_validator, {**sample_r, f: fx_answer()[f]}) for f in RECONSIDER_REFUSED))
|
|
2622
|
+
shown_r = {"units": {"n1": "Feed the zebra at noon."}, "quotes": ["q1"], "entries": []}
|
|
2623
|
+
control("J3c: a units-only reconsideration answer is no problem", not answer_problems(shown_r, sample_r, reconsider=True))
|
|
2624
|
+
for field in RECONSIDER_REFUSED:
|
|
2625
|
+
named(f"control: a reconsideration answering `{field}` is FIELD_UNEXPECTED",
|
|
2626
|
+
answer_problems(shown_r, {**sample_r, field: fx_answer()[field]}, reconsider=True), "FIELD_UNEXPECTED")
|
|
2627
|
+
judge_md, recon_md = (guarded(lambda n=n: packet.template_text(n), "") for n in (TEMPLATE, RECONSIDER_TEMPLATE))
|
|
2628
|
+
unit_rules = [t[t.find("For every unit in <units>, exactly once"):t.find("`text`; otherwise the empty string.")]
|
|
2629
|
+
for t in (judge_md, recon_md)]
|
|
2630
|
+
control("J3c: the reconsideration asks for each unit's judgment in the judgment packet's own words",
|
|
2631
|
+
unit_rules[0] and unit_rules[0] == unit_rules[1] and "For the candidate" not in recon_md
|
|
2632
|
+
and "<ledger_entries>" not in recon_md)
|
|
2633
|
+
form_text, judge_text = (guarded(lambda name=n: packet.template_text(name), "") for n in ("form", TEMPLATE))
|
|
2634
|
+
definitions = [line for line in form_text.splitlines() if re.match(r"^(\d\. `| \S)", line)]
|
|
2635
|
+
control("the eight requirements are defined in the judge template exactly as the formation template defines them",
|
|
2636
|
+
definitions and "\n".join(definitions) in judge_text and len([d for d in definitions if re.match(r"^\d\. ", d)]) == 8,
|
|
2637
|
+
f"{len(definitions)} definition lines")
|
|
2638
|
+
control("the eight requirements of the template are the schema's", all(f"`{r}`" in judge_text for r in REQUIREMENTS))
|
|
2639
|
+
control("the judged scope's keys in run.json's schema are S5's sources", sorted(json.loads(
|
|
2640
|
+
(HERE / "schemas" / "run.schema.json").read_text(encoding="utf-8"))["properties"]["judge"]["properties"]
|
|
2641
|
+
["candidate_kinds"]["properties"]) == sorted(SOURCES), f"{SOURCES}")
|
|
2642
|
+
said = refusal(lambda: seats_of({"seats": {"S6.A": "claude:claude-opus-5-5/high"}}))
|
|
2643
|
+
control("control: a declaration without Judge B's seat is SEAT_UNDECLARED", said.startswith("SEAT_UNDECLARED"), said)
|
|
2644
|
+
root = pathlib.Path(tempfile.mkdtemp(prefix="s6-"))
|
|
2645
|
+
try:
|
|
2646
|
+
seats_file = fx_seats(root)
|
|
2647
|
+
base = guarded(lambda: stage_retrieve.fx_gold(root / "base", stage_retrieve.fx_current(fx_library())), lambda e: e)
|
|
2648
|
+
if isinstance(base, Exception):
|
|
2649
|
+
failures.append(f"the golden run through S4 could not be made: {base!r}")
|
|
2650
|
+
base = None
|
|
2651
|
+
|
|
2652
|
+
def copy_of(label, through_s5=True):
|
|
2653
|
+
where = root / f"c-{label}"
|
|
2654
|
+
shutil.copytree(base.parent, where)
|
|
2655
|
+
run_dir = where / base.name
|
|
2656
|
+
if through_s5:
|
|
2657
|
+
stage_retrieve.run(run_dir, "aa" * 8)
|
|
2658
|
+
return run_dir
|
|
2659
|
+
|
|
2660
|
+
if base is not None:
|
|
2661
|
+
gold = copy_of("gold")
|
|
2662
|
+
made = guarded(lambda: run(gold, dry=True, seats_path=seats_file), lambda e: {"problem": repr(e)})
|
|
2663
|
+
record = guarded(lambda: records.read_json(records.record_path(gold, STAGE)), {})
|
|
2664
|
+
dry = guarded(lambda: records.read_json(gold / DRY_RECORD), {})
|
|
2665
|
+
control("golden: S6 dry over S5's population records its dry measure and stays partial",
|
|
2666
|
+
record.get("status") == "partial" and [o["artifact"] for o in record.get("outputs", [])] == [DRY_RECORD]
|
|
2667
|
+
and dry.get("dry") is True, f"{made}")
|
|
2668
|
+
checks = guarded(lambda: records.read_json(gold / "checks.json"), {"candidates": []})
|
|
2669
|
+
population = guarded(lambda: records.read_json(gold / "checked-candidates.json"), {"candidates": []})
|
|
2670
|
+
planted = guarded(lambda: records.read_json(gold / controls.CONTROLS_FILE), {"planted": []})
|
|
2671
|
+
failed_ids = {r["candidate_id"] for r in checks["candidates"] if r["quote_ok"] is False or r["session_problems"]}
|
|
2672
|
+
pop = dry.get("population", {})
|
|
2673
|
+
control("golden: every candidate S5's checks passed is judged; S5's failures - the altered quote and the "
|
|
2674
|
+
"fabricated session among them - are rejected by check failure, by name; none is left out",
|
|
2675
|
+
pop.get("judged") == len(population["candidates"]) - len(failed_ids) and len(failed_ids) >= 2
|
|
2676
|
+
and set(pop.get("check_failed", {})) == failed_ids and pop.get("left_out") == {}
|
|
2677
|
+
and {r["candidate_id"] for r in dry.get("packets", [])} == {k["candidate_id"] for k in population["candidates"]} - failed_ids,
|
|
2678
|
+
f"{pop}")
|
|
2679
|
+
control("golden: Judge A's input is measured; Judge B's is not, its unmeasured allowance and capacity named (D13)",
|
|
2680
|
+
all(isinstance(r["input_at_most"]["A"], int) and r["input_at_most"]["B"] is None for r in dry.get("packets", []))
|
|
2681
|
+
and [c.split()[0] for c in dry.get("limits", {}).get("B", {}).get("unmeasured", [])]
|
|
2682
|
+
== ["ALLOWANCE_UNMEASURED", "CAPACITY_UNDECLARED"] and dry.get("output_cap") == OUTPUT_CAP,
|
|
2683
|
+
f"{dry.get('limits')}")
|
|
2684
|
+
# Codex WP-10 X r1 #7: whatever module S6 runs, and however it reaches the expected verdicts' file - a glob
|
|
2685
|
+
# over the run, a computed name, a link under another name, an open relative to the run's directory - it is
|
|
2686
|
+
# refused CONTROLS_READ; each reader is planted in S6's own builder on a copy of the golden run
|
|
2687
|
+
kept_build = globals()["build"]
|
|
2688
|
+
|
|
2689
|
+
def plant_reader(read):
|
|
2690
|
+
def reading(run_dir, *rest, **kw):
|
|
2691
|
+
read(pathlib.Path(run_dir))
|
|
2692
|
+
return kept_build(run_dir, *rest, **kw)
|
|
2693
|
+
return reading
|
|
2694
|
+
|
|
2695
|
+
def linked(where):
|
|
2696
|
+
os.link(where / controls.CONTROLS_FILE, where / "linked.json")
|
|
2697
|
+
return (where / "linked.json").read_text(encoding="utf-8")
|
|
2698
|
+
|
|
2699
|
+
def by_fd(where):
|
|
2700
|
+
fd = os.open(where, os.O_RDONLY)
|
|
2701
|
+
try:
|
|
2702
|
+
os.close(os.open(controls.CONTROLS_FILE, os.O_RDONLY, dir_fd=fd))
|
|
2703
|
+
finally:
|
|
2704
|
+
os.close(fd)
|
|
2705
|
+
|
|
2706
|
+
def swallowed(where):
|
|
2707
|
+
try:
|
|
2708
|
+
(where / controls.CONTROLS_FILE).read_bytes()
|
|
2709
|
+
except Exception: # noqa: BLE001 - the planted reader hides the refusal; the seal names it at the end
|
|
2710
|
+
pass
|
|
2711
|
+
readers = {"glob": lambda where: {p.name: p.read_text(encoding="utf-8") for p in where.glob("*.json")},
|
|
2712
|
+
"constructed": lambda where: (where / ("con" + "trols." + "json")).read_text(encoding="utf-8"),
|
|
2713
|
+
"linked": linked, "fd-relative": by_fd, "swallowed": swallowed}
|
|
2714
|
+
sealed_said = {}
|
|
2715
|
+
for label, read in readers.items():
|
|
2716
|
+
target = copy_of(f"sealed-{label}")
|
|
2717
|
+
globals()["build"] = plant_reader(read)
|
|
2718
|
+
try:
|
|
2719
|
+
sealed_said[label] = refusal(lambda: run(target, dry=True, seats_path=seats_file))
|
|
2720
|
+
finally:
|
|
2721
|
+
globals()["build"] = kept_build
|
|
2722
|
+
control("Codex WP-10 X r1 #7: a glob over the run, a computed name, a link, an fd-relative open, and a read "
|
|
2723
|
+
"whose refusal is swallowed, planted in S6's own builder, are each CONTROLS_READ",
|
|
2724
|
+
all(str(v).startswith("CONTROLS_READ S6") for v in sealed_said.values()) and len(sealed_said) == 5,
|
|
2725
|
+
f"{ {k: str(v)[:90] for k, v in sealed_said.items()} }")
|
|
2726
|
+
outside = copy_of("sealed-after")
|
|
2727
|
+
control("Codex WP-10 X r1 #7: the seal holds only while S6 runs: the same file opens after it",
|
|
2728
|
+
guarded(lambda: run(outside, dry=True, seats_path=seats_file).get("dry"), None) is True
|
|
2729
|
+
and guarded(lambda: bool((outside / controls.CONTROLS_FILE).read_bytes()), False), "")
|
|
2730
|
+
lines = guarded(lambda: report_lines(made), [])
|
|
2731
|
+
control("golden: the report says what was judged, measured and not measured, in counts and codes",
|
|
2732
|
+
any("candidates judged" in l for l in lines) and any("not computed: ALLOWANCE_UNMEASURED" in l for l in lines),
|
|
2733
|
+
f"{lines}")
|
|
2734
|
+
# the packets themselves, built again as the stage builds them, under a stage admission of a copy
|
|
2735
|
+
again = copy_of("again")
|
|
2736
|
+
with records.run_stage(again, STAGE, INPUTS) as stage:
|
|
2737
|
+
again_summary, packets = guarded(lambda: build(again, stage.declaration, seats_file), lambda e: (repr(e), {}))
|
|
2738
|
+
built = dict(packets)
|
|
2739
|
+
control("golden: building again gives the packets dry.json measured, candidate by candidate",
|
|
2740
|
+
isinstance(again_summary, dict) and [r["payload_sha256"] for r in again_summary["packets"]]
|
|
2741
|
+
== [r["payload_sha256"] for r in dry.get("packets", [])], f"{again_summary if isinstance(again_summary, str) else ''}")
|
|
2742
|
+
by_id = {k["candidate_id"]: k for k in population["candidates"]}
|
|
2743
|
+
rows_of = {r["candidate_id"]: r for r in checks["candidates"]}
|
|
2744
|
+
units = {u["unit_id"]: u for u in records.read_json(gold / "inventory" / "current.json")["units"]}
|
|
2745
|
+
control("golden: each packet's payload is the one dry.json measured",
|
|
2746
|
+
all(r["payload_sha256"] == packet.sha256_bytes(built[r["candidate_id"]][1].encode("utf-8"))
|
|
2747
|
+
for r in dry.get("packets", []) if r["candidate_id"] in built) and built)
|
|
2748
|
+
leaked = sorted({cid for cid, (labels, text) in built.items()
|
|
2749
|
+
for stored in labels.label_of if len(stored) > 6 and stored in text})
|
|
2750
|
+
control("golden: no stored id reaches a packet - every unit, entry, claim, quote, event and session is a label",
|
|
2751
|
+
not leaked, f"{leaked[:3]}")
|
|
2752
|
+
push = next(((labels, text) for labels, text in built.values() if "u-push" in labels.units.values()), None)
|
|
2753
|
+
if push is None:
|
|
2754
|
+
failures.append("golden: no candidate retrieved u-push, the unit the fixture encloses and has mention others")
|
|
2755
|
+
else:
|
|
2756
|
+
labels, text = push
|
|
2757
|
+
_frame, blocks = blocks_of(text)
|
|
2758
|
+
# looked up by label without assuming one: a packet that shows a stored id fails a control, not the suite
|
|
2759
|
+
row = next((r for r in blocks["units"] if labels.units.get(r["unit_id"]) == "u-push"), {})
|
|
2760
|
+
context = {r["context_id"]: r for r in blocks["context"]}
|
|
2761
|
+
control("golden (a1_min): a unit's enclosing line is shown whole in <context> under its label, and the "
|
|
2762
|
+
"file it mentions by its heading and count, its unresolved mention counted",
|
|
2763
|
+
[labels.context.get(x) for x in row.get("context", [])] == ["u-front"]
|
|
2764
|
+
and context.get(row["context"][0], {}).get("block") == "frontmatter"
|
|
2765
|
+
and row.get("mentions") == [{"path": units["u-tests"]["path"], "headings": [units["u-tests"]["heading"]],
|
|
2766
|
+
"units": 1}]
|
|
2767
|
+
and row.get("unresolved_mentions") == 1, f"{row} {context}")
|
|
2768
|
+
control("golden: every unit S5 retrieved is in <units> once, in S5's order, and every entry in "
|
|
2769
|
+
"<ledger_entries> once", [labels.units.get(r["unit_id"]) for r in blocks["units"]]
|
|
2770
|
+
== [r["unit_id"] for r in labels.unit_rows]
|
|
2771
|
+
and [labels.entries.get(r["entry_id"]) for r in blocks["entries"]] == [r["entry_id"] for r in labels.entry_rows])
|
|
2772
|
+
answer = {**fx_answer(units=tuple(labels.units), yes=(), entries=tuple(labels.entries)),
|
|
2773
|
+
"matching_units": []}
|
|
2774
|
+
control("golden: an answer that judges the packet's own units and entries passes answer_problems",
|
|
2775
|
+
not answer_problems(labels.shown(), answer), f"{answer_problems(labels.shown(), answer)[:3]}")
|
|
2776
|
+
shown_quotes, cited_quotes, with_cited = {}, {}, 0
|
|
2777
|
+
for cid, (labels, text) in built.items():
|
|
2778
|
+
_frame, blocks = blocks_of(text)
|
|
2779
|
+
cand = blocks["candidate"][0] if blocks["candidate"] else {}
|
|
2780
|
+
shown_quotes[cid] = ({q["evidence_id"] for c in blocks["claims"] for q in c["quotes"]}
|
|
2781
|
+
| {o.get("evidence_id") for ev in cand.get("events", []) for o in ev.get("origin", [])}
|
|
2782
|
+
| {q["evidence_id"] for q in cand.get("quotes", [])})
|
|
2783
|
+
cited_quotes[cid] = {q for req in (cand.get("admission") or {}).values() for q in req.get("evidence_ids") or []}
|
|
2784
|
+
with_cited += bool(cand.get("quotes"))
|
|
2785
|
+
control("golden: every quote a candidate's admission cites is shown with its text in the packet, one beyond "
|
|
2786
|
+
"its claims and its own events among them", with_cited > 0
|
|
2787
|
+
and all(cited_quotes[c] <= shown_quotes[c] for c in built), f"{with_cited}")
|
|
2788
|
+
beyond = next((labels for labels, _t in built.values() if labels.cited), None)
|
|
2789
|
+
if beyond is not None:
|
|
2790
|
+
said = refusal(lambda: JudgeLabels(beyond.candidate, rows_of[beyond.candidate["candidate_id"]],
|
|
2791
|
+
beyond.unit_store, beyond.entry_store, stage_form.subject(gold), {}))
|
|
2792
|
+
control("control: a cited quote no evidence record holds is RECORD_INTEGRITY", said.startswith(
|
|
2793
|
+
"RECORD_INTEGRITY") and "no evidence record holds" in said, said[:200])
|
|
2794
|
+
mismatch = copy_of("mismatch")
|
|
2795
|
+
with records.run_stage(mismatch, STAGE, INPUTS) as stage:
|
|
2796
|
+
where = mismatch / "checked-candidates.json"
|
|
2797
|
+
held_pop = records.read_json(where)
|
|
2798
|
+
held_pop["candidates"] = held_pop["candidates"][1:]
|
|
2799
|
+
where.chmod(0o600)
|
|
2800
|
+
where.write_text(json.dumps(held_pop), encoding="utf-8")
|
|
2801
|
+
said = refusal(lambda: build(mismatch, stage.declaration, seats_file))
|
|
2802
|
+
stage.record["status"] = "partial"
|
|
2803
|
+
control("control: checks.json and the population naming different candidates is SET_MISMATCH",
|
|
2804
|
+
said.startswith("SET_MISMATCH S6"), said[:200])
|
|
2805
|
+
narrow_seats = fx_seats(root, capacity_a=1000, name="narrow-seats.json")
|
|
2806
|
+
tight = copy_of("tight")
|
|
2807
|
+
with records.run_stage(tight, STAGE, INPUTS) as stage:
|
|
2808
|
+
tight_summary, _p = guarded(lambda: build(tight, stage.declaration, narrow_seats), lambda e: ({"problem": repr(e)}, {}))
|
|
2809
|
+
stage.record["status"] = "partial"
|
|
2810
|
+
control("golden: a seat whose capacity a packet exceeds lists that packet by name (over_capacity)",
|
|
2811
|
+
sorted((tight_summary.get("over_capacity") or {}).get("A", [])) == sorted(built) and built
|
|
2812
|
+
and (tight_summary.get("over_capacity") or {}).get("B") == [], f"{tight_summary.get('over_capacity', tight_summary)}")
|
|
2813
|
+
# F27: a control's packet has a natural one's frame, blocks, rows and fields
|
|
2814
|
+
judged_controls = [e for e in planted["planted"] if "S6" in e["checked_at"] and e["candidate_id"] in built]
|
|
2815
|
+
pairs = []
|
|
2816
|
+
for entry in judged_controls:
|
|
2817
|
+
mine = by_id[entry["candidate_id"]]
|
|
2818
|
+
twin = next((k for k in population["candidates"] if k["candidate_id"] in built and k["candidate_id"] not in
|
|
2819
|
+
{e["candidate_id"] for e in planted["planted"]} and k.get("event_ids") == mine.get("event_ids")), None)
|
|
2820
|
+
if twin is not None:
|
|
2821
|
+
pairs.append((entry["kind"], packet_markers(built[entry["candidate_id"]][1], built[twin["candidate_id"]][1])))
|
|
2822
|
+
control("F27: every judged control's packet has its natural twin's frame, blocks, rows and fields",
|
|
2823
|
+
len(pairs) == len(judged_controls) >= 4 and not any(problems for _k, problems in pairs), f"{pairs}")
|
|
2824
|
+
if built:
|
|
2825
|
+
some = next(iter(built.values()))[1]
|
|
2826
|
+
marked = some.replace('"named": ', '"planted": true, "named": ', 1)
|
|
2827
|
+
control("control: a field planted in one row of a packet is MARKER_FIELD", any(
|
|
2828
|
+
p.startswith("MARKER_FIELD") for p in packet_markers(marked, some)), "")
|
|
2829
|
+
control("control: a line added outside the blocks is FRAME_DIFFERS",
|
|
2830
|
+
packet_markers(some.replace("# Your task", "# Your task (a control)"), some) ==
|
|
2831
|
+
["FRAME_DIFFERS: the text outside the blocks is not the natural packet's"])
|
|
2832
|
+
# a declared scope, through the declaration
|
|
2833
|
+
from runlib import declare
|
|
2834
|
+
scoped = copy_of("scoped", through_s5=False)
|
|
2835
|
+
declare.amend(scoped, [("judge", {"candidate_kinds": {"formed": "all"}})], "judge the formed candidates only (WP-11)",
|
|
2836
|
+
scope=["S5", "S6"])
|
|
2837
|
+
stage_retrieve.run(scoped, "aa" * 8)
|
|
2838
|
+
narrowed = guarded(lambda: run(scoped, dry=True, seats_path=seats_file), lambda e: {"problem": repr(e)})
|
|
2839
|
+
lifecycle = {k["source"] for k in population["candidates"] if k["source"] != "formed"}
|
|
2840
|
+
control("golden: a declared scope judges what it names and reports every source it leaves out by count",
|
|
2841
|
+
set(narrowed.get("population", {}).get("left_out", {})) == lifecycle and lifecycle
|
|
2842
|
+
and all(r["source"] == "formed" for r in narrowed.get("packets", [])), f"{narrowed.get('population', narrowed)}")
|
|
2843
|
+
# what is refused, by name, with nothing written
|
|
2844
|
+
# an inventory as S2 published one before the edges: a golden of its own, S4 run over it
|
|
2845
|
+
plain = stage_retrieve.fx_current([{k: v for k, v in u.items() if k != "edges"} for u in fx_library()])
|
|
2846
|
+
bare = guarded(lambda: stage_retrieve.fx_gold(root / "bare", plain), lambda e: e)
|
|
2847
|
+
said = refusal(lambda: (stage_retrieve.run(bare, "aa" * 8), run(bare, dry=True, seats_path=seats_file))) \
|
|
2848
|
+
if not isinstance(bare, Exception) else repr(bare)
|
|
2849
|
+
control("control: an inventory without per-unit edges is EDGES_ABSENT, and no dry measure is written",
|
|
2850
|
+
said.startswith("EDGES_ABSENT") and not (pathlib.Path(str(bare)) / DRY_RECORD).exists(), said[:200])
|
|
2851
|
+
unrun = copy_of("no-s5", through_s5=False)
|
|
2852
|
+
said = refusal(lambda: run(unrun, dry=True, seats_path=seats_file))
|
|
2853
|
+
control("control: S6 over a run S5 has not run is refused by name (INPUT_INVALID S5)", "INPUT_INVALID S5" in said, said[:200])
|
|
2854
|
+
said = refusal(lambda: run(unrun))
|
|
2855
|
+
control("control: S6 with neither --dry nor a supervisor is JUDGE_UNSUPERVISED, before anything is recorded",
|
|
2856
|
+
said.startswith("JUDGE_UNSUPERVISED") and not records.record_path(unrun, STAGE).exists(), said)
|
|
2857
|
+
|
|
2858
|
+
# ---- the calls (J2a): a golden run of both judges through the golden hosts --------------------------------
|
|
2859
|
+
from runlib import declare
|
|
2860
|
+
called = copy_of("called", through_s5=False)
|
|
2861
|
+
declare.amend(called, [("budget.per_stage.S6", 20_000_000)], "S6's golden budget (WP-11 J2)", scope=["S5", "S6"])
|
|
2862
|
+
stage_retrieve.run(called, "aa" * 8)
|
|
2863
|
+
planner = root / "planner"
|
|
2864
|
+
shutil.copytree(called.parent, planner)
|
|
2865
|
+
replayed = records.fixture_root("replay") / "claude-runner" / "ctl-cfg-claude-md-001" / "host.json"
|
|
2866
|
+
clean_plan, packets = fx_judge_plan(planner / called.name, root / "plan-clean.json")
|
|
2867
|
+
judged_ids = sorted(packets)
|
|
2868
|
+
tainted, unjudged = judged_ids[0], judged_ids[-1]
|
|
2869
|
+
|
|
2870
|
+
def defects(cid, who, row):
|
|
2871
|
+
if cid == tainted and who == "A": # WP-03's planted user CLAUDE.md, loaded beside a schema-valid answer
|
|
2872
|
+
row["context"] = str(replayed)
|
|
2873
|
+
if cid == unjudged and who == "B": # an answer that leaves one unit unjudged, on both attempts
|
|
2874
|
+
row["answer"]["units"] = row["answer"]["units"][1:]
|
|
2875
|
+
defect_plan, _p = fx_judge_plan(planner / called.name, root / "plan-defects.json", defects)
|
|
2876
|
+
first = guarded(lambda: run(called, supervisor(called, root / "cells-1", defect_plan)), lambda e: {"problem": repr(e)})
|
|
2877
|
+
record = guarded(lambda: records.read_json(records.record_path(called, STAGE)), {})
|
|
2878
|
+
rows = {r["candidate_id"]: r for r in first.get("calls", [])}
|
|
2879
|
+
seated = lambda cid, who: (rows.get(cid) or {}).get("seats", {}).get(who, {})
|
|
2880
|
+
control("golden (J2): every judged candidate goes to both judges, each an item of its own, and the calls that "
|
|
2881
|
+
"end other than accepted leave the record partial", set(rows) == set(judged_ids) and len(judged_ids) >= 6
|
|
2882
|
+
and first.get("counts", {}).get("accepted") == 2 * len(judged_ids) - 2 and record.get("status") == "partial",
|
|
2883
|
+
f"{first.get('counts', first)}")
|
|
2884
|
+
taint = seated(tainted, "A")
|
|
2885
|
+
control("golden (J2, done-when 5): a judgment call whose capture shows an undeclared instruction loaded is "
|
|
2886
|
+
"failed, though its answer is schema-valid and the stage's check was never asked",
|
|
2887
|
+
taint.get("outcome") == "failed" and "CONTEXT_UNDECLARED" in taint.get("codes", [])
|
|
2888
|
+
and all(a["stage_check"] is None for a in taint.get("attempts", [])) and taint.get("attempts")
|
|
2889
|
+
and not (called / judgment_rel(item_of(tainted), "A")).exists(), f"{taint}")
|
|
2890
|
+
short = seated(unjudged, "B")
|
|
2891
|
+
control("golden (J2): an answer that leaves a unit unjudged fails the stage's check on both attempts, by name",
|
|
2892
|
+
short.get("outcome") == "failed" and len(short.get("attempts", [])) == 2
|
|
2893
|
+
and all(any(line.startswith("UNIT_UNJUDGED") for line in a["stage_check"] or [])
|
|
2894
|
+
for a in short.get("attempts", [])), f"{short}")
|
|
2895
|
+
dv_first = guarded(lambda: records.read_json(called / DERIVATIONS), {})
|
|
2896
|
+
control("J4a: a candidate a judge's call did not finish for is not derived, and is named",
|
|
2897
|
+
sorted(r["candidate_id"] for r in dv_first.get("not_derived", [])
|
|
2898
|
+
if r["why"] == "a judge's call did not finish") == sorted({tainted, unjudged})
|
|
2899
|
+
and not {tainted, unjudged} & set(dv_first.get("verdicts", {}))
|
|
2900
|
+
and len(dv_first.get("verdicts", {})) == len(judged_ids) - 2, f"{dv_first.get('not_derived')}")
|
|
2901
|
+
made = {d.name for d in (called / "calls").iterdir()} if (called / "calls").is_dir() else set()
|
|
2902
|
+
given_seen, kept_given = {}, globals()["derivation_given"]
|
|
2903
|
+
|
|
2904
|
+
def recording(candidate, *rest):
|
|
2905
|
+
held = kept_given(candidate, *rest)
|
|
2906
|
+
given_seen[candidate["candidate_id"]] = json.loads(json.dumps(held))
|
|
2907
|
+
return held
|
|
2908
|
+
globals()["derivation_given"] = recording # S6's own derivation, its inputs kept as it made them
|
|
2909
|
+
try:
|
|
2910
|
+
second = guarded(lambda: run(called, supervisor(called, root / "cells-2", clean_plan)),
|
|
2911
|
+
lambda e: {"problem": repr(e)})
|
|
2912
|
+
finally:
|
|
2913
|
+
globals()["derivation_given"] = kept_given
|
|
2914
|
+
dv_second = guarded(lambda: records.read_json(called / DERIVATIONS), {})
|
|
2915
|
+
from_disk = {cid: guarded(lambda cid=cid: given_from_run(called, cid), lambda e: {"problem": repr(e)})
|
|
2916
|
+
for cid in given_seen}
|
|
2917
|
+
differs = sorted(cid for cid in given_seen if from_disk[cid] != given_seen[cid])
|
|
2918
|
+
control("K5: S6's derivation and a recomputation from S6's own files on disk get identical inputs for "
|
|
2919
|
+
"every candidate S6 derived", bool(given_seen) and set(given_seen) == set(dv_second.get("verdicts", {}))
|
|
2920
|
+
and not differs, f"{len(given_seen)} derived, differing {differs[:3]}")
|
|
2921
|
+
replayed = sorted(cid for cid in given_seen if guarded(lambda cid=cid: derive.unit_outcome(
|
|
2922
|
+
from_disk[cid], {}, TEST_STATE), {}) != dv_second.get("verdicts", {}).get(cid, {}).get("outcome"))
|
|
2923
|
+
control("K5: and derive.unit_outcome over the input from disk reproduces each stored outcome",
|
|
2924
|
+
bool(given_seen) and not replayed, f"not reproduced {replayed[:3]}")
|
|
2925
|
+
# the golden's two judges answer alike, so a seat read in place of the other would pass the comparison
|
|
2926
|
+
# above: B's file is changed in a copy and must reach B's side of the input, and only B's
|
|
2927
|
+
# the fixture is the whole run, copied under its own name (a call id names its run), not the files the
|
|
2928
|
+
# function under test lists (Codex WP-11 r2 #4); B's edit is registered in the copy's S6 record, since what is
|
|
2929
|
+
# asked here is which file reaches which side, not whether an edit is caught
|
|
2930
|
+
seat_root = root / "k5-seats"
|
|
2931
|
+
some_cid = sorted(given_seen)[0] if given_seen else None
|
|
2932
|
+
seat_marks = {}
|
|
2933
|
+
if some_cid is not None:
|
|
2934
|
+
shutil.copytree(called, seat_root / called.name)
|
|
2935
|
+
seated_run = seat_root / called.name
|
|
2936
|
+
b_rel = judgment_rel(item_of(some_cid), "B")
|
|
2937
|
+
b_held = records.read_json(seated_run / b_rel)
|
|
2938
|
+
name = sorted(b_held["judgment"]["requirements"])[0]
|
|
2939
|
+
b_held["judgment"]["requirements"][name]["mark"] = "uncertain"
|
|
2940
|
+
(seated_run / b_rel).chmod(0o600)
|
|
2941
|
+
(seated_run / b_rel).write_text(json.dumps(b_held), encoding="utf-8")
|
|
2942
|
+
seat_record = records.read_json(records.record_path(seated_run, STAGE))
|
|
2943
|
+
for o in seat_record.get("outputs") or []:
|
|
2944
|
+
if o["artifact"] == b_rel:
|
|
2945
|
+
o["sha256"] = records.sha256_file(seated_run / b_rel)
|
|
2946
|
+
records.record_path(seated_run, STAGE).chmod(0o600)
|
|
2947
|
+
records.record_path(seated_run, STAGE).write_text(json.dumps(seat_record), encoding="utf-8")
|
|
2948
|
+
seated = guarded(lambda: given_from_run(seated_run, some_cid), lambda e: {"problem": repr(e)})
|
|
2949
|
+
seat_marks = {who: ((seated.get("judges") or {}).get(who) or {}).get("requirements", {}).get(name)
|
|
2950
|
+
for who in SEAT_KEYS} if "problem" not in seated else {"problem": seated["problem"][:160]}
|
|
2951
|
+
control("K5: each judge's side of the input is read from that judge's own file",
|
|
2952
|
+
seat_marks.get("B") == "uncertain" and seat_marks.get("A") not in (None, "uncertain"), f"{seat_marks}")
|
|
2953
|
+
# exactly the per-candidate files S6 left for it on disk, enumerated from the directory, and each an output
|
|
2954
|
+
# S6's record holds
|
|
2955
|
+
held_outputs = {o["artifact"] for o in guarded(
|
|
2956
|
+
lambda: records.read_json(records.record_path(called, STAGE)), {}).get("outputs", [])}
|
|
2957
|
+
|
|
2958
|
+
def on_disk(cid):
|
|
2959
|
+
i = item_of(cid)
|
|
2960
|
+
return {str(f.relative_to(called)) for pattern in (f"judgments/{i}/*.json", f"cross_review/{i}.json",
|
|
2961
|
+
f"reconsiderations/{i}/*.json")
|
|
2962
|
+
for f in called.glob(pattern)}
|
|
2963
|
+
listed = {cid: guarded(lambda cid=cid: given_artifacts(called, cid), lambda e: [repr(e)]) for cid in given_seen}
|
|
2964
|
+
control("K5: given_artifacts names exactly the per-candidate files S6 left, both judges' judgments among them, "
|
|
2965
|
+
"each an output S6's record holds",
|
|
2966
|
+
bool(given_seen) and all(sorted(listed[cid]) == sorted(on_disk(cid)) and set(listed[cid]) <= held_outputs
|
|
2967
|
+
and {f"judgments/{item_of(cid)}/{w}.json" for w in "AB"} <= set(listed[cid])
|
|
2968
|
+
for cid in given_seen),
|
|
2969
|
+
f"{[(cid[:12], sorted(listed[cid])[:3]) for cid in given_seen if sorted(listed[cid]) != sorted(on_disk(cid))][:2]}")
|
|
2970
|
+
record = guarded(lambda: records.read_json(records.record_path(called, STAGE)), {})
|
|
2971
|
+
remade = {d.name for d in (called / "calls").iterdir()} - made if (called / "calls").is_dir() else set()
|
|
2972
|
+
control("golden (J2): run again, S6 reuses every accepted attempt and calls only the two items that were not "
|
|
2973
|
+
"accepted; the record is complete", record.get("status") == "complete"
|
|
2974
|
+
and second.get("counts", {}).get("reused") == 2 * len(judged_ids) - 2
|
|
2975
|
+
and second.get("counts", {}).get("judged_by_both") == len(judged_ids)
|
|
2976
|
+
and sorted(n.rsplit("-a", 1)[0].split(f"-{STAGE}-", 1)[1] for n in remade)
|
|
2977
|
+
== sorted([item_of(tainted) + "-A", item_of(unjudged) + "-B"]), f"{second.get('counts', second)} {sorted(remade)}")
|
|
2978
|
+
kept = {(cid, who): guarded(lambda c=cid, w=who: records.read_json(called / judgment_rel(item_of(c), w)), {})
|
|
2979
|
+
for cid in judged_ids for who in ("A", "B")}
|
|
2980
|
+
control("golden (J2, N#1): both judges of a candidate were sent its one payload - the payload hash S6 built, "
|
|
2981
|
+
"equal in both judgments - and every call's packet hash is its own",
|
|
2982
|
+
all(kept[(c, "A")].get("payload_sha256") == kept[(c, "B")].get("payload_sha256")
|
|
2983
|
+
== packet.sha256_bytes(packets[c][1].encode("utf-8")) for c in judged_ids)
|
|
2984
|
+
and len({k.get("packet_sha256") for k in kept.values()}) == len(kept), "")
|
|
2985
|
+
shown_cid = next((c for c in judged_ids if packets[c][0].units and packets[c][0].quotes and packets[c][0].entries),
|
|
2986
|
+
judged_ids[1])
|
|
2987
|
+
labels0 = packets[shown_cid][0]
|
|
2988
|
+
judgment = kept[(shown_cid, "A")].get("judgment", {})
|
|
2989
|
+
control("golden (J2): a judgment is kept in the stores' ids - its units in S5's order by unit id, its quotes "
|
|
2990
|
+
"by evidence id, its ledger relations by entry id",
|
|
2991
|
+
[u["unit_id"] for u in judgment.get("units", [])] == [r["unit_id"] for r in labels0.unit_rows]
|
|
2992
|
+
and [r["entry_id"] for r in judgment.get("ledger_relations", [])] == [r["entry_id"] for r in labels0.entry_rows]
|
|
2993
|
+
and all(q in labels0.quotes.values() for m in judgment.get("matching_units", [])
|
|
2994
|
+
for q in m["following_evidence_ids"]) and judgment.get("matching_units"),
|
|
2995
|
+
f"{[u['unit_id'] for u in judgment.get('units', [])]} {[r['unit_id'] for r in labels0.unit_rows]} "
|
|
2996
|
+
f"{[r['entry_id'] for r in judgment.get('ledger_relations', [])]} {[r['entry_id'] for r in labels0.entry_rows]} "
|
|
2997
|
+
f"{judgment.get('matching_units')} {list(labels0.quotes.values())[:3]}")
|
|
2998
|
+
lines = guarded(lambda: report_lines(second), [])
|
|
2999
|
+
control("golden (J2): the report says what the calls did, in counts and codes",
|
|
3000
|
+
any(l.startswith("calls (calibration tranche): accepted") for l in lines), f"{lines}")
|
|
3001
|
+
control("(i) golden (J2): the report says the compiled text's withheld would-be units the current point holds",
|
|
3002
|
+
any(l.startswith("compiled text at the current point: ") and "would-be units withheld" in l
|
|
3003
|
+
for l in lines) and (second.get("sweeps") or {}).get("withheld") is not None,
|
|
3004
|
+
f"{[l for l in lines if l.startswith('compiled text')]} {(second.get('sweeps') or {}).get('withheld')}")
|
|
3005
|
+
# the receipts, planted on copies of the accepted calls' own
|
|
3006
|
+
held = []
|
|
3007
|
+
for cid in judged_ids[:2]:
|
|
3008
|
+
for who in ("A", "B"):
|
|
3009
|
+
k = kept[(cid, who)]
|
|
3010
|
+
held.append((cid, k.get("seat"), k.get("call_id"),
|
|
3011
|
+
guarded(lambda c=k.get("call_id"): records.read_json(called / "calls" / c / "receipt.json"), {}),
|
|
3012
|
+
packet.sha256_bytes(packets[cid][1].encode("utf-8"))))
|
|
3013
|
+
held = [h for h in held if h[2]]
|
|
3014
|
+
if len(held) < 4: # the calls these controls copy were not all accepted: named, and the copies not made
|
|
3015
|
+
failures.append(f"golden (J2): the receipt controls need four accepted calls, and {len(held)} were")
|
|
3016
|
+
held = [("k", "s", f"c{n}", {}, "") for n in range(4)]
|
|
3017
|
+
control("the accepted calls' receipts pass", not guarded(lambda: stage_receipts(held), ["RAISED"]),
|
|
3018
|
+
f"{guarded(lambda: stage_receipts(held), ['RAISED'])}")
|
|
3019
|
+
stale = [*held[:3], (held[3][0], held[3][1], held[3][2], {**held[3][3], "packet_sha256": held[2][3].get("packet_sha256")},
|
|
3020
|
+
held[3][4])]
|
|
3021
|
+
control("control: two receipts carrying one packet hash is RECEIPT_STALE",
|
|
3022
|
+
any(p.startswith("RECEIPT_STALE") for p in stage_receipts(stale)), f"{stage_receipts(stale)}")
|
|
3023
|
+
moved = [*held[:3], (held[3][0], held[3][1], held[3][2],
|
|
3024
|
+
{**held[3][3], "evidence": {**(held[3][3].get("evidence") or {}), "payload_sha256": "f" * 64}},
|
|
3025
|
+
held[3][4])]
|
|
3026
|
+
control("control: a receipt whose payload hash is not the payload S6 built is PACKET_DIVERGENCE",
|
|
3027
|
+
sum(p.startswith("PACKET_DIVERGENCE") for p in stage_receipts(moved)) == 2, f"{stage_receipts(moved)}")
|
|
3028
|
+
# ---- design §3.2's gate controls (J4b, D5) ---------------------------------------------------------------
|
|
3029
|
+
gated = guarded(lambda: records.read_json(called / GATE_VERDICTS), {})
|
|
3030
|
+
gv = gated.get("gate_verdicts", {})
|
|
3031
|
+
table_gate = {row["kind"]: row["code"] for row in controls.table()["gate"]}
|
|
3032
|
+
control("J4b: every gate control the table declares has a host S6 plants it on, and S6 plants no other",
|
|
3033
|
+
set(GATE_HOSTS) == set(table_gate) and len(table_gate) == 10, f"{sorted(set(GATE_HOSTS) ^ set(table_gate))}")
|
|
3034
|
+
source_g = gated.get("source") or {}
|
|
3035
|
+
control("J4b (D5): the ten gate controls are planted on copies of one accepted Judge A call and one accepted "
|
|
3036
|
+
"Judge B call, each on its own host's copy under judgments/gate-controls/<kind>/",
|
|
3037
|
+
sorted(gv) == sorted(table_gate) and all(
|
|
3038
|
+
v["host"] == GATE_HOSTS[k] and v["planted"]["call_id"] == source_g.get(v["host"])
|
|
3039
|
+
and v["planted"]["at"] == f"{GATE_PLANTS}/{k}/{source_g.get(v['host'])}"
|
|
3040
|
+
and (called / v["planted"]["at"]).is_dir() for k, v in gv.items())
|
|
3041
|
+
and f"-{STAGE}-" in source_g.get("A", "") and "-A-a" in source_g.get("A", "")
|
|
3042
|
+
and "-B-a" in source_g.get("B", ""), f"{source_g}")
|
|
3043
|
+
control("J4b (§3.2): the gate rejects every planted copy by the code the table gives it, and accepts both "
|
|
3044
|
+
"originals as the clean counterparts", gv and all(
|
|
3045
|
+
v["planted"]["ok"] is False and table_gate[k] in v["planted"]["codes"] and v["clean"]["ok"] is True
|
|
3046
|
+
for k, v in gv.items()), f"{[(k, v['planted']['codes']) for k, v in gv.items()]}")
|
|
3047
|
+
control("J4b: a planted call whose receipt is not itself the defect is sealed again, so the gate finds no "
|
|
3048
|
+
"receipt disagreement in it", gv and all(
|
|
3049
|
+
not any(line.startswith("RECORD_INTEGRITY receipt") for line in v["planted"]["failures"])
|
|
3050
|
+
for k, v in gv.items() if k not in GATE_UNSEALED), "")
|
|
3051
|
+
originals_ok = all(guarded(lambda who=who: gate.accept(called / "calls" / source_g[who])["ok"], False)
|
|
3052
|
+
for who in ("A", "B")) if source_g else False
|
|
3053
|
+
control("J4b: planting leaves the original calls as they were", originals_ok)
|
|
3054
|
+
evaluated = guarded(lambda: controls.evaluate({"incomplete": [], "planted": [], "gate": [
|
|
3055
|
+
{"kind": k, "code": c} for k, c in table_gate.items()]}, {}, gv, [], {}), {"problems": ["RAISED"]})
|
|
3056
|
+
control("J4b (D4): controls.evaluate reads S6's gate verdicts and finds every gate control given its verdict",
|
|
3057
|
+
not evaluated["problems"] and len(evaluated.get("gate", [])) == 10
|
|
3058
|
+
and all(g["ok"] for g in evaluated["gate"]), f"{evaluated.get('problems')}")
|
|
3059
|
+
no_pair = root / "no-pair"
|
|
3060
|
+
no_pair.mkdir()
|
|
3061
|
+
alone = guarded(lambda: gate_stage(no_pair, [{"seats": {"A": {"outcome": "accepted"}, "B": {"outcome": "failed"}}}]),
|
|
3062
|
+
{})
|
|
3063
|
+
control("J4b: with no candidate both judges' calls were accepted for, nothing is planted and the verdicts say why",
|
|
3064
|
+
alone.get("gate_verdicts") == {} and alone.get("source") is None and "no candidate" in alone.get("why", ""),
|
|
3065
|
+
f"{alone}")
|
|
3066
|
+
control("J4b: the run summary counts the planted controls the gate rejected",
|
|
3067
|
+
second.get("gate_controls", {}).get("planted") == 10
|
|
3068
|
+
and second.get("gate_controls", {}).get("planted_rejected") == sorted(table_gate)
|
|
3069
|
+
and second.get("gate_controls", {}).get("clean_accepted") is True, f"{second.get('gate_controls')}")
|
|
3070
|
+
unbudgeted = copy_of("unbudgeted")
|
|
3071
|
+
said = refusal(lambda: run(unbudgeted, supervisor(unbudgeted, root / "cells-ub", clean_plan)))
|
|
3072
|
+
control("control: a run that declares no budget.per_stage.S6 is refused BUDGET_UNDECLARED S6 at the first "
|
|
3073
|
+
"reservation, before any S6 call", said.startswith("BUDGET_UNDECLARED S6")
|
|
3074
|
+
and not any(f"-{STAGE}-" in d.name for d in (unbudgeted / "calls").iterdir()), said[:200])
|
|
3075
|
+
dv_called = guarded(lambda: records.read_json(called / DERIVATIONS), {})
|
|
3076
|
+
gap_row = next(r for r in derive.table()["candidate_diagnosis"] if not r.get("lifecycle") and r["if_any_unit"] is None)
|
|
3077
|
+
currents = [v["outcome"]["candidate_diagnosis"]["current"] for v in dv_called.get("verdicts", {}).values()]
|
|
3078
|
+
control("J4a: at an incomplete current point no candidate is a gap - a candidate no unit matches is the gap "
|
|
3079
|
+
"row's incomplete answer", dv_called.get("points", {}).get("current", {}).get("complete") is False
|
|
3080
|
+
and currents and not any(c["diagnosis"] == "gap" for c in currents)
|
|
3081
|
+
and any(c["row"] == gap_row["id"] and c["diagnosis"] == gap_row["incomplete"] for c in currents),
|
|
3082
|
+
f"{collections.Counter((c['diagnosis'], c['row']) for c in currents)}")
|
|
3083
|
+
# refused before anything is sent
|
|
3084
|
+
tight = copy_of("tight-called", through_s5=False)
|
|
3085
|
+
declare.amend(tight, [("budget.per_stage.S6", 20_000_000)], "S6's golden budget (WP-11 J2)", scope=["S5", "S6"])
|
|
3086
|
+
stage_retrieve.run(tight, "aa" * 8)
|
|
3087
|
+
said = refusal(lambda: run(tight, supervisor(tight, root / "cells-3", clean_plan, seats_path=narrow_seats)))
|
|
3088
|
+
control("control: a packet over a judge's capacity is JUDGE_OVER_CAPACITY S6 before any call is reserved",
|
|
3089
|
+
said.startswith("JUDGE_OVER_CAPACITY S6")
|
|
3090
|
+
and not any(f"-{STAGE}-" in d.name for d in (tight / "calls").iterdir()), said[:200])
|
|
3091
|
+
limits_a = second.get("limits", {}).get("A", {})
|
|
3092
|
+
some_call = kept[(judged_ids[0], "A")].get("call_id", "")
|
|
3093
|
+
sent = guarded(lambda: (called / "calls" / some_call / "packet.md").read_bytes(), b"")
|
|
3094
|
+
held_schema_bytes = packet.schema_bytes(schema())
|
|
3095
|
+
control("an accepted attempt's own packet is within Judge A's capacity",
|
|
3096
|
+
bool(sent) and not guarded(lambda: attempt_problems(sent, limits_a, held_schema_bytes, "A"), ["RAISED"]), "")
|
|
3097
|
+
control("control: an attempt's packet past the seat's capacity is JUDGE_OVER_CAPACITY by the attempt's bound",
|
|
3098
|
+
any(p.startswith("JUDGE_OVER_CAPACITY A") for p in guarded(lambda: attempt_problems(
|
|
3099
|
+
sent, {**limits_a, "capacity": 1000}, held_schema_bytes, "A"), [])), "")
|
|
3100
|
+
moved_dir = root / "capacity-moved"
|
|
3101
|
+
if some_call and (called / "calls" / some_call / "call.json").is_file():
|
|
3102
|
+
shutil.copytree(called / "calls" / some_call, moved_dir)
|
|
3103
|
+
call_record = records.read_json(moved_dir / "call.json")
|
|
3104
|
+
call_record["bound"]["context_capacity"] = 999
|
|
3105
|
+
(moved_dir / "call.json").chmod(0o600)
|
|
3106
|
+
(moved_dir / "call.json").write_text(json.dumps(call_record), encoding="utf-8")
|
|
3107
|
+
said = refusal(lambda: check(packets[judged_ids[0]][0], limits_a.get("capacity"))(moved_dir))
|
|
3108
|
+
else: # the call this copies was not accepted: the control says so rather than the suite ending here
|
|
3109
|
+
said = f"no accepted call of Judge A to copy ({some_call!r})"
|
|
3110
|
+
control("control: an attempt whose call record carries another capacity than S6 was admitted against is "
|
|
3111
|
+
"CAPACITY_UNRECORDED", said.startswith("CAPACITY_UNRECORDED"), said[:200])
|
|
3112
|
+
# ---- done-when 4's decidable halves (J2b deferred, D-20261111-c4fa71) -------------------------------------
|
|
3113
|
+
# no cross-run reuse: the same inputs under another run id, an earlier run's judgments and reuse map in it
|
|
3114
|
+
nxt_root = root / "next"
|
|
3115
|
+
shutil.copytree(planner, nxt_root)
|
|
3116
|
+
nxt = nxt_root / f"{called.name}-next"
|
|
3117
|
+
(nxt_root / called.name).rename(nxt)
|
|
3118
|
+
shutil.copytree(called / "judgments", nxt / "judgments")
|
|
3119
|
+
earlier_map = nxt / "judgments" / "reuse.json"
|
|
3120
|
+
earlier_map.write_text(json.dumps({sha256_json([c, w]): judgment_rel(item_of(c), w) for c in judged_ids
|
|
3121
|
+
for w in ("A", "B")}), encoding="utf-8")
|
|
3122
|
+
planted_bytes = earlier_map.read_bytes()
|
|
3123
|
+
fresh = guarded(lambda: run(nxt, supervisor(nxt, root / "cells-5", clean_plan)), lambda e: {"problem": repr(e)})
|
|
3124
|
+
fresh_calls = sorted(d.name for d in (nxt / "calls").iterdir() if d.name.startswith(f"{nxt.name}-{STAGE}-"))
|
|
3125
|
+
control("done-when 4: a new run with the same inputs makes a fresh call for every judgment - an earlier run's "
|
|
3126
|
+
"judgments and reuse map in its directory are ignored, and the map is left as it was",
|
|
3127
|
+
fresh.get("counts", {}).get("reused") == 0 and fresh.get("counts", {}).get("accepted") == 2 * len(judged_ids)
|
|
3128
|
+
and len(fresh_calls) == 2 * len(judged_ids) and earlier_map.read_bytes() == planted_bytes,
|
|
3129
|
+
f"{fresh.get('counts', fresh)} {len(fresh_calls)}")
|
|
3130
|
+
# A's judgment never answers B: every A accepted and no B, then both
|
|
3131
|
+
only_a = copy_of("only-a", through_s5=False)
|
|
3132
|
+
declare.amend(only_a, [("budget.per_stage.S6", 20_000_000), ("judge", {"candidate_kinds": {"formed": "all"}})],
|
|
3133
|
+
"S6's golden budget, the formed candidates only (WP-11 J2)", scope=["S5", "S6"])
|
|
3134
|
+
stage_retrieve.run(only_a, "aa" * 8)
|
|
3135
|
+
a_plan = root / "plan-a-only.json"
|
|
3136
|
+
seat_a = f"SEAT: {fresh.get('seats', {}).get('A')}"
|
|
3137
|
+
a_plan.write_text(json.dumps([r for r in json.loads(pathlib.Path(clean_plan).read_text(encoding="utf-8"))
|
|
3138
|
+
if r["match"][0] == seat_a]), encoding="utf-8")
|
|
3139
|
+
one = guarded(lambda: run(only_a, supervisor(only_a, root / "cells-6", a_plan)), lambda e: {"problem": repr(e)})
|
|
3140
|
+
two = guarded(lambda: run(only_a, supervisor(only_a, root / "cells-7", clean_plan)), lambda e: {"problem": repr(e)})
|
|
3141
|
+
a_rows, b_rows = ([row["seats"].get(w, {}) for row in got.get("calls", [])] for got, w in ((one, "A"), (two, "B")))
|
|
3142
|
+
control("done-when 4: A's accepted judgment never answers B - with every A accepted and no B, the next run calls "
|
|
3143
|
+
"every B anew, and no B considers an attempt of A's",
|
|
3144
|
+
a_rows and all(h.get("outcome") == "accepted" for h in a_rows)
|
|
3145
|
+
and all(h.get("outcome") == "failed" for row in one.get("calls", []) for h in [row["seats"].get("B", {})])
|
|
3146
|
+
and two.get("counts", {}).get("reused") == len(a_rows)
|
|
3147
|
+
and all(h.get("outcome") == "accepted" and not h.get("reused")
|
|
3148
|
+
and all("-B-a" in reason.split()[1] for reason in h.get("not_reused", [])) for h in b_rows),
|
|
3149
|
+
f"{one.get('counts', one)} {two.get('counts', two)}")
|
|
3150
|
+
# ---- the absence sweeps (J3a, done-when 6) --------------------------------------------------------------
|
|
3151
|
+
sw_second = second.get("sweeps") or {}
|
|
3152
|
+
control("done-when 6: at a reference point the absence policy reads as incomplete, no absence claim stands and "
|
|
3153
|
+
"nothing is swept", sw_second.get("complete") is False and sw_second.get("calls") == []
|
|
3154
|
+
and sw_second.get("absent") == [] and "absence unknown" in sw_second.get("why", ""), f"{sw_second}")
|
|
3155
|
+
# the expectation is read from the judgments on disk, not through absent_candidates: a candidate whose every
|
|
3156
|
+
# unit both judges marked situation no and action no is an absence claim whatever the policy
|
|
3157
|
+
claims = sw_second.get("claims") or {}
|
|
3158
|
+
|
|
3159
|
+
def marked_none(cid):
|
|
3160
|
+
held = [guarded(lambda w=w: records.read_json(called / judgment_rel(item_of(cid), w))["judgment"], None)
|
|
3161
|
+
for w in SEAT_KEYS]
|
|
3162
|
+
return all(held) and all(u.get("situation") == "no" and u.get("action") == "no"
|
|
3163
|
+
for h in held for u in h["units"])
|
|
3164
|
+
planted_claims = sorted(c for c in judged_ids if marked_none(c))
|
|
3165
|
+
inventory_layers = {row["layer"]: row["status"] for row in
|
|
3166
|
+
guarded(lambda: records.read_json(called / "inventory" / "current.json"), {}).get("layers") or []}
|
|
3167
|
+
control("J3a (D-20261111-eaa2a8): at an incomplete point the judges' absence claims are still named and "
|
|
3168
|
+
"counted per candidate kind beside the number judged, with the point's state and every layer's "
|
|
3169
|
+
"status, and no sweep is called", bool(planted_claims)
|
|
3170
|
+
and claims.get("candidates") == planted_claims and claims.get("count") == len(planted_claims)
|
|
3171
|
+
and sum(v.get("claims", 0) for v in (claims.get("by_kind") or {}).values()) == len(planted_claims)
|
|
3172
|
+
and claims.get("swept") is False and (claims.get("reference") or {}).get("complete") is False
|
|
3173
|
+
and (claims.get("reference") or {}).get("layers") == inventory_layers and bool(inventory_layers)
|
|
3174
|
+
and sw_second.get("calls") == [] and sw_second.get("absent") == [], f"{claims} {planted_claims}")
|
|
3175
|
+
ub = dry.get("sweep_upper_bound") or {}
|
|
3176
|
+
index = stage_retrieve.UnitIndex(records.read_json(gold / "inventory" / "current.json")["units"])
|
|
3177
|
+
dry_judged = [r["candidate_id"] for r in dry.get("packets", [])]
|
|
3178
|
+
# computed here from the index itself, not through remaining_of, so a revert of it cannot move both sides
|
|
3179
|
+
ub_remaining = {c: sorted(rep for rep in index.copies if index.layer_of[rep] == "catalog"
|
|
3180
|
+
and rep not in {index.rep_of.get(r["unit_id"], r["unit_id"])
|
|
3181
|
+
for r in rows_of[c]["retrieved_units"]}) for c in dry_judged}
|
|
3182
|
+
ub_groups = shard_plan(ub_remaining, SWEEP_DEFAULTS["candidates_per_shard"], SWEEP_DEFAULTS["shard_units"])
|
|
3183
|
+
with_pairs = sum(1 for g in ub_groups for sh in g["shards"] if sh["pairs"])
|
|
3184
|
+
control("dry: the sweep's upper bound is every judged candidate as a gap over the catalog layer less its "
|
|
3185
|
+
"retrieved units, labelled as the bound, in groups, shards, calls, pairs, bytes and tokens at J0's density",
|
|
3186
|
+
ub.get("basis") == UPPER_BOUND_BASIS and ub.get("candidates") == len(dry_judged)
|
|
3187
|
+
and ub.get("groups") == len(ub_groups) == math.ceil(len(dry_judged) / SWEEP_DEFAULTS["candidates_per_shard"])
|
|
3188
|
+
and ub.get("packets") == 2 * with_pairs and ub.get("pairs") == sum(len(v) for v in ub_remaining.values())
|
|
3189
|
+
and all(ub.get("input_tokens_at_j0_density", {}).get(side) == math.ceil(ub["driver_bytes"][side] / J0_DENSITY)
|
|
3190
|
+
for side in ("a", "b")) and ub.get("output_tokens_at_most") == ub.get("packets", 0) * 20_000,
|
|
3191
|
+
f"{ub}")
|
|
3192
|
+
# a golden run whose current reference point is complete, three formed candidates judged with no unit that
|
|
3193
|
+
# matches, so they and the candidates S5 retrieved nothing for are absence claims
|
|
3194
|
+
whole = guarded(lambda: stage_retrieve.fx_gold(root / "whole",
|
|
3195
|
+
stage_retrieve.fx_current(fx_library(wide=70), complete=True)),
|
|
3196
|
+
lambda e: e)
|
|
3197
|
+
if isinstance(whole, Exception):
|
|
3198
|
+
failures.append(f"the complete golden run could not be made: {whole!r}")
|
|
3199
|
+
else:
|
|
3200
|
+
declare.amend(whole, [("budget.per_stage.S6", 20_000_000),
|
|
3201
|
+
("sweeps", {"shard_units": 40, "candidates_per_shard": 3})],
|
|
3202
|
+
"S6's golden budget and small shards (WP-11 J3a)", scope=["S5", "S6"])
|
|
3203
|
+
stage_retrieve.run(whole, "aa" * 8)
|
|
3204
|
+
whole_plan_root = root / "whole-planner"
|
|
3205
|
+
shutil.copytree(whole.parent, whole_plan_root)
|
|
3206
|
+
made_gaps = []
|
|
3207
|
+
|
|
3208
|
+
def no_match(cid, who, row):
|
|
3209
|
+
if cid in made_gaps or (len(made_gaps) < 3 and cid.startswith("k-") and row["answer"]["units"]):
|
|
3210
|
+
if cid not in made_gaps:
|
|
3211
|
+
made_gaps.append(cid)
|
|
3212
|
+
for u in row["answer"]["units"]:
|
|
3213
|
+
u.update(situation="no", action="no", quote="")
|
|
3214
|
+
row["answer"]["matching_units"] = []
|
|
3215
|
+
# done-when 2 (J4a): the next candidate both judges mark `bounded` uncertain, the one after both mark
|
|
3216
|
+
# `consequence` unmet; every other requirement of every candidate both mark met
|
|
3217
|
+
planted_marks = {}
|
|
3218
|
+
|
|
3219
|
+
def plan_edit(cid, who, row):
|
|
3220
|
+
no_match(cid, who, row)
|
|
3221
|
+
if cid not in made_gaps and (cid in planted_marks or len(planted_marks) < 2):
|
|
3222
|
+
mark = planted_marks.setdefault(cid, ("uncertain", "bounded") if not planted_marks
|
|
3223
|
+
else ("unmet", "consequence"))
|
|
3224
|
+
row["answer"]["requirements"][mark[1]] = {"mark": mark[0], "reason": "planted"}
|
|
3225
|
+
whole_plan, whole_packets = fx_judge_plan(whole_plan_root / whole.name, root / "plan-whole.json", plan_edit)
|
|
3226
|
+
# each sweep flags its own unit, so a flag is what either raised, not both (J3b)
|
|
3227
|
+
sweep_rows = [{"match": [f"SEAT: {seat}"], "auto": "sweep", "partial_where": where}
|
|
3228
|
+
for seat, where in (("claude:claude-sonnet-5-5/medium", "glob"),
|
|
3229
|
+
("codex:gpt-6-luna/medium", "Note step 3 of"))]
|
|
3230
|
+
# Judge B's cross-review: every unit judged, a match on the first unit neither sweep flagged (J3b, J3c)
|
|
3231
|
+
sweep_rows.append({"match": ["SEAT: codex:gpt-6-astra/xhigh", "Two checkers then"], "auto": "cross",
|
|
3232
|
+
"flag_first_negative": True})
|
|
3233
|
+
# the reconsiderations (J3c): the first claim's first returned unit both judges now find matching, the
|
|
3234
|
+
# second's only Judge A, every other's none
|
|
3235
|
+
claims_known = sorted(c for c, (labels, _t) in whole_packets.items() if c in made_gaps or not labels.units)
|
|
3236
|
+
recon_of = {n: c for n, c in enumerate(claims_known[:3])}
|
|
3237
|
+
if len(recon_of) == 3:
|
|
3238
|
+
sweep_rows += [{"match": [f"-{STAGE}-{item_of(recon_of[0])}-{RECONSIDER}{who}-a"], "auto": "reconsider",
|
|
3239
|
+
"yes_first": True} for who in ("A", "B")]
|
|
3240
|
+
sweep_rows.append({"match": [f"-{STAGE}-{item_of(recon_of[1])}-{RECONSIDER}A-a"], "auto": "reconsider",
|
|
3241
|
+
"yes_first": True})
|
|
3242
|
+
sweep_rows += [{"match": [f"-{RECONSIDER}{who}-a"], "auto": "reconsider"} for who in ("A", "B")]
|
|
3243
|
+
judge_rows = json.loads(pathlib.Path(whole_plan).read_text(encoding="utf-8"))
|
|
3244
|
+
pathlib.Path(whole_plan).write_text(json.dumps(judge_rows + sweep_rows), encoding="utf-8")
|
|
3245
|
+
# the same run before any S6 call, for the corrective-retry runs below (Codex WP-11 r1 #1)
|
|
3246
|
+
retry_base = root / "retry-base"
|
|
3247
|
+
shutil.copytree(whole.parent, retry_base)
|
|
3248
|
+
defect_sweep_plan = root / "plan-whole-defect.json"
|
|
3249
|
+
defect_sweep_plan.write_text(json.dumps(
|
|
3250
|
+
judge_rows + [{"match": [f"-{STAGE}-sweep-g001-s001-b-a"], "auto": "sweep", "drop_first": True}] + sweep_rows),
|
|
3251
|
+
encoding="utf-8")
|
|
3252
|
+
swept_run = guarded(lambda: run(whole, supervisor(whole, root / "cells-8", defect_sweep_plan)),
|
|
3253
|
+
lambda e: {"problem": repr(e)})
|
|
3254
|
+
sw = swept_run.get("sweeps") or {}
|
|
3255
|
+
first_record = guarded(lambda: records.read_json(records.record_path(whole, STAGE)), {})
|
|
3256
|
+
dropped = next((row["seats"].get("b", {}) for row in sw.get("calls", [])
|
|
3257
|
+
if (row["group"], row["shard"]) == ("g001", "s001")), {})
|
|
3258
|
+
control("J3a: a sweep answer that leaves a listed pair out fails the stage's check on both attempts, by name, "
|
|
3259
|
+
"and leaves the record partial", dropped.get("outcome") == "failed" and len(dropped.get("attempts", [])) == 2
|
|
3260
|
+
and all(any(line.startswith("SWEEP_PAIR_MISSING") for line in a["stage_check"] or [])
|
|
3261
|
+
for a in dropped.get("attempts", [])) and first_record.get("status") == "partial",
|
|
3262
|
+
f"{dropped} {first_record.get('status')}")
|
|
3263
|
+
first_cross = swept_run.get("cross_review") or {}
|
|
3264
|
+
g001 = next((g["candidates"] for g in sw.get("groups", []) if g["group"] == "g001"), [])
|
|
3265
|
+
control("J3b: an absence claim whose group's sweeps did not all finish is not cross-reviewed, and is named",
|
|
3266
|
+
g001 and sorted(r["candidate_id"] for r in first_cross.get("not_reviewed", [])
|
|
3267
|
+
if r["why"] == "a sweep of its group did not finish") == sorted(g001)
|
|
3268
|
+
and not set(g001) & set(first_cross.get("reviewed", [])), f"{first_cross.get('not_reviewed')} {g001}")
|
|
3269
|
+
# the second run: the sweeps whole, and one absence claim's cross-review leaving a unit out
|
|
3270
|
+
cross_defect = root / "plan-whole-cross-defect.json"
|
|
3271
|
+
cross_defect.write_text(json.dumps(judge_rows + [
|
|
3272
|
+
{"match": [f"-{STAGE}-{item_of(claims_known[0])}-X-a"], "auto": "cross", "drop_first": True}] + sweep_rows),
|
|
3273
|
+
encoding="utf-8")
|
|
3274
|
+
swept_run = guarded(lambda: run(whole, supervisor(whole, root / "cells-8b", cross_defect)),
|
|
3275
|
+
lambda e: {"problem": repr(e)})
|
|
3276
|
+
second_record = guarded(lambda: records.read_json(records.record_path(whole, STAGE)), {})
|
|
3277
|
+
short_cross = next((r for r in (swept_run.get("cross_review") or {}).get("calls", [])
|
|
3278
|
+
if r["candidate_id"] == claims_known[0]), {})
|
|
3279
|
+
control("J3b: a cross-review that leaves a unit it was shown unjudged fails the stage's check on both attempts, "
|
|
3280
|
+
"by name, and leaves the record partial", short_cross.get("outcome") == "failed"
|
|
3281
|
+
and len(short_cross.get("attempts", [])) == 2
|
|
3282
|
+
and all(any(line.startswith("CROSS_UNIT_MISSING") for line in a["stage_check"] or [])
|
|
3283
|
+
for a in short_cross.get("attempts", [])) and second_record.get("status") == "partial",
|
|
3284
|
+
f"{short_cross} {second_record.get('status')}")
|
|
3285
|
+
sw = swept_run.get("sweeps") or {}
|
|
3286
|
+
whole_rows = {r["candidate_id"]: r for r in records.read_json(whole / "checks.json")["candidates"]}
|
|
3287
|
+
expected = sorted(c for c, (labels, _t) in whole_packets.items() if c in made_gaps or not labels.units)
|
|
3288
|
+
control("J3a: the absence claims are the judged candidates no unit matches by both judges - the three planted "
|
|
3289
|
+
"and every one S5 retrieved nothing for", sw.get("complete") is True and sw.get("absent") == expected
|
|
3290
|
+
and len(made_gaps) == 3, f"{sw.get('absent')} {expected}")
|
|
3291
|
+
whole_index = stage_retrieve.UnitIndex(records.read_json(whole / "inventory" / "current.json")["units"])
|
|
3292
|
+
inventory_hash = packet.sha256_bytes((whole / "inventory" / "current.json").read_bytes())
|
|
3293
|
+
want = {c: sorted(rep for rep in whole_index.copies
|
|
3294
|
+
if rep not in {whole_index.rep_of.get(r["unit_id"], r["unit_id"])
|
|
3295
|
+
for r in whole_rows[c]["retrieved_units"]}) for c in expected}
|
|
3296
|
+
kept_sw = {}
|
|
3297
|
+
for g in sw.get("groups", []):
|
|
3298
|
+
for sh in g["shards"]:
|
|
3299
|
+
for side in ("a", "b"):
|
|
3300
|
+
rel = sweep_rel(g["group"], sh["shard"], side)
|
|
3301
|
+
if (whole / rel).exists():
|
|
3302
|
+
kept_sw[(g["group"], sh["shard"], side)] = guarded(lambda r=rel: kept_sweep(whole, r, inventory_hash), {})
|
|
3303
|
+
judged_pairs = {side: collections.Counter((p["candidate_id"], p["unit_id"]) for (g, sh, sd), k in kept_sw.items()
|
|
3304
|
+
if sd == side for p in k.get("pairs", [])) for side in ("a", "b")}
|
|
3305
|
+
control("J3a (done-when 6): each sweep judged every absence claim's remaining units exactly once - every unit "
|
|
3306
|
+
"S5 indexes less the ones retrieved for it - and nothing else",
|
|
3307
|
+
all(set(judged_pairs[side]) == {(c, u) for c, us in want.items() for u in us}
|
|
3308
|
+
and all(n == 1 for n in judged_pairs[side].values()) for side in ("a", "b")) and want,
|
|
3309
|
+
f"{sum(judged_pairs['a'].values())} {sum(len(v) for v in want.values())}")
|
|
3310
|
+
shards_made = [(g, sh) for (g, sh, sd) in kept_sw if sd == "a"]
|
|
3311
|
+
control("J3a (N#1, done-when 6): both sweeps of a shard were sent one payload bound to the inventory's hash, "
|
|
3312
|
+
"each call its own packet", shards_made and all(
|
|
3313
|
+
kept_sw[(g, sh, "a")].get("payload_sha256") == kept_sw.get((g, sh, "b"), {}).get("payload_sha256")
|
|
3314
|
+
and kept_sw[(g, sh, "a")].get("inventory_sha256") == inventory_hash for g, sh in shards_made)
|
|
3315
|
+
and len({k.get("packet_sha256") for k in kept_sw.values()}) == len(kept_sw)
|
|
3316
|
+
and sw.get("counts", {}).get("accepted") == 2 * len(shards_made), f"{sw.get('counts')}")
|
|
3317
|
+
# the third run: Judge B's reconsideration of the first claim answers the candidate's requirements too
|
|
3318
|
+
recon_defect = root / "plan-whole-recon-defect.json"
|
|
3319
|
+
recon_defect.write_text(json.dumps(judge_rows + [
|
|
3320
|
+
{"match": [f"-{STAGE}-{item_of(claims_known[0])}-{RECONSIDER}B-a"], "auto": "reconsider",
|
|
3321
|
+
"yes_first": True, "extra": {"requirements": fx_answer()["requirements"]}}] + sweep_rows), encoding="utf-8")
|
|
3322
|
+
again_sw = guarded(lambda: run(whole, supervisor(whole, root / "cells-9", recon_defect)),
|
|
3323
|
+
lambda e: {"problem": repr(e)})
|
|
3324
|
+
third_record = guarded(lambda: records.read_json(records.record_path(whole, STAGE)), {})
|
|
3325
|
+
third_dv = guarded(lambda: records.read_json(whole / DERIVATIONS), {})
|
|
3326
|
+
control("J4a: an absence claim whose reconsideration did not finish is not derived, and is named",
|
|
3327
|
+
[r["candidate_id"] for r in third_dv.get("not_derived", [])] == [claims_known[0]]
|
|
3328
|
+
and claims_known[0] not in third_dv.get("verdicts", {}) and len(third_dv.get("verdicts", {})) > 1,
|
|
3329
|
+
f"{third_dv.get('not_derived')}")
|
|
3330
|
+
third_again = again_sw.get("reconsiderations") or {}
|
|
3331
|
+
third_calls = {r["candidate_id"]: r for r in third_again.get("calls", [])}
|
|
3332
|
+
c0_b = third_calls.get(claims_known[0], {}).get("seats", {}).get("B", {})
|
|
3333
|
+
control("J3c: a reconsideration Judge B answers with the candidate's requirements is refused by the schema on "
|
|
3334
|
+
"both attempts, the claim is named RECONSIDERATION_MISSING and not diagnosed, and the record is "
|
|
3335
|
+
"partial while every other call is accepted",
|
|
3336
|
+
c0_b.get("outcome") == "failed" and len(c0_b.get("attempts", [])) == 2
|
|
3337
|
+
and "SCHEMA_INVALID" in " ".join(map(str, c0_b.get("codes", [])))
|
|
3338
|
+
and any(m.startswith(f"RECONSIDERATION_MISSING {claims_known[0]} B") for m in third_again.get("missing", []))
|
|
3339
|
+
and [r["candidate_id"] for r in third_again.get("not_reconsidered", [])] == [claims_known[0]]
|
|
3340
|
+
and claims_known[0] not in [r["candidate_id"] for r in third_again.get("reconsidered", [])]
|
|
3341
|
+
and third_record.get("status") == "partial"
|
|
3342
|
+
and not (again_sw.get("cross_review") or {}).get("not_reviewed")
|
|
3343
|
+
and all(h["outcome"] == "accepted" for c, r in third_calls.items() for w, h in r["seats"].items()
|
|
3344
|
+
if (c, w) != (claims_known[0], "B")),
|
|
3345
|
+
f"{c0_b.get('outcome')} {third_again.get('missing')} {third_record.get('status')}")
|
|
3346
|
+
fourth = guarded(lambda: run(whole, supervisor(whole, root / "cells-10", whole_plan)), lambda e: {"problem": repr(e)})
|
|
3347
|
+
record = guarded(lambda: records.read_json(records.record_path(whole, STAGE)), {})
|
|
3348
|
+
control("J3a: run again after the defect, only the failed sweep is called anew; run once more, every sweep is "
|
|
3349
|
+
"answered by its accepted attempt and the record is complete",
|
|
3350
|
+
record.get("status") == "complete" and sw.get("counts", {}).get("reused") == 2 * len(shards_made) - 1
|
|
3351
|
+
and (again_sw.get("sweeps") or {}).get("counts", {}).get("reused") == 2 * len(shards_made),
|
|
3352
|
+
f"{sw.get('counts')} {(again_sw.get('sweeps') or {}).get('counts', again_sw)} {record.get('status')}")
|
|
3353
|
+
fourth_calls = {r["candidate_id"]: r for r in (fourth.get("reconsiderations") or {}).get("calls", [])}
|
|
3354
|
+
control("J3c: run once more, only the unanswered reconsideration is called anew and accepted; every other is "
|
|
3355
|
+
"answered by its accepted attempt",
|
|
3356
|
+
fourth_calls.get(claims_known[0], {}).get("seats", {}).get("B", {}).get("outcome") == "accepted"
|
|
3357
|
+
and not fourth_calls.get(claims_known[0], {}).get("seats", {}).get("B", {}).get("reused")
|
|
3358
|
+
and all(h.get("reused") for c, r in fourth_calls.items() for w, h in r["seats"].items()
|
|
3359
|
+
if (c, w) != (claims_known[0], "B")) and len(fourth_calls) >= 3,
|
|
3360
|
+
f"{[(c[:12], {w: (h.get('outcome'), h.get('reused')) for w, h in r['seats'].items()}) for c, r in fourth_calls.items()]}")
|
|
3361
|
+
again_cross = {r["candidate_id"]: r for r in (again_sw.get("cross_review") or {}).get("calls", [])}
|
|
3362
|
+
control("J3b: run once more, only the failed cross-review is called anew and accepted; every other is answered "
|
|
3363
|
+
"by its accepted attempt", again_cross.get(claims_known[0], {}).get("outcome") == "accepted"
|
|
3364
|
+
and not again_cross.get(claims_known[0], {}).get("reused")
|
|
3365
|
+
and all(r.get("reused") for c, r in again_cross.items() if c != claims_known[0]) and len(again_cross) > 1,
|
|
3366
|
+
f"{[(c[:12], r.get('outcome'), r.get('reused')) for c, r in again_cross.items()]}")
|
|
3367
|
+
# Codex WP-11 r1 #1: in each of the four call kinds one attempt fails its check and its one corrective retry,
|
|
3368
|
+
# sent with the gate's correction, is accepted; the run completes, and a run after it answers every call
|
|
3369
|
+
# from those attempts. The first attempts are planted by call id, so the retries meet the ordinary rows.
|
|
3370
|
+
retried = retry_base / whole.name
|
|
3371
|
+
judged_one = next((c for c in sorted(whole_packets) if c not in made_gaps and whole_packets[c][0].units), None)
|
|
3372
|
+
seat_a = f"SEAT: {fresh.get('seats', {}).get('A')}"
|
|
3373
|
+
normal = next((r for r in judge_rows if judged_one and r["match"] == [seat_a, whole_packets[judged_one][1]]), None)
|
|
3374
|
+
planted_first = {
|
|
3375
|
+
"judge": f"-{STAGE}-{item_of(judged_one or '')}-A-a1",
|
|
3376
|
+
"sweep": f"-{STAGE}-sweep-g001-s001-b-a1",
|
|
3377
|
+
"cross": f"-{STAGE}-{item_of(claims_known[1] if len(claims_known) > 1 else '')}-X-a1",
|
|
3378
|
+
"reconsider": f"-{STAGE}-{item_of(recon_of.get(0, ''))}-{RECONSIDER}A-a1"}
|
|
3379
|
+
retry_rows = ([{"match": [planted_first["judge"]], "answer": {**normal["answer"],
|
|
3380
|
+
"units": normal["answer"]["units"][1:]}}]
|
|
3381
|
+
if normal else []) + [
|
|
3382
|
+
{"match": [planted_first["sweep"]], "auto": "sweep", "drop_first": True},
|
|
3383
|
+
{"match": [planted_first["cross"]], "auto": "cross", "drop_first": True},
|
|
3384
|
+
{"match": [planted_first["reconsider"]], "auto": "reconsider", "yes_first": True,
|
|
3385
|
+
"extra": {"requirements": fx_answer()["requirements"]}}]
|
|
3386
|
+
retry_plan = root / "plan-whole-retry.json"
|
|
3387
|
+
retry_plan.write_text(json.dumps(retry_rows + judge_rows + sweep_rows), encoding="utf-8")
|
|
3388
|
+
fifth = guarded(lambda: run(retried, supervisor(retried, root / "cells-11", retry_plan)),
|
|
3389
|
+
lambda e: {"problem": repr(e)})
|
|
3390
|
+
fifth_record = guarded(lambda: records.read_json(records.record_path(retried, STAGE)), {})
|
|
3391
|
+
attempts_of = {kind: sorted(d.name for d in (retried / "calls").iterdir()
|
|
3392
|
+
if (retried / "calls").is_dir() and d.name.endswith(frag[:-1] + "2")
|
|
3393
|
+
and (retried / "calls" / d.name / "receipt.json").is_file())
|
|
3394
|
+
for kind, frag in planted_first.items()}
|
|
3395
|
+
control("Codex WP-11 r1 #1: an attempt that fails its check in each of the four call kinds is retried once "
|
|
3396
|
+
"with the gate's correction, the retry is accepted and its receipt passes N#1, and the run completes",
|
|
3397
|
+
normal is not None and len(recon_of) == 3 and "problem" not in fifth
|
|
3398
|
+
and fifth_record.get("status") == "complete" and all(len(v) == 1 for v in attempts_of.values()),
|
|
3399
|
+
f"{str(fifth.get('problem'))[:300]} {fifth_record.get('status')} {attempts_of}")
|
|
3400
|
+
retry_dir = retried / "calls" / attempts_of["judge"][0] if attempts_of.get("judge") else None
|
|
3401
|
+
text_one = whole_packets[judged_one][1] if judged_one else ""
|
|
3402
|
+
due = guarded(lambda: corrected_sha256(retry_dir, text_one), "RAISED") if retry_dir else None
|
|
3403
|
+
receipt_one = guarded(lambda: records.read_json(retry_dir / "receipt.json"), {}) if retry_dir else {}
|
|
3404
|
+
control("Codex WP-11 r1 #1: a retry's due hash is its receipt's only when what was sent is the payload S6 "
|
|
3405
|
+
"built and the gate's correction; another payload, or the first attempt, is held to S6's own hash",
|
|
3406
|
+
due is not None and due == (receipt_one.get("evidence") or {}).get("payload_sha256")
|
|
3407
|
+
and guarded(lambda: corrected_sha256(retry_dir, text_one.replace("\n", " \n", 1)), "RAISED") is None
|
|
3408
|
+
and guarded(lambda: corrected_sha256(pathlib.Path(str(retry_dir)[:-1] + "1"), text_one), "RAISED")
|
|
3409
|
+
is None, f"{due} {(receipt_one.get('evidence') or {}).get('payload_sha256')}")
|
|
3410
|
+
# Codex WP-11 r2 #1, in each of the four call kinds: a retry's due hash is its receipt's only when the attempt
|
|
3411
|
+
# was sent the first attempt's payload, a newline and the exact correction the gate rebuilds from that first
|
|
3412
|
+
# attempt's own records. Each tampering is made on a copy of the item's two call directories; an untouched
|
|
3413
|
+
# copy is accepted, so a refusal is the tampering's and not the copy's.
|
|
3414
|
+
def tampered(kind, edit):
|
|
3415
|
+
second_name = (attempts_of.get(kind) or [""])[0]
|
|
3416
|
+
first_name = second_name[:-1] + "1"
|
|
3417
|
+
where = root / "retry-tamper" / f"{kind}-{edit}"
|
|
3418
|
+
for name in (first_name, second_name):
|
|
3419
|
+
if (retried / "calls" / name).is_dir() and not (where / name).exists():
|
|
3420
|
+
shutil.copytree(retried / "calls" / name, where / name)
|
|
3421
|
+
first_dir, second_dir = where / first_name, where / second_name
|
|
3422
|
+
base = guarded(lambda: packet.split((first_dir / "packet.md").read_bytes())[1].decode("utf-8"), "")
|
|
3423
|
+
correction = guarded(lambda: due_correction(second_dir), None) or ""
|
|
3424
|
+
|
|
3425
|
+
def resend(target, payload):
|
|
3426
|
+
held_packet = (target / "packet.md").read_bytes()
|
|
3427
|
+
envelope = held_packet[:held_packet.index(("\n" + packet.PAYLOAD_MARKER + "\n").encode("utf-8"))]
|
|
3428
|
+
(target / "packet.md").chmod(0o600)
|
|
3429
|
+
(target / "packet.md").write_bytes(envelope + ("\n" + packet.PAYLOAD_MARKER + "\n" + payload)
|
|
3430
|
+
.encode("utf-8"))
|
|
3431
|
+
other = next((t for c, (_l, t) in sorted(whole_packets.items()) if t != base), "")
|
|
3432
|
+
try:
|
|
3433
|
+
if edit == "invented":
|
|
3434
|
+
resend(second_dir, base + "\n" + gate.correction({"failures": ["INVENTED a diagnostic"]}))
|
|
3435
|
+
elif edit == "double":
|
|
3436
|
+
resend(second_dir, base + "\n" + correction + "\n" + correction)
|
|
3437
|
+
elif edit == "first":
|
|
3438
|
+
resend(first_dir, base + "\n" + correction)
|
|
3439
|
+
return guarded(lambda: corrected_sha256(first_dir, base), "RAISED")
|
|
3440
|
+
elif edit == "wrong-predecessor":
|
|
3441
|
+
# the predecessor accepted after all (its stage check had nothing to say), or, where the gate
|
|
3442
|
+
# refused it, sent something other than the payload alone
|
|
3443
|
+
if (first_dir / gate.STAGE_CHECK).is_file():
|
|
3444
|
+
(first_dir / gate.STAGE_CHECK).chmod(0o600)
|
|
3445
|
+
(first_dir / gate.STAGE_CHECK).write_text(json.dumps({"failures": []}), encoding="utf-8")
|
|
3446
|
+
else:
|
|
3447
|
+
resend(first_dir, base + " ")
|
|
3448
|
+
elif edit == "other-payload":
|
|
3449
|
+
return guarded(lambda: corrected_sha256(second_dir, other), "RAISED")
|
|
3450
|
+
except (OSError, ValueError) as exc:
|
|
3451
|
+
return f"RAISED {exc!r}"
|
|
3452
|
+
return guarded(lambda: corrected_sha256(second_dir, base), "RAISED")
|
|
3453
|
+
receipt_hash = {kind: (guarded(lambda kind=kind: records.read_json(
|
|
3454
|
+
retried / "calls" / attempts_of[kind][0] / "receipt.json"), {}).get("evidence") or {}).get("payload_sha256")
|
|
3455
|
+
for kind in planted_first if attempts_of.get(kind)}
|
|
3456
|
+
kept = {kind: tampered(kind, "untouched") for kind in planted_first}
|
|
3457
|
+
control("Codex WP-11 r2 #1: in each call kind, the retried attempt's due hash, rebuilt from its first attempt's "
|
|
3458
|
+
"records, is its receipt's", len(receipt_hash) == 4
|
|
3459
|
+
and all(kept[k] is not None and kept[k] == receipt_hash.get(k) for k in planted_first),
|
|
3460
|
+
f"{kept} {receipt_hash}")
|
|
3461
|
+
refused_kinds = {(kind, edit): tampered(kind, edit) for kind in planted_first
|
|
3462
|
+
for edit in ("invented", "double", "first", "wrong-predecessor", "other-payload")}
|
|
3463
|
+
control("Codex WP-11 r2 #1: in each call kind, an invented diagnostic, a doubled correction, a correction on "
|
|
3464
|
+
"a first attempt, a wrong predecessor, and another candidate's payload get no due hash",
|
|
3465
|
+
len(refused_kinds) == 20 and all(v is None for v in refused_kinds.values()),
|
|
3466
|
+
f"{[k for k, v in refused_kinds.items() if v is not None]}")
|
|
3467
|
+
# Codex WP-11 r1 #2 and r2 #2: S10's reader takes S6's files only as S6's stage record registered them, and
|
|
3468
|
+
# holds each to the call S6 accepted; each case on its own copy of the run after its last invocation
|
|
3469
|
+
c0 = claims_known[0] if claims_known else ""
|
|
3470
|
+
other = next((c for c in sorted(whole_packets) if c not in claims_known), "")
|
|
3471
|
+
|
|
3472
|
+
def stale_case(name, mutate=None):
|
|
3473
|
+
here = root / "stale" / name
|
|
3474
|
+
shutil.copytree(whole.parent, here)
|
|
3475
|
+
run_here = here / whole.name
|
|
3476
|
+
|
|
3477
|
+
def rewrite(rel, change):
|
|
3478
|
+
path = run_here / rel
|
|
3479
|
+
held = records.read_json(path)
|
|
3480
|
+
path.chmod(0o600)
|
|
3481
|
+
path.write_text(json.dumps(change(held)), encoding="utf-8")
|
|
3482
|
+
|
|
3483
|
+
def reregister(*rels): # S6's stage record made to agree with the files as they now are
|
|
3484
|
+
rec_path = records.record_path(run_here, STAGE)
|
|
3485
|
+
rec = records.read_json(rec_path)
|
|
3486
|
+
for o in rec.get("outputs") or []:
|
|
3487
|
+
if o["artifact"] in rels:
|
|
3488
|
+
o["sha256"] = records.sha256_file(run_here / o["artifact"])
|
|
3489
|
+
rec_path.chmod(0o600)
|
|
3490
|
+
rec_path.write_text(json.dumps(rec), encoding="utf-8")
|
|
3491
|
+
try:
|
|
3492
|
+
if mutate is not None:
|
|
3493
|
+
mutate(run_here, rewrite, reregister)
|
|
3494
|
+
except (OSError, KeyError, ValueError, Refused) as exc:
|
|
3495
|
+
return f"RAISED {exc!r}", run_here
|
|
3496
|
+
return refusal(lambda: given_from_run(run_here, c0 if name.startswith("r-") else other)) or \
|
|
3497
|
+
guarded(lambda: derive.unit_outcome(given_from_run(run_here, c0 if name.startswith("r-") else other),
|
|
3498
|
+
{}, TEST_STATE)["candidate_diagnosis"]["current"]["diagnosis"],
|
|
3499
|
+
"RAISED"), run_here
|
|
3500
|
+
rel_b, rel_a = reconsideration_rel(item_of(c0), "B"), judgment_rel(item_of(other), "A")
|
|
3501
|
+
|
|
3502
|
+
def shrink(run_here, rewrite, reregister=None):
|
|
3503
|
+
def change(held):
|
|
3504
|
+
for r in (held.get("reconsiderations") or {}).get("reconsidered") or []:
|
|
3505
|
+
if r["candidate_id"] == c0:
|
|
3506
|
+
r["returned"] = 0
|
|
3507
|
+
return held
|
|
3508
|
+
rewrite(SUMMARY, change)
|
|
3509
|
+
if reregister:
|
|
3510
|
+
reregister(SUMMARY)
|
|
3511
|
+
|
|
3512
|
+
def foreign_named(run_here, rewrite, reregister):
|
|
3513
|
+
rewrite(rel_b, lambda held: {**held, "call_id": "another-run-S6-x-a1"})
|
|
3514
|
+
|
|
3515
|
+
def change(held):
|
|
3516
|
+
for r in (held.get("reconsiderations") or {}).get("calls") or []:
|
|
3517
|
+
if r["candidate_id"] == c0:
|
|
3518
|
+
r["seats"]["B"]["call_id"] = "another-run-S6-x-a1"
|
|
3519
|
+
return held
|
|
3520
|
+
rewrite(SUMMARY, change)
|
|
3521
|
+
reregister(rel_b, SUMMARY)
|
|
3522
|
+
|
|
3523
|
+
def copied_from(run_here, rewrite, reregister):
|
|
3524
|
+
held = records.read_json(run_here / judgment_rel(item_of(other), "B"))
|
|
3525
|
+
rewrite(rel_b, lambda _old: {**held, "call_id": records.read_json(run_here / rel_b)["call_id"]})
|
|
3526
|
+
reregister(rel_b)
|
|
3527
|
+
said = {name: stale_case(name, mutate)[0] for name, mutate in (
|
|
3528
|
+
("r-kept", None),
|
|
3529
|
+
("r-summary-edited", lambda r, w, g: shrink(r, w)),
|
|
3530
|
+
("r-summary-agrees", lambda r, w, g: shrink(r, w, g)),
|
|
3531
|
+
("r-summary-copied", lambda r, w, g: (shutil.copyfile(called / SUMMARY, r / SUMMARY), None)),
|
|
3532
|
+
("r-seat", lambda r, w, g: (w(rel_b, lambda h: {**h, "seat": "codex:another/seat"}), g(rel_b))),
|
|
3533
|
+
("r-candidate", copied_from),
|
|
3534
|
+
("r-foreign-named", foreign_named),
|
|
3535
|
+
("j-seat", lambda r, w, g: (w(rel_a, lambda h: {**h, "seat": "claude:another/seat"}), g(rel_a))),
|
|
3536
|
+
("j-edited", lambda r, w, g: w(rel_a, lambda h: {**h, "call_id": "another-run-S6-y-a1"})))}
|
|
3537
|
+
control("Codex WP-11 r2 #2: S10's reader derives a reconsidered claim from S6's files as its stage record "
|
|
3538
|
+
"registered them: covered", said["r-kept"] == "covered", f"{said['r-kept']}")
|
|
3539
|
+
control("Codex WP-11 r2 #2: a summary edited after S6 wrote it is OUTPUT_UNRECORDED",
|
|
3540
|
+
str(said["r-summary-edited"]).startswith(f"OUTPUT_UNRECORDED S6 {SUMMARY}"), f"{said['r-summary-edited']}")
|
|
3541
|
+
control("Codex WP-11 r2 #2: a summary made to agree with the stage record, saying nothing was returned, is "
|
|
3542
|
+
"RECONSIDERATION_STALE against the cross-review S6 registered",
|
|
3543
|
+
str(said["r-summary-agrees"]).startswith(f"RECONSIDERATION_STALE {c0}: its cross-review returned"),
|
|
3544
|
+
f"{said['r-summary-agrees']}")
|
|
3545
|
+
control("Codex WP-11 r2 #2: another run's summary copied in place of S6's is OUTPUT_UNRECORDED",
|
|
3546
|
+
str(said["r-summary-copied"]).startswith(f"OUTPUT_UNRECORDED S6 {SUMMARY}"),
|
|
3547
|
+
f"{said['r-summary-copied']}")
|
|
3548
|
+
i0, i1 = item_of(c0), item_of(other)
|
|
3549
|
+
exact = {c: guarded(lambda c=c: sorted(given_artifacts(whole, c)), lambda e: [repr(e)]) for c in (c0, other)}
|
|
3550
|
+
control("Codex WP-11 r2 #4: given_artifacts names exactly a reconsidered claim's two judgments, its "
|
|
3551
|
+
"cross-review and its two reconsiderations, and exactly the two judgments of a candidate that was "
|
|
3552
|
+
"not a claim", bool(c0) and bool(other) and exact == {
|
|
3553
|
+
c0: sorted([f"judgments/{i0}/A.json", f"judgments/{i0}/B.json", f"cross_review/{i0}.json",
|
|
3554
|
+
f"reconsiderations/{i0}/A.json", f"reconsiderations/{i0}/B.json"]),
|
|
3555
|
+
other: sorted([f"judgments/{i1}/A.json", f"judgments/{i1}/B.json"])}, f"{exact}")
|
|
3556
|
+
control("Codex WP-11 r2 #2: same call id, wrong seat: RECONSIDERATION_STALE naming the seat",
|
|
3557
|
+
f"RECONSIDERATION_STALE {c0} B: its seat" in str(said["r-seat"]), f"{said['r-seat']}")
|
|
3558
|
+
control("Codex WP-11 r2 #2: same call id, another candidate's reconsideration: RECONSIDERATION_STALE "
|
|
3559
|
+
"naming the candidate", f"RECONSIDERATION_STALE {c0} B: its candidate_id" in str(said["r-candidate"]),
|
|
3560
|
+
f"{said['r-candidate']}")
|
|
3561
|
+
control("Codex WP-11 r2 #2: a foreign call id the summary and the stage record were both made to name is "
|
|
3562
|
+
"not one of this run's calls", f"RECONSIDERATION_STALE {c0} B: the call 'another-run-S6-x-a1' is not"
|
|
3563
|
+
in str(said["r-foreign-named"]), f"{said['r-foreign-named']}")
|
|
3564
|
+
control("Codex WP-11 r2 #2: a first judgment with the same call id and another seat is JUDGMENT_STALE, and "
|
|
3565
|
+
"one edited without its record is OUTPUT_UNRECORDED",
|
|
3566
|
+
f"JUDGMENT_STALE {other} A: its seat" in str(said["j-seat"])
|
|
3567
|
+
and str(said["j-edited"]).startswith(f"OUTPUT_UNRECORDED S6 {rel_a}"),
|
|
3568
|
+
f"{said['j-seat']} {said['j-edited']}")
|
|
3569
|
+
# the live derivation reads the reconsiderations it accepted, held in memory, and never their files
|
|
3570
|
+
live_root = root / "stale" / "live"
|
|
3571
|
+
shutil.copytree(whole.parent, live_root)
|
|
3572
|
+
live = live_root / whole.name
|
|
3573
|
+
summary_l = guarded(lambda: records.read_json(live / SUMMARY), {})
|
|
3574
|
+
judgments_l = {c: {w: guarded(lambda c=c, w=w: records.read_json(live / judgment_rel(item_of(c), w))
|
|
3575
|
+
["judgment"], {}) for w in SEAT_KEYS} for c in sorted(whole_packets)}
|
|
3576
|
+
accepted_l = {c0: {w: guarded(lambda w=w: records.read_json(live / reconsideration_rel(item_of(c0), w))
|
|
3577
|
+
["judgment"], {}) for w in SEAT_KEYS}}
|
|
3578
|
+
for w in SEAT_KEYS:
|
|
3579
|
+
(live / reconsideration_rel(item_of(c0), w)).unlink(missing_ok=True)
|
|
3580
|
+
swept_l, again_l = summary_l.get("sweeps") or {}, summary_l.get("reconsiderations") or {}
|
|
3581
|
+
|
|
3582
|
+
def live_current(held):
|
|
3583
|
+
out = guarded(lambda: derive_stage(live, summary_l, judgments_l, swept_l, again_l, held), {})
|
|
3584
|
+
return (((out.get("verdicts") or {}).get(c0) or {}).get("outcome") or {}).get(
|
|
3585
|
+
"candidate_diagnosis", {}).get("current", {}).get("diagnosis")
|
|
3586
|
+
control("Codex WP-11 r2 #2: the live derivation reads the reconsiderations it accepted, not their files: with "
|
|
3587
|
+
"the files gone it derives covered from what it holds, and gap when it holds none",
|
|
3588
|
+
(live_current(accepted_l), live_current({})) == ("covered", "gap"),
|
|
3589
|
+
f"{live_current(accepted_l)} {live_current({})}")
|
|
3590
|
+
# Codex WP-11 r1 #3: the sweeps and Judge B's cross-review are held to their seats' capacity, every packet
|
|
3591
|
+
# before the first call of its kind and each attempt as it is sent; a seat nobody measured is not bounded
|
|
3592
|
+
# (D13). Driven with a supervisor that records what it is asked, over a copy of the swept run.
|
|
3593
|
+
cap_root = root / "cap-copy"
|
|
3594
|
+
shutil.copytree(whole.parent, cap_root)
|
|
3595
|
+
capped = cap_root / whole.name
|
|
3596
|
+
judged_w = sorted(whole_packets)
|
|
3597
|
+
judgments_w = {c: {w: guarded(lambda c=c, w=w: records.read_json(capped / judgment_rel(item_of(c), w))
|
|
3598
|
+
["judgment"], {}) for w in SEAT_KEYS} for c in judged_w}
|
|
3599
|
+
sources_w = {r["candidate_id"]: r["source"]
|
|
3600
|
+
for r in guarded(lambda: records.read_json(capped / SUMMARY), {}).get("packets", [])}
|
|
3601
|
+
swept_w = guarded(lambda: records.read_json(capped / SUMMARY), {}).get("sweeps") or {}
|
|
3602
|
+
|
|
3603
|
+
class Asked:
|
|
3604
|
+
def __init__(self, seats_path):
|
|
3605
|
+
self.seats_path, self.items = seats_path, []
|
|
3606
|
+
|
|
3607
|
+
def item(self, stage_, item, seat, text, schema_, **kw):
|
|
3608
|
+
self.items.append((item, seat, kw))
|
|
3609
|
+
return {"item": item, "outcome": "failed", "codes": ["NOT_SENT"], "attempts": []}
|
|
3610
|
+
|
|
3611
|
+
def remaining(self, stage_):
|
|
3612
|
+
return 10 ** 12
|
|
3613
|
+
|
|
3614
|
+
def asked(kind, seats_file):
|
|
3615
|
+
sup = Asked(seats_file)
|
|
3616
|
+
said = ""
|
|
3617
|
+
with records.run_stage(capped, STAGE, INPUTS) as stg:
|
|
3618
|
+
try:
|
|
3619
|
+
if kind == "sweep":
|
|
3620
|
+
sweep_stage(capped, stg, sup, stg.declaration, judged_w, judgments_w, sources_w, {},
|
|
3621
|
+
"calibration")
|
|
3622
|
+
else:
|
|
3623
|
+
cross_stage(capped, stg, sup, stg.declaration, swept_w, item_of, {}, "calibration")
|
|
3624
|
+
except Refused as exc:
|
|
3625
|
+
said = str(exc)
|
|
3626
|
+
except Exception as exc: # noqa: BLE001 - an earlier part's failure, read by the control
|
|
3627
|
+
said = f"RAISED {exc!r}"
|
|
3628
|
+
stg.record["status"] = "partial"
|
|
3629
|
+
return said, sup.items
|
|
3630
|
+
sweep_seat, cross_seat = "claude:claude-sonnet-5-5/medium", "codex:gpt-6-astra/xhigh"
|
|
3631
|
+
huge = packet.build("c-a2", STAGE, "s", "x" * 8_000_000)
|
|
3632
|
+
said_s, asked_s = asked("sweep", fx_seats(root, name="sweep-tight.json", capacities={sweep_seat: 3000}))
|
|
3633
|
+
control("Codex WP-11 r1 #3: a sweep shard over its seat's capacity is SWEEP_OVER_CAPACITY before any sweep "
|
|
3634
|
+
"is sent", said_s.startswith("SWEEP_OVER_CAPACITY S6") and asked_s == [], f"{said_s[:200]} {len(asked_s)}")
|
|
3635
|
+
said_s, asked_s = asked("sweep", fx_seats(root, name="sweep-room.json", capacities={sweep_seat: 150_000}))
|
|
3636
|
+
side_a = [kw for item, seat, kw in asked_s if seat == sweep_seat]
|
|
3637
|
+
side_b = [kw for item, seat, kw in asked_s if seat != sweep_seat]
|
|
3638
|
+
control("Codex WP-11 r1 #3: within capacity every sweep is sent with its seat's capacity and an attempt bound "
|
|
3639
|
+
"that refuses an oversized attempt, and the unmeasured Codex sweep seat is not bounded (D13)",
|
|
3640
|
+
not said_s and side_a and side_b and all(kw.get("context_capacity") == 150_000 for kw in side_a)
|
|
3641
|
+
and all(any(x.startswith("SWEEP_OVER_CAPACITY sweep a") for x in kw.get("packet_check", lambda m: [])(huge))
|
|
3642
|
+
for kw in side_a)
|
|
3643
|
+
and all(kw.get("context_capacity") is None and kw.get("packet_check", lambda m: [])(huge) == [] for kw in side_b),
|
|
3644
|
+
f"{said_s[:200]} {[kw.get('context_capacity') for kw in side_a]} "
|
|
3645
|
+
f"{[guarded(lambda kw=kw: kw.get('packet_check', lambda m: [])(huge), ['RAISED'])[:1] for kw in side_a]} "
|
|
3646
|
+
f"{[kw.get('context_capacity') for kw in side_b]} "
|
|
3647
|
+
f"{[guarded(lambda kw=kw: kw.get('packet_check', lambda m: [])(huge), ['RAISED'])[:1] for kw in side_b]}")
|
|
3648
|
+
said_c, asked_c = asked("cross", fx_seats(root, name="cross-tight.json", capacities={cross_seat: 3000},
|
|
3649
|
+
codex_allowance=5000))
|
|
3650
|
+
control("Codex WP-11 r1 #3: a cross-review packet over Judge B's capacity is CROSS_OVER_CAPACITY before any "
|
|
3651
|
+
"cross-review is sent", said_c.startswith("CROSS_OVER_CAPACITY S6") and asked_c == [],
|
|
3652
|
+
f"{said_c[:200]} {len(asked_c)}")
|
|
3653
|
+
said_c, asked_c = asked("cross", fx_seats(root, name="cross-room.json", capacities={cross_seat: 150_000},
|
|
3654
|
+
codex_allowance=5000))
|
|
3655
|
+
control("Codex WP-11 r1 #3: within capacity every cross-review is sent with Judge B's capacity and an attempt "
|
|
3656
|
+
"bound that refuses an oversized attempt", not said_c and asked_c
|
|
3657
|
+
and all(kw.get("context_capacity") == 150_000
|
|
3658
|
+
and any(x.startswith("CROSS_OVER_CAPACITY B") for x in kw.get("packet_check", lambda m: [])(huge))
|
|
3659
|
+
for _i, _s, kw in asked_c), f"{said_c[:200]} {len(asked_c)}")
|
|
3660
|
+
# C3 (lead's (가)): before the first sweep, the whole plan's claims are held against what S6 has left, all
|
|
3661
|
+
# or none; driven over the same copy with both sweep seats measured, so each call's claim is computable
|
|
3662
|
+
summary_pre = guarded(lambda: records.read_json(capped / SUMMARY), {})
|
|
3663
|
+
|
|
3664
|
+
def preflight(left):
|
|
3665
|
+
sup = Asked(fx_seats(root, name=f"sweep-preflight-{left}.json",
|
|
3666
|
+
capacities={"codex:gpt-6-luna/medium": 272_000}, codex_allowance=19_167))
|
|
3667
|
+
sup.remaining = lambda stage_: left
|
|
3668
|
+
with records.run_stage(capped, STAGE, INPUTS) as stg:
|
|
3669
|
+
try:
|
|
3670
|
+
section, _receipts = sweep_stage(capped, stg, sup, stg.declaration, judged_w, judgments_w,
|
|
3671
|
+
sources_w, {}, "calibration")
|
|
3672
|
+
except Exception as exc: # noqa: BLE001 - read by the controls below, never the suite's end
|
|
3673
|
+
section = {"raised": repr(exc)}
|
|
3674
|
+
stg.record["status"] = "partial"
|
|
3675
|
+
return section, sup.items
|
|
3676
|
+
low, low_asked = preflight(1)
|
|
3677
|
+
low_plan = low.get("plan") or {}
|
|
3678
|
+
control("C3 (가): with too little of S6 left for the whole sweep plan no sweep is sent, and SWEEPS_NOT_RUN "
|
|
3679
|
+
"names the plan's calls, the total they claim at most and what S6 has left",
|
|
3680
|
+
low.get("run") is False and low_asked == [] and bool(low.get("absent"))
|
|
3681
|
+
and low_plan.get("calls", 0) > 0 and low_plan.get("claims_at_most", 0) > 1 and low_plan.get("left") == 1
|
|
3682
|
+
and str(low.get("why", "")).startswith(
|
|
3683
|
+
f"SWEEPS_NOT_RUN budget: the plan's {low_plan.get('calls')} calls claim "
|
|
3684
|
+
f"{low_plan.get('claims_at_most')} at most and S6 has 1 left"),
|
|
3685
|
+
f"{ {key: low.get(key) for key in ('run', 'plan', 'why', 'absent', 'raised')} } asked={len(low_asked)}")
|
|
3686
|
+
said_low = guarded(lambda: report_lines({**summary_pre, "dry": False, "sweeps": low}), [])
|
|
3687
|
+
control("C3 (가): the report says no sweep was sent and why",
|
|
3688
|
+
f"sweeps: none - {low.get('why')}" in said_low, f"{[l for l in said_low if l.startswith('sweeps')]}")
|
|
3689
|
+
derived_low = guarded(lambda: derive_stage(capped, summary_pre, judgments_w, low, {}), {})
|
|
3690
|
+
withheld_low = {row["candidate_id"]: row["why"] for row in derived_low.get("not_derived") or []}
|
|
3691
|
+
control("C3 (가): and every absence claim stays listed and is left underived for that reason, never derived "
|
|
3692
|
+
"as a gap nobody swept",
|
|
3693
|
+
bool(low.get("absent")) and all(withheld_low.get(cid) == low.get("why") for cid in low["absent"])
|
|
3694
|
+
and not set(low["absent"]) & set(derived_low.get("verdicts") or {}),
|
|
3695
|
+
f"{withheld_low} verdicts={sorted(derived_low.get('verdicts') or {})}")
|
|
3696
|
+
high, high_asked = preflight(10 ** 12)
|
|
3697
|
+
control("C3 (가): with room for the whole plan the sweeps are sent as before, each planned call asked once",
|
|
3698
|
+
high.get("run") is not False and "plan" not in high and low_plan.get("calls", 0) > 0
|
|
3699
|
+
and len(high_asked) == low_plan.get("calls"),
|
|
3700
|
+
f"run={high.get('run')} asked={len(high_asked)} planned={low_plan.get('calls')} {high.get('raised')}")
|
|
3701
|
+
# Codex WP-11 r1 #4: a claim S5 retrieved every remaining unit for has nothing to sweep (shard_plan gives it
|
|
3702
|
+
# no shard); it completes with no cross-review or reconsideration call and is derived from the judges'
|
|
3703
|
+
# own judgments, as a gap
|
|
3704
|
+
c_ex = claims_known[0] if claims_known else ""
|
|
3705
|
+
swept_ex = {**swept_w, "absent": [c_ex], "groups": shard_plan({c_ex: []}, 5, 100), "calls": []}
|
|
3706
|
+
summary_w = guarded(lambda: records.read_json(capped / SUMMARY), {})
|
|
3707
|
+
sup_ex = Asked(None)
|
|
3708
|
+
with records.run_stage(capped, STAGE, INPUTS) as stg:
|
|
3709
|
+
crossed_ex = guarded(lambda: cross_stage(capped, stg, sup_ex, stg.declaration, swept_ex, item_of, {},
|
|
3710
|
+
"calibration")[0], {})
|
|
3711
|
+
again_ex = guarded(lambda: reconsider_stage(capped, stg, sup_ex, stg.declaration, summary_w,
|
|
3712
|
+
whole_packets, judgments_w, crossed_ex, {},
|
|
3713
|
+
"calibration")[0], {})
|
|
3714
|
+
stg.record["status"] = "partial"
|
|
3715
|
+
derived_ex = guarded(lambda: derive_stage(capped, summary_w, judgments_w, swept_ex, again_ex), {})
|
|
3716
|
+
current_ex = (((derived_ex.get("verdicts") or {}).get(c_ex) or {}).get("outcome") or {}).get(
|
|
3717
|
+
"candidate_diagnosis", {}).get("current", {}).get("diagnosis")
|
|
3718
|
+
control("Codex WP-11 r1 #4: an absence claim with nothing left to sweep is complete with no cross-review or "
|
|
3719
|
+
"reconsideration call, and is derived from the judges' judgments as a gap",
|
|
3720
|
+
bool(c_ex) and crossed_ex.get("exhausted") == [c_ex] and not crossed_ex.get("not_reviewed")
|
|
3721
|
+
and sup_ex.items == [] and [r["candidate_id"] for r in again_ex.get("reconsidered", [])] == [c_ex]
|
|
3722
|
+
and current_ex == "gap"
|
|
3723
|
+
and c_ex not in [r["candidate_id"] for r in derived_ex.get("not_derived", [])],
|
|
3724
|
+
f"{crossed_ex.get('exhausted')} {crossed_ex.get('not_reviewed')} {len(sup_ex.items)} "
|
|
3725
|
+
f"{again_ex.get('reconsidered')} {current_ex} {derived_ex.get('not_derived')}")
|
|
3726
|
+
# Codex WP-11 r1 #5: a units-only reconsideration packet shows no stored unit or ledger entry id - the
|
|
3727
|
+
# candidate's own references to ones it does not show carry labels of their own. Read value by value
|
|
3728
|
+
# from the packet's candidate object, so an id inside other text (a decision id) is not counted.
|
|
3729
|
+
def stored_values(value, labels):
|
|
3730
|
+
if isinstance(value, dict):
|
|
3731
|
+
return [x for v in value.values() for x in stored_values(v, labels)]
|
|
3732
|
+
if isinstance(value, list):
|
|
3733
|
+
return [x for v in value for x in stored_values(v, labels)]
|
|
3734
|
+
if isinstance(value, str):
|
|
3735
|
+
target = value[len(CLUSTER_PREFIX):] if value.startswith(CLUSTER_PREFIX) else value
|
|
3736
|
+
return [value] if target in labels.unit_store or target in labels.entry_store else []
|
|
3737
|
+
return []
|
|
3738
|
+
referring = [(c, labels) for c, (labels, _t) in sorted(whole_packets.items()) if labels.units
|
|
3739
|
+
and stored_values({k: v for k, v in labels.candidate.items()
|
|
3740
|
+
if k not in ("candidate_id", "label", "event_ids", "sessions")}, labels)]
|
|
3741
|
+
leaked = {}
|
|
3742
|
+
for c, labels in referring:
|
|
3743
|
+
shown = guarded(lambda labels=labels: json.loads(reconsider_payload(returned_labels(
|
|
3744
|
+
labels, [labels.units["n1"]])).split("<candidate>\n", 1)[1].split("\n</candidate>", 1)[0]), "RAISED")
|
|
3745
|
+
leaked[c] = ["RAISED"] if shown == "RAISED" else stored_values(shown, labels)
|
|
3746
|
+
control("Codex WP-11 r1 #5: a reconsideration packet's candidate holds no stored unit or ledger entry id; "
|
|
3747
|
+
"the fixture holds candidates whose fields reference them",
|
|
3748
|
+
referring and not any(leaked.values()),
|
|
3749
|
+
f"{len(referring)} {[(c[:20], v[:3]) for c, v in leaked.items() if v][:3]}")
|
|
3750
|
+
# Codex WP-11 r2 #3: no packet of any of the four kinds shows a decision reference - a decision id
|
|
3751
|
+
# (`<entry id>@<run>`, every one the ledger's entries hold and every one a candidate resolves) or the
|
|
3752
|
+
# approval, adjudication or confirmation a decision records - nor a stored unit or ledger entry id. Read
|
|
3753
|
+
# value by value: every JSON string a payload holds, decoded, compared whole.
|
|
3754
|
+
def strings_of(text):
|
|
3755
|
+
out = []
|
|
3756
|
+
for raw in re.findall(r'"((?:[^"\\\n]|\\.)*)"', text):
|
|
3757
|
+
try:
|
|
3758
|
+
out.append(json.loads(f'"{raw}"'))
|
|
3759
|
+
except ValueError:
|
|
3760
|
+
out.append(raw)
|
|
3761
|
+
return out
|
|
3762
|
+
any_labels = next(iter(whole_packets.values()))[0] if whole_packets else None
|
|
3763
|
+
decision_refs = set()
|
|
3764
|
+
for entry in (any_labels.entry_store.values() if any_labels else []):
|
|
3765
|
+
for d in entry.get("decisions") or []:
|
|
3766
|
+
decision_refs.add(f"{entry['id']}@{d.get('run')}")
|
|
3767
|
+
# an approval the ledger records as `legacy` or `unavailable` names no row: a state, not a reference
|
|
3768
|
+
decision_refs |= {d.get(k) for k in ("approval_id", "adjudication_id", "confirmation")
|
|
3769
|
+
if isinstance(d.get(k), str)
|
|
3770
|
+
and d.get(k) not in lifecycle_intake.ledger_lib.UNAPPROVED}
|
|
3771
|
+
resolving = [(c, labels) for c, (labels, _t) in sorted(whole_packets.items())
|
|
3772
|
+
if ((labels.candidate.get("lifecycle") or {}).get("resolves"))]
|
|
3773
|
+
decision_refs |= {labels.candidate["lifecycle"]["resolves"] for _c, labels in resolving}
|
|
3774
|
+
|
|
3775
|
+
def four_kinds(c, labels):
|
|
3776
|
+
u = labels.units.get("n1") or sorted(labels.unit_store)[0]
|
|
3777
|
+
kinds = {"judge": lambda: payload(labels),
|
|
3778
|
+
"reconsider": lambda: reconsider_payload(returned_labels(labels, [u])),
|
|
3779
|
+
"sweep": lambda: sweep_payload(SweepLabels({"pairs": {c: [u]}, "units": [u]},
|
|
3780
|
+
{c: labels.candidate}, labels.unit_store,
|
|
3781
|
+
labels.entry_store), "a" * 64),
|
|
3782
|
+
"cross": lambda: cross_payload(CrossLabels(labels.candidate, {u: {"A": {"situation": "no"}}},
|
|
3783
|
+
[u], [], labels.unit_store, labels.entry_store))}
|
|
3784
|
+
return {kind: guarded(make, "RAISED") for kind, make in kinds.items()}
|
|
3785
|
+
shown_refs = {}
|
|
3786
|
+
for c, labels in [(c, labels) for c, (labels, _t) in sorted(whole_packets.items())
|
|
3787
|
+
if labels.candidate.get("lifecycle")]:
|
|
3788
|
+
stored = set(labels.unit_store) | set(labels.entry_store)
|
|
3789
|
+
for kind, text in four_kinds(c, labels).items():
|
|
3790
|
+
hits = ["RAISED"] if text == "RAISED" else sorted(
|
|
3791
|
+
{v for v in strings_of(text) if v in decision_refs or v in stored})
|
|
3792
|
+
if hits:
|
|
3793
|
+
shown_refs[(c[:24], kind)] = hits[:3]
|
|
3794
|
+
control("Codex WP-11 r2 #3: no judge, sweep, cross-review or reconsideration packet of a lifecycle candidate "
|
|
3795
|
+
"shows a decision reference or a stored unit or entry id; the fixture holds candidates that resolve "
|
|
3796
|
+
"a decision", bool(resolving) and bool(decision_refs) and not shown_refs,
|
|
3797
|
+
f"{len(resolving)} resolving, {len(decision_refs)} references, shown {sorted(shown_refs.items())[:3]}")
|
|
3798
|
+
# WP-10 X r1 #4: on disk the mixed population tells a planted candidate from a natural one (S4's
|
|
3799
|
+
# candidates.json lists the naturals by construction; S4 derives their ids from their labels, and the
|
|
3800
|
+
# planted ones take the labels after them), and no byte a model is sent carries either: in every packet
|
|
3801
|
+
# the complete golden sent, of all four kinds, no JSON string is a candidate id or the stored label of the
|
|
3802
|
+
# call's own candidate, and each CALL-ID names a candidate only by `item_of`, one digest for every member
|
|
3803
|
+
population_w = guarded(lambda: records.read_json(whole / "checked-candidates.json"),
|
|
3804
|
+
{"candidates": []})["candidates"]
|
|
3805
|
+
planted_w = {e["candidate_id"] for e in guarded(lambda: records.read_json(whole / controls.CONTROLS_FILE),
|
|
3806
|
+
{"planted": []})["planted"]}
|
|
3807
|
+
ids_w = {k["candidate_id"] for k in population_w}
|
|
3808
|
+
of_item = {item_of(k["candidate_id"]): k for k in population_w}
|
|
3809
|
+
kinds_w, carried = collections.Counter(), []
|
|
3810
|
+
for call_json in sorted((whole / "calls").glob("*/call.json")) if (whole / "calls").is_dir() else []:
|
|
3811
|
+
held_call = guarded(lambda: records.read_json(call_json), {})
|
|
3812
|
+
if held_call.get("stage") != STAGE:
|
|
3813
|
+
continue # the run's earlier stages' calls (S3, S4) are other packets
|
|
3814
|
+
item = str(held_call.get("item") or "")
|
|
3815
|
+
sent = guarded(lambda: (call_json.parent / "packet.md").read_text(encoding="utf-8"), "")
|
|
3816
|
+
head, _sep, body = sent.partition("\n" + packet.PAYLOAD_MARKER + "\n")
|
|
3817
|
+
call_line = head.split("\n", 1)[0]
|
|
3818
|
+
kind = ("sweep" if item.startswith("sweep-") else "cross" if item.endswith("-X")
|
|
3819
|
+
else "reconsider" if item[:-1].endswith(f"-{RECONSIDER}") else "judge")
|
|
3820
|
+
kinds_w[kind] += 1
|
|
3821
|
+
own = of_item.get(item.split("-", 1)[0]) if kind != "sweep" else None
|
|
3822
|
+
shown = set(strings_of(body))
|
|
3823
|
+
# a sweep's candidates are k1, ... in candidate-id order within the shard and a cross-review's is
|
|
3824
|
+
# always k1: packet labels, which a stored label may happen to spell, so those two kinds are held to
|
|
3825
|
+
# carrying no id; the judge and reconsideration packets label nothing k
|
|
3826
|
+
hits = sorted(shown & ids_w) + ([own["label"]] if own and kind in ("judge", "reconsider")
|
|
3827
|
+
and own.get("label") in shown else [])
|
|
3828
|
+
hits += [i for i in ids_w if i in call_line]
|
|
3829
|
+
if kind != "sweep" and own is None:
|
|
3830
|
+
hits.append(f"no candidate has the item {item}")
|
|
3831
|
+
if hits:
|
|
3832
|
+
carried.append((call_json.parent.name[-30:], kind, hits[:3]))
|
|
3833
|
+
control("WP-10 X r1 #4: no packet of any kind carries a candidate id or its stored label, and each CALL-ID "
|
|
3834
|
+
"names its candidate by the one digest every member gets; the golden mixes natural and planted "
|
|
3835
|
+
"candidates and sent all four kinds", not carried and planted_w and ids_w - planted_w
|
|
3836
|
+
and set(kinds_w) == {"judge", "sweep", "cross", "reconsider"},
|
|
3837
|
+
f"{dict(kinds_w)} planted {len(planted_w)} natural {len(ids_w - planted_w)} carried {carried[:3]}")
|
|
3838
|
+
# and in the calls that carry several candidates (a sweep shard; a cross-review carries one, always k1),
|
|
3839
|
+
# what orders them is the candidate id: `shard_plan` groups them in id order and `SweepLabels` labels a
|
|
3840
|
+
# shard's k1, ... in id order, whatever order they arrive in. A planted candidate is a formed one, and
|
|
3841
|
+
# every formed id, planted or natural, is `k-` and sixteen hex digits of a sha256 (a planted one of the
|
|
3842
|
+
# nonce, a natural one of its run and label), so among them the order is a digest's, one rule for both
|
|
3843
|
+
# kinds, and no position follows creation or label number. A lifecycle candidate's id names its source,
|
|
3844
|
+
# which its sweep view shows anyway.
|
|
3845
|
+
id_form = re.compile(r"k-[0-9a-f]{16}")
|
|
3846
|
+
by_id_w = {k["candidate_id"]: k for k in population_w}
|
|
3847
|
+
formed_w = {k["candidate_id"] for k in population_w if k.get("source") == "formed"}
|
|
3848
|
+
some_labels = next(iter(whole_packets.values()))[0] if whole_packets else None
|
|
3849
|
+
unit_w = sorted(some_labels.unit_store)[0] if some_labels else None
|
|
3850
|
+
arriving = sorted(formed_w, reverse=True)[:5]
|
|
3851
|
+
probe_labels = guarded(lambda: SweepLabels({"pairs": {c: [unit_w] for c in arriving}, "units": [unit_w]},
|
|
3852
|
+
by_id_w, some_labels.unit_store, some_labels.entry_store), None)
|
|
3853
|
+
grouped = [c for g in (guarded(lambda: records.read_json(whole / SUMMARY), {}).get("sweeps") or {})
|
|
3854
|
+
.get("groups") or [] for c in g.get("candidates") or []]
|
|
3855
|
+
control("WP-10 X r1 #4 (round 2's question): candidates sharing a packet are ordered and labelled by "
|
|
3856
|
+
"candidate id, and every id is one digest form for planted and natural alike",
|
|
3857
|
+
probe_labels is not None and list(probe_labels.candidates.values()) == sorted(arriving)
|
|
3858
|
+
and planted_w <= formed_w and all(id_form.fullmatch(i) for i in formed_w)
|
|
3859
|
+
and grouped and grouped == sorted(grouped),
|
|
3860
|
+
f"{getattr(probe_labels, 'candidates', None)} {[i for i in formed_w if not id_form.fullmatch(i)][:2]} "
|
|
3861
|
+
f"{grouped[:4]}")
|
|
3862
|
+
sixth = guarded(lambda: run(retried, supervisor(retried, root / "cells-12", whole_plan)),
|
|
3863
|
+
lambda e: {"problem": repr(e)})
|
|
3864
|
+
sixth_reused = [h.get("reused") for row in sixth.get("calls", []) for h in row["seats"].values()] + [
|
|
3865
|
+
h.get("reused") for row in (sixth.get("sweeps") or {}).get("calls", []) for h in row["seats"].values()] + [
|
|
3866
|
+
row.get("reused") for row in (sixth.get("cross_review") or {}).get("calls", [])] + [
|
|
3867
|
+
h.get("reused") for row in (sixth.get("reconsiderations") or {}).get("calls", [])
|
|
3868
|
+
for h in row["seats"].values()]
|
|
3869
|
+
control("Codex WP-11 r1 #1: run again, every call is answered by its accepted attempt, the retried ones "
|
|
3870
|
+
"included, and the receipts still pass", "problem" not in sixth and sixth_reused
|
|
3871
|
+
and all(sixth_reused), f"{str(sixth.get('problem'))[:300]} {sixth_reused.count(None)}")
|
|
3872
|
+
# ---- Judge B's cross-review (J3b, done-when 3) --------------------------------------------------------
|
|
3873
|
+
cr = again_sw.get("cross_review") or {}
|
|
3874
|
+
pop_b = {k["candidate_id"]: k for k in records.read_json(whole / "checked-candidates.json")["candidates"]}
|
|
3875
|
+
units_b = {u["unit_id"]: u for u in records.read_json(whole / "inventory" / "current.json")["units"]}
|
|
3876
|
+
entries_b = whole_packets[next(iter(whole_packets))][0].entry_store
|
|
3877
|
+
marks_w = {}
|
|
3878
|
+
for (g, sh, side), k in kept_sw.items(): # from the kept sweep files, not through sweep_marks
|
|
3879
|
+
for pr in k.get("pairs", []):
|
|
3880
|
+
marks_w.setdefault(pr["candidate_id"], {}).setdefault(pr["unit_id"], {})[side] = pr
|
|
3881
|
+
want_flags = {c: sorted(u for u, sides in m.items() if any("yes" in (x["situation"], x["action"])
|
|
3882
|
+
for x in sides.values())) for c, m in marks_w.items()}
|
|
3883
|
+
both_no = {c: [u for u, sides in m.items() if len(sides) == 2
|
|
3884
|
+
and all(x["situation"] == x["action"] == "no" for x in sides.values())] for c, m in marks_w.items()}
|
|
3885
|
+
want_neg = {c: sorted(us, key=lambda u, c=c: hashlib.sha256(f"{whole.name}\x00{c}\x00{u}".encode("utf-8"))
|
|
3886
|
+
.hexdigest())[:50] for c, us in both_no.items()}
|
|
3887
|
+
crossed_kept = {c: guarded(lambda c=c: records.read_json(whole / cross_rel(item_of(c))), {}) for c in expected}
|
|
3888
|
+
control("J3b (done-when 3): every absence claim is reviewed by Judge B, its packet carrying every unit either "
|
|
3889
|
+
"sweep flagged and the fifty units both found unrelated that the run id draws, with both sweeps' reasons",
|
|
3890
|
+
sorted(cr.get("reviewed", [])) == expected and all(
|
|
3891
|
+
crossed_kept[c].get("partial_flags") == want_flags.get(c, [])
|
|
3892
|
+
and crossed_kept[c].get("seeded_negatives") == want_neg.get(c, [])
|
|
3893
|
+
and crossed_kept[c].get("seat") == "codex:gpt-6-astra/xhigh"
|
|
3894
|
+
and len(crossed_kept[c].get("verdicts", [])) == len(set(want_flags.get(c, [])) | set(want_neg.get(c, [])))
|
|
3895
|
+
for c in expected), f"{cr.get('reviewed')} {expected}")
|
|
3896
|
+
full = [c for c in expected if len(both_no.get(c, [])) > 50]
|
|
3897
|
+
flagged_claims = [c for c in expected if want_flags.get(c)]
|
|
3898
|
+
one_side = [c for c in flagged_claims if any(len({s for s, x in marks_w[c][u].items()
|
|
3899
|
+
if "yes" in (x["situation"], x["action"])}) == 1
|
|
3900
|
+
for u in want_flags[c])]
|
|
3901
|
+
control("J3b: a claim with more than fifty units both sweeps found unrelated is shown exactly fifty; the "
|
|
3902
|
+
"fixture holds such a claim, and a claim with a unit only one sweep flagged",
|
|
3903
|
+
full and all(len(crossed_kept[c].get("seeded_negatives", [])) == 50 for c in full) and one_side,
|
|
3904
|
+
f"{[len(both_no.get(c, [])) for c in expected]} {len(flagged_claims)}")
|
|
3905
|
+
few = {f"u{n}": {side: {"situation": "no", "action": "no", "reason": "r"} for side in ("a", "b")} for n in range(7)}
|
|
3906
|
+
few["u-flag"] = {"a": {"situation": "yes", "action": "no", "reason": "r"},
|
|
3907
|
+
"b": {"situation": "no", "action": "no", "reason": "r"}}
|
|
3908
|
+
control("J3b: a claim with fewer than fifty units both sweeps found unrelated is shown every one of them, and "
|
|
3909
|
+
"a unit one sweep flagged is a flag, not a negative",
|
|
3910
|
+
sorted(negatives_of(few, "r1", "k-a")) == sorted(f"u{n}" for n in range(7)) and flags_of(few) == ["u-flag"])
|
|
3911
|
+
if full:
|
|
3912
|
+
c = full[0]
|
|
3913
|
+
marks_c = {u: {side: {k: x[k] for k in ("situation", "action", "reason")} for side, x in sides.items()}
|
|
3914
|
+
for u, sides in marks_w[c].items()}
|
|
3915
|
+
control("J3b (done-when 3): another seed draws another sample",
|
|
3916
|
+
negatives_of(marks_c, "another-run", c) != negatives_of(marks_c, whole.name, c)
|
|
3917
|
+
and negatives_of(marks_c, whole.name, c) == want_neg[c])
|
|
3918
|
+
if flagged_claims:
|
|
3919
|
+
c = flagged_claims[0]
|
|
3920
|
+
rec = {"partial_flags": [], "seeded_negatives": [], **crossed_kept[c]}
|
|
3921
|
+
marks_c = {u: {side: {k: x[k] for k in ("situation", "action", "reason")} for side, x in sides.items()}
|
|
3922
|
+
for u, sides in marks_w[c].items()}
|
|
3923
|
+
flags_c, neg_c = flags_of(marks_c), negatives_of(marks_c, whole.name, c)
|
|
3924
|
+
labels_c = CrossLabels(pop_b[c], marks_c, flags_c, neg_c, units_b, entries_b)
|
|
3925
|
+
built_sha = packet.sha256_bytes(cross_payload(labels_c).encode("utf-8"))
|
|
3926
|
+
control("J3b: a kept cross-review is the one the kept sweep results build", not cross_review_problems(
|
|
3927
|
+
rec, flags_c, neg_c, built_sha), f"{cross_review_problems(rec, flags_c, neg_c, built_sha)}")
|
|
3928
|
+
named("control (done-when 3): a cross-review missing one partial flag is CROSS_REVIEW_INCOMPLETE",
|
|
3929
|
+
cross_review_problems({**rec, "partial_flags": rec["partial_flags"][1:]}, flags_c, neg_c, built_sha),
|
|
3930
|
+
"CROSS_REVIEW_INCOMPLETE")
|
|
3931
|
+
# another sample is always built and always judged by the checker: the drawn ones reversed, or with
|
|
3932
|
+
# a unit nobody drew added when there are fewer than two (Codex WP-11 r1 #7)
|
|
3933
|
+
kept_negatives = list(rec["seeded_negatives"])
|
|
3934
|
+
another = kept_negatives[::-1] if len(set(kept_negatives)) > 1 else kept_negatives + ["u-not-drawn"]
|
|
3935
|
+
named("control: a cross-review whose negatives are another sample is CROSS_REVIEW_INCOMPLETE",
|
|
3936
|
+
cross_review_problems({**rec, "seeded_negatives": another}, flags_c, neg_c, built_sha),
|
|
3937
|
+
"CROSS_REVIEW_INCOMPLETE")
|
|
3938
|
+
corrupted = json.loads(json.dumps(marks_c))
|
|
3939
|
+
some_neg = (neg_c or flags_c)[0]
|
|
3940
|
+
corrupted[some_neg]["a"]["reason"] = "a reason changed after the review"
|
|
3941
|
+
stale_sha = packet.sha256_bytes(cross_payload(CrossLabels(
|
|
3942
|
+
pop_b[c], corrupted, flags_c, neg_c, units_b, entries_b)).encode("utf-8"))
|
|
3943
|
+
named("control (done-when 3): one sampled reason changed in the sweep results is CROSS_REVIEW_STALE by "
|
|
3944
|
+
"the payload hash", cross_review_problems(rec, flags_c, neg_c, stale_sha), "CROSS_REVIEW_STALE")
|
|
3945
|
+
good = {"verdicts": [{"unit": u, "situation": "no", "action": "no", "reason": "unrelated"}
|
|
3946
|
+
for u in labels_c.units]}
|
|
3947
|
+
control("J3b: a cross-review judging every unit shown once passes", not cross_problems(labels_c, good))
|
|
3948
|
+
for name, answer, code in (
|
|
3949
|
+
("a unit shown and not judged", {"verdicts": good["verdicts"][1:]}, "CROSS_UNIT_MISSING"),
|
|
3950
|
+
("a unit judged twice", {"verdicts": good["verdicts"] + good["verdicts"][:1]}, "CROSS_UNIT_TWICE"),
|
|
3951
|
+
("a unit the packet does not show", {"verdicts": good["verdicts"] + [{**good["verdicts"][0], "unit": "n999"}]},
|
|
3952
|
+
"UNKNOWN_LABEL")):
|
|
3953
|
+
named(f"control: in a cross-review, {name} is refused by name", cross_problems(labels_c, answer), code)
|
|
3954
|
+
text_c = cross_payload(labels_c)
|
|
3955
|
+
control("J3b: the cross-review packet shows each unit with both sweeps' marks and reasons, and no stored id",
|
|
3956
|
+
all(f'"sweeps": {{"a": ' in line and '"b": ' in line for line in text_c.split("<units>\n", 1)[1]
|
|
3957
|
+
.split("\n</units>", 1)[0].splitlines()) and c not in text_c
|
|
3958
|
+
and not any(u in text_c for u in labels_c.units.values()), "")
|
|
3959
|
+
# ---- the reconsiderations (J3c, done-when 3) ----------------------------------------------------------
|
|
3960
|
+
rc = fourth.get("reconsiderations") or {}
|
|
3961
|
+
kept_rc = {(c, who): guarded(lambda c=c, who=who: records.read_json(
|
|
3962
|
+
whole / reconsideration_rel(item_of(c), who)), {}) for c in expected for who in ("A", "B")}
|
|
3963
|
+
b_matched = {c: sorted(v["unit_id"] for v in crossed_kept[c].get("verdicts", [])
|
|
3964
|
+
if "yes" in (v["situation"], v["action"])) for c in expected}
|
|
3965
|
+
want_returned = {c: sorted(set(want_flags.get(c, [])) | set(b_matched[c])) for c in expected}
|
|
3966
|
+
control("J3c (done-when 3): every unit either sweep flagged or Judge B marked a match returns to both judges, "
|
|
3967
|
+
"each reconsideration judging exactly those units",
|
|
3968
|
+
all(kept_rc[(c, who)].get("returned") == want_returned[c] and want_returned[c]
|
|
3969
|
+
and sorted(u["unit_id"] for u in kept_rc[(c, who)].get("judgment", {}).get("units", []))
|
|
3970
|
+
== want_returned[c] for c in expected for who in ("A", "B")),
|
|
3971
|
+
f"{[(c[:12], len(want_returned[c]), len(kept_rc[(c, 'A')].get('returned') or [])) for c in expected]}")
|
|
3972
|
+
control("J3c: the fixture returns a unit only Judge B marked, and the first claim's first returned unit is one "
|
|
3973
|
+
"only one sweep flagged",
|
|
3974
|
+
any(set(b_matched[c]) - set(want_flags.get(c, [])) for c in expected)
|
|
3975
|
+
and want_returned[claims_known[0]][:1]
|
|
3976
|
+
and len({side for side, x in marks_w.get(claims_known[0], {}).get(want_returned[claims_known[0]][0], {}).items()
|
|
3977
|
+
if "yes" in (x["situation"], x["action"])}) == 1,
|
|
3978
|
+
f"{b_matched} {want_flags}")
|
|
3979
|
+
control("J3c (N#1): both judges' reconsiderations of a claim carry one payload and two packets",
|
|
3980
|
+
all(kept_rc[(c, "A")].get("payload_sha256") and kept_rc[(c, "A")].get("payload_sha256")
|
|
3981
|
+
== kept_rc[(c, "B")].get("payload_sha256")
|
|
3982
|
+
and kept_rc[(c, "A")].get("packet_sha256") != kept_rc[(c, "B")].get("packet_sha256") for c in expected))
|
|
3983
|
+
c0_labels = guarded(lambda: returned_labels(whole_packets[claims_known[0]][0], want_returned[claims_known[0]]), None)
|
|
3984
|
+
c0_text = guarded(lambda: reconsider_payload(c0_labels), "") if c0_labels is not None else ""
|
|
3985
|
+
control("J3c: a reconsideration shows the candidate, its claims and the returned units with their context, no "
|
|
3986
|
+
"ledger entry and no candidate-level question, and its payload is the one kept",
|
|
3987
|
+
c0_labels is not None and list(c0_labels.units.values()) == want_returned[claims_known[0]]
|
|
3988
|
+
and not c0_labels.entries and "<ledger_entries>" not in c0_text and "<units>" in c0_text
|
|
3989
|
+
and not any(f"`{f}`" in c0_text for f in RECONSIDER_REFUSED)
|
|
3990
|
+
and packet.sha256_bytes(c0_text.encode("utf-8")) == kept_rc[(claims_known[0], "A")].get("payload_sha256")
|
|
3991
|
+
and claims_known[0] not in c0_text, "")
|
|
3992
|
+
c0_kept = [kept_rc[(claims_known[0], who)].get("judgment") or {} for who in ("A", "B")]
|
|
3993
|
+
control("J3c: a kept reconsideration holds the returned units and their matching units only, and a unit both "
|
|
3994
|
+
"judges now find matching carries its following and contribution",
|
|
3995
|
+
all(sorted(k) == sorted(RECONSIDER_FIELDS) for k in c0_kept)
|
|
3996
|
+
and all(k["matching_units"] and k["matching_units"][0].get("following") == "followed"
|
|
3997
|
+
and k["matching_units"][0]["unit_id"] == want_returned[claims_known[0]][0] for k in c0_kept),
|
|
3998
|
+
f"{[sorted(k) for k in c0_kept]}")
|
|
3999
|
+
after = {r["candidate_id"]: (r["diagnosis"], r["row"]) for r in rc.get("reconsidered", [])}
|
|
4000
|
+
control("J3c (O4): a gap claim contradicted by a unit only one sweep flagged is reconsidered by both judges - "
|
|
4001
|
+
"both now matching, it is no gap; one only, it is disputed; neither, the gap stands",
|
|
4002
|
+
after.get(claims_known[0], ("gap",))[0] not in ("gap", "unknown")
|
|
4003
|
+
and after.get(claims_known[1]) == ("unknown", derive.DISPUTED)
|
|
4004
|
+
and after.get(claims_known[2], ("",))[0] == "gap" and not rc.get("missing"), f"{after}")
|
|
4005
|
+
held_a = kept_rc[(claims_known[1], "A")].get("judgment")
|
|
4006
|
+
held_b = kept_rc[(claims_known[1], "B")].get("judgment")
|
|
4007
|
+
if held_a and held_b:
|
|
4008
|
+
returned_1 = want_returned[claims_known[1]]
|
|
4009
|
+
named("control (done-when 3): a claim missing Judge B's reconsideration is RECONSIDERATION_MISSING",
|
|
4010
|
+
reconsideration_problems(claims_known[1], returned_1, {"A": held_a}), "RECONSIDERATION_MISSING")
|
|
4011
|
+
named("control: a reconsideration judging fewer units than were returned is RECONSIDERATION_MISSING",
|
|
4012
|
+
reconsideration_problems(claims_known[1], returned_1,
|
|
4013
|
+
{"A": held_a, "B": {**held_b, "units": held_b["units"][1:]}}),
|
|
4014
|
+
"RECONSIDERATION_MISSING")
|
|
4015
|
+
control("J3c: both judges reconsidering every returned unit is no problem",
|
|
4016
|
+
not reconsideration_problems(claims_known[1], returned_1, {"A": held_a, "B": held_b}))
|
|
4017
|
+
# a claim whose cross-review returns nothing keeps its gap without a call
|
|
4018
|
+
c2 = claims_known[2]
|
|
4019
|
+
quiet = root / "nothing-returned"
|
|
4020
|
+
(quiet / "cross_review").mkdir(parents=True, exist_ok=True)
|
|
4021
|
+
(quiet / cross_rel(item_of(c2))).write_text(json.dumps({**crossed_kept[c2], "partial_flags": [], "verdicts": [
|
|
4022
|
+
{**v, "situation": "no", "action": "no"} for v in crossed_kept[c2].get("verdicts", [])]}), encoding="utf-8")
|
|
4023
|
+
firsts = {who: guarded(lambda who=who: records.read_json(whole / judgment_rel(item_of(c2), who))["judgment"], {})
|
|
4024
|
+
for who in ("A", "B")}
|
|
4025
|
+
quiet_section = guarded(lambda: reconsider_stage(
|
|
4026
|
+
quiet, None, None, None, {"packets": [{"candidate_id": c2, "source": pop_b[c2]["source"]}], "seats": {}, "limits": {}},
|
|
4027
|
+
{c2: whole_packets[c2]}, {c2: firsts}, {"reviewed": [c2]}, {}, "calibration"), lambda e: ({"problem": repr(e)}, []))
|
|
4028
|
+
control("J3c: a claim its cross-review returns nothing for keeps its gap, with no reconsideration call",
|
|
4029
|
+
quiet_section[0].get("reconsidered") == [{"candidate_id": c2, "returned": 0, "diagnosis": "gap",
|
|
4030
|
+
"row": quiet_section[0]["reconsidered"][0]["row"]}]
|
|
4031
|
+
and not quiet_section[0].get("calls") and not quiet_section[1] if quiet_section[0].get("reconsidered")
|
|
4032
|
+
else False, f"{quiet_section[0]}")
|
|
4033
|
+
# ---- the derivations (J4a) ----------------------------------------------------------------------------
|
|
4034
|
+
dv = guarded(lambda: records.read_json(whole / DERIVATIONS), {})
|
|
4035
|
+
verd = dv.get("verdicts", {})
|
|
4036
|
+
judged_whole = sorted(whole_packets)
|
|
4037
|
+
admitted_of = {c: v["outcome"]["admission"] for c, v in verd.items()}
|
|
4038
|
+
uncertain_c, unmet_c = (list(planted_marks) + [None, None])[:2]
|
|
4039
|
+
control("J4a (done-when 2, O4): both judges uncertain on a requirement is disputed, not admitted; both unmet "
|
|
4040
|
+
"is rejected; both met on every requirement is admitted",
|
|
4041
|
+
len(planted_marks) == 2 and admitted_of.get(uncertain_c) == {"admission": "disputed", "row": "disputed"}
|
|
4042
|
+
and admitted_of.get(unmet_c, {}).get("admission") == "rejected"
|
|
4043
|
+
and all(a == {"admission": "admitted", "row": "admitted"} for c, a in admitted_of.items()
|
|
4044
|
+
if c not in planted_marks) and len(admitted_of) > 2, f"{planted_marks} {admitted_of}")
|
|
4045
|
+
control("J4a: every candidate both judges judged is derived, and no other",
|
|
4046
|
+
sorted(verd) == judged_whole and not dv.get("not_derived"), f"{len(verd)} {len(judged_whole)}")
|
|
4047
|
+
firsts_w = {c: {who: guarded(lambda c=c, who=who: records.read_json(
|
|
4048
|
+
whole / judgment_rel(item_of(c), who))["judgment"], {}) for who in ("A", "B")} for c in judged_whole}
|
|
4049
|
+
control("J4a: a derivation reads both judges' requirement marks from their first judgments and the "
|
|
4050
|
+
"candidate's lineages from S5's recurrence count",
|
|
4051
|
+
all(verd.get(c, {}).get("requirements", {}).get(who) == {n: m["mark"] for n, m in
|
|
4052
|
+
firsts_w[c][who].get("requirements", {}).items()}
|
|
4053
|
+
and firsts_w[c][who].get("requirements") for c in judged_whole for who in ("A", "B"))
|
|
4054
|
+
and all(verd.get(c, {}).get("lineages") == (whole_rows[c].get("recurrence") or {}).get("count")
|
|
4055
|
+
for c in judged_whole) and any(verd.get(c, {}).get("lineages") for c in judged_whole),
|
|
4056
|
+
"")
|
|
4057
|
+
after_rc = {r["candidate_id"]: r["diagnosis"] for r in rc.get("reconsidered", [])}
|
|
4058
|
+
control("J4a: a reconsidered absence claim is derived with its reconsidered units - its current diagnosis is "
|
|
4059
|
+
"the reconsideration's", after_rc and all(
|
|
4060
|
+
verd.get(c, {}).get("outcome", {}).get("candidate_diagnosis", {}).get("current", {}).get("diagnosis")
|
|
4061
|
+
== d for c, d in after_rc.items()), f"{after_rc}")
|
|
4062
|
+
control("J4a: no release point is judged, so every derivation's release diagnosis is unknown by `absent`, it "
|
|
4063
|
+
"has no unit outcome, and it names its test state",
|
|
4064
|
+
verd and all(v["outcome"]["candidate_diagnosis"]["release"] == {"diagnosis": "unknown", "row": "absent",
|
|
4065
|
+
"absence": None}
|
|
4066
|
+
and v["outcome"]["unit_outcomes"] == [] and v["outcome"]["test"] == "untested: s8_deferred"
|
|
4067
|
+
for v in verd.values()))
|
|
4068
|
+
want_pairs = 0
|
|
4069
|
+
for c in judged_whole:
|
|
4070
|
+
pairs_c = {}
|
|
4071
|
+
for who in ("A", "B"):
|
|
4072
|
+
for u in firsts_w[c][who].get("units", []):
|
|
4073
|
+
pairs_c.setdefault(u["unit_id"], {})[who] = u
|
|
4074
|
+
again_c = guarded(lambda c=c, who=who: records.read_json(
|
|
4075
|
+
whole / reconsideration_rel(item_of(c), who))["judgment"], {})
|
|
4076
|
+
for u in again_c.get("units", []):
|
|
4077
|
+
pairs_c.setdefault(u["unit_id"], {})[who] = u
|
|
4078
|
+
matched_c = [u for u, pr in pairs_c.items() if derive.unit_diagnosis(
|
|
4079
|
+
derive.agreed(pr.get("A", {}).get("situation"), pr.get("B", {}).get("situation")),
|
|
4080
|
+
derive.agreed(pr.get("A", {}).get("action"), pr.get("B", {}).get("action"))) != "no match"]
|
|
4081
|
+
want_pairs += len(pop_b[c].get("sessions") or []) * len(matched_c)
|
|
4082
|
+
control("J4a (D3): delivery is not read; every (session, unit) pair a matching unit would need is counted as "
|
|
4083
|
+
"delivery_assembly_waiting", dv.get("delivery", {}).get("state") == "delivery_assembly_waiting"
|
|
4084
|
+
and dv.get("delivery", {}).get("pairs") == want_pairs and want_pairs > 0,
|
|
4085
|
+
f"{dv.get('delivery')} {want_pairs}")
|
|
4086
|
+
control("J4a: the derivations say by name that no unit outcome is derived, why, and for how many candidates",
|
|
4087
|
+
dv.get("unit_outcomes", {}).get("state") == "none"
|
|
4088
|
+
and dv.get("unit_outcomes", {}).get("candidates") == len(verd) and len(verd) > 0
|
|
4089
|
+
and "D-20261111-c4fa71" in dv.get("unit_outcomes", {}).get("why", "")
|
|
4090
|
+
and fourth.get("derivations", {}).get("unit_outcomes") == dv.get("unit_outcomes"),
|
|
4091
|
+
f"{dv.get('unit_outcomes')}")
|
|
4092
|
+
g_ids = sorted(c for c in verd if pop_b[c].get("type") in G_TYPES)
|
|
4093
|
+
bar_g = next(r for r in derive.table()["promotion"] if r["id"] == "type_g")["independent_lineages_at_least"]
|
|
4094
|
+
arc = dv.get("arc_confirmation", {})
|
|
4095
|
+
control("J4a (D-20261111-f122c0): every type G verdict says its arc confirmation is undetermined, no other "
|
|
4096
|
+
"verdict does, and the derivations count the G candidates and those below the lineage bar",
|
|
4097
|
+
g_ids and all(verd[c].get("arc_confirmation") == "undetermined" for c in g_ids)
|
|
4098
|
+
and not any("arc_confirmation" in v for c, v in verd.items() if c not in g_ids)
|
|
4099
|
+
and arc.get("state") == "undetermined" and arc.get("passed_as") is False
|
|
4100
|
+
and arc.get("g_candidates") == len(g_ids)
|
|
4101
|
+
and arc.get("g_below_lineage_bar") == sum(1 for c in g_ids if verd[c]["lineages"] < bar_g),
|
|
4102
|
+
f"{arc} {g_ids}")
|
|
4103
|
+
# N#1 over the reconsiderations (J3c): the check that reads their receipts, and what the run handed it
|
|
4104
|
+
accepted_rc = sum(1 for r in rc.get("calls", []) for h in r["seats"].values() if h["outcome"] == "accepted")
|
|
4105
|
+
control("J3c (N#1): the run holds every accepted reconsideration's receipt to N#1 - the receipts it checked "
|
|
4106
|
+
"count each accepted reconsideration call once", accepted_rc > 0
|
|
4107
|
+
and fourth.get("receipts_checked", {}).get("reconsider") == accepted_rc
|
|
4108
|
+
and fourth.get("receipts_checked", {}).get("cross") == len(cr.get("calls", [])),
|
|
4109
|
+
f"{fourth.get('receipts_checked')} {accepted_rc}")
|
|
4110
|
+
pair_rc = []
|
|
4111
|
+
for who in ("A", "B"):
|
|
4112
|
+
call_rc = kept_rc[(claims_known[1], who)].get("call_id")
|
|
4113
|
+
held_rc = guarded(lambda call_rc=call_rc: records.read_json(whole / "calls" / call_rc / "receipt.json"), {})
|
|
4114
|
+
pair_rc.append((f"reconsider/{claims_known[1]}", who, call_rc, held_rc,
|
|
4115
|
+
kept_rc[(claims_known[1], who)].get("payload_sha256")))
|
|
4116
|
+
control("J3c (N#1): the kept reconsiderations' receipt pair passes the check that reads it",
|
|
4117
|
+
all(r[3] for r in pair_rc) and not stage_receipts(pair_rc), f"{stage_receipts(pair_rc)}")
|
|
4118
|
+
moved_rc = [pair_rc[0], (*pair_rc[1][:3], {**pair_rc[1][3], "evidence": {
|
|
4119
|
+
**(pair_rc[1][3].get("evidence") or {}), "payload_sha256": "0" * 64}}, pair_rc[1][4])]
|
|
4120
|
+
named("control (N#1): a reconsideration's two receipts carrying different payload hashes is "
|
|
4121
|
+
"PACKET_DIVERGENCE", stage_receipts(moved_rc), "PACKET_DIVERGENCE")
|
|
4122
|
+
control("J3c: a receipt missing from the list is not something the check can see - receipt_counts says what "
|
|
4123
|
+
"it held", receipt_counts(pair_rc[:1]).get("reconsider") == 1 and not stage_receipts(pair_rc[:1]))
|
|
4124
|
+
some = next(iter(sorted(kept_sw)), None)
|
|
4125
|
+
if some is not None:
|
|
4126
|
+
said = refusal(lambda: kept_sweep(whole, sweep_rel(*some), "0" * 64))
|
|
4127
|
+
control("control (done-when 6): a sweep result cut from another inventory is SWEEP_INVENTORY_MOVED",
|
|
4128
|
+
said.startswith("SWEEP_INVENTORY_MOVED"), said[:200])
|
|
4129
|
+
# a shard's packet, its answer checked, its plan's set accounting, a lifecycle candidate's view
|
|
4130
|
+
plan_w = shard_plan(want, 2, 2)
|
|
4131
|
+
# a shard where one candidate lacks a unit another has, so E3's unlisted pair can be planted
|
|
4132
|
+
first_shard = next((sh for g in plan_w for sh in g["shards"] if len(sh["pairs"]) > 1
|
|
4133
|
+
and any(len(us) < len(sh["units"]) for us in sh["pairs"].values())),
|
|
4134
|
+
next(sh for g in plan_w for sh in g["shards"] if sh["pairs"]))
|
|
4135
|
+
pop_w = {k["candidate_id"]: k for k in records.read_json(whole / "checked-candidates.json")["candidates"]}
|
|
4136
|
+
units_w = {u["unit_id"]: u for u in records.read_json(whole / "inventory" / "current.json")["units"]}
|
|
4137
|
+
labels_w = guarded(lambda: SweepLabels(first_shard, pop_w, units_w, whole_packets[next(iter(whole_packets))][0].entry_store),
|
|
4138
|
+
lambda e: e)
|
|
4139
|
+
if isinstance(labels_w, Exception):
|
|
4140
|
+
failures.append(f"J3a: a sweep packet could not be labelled: {labels_w!r}")
|
|
4141
|
+
else:
|
|
4142
|
+
good = {"pairs": [{"candidate": k, "unit": u, "situation": "no", "action": "no", "reason": "unrelated"}
|
|
4143
|
+
for k, u in sorted(labels_w.listed)]}
|
|
4144
|
+
control("J3a: a sweep answer judging exactly the listed pairs passes", not sweep_problems(labels_w, good),
|
|
4145
|
+
f"{sweep_problems(labels_w, good)}")
|
|
4146
|
+
k0, u0 = sorted(labels_w.listed)[0]
|
|
4147
|
+
unlisted = next(((k, u) for k in labels_w.candidates for u in labels_w.units if (k, u) not in labels_w.listed),
|
|
4148
|
+
None)
|
|
4149
|
+
cases = [("a listed pair left out", {"pairs": good["pairs"][1:]}, "SWEEP_PAIR_MISSING"),
|
|
4150
|
+
("a pair judged twice", {"pairs": good["pairs"] + good["pairs"][:1]}, "SWEEP_PAIR_TWICE"),
|
|
4151
|
+
("a label the packet does not show", {"pairs": good["pairs"] + [{**good["pairs"][0], "unit": "n99"}]},
|
|
4152
|
+
"UNKNOWN_LABEL")]
|
|
4153
|
+
if unlisted is not None:
|
|
4154
|
+
cases.append(("a pair the packet does not list", {"pairs": good["pairs"] + [
|
|
4155
|
+
{**good["pairs"][0], "candidate": unlisted[0], "unit": unlisted[1]}]}, "SWEEP_PAIR_UNLISTED"))
|
|
4156
|
+
for name, answer, code in cases:
|
|
4157
|
+
named(f"control: {name} is refused by name", sweep_problems(labels_w, answer), code)
|
|
4158
|
+
control("control: the sweep packet names an unlisted pair to plant (E3 has one to refuse)", unlisted is not None)
|
|
4159
|
+
control("J3a: a sweep payload is bound to its inventory - another inventory hash is another payload",
|
|
4160
|
+
sweep_payload(labels_w, "a" * 64) != sweep_payload(labels_w, "b" * 64))
|
|
4161
|
+
shifted = json.loads(json.dumps(plan_w))
|
|
4162
|
+
g0 = shifted[0]
|
|
4163
|
+
c0 = next(c for c in g0["candidates"] if any(c in sh["pairs"] for sh in g0["shards"]))
|
|
4164
|
+
sh0 = next(sh for sh in g0["shards"] if c0 in sh["pairs"])
|
|
4165
|
+
for name, change, code in (
|
|
4166
|
+
("a remaining unit in two shards", lambda: g0["shards"][-1]["pairs"].setdefault(c0, []).append(sh0["pairs"][c0][0]),
|
|
4167
|
+
"SET_MISMATCH sweep g001"),
|
|
4168
|
+
("a remaining unit in no shard", lambda: sh0["pairs"][c0].pop(), "SET_MISMATCH sweep g001"),
|
|
4169
|
+
("a candidate in two groups", lambda: shifted[-1]["candidates"].append(c0), "SET_MISMATCH sweep groups")):
|
|
4170
|
+
shifted = json.loads(json.dumps(plan_w))
|
|
4171
|
+
g0 = shifted[0]
|
|
4172
|
+
sh0 = next(sh for sh in g0["shards"] if c0 in sh["pairs"])
|
|
4173
|
+
change()
|
|
4174
|
+
named(f"control (done-when 6): {name} is refused by the set accounting", shard_problems(shifted, want), code)
|
|
4175
|
+
control("J3a: the plan's set accounting passes", not shard_problems(plan_w, want), f"{shard_problems(plan_w, want)}")
|
|
4176
|
+
said = refusal(lambda: sweep_seats({"seats": {"S6.sweep_a": "claude:claude-sonnet-5-5/medium"}}))
|
|
4177
|
+
control("control: a declaration without the OpenAI-side sweep's seat is SEAT_UNDECLARED",
|
|
4178
|
+
said.startswith("SEAT_UNDECLARED"), said)
|
|
4179
|
+
lifecycle_w = next((k for k in pop_w.values() if k["source"] == "legacy"), None)
|
|
4180
|
+
if lifecycle_w is not None:
|
|
4181
|
+
shown_w = guarded(lambda: sweep_view(lifecycle_w, {}, units_w), {})
|
|
4182
|
+
held_w = guarded(lambda: sweep_view(lifecycle_w, labels_w.entry_store, units_w), {})
|
|
4183
|
+
control("J3a: a lifecycle candidate is shown with the texts of the entries it names; a name the stores do "
|
|
4184
|
+
"not hold is counted, as S5 counts one", shown_w.get("entry_texts") == [] and shown_w.get("names_not_held", 0) >= 1
|
|
4185
|
+
and held_w.get("entry_texts") and held_w.get("names_not_held") == 0
|
|
4186
|
+
and not set(held_w) & (set(LIFECYCLE_NAMED) - {"source"}), f"{shown_w} {held_w}")
|
|
4187
|
+
# the absence rule itself: a judge missing, and a unit the judges disagree on
|
|
4188
|
+
one_side = {"k-x": {"A": {"units": []}}}
|
|
4189
|
+
control("J3a: a candidate either judge did not judge is not swept, and is named",
|
|
4190
|
+
guarded(lambda: absent_candidates(["k-x"], one_side, {"k-x": "formed"}), None) == ([], ["k-x"]))
|
|
4191
|
+
split = {"k-y": {"A": {"units": [{"unit_id": "u", "situation": "yes", "action": "yes"}]},
|
|
4192
|
+
"B": {"units": [{"unit_id": "u", "situation": "no", "action": "no"}]}}}
|
|
4193
|
+
control("J3a: a candidate whose only unit the judges disagree on is no absence claim (the disputed unit could "
|
|
4194
|
+
"cover it)", guarded(lambda: absent_candidates(["k-y"], split, {"k-y": "formed"}), None) == ([], []))
|
|
4195
|
+
agreed_no = {"k-z": {w: {"units": [{"unit_id": "u", "situation": "no", "action": "no"}]} for w in ("A", "B")}}
|
|
4196
|
+
control("J3a: a candidate both judges find no unit matching is an absence claim",
|
|
4197
|
+
guarded(lambda: absent_candidates(["k-z"], agreed_no, {"k-z": "formed"}), None) == (["k-z"], []))
|
|
4198
|
+
token = os.environ.pop("CLAUDE_RUN_TOKEN_FILE", None)
|
|
4199
|
+
try:
|
|
4200
|
+
said = refusal(lambda: supervisor(tight, root / "cells-4"))
|
|
4201
|
+
finally:
|
|
4202
|
+
if token is not None:
|
|
4203
|
+
os.environ["CLAUDE_RUN_TOKEN_FILE"] = token
|
|
4204
|
+
control("control: a live supervisor without CLAUDE_RUN_TOKEN_FILE is TOKEN_FILE_UNSET", said.startswith(
|
|
4205
|
+
"TOKEN_FILE_UNSET S6"), said)
|
|
4206
|
+
finally:
|
|
4207
|
+
shutil.rmtree(root, ignore_errors=True)
|
|
4208
|
+
|
|
4209
|
+
for failure in failures:
|
|
4210
|
+
print(f"stage_judge --self-test [FAIL] {failure}")
|
|
4211
|
+
if failures:
|
|
4212
|
+
return 1
|
|
4213
|
+
print(f"stage_judge --self-test: OK ({len(ran)} controls: done-when 8's two halves - the judgment schema's fields "
|
|
4214
|
+
"against §6.2's both ways and the reuse key's components against §6.2's, each with a planted drift; D12's key "
|
|
4215
|
+
"per candidate, unit and seat, changed by each component; done-when 1's one payload and one receipt per call "
|
|
4216
|
+
"with PACKET_DIVERGENCE and RECEIPT_STALE planted; D14's quotes and every unit, matching unit and ledger entry "
|
|
4217
|
+
"judged once, each refusal planted; D11's classes from the schema's enum; the judged scope and S5's check "
|
|
4218
|
+
"failures; the packet (a1_min) and the dry stage over a golden run through S5 - labels only, the enclosing line "
|
|
4219
|
+
"whole and the mentioned file by heading and count, F27's packet check with its planted field and frame, "
|
|
4220
|
+
"EDGES_ABSENT, JUDGE_UNSUPERVISED and INPUT_INVALID S5; the calls (J2) through the golden hosts - both judges per "
|
|
4221
|
+
"candidate, done-when 5's replayed undeclared instruction failed, a unit left unjudged failed by name, the "
|
|
4222
|
+
"re-run reusing every accepted attempt, one payload and one packet per receipt with RECEIPT_STALE and "
|
|
4223
|
+
"PACKET_DIVERGENCE planted, JUDGE_OVER_CAPACITY and TOKEN_FILE_UNSET; done-when 4's decidable halves - no "
|
|
4224
|
+
"reuse across runs, and A's judgment never answering B; the absence sweeps (J3a) - nothing swept at an "
|
|
4225
|
+
"incomplete reference point, the dry upper bound, the absence claims, every remaining unit judged once by each "
|
|
4226
|
+
"sweep, one payload bound to the inventory, the re-run reused, SWEEP_INVENTORY_MOVED, the pair and set "
|
|
4227
|
+
"accounting refusals planted, a sweep answer missing a pair failed by name, SEAT_UNDECLARED, a lifecycle "
|
|
4228
|
+
"candidate's named texts with the names not held counted; Judge B's cross-review (J3b) - every flag and the "
|
|
4229
|
+
"drawn fifty, another seed another sample, CROSS_REVIEW_INCOMPLETE and CROSS_REVIEW_STALE planted, a review "
|
|
4230
|
+
"missing a unit failed by name, the re-run reusing the rest; the reconsiderations (J3c) - the returned set "
|
|
4231
|
+
"both ways, one payload for both judges, contradicted, disputed and standing claims, RECONSIDERATION_MISSING "
|
|
4232
|
+
"planted and run, a claim with nothing returned; the reconsideration's units-only shape - its schema the judge "
|
|
4233
|
+
"schema's projection with drift planted both ways, candidate-level fields refused by the schema in a run and "
|
|
4234
|
+
"by FIELD_UNEXPECTED, the unit rules in the judgment packet's own words; the derivations (J4a) - done-when 2's "
|
|
4235
|
+
"disputed, rejected and admitted, every judged candidate derived, the marks and lineages read, the reconsidered "
|
|
4236
|
+
"diagnosis carried, no release point, the delivery pairs counted as waiting, an unfinished claim named, no unit "
|
|
4237
|
+
"outcome said by name, the type G arc confirmation undetermined and counted, the reconsiderations' receipts held "
|
|
4238
|
+
"to N#1 and counted, a run with no S6 budget refused before any call; design §3.2's ten gate controls (J4b) - "
|
|
4239
|
+
"planted on copies of an accepted A and B call by host, each rejected by its code, sealed again, the originals "
|
|
4240
|
+
"accepted, read by controls.evaluate)")
|
|
4241
|
+
return 0
|
|
4242
|
+
|
|
4243
|
+
|
|
4244
|
+
if __name__ == "__main__":
|
|
4245
|
+
if sys.argv[1:] == ["--self-test"]:
|
|
4246
|
+
sys.exit(self_test())
|
|
4247
|
+
print("usage: stage_judge.py --self-test (the stage runs as `distill.py judge --run-id ID`)", file=sys.stderr)
|
|
4248
|
+
sys.exit(2)
|