agent-bios 0.19.4 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/DEPENDENCIES.md +19 -5
  2. package/README.md +14 -19
  3. package/claude/agents/frontier.md +1 -1
  4. package/claude/guides/claude-prompting.md +475 -234
  5. package/claude/guides/cli-multi-model-workflow.md +4 -3
  6. package/claude/guides/gpt-prompting.md +235 -136
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/guides/claude-prompting.md +475 -234
  10. package/codex/guides/cli-multi-model-workflow.md +4 -3
  11. package/codex/guides/gpt-prompting.md +235 -136
  12. package/codex/guides/session-distill-workflow.md +93 -43
  13. package/codex/guides/tooling-gotchas.md +3 -1
  14. package/compose/assemble.py +4 -1
  15. package/compose/canary.sh +8 -6
  16. package/compose/host_platform.py +158 -15
  17. package/compose/instructions-state.py +183 -41
  18. package/compose/instructions_install.py +222 -27
  19. package/compose/instructions_session.py +250 -75
  20. package/compose/instructions_setup_cli.py +2 -36
  21. package/compose/instructions_store.py +160 -3
  22. package/compose/instructions_transaction.py +29 -5
  23. package/docs/advanced-launch.md +4 -0
  24. package/docs/releases/0.20.0.md +102 -0
  25. package/install.sh +42 -14
  26. package/launch/agent-launch.py +152 -18
  27. package/launch/agent-launch.toml +17 -7
  28. package/launch/agent-launch.zsh +104 -13
  29. package/launch/claude_subcommands.py +179 -0
  30. package/launch/shell_integration.py +7 -1
  31. package/learn/collect-learning.py +60 -9
  32. package/learn/migrate-learnings.py +70 -4
  33. package/learn/redact.py +2 -1
  34. package/package.json +36 -3
  35. package/provenance.json +1 -1
  36. package/session-cost.py +80 -9
  37. package/session-distill/coverage.json +6 -0
  38. package/session-distill/distill.py +2575 -0
  39. package/session-distill/grammar/__init__.py +0 -0
  40. package/session-distill/grammar/owner_lines.py +874 -0
  41. package/session-distill/originators.json +9 -0
  42. package/session-distill/packets/cross_review.md +31 -0
  43. package/session-distill/packets/form.md +86 -0
  44. package/session-distill/packets/judge.md +81 -0
  45. package/session-distill/packets/placement_contract.md +90 -0
  46. package/session-distill/packets/propose.md +124 -0
  47. package/session-distill/packets/read.md +57 -0
  48. package/session-distill/packets/reconsider.md +53 -0
  49. package/session-distill/packets/s7b.md +65 -0
  50. package/session-distill/packets/s9b.md +39 -0
  51. package/session-distill/packets/stitch.md +35 -0
  52. package/session-distill/packets/sweep.md +33 -0
  53. package/session-distill/runlib/__init__.py +0 -0
  54. package/session-distill/runlib/bound.py +1102 -0
  55. package/session-distill/runlib/breaker.py +467 -0
  56. package/session-distill/runlib/census.py +2347 -0
  57. package/session-distill/runlib/claims.py +420 -0
  58. package/session-distill/runlib/controls.py +902 -0
  59. package/session-distill/runlib/coverage.py +881 -0
  60. package/session-distill/runlib/declare.py +888 -0
  61. package/session-distill/runlib/delivery_evidence.py +1145 -0
  62. package/session-distill/runlib/derive.py +812 -0
  63. package/session-distill/runlib/destinations.py +3072 -0
  64. package/session-distill/runlib/dispatch.py +7939 -0
  65. package/session-distill/runlib/drift.py +1077 -0
  66. package/session-distill/runlib/entry.py +401 -0
  67. package/session-distill/runlib/evidence.py +890 -0
  68. package/session-distill/runlib/exposure.py +1162 -0
  69. package/session-distill/runlib/gate.py +2727 -0
  70. package/session-distill/runlib/gitread.py +79 -0
  71. package/session-distill/runlib/inventory.py +19624 -0
  72. package/session-distill/runlib/journal.py +1919 -0
  73. package/session-distill/runlib/ledger.py +3210 -0
  74. package/session-distill/runlib/ledger_compat.py +101 -0
  75. package/session-distill/runlib/ledger_migration.py +190 -0
  76. package/session-distill/runlib/lifecycle_intake.py +693 -0
  77. package/session-distill/runlib/lineage.py +454 -0
  78. package/session-distill/runlib/measures.py +249 -0
  79. package/session-distill/runlib/monitor.py +1180 -0
  80. package/session-distill/runlib/operations.py +522 -0
  81. package/session-distill/runlib/packet.py +838 -0
  82. package/session-distill/runlib/placement.py +1769 -0
  83. package/session-distill/runlib/projection.py +4090 -0
  84. package/session-distill/runlib/ranking.py +740 -0
  85. package/session-distill/runlib/receipts.py +200 -0
  86. package/session-distill/runlib/records.py +1965 -0
  87. package/session-distill/runlib/search.py +249 -0
  88. package/session-distill/runlib/sequencing.py +829 -0
  89. package/session-distill/runlib/sources.py +641 -0
  90. package/session-distill/runlib/stage_adjudicate.py +845 -0
  91. package/session-distill/runlib/stage_apply.py +1378 -0
  92. package/session-distill/runlib/stage_approvals.py +758 -0
  93. package/session-distill/runlib/stage_close.py +1220 -0
  94. package/session-distill/runlib/stage_confirm.py +929 -0
  95. package/session-distill/runlib/stage_delivery.py +3080 -0
  96. package/session-distill/runlib/stage_form.py +2576 -0
  97. package/session-distill/runlib/stage_judge.py +4248 -0
  98. package/session-distill/runlib/stage_propose.py +3307 -0
  99. package/session-distill/runlib/stage_read.py +5179 -0
  100. package/session-distill/runlib/stage_render.py +2739 -0
  101. package/session-distill/runlib/stage_retrieve.py +924 -0
  102. package/session-distill/runlib/stage_review_korean.py +1002 -0
  103. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  104. package/session-distill/runlib/stagelock.py +412 -0
  105. package/session-distill/runlib/stop.py +1061 -0
  106. package/session-distill/runlib/targets.py +809 -0
  107. package/session-distill/runlib/usage.py +280 -0
  108. package/session-distill/runlib/validate.py +319 -0
  109. package/session-distill/runlib/views.py +4327 -0
  110. package/session-distill/schemas/adjudication.schema.json +35 -0
  111. package/session-distill/schemas/approval.schema.json +35 -0
  112. package/session-distill/schemas/census.schema.json +128 -0
  113. package/session-distill/schemas/checks.schema.json +207 -0
  114. package/session-distill/schemas/claim.schema.json +16 -0
  115. package/session-distill/schemas/confirmation.schema.json +24 -0
  116. package/session-distill/schemas/coverage.schema.json +66 -0
  117. package/session-distill/schemas/cross_review.schema.json +24 -0
  118. package/session-distill/schemas/event.schema.json +20 -0
  119. package/session-distill/schemas/evidence.schema.json +20 -0
  120. package/session-distill/schemas/expected_observation.schema.json +18 -0
  121. package/session-distill/schemas/form.schema.json +103 -0
  122. package/session-distill/schemas/intake.schema.json +71 -0
  123. package/session-distill/schemas/inventory.schema.json +872 -0
  124. package/session-distill/schemas/judge.schema.json +77 -0
  125. package/session-distill/schemas/ledger.schema.json +313 -0
  126. package/session-distill/schemas/observation.schema.json +16 -0
  127. package/session-distill/schemas/propose.schema.json +555 -0
  128. package/session-distill/schemas/read.schema.json +76 -0
  129. package/session-distill/schemas/reconsider.schema.json +122 -0
  130. package/session-distill/schemas/run.schema.json +150 -0
  131. package/session-distill/schemas/s7b.schema.json +200 -0
  132. package/session-distill/schemas/s9b.schema.json +28 -0
  133. package/session-distill/schemas/stitch.schema.json +25 -0
  134. package/session-distill/schemas/sweep.schema.json +25 -0
  135. package/session-distill/seats.json +149 -0
  136. package/session-distill/tables/allowed_pairs.json +257 -0
  137. package/session-distill/tables/controls.json +30 -0
  138. package/session-distill/tables/delivery_evidence.json +36 -0
  139. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  140. package/session-distill/tables/destinations.json +684 -0
  141. package/session-distill/tables/drift_layers.json +68 -0
  142. package/session-distill/tables/exposure_rules.json +192 -0
  143. package/session-distill/tables/placement_rules.json +148 -0
  144. package/session-distill/tables/propose_fixtures.json +154 -0
  145. package/session-distill/tables/ranking.json +194 -0
  146. package/session-distill/tables/redundancy.json +10 -0
  147. package/session-distill/tables/structural_rules.json +44 -0
  148. package/session-distill/tables/transition_fixtures.json +398 -0
  149. package/session-distill/tables/transitions.json +69 -0
  150. package/session-distill/tables/unit_outcome.json +67 -0
  151. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  152. package/wrappers/claude-run.sh +481 -33
  153. package/wrappers/claude_hermetic_evidence.py +1423 -0
  154. package/wrappers/codex-helm.sh +38 -7
  155. package/wrappers/codex-run.sh +183 -20
  156. package/wrappers/codex_frame_filter.py +1199 -0
  157. package/wrappers/codex_protocol.py +737 -0
  158. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,280 @@
