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,838 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""The packet a model call is sent, and the linter every packet passes before dispatch.
|
|
3
|
+
|
|
4
|
+
A dispatched packet is the per-call envelope followed by the judgment payload:
|
|
5
|
+
|
|
6
|
+
CALL-ID: <call_id>
|
|
7
|
+
STAGE: <stage>
|
|
8
|
+
SEAT: <provider:model/effort>
|
|
9
|
+
SCHEMA: sha256:<hex of schema.json> | none
|
|
10
|
+
PRINCIPLES: sha256:<hex of the principles block>
|
|
11
|
+
|
|
12
|
+
<the principles block>
|
|
13
|
+
=== PAYLOAD ===
|
|
14
|
+
<the payload>
|
|
15
|
+
|
|
16
|
+
`packet_sha256` (the receipt's) hashes the whole packet and is unique per call, since the
|
|
17
|
+
envelope carries the call id; `payload_sha256` hashes the payload alone and is what two calls
|
|
18
|
+
of one judgment share, so a judgment-reuse key is computed over the payload and never over
|
|
19
|
+
the envelope.
|
|
20
|
+
|
|
21
|
+
The principles block carries what a hermetic reader cannot load (plan P9): concept economy,
|
|
22
|
+
the LLM/capability boundary, the staged workflow, verification discipline and the
|
|
23
|
+
mock/realization boundary. Each summary is taken from the guide that owns it — its frontmatter
|
|
24
|
+
`core_rules`, or, for the staged-workflow guide, which declares none, its `## Stages` list — so
|
|
25
|
+
nothing here restates a guide, and the block's hash says which version a packet carried.
|
|
26
|
+
|
|
27
|
+
The schema a call is given is compiled through `validate.compile_schema` (closed objects,
|
|
28
|
+
supported keywords) before it is written, so a packet never references a schema the policy
|
|
29
|
+
refuses. The form a host is handed holds only keywords the host's draft-07 check and the policy's
|
|
30
|
+
2020-12 reading read alike (HOST_KEYWORDS); any other is HOST_SCHEMA_KEYWORD.
|
|
31
|
+
|
|
32
|
+
A stage's payload is one of the templates under `session-distill/packets/` (`read.md`, `stitch.md`)
|
|
33
|
+
with its `{{field}}` placeholders filled by `render`, once and in one pass: every placeholder takes
|
|
34
|
+
exactly one field, no field is left over, and a field's text is never read as a template, so a
|
|
35
|
+
transcript quoting `{{window}}` stays text.
|
|
36
|
+
|
|
37
|
+
Linter failures are named CALL_ID_MISSING, PRINCIPLES_MISSING, SCHEMA_REFERENCE_MISSING and
|
|
38
|
+
PAYLOAD_MISSING; a guide without its section is PRINCIPLES_UNAVAILABLE; a template that is not there,
|
|
39
|
+
or fields that are not its placeholders, are TEMPLATE_UNAVAILABLE and TEMPLATE_FIELDS_MISMATCH.
|
|
40
|
+
|
|
41
|
+
packet.py --self-test
|
|
42
|
+
"""
|
|
43
|
+
import hashlib
|
|
44
|
+
import json
|
|
45
|
+
import pathlib
|
|
46
|
+
import re
|
|
47
|
+
import sys
|
|
48
|
+
|
|
49
|
+
if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
|
|
50
|
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
51
|
+
from runlib import validate
|
|
52
|
+
|
|
53
|
+
REPO = pathlib.Path(__file__).resolve().parents[2]
|
|
54
|
+
PAYLOAD_MARKER = "=== PAYLOAD ==="
|
|
55
|
+
TEMPLATE_DIR = pathlib.Path(__file__).resolve().parents[1] / "packets"
|
|
56
|
+
TEMPLATES = ("read", "stitch", "form", "judge", "sweep", "cross_review", "reconsider") # S3's two calls (plan WP-08), S4's one (plan WP-09), S6's judges', sweeps', cross-review and reconsiderations (plan WP-11)
|
|
57
|
+
WINDOW_TEMPLATES = ("read", "stitch") # the calls whose fixed part the view windows were cut to leave room for
|
|
58
|
+
PLACEHOLDER = re.compile(r"\{\{([a-z_]+)\}\}")
|
|
59
|
+
# (summary title, owning guide, the part of it that is the summary)
|
|
60
|
+
PRINCIPLE_SOURCES = (
|
|
61
|
+
("Concept economy", "claude/guides/concept-economy.md", "core_rules"),
|
|
62
|
+
("LLM and capability boundary", "claude/guides/llm-capability-boundary.md", "core_rules"),
|
|
63
|
+
("Staged workflow", "claude/guides/coding-staged-workflow.md", "## Stages"),
|
|
64
|
+
("Verification discipline", "claude/guides/verification-discipline.md", "core_rules"),
|
|
65
|
+
("Mock and realization boundary", "claude/guides/mock-realization-boundary.md", "core_rules"),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Unavailable(Exception):
|
|
70
|
+
"""A guide lacks the section its summary is taken from; the message starts with PRINCIPLES_UNAVAILABLE."""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class TemplateError(Exception):
|
|
74
|
+
"""A payload template is missing or was given other fields than its placeholders; the message starts with
|
|
75
|
+
TEMPLATE_UNAVAILABLE or TEMPLATE_FIELDS_MISMATCH."""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def sha256_bytes(data):
|
|
79
|
+
return hashlib.sha256(data).hexdigest()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def summary(text, part, where):
|
|
83
|
+
"""The lines of `part` in one guide's text: a frontmatter list, or the body under a heading."""
|
|
84
|
+
if part.startswith("## "):
|
|
85
|
+
body = text.split(f"\n{part}\n", 1)[1].split("\n## ", 1)[0] if f"\n{part}\n" in text else ""
|
|
86
|
+
lines = body.splitlines()
|
|
87
|
+
else:
|
|
88
|
+
front = text.split("\n---", 1)[0] if text.startswith("---\n") else ""
|
|
89
|
+
block = re.search(rf"^{re.escape(part)}:\n((?: - .*\n?)+)", front + "\n", re.M)
|
|
90
|
+
lines = ["- " + line[4:] for line in block.group(1).splitlines()] if block else []
|
|
91
|
+
lines = [line for line in lines if line.strip()]
|
|
92
|
+
if not lines:
|
|
93
|
+
raise Unavailable(f"PRINCIPLES_UNAVAILABLE {where}: no {part!r} to summarize")
|
|
94
|
+
return "\n".join(lines)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def principles_block(repo=REPO):
|
|
98
|
+
texts = {}
|
|
99
|
+
for _title, guide, _part in PRINCIPLE_SOURCES:
|
|
100
|
+
try:
|
|
101
|
+
texts[guide] = (pathlib.Path(repo) / guide).read_text(encoding="utf-8")
|
|
102
|
+
except OSError as exc:
|
|
103
|
+
raise Unavailable(f"PRINCIPLES_UNAVAILABLE {guide}: {exc}") from exc
|
|
104
|
+
return "\n\n".join(["# Working principles (the instructions you do not load)"]
|
|
105
|
+
+ [f"## {title} ({guide})\n{summary(texts[guide], part, guide)}"
|
|
106
|
+
for title, guide, part in PRINCIPLE_SOURCES]) + "\n"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def host_schema(schema):
|
|
110
|
+
"""The schema a host is handed, derived from `schema` by code and never written by hand (WP-08 commit 7, dw2-live1):
|
|
111
|
+
no `$schema`, every `$ref` replaced by a copy of the `$defs` entry it names, and no `$defs`.
|
|
112
|
+
|
|
113
|
+
Claude Code's `--json-schema` check builds Ajv's draft-07 class, which refuses a schema naming a meta-schema it does
|
|
114
|
+
not hold - the 2020-12 one every distill schema names - and exits before any request; and the host hands the schema
|
|
115
|
+
on as a tool's input schema, which then holds no reference to resolve. The policy pins draft 2020-12 in code
|
|
116
|
+
(`validate.compile_schema`) and allows a `$ref` only to an entry of the schema's own `$defs` (`validate.lint`), so
|
|
117
|
+
neither key decides anything the inlined form does not. A `$ref` beside other keywords, one that reaches itself, or
|
|
118
|
+
one naming no entry of `$defs` has no inlined form and is refused. A reference's name is read by
|
|
119
|
+
`validate.local_ref_name`, as the policy's lint reads it: a name of letters, digits, `_` and `-` only, which a JSON
|
|
120
|
+
Pointer resolves as written, so nothing is decoded here (WP-08c, W r2).
|
|
121
|
+
|
|
122
|
+
The schema is walked by its structure, as `host_keywords` walks it (WP-08c, X and W r1): a reference is a `$ref` at
|
|
123
|
+
a schema position, and the schemas inside are the values under `properties` and `patternProperties` by name and
|
|
124
|
+
the schema `items` or `additionalProperties` holds. A property named `$ref` is a name, and an `enum`, `const`,
|
|
125
|
+
`default` or `examples` value is data, kept as written: a literal `{"$ref": ...}` there is not a reference, and
|
|
126
|
+
inlining it would hand the host a schema that accepts other answers. Any other keyword's value is kept as written
|
|
127
|
+
too, and `host_keywords` then refuses the keyword by name."""
|
|
128
|
+
defs = schema.get("$defs") or {}
|
|
129
|
+
|
|
130
|
+
def inline(node, seen):
|
|
131
|
+
if not isinstance(node, dict):
|
|
132
|
+
return node # a boolean schema, or `items` as a list, which `host_keywords` refuses
|
|
133
|
+
if "$ref" in node:
|
|
134
|
+
ref = node["$ref"]
|
|
135
|
+
name = validate.local_ref_name(ref)
|
|
136
|
+
if set(node) != {"$ref"}:
|
|
137
|
+
raise validate.SchemaPolicyError(f"HOST_SCHEMA {ref}: a $ref beside {sorted(set(node) - {'$ref'})} has no inlined form")
|
|
138
|
+
if name is None:
|
|
139
|
+
raise validate.SchemaPolicyError(f"HOST_SCHEMA {ref}: a reference is {validate.LOCAL_REF}<name>, its name read "
|
|
140
|
+
"as written (validate.local_ref_name)")
|
|
141
|
+
if name not in defs:
|
|
142
|
+
raise validate.SchemaPolicyError(f"HOST_SCHEMA {ref}: the reference names no entry of $defs")
|
|
143
|
+
if name in seen:
|
|
144
|
+
raise validate.SchemaPolicyError(f"HOST_SCHEMA {ref}: the reference reaches itself")
|
|
145
|
+
return inline(defs[name], seen | {name})
|
|
146
|
+
out = {}
|
|
147
|
+
for key, value in node.items():
|
|
148
|
+
if key in SUBSCHEMA_MAPS and isinstance(value, dict):
|
|
149
|
+
out[key] = {name: inline(sub, seen) for name, sub in value.items()}
|
|
150
|
+
elif key in SUBSCHEMAS:
|
|
151
|
+
out[key] = inline(value, seen)
|
|
152
|
+
else:
|
|
153
|
+
out[key] = value
|
|
154
|
+
return out
|
|
155
|
+
return inline({key: value for key, value in schema.items() if key not in ("$schema", "$defs")}, frozenset())
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# The keywords a schema handed to a host may hold (WP-08c): of those the distill schemas use, the ones Claude Code's
|
|
159
|
+
# `--json-schema` check (Ajv 8's draft-07 class, as Claude Code 2.1.317 configures it) and the policy's draft 2020-12
|
|
160
|
+
# reading read alike. Measured offline with Ajv 8.20.0 (record 2026-11-06T0055--3809707): each of these compiles; a
|
|
161
|
+
# 2019-09 or 2020-12 keyword (dependentRequired, dependentSchemas, prefixItems, unevaluatedProperties) is refused as
|
|
162
|
+
# unknown. `$defs`, `$ref` and `$schema` are not here because the handed form has none (`host_schema`), and `items` is
|
|
163
|
+
# here as one schema only: as a list, draft-07 reads a tuple and 2020-12 refuses the schema.
|
|
164
|
+
HOST_KEYWORDS = frozenset({"$comment", "title", "type", "properties", "patternProperties", "additionalProperties",
|
|
165
|
+
"required", "items", "enum", "const", "pattern", "minLength", "minimum", "minItems", "maxItems",
|
|
166
|
+
"uniqueItems", "minProperties"})
|
|
167
|
+
# keywords whose value is a map of names to schemas, or one schema; every other keyword's value is data
|
|
168
|
+
SUBSCHEMA_MAPS, SUBSCHEMAS = ("properties", "patternProperties"), ("items", "additionalProperties")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def host_keywords(schema, at="#"):
|
|
172
|
+
"""`[(pointer, keyword)]` of what a schema handed to a host must not hold: every keyword outside HOST_KEYWORDS, and
|
|
173
|
+
`items` as a list. Walked by the schema's structure, so a property named `items` or `required` under `properties` is
|
|
174
|
+
a name, not a keyword, and an `enum` or `const` value is data."""
|
|
175
|
+
out = []
|
|
176
|
+
if not isinstance(schema, dict):
|
|
177
|
+
return out
|
|
178
|
+
for key, value in schema.items():
|
|
179
|
+
if key not in HOST_KEYWORDS or (key == "items" and isinstance(value, list)):
|
|
180
|
+
out.append((at, key))
|
|
181
|
+
continue
|
|
182
|
+
if key in SUBSCHEMA_MAPS and isinstance(value, dict):
|
|
183
|
+
for name, sub in value.items():
|
|
184
|
+
out += host_keywords(sub, f"{at}/{key}/{name}")
|
|
185
|
+
elif key in SUBSCHEMAS:
|
|
186
|
+
out += host_keywords(value, f"{at}/{key}")
|
|
187
|
+
return out
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def schema_bytes(schema):
|
|
191
|
+
"""The bytes `schema.json` holds, which are the schema the host is handed (`host_schema`), as canonical JSON. The
|
|
192
|
+
schema and its handed form are both compiled through the policy. The same bytes are what the packet's SCHEMA hash
|
|
193
|
+
names and the receipt hashes, so the gate binds one schema from the driver to the host."""
|
|
194
|
+
validate.compile_schema(schema)
|
|
195
|
+
sent = host_schema(schema)
|
|
196
|
+
validate.compile_schema(sent)
|
|
197
|
+
unread = host_keywords(sent)
|
|
198
|
+
if unread:
|
|
199
|
+
raise validate.SchemaPolicyError("HOST_SCHEMA_KEYWORD " + "; ".join(f"{key} at {at}" for at, key in unread)
|
|
200
|
+
+ ": the host's draft-07 check refuses it, or reads it otherwise than the "
|
|
201
|
+
"policy's 2020-12 reading (HOST_KEYWORDS)")
|
|
202
|
+
return (json.dumps(sent, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + "\n").encode("utf-8")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
# What each host is handed for a call's answer (D7, 2026-11-12). Claude Code reads schema.json itself: its
|
|
206
|
+
# `--json-schema` check is the draft-07 reading HOST_KEYWORDS was measured for. Codex hands its `--output-schema` to
|
|
207
|
+
# OpenAI's strict structured output, which takes a subset of JSON Schema, and the first live Codex judge call was
|
|
208
|
+
# refused by the provider before it generated anything (`invalid_json_schema`, status 400). So a Codex call's host
|
|
209
|
+
# receives a projection of schema.json made here by code (`provider_schema`); the gate still validates the answer
|
|
210
|
+
# against schema.json and holds the projection to this function, so nothing the projection leaves out goes unchecked.
|
|
211
|
+
PROVIDER_DIALECTS = {"claude": None, "codex": "openai-strict"}
|
|
212
|
+
# The strict subset, from the provider's Structured Outputs guide ("Supported schemas", read 2026-11-12 through its
|
|
213
|
+
# documentation index): the supported types; the keywords it lists per type; `additionalProperties: false` on every
|
|
214
|
+
# object and every property in `required`; the root an object and not `anyOf`; each `anyOf` branch a schema of the
|
|
215
|
+
# subset; definitions by `$defs`; and its limits. `description` is the one annotation its examples carry. A keyword
|
|
216
|
+
# the guide lists for no type is refused, the composition keywords it names as unsupported among them.
|
|
217
|
+
STRICT_TYPES = frozenset({"string", "number", "boolean", "integer", "object", "array", "null"})
|
|
218
|
+
STRICT_COMMON = frozenset({"type", "description", "enum", "const", "anyOf", "$ref"})
|
|
219
|
+
_STRICT_NUMBER = frozenset({"multipleOf", "maximum", "exclusiveMaximum", "minimum", "exclusiveMinimum"})
|
|
220
|
+
STRICT_BY_TYPE = {"string": frozenset({"pattern", "format"}), "number": _STRICT_NUMBER, "integer": _STRICT_NUMBER,
|
|
221
|
+
"array": frozenset({"items", "minItems", "maxItems"}),
|
|
222
|
+
"object": frozenset({"properties", "required", "additionalProperties"}),
|
|
223
|
+
"boolean": frozenset(), "null": frozenset()}
|
|
224
|
+
STRICT_FORMATS = frozenset({"date-time", "time", "date", "duration", "email", "hostname", "ipv4", "ipv6", "uuid"})
|
|
225
|
+
STRICT_LIMITS = {"properties": 5000, "depth": 10, "enum_values": 1000, "string_chars": 120_000,
|
|
226
|
+
"large_enum": 250, "large_enum_chars": 15_000}
|
|
227
|
+
# A pattern's syntax beyond what the guide shows is not assumed: its examples anchor with `^` and `$`, and it names no
|
|
228
|
+
# regular-expression dialect, so a lookaround or a backreference is refused rather than sent.
|
|
229
|
+
STRICT_PATTERN_UNESTABLISHED = re.compile(r"\(\?(?:=|!|<=|<!)|\\[1-9]|\\k<")
|
|
230
|
+
# What the projection leaves out: the annotations the subset does not list, and the constraints it does not support,
|
|
231
|
+
# which the gate still checks against schema.json.
|
|
232
|
+
STRICT_DROPPED = ("$comment", "title", "minLength", "maxLength", "uniqueItems")
|
|
233
|
+
# The policy's end of input: a pattern ending in it ends there, which the host reads as `$` (no multiline flag).
|
|
234
|
+
END_OF_INPUT = "(?![\\s\\S])"
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def strict_problems(schema):
|
|
238
|
+
"""What makes `schema` fall outside the strict subset (STRICT_*), each line naming its JSON pointer; empty when
|
|
239
|
+
nothing does. Walked by the schema's structure: names under `properties` and `$defs` are names, and an `enum` or
|
|
240
|
+
`const` value is data."""
|
|
241
|
+
problems, totals = [], {"properties": 0, "enum_values": 0, "string_chars": 0}
|
|
242
|
+
if not isinstance(schema, dict) or schema.get("type") != "object" or "anyOf" in schema:
|
|
243
|
+
problems.append("STRICT_ROOT at #: the root is an object schema, and not anyOf")
|
|
244
|
+
|
|
245
|
+
def walk(node, at, depth):
|
|
246
|
+
if not isinstance(node, dict):
|
|
247
|
+
problems.append(f"STRICT_SCHEMA_SHAPE at {at}: a schema of the subset is an object")
|
|
248
|
+
return
|
|
249
|
+
if depth > STRICT_LIMITS["depth"]:
|
|
250
|
+
problems.append(f"STRICT_DEPTH at {at}: more than {STRICT_LIMITS['depth']} levels of nesting")
|
|
251
|
+
declared = node.get("type")
|
|
252
|
+
types = [declared] if isinstance(declared, str) else declared if isinstance(declared, list) else []
|
|
253
|
+
if declared is None and not {"anyOf", "$ref", "enum", "const"} & set(node):
|
|
254
|
+
problems.append(f"STRICT_TYPE_MISSING at {at}: a schema names its type")
|
|
255
|
+
for t in types:
|
|
256
|
+
if t not in STRICT_TYPES:
|
|
257
|
+
problems.append(f"STRICT_TYPE_UNSUPPORTED {t!r} at {at}")
|
|
258
|
+
allowed = set(STRICT_COMMON) | ({"$defs"} if at == "#" else set())
|
|
259
|
+
for t in types:
|
|
260
|
+
allowed |= STRICT_BY_TYPE.get(t, frozenset())
|
|
261
|
+
for key in node:
|
|
262
|
+
if key not in allowed:
|
|
263
|
+
problems.append(f"STRICT_KEYWORD_UNSUPPORTED {key} at {at}")
|
|
264
|
+
if "format" in node and node["format"] not in STRICT_FORMATS:
|
|
265
|
+
problems.append(f"STRICT_FORMAT_UNSUPPORTED {node['format']!r} at {at}")
|
|
266
|
+
if isinstance(node.get("pattern"), str) and STRICT_PATTERN_UNESTABLISHED.search(node["pattern"]):
|
|
267
|
+
problems.append(f"STRICT_PATTERN_UNESTABLISHED at {at}: a lookaround or a backreference")
|
|
268
|
+
if "object" in types:
|
|
269
|
+
props = node.get("properties") if isinstance(node.get("properties"), dict) else {}
|
|
270
|
+
if node.get("additionalProperties") is not False:
|
|
271
|
+
problems.append(f"STRICT_ADDITIONAL_PROPERTIES at {at}: every object sets additionalProperties false")
|
|
272
|
+
required = node.get("required") if isinstance(node.get("required"), list) else []
|
|
273
|
+
optional = [name for name in props if name not in required]
|
|
274
|
+
if optional:
|
|
275
|
+
problems.append(f"STRICT_OPTIONAL_PROPERTY at {at}: {optional} not required; the subset requires every "
|
|
276
|
+
"property, and a nullable stand-in would let the host answer null where schema.json "
|
|
277
|
+
"refuses it")
|
|
278
|
+
unknown = [name for name in required if name not in props]
|
|
279
|
+
if unknown:
|
|
280
|
+
problems.append(f"STRICT_REQUIRED_UNKNOWN at {at}: {unknown} required and not properties")
|
|
281
|
+
totals["properties"] += len(props)
|
|
282
|
+
totals["string_chars"] += sum(len(name) for name in props)
|
|
283
|
+
for name, sub in props.items():
|
|
284
|
+
walk(sub, f"{at}/properties/{name}", depth + 1)
|
|
285
|
+
if "array" in types and "items" in node:
|
|
286
|
+
walk(node["items"], f"{at}/items", depth + 1)
|
|
287
|
+
for n, sub in enumerate(node.get("anyOf") if isinstance(node.get("anyOf"), list) else []):
|
|
288
|
+
walk(sub, f"{at}/anyOf/{n}", depth)
|
|
289
|
+
if isinstance(node.get("enum"), list):
|
|
290
|
+
values = node["enum"]
|
|
291
|
+
chars = sum(len(v) for v in values if isinstance(v, str))
|
|
292
|
+
totals["enum_values"] += len(values)
|
|
293
|
+
totals["string_chars"] += chars
|
|
294
|
+
if len(values) > STRICT_LIMITS["large_enum"] and chars > STRICT_LIMITS["large_enum_chars"]:
|
|
295
|
+
problems.append(f"STRICT_ENUM_SIZE at {at}: {len(values)} values, {chars} characters")
|
|
296
|
+
if isinstance(node.get("const"), str):
|
|
297
|
+
totals["string_chars"] += len(node["const"])
|
|
298
|
+
for name, sub in (node.get("$defs") if isinstance(node.get("$defs"), dict) else {}).items():
|
|
299
|
+
totals["string_chars"] += len(name)
|
|
300
|
+
walk(sub, f"{at}/$defs/{name}", depth)
|
|
301
|
+
if isinstance(schema, dict):
|
|
302
|
+
walk(schema, "#", 1)
|
|
303
|
+
for key, limit in (("properties", "properties"), ("enum_values", "enum_values"), ("string_chars", "string_chars")):
|
|
304
|
+
if totals[key] > STRICT_LIMITS[limit]:
|
|
305
|
+
problems.append(f"STRICT_LIMIT {key} at #: {totals[key]} over {STRICT_LIMITS[limit]}")
|
|
306
|
+
return problems
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def provider_schema(handed, host):
|
|
310
|
+
"""`(projection, problems)`: what `host` is handed for a schema whose handed form (schema.json's content) is
|
|
311
|
+
`handed`. A host whose dialect reads schema.json itself gets None, and nothing is projected; for the strict
|
|
312
|
+
dialect the projection leaves out STRICT_DROPPED and ends a pattern ending at END_OF_INPUT with `$`, and its
|
|
313
|
+
problems are `strict_problems` of the result. Nothing is made optional, nullable or open that schema.json closes:
|
|
314
|
+
a schema the subset cannot hold is refused by name, never sent weakened."""
|
|
315
|
+
if host not in PROVIDER_DIALECTS:
|
|
316
|
+
return None, [f"PROVIDER_DIALECT_UNKNOWN {host!r}: no dialect is declared for it"]
|
|
317
|
+
if PROVIDER_DIALECTS[host] is None:
|
|
318
|
+
return None, []
|
|
319
|
+
|
|
320
|
+
def project(node):
|
|
321
|
+
if not isinstance(node, dict):
|
|
322
|
+
return node
|
|
323
|
+
out = {}
|
|
324
|
+
for key, value in node.items():
|
|
325
|
+
if key in STRICT_DROPPED:
|
|
326
|
+
continue
|
|
327
|
+
if key == "pattern" and isinstance(value, str) and value.endswith(END_OF_INPUT):
|
|
328
|
+
head = value[:-len(END_OF_INPUT)]
|
|
329
|
+
escaped = (len(head) - len(head.rstrip("\\"))) % 2 # an escaped "(" opens no lookahead
|
|
330
|
+
out[key] = value if escaped else head + "$"
|
|
331
|
+
elif key in ("properties", "$defs") and isinstance(value, dict):
|
|
332
|
+
out[key] = {name: project(sub) for name, sub in value.items()}
|
|
333
|
+
elif key == "items" and isinstance(value, dict):
|
|
334
|
+
out[key] = project(value)
|
|
335
|
+
elif key == "anyOf" and isinstance(value, list):
|
|
336
|
+
out[key] = [project(sub) for sub in value]
|
|
337
|
+
else:
|
|
338
|
+
out[key] = value
|
|
339
|
+
return out
|
|
340
|
+
projected = project(handed)
|
|
341
|
+
return projected, strict_problems(projected)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def provider_schema_bytes(schema_json, host):
|
|
345
|
+
"""The bytes `host` is handed beside schema.json (`schema_json`, its bytes), as canonical JSON, or None when the
|
|
346
|
+
host reads schema.json itself. A projection outside the dialect raises SchemaPolicyError naming every problem."""
|
|
347
|
+
projected, problems = provider_schema(json.loads(schema_json), host)
|
|
348
|
+
if problems:
|
|
349
|
+
raise validate.SchemaPolicyError("SCHEMA_UNPROJECTABLE " + "; ".join(problems))
|
|
350
|
+
if projected is None:
|
|
351
|
+
return None
|
|
352
|
+
return (json.dumps(projected, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + "\n").encode("utf-8")
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def build(call_id, stage, seat, payload, schema=None, repo=REPO):
|
|
356
|
+
"""The packet's bytes. `schema` is the bytes of `schema.json`, or None for a schema-less call."""
|
|
357
|
+
block = principles_block(repo)
|
|
358
|
+
reference = f"sha256:{sha256_bytes(schema)}" if schema is not None else "none"
|
|
359
|
+
header = (f"CALL-ID: {call_id}\nSTAGE: {stage}\nSEAT: {seat}\nSCHEMA: {reference}\n"
|
|
360
|
+
f"PRINCIPLES: sha256:{sha256_bytes(block.encode('utf-8'))}\n\n")
|
|
361
|
+
return (header + block + PAYLOAD_MARKER + "\n" + payload).encode("utf-8")
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def template_text(name, template_dir=TEMPLATE_DIR):
|
|
365
|
+
try:
|
|
366
|
+
return (pathlib.Path(template_dir) / f"{name}.md").read_text(encoding="utf-8")
|
|
367
|
+
except OSError as exc:
|
|
368
|
+
raise TemplateError(f"TEMPLATE_UNAVAILABLE {name}: {exc}") from exc
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def template_fields(name, template_dir=TEMPLATE_DIR):
|
|
372
|
+
"""The placeholders of one template, sorted."""
|
|
373
|
+
return sorted(set(PLACEHOLDER.findall(template_text(name, template_dir))))
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def render(name, fields, template_dir=TEMPLATE_DIR):
|
|
377
|
+
"""The payload of template `name` with every placeholder replaced by its field's text, in one pass."""
|
|
378
|
+
text = template_text(name, template_dir)
|
|
379
|
+
wanted = set(PLACEHOLDER.findall(text))
|
|
380
|
+
missing, extra = sorted(wanted - set(fields)), sorted(set(fields) - wanted)
|
|
381
|
+
if missing or extra or not all(isinstance(v, str) for v in fields.values()):
|
|
382
|
+
raise TemplateError(f"TEMPLATE_FIELDS_MISMATCH {name}: missing={missing} extra={extra}; every placeholder "
|
|
383
|
+
"takes exactly one text field")
|
|
384
|
+
return PLACEHOLDER.sub(lambda m: fields[m.group(1)], text)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def split(packet):
|
|
388
|
+
"""(envelope text, payload bytes) at the first marker line, or (whole text, None)."""
|
|
389
|
+
marker = ("\n" + PAYLOAD_MARKER + "\n").encode("utf-8")
|
|
390
|
+
at = packet.find(marker)
|
|
391
|
+
if at < 0:
|
|
392
|
+
return packet.decode("utf-8", "replace"), None
|
|
393
|
+
return packet[:at + 1].decode("utf-8", "replace"), packet[at + len(marker):]
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def payload_sha256(packet):
|
|
397
|
+
"""The hash of the payload alone; of the whole packet when it carries no marker."""
|
|
398
|
+
payload = split(packet)[1]
|
|
399
|
+
return sha256_bytes(packet if payload is None else payload)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def check(packet, call_id, schema=None, repo=REPO):
|
|
403
|
+
"""Every reason `packet` may not be dispatched for `call_id` with `schema` (bytes or None)."""
|
|
404
|
+
errors = []
|
|
405
|
+
envelope, payload = split(packet)
|
|
406
|
+
lines = envelope.splitlines()
|
|
407
|
+
if not lines or lines[0] != f"CALL-ID: {call_id}":
|
|
408
|
+
errors.append(f"CALL_ID_MISSING: the packet's first line is not 'CALL-ID: {call_id}'")
|
|
409
|
+
header = dict(line.split(": ", 1) for line in lines[1:5] if ": " in line)
|
|
410
|
+
block = principles_block(repo)
|
|
411
|
+
if header.get("PRINCIPLES") != f"sha256:{sha256_bytes(block.encode('utf-8'))}" or block not in envelope:
|
|
412
|
+
errors.append("PRINCIPLES_MISSING: the packet does not carry the current principles block and its hash (plan P9)")
|
|
413
|
+
want = f"sha256:{sha256_bytes(schema)}" if schema is not None else "none"
|
|
414
|
+
if header.get("SCHEMA") != want:
|
|
415
|
+
errors.append(f"SCHEMA_REFERENCE_MISSING: the envelope's schema reference is {header.get('SCHEMA')!r}, "
|
|
416
|
+
f"the call's schema is {want}")
|
|
417
|
+
if not payload:
|
|
418
|
+
errors.append(f"PAYLOAD_MISSING: no payload after a '{PAYLOAD_MARKER}' line")
|
|
419
|
+
return errors
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def self_test():
|
|
423
|
+
import tempfile
|
|
424
|
+
failures, ran = [], []
|
|
425
|
+
|
|
426
|
+
def control(name, errors, *needles):
|
|
427
|
+
ran.append(name)
|
|
428
|
+
if not needles and errors:
|
|
429
|
+
failures.append(f"{name}: expected no violation, got {errors}")
|
|
430
|
+
for needle in needles:
|
|
431
|
+
if not any(needle in line for line in errors):
|
|
432
|
+
failures.append(f"{name}: expected {needle!r} in {errors}")
|
|
433
|
+
|
|
434
|
+
conforming = {"type": "object", "additionalProperties": False, "required": ["answer"],
|
|
435
|
+
"properties": {"answer": {"type": "string"}}}
|
|
436
|
+
# the product refusing a conforming schema fails this control by its name, never as a traceback that would hide
|
|
437
|
+
# every control after it (WP-08c); the envelope controls below then run on the schema's bytes as written
|
|
438
|
+
try:
|
|
439
|
+
schema, refusal = schema_bytes(conforming), []
|
|
440
|
+
except validate.SchemaPolicyError as exc:
|
|
441
|
+
schema = (json.dumps(conforming, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8")
|
|
442
|
+
refusal = [f"refused: {str(exc)[:200]}"]
|
|
443
|
+
control("schema-builder-takes-a-conforming-schema", refusal)
|
|
444
|
+
payload = "Judge the candidate below.\n{\"candidate\": \"c1\"}\n"
|
|
445
|
+
good = build("r1-S6-c1-a1", "S6", "claude:claude-opus-5-5/high", payload, schema)
|
|
446
|
+
control("conforming-packet", check(good, "r1-S6-c1-a1", schema)) # the positive control, first
|
|
447
|
+
other = build("r1-S6-c1-a2", "S6", "codex:gpt-6-astra/xhigh", payload, schema)
|
|
448
|
+
control("payload-hash-shared-packet-hash-unique",
|
|
449
|
+
[] if payload_sha256(good) == payload_sha256(other) == sha256_bytes(payload.encode())
|
|
450
|
+
and sha256_bytes(good) != sha256_bytes(other) else ["two calls of one judgment did not share only the payload hash"])
|
|
451
|
+
schemaless = build("r1-S8-e1-a1", "S8", "claude:claude-sonnet-5-5/xhigh", payload)
|
|
452
|
+
control("schema-less-packet-says-none", check(schemaless, "r1-S8-e1-a1"))
|
|
453
|
+
|
|
454
|
+
block = principles_block()
|
|
455
|
+
control("block-carries-all-five-summaries",
|
|
456
|
+
[] if all(f"## {title} ({guide})\n" in block for title, guide, _ in PRINCIPLE_SOURCES)
|
|
457
|
+
and len(PRINCIPLE_SOURCES) == 5 else ["a principle summary is missing from the block"])
|
|
458
|
+
control("block-is-taken-from-the-guides",
|
|
459
|
+
[] if "one value has one owner" in block and "1. High-level design:" in block
|
|
460
|
+
and "mocks are verification realizations" in block else ["the block is not the guides' own text"])
|
|
461
|
+
|
|
462
|
+
control("no-principles-block", check(good.replace(block.encode(), b""), "r1-S6-c1-a1", schema),
|
|
463
|
+
"PRINCIPLES_MISSING")
|
|
464
|
+
control("principles-text-altered", check(good.replace(b"one value has one owner", b"one value, many owners"),
|
|
465
|
+
"r1-S6-c1-a1", schema), "PRINCIPLES_MISSING")
|
|
466
|
+
stale = good.replace(f"PRINCIPLES: sha256:{sha256_bytes(block.encode())}".encode(), b"PRINCIPLES: sha256:" + b"0" * 64)
|
|
467
|
+
control("principles-hash-stale", check(stale, "r1-S6-c1-a1", schema), "PRINCIPLES_MISSING")
|
|
468
|
+
control("no-schema-reference", check(good.replace(b"SCHEMA: sha256:", b"SCHEMAX: sha256:"), "r1-S6-c1-a1", schema),
|
|
469
|
+
"SCHEMA_REFERENCE_MISSING")
|
|
470
|
+
control("schema-reference-names-another-schema", check(good, "r1-S6-c1-a1", schema + b" "),
|
|
471
|
+
"SCHEMA_REFERENCE_MISSING")
|
|
472
|
+
control("schema-given-to-a-schema-less-packet", check(schemaless, "r1-S8-e1-a1", schema),
|
|
473
|
+
"SCHEMA_REFERENCE_MISSING")
|
|
474
|
+
control("another-call-id", check(good, "r1-S6-c1-a9", schema), "CALL_ID_MISSING")
|
|
475
|
+
control("no-payload", check(split(good)[0].encode(), "r1-S6-c1-a1", schema), "PAYLOAD_MISSING")
|
|
476
|
+
control("no-marker-hashes-the-whole-packet",
|
|
477
|
+
[] if payload_sha256(b"plain text\n") == sha256_bytes(b"plain text\n") else ["payload of an unmarked packet"])
|
|
478
|
+
|
|
479
|
+
def raised(action, error_type, needle):
|
|
480
|
+
try:
|
|
481
|
+
action()
|
|
482
|
+
except error_type as exc:
|
|
483
|
+
return [] if needle in str(exc) else [f"refused without {needle!r}: {exc}"]
|
|
484
|
+
except Exception as exc:
|
|
485
|
+
return [f"raised {exc!r}"]
|
|
486
|
+
return [f"not refused (expected {needle})"]
|
|
487
|
+
|
|
488
|
+
control("schema-builder-refuses-an-open-schema",
|
|
489
|
+
raised(lambda: schema_bytes({"type": "object", "properties": {}}), validate.SchemaPolicyError, "open object"))
|
|
490
|
+
# WP-08c: the form a host is handed holds only keywords its draft-07 check and the policy's 2020-12 reading read
|
|
491
|
+
# alike - walked by structure, so a property named like a keyword is a name, and checked on the handed form
|
|
492
|
+
named_like = {"type": "object", "additionalProperties": False, "required": ["items"],
|
|
493
|
+
"properties": {"items": {"type": "string"}, "required": {"type": "string"},
|
|
494
|
+
"dependentRequired": {"type": "string", "enum": ["prefixItems"]}}}
|
|
495
|
+
def handed_keywords(held):
|
|
496
|
+
try:
|
|
497
|
+
return host_keywords(json.loads(schema_bytes(held)))
|
|
498
|
+
except (validate.SchemaPolicyError, ValueError) as exc:
|
|
499
|
+
return [("refused", str(exc)[:120])]
|
|
500
|
+
control("host-schema-takes-properties-named-like-keywords",
|
|
501
|
+
[f"{handed_keywords(named_like)}"] if handed_keywords(named_like) else [])
|
|
502
|
+
planted = {"type": "object", "additionalProperties": False, "required": ["a"],
|
|
503
|
+
"properties": {"a": {"type": "string"}, "b": {"type": "array", "items": {"type": "string"}}},
|
|
504
|
+
"dependentRequired": {"a": ["b"]}}
|
|
505
|
+
control("host-schema-refuses-a-2019-keyword-by-name",
|
|
506
|
+
raised(lambda: schema_bytes(planted), validate.SchemaPolicyError, "HOST_SCHEMA_KEYWORD dependentRequired at #"))
|
|
507
|
+
deep = {"type": "object", "properties": {"b": {"type": "array", "items": {"type": "object", "unevaluatedProperties": False}}}}
|
|
508
|
+
control("host-keywords-name-each-unread-keyword-where-it-stands",
|
|
509
|
+
[] if (host_keywords(deep), host_keywords({"type": "array", "items": [{"type": "string"}]}),
|
|
510
|
+
host_keywords({"$schema": "x", "$defs": {"s": {"type": "string"}}, "properties": {"a": {"$ref": "#/$defs/s"}}}))
|
|
511
|
+
== ([("#/properties/b/items", "unevaluatedProperties")], [("#", "items")],
|
|
512
|
+
[("#", "$schema"), ("#", "$defs"), ("#/properties/a", "$ref")]) else ["walked otherwise"])
|
|
513
|
+
# the schema a host is handed (WP-08 commit 7, dw2-live1), asked of the schemas S3 hands a host, each of which names
|
|
514
|
+
# the 2020-12 meta-schema and holds references: no meta-schema, no reference and no $defs in the bytes, which the
|
|
515
|
+
# policy still compiles; and the inlined form is derived from the schema itself, so a change to an entry of its
|
|
516
|
+
# $defs shows at every place a reference reached it
|
|
517
|
+
host_bound = {}
|
|
518
|
+
for name in TEMPLATES:
|
|
519
|
+
try:
|
|
520
|
+
held = json.loads((pathlib.Path(__file__).resolve().parents[1] / "schemas" / f"{name}.schema.json").read_text(encoding="utf-8"))
|
|
521
|
+
sent_text = schema_bytes(held).decode("utf-8")
|
|
522
|
+
validate.compile_schema(json.loads(sent_text))
|
|
523
|
+
host_bound[name] = (held, sent_text)
|
|
524
|
+
except Exception as exc: # noqa: BLE001 - whatever stops a schema here is reported by name
|
|
525
|
+
failures.append(f"positive control: the {name} schema did not load or compile: {exc}")
|
|
526
|
+
control("host-schema-names-no-meta-schema-and-no-reference",
|
|
527
|
+
[] if sorted(host_bound) == sorted(TEMPLATES) and all(
|
|
528
|
+
"$schema" in held and held.get("$defs") and '"$ref"' in json.dumps(held)
|
|
529
|
+
and not any(key in sent for key in ('"$schema"', '"$defs"', '"$ref"')) for held, sent in host_bound.values())
|
|
530
|
+
else [f"a handed schema still names a meta-schema or a reference: "
|
|
531
|
+
f"{[n for n, (_h, s) in host_bound.items() if any(k in s for k in ('$schema', '$defs', '$ref'))]}"])
|
|
532
|
+
|
|
533
|
+
def reached(schema, node=None, seen=frozenset()):
|
|
534
|
+
"""How many times each $defs entry is reached from the schema's root, following references through entries."""
|
|
535
|
+
node = {k: v for k, v in schema.items() if k != "$defs"} if node is None else node
|
|
536
|
+
counts = {}
|
|
537
|
+
for value in (node.values() if isinstance(node, dict) else node if isinstance(node, list) else ()):
|
|
538
|
+
if isinstance(value, dict) and "$ref" in value:
|
|
539
|
+
name = value["$ref"][len("#/$defs/"):]
|
|
540
|
+
counts[name] = counts.get(name, 0) + 1
|
|
541
|
+
for inner, n in reached(schema, schema["$defs"][name], seen | {name}).items():
|
|
542
|
+
counts[inner] = counts.get(inner, 0) + n
|
|
543
|
+
elif isinstance(value, (dict, list)):
|
|
544
|
+
for inner, n in reached(schema, value, seen).items():
|
|
545
|
+
counts[inner] = counts.get(inner, 0) + n
|
|
546
|
+
return counts
|
|
547
|
+
followed = {}
|
|
548
|
+
for name, (held, sent_text) in host_bound.items():
|
|
549
|
+
marked = json.loads(json.dumps(held))
|
|
550
|
+
for entry, sub in marked["$defs"].items():
|
|
551
|
+
sub["$comment"] = f"FOLLOWS-{name}-{entry}"
|
|
552
|
+
made, problem = None, None
|
|
553
|
+
try:
|
|
554
|
+
made = schema_bytes(marked).decode("utf-8")
|
|
555
|
+
except Exception as exc: # noqa: BLE001 - reported by the control below
|
|
556
|
+
problem = str(exc)
|
|
557
|
+
expected = reached(held)
|
|
558
|
+
followed[name] = (made is not None and made != sent_text and bool(expected) and all(
|
|
559
|
+
made.count(f'"FOLLOWS-{name}-{entry}"') == expected.get(entry, 0) for entry in held["$defs"]), problem)
|
|
560
|
+
control("host-schema-follows-a-change-to-its-defs",
|
|
561
|
+
[] if sorted(followed) == sorted(TEMPLATES) and all(ok for ok, _t in followed.values())
|
|
562
|
+
else [f"a handed schema did not follow its $defs: {followed}"])
|
|
563
|
+
control("host-schema-refuses-a-reference-it-cannot-inline",
|
|
564
|
+
raised(lambda: host_schema({"type": "object", "additionalProperties": False, "$defs": {"a": {"type": "string"}},
|
|
565
|
+
"properties": {"x": {"$ref": "#/$defs/a", "title": "beside"}}}),
|
|
566
|
+
validate.SchemaPolicyError, "HOST_SCHEMA #/$defs/a: a $ref beside"))
|
|
567
|
+
control("host-schema-refuses-a-reference-that-reaches-itself",
|
|
568
|
+
raised(lambda: host_schema({"type": "object", "additionalProperties": False,
|
|
569
|
+
"$defs": {"a": {"type": "object", "additionalProperties": False,
|
|
570
|
+
"properties": {"next": {"$ref": "#/$defs/a"}}}},
|
|
571
|
+
"properties": {"x": {"$ref": "#/$defs/a"}}}),
|
|
572
|
+
validate.SchemaPolicyError, "HOST_SCHEMA #/$defs/a: the reference reaches itself"))
|
|
573
|
+
control("host-schema-refuses-a-reference-to-no-entry",
|
|
574
|
+
raised(lambda: host_schema({"type": "object", "additionalProperties": False, "$defs": {"a": {"type": "string"}},
|
|
575
|
+
"properties": {"x": {"$ref": "#/$defs/b"}}}),
|
|
576
|
+
validate.SchemaPolicyError, "HOST_SCHEMA #/$defs/b: the reference names no entry of $defs"))
|
|
577
|
+
# WP-08c (W r2): a reference's name holding a JSON Pointer or URI escape is refused before a host is handed it - by
|
|
578
|
+
# the policy's lint where schema_bytes compiles it, and by host_schema itself when called alone - so the escaped
|
|
579
|
+
# name "a~1b" never reaches a host as the literal entry while jsonschema resolves it as "a/b"
|
|
580
|
+
escaped_names = {"type": "object", "additionalProperties": False, "required": ["x"],
|
|
581
|
+
"$defs": {"a/b": {"type": "integer"}, "a~1b": {"type": "string"}},
|
|
582
|
+
"properties": {"x": {"$ref": "#/$defs/a~1b"}}}
|
|
583
|
+
control("schema-builder-refuses-an-escaped-reference-name",
|
|
584
|
+
raised(lambda: schema_bytes(escaped_names), validate.SchemaPolicyError, "as #/$defs/<name>, the name of letters")
|
|
585
|
+
+ [line for name in ("a~0b", "a%2Fb") for line in raised(
|
|
586
|
+
lambda name=name: schema_bytes({"type": "object", "additionalProperties": False, "required": ["x"],
|
|
587
|
+
"$defs": {name: {"type": "string"}},
|
|
588
|
+
"properties": {"x": {"$ref": f"#/$defs/{name}"}}}),
|
|
589
|
+
validate.SchemaPolicyError, "as #/$defs/<name>, the name of letters")])
|
|
590
|
+
control("host-schema-refuses-an-escaped-reference-name",
|
|
591
|
+
raised(lambda: host_schema(escaped_names), validate.SchemaPolicyError,
|
|
592
|
+
"HOST_SCHEMA #/$defs/a~1b: a reference is #/$defs/<name>"))
|
|
593
|
+
# WP-08c (X and W r1): the handed form is made by walking the schema's structure, so a literal {"$ref": ...} that an
|
|
594
|
+
# enum, a const, a default or an example holds is data, and a property named $ref is a name; and the schema as
|
|
595
|
+
# written and the form a host is handed accept and refuse the same answers, for those and for every schema a host
|
|
596
|
+
# is handed now (read, stitch, and the judge's verdict as dispatch hands it)
|
|
597
|
+
kept_as_data = None
|
|
598
|
+
try:
|
|
599
|
+
kept_as_data = host_schema({"type": "object", "additionalProperties": False, "$defs": {"s": {"type": "string"}},
|
|
600
|
+
"properties": {"a": {"type": "object", "default": {"$ref": "#/$defs/s"},
|
|
601
|
+
"examples": [{"$ref": "#/$defs/s"}]},
|
|
602
|
+
"$ref": {"$ref": "#/$defs/s"}}})
|
|
603
|
+
except Exception as exc: # noqa: BLE001 - whatever stops it is reported by the control's name
|
|
604
|
+
kept_as_data = f"raised {type(exc).__name__}: {exc}"
|
|
605
|
+
control("host-schema-keeps-data-and-names-as-written",
|
|
606
|
+
[] if kept_as_data == {"type": "object", "additionalProperties": False,
|
|
607
|
+
"properties": {"a": {"type": "object", "default": {"$ref": "#/$defs/s"},
|
|
608
|
+
"examples": [{"$ref": "#/$defs/s"}]},
|
|
609
|
+
"$ref": {"type": "string"}}} else [f"made {kept_as_data}"])
|
|
610
|
+
|
|
611
|
+
def judged_alike(held, answers):
|
|
612
|
+
"""`(problem, [(answer, as written, as handed)])`: each answer judged by the schema and by its handed form."""
|
|
613
|
+
try:
|
|
614
|
+
written, handed = validate.compile_schema(held), validate.compile_schema(json.loads(schema_bytes(held)))
|
|
615
|
+
except Exception as exc: # noqa: BLE001 - a refused or broken schema fails the control by its name
|
|
616
|
+
return f"refused: {type(exc).__name__}: {str(exc)[:160]}", []
|
|
617
|
+
return None, [(json.dumps(a, sort_keys=True), written.is_valid(a), handed.is_valid(a)) for a in answers]
|
|
618
|
+
schemas_dir = pathlib.Path(__file__).resolve().parents[1] / "schemas"
|
|
619
|
+
def held_schema(name):
|
|
620
|
+
return json.loads((schemas_dir / f"{name}.schema.json").read_text(encoding="utf-8"))
|
|
621
|
+
quote = {"quote_id": "q1", "entry": "e1", "text": "x"}
|
|
622
|
+
empty_read = {"quotes": [], "claims": [], "events": [], "decisions": [], "observations": []}
|
|
623
|
+
resolved = {"event_id": "v1", "outcome": "resolved", "claim_ids": ["c1"], "evidence_ids": ["q1"]}
|
|
624
|
+
alike = {
|
|
625
|
+
"a literal $ref in an enum and a const": (
|
|
626
|
+
{"type": "object", "additionalProperties": False, "required": ["payload", "word"], "$defs": {"s": {"type": "string"}},
|
|
627
|
+
"properties": {"payload": {"enum": [{"$ref": "#/$defs/s"}, "plain"]}, "pinned": {"const": {"$ref": "#/$defs/s"}},
|
|
628
|
+
"word": {"$ref": "#/$defs/s"}}},
|
|
629
|
+
[{"payload": {"$ref": "#/$defs/s"}, "word": "w"}, {"payload": {"type": "string"}, "word": "w"},
|
|
630
|
+
{"payload": "plain", "word": "w", "pinned": {"$ref": "#/$defs/s"}},
|
|
631
|
+
{"payload": "plain", "word": "w", "pinned": {"type": "string"}}, {"payload": "plain", "word": 3}]),
|
|
632
|
+
"a property named $ref": (
|
|
633
|
+
{"type": "object", "additionalProperties": False, "required": ["$ref"], "$defs": {"n": {"type": "integer"}},
|
|
634
|
+
"properties": {"$ref": {"type": "string"}, "count": {"$ref": "#/$defs/n"}}},
|
|
635
|
+
[{"$ref": "a"}, {"$ref": "a", "count": 2}, {"$ref": 1}, {"$ref": "a", "count": "2"}, {}]),
|
|
636
|
+
"read": (held_schema("read"),
|
|
637
|
+
[empty_read, {**empty_read, "quotes": [quote]}, {**empty_read, "quotes": [{**quote, "quote_id": "q1\n"}]},
|
|
638
|
+
{**empty_read, "quotes": [{**quote, "entry": "3/message/content"}]},
|
|
639
|
+
{k: v for k, v in empty_read.items() if k != "observations"}, {**empty_read, "extra": []}]),
|
|
640
|
+
"stitch": (held_schema("stitch"),
|
|
641
|
+
[{"resolutions": []}, {"resolutions": [resolved]}, {"resolutions": [{**resolved, "outcome": "maybe"}]},
|
|
642
|
+
{"resolutions": [{**resolved, "claim_ids": ["c1\n"]}]}, {}]),
|
|
643
|
+
"verdict": ({"type": "object", "additionalProperties": False, "required": ["verdict", "why"],
|
|
644
|
+
"properties": {"verdict": {"enum": ["PRESENT", "ABSENT", "UNCLEAR"]}, "why": {"type": "string"}}},
|
|
645
|
+
[{"verdict": "ABSENT", "why": "x"}, {"verdict": "NO", "why": "x"}, {"verdict": "ABSENT"}]),
|
|
646
|
+
}
|
|
647
|
+
verdicts = {name: judged_alike(held, answers) for name, (held, answers) in alike.items()}
|
|
648
|
+
control("host-schema-judges-every-answer-as-the-schema-does",
|
|
649
|
+
[f"{name}: {problem or [r for r in rows if r[1] != r[2]] or 'no answer accepted, or none refused'}"
|
|
650
|
+
for name, (problem, rows) in verdicts.items()
|
|
651
|
+
if problem or any(r[1] != r[2] for r in rows) or {r[1] for r in rows} != {True, False}])
|
|
652
|
+
with tempfile.TemporaryDirectory() as td:
|
|
653
|
+
for _title, guide, _part in PRINCIPLE_SOURCES:
|
|
654
|
+
target = pathlib.Path(td) / guide
|
|
655
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
656
|
+
target.write_text((REPO / guide).read_text(encoding="utf-8"), encoding="utf-8")
|
|
657
|
+
control("copied-guides-give-the-same-block", [] if principles_block(td) == block else ["block differs"])
|
|
658
|
+
staged = pathlib.Path(td) / "claude/guides/coding-staged-workflow.md"
|
|
659
|
+
staged.write_text(staged.read_text(encoding="utf-8").replace("## Stages", "## Phases"), encoding="utf-8")
|
|
660
|
+
control("guide-without-its-section", raised(lambda: principles_block(td), Unavailable,
|
|
661
|
+
"PRINCIPLES_UNAVAILABLE claude/guides/coding-staged-workflow.md"))
|
|
662
|
+
concept = pathlib.Path(td) / "claude/guides/concept-economy.md"
|
|
663
|
+
concept.write_text(concept.read_text(encoding="utf-8").replace("core_rules:", "other_rules:"), encoding="utf-8")
|
|
664
|
+
control("guide-without-core-rules", raised(lambda: summary(concept.read_text(encoding="utf-8"), "core_rules",
|
|
665
|
+
"concept-economy.md"), Unavailable,
|
|
666
|
+
"PRINCIPLES_UNAVAILABLE concept-economy.md"))
|
|
667
|
+
(pathlib.Path(td) / "claude/guides/verification-discipline.md").unlink()
|
|
668
|
+
control("guide-missing", raised(lambda: principles_block(td), Unavailable,
|
|
669
|
+
"PRINCIPLES_UNAVAILABLE claude/guides/verification-discipline.md"))
|
|
670
|
+
control("template-missing", raised(lambda: render("read", {}, template_dir=td), TemplateError,
|
|
671
|
+
"TEMPLATE_UNAVAILABLE read"))
|
|
672
|
+
|
|
673
|
+
# S3's two templates (plan WP-08): each takes exactly the fields its stage fills, the packet it makes passes the
|
|
674
|
+
# linter, and the part every call of it carries - envelope, principles, template, schema - leaves room in the
|
|
675
|
+
# overhead the windows were cut with for what the call adds (its omissions and expected observations). The room
|
|
676
|
+
# is reported, not judged: what one call adds is counted with the call, by the dispatcher's bound check.
|
|
677
|
+
from runlib import bound
|
|
678
|
+
schemas = pathlib.Path(__file__).resolve().parents[1] / "schemas"
|
|
679
|
+
filled_by = {"read": ["expected", "omissions", "window"], "stitch": ["claims", "events"],
|
|
680
|
+
"form": ["claims", "clusters", "events"], "judge": ["candidate", "claims", "context", "entries", "units"],
|
|
681
|
+
"sweep": ["candidates", "inventory", "units"], "cross_review": ["candidate", "units"],
|
|
682
|
+
"reconsider": ["candidate", "claims", "context", "units"]}
|
|
683
|
+
room = {}
|
|
684
|
+
for name in TEMPLATES:
|
|
685
|
+
try:
|
|
686
|
+
fields = template_fields(name)
|
|
687
|
+
answer = schema_bytes(json.loads((schemas / f"{name}.schema.json").read_text(encoding="utf-8")))
|
|
688
|
+
except (TemplateError, OSError, ValueError, validate.SchemaPolicyError) as exc:
|
|
689
|
+
failures.extend(f"{name}-{what}: not run (the {name} template or schema did not load: {str(exc)[:160]})"
|
|
690
|
+
for what in ("template-takes-the-fields-its-stage-fills", "packet-passes-the-linter",
|
|
691
|
+
"fixed-part-fits-the-overhead"))
|
|
692
|
+
continue
|
|
693
|
+
control(f"{name}-template-takes-the-fields-its-stage-fills",
|
|
694
|
+
[] if fields == filled_by[name] else [f"placeholders {fields}, filled {filled_by[name]}"])
|
|
695
|
+
call = f"r1-S3-{name}-a1"
|
|
696
|
+
made = build(call, "S3", "claude:claude-sonnet-5-5/high", render(name, {f: f"<{f}>" for f in fields}), answer)
|
|
697
|
+
control(f"{name}-packet-passes-the-linter", check(made, call, answer))
|
|
698
|
+
if name not in WINDOW_TEMPLATES:
|
|
699
|
+
continue # S4's packet is bounded by its own stage (plan WP-09), not by the overhead S3's windows were cut with
|
|
700
|
+
fixed = len(build(call, "S3", "claude:claude-sonnet-5-5/high", render(name, {f: "" for f in fields}), answer)) \
|
|
701
|
+
+ len(answer)
|
|
702
|
+
room[name] = bound.PACKET_OVERHEAD - fixed
|
|
703
|
+
control(f"{name}-fixed-part-fits-the-overhead",
|
|
704
|
+
[] if room[name] > 0 else [f"{fixed} fixed bytes, overhead {bound.PACKET_OVERHEAD}"])
|
|
705
|
+
control("template-field-missing", raised(lambda: render("read", {"window": "w", "omissions": "o"}), TemplateError,
|
|
706
|
+
"TEMPLATE_FIELDS_MISMATCH read: missing=['expected']"))
|
|
707
|
+
control("template-field-extra", raised(lambda: render("stitch", {"events": "e", "claims": "c", "window": "w"}),
|
|
708
|
+
TemplateError, "TEMPLATE_FIELDS_MISMATCH stitch: missing=[] extra=['window']"))
|
|
709
|
+
control("template-field-not-text", raised(lambda: render("stitch", {"events": "e", "claims": 3}), TemplateError,
|
|
710
|
+
"TEMPLATE_FIELDS_MISMATCH stitch"))
|
|
711
|
+
# a template that no longer takes these fields fails this control by its name, never as a traceback that would
|
|
712
|
+
# hide every failure recorded before it
|
|
713
|
+
try:
|
|
714
|
+
once = render("read", {"window": "a record quoting {{omissions}}", "omissions": "ONLY-HERE", "expected": "none"})
|
|
715
|
+
expanded = [] if "a record quoting {{omissions}}" in once and once.count("ONLY-HERE") == 1 else ["a field was expanded"]
|
|
716
|
+
except TemplateError as exc:
|
|
717
|
+
expanded = [f"RAISED {exc}"]
|
|
718
|
+
control("a-field-is-never-read-as-a-template", expanded)
|
|
719
|
+
|
|
720
|
+
# D7: every schema a Codex seat can be sent projects into the strict subset. The stages are the ones seats.json
|
|
721
|
+
# gives a Codex seat, and the schemas each sends are the ones its own module builds, so a Codex seat added to
|
|
722
|
+
# another stage fails this control until that stage's schemas are named here.
|
|
723
|
+
try:
|
|
724
|
+
from runlib import stage_judge as sj, stage_review_korean as s9b, stage_review_proposals as s7b
|
|
725
|
+
sent_by = {"S6": {"judge": sj.schema, "sweep": sj.sweep_schema, "cross_review": sj.cross_schema,
|
|
726
|
+
"reconsider": sj.reconsider_schema},
|
|
727
|
+
"S7b": {"s7b": lambda: json.loads(s7b.schema_bytes())},
|
|
728
|
+
"S9b": {"s9b": lambda: json.loads(s9b.schema_bytes())}}
|
|
729
|
+
seats_doc = json.loads((REPO / "session-distill" / "seats.json").read_text(encoding="utf-8"))
|
|
730
|
+
codex_stages = {stage for stage, held in seats_doc["stage_seats"].items()
|
|
731
|
+
if not stage.startswith("$") and any(str(seat).startswith("codex:") for seat in held)}
|
|
732
|
+
handed = {name: json.loads(schema_bytes(make())) for stage in sent_by for name, make in sent_by[stage].items()}
|
|
733
|
+
found = {name: provider_schema(held, "codex") for name, held in handed.items()}
|
|
734
|
+
reached = []
|
|
735
|
+
except Exception as exc: # noqa: BLE001 - a module that no longer builds its schema fails the control by name
|
|
736
|
+
codex_stages, handed, found, reached = set(), {}, {}, [f"RAISED {type(exc).__name__}: {str(exc)[:160]}"]
|
|
737
|
+
# Every schema a Codex seat can be sent projects cleanly. S7b's five optional properties were the one exception
|
|
738
|
+
# (named by site here while its owner decided the contract); each is now required with its absence given a name —
|
|
739
|
+
# `merge_findings` and `alternative.destination` nullable, both judgments' `evidence` required outright — so the
|
|
740
|
+
# exception is gone rather than carried, and this dict is empty because there is nothing to excuse.
|
|
741
|
+
unprojectable = {}
|
|
742
|
+
wrong = list(reached)
|
|
743
|
+
if codex_stages != set(sent_by) or not handed:
|
|
744
|
+
wrong.append(f"the stages with a Codex seat are {sorted(codex_stages)}, the ones named here {sorted(sent_by)}")
|
|
745
|
+
for name, (projected, problems) in sorted(found.items()):
|
|
746
|
+
sites = {line.split(" at ", 1)[1].split(":", 1)[0] for line in problems if line.startswith("STRICT_OPTIONAL_PROPERTY")}
|
|
747
|
+
expected = unprojectable.get(name, set())
|
|
748
|
+
if projected is None or sites != expected or len(problems) != len(expected):
|
|
749
|
+
wrong.append(f"{name}: {problems[:3]}")
|
|
750
|
+
control("every-schema-a-codex-seat-can-be-sent-projects-into-the-strict-subset", wrong)
|
|
751
|
+
|
|
752
|
+
# the projection weakens nothing schema.json closes: at every pointer the same types, properties, required,
|
|
753
|
+
# additionalProperties, enum, const, items and bounds; only STRICT_DROPPED goes, and an end of input becomes `$`
|
|
754
|
+
def weakened(full, sent, at):
|
|
755
|
+
out = []
|
|
756
|
+
if not isinstance(full, dict) or not isinstance(sent, dict):
|
|
757
|
+
return [] if full == sent else [f"{at}: not the same schema"]
|
|
758
|
+
for key in set(full) | set(sent):
|
|
759
|
+
if key in STRICT_DROPPED:
|
|
760
|
+
if key in sent:
|
|
761
|
+
out.append(f"{at}: {key} kept")
|
|
762
|
+
elif key not in full or key not in sent:
|
|
763
|
+
out.append(f"{at}: {key} only on one side")
|
|
764
|
+
elif key in ("properties", "$defs"):
|
|
765
|
+
if set(full[key]) != set(sent[key]):
|
|
766
|
+
out.append(f"{at}/{key}: other names")
|
|
767
|
+
out += [line for name in full[key] for line in weakened(full[key][name], sent[key].get(name), f"{at}/{key}/{name}")]
|
|
768
|
+
elif key == "items":
|
|
769
|
+
out += weakened(full[key], sent[key], f"{at}/items")
|
|
770
|
+
elif key == "anyOf":
|
|
771
|
+
out += [line for n, (a, b) in enumerate(zip(full[key], sent[key])) for line in weakened(a, b, f"{at}/anyOf/{n}")]
|
|
772
|
+
if len(full[key]) != len(sent[key]):
|
|
773
|
+
out.append(f"{at}/anyOf: another number of branches")
|
|
774
|
+
elif key == "pattern":
|
|
775
|
+
if sent[key] not in (full[key], full[key][:-len(END_OF_INPUT)] + "$" if full[key].endswith(END_OF_INPUT) else None):
|
|
776
|
+
out.append(f"{at}: pattern {sent[key]!r} is not {full[key]!r}")
|
|
777
|
+
elif full[key] != sent[key]:
|
|
778
|
+
out.append(f"{at}: {key} differs")
|
|
779
|
+
return out
|
|
780
|
+
control("the-projection-weakens-nothing-schema-json-closes",
|
|
781
|
+
([] if found else ["nothing projected"])
|
|
782
|
+
+ [f"{name} {line}" for name, (projected, _p) in sorted(found.items()) for line in weakened(handed[name], projected, "#")])
|
|
783
|
+
|
|
784
|
+
# each strict rule refuses by name, each on a schema of its own (so none stops testing when a real schema changes)
|
|
785
|
+
def closed(**props):
|
|
786
|
+
return {"type": "object", "additionalProperties": False, "required": sorted(props), "properties": props}
|
|
787
|
+
text = {"type": "string"}
|
|
788
|
+
nested = text
|
|
789
|
+
for _ in range(11):
|
|
790
|
+
nested = closed(x=nested)
|
|
791
|
+
planted = (
|
|
792
|
+
("a-planted-unsupported-keyword", closed(a={"type": "array", "items": text, "uniqueItems": True}),
|
|
793
|
+
"STRICT_KEYWORD_UNSUPPORTED uniqueItems at #/properties/a"),
|
|
794
|
+
("a-planted-composition-keyword", closed(a={"allOf": [text], "type": "string"}),
|
|
795
|
+
"STRICT_KEYWORD_UNSUPPORTED allOf at #/properties/a"),
|
|
796
|
+
("a-planted-open-object", {**closed(a=text), "additionalProperties": True}, "STRICT_ADDITIONAL_PROPERTIES at #"),
|
|
797
|
+
("a-planted-optional-property", {**closed(a=text, b=text), "required": ["a"]}, "STRICT_OPTIONAL_PROPERTY at #"),
|
|
798
|
+
("a-planted-anyof-root", {"anyOf": [closed(a=text)]}, "STRICT_ROOT at #"),
|
|
799
|
+
("a-planted-lookahead", closed(a={"type": "string", "pattern": "^(?=a)b$"}),
|
|
800
|
+
"STRICT_PATTERN_UNESTABLISHED at #/properties/a"),
|
|
801
|
+
("a-planted-format", closed(a={"type": "string", "format": "uri"}), "STRICT_FORMAT_UNSUPPORTED 'uri' at #/properties/a"),
|
|
802
|
+
("a-planted-type", closed(a={"type": "tuple"}), "STRICT_TYPE_UNSUPPORTED 'tuple' at #/properties/a"),
|
|
803
|
+
("a-planted-depth", nested, "STRICT_DEPTH at #/properties/x/properties/x/properties/x/properties/x/properties/x/"
|
|
804
|
+
"properties/x/properties/x/properties/x/properties/x/properties/x"),
|
|
805
|
+
("a-planted-property-count", closed(**{f"p{n}": text for n in range(5001)}), "STRICT_LIMIT properties at #"),
|
|
806
|
+
("a-planted-enum-count", closed(**{f"e{n}": {"type": "string", "enum": [f"v{m}" for m in range(11)]}
|
|
807
|
+
for n in range(100)}), "STRICT_LIMIT enum_values at #"),
|
|
808
|
+
("a-planted-large-enum", closed(a={"type": "string", "enum": [f"{n:03d}" + "v" * 60 for n in range(251)]}),
|
|
809
|
+
"STRICT_ENUM_SIZE at #/properties/a"))
|
|
810
|
+
for name, schema, needle in planted:
|
|
811
|
+
control(name, strict_problems(schema), needle)
|
|
812
|
+
control("a-conforming-schema-is-in-the-subset", strict_problems(closed(a=text, b={"type": ["string", "null"]})))
|
|
813
|
+
# the end of input becomes `$`, an escaped backslash before it included; Claude reads schema.json itself
|
|
814
|
+
ended, _ = provider_schema(closed(a={"type": "string", "pattern": "^n[1-9][0-9]*" + END_OF_INPUT},
|
|
815
|
+
b={"type": "string", "pattern": "^a\\\\" + END_OF_INPUT}), "codex")
|
|
816
|
+
control("an-end-of-input-is-sent-as-dollar",
|
|
817
|
+
[] if ended and ended["properties"]["a"]["pattern"] == "^n[1-9][0-9]*$"
|
|
818
|
+
and ended["properties"]["b"]["pattern"] == "^a\\\\$" else [f"{ended}"])
|
|
819
|
+
control("claude-reads-schema-json-itself", [] if provider_schema(closed(a=text), "claude") == (None, []) else ["projected"])
|
|
820
|
+
control("an-undeclared-host-has-no-dialect", provider_schema(closed(a=text), "gemini")[1], "PROVIDER_DIALECT_UNKNOWN 'gemini'")
|
|
821
|
+
control("an-unprojectable-schema-is-refused-with-its-problems",
|
|
822
|
+
raised(lambda: provider_schema_bytes(b'{"type":"object","properties":{"a":{"type":"string"}},"required":[],'
|
|
823
|
+
b'"additionalProperties":false}', "codex"),
|
|
824
|
+
validate.SchemaPolicyError, "SCHEMA_UNPROJECTABLE STRICT_OPTIONAL_PROPERTY at #"))
|
|
825
|
+
|
|
826
|
+
for failure in failures:
|
|
827
|
+
print(f"packet --self-test [FAIL] {failure}")
|
|
828
|
+
if failures:
|
|
829
|
+
return 1
|
|
830
|
+
print(f"packet --self-test: OK ({len(ran)} controls: " + ", ".join(ran) + "; room left in the "
|
|
831
|
+
f"{bound.PACKET_OVERHEAD}-byte overhead: " + ", ".join(f"{k} {v}" for k, v in room.items()) + ")")
|
|
832
|
+
return 0
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
if __name__ == "__main__":
|
|
836
|
+
if "--self-test" not in sys.argv[1:]:
|
|
837
|
+
sys.exit("usage: packet.py --self-test")
|
|
838
|
+
sys.exit(self_test())
|