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,1220 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""S12 close, release 1: the run's decisions recorded in the checkout's ledger, its window and its
|
|
3
|
+
coverage, and nothing outside the checkout and the run directory.
|
|
4
|
+
|
|
5
|
+
Release 1's S11 writes files and the owner commits (D-20261113-f22b7d). The close follows the same
|
|
6
|
+
rule: it writes two tracked files of the declared checkout — the ledger and, for a periodic run,
|
|
7
|
+
the coverage state — and its own records in the run directory. Where those two files are inside the
|
|
8
|
+
checkout is the CALLER's to name (`ledger_ref`, `coverage_ref`; the driver's `--checkout-ledger` and
|
|
9
|
+
`--checkout-coverage`), because the layout of a checkout is not a shipped module's to assume; with
|
|
10
|
+
no reference the stage is refused by name. Both are written the way S11 writes a file (`stage_apply.Checkout`): reached from the
|
|
11
|
+
checkout's own descriptor, staged first, held to the state the run pinned, read back; nothing else
|
|
12
|
+
is left in the checkout, not a lock and not a temporary. It starts no process.
|
|
13
|
+
It ends by naming the commands the owner runs: the commit over everything S11 and this stage
|
|
14
|
+
changed, the install, and the launcher's state update. The version registry maps a window to the
|
|
15
|
+
commit that carries it, and no commit exists until the owner makes one, so the registry is the
|
|
16
|
+
owner's line after that commit and this stage names it rather than writes it.
|
|
17
|
+
|
|
18
|
+
What is recorded, per item of the confirmed final set, through `runlib/ledger.py` and nothing else —
|
|
19
|
+
its transitions (design §12.3) decide what an entry becomes, and a pair it rejects is refused here
|
|
20
|
+
by its own name with nothing written:
|
|
21
|
+
|
|
22
|
+
- an item S11 applied carries `applied` with the operation ids of S11's journal, the paths, and
|
|
23
|
+
delivery `unverified`: this release runs no installer, so nothing was delivered to verify;
|
|
24
|
+
- a ledger-only item (keep, incubate, drop) carries `applied` with no operation — it takes effect
|
|
25
|
+
here, at S12 (§10.4);
|
|
26
|
+
- a `none` records the decision and changes nothing: on an existing entry an element with no
|
|
27
|
+
`applied`, on a candidate with no entry nothing at all (the table's "no entry");
|
|
28
|
+
- a candidate formed in this window with no entry becomes a NEW entry, its id allocated here and
|
|
29
|
+
frozen in the run directory before the ledger is written; a legacy entry or a due decision is
|
|
30
|
+
decided on the entry it names; a due decision names the incubate it resolves.
|
|
31
|
+
|
|
32
|
+
The window is appended to `windows[]` with `commit: null` — the owner's commit is not this stage's
|
|
33
|
+
to know. A periodic run's coverage is S3's results folded against the state S1 pinned
|
|
34
|
+
(`census.reconcile`), promoted with `coverage.write_atomic`; a targeted run never advances coverage.
|
|
35
|
+
|
|
36
|
+
Each tracked file is written only if it still hashes to what the run pinned at S0
|
|
37
|
+
(`starting_hashes`), so a ledger or a coverage state another run advanced is refused, not merged.
|
|
38
|
+
The ledger is written first and the coverage after it; a re-run after a stop between the two finds
|
|
39
|
+
the ledger already holding this run's window and writes only what is missing.
|
|
40
|
+
|
|
41
|
+
Not done by release 1's close, each named in `close.json`: delivery verification, the expected-
|
|
42
|
+
observation resolutions of §11 (S3 derives them into the run directory; appending them to the ledger
|
|
43
|
+
waits for delivery evidence that can show exposure), the occasion index, the dated run record under
|
|
44
|
+
`design/`, the version registry, and the launcher's state file (an owner command).
|
|
45
|
+
|
|
46
|
+
stage_close.py --self-test
|
|
47
|
+
"""
|
|
48
|
+
import copy
|
|
49
|
+
import json
|
|
50
|
+
import pathlib
|
|
51
|
+
import re
|
|
52
|
+
import sys
|
|
53
|
+
|
|
54
|
+
HERE = pathlib.Path(__file__).resolve().parents[1]
|
|
55
|
+
sys.path.insert(0, str(HERE))
|
|
56
|
+
from runlib import (census, coverage, drift, ledger, placement, records, stage_apply, stage_approvals, # noqa: E402
|
|
57
|
+
stage_propose, stagelock, stage_confirm, targets)
|
|
58
|
+
from runlib.records import Refused # noqa: E402
|
|
59
|
+
|
|
60
|
+
STAGE = "S12"
|
|
61
|
+
OUTPUT = "close.json"
|
|
62
|
+
ALLOCATION = "close/allocation.json"
|
|
63
|
+
READ_RESULTS = "read-results.json"
|
|
64
|
+
LEDGER_ONLY_APPLIED = ("keep", "incubate", "drop")
|
|
65
|
+
NOT_DONE = {
|
|
66
|
+
"delivery_verification": "this release runs no installer, so every applied item is recorded delivery unverified",
|
|
67
|
+
"observation_resolutions": "S3 derived them in the run directory; appending them to the ledger waits for delivery "
|
|
68
|
+
"evidence that can show exposure",
|
|
69
|
+
"occasion_index": "not written by release 1",
|
|
70
|
+
"dated_run_record": "not written by release 1",
|
|
71
|
+
"version_registry": "it maps the window to the commit that carries it, and the owner makes that commit",
|
|
72
|
+
"launcher_state": "an owner command, named in owner_commands",
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# ---- what each decided item is, for the ledger ----------------------------------------------------
|
|
77
|
+
|
|
78
|
+
def decided_items(manifest, current, approvals, apply_doc):
|
|
79
|
+
"""The confirmed final set as the close reads it, F in its confirmed order and then the ledger-
|
|
80
|
+
only items: `{item_id, approval_id, disposition, row, proposal, operations, paths, adopted,
|
|
81
|
+
member_of}`. `operations` are S11's journalled effects, `{operation_id, type, target}`."""
|
|
82
|
+
rows = {r["item_id"]: r for r in current["rows"]}
|
|
83
|
+
last = {}
|
|
84
|
+
for row in approvals:
|
|
85
|
+
last[row["item_id"]] = row
|
|
86
|
+
by_item = {}
|
|
87
|
+
for effect in (apply_doc or {}).get("effects") or []:
|
|
88
|
+
by_item.setdefault(effect["item_id"], []).append(effect)
|
|
89
|
+
out = []
|
|
90
|
+
for item_id in manifest["sequencing"].get("order") or []:
|
|
91
|
+
row = rows[item_id]
|
|
92
|
+
proposal = row.get("proposal") or {}
|
|
93
|
+
effects = by_item.get(item_id) or []
|
|
94
|
+
paths = []
|
|
95
|
+
for effect in effects:
|
|
96
|
+
if effect["path"] not in paths:
|
|
97
|
+
paths.append(effect["path"])
|
|
98
|
+
out.append({"item_id": item_id, "approval_id": last[item_id]["approval_id"],
|
|
99
|
+
"disposition": proposal.get("disposition") or row.get("disposition"),
|
|
100
|
+
"row": row, "proposal": proposal, "paths": paths, "adopted": None, "member_of": None,
|
|
101
|
+
"operations": [{"operation_id": e["operation_id"], "type": e["type"], "target": e["path"]}
|
|
102
|
+
for e in effects]})
|
|
103
|
+
for held in manifest.get("ledger_only") or []:
|
|
104
|
+
row = rows[held.get("member_of") or held["item_id"]]
|
|
105
|
+
out.append({"item_id": held["item_id"], "approval_id": held["approval_id"],
|
|
106
|
+
"disposition": held["disposition"], "row": row,
|
|
107
|
+
"proposal": {} if held.get("member_of") or held.get("adopted") else (row.get("proposal") or {}),
|
|
108
|
+
"paths": [], "operations": [], "adopted": held.get("adopted"),
|
|
109
|
+
"alternative_reason": held.get("alternative_reason"), "member_of": held.get("member_of")})
|
|
110
|
+
return out
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def target_of(item, candidates):
|
|
114
|
+
"""`(kind, entry id | None, resolves | None)`, by S10b's rule (`stage_confirm.target_of`), whose page says where
|
|
115
|
+
an item without a file change is kept."""
|
|
116
|
+
return stage_confirm.target_of(item, candidates)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def observation_of(proposal):
|
|
120
|
+
held = (proposal or {}).get("expected_observation")
|
|
121
|
+
if not isinstance(held, dict):
|
|
122
|
+
return None
|
|
123
|
+
out = {"occasion_criteria": held.get("occasion"), "exposure_rule": held.get("exposure_rule"),
|
|
124
|
+
"expected_behavior": held.get("expected_behavior"), "retrieval_terms": list(held.get("retrieval_terms") or []),
|
|
125
|
+
"expiry": held.get("expiry"), "resolutions": []}
|
|
126
|
+
counter = held.get("counter")
|
|
127
|
+
if isinstance(counter, dict):
|
|
128
|
+
if counter.get("name"):
|
|
129
|
+
out["counter"] = counter["name"]
|
|
130
|
+
if counter.get("threshold") is not None:
|
|
131
|
+
out["threshold"] = counter["threshold"]
|
|
132
|
+
elif isinstance(counter, str) and counter:
|
|
133
|
+
out["counter"] = counter
|
|
134
|
+
return out
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def reason_of(item):
|
|
138
|
+
reasons = (item["proposal"] or {}).get("reasons") or {}
|
|
139
|
+
adopted = item.get("adopted")
|
|
140
|
+
return (reasons.get("reason")
|
|
141
|
+
or (adopted.get("reason") if isinstance(adopted, dict) else None)
|
|
142
|
+
or item.get("alternative_reason")
|
|
143
|
+
or (f"the owner's default for the legacy group {item['member_of']}" if item.get("member_of") else None))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def element_of(run_id, item, confirmation_id, adjudication_id, resolves):
|
|
147
|
+
"""The `decisions[]` element of one decided item (design §12.1's eight keys)."""
|
|
148
|
+
disposition = item["disposition"]
|
|
149
|
+
if item["operations"] or disposition in LEDGER_ONLY_APPLIED or (item["paths"] == [] and disposition != "none"):
|
|
150
|
+
applied = {"commit": None, "paths": list(item["paths"]), "operations": list(item["operations"]),
|
|
151
|
+
"delivery": "unverified" if item["operations"] else "not_applicable"}
|
|
152
|
+
else:
|
|
153
|
+
applied = None
|
|
154
|
+
element = {"run": run_id, "disposition": disposition, "approval_id": item["approval_id"],
|
|
155
|
+
"adjudication_id": adjudication_id, "confirmation": confirmation_id, "applied": applied,
|
|
156
|
+
"tests": None, "expected_observation": observation_of(item["proposal"])}
|
|
157
|
+
if disposition in ("keep", "drop"):
|
|
158
|
+
element["reason"] = reason_of(item)
|
|
159
|
+
if resolves:
|
|
160
|
+
element["resolves"] = resolves
|
|
161
|
+
return element
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _destination(item):
|
|
165
|
+
"""The destination the item's proposal carries (`stage_propose.carried_destination`: none for a `none`)."""
|
|
166
|
+
proposal = item["proposal"] or {}
|
|
167
|
+
if "disposition" not in proposal: # a group member or an adopted alternative: the item's own disposition
|
|
168
|
+
proposal = {**proposal, "disposition": item.get("disposition")}
|
|
169
|
+
return stage_propose.carried_destination(proposal) or {}
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def destination_of(item):
|
|
173
|
+
held = _destination(item)
|
|
174
|
+
carrier = held.get("carrier")
|
|
175
|
+
return {"implementation": carrier, "anchor": None, "package_id": None} if carrier else None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def keep_of(item):
|
|
179
|
+
units = [u for u in ((item["row"].get("units") or []) + (item["row"].get("guarded_keeps") or []))
|
|
180
|
+
if isinstance(u, str) and u]
|
|
181
|
+
carrier = _destination(item).get("carrier")
|
|
182
|
+
units = units or ([carrier] if carrier else [])
|
|
183
|
+
return {"units": units, "reason": reason_of(item)} if units else None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def retires(row, element):
|
|
187
|
+
"""Whether design §12.3's cell for this row and this decision leaves the entry RETIRED. A drop or a reduce
|
|
188
|
+
retires an incubating entry; on a placed one a drop drops the proposed intervention and the unit stays placed,
|
|
189
|
+
so retirement fields written there said a placed unit had been retired (the S12 review). A pair the table
|
|
190
|
+
does not allow answers False here and is refused, by name, where the decision is applied."""
|
|
191
|
+
try:
|
|
192
|
+
return ledger.transition(row, ledger.disposition_key(element))["status"] == "retired"
|
|
193
|
+
except ledger.LedgerError:
|
|
194
|
+
return False
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def updates_of(item, closed_on, element=None, status=None):
|
|
198
|
+
"""The entry fields an applied decision on an EXISTING entry changes (what `ledger.py` licenses
|
|
199
|
+
for its disposition; a field it does not license is its refusal, not this function's guess)."""
|
|
200
|
+
disposition = item["disposition"]
|
|
201
|
+
if disposition in ("place", "correct", "re-deliver"):
|
|
202
|
+
held = destination_of(item)
|
|
203
|
+
return {"destination": held} if held else {}
|
|
204
|
+
if disposition == "keep":
|
|
205
|
+
held = keep_of(item)
|
|
206
|
+
return {"keep": held} if held else {}
|
|
207
|
+
if element is not None and status is not None and retires(ledger.row_of(status), element):
|
|
208
|
+
return {"retired": closed_on, "retire_reason": reason_of(item) or "retired by this run's decision"}
|
|
209
|
+
return {}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def new_entry(entry_id, item, candidate, window_label, closed_on, element=None):
|
|
213
|
+
"""The entry a candidate with none becomes (design §12.1's fields; `create_entry` sets its status
|
|
214
|
+
and first decision). The claim is the candidate; its evidence is the events it was formed from."""
|
|
215
|
+
row, proposal = item["row"], item["proposal"] or {}
|
|
216
|
+
lifecycle = (candidate or {}).get("lifecycle") or {}
|
|
217
|
+
lesson = ((candidate or {}).get("lesson") or next(iter(lifecycle.get("lessons") or []), None)
|
|
218
|
+
or (proposal.get("reasons") or {}).get("what_happened") or item["item_id"])
|
|
219
|
+
consequence = proposal.get("consequence") or row.get("consequence")
|
|
220
|
+
entry = {"id": entry_id, "lesson": lesson, "status": "incubating", "classification": None,
|
|
221
|
+
"window": window_label, "kind": row.get("kind") or "unclassified",
|
|
222
|
+
"diagnosis": row.get("diagnosis") or "unknown", "disposition": "none",
|
|
223
|
+
"destination": destination_of(item),
|
|
224
|
+
"evidence": [{"claim_id": item["item_id"], "evidence_id": event}
|
|
225
|
+
for event in (candidate or {}).get("event_ids") or []],
|
|
226
|
+
"independent_lineages": row.get("lineages") if isinstance(row.get("lineages"), int) else "unavailable",
|
|
227
|
+
"consequence": {"kinds": [consequence] if consequence and consequence != "none" else []},
|
|
228
|
+
"coverage": {"basis": "view"}, "keep": keep_of(item) if item["disposition"] == "keep" else None,
|
|
229
|
+
"relations": {}, "decisions": []}
|
|
230
|
+
# Retirement is the TRANSITION's to say, not the disposition's: a drop on a new learning retires it (never
|
|
231
|
+
# placed), and a drop on an existing unit leaves a placed entry whose proposed intervention was dropped.
|
|
232
|
+
if element is not None and retires(ledger.entry_row(entry), element):
|
|
233
|
+
entry.update(destination=None, retired=closed_on,
|
|
234
|
+
retire_reason=reason_of(item) or "retired by this run's decision")
|
|
235
|
+
return entry
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def next_ids(held_ledger, count):
|
|
239
|
+
"""`count` new entry ids: the series after the highest `S<n>` the ledger holds, numbered from 01."""
|
|
240
|
+
series = [int(m.group(1)) for e in held_ledger["entries"] for m in [re.fullmatch(r"S(\d+)-\d+", e["id"])] if m]
|
|
241
|
+
name = f"S{max(series, default=0) + 1}"
|
|
242
|
+
return [f"{name}-{n:02d}" for n in range(1, count + 1)]
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def window_row(declaration, run_id, accounted=None, fully_read=None):
|
|
246
|
+
window = declaration["window"]
|
|
247
|
+
return {"start": str(window["start"])[:10], "end": str(window["end"])[:10], "run_id": run_id,
|
|
248
|
+
"kind": declaration["kind"], "commit": None, "accounted": accounted, "fully_read": fully_read}
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def closed_ledger(base, items, candidates, declaration, run_id, confirmation_id, adjudications, ids=None,
|
|
252
|
+
flags=(None, None)):
|
|
253
|
+
"""`(ledger, rows, allocated, problems)`: `base` with every decided item recorded and the window
|
|
254
|
+
appended. `rows` says what each item became; `problems` names every item the ledger refused, and
|
|
255
|
+
with any the result is not to be written."""
|
|
256
|
+
held = copy.deepcopy(base)
|
|
257
|
+
closed_on = str(declaration["window"]["end"])[:10]
|
|
258
|
+
label = closed_on # an entry's `window` is the day its window ended (the ledger's own form)
|
|
259
|
+
need = [i for i in items if target_of(i, candidates)[0] == "new" and i["disposition"] != "none"]
|
|
260
|
+
allocated = list(ids) if ids is not None else next_ids(base, len(need))
|
|
261
|
+
if len(allocated) != len(need):
|
|
262
|
+
return base, [], allocated, [f"ALLOCATION_CHANGED S12: {len(need)} items need a new entry and the frozen "
|
|
263
|
+
f"allocation holds {len(allocated)}"]
|
|
264
|
+
fresh, rows, problems = iter(allocated), [], []
|
|
265
|
+
for item in items:
|
|
266
|
+
kind, entry_id, resolves = target_of(item, candidates)
|
|
267
|
+
element = element_of(run_id, item, confirmation_id, adjudications.get(item["item_id"]), resolves)
|
|
268
|
+
try:
|
|
269
|
+
if kind == "entry":
|
|
270
|
+
if entry_id not in {e["id"] for e in held["entries"]}:
|
|
271
|
+
raise ledger.LedgerError(f"ENTRY_UNKNOWN {entry_id}")
|
|
272
|
+
was = next(e for e in held["entries"] if e["id"] == entry_id)
|
|
273
|
+
updates = (updates_of(item, closed_on, element, was["status"])
|
|
274
|
+
if element["applied"] is not None else None)
|
|
275
|
+
held = ledger.apply_decision(held, entry_id, element, updates or None)
|
|
276
|
+
rows.append({"item_id": item["item_id"], "entry": entry_id, "disposition": item["disposition"],
|
|
277
|
+
"recorded": "decision"})
|
|
278
|
+
elif item["disposition"] == "none":
|
|
279
|
+
rows.append({"item_id": item["item_id"], "entry": None, "disposition": "none",
|
|
280
|
+
"recorded": "nothing: a none on a candidate with no entry makes none"})
|
|
281
|
+
else:
|
|
282
|
+
entry_id = next(fresh)
|
|
283
|
+
held = ledger.create_entry(held, new_entry(entry_id, item, candidates.get(item["item_id"]), label,
|
|
284
|
+
closed_on, element), element)
|
|
285
|
+
rows.append({"item_id": item["item_id"], "entry": entry_id, "disposition": item["disposition"],
|
|
286
|
+
"recorded": "new entry"})
|
|
287
|
+
except (ledger.LedgerError, Refused) as exc:
|
|
288
|
+
problems.append(f"CLOSE_ITEM_REFUSED {item['item_id']}: {exc}")
|
|
289
|
+
held["windows"] = list(held.get("windows") or []) + [window_row(declaration, run_id, *flags)]
|
|
290
|
+
made = [r["entry"] for r in rows if r["recorded"] == "new entry"]
|
|
291
|
+
return held, rows, made, problems
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
# ---- the two tracked files, written the way S11 writes a file ------------------------------------------
|
|
295
|
+
# Both go through `stage_apply.Checkout`: reached from the checkout's own descriptor with no link followed, the new
|
|
296
|
+
# bytes staged and synced first, the file then held to the state this run pinned, and the after-state read back.
|
|
297
|
+
# `ledger.write_atomic` and `coverage.write_atomic` resolve a path and then open it by name, hold their check
|
|
298
|
+
# before they stage, and the second keeps its lock in a directory beside the file - inside the checkout (the S12
|
|
299
|
+
# review). Their validation is kept; their writing is not used here.
|
|
300
|
+
|
|
301
|
+
def write_ledger(tree, ledger_rel, base, closed, allocated, base_sha):
|
|
302
|
+
"""The closed ledger over the base this run pinned, or Refused with the file as it was."""
|
|
303
|
+
problems = ledger.validate_ledger(closed)
|
|
304
|
+
if problems:
|
|
305
|
+
raise Refused(f"LEDGER_WRITE_REFUSED {ledger_rel}: LEDGER_INVALID, nothing written: " + "; ".join(problems))
|
|
306
|
+
problems = ledger.validate_ledger(base) + ledger.check_pair(base, closed, allocated)
|
|
307
|
+
if problems:
|
|
308
|
+
raise Refused(f"LEDGER_WRITE_REFUSED {ledger_rel}: TRANSACTION_INVALID, nothing written: "
|
|
309
|
+
+ "; ".join(problems))
|
|
310
|
+
data = ledger.render(closed).encode("utf-8")
|
|
311
|
+
try:
|
|
312
|
+
tree.take({"path": ledger_rel, "data": data, "before": base_sha, "after": stage_apply.sha_of(data)})
|
|
313
|
+
except Refused as exc:
|
|
314
|
+
raise Refused(f"LEDGER_WRITE_REFUSED {ledger_rel}: {exc}") from exc
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def promote_coverage(tree, coverage_rel, state, pinned_sha):
|
|
318
|
+
"""The coverage state this run leaves, written over the one it pinned. True when this call or an earlier
|
|
319
|
+
close of this run wrote it; Refused, with the file as it was, when another run advanced it."""
|
|
320
|
+
errors = coverage.check_state(state)
|
|
321
|
+
if errors:
|
|
322
|
+
raise Refused("\n".join(errors))
|
|
323
|
+
data = records.json_text(state).encode("utf-8")
|
|
324
|
+
after, now = stage_apply.sha_of(data), tree.state(coverage_rel)
|
|
325
|
+
if now == after:
|
|
326
|
+
return True
|
|
327
|
+
# S0 pins an absent coverage file as the empty state's hash (`coverage.load`); on disk that is `absent`
|
|
328
|
+
empty = records.sha256_bytes(records.json_text(coverage.new_state()).encode("utf-8"))
|
|
329
|
+
before = stage_apply.ABSENT if now == stage_apply.ABSENT and pinned_sha == empty else pinned_sha
|
|
330
|
+
try:
|
|
331
|
+
tree.take({"path": coverage_rel, "data": data, "before": before, "after": after})
|
|
332
|
+
except Refused as exc:
|
|
333
|
+
raise Refused(f"COVERAGE_BASE_STALE {coverage_rel}: {exc}") from exc
|
|
334
|
+
return True
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
# ---- the stage ---------------------------------------------------------------------------------------
|
|
338
|
+
|
|
339
|
+
def inputs_of(run_dir, version):
|
|
340
|
+
run_dir = pathlib.Path(run_dir)
|
|
341
|
+
held = stage_apply.inputs_of(run_dir, version) + [
|
|
342
|
+
{"artifact": stage_apply.OUTPUT, "producer_stage": "S11"},
|
|
343
|
+
{"artifact": "checked-candidates.json", "producer_stage": "S5"}]
|
|
344
|
+
if (run_dir / READ_RESULTS).is_file():
|
|
345
|
+
held += [{"artifact": READ_RESULTS, "producer_stage": "S3"},
|
|
346
|
+
{"artifact": "census.json", "producer_stage": "S1"},
|
|
347
|
+
{"artifact": "coverage.json", "producer_stage": "S1"}]
|
|
348
|
+
return held
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def coverage_after(run_dir, declaration):
|
|
352
|
+
"""`(state | None, why)`: the coverage state this run leaves — S3's results folded against the
|
|
353
|
+
state S1 pinned — or None with the reason nothing is promoted."""
|
|
354
|
+
run_dir = pathlib.Path(run_dir)
|
|
355
|
+
if declaration.get("kind") != "periodic":
|
|
356
|
+
return None, f"a {declaration.get('kind')} run reads and never advances coverage"
|
|
357
|
+
if not (run_dir / READ_RESULTS).is_file():
|
|
358
|
+
raise Refused(f"READ_RESULTS_ABSENT S12: a periodic run's coverage is S3's {READ_RESULTS} folded against "
|
|
359
|
+
f"the state S1 pinned, and the run holds none")
|
|
360
|
+
results = records.read_json(run_dir / READ_RESULTS)["results"]
|
|
361
|
+
_census, state, _flags = census.reconcile(census.load(run_dir), coverage.load(run_dir / "coverage.json")[0],
|
|
362
|
+
results, "periodic")
|
|
363
|
+
return state, None
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def window_flags(run_dir, declaration):
|
|
367
|
+
"""`(accounted, fully_read)` of this run's window, as S3's results fold against the state S1 pinned - the two
|
|
368
|
+
answers `census.reconcile` gives S3 itself - or `(None, None)` for a run S3 did not read (the ledger's schema
|
|
369
|
+
takes null there: nobody measured it)."""
|
|
370
|
+
run_dir = pathlib.Path(run_dir)
|
|
371
|
+
if not (run_dir / READ_RESULTS).is_file():
|
|
372
|
+
return None, None
|
|
373
|
+
results = records.read_json(run_dir / READ_RESULTS)["results"]
|
|
374
|
+
_census, _state, flags = census.reconcile(census.load(run_dir), coverage.load(run_dir / "coverage.json")[0],
|
|
375
|
+
results, declaration["kind"])
|
|
376
|
+
return flags["accounted"], flags["fully_read"]
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def commands_of(checkout, paths):
|
|
380
|
+
root = "'" + str(checkout).replace("'", "'\\''") + "'"
|
|
381
|
+
quoted = " ".join("'" + p.replace("'", "'\\''") + "'" for p in paths)
|
|
382
|
+
return {"commit": f"git -C {root} add -- {quoted} && git -C {root} commit",
|
|
383
|
+
"install": f"bash {root}/install.sh install --non-interactive",
|
|
384
|
+
"launcher_state": f"python3 {root}/session-distill/update-state.py",
|
|
385
|
+
"version_registry": "after the commit: add this window and that commit's sha to "
|
|
386
|
+
"the checkout's version registry"}
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def closed_paths(applied, ledger_rel, coverage_rel, coverage_written):
|
|
390
|
+
"""`(paths, local_state)`: the changed files the owner's commit command names (S11's and the ledger), and apart
|
|
391
|
+
from them the coverage state when this run promoted it. The coverage state is keyed by the owner's session
|
|
392
|
+
identifiers: local state of this checkout, never a path of the commit command."""
|
|
393
|
+
return list(applied) + [ledger_rel], ([coverage_rel] if coverage_written else [])
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _file_sha(path):
|
|
397
|
+
return ledger.sha256_bytes(ledger.read_current(path))
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def destination_problems(paths, checkout=None):
|
|
401
|
+
"""S12's own state files kept out of the library (Codex release-1 review F1, both rounds): a ledger or a coverage
|
|
402
|
+
state named in a layer that carries instructions, or under an instruction tree - as spelled, and where it lands
|
|
403
|
+
from the declared checkout, which may itself lie inside a skill or inside a host's home as the environment
|
|
404
|
+
configures it - would be written as a library member (`inventory.instructions_place`)."""
|
|
405
|
+
from runlib import inventory
|
|
406
|
+
out = []
|
|
407
|
+
for rel in paths:
|
|
408
|
+
where = drift.library_place(rel) or (inventory.instructions_place(pathlib.Path(checkout) / rel)
|
|
409
|
+
if checkout else None)
|
|
410
|
+
if where:
|
|
411
|
+
out.append(f"CLOSE_DESTINATION_IN_LIBRARY {rel}: S12 writes the ledger and the coverage state outside the "
|
|
412
|
+
f"instructions, and this path is {where}")
|
|
413
|
+
return out
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def run(run_dir, ledger_ref=None, coverage_ref=None):
|
|
417
|
+
"""S12 over a run S11 applied: `close.json`, or Refused with no tracked file written by this call. `ledger_ref`
|
|
418
|
+
and `coverage_ref` are the two tracked files' paths inside the declared checkout, named by the caller."""
|
|
419
|
+
from runlib import lifecycle_intake
|
|
420
|
+
ledger_rel = ledger_ref or lifecycle_intake.CHECKOUT_LEDGER
|
|
421
|
+
if not ledger_rel:
|
|
422
|
+
raise Refused("LEDGER_UNNAMED S12: no ledger reference was named for the declaration's checkout; the caller "
|
|
423
|
+
"names it (--checkout-ledger), because no path inside a checkout is this module's to assume")
|
|
424
|
+
coverage_rel = coverage_ref
|
|
425
|
+
if coverage_rel and pathlib.PurePosixPath(coverage_rel).name != "coverage.json":
|
|
426
|
+
raise Refused(f"COVERAGE_REF_INVALID S12: {coverage_rel!r} does not name a coverage.json")
|
|
427
|
+
run_dir = pathlib.Path(run_dir)
|
|
428
|
+
run_id = run_dir.resolve().name
|
|
429
|
+
if not (run_dir / stage_confirm.CONFIRMATION).is_file():
|
|
430
|
+
raise Refused("CONFIRMATION_ABSENT S12: the final set is not confirmed, so there is nothing to close")
|
|
431
|
+
confirmation = records.read_json(run_dir / stage_confirm.CONFIRMATION)
|
|
432
|
+
version = confirmation["confirm_version"]
|
|
433
|
+
if not (run_dir / stage_apply.OUTPUT).is_file():
|
|
434
|
+
raise Refused("APPLY_ABSENT S12: S11 has not applied the confirmed set; the close records what was applied")
|
|
435
|
+
with records.run_stage(run_dir, STAGE, inputs_of(run_dir, version)) as stage:
|
|
436
|
+
declaration = stage.declaration
|
|
437
|
+
checkout = ((declaration or {}).get("destinations") or {}).get("checkout")
|
|
438
|
+
if not checkout or not pathlib.Path(checkout).is_dir():
|
|
439
|
+
raise Refused("CHECKOUT_UNDECLARED S12: the ledger is the declared checkout's")
|
|
440
|
+
checkout = pathlib.Path(checkout)
|
|
441
|
+
apply_doc = records.read_json(run_dir / stage_apply.OUTPUT)
|
|
442
|
+
if apply_doc.get("confirmation_id") != confirmation["confirmation_id"]:
|
|
443
|
+
raise Refused("APPLY_UNBOUND S12: apply.json is another confirmation's")
|
|
444
|
+
if any(e.get("state") not in ("applied", "done_before") for e in apply_doc.get("effects") or []):
|
|
445
|
+
raise Refused("APPLY_INCOMPLETE S12: apply.json holds an effect that was not written")
|
|
446
|
+
stored = records.read_json(run_dir / stage_confirm.manifest_rel(version))
|
|
447
|
+
# Release 1 changes no library file (Codex release-1 review F3): a run whose confirmed set held a change, or
|
|
448
|
+
# whose S11 record holds an effect, was applied by an earlier version, and its close would record those
|
|
449
|
+
# transitions (a keep release among them) on the ledger. Refused before the allocation and every write.
|
|
450
|
+
if placement.release_scope() == "release_1" and (stored.get("F") or apply_doc.get("effects")):
|
|
451
|
+
raise Refused(f"RELEASE_1_NO_LIBRARY_CHANGE S12: this run's confirmed set holds {len(stored.get('F') or [])} "
|
|
452
|
+
f"change(s) to a library file and S11 recorded {len(apply_doc.get('effects') or [])} effect(s), "
|
|
453
|
+
f"applied by an earlier version; release 1 closes no such run. Restore the changed files in "
|
|
454
|
+
f"the checkout if they should not stay, and decide the items again in a new run")
|
|
455
|
+
gathered = stage_confirm.gathered(run_dir)
|
|
456
|
+
current, approvals = gathered[0], gathered[1]
|
|
457
|
+
found = list(targets.set_problems([ledger_rel] + ([coverage_rel] if coverage_rel else []), str(checkout)))
|
|
458
|
+
found += destination_problems([ledger_rel] + ([coverage_rel] if coverage_rel else []), checkout)
|
|
459
|
+
if found:
|
|
460
|
+
raise Refused("\n".join(found))
|
|
461
|
+
candidates = {c["candidate_id"]: c for c in
|
|
462
|
+
records.read_json(run_dir / "checked-candidates.json")["candidates"]}
|
|
463
|
+
adjudications = {}
|
|
464
|
+
for row in stage_approvals.rows_in(run_dir / stage_approvals.ADJUDICATIONS) \
|
|
465
|
+
if (run_dir / stage_approvals.ADJUDICATIONS).is_file() else []:
|
|
466
|
+
if row.get("candidate_id") and row.get("adjudication_id"):
|
|
467
|
+
adjudications[row["candidate_id"]] = row["adjudication_id"]
|
|
468
|
+
items = decided_items(stored, current, approvals, apply_doc)
|
|
469
|
+
pinned = declaration["starting_hashes"]
|
|
470
|
+
with stage_apply.Checkout(checkout) as tree:
|
|
471
|
+
base_bytes = tree.read(ledger_rel)
|
|
472
|
+
if not base_bytes:
|
|
473
|
+
raise Refused(f"LEDGER_ABSENT {ledger_rel}: the declared checkout holds no ledger to close on")
|
|
474
|
+
on_disk = stage_apply.sha_of(base_bytes)
|
|
475
|
+
try:
|
|
476
|
+
base = json.loads(base_bytes.decode("utf-8"))
|
|
477
|
+
except (UnicodeDecodeError, ValueError) as exc:
|
|
478
|
+
raise Refused(f"LEDGER_UNREADABLE {ledger_rel}: the file the close would replace is not a ledger "
|
|
479
|
+
f"({type(exc).__name__})") from exc
|
|
480
|
+
# read AS A LEDGER before anything is read out of it - its windows among them: a file holding only this
|
|
481
|
+
# run's window marker was taken for a finished close, and a list or a null died on `.get` (round 2)
|
|
482
|
+
unsound = (ledger.validate_ledger(base) if isinstance(base, dict)
|
|
483
|
+
else [f"it holds {type(base).__name__}, not an object"])
|
|
484
|
+
if unsound:
|
|
485
|
+
raise Refused(f"LEDGER_UNREADABLE {ledger_rel}: the file the close would replace is not a ledger: "
|
|
486
|
+
+ "; ".join(unsound[:3]))
|
|
487
|
+
ledger_done = any(w.get("run_id") == run_id for w in base.get("windows") or [])
|
|
488
|
+
rows, made = [], []
|
|
489
|
+
if ledger_done:
|
|
490
|
+
# an earlier close of this run wrote the ledger and stopped before it ended: nothing is
|
|
491
|
+
# computed or written again, and the allocation it froze says which entries it made
|
|
492
|
+
frozen_doc = records.read_json(run_dir / ALLOCATION) if (run_dir / ALLOCATION).is_file() else {}
|
|
493
|
+
made, rows = frozen_doc.get("ids") or [], frozen_doc.get("items") or []
|
|
494
|
+
# the window marker alone is not the close: every entry this run's allocation froze is there, and
|
|
495
|
+
# every item it recorded on an entry has this run's decision on it
|
|
496
|
+
by_id = {e["id"]: e for e in base["entries"]}
|
|
497
|
+
lost = [r["entry"] for r in rows if r.get("entry") and not any(
|
|
498
|
+
d.get("run") == run_id for d in (by_id.get(r["entry"]) or {}).get("decisions") or [])]
|
|
499
|
+
lost += [i for i in made if i not in by_id]
|
|
500
|
+
if not frozen_doc or lost:
|
|
501
|
+
raise Refused(f"CLOSE_INCOMPLETE {ledger_rel}: it carries this run's window and not its decisions "
|
|
502
|
+
f"({sorted(set(lost)) or 'no allocation was frozen'}); the ledger was changed after "
|
|
503
|
+
f"the close wrote it")
|
|
504
|
+
else:
|
|
505
|
+
if on_disk != pinned["ledger"]:
|
|
506
|
+
raise Refused(f"LEDGER_BASE_STALE {ledger_rel}: it hashes {on_disk[:12]}, and the run pinned "
|
|
507
|
+
f"{str(pinned['ledger'])[:12]} at S0; another run advanced it, so this run is closed "
|
|
508
|
+
f"against a ledger it did not read")
|
|
509
|
+
frozen = records.read_json(run_dir / ALLOCATION)["ids"] if (run_dir / ALLOCATION).is_file() else None
|
|
510
|
+
closed, rows, made, problems = closed_ledger(base, items, candidates, declaration, run_id,
|
|
511
|
+
confirmation["confirmation_id"], adjudications, frozen,
|
|
512
|
+
window_flags(run_dir, declaration))
|
|
513
|
+
if problems:
|
|
514
|
+
raise Refused("\n".join(problems))
|
|
515
|
+
# frozen WITH what each item became: a re-run after the ledger is written computes nothing again,
|
|
516
|
+
# and without the rows its close.json said four items and listed none (the S12 review)
|
|
517
|
+
records.write_json(run_dir, run_dir / ALLOCATION, {"stage": STAGE, "ids": made, "items": rows})
|
|
518
|
+
stage.output(ALLOCATION)
|
|
519
|
+
state, why_not = coverage_after(run_dir, declaration)
|
|
520
|
+
if state is not None and not coverage_rel:
|
|
521
|
+
raise Refused("COVERAGE_UNNAMED S12: a periodic run promotes its coverage, and no reference was named for "
|
|
522
|
+
"the coverage state inside the declaration's checkout (--checkout-coverage)")
|
|
523
|
+
coverage_written = False
|
|
524
|
+
# The declaration this stage was admitted under, held for both writes: admission releases the declaration's
|
|
525
|
+
# lock, and an amendment that moved `destinations.checkout` after it had this stage write the old one.
|
|
526
|
+
admitted = (declaration["declaration_seq"], stage.record["run_json_sha256"])
|
|
527
|
+
with stagelock.hold(run_dir, "declaration", wait_s=stage_apply.DECLARATION_WAIT_S):
|
|
528
|
+
stage_apply._held_declaration(run_dir, admitted, STAGE)
|
|
529
|
+
with stage_apply.Checkout(checkout) as tree:
|
|
530
|
+
if not ledger_done:
|
|
531
|
+
write_ledger(tree, ledger_rel, base, closed, made, on_disk)
|
|
532
|
+
if state is not None:
|
|
533
|
+
coverage_written = promote_coverage(tree, coverage_rel, state, pinned["coverage"])
|
|
534
|
+
ledger_sha = tree.state(ledger_rel)
|
|
535
|
+
paths, local_state = closed_paths(apply_doc.get("paths") or [], ledger_rel, coverage_rel, coverage_written)
|
|
536
|
+
doc = {"stage": STAGE, "run_id": run_id, "confirmation_id": confirmation["confirmation_id"],
|
|
537
|
+
"checkout": str(checkout),
|
|
538
|
+
"ledger": {"path": ledger_rel, "sha256": ledger_sha, "allocated": made,
|
|
539
|
+
"window": window_row(declaration, run_id, *window_flags(run_dir, declaration)),
|
|
540
|
+
"written_by_this_call": not ledger_done},
|
|
541
|
+
"coverage": ({"path": coverage_rel, "promoted": True} if coverage_written
|
|
542
|
+
else {"path": coverage_rel, "promoted": False, "why": why_not}),
|
|
543
|
+
"items": rows, "counts": {"items": len(items), "new_entries": len(made),
|
|
544
|
+
"applied": sum(1 for i in items if i["operations"]),
|
|
545
|
+
"ledger_only": sum(1 for i in items if not i["operations"])},
|
|
546
|
+
"paths": paths, "local_state": local_state,
|
|
547
|
+
"owner_commands": commands_of(checkout, paths), "not_done": NOT_DONE,
|
|
548
|
+
# the planted controls as S9 evaluated and recorded them (D-20261115-18d56b), carried, not recomputed
|
|
549
|
+
"controls": records.read_json(
|
|
550
|
+
run_dir / f"review.v{stage_approvals.latest_version(run_dir)}.json").get("controls")}
|
|
551
|
+
with stagelock.hold(run_dir, "declaration", wait_s=stage_apply.DECLARATION_WAIT_S):
|
|
552
|
+
stage_apply._held_declaration(run_dir, admitted, STAGE) # once more before the stage says complete
|
|
553
|
+
records.write_json(run_dir, run_dir / OUTPUT, doc)
|
|
554
|
+
stage.output(OUTPUT)
|
|
555
|
+
return doc
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def controls_summary(evaluation):
|
|
559
|
+
"""The close report's line on the planted controls: the counts, each failed one by name, why any was not
|
|
560
|
+
applicable. A render made before S9 recorded the evaluation carries none, and says so."""
|
|
561
|
+
if not evaluation:
|
|
562
|
+
return "not evaluated: the review this close descends from records no evaluation"
|
|
563
|
+
counts = evaluation["counts"]
|
|
564
|
+
failed = [f"{r.get('candidate_id') or 'gate'} {r['kind']}" for r in evaluation["controls"] + evaluation["gate"]
|
|
565
|
+
if r["state"] == "failed"]
|
|
566
|
+
whys = sorted({r["why"] for r in evaluation["controls"] + evaluation["gate"] if r["state"] == "not_applicable"})
|
|
567
|
+
return (f"{counts['expected']} given their expected verdict, {counts['failed']} not"
|
|
568
|
+
+ (f" ({', '.join(failed)})" if failed else "") + f", {counts['not_applicable']} not applicable"
|
|
569
|
+
+ (f" ({'; '.join(whys)})" if whys else "")
|
|
570
|
+
+ (f"; {counts['kinds_not_planted']} kinds not planted" if counts["kinds_not_planted"] else ""))
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def report_lines(doc):
|
|
574
|
+
counts = doc["counts"]
|
|
575
|
+
# an approved `none` on a candidate with no entry makes no ledger row: said, never counted as recorded there
|
|
576
|
+
unrecorded = sum(1 for r in doc.get("items") or [] if r.get("entry") is None)
|
|
577
|
+
lines = [f"S12 close: {counts['items']} decided items closed, {counts['items'] - unrecorded} recorded in "
|
|
578
|
+
f"{doc['ledger']['path']} "
|
|
579
|
+
f"({counts['applied']} applied by S11, {counts['ledger_only']} ledger-only, {counts['new_entries']} new "
|
|
580
|
+
f"entries: {', '.join(doc['ledger']['allocated']) or 'none'})"
|
|
581
|
+
+ (f"; {unrecorded} approved `none` on a candidate with no entry make no ledger row and are kept in "
|
|
582
|
+
f"this run's {OUTPUT} alone" if unrecorded else "") + "; the window "
|
|
583
|
+
f"{doc['ledger']['window']['start']}..{doc['ledger']['window']['end']} is appended with no commit yet",
|
|
584
|
+
("coverage promoted to " + str(doc["coverage"]["path"]) + ": local state keyed by session identifiers, "
|
|
585
|
+
"left out of the commit command below; keep its path out of git") if doc["coverage"]["promoted"]
|
|
586
|
+
else f"coverage not promoted: {doc['coverage']['why']}",
|
|
587
|
+
"Planted controls (recorded, never a stop): " + controls_summary(doc.get("controls")),
|
|
588
|
+
"Not done by this release's close: " + "; ".join(sorted(doc["not_done"])),
|
|
589
|
+
"This stage ran no git and no installer. The commands are yours to run:"]
|
|
590
|
+
lines += [f" {doc['owner_commands'][k]}" for k in ("commit", "install", "launcher_state")]
|
|
591
|
+
lines.append(f" {doc['owner_commands']['version_registry']}")
|
|
592
|
+
return lines
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
# ---- self-test ---------------------------------------------------------------------------------------
|
|
596
|
+
|
|
597
|
+
def self_test():
|
|
598
|
+
"""The suite under the release scope `all`: the contract as designed, which release 1 holds closed
|
|
599
|
+
(`placement.scoped`), so the path the redesign reopens stays held by its controls. Release 1's own controls
|
|
600
|
+
run inside it under `release_1`."""
|
|
601
|
+
with placement.scoped("all"):
|
|
602
|
+
return _self_test_all()
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def _self_test_all():
|
|
606
|
+
failures, ran, reporting = [], [], []
|
|
607
|
+
try:
|
|
608
|
+
_self_test_body(failures, ran, reporting)
|
|
609
|
+
except Exception as exc: # noqa: BLE001 - a suite that dies says so by name
|
|
610
|
+
if reporting:
|
|
611
|
+
raise
|
|
612
|
+
failures.append(("the suite ran to its end", f"{type(exc).__name__}: {exc}"[:700]))
|
|
613
|
+
ran.append("the suite ran to its end")
|
|
614
|
+
if failures:
|
|
615
|
+
for name, detail in failures:
|
|
616
|
+
print(f"stage_close --self-test [FAIL] {name}: {detail}", file=sys.stderr)
|
|
617
|
+
print(f"stage_close --self-test: FAILED ({len(failures)} of {len(ran)} controls)", file=sys.stderr)
|
|
618
|
+
return 1
|
|
619
|
+
print(f"stage_close --self-test: OK ({len(ran)} controls: each decided item's element and what its entry becomes "
|
|
620
|
+
f"through the ledger's own transitions, the allocation, the window, a stale base and a refused pair with "
|
|
621
|
+
f"nothing written, and the stage from S10's real parse through S11)")
|
|
622
|
+
return 0
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def _self_test_body(failures, ran, reporting):
|
|
626
|
+
import os
|
|
627
|
+
import shutil
|
|
628
|
+
import tempfile
|
|
629
|
+
from grammar import owner_lines
|
|
630
|
+
from runlib import declare
|
|
631
|
+
|
|
632
|
+
def control(name, got, want):
|
|
633
|
+
if reporting:
|
|
634
|
+
raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}")
|
|
635
|
+
ran.append(name)
|
|
636
|
+
if got != want:
|
|
637
|
+
failures.append((name, f"expected {want!r}, got {got!r}"[:1100]))
|
|
638
|
+
|
|
639
|
+
def refusal(call):
|
|
640
|
+
try:
|
|
641
|
+
call()
|
|
642
|
+
except (Refused, ledger.LedgerError) as exc:
|
|
643
|
+
return str(exc)
|
|
644
|
+
except Exception as exc: # noqa: BLE001 - the exception IS the answer here
|
|
645
|
+
return f"RAISED {type(exc).__name__}: {exc}"
|
|
646
|
+
return ""
|
|
647
|
+
|
|
648
|
+
declaration = {"window": {"start": "2026-11-01T00:00:00", "end": "2026-11-08T00:00:00"}, "kind": "periodic"}
|
|
649
|
+
base = ledger.sample_ledger(
|
|
650
|
+
ledger.sample_entry("S4-01", "incubating", kind="gap",
|
|
651
|
+
decisions=[ledger.sample_element("run-0", "incubate",
|
|
652
|
+
observation=ledger.sample_observation("2026-11-05"))]),
|
|
653
|
+
ledger.sample_entry("S4-02", "incubating", kind="gap"),
|
|
654
|
+
ledger.sample_entry("G-1", "placed"))
|
|
655
|
+
|
|
656
|
+
def item(item_id, disposition, operations=(), proposal=None, row=None, **over):
|
|
657
|
+
held = {"item_id": item_id, "approval_id": f"P-{item_id}", "disposition": disposition,
|
|
658
|
+
"row": {"kind": "gap", "diagnosis": "gap", "lineages": 2, **(row or {})},
|
|
659
|
+
"proposal": {"disposition": disposition, "consequence": "quality",
|
|
660
|
+
"destination": {"layer": "guides", "carrier": "claude/guides/g.md"},
|
|
661
|
+
"reasons": {"reason": "이유", "what_happened": "무슨 일"}, **(proposal or {})},
|
|
662
|
+
"operations": [{"operation_id": f"A-{n}", "type": t, "target": p}
|
|
663
|
+
for n, (t, p) in enumerate(operations)],
|
|
664
|
+
"paths": [p for _t, p in operations], "adopted": None, "member_of": None}
|
|
665
|
+
held.update(over)
|
|
666
|
+
return held
|
|
667
|
+
|
|
668
|
+
candidates = {"k-new": {"candidate_id": "k-new", "source": "formed", "lesson": "Quote a glob.",
|
|
669
|
+
"event_ids": ["v-1", "v-2"], "lifecycle": None},
|
|
670
|
+
"legacy:S4-02": {"candidate_id": "legacy:S4-02", "source": "legacy",
|
|
671
|
+
"lifecycle": {"target_entry": "S4-02"}},
|
|
672
|
+
"due_decision:S4-01@run-0": {"candidate_id": "due_decision:S4-01@run-0", "source": "due_decision",
|
|
673
|
+
"lifecycle": {"target_entry": "S4-01", "resolves": "S4-01@run-0"}}}
|
|
674
|
+
|
|
675
|
+
def closed(*items, ids=None, held=base):
|
|
676
|
+
return closed_ledger(held, list(items), candidates, declaration, "run-1", "C-1", {}, ids)
|
|
677
|
+
|
|
678
|
+
def entry(held, entry_id):
|
|
679
|
+
return next((e for e in held["entries"] if e["id"] == entry_id), None)
|
|
680
|
+
|
|
681
|
+
kept = []
|
|
682
|
+
placed = item("k-new", "place", [("create", "claude/guides/g.md")])
|
|
683
|
+
out, rows, made, problems = closed(placed)
|
|
684
|
+
new = entry(out, "S5-01") or {}
|
|
685
|
+
control("a candidate formed in this window and placed becomes a new entry, its id the next series, with the "
|
|
686
|
+
"operations S11 journalled and delivery unverified",
|
|
687
|
+
[problems, made, rows, new.get("status"), new.get("lesson"), new.get("evidence"),
|
|
688
|
+
(new.get("decisions") or [{}])[0].get("applied", {}).get("operations"),
|
|
689
|
+
(new.get("decisions") or [{}])[0].get("applied", {}).get("delivery"),
|
|
690
|
+
(new.get("decisions") or [{}])[0].get("confirmation"), new.get("destination")],
|
|
691
|
+
[[], ["S5-01"], [{"item_id": "k-new", "entry": "S5-01", "disposition": "place", "recorded": "new entry"}],
|
|
692
|
+
"placed", "Quote a glob.", [{"claim_id": "k-new", "evidence_id": "v-1"},
|
|
693
|
+
{"claim_id": "k-new", "evidence_id": "v-2"}],
|
|
694
|
+
[{"operation_id": "A-0", "type": "create", "target": "claude/guides/g.md"}], "unverified", "C-1",
|
|
695
|
+
{"implementation": "claude/guides/g.md", "anchor": None, "package_id": None}])
|
|
696
|
+
control("the window is appended with no commit, and the result is a ledger the ledger's own check accepts as a "
|
|
697
|
+
"transaction over the base",
|
|
698
|
+
[out["windows"][-1], ledger.check_pair(base, out, made)],
|
|
699
|
+
[{"start": "2026-11-01", "end": "2026-11-08", "run_id": "run-1", "kind": "periodic", "commit": None,
|
|
700
|
+
"accounted": None, "fully_read": None}, []])
|
|
701
|
+
out, rows, made, problems = closed(item("legacy:S4-02", "none", proposal={"destination": None}))
|
|
702
|
+
control("a none on a legacy entry records the decision and changes nothing: no applied, the status as it was",
|
|
703
|
+
[problems, made, entry(out, "S4-02")["status"], entry(out, "S4-02")["decisions"][-1]["applied"],
|
|
704
|
+
entry(out, "S4-02")["decisions"][-1]["run"]], [[], [], "incubating", None, "run-1"])
|
|
705
|
+
out, rows, made, problems = closed(item("k-new", "none"))
|
|
706
|
+
control("a none on a candidate with no entry makes none, and says so",
|
|
707
|
+
[problems, made, len(out["entries"]) == len(base["entries"]), rows[0]["recorded"].split(":")[0]],
|
|
708
|
+
[[], [], True, "nothing"])
|
|
709
|
+
out, rows, made, problems = closed(item("legacy:S4-02", "drop", proposal={"destination": None}))
|
|
710
|
+
control("a ledger-only drop takes effect here: applied with no operation, the entry retired with the reason",
|
|
711
|
+
[problems, entry(out, "S4-02")["status"], entry(out, "S4-02")["decisions"][-1]["applied"]["operations"],
|
|
712
|
+
entry(out, "S4-02")["decisions"][-1]["applied"]["delivery"], entry(out, "S4-02").get("retire_reason")],
|
|
713
|
+
[[], "retired", [], "not_applicable", "이유"])
|
|
714
|
+
# Retirement is the transition's to say (§12.3), not the disposition's.
|
|
715
|
+
placed_candidates = {**candidates, "legacy:G-1": {"candidate_id": "legacy:G-1", "source": "legacy",
|
|
716
|
+
"lifecycle": {"target_entry": "G-1"}}}
|
|
717
|
+
out, rows, made, problems = closed_ledger(base, [item("legacy:G-1", "drop", proposal={"destination": None})],
|
|
718
|
+
placed_candidates, declaration, "run-1", "C-1", {}, None)
|
|
719
|
+
control("a drop on a PLACED entry drops the proposed intervention: the unit stays placed and gets no retirement",
|
|
720
|
+
[problems, entry(out, "G-1")["status"], "retired" in entry(out, "G-1"),
|
|
721
|
+
"retire_reason" in entry(out, "G-1"), entry(out, "G-1")["decisions"][-1]["disposition"],
|
|
722
|
+
ledger.check_pair(base, out, made)],
|
|
723
|
+
[[], "placed", False, False, "drop", []])
|
|
724
|
+
out, rows, made, problems = closed(item("k-new", "drop", row={"kind": "misfire", "diagnosis": "covered"}))
|
|
725
|
+
existing = entry(out, "S5-01") or {}
|
|
726
|
+
control("a drop on a candidate about an EXISTING unit makes a placed entry with its destination kept and no "
|
|
727
|
+
"retirement",
|
|
728
|
+
[problems, existing.get("status"), "retired" in existing, existing.get("destination")],
|
|
729
|
+
[[], "placed", False, {"implementation": "claude/guides/g.md", "anchor": None, "package_id": None}])
|
|
730
|
+
out, rows, made, problems = closed(item("k-new", "drop"))
|
|
731
|
+
learned = entry(out, "S5-01") or {}
|
|
732
|
+
control("a drop on a NEW learning retires it, never placed: retired with the reason and no destination",
|
|
733
|
+
[problems, learned.get("status"), learned.get("retired"), learned.get("retire_reason"),
|
|
734
|
+
learned.get("destination")], [[], "retired", "2026-11-08", "이유", None])
|
|
735
|
+
due = item("due_decision:S4-01@run-0", "place", [("create", "claude/guides/g.md")])
|
|
736
|
+
out, rows, made, problems = closed(due)
|
|
737
|
+
control("a due decision is decided on its entry and names the incubate it resolves",
|
|
738
|
+
[problems, entry(out, "S4-01")["status"], entry(out, "S4-01")["decisions"][-1].get("resolves")],
|
|
739
|
+
[[], "placed", "S4-01@run-0"])
|
|
740
|
+
renewed = item("due_decision:S4-01@run-0", "incubate", proposal={"expected_observation": {
|
|
741
|
+
"occasion": "the owner asks again", "exposure_rule": "delivered first", "expected_behavior": "no second ask",
|
|
742
|
+
"retrieval_terms": ["ask"], "expiry": "2027-01-31", "counter": None}})
|
|
743
|
+
out, rows, made, problems = closed(renewed)
|
|
744
|
+
control("an incubate carries its observation in the ledger's own field names",
|
|
745
|
+
[problems, entry(out, "S4-01")["decisions"][-1]["expected_observation"]],
|
|
746
|
+
[[], {"occasion_criteria": "the owner asks again", "exposure_rule": "delivered first",
|
|
747
|
+
"expected_behavior": "no second ask", "retrieval_terms": ["ask"], "expiry": "2027-01-31",
|
|
748
|
+
"resolutions": []}])
|
|
749
|
+
out, rows, made, problems = closed(item("legacy:S4-02", "incubate", proposal={"destination": None}))
|
|
750
|
+
control("a pair or an element the ledger refuses is named with its item, by the ledger's own code",
|
|
751
|
+
[[p.split(":")[0] for p in problems], "EFFECT_MISSING S4-02: expiry_renewed" in " ".join(problems)],
|
|
752
|
+
[["CLOSE_ITEM_REFUSED legacy"], True])
|
|
753
|
+
control("an item that names an entry the ledger does not hold is refused by name",
|
|
754
|
+
[p.split(":")[0] + ":" + p.split(":")[1] for p in closed(
|
|
755
|
+
item("legacy:S9-99", "none"))[3]], ["CLOSE_ITEM_REFUSED legacy:S9-99"])
|
|
756
|
+
control("a frozen allocation that no longer fits the items is refused before anything is recorded",
|
|
757
|
+
(refusal(lambda: kept.append(closed(placed, ids=[])[3])) or " ".join(kept[-1])).split()[:1],
|
|
758
|
+
["ALLOCATION_CHANGED"])
|
|
759
|
+
control("the series follows the highest S-series the ledger holds, whatever else it holds",
|
|
760
|
+
[next_ids(base, 2), next_ids(ledger.sample_ledger(ledger.sample_entry("G-1")), 1)],
|
|
761
|
+
[["S5-01", "S5-02"], ["S1-01"]])
|
|
762
|
+
|
|
763
|
+
# ---- the stage: S10's real parse, S10b, S11, then the close ---------------------------------------
|
|
764
|
+
K = b"# K\n\nold\n"
|
|
765
|
+
made_dirs = []
|
|
766
|
+
LEDGER_AT, COVERAGE_AT = "book/ledger.json", "state/coverage.json" # this fixture's own layout
|
|
767
|
+
|
|
768
|
+
def close_run(run_dir, **refs): # the stage, with this fixture's references
|
|
769
|
+
return run(run_dir, **{"ledger_ref": LEDGER_AT, **refs})
|
|
770
|
+
|
|
771
|
+
RECORDED_EVALUATION = {"controls": [{"candidate_id": "k-c1", "kind": "temporal_order_cause", "stage": "S6",
|
|
772
|
+
"state": "failed"},
|
|
773
|
+
{"candidate_id": "k-c2", "kind": "paraphrase_covered", "stage": "S6",
|
|
774
|
+
"state": "not_applicable", "why": "the point is incomplete"}],
|
|
775
|
+
"gate": [{"kind": "refusal", "state": "expected"}],
|
|
776
|
+
"counts": {"expected": 1, "failed": 1, "not_applicable": 1, "kinds_not_planted": 0}}
|
|
777
|
+
|
|
778
|
+
def applied(name, kind="targeted", legacy_target="L-2", alternative=None, decisions=None, checkout_at=None):
|
|
779
|
+
root = pathlib.Path(tempfile.mkdtemp(prefix=f"s12-{name}-"))
|
|
780
|
+
made_dirs.append(root)
|
|
781
|
+
checkout = root / (checkout_at or "checkout")
|
|
782
|
+
if checkout_at: # inside an enclosing checkout: it holds claude/ and codex/
|
|
783
|
+
(root / "repo" / "codex").mkdir(parents=True)
|
|
784
|
+
(checkout / "claude" / "guides").mkdir(parents=True)
|
|
785
|
+
(checkout / "claude" / "guides" / "k.md").write_bytes(K)
|
|
786
|
+
(checkout / LEDGER_AT).parent.mkdir(parents=True)
|
|
787
|
+
held_ledger = ledger.sample_ledger(ledger.sample_entry("L-1", "incubating"),
|
|
788
|
+
ledger.sample_entry("L-2", "incubating"))
|
|
789
|
+
(checkout / LEDGER_AT).write_text(ledger.render(held_ledger), encoding="utf-8")
|
|
790
|
+
held = declare.fixture()
|
|
791
|
+
held["destinations"]["checkout"] = str(checkout)
|
|
792
|
+
held["kind"] = kind
|
|
793
|
+
held["starting_hashes"]["ledger"] = _file_sha(checkout / LEDGER_AT)
|
|
794
|
+
|
|
795
|
+
def edit(rows_doc):
|
|
796
|
+
rows_doc["controls"] = copy.deepcopy(RECORDED_EVALUATION) # as S9 records it (D-20261115-18d56b)
|
|
797
|
+
if alternative:
|
|
798
|
+
next(r for r in rows_doc["rows"] if r["item_id"] == "k-place")["s7b"]["alternative"] = dict(alternative)
|
|
799
|
+
for row in rows_doc["rows"]:
|
|
800
|
+
for operation in (row.get("proposal") or {}).get("operations") or []:
|
|
801
|
+
if operation["target"] == "claude/guides/k.md":
|
|
802
|
+
operation["before_state_sha256"] = stage_apply.sha_of(K)
|
|
803
|
+
run_dir = stage_confirm.fx_run(root, held, edit, alternative)
|
|
804
|
+
records.write_json(run_dir, run_dir / "checked-candidates.json", {"candidates": [
|
|
805
|
+
{"candidate_id": "k-place", "source": "formed", "lesson": "Place it.", "event_ids": ["v-9"],
|
|
806
|
+
"lifecycle": None},
|
|
807
|
+
{"candidate_id": "k-reduce", "source": "formed", "lesson": "Reduce it.", "event_ids": [],
|
|
808
|
+
"lifecycle": None},
|
|
809
|
+
{"candidate_id": "legacy:L-1", "source": "legacy", "lifecycle": {"target_entry": "L-1"}},
|
|
810
|
+
{"candidate_id": "legacy:L-2", "source": "legacy", "lifecycle": {"target_entry": legacy_target}}]})
|
|
811
|
+
with records.run_stage(run_dir, "S5", []) as stage:
|
|
812
|
+
stage.output("checked-candidates.json")
|
|
813
|
+
copy_path = run_dir / "decisions.ko.v1.md"
|
|
814
|
+
lines = copy_path.read_text(encoding="utf-8").split("\n")
|
|
815
|
+
for ident, said in (decisions or {"k-place": ["결정: 승인"],
|
|
816
|
+
"k-reduce": ["결정: 승인", "keep 해제: R-1 사용자가 직접 줄인다"],
|
|
817
|
+
"group:legacy:incubating": ["결정: 승인"]}).items():
|
|
818
|
+
start = next(i for i, x in enumerate(lines) if x.startswith(f"<!-- owner-block review item={ident} "))
|
|
819
|
+
end = next(i for i in range(start + 1, len(lines)) if lines[i] == owner_lines.CLOSE)
|
|
820
|
+
lines = lines[:start + 1] + said + lines[end:]
|
|
821
|
+
copy_path.write_text("\n".join(lines), encoding="utf-8")
|
|
822
|
+
stage_approvals.run(run_dir, 1)
|
|
823
|
+
stage_confirm.build(run_dir)
|
|
824
|
+
page = run_dir / stage_confirm.copy_name(1)
|
|
825
|
+
page.write_text(page.read_text(encoding="utf-8").replace("확인:\n", "확인: 확정\n", 1), encoding="utf-8")
|
|
826
|
+
stage_confirm.confirm(run_dir)
|
|
827
|
+
return root, run_dir, checkout
|
|
828
|
+
|
|
829
|
+
def section(title, body):
|
|
830
|
+
"""One scenario: a break inside it fails under ITS name, and the scenarios after it still run."""
|
|
831
|
+
try:
|
|
832
|
+
body()
|
|
833
|
+
except Exception as exc: # noqa: BLE001 - reported by name, never swallowed
|
|
834
|
+
control(title, f"{type(exc).__name__}: {exc}"[:600], "ran to its end")
|
|
835
|
+
|
|
836
|
+
def code(call):
|
|
837
|
+
return (refusal(call).split() or [""])[0]
|
|
838
|
+
|
|
839
|
+
try:
|
|
840
|
+
def scenario_0():
|
|
841
|
+
root, run_dir, checkout = applied("unapplied")
|
|
842
|
+
control("a confirmed set S11 has not applied is not closed", refusal(lambda: close_run(run_dir)).split(":")[0],
|
|
843
|
+
"APPLY_ABSENT S12")
|
|
844
|
+
control("with no ledger reference the close is refused by name: no path inside a checkout is assumed",
|
|
845
|
+
code(lambda: run(run_dir)), "LEDGER_UNNAMED")
|
|
846
|
+
control("and a coverage reference names a coverage.json",
|
|
847
|
+
code(lambda: close_run(run_dir, coverage_ref="state/other.json")), "COVERAGE_REF_INVALID")
|
|
848
|
+
section('a confirmed set S11 has not applied (section)', scenario_0)
|
|
849
|
+
|
|
850
|
+
def scenario_release_1():
|
|
851
|
+
# Codex release-1 review F1: S12's own files are not written into the library, under either scope
|
|
852
|
+
clean_paths = destination_problems(["design/session-distill/ledger.json", "session-distill/local/coverage.json"])
|
|
853
|
+
control("S12's ledger and coverage destinations outside the library pass", clean_paths, [])
|
|
854
|
+
control("and one inside a skill, a guide, an instruction tree or a case-folded spelling of one is refused",
|
|
855
|
+
[p.split(":")[0] for p in destination_problems(
|
|
856
|
+
["claude/skills/understand/ledger.json", "claude/guides/coverage.json",
|
|
857
|
+
"ko/claude/notes/ledger.json", "Claude/Skills/u/coverage.json", "compose/ledger.json"])],
|
|
858
|
+
["CLOSE_DESTINATION_IN_LIBRARY claude/skills/understand/ledger.json",
|
|
859
|
+
"CLOSE_DESTINATION_IN_LIBRARY claude/guides/coverage.json",
|
|
860
|
+
"CLOSE_DESTINATION_IN_LIBRARY ko/claude/notes/ledger.json",
|
|
861
|
+
"CLOSE_DESTINATION_IN_LIBRARY Claude/Skills/u/coverage.json",
|
|
862
|
+
"CLOSE_DESTINATION_IN_LIBRARY compose/ledger.json"])
|
|
863
|
+
root, run_dir, checkout = applied("dest")
|
|
864
|
+
stage_apply.run(run_dir) # S11 under the design's scope, as an earlier version ran it
|
|
865
|
+
before = (checkout / LEDGER_AT).read_bytes()
|
|
866
|
+
control("the stage refuses a coverage state named inside a skill, before it writes",
|
|
867
|
+
code(lambda: close_run(run_dir, coverage_ref="claude/skills/understand/coverage.json")),
|
|
868
|
+
"CLOSE_DESTINATION_IN_LIBRARY")
|
|
869
|
+
control("and the ledger and the skill are as they were",
|
|
870
|
+
[(checkout / LEDGER_AT).read_bytes() == before,
|
|
871
|
+
(checkout / "claude" / "skills" / "understand" / "coverage.json").exists()], [True, False])
|
|
872
|
+
# round 2 F1: a declared checkout inside a skill makes the ordinary destinations instruction members
|
|
873
|
+
root, run_dir, checkout = applied("nested", checkout_at="repo/claude/skills/understand")
|
|
874
|
+
stage_apply.run(run_dir)
|
|
875
|
+
before = (checkout / LEDGER_AT).read_bytes()
|
|
876
|
+
control("a ledger destination is named where it lands, inside a skill, though its spelling is ordinary",
|
|
877
|
+
[p.split(":")[0] for p in destination_problems([LEDGER_AT], checkout)],
|
|
878
|
+
[f"CLOSE_DESTINATION_IN_LIBRARY {LEDGER_AT}"])
|
|
879
|
+
control("and the stage refuses a close whose declared checkout lies inside a skill, before it writes",
|
|
880
|
+
(code(lambda: close_run(run_dir)), (checkout / LEDGER_AT).read_bytes() == before),
|
|
881
|
+
("CLOSE_DESTINATION_IN_LIBRARY", True))
|
|
882
|
+
# round 3 F2: a host home its variable moves under an ordinary name holds the declared checkout
|
|
883
|
+
root, run_dir, checkout = applied("homed", checkout_at="config-A/proj")
|
|
884
|
+
stage_apply.run(run_dir)
|
|
885
|
+
before = (checkout / LEDGER_AT).read_bytes()
|
|
886
|
+
held_config = os.environ.get("CLAUDE_CONFIG_DIR")
|
|
887
|
+
try:
|
|
888
|
+
control("a declared checkout in an ordinary directory is closed past the destination check",
|
|
889
|
+
"CLOSE_DESTINATION_IN_LIBRARY" in "; ".join(destination_problems([LEDGER_AT], checkout)), False)
|
|
890
|
+
os.environ["CLAUDE_CONFIG_DIR"] = str(root / "config-A")
|
|
891
|
+
control("and once the environment names that directory a host's home, the stage refuses the close "
|
|
892
|
+
"where its ledger lands, before it writes",
|
|
893
|
+
(code(lambda: close_run(run_dir)), (checkout / LEDGER_AT).read_bytes() == before),
|
|
894
|
+
("CLOSE_DESTINATION_IN_LIBRARY", True))
|
|
895
|
+
finally:
|
|
896
|
+
if held_config is None:
|
|
897
|
+
os.environ.pop("CLAUDE_CONFIG_DIR", None)
|
|
898
|
+
else:
|
|
899
|
+
os.environ["CLAUDE_CONFIG_DIR"] = held_config
|
|
900
|
+
# Codex release-1 review F3: a run an earlier version applied is not closed in release 1
|
|
901
|
+
root, run_dir, checkout = applied("rel1")
|
|
902
|
+
stage_apply.run(run_dir) # S11 under the design's scope, as an earlier version ran it
|
|
903
|
+
before = (checkout / LEDGER_AT).read_bytes()
|
|
904
|
+
with placement.scoped("release_1"):
|
|
905
|
+
said_rel1 = refusal(lambda: close_run(run_dir))
|
|
906
|
+
control("in release 1 the close of a run whose confirmed set changed a library file is refused by name",
|
|
907
|
+
said_rel1.split(":")[0], "RELEASE_1_NO_LIBRARY_CHANGE S12")
|
|
908
|
+
control("and nothing is written: the ledger as it was, no close record",
|
|
909
|
+
[(checkout / LEDGER_AT).read_bytes() == before, (run_dir / OUTPUT).exists()], [True, False])
|
|
910
|
+
section('release 1 and the close (section)', scenario_release_1)
|
|
911
|
+
|
|
912
|
+
def scenario_release_1_run():
|
|
913
|
+
# the run release 1 can make, from S10's parse through S12 at the shipped scope: the owner adopts S7b's
|
|
914
|
+
# drop for k-place and approves the legacy group, so nothing changes a file (Codex release-1 review F2)
|
|
915
|
+
with placement.scoped("release_1"):
|
|
916
|
+
root, run_dir, checkout = applied(
|
|
917
|
+
"rel1-run", alternative={"disposition": "drop", "reason": "이번 근거로는 약하다"},
|
|
918
|
+
decisions={"k-place": ["결정: 수정 대안 s7b"], "group:legacy:incubating": ["결정: 승인"]})
|
|
919
|
+
library_before = (checkout / "claude" / "guides" / "k.md").read_bytes()
|
|
920
|
+
done = stage_apply.run(run_dir)
|
|
921
|
+
closed = close_run(run_dir)
|
|
922
|
+
control("in release 1 S11 writes nothing for a set that changes no file", (done["counts"]["effects"],
|
|
923
|
+
done["paths"], (checkout / "claude" / "guides" / "k.md").read_bytes() == library_before),
|
|
924
|
+
(0, [], True))
|
|
925
|
+
held_doc = json.loads((checkout / LEDGER_AT).read_text(encoding="utf-8"))
|
|
926
|
+
dropped = [d for e in held_doc.get("entries") or [] for d in e.get("decisions") or []
|
|
927
|
+
if d.get("run") == run_dir.name and d.get("disposition") == "drop"]
|
|
928
|
+
control("and S12 closes it, the adopted drop recorded with the reason the owner read",
|
|
929
|
+
(bool(closed), [d.get("reason") for d in dropped]), (True, ["이번 근거로는 약하다"]))
|
|
930
|
+
section('a release-1 run through S12 (section)', scenario_release_1_run)
|
|
931
|
+
|
|
932
|
+
def scenario_coverage_paths():
|
|
933
|
+
# The stage's own call site with a coverage state to promote, on its first pass and on the re-run after
|
|
934
|
+
# a stop between the ledger and the coverage write. What the state is and how it is written have their
|
|
935
|
+
# own controls below; here the two are stood in for, so the paths `run` hands the owner are what is read.
|
|
936
|
+
real = (globals()["coverage_after"], globals()["promote_coverage"])
|
|
937
|
+
stops = []
|
|
938
|
+
|
|
939
|
+
def promoting(tree, coverage_rel, state, pinned_sha):
|
|
940
|
+
if stops:
|
|
941
|
+
raise Refused(f"COVERAGE_BASE_STALE {coverage_rel}: {stops.pop()}")
|
|
942
|
+
return True
|
|
943
|
+
globals()["coverage_after"] = lambda run_dir, declaration: (coverage.new_state(), None)
|
|
944
|
+
globals()["promote_coverage"] = promoting
|
|
945
|
+
try:
|
|
946
|
+
_root, first_run, first_checkout = applied("coverage-first")
|
|
947
|
+
stage_apply.run(first_run)
|
|
948
|
+
first = close_run(first_run, coverage_ref=COVERAGE_AT)
|
|
949
|
+
_root, second_run, _checkout = applied("coverage-resumed")
|
|
950
|
+
stage_apply.run(second_run)
|
|
951
|
+
stops.append("a stop planted between the ledger and the coverage write")
|
|
952
|
+
stopped = code(lambda: close_run(second_run, coverage_ref=COVERAGE_AT))
|
|
953
|
+
resumed = close_run(second_run, coverage_ref=COVERAGE_AT)
|
|
954
|
+
finally:
|
|
955
|
+
globals()["coverage_after"], globals()["promote_coverage"] = real
|
|
956
|
+
for label, doc in (("its first pass", first), ("the re-run after a stop between its two writes", resumed)):
|
|
957
|
+
control(f"a close that promotes coverage names it local state and leaves it out of the commit on {label}",
|
|
958
|
+
[doc["coverage"]["promoted"], doc["local_state"], COVERAGE_AT in doc["paths"],
|
|
959
|
+
LEDGER_AT in doc["paths"], f"'{COVERAGE_AT}'" in doc["owner_commands"]["commit"],
|
|
960
|
+
f"'{LEDGER_AT}'" in doc["owner_commands"]["commit"]],
|
|
961
|
+
[True, [COVERAGE_AT], False, True, False, True])
|
|
962
|
+
control("and the planted stop was the coverage write's, after the ledger was written",
|
|
963
|
+
[stopped, resumed["ledger"]["written_by_this_call"]], ["COVERAGE_BASE_STALE", False])
|
|
964
|
+
section('a close that promotes coverage (section)', scenario_coverage_paths)
|
|
965
|
+
|
|
966
|
+
def scenario_1():
|
|
967
|
+
root, run_dir, checkout = applied("closed")
|
|
968
|
+
stage_apply.run(run_dir)
|
|
969
|
+
before = (checkout / LEDGER_AT).read_bytes()
|
|
970
|
+
doc = close_run(run_dir)
|
|
971
|
+
after = json.loads((checkout / LEDGER_AT).read_text(encoding="utf-8"))
|
|
972
|
+
by_id = {e["id"]: e for e in after["entries"]}
|
|
973
|
+
control("the close records the applied create and delete as new entries and the legacy group's two members "
|
|
974
|
+
"as decisions on their entries",
|
|
975
|
+
[doc["counts"], doc["ledger"]["allocated"], sorted(by_id),
|
|
976
|
+
[by_id[i]["status"] for i in ("S1-01", "S1-02", "L-1", "L-2")],
|
|
977
|
+
[len(by_id[i]["decisions"]) for i in ("L-1", "L-2")]],
|
|
978
|
+
[{"items": 4, "new_entries": 2, "applied": 2, "ledger_only": 2}, ["S1-01", "S1-02"],
|
|
979
|
+
["L-1", "L-2", "S1-01", "S1-02"], ["placed", "retired", "incubating", "incubating"], [1, 1]])
|
|
980
|
+
control("the new entries carry S11's journalled operations, and the window is appended",
|
|
981
|
+
[[o["type"] for i in ("S1-01", "S1-02") for o in by_id[i]["decisions"][0]["applied"]["operations"]],
|
|
982
|
+
after["windows"][-1]["run_id"], after["windows"][-1]["commit"]],
|
|
983
|
+
[["create", "delete"], run_dir.name, None])
|
|
984
|
+
control("a targeted run's coverage is not promoted, and the close says why and what it did not do",
|
|
985
|
+
[doc["coverage"]["promoted"], "targeted" in doc["coverage"]["why"], sorted(doc["not_done"]),
|
|
986
|
+
(checkout / COVERAGE_AT).exists()],
|
|
987
|
+
[False, True, ["dated_run_record", "delivery_verification", "launcher_state",
|
|
988
|
+
"observation_resolutions", "occasion_index", "version_registry"], False])
|
|
989
|
+
said = {**doc, "items": [{"item_id": "k-1", "entry": None, "disposition": "none"},
|
|
990
|
+
{"item_id": "legacy:L-1", "entry": "L-1", "disposition": "none"}],
|
|
991
|
+
"counts": {"items": 2, "new_entries": 0, "applied": 0, "ledger_only": 2}}
|
|
992
|
+
control("the report counts an approved none on a candidate with no entry as kept in the run alone, and "
|
|
993
|
+
"only the other as recorded in the ledger",
|
|
994
|
+
[report_lines(said)[0].split(" (")[0],
|
|
995
|
+
"1 approved `none` on a candidate with no entry make no ledger row" in report_lines(said)[0],
|
|
996
|
+
"make no ledger row" in report_lines(doc)[0]],
|
|
997
|
+
[f"S12 close: 2 decided items closed, 1 recorded in {doc['ledger']['path']}", True, False])
|
|
998
|
+
# D-20261115-18d56b: the close carries S9's recorded evaluation of the planted controls, and says so in
|
|
999
|
+
# one report line; a review that recorded none (this fixture's, and any render before S9 recorded it)
|
|
1000
|
+
# is said to be unevaluated, never counted clean
|
|
1001
|
+
control("the close carries the evaluation S9 recorded, says it in one report line, and a review that "
|
|
1002
|
+
"recorded none is said to be unevaluated",
|
|
1003
|
+
[doc["controls"], [x for x in report_lines(doc) if x.startswith("Planted controls")],
|
|
1004
|
+
[x for x in report_lines({**doc, "controls": None}) if x.startswith("Planted controls")]],
|
|
1005
|
+
[RECORDED_EVALUATION,
|
|
1006
|
+
["Planted controls (recorded, never a stop): 1 given their expected verdict, 1 not "
|
|
1007
|
+
"(k-c1 temporal_order_cause), 1 not applicable (the point is incomplete)"],
|
|
1008
|
+
["Planted controls (recorded, never a stop): not evaluated: the review this close descends "
|
|
1009
|
+
"from records no evaluation"]])
|
|
1010
|
+
control("the commit command leaves the coverage state out and keeps every other changed path, in order",
|
|
1011
|
+
[closed_paths(["a.md"], "book/ledger.json", "state/coverage.json", True),
|
|
1012
|
+
closed_paths(["a.md"], "book/ledger.json", "state/coverage.json", False),
|
|
1013
|
+
"coverage.json" in commands_of("/c", closed_paths([], "l.json", "s/coverage.json", True)[0])["commit"],
|
|
1014
|
+
doc["local_state"]],
|
|
1015
|
+
[(["a.md", "book/ledger.json"], ["state/coverage.json"]), (["a.md", "book/ledger.json"], []),
|
|
1016
|
+
False, []])
|
|
1017
|
+
control("the commit command names every file S11 and the close changed, the ledger among them",
|
|
1018
|
+
[sorted(doc["paths"]), all(f"'{p}'" in doc["owner_commands"]["commit"] for p in doc["paths"])],
|
|
1019
|
+
[sorted(["claude/guides/g.md", "claude/guides/k.md", LEDGER_AT]), True])
|
|
1020
|
+
rec = records.stage_records(run_dir).get(STAGE) or {}
|
|
1021
|
+
control("the stage's record holds the allocation and close.json",
|
|
1022
|
+
[rec.get("status"), sorted(o["artifact"] for o in rec.get("outputs") or [])],
|
|
1023
|
+
["complete", sorted([ALLOCATION, OUTPUT])])
|
|
1024
|
+
sha = _file_sha(checkout / LEDGER_AT)
|
|
1025
|
+
again = refusal(lambda: close_run(run_dir))
|
|
1026
|
+
control("a second close writes the ledger no second time", [again, _file_sha(checkout / LEDGER_AT) == sha,
|
|
1027
|
+
before != (checkout / LEDGER_AT).read_bytes()],
|
|
1028
|
+
["", True, True])
|
|
1029
|
+
second = records.read_json(run_dir / OUTPUT)
|
|
1030
|
+
control("and its close.json still says what each item became, and that this call wrote no ledger",
|
|
1031
|
+
[second["items"] == doc["items"], len(second["items"]), second["ledger"]["written_by_this_call"],
|
|
1032
|
+
second["ledger"]["sha256"] == sha], [True, 4, False, True])
|
|
1033
|
+
control("the close leaves nothing in the checkout but what S11 wrote and the ledger: no lock, no "
|
|
1034
|
+
"temporary",
|
|
1035
|
+
sorted(str(p.relative_to(checkout)) for p in checkout.rglob("*") if p.is_file()),
|
|
1036
|
+
sorted(["claude/guides/g.md", LEDGER_AT]))
|
|
1037
|
+
section('the close of an applied run (section)', scenario_1)
|
|
1038
|
+
|
|
1039
|
+
def scenario_2():
|
|
1040
|
+
root, run_dir, checkout = applied("stale")
|
|
1041
|
+
stage_apply.run(run_dir)
|
|
1042
|
+
moved = json.loads((checkout / LEDGER_AT).read_text(encoding="utf-8"))
|
|
1043
|
+
moved["entries"].append(ledger.sample_entry("L-3", "incubating"))
|
|
1044
|
+
(checkout / LEDGER_AT).write_text(ledger.render(moved), encoding="utf-8")
|
|
1045
|
+
held_bytes = (checkout / LEDGER_AT).read_bytes()
|
|
1046
|
+
control("a ledger another run advanced since S0 is refused, and left as it is",
|
|
1047
|
+
[code(lambda: close_run(run_dir)), (checkout / LEDGER_AT).read_bytes() == held_bytes],
|
|
1048
|
+
["LEDGER_BASE_STALE", True])
|
|
1049
|
+
section('a ledger that moved since S0 (section)', scenario_2)
|
|
1050
|
+
|
|
1051
|
+
def scenario_3():
|
|
1052
|
+
root, run_dir, checkout = applied("unknown", legacy_target="L-9")
|
|
1053
|
+
stage_apply.run(run_dir)
|
|
1054
|
+
held_bytes = (checkout / LEDGER_AT).read_bytes()
|
|
1055
|
+
control("an item the ledger cannot record stops the close with nothing written: the ledger is as it was",
|
|
1056
|
+
[code(lambda: close_run(run_dir)), (checkout / LEDGER_AT).read_bytes() == held_bytes,
|
|
1057
|
+
(run_dir / ALLOCATION).exists()], ["CLOSE_ITEM_REFUSED", True, False])
|
|
1058
|
+
section('an item the ledger cannot record (section)', scenario_3)
|
|
1059
|
+
|
|
1060
|
+
def scenario_4():
|
|
1061
|
+
root, run_dir, checkout = applied("periodic", kind="periodic")
|
|
1062
|
+
stage_apply.run(run_dir)
|
|
1063
|
+
held_bytes = (checkout / LEDGER_AT).read_bytes()
|
|
1064
|
+
control("a periodic run with no read results is refused before the ledger is written",
|
|
1065
|
+
[code(lambda: close_run(run_dir)), (checkout / LEDGER_AT).read_bytes() == held_bytes],
|
|
1066
|
+
["READ_RESULTS_ABSENT", True])
|
|
1067
|
+
section('a periodic run with no read results (section)', scenario_4)
|
|
1068
|
+
|
|
1069
|
+
def scenario_4b():
|
|
1070
|
+
root, run_dir, checkout = applied("amended")
|
|
1071
|
+
stage_apply.run(run_dir)
|
|
1072
|
+
held_bytes = (checkout / LEDGER_AT).read_bytes()
|
|
1073
|
+
real_gathered, done = stage_confirm.gathered, []
|
|
1074
|
+
|
|
1075
|
+
def amend_after_admission(directory):
|
|
1076
|
+
if not done:
|
|
1077
|
+
done.append(declare.amend(run_dir, [("budget.per_stage.S8", 10_000)],
|
|
1078
|
+
"an amendment after S12 was admitted", scope=["S8"]))
|
|
1079
|
+
return real_gathered(directory)
|
|
1080
|
+
stage_confirm.gathered = amend_after_admission
|
|
1081
|
+
try:
|
|
1082
|
+
answer = code(lambda: close_run(run_dir))
|
|
1083
|
+
finally:
|
|
1084
|
+
stage_confirm.gathered = real_gathered
|
|
1085
|
+
control("an amendment that landed after the close was admitted stops it before either file is written",
|
|
1086
|
+
[answer, (checkout / LEDGER_AT).read_bytes() == held_bytes, (run_dir / OUTPUT).exists()],
|
|
1087
|
+
["DECLARATION_MOVED", True, False])
|
|
1088
|
+
section('an amendment after the close was admitted (section)', scenario_4b)
|
|
1089
|
+
|
|
1090
|
+
def scenario_4c():
|
|
1091
|
+
root, run_dir, checkout = applied("marker")
|
|
1092
|
+
stage_apply.run(run_dir)
|
|
1093
|
+
start = (checkout / LEDGER_AT).read_bytes()
|
|
1094
|
+
answers = []
|
|
1095
|
+
for planted in (b"[]", b"null", json.dumps({"windows": [{"run_id": run_dir.name}]}).encode()):
|
|
1096
|
+
(checkout / LEDGER_AT).write_bytes(planted)
|
|
1097
|
+
answers.append(code(lambda: close_run(run_dir)))
|
|
1098
|
+
control("a file that is not a ledger - a list, a null, an object holding only this run's window - is "
|
|
1099
|
+
"refused by name before anything is read out of it",
|
|
1100
|
+
answers, ["LEDGER_UNREADABLE"] * 3)
|
|
1101
|
+
marked = json.loads(start)
|
|
1102
|
+
marked["windows"] = list(marked.get("windows") or []) + [window_row(
|
|
1103
|
+
records.declaration_state(run_dir, who="S12 self-test")[0], run_dir.name)]
|
|
1104
|
+
(checkout / LEDGER_AT).write_text(ledger.render(marked), encoding="utf-8")
|
|
1105
|
+
control("a ledger that carries this run's window and none of its decisions is not a finished close",
|
|
1106
|
+
[code(lambda: close_run(run_dir)), (run_dir / OUTPUT).exists()], ["CLOSE_INCOMPLETE", False])
|
|
1107
|
+
section('a file that is not a ledger, and a window with no decisions (section)', scenario_4c)
|
|
1108
|
+
|
|
1109
|
+
def scenario_5():
|
|
1110
|
+
# the coverage a periodic run leaves, over a run carried through S3 by S3's own fixture
|
|
1111
|
+
from runlib import stage_form
|
|
1112
|
+
s3_root = pathlib.Path(tempfile.mkdtemp(prefix="s12-s3-"))
|
|
1113
|
+
made_dirs.append(s3_root)
|
|
1114
|
+
s3_run = stage_form.fx_s3(s3_root)[0]
|
|
1115
|
+
s3_declaration = records.declaration_state(s3_run, who="S12 self-test")[0]
|
|
1116
|
+
state, why = coverage_after(s3_run, s3_declaration)
|
|
1117
|
+
control("a periodic run's coverage is S3's results folded against the state S1 pinned: a valid state that "
|
|
1118
|
+
"credits this window",
|
|
1119
|
+
[why, coverage.check_state(state), s3_declaration["kind"],
|
|
1120
|
+
state != coverage.load(s3_run / "coverage.json")[0]], [None, [], "periodic", True])
|
|
1121
|
+
control("the window row's two answers are S3's own: what its results fold to against the state S1 pinned, "
|
|
1122
|
+
"and null for a run S3 did not read",
|
|
1123
|
+
[window_flags(s3_run, s3_declaration) == tuple(
|
|
1124
|
+
census.reconcile(census.load(s3_run), coverage.load(s3_run / "coverage.json")[0],
|
|
1125
|
+
records.read_json(s3_run / READ_RESULTS)["results"], "periodic")[2][k]
|
|
1126
|
+
for k in ("accounted", "fully_read")),
|
|
1127
|
+
all(isinstance(v, bool) for v in window_flags(s3_run, s3_declaration)),
|
|
1128
|
+
window_flags(s3_root / "no-such-run", s3_declaration),
|
|
1129
|
+
closed_ledger(ledger.sample_ledger(ledger.sample_entry("L-1", "incubating")), [], {},
|
|
1130
|
+
{"window": {"start": "2026-11-01", "end": "2026-11-08"}, "kind": "periodic"},
|
|
1131
|
+
"run-f", "C-f", {}, None, (True, False))[0]["windows"][-1]["fully_read"]],
|
|
1132
|
+
[True, True, (None, None), False])
|
|
1133
|
+
control("and a targeted run promotes nothing, with the reason",
|
|
1134
|
+
[coverage_after(s3_run, {**s3_declaration, "kind": "targeted"})[0],
|
|
1135
|
+
"targeted" in coverage_after(s3_run, {**s3_declaration, "kind": "targeted"})[1]], [None, True])
|
|
1136
|
+
dest = s3_root / "checkout"
|
|
1137
|
+
dest.mkdir(parents=True)
|
|
1138
|
+
pinned_absent = coverage.load(dest / COVERAGE_AT)[1] # what S0 pins when the file is not there
|
|
1139
|
+
with stage_apply.Checkout(dest) as tree:
|
|
1140
|
+
first = promote_coverage(tree, COVERAGE_AT, state, pinned_absent)
|
|
1141
|
+
again = promote_coverage(tree, COVERAGE_AT, state, pinned_absent)
|
|
1142
|
+
stale = code(lambda: promote_coverage(tree, COVERAGE_AT, coverage.new_state(), "0" * 64))
|
|
1143
|
+
control("the coverage is promoted over the state the run pinned - an absent file is the empty state - "
|
|
1144
|
+
"and a second close finds it there",
|
|
1145
|
+
[first, again, coverage.load(dest / COVERAGE_AT)[1]
|
|
1146
|
+
== records.sha256_bytes(records.json_text(state).encode("utf-8"))], [True, True, True])
|
|
1147
|
+
control("the promotion leaves ONE file in the checkout: no lock directory beside it, no temporary",
|
|
1148
|
+
sorted(str(p.relative_to(dest)) for p in dest.rglob("*")), ["state", COVERAGE_AT])
|
|
1149
|
+
control("a coverage state another run advanced since S0 is refused and left as it is",
|
|
1150
|
+
[stale, coverage.load(dest / COVERAGE_AT)[1]
|
|
1151
|
+
== records.sha256_bytes(records.json_text(state).encode("utf-8"))],
|
|
1152
|
+
["COVERAGE_BASE_STALE", True])
|
|
1153
|
+
# the ledger's writer, on its own: a rival's change between the base check and the rename
|
|
1154
|
+
ledger_root = s3_root / "ledger-checkout"
|
|
1155
|
+
(ledger_root / "book").mkdir(parents=True)
|
|
1156
|
+
start = ledger.sample_ledger(ledger.sample_entry("L-1", "incubating"))
|
|
1157
|
+
(ledger_root / LEDGER_AT).write_text(ledger.render(start), encoding="utf-8")
|
|
1158
|
+
start_sha = _file_sha(ledger_root / LEDGER_AT)
|
|
1159
|
+
head = closed_ledger(start, [], {}, {"window": {"start": "2026-11-01", "end": "2026-11-08"},
|
|
1160
|
+
"kind": "targeted"}, "run-w", "C-w", {}, None)[0]
|
|
1161
|
+
rival = ledger.render(ledger.sample_ledger(ledger.sample_entry("L-1", "incubating"),
|
|
1162
|
+
ledger.sample_entry("L-2", "incubating")))
|
|
1163
|
+
real_state, calls = stage_apply.Checkout._state, []
|
|
1164
|
+
|
|
1165
|
+
def rival_writes_during_staging(self, parent, leaf, path):
|
|
1166
|
+
calls.append(leaf)
|
|
1167
|
+
if len(calls) == 2:
|
|
1168
|
+
(ledger_root / LEDGER_AT).write_text(rival, encoding="utf-8")
|
|
1169
|
+
return real_state(self, parent, leaf, path)
|
|
1170
|
+
stage_apply.Checkout._state = rival_writes_during_staging
|
|
1171
|
+
try:
|
|
1172
|
+
with stage_apply.Checkout(ledger_root) as tree:
|
|
1173
|
+
lost = code(lambda: write_ledger(tree, LEDGER_AT, start, head, [], start_sha))
|
|
1174
|
+
finally:
|
|
1175
|
+
stage_apply.Checkout._state = real_state
|
|
1176
|
+
control("a ledger a rival changed while this close staged its own is not overwritten: the rival's entry "
|
|
1177
|
+
"is still there",
|
|
1178
|
+
[lost, (ledger_root / LEDGER_AT).read_text(encoding="utf-8") == rival,
|
|
1179
|
+
sorted(p.name for p in (ledger_root / "book").iterdir())],
|
|
1180
|
+
["LEDGER_WRITE_REFUSED", True, ["ledger.json"]])
|
|
1181
|
+
(ledger_root / LEDGER_AT).write_text(ledger.render(start), encoding="utf-8")
|
|
1182
|
+
erased = {**head, "entries": []}
|
|
1183
|
+
with stage_apply.Checkout(ledger_root) as tree:
|
|
1184
|
+
said = refusal(lambda: write_ledger(tree, LEDGER_AT, start, erased, [], start_sha))
|
|
1185
|
+
control("a closed ledger that erases an entry of its base is not a transaction over it, and is not written",
|
|
1186
|
+
[said.split(":")[0], "TRANSACTION_INVALID" in said,
|
|
1187
|
+
(ledger_root / LEDGER_AT).read_text(encoding="utf-8") == ledger.render(start)],
|
|
1188
|
+
[f"LEDGER_WRITE_REFUSED {LEDGER_AT}", True, True])
|
|
1189
|
+
outside = s3_root / "outside"
|
|
1190
|
+
outside.mkdir()
|
|
1191
|
+
shutil.rmtree(ledger_root / "book")
|
|
1192
|
+
os.symlink(outside, ledger_root / "book")
|
|
1193
|
+
(outside / "ledger.json").write_text(ledger.render(start), encoding="utf-8")
|
|
1194
|
+
with stage_apply.Checkout(ledger_root) as tree:
|
|
1195
|
+
escaped = code(lambda: write_ledger(tree, LEDGER_AT, start, head, [], start_sha))
|
|
1196
|
+
control("a ledger whose directory became a link out of the checkout is not written through it",
|
|
1197
|
+
[bool(escaped), (outside / "ledger.json").read_text(encoding="utf-8") == ledger.render(start)],
|
|
1198
|
+
[True, True])
|
|
1199
|
+
section('the coverage a periodic run leaves (section)', scenario_5)
|
|
1200
|
+
|
|
1201
|
+
finally:
|
|
1202
|
+
for held_dir in made_dirs:
|
|
1203
|
+
shutil.rmtree(held_dir, ignore_errors=True)
|
|
1204
|
+
|
|
1205
|
+
body = pathlib.Path(__file__).read_text(encoding="utf-8").split("# ---- self-test ----")[0]
|
|
1206
|
+
control("the stage starts no process: its source names no subprocess, os.system, exec or spawn",
|
|
1207
|
+
[word for word in ("subprocess", "os.system", "os.exec", "os.spawn", "os.popen", "pty.")
|
|
1208
|
+
if word in body.split('"""', 2)[2]], [])
|
|
1209
|
+
reporting.append(True)
|
|
1210
|
+
|
|
1211
|
+
|
|
1212
|
+
def main(argv):
|
|
1213
|
+
if argv[1:] == ["--self-test"]:
|
|
1214
|
+
return self_test()
|
|
1215
|
+
print(__doc__)
|
|
1216
|
+
return 2
|
|
1217
|
+
|
|
1218
|
+
|
|
1219
|
+
if __name__ == "__main__":
|
|
1220
|
+
sys.exit(main(sys.argv))
|