1
+ #!/usr/bin/env python3
2
+ """Per-call usage in the three states of design §13.3, and its one estimate rule.
3
+
4
+ Every model call leaves `calls/<call_id>/usage.json`, captured before any temporary home is
5
+ deleted: the call id, the stage, the seat requested and the models observed per role, the
6
+ input, output and cache tokens of every request, the wall time and the host's attempts. Each
7
+ request is in one of three states, kept apart:
8
+
9
+ measured the host reported its usage (the four token counts are set)
10
+ provisional its final usage has not arrived; it is carried at an estimate, labelled as one
11
+ unresolved no estimate is possible (the agent has no earlier request to start from)
12
+
13
+ The estimate is the same agent's previous request plus the new content (characters / 3),
14
+ with a safety factor of 2 on tool results; never the class's highest observed request, which
15
+ later requests exceeded in probe 9. The totals keep the states apart (measured tokens,
16
+ provisional tokens, the count of unresolved requests) and `complete` stays false until every
17
+ request is measured and the closing aggregate has reconciled (`reconciled`). A call's state,
18
+ as its receipt carries it, is `measured` only when complete.
19
+
20
+ What a call's driver bytes took as tokens is read from its first main request (`first_input`), and
21
+ what the host's own retry of a refused structured output added from each later one (`retry_shares`);
22
+ the two are kept apart, so a retry is never read as density (WP-08e).
23
+
24
+ Failures are named USAGE_INVALID.
25
+
26
+ usage.py --self-test
27
+ """
28
+ import json
29
+ import math
30
+ import pathlib
31
+ import sys
32
+
33
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
34
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
35
+ from runlib import validate
36
+
37
+ STATES = ("measured", "provisional", "unresolved")
38
+ SAFETY_FACTOR = 2 # on tool-result content (design §13.3: "at least 2")
39
+ TOKEN_KEYS = ("input", "output", "cache_read", "cache_creation")
40
+ ROLES = ("main", "subagent", "child", "compaction", "warmup", "unknown")
41
+
42
+ SCHEMA = {
43
+ "$comment": "design §13.3: call_id, stage, seat requested and observed, input, output and cache tokens per "
44
+ "request, wall time, attempts; the plan adds `reconciled` (the closing reconciliation complete waits for)",
45
+ "type": "object",
46
+ "additionalProperties": False,
47
+ "required": ["call_id", "stage", "seat_requested", "seat_observed", "requests", "wall_ms", "attempts",
48
+ "reconciled"],
49
+ "properties": {
50
+ "call_id": {"type": "string", "minLength": 1},
51
+ "stage": {"type": "string", "minLength": 1},
52
+ "seat_requested": {"type": "string", "minLength": 1},
53
+ "seat_observed": {"type": "object", "additionalProperties": False,
54
+ "patternProperties": {"^[a-z]+$": {"type": "array", "items": {"type": "string"}}}},
55
+ "requests": {"type": "array", "items": {"$ref": "#/$defs/request"}},
56
+ "wall_ms": {"type": ["integer", "null"], "minimum": 0},
57
+ "attempts": {"type": "integer", "minimum": 0},
58
+ "reconciled": {"type": "boolean"},
59
+ },
60
+ "$defs": {
61
+ "count": {"type": ["integer", "null"], "minimum": 0},
62
+ "request": {
63
+ "type": "object",
64
+ "additionalProperties": False,
65
+ "required": ["id", "role", "state", *TOKEN_KEYS, "estimate"],
66
+ "properties": {"id": {"type": "string", "minLength": 1}, "role": {"enum": list(ROLES)},
67
+ "state": {"enum": list(STATES)}, "estimate": {"$ref": "#/$defs/count"},
68
+ **{key: {"$ref": "#/$defs/count"} for key in TOKEN_KEYS}},
69
+ },
70
+ },
71
+ }
72
+ VALIDATOR = validate.compile_schema(SCHEMA)
73
+
74
+
75
+ # a Codex otel completion's token counts and the frame response usage they must equal (design §3.2's join)
76
+ OTEL_PAIRS = (("input_token_count", "input_tokens"), ("output_token_count", "output_tokens"),
77
+ ("cached_token_count", "cached_tokens"), ("cache_write_token_count", "cache_write_tokens"))
78
+
79
+
80
+ def same_usage(comp, usage):
81
+ """Every token count the otel row carries equals the frame response's (absent on both is equal)."""
82
+ return isinstance(usage, dict) and all(
83
+ comp.get(otel) is None and usage.get(frame) in (None, 0) or str(usage.get(frame) or 0) == str(comp.get(otel))
84
+ for otel, frame in OTEL_PAIRS)
85
+
86
+
87
+ def request_total(request):
88
+ return sum(request.get(key) or 0 for key in TOKEN_KEYS)
89
+
90
+
91
+ INPUT_KEYS = ("input", "cache_read", "cache_creation") # what one request put in front of the model
92
+
93
+
94
+ def countable(value):
95
+ return isinstance(value, int) and not isinstance(value, bool) and value >= 0
96
+
97
+
98
+ def request_input(request):
99
+ """The input one measured request put in front of the model (input, cache read and cache creation), or None when
100
+ the request is not measured or a count is not a count."""
101
+ if not isinstance(request, dict) or request.get("state") != "measured":
102
+ return None
103
+ counts = [request.get(key) for key in INPUT_KEYS]
104
+ return sum(counts) if all(countable(c) for c in counts) else None
105
+
106
+
107
+ def main_requests(requests):
108
+ """A call's main-agent requests, in the order the host made them."""
109
+ return [r for r in (requests or []) if isinstance(r, dict) and r.get("role") == "main"]
110
+
111
+
112
+ def first_input(requests):
113
+ """The input of a call's FIRST main request, or None when it is not measured (WP-08e). The first request carries the
114
+ packet alone, so the driver bytes over it are what the text takes as tokens. A later main request of the same call
115
+ is the host's own retry of a refused structured output: it carries the first answer and the refusal on top, which is
116
+ a retry's margin (`retry_shares`), never density. Summing a call's requests read C2's window 8 at 1.01 bytes a token
117
+ and its largest request at 1.90, where its first request read 2.16."""
118
+ mains = main_requests(requests)
119
+ return request_input(mains[0]) if mains else None
120
+
121
+
122
+ def retry_shares(requests):
123
+ """What each later main request of a call put in front of the model beyond the request before it and that
124
+ request's answer: the error text of a refused structured output, with whatever the host adds around it (WP-08e).
125
+ Empty for a call of one request; a pair with a count missing is left out."""
126
+ mains, shares = main_requests(requests), []
127
+ for before, after in zip(mains, mains[1:]):
128
+ a, b = request_input(before), request_input(after)
129
+ if a is not None and b is not None and countable(before.get("output")):
130
+ shares.append(b - a - before["output"])
131
+ return shares
132
+
133
+
134
+ def estimate(previous_total, new_content_chars=0, tool_result=False):
135
+ """The provisional figure of a request in flight: the same agent's previous request plus
136
+ the new content at three characters a token, doubled for tool results; None (unresolved)
137
+ when the agent has no previous request."""
138
+ if previous_total is None:
139
+ return None
140
+ return previous_total + (SAFETY_FACTOR if tool_result else 1) * math.ceil(new_content_chars / 3)
141
+
142
+
143
+ def check(record):
144
+ """Every violation of one usage record, schema and state rules; empty when it holds."""
145
+ errors = [f"USAGE_INVALID {line}" for line in validate.validate_instance(VALIDATOR, record)]
146
+ if errors:
147
+ return errors
148
+ for request in record["requests"]:
149
+ counts = [request[key] for key in TOKEN_KEYS]
150
+ if request["state"] == "measured" and None in counts:
151
+ errors.append(f"USAGE_INVALID {request['id']}: measured without all four token counts")
152
+ if request["state"] != "measured" and any(c is not None for c in counts):
153
+ errors.append(f"USAGE_INVALID {request['id']}: {request['state']} but carries token counts")
154
+ if (request["state"] == "provisional") != (request["estimate"] is not None):
155
+ errors.append(f"USAGE_INVALID {request['id']}: only a provisional request carries an estimate")
156
+ return errors
157
+
158
+
159
+ def totals(record):
160
+ """`{measured, provisional, unresolved, complete}`, the shape a stage record sums."""
161
+ requests = record["requests"]
162
+ measured = sum(request_total(r) for r in requests if r["state"] == "measured")
163
+ provisional = sum(r["estimate"] for r in requests if r["state"] == "provisional")
164
+ unresolved = sum(1 for r in requests if r["state"] == "unresolved")
165
+ complete = bool(record["reconciled"]) and provisional == 0 and unresolved == 0 \
166
+ and all(r["state"] == "measured" for r in requests)
167
+ return {"measured": measured, "provisional": provisional, "unresolved": unresolved, "complete": complete}
168
+
169
+
170
+ def call_state(record):
171
+ """What the receipt's `usage_state` says: measured only when complete."""
172
+ summed = totals(record)
173
+ if summed["complete"]:
174
+ return "measured"
175
+ return "unresolved" if summed["unresolved"] else "provisional"
176
+
177
+
178
+ def totals_text(record):
179
+ """The receipt's `usage_totals`: the totals as canonical JSON."""
180
+ return json.dumps(totals(record), sort_keys=True, separators=(",", ":"))
181
+
182
+
183
+ def self_test():
184
+ failures, ran = [], []
185
+
186
+ def control(name, errors, *needles):
187
+ ran.append(name)
188
+ if not needles and errors:
189
+ failures.append(f"{name}: expected no violation, got {errors}")
190
+ for needle in needles:
191
+ if not any(needle in line for line in errors):
192
+ failures.append(f"{name}: expected {needle!r} in {errors}")
193
+
194
+ def req(rid, state, tokens=None, est=None, role="main"):
195
+ counts = dict(zip(TOKEN_KEYS, tokens or (None,) * 4))
196
+ return {"id": rid, "role": role, "state": state, **counts, "estimate": est}
197
+
198
+ def record(*requests, reconciled=True):
199
+ return {"call_id": "r1-S6-x-a1", "stage": "S6", "seat_requested": "claude:claude-opus-5-5/high",
200
+ "seat_observed": {"main": ["claude-opus-5-5"]}, "requests": list(requests), "wall_ms": 4111,
201
+ "attempts": len(requests), "reconciled": reconciled}
202
+
203
+ clean = record(req("q1", "measured", (2, 61, 2802, 351)))
204
+ control("valid-measured-record", check(clean)) # the positive control, first
205
+ control("measured-and-reconciled-is-complete",
206
+ [] if totals(clean) == {"measured": 3216, "provisional": 0, "unresolved": 0, "complete": True}
207
+ and call_state(clean) == "measured" else [f"totals {totals(clean)}, state {call_state(clean)}"])
208
+
209
+ # contract fidelity (WP-02 done-when 8): the states and the record's field list are design §13.3's,
210
+ # copied here once; `reconciled` is the plan's addition, named in the schema's $comment.
211
+ control("states-are-design-13.3", [] if STATES == ("measured", "provisional", "unresolved")
212
+ else [f"CONTRACT_MISMATCH usage states {STATES} (design §13.3)"])
213
+ section = {"call_id", "stage", "seat_requested", "seat_observed", "requests", "wall_ms", "attempts"}
214
+ control("fields-are-design-13.3", [] if set(SCHEMA["required"]) == section | {"reconciled"}
215
+ == set(SCHEMA["properties"]) and SCHEMA["$comment"].startswith("design §13.3")
216
+ else [f"CONTRACT_MISMATCH usage fields {sorted(SCHEMA['required'])} (design §13.3)"])
217
+ control("per-request-tokens-are-design-13.3",
218
+ [] if set(TOKEN_KEYS) == {"input", "output", "cache_read", "cache_creation"} else ["token keys"])
219
+
220
+ provisional = record(req("q1", "measured", (2, 61, 2802, 351)), req("q2", "provisional", est=4000))
221
+ control("provisional-is-not-complete",
222
+ [] if totals(provisional) == {"measured": 3216, "provisional": 4000, "unresolved": 0, "complete": False}
223
+ and call_state(provisional) == "provisional" else [f"totals {totals(provisional)}"])
224
+ unresolved = record(req("q1", "unresolved"))
225
+ control("unresolved-is-counted-not-estimated",
226
+ [] if totals(unresolved) == {"measured": 0, "provisional": 0, "unresolved": 1, "complete": False}
227
+ and call_state(unresolved) == "unresolved" else [f"totals {totals(unresolved)}"])
228
+ control("unreconciled-is-not-complete",
229
+ [] if not totals(record(req("q1", "measured", (1, 1, 1, 1)), reconciled=False))["complete"]
230
+ else ["a record whose closing aggregate has not reconciled was reported complete"])
231
+ control("empty-call-is-not-measured-unless-reconciled",
232
+ [] if call_state(record(reconciled=False)) == "provisional" else ["an empty unreconciled call read measured"])
233
+
234
+ # the estimate rule
235
+ control("estimate-previous-plus-content", [] if estimate(1000, 300) == 1100 else [f"{estimate(1000, 300)}"])
236
+ control("estimate-doubles-tool-results", [] if estimate(1000, 300, tool_result=True) == 1200
237
+ else [f"{estimate(1000, 300, tool_result=True)}"])
238
+ control("estimate-rounds-up", [] if estimate(0, 1) == 1 else [f"{estimate(0, 1)}"])
239
+ control("no-previous-request-is-unresolved", [] if estimate(None, 5000) is None else ["estimated from nothing"])
240
+
241
+ # WP-08e: C2's window 8 as its usage record held it (counts only): two main requests, the second the host's retry
242
+ c2_w8 = [req("main#1", "measured", (2, 6366, 3297, 50247)), req("main#2", "measured", (2, 3613, 53544, 7484))]
243
+ control("WP-08e: a call's density reads its first main request, never the sum of its requests or the largest",
244
+ [] if first_input(c2_w8) == 53546 else [f"first_input {first_input(c2_w8)}"])
245
+ control("WP-08e: a retry's share is what its request added beyond the request before it and that request's answer",
246
+ [] if retry_shares(c2_w8) == [1118] and retry_shares(c2_w8[:1]) == [] else [f"shares {retry_shares(c2_w8)}"])
247
+ control("WP-08e: a first request not measured gives no density",
248
+ [] if first_input([req("main#1", "provisional", est=5000), *c2_w8[1:]]) is None
249
+ and first_input([req("s#1", "measured", (1, 1, 1, 1), role="subagent")]) is None else ["read a density"])
250
+
251
+ # the state rules a schema cannot state
252
+ control("measured-without-counts", check(record(req("q1", "measured", (1, None, 1, 1)))),
253
+ "USAGE_INVALID q1: measured without all four")
254
+ control("provisional-with-counts", check(record({**req("q1", "provisional", est=5), "input": 3})),
255
+ "USAGE_INVALID q1: provisional but carries token counts")
256
+ control("provisional-without-estimate", check(record(req("q1", "provisional"))),
257
+ "USAGE_INVALID q1: only a provisional request carries an estimate")
258
+ control("unresolved-with-estimate", check(record(req("q1", "unresolved", est=7))),
259
+ "USAGE_INVALID q1: only a provisional request carries an estimate")
260
+ control("state-outside-the-three", check(record({**req("q1", "measured", (1, 1, 1, 1)), "state": "estimated"})),
261
+ "USAGE_INVALID requests/0/state")
262
+ control("role-outside-the-declared", check(record({**req("q1", "measured", (1, 1, 1, 1)), "role": "helper"})),
263
+ "USAGE_INVALID requests/0/role")
264
+ control("missing-field", check({k: v for k, v in clean.items() if k != "wall_ms"}),
265
+ "USAGE_INVALID <root>: 'wall_ms' is a required property")
266
+ control("totals-text-is-canonical", [] if totals_text(clean) ==
267
+ '{"complete":true,"measured":3216,"provisional":0,"unresolved":0}' else [totals_text(clean)])
268
+
269
+ for failure in failures:
270
+ print(f"usage --self-test [FAIL] {failure}")
271
+ if failures:
272
+ return 1
273
+ print(f"usage --self-test: OK ({len(ran)} controls: " + ", ".join(ran) + ")")
274
+ return 0
275
+
276
+
277
+ if __name__ == "__main__":
278
+ if "--self-test" not in sys.argv[1:]:
279
+ sys.exit("usage: usage.py --self-test")
280
+ sys.exit(self_test())
@@ -0,0 +1,319 @@
1
+ #!/usr/bin/env python3
2
+ """The one schema validator of the driver: jsonschema, loaded as learn/check-learning.py loads it.
3
+
4
+ A schema is accepted in two steps, in this order. `Draft202012Validator.check_schema` refuses
5
+ a schema that is not valid JSON Schema (it raises `SchemaError`). Then `lint` applies the
6
+ project's policy, which jsonschema does not: it accepts unknown keywords, open objects and
7
+ subschemas that say nothing about their type as valid. The policy is that every subschema
8
+ declares what it is (`type`, `enum`, `const` or a local `$ref`), every object schema is closed
9
+ (`additionalProperties: false`, whether or not it says `type: object`), and every keyword is
10
+ one this lint can see through. Instance validation stays jsonschema's.
11
+
12
+ The driver runs under the interpreter `learn/check-learning.py` runs under, and refuses by name
13
+ (JSONSCHEMA_MISSING, JSONSCHEMA_VERSION_MISMATCH, JSONSCHEMA_PIN_UNREADABLE) a jsonschema other
14
+ than the one `JSONSCHEMA_PIN` in `launch/provision-venv.sh` names: the pin has one owner, and
15
+ the installed version is read from the package metadata.
16
+
17
+ validate.py --self-test
18
+ """
19
+ import importlib.metadata
20
+ import pathlib
21
+ import re
22
+ import sys
23
+
24
+ try:
25
+ import jsonschema
26
+ except ImportError:
27
+ sys.exit("validate: JSONSCHEMA_MISSING: the 'jsonschema' package is required "
28
+ "(pip install jsonschema; verified 4.26.0 in DEPENDENCIES.md)")
29
+
30
+ PIN_FILE = pathlib.Path(__file__).resolve().parents[2] / "launch" / "provision-venv.sh"
31
+
32
+
33
+ def pinned_version(pin_file=PIN_FILE):
34
+ """The version `JSONSCHEMA_PIN` names in `pin_file`, or None when it names none."""
35
+ try:
36
+ match = re.search(r'^JSONSCHEMA_PIN="jsonschema==([^"]+)"$', pathlib.Path(pin_file).read_text(encoding="utf-8"), re.M)
37
+ except OSError:
38
+ return None
39
+ return match.group(1) if match else None
40
+
41
+
42
+ def version_problem(installed, pin_file=PIN_FILE):
43
+ """None when `installed` is the jsonschema version `JSONSCHEMA_PIN` names in `pin_file`,
44
+ else the named refusal."""
45
+ pin = pinned_version(pin_file)
46
+ if pin is None:
47
+ return f'JSONSCHEMA_PIN_UNREADABLE: {pin_file} has no JSONSCHEMA_PIN="jsonschema==<version>" line to compare with'
48
+ if installed != pin:
49
+ return f"JSONSCHEMA_VERSION_MISMATCH: jsonschema {installed} is installed, {pin_file} pins {pin}"
50
+ return None
51
+
52
+
53
+ _problem = version_problem(importlib.metadata.version("jsonschema"))
54
+ if _problem:
55
+ sys.exit(f"validate: {_problem}")
56
+
57
+ # Keywords the lint understands. A keyword that carries a subschema is supported only when
58
+ # `lint` descends into it, so a closed-object rule cannot be bypassed by hiding an open
59
+ # object under `allOf`, `anyOf`, `if` and the like: those are not supported.
60
+ SUPPORTED_KEYWORDS = frozenset({
61
+ "$schema", "$comment", "title", "type", "required", "enum", "const", "pattern",
62
+ "minimum", "minLength", "minItems", "maxItems", "minProperties", "uniqueItems",
63
+ "dependentRequired",
64
+ "additionalProperties", # only `false` passes the lint
65
+ "properties", "patternProperties", "items", "$defs", # the subschema carriers `lint` descends into
66
+ "$ref", # only `#/$defs/<name>` of the same schema
67
+ })
68
+ # A `$defs` name, and so the name a local `$ref` reads (WP-08c, W r2): letters, digits, `_` and `-` only. A JSON Pointer
69
+ # reads `~1` as "/" and `~0` as "~", and a URI fragment reads `%2F` as "/", so a name holding them is resolved by the
70
+ # policy's jsonschema as one entry and read as written by `packet.host_schema` as another. Within these characters a
71
+ # name reads the same in all three, so nothing is decoded anywhere.
72
+ LOCAL_NAME = re.compile(r"[A-Za-z0-9_-]+\Z")
73
+ LOCAL_REF = "#/$defs/"
74
+
75
+
76
+ def local_ref_name(ref):
77
+ """The `$defs` name a local reference names, or None when `ref` is not `#/$defs/<name>` with a name `LOCAL_NAME`
78
+ allows. `lint` and `packet.host_schema` both read a reference through this, so the two cannot read it apart."""
79
+ if not isinstance(ref, str) or not ref.startswith(LOCAL_REF):
80
+ return None
81
+ name = ref[len(LOCAL_REF):]
82
+ return name if LOCAL_NAME.match(name) else None
83
+ # Keywords that constrain an object; a subschema carrying any of them is an object schema
84
+ # whether or not it says `type: object`.
85
+ OBJECT_KEYWORDS = frozenset({"properties", "patternProperties", "required", "additionalProperties",
86
+ "minProperties", "dependentRequired"})
87
+
88
+
89
+ def lint(schema, path="#", root=None):
90
+ """Policy violations of one schema, each naming the keyword or the subschema's place."""
91
+ root = schema if root is None else root
92
+ if not isinstance(schema, dict):
93
+ return [f"SCHEMA_POLICY {path}: a subschema must be an object, got {type(schema).__name__}"]
94
+ errors = [f"SCHEMA_POLICY unknown keyword {key!r} at {path}"
95
+ for key in sorted(set(schema) - SUPPORTED_KEYWORDS)]
96
+ if "$ref" in schema:
97
+ ref = schema["$ref"]
98
+ name = local_ref_name(ref)
99
+ if name is None:
100
+ errors.append(f"SCHEMA_POLICY {path}: $ref must name an entry of this schema's $defs as {LOCAL_REF}<name>, "
101
+ f"the name of letters, digits, _ and - only (no JSON Pointer or URI escape), got {ref!r}")
102
+ elif name not in (root.get("$defs") or {}):
103
+ errors.append(f"SCHEMA_POLICY {path}: $ref must name an entry of this schema's $defs, got {ref!r}")
104
+ if not {"type", "enum", "const", "$ref"} & set(schema):
105
+ errors.append(f"SCHEMA_POLICY untyped subschema at {path}: declare type, enum, const or $ref")
106
+ types = schema.get("type")
107
+ types = types if isinstance(types, list) else [types]
108
+ if ("object" in types or OBJECT_KEYWORDS & set(schema)) and schema.get("additionalProperties") is not False:
109
+ errors.append(f"SCHEMA_POLICY open object at {path}: additionalProperties must be false")
110
+ for keyword in ("properties", "patternProperties", "$defs"):
111
+ for name, sub in (schema.get(keyword) or {}).items():
112
+ if keyword == "$defs" and not LOCAL_NAME.match(name):
113
+ errors.append(f"SCHEMA_POLICY {path}/$defs: the name {name!r} is not of letters, digits, _ and - only, "
114
+ "so a reference to it could be read as another entry")
115
+ errors.extend(lint(sub, f"{path}/{keyword}/{name}", root))
116
+ if "items" in schema:
117
+ errors.extend(lint(schema["items"], f"{path}/items", root))
118
+ return errors
119
+
120
+
121
+ class SchemaPolicyError(Exception):
122
+ """A schema that jsonschema accepts but the policy refuses; the message lists every violation."""
123
+
124
+
125
+ def compile_schema(schema):
126
+ """A validator for `schema`: `check_schema` first (raises `jsonschema.SchemaError`), then the lint."""
127
+ jsonschema.Draft202012Validator.check_schema(schema)
128
+ errors = lint(schema)
129
+ if errors:
130
+ raise SchemaPolicyError("; ".join(errors))
131
+ return jsonschema.Draft202012Validator(schema)
132
+
133
+
134
+ def violations(validator, instance):
135
+ """jsonschema's errors for `instance`, in a stable order (for callers that need structure)."""
136
+ return sorted(validator.iter_errors(instance), key=lambda e: list(map(str, e.absolute_path)))
137
+
138
+
139
+ def validate_instance(validator, instance):
140
+ """Every violation of `instance`, as `<json path>: <message>`; empty when it conforms."""
141
+ return [f"{'/'.join(str(p) for p in err.absolute_path) or '<root>'}: {err.message}"
142
+ for err in violations(validator, instance)]
143
+
144
+
145
+ def self_test():
146
+ import importlib.metadata
147
+ import importlib.util
148
+ failures = []
149
+ good = {"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object",
150
+ "additionalProperties": False, "required": ["a"],
151
+ "properties": {"a": {"type": "string"},
152
+ "b": {"type": "array", "items": {"type": "object",
153
+ "additionalProperties": False,
154
+ "properties": {"c": {"type": "integer"}}}}}}
155
+ try: # positive control first: the valid, closed schema compiles and validates
156
+ validator = compile_schema(good)
157
+ if validate_instance(validator, {"a": "x", "b": [{"c": 1}]}):
158
+ failures.append("a conforming instance was reported")
159
+ except Exception as exc:
160
+ failures.append(f"positive control: the valid closed schema was refused: {exc!r}")
161
+ validator = None
162
+
163
+ if validator is not None:
164
+ found = validate_instance(validator, {"b": [{"c": "x", "d": 1}]})
165
+ for want in ("<root>: 'a' is a required property", "b/0/c:", "b/0: Additional properties"):
166
+ if not any(want in line for line in found):
167
+ failures.append(f"instance violation missing {want!r}: {found}")
168
+
169
+ def refused_with(schema, error_type, needle):
170
+ try:
171
+ compile_schema(schema)
172
+ except error_type as exc:
173
+ return needle in str(exc)
174
+ except Exception:
175
+ return False
176
+ return False
177
+
178
+ if not refused_with({"type": "object", "required": "x"}, jsonschema.SchemaError, "'x' is not of type 'array'"):
179
+ failures.append("an invalid schema (required: \"x\") was not refused by check_schema with SchemaError")
180
+ unknown = {**good, "properties": {"a": {"type": "string", "x-note": "ignored by jsonschema"}}}
181
+ if not refused_with(unknown, SchemaPolicyError, "unknown keyword 'x-note' at #/properties/a"):
182
+ failures.append("an unknown keyword was not refused by the lint, naming the keyword and its place")
183
+ if not refused_with({k: v for k, v in good.items() if k != "additionalProperties"},
184
+ SchemaPolicyError, "open object at #:"):
185
+ failures.append("an object without additionalProperties: false was not refused by the lint")
186
+ nested = {**good, "properties": {"b": {"type": "array", "items": {"type": "object", "properties": {}}}}}
187
+ if not refused_with(nested, SchemaPolicyError, "open object at #/properties/b/items"):
188
+ failures.append("an open object nested under items was not named by its path")
189
+ for open_form in (True, {"type": "string"}):
190
+ if not refused_with({**good, "additionalProperties": open_form}, SchemaPolicyError, "open object at #:"):
191
+ failures.append(f"additionalProperties {open_form!r} was not refused")
192
+ if not refused_with({**good, "allOf": [{"type": "object"}]}, SchemaPolicyError, "unknown keyword 'allOf'"):
193
+ failures.append("a subschema carrier the lint cannot see (allOf) was not refused")
194
+ # an object that never says `type: object` is still an object schema, and must be closed
195
+ implicit = {**good, "properties": {"a": {"required": ["x"], "additionalProperties": True}}}
196
+ if not refused_with(implicit, SchemaPolicyError, "open object at #/properties/a"):
197
+ failures.append("an implicit object schema (object keywords, no type) was not refused as open")
198
+ implicit_bare = {**good, "properties": {"a": {"required": ["x"]}}}
199
+ if not refused_with(implicit_bare, SchemaPolicyError, "open object at #/properties/a"):
200
+ failures.append("an implicit object schema without additionalProperties was not refused as open")
201
+ for bare in ({}, {"minLength": 1}):
202
+ if not refused_with({**good, "properties": {"a": bare}}, SchemaPolicyError, "untyped subschema at #/properties/a"):
203
+ failures.append(f"an untyped subschema {bare!r} was not refused")
204
+ mapped = {"type": "object", "additionalProperties": False, "minProperties": 1,
205
+ "patternProperties": {"^[a-z]+$": {"type": "object", "properties": {}}}}
206
+ if not refused_with(mapped, SchemaPolicyError, "open object at #/patternProperties/^[a-z]+$"):
207
+ failures.append("an open object under patternProperties was not named by its path")
208
+ # positive controls for the carriers the lint supports: $defs with $ref, and a closed patternProperties map
209
+ shared = {"type": "object", "additionalProperties": False, "required": ["k"],
210
+ "$defs": {"sha": {"type": "string", "pattern": "^[0-9a-f]{4}$"}},
211
+ "properties": {"k": {"$ref": "#/$defs/sha"}},
212
+ "patternProperties": {"^x-": {"$ref": "#/$defs/sha"}}}
213
+ try:
214
+ validator_shared = compile_schema(shared)
215
+ if validate_instance(validator_shared, {"k": "abcd", "x-1": "0123"}):
216
+ failures.append("a conforming instance of a $ref schema was reported")
217
+ if not validate_instance(validator_shared, {"k": "zzzz"}):
218
+ failures.append("the $ref'd definition did not constrain the instance")
219
+ if not validate_instance(validator_shared, {"k": "abcd", "other": "abcd"}):
220
+ failures.append("a key outside patternProperties was accepted by a closed map")
221
+ except Exception as exc:
222
+ failures.append(f"positive control: a closed $defs/$ref/patternProperties schema was refused: {exc!r}")
223
+ for ref in ("#/$defs/missing", "https://example.invalid/schema.json", "#/properties/k"):
224
+ if not refused_with({**shared, "properties": {"k": {"$ref": ref}}}, SchemaPolicyError,
225
+ "$ref must name an entry of this schema's $defs"):
226
+ failures.append(f"$ref {ref!r} was not refused")
227
+ if not refused_with({**good, "properties": {"a": True}}, SchemaPolicyError, "must be an object"):
228
+ failures.append("a boolean subschema was not refused")
229
+ # WP-08c (W r2): a $defs name and a $ref's name are letters, digits, _ and - only. A JSON Pointer reads "~1" as "/"
230
+ # and "~0" as "~", a URI fragment "%2F" as "/", so jsonschema resolves such a name as one entry while a reader of
231
+ # it as written takes another: with both "a/b" and "a~1b" defined, "#/$defs/a~1b" is "a/b" to jsonschema
232
+ escaped = {"type": "object", "additionalProperties": False, "required": ["x"],
233
+ "$defs": {"a/b": {"type": "integer"}, "a~1b": {"type": "string"}},
234
+ "properties": {"x": {"$ref": "#/$defs/a~1b"}}}
235
+ for label, schema, needle in (
236
+ ("both spellings defined (the reference)", escaped, "as #/$defs/<name>, the name of letters"),
237
+ ("both spellings defined (the names)", escaped, "the name 'a/b' is not of letters"),
238
+ ("~1", {**shared, "$defs": {"a~1b": {"type": "string"}}, "properties": {"k": {"$ref": "#/$defs/a~1b"}},
239
+ "patternProperties": {}}, "as #/$defs/<name>, the name of letters"),
240
+ ("~0", {**shared, "$defs": {"a~0b": {"type": "string"}}, "properties": {"k": {"$ref": "#/$defs/a~0b"}},
241
+ "patternProperties": {}}, "as #/$defs/<name>, the name of letters"),
242
+ ("%2F", {**shared, "$defs": {"a%2Fb": {"type": "string"}}, "properties": {"k": {"$ref": "#/$defs/a%2Fb"}},
243
+ "patternProperties": {}}, "as #/$defs/<name>, the name of letters"),
244
+ ("an escaped reference to a plain name", {**shared, "properties": {"k": {"$ref": "#/$defs/sh%61"}}},
245
+ "as #/$defs/<name>, the name of letters"),
246
+ ("a name no reference reads", {**shared, "$defs": {**shared["$defs"], "a.b": {"type": "string"}}},
247
+ "the name 'a.b' is not of letters")):
248
+ if not refused_with(schema, SchemaPolicyError, needle):
249
+ failures.append(f"an escaped $defs or $ref name, {label}, was not refused naming {needle!r}")
250
+ if [local_ref_name(r) for r in ("#/$defs/sha", "#/$defs/a_b-1", "#/$defs/a~1b", "#/$defs/", "#/$defs/a\n", 3)] \
251
+ != ["sha", "a_b-1", None, None, None, None]:
252
+ failures.append("local_ref_name read a name other than letters, digits, _ and -, or refused one of them")
253
+
254
+ # a missing package and a package of another version are named failures at import, never a silent skip
255
+ source = pathlib.Path(__file__).read_text(encoding="utf-8")
256
+
257
+ def import_outcome(installed=None, missing=False):
258
+ """What importing this module says when jsonschema is missing, or reports `installed`."""
259
+ saved_module, saved_version = sys.modules.get("jsonschema"), importlib.metadata.version
260
+ if missing:
261
+ sys.modules["jsonschema"] = None # makes `import jsonschema` raise ImportError
262
+ if installed is not None:
263
+ importlib.metadata.version = lambda name: installed
264
+ try:
265
+ module = importlib.util.module_from_spec(importlib.util.spec_from_loader("validate_probe", loader=None))
266
+ module.__dict__["__file__"] = __file__
267
+ exec(compile(source, __file__, "exec"), module.__dict__)
268
+ return "imported"
269
+ except SystemExit as exc:
270
+ return str(exc)
271
+ finally:
272
+ importlib.metadata.version = saved_version
273
+ if saved_module is None:
274
+ sys.modules.pop("jsonschema", None)
275
+ else:
276
+ sys.modules["jsonschema"] = saved_module
277
+
278
+ real_pin = pinned_version()
279
+ if real_pin is None:
280
+ failures.append(f"the real pin file {PIN_FILE} names no jsonschema version")
281
+ real_pin = "unreadable"
282
+ if "JSONSCHEMA_MISSING" not in import_outcome(missing=True):
283
+ failures.append("import without jsonschema did not fail by name")
284
+ if import_outcome(installed=real_pin) != "imported":
285
+ failures.append("import under the pinned version was refused")
286
+ if version_problem(importlib.metadata.version("jsonschema")) is not None:
287
+ failures.append(f"the interpreter running this self-test does not carry the pinned jsonschema: "
288
+ f"{version_problem(importlib.metadata.version('jsonschema'))}")
289
+ outcome = import_outcome(installed="4.25.1")
290
+ if "JSONSCHEMA_VERSION_MISMATCH" not in outcome or "4.25.1" not in outcome or real_pin not in outcome:
291
+ failures.append(f"import under another jsonschema version did not fail naming both versions: {outcome}")
292
+ import tempfile
293
+ with tempfile.TemporaryDirectory() as td:
294
+ scratch = pathlib.Path(td) / "provision-venv.sh"
295
+ text = PIN_FILE.read_text(encoding="utf-8")
296
+ scratch.write_text(text.replace(f'"jsonschema=={real_pin}"', '"jsonschema==9.9.9"'), encoding="utf-8")
297
+ planted = version_problem(importlib.metadata.version("jsonschema"), scratch)
298
+ if not (planted and "JSONSCHEMA_VERSION_MISMATCH" in planted and "9.9.9" in planted):
299
+ failures.append(f"a planted pin 9.9.9 was not refused by name: {planted}")
300
+ scratch.write_text(text.replace("JSONSCHEMA_PIN=", "OTHER_PIN="), encoding="utf-8")
301
+ if "JSONSCHEMA_PIN_UNREADABLE" not in (version_problem(real_pin, scratch) or ""):
302
+ failures.append("a pin file without JSONSCHEMA_PIN was not refused by name")
303
+ if "JSONSCHEMA_PIN_UNREADABLE" not in (version_problem(real_pin, pathlib.Path(td) / "absent.sh") or ""):
304
+ failures.append("a missing pin file was not refused by name")
305
+
306
+ for failure in failures:
307
+ print(f"validate --self-test [FAIL] {failure}")
308
+ if failures:
309
+ return 1
310
+ print(f"validate --self-test: OK (jsonschema {importlib.metadata.version('jsonschema')}; check_schema refusal, "
311
+ "unknown keyword, open object (explicit, nested, implicit, under patternProperties), untyped "
312
+ "subschema, hidden subschema, $defs/$ref, missing package)")
313
+ return 0
314
+
315
+
316
+ if __name__ == "__main__":
317
+ if "--self-test" not in sys.argv[1:]:
318
+ sys.exit("usage: validate.py --self-test")
319
+ sys.exit(self_test())