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,2347 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""S1, the census (design §5.1, §5.2, §5.3): what transcripts exist, which are the owner's, and what each owes.
|
|
3
|
+
|
|
4
|
+
Enumeration starts from the transcript directories (`claude_projects`, `codex_sessions`,
|
|
5
|
+
`codex_archived_sessions`), plain and zstd-compressed alike, and takes the union with the identities the
|
|
6
|
+
host indexes name for the window. Every discovered identity ends in exactly one status of §5.1:
|
|
7
|
+
`excluded(reason)`, `child_of(parent)`, `unknown_provenance`, `unreadable`, `known_absent`, or eligible,
|
|
8
|
+
which S3's results later turn into `read_complete`, `read_partial`, `failed` or `deferred` (`reconcile`).
|
|
9
|
+
`nothing_new` is decided here, when the window owns nothing the coverage state still owes. A source whose
|
|
10
|
+
directory is missing is reported unknown with no total, never zero.
|
|
11
|
+
|
|
12
|
+
Every transcript is read at its head, which is enough for its class and for the children and the
|
|
13
|
+
automated rollouts that are known by their first record. Every eligible transcript is then read in full,
|
|
14
|
+
once, whatever its age: sha, record count, the append-only test against the version on record, the records
|
|
15
|
+
the window owns, and all the lineage evidence (pointers, host-minted record ids, (timestamp, human text)
|
|
16
|
+
turns) wherever in the file it lies, because an old transcript's only link to an active one may be past
|
|
17
|
+
its head. The version is the transcript's complete lines (D-20261103-8facee): a line the host is still
|
|
18
|
+
writing is not in it, and what the host appends after this read is the next run's. The next run reads another
|
|
19
|
+
window, so what it finds appended to a version and stamped inside a window already run - a line that was still being
|
|
20
|
+
written then, or one written late - it holds in the backlog under that window, for itself to read (`carry_appended`).
|
|
21
|
+
|
|
22
|
+
Every row's `window_overlap` says how it lies against the window: from its record timestamps for a row read in full
|
|
23
|
+
(inside, straddles_start, straddles_end, straddles_both, context_only); for a row left unread - unknown, unreadable, or
|
|
24
|
+
a member of such a root - from the best evidence its files give (`unread_overlap`): `before_window` when each was last
|
|
25
|
+
written before the window starts, its record timestamps otherwise, `undetermined` when neither decides. The observation
|
|
26
|
+
basis counts a row only when its unit may hold a record of the window (D-20261106-208882).
|
|
27
|
+
|
|
28
|
+
The unit S1 judges and S2 reads is a root with all its descendants at any depth (D-20261103-85f3e8): every
|
|
29
|
+
member of an eligible root is read in full like the root, and the root is `nothing_new` only when neither it
|
|
30
|
+
nor any member owes the window anything. A member whose read fails leaves the unit and its descendants stay in it:
|
|
31
|
+
the unit follows the parent links, not the statuses. One S3 result answers the unit, crediting each member's readings to
|
|
32
|
+
the member. Counting follows §5.3: a lineage counts once, through its root, when its component has exactly
|
|
33
|
+
one root and a host-written index names that root.
|
|
34
|
+
|
|
35
|
+
Identity is `(host, session id)`: a transcript is keyed `<host>:<id>` (`lineage.identity`) in the coverage
|
|
36
|
+
state, in lineage components and in S3's results. The originator table is a declared source of the run
|
|
37
|
+
(`name: originators`, its `path` and `sha256`); S1 reads exactly those bytes.
|
|
38
|
+
|
|
39
|
+
An S3 result, which `reconcile` takes, is `{transcript, status, readings, pending_events, resolved_events}`,
|
|
40
|
+
`readings` a list of `{version, sha, read, processed}` over the versions it read (`processed` is keyed by
|
|
41
|
+
window id); `coverage.apply_results` says what each field must satisfy.
|
|
42
|
+
|
|
43
|
+
The legacy `session-distill/census.py` survives the cutover as an author-side window tool (the v1 window
|
|
44
|
+
census), not as part of this pipeline; this module is `distill.py census`.
|
|
45
|
+
Failures are named by their first word: SET_MISMATCH, ORIGINATOR_TABLE_INVALID, ORIGINATOR_TABLE_UNDECLARED,
|
|
46
|
+
ORIGINATOR_TABLE_CHANGED, COVERAGE_BASE_STALE, CENSUS_INVALID, RUN_PATH_ESCAPE (the snapshot directory leaves the run).
|
|
47
|
+
|
|
48
|
+
census.py --self-test
|
|
49
|
+
"""
|
|
50
|
+
import concurrent.futures
|
|
51
|
+
import contextlib
|
|
52
|
+
import copy
|
|
53
|
+
import datetime
|
|
54
|
+
import functools
|
|
55
|
+
import hashlib
|
|
56
|
+
import json
|
|
57
|
+
import os
|
|
58
|
+
import pathlib
|
|
59
|
+
import re
|
|
60
|
+
import shutil
|
|
61
|
+
import sqlite3
|
|
62
|
+
import subprocess
|
|
63
|
+
import sys
|
|
64
|
+
import tempfile
|
|
65
|
+
|
|
66
|
+
if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
|
|
67
|
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
68
|
+
from runlib import coverage, lineage, records, sources, stagelock, validate
|
|
69
|
+
from runlib.records import Refused
|
|
70
|
+
|
|
71
|
+
HERE = pathlib.Path(__file__).resolve().parents[1]
|
|
72
|
+
SCHEMA_PATH = HERE / "schemas" / "census.schema.json"
|
|
73
|
+
ORIGINATORS_PATH = HERE / "originators.json"
|
|
74
|
+
ORIGINATORS_SOURCE = "originators" # the name under which a run declares its originator table
|
|
75
|
+
CLASSES = ("claude-cli", "claude-desktop", "codex-cli", "codex-desktop")
|
|
76
|
+
TABLE_CLASSES = ("codex-cli", "codex-desktop", "excluded", "unknown_provenance")
|
|
77
|
+
DIRECTORIES = ("claude_projects", "codex_sessions", "codex_archived_sessions", "claude_desktop_index", "agent_bios_state")
|
|
78
|
+
HEAD_RECORDS = 256 # records of a head: enough to classify a transcript before it is read in full
|
|
79
|
+
ENTRYPOINT_SCAN = 4096 # how far into a Claude file the first entrypoint is looked for
|
|
80
|
+
# Rows the census leaves unread whose place against the window the observation basis still needs (D-20261106-208882),
|
|
81
|
+
# and the window_overlap values that say a row holds no record of the window: by its record timestamps, or by the
|
|
82
|
+
# file-time bound (`unread_overlap`).
|
|
83
|
+
UNREAD_STATUSES = ("unknown_provenance", "unreadable")
|
|
84
|
+
OUTSIDE = ("context_only", "before_window")
|
|
85
|
+
UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
|
86
|
+
_VALIDATOR = []
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def validator():
|
|
90
|
+
if not _VALIDATOR:
|
|
91
|
+
_VALIDATOR.append(validate.compile_schema(json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))))
|
|
92
|
+
return _VALIDATOR[0]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def load_originators(path=ORIGINATORS_PATH):
|
|
96
|
+
"""(`{originator: class}`, sha256 of the file): the owner's table that assigns a source class to the
|
|
97
|
+
Codex clients that all write `vscode` (design §5.1)."""
|
|
98
|
+
data = pathlib.Path(path).read_bytes()
|
|
99
|
+
try:
|
|
100
|
+
table = json.loads(data)["codex"]
|
|
101
|
+
bad = {k: v for k, v in table.items() if v not in TABLE_CLASSES}
|
|
102
|
+
except (ValueError, KeyError, AttributeError, TypeError) as exc:
|
|
103
|
+
raise Refused(f"ORIGINATOR_TABLE_INVALID {path}: expected {{\"codex\": {{originator: class}}}} ({exc})") from exc
|
|
104
|
+
if bad:
|
|
105
|
+
raise Refused(f"ORIGINATOR_TABLE_INVALID {path}: {bad} are not one of {TABLE_CLASSES}")
|
|
106
|
+
return table, records.sha256_bytes(data)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def bound_table(declaration, override=None):
|
|
110
|
+
"""(`{originator: class}`, sha256) of the table the declaration binds to this run.
|
|
111
|
+
|
|
112
|
+
The table is a declared source: `{name: originators, path, sha256}`. S1 refuses a declaration that names
|
|
113
|
+
none, a `--originators` that is not the declared path, an entry without a pin and bytes that are not the
|
|
114
|
+
pinned ones, so classification cannot change under one declaration without an amendment."""
|
|
115
|
+
entry = next((s for s in declaration["sources"] if s["name"] == ORIGINATORS_SOURCE), None)
|
|
116
|
+
if entry is None:
|
|
117
|
+
raise Refused(f"ORIGINATOR_TABLE_UNDECLARED S1: the declaration names no '{ORIGINATORS_SOURCE}' source; declare the table with its path and sha256")
|
|
118
|
+
if override and os.path.abspath(override) != entry["path"]:
|
|
119
|
+
raise Refused(f"ORIGINATOR_TABLE_UNDECLARED S1: {override} is not the declared table {entry['path']}; amend the declaration to use another")
|
|
120
|
+
if not entry.get("sha256"):
|
|
121
|
+
raise Refused(f"ORIGINATOR_TABLE_UNDECLARED S1: the '{ORIGINATORS_SOURCE}' source {entry['path']} carries no sha256")
|
|
122
|
+
table, sha = load_originators(entry["path"])
|
|
123
|
+
if sha != entry["sha256"]:
|
|
124
|
+
raise Refused(f"ORIGINATOR_TABLE_CHANGED S1: {entry['path']} hashes {sha[:12]}, the declaration pinned {entry['sha256'][:12]}; "
|
|
125
|
+
"amend the declaration with the new hash to accept the edit")
|
|
126
|
+
return table, sha
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def key_of(entry):
|
|
130
|
+
return lineage.identity(entry["host"], entry["id"])
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
# What a census row holds of one transcript file. A Claude row holds its one file in these fields; a Codex row holds
|
|
134
|
+
# them per file in `segments`, never on the row (D-20261103-a7128a): Codex Desktop writes one thread across several
|
|
135
|
+
# rollout files under one id, and a row-level copy of one file's fields read as the session's would drop the others.
|
|
136
|
+
SEGMENT_FIELDS = ("path", "sha256", "versions", "owned", "work")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def stem_of(path):
|
|
140
|
+
"""A Codex rollout file's name without `.jsonl` or `.jsonl.zst`: the same for a file and its compressed copy."""
|
|
141
|
+
return re.sub(r"\.jsonl$", "", re.sub(r"\.zst$", "", os.path.basename(path)))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def segment(stem, source, path=None):
|
|
145
|
+
return {"stem": stem, "source": source, "path": path, "sha256": None, "versions": [], "owned": [],
|
|
146
|
+
"work": {"version": None, "in_window": [], "backlog": []}}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def coverage_key(entry, seg):
|
|
150
|
+
"""The coverage state's name for one file of a row: the row's identity for a Claude transcript, and
|
|
151
|
+
`codex:<id>@<stem>` for every Codex rollout file, one file or several (D-20261103-a7128a)."""
|
|
152
|
+
return key_of(entry) if entry["host"] == "claude" else f"{key_of(entry)}@{seg['stem']}"
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def identity_of_key(key):
|
|
156
|
+
"""The row identity a coverage key belongs to."""
|
|
157
|
+
return key.split("@", 1)[0]
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def segments_of(entry):
|
|
161
|
+
"""The transcript files of a census row in their order, each `{key, stem, source, path, sha256, versions, owned,
|
|
162
|
+
work}` with `key` its coverage key: the one reader of a row's files outside the census (D-20261103-a7128a). A Codex
|
|
163
|
+
row's are its `segments` (none for a row an index or the coverage state names without a file); a Claude row's is the
|
|
164
|
+
row itself. What it returns is a copy: a reader changes nothing in the census through it."""
|
|
165
|
+
if entry["host"] == "codex":
|
|
166
|
+
return [{"key": coverage_key(entry, seg), **copy.deepcopy(seg)} for seg in entry["segments"]]
|
|
167
|
+
return [{"key": key_of(entry), "stem": None, "source": entry["source"], **copy.deepcopy({k: entry[k] for k in SEGMENT_FIELDS})}]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
CENSUS_FILE = "census.json"
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def load_document(path):
|
|
174
|
+
"""The census document at `path`, parsed. What the read raises - absent, unreadable, not JSON - is the caller's to
|
|
175
|
+
name; `rows` then takes the rows out of it."""
|
|
176
|
+
return json.loads(pathlib.Path(path).read_text(encoding="utf-8"))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def load(run_dir):
|
|
180
|
+
"""The census S1 left in `run_dir`, refused by name when there is none."""
|
|
181
|
+
path = pathlib.Path(run_dir) / CENSUS_FILE
|
|
182
|
+
if not path.is_file():
|
|
183
|
+
raise Refused(f"INPUT_INVALID S1: {path} is absent; run the census first")
|
|
184
|
+
return load_document(path)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def misplaced(e):
|
|
188
|
+
"""Why a row's files are not where its host keeps them, or None: a Codex row holds them in `segments` and never on
|
|
189
|
+
the row, a Claude row never in `segments` (D-20261103-a7128a)."""
|
|
190
|
+
if e.get("host") == "codex":
|
|
191
|
+
on_row = [k for k in SEGMENT_FIELDS if k in e]
|
|
192
|
+
return (f"a Codex row carries {on_row} on the row" if on_row
|
|
193
|
+
else None if isinstance(e.get("segments"), list) else "a Codex row has no segments")
|
|
194
|
+
return "a Claude row carries segments" if "segments" in e else None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def rows(document):
|
|
198
|
+
"""The rows of a census document: the one way into them outside the census (with `segments_of` for a row's files).
|
|
199
|
+
ValueError, naming the first row, when they are not a list of rows each holding its files where its host keeps
|
|
200
|
+
them, so a reader built for another shape fails here by name instead of reading a part of a session as the whole."""
|
|
201
|
+
transcripts = document.get("transcripts") if isinstance(document, dict) else None
|
|
202
|
+
if not isinstance(transcripts, list) or not all(isinstance(e, dict) for e in transcripts):
|
|
203
|
+
raise ValueError("CENSUS_MALFORMED: its transcripts are not a list of rows")
|
|
204
|
+
for e in transcripts:
|
|
205
|
+
why = misplaced(e)
|
|
206
|
+
if why:
|
|
207
|
+
raise ValueError(f"CENSUS_MALFORMED {e.get('host')}:{e.get('id')}: {why}")
|
|
208
|
+
return transcripts
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# The structural guard of D-20261103-a7128a: outside this module a census document is read only through `load` or
|
|
212
|
+
# `load_document` and its rows only through `rows`, so every reader meets the row shapes above. A module that names the
|
|
213
|
+
# census file is listed here with the reason it may; a site not listed, or a listed site that no longer names it, fails.
|
|
214
|
+
READER_MODULES = ("distill.py", "runlib/*.py")
|
|
215
|
+
READER_EXCEPTIONS = {
|
|
216
|
+
("runlib/views.py", "run"): "declares census.json as S2's input artifact; the census itself is read through load",
|
|
217
|
+
("runlib/stage_close.py", "inputs_of"): "declares census.json as S12's S1 input artifact for a periodic run; the "
|
|
218
|
+
"census itself is read through load and folded through reconcile",
|
|
219
|
+
("runlib/stage_read.py", "run"): "declares census.json as S3's input artifact; the census itself is read through load "
|
|
220
|
+
"and rows, and folded back through reconcile",
|
|
221
|
+
("runlib/inventory.py", "<module>"): "CENSUS names the file the inventory part declares and opens",
|
|
222
|
+
("runlib/inventory.py", "census_entries"): "maps an absent, unreadable or malformed census to the transcript layers' "
|
|
223
|
+
"named unknowns, reading it through load_document and rows",
|
|
224
|
+
("distill.py", "cmd_inventory"): "declares the census as the inventory part's S1 input artifact",
|
|
225
|
+
("runlib/stage_form.py", "<module>"): "INPUTS declares census.json as S4's S1 input artifact; the barrier reads the "
|
|
226
|
+
"census itself through load and rows",
|
|
227
|
+
("runlib/stage_retrieve.py", "<module>"): "INPUTS declares census.json as S5's S1 input artifact; the recurrence reads "
|
|
228
|
+
"the census itself through load and rows",
|
|
229
|
+
("runlib/stage_judge.py", "<module>"): "INPUTS declares census.json as S6's S1 input artifact, so a census taken again "
|
|
230
|
+
"makes S6 stale; S6 reads no census row",
|
|
231
|
+
("runlib/stage_render.py", "<module>"): "INPUTS declares census.json as S9's S1 input artifact, so a census taken again "
|
|
232
|
+
"makes the review stale",
|
|
233
|
+
("runlib/stage_render.py", "load"): "reads the admitted census once for the review header's per-source state, "
|
|
234
|
+
"discovered count and totals (`sources`); S9 reads no census row",
|
|
235
|
+
}
|
|
236
|
+
LOADERS = frozenset(("load", "load_document", "build", "reconcile", "run"))
|
|
237
|
+
TEST_CODE = ("self_test", "fx_", "golden")
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def reader_bypasses(texts):
|
|
241
|
+
"""Violations of the guard over `texts` (`{relative path: source}`): `(violations, sites)`. A site is a
|
|
242
|
+
`(module, top-level function)` of non-test code that names the census file (`"census.json"` or `CENSUS`); a
|
|
243
|
+
violation is a site no exception lists, an exception no site matches, or a census document taken from this
|
|
244
|
+
module's loaders and indexed for its `transcripts` instead of read through `rows`."""
|
|
245
|
+
import ast
|
|
246
|
+
sites, violations = set(), []
|
|
247
|
+
for rel, text in sorted(texts.items()):
|
|
248
|
+
tree = ast.parse(text)
|
|
249
|
+
for top in [n for n in tree.body]:
|
|
250
|
+
name = top.name if isinstance(top, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) else "<module>"
|
|
251
|
+
if name.startswith(TEST_CODE):
|
|
252
|
+
continue
|
|
253
|
+
skipped = {id(n) for f in ast.walk(top) if isinstance(f, (ast.FunctionDef, ast.AsyncFunctionDef)) and f.name.startswith(TEST_CODE)
|
|
254
|
+
for n in ast.walk(f)}
|
|
255
|
+
loaded = set()
|
|
256
|
+
for node in ast.walk(top):
|
|
257
|
+
if id(node) in skipped:
|
|
258
|
+
continue
|
|
259
|
+
if (isinstance(node, ast.Constant) and node.value == CENSUS_FILE) or (isinstance(node, ast.Name) and node.id == "CENSUS") \
|
|
260
|
+
or (isinstance(node, ast.Attribute) and node.attr == "CENSUS"):
|
|
261
|
+
sites.add((rel, name))
|
|
262
|
+
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Attribute) \
|
|
263
|
+
and isinstance(node.value.func.value, ast.Name) and node.value.func.value.id == "census" and node.value.func.attr in LOADERS:
|
|
264
|
+
for target in node.targets:
|
|
265
|
+
loaded |= {n.id for n in ast.walk(target) if isinstance(n, ast.Name)}
|
|
266
|
+
for node in ast.walk(top):
|
|
267
|
+
if id(node) in skipped:
|
|
268
|
+
continue
|
|
269
|
+
key = (node.slice if isinstance(node, ast.Subscript) else node.args[0] if isinstance(node, ast.Call) and node.args
|
|
270
|
+
and isinstance(node.func, ast.Attribute) and node.func.attr == "get" else None)
|
|
271
|
+
holder = node.value if isinstance(node, ast.Subscript) else node.func.value if key is not None else None
|
|
272
|
+
if isinstance(key, ast.Constant) and key.value == "transcripts" and isinstance(holder, ast.Name) and holder.id in loaded:
|
|
273
|
+
violations.append(f"CENSUS_READER_BYPASS {rel}:{node.lineno} ({name}): {holder.id}['transcripts'] is a census "
|
|
274
|
+
"document's rows taken around census.rows")
|
|
275
|
+
violations += [f"CENSUS_READER_BYPASS {rel} ({name}) names the census file outside the census, and no exception lists it"
|
|
276
|
+
for rel, name in sorted(sites - set(READER_EXCEPTIONS))]
|
|
277
|
+
violations += [f"CENSUS_READER_BYPASS stale exception {rel} ({name}): it no longer names the census file"
|
|
278
|
+
for rel, name in sorted(set(READER_EXCEPTIONS) - sites) if rel in texts]
|
|
279
|
+
return violations, sites
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def reader_texts():
|
|
283
|
+
"""The sources `reader_bypasses` judges: every module of `READER_MODULES` but this one."""
|
|
284
|
+
found = {}
|
|
285
|
+
for pattern in READER_MODULES:
|
|
286
|
+
for path in sorted(HERE.glob(pattern)):
|
|
287
|
+
rel = path.relative_to(HERE).as_posix()
|
|
288
|
+
if rel != "runlib/census.py":
|
|
289
|
+
found[rel] = path.read_text(encoding="utf-8")
|
|
290
|
+
return found
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def blank(host, ident, source, path=None, **fields):
|
|
294
|
+
"""A row as the census builds it: its files in `segments` whatever the host, until `finish` gives it its shape."""
|
|
295
|
+
entry = {"host": host, "id": ident, "source": source, "status": "eligible", "reason": None,
|
|
296
|
+
"parent": None, "originator": None, "entrypoint": None, "source_class": None,
|
|
297
|
+
"lineage": {"component": None, "root": None, "unique_root": False, "affirmed": [], "measurement_pending": False},
|
|
298
|
+
"provenance": None, "counted": False, "window_overlap": None, "pin": {"content_ref": None},
|
|
299
|
+
"segments": [segment(stem_of(path) if host == "codex" else None, source, path)] if path else [], "alt_paths": []}
|
|
300
|
+
entry.update(fields)
|
|
301
|
+
return entry
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def finish(entry):
|
|
305
|
+
"""A built row in the shape the census document holds: a Claude row's one file moved onto the row, a Codex row's
|
|
306
|
+
files left in `segments`."""
|
|
307
|
+
if entry["host"] == "claude":
|
|
308
|
+
files = entry.pop("segments")
|
|
309
|
+
entry.update({k: (files[0] if files else segment(None, entry["source"]))[k] for k in SEGMENT_FIELDS})
|
|
310
|
+
return entry
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def name_id(path):
|
|
314
|
+
"""The session id a rollout's file name carries, for the one whose first record cannot be read."""
|
|
315
|
+
stem = os.path.basename(path)
|
|
316
|
+
found = UUID.findall(stem)
|
|
317
|
+
return found[-1] if found else re.sub(r"\.(zst|jsonl)", "", stem)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def parse(text):
|
|
321
|
+
try:
|
|
322
|
+
when = datetime.datetime.fromisoformat(text)
|
|
323
|
+
return when if when.tzinfo else when.replace(tzinfo=datetime.timezone.utc)
|
|
324
|
+
except (TypeError, ValueError):
|
|
325
|
+
return None
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def head_of(file, zstd):
|
|
329
|
+
"""A transcript's head: its scan, its first timestamp, and the error that stopped the read."""
|
|
330
|
+
claude = file["host"] == "claude"
|
|
331
|
+
scan, first_ts, error = (lineage.ClaudeScan() if claude else lineage.CodexScan(file["stem"])), None, None
|
|
332
|
+
try:
|
|
333
|
+
with contextlib.closing(sources.read_lines(file["path"], zstd)) as lines:
|
|
334
|
+
for index, raw in enumerate(lines):
|
|
335
|
+
try:
|
|
336
|
+
rec = json.loads(raw)
|
|
337
|
+
except ValueError:
|
|
338
|
+
rec = None
|
|
339
|
+
if isinstance(rec, dict):
|
|
340
|
+
scan.feed(rec, index)
|
|
341
|
+
first_ts = first_ts or (rec["timestamp"] if isinstance(rec.get("timestamp"), str) else None)
|
|
342
|
+
if claude:
|
|
343
|
+
if (index + 1 >= HEAD_RECORDS and scan.entrypoint) or index + 1 >= ENTRYPOINT_SCAN:
|
|
344
|
+
break
|
|
345
|
+
elif index + 1 >= HEAD_RECORDS or (index == 0 and (
|
|
346
|
+
scan.meta is None or scan.kind()[0] == "subagent" or scan.meta.get("source") not in ("cli", "vscode"))):
|
|
347
|
+
break # a child or an automated rollout is known by its first record
|
|
348
|
+
except sources.Unreadable as exc:
|
|
349
|
+
error = str(exc)
|
|
350
|
+
return {"scan": scan, "first_ts": first_ts, "error": error}
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def read_full(file, zstd, scan, own, prev, earlier=()):
|
|
354
|
+
"""One pass over a whole transcript: `{sha, record_count, prefix_sha, prefix_ok, partial_tail, owned, before, after,
|
|
355
|
+
late}`.
|
|
356
|
+
|
|
357
|
+
The version this run reads is the transcript's complete lines (D-20261103-8facee): `sha` and `prefix_sha` both
|
|
358
|
+
hash them, and a record the host is still writing is no record yet, so it moves neither (`partial_tail` says it was
|
|
359
|
+
there). S2 copies exactly these `record_count` lines and accepts them when they hash to `sha`; what the host
|
|
360
|
+
appends after this read belongs to the next run. `prefix_ok` answers §5.2's append-only test against `prev`, the
|
|
361
|
+
version on record: did the first `prev.record_count` lines hash to its `prefix_sha`. Of the windows of `earlier`
|
|
362
|
+
(`(start, end, id)`, the windows already run), `late` maps each to the records it owns past `prev.record_count` in
|
|
363
|
+
an append - what was written after that window was read (review c0fix r1 #1) - and `unowned` to the records it owns
|
|
364
|
+
in a version with no earlier one to be owed through: a file never read before, or one rewritten since. Those are
|
|
365
|
+
owned by no run, and the census counts them."""
|
|
366
|
+
whole, count, boundary, tail = hashlib.sha256(), 0, None, b""
|
|
367
|
+
owners = coverage.Owners(earlier) if earlier else None
|
|
368
|
+
if prev and prev["record_count"] == 0:
|
|
369
|
+
boundary = whole.hexdigest()
|
|
370
|
+
for raw in sources.read_lines(file["path"], zstd):
|
|
371
|
+
if not raw.endswith(b"\n"):
|
|
372
|
+
tail = raw
|
|
373
|
+
break
|
|
374
|
+
whole.update(raw)
|
|
375
|
+
try:
|
|
376
|
+
rec = json.loads(raw)
|
|
377
|
+
except ValueError:
|
|
378
|
+
rec = None
|
|
379
|
+
if isinstance(rec, dict):
|
|
380
|
+
scan.feed(rec, count)
|
|
381
|
+
own.feed(count, rec.get("timestamp"))
|
|
382
|
+
if owners:
|
|
383
|
+
owners.feed(count, rec.get("timestamp"))
|
|
384
|
+
count += 1
|
|
385
|
+
if prev and count == prev["record_count"]:
|
|
386
|
+
boundary = whole.hexdigest()
|
|
387
|
+
prefix = whole.hexdigest()
|
|
388
|
+
prefix_ok = None if prev is None else boundary == prev["prefix_sha"]
|
|
389
|
+
earlier_owned = owners.finish(count) if owners else {}
|
|
390
|
+
appended = {window: coverage.subtract(ranges, [[0, prev["record_count"]]]) for window, ranges in earlier_owned.items()} if prefix_ok else {}
|
|
391
|
+
return {"sha": prefix, "record_count": count, "prefix_sha": prefix, "partial_tail": bool(tail), "prefix_ok": prefix_ok,
|
|
392
|
+
"late": {w: r for w, r in appended.items() if r}, "unowned": {} if prefix_ok else earlier_owned, **own.finish(count)}
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
class _NoScan:
|
|
396
|
+
"""`read_full`'s scan for a unit member: its records are the root's evidence, not lineage of their own (§5.1)."""
|
|
397
|
+
|
|
398
|
+
def feed(self, rec, index=0):
|
|
399
|
+
pass
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
NO_SCAN = _NoScan()
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def overlap_of(got):
|
|
406
|
+
"""How a read transcript lies against the window: inside it, across its start, its end or both, or only as context."""
|
|
407
|
+
if not got["owned"]:
|
|
408
|
+
return "context_only"
|
|
409
|
+
return {(False, False): "inside", (True, False): "straddles_start", (False, True): "straddles_end",
|
|
410
|
+
(True, True): "straddles_both"}[(bool(got["before"]), bool(got["after"]))]
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def unread_overlap(entry, zstd, start, end):
|
|
414
|
+
"""How a row the census does not read in full lies against the window (lead decision D-20261106-208882), from the
|
|
415
|
+
best evidence each of its files gives. A file last written before the window starts holds none of its records,
|
|
416
|
+
since a record is written no earlier than its timestamp: the file-time bound, `before_window` when it decides every
|
|
417
|
+
file. A file it cannot rule out has its record timestamps read to the end, as `read_full` reads them (complete
|
|
418
|
+
lines only), and lies inside, across or outside the window by them (`overlap_of`). A file named with no path, one
|
|
419
|
+
that cannot be read and one with no timestamped record leave the row `undetermined`, and so in the basis's scope.
|
|
420
|
+
|
|
421
|
+
The bound fails only where a record's timestamp is later than its writing (a skewed clock) or a file's time was set
|
|
422
|
+
back by hand; both are outside what the census can see, and a file the bound cannot decide is read."""
|
|
423
|
+
sides, decided_by_time = {"owned": False, "before": False, "after": False}, True
|
|
424
|
+
for seg in entry["segments"]:
|
|
425
|
+
path = seg["path"]
|
|
426
|
+
try:
|
|
427
|
+
if path is None:
|
|
428
|
+
return "undetermined"
|
|
429
|
+
if os.stat(path).st_mtime < start.timestamp():
|
|
430
|
+
sides["before"] = True # every record of it lies before the window
|
|
431
|
+
continue
|
|
432
|
+
own, count = coverage.Ownership(start, end), 0
|
|
433
|
+
for raw in sources.read_lines(path, zstd):
|
|
434
|
+
if not raw.endswith(b"\n"):
|
|
435
|
+
break
|
|
436
|
+
try:
|
|
437
|
+
rec = json.loads(raw)
|
|
438
|
+
except ValueError:
|
|
439
|
+
rec = None
|
|
440
|
+
if isinstance(rec, dict):
|
|
441
|
+
own.feed(count, rec.get("timestamp"))
|
|
442
|
+
count += 1
|
|
443
|
+
except (OSError, sources.Unreadable):
|
|
444
|
+
return "undetermined"
|
|
445
|
+
if not own.stamped:
|
|
446
|
+
return "undetermined"
|
|
447
|
+
decided_by_time = False
|
|
448
|
+
got = own.finish(count)
|
|
449
|
+
for side in sides:
|
|
450
|
+
sides[side] = sides[side] or bool(got[side])
|
|
451
|
+
return "before_window" if decided_by_time else overlap_of(sides)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def root_of(by_key, entry):
|
|
455
|
+
"""The root `entry`'s chain of parents reaches in `by_key` (`{<host>:<id>: entry}`): the first ancestor that names
|
|
456
|
+
no parent, `entry` itself when it names none, or None when the chain breaks or loops. The chain is the parent links,
|
|
457
|
+
not the statuses: a member whose own read failed keeps its parent and stays a link, so what lies below it is still
|
|
458
|
+
in its root's unit (review c0fix r1 #2)."""
|
|
459
|
+
seen = set()
|
|
460
|
+
while entry is not None and entry.get("parent") is not None:
|
|
461
|
+
if key_of(entry) in seen:
|
|
462
|
+
return None
|
|
463
|
+
seen.add(key_of(entry))
|
|
464
|
+
entry = by_key.get(lineage.identity(entry["host"], entry["parent"]))
|
|
465
|
+
return entry
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def units_of(by_key):
|
|
469
|
+
"""`{root key: [member keys]}`: every `child_of` entry of `by_key` under the root its chain reaches, at any depth
|
|
470
|
+
(D-20261103-85f3e8). A member that could not be read is no member, and its descendants still are. The members are
|
|
471
|
+
sorted, so a unit reads the same in every run."""
|
|
472
|
+
found = {}
|
|
473
|
+
for key, entry in by_key.items():
|
|
474
|
+
root = root_of(by_key, entry) if entry["status"] == "child_of" else None
|
|
475
|
+
if root is not None:
|
|
476
|
+
found.setdefault(key_of(root), []).append(key)
|
|
477
|
+
return {root: sorted(members) for root, members in found.items()}
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def units(transcripts):
|
|
481
|
+
"""`units_of` over a census document's transcripts: the one reader of the unit that reconcile and S2 share."""
|
|
482
|
+
return units_of({key_of(e): e for e in transcripts})
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def load_index(src, report, name, loader):
|
|
486
|
+
"""What `loader` reads from the index `name`, or None; the report says whether it was read, and why not."""
|
|
487
|
+
rep = report[name]
|
|
488
|
+
if rep["state"] != "present":
|
|
489
|
+
return None
|
|
490
|
+
try:
|
|
491
|
+
return loader(src[name])
|
|
492
|
+
except sources.Unreadable as exc:
|
|
493
|
+
rep["state"], rep["detail"] = "unreadable", str(exc)
|
|
494
|
+
return None
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def discover(src, report):
|
|
498
|
+
files = []
|
|
499
|
+
if report["claude_projects"]["state"] == "present":
|
|
500
|
+
top, children, report["claude_projects"]["unrecognized"] = sources.discover_claude(src["claude_projects"])
|
|
501
|
+
files += [{"host": "claude", "source": "claude_projects", "path": p, "stem": i, "child_of": None} for i, p in top]
|
|
502
|
+
files += [{"host": "claude", "source": "claude_projects", "path": p, "stem": os.path.basename(p)[:-len(".jsonl")],
|
|
503
|
+
"child_of": parent} for parent, p in children]
|
|
504
|
+
for name in ("codex_sessions", "codex_archived_sessions"):
|
|
505
|
+
if report[name]["state"] == "present":
|
|
506
|
+
found, report[name]["unrecognized"] = sources.discover_codex(src[name])
|
|
507
|
+
files += [{"host": "codex", "source": name, "path": p, "stem": os.path.basename(p), "child_of": None} for p in found]
|
|
508
|
+
return files
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def entry_of(file, head, pins, table):
|
|
512
|
+
"""The first classification of one transcript file, from its head alone (design §5.1)."""
|
|
513
|
+
host = file["host"]
|
|
514
|
+
if file["child_of"]: # a Claude subagent file: linked to its session, read as part of it, never counted
|
|
515
|
+
return blank(host, f"{file['child_of']}/{file['stem']}", file["source"], file["path"], status="child_of",
|
|
516
|
+
parent=file["child_of"], entrypoint="subagents")
|
|
517
|
+
scan = head["scan"]
|
|
518
|
+
ident = file["stem"] if host == "claude" else (scan.meta or {}).get("id") or name_id(file["path"])
|
|
519
|
+
entry = blank(host, ident, file["source"], file["path"])
|
|
520
|
+
if head["error"]:
|
|
521
|
+
entry.update(status="unreadable", reason=head["error"])
|
|
522
|
+
elif host == "claude":
|
|
523
|
+
if scan.child(): # a sidechain thread wherever it lies on disk; its records carry the parent's session id
|
|
524
|
+
parent = scan.session_id if scan.session_id and scan.session_id != ident else None
|
|
525
|
+
entry.update(entrypoint="sidechain", **({"status": "child_of", "parent": parent} if parent else
|
|
526
|
+
{"status": "unknown_provenance", "reason": "child_without_parent"}))
|
|
527
|
+
else:
|
|
528
|
+
status, reason, cls = lineage.classify_claude(scan.entrypoint)
|
|
529
|
+
entry.update(status=status, reason=reason, source_class=cls, entrypoint=scan.entrypoint)
|
|
530
|
+
else:
|
|
531
|
+
meta, (kind, parent) = scan.meta, scan.kind()
|
|
532
|
+
source = meta.get("source") if meta else None
|
|
533
|
+
entry.update(originator=meta.get("originator") if meta else None,
|
|
534
|
+
entrypoint=source if isinstance(source, str) else "subagent" if kind == "subagent" else None)
|
|
535
|
+
sub = meta.get("source", {}).get("subagent") if meta and isinstance(meta.get("source"), dict) else None
|
|
536
|
+
if meta is None:
|
|
537
|
+
entry.update(status="unknown_provenance", reason="no_session_meta")
|
|
538
|
+
elif isinstance(sub, dict) and sub.get("other") == "guardian":
|
|
539
|
+
# Codex's own automatic risk review of a session's actions (D-20261103-b1989d): automated like `exec`, never a unit member
|
|
540
|
+
entry.update(status="excluded", reason="guardian")
|
|
541
|
+
elif kind == "subagent":
|
|
542
|
+
entry.update(status="child_of", parent=parent) if parent else entry.update(status="unknown_provenance", reason="child_without_parent")
|
|
543
|
+
else:
|
|
544
|
+
status, reason, cls = lineage.classify_codex(source, entry["originator"], ("codex", ident) in pins, table)
|
|
545
|
+
entry.update(status=status, reason=reason, source_class=cls)
|
|
546
|
+
entry["pin"]["content_ref"] = pins.get((host, ident))
|
|
547
|
+
return entry
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def provenance_of(entry, host, threads, history, desktop):
|
|
551
|
+
"""`indexed`, `not_indexed` or `index_missing` from the index the host itself writes (design §5.3).
|
|
552
|
+
|
|
553
|
+
Codex: a `threads` row of this id whose `rollout_path` is one of the row's files - any segment of a thread
|
|
554
|
+
written across several, or a true copy of one (`alt_paths`) - or such a file before in-place compression (the index
|
|
555
|
+
keeps the pre-compression path). Claude CLI: a `history.jsonl` entry with the id. Claude Desktop: a session-index file
|
|
556
|
+
whose `cliSessionId` is the id."""
|
|
557
|
+
if host == "codex":
|
|
558
|
+
if threads is None:
|
|
559
|
+
return "index_missing"
|
|
560
|
+
row = threads.get(entry["id"])
|
|
561
|
+
if not row or not row["rollout_path"]:
|
|
562
|
+
return "not_indexed"
|
|
563
|
+
have = os.path.realpath(row["rollout_path"])
|
|
564
|
+
wanted = [os.path.realpath(p) for p in [s["path"] for s in entry["segments"] if s["path"]] + entry["alt_paths"]]
|
|
565
|
+
return "indexed" if any(have in (want, want[:-len(".zst")] if want.endswith(".zst") else want) for want in wanted) else "not_indexed"
|
|
566
|
+
index = desktop if entry["entrypoint"] == "claude-desktop" else history
|
|
567
|
+
return "index_missing" if index is None else "indexed" if entry["id"] in index else "not_indexed"
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def index_only(seen, threads, history, desktop, pins, table, start, end):
|
|
571
|
+
"""Identities an index names with a timestamp in the window and no transcript here (design §5.1);
|
|
572
|
+
`seen` holds the identities (`<host>:<id>`) of the transcripts that are here."""
|
|
573
|
+
lo, hi, found = start.timestamp(), end.timestamp(), []
|
|
574
|
+
for sid, row in sorted((desktop or {}).items()):
|
|
575
|
+
if lineage.identity("claude", sid) not in seen and row[0] is not None and row[0] / 1000 < hi and (row[1] or row[0]) / 1000 >= lo:
|
|
576
|
+
found.append(blank("claude", sid, "claude_desktop_index", status="known_absent", source_class="claude-desktop", entrypoint="claude-desktop"))
|
|
577
|
+
seen.add(lineage.identity("claude", sid))
|
|
578
|
+
for sid, span in sorted((history or {}).items()):
|
|
579
|
+
if lineage.identity("claude", sid) not in seen and span[0] is not None and span[0] / 1000 < hi and span[1] / 1000 >= lo:
|
|
580
|
+
found.append(blank("claude", sid, "claude_history", status="known_absent", source_class="claude-cli", entrypoint="cli"))
|
|
581
|
+
seen.add(lineage.identity("claude", sid))
|
|
582
|
+
for sid, row in sorted((threads or {}).items()):
|
|
583
|
+
if lineage.identity("codex", sid) in seen or row["created_at"] is None or not (row["created_at"] < hi and (row["updated_at"] or row["created_at"]) >= lo):
|
|
584
|
+
continue
|
|
585
|
+
raw = row["source"]
|
|
586
|
+
source = "subagent" if isinstance(raw, str) and raw.startswith("{") else raw
|
|
587
|
+
status, reason, cls = ("excluded", "subagent", None) if source == "subagent" else \
|
|
588
|
+
lineage.classify_codex(source, row["originator"], ("codex", sid) in pins, table)
|
|
589
|
+
found.append(blank("codex", sid, "codex_state", status="known_absent" if status == "eligible" else status, reason=reason, source_class=cls,
|
|
590
|
+
entrypoint=source, originator=row["originator"], pin={"content_ref": pins.get(("codex", sid))}))
|
|
591
|
+
seen.add(lineage.identity("codex", sid))
|
|
592
|
+
return found
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def build(run, base, table, table_sha, jobs=8, scratch=None):
|
|
596
|
+
"""The census of one run: `(census, coverage state after the run)`; `base` is not touched.
|
|
597
|
+
|
|
598
|
+
A targeted run reads but never advances periodic coverage, so what it returns is `base`. `scratch` is
|
|
599
|
+
the confined parent under which the Codex index snapshot gets a directory of its own while it is read."""
|
|
600
|
+
src = sources.declared(run)
|
|
601
|
+
zstd = src.get("zstd")
|
|
602
|
+
start, end, window_id = coverage.window_bounds(run["window"])
|
|
603
|
+
state = copy.deepcopy(base)
|
|
604
|
+
report = {name: {"state": sources.state_of(src.get(name), name in DIRECTORIES), "path": src.get(name), "discovered": None,
|
|
605
|
+
"unrecognized": 0, "totals": None, "detail": None} for name in sources.SOURCE_NAMES if name != "zstd"}
|
|
606
|
+
files = discover(src, report)
|
|
607
|
+
with concurrent.futures.ThreadPoolExecutor(jobs) as pool: # before the indexes are loaded: spawning is cheapest from a small heap
|
|
608
|
+
heads = list(pool.map(lambda f: None if f["child_of"] else head_of(f, zstd), files))
|
|
609
|
+
# The ROLLOUT lookup, in which a Codex key is a rollout id some pin names and never a thread id, so
|
|
610
|
+
# a pin cannot answer for a rollout it does not name (X r2 F3).
|
|
611
|
+
pins, bad, claimed, _threads = (sources.read_pins(src["agent_bios_state"])
|
|
612
|
+
if report["agent_bios_state"]["state"] == "present" else ({}, 0, {}, {}))
|
|
613
|
+
# A rollout two pins claim is keyed to neither (X r1 F5): the census makes no choice by file order,
|
|
614
|
+
# and the ambiguity is reported here so a reader sees it rather than a missing pin.
|
|
615
|
+
detail = [f"{bad} pin files ignored"] if bad else []
|
|
616
|
+
detail += [f"{len(claimed)} rollout(s) claimed by more than one pin: "
|
|
617
|
+
+ "; ".join(f"{rollout}={','.join(ids)}" for rollout, ids in sorted(claimed.items()))] if claimed else []
|
|
618
|
+
report["agent_bios_state"]["detail"] = "; ".join(detail) or None
|
|
619
|
+
threads = load_index(src, report, "codex_state", functools.partial(sources.read_threads, scratch=scratch))
|
|
620
|
+
history = load_index(src, report, "claude_history", sources.read_history)
|
|
621
|
+
desktop = load_index(src, report, "claude_desktop_index", sources.read_desktop_index)
|
|
622
|
+
if history is not None:
|
|
623
|
+
history, bad = history
|
|
624
|
+
report["claude_history"]["detail"] = f"{bad} lines ignored" if bad else None
|
|
625
|
+
|
|
626
|
+
entries, extras = {}, {}
|
|
627
|
+
for file, head in zip(files, heads):
|
|
628
|
+
entry = entry_of(file, head, pins, table)
|
|
629
|
+
ident = key_of(entry)
|
|
630
|
+
if ident not in entries:
|
|
631
|
+
entries[ident], extras[ident] = entry, {"file": file, "head": head, "files": [file]}
|
|
632
|
+
continue
|
|
633
|
+
have, stem = entries[ident], entry["segments"][0]["stem"]
|
|
634
|
+
if entry["host"] == "claude" or any(s["stem"] == stem for s in have["segments"]):
|
|
635
|
+
have["alt_paths"].append(file["path"]) # the same file found twice: the first keeps it, the copy is named beside it
|
|
636
|
+
continue
|
|
637
|
+
# one Codex thread written across several rollout files under one id (D-20261103-a7128a): one row, a segment per
|
|
638
|
+
# file in name order, which is the order the host wrote them in; the row is classified from its first file
|
|
639
|
+
files_now = sorted(extras[ident]["files"] + [file], key=lambda f: stem_of(f["path"]))
|
|
640
|
+
if files_now[0] is file:
|
|
641
|
+
entry["segments"], entry["alt_paths"] = have["segments"] + entry["segments"], have["alt_paths"]
|
|
642
|
+
entries[ident], extras[ident]["file"], extras[ident]["head"] = entry, file, head
|
|
643
|
+
else:
|
|
644
|
+
have["segments"] = have["segments"] + entry["segments"]
|
|
645
|
+
entries[ident]["segments"].sort(key=lambda s: s["stem"])
|
|
646
|
+
extras[ident]["files"] = files_now
|
|
647
|
+
discovered = {} # the identities each source named, counted before anything else is decided about them
|
|
648
|
+
for entry in entries.values():
|
|
649
|
+
discovered[entry["source"]] = discovered.get(entry["source"], 0) + 1
|
|
650
|
+
for ident, entry in entries.items():
|
|
651
|
+
if entry["status"] == "child_of" and lineage.identity(entry["host"], entry["parent"]) not in entries:
|
|
652
|
+
entry.update(status="unknown_provenance", reason="orphan_child", parent=None) # a link to nothing
|
|
653
|
+
elif entry["status"] not in ("child_of", "unreadable"):
|
|
654
|
+
entry["provenance"] = provenance_of(entry, entry["host"], threads, history, desktop)
|
|
655
|
+
|
|
656
|
+
for ident, entry in entries.items():
|
|
657
|
+
if entry["status"] == "child_of" and root_of(entries, entry) is None: # parents that loop reach no root: a link to nothing
|
|
658
|
+
entry.update(status="unknown_provenance", reason="orphan_child", parent=None)
|
|
659
|
+
|
|
660
|
+
# every eligible transcript is read in full, whatever its age: its sha, its continuity against the version on
|
|
661
|
+
# record, the records the window owns, and the lineage evidence wherever in the file it lies
|
|
662
|
+
owed = {b["transcript"] for b in state["backlog"]} | {e["transcript"] for e in state["pending_events"]}
|
|
663
|
+
# a file of a row the coverage state owes work on and that is no longer here: the session cannot be read in full, so
|
|
664
|
+
# its row says which file it lacks, and the work stays owed (the file is listed with no path)
|
|
665
|
+
present = {coverage_key(e, s) for e in entries.values() for s in e["segments"]}
|
|
666
|
+
for key in sorted(k for k in owed - present if identity_of_key(k) in entries and "@" in k):
|
|
667
|
+
entry = entries[identity_of_key(key)]
|
|
668
|
+
entry["segments"] = sorted(entry["segments"] + [segment(key.split("@", 1)[1], "coverage_state")], key=lambda s: s["stem"])
|
|
669
|
+
entry.update(status="unreadable", reason=f"SEGMENT_ABSENT {key}: the coverage state owes work on this file of the "
|
|
670
|
+
"session and it is no longer here")
|
|
671
|
+
|
|
672
|
+
# the windows already run, whose records appended since their run are owed to them (review c0fix r1 #1); what the
|
|
673
|
+
# windows own in a file never read before or in a rewritten version is owed through no version, and is counted
|
|
674
|
+
earlier = [(*coverage.bounds_of(w), w) for w in sorted(state["windows"]) if w != window_id]
|
|
675
|
+
unowned = {"earlier_windows": len(earlier), "rewritten": {"files": 0, "records": 0}, "first_seen": {"files": 0, "records": 0}}
|
|
676
|
+
|
|
677
|
+
def read(ident, scanned=True):
|
|
678
|
+
"""Every file of row `ident` read in full: `(scan, [(segment, got)], stamped records, error)`. The scan is the
|
|
679
|
+
first file's - its kind and its pointer are the row's - with the lineage evidence of the later files added; a
|
|
680
|
+
later file's own `history_base` is no edge (D-20261103-a7128a)."""
|
|
681
|
+
entry, row_scan, out, stamped = entries[ident], None, [], 0
|
|
682
|
+
for seg, file in zip(entry["segments"], extras[ident]["files"]):
|
|
683
|
+
scan = (lineage.ClaudeScan() if file["host"] == "claude" else lineage.CodexScan(file["stem"])) if scanned else NO_SCAN
|
|
684
|
+
own = coverage.Ownership(start, end)
|
|
685
|
+
try:
|
|
686
|
+
got = read_full(file, zstd, scan, own, coverage.latest(state, coverage_key(entry, seg)), earlier)
|
|
687
|
+
except sources.Unreadable as exc:
|
|
688
|
+
return None, [], 0, str(exc)
|
|
689
|
+
if scanned:
|
|
690
|
+
row_scan = scan if row_scan is None else row_scan.absorb(scan)
|
|
691
|
+
out.append((seg, got))
|
|
692
|
+
stamped += own.stamped
|
|
693
|
+
return row_scan, out, stamped, None
|
|
694
|
+
|
|
695
|
+
def taken(entry, out):
|
|
696
|
+
for seg, got in out:
|
|
697
|
+
if coverage.observe(state, coverage_key(entry, seg), got["sha"], got["record_count"], got["prefix_sha"], got["prefix_ok"]) == "append":
|
|
698
|
+
coverage.carry_appended(state, coverage_key(entry, seg), got["late"])
|
|
699
|
+
nobody = coverage.normalize([r for ranges in got["unowned"].values() for r in ranges])
|
|
700
|
+
if nobody:
|
|
701
|
+
cell = unowned["first_seen" if got["prefix_ok"] is None else "rewritten"]
|
|
702
|
+
cell["files"], cell["records"] = cell["files"] + 1, cell["records"] + sum(end - start for start, end in nobody)
|
|
703
|
+
seg.update(sha256=got["sha"], owned=got["owned"])
|
|
704
|
+
entry["window_overlap"] = overlap_of({side: any(got[side] for _seg, got in out) for side in ("owned", "before", "after")})
|
|
705
|
+
|
|
706
|
+
def unstamped(out, stamped):
|
|
707
|
+
return stamped == 0 and any(got["record_count"] for _seg, got in out)
|
|
708
|
+
|
|
709
|
+
for ident, entry in entries.items():
|
|
710
|
+
if entry["status"] != "eligible":
|
|
711
|
+
continue
|
|
712
|
+
scan, out, stamped, error = read(ident) # one at a time: decompression runs beside it in zstd, and CPU-bound threads only fight for the GIL
|
|
713
|
+
if error:
|
|
714
|
+
entry.update(status="unreadable", reason=error)
|
|
715
|
+
elif unstamped(out, stamped):
|
|
716
|
+
entry.update(status="unknown_provenance", reason="no_timestamps", source_class=None)
|
|
717
|
+
else:
|
|
718
|
+
extras[ident]["head"]["scan"] = scan
|
|
719
|
+
taken(entry, out)
|
|
720
|
+
|
|
721
|
+
# The unit S1 judges and S2 reads is a root with all its descendants, at any depth (D-20261103-85f3e8; design §5.1:
|
|
722
|
+
# a child is "read as part of the parent's evidence"). Every member of a root still eligible after its own read is
|
|
723
|
+
# read in full like the root, so what the window owns in it is known. A member that cannot be read, or carries no
|
|
724
|
+
# timestamp, is named the way a root would be and leaves the unit; the rest of the unit is judged without it.
|
|
725
|
+
unit_members = units_of(entries)
|
|
726
|
+
for root, members in unit_members.items():
|
|
727
|
+
if entries[root]["status"] != "eligible":
|
|
728
|
+
continue
|
|
729
|
+
for ident in members:
|
|
730
|
+
entry = entries[ident]
|
|
731
|
+
_scan, out, stamped, error = read(ident, scanned=False)
|
|
732
|
+
if error:
|
|
733
|
+
entry.update(status="unreadable", reason=error)
|
|
734
|
+
continue
|
|
735
|
+
if unstamped(out, stamped):
|
|
736
|
+
entry.update(status="unknown_provenance", reason="no_timestamps")
|
|
737
|
+
continue
|
|
738
|
+
taken(entry, out)
|
|
739
|
+
|
|
740
|
+
# A row left unread - unknown, unreadable, or a member of such a root - still lies somewhere against the window, and
|
|
741
|
+
# the observation basis counts it only when it may hold a record of it (D-20261106-208882; stage_read.observation_scope).
|
|
742
|
+
# A member of an excluded root is out of every scope with its root, so it is not looked at.
|
|
743
|
+
for ident, entry in entries.items():
|
|
744
|
+
if entry["window_overlap"] is not None:
|
|
745
|
+
continue
|
|
746
|
+
root = root_of(entries, entry) if entry["status"] == "child_of" else None
|
|
747
|
+
if entry["status"] in UNREAD_STATUSES or (root is not None and root["status"] in UNREAD_STATUSES):
|
|
748
|
+
entry["window_overlap"] = unread_overlap(entry, zstd, start, end)
|
|
749
|
+
|
|
750
|
+
def owes(entry):
|
|
751
|
+
return any(s["work"]["in_window"] or s["work"]["backlog"] for s in entry["segments"])
|
|
752
|
+
|
|
753
|
+
def worked(entry):
|
|
754
|
+
for seg in entry["segments"]:
|
|
755
|
+
key = coverage_key(entry, seg)
|
|
756
|
+
seg["work"] = coverage.work_of(state, key, seg["owned"], window_id)
|
|
757
|
+
known = state["transcripts"].get(key, {"versions": []})["versions"]
|
|
758
|
+
seg["versions"] = [{k: v[k] for k in ("sha", "record_count", "prefix_sha")} for v in known]
|
|
759
|
+
seg["sha256"] = seg["sha256"] or (known[-1]["sha"] if known else None)
|
|
760
|
+
|
|
761
|
+
for ident, entry in entries.items():
|
|
762
|
+
if entry["status"] != "eligible":
|
|
763
|
+
continue
|
|
764
|
+
worked(entry)
|
|
765
|
+
read_members = [m for m in unit_members.get(ident, []) if entries[m]["status"] == "child_of"]
|
|
766
|
+
for member in read_members:
|
|
767
|
+
worked(entries[member])
|
|
768
|
+
# nothing is new for the unit only when neither the root nor any member owes the window anything
|
|
769
|
+
if not owes(entry) and not any(owes(entries[m]) for m in read_members):
|
|
770
|
+
entry["status"] = "nothing_new"
|
|
771
|
+
|
|
772
|
+
# lineage over the owner's transcripts, then the counting rule (design §5.3); a component is active in the window
|
|
773
|
+
# when any unit in it owns a record of the window, a member's as much as a root's
|
|
774
|
+
def owns(entry):
|
|
775
|
+
return any(s["owned"] for s in entry["segments"])
|
|
776
|
+
|
|
777
|
+
mine = {i: e for i, e in entries.items() if e["status"] in ("eligible", "nothing_new")}
|
|
778
|
+
nodes = [extras[i]["head"]["scan"].lineage_node(e["id"]) for i, e in mine.items()]
|
|
779
|
+
linked, pending, active = lineage.components(nodes), {n["id"]: n.get("pending", False) for n in nodes}, {}
|
|
780
|
+
for ident, entry in mine.items():
|
|
781
|
+
entry["lineage"] = {**linked[ident], "measurement_pending": pending[ident]}
|
|
782
|
+
unit_owned = owns(entry) or any(owns(entries[m]) for m in unit_members.get(ident, []) if entries[m]["status"] == "child_of")
|
|
783
|
+
active[entry["lineage"]["component"]] = active.get(entry["lineage"]["component"], False) or unit_owned
|
|
784
|
+
for ident, entry in mine.items():
|
|
785
|
+
lin = entry["lineage"]
|
|
786
|
+
entry["counted"] = bool(lin["unique_root"] and lin["root"] == ident and entry["provenance"] == "indexed"
|
|
787
|
+
and active[lin["component"]] and entry["source_class"] in CLASSES)
|
|
788
|
+
named = index_only(set(entries), threads, history, desktop, pins, table, start, end)
|
|
789
|
+
# work the coverage state still owes on a transcript that is no longer here is a lost transcript, not a vanished obligation
|
|
790
|
+
present = {coverage_key(e, s) for e in entries.values() for s in e["segments"]}
|
|
791
|
+
lost_keys = sorted(k for k in owed - present if identity_of_key(k) not in {key_of(e) for e in named})
|
|
792
|
+
lost = []
|
|
793
|
+
for ident in sorted({identity_of_key(k) for k in lost_keys}):
|
|
794
|
+
row = blank(*lineage.split_identity(ident), "coverage_state", status="known_absent", reason="owed_by_coverage")
|
|
795
|
+
if row["host"] == "codex":
|
|
796
|
+
row["segments"] = [segment(k.split("@", 1)[1], "coverage_state") for k in lost_keys if identity_of_key(k) == ident and "@" in k]
|
|
797
|
+
lost.append(row)
|
|
798
|
+
if lost:
|
|
799
|
+
report["coverage_state"] = {"state": "present", "path": None, "discovered": None, "unrecognized": 0, "totals": None,
|
|
800
|
+
"detail": "transcripts the coverage state owes work on that are no longer here"}
|
|
801
|
+
for entry in named + lost:
|
|
802
|
+
discovered[entry["source"]] = discovered.get(entry["source"], 0) + 1
|
|
803
|
+
everything = [finish(e) for e in list(entries.values()) + named + lost]
|
|
804
|
+
for name, rep in report.items():
|
|
805
|
+
if rep["state"] == "present" and name != "agent_bios_state":
|
|
806
|
+
rep["discovered"] = discovered.get(name, 0)
|
|
807
|
+
census = summarize(everything, report, run["kind"], window_id, table, table_sha, state, unowned)
|
|
808
|
+
return census, (state if run["kind"] == "periodic" else base)
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
def totals_of(entries, report):
|
|
812
|
+
for name, rep in report.items():
|
|
813
|
+
if rep["state"] == "present" and name != "agent_bios_state":
|
|
814
|
+
rep["totals"] = {}
|
|
815
|
+
for e in entries:
|
|
816
|
+
if e["source"] == name:
|
|
817
|
+
rep["totals"][e["status"]] = rep["totals"].get(e["status"], 0) + 1
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
def summarize(entries, report, kind, window_id, table, table_sha, state, unowned):
|
|
821
|
+
"""Fold per-transcript entries into the census document and check that nothing was dropped."""
|
|
822
|
+
totals_of(entries, report)
|
|
823
|
+
entries.sort(key=lambda e: (e["source"], first_path(e) or "", e["id"]))
|
|
824
|
+
originators, provenance, pins, components = {}, {}, {}, {}
|
|
825
|
+
for e in entries:
|
|
826
|
+
if e["originator"] is not None and e["entrypoint"] == "vscode" and first_path(e):
|
|
827
|
+
cell = originators.setdefault(e["originator"], {"count": 0, "class": table.get(e["originator"], "unmapped")})
|
|
828
|
+
cell["count"] += 1
|
|
829
|
+
if e["provenance"]:
|
|
830
|
+
cell = provenance.setdefault(f"{e['host']}/{e['entrypoint'] or 'none'}",
|
|
831
|
+
{"indexed": 0, "not_indexed": 0, "index_missing": 0})
|
|
832
|
+
cell[e["provenance"]] += 1
|
|
833
|
+
if e["status"] in ("eligible", "nothing_new"):
|
|
834
|
+
cell = pins.setdefault(e["source"], {"eligible": 0, "pinned": 0})
|
|
835
|
+
cell["eligible"] += 1
|
|
836
|
+
cell["pinned"] += e["pin"]["content_ref"] is not None
|
|
837
|
+
if e["lineage"]["component"]:
|
|
838
|
+
components.setdefault(e["lineage"]["component"], []).append(e)
|
|
839
|
+
unknown = [c for c, members in components.items() if not (members[0]["lineage"]["unique_root"] and any(
|
|
840
|
+
key_of(m) == m["lineage"]["root"] and m["provenance"] == "indexed" for m in members))]
|
|
841
|
+
census = {"kind": kind, "window": window_id, "originator_table_sha256": table_sha, "sources": report,
|
|
842
|
+
"originators": originators, "provenance": provenance, "pins": pins,
|
|
843
|
+
"independence": {"components": len(components), "unknown_components": len(unknown),
|
|
844
|
+
"sessions": sum(map(len, components.values())),
|
|
845
|
+
"unknown_sessions": sum(len(components[c]) for c in unknown)},
|
|
846
|
+
"unowned": unowned, "pending_events": copy.deepcopy(state["pending_events"]), "transcripts": entries}
|
|
847
|
+
errors = account(census)
|
|
848
|
+
if errors:
|
|
849
|
+
raise Refused("\n".join(errors))
|
|
850
|
+
return census
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def first_path(e):
|
|
854
|
+
"""The path of a finished row's first file, or None."""
|
|
855
|
+
return e["path"] if e["host"] == "claude" else (e["segments"][0]["path"] if e["segments"] else None)
|
|
856
|
+
|
|
857
|
+
|
|
858
|
+
def shape_errors(e):
|
|
859
|
+
"""Where a row departs from its host's shape: a Claude row holds its file's fields on the row and has no `segments`;
|
|
860
|
+
a Codex row holds them only in `segments` (D-20261103-a7128a). The schema cannot say this - its lint admits no
|
|
861
|
+
conditional keyword (validate.SUPPORTED_KEYWORDS) - so the census's own accounting does."""
|
|
862
|
+
if e["host"] == "codex":
|
|
863
|
+
on_row = [k for k in SEGMENT_FIELDS if k in e]
|
|
864
|
+
if on_row or not isinstance(e.get("segments"), list):
|
|
865
|
+
return [f"SET_MISMATCH shape {key_of(e)}: a Codex row holds its files in segments, "
|
|
866
|
+
+ (f"never {on_row} on the row" if on_row else "and this one has none")]
|
|
867
|
+
return []
|
|
868
|
+
missing = [k for k in SEGMENT_FIELDS if k not in e]
|
|
869
|
+
if missing or "segments" in e:
|
|
870
|
+
return [f"SET_MISMATCH shape {key_of(e)}: a Claude row holds its file on the row, "
|
|
871
|
+
+ (f"and this one lacks {missing}" if missing else "never in segments")]
|
|
872
|
+
return []
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
def account(census):
|
|
876
|
+
"""Violations of the set accounting of §5.1, empty when it holds: no identity appears twice, a source with
|
|
877
|
+
no total files nothing under it, each source's statuses add up to the identities it discovered, and every row has
|
|
878
|
+
its host's shape."""
|
|
879
|
+
errors, seen = [], {}
|
|
880
|
+
for e in census["transcripts"]:
|
|
881
|
+
errors += shape_errors(e)
|
|
882
|
+
seen.setdefault(key_of(e), []).append(e["source"])
|
|
883
|
+
errors += [f"SET_MISMATCH id {i} appears {len(s)} times ({sorted(s)})" for i, s in sorted(seen.items()) if len(s) > 1]
|
|
884
|
+
for name, rep in census["sources"].items():
|
|
885
|
+
mine = [e for e in census["transcripts"] if e["source"] == name]
|
|
886
|
+
if rep["totals"] is None:
|
|
887
|
+
errors += [f"SET_MISMATCH {e['id']}: filed under {name}, which has no total ({rep['state']})" for e in mine]
|
|
888
|
+
elif sum(rep["totals"].values()) != rep["discovered"] or len(mine) != rep["discovered"]:
|
|
889
|
+
errors.append(f"SET_MISMATCH {name}: discovered {rep['discovered']}, statuses sum to {sum(rep['totals'].values())}, {len(mine)} entries")
|
|
890
|
+
stray = sorted({e["source"] for e in census["transcripts"]} - set(census["sources"]))
|
|
891
|
+
errors += [f"SET_MISMATCH entries are filed under {s}, which is not a source" for s in stray]
|
|
892
|
+
return errors
|
|
893
|
+
|
|
894
|
+
|
|
895
|
+
def dump(census):
|
|
896
|
+
"""The census as JSON, one transcript to a line: a corpus of 60,000 rollouts is read with `grep`."""
|
|
897
|
+
head = json.dumps({k: v for k, v in census.items() if k != "transcripts"}, indent=1, sort_keys=True, ensure_ascii=False)
|
|
898
|
+
lines = ",\n".join(" " + json.dumps(e, sort_keys=True, ensure_ascii=False, separators=(",", ":")) for e in census["transcripts"])
|
|
899
|
+
return head[:-2] + ',\n "transcripts": [\n' + lines + "\n ]\n}\n"
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
def reconcile(census, state, results, kind):
|
|
903
|
+
"""S3's `results` folded back: `(census, state, flags)` with the eligible statuses terminal.
|
|
904
|
+
|
|
905
|
+
Every session that was `eligible` at S1 needs exactly one result, and a result names an eligible session
|
|
906
|
+
(SET_MISMATCH otherwise, listing the sessions). A result answers the session's whole unit: the readings of its
|
|
907
|
+
read members are credited to them (`coverage.apply_results`). The inputs are not touched, and the reconciled census
|
|
908
|
+
must still conform to its schema. A reading names the file it read by its coverage key (`segments_of`) unless the
|
|
909
|
+
session is one file."""
|
|
910
|
+
census, window_id = copy.deepcopy(census), census["window"]
|
|
911
|
+
waiting = {key_of(e): e for e in census["transcripts"] if e["status"] == "eligible"}
|
|
912
|
+
# one result answers a unit (D-20261103-85f3e8): its members' readings are credited to them, and what they own is owed
|
|
913
|
+
# the coverage state names files, not rows: a Codex thread's files each by its own key (D-20261103-a7128a), so a unit is
|
|
914
|
+
# the files of its root and the files of its read members
|
|
915
|
+
by_key, found = {key_of(e): e for e in census["transcripts"]}, units(census["transcripts"])
|
|
916
|
+
files = {i: segments_of(e) for i, e in by_key.items() if i in waiting or e["status"] == "child_of"}
|
|
917
|
+
members = {root: [m for m in found.get(root, []) if by_key[m]["status"] == "child_of" and any(s["sha256"] for s in files[m])]
|
|
918
|
+
for root in waiting}
|
|
919
|
+
got = [r["transcript"] for r in results]
|
|
920
|
+
missing, extra = sorted(set(waiting) - set(got)), sorted(set(got) - set(waiting))
|
|
921
|
+
repeated = sorted({i for i in got if got.count(i) > 1})
|
|
922
|
+
if missing or extra or repeated:
|
|
923
|
+
raise Refused(f"SET_MISMATCH S3 results do not match the eligible sessions: missing={missing} extra={extra} repeated={repeated}")
|
|
924
|
+
unit_keys = {root: ([s["key"] for s in files[root]], [s["key"] for m in members[root] for s in files[m]]) for root in waiting}
|
|
925
|
+
read = [s for root in waiting for s in files[root]] + [s for ms in members.values() for m in ms for s in files[m]]
|
|
926
|
+
# a targeted run's results are held to the periodic rules against the state the census observed, and then discarded
|
|
927
|
+
seen = state if kind == "periodic" else coverage.observed(state, read)
|
|
928
|
+
owned = {s["key"]: s["owned"] for s in read}
|
|
929
|
+
after = coverage.apply_results(seen, window_id, kind, results, owned, unit_keys)
|
|
930
|
+
for result in results:
|
|
931
|
+
waiting[result["transcript"]]["status"] = result["status"]
|
|
932
|
+
totals_of(census["transcripts"], census["sources"])
|
|
933
|
+
census["pending_events"] = copy.deepcopy(after["pending_events"])
|
|
934
|
+
errors = account(census) + [f"CENSUS_INVALID {p}" for p in validate.validate_instance(validator(), census)[:5]]
|
|
935
|
+
if errors:
|
|
936
|
+
raise Refused("\n".join(errors))
|
|
937
|
+
flags = dict(zip(("accounted", "fully_read"), coverage.accounted(census["transcripts"], after, window_id, unit_keys, owned)))
|
|
938
|
+
if kind == "periodic":
|
|
939
|
+
after["windows"][window_id] = flags
|
|
940
|
+
else:
|
|
941
|
+
errors = coverage.check_targeted(seen, after)
|
|
942
|
+
if errors:
|
|
943
|
+
raise Refused("\n".join(errors))
|
|
944
|
+
after = copy.deepcopy(state) # nothing of it is kept: periodic coverage stays what it was, byte for byte
|
|
945
|
+
return census, after, flags
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
def window_counts(entries):
|
|
949
|
+
"""The eligible sessions, how many have a terminal status (accounted) and how many were read to the end
|
|
950
|
+
or had nothing to read (fully read): reported apart, since a deferred session is the first and not the second."""
|
|
951
|
+
eligible = [e["status"] for e in entries if e["status"] == "eligible" or e["status"] in coverage.TERMINAL]
|
|
952
|
+
return {"eligible": len(eligible), "accounted": sum(s in coverage.TERMINAL for s in eligible),
|
|
953
|
+
"fully_read": sum(s in ("read_complete", "nothing_new") for s in eligible)}
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
def run(run_dir, coverage_path=None, originators_path=None, jobs=8):
|
|
957
|
+
"""`distill.py census`: write `census.json` and the run's `coverage.json` into the run directory.
|
|
958
|
+
|
|
959
|
+
The coverage state read is the one the declaration pinned (`starting_hashes.coverage`) and the originator
|
|
960
|
+
table the one it declared (`bound_table`); the tracked file is not written here, S12 promotes the run's
|
|
961
|
+
copy with `coverage.write_atomic`. The Codex index is read through a snapshot in a directory of its own, made fresh
|
|
962
|
+
under `<run>/private` (confined first) and removed by the reader that made it, and nothing else."""
|
|
963
|
+
run_dir = pathlib.Path(run_dir)
|
|
964
|
+
if not records.run_json_path(run_dir).is_file():
|
|
965
|
+
raise Refused(f"RUN_UNDECLARED {run_dir}: no run.json")
|
|
966
|
+
declaration = records.read_json(records.run_json_path(run_dir))
|
|
967
|
+
base, base_sha = coverage.load(coverage_path or HERE / "coverage.json")
|
|
968
|
+
pinned = declaration["starting_hashes"]["coverage"]
|
|
969
|
+
if pinned != base_sha:
|
|
970
|
+
raise Refused(f"COVERAGE_BASE_STALE S1: the declaration pinned coverage {pinned[:12]}, the file hashes {base_sha[:12]}; "
|
|
971
|
+
"amend starting_hashes.coverage or restore the file")
|
|
972
|
+
table, table_sha = bound_table(declaration, originators_path)
|
|
973
|
+
parent = stagelock.confine(run_dir, run_dir / "private") # resolved beneath the run before anything is created or read into it
|
|
974
|
+
with records.run_stage(run_dir, "S1") as stage:
|
|
975
|
+
# the declaration was read first so that a stale pin or table is refused before any record is written; what
|
|
976
|
+
# builds the census is that read only if it is the declaration S1 was admitted against (X review of WP-08 r2)
|
|
977
|
+
declaration = stage.admitted(declaration)
|
|
978
|
+
parent.mkdir(exist_ok=True)
|
|
979
|
+
census, state = build(declaration, base, table, table_sha, jobs, parent)
|
|
980
|
+
problems = validate.validate_instance(validator(), census)
|
|
981
|
+
if problems:
|
|
982
|
+
raise Refused("CENSUS_INVALID " + "; ".join(problems[:5]))
|
|
983
|
+
records.write_text(run_dir, run_dir / "census.json", dump(census))
|
|
984
|
+
records.write_json(run_dir, run_dir / "coverage.json", state)
|
|
985
|
+
stage.output("census.json")
|
|
986
|
+
stage.output("coverage.json")
|
|
987
|
+
return census
|
|
988
|
+
|
|
989
|
+
|
|
990
|
+
def report_lines(census):
|
|
991
|
+
"""The census as the few lines a person reads: counts per source, never a transcript's content."""
|
|
992
|
+
def totals(rep):
|
|
993
|
+
return "unknown (no total)" if rep["totals"] is None else ", ".join(f"{k} {v}" for k, v in sorted(rep["totals"].items())) or "empty"
|
|
994
|
+
ind, counts = census["independence"], window_counts(census["transcripts"])
|
|
995
|
+
return [f"census {census['kind']} window {census['window']}: {counts['eligible']} eligible, {counts['accounted']} accounted, "
|
|
996
|
+
f"{counts['fully_read']} fully read",
|
|
997
|
+
*[f" {name}: {rep['state']}{' - ' + rep['detail'] if rep['detail'] else ''}; {totals(rep)}" for name, rep in sorted(census["sources"].items())],
|
|
998
|
+
*[f" provenance {key}: indexed {c['indexed']}, not_indexed {c['not_indexed']}, index_missing {c['index_missing']}"
|
|
999
|
+
for key, c in sorted(census["provenance"].items())],
|
|
1000
|
+
*[f" originator {name}: {c['count']} ({c['class']})" for name, c in sorted(census["originators"].items())],
|
|
1001
|
+
f" independence: {ind['unknown_components']}/{ind['components']} components and {ind['unknown_sessions']}/{ind['sessions']} sessions unknown",
|
|
1002
|
+
f" owned by no run, against {census['unowned']['earlier_windows']} windows already run: "
|
|
1003
|
+
+ "; ".join(f"{cause} {c['files']} files {c['records']} records" for cause, c in (
|
|
1004
|
+
("rewritten", census["unowned"]["rewritten"]), ("first seen", census["unowned"]["first_seen"])))]
|
|
1005
|
+
|
|
1006
|
+
|
|
1007
|
+
def contract_mismatch(schema, statuses):
|
|
1008
|
+
"""Where the census schema's status vocabulary departs from §5.1's list (`statuses`)."""
|
|
1009
|
+
have = schema["$defs"]["transcript"]["properties"]["status"]["enum"]
|
|
1010
|
+
errors = [f"CONTRACT_MISMATCH census (design §5.1): status {verb} {sorted(fields)}"
|
|
1011
|
+
for verb, fields in (("lacks", set(statuses) - set(have)), ("adds", set(have) - set(statuses))) if fields]
|
|
1012
|
+
if not str(schema.get("$comment", "")).startswith("design §5.1"):
|
|
1013
|
+
errors.append("CONTRACT_MISMATCH census (design §5.1): $comment does not cite the section")
|
|
1014
|
+
return errors
|
|
1015
|
+
|
|
1016
|
+
|
|
1017
|
+
# ---- the self-test: a synthetic corpus, one fixture for each O1 plant of design §18, every one golden -----------------
|
|
1018
|
+
|
|
1019
|
+
REALIZATION = "golden" # every fixture is synthetic: `Home` builds the host layout, `fx_*` the records (mock/realization boundary)
|
|
1020
|
+
ZSTD = "/opt/homebrew/bin/zstd"
|
|
1021
|
+
WINDOW = {"start": "2026-10-01T00:00:00", "end": "2026-10-08T00:00:00", "tz": "UTC"}
|
|
1022
|
+
NEXT = {"start": "2026-10-08T00:00:00", "end": "2026-10-15T00:00:00", "tz": "UTC"}
|
|
1023
|
+
NEXT_ID = "2026-10-08T00:00:00/2026-10-15T00:00:00@UTC" # the id the state files NEXT under
|
|
1024
|
+
STATUSES_5_1 = ("excluded", "child_of", "unknown_provenance", "unreadable", "known_absent", "eligible",
|
|
1025
|
+
"read_complete", "read_partial", "failed", "deferred", "nothing_new") # design §5.1, copied once and cited
|
|
1026
|
+
|
|
1027
|
+
|
|
1028
|
+
def fx_when(day, month=10, hour=0):
|
|
1029
|
+
return datetime.datetime(2026, month, day, hour, tzinfo=datetime.timezone.utc).timestamp()
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
def fx_stamp(day, k, month=10):
|
|
1033
|
+
"""The k-th second after 10:00 on a day: a transcript of any length gets distinct, ordered timestamps."""
|
|
1034
|
+
return f"2026-{month:02d}-{day:02d}T{10 + k // 3600:02d}:{k // 60 % 60:02d}:{k % 60:02d}.000Z"
|
|
1035
|
+
|
|
1036
|
+
|
|
1037
|
+
def fx_claude(sid, entry="cli", head="fresh", day=3, turns=3, uuids=None, stamps=None, entries=None, texts=None, side=None, month=10):
|
|
1038
|
+
"""The records of a Claude Code session: a head, then alternating user and assistant records.
|
|
1039
|
+
A user record carries a text of its own unless `texts` gives it one; `side` is `(isSidechain, agentId)`."""
|
|
1040
|
+
rows = [{"type": t} for t in {"fresh": ["mode", "permission-mode", "atis-latch", "file-history-snapshot"],
|
|
1041
|
+
"fork": ["ai-title", "last-prompt", "file-history-snapshot", "file-history-snapshot"]}[head]]
|
|
1042
|
+
for k, stamp in enumerate(stamps or [fx_stamp(day, k, month) for k in range(turns * 2)]):
|
|
1043
|
+
ep = entries[k] if entries else entry
|
|
1044
|
+
text = texts[k // 2] if texts and k // 2 < len(texts) else f"{sid} question {k // 2}"
|
|
1045
|
+
rows.append({"type": "user" if k % 2 == 0 else "assistant", "timestamp": stamp, "sessionId": sid,
|
|
1046
|
+
"uuid": uuids[k] if uuids and k < len(uuids) else f"{sid}-{k}", **({"entrypoint": ep} if ep else {}),
|
|
1047
|
+
**({"message": {"role": "user", "content": text}} if k % 2 == 0 else {}),
|
|
1048
|
+
**({"isSidechain": side[0], "agentId": side[1]} if side else {})})
|
|
1049
|
+
return rows
|
|
1050
|
+
|
|
1051
|
+
|
|
1052
|
+
def fx_codex(tid, source="cli", originator="codex-tui", day=3, turns=3, ns=None, meta=None, compacted=False, ordinal=0, texts=None, month=10):
|
|
1053
|
+
"""The records of a Codex rollout: session_meta, then a turn start and a user message for each turn."""
|
|
1054
|
+
at = lambda k: fx_stamp(day, k, month) # noqa: E731
|
|
1055
|
+
rows = [{"timestamp": at(0), "ordinal": ordinal, "type": "session_meta",
|
|
1056
|
+
"payload": {"id": tid, "timestamp": at(0), "originator": originator, "source": source, **(meta or {})}}]
|
|
1057
|
+
for k in range(turns):
|
|
1058
|
+
text = texts[k] if texts and k < len(texts) else f"{tid} prompt {k}"
|
|
1059
|
+
rows.append({"timestamp": at(k + 1), "type": "event_msg", "payload": {"type": "task_started", "turn_id": f"{ns or tid}-t{k}"}})
|
|
1060
|
+
rows.append({"timestamp": at(k + 1), "type": "response_item", "payload": {
|
|
1061
|
+
"type": "message", "role": "user", "id": f"msg_{ns or tid}_{k}", "content": [{"type": "input_text", "text": text}]}})
|
|
1062
|
+
if compacted:
|
|
1063
|
+
rows.append({"timestamp": at(turns + 1), "type": "compacted", "payload": {}})
|
|
1064
|
+
return rows
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
class Home:
|
|
1068
|
+
"""A host layout under a scratch directory: the transcripts, the three indexes, the pins."""
|
|
1069
|
+
|
|
1070
|
+
open_writers = [] # the homes whose Codex database is held open by a writer; the self-test closes them
|
|
1071
|
+
|
|
1072
|
+
def __init__(self, root):
|
|
1073
|
+
self.root = pathlib.Path(root)
|
|
1074
|
+
self.projects = self.root / ".claude" / "projects"
|
|
1075
|
+
self.history_path = self.root / ".claude" / "history.jsonl"
|
|
1076
|
+
self.desktop_dir = self.root / "Library" / "claude-code-sessions"
|
|
1077
|
+
self.sessions = self.root / ".codex" / "sessions"
|
|
1078
|
+
self.archived = self.root / ".codex" / "archived_sessions"
|
|
1079
|
+
self.db = self.root / ".codex" / "state_5.sqlite"
|
|
1080
|
+
self.state = self.root / "agent-bios-state"
|
|
1081
|
+
self.hist, self.rows, self.desktops, self.writer = {}, [], 0, None
|
|
1082
|
+
for directory in (self.projects, self.desktop_dir, self.sessions, self.archived, self.state):
|
|
1083
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
1084
|
+
|
|
1085
|
+
@staticmethod
|
|
1086
|
+
def put(path, rows, mtime=None):
|
|
1087
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
1088
|
+
path.write_bytes(b"".join(json.dumps(r).encode() + b"\n" for r in rows))
|
|
1089
|
+
os.utime(path, (mtime or fx_when(5), mtime or fx_when(5)))
|
|
1090
|
+
return path
|
|
1091
|
+
|
|
1092
|
+
def claude(self, sid, rows, mtime=None, history=True):
|
|
1093
|
+
if history:
|
|
1094
|
+
self.hist[sid] = int(fx_when(3) * 1000)
|
|
1095
|
+
return self.put(self.projects / "-fx" / f"{sid}.jsonl", rows, mtime)
|
|
1096
|
+
|
|
1097
|
+
def child(self, parent, name, rows):
|
|
1098
|
+
return self.put(self.projects / "-fx" / parent / "subagents" / f"{name}.jsonl", rows)
|
|
1099
|
+
|
|
1100
|
+
def desktop(self, sid, created, last, listed=True):
|
|
1101
|
+
self.desktops += 1
|
|
1102
|
+
(self.desktop_dir / "a" / "b").mkdir(parents=True, exist_ok=True)
|
|
1103
|
+
(self.desktop_dir / "a" / "b" / f"local_{self.desktops}.json").write_text(json.dumps(
|
|
1104
|
+
{"sessionId": f"local_{self.desktops}", "cliSessionId": sid, "createdAt": int(fx_when(created) * 1000),
|
|
1105
|
+
"lastActivityAt": int(fx_when(last) * 1000), "title": "fixture"}))
|
|
1106
|
+
|
|
1107
|
+
def codex(self, tid, rows, where="sessions", zst=False, indexed=True, source=None, mtime=None, raw=None, day=3, name_at=None):
|
|
1108
|
+
directory = self.sessions / "2026" / "10" / f"{day:02d}" if where == "sessions" else self.archived
|
|
1109
|
+
path = directory / f"rollout-{name_at or f'2026-10-{day:02d}T10-00-00'}-{tid}.jsonl"
|
|
1110
|
+
if raw is None:
|
|
1111
|
+
self.put(path, rows, mtime)
|
|
1112
|
+
else:
|
|
1113
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
1114
|
+
path.write_bytes(raw)
|
|
1115
|
+
if zst:
|
|
1116
|
+
subprocess.run([ZSTD, "-q", "-f", "--rm", str(path)], check=True)
|
|
1117
|
+
path = path.with_name(path.name + ".zst")
|
|
1118
|
+
os.utime(path, (mtime or fx_when(5), mtime or fx_when(5)))
|
|
1119
|
+
if indexed:
|
|
1120
|
+
first = rows[0]["payload"]
|
|
1121
|
+
self.rows.append((tid, str(path)[:-len(".zst")] if zst else str(path), first["source"], first["originator"],
|
|
1122
|
+
int(fx_when(3)), int(fx_when(4)), 1 if where == "archived" else 0))
|
|
1123
|
+
return path
|
|
1124
|
+
|
|
1125
|
+
def finish(self, corrupt=False, wal=False):
|
|
1126
|
+
"""Write the indexes. With `wal` the host has the Codex database open: every row is committed to its write-ahead
|
|
1127
|
+
log, never checkpointed, and the connection stays open (`close`) so the `-wal` and `-shm` are there to be read."""
|
|
1128
|
+
self.history_path.write_text("".join(json.dumps({"sessionId": s, "timestamp": ms, "display": "fixture"}) + "\n"
|
|
1129
|
+
for s, ms in sorted(self.hist.items())))
|
|
1130
|
+
if corrupt:
|
|
1131
|
+
self.db.write_bytes(b"not a database" * 200)
|
|
1132
|
+
return
|
|
1133
|
+
conn = sqlite3.connect(self.db)
|
|
1134
|
+
if wal:
|
|
1135
|
+
conn.execute("pragma journal_mode=wal")
|
|
1136
|
+
conn.execute("create table threads(id text, rollout_path text, source text, originator text, created_at integer, "
|
|
1137
|
+
"updated_at integer, archived integer)")
|
|
1138
|
+
conn.commit()
|
|
1139
|
+
if wal:
|
|
1140
|
+
conn.execute("pragma wal_checkpoint(truncate)")
|
|
1141
|
+
conn.execute("pragma wal_autocheckpoint=0")
|
|
1142
|
+
conn.executemany("insert into threads values(?,?,?,?,?,?,?)", self.rows)
|
|
1143
|
+
conn.commit()
|
|
1144
|
+
if wal:
|
|
1145
|
+
self.writer = conn
|
|
1146
|
+
Home.open_writers.append(self)
|
|
1147
|
+
else:
|
|
1148
|
+
conn.close()
|
|
1149
|
+
|
|
1150
|
+
def close(self):
|
|
1151
|
+
writer, self.writer = self.writer, None
|
|
1152
|
+
if writer:
|
|
1153
|
+
writer.close()
|
|
1154
|
+
|
|
1155
|
+
def host_bytes(self):
|
|
1156
|
+
"""The Codex database, its -wal and its -shm: name, size, mtime and the hash of the bytes (absent ones omitted)."""
|
|
1157
|
+
out = []
|
|
1158
|
+
for suffix in ("", "-wal", "-shm"):
|
|
1159
|
+
path = pathlib.Path(str(self.db) + suffix)
|
|
1160
|
+
if path.exists():
|
|
1161
|
+
out.append((path.name, path.stat().st_size, path.stat().st_mtime_ns, hashlib.sha256(path.read_bytes()).hexdigest()))
|
|
1162
|
+
return out
|
|
1163
|
+
|
|
1164
|
+
def pin(self, tid):
|
|
1165
|
+
"""An activation pin as the current activation writes one: named by the app-server's thread id and
|
|
1166
|
+
NAMING the rollout the host wrote, which is the id a census row carries (F-22). Without the rollout
|
|
1167
|
+
fields the pin answers for no transcript, which is what every pin written before the binding is."""
|
|
1168
|
+
(self.state / "sessions" / "pins" / "codex").mkdir(parents=True, exist_ok=True)
|
|
1169
|
+
(self.state / "sessions" / "pins" / "codex" / f"{tid}.json").write_text(
|
|
1170
|
+
json.dumps({"host": "codex", "session_id": tid, "content_ref": "sha256:fixture",
|
|
1171
|
+
"rollout_id": tid, "rollout_path": str(self.sessions / f"rollout-{tid}.jsonl"),
|
|
1172
|
+
"rollout_method": "thread.path"}))
|
|
1173
|
+
|
|
1174
|
+
def run(self, kind="periodic", window=WINDOW, drop=(), table=None, **paths):
|
|
1175
|
+
"""A declaration's `kind`, `window` and `sources`; `table` is the `(path, sha256)` of the originator table it binds."""
|
|
1176
|
+
declared = {"claude_projects": self.projects, "claude_history": self.history_path, "claude_desktop_index": self.desktop_dir,
|
|
1177
|
+
"codex_sessions": self.sessions, "codex_archived_sessions": self.archived, "codex_state": self.db,
|
|
1178
|
+
"agent_bios_state": self.state, "zstd": ZSTD}
|
|
1179
|
+
declared.update(paths)
|
|
1180
|
+
path, sha = table or (ORIGINATORS_PATH, load_originators()[1])
|
|
1181
|
+
return {"kind": kind, "window": window, "sources": [{"name": n, "path": str(p)} for n, p in declared.items() if n not in drop]
|
|
1182
|
+
+ [{"name": ORIGINATORS_SOURCE, "path": str(path), "sha256": sha}]}
|
|
1183
|
+
|
|
1184
|
+
|
|
1185
|
+
def fx_get(entry, key):
|
|
1186
|
+
for part in key.split("."):
|
|
1187
|
+
entry = entry[part]
|
|
1188
|
+
return entry
|
|
1189
|
+
|
|
1190
|
+
|
|
1191
|
+
def fx_view(e):
|
|
1192
|
+
"""A row as the fixtures read it: a Codex row of one file, or of none, with that file's fields beside its own, so one
|
|
1193
|
+
expectation reads a row of either host alike. A row of several files is left as it is: what it holds per file is
|
|
1194
|
+
read through `segments_of`."""
|
|
1195
|
+
if e["host"] != "codex" or len(e["segments"]) > 1:
|
|
1196
|
+
return e
|
|
1197
|
+
seg = e["segments"][0] if e["segments"] else segment(None, e["source"])
|
|
1198
|
+
return {**e, **{k: seg[k] for k in SEGMENT_FIELDS}}
|
|
1199
|
+
|
|
1200
|
+
|
|
1201
|
+
def fx_check(census, expected):
|
|
1202
|
+
"""Violations of a fixture table `{name: (identity, {attribute: value})}`, each naming its fixture."""
|
|
1203
|
+
by_id, errors = {key_of(e): fx_view(e) for e in census["transcripts"]}, []
|
|
1204
|
+
for name, (ident, want) in sorted(expected.items()):
|
|
1205
|
+
got = by_id.get(ident)
|
|
1206
|
+
if got is None:
|
|
1207
|
+
errors.append(f"FIXTURE {name}: {ident} is not in the census")
|
|
1208
|
+
continue
|
|
1209
|
+
errors += [f"FIXTURE {name}: {key} is {fx_get(got, key)!r}, expected {value!r}" for key, value in want.items() if fx_get(got, key) != value]
|
|
1210
|
+
return errors
|
|
1211
|
+
|
|
1212
|
+
|
|
1213
|
+
def fx_corpus(h):
|
|
1214
|
+
"""Plant every fixture of design §18 O1 in `h` and return `{name: (id, expected attributes)}`."""
|
|
1215
|
+
C = lambda n: f"c{n:07d}-0000-4000-8000-000000000000" # noqa: E731
|
|
1216
|
+
X = lambda n: f"019e{n:04d}-0000-7000-8000-000000000000" # noqa: E731
|
|
1217
|
+
CK = lambda n: lineage.identity("claude", C(n)) # noqa: E731
|
|
1218
|
+
XK = lambda n: lineage.identity("codex", X(n)) # noqa: E731
|
|
1219
|
+
exp = {}
|
|
1220
|
+
|
|
1221
|
+
def claude(name, n, rows, want, **kw):
|
|
1222
|
+
h.claude(C(n), rows, **kw)
|
|
1223
|
+
exp[name] = (CK(n), want)
|
|
1224
|
+
|
|
1225
|
+
def codex(name, n, rows, want, **kw):
|
|
1226
|
+
h.codex(X(n), rows, **kw)
|
|
1227
|
+
exp[name] = (XK(n), want)
|
|
1228
|
+
|
|
1229
|
+
counted = {"status": "eligible", "provenance": "indexed", "counted": True, "lineage.unique_root": True}
|
|
1230
|
+
claude("claude_cli_root", 1, fx_claude(C(1)), {**counted, "source_class": "claude-cli", "window_overlap": "inside", "owned": [[0, 10]],
|
|
1231
|
+
"lineage.root": CK(1)})
|
|
1232
|
+
claude("claude_desktop_named", 2, fx_claude(C(2), entry="claude-desktop"), {**counted, "source_class": "claude-desktop"}, history=False)
|
|
1233
|
+
h.desktop(C(2), 2, 3)
|
|
1234
|
+
claude("claude_desktop_unindexed", 3, fx_claude(C(3), entry="claude-desktop"),
|
|
1235
|
+
{"status": "eligible", "source_class": "claude-desktop", "provenance": "not_indexed", "counted": False}, history=False)
|
|
1236
|
+
claude("claude_sdk", 4, fx_claude(C(4), entry="sdk-cli"), {"status": "excluded", "reason": "sdk-cli", "source_class": None}, history=False)
|
|
1237
|
+
claude("claude_no_entrypoint", 5, fx_claude(C(5), entry=None), {"status": "unknown_provenance", "reason": "no_entrypoint"}, history=False)
|
|
1238
|
+
claude("claude_resumed_headless", 6, fx_claude(C(6), entries=["cli", "cli", "sdk-cli", "sdk-cli", "sdk-cli", "sdk-cli"]),
|
|
1239
|
+
{**counted, "source_class": "claude-cli", "entrypoint": "cli"})
|
|
1240
|
+
h.child(C(1), "agent-a", fx_claude(C(1)))
|
|
1241
|
+
exp["claude_child"] = (lineage.identity("claude", f"{C(1)}/agent-a"), {"status": "child_of", "parent": C(1), "counted": False, "provenance": None})
|
|
1242
|
+
h.child(C(9), "agent-b", fx_claude(C(9)))
|
|
1243
|
+
exp["claude_orphan_child"] = (lineage.identity("claude", f"{C(9)}/agent-b"), {"status": "unknown_provenance", "reason": "orphan_child", "parent": None})
|
|
1244
|
+
claude("claude_fork", 7, fx_claude(C(7), head="fork", uuids=[f"{C(1)}-0", f"{C(1)}-1"]),
|
|
1245
|
+
{"status": "eligible", "counted": False, "provenance": "not_indexed", "lineage.unique_root": True, "lineage.root": CK(1),
|
|
1246
|
+
"lineage.affirmed": [{"from": CK(7), "to": CK(1), "via": ["record_ids"]}]}, history=False)
|
|
1247
|
+
shared = [f"{C(10)}-{k}" for k in range(6)]
|
|
1248
|
+
claude("claude_copy_original", 10, fx_claude(C(10), uuids=shared), {"status": "eligible", "provenance": "indexed", "counted": False,
|
|
1249
|
+
"lineage.unique_root": False, "lineage.root": None})
|
|
1250
|
+
claude("claude_copy_beside_original", 11, fx_claude(C(11), uuids=shared), {"status": "eligible", "provenance": "not_indexed",
|
|
1251
|
+
"counted": False, "lineage.unique_root": False}, history=False)
|
|
1252
|
+
claude("claude_lone_copy", 12, fx_claude(C(12)), {"status": "eligible", "provenance": "not_indexed", "counted": False,
|
|
1253
|
+
"lineage.unique_root": True}, history=False)
|
|
1254
|
+
straddle = ["2026-09-30T10:00:00.000Z", "2026-09-30T10:01:00.000Z"] + [f"2026-10-02T10:0{k}:00.000Z" for k in range(4)]
|
|
1255
|
+
claude("claude_straddles_window_start", 13, fx_claude(C(13), stamps=straddle),
|
|
1256
|
+
{**counted, "window_overlap": "straddles_start", "owned": [[6, 10]]})
|
|
1257
|
+
old = [f"2026-09-01T10:0{k}:00.000Z" for k in range(4)]
|
|
1258
|
+
claude("claude_before_the_window", 14, fx_claude(C(14), stamps=old), {"status": "nothing_new", "window_overlap": "context_only",
|
|
1259
|
+
"owned": [], "counted": False}, mtime=fx_when(1, 9))
|
|
1260
|
+
|
|
1261
|
+
claude("claude_continued_in", 15, fx_claude(C(15)) + [{"type": "continued-in", "continuedInSessionId": C(16)}], {**counted, "lineage.root": CK(15)})
|
|
1262
|
+
claude("claude_continuation_by_pointer", 16, fx_claude(C(16)), {"status": "eligible", "counted": False, "lineage.root": CK(15), "lineage.unique_root": True,
|
|
1263
|
+
"provenance": "not_indexed"}, history=False)
|
|
1264
|
+
|
|
1265
|
+
dated = {"status": "eligible", "provenance": "indexed", "counted": True, "lineage.unique_root": True}
|
|
1266
|
+
codex("codex_cli", 1, fx_codex(X(1)), {**dated, "source_class": "codex-cli", "window_overlap": "inside",
|
|
1267
|
+
"alt_paths": [str(h.archived / f"rollout-2026-10-03T10-00-00-{X(1)}.jsonl")]})
|
|
1268
|
+
h.codex(X(1), fx_codex(X(1)), where="archived", indexed=False) # the same id in a second file
|
|
1269
|
+
codex("codex_desktop_named", 2, fx_codex(X(2), "vscode", "Codex Desktop"), {**dated, "source_class": "codex-desktop", "originator": "Codex Desktop"})
|
|
1270
|
+
codex("codex_work_desktop", 3, fx_codex(X(3), "vscode", "codex_work_desktop"), {**dated, "source_class": "codex-desktop"})
|
|
1271
|
+
codex("codex_exec", 4, fx_codex(X(4), "exec", "codex_exec"), {"status": "excluded", "reason": "exec", "counted": False}, indexed=False)
|
|
1272
|
+
codex("codex_claude_code_in_vscode", 5, fx_codex(X(5), "vscode", "Claude Code"),
|
|
1273
|
+
{"status": "excluded", "reason": "originator:Claude Code", "provenance": "not_indexed"}, indexed=False)
|
|
1274
|
+
codex("codex_unnamed_originator", 6, fx_codex(X(6), "vscode", "NewClient"),
|
|
1275
|
+
{"status": "unknown_provenance", "reason": "originator:NewClient"}, indexed=False)
|
|
1276
|
+
codex("codex_activated_with_pin", 7, fx_codex(X(7), "vscode", "agent-bios"),
|
|
1277
|
+
{**dated, "source_class": "codex-cli", "pin.content_ref": "sha256:fixture"})
|
|
1278
|
+
h.pin(X(7))
|
|
1279
|
+
codex("codex_activated_without_pin", 8, fx_codex(X(8), "vscode", "agent-bios"),
|
|
1280
|
+
{"status": "unknown_provenance", "reason": "agent-bios:unpinned", "pin.content_ref": None}, indexed=False)
|
|
1281
|
+
codex("codex_child", 9, fx_codex(X(9), "cli", meta={"parent_thread_id": X(1)}), {"status": "child_of", "parent": X(1), "counted": False},
|
|
1282
|
+
indexed=False)
|
|
1283
|
+
codex("codex_compressed_in_place", 10, fx_codex(X(10), "vscode", "Codex Desktop"),
|
|
1284
|
+
{**dated, "source_class": "codex-desktop"}, zst=True)
|
|
1285
|
+
codex("codex_moved_to_archive", 11, fx_codex(X(11), "vscode", "Codex Desktop"), {**dated, "source_class": "codex-desktop"},
|
|
1286
|
+
where="archived", zst=True)
|
|
1287
|
+
codex("codex_lone_copy", 12, fx_codex(X(12), "vscode", "Codex Desktop"),
|
|
1288
|
+
{"status": "eligible", "provenance": "not_indexed", "counted": False, "lineage.unique_root": True}, indexed=False)
|
|
1289
|
+
codex("codex_fork", 13, fx_codex(X(13), "cli", meta={"forked_from_id": X(1)}, ordinal=5),
|
|
1290
|
+
{"status": "eligible", "counted": False, "lineage.root": XK(1), "lineage.unique_root": True,
|
|
1291
|
+
"lineage.affirmed": [{"from": XK(13), "to": XK(1), "via": ["forked_from_id"]}]})
|
|
1292
|
+
codex("codex_compaction", 14, fx_codex(X(14), compacted=True),
|
|
1293
|
+
{"status": "eligible", "counted": False, "lineage.unique_root": False, "lineage.measurement_pending": True})
|
|
1294
|
+
shared_ids = "copyns"
|
|
1295
|
+
codex("codex_copy_original", 15, fx_codex(X(15), ns=shared_ids), {"status": "eligible", "counted": False, "lineage.unique_root": False})
|
|
1296
|
+
codex("codex_copy_beside_original", 16, fx_codex(X(16), ns=shared_ids),
|
|
1297
|
+
{"status": "eligible", "counted": False, "lineage.unique_root": False, "provenance": "not_indexed"}, indexed=False)
|
|
1298
|
+
codex("codex_index_names_another_file", 18, fx_codex(X(18)), {"status": "eligible", "provenance": "not_indexed", "counted": False,
|
|
1299
|
+
"lineage.unique_root": True}, indexed=False)
|
|
1300
|
+
h.rows.append((X(18), "/elsewhere/rollout.jsonl", "cli", "codex-tui", int(fx_when(3)), int(fx_when(4)), 0))
|
|
1301
|
+
codex("codex_unreadable_rollout", 17, [], {"status": "unreadable", "counted": False}, raw=b"not zstd at all", zst=False, indexed=False)
|
|
1302
|
+
junk = h.sessions / "2026" / "10" / "03" / f"rollout-2026-10-03T10-00-00-{X(17)}.jsonl"
|
|
1303
|
+
junk.rename(junk.with_name(junk.name + ".zst"))
|
|
1304
|
+
|
|
1305
|
+
# design §5.3's third link, an identical (timestamp, human text) turn, with no pointer and no shared record id
|
|
1306
|
+
claude("claude_turn_root", 30, fx_claude(C(30), texts=["shared plan"]), {**counted, "lineage.root": CK(30)})
|
|
1307
|
+
claude("claude_turn_replay", 31, fx_claude(C(31), head="fork", texts=["shared plan"]),
|
|
1308
|
+
{"status": "eligible", "counted": False, "provenance": "not_indexed", "lineage.unique_root": True, "lineage.root": CK(30),
|
|
1309
|
+
"lineage.affirmed": [{"from": CK(31), "to": CK(30), "via": ["timestamp_text"]}]}, history=False)
|
|
1310
|
+
claude("claude_same_text_other_time_root", 32, fx_claude(C(32), texts=["same words"]), {**counted})
|
|
1311
|
+
claude("claude_same_text_other_time_replay", 33, fx_claude(C(33), head="fork", day=4, texts=["same words"]),
|
|
1312
|
+
{"status": "eligible", "counted": False, "lineage.unique_root": False}, history=False)
|
|
1313
|
+
claude("claude_same_time_other_text_root", 34, fx_claude(C(34)), {**counted})
|
|
1314
|
+
claude("claude_same_time_other_text_replay", 35, fx_claude(C(35), head="fork"),
|
|
1315
|
+
{"status": "eligible", "counted": False, "lineage.unique_root": False}, history=False)
|
|
1316
|
+
codex("codex_turn_root", 30, fx_codex(X(30), texts=["codex shared plan"]), {**dated, "lineage.root": XK(30)})
|
|
1317
|
+
codex("codex_turn_replay", 31, fx_codex(X(31), meta={"history_base": {"thread_id": "gone"}}, ordinal=5, texts=["codex shared plan"]),
|
|
1318
|
+
{"status": "eligible", "counted": False, "lineage.unique_root": True, "lineage.root": XK(30),
|
|
1319
|
+
"lineage.affirmed": [{"from": XK(31), "to": XK(30), "via": ["timestamp_text"]}]}, indexed=False)
|
|
1320
|
+
codex("codex_same_text_other_time_root", 32, fx_codex(X(32), texts=["codex same words"]), {**dated})
|
|
1321
|
+
codex("codex_same_text_other_time_replay", 33, fx_codex(X(33), meta={"history_base": {"thread_id": "gone"}}, ordinal=5, day=4, texts=["codex same words"]),
|
|
1322
|
+
{"status": "eligible", "counted": False, "lineage.unique_root": False}, indexed=False)
|
|
1323
|
+
|
|
1324
|
+
# a Claude child by its records (a sidechain thread, or one that names an agent), wherever the file lies; an ordinary session is not one
|
|
1325
|
+
claude("claude_sidechain_parent", 36, fx_claude(C(36)), {**counted})
|
|
1326
|
+
claude("claude_sidechain_child", 37, fx_claude(C(36), side=(True, "a1")),
|
|
1327
|
+
{"status": "child_of", "parent": C(36), "counted": False, "entrypoint": "sidechain", "provenance": None}, history=False)
|
|
1328
|
+
claude("claude_agentid_child", 38, fx_claude(C(36), side=(False, "a2")), {"status": "child_of", "parent": C(36), "counted": False}, history=False)
|
|
1329
|
+
claude("claude_sidechain_without_parent", 39, fx_claude(C(39), side=(True, "a3")),
|
|
1330
|
+
{"status": "unknown_provenance", "reason": "child_without_parent", "counted": False}, history=False)
|
|
1331
|
+
inline = {"type": "user", "timestamp": fx_stamp(3, 90), "sessionId": C(41), "isSidechain": True, "message": {"role": "user", "content": "inline side"}}
|
|
1332
|
+
claude("claude_inline_sidechain_is_no_child", 41, fx_claude(C(41), side=(False, None)) + [inline], {**counted})
|
|
1333
|
+
|
|
1334
|
+
# lineage evidence past the first 256 records of an old transcript, where the head-only test never looks
|
|
1335
|
+
old = {"month": 9, "day": 1, "turns": 140}
|
|
1336
|
+
before = {"status": "nothing_new", "window_overlap": "context_only", "counted": True, "lineage.unique_root": True}
|
|
1337
|
+
claude("claude_old_continued_in_past_the_head", 42, fx_claude(C(42), **old) + [{"type": "continued-in", "continuedInSessionId": C(43)}],
|
|
1338
|
+
{**before, "lineage.root": CK(42)}, mtime=fx_when(1, 9))
|
|
1339
|
+
claude("claude_continuation_of_the_old_one", 43, fx_claude(C(43)),
|
|
1340
|
+
{"status": "eligible", "provenance": "indexed", "counted": False, "lineage.unique_root": True, "lineage.root": CK(42)})
|
|
1341
|
+
claude("claude_old_shares_an_id_past_the_head", 44, fx_claude(C(44), uuids=[None] * 270 + ["late-shared-uuid"], **old),
|
|
1342
|
+
{**before, "lineage.root": CK(44)}, mtime=fx_when(1, 9))
|
|
1343
|
+
claude("claude_fork_of_the_old_one", 45, fx_claude(C(45), head="fork", uuids=["late-shared-uuid"]),
|
|
1344
|
+
{"status": "eligible", "provenance": "not_indexed", "counted": False, "lineage.unique_root": True, "lineage.root": CK(44)}, history=False)
|
|
1345
|
+
late_texts = [f"{C(46)} question {k}" for k in range(140)]
|
|
1346
|
+
late_texts[135] = "late shared words"
|
|
1347
|
+
claude("claude_old_shares_a_turn_past_the_head", 46, fx_claude(C(46), texts=late_texts, **old), {**before, "lineage.root": CK(46)}, mtime=fx_when(1, 9))
|
|
1348
|
+
claude("claude_replay_of_the_old_turn", 47, fx_claude(C(47), head="fork", stamps=[fx_stamp(1, 270, 9)] + [fx_stamp(3, k) for k in range(1, 6)],
|
|
1349
|
+
texts=["late shared words"]),
|
|
1350
|
+
{"status": "eligible", "provenance": "not_indexed", "counted": False, "window_overlap": "straddles_start",
|
|
1351
|
+
"lineage.unique_root": True, "lineage.root": CK(46)}, history=False)
|
|
1352
|
+
codex("codex_old_shares_a_turn_id_past_the_head", 34, fx_codex(X(34), month=9, day=1, turns=200),
|
|
1353
|
+
{**before, "lineage.root": XK(34)}, mtime=fx_when(1, 9))
|
|
1354
|
+
tail = {"timestamp": fx_stamp(3, 50), "type": "event_msg", "payload": {"type": "task_started", "turn_id": f"{X(34)}-t190"}}
|
|
1355
|
+
codex("codex_continuation_of_the_old_one", 35, fx_codex(X(35), meta={"history_base": {"thread_id": "gone"}}, ordinal=5) + [tail],
|
|
1356
|
+
{"status": "eligible", "counted": False, "lineage.unique_root": True, "lineage.root": XK(34)}, indexed=False)
|
|
1357
|
+
|
|
1358
|
+
# the remaining pointers of §5.3: a Codex history_base to a session that is here, and a thread_spawn child
|
|
1359
|
+
codex("codex_history_base_root", 36, fx_codex(X(36)), {**dated, "lineage.root": XK(36)})
|
|
1360
|
+
codex("codex_history_base_continuation", 37, fx_codex(X(37), meta={"history_base": {"thread_id": X(36)}}, ordinal=5),
|
|
1361
|
+
{"status": "eligible", "counted": False, "lineage.unique_root": True, "lineage.root": XK(36),
|
|
1362
|
+
"lineage.affirmed": [{"from": XK(37), "to": XK(36), "via": ["history_base"]}]}, indexed=False)
|
|
1363
|
+
codex("codex_thread_spawn_child", 38, fx_codex(X(38), source={"subagent": {"thread_spawn": {"parent_thread_id": X(36)}}}),
|
|
1364
|
+
{"status": "child_of", "parent": X(36), "counted": False}, indexed=False)
|
|
1365
|
+
|
|
1366
|
+
# identity is (host, id): one string names a Claude session and a Codex thread, and both survive
|
|
1367
|
+
claude("same_id_claude", 60, fx_claude(C(60)), {**counted, "host": "claude"})
|
|
1368
|
+
h.codex(C(60), fx_codex(C(60)), day=3)
|
|
1369
|
+
exp["same_id_codex"] = (lineage.identity("codex", C(60)), {**dated, "host": "codex", "source_class": "codex-cli"})
|
|
1370
|
+
|
|
1371
|
+
# identities an index names for the window with no transcript here, and one outside the window
|
|
1372
|
+
h.rows.append((X(20), "/gone/a.jsonl", "cli", "codex-tui", int(fx_when(3)), int(fx_when(4)), 0))
|
|
1373
|
+
exp["codex_index_only"] = (XK(20), {"status": "known_absent", "source_class": "codex-cli", "source": "codex_state", "path": None})
|
|
1374
|
+
h.rows.append((X(21), "/gone/b.jsonl", "exec", "codex_exec", int(fx_when(3)), int(fx_when(4)), 0))
|
|
1375
|
+
exp["codex_index_only_excluded"] = (XK(21), {"status": "excluded", "reason": "exec", "source": "codex_state"})
|
|
1376
|
+
h.rows.append((X(22), "/gone/c.jsonl", "cli", "codex-tui", int(fx_when(1, 1)), int(fx_when(2, 1)), 0))
|
|
1377
|
+
h.desktop(C(20), 3, 4)
|
|
1378
|
+
exp["desktop_index_only"] = (CK(20), {"status": "known_absent", "source_class": "claude-desktop", "source": "claude_desktop_index"})
|
|
1379
|
+
h.hist[C(21)] = int(fx_when(4) * 1000)
|
|
1380
|
+
exp["history_index_only"] = (CK(21), {"status": "known_absent", "source_class": "claude-cli", "source": "claude_history"})
|
|
1381
|
+
return exp
|
|
1382
|
+
|
|
1383
|
+
|
|
1384
|
+
def fx_results(census, status="read_complete", skip=(), extra_read=None, pending=None, resolved=None, members=True):
|
|
1385
|
+
"""S3's results for every eligible session: it read and processed everything the window owns (and the backlog),
|
|
1386
|
+
each range credited to the version it belongs to - of every file of the root, and of every file of each read member
|
|
1387
|
+
of its unit, a file named by its coverage key unless it is the root's only file under the root's own identity
|
|
1388
|
+
(D-20261103-85f3e8, D-20261103-a7128a). `skip` names sessions, `extra_read` files by key; `pending` and `resolved`
|
|
1389
|
+
are keyed by session. With `members` False the results answer the roots' own files alone."""
|
|
1390
|
+
by_key, found = {key_of(e): e for e in census["transcripts"]}, units(census["transcripts"])
|
|
1391
|
+
|
|
1392
|
+
def readings_of(file, named):
|
|
1393
|
+
newest = file["work"]["version"]
|
|
1394
|
+
if newest is None:
|
|
1395
|
+
return []
|
|
1396
|
+
name = {"transcript": file["key"]} if named else {}
|
|
1397
|
+
readings = {newest: {**name, "version": newest, "sha": file["sha256"], "processed": {census["window"]: file["work"]["in_window"]},
|
|
1398
|
+
"read": coverage.union(coverage.union(file["owned"], file["work"]["in_window"]), (extra_read or {}).get(file["key"], []))}}
|
|
1399
|
+
for b in file["work"]["backlog"]:
|
|
1400
|
+
got = readings.setdefault(b["version"], {**name, "version": b["version"], "sha": file["versions"][b["version"]]["sha"], "processed": {}, "read": []})
|
|
1401
|
+
got["processed"][b["window"]] = coverage.union(got["processed"].get(b["window"], []), b["unread"])
|
|
1402
|
+
got["read"] = coverage.union(got["read"], b["unread"])
|
|
1403
|
+
return [readings[v] for v in sorted(readings)]
|
|
1404
|
+
|
|
1405
|
+
out = []
|
|
1406
|
+
for e in census["transcripts"]:
|
|
1407
|
+
ident = key_of(e)
|
|
1408
|
+
if e["status"] != "eligible" or ident in skip:
|
|
1409
|
+
continue
|
|
1410
|
+
readings = [r for f in segments_of(e) for r in readings_of(f, f["key"] != ident)]
|
|
1411
|
+
for m in found.get(ident, []) if members else []:
|
|
1412
|
+
if by_key[m]["status"] == "child_of" and any(f["sha256"] for f in segments_of(by_key[m])):
|
|
1413
|
+
readings += [r for f in segments_of(by_key[m]) for r in readings_of(f, True)]
|
|
1414
|
+
out.append({"transcript": ident, "status": status, "readings": readings,
|
|
1415
|
+
"pending_events": (pending or {}).get(ident, []), "resolved_events": (resolved or {}).get(ident, [])})
|
|
1416
|
+
return out
|
|
1417
|
+
|
|
1418
|
+
|
|
1419
|
+
class Checks:
|
|
1420
|
+
"""The assertions of the self-test: each records its label and, when it does not hold, a failure that names it."""
|
|
1421
|
+
|
|
1422
|
+
def __init__(self):
|
|
1423
|
+
self.failures, self.ran = [], []
|
|
1424
|
+
|
|
1425
|
+
def expect(self, label, got, want):
|
|
1426
|
+
failures = self.failures
|
|
1427
|
+
self.ran.append(label)
|
|
1428
|
+
if got != want:
|
|
1429
|
+
failures.append(f"{label}: expected {want!r}, got {got!r}")
|
|
1430
|
+
|
|
1431
|
+
def refused(self, label, fn, *codes):
|
|
1432
|
+
failures = self.failures
|
|
1433
|
+
self.ran.append(label)
|
|
1434
|
+
try:
|
|
1435
|
+
fn()
|
|
1436
|
+
failures.append(f"{label}: nothing was refused")
|
|
1437
|
+
except (Refused, stagelock.Escaped) as exc:
|
|
1438
|
+
for code in codes:
|
|
1439
|
+
if code not in str(exc):
|
|
1440
|
+
failures.append(f"{label}: expected {code!r} in {exc}")
|
|
1441
|
+
|
|
1442
|
+
|
|
1443
|
+
def controls(checks):
|
|
1444
|
+
expect, refused = checks.expect, checks.refused
|
|
1445
|
+
probe = Checks()
|
|
1446
|
+
probe.expect("wrong value", 1, 2)
|
|
1447
|
+
probe.refused("no refusal", lambda: None)
|
|
1448
|
+
probe.refused("wrong code", lambda: (_ for _ in ()).throw(Refused("CODE_A")), "CODE_B")
|
|
1449
|
+
probe.refused("right code", lambda: (_ for _ in ()).throw(Refused("CODE_A")), "CODE_A")
|
|
1450
|
+
# an assert, not `expect`: the assertions are what is under test, and a statement that vouches for itself vouches for nothing
|
|
1451
|
+
assert [f.split(":")[0] for f in probe.failures] == ["wrong value", "no refusal", "wrong code"], \
|
|
1452
|
+
f"the assertions do not record a wrong value, a missing refusal and a wrong code, each by its label: {probe.failures}"
|
|
1453
|
+
table, table_sha = load_originators()
|
|
1454
|
+
empty = coverage.new_state()
|
|
1455
|
+
|
|
1456
|
+
def make(root, name="home", corrupt=False):
|
|
1457
|
+
home = Home(root / name)
|
|
1458
|
+
expected = fx_corpus(home)
|
|
1459
|
+
home.finish(corrupt=corrupt, wal=not corrupt) # the host has the Codex database open, its rows only in the write-ahead log
|
|
1460
|
+
return home, expected
|
|
1461
|
+
|
|
1462
|
+
def by_id(census):
|
|
1463
|
+
"""The census by bare session id: the fixtures share none across hosts except the one `by_key` serves."""
|
|
1464
|
+
return {e["id"]: fx_view(e) for e in census["transcripts"]}
|
|
1465
|
+
|
|
1466
|
+
def by_key(census):
|
|
1467
|
+
return {key_of(e): fx_view(e) for e in census["transcripts"]}
|
|
1468
|
+
|
|
1469
|
+
X1, C1 = "019e0001-0000-7000-8000-000000000000", "c0000001-0000-4000-8000-000000000000"
|
|
1470
|
+
cid, xid = (lambda sid: lineage.identity("claude", sid)), (lambda sid: lineage.identity("codex", sid)) # noqa: E731
|
|
1471
|
+
with tempfile.TemporaryDirectory() as td:
|
|
1472
|
+
root = pathlib.Path(td).resolve()
|
|
1473
|
+
scratch = root / "scratch"
|
|
1474
|
+
scratch.mkdir()
|
|
1475
|
+
home, expected = make(root)
|
|
1476
|
+
host_before = home.host_bytes()
|
|
1477
|
+
census, state = build(home.run(), empty, table, table_sha, jobs=4, scratch=scratch)
|
|
1478
|
+
found = by_id(census)
|
|
1479
|
+
expect("done-when 6, end to end: the host's db, -wal and -shm keep their bytes and mtimes through a whole census",
|
|
1480
|
+
(sorted(n for n, *_ in host_before), home.host_bytes() == host_before, list(scratch.iterdir())),
|
|
1481
|
+
(["state_5.sqlite", "state_5.sqlite-shm", "state_5.sqlite-wal"], True, []))
|
|
1482
|
+
expect("every thread row lives only in the write-ahead log and is still found: the census indexed them",
|
|
1483
|
+
(sqlite3.connect(f"file:{home.db}?immutable=1", uri=True).execute("select count(*) from threads").fetchone()[0], by_id(census)[X1]["provenance"]),
|
|
1484
|
+
(0, "indexed"))
|
|
1485
|
+
|
|
1486
|
+
# the corpus is O1 of design §18; the positive control comes first, then each fixture's status flipped by name
|
|
1487
|
+
expect("the fixtures are declared golden", REALIZATION, "golden")
|
|
1488
|
+
expect("every fixture is declared and present", (len(expected) >= 60, [n for n, (i, _) in expected.items() if i not in by_key(census)]), (True, []))
|
|
1489
|
+
expect("every fixture classifies as expected", fx_check(census, expected), [])
|
|
1490
|
+
expect("the census can emit every link of design §5.3: pointers, shared record ids and identical (timestamp, human text) turns",
|
|
1491
|
+
{via for e in census["transcripts"] for edge in e["lineage"]["affirmed"] for via in edge["via"]},
|
|
1492
|
+
{"forked_from_id", "history_base", "continued_in", "record_ids", "timestamp_text"})
|
|
1493
|
+
expect("the other pointers of §5.3 name a child: parent_thread_id and source.subagent.thread_spawn",
|
|
1494
|
+
[(found[xi]["status"], found[xi]["parent"]) for xi in ("019e0009-0000-7000-8000-000000000000", "019e0038-0000-7000-8000-000000000000")],
|
|
1495
|
+
[("child_of", "019e0001-0000-7000-8000-000000000000"), ("child_of", "019e0036-0000-7000-8000-000000000000")])
|
|
1496
|
+
same = lineage.split_identity(lineage.identity("codex", "c0000060-0000-4000-8000-000000000000"))[1]
|
|
1497
|
+
expect("one id on two hosts is two transcripts, two entries of the coverage state, and the sets still add up",
|
|
1498
|
+
(sorted(e["host"] for e in census["transcripts"] if e["id"] == same),
|
|
1499
|
+
sorted(identity_of_key(k) for k in state["transcripts"] if identity_of_key(k).endswith(same)), account(census)),
|
|
1500
|
+
(["claude", "codex"], [f"claude:{same}", f"codex:{same}"], []))
|
|
1501
|
+
for name, (ident, want) in sorted(expected.items()):
|
|
1502
|
+
flipped = next(s for s in STATUSES_5_1 if s != want.get("status", "eligible"))
|
|
1503
|
+
named = [e for e in fx_check(census, {name: (ident, {**want, "status": flipped})}) if f"FIXTURE {name}:" in e and "status" in e]
|
|
1504
|
+
expect(f"fixture {name}: a flipped expected status fails by its name", len(named), 1)
|
|
1505
|
+
expect("an expected id that is not there is named", fx_check(census, {"ghost": ("nope", {"status": "eligible"})}),
|
|
1506
|
+
["FIXTURE ghost: nope is not in the census"])
|
|
1507
|
+
expect("a windowed read leaves no non-vacuous gap: the census read the compressed rollout in the window",
|
|
1508
|
+
(found["019e0010-0000-7000-8000-000000000000"]["sha256"] is not None, found["019e0010-0000-7000-8000-000000000000"]["owned"] != []),
|
|
1509
|
+
(True, True))
|
|
1510
|
+
|
|
1511
|
+
# the reports of §5.1 and §5.3: originators with counts, the unknown-independence share, pins per source
|
|
1512
|
+
expect("originators are listed with their counts", {k: v["count"] for k, v in census["originators"].items()},
|
|
1513
|
+
{"Codex Desktop": 4, "codex_work_desktop": 1, "Claude Code": 1, "NewClient": 1, "agent-bios": 2})
|
|
1514
|
+
expect("the share of components and sessions with unknown independence", census["independence"],
|
|
1515
|
+
{"components": 36, "unknown_components": 10, "sessions": 48, "unknown_sessions": 12})
|
|
1516
|
+
expect("pins are counted per source", census["pins"]["codex_sessions"], {"eligible": 20, "pinned": 1})
|
|
1517
|
+
expect("provenance is counted per host and first entrypoint", (census["provenance"]["claude/claude-desktop"], census["provenance"]["codex/vscode"]),
|
|
1518
|
+
({"indexed": 1, "not_indexed": 1, "index_missing": 0}, {"indexed": 5, "not_indexed": 4, "index_missing": 0}))
|
|
1519
|
+
expect("index-only identities are filed under the index that named them", {n: r["totals"] for n, r in census["sources"].items()
|
|
1520
|
+
if n in ("codex_state", "claude_history", "claude_desktop_index")},
|
|
1521
|
+
{"codex_state": {"known_absent": 1, "excluded": 1}, "claude_history": {"known_absent": 1}, "claude_desktop_index": {"known_absent": 1}})
|
|
1522
|
+
expect("an index row outside the window names nothing", "019e0022-0000-7000-8000-000000000000" in found, False)
|
|
1523
|
+
expect("the census conforms to its schema and the dump is JSON of it", (validate.validate_instance(validator(), census),
|
|
1524
|
+
json.loads(dump(census)) == json.loads(json.dumps(census))), ([], True))
|
|
1525
|
+
expect("a census document holds one transcript to a line", sum(1 for line in dump(census).splitlines() if line.startswith(' {"alt_paths"')),
|
|
1526
|
+
len(census["transcripts"]))
|
|
1527
|
+
|
|
1528
|
+
# done-when 2: statuses are disjoint and add up; a dropped, repeated or misfiled entry is SET_MISMATCH
|
|
1529
|
+
expect("the discovered set equals the statuses' union", account(census), [])
|
|
1530
|
+
dropped = copy.deepcopy(census)
|
|
1531
|
+
dropped["transcripts"] = [e for e in dropped["transcripts"] if e["id"] != X1]
|
|
1532
|
+
expect("an entry dropped from the census is named", [e.split(":")[0] for e in account(dropped)], ["SET_MISMATCH codex_sessions"])
|
|
1533
|
+
repeated = copy.deepcopy(census)
|
|
1534
|
+
repeated["transcripts"].append(copy.deepcopy(repeated["transcripts"][0]))
|
|
1535
|
+
expect("an identity that appears twice is named", any("appears 2 times" in e for e in account(repeated)), True)
|
|
1536
|
+
stray = copy.deepcopy(census)
|
|
1537
|
+
stray["transcripts"][0]["source"] = "no_such_source"
|
|
1538
|
+
expect("an entry filed under no source is named", any("not a source" in e for e in account(stray)), True)
|
|
1539
|
+
absent = copy.deepcopy(census)
|
|
1540
|
+
absent["sources"]["codex_archived_sessions"]["totals"] = None
|
|
1541
|
+
expect("an entry under a source with no total is named", any("has no total" in e for e in account(absent)), True)
|
|
1542
|
+
|
|
1543
|
+
# done-when 2, reconcile: S3's results fold back, the counts add up, and a deleted result is named
|
|
1544
|
+
results = fx_results(census)
|
|
1545
|
+
reconciled, after, flags = reconcile(census, state, results, "periodic")
|
|
1546
|
+
expect("no session stays eligible once S3 has answered", {e["status"] for e in reconciled["transcripts"] if e["source"] in ("claude_projects", "codex_sessions")}
|
|
1547
|
+
<= {"read_complete", "nothing_new", "child_of", "excluded", "unknown_provenance", "unreadable"}, True)
|
|
1548
|
+
expect("the per-source counts add up again", account(reconciled), [])
|
|
1549
|
+
expect("a window fully answered is accounted and fully read", (flags, after["windows"][census["window"]]), ({"accounted": True, "fully_read": True},) * 2)
|
|
1550
|
+
victim = results[3]["transcript"]
|
|
1551
|
+
refused("an S3 record deleted fails the reconciliation naming the session",
|
|
1552
|
+
lambda: reconcile(census, state, results[:3] + results[4:], "periodic"), "SET_MISMATCH", victim)
|
|
1553
|
+
refused("a result for a session that was not eligible", lambda: reconcile(census, state, results + [{**results[0], "transcript": cid("c0000004-0000-4000-8000-000000000000")}], "periodic"),
|
|
1554
|
+
"SET_MISMATCH", "extra=['claude:c0000004")
|
|
1555
|
+
refused("a session answered twice", lambda: reconcile(census, state, results + [results[0]], "periodic"), "SET_MISMATCH", "repeated=")
|
|
1556
|
+
left = fx_results(census, skip=(victim,))
|
|
1557
|
+
partial = copy.deepcopy(reconciled)
|
|
1558
|
+
next(e for e in partial["transcripts"] if key_of(e) == victim)["status"] = "eligible"
|
|
1559
|
+
expect("one session left non-terminal: the window is not accounted", coverage.accounted(partial["transcripts"], after, census["window"])[0], False)
|
|
1560
|
+
|
|
1561
|
+
# source states: a missing directory is unknown, never zero; an undeclared one is told apart; an empty one is zero
|
|
1562
|
+
census_missing, _ = build(home.run(codex_archived_sessions=root / "no-such-dir"), empty, table, table_sha, jobs=4)
|
|
1563
|
+
missing = census_missing["sources"]["codex_archived_sessions"]
|
|
1564
|
+
expect("a missing source directory is unknown with no total", (missing["state"], missing["totals"], missing["discovered"]), ("missing", None, None))
|
|
1565
|
+
expect("the other sources are unaffected and the sets still add up", (account(census_missing), census_missing["sources"]["codex_sessions"]["totals"]),
|
|
1566
|
+
([], census["sources"]["codex_sessions"]["totals"]))
|
|
1567
|
+
lost = by_id(census_missing)["019e0011-0000-7000-8000-000000000000"]
|
|
1568
|
+
expect("what lived in the missing directory is not claimed as read: the index still names it, absent",
|
|
1569
|
+
(lost["status"], lost["source"], lost["path"]), ("known_absent", "codex_state", None))
|
|
1570
|
+
census_undeclared, _ = build(home.run(drop=("claude_history",)), empty, table, table_sha, jobs=4)
|
|
1571
|
+
expect("an undeclared index is told from a missing one and its sessions are index_missing",
|
|
1572
|
+
(census_undeclared["sources"]["claude_history"]["state"], by_id(census_undeclared)["c0000001-0000-4000-8000-000000000000"]["provenance"],
|
|
1573
|
+
by_id(census_undeclared)["c0000001-0000-4000-8000-000000000000"]["counted"]), ("undeclared", "index_missing", False))
|
|
1574
|
+
void = Home(root / "void")
|
|
1575
|
+
void.finish()
|
|
1576
|
+
census_void, state_void = build(void.run(), empty, table, table_sha, jobs=4)
|
|
1577
|
+
expect("all sources empty: the run succeeds with zero eligible and zero totals, not unknown",
|
|
1578
|
+
([e for e in census_void["transcripts"] if e["status"] == "eligible"], census_void["sources"]["codex_sessions"]["totals"],
|
|
1579
|
+
census_void["sources"]["claude_projects"]["discovered"], census_void["independence"]),
|
|
1580
|
+
([], {}, 0, {"components": 0, "unknown_components": 0, "sessions": 0, "unknown_sessions": 0}))
|
|
1581
|
+
census_unzstd, _ = build(home.run(zstd="/nonexistent/zstd"), empty, table, table_sha, jobs=4)
|
|
1582
|
+
unreadable = {e["id"]: fx_view(e) for e in census_unzstd["transcripts"] if e["status"] == "unreadable"}
|
|
1583
|
+
packed = sorted(p.name for p in list(home.sessions.rglob("*.zst")) + list(home.archived.rglob("*.zst")))
|
|
1584
|
+
expect("with zstd missing every .zst rollout is unreadable by name, not skipped",
|
|
1585
|
+
(len(unreadable), len(packed), all("ZSTD_UNAVAILABLE /nonexistent/zstd" in e["reason"] and e["path"] in e["reason"] for e in unreadable.values() if e["path"].endswith(".zst"))),
|
|
1586
|
+
(len(packed), len(packed), True))
|
|
1587
|
+
expect("the plain rollouts are still read", by_id(census_unzstd)["019e0001-0000-7000-8000-000000000000"]["status"], "eligible")
|
|
1588
|
+
home_bad, _ = make(root, "bad-index", corrupt=True)
|
|
1589
|
+
census_bad, _ = build(home_bad.run(), empty, table, table_sha, jobs=4)
|
|
1590
|
+
bad = by_id(census_bad)["019e0001-0000-7000-8000-000000000000"]
|
|
1591
|
+
expect("an unreadable index makes its sessions index_missing: read, not counted",
|
|
1592
|
+
(census_bad["sources"]["codex_state"]["state"], bad["status"], bad["provenance"], bad["counted"], bad["sha256"] is not None),
|
|
1593
|
+
("unreadable", "eligible", "index_missing", False, True))
|
|
1594
|
+
|
|
1595
|
+
# D-20261103-85f3e8: the unit S1 judges is a root with every member at any depth. A Codex root whose own records
|
|
1596
|
+
# are all before the window, with a member chain three deep: the first two write in the window, the third does not
|
|
1597
|
+
units_home = Home(root / "units")
|
|
1598
|
+
R, K1, K2, K3 = (f"019e00{n}-0000-7000-8000-000000000000" for n in (80, 81, 82, 83))
|
|
1599
|
+
spawn = lambda parent: {"subagent": {"thread_spawn": {"parent_thread_id": parent}}} # noqa: E731
|
|
1600
|
+
units_home.codex(R, fx_codex(R, "vscode", "Codex Desktop", month=9, day=1), mtime=fx_when(1, 9))
|
|
1601
|
+
units_home.codex(K1, fx_codex(K1, spawn(R)), indexed=False)
|
|
1602
|
+
units_home.codex(K2, fx_codex(K2, spawn(K1)), indexed=False)
|
|
1603
|
+
units_home.codex(K3, fx_codex(K3, spawn(K2), month=9, day=1), indexed=False, mtime=fx_when(1, 9))
|
|
1604
|
+
# a Claude root before the window whose one subagent writes in it, and a second subagent that cannot be read
|
|
1605
|
+
CR = "c0000080-0000-4000-8000-000000000000"
|
|
1606
|
+
units_home.claude(CR, fx_claude(CR, month=9, day=1), mtime=fx_when(1, 9))
|
|
1607
|
+
units_home.child(CR, "agent-in", fx_claude(CR, side=(True, "in")))
|
|
1608
|
+
locked = units_home.child(CR, "agent-locked", fx_claude(CR, side=(True, "locked")))
|
|
1609
|
+
# a root with records before, inside and after the window, and one whose last line the host is still writing
|
|
1610
|
+
CB, CT = "c0000081-0000-4000-8000-000000000000", "c0000082-0000-4000-8000-000000000000"
|
|
1611
|
+
units_home.claude(CB, fx_claude(CB, stamps=["2026-09-30T10:00:00.000Z", "2026-10-03T10:00:00.000Z", "2026-10-09T10:00:00.000Z"]))
|
|
1612
|
+
writing = units_home.claude(CT, fx_claude(CT))
|
|
1613
|
+
with writing.open("ab") as handle:
|
|
1614
|
+
handle.write(b'{"type": "user", "timestamp": "2026-10-03T11:00:00.000Z", "message": {"role": "user", "content": "half')
|
|
1615
|
+
units_home.finish()
|
|
1616
|
+
locked.chmod(0)
|
|
1617
|
+
try:
|
|
1618
|
+
unit_census, unit_state = build(units_home.run(), empty, table, table_sha, jobs=2)
|
|
1619
|
+
finally:
|
|
1620
|
+
locked.chmod(0o644)
|
|
1621
|
+
u = by_key(unit_census)
|
|
1622
|
+
RK, K1K, K2K, K3K, CRK = xid(R), xid(K1), xid(K2), xid(K3), cid(CR)
|
|
1623
|
+
CIN, CLOCK = cid(f"{CR}/agent-in"), cid(f"{CR}/agent-locked")
|
|
1624
|
+
expect("85f3e8: a root whose own records are all before the window is eligible when a member writes in it",
|
|
1625
|
+
(u[RK]["status"], u[RK]["window_overlap"], u[RK]["owned"], u[CRK]["status"]), ("eligible", "context_only", [], "eligible"))
|
|
1626
|
+
expect("85f3e8: members are read at every depth - each carries the version S1 read and what the window owns of it",
|
|
1627
|
+
[(k, u[k]["status"], u[k]["sha256"] is not None, u[k]["owned"] != []) for k in (K1K, K2K, K3K, CIN)],
|
|
1628
|
+
[(K1K, "child_of", True, True), (K2K, "child_of", True, True), (K3K, "child_of", True, False), (CIN, "child_of", True, True)])
|
|
1629
|
+
expect("85f3e8: the unit is the root with every member under it, whatever the depth; a member left unreadable is no longer in it",
|
|
1630
|
+
(units(unit_census["transcripts"]).get(RK), units(unit_census["transcripts"]).get(CRK)), ([K1K, K2K, K3K], [CIN]))
|
|
1631
|
+
expect("85f3e8: a member that cannot be read is named unreadable under its parent, and the unit is judged on the rest",
|
|
1632
|
+
(u[CLOCK]["status"], u[CLOCK]["parent"], "READ_FAILED" in (u[CLOCK]["reason"] or ""), u[CRK]["status"]),
|
|
1633
|
+
("unreadable", CR, True, "eligible"))
|
|
1634
|
+
expect("85f3e8: a unit active only through a member counts once, through its root",
|
|
1635
|
+
(u[RK]["counted"], u[RK]["provenance"], u[RK]["lineage"]["unique_root"]), (True, "indexed", True))
|
|
1636
|
+
expect("the window_overlap of a transcript with records before, inside and after the window says it straddles both",
|
|
1637
|
+
(u[cid(CB)]["window_overlap"], u[cid(CB)]["owned"]), ("straddles_both", [[5, 6]]))
|
|
1638
|
+
complete = writing.read_bytes().rsplit(b"\n", 1)[0] + b"\n"
|
|
1639
|
+
expect("8facee: the version S1 records is the complete lines - a line the host is still writing moves no hash",
|
|
1640
|
+
(u[cid(CT)]["sha256"], u[cid(CT)]["versions"][-1]["prefix_sha"], u[cid(CT)]["versions"][-1]["record_count"]),
|
|
1641
|
+
(hashlib.sha256(complete).hexdigest(), hashlib.sha256(complete).hexdigest(), 10))
|
|
1642
|
+
expect("the unit census conforms to its schema and its sets add up", (validate.validate_instance(validator(), unit_census), account(unit_census)), ([], []))
|
|
1643
|
+
# one S3 result answers the unit: its members' readings are credited to them, and a result that leaves a member's
|
|
1644
|
+
# window unprocessed, or reads outside its unit, is refused by name
|
|
1645
|
+
unit_results = fx_results(unit_census)
|
|
1646
|
+
_rc, unit_after, unit_flags = reconcile(unit_census, unit_state, unit_results, "periodic")
|
|
1647
|
+
expect("85f3e8: a member's readings are credited to the member, and the window is accounted",
|
|
1648
|
+
(coverage.latest(unit_after, segments_of(by_key(unit_census)[K2K])[0]["key"])["processed"].get(unit_census["window"]), unit_flags),
|
|
1649
|
+
(u[K2K]["owned"], {"accounted": True, "fully_read": True}))
|
|
1650
|
+
refused("85f3e8: a read_complete that leaves a member's window unprocessed is refused, naming the member",
|
|
1651
|
+
lambda: reconcile(unit_census, unit_state, fx_results(unit_census, members=False), "periodic"), "RESULT_INCONSISTENT", CIN)
|
|
1652
|
+
stranger = [{**r, "readings": r["readings"] + [{**r["readings"][0], "transcript": XK1}]} for r in unit_results
|
|
1653
|
+
for XK1 in [xid(X1)]]
|
|
1654
|
+
refused("85f3e8: a reading that names a transcript outside the result's unit is refused",
|
|
1655
|
+
lambda: reconcile(unit_census, unit_state, stranger, "periodic"), "RESULT_INCONSISTENT", "not a member of its unit")
|
|
1656
|
+
partial = {r["transcript"]: r for r in fx_results(unit_census, status="deferred", members=False)}
|
|
1657
|
+
deferred = [partial[r["transcript"]] if r["transcript"] in (RK, CRK) else r for r in unit_results]
|
|
1658
|
+
_rd, deferred_after, deferred_flags = reconcile(unit_census, unit_state, deferred, "periodic")
|
|
1659
|
+
expect("85f3e8: a carried result keeps every member's unread window in the backlog, under the member",
|
|
1660
|
+
(sorted(identity_of_key(b["transcript"]) for b in deferred_after["backlog"] if identity_of_key(b["transcript"]) in (K1K, K2K, CIN)),
|
|
1661
|
+
deferred_flags["accounted"]),
|
|
1662
|
+
(sorted([K1K, K2K, CIN]), True))
|
|
1663
|
+
|
|
1664
|
+
# review c0fix r1 #2: a member whose full read fails, under a root and above a member of its own, is named and
|
|
1665
|
+
# leaves the unit; what lies below it stays in the root's unit and is read, processed and carried with it
|
|
1666
|
+
mid_home = Home(root / "mid")
|
|
1667
|
+
MR, MM, MD = (f"019e00{n}-0000-7000-8000-000000000000" for n in (84, 85, 86))
|
|
1668
|
+
mid_home.codex(MR, fx_codex(MR, "vscode", "Codex Desktop"))
|
|
1669
|
+
mid_file = mid_home.codex(MM, fx_codex(MM, spawn(MR)), indexed=False)
|
|
1670
|
+
mid_home.codex(MD, fx_codex(MD, spawn(MM)), indexed=False)
|
|
1671
|
+
mid_home.finish()
|
|
1672
|
+
whole_read = globals()["read_full"]
|
|
1673
|
+
|
|
1674
|
+
def mid_fails(file, *args, **kwargs):
|
|
1675
|
+
"""The head of the middle member reads, so it names its parent; its full read fails, as a tail the host
|
|
1676
|
+
corrupted or a file replaced between the two reads would make it."""
|
|
1677
|
+
if file["path"] == str(mid_file):
|
|
1678
|
+
raise sources.Unreadable(f"READ_FAILED {mid_file}: planted")
|
|
1679
|
+
return whole_read(file, *args, **kwargs)
|
|
1680
|
+
|
|
1681
|
+
globals()["read_full"] = mid_fails
|
|
1682
|
+
try:
|
|
1683
|
+
mid_census, mid_state = build(mid_home.run(), empty, table, table_sha, jobs=2)
|
|
1684
|
+
finally:
|
|
1685
|
+
globals()["read_full"] = whole_read
|
|
1686
|
+
mv, MDK = by_key(mid_census), segments_of(by_key(mid_census)[xid(MD)])[0]["key"]
|
|
1687
|
+
expect("r1 #2: a member whose read failed keeps its parent, and the member below it stays in the root's unit",
|
|
1688
|
+
(mv[xid(MM)]["status"], mv[xid(MM)]["parent"], units(mid_census["transcripts"]).get(xid(MR))), ("unreadable", MR, [xid(MD)]))
|
|
1689
|
+
_rm, mid_after, mid_flags = reconcile(mid_census, mid_state, fx_results(mid_census), "periodic")
|
|
1690
|
+
expect("r1 #2: the member below a failed one is processed with its root, and the window is accounted",
|
|
1691
|
+
((coverage.latest(mid_after, MDK) or {}).get("processed", {}).get(mid_census["window"]), mid_flags),
|
|
1692
|
+
(mv[xid(MD)]["owned"], {"accounted": True, "fully_read": True}))
|
|
1693
|
+
refused("r1 #2: a read_complete that leaves the member below a failed one unprocessed is refused, naming it",
|
|
1694
|
+
lambda: reconcile(mid_census, mid_state, fx_results(mid_census, members=False), "periodic"), "RESULT_INCONSISTENT", MDK)
|
|
1695
|
+
|
|
1696
|
+
# review c0fix r1 #1: a record appended after the run of the window its stamp is in is owed to that window by the
|
|
1697
|
+
# next run (D-20261103-8facee): a line the host was still writing at window 1's census and completed since, and a
|
|
1698
|
+
# complete line written late; a line stamped in the window being run is that window's, as before
|
|
1699
|
+
late_home = Home(root / "late")
|
|
1700
|
+
LP, LA = "c0000090-0000-4000-8000-000000000000", "c0000091-0000-4000-8000-000000000000"
|
|
1701
|
+
partial_path, append_path = late_home.claude(LP, fx_claude(LP, day=7)), late_home.claude(LA, fx_claude(LA, day=7))
|
|
1702
|
+
with partial_path.open("ab") as handle:
|
|
1703
|
+
handle.write(b'{"type": "user", "timestamp": "2026-10-07T12:00:00.000Z", "message": {"role": "user", "content": "half')
|
|
1704
|
+
LR, LF = "c0000092-0000-4000-8000-000000000000", "c0000093-0000-4000-8000-000000000000"
|
|
1705
|
+
rewritten_path = late_home.claude(LR, fx_claude(LR, day=7))
|
|
1706
|
+
late_home.finish()
|
|
1707
|
+
late1, late_state1 = build(late_home.run(), empty, table, table_sha, jobs=2)
|
|
1708
|
+
_rl, late_after1, _fl = reconcile(late1, late_state1, fx_results(late1), "periodic")
|
|
1709
|
+
with partial_path.open("ab") as handle:
|
|
1710
|
+
handle.write(b'"}}\n')
|
|
1711
|
+
with append_path.open("ab") as handle:
|
|
1712
|
+
for stamp in ("2026-10-07T13:00:00.000Z", "2026-10-09T09:00:00.000Z"):
|
|
1713
|
+
handle.write(json.dumps({"type": "user", "timestamp": stamp, "message": {"role": "user", "content": "late"}}).encode() + b"\n")
|
|
1714
|
+
# outside the fix, and counted: a session rewritten since window 1 was run, and one never read before, both stamped in it
|
|
1715
|
+
late_home.put(rewritten_path, fx_claude(LR, day=7, texts=["the first question, rewritten"]))
|
|
1716
|
+
late_home.claude(LF, fx_claude(LF, day=7, turns=2))
|
|
1717
|
+
late2, late_state2 = build(late_home.run(window=NEXT), late_after1, table, table_sha, jobs=2)
|
|
1718
|
+
lv, W1ID = by_key(late2), late1["window"]
|
|
1719
|
+
expect("r1 #1: with no window run before, nothing can be owned by no run, and the census says it judged no window",
|
|
1720
|
+
late1["unowned"], {"earlier_windows": 0, "rewritten": {"files": 0, "records": 0}, "first_seen": {"files": 0, "records": 0}})
|
|
1721
|
+
expect("r1 #1: what a window already run owns in a rewritten version or a file never read before is counted, by cause",
|
|
1722
|
+
late2["unowned"], {"earlier_windows": 1, "rewritten": {"files": 1, "records": 10}, "first_seen": {"files": 1, "records": 8}})
|
|
1723
|
+
expect("r1 #1: a line completed after its window was run is owed to that window by the next run",
|
|
1724
|
+
(lv[cid(LP)]["status"], lv[cid(LP)]["work"]["backlog"], lv[cid(LP)]["work"]["in_window"]),
|
|
1725
|
+
("eligible", [{"window": W1ID, "version": 0, "unread": [[10, 11]]}], []))
|
|
1726
|
+
expect("r1 #1: a complete line written late is owed to the window its stamp is in, a line of the window being run to it",
|
|
1727
|
+
(lv[cid(LA)]["work"]["backlog"], lv[cid(LA)]["work"]["in_window"]),
|
|
1728
|
+
([{"window": W1ID, "version": 0, "unread": [[10, 11]]}], [[11, 12]]))
|
|
1729
|
+
expect("r1 #1: S1 holds them in the run's backlog under the status appended",
|
|
1730
|
+
sorted((b["transcript"], b["window"], b["status"], b["unread"]) for b in late_state2["backlog"]),
|
|
1731
|
+
[(cid(LP), W1ID, "appended", [[10, 11]]), (cid(LA), W1ID, "appended", [[10, 11]])])
|
|
1732
|
+
_rl2, late_after2, late_flags2 = reconcile(late2, late_state2, fx_results(late2), "periodic")
|
|
1733
|
+
expect("r1 #1: the next run processes each under its own window, and nothing is left owed",
|
|
1734
|
+
([coverage.latest(late_after2, k)["processed"] for k in (cid(LP), cid(LA))], late_after2["backlog"], late_flags2),
|
|
1735
|
+
([{W1ID: [[0, 11]]}, {W1ID: [[0, 11]], NEXT_ID: [[11, 12]]}], [], {"accounted": True, "fully_read": True}))
|
|
1736
|
+
late_t, late_t_state = build(late_home.run(kind="targeted", window=NEXT), late_after1, table, table_sha, jobs=2)
|
|
1737
|
+
try:
|
|
1738
|
+
_rt, late_t_after, late_t_flags = reconcile(late_t, late_t_state, fx_results(late_t), "targeted")
|
|
1739
|
+
targeted_late = (late_t_flags, records.json_text(late_t_after) == records.json_text(late_after1))
|
|
1740
|
+
except Refused as exc: # a control reads the refusal, never a traceback
|
|
1741
|
+
targeted_late = str(exc)[:300]
|
|
1742
|
+
expect("r1 #1: a targeted run reads the appended records under their window, and leaves periodic coverage as it was",
|
|
1743
|
+
targeted_late, ({"accounted": True, "fully_read": True}, True))
|
|
1744
|
+
# WP-08 commit 4b, Q4: unowned records are counted only against the windows already run other than the one being
|
|
1745
|
+
# run (`earlier` in `build`), so the share of the window S3 reads is zero by construction, and S3's observation
|
|
1746
|
+
# basis takes no unowned input (`stage_read.observation_scope`). A re-run of window 1 over the state its first run
|
|
1747
|
+
# left, with a file rewritten and one first seen since, counts none of their records as unowned.
|
|
1748
|
+
try:
|
|
1749
|
+
rerun_unowned = build(late_home.run(), late_after1, table, table_sha, jobs=2)[0]["unowned"]
|
|
1750
|
+
except Refused as exc: # a control reads the refusal, never a traceback
|
|
1751
|
+
rerun_unowned = str(exc)[:300]
|
|
1752
|
+
expect("4b Q4: a census never counts the window it is run for among the windows unowned records are owed to",
|
|
1753
|
+
rerun_unowned, {"earlier_windows": 0, "rewritten": {"files": 0, "records": 0}, "first_seen": {"files": 0, "records": 0}})
|
|
1754
|
+
# what read_full says a window already run owns is the appended records only, never the ones before them
|
|
1755
|
+
lines = append_path.read_bytes().splitlines(keepends=True)
|
|
1756
|
+
before = {"record_count": 10, "prefix_sha": hashlib.sha256(b"".join(lines[:10])).hexdigest()}
|
|
1757
|
+
w1_start, w1_end, _w1 = coverage.window_bounds(WINDOW)
|
|
1758
|
+
got_late = read_full({"host": "claude", "path": str(append_path)}, ZSTD, NO_SCAN, coverage.Ownership(*coverage.window_bounds(NEXT)[:2]),
|
|
1759
|
+
before, [(w1_start, w1_end, W1ID)])
|
|
1760
|
+
expect("r1 #1: the records a window already run owns are taken from the append alone", (got_late["prefix_ok"], got_late["late"]),
|
|
1761
|
+
(True, {W1ID: [[10, 11]]}))
|
|
1762
|
+
|
|
1763
|
+
# D-20261103-a7128a: a Codex thread written across several rollout files under one id is one row, a file per
|
|
1764
|
+
# segment in name order, each under its own coverage key; a copy of one file under the same name is no segment
|
|
1765
|
+
seg_home = Home(root / "segments")
|
|
1766
|
+
SL, SF, SS, ST, SC, G = (f"019e01{n}-0000-7000-8000-000000000000" for n in (10, 11, 12, 13, 14, 15))
|
|
1767
|
+
later = {"history_base": {"thread_id": "019e0199-0000-7000-8000-000000000000", "end_ordinal_exclusive": 7}}
|
|
1768
|
+
# SL: in the window only in its last file, the first before it; the index names the last; only the last compacted
|
|
1769
|
+
seg_home.codex(SL, fx_codex(SL, "vscode", "Codex Desktop", month=9, day=20), indexed=False, name_at="2026-09-20T10-00-00")
|
|
1770
|
+
seg_home.codex(SL, fx_codex(SL, "vscode", "Codex Desktop", meta=later, compacted=True), name_at="2026-10-03T10-00-00")
|
|
1771
|
+
# SF: in the window only in its first file, the last after it, and the later file's history_base points elsewhere;
|
|
1772
|
+
# its first file was archived, so the census finds the later one first, and the later one says it was run by exec
|
|
1773
|
+
seg_home.codex(SF, fx_codex(SF, "vscode", "Codex Desktop"), where="archived", name_at="2026-10-03T10-00-00")
|
|
1774
|
+
seg_home.codex(SF, fx_codex(SF, "exec", "codex_exec", day=10, meta=later), indexed=False, name_at="2026-10-10T10-00-00")
|
|
1775
|
+
# SS: both files in the window; the second has a compressed copy in archived_sessions, which the index names
|
|
1776
|
+
seg_home.codex(SS, fx_codex(SS, "vscode", "Codex Desktop", day=2), indexed=False, name_at="2026-10-02T10-00-00")
|
|
1777
|
+
seg_home.codex(SS, fx_codex(SS, "vscode", "Codex Desktop", day=4, meta=later), indexed=False, name_at="2026-10-04T10-00-00", day=4)
|
|
1778
|
+
copy_of = seg_home.codex(SS, fx_codex(SS, "vscode", "Codex Desktop", day=4, meta=later), where="archived", zst=True,
|
|
1779
|
+
name_at="2026-10-04T10-00-00", day=4)
|
|
1780
|
+
# ST: its last file is being written: a line without its end
|
|
1781
|
+
seg_home.codex(ST, fx_codex(ST, "vscode", "Codex Desktop", day=2), name_at="2026-10-02T10-00-00")
|
|
1782
|
+
writing_file = seg_home.codex(ST, fx_codex(ST, "vscode", "Codex Desktop", day=4, meta=later), indexed=False, name_at="2026-10-04T10-00-00", day=4)
|
|
1783
|
+
with writing_file.open("ab") as handle:
|
|
1784
|
+
handle.write(b'{"timestamp": "2026-10-04T11:00:00.000Z", "type": "event_msg", "payload": {"type": "task_sta')
|
|
1785
|
+
# SC: a child of SF in two files; G: a Guardian review of SS
|
|
1786
|
+
spawn_of = lambda parent: {"subagent": {"thread_spawn": {"parent_thread_id": parent}}} # noqa: E731
|
|
1787
|
+
seg_home.codex(SC, fx_codex(SC, spawn_of(SF)), indexed=False, name_at="2026-10-03T11-00-00")
|
|
1788
|
+
seg_home.codex(SC, fx_codex(SC, spawn_of(SF), day=5, meta=later), indexed=False, name_at="2026-10-05T11-00-00", day=5)
|
|
1789
|
+
seg_home.codex(G, fx_codex(G, {"subagent": {"other": "guardian"}}, meta={"parent_thread_id": SS}), indexed=False)
|
|
1790
|
+
# a Claude session with a workflow's journal beside its subagents
|
|
1791
|
+
CW = "c0000090-0000-4000-8000-000000000000"
|
|
1792
|
+
seg_home.claude(CW, fx_claude(CW))
|
|
1793
|
+
seg_home.put(seg_home.projects / "-fx" / CW / "subagents" / "workflows" / "w" / "journal.jsonl", [{"type": "step"}])
|
|
1794
|
+
seg_home.finish()
|
|
1795
|
+
seg_census, seg_state = build(seg_home.run(), empty, table, table_sha, jobs=2)
|
|
1796
|
+
sg = {key_of(e): e for e in seg_census["transcripts"]}
|
|
1797
|
+
files = {k: segments_of(e) for k, e in sg.items()}
|
|
1798
|
+
SLK, SFK, SSK, STK, SCK, GK = (xid(s) for s in (SL, SF, SS, ST, SC, G))
|
|
1799
|
+
expect("a7128a: a thread in several files is one row, its files in name order, each under its own coverage key",
|
|
1800
|
+
[(f["key"], f["source"]) for f in files[SSK]],
|
|
1801
|
+
[(f"{SSK}@rollout-2026-10-02T10-00-00-{SS}", "codex_sessions"), (f"{SSK}@rollout-2026-10-04T10-00-00-{SS}", "codex_sessions")])
|
|
1802
|
+
expect("a7128a: a file found again under its own name is a copy beside its row, not a file of the session",
|
|
1803
|
+
(sg[SSK]["alt_paths"], len(files[SSK])), ([str(copy_of)], 2))
|
|
1804
|
+
expect("a7128a: a thread in the window only in its last file is eligible, and the window owns that file's records",
|
|
1805
|
+
(sg[SLK]["status"], [f["owned"] != [] for f in files[SLK]], [f["sha256"] is not None for f in files[SLK]], sg[SLK]["window_overlap"]),
|
|
1806
|
+
("eligible", [False, True], [True, True], "straddles_start"))
|
|
1807
|
+
expect("a7128a: a thread in the window only in its first file is eligible, and the window owns that file's records",
|
|
1808
|
+
(sg[SFK]["status"], [f["owned"] != [] for f in files[SFK]], sg[SFK]["window_overlap"]), ("eligible", [True, False], "straddles_end"))
|
|
1809
|
+
expect("a7128a: a thread spanning two files owes the window both",
|
|
1810
|
+
[f["work"]["in_window"] != [] for f in files[SSK]], [True, True])
|
|
1811
|
+
complete_lines = writing_file.read_bytes().rsplit(b"\n", 1)[0] + b"\n"
|
|
1812
|
+
expect("a7128a: a file still being written is its complete lines, like any transcript",
|
|
1813
|
+
(files[STK][1]["sha256"], files[STK][1]["versions"][-1]["record_count"]), (hashlib.sha256(complete_lines).hexdigest(), 7))
|
|
1814
|
+
expect("a7128a: a thread is indexed when the index names any of its files, or a copy of one",
|
|
1815
|
+
(sg[SLK]["provenance"], sg[SFK]["provenance"], sg[SSK]["provenance"]), ("indexed", "indexed", "indexed"))
|
|
1816
|
+
expect("a7128a: the kind and pointer are the first file's, though the census found a later one first: its source "
|
|
1817
|
+
"classifies the thread, and a later file's history_base is no edge, so the thread is its own root",
|
|
1818
|
+
(sg[SFK]["status"], sg[SFK]["entrypoint"], sg[SFK]["lineage"]["root"], sg[SFK]["lineage"]["unique_root"],
|
|
1819
|
+
sg[SFK]["lineage"]["affirmed"], sg[SFK]["counted"]),
|
|
1820
|
+
("eligible", "vscode", SFK, True, [], True))
|
|
1821
|
+
expect("a7128a: a compaction in any file of a thread keeps its lineage pending",
|
|
1822
|
+
(sg[SLK]["lineage"]["measurement_pending"], sg[SFK]["lineage"]["measurement_pending"]), (True, False))
|
|
1823
|
+
expect("85f3e8 with a7128a: a member in two files is read in both, as part of its root's unit",
|
|
1824
|
+
(sg[SCK]["status"], [f["sha256"] is not None and f["owned"] != [] for f in files[SCK]], units(seg_census["transcripts"]).get(SFK)),
|
|
1825
|
+
("child_of", [True, True], [SCK]))
|
|
1826
|
+
expect("b1989d: a Guardian review session is excluded by name, and is no member of the session it reviews",
|
|
1827
|
+
(sg[GK]["status"], sg[GK]["reason"], units(seg_census["transcripts"]).get(SSK)), ("excluded", "guardian", None))
|
|
1828
|
+
expect("a workflow's journal under subagents/ is no child: no row, and counted with the files that are not read",
|
|
1829
|
+
(sorted(k for k in sg if k.startswith(cid(CW))), seg_census["sources"]["claude_projects"]["unrecognized"]), ([cid(CW)], 1))
|
|
1830
|
+
expect("the census of split threads conforms to its schema and its sets add up",
|
|
1831
|
+
(validate.validate_instance(validator(), seg_census), account(seg_census)), ([], []))
|
|
1832
|
+
|
|
1833
|
+
# one S3 result answers a thread in several files: each reading names the file it read, and is credited to it
|
|
1834
|
+
seg_results = fx_results(seg_census)
|
|
1835
|
+
_seg_done, seg_after, seg_flags = reconcile(seg_census, seg_state, seg_results, "periodic")
|
|
1836
|
+
expect("a7128a: each file's readings are credited to that file, the first and the last alike",
|
|
1837
|
+
([coverage.latest(seg_after, f["key"])["processed"].get(seg_census["window"]) for f in files[SSK]], seg_flags),
|
|
1838
|
+
([f["owned"] for f in files[SSK]], {"accounted": True, "fully_read": True}))
|
|
1839
|
+
pending_results = [{**r, "pending_events": [{"id": "pe-seg", "first_record": 2}]} if r["transcript"] == SSK else r for r in seg_results]
|
|
1840
|
+
_pending_done, pending_after, _pending_flags = reconcile(seg_census, seg_state, pending_results, "periodic")
|
|
1841
|
+
expect("a7128a: a pending event of a thread in several files is held under its last file unless it names one",
|
|
1842
|
+
[(e["transcript"], e["version"]) for e in pending_after["pending_events"] if e["id"] == "pe-seg"], [(files[SSK][-1]["key"], 0)])
|
|
1843
|
+
stray_event = [{**r, "pending_events": [{"id": "pe-stray", "first_record": 2, "transcript": f"{SSK}@nowhere"}]} if r["transcript"] == SSK
|
|
1844
|
+
else r for r in seg_results]
|
|
1845
|
+
refused("a7128a: a pending event naming a file outside its unit is refused",
|
|
1846
|
+
lambda: reconcile(seg_census, seg_state, stray_event, "periodic"), "RESULT_INCONSISTENT", "not a file of its unit")
|
|
1847
|
+
unnamed = [{**r, "readings": [{k: v for k, v in g.items() if k != "transcript"} for g in r["readings"]]} if r["transcript"] == SSK else r
|
|
1848
|
+
for r in seg_results]
|
|
1849
|
+
refused("a7128a: a reading that names no file of a thread written in several is refused",
|
|
1850
|
+
lambda: reconcile(seg_census, seg_state, unnamed, "periodic"), "RESULT_INCONSISTENT", "names no file")
|
|
1851
|
+
first_only = [{**r, "readings": [g for g in r["readings"] if g.get("transcript") != files[SSK][0]["key"]]} if r["transcript"] == SSK else r
|
|
1852
|
+
for r in seg_results]
|
|
1853
|
+
refused("a7128a: a read_complete that leaves the first file's window unprocessed is refused, naming that file",
|
|
1854
|
+
lambda: reconcile(seg_census, seg_state, first_only, "periodic"), "RESULT_INCONSISTENT", files[SSK][0]["key"])
|
|
1855
|
+
|
|
1856
|
+
# the shape of a row is its host's: the census's own accounting names a row that departs from it, and so does
|
|
1857
|
+
# the one reader of rows outside the census
|
|
1858
|
+
def bent(change):
|
|
1859
|
+
doc = copy.deepcopy(seg_census)
|
|
1860
|
+
change({key_of(e): e for e in doc["transcripts"]})
|
|
1861
|
+
return doc
|
|
1862
|
+
for label, change, why in (
|
|
1863
|
+
("a Codex row carrying a file's path on the row", lambda rows_: rows_[SSK].update(path="/x"), "never ['path'] on the row"),
|
|
1864
|
+
("a Codex row without segments", lambda rows_: rows_[SSK].pop("segments"), "and this one has none"),
|
|
1865
|
+
("a Claude row carrying segments", lambda rows_: rows_[cid(CW)].update(segments=[]), "never in segments")):
|
|
1866
|
+
doc = bent(change)
|
|
1867
|
+
expect(f"a7128a: {label} is named by the census's accounting",
|
|
1868
|
+
[e for e in account(doc) if "SET_MISMATCH shape" in e and why in e] != [], True)
|
|
1869
|
+
try:
|
|
1870
|
+
rows(doc)
|
|
1871
|
+
said = None
|
|
1872
|
+
except ValueError as exc:
|
|
1873
|
+
said = str(exc)
|
|
1874
|
+
expect(f"a7128a: {label} is refused by the reader of rows", "CENSUS_MALFORMED" in (said or ""), True)
|
|
1875
|
+
|
|
1876
|
+
# a file of a thread the coverage state owes work on that is gone: the row says which, and the work stays owed;
|
|
1877
|
+
# a thread with no file left is a lost transcript under the file's own key
|
|
1878
|
+
gone_key, lost_key = f"{SSK}@rollout-2026-10-01T09-00-00-{SS}", f"{xid('019e0198-0000-7000-8000-000000000000')}@rollout-2026-10-01T09-00-00-x"
|
|
1879
|
+
owing = coverage.new_state()
|
|
1880
|
+
for key in (gone_key, lost_key):
|
|
1881
|
+
coverage.observe(owing, key, "ab" * 32, 3, "ab" * 32, None)
|
|
1882
|
+
owing["backlog"].append({"transcript": key, "version": 0, "window": NEXT_ID, "status": "deferred", "unread": [[0, 3]]})
|
|
1883
|
+
owed_census, _owed_state = build(seg_home.run(), owing, table, table_sha, jobs=2)
|
|
1884
|
+
og = {key_of(e): e for e in owed_census["transcripts"]}
|
|
1885
|
+
expect("a7128a: a session whose owed file is gone is unreadable, naming the file, and lists it with no path",
|
|
1886
|
+
(og[SSK]["status"], (og[SSK]["reason"] or "").startswith(f"SEGMENT_ABSENT {gone_key}:"),
|
|
1887
|
+
[(f["key"], f["path"] is None) for f in segments_of(og[SSK])][0]),
|
|
1888
|
+
("unreadable", True, (gone_key, True)))
|
|
1889
|
+
expect("a7128a: a thread whose every owed file is gone is a lost transcript, listing the file it owes",
|
|
1890
|
+
((og[identity_of_key(lost_key)]["status"], [f["key"] for f in segments_of(og[identity_of_key(lost_key)])]),
|
|
1891
|
+
account(owed_census), validate.validate_instance(validator(), owed_census)),
|
|
1892
|
+
(("known_absent", [lost_key]), [], []))
|
|
1893
|
+
|
|
1894
|
+
# the structural guard: outside the census a census document is read only through its readers
|
|
1895
|
+
texts = reader_texts()
|
|
1896
|
+
bypasses, reader_sites = reader_bypasses(texts)
|
|
1897
|
+
expect("a7128a: outside the census, the census file is named only where an exception says why, and its rows are read through rows",
|
|
1898
|
+
(bypasses, len(texts) >= 20, sorted(reader_sites)), ([], True, sorted(READER_EXCEPTIONS)))
|
|
1899
|
+
for label, planted_text, code in (
|
|
1900
|
+
("a module that parses the census file itself", texts["runlib/views.py"]
|
|
1901
|
+
+ '\n\ndef sneak(run_dir):\n return json.loads((run_dir / "census.json").read_text())\n', "runlib/views.py (sneak)"),
|
|
1902
|
+
("a census document's rows taken around rows", texts["runlib/views.py"]
|
|
1903
|
+
+ '\n\ndef sneak(run_dir):\n doc = census.load(run_dir)\n return doc["transcripts"]\n', "(sneak): doc['transcripts']"),
|
|
1904
|
+
("an exception whose site no longer names the file", texts["runlib/views.py"].replace('"census.json"', '"elsewhere.json"'),
|
|
1905
|
+
"stale exception runlib/views.py (run)")):
|
|
1906
|
+
found_here = reader_bypasses({**texts, "runlib/views.py": planted_text})[0]
|
|
1907
|
+
expect(f"a7128a: {label} is named", [v for v in found_here if code in v] != [], True)
|
|
1908
|
+
|
|
1909
|
+
# done-when 1 and 3, the runs that follow one another: a resume, an event across the window's end, a rewrite
|
|
1910
|
+
two = Home(root / "two")
|
|
1911
|
+
T = "c0000070-0000-4000-8000-000000000000"
|
|
1912
|
+
TK = cid(T)
|
|
1913
|
+
stamps = ["2026-10-02T10:00:00.000Z", "2026-10-03T10:00:00.000Z", "2026-10-07T23:50:00.000Z", "2026-10-08T00:10:00.000Z", "2026-10-08T01:00:00.000Z"]
|
|
1914
|
+
path = two.claude(T, fx_claude(T, stamps=stamps), mtime=fx_when(9))
|
|
1915
|
+
original = path.read_bytes()
|
|
1916
|
+
M = "019e0070-0000-7000-8000-000000000000"
|
|
1917
|
+
MK = xid(M)
|
|
1918
|
+
moved = two.codex(M, fx_codex(M, "vscode", "Codex Desktop"), zst=True)
|
|
1919
|
+
two.finish()
|
|
1920
|
+
run1, built1 = build(two.run(), empty, table, table_sha, jobs=2)
|
|
1921
|
+
t1 = by_id(run1)[T]
|
|
1922
|
+
expect("run 1: the event's outcome lies past the window, so the session straddles its end and owns the records before it",
|
|
1923
|
+
(t1["window_overlap"], t1["owned"], t1["work"]["in_window"]), ("straddles_end", [[0, 7]], [[0, 7]]))
|
|
1924
|
+
event = {"id": "event-1", "first_record": 6}
|
|
1925
|
+
r1 = fx_results(run1, extra_read={TK: [[7, 9]]}, pending={TK: [event]})
|
|
1926
|
+
state1 = reconcile(run1, built1, r1, "periodic")[1]
|
|
1927
|
+
v1 = coverage.latest(state1, TK)
|
|
1928
|
+
expect("run 1: the outcome was read as context and is not processed for the window that did not own it",
|
|
1929
|
+
(v1["read"], v1["processed"]), ([[0, 9]], {run1["window"]: [[0, 7]]}))
|
|
1930
|
+
run2, built2 = build(two.run(window=NEXT), state1, table, table_sha, jobs=2)
|
|
1931
|
+
t2 = by_id(run2)[T]
|
|
1932
|
+
expect("run 2: the window that owns the outcome processes it again though run 1 read it", (t2["owned"], t2["work"]["in_window"]), ([[7, 9]], [[7, 9]]))
|
|
1933
|
+
expect("run 2: the pending event survives the run boundary with its id", [e["id"] for e in run2["pending_events"]], ["event-1"])
|
|
1934
|
+
state2 = reconcile(run2, built2, fx_results(run2, resolved={TK: ["event-1"]}), "periodic")[1]
|
|
1935
|
+
expect("run 2: the event is stitched and resolved; each record is processed once, by its own window",
|
|
1936
|
+
(coverage.latest(state2, TK)["processed"], state2["pending_events"]),
|
|
1937
|
+
({run1["window"]: [[0, 7]], run2["window"]: [[7, 9]]}, []))
|
|
1938
|
+
no_reread = fx_results(run2, resolved={TK: ["event-1"]})
|
|
1939
|
+
for answer in no_reread:
|
|
1940
|
+
for got in answer["readings"]:
|
|
1941
|
+
got["read"] = [] # the owning run keeps its processed credit but does not read the records again
|
|
1942
|
+
refused("the run that owns a context-read record may not process it without reading it again", lambda: reconcile(run2, built2, no_reread, "periodic"),
|
|
1943
|
+
"PROCESSED_UNREAD", "which this result did not read")
|
|
1944
|
+
again, _ = build(two.run(window=NEXT), state2, table, table_sha, jobs=2)
|
|
1945
|
+
expect("a transcript with nothing new since the last window is nothing_new", (by_id(again)[T]["status"], by_id(again)[T]["work"]["in_window"]),
|
|
1946
|
+
("nothing_new", []))
|
|
1947
|
+
before = fx_when(10)
|
|
1948
|
+
two.put(path, fx_claude(T, stamps=stamps + ["2026-10-09T09:00:00.000Z", "2026-10-09T09:01:00.000Z"]), mtime=before)
|
|
1949
|
+
appended, state3 = build(two.run(window=NEXT), state2, table, table_sha, jobs=2)
|
|
1950
|
+
t3 = by_id(appended)[T]
|
|
1951
|
+
expect("a resumed session with appended records is one transcript whose continuity holds and whose new records are a new range",
|
|
1952
|
+
(len(t3["versions"]), t3["versions"][0]["record_count"], t3["owned"], t3["work"]["in_window"], t3["status"], T in {e["id"] for e in appended["transcripts"]}),
|
|
1953
|
+
(1, 11, [[7, 11]], [[9, 11]], "eligible", True))
|
|
1954
|
+
|
|
1955
|
+
# a rewrite: a new version read in full; the evidence ids of the prior version still resolve to the copy of the bytes they came from
|
|
1956
|
+
store = root / "immutable-copies"
|
|
1957
|
+
store.mkdir()
|
|
1958
|
+
|
|
1959
|
+
def keep(data):
|
|
1960
|
+
"""The immutable copy S2 will make of each version, named by its sha (WP-06 owns it; this stands in for its store)."""
|
|
1961
|
+
(store / hashlib.sha256(data).hexdigest()).write_bytes(data)
|
|
1962
|
+
return hashlib.sha256(data).hexdigest()
|
|
1963
|
+
|
|
1964
|
+
def resolve(locator, state, defective=False):
|
|
1965
|
+
"""The bytes of one record an evidence id names: the version it came from, found by the sha the id carries."""
|
|
1966
|
+
versions = state["transcripts"][locator["transcript"]]["versions"]
|
|
1967
|
+
version = versions[-1] if defective else next(v for v in versions if v["sha"] == locator["sha"])
|
|
1968
|
+
return (store / version["sha"]).read_bytes().splitlines()[locator["record"]]
|
|
1969
|
+
|
|
1970
|
+
prior = {"transcript": TK, "sha": keep(original), "record": 4}
|
|
1971
|
+
two.put(path, fx_claude(T, stamps=["2026-10-02T11:00:00.000Z"] + stamps[1:]), mtime=before)
|
|
1972
|
+
rewritten, state4 = build(two.run(window=NEXT), state2, table, table_sha, jobs=2)
|
|
1973
|
+
t4 = by_id(rewritten)[T]
|
|
1974
|
+
expect("a rewritten transcript fails continuity: a new version, read in full, the prior version kept for its evidence",
|
|
1975
|
+
(len(t4["versions"]), t4["versions"][0]["sha"] == coverage.latest(state2, TK)["sha"], t4["versions"][1]["sha"] == t4["sha256"], t4["work"]["in_window"],
|
|
1976
|
+
coverage.latest(state4, TK)["read"]), (2, True, True, [[7, 9]], []))
|
|
1977
|
+
current = {"transcript": TK, "sha": keep(path.read_bytes()), "record": 4}
|
|
1978
|
+
live_record = path.read_bytes().splitlines()[4]
|
|
1979
|
+
expect("a prior version's evidence id still resolves to the bytes it was cut from, a new one to the new version's",
|
|
1980
|
+
(resolve(prior, state4) == original.splitlines()[4], resolve(prior, state4) != live_record, resolve(current, state4) == live_record),
|
|
1981
|
+
(True, True, True))
|
|
1982
|
+
expect("instrument control: a resolver that follows the latest version returns the rewritten record for the old id",
|
|
1983
|
+
resolve(prior, state4, defective=True) == live_record, True)
|
|
1984
|
+
|
|
1985
|
+
# a rollout moved to archived_sessions is the same transcript: the coverage captured before the move is the base of the run after it
|
|
1986
|
+
parked = by_id(run1)[M]
|
|
1987
|
+
archived_at = two.archived / moved.name
|
|
1988
|
+
archived_at.parent.mkdir(parents=True, exist_ok=True)
|
|
1989
|
+
moved.rename(archived_at)
|
|
1990
|
+
two.rows = [(M, str(archived_at)[:-len(".zst")], "vscode", "Codex Desktop", int(fx_when(3)), int(fx_when(4)), 1)]
|
|
1991
|
+
two.close()
|
|
1992
|
+
two.db.unlink()
|
|
1993
|
+
two.finish()
|
|
1994
|
+
run_b, state_b = build(two.run(), state1, table, table_sha, jobs=2)
|
|
1995
|
+
t_b = by_id(run_b)[M]
|
|
1996
|
+
expect("a rollout moved to archived_sessions is the same transcript: one version, a new path, still indexed",
|
|
1997
|
+
(t_b["id"], len(t_b["versions"]), t_b["sha256"] == parked["sha256"], t_b["source"], t_b["provenance"]),
|
|
1998
|
+
(M, 1, True, "codex_archived_sessions", "indexed"))
|
|
1999
|
+
expect("the move keeps its continuity: the ranges processed before it are still processed, so the window owes it nothing",
|
|
2000
|
+
(t_b["status"], t_b["work"]["in_window"],
|
|
2001
|
+
coverage.latest(state_b, f"{MK}@{stem_of(moved)}")["processed"] == coverage.latest(state1, f"{MK}@{stem_of(moved)}")["processed"] != {}),
|
|
2002
|
+
("nothing_new", [], True))
|
|
2003
|
+
run_c, _ = build(two.run(), empty, table, table_sha, jobs=2)
|
|
2004
|
+
expect("instrument control: a census that forgot the pre-move coverage would treat the moved file as new work",
|
|
2005
|
+
(by_id(run_c)[M]["status"], by_id(run_c)[M]["work"]["in_window"] != []), ("eligible", True))
|
|
2006
|
+
|
|
2007
|
+
# F#3 at the census: a backlog belongs to a version, and a rewrite that keeps the offsets cannot discharge it
|
|
2008
|
+
rw = Home(root / "rewrite")
|
|
2009
|
+
R = "c0000071-0000-4000-8000-000000000000"
|
|
2010
|
+
RK = cid(R)
|
|
2011
|
+
rpath = rw.claude(R, fx_claude(R))
|
|
2012
|
+
rw.finish()
|
|
2013
|
+
first_rw, built_rw = build(rw.run(), empty, table, table_sha, jobs=2)
|
|
2014
|
+
answers = fx_results(first_rw)
|
|
2015
|
+
answers[0].update(status="read_partial")
|
|
2016
|
+
answers[0]["readings"][0].update(read=[[0, 6]], processed={first_rw["window"]: [[0, 6]]})
|
|
2017
|
+
_, partial_rw, _ = reconcile(first_rw, built_rw, answers, "periodic")
|
|
2018
|
+
rw.put(rpath, fx_claude(R, texts=["rewritten a", "rewritten b", "rewritten c"], stamps=[fx_stamp(3, k) for k in range(5)] + [fx_stamp(3, 99)]))
|
|
2019
|
+
after_rw, built_after = build(rw.run(window=NEXT), partial_rw, table, table_sha, jobs=2)
|
|
2020
|
+
r_entry = by_id(after_rw)[R]
|
|
2021
|
+
expect("after a rewrite the backlog still names the version it was owed on, and the new version has work of its own",
|
|
2022
|
+
(len(r_entry["versions"]), r_entry["work"]["version"], r_entry["work"]["backlog"], r_entry["status"]),
|
|
2023
|
+
(2, 1, [{"window": first_rw["window"], "version": 0, "unread": [[6, 10]]}], "eligible"))
|
|
2024
|
+
good = fx_results(after_rw)
|
|
2025
|
+
done_rw, state_rw, _ = reconcile(after_rw, built_after, good, "periodic")
|
|
2026
|
+
expect("the backlog is discharged from a reading of the version it belongs to",
|
|
2027
|
+
(state_rw["backlog"], coverage.latest(state_rw, RK)["processed"], state_rw["transcripts"][RK]["versions"][0]["processed"]),
|
|
2028
|
+
([], {}, {first_rw["window"]: [[0, 10]]}))
|
|
2029
|
+
forged = copy.deepcopy(good)
|
|
2030
|
+
forged[0]["readings"] = [{"version": 1, "sha": forged[0]["readings"][-1]["sha"], "read": [[0, 10]], "processed": {first_rw["window"]: [[6, 10]]}}]
|
|
2031
|
+
refused("the same offsets read from the rewritten version do not discharge the old version's backlog",
|
|
2032
|
+
lambda: reconcile(after_rw, built_after, forged, "periodic"), "PROCESSED_OUTSIDE_OWNED", f"version 1 processed [[6, 10]] for window {first_rw['window']}")
|
|
2033
|
+
|
|
2034
|
+
# done-when 1 and 3: deferred and partial sessions are carried, and read first by the next run
|
|
2035
|
+
carry = Home(root / "carry")
|
|
2036
|
+
ids = [f"c00000{n}-0000-4000-8000-000000000000" for n in (40, 41, 42)]
|
|
2037
|
+
keys = [cid(i) for i in ids]
|
|
2038
|
+
for sid in ids:
|
|
2039
|
+
carry.claude(sid, fx_claude(sid))
|
|
2040
|
+
carry.finish()
|
|
2041
|
+
first, built_first = build(carry.run(), empty, table, table_sha, jobs=2)
|
|
2042
|
+
answers = fx_results(first)
|
|
2043
|
+
answers[0].update(status="read_partial")
|
|
2044
|
+
answers[0]["readings"][0].update(read=[[0, 6]], processed={first["window"]: [[0, 6]]})
|
|
2045
|
+
answers[1].update(status="deferred", readings=[])
|
|
2046
|
+
answers[2].update(status="failed", readings=[])
|
|
2047
|
+
done, carried, flags = reconcile(first, built_first, answers, "periodic")
|
|
2048
|
+
expect("partial, deferred and failed sessions are terminal, with their unread ranges in the backlog",
|
|
2049
|
+
({key_of(e): e["status"] for e in done["transcripts"]}, [(b["transcript"], b["status"], b["unread"]) for b in carried["backlog"]], flags),
|
|
2050
|
+
(dict(zip(keys, ("read_partial", "deferred", "failed"))), [(keys[0], "read_partial", [[6, 10]]), (keys[1], "deferred", [[0, 10]]),
|
|
2051
|
+
(keys[2], "failed", [[0, 10]])], {"accounted": True, "fully_read": False}))
|
|
2052
|
+
expect("accounted and fully read are counted apart", (window_counts(first["transcripts"]), window_counts(done["transcripts"])),
|
|
2053
|
+
({"eligible": 3, "accounted": 0, "fully_read": 0}, {"eligible": 3, "accounted": 3, "fully_read": 0}))
|
|
2054
|
+
wait = copy.deepcopy(answers)
|
|
2055
|
+
refused("a backlog lost is not accepted: a session unanswered", lambda: reconcile(first, built_first, wait[:2], "periodic"), "SET_MISMATCH", ids[2])
|
|
2056
|
+
ahead = copy.deepcopy(answers)
|
|
2057
|
+
ahead[0]["readings"][0]["processed"][NEXT_ID] = [[6, 10]]
|
|
2058
|
+
ahead[0]["readings"][0]["read"] = [[0, 10]]
|
|
2059
|
+
refused("S3 may not credit the records of a later window in advance", lambda: reconcile(first, built_first, ahead, "periodic"),
|
|
2060
|
+
"PROCESSED_OUTSIDE_OWNED", f"for window {NEXT_ID}")
|
|
2061
|
+
for label, status, code in (("a session answered nothing_new while it still owes work", "nothing_new", "RESULT_INCONSISTENT"),
|
|
2062
|
+
("a session answered with a status that is not terminal", "eligible", "RESULT_STATUS_INVALID"),
|
|
2063
|
+
("a session answered with a status of the census's own", "known_absent", "RESULT_STATUS_INVALID")):
|
|
2064
|
+
bad = copy.deepcopy(fx_results(first))
|
|
2065
|
+
bad[0]["status"] = status
|
|
2066
|
+
if status == "nothing_new":
|
|
2067
|
+
bad[0]["readings"][0]["processed"] = {} # it processed nothing, so the window's records are still owed
|
|
2068
|
+
refused(label, lambda bad=bad: reconcile(first, built_first, bad, "periodic"), code)
|
|
2069
|
+
nxt, built_nxt = build(carry.run(window=NEXT), carried, table, table_sha, jobs=2)
|
|
2070
|
+
expect("the next run reads the backlog first, tagged with the window it belongs to, though the window owns nothing",
|
|
2071
|
+
([e["status"] for e in nxt["transcripts"]], by_id(nxt)[ids[0]]["work"]["backlog"], by_id(nxt)[ids[0]]["work"]["in_window"]),
|
|
2072
|
+
(["eligible"] * 3, [{"window": first["window"], "version": 0, "unread": [[6, 10]]}], []))
|
|
2073
|
+
deferral = fx_results(nxt, status="deferred")
|
|
2074
|
+
for answer in deferral:
|
|
2075
|
+
answer["readings"] = []
|
|
2076
|
+
_, kept_state, kept_flags = reconcile(nxt, built_nxt, deferral, "periodic")
|
|
2077
|
+
expect("a session that defers the earlier window's backlog again keeps it under that window, and the current window is accounted, not fully read",
|
|
2078
|
+
(kept_flags, sorted({b["window"] for b in kept_state["backlog"]}), sorted((b["transcript"], b["unread"]) for b in kept_state["backlog"])),
|
|
2079
|
+
({"accounted": True, "fully_read": False}, [first["window"]], sorted((b["transcript"], b["unread"]) for b in carried["backlog"])))
|
|
2080
|
+
cleared = reconcile(nxt, built_nxt, fx_results(nxt), "periodic")
|
|
2081
|
+
expect("reading the backlog clears it and credits the window it belongs to",
|
|
2082
|
+
(cleared[1]["backlog"], coverage.latest(cleared[1], keys[1])["processed"], cleared[2]), ([], {first["window"]: [[0, 10]]}, {"accounted": True, "fully_read": True}))
|
|
2083
|
+
|
|
2084
|
+
nowhere = root / "nowhere"
|
|
2085
|
+
nowhere.mkdir()
|
|
2086
|
+
gone, _ = build(carry.run(window=NEXT, claude_projects=nowhere), carried, table, table_sha, jobs=2)
|
|
2087
|
+
expect("a transcript the coverage state still owes that is gone is a lost transcript, filed and counted, not a vanished obligation",
|
|
2088
|
+
([(e["id"], e["status"], e["reason"], e["source"]) for e in gone["transcripts"]], gone["sources"]["coverage_state"]["totals"], account(gone)),
|
|
2089
|
+
([(i, "known_absent", "owed_by_coverage", "coverage_state") for i in ids], {"known_absent": 3}, []))
|
|
2090
|
+
|
|
2091
|
+
# done-when 3: a targeted run reads but never advances periodic coverage
|
|
2092
|
+
tgt, tstate = build(carry.run(kind="targeted"), carried, table, table_sha, jobs=2)
|
|
2093
|
+
expect("a targeted run starts from the base and returns it", records.json_text(tstate), records.json_text(carried))
|
|
2094
|
+
t_done, t_state, t_flags = reconcile(tgt, carried, fx_results(tgt), "targeted")
|
|
2095
|
+
expect("a targeted run's results reconcile its statuses and leave periodic coverage byte-identical",
|
|
2096
|
+
(records.json_text(t_state) == records.json_text(carried), {e["status"] for e in t_done["transcripts"]}), (True, {"read_complete"}))
|
|
2097
|
+
fresh_t, fresh_base = build(carry.run(kind="targeted"), empty, table, table_sha, jobs=2)
|
|
2098
|
+
fresh_answers = fx_results(fresh_t)
|
|
2099
|
+
_, fresh_after, _ = reconcile(fresh_t, fresh_base, fresh_answers, "targeted")
|
|
2100
|
+
expect("a targeted run over transcripts the base never saw reconciles against the state it observed, and leaves the base as it was",
|
|
2101
|
+
(records.json_text(fresh_after) == records.json_text(empty), len(fresh_answers)), (True, 3))
|
|
2102
|
+
false_new = copy.deepcopy(fresh_answers)
|
|
2103
|
+
false_new[0].update(status="nothing_new")
|
|
2104
|
+
false_new[0]["readings"][0]["processed"] = {}
|
|
2105
|
+
refused("a targeted run's unread work reported nothing_new is refused by name", lambda: reconcile(fresh_t, fresh_base, false_new, "targeted"),
|
|
2106
|
+
"RESULT_INCONSISTENT", "nothing_new")
|
|
2107
|
+
wrong_sha = copy.deepcopy(fresh_answers)
|
|
2108
|
+
wrong_sha[0]["readings"][0]["sha"] = "0" * 64
|
|
2109
|
+
refused("a targeted run's reading of bytes the census did not see is refused by name", lambda: reconcile(fresh_t, fresh_base, wrong_sha, "targeted"),
|
|
2110
|
+
"VERSION_MISMATCH")
|
|
2111
|
+
original = coverage.apply_results
|
|
2112
|
+
coverage.apply_results = lambda st, w, kind, res, owned, members=None: original(st, w, "periodic", res, owned, members) # a writer that ignores the run kind
|
|
2113
|
+
try:
|
|
2114
|
+
refused("a targeted run that advanced a processed range fails TARGETED_ADVANCED_COVERAGE",
|
|
2115
|
+
lambda: reconcile(tgt, carried, fx_results(tgt), "targeted"), "TARGETED_ADVANCED_COVERAGE")
|
|
2116
|
+
finally:
|
|
2117
|
+
coverage.apply_results = original
|
|
2118
|
+
|
|
2119
|
+
# Codex compaction is classified only once design §14 check 5 has measured it (WP-23 records that)
|
|
2120
|
+
lineage.CODEX_COMPACTION_MEASURED = True
|
|
2121
|
+
try:
|
|
2122
|
+
measured, _ = build(home.run(), empty, table, table_sha, jobs=4)
|
|
2123
|
+
finally:
|
|
2124
|
+
lineage.CODEX_COMPACTION_MEASURED = False
|
|
2125
|
+
later = by_id(measured)["019e0014-0000-7000-8000-000000000000"]
|
|
2126
|
+
expect("once the compaction is measured the same fixture is an ordinary counted root",
|
|
2127
|
+
(later["lineage"]["measurement_pending"], later["lineage"]["unique_root"], later["counted"]), (False, True, True))
|
|
2128
|
+
|
|
2129
|
+
# the originator table: the shipped defaults are design §5.1's, and an owner's bad edit is named
|
|
2130
|
+
expect("the shipped originator table is the design's default", table,
|
|
2131
|
+
{"Codex Desktop": "codex-desktop", "codex_work_desktop": "codex-desktop", "Claude Code": "excluded",
|
|
2132
|
+
"codex_vscode": "unknown_provenance", "codex-chrome-extension-sidepanel": "unknown_provenance"})
|
|
2133
|
+
(root / "table.json").write_text('{"codex": {"Codex Desktop": "everything"}}')
|
|
2134
|
+
refused("an originator mapped to a class that does not exist", lambda: load_originators(root / "table.json"), "ORIGINATOR_TABLE_INVALID", "everything")
|
|
2135
|
+
(root / "table.json").write_text("[1]")
|
|
2136
|
+
refused("an originator table that is not the expected object", lambda: load_originators(root / "table.json"), "ORIGINATOR_TABLE_INVALID")
|
|
2137
|
+
owner_map = by_id(build(home.run(), empty, {**table, "NewClient": "codex-desktop"}, table_sha, jobs=4)[0])["019e0006-0000-7000-8000-000000000000"]
|
|
2138
|
+
expect("the owner maps an originator at S0 and its sessions follow", (owner_map["status"], owner_map["source_class"]), ("eligible", "codex-desktop"))
|
|
2139
|
+
|
|
2140
|
+
# S1 as a stage: it reads the coverage the declaration pinned, writes into the run directory, and the tracked file stays
|
|
2141
|
+
from runlib import declare
|
|
2142
|
+
out, tracked = root / "out", root / "state"
|
|
2143
|
+
out.mkdir()
|
|
2144
|
+
tracked.mkdir()
|
|
2145
|
+
(tracked / "coverage.json").write_text(records.json_text(empty))
|
|
2146
|
+
_, base_sha = coverage.load(tracked / "coverage.json")
|
|
2147
|
+
fixture = declare.fixture()
|
|
2148
|
+
declaration = {**fixture, "window": WINDOW, "sources": home.run()["sources"], "starting_hashes": {**fixture["starting_hashes"], "coverage": base_sha}}
|
|
2149
|
+
declare.create(out / "r1", declaration)
|
|
2150
|
+
done = run(out / "r1", tracked / "coverage.json", jobs=2)
|
|
2151
|
+
record = records.read_json(records.record_path(out / "r1", "S1"))
|
|
2152
|
+
expect("the stage records census.json and the run's coverage.json, complete", (record["status"], [o["artifact"] for o in record["outputs"]]),
|
|
2153
|
+
("complete", ["census.json", "coverage.json"]))
|
|
2154
|
+
expect("the file is the census", json.loads((out / "r1" / "census.json").read_text()) == json.loads(json.dumps(done)), True)
|
|
2155
|
+
expect("the run's coverage is the base plus what was observed, and the tracked file is untouched",
|
|
2156
|
+
(len(coverage.load(out / "r1" / "coverage.json")[0]["transcripts"]) > 0, coverage.load(tracked / "coverage.json")[1] == base_sha), (True, True))
|
|
2157
|
+
refused("a census of a run that was never declared", lambda: run(out / "nobody", tracked / "coverage.json", jobs=2), "RUN_UNDECLARED")
|
|
2158
|
+
declare.create(out / "r2", {**declaration, "starting_hashes": {**fixture["starting_hashes"], "coverage": "0" * 64}})
|
|
2159
|
+
refused("a declaration that pinned another coverage state stops the stage", lambda: run(out / "r2", tracked / "coverage.json", jobs=2), "COVERAGE_BASE_STALE")
|
|
2160
|
+
expect("the refused stage left no record", records.record_path(out / "r2", "S1").exists(), False)
|
|
2161
|
+
# X review of WP-08 r2: an amendment landing just before S1's admission, after census.run read the declaration, is
|
|
2162
|
+
# refused by name; one landing just after it changes nothing the census was built from
|
|
2163
|
+
later = [("window.end", "2026-10-09T00:00:00")]
|
|
2164
|
+
for when in ("before", "after"):
|
|
2165
|
+
raced = out / f"race-{when}"
|
|
2166
|
+
declare.create(raced, declaration)
|
|
2167
|
+
with records.fx_amended_at_admission("S1", later, when):
|
|
2168
|
+
try:
|
|
2169
|
+
got = run(raced, tracked / "coverage.json", jobs=2)["window"]
|
|
2170
|
+
except Refused as exc:
|
|
2171
|
+
got = str(exc).split()[0]
|
|
2172
|
+
except Exception as exc: # noqa: BLE001 - reported by the control below, by name
|
|
2173
|
+
got = repr(exc)
|
|
2174
|
+
s1 = records.record_path(raced, "S1")
|
|
2175
|
+
seq = records.read_json(s1)["declaration_seq"] if s1.is_file() else None
|
|
2176
|
+
if when == "before":
|
|
2177
|
+
expect("X r2: an amendment between census.run's read and S1's admission is refused, and no census is written",
|
|
2178
|
+
(got, (raced / "census.json").exists()), ("DECLARATION_MOVED", False))
|
|
2179
|
+
else:
|
|
2180
|
+
expect("X r2: an amendment just after S1's admission changes nothing the census was built from",
|
|
2181
|
+
(got, seq, records.read_json(records.run_json_path(raced))["declaration_seq"]),
|
|
2182
|
+
(coverage.window_bounds(WINDOW)[2], 0, 1))
|
|
2183
|
+
declare.create(out / "r3", declaration)
|
|
2184
|
+
real_build = build
|
|
2185
|
+
globals()["build"] = lambda *a, **k: ({**real_build(*a, **k)[0], "kind": "bogus"}, empty)
|
|
2186
|
+
try:
|
|
2187
|
+
refused("a census that breaks its own schema is not written", lambda: run(out / "r3", tracked / "coverage.json", jobs=2), "CENSUS_INVALID")
|
|
2188
|
+
finally:
|
|
2189
|
+
globals()["build"] = real_build
|
|
2190
|
+
expect("nothing was written for it", (out / "r3" / "census.json").exists(), False)
|
|
2191
|
+
|
|
2192
|
+
# the snapshot directory: confined beneath the run, made fresh for each read, and the only thing ever removed
|
|
2193
|
+
expect("a finished run leaves no snapshot directory behind", sorted(p.name for p in (out / "r1" / "private").glob("*")), [])
|
|
2194
|
+
external = root / "external-source"
|
|
2195
|
+
external.mkdir()
|
|
2196
|
+
declare.create(out / "r7", declaration)
|
|
2197
|
+
os.symlink(external, out / "r7" / "private")
|
|
2198
|
+
with sources.open_threads(home.db, scratch=out / "r7" / "private"):
|
|
2199
|
+
expect("instrument control: an unconfined snapshot parent that is a link writes the clone outside the run", len(list(external.iterdir())), 1)
|
|
2200
|
+
refused("a snapshot parent that is a link out of the run is refused before any snapshot byte is written",
|
|
2201
|
+
lambda: run(out / "r7", tracked / "coverage.json", jobs=2), "RUN_PATH_ESCAPE")
|
|
2202
|
+
expect("nothing was written through the link and the refused stage left no record",
|
|
2203
|
+
(list(external.iterdir()), records.record_path(out / "r7", "S1").exists()), ([], False))
|
|
2204
|
+
declare.create(out / "r8", declaration)
|
|
2205
|
+
keep = out / "r8" / "keep"
|
|
2206
|
+
keep.mkdir()
|
|
2207
|
+
(keep / "artifact.txt").write_text("another stage's output")
|
|
2208
|
+
os.symlink(keep, out / "r8" / "scratch") # the name an earlier shape used for its scratch directory
|
|
2209
|
+
os.symlink(keep, out / "r8" / "private") # and the parent itself, a link to another directory of the run
|
|
2210
|
+
run(out / "r8", tracked / "coverage.json", jobs=2)
|
|
2211
|
+
expect("links planted where a scratch directory might be, to a directory of the run that holds an artifact: the artifact survives "
|
|
2212
|
+
"and only the run's own snapshot directory was removed",
|
|
2213
|
+
(sorted(p.name for p in keep.glob("*")), (out / "r8" / "census.json").is_file()), (["artifact.txt"], True))
|
|
2214
|
+
declare.create(out / "r9", declaration)
|
|
2215
|
+
(out / "r9" / "private").mkdir()
|
|
2216
|
+
(out / "r9" / "private" / "artifact.txt").write_text("already there")
|
|
2217
|
+
run(out / "r9", tracked / "coverage.json", jobs=2)
|
|
2218
|
+
expect("a private directory that already held an artifact is not taken over or emptied", sorted(p.name for p in (out / "r9" / "private").glob("*")), ["artifact.txt"])
|
|
2219
|
+
|
|
2220
|
+
# F#8: the originator table is bound to the declaration; classification cannot change under it without an amendment
|
|
2221
|
+
shutil.copyfile(ORIGINATORS_PATH, root / "bound.json")
|
|
2222
|
+
bound_sha = records.sha256_bytes((root / "bound.json").read_bytes())
|
|
2223
|
+
with_table = {**declaration, "sources": [x for x in declaration["sources"] if x["name"] != ORIGINATORS_SOURCE]
|
|
2224
|
+
+ [{"name": ORIGINATORS_SOURCE, "path": str(root / "bound.json"), "sha256": bound_sha}]}
|
|
2225
|
+
expect("a declared table whose bytes are the pinned ones is the run's table", bound_table(with_table), (table, bound_sha))
|
|
2226
|
+
expect("naming the declared path again is no override", bound_table(with_table, str(root / "bound.json"))[1], bound_sha)
|
|
2227
|
+
refused("a --originators that is not the declared table", lambda: bound_table(with_table, str(ORIGINATORS_PATH)), "ORIGINATOR_TABLE_UNDECLARED", "is not the declared table")
|
|
2228
|
+
refused("a declaration that names no table", lambda: bound_table({**declaration, "sources": [x for x in declaration["sources"] if x["name"] != ORIGINATORS_SOURCE]}),
|
|
2229
|
+
"ORIGINATOR_TABLE_UNDECLARED", "names no 'originators' source")
|
|
2230
|
+
refused("a declared table with no pin", lambda: bound_table({**declaration, "sources": [x for x in with_table["sources"] if x["name"] != ORIGINATORS_SOURCE]
|
|
2231
|
+
+ [{"name": ORIGINATORS_SOURCE, "path": str(root / "bound.json")}]}),
|
|
2232
|
+
"ORIGINATOR_TABLE_UNDECLARED", "carries no sha256")
|
|
2233
|
+
declare.create(out / "r4", with_table)
|
|
2234
|
+
(root / "bound.json").write_text('{"codex": {"Codex Desktop": "codex-cli"}}') # the owner edits the table after declaring
|
|
2235
|
+
refused("a table edited after the declaration pinned it stops the stage", lambda: run(out / "r4", tracked / "coverage.json", jobs=2),
|
|
2236
|
+
"ORIGINATOR_TABLE_CHANGED", "amend the declaration")
|
|
2237
|
+
expect("the refused stage left no record", records.record_path(out / "r4", "S1").exists(), False)
|
|
2238
|
+
declare.create(out / "r5", {**declaration, "sources": [x for x in declaration["sources"] if x["name"] != ORIGINATORS_SOURCE]})
|
|
2239
|
+
refused("a stage over a declaration without a table", lambda: run(out / "r5", tracked / "coverage.json", jobs=2), "ORIGINATOR_TABLE_UNDECLARED")
|
|
2240
|
+
declare.create(out / "r6", declaration)
|
|
2241
|
+
refused("a stage given another table than the declared one", lambda: run(out / "r6", tracked / "coverage.json", str(root / "bound.json"), jobs=2),
|
|
2242
|
+
"ORIGINATOR_TABLE_UNDECLARED")
|
|
2243
|
+
|
|
2244
|
+
# done-when 7: the status vocabulary is design §5.1's
|
|
2245
|
+
schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
|
|
2246
|
+
expect("the census schema's statuses are design §5.1's", contract_mismatch(schema, STATUSES_5_1), [])
|
|
2247
|
+
expect("the endings of an eligible session are the terminal statuses of the coverage state", STATUSES_5_1[6:], coverage.TERMINAL)
|
|
2248
|
+
uncited = {**schema, "$comment": "design §0.0"}
|
|
2249
|
+
expect("a census schema that cites another section is named", contract_mismatch(uncited, STATUSES_5_1),
|
|
2250
|
+
["CONTRACT_MISMATCH census (design §5.1): $comment does not cite the section"])
|
|
2251
|
+
for how, mutate in (("lacking one", lambda e: e.remove("nothing_new")), ("adding one", lambda e: e.append("quarantined"))):
|
|
2252
|
+
mutated = copy.deepcopy(schema)
|
|
2253
|
+
mutate(mutated["$defs"]["transcript"]["properties"]["status"]["enum"])
|
|
2254
|
+
expect(f"a schema {how} status is named", [e.split(":")[0] for e in contract_mismatch(mutated, STATUSES_5_1)], ["CONTRACT_MISMATCH census (design §5.1)"])
|
|
2255
|
+
|
|
2256
|
+
# D-20261106-208882: a row the census leaves unread lies against the window by the best evidence its files give -
|
|
2257
|
+
# the file-time bound first, its record timestamps where the bound cannot rule it out, undetermined otherwise
|
|
2258
|
+
lay = Home(root / "overlap")
|
|
2259
|
+
U = lambda n: f"c00000{n:02d}-0000-4000-8000-0000000000aa" # noqa: E731
|
|
2260
|
+
UX = lambda n: f"019e00{n:02d}-0000-7000-8000-0000000000aa" # noqa: E731
|
|
2261
|
+
sept = [f"2026-09-01T10:0{k}:00.000Z" for k in range(6)]
|
|
2262
|
+
unstamped = [{k: v for k, v in r.items() if k != "timestamp"} for r in fx_claude(U(4), entry=None)]
|
|
2263
|
+
lay.claude(U(1), fx_claude(U(1), entry=None), history=False) # unknown: records in the window, written in it
|
|
2264
|
+
lay.claude(U(2), fx_claude(U(2), entry=None, stamps=sept), mtime=fx_when(1, 9), history=False) # last written before it
|
|
2265
|
+
lay.claude(U(3), fx_claude(U(3), entry=None, stamps=sept), history=False) # records before it, written in it
|
|
2266
|
+
lay.claude(U(4), unstamped, history=False) # no timestamp at all, written in the window
|
|
2267
|
+
lay.claude(U(6), [{**r, "sessionId": U(6)} for r in unstamped], mtime=fx_when(1, 9), history=False) # the same, written before it
|
|
2268
|
+
lay.claude(U(5), fx_claude(U(5), entry=None, stamps=sept), mtime=fx_when(1, 9), history=False) # an unknown root out of the window
|
|
2269
|
+
lay.child(U(5), "agent-in", fx_claude(U(5))) # ... whose member has records in it
|
|
2270
|
+
lay.claude(U(7), fx_claude(U(7), entry="sdk-cli"), history=False) # an excluded root
|
|
2271
|
+
lay.child(U(7), "agent-ex", fx_claude(U(7))) # ... whose member is never looked at
|
|
2272
|
+
lay.claude(U(8), fx_claude(U(8))) # an eligible session, read in full
|
|
2273
|
+
lay.codex(UX(1), fx_codex(UX(1), "vscode", "NewClient"), indexed=False) # unknown Codex, in the window
|
|
2274
|
+
lay.codex(UX(2), fx_codex(UX(2), "vscode", "NewClient", month=9, day=1), mtime=fx_when(1, 9), indexed=False) # out by the bound
|
|
2275
|
+
for n, when in ((3, fx_when(5)), (4, fx_when(1, 9))): # unreadable rollouts, written in the window and before it
|
|
2276
|
+
bad = lay.codex(UX(n), [], raw=b"not zstd at all", zst=False, indexed=False)
|
|
2277
|
+
bad = bad.rename(bad.with_name(bad.name + ".zst"))
|
|
2278
|
+
os.utime(bad, (when, when))
|
|
2279
|
+
# unknown Codex threads in two files, the window in one of them: every file's evidence decides the row, whichever
|
|
2280
|
+
# comes first (W review of WP-08d r1, F1). UX5's first file was last written before the window and its second
|
|
2281
|
+
# holds records in it; UX6's first holds records in the window and its second only records after it
|
|
2282
|
+
lay.codex(UX(5), fx_codex(UX(5), "vscode", "NewClient", month=9, day=20), mtime=fx_when(20, 9), indexed=False,
|
|
2283
|
+
name_at="2026-09-20T10-00-00")
|
|
2284
|
+
lay.codex(UX(5), fx_codex(UX(5), "vscode", "NewClient"), indexed=False, name_at="2026-10-03T10-00-00")
|
|
2285
|
+
lay.codex(UX(6), fx_codex(UX(6), "vscode", "NewClient"), indexed=False, name_at="2026-10-03T10-00-00")
|
|
2286
|
+
lay.codex(UX(6), fx_codex(UX(6), "vscode", "NewClient", day=10), mtime=fx_when(10), indexed=False,
|
|
2287
|
+
name_at="2026-10-10T10-00-00", day=10)
|
|
2288
|
+
lay.finish()
|
|
2289
|
+
laid, _laid_state = build(lay.run(), empty, table, table_sha, jobs=2, scratch=scratch)
|
|
2290
|
+
laid_by = {key_of(e): (e["status"], e["window_overlap"]) for e in laid["transcripts"]}
|
|
2291
|
+
want_laid = {cid(U(1)): ("unknown_provenance", "inside"), cid(U(2)): ("unknown_provenance", "before_window"),
|
|
2292
|
+
cid(U(3)): ("unknown_provenance", "context_only"), cid(U(4)): ("unknown_provenance", "undetermined"),
|
|
2293
|
+
cid(U(6)): ("unknown_provenance", "before_window"), cid(U(5)): ("unknown_provenance", "before_window"),
|
|
2294
|
+
cid(f"{U(5)}/agent-in"): ("child_of", "inside"), cid(U(7)): ("excluded", None),
|
|
2295
|
+
cid(f"{U(7)}/agent-ex"): ("child_of", None), cid(U(8)): ("eligible", "inside"),
|
|
2296
|
+
xid(UX(1)): ("unknown_provenance", "inside"), xid(UX(2)): ("unknown_provenance", "before_window"),
|
|
2297
|
+
xid(UX(3)): ("unreadable", "undetermined"), xid(UX(4)): ("unreadable", "before_window")}
|
|
2298
|
+
expect("D-208882: an unread row lies against the window by its evidence - the file-time bound, its record timestamps "
|
|
2299
|
+
"where the bound cannot decide, undetermined where neither can - and a member of an unknown root is looked at "
|
|
2300
|
+
"while one of an excluded root is not", {k: laid_by.get(k) for k in want_laid}, want_laid)
|
|
2301
|
+
expect("D-208882: the census document with the new window_overlap values meets its schema and its sets add up",
|
|
2302
|
+
(validate.validate_instance(validator(), laid), account(laid)), ([], []))
|
|
2303
|
+
laid_rows = {key_of(e): e for e in laid["transcripts"]}
|
|
2304
|
+
split = {xid(UX(n)): (laid_by.get(xid(UX(n))), len(segments_of(laid_rows[xid(UX(n))])) if xid(UX(n)) in laid_rows else 0)
|
|
2305
|
+
for n in (5, 6)}
|
|
2306
|
+
expect("D-208882: an unread thread in two files lies by the evidence of both - an old first file and a second in the "
|
|
2307
|
+
"window straddle its start, a first in the window and a second after it straddle its end",
|
|
2308
|
+
split, {xid(UX(5)): (("unknown_provenance", "straddles_start"), 2), xid(UX(6)): (("unknown_provenance", "straddles_end"), 2)})
|
|
2309
|
+
# ... and the observation basis S3 settles over them (stage_read.observation_scope, imported here so that the
|
|
2310
|
+
# census's own evidence is what the scope is judged on): each, beside a unit read whole, keeps it incomplete, named
|
|
2311
|
+
from runlib import stage_read, views
|
|
2312
|
+
alone = []
|
|
2313
|
+
for n in (5, 6):
|
|
2314
|
+
doc = copy.deepcopy(laid)
|
|
2315
|
+
doc["transcripts"] = [e for e in doc["transcripts"] if key_of(e) in (cid(U(8)), xid(UX(n)))]
|
|
2316
|
+
scope, causes = stage_read.observation_scope(doc, [{"transcript": cid(U(8)), "status": "read_complete"}],
|
|
2317
|
+
{cid(U(8)): (True, True)})
|
|
2318
|
+
alone.append((views.coverage_basis(scope), [c["session"] for c in causes["sessions"]], causes["sources"]))
|
|
2319
|
+
expect("D-208882: the observation scope over an unread thread in two files, one of them in the window, is incomplete "
|
|
2320
|
+
"and names it, whichever file comes first", alone,
|
|
2321
|
+
[("incomplete", [xid(UX(5))], []), ("incomplete", [xid(UX(6))], [])])
|
|
2322
|
+
|
|
2323
|
+
|
|
2324
|
+
def self_test():
|
|
2325
|
+
if not os.access(ZSTD, os.X_OK):
|
|
2326
|
+
print(f"census --self-test [FAIL] ZSTD_UNAVAILABLE {ZSTD}: the compressed fixtures need the declared zstd")
|
|
2327
|
+
return 1
|
|
2328
|
+
checks = Checks()
|
|
2329
|
+
try:
|
|
2330
|
+
controls(checks)
|
|
2331
|
+
except Exception as exc: # a reverted check fails the control it served, by name, not as a traceback
|
|
2332
|
+
checks.failures.append(f"RAISED {exc!r} after control {checks.ran[-1] if checks.ran else '(none)'!r}")
|
|
2333
|
+
finally:
|
|
2334
|
+
for home in Home.open_writers:
|
|
2335
|
+
home.close()
|
|
2336
|
+
for failure in checks.failures:
|
|
2337
|
+
print(f"census --self-test [FAIL] {failure}")
|
|
2338
|
+
if checks.failures:
|
|
2339
|
+
return 1
|
|
2340
|
+
print(f"census --self-test: OK ({len(checks.ran)} controls)")
|
|
2341
|
+
return 0
|
|
2342
|
+
|
|
2343
|
+
|
|
2344
|
+
if __name__ == "__main__":
|
|
2345
|
+
if "--self-test" not in sys.argv[1:]:
|
|
2346
|
+
sys.exit("usage: census.py --self-test")
|
|
2347
|
+
sys.exit(self_test())
|