agent-bios 0.19.4 → 0.20.1
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 +20 -5
- package/README.md +14 -19
- package/claude/agents/frontier.md +1 -1
- package/claude/guides/claude-prompting.md +475 -234
- package/claude/guides/cli-multi-model-workflow.md +8 -7
- package/claude/guides/gpt-prompting.md +319 -144
- package/claude/guides/session-distill-workflow.md +93 -43
- package/claude/guides/tooling-gotchas.md +3 -1
- package/codex/agents/frontier.toml +1 -1
- package/codex/agents/reviewer.toml +1 -1
- package/codex/agents/workhorse.toml +1 -1
- package/codex/guides/claude-prompting.md +475 -234
- package/codex/guides/cli-multi-model-workflow.md +8 -7
- package/codex/guides/gpt-prompting.md +319 -144
- 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_install.py +222 -27
- package/compose/instructions_session.py +250 -75
- package/compose/instructions_setup_cli.py +2 -36
- package/compose/instructions_store.py +160 -3
- package/compose/instructions_transaction.py +29 -5
- package/docs/advanced-launch.md +5 -1
- package/docs/releases/0.20.0.md +102 -0
- package/docs/releases/0.20.1.md +76 -0
- package/install.sh +42 -14
- package/launch/agent-launch.py +152 -18
- package/launch/agent-launch.toml +28 -16
- package/launch/agent-launch.zsh +104 -13
- package/launch/claude_subcommands.py +179 -0
- 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 +36 -3
- package/provenance.json +1 -1
- package/session-cost.py +80 -9
- 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 +7940 -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 +46 -15
- 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,1378 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""S11 apply: the confirmed final set written into files of the declared checkout - which release 1 does not do.
|
|
3
|
+
|
|
4
|
+
**Release 1 writes no library file (D-20261116-7853bc).** `items_of`, which both parts take their items through,
|
|
5
|
+
refuses a confirmed set that holds a change by name (`RELEASE_1_NO_LIBRARY_CHANGE`) before any plan or effect, so a
|
|
6
|
+
release-1 run's S11 records a set that changes no file and writes nothing into the checkout. S7, S7b and S10b refuse
|
|
7
|
+
the same change upstream (`placement.release_problems`). What follows is the write path as designed, which this
|
|
8
|
+
module's suite runs under the scope `all` (`placement.scoped`) so the redesign that reopens it starts from a path its
|
|
9
|
+
controls still hold.
|
|
10
|
+
|
|
11
|
+
The owner decided that form on 2026-11-13 (D-20261113-f22b7d): S11 writes the approved
|
|
12
|
+
changes into files of the declared checkout and NOTHING else. It starts no process — no git, no
|
|
13
|
+
installer, no hook — and writes no personal layer and no state root. Its other writes are inside the
|
|
14
|
+
run directory: the plan, the write-ahead journal and its own record. It ends by naming the two
|
|
15
|
+
commands the owner runs, the commit and the install, and runs neither.
|
|
16
|
+
|
|
17
|
+
What an operation does to a file's text is `runlib/operations.py`'s contract; this module decides
|
|
18
|
+
when it is allowed to happen and makes it happen on disk. The stage has two parts, each its own
|
|
19
|
+
admission (`records.run_stage`), so the plan the effects are taken from is a RECORDED output and not
|
|
20
|
+
a file the effects part trusts because it is there:
|
|
21
|
+
|
|
22
|
+
**plan** — refusing before anything is written:
|
|
23
|
+
1. the confirmation binds: the manifest S10b recorded is on disk unchanged and the final set built
|
|
24
|
+
again from the run's records is that manifest (`stage_confirm.binding_problems`);
|
|
25
|
+
2. every path any operation touches passes the target contract (`targets.set_problems`), no two
|
|
26
|
+
paths spell one directory or file differently, and an operation that ADDS to the always-loaded
|
|
27
|
+
file has S7b's faithful-merge judgment (`drift.global_op_problems`);
|
|
28
|
+
3. every operation is applied in the confirmed order to the files as they are NOW, in memory
|
|
29
|
+
(`operations.plan_of`). Each operation's `before_state_sha256` — the state S7 read when the
|
|
30
|
+
proposal was written — must be the file's state now, so a file that moved since is refused, not
|
|
31
|
+
patched. `apply/plan.json` is written once, as this part's output.
|
|
32
|
+
|
|
33
|
+
**effects** — `apply/plan.json` is an input the shared record check holds to the plan part's
|
|
34
|
+
recorded hash, so an edited plan is refused before it is read; its bytes are then read once and
|
|
35
|
+
must be the bytes admission pinned. Then, before any write: the binding again; every effect of the
|
|
36
|
+
plan held to the confirmed set (its item, its approval, its operation, a path that operation names,
|
|
37
|
+
its operation id recomputed, its bytes at their own hash, and each file's effects chained); the
|
|
38
|
+
journal read whole and refused if it does not parse, holds a record the plan does not, or holds a
|
|
39
|
+
history other than planned-then-done in the plan's order; and the plan held WHOLE - before any
|
|
40
|
+
effect, the confirmed operations planned again over the files must give this plan byte for byte,
|
|
41
|
+
and after one, the plan must be the very one the journal's effects were taken from. Then one file
|
|
42
|
+
at a time through `journal.journalled`, the journal's lock held from the plan record to the done
|
|
43
|
+
record:
|
|
44
|
+
|
|
45
|
+
- the declaration's lock is held around each effect and the declaration read again under it: it
|
|
46
|
+
must be the one this part was admitted under, and an amendment cannot land during a write. It
|
|
47
|
+
is held once more before the stage says it is complete;
|
|
48
|
+
- the file is reached by a confined walk from the checkout's own descriptor (`journal.Confined`):
|
|
49
|
+
no symlink in the chain, every component spelled as the directory holds it, the leaf a regular
|
|
50
|
+
file with one name, opened without blocking;
|
|
51
|
+
- the new bytes are written to a temporary beside the target and synced FIRST; only then is the
|
|
52
|
+
target's state read through its descriptor and held to the plan's before-state, the staged file
|
|
53
|
+
read back through the descriptor that wrote it (regular, one name, the planned bytes, still what
|
|
54
|
+
its name holds), and the rename made; then the name is checked to hold
|
|
55
|
+
that same file, the directories are synced, and the after-state is read back before the done
|
|
56
|
+
record.
|
|
57
|
+
|
|
58
|
+
What stays open, stated as it is: POSIX has no compare-and-rename, and no check is one instant.
|
|
59
|
+
The target's bytes, its name's identity, and the staged file's bytes, metadata and name are each
|
|
60
|
+
read by a separate call, and the rename is one more. A writer acting between two of those calls can
|
|
61
|
+
still have the target overwritten, or bytes installed that the plan did not hold; what the checks
|
|
62
|
+
bound is that such a writer must act inside that sequence of calls, after the target was read whole
|
|
63
|
+
and the staged file was read back standing still. An installed file that is not the plan's is
|
|
64
|
+
detected and reported (`APPLY_AFTER_MISMATCH`), never hidden. This stage is safe against accident
|
|
65
|
+
and against a second run of itself; it is not a defence against a concurrent adversary writing the
|
|
66
|
+
checkout, and nothing else should be writing the checkout while it runs.
|
|
67
|
+
|
|
68
|
+
What this stage trusts: the run directory against accident and against a second caller, not against
|
|
69
|
+
a writer who can rewrite the run's own records, approvals and confirmation together - that writer
|
|
70
|
+
is the owner. One S11 call runs at a time (`APPLY_LOCK`).
|
|
71
|
+
|
|
72
|
+
A re-run skips what the journal says is done. An operation the journal holds as planned with no
|
|
73
|
+
done record is not run again: the stage says whether the file is at its before-state, its
|
|
74
|
+
after-state or neither, and stops (`APPLY_UNRECONCILED`). The checkout is a git repository the owner
|
|
75
|
+
controls, so the way back is theirs: inspect, restore the file, and apply in a new run.
|
|
76
|
+
|
|
77
|
+
stage_apply.py --self-test
|
|
78
|
+
"""
|
|
79
|
+
import base64
|
|
80
|
+
import errno
|
|
81
|
+
import hashlib
|
|
82
|
+
import json
|
|
83
|
+
import os
|
|
84
|
+
import pathlib
|
|
85
|
+
import stat
|
|
86
|
+
import sys
|
|
87
|
+
import unicodedata
|
|
88
|
+
|
|
89
|
+
HERE = pathlib.Path(__file__).resolve().parents[1]
|
|
90
|
+
sys.path.insert(0, str(HERE))
|
|
91
|
+
from runlib import (drift, journal, operations, placement, records, stage_approvals, stage_confirm, # noqa: E402
|
|
92
|
+
stagelock, targets)
|
|
93
|
+
from runlib.operations import ABSENT, sha_of, split_target # noqa: E402
|
|
94
|
+
from runlib.records import Refused # noqa: E402
|
|
95
|
+
|
|
96
|
+
STAGE = "S11"
|
|
97
|
+
PLAN_PART, EFFECTS_PART = "plan", "effects"
|
|
98
|
+
OUTPUT = "apply.json"
|
|
99
|
+
PLAN = "apply/plan.json"
|
|
100
|
+
JOURNAL = "apply/journal.jsonl"
|
|
101
|
+
_NOFOLLOW = journal._NOFOLLOW # one answer for the walk and the leaf: the journal's own
|
|
102
|
+
plan_of = operations.plan_of
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def operation_id(confirmation_id, effect, ordinal):
|
|
106
|
+
held = json.dumps([confirmation_id, effect["item_id"], effect["operation"], effect["path"], ordinal,
|
|
107
|
+
effect["before"], effect["after"]])
|
|
108
|
+
return "A-" + hashlib.sha256(held.encode("utf-8")).hexdigest()[:24]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def spelling_problems(paths, folds):
|
|
112
|
+
"""Two planned paths that spell one directory or file in two CASES, by name, where that is one name.
|
|
113
|
+
|
|
114
|
+
Each path alone can pass the target contract while its directory does not exist yet; written one
|
|
115
|
+
after the other on a filesystem that folds case, the second lands in the first's directory under
|
|
116
|
+
a name the plan never held. Whether two cases are one name is the filesystem's to say
|
|
117
|
+
(`targets.folds_case`): True refuses, False allows - they are two directories - and None, a
|
|
118
|
+
filesystem that did not say, refuses rather than guesses, as `targets.collision_problems` does.
|
|
119
|
+
Canonically equivalent spellings are one name already (`targets.identity` is NFC), so only a case
|
|
120
|
+
difference is asked about."""
|
|
121
|
+
if folds is False:
|
|
122
|
+
return []
|
|
123
|
+
seen, pairs = {}, []
|
|
124
|
+
for path in paths:
|
|
125
|
+
pieces = [p for p in unicodedata.normalize("NFC", str(path)).split("/") if p]
|
|
126
|
+
for depth in range(1, len(pieces) + 1):
|
|
127
|
+
spelled = "/".join(pieces[:depth])
|
|
128
|
+
other = seen.setdefault(spelled.casefold(), spelled)
|
|
129
|
+
if other != spelled and (other, spelled) not in pairs:
|
|
130
|
+
pairs.append((other, spelled))
|
|
131
|
+
code = "APPLY_SPELLING_CONFLICT" if folds else "APPLY_SPELLING_UNDECIDED"
|
|
132
|
+
why = ("this filesystem folds case, so both would be written under one name" if folds else
|
|
133
|
+
"whether this filesystem folds case could not be established, so the set is refused rather than applied")
|
|
134
|
+
return [f"{code} {a} and {b}: two planned paths spell one name in two cases; {why}" for a, b in pairs]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# ---- the files of the checkout -----------------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
class Checkout:
|
|
140
|
+
"""The declared checkout opened once; every file under it reached by a confined walk."""
|
|
141
|
+
|
|
142
|
+
def __init__(self, root):
|
|
143
|
+
self.root = pathlib.Path(root)
|
|
144
|
+
self.confined = journal.Confined(str(self.root))
|
|
145
|
+
|
|
146
|
+
def close(self):
|
|
147
|
+
self.confined.close()
|
|
148
|
+
|
|
149
|
+
def __enter__(self):
|
|
150
|
+
return self
|
|
151
|
+
|
|
152
|
+
def __exit__(self, *_exc):
|
|
153
|
+
self.close()
|
|
154
|
+
return False
|
|
155
|
+
|
|
156
|
+
def _pieces(self, path):
|
|
157
|
+
return self.confined.parts(self.root / path)
|
|
158
|
+
|
|
159
|
+
@staticmethod
|
|
160
|
+
def _close(fds):
|
|
161
|
+
for held in fds[1:]:
|
|
162
|
+
try:
|
|
163
|
+
os.close(held)
|
|
164
|
+
except OSError:
|
|
165
|
+
pass
|
|
166
|
+
|
|
167
|
+
@staticmethod
|
|
168
|
+
def _open(parent, leaf, path):
|
|
169
|
+
"""The leaf's descriptor, or None when it is absent: never through a link, never blocking, and
|
|
170
|
+
only a regular file with one name."""
|
|
171
|
+
try:
|
|
172
|
+
handle = os.open(leaf, os.O_RDONLY | _NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
|
|
173
|
+
except OSError as exc:
|
|
174
|
+
if exc.errno == errno.ENOENT:
|
|
175
|
+
return None
|
|
176
|
+
raise Refused(f"APPLY_TARGET_UNOPENABLE {path}: {exc.strerror} - a target is a regular file "
|
|
177
|
+
f"and never a link") from exc
|
|
178
|
+
try:
|
|
179
|
+
held = os.fstat(handle)
|
|
180
|
+
if not stat.S_ISREG(held.st_mode):
|
|
181
|
+
raise Refused(f"APPLY_TARGET_NOT_FILE {path}: a target is a regular file")
|
|
182
|
+
if held.st_nlink != 1:
|
|
183
|
+
raise Refused(f"APPLY_TARGET_HARD_LINKED {path}: it has {held.st_nlink} names, and a write "
|
|
184
|
+
f"through one would change a file the checkout does not name")
|
|
185
|
+
except BaseException:
|
|
186
|
+
os.close(handle)
|
|
187
|
+
raise
|
|
188
|
+
return handle
|
|
189
|
+
|
|
190
|
+
@staticmethod
|
|
191
|
+
def _bytes(handle):
|
|
192
|
+
out = b""
|
|
193
|
+
while True:
|
|
194
|
+
chunk = os.read(handle, 1 << 20)
|
|
195
|
+
if not chunk:
|
|
196
|
+
return out
|
|
197
|
+
out += chunk
|
|
198
|
+
|
|
199
|
+
def _state(self, parent, leaf, path):
|
|
200
|
+
"""`(sha | "absent", mode | None, (device, inode) | None)` of the leaf, through its descriptor."""
|
|
201
|
+
handle = self._open(parent, leaf, path)
|
|
202
|
+
if handle is None:
|
|
203
|
+
return ABSENT, None, None
|
|
204
|
+
try:
|
|
205
|
+
held = os.fstat(handle)
|
|
206
|
+
return hashlib.sha256(self._bytes(handle)).hexdigest(), stat.S_IMODE(held.st_mode), (held.st_dev,
|
|
207
|
+
held.st_ino)
|
|
208
|
+
finally:
|
|
209
|
+
os.close(handle)
|
|
210
|
+
|
|
211
|
+
@staticmethod
|
|
212
|
+
def _spelled(fds, pieces, path):
|
|
213
|
+
"""Every component the walk reached is spelled as its directory holds it. `open` on a filesystem
|
|
214
|
+
that folds case answers for `upper/` with `Upper/`, and the file then lands under a name the
|
|
215
|
+
plan never held."""
|
|
216
|
+
for parent, piece in zip(fds, pieces):
|
|
217
|
+
# the target contract's own comparison, so the plan and the write agree on what one name is:
|
|
218
|
+
# a canonically equivalent entry is the name, a case difference is another
|
|
219
|
+
found = targets._spelling_on_disk([piece], parent, path)
|
|
220
|
+
if found:
|
|
221
|
+
raise Refused(f"APPLY_SPELLING_ON_DISK {path}: " + "; ".join(found))
|
|
222
|
+
|
|
223
|
+
def read(self, path):
|
|
224
|
+
"""The file's bytes, or None when it is absent (the plan's reader)."""
|
|
225
|
+
pieces = self._pieces(path)
|
|
226
|
+
fds, leaf, _made = self.confined.walk(pieces, missing_ok=True)
|
|
227
|
+
if fds is None:
|
|
228
|
+
return None
|
|
229
|
+
try:
|
|
230
|
+
self._spelled(fds, pieces, path)
|
|
231
|
+
handle = self._open(fds[-1], leaf, path)
|
|
232
|
+
if handle is None:
|
|
233
|
+
return None
|
|
234
|
+
try:
|
|
235
|
+
return self._bytes(handle)
|
|
236
|
+
finally:
|
|
237
|
+
os.close(handle)
|
|
238
|
+
finally:
|
|
239
|
+
self._close(fds)
|
|
240
|
+
|
|
241
|
+
def state(self, path):
|
|
242
|
+
fds, leaf, _made = self.confined.walk(self._pieces(path), missing_ok=True)
|
|
243
|
+
if fds is None:
|
|
244
|
+
return ABSENT
|
|
245
|
+
try:
|
|
246
|
+
return self._state(fds[-1], leaf, path)[0]
|
|
247
|
+
finally:
|
|
248
|
+
self._close(fds)
|
|
249
|
+
|
|
250
|
+
@staticmethod
|
|
251
|
+
def _named(parent, name):
|
|
252
|
+
"""`(device, inode)` of what `name` is in `parent` now, a regular file with one name, or None."""
|
|
253
|
+
try:
|
|
254
|
+
held = os.stat(name, dir_fd=parent, follow_symlinks=False)
|
|
255
|
+
except FileNotFoundError:
|
|
256
|
+
return None
|
|
257
|
+
return (held.st_dev, held.st_ino) if stat.S_ISREG(held.st_mode) and held.st_nlink == 1 else None
|
|
258
|
+
|
|
259
|
+
def take(self, effect):
|
|
260
|
+
"""One effect on disk. The new bytes are staged and synced first; the target is then held to
|
|
261
|
+
the plan's before-state and the staged name to the staged file, the rename is made, and what
|
|
262
|
+
the name holds is read back. Raises Refused, with the done record unwritten, on any
|
|
263
|
+
difference."""
|
|
264
|
+
path, data = effect["path"], effect["data"]
|
|
265
|
+
pieces = self._pieces(path)
|
|
266
|
+
# directories are made only for a file that is not there yet: replacing one never needs a new directory,
|
|
267
|
+
# and a refused replacement must not leave one behind (the S12 review, round 2)
|
|
268
|
+
fds, leaf, _made = self.confined.walk(pieces, create=data is not None and effect["before"] == ABSENT)
|
|
269
|
+
try:
|
|
270
|
+
parent = fds[-1]
|
|
271
|
+
self._spelled(fds, pieces, path)
|
|
272
|
+
|
|
273
|
+
def held_to_before():
|
|
274
|
+
now, mode, where = self._state(parent, leaf, path)
|
|
275
|
+
if now != effect["before"]:
|
|
276
|
+
raise Refused(f"APPLY_BEFORE_MISMATCH {path}: it is {now[:12]} at the write, and the plan "
|
|
277
|
+
f"holds {effect['before'][:12]}")
|
|
278
|
+
# ... and the NAME still holds the file that was read: a file put under the name while the old
|
|
279
|
+
# one was being read is not the one the plan's before-state describes
|
|
280
|
+
if self._named(parent, leaf) != where:
|
|
281
|
+
raise Refused(f"APPLY_BEFORE_MISMATCH {path}: the name was given to another file while the "
|
|
282
|
+
f"one the plan holds was being read")
|
|
283
|
+
return mode
|
|
284
|
+
|
|
285
|
+
if data is None:
|
|
286
|
+
held_to_before()
|
|
287
|
+
os.unlink(leaf, dir_fd=parent)
|
|
288
|
+
else:
|
|
289
|
+
mode = held_to_before() # an early answer; the binding one follows the staging
|
|
290
|
+
temp = f".{leaf}.s11-{os.urandom(8).hex()}.tmp"
|
|
291
|
+
handle = os.open(temp, os.O_RDWR | os.O_CREAT | os.O_EXCL | _NOFOLLOW,
|
|
292
|
+
0o644 if mode is None else mode, dir_fd=parent)
|
|
293
|
+
try:
|
|
294
|
+
try:
|
|
295
|
+
view = memoryview(data)
|
|
296
|
+
while view:
|
|
297
|
+
view = view[os.write(handle, view):]
|
|
298
|
+
os.fsync(handle)
|
|
299
|
+
held_to_before() # the target, immediately before the rename
|
|
300
|
+
# ... and the staged file, through the descriptor that wrote it: still a regular file
|
|
301
|
+
# with one name, still holding the planned bytes, and still what its name holds. A
|
|
302
|
+
# writer that changed it in place, or gave its name to another file, installs nothing.
|
|
303
|
+
staged = os.fstat(handle)
|
|
304
|
+
there = hashlib.sha256()
|
|
305
|
+
offset = 0
|
|
306
|
+
while True:
|
|
307
|
+
chunk = os.pread(handle, 1 << 20, offset)
|
|
308
|
+
if not chunk:
|
|
309
|
+
break
|
|
310
|
+
there.update(chunk)
|
|
311
|
+
offset += len(chunk)
|
|
312
|
+
after_scan = os.fstat(handle) # the scan itself must have read a file standing still
|
|
313
|
+
still = (staged.st_size, staged.st_mtime_ns, staged.st_ctime_ns) == (
|
|
314
|
+
after_scan.st_size, after_scan.st_mtime_ns, after_scan.st_ctime_ns)
|
|
315
|
+
if (not stat.S_ISREG(staged.st_mode) or staged.st_nlink != 1 or not still
|
|
316
|
+
or there.hexdigest() != effect["after"]
|
|
317
|
+
or self._named(parent, temp) != (staged.st_dev, staged.st_ino)):
|
|
318
|
+
raise Refused(f"APPLY_STAGING_MOVED {path}: the temporary no longer holds the planned "
|
|
319
|
+
f"bytes under its own name, so nothing is installed")
|
|
320
|
+
staged = (staged.st_dev, staged.st_ino)
|
|
321
|
+
os.replace(temp, leaf, src_dir_fd=parent, dst_dir_fd=parent)
|
|
322
|
+
finally:
|
|
323
|
+
os.close(handle)
|
|
324
|
+
except BaseException:
|
|
325
|
+
try:
|
|
326
|
+
os.unlink(temp, dir_fd=parent)
|
|
327
|
+
except OSError:
|
|
328
|
+
pass
|
|
329
|
+
raise
|
|
330
|
+
if self._named(parent, leaf) != staged:
|
|
331
|
+
raise Refused(f"APPLY_AFTER_MISMATCH {path}: the name does not hold the file that was "
|
|
332
|
+
f"staged for it")
|
|
333
|
+
for held in reversed(fds): # the entry, and any directory this walk made
|
|
334
|
+
os.fsync(held)
|
|
335
|
+
after = self._state(parent, leaf, path)[0]
|
|
336
|
+
if after != effect["after"]:
|
|
337
|
+
raise Refused(f"APPLY_AFTER_MISMATCH {path}: it is {after[:12]} after the write, and the "
|
|
338
|
+
f"plan holds {effect['after'][:12]}")
|
|
339
|
+
finally:
|
|
340
|
+
self._close(fds)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
# ---- the stage ---------------------------------------------------------------------------------------
|
|
344
|
+
|
|
345
|
+
def inputs_of(run_dir, version):
|
|
346
|
+
return stage_confirm.inputs_of(run_dir) + [
|
|
347
|
+
{"artifact": stage_confirm.CONFIRMATION, "producer_stage": "S10b"},
|
|
348
|
+
{"artifact": stage_confirm.manifest_rel(version), "producer_stage": "S10b"}]
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def items_of(manifest, current, approvals):
|
|
352
|
+
"""The confirmed items in the confirmed order, each with its approval and its WHOLE operations
|
|
353
|
+
(the manifest's F carries type, target and before-state only)."""
|
|
354
|
+
rows = {r["item_id"]: r for r in current["rows"]}
|
|
355
|
+
last = {}
|
|
356
|
+
for row in approvals:
|
|
357
|
+
last[row["item_id"]] = row
|
|
358
|
+
in_f = [i["item_id"] for i in manifest["F"]]
|
|
359
|
+
# Release 1 writes no library file: the plan and the effects both take their items here, so no write follows
|
|
360
|
+
if in_f and placement.release_scope() == "release_1":
|
|
361
|
+
raise Refused(f"RELEASE_1_NO_LIBRARY_CHANGE S11: the confirmed set holds {len(in_f)} item(s) that change a "
|
|
362
|
+
f"library file, and release 1 writes none")
|
|
363
|
+
order = list(manifest["sequencing"].get("order") or [])
|
|
364
|
+
if in_f and manifest["sequencing"].get("sequenced") is not True:
|
|
365
|
+
raise Refused(f"APPLY_UNSEQUENCED S11: the confirmed set holds {len(in_f)} items and no order "
|
|
366
|
+
f"({manifest['sequencing'].get('reason')})")
|
|
367
|
+
if sorted(order) != sorted(in_f):
|
|
368
|
+
raise Refused("APPLY_ORDER_INCOMPLETE S11: the confirmed order does not hold exactly the items of F")
|
|
369
|
+
items = []
|
|
370
|
+
for item_id in order:
|
|
371
|
+
approval = last.get(item_id) or {}
|
|
372
|
+
if approval.get("approval_id") not in manifest["approval_ids"]:
|
|
373
|
+
raise Refused(f"APPROVAL_UNBOUND {item_id}: its last approval is not one the confirmation binds")
|
|
374
|
+
items.append({"item_id": item_id, "approval_id": approval["approval_id"],
|
|
375
|
+
"operations": list((rows[item_id].get("proposal") or {}).get("operations") or [])})
|
|
376
|
+
return items
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def paths_of(items):
|
|
380
|
+
out = []
|
|
381
|
+
for item in items:
|
|
382
|
+
for operation in item["operations"]:
|
|
383
|
+
for held in [operation.get("target")] + list(operation.get("units") or ()):
|
|
384
|
+
path = split_target(held)[0]
|
|
385
|
+
if path and path not in out:
|
|
386
|
+
out.append(path)
|
|
387
|
+
return out
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def commands_of(checkout, paths):
|
|
391
|
+
"""The two commands the owner runs. S11 runs neither."""
|
|
392
|
+
quoted = " ".join("'" + p.replace("'", "'\\''") + "'" for p in paths)
|
|
393
|
+
root = "'" + str(checkout).replace("'", "'\\''") + "'"
|
|
394
|
+
return {"commit": f"git -C {root} add -- {quoted} && git -C {root} commit",
|
|
395
|
+
"install": f"bash {root}/install.sh install --non-interactive"}
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _plan_doc(confirmation_id, effects):
|
|
399
|
+
rows = []
|
|
400
|
+
for ordinal, effect in enumerate(effects):
|
|
401
|
+
rows.append({**{k: effect[k] for k in ("item_id", "approval_id", "operation", "type", "path", "before",
|
|
402
|
+
"after")},
|
|
403
|
+
"operation_id": operation_id(confirmation_id, effect, ordinal),
|
|
404
|
+
"data_b64": None if effect["data"] is None else base64.b64encode(effect["data"]).decode("ascii")})
|
|
405
|
+
return {"stage": STAGE, "confirmation_id": confirmation_id, "effects": rows}
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def plan_problems(plan, confirmation_id, items):
|
|
409
|
+
"""Why a plan read back is not the confirmed set's, by name. The shared record check already holds
|
|
410
|
+
the file to the hash the plan part recorded; this holds what it SAYS to what was confirmed, so
|
|
411
|
+
the effects part acts on nothing the confirmation does not bind."""
|
|
412
|
+
if plan.get("confirmation_id") != confirmation_id:
|
|
413
|
+
return [f"PLAN_UNBOUND {PLAN}: it was planned for another confirmation"]
|
|
414
|
+
by_item, problems, last = {i["item_id"]: i for i in items}, [], {}
|
|
415
|
+
for ordinal, row in enumerate(plan.get("effects") or []):
|
|
416
|
+
who = f"{PLAN} effects[{ordinal}]"
|
|
417
|
+
item = by_item.get(row.get("item_id"))
|
|
418
|
+
if item is None or row.get("approval_id") != item["approval_id"]:
|
|
419
|
+
problems.append(f"PLAN_EFFECT_UNCONFIRMED {who}: {row.get('item_id')} under approval "
|
|
420
|
+
f"{row.get('approval_id')} is not an item of the confirmed set")
|
|
421
|
+
continue
|
|
422
|
+
index = row.get("operation")
|
|
423
|
+
if not isinstance(index, int) or isinstance(index, bool) or not 0 <= index < len(item["operations"]):
|
|
424
|
+
problems.append(f"PLAN_EFFECT_UNCONFIRMED {who}: {row.get('item_id')} has no operation {index!r}")
|
|
425
|
+
continue
|
|
426
|
+
operation = item["operations"][index]
|
|
427
|
+
named = {split_target(held)[0] for held in [operation.get("target")] + list(operation.get("units") or ())}
|
|
428
|
+
if row.get("path") not in named or row.get("type") != operation.get("type"):
|
|
429
|
+
problems.append(f"PLAN_EFFECT_UNCONFIRMED {who}: {row.get('type')} {row.get('path')} is not what "
|
|
430
|
+
f"operation {index} of {row.get('item_id')} names")
|
|
431
|
+
continue
|
|
432
|
+
try:
|
|
433
|
+
data = None if row.get("data_b64") is None else base64.b64decode(row["data_b64"], validate=True)
|
|
434
|
+
except (ValueError, TypeError):
|
|
435
|
+
problems.append(f"PLAN_CHANGED {who}: its bytes do not decode")
|
|
436
|
+
continue
|
|
437
|
+
if sha_of(data) != row.get("after"):
|
|
438
|
+
problems.append(f"PLAN_CHANGED {who}: the bytes it holds for {row.get('path')} are not the ones it "
|
|
439
|
+
f"planned")
|
|
440
|
+
if row.get("operation_id") != operation_id(confirmation_id, row, ordinal):
|
|
441
|
+
problems.append(f"PLAN_CHANGED {who}: its operation id is not the one its fields derive")
|
|
442
|
+
if row["path"] in last and last[row["path"]] != row.get("before"):
|
|
443
|
+
problems.append(f"PLAN_CHANGED {who}: {row['path']} is planned from {str(row.get('before'))[:12]}, and "
|
|
444
|
+
f"the effect before it leaves {str(last[row['path']])[:12]}")
|
|
445
|
+
last[row["path"]] = row.get("after")
|
|
446
|
+
return problems
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _effects_in(doc):
|
|
450
|
+
return [{**{k: v for k, v in row.items() if k != "data_b64"},
|
|
451
|
+
"data": None if row["data_b64"] is None else base64.b64decode(row["data_b64"])}
|
|
452
|
+
for row in doc["effects"]]
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def journal_problems(held, effects):
|
|
456
|
+
"""Why the journal on disk is not this plan's, by name: it does not parse, or it holds a record
|
|
457
|
+
the plan does not."""
|
|
458
|
+
problems = [f"APPLY_JOURNAL_CORRUPT {JOURNAL}: {p}" for p in held.get("problems") or []]
|
|
459
|
+
if held.get("torn") or held.get("unterminated"):
|
|
460
|
+
problems.append(f"APPLY_JOURNAL_CORRUPT {JOURNAL}: its last record is torn or unterminated")
|
|
461
|
+
planned = {e["operation_id"]: e for e in effects}
|
|
462
|
+
rows = list(held.get("records") or [])
|
|
463
|
+
for row in rows:
|
|
464
|
+
effect = planned.get(row.get("operation_id"))
|
|
465
|
+
if effect is None or (row.get("target"), row.get("before_sha256"), row.get("after_sha256"),
|
|
466
|
+
row.get("item_id"), row.get("approval_id")) != (
|
|
467
|
+
effect["path"], effect["before"], effect["after"], effect["item_id"], effect["approval_id"]):
|
|
468
|
+
problems.append(f"APPLY_JOURNAL_FOREIGN {JOURNAL}: it holds a {row.get('kind')} record for "
|
|
469
|
+
f"{row.get('target')} that the plan does not")
|
|
470
|
+
if problems:
|
|
471
|
+
return problems
|
|
472
|
+
# The stream itself, in ITS order, is the plan's: planned then done for each effect in the plan's order - a
|
|
473
|
+
# completed prefix, and at most one planned record after it. Read against the expected order instead of in its
|
|
474
|
+
# own, two completed pairs swapped and two effects interleaved both passed (the S12 review, round 2).
|
|
475
|
+
expected = [(e["operation_id"], kind) for e in effects for kind in ("planned", "done")]
|
|
476
|
+
got = [(row.get("operation_id"), row.get("kind")) for row in rows]
|
|
477
|
+
if got != expected[:len(got)]:
|
|
478
|
+
at = next(i for i, pair in enumerate(got) if i >= len(expected) or pair != expected[i])
|
|
479
|
+
problems.append(f"APPLY_JOURNAL_CORRUPT {JOURNAL}: record {at + 1} is a {got[at][1]!r} record where the "
|
|
480
|
+
f"plan's history has {'nothing' if at >= len(expected) else repr(expected[at][1])}; an "
|
|
481
|
+
f"operation's history is planned then done, in the plan's order")
|
|
482
|
+
return problems
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def _bound(run_dir, declaration, confirmation, version):
|
|
486
|
+
"""`(stored manifest, gathered, checkout)` once the confirmation binds, or Refused."""
|
|
487
|
+
checkout = ((declaration or {}).get("destinations") or {}).get("checkout")
|
|
488
|
+
if not checkout or not pathlib.Path(checkout).is_dir():
|
|
489
|
+
raise Refused("CHECKOUT_UNDECLARED S11: the files are written in run.json's destinations.checkout, "
|
|
490
|
+
"which must be a directory")
|
|
491
|
+
manifest_path = run_dir / stage_confirm.manifest_rel(version)
|
|
492
|
+
stored = records.read_json(manifest_path)
|
|
493
|
+
gathered = stage_confirm.gathered(run_dir)
|
|
494
|
+
again, found = stage_confirm.final_set(declaration, *gathered)
|
|
495
|
+
found = list(found) + stage_confirm.binding_problems(stored, again, records.sha256_file(manifest_path),
|
|
496
|
+
confirmation["manifest_sha"])
|
|
497
|
+
if sorted(confirmation["approval_ids"]) != sorted(stored["approval_ids"]):
|
|
498
|
+
found.append("CONFIRMATION_UNBOUND approval_ids: the confirmation does not bind the manifest's approvals")
|
|
499
|
+
if found:
|
|
500
|
+
raise Refused("\n".join(found))
|
|
501
|
+
return stored, gathered, checkout
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
COMMITMENT = "apply/plan-commitment.json"
|
|
505
|
+
APPLY_LOCK = "S11-apply"
|
|
506
|
+
DECLARATION_WAIT_S = 5 # how long a write waits for an amendment in progress before it is refused
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def plan(run_dir):
|
|
510
|
+
"""S11's plan part: `apply/plan.json`, or Refused with nothing written. One S11 call at a time: the lock is
|
|
511
|
+
what makes "no journal yet" still true when the part's record is replaced."""
|
|
512
|
+
with stagelock.hold(run_dir, APPLY_LOCK):
|
|
513
|
+
return _plan(pathlib.Path(run_dir))
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _plan(run_dir):
|
|
517
|
+
confirmation = records.read_json(run_dir / stage_confirm.CONFIRMATION)
|
|
518
|
+
version = confirmation["confirm_version"]
|
|
519
|
+
if (run_dir / JOURNAL).exists():
|
|
520
|
+
raise Refused(f"PLAN_AFTER_EFFECTS {JOURNAL}: effects were taken from a plan that is not there to read; "
|
|
521
|
+
f"nothing is planned over them")
|
|
522
|
+
with records.run_stage(run_dir, STAGE, inputs_of(run_dir, version), part=PLAN_PART) as stage:
|
|
523
|
+
stored, gathered, checkout = _bound(run_dir, stage.declaration, confirmation, version)
|
|
524
|
+
current, approvals, s7b = gathered[0], gathered[1], gathered[2]
|
|
525
|
+
items = items_of(stored, current, approvals)
|
|
526
|
+
paths = paths_of(items)
|
|
527
|
+
judgments = {r.get("item_id"): r.get("faithful_merge") for r in (s7b or {}).get("reviews") or []}
|
|
528
|
+
problems = (list(targets.set_problems(paths, checkout))
|
|
529
|
+
+ spelling_problems(paths, targets.folds_case(checkout))
|
|
530
|
+
+ list(drift.global_op_problems(items, judgments)))
|
|
531
|
+
if problems:
|
|
532
|
+
raise Refused("\n".join(problems))
|
|
533
|
+
with Checkout(checkout) as tree:
|
|
534
|
+
planned, problems = operations.plan_of(items, tree.read)
|
|
535
|
+
if problems:
|
|
536
|
+
raise Refused("\n".join(problems))
|
|
537
|
+
records.write_json(run_dir, run_dir / PLAN, _plan_doc(confirmation["confirmation_id"], planned))
|
|
538
|
+
stage.output(PLAN)
|
|
539
|
+
return {"effects": len(planned)}
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def _part(run_dir, name):
|
|
543
|
+
return (((records.stage_records(run_dir).get(STAGE) or {}).get("parts") or {}).get(name)) or {}
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def run(run_dir):
|
|
547
|
+
"""S11 over the confirmed final set: `apply.json`, or Refused with no file of the checkout
|
|
548
|
+
written by this call."""
|
|
549
|
+
with stagelock.hold(run_dir, APPLY_LOCK):
|
|
550
|
+
return _run(pathlib.Path(run_dir))
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _held_declaration(run_dir, admitted, who=STAGE):
|
|
554
|
+
"""Refused unless the declaration is the one this part was admitted under. Called with the declaration's lock
|
|
555
|
+
held, so an amendment (`declare.amend` takes that lock) cannot land between this answer and what follows it."""
|
|
556
|
+
now_run, now_digest, _amendments = records.declaration_state(run_dir, who=who)
|
|
557
|
+
if (now_run["declaration_seq"], now_digest) != admitted:
|
|
558
|
+
raise Refused(f"DECLARATION_MOVED {who}: the declaration is at sequence {now_run['declaration_seq']} and "
|
|
559
|
+
f"this stage was admitted at {admitted[0]}; no further file is written")
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _run(run_dir):
|
|
563
|
+
if not (run_dir / stage_confirm.CONFIRMATION).is_file():
|
|
564
|
+
raise Refused("CONFIRMATION_ABSENT S11: the final set is not confirmed; S10b's confirm comes first")
|
|
565
|
+
confirmation = records.read_json(run_dir / stage_confirm.CONFIRMATION)
|
|
566
|
+
version = confirmation["confirm_version"]
|
|
567
|
+
if _part(run_dir, PLAN_PART).get("status") != "complete" or not (run_dir / PLAN).is_file():
|
|
568
|
+
_plan(run_dir)
|
|
569
|
+
# The plan the effects are taken from is committed ONCE, before the first effect, in a file no attempt
|
|
570
|
+
# replaces. The effects record's own pinned input is replaced by every attempt - a refused one too - so
|
|
571
|
+
# reading the commitment from it let a refused retry authorize the plan it had just refused (round 2).
|
|
572
|
+
earlier_plan = (records.read_json(run_dir / COMMITMENT).get("plan_sha256")
|
|
573
|
+
if (run_dir / COMMITMENT).is_file() else None)
|
|
574
|
+
specs = inputs_of(run_dir, version) + [{"artifact": PLAN, "producer_stage": STAGE}]
|
|
575
|
+
with records.run_stage(run_dir, STAGE, specs, part=EFFECTS_PART) as stage:
|
|
576
|
+
declaration = stage.declaration
|
|
577
|
+
stored, gathered, checkout = _bound(run_dir, declaration, confirmation, version)
|
|
578
|
+
items = items_of(stored, gathered[0], gathered[1])
|
|
579
|
+
# The plan's bytes are read ONCE, and they are the bytes admission checked: the record's pinned input.
|
|
580
|
+
plan_bytes = (run_dir / PLAN).read_bytes()
|
|
581
|
+
plan_sha = hashlib.sha256(plan_bytes).hexdigest()
|
|
582
|
+
admitted_sha = next((i["sha256"] for i in stage.record["inputs"] if i["artifact"] == PLAN), None)
|
|
583
|
+
if plan_sha != admitted_sha:
|
|
584
|
+
raise Refused(f"PLAN_CHANGED {PLAN}: its bytes are not the ones this part was admitted on")
|
|
585
|
+
held_plan = json.loads(plan_bytes.decode("utf-8"))
|
|
586
|
+
problems = plan_problems(held_plan, confirmation["confirmation_id"], items)
|
|
587
|
+
if problems:
|
|
588
|
+
raise Refused("\n".join(problems))
|
|
589
|
+
effects = _effects_in(held_plan)
|
|
590
|
+
held = journal.read(run_dir / JOURNAL)
|
|
591
|
+
problems = journal_problems(held, effects)
|
|
592
|
+
if problems:
|
|
593
|
+
raise Refused("\n".join(problems))
|
|
594
|
+
# ... and the plan is the WHOLE ordered result of the confirmed operations, not rows that each pass.
|
|
595
|
+
# Before any effect that is asked directly: the confirmed set planned again over the files as they are
|
|
596
|
+
# must be this plan, byte for byte. Once effects were taken the files have moved, so the plan must be
|
|
597
|
+
# the very one those effects were taken from.
|
|
598
|
+
if held["records"] or earlier_plan is not None:
|
|
599
|
+
if earlier_plan != plan_sha:
|
|
600
|
+
raise Refused(f"PLAN_CHANGED {PLAN}: the effects of this run are committed to another plan "
|
|
601
|
+
f"({str(earlier_plan)[:12]}), and this one is {plan_sha[:12]}")
|
|
602
|
+
else:
|
|
603
|
+
with Checkout(checkout) as tree:
|
|
604
|
+
again, problems = operations.plan_of(items, tree.read)
|
|
605
|
+
if problems:
|
|
606
|
+
raise Refused("\n".join(problems))
|
|
607
|
+
if _plan_doc(confirmation["confirmation_id"], again) != held_plan:
|
|
608
|
+
raise Refused(f"PLAN_NOT_THE_CONFIRMED_SET {PLAN}: the confirmed operations, planned over the files "
|
|
609
|
+
f"as they are, give {len(again)} effects that are not this plan's "
|
|
610
|
+
f"{len(held_plan.get('effects') or [])} in order and bytes")
|
|
611
|
+
records.write_json(run_dir, run_dir / COMMITMENT,
|
|
612
|
+
{"stage": STAGE, "confirmation_id": confirmation["confirmation_id"],
|
|
613
|
+
"plan_sha256": plan_sha})
|
|
614
|
+
stage.output(COMMITMENT)
|
|
615
|
+
done = {r["operation_id"] for r in held["records"] if r.get("kind") == "done"}
|
|
616
|
+
pending = {r["operation_id"] for r in held["records"] if r.get("kind") == "planned"} - done
|
|
617
|
+
admitted = (declaration["declaration_seq"], stage.record["run_json_sha256"])
|
|
618
|
+
with Checkout(checkout) as tree:
|
|
619
|
+
for effect in effects:
|
|
620
|
+
if effect["operation_id"] in pending:
|
|
621
|
+
now = tree.state(effect["path"])
|
|
622
|
+
where = ("its before-state" if now == effect["before"] else
|
|
623
|
+
"its after-state" if now == effect["after"] else "neither state the plan holds")
|
|
624
|
+
raise Refused(f"APPLY_UNRECONCILED {effect['path']}: an earlier run planned this write and "
|
|
625
|
+
f"recorded no end; the file is at {where}. Inspect it in the checkout, restore "
|
|
626
|
+
f"it if needed, and apply in a new run")
|
|
627
|
+
rows = []
|
|
628
|
+
for effect in effects:
|
|
629
|
+
row = {k: effect[k] for k in ("operation_id", "item_id", "approval_id", "operation", "type",
|
|
630
|
+
"path", "before", "after")}
|
|
631
|
+
if effect["operation_id"] in done:
|
|
632
|
+
rows.append({**row, "state": "done_before"})
|
|
633
|
+
continue
|
|
634
|
+
# The declaration this part was admitted under, held for the whole of each write: admission
|
|
635
|
+
# releases the declaration's lock, so the lock is taken again around the check AND the effect,
|
|
636
|
+
# and an amendment waits for the write or the write is refused - never both at once.
|
|
637
|
+
with stagelock.hold(run_dir, "declaration", wait_s=DECLARATION_WAIT_S):
|
|
638
|
+
_held_declaration(run_dir, admitted)
|
|
639
|
+
record = journal.planned(effect["operation_id"], effect["path"], effect["before"],
|
|
640
|
+
effect["after"], effect["item_id"], effect["approval_id"])
|
|
641
|
+
journal.journalled(run_dir / JOURNAL, record, str(run_dir),
|
|
642
|
+
lambda effect=effect: tree.take(effect))
|
|
643
|
+
rows.append({**row, "state": "applied"})
|
|
644
|
+
if (run_dir / JOURNAL).is_file():
|
|
645
|
+
stage.output(JOURNAL)
|
|
646
|
+
changed = []
|
|
647
|
+
for row in rows:
|
|
648
|
+
if row["path"] not in changed:
|
|
649
|
+
changed.append(row["path"])
|
|
650
|
+
doc = {"stage": STAGE, "confirmation_id": confirmation["confirmation_id"], "checkout": str(checkout),
|
|
651
|
+
"effects": rows, "paths": changed,
|
|
652
|
+
"ledger_only": len(stored.get("ledger_only") or []),
|
|
653
|
+
"counts": {"items": len(items), "effects": len(rows),
|
|
654
|
+
"applied": sum(1 for r in rows if r["state"] == "applied"),
|
|
655
|
+
"done_before": sum(1 for r in rows if r["state"] == "done_before"),
|
|
656
|
+
"files": len(changed)},
|
|
657
|
+
"owner_commands": commands_of(checkout, changed) if changed else None,
|
|
658
|
+
"not_done_by_this_stage": ["git", "install", "personal layers", "state roots"]}
|
|
659
|
+
with stagelock.hold(run_dir, "declaration", wait_s=DECLARATION_WAIT_S):
|
|
660
|
+
_held_declaration(run_dir, admitted) # and once more before the stage says it is complete
|
|
661
|
+
records.write_json(run_dir, run_dir / OUTPUT, doc)
|
|
662
|
+
stage.output(OUTPUT)
|
|
663
|
+
return doc
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
def report_lines(doc):
|
|
667
|
+
"""What the driver prints: counts, the files, and the two commands the owner runs."""
|
|
668
|
+
counts = doc["counts"]
|
|
669
|
+
lines = [f"S11 apply: {counts['items']} items, {counts['effects']} file changes over {counts['files']} files "
|
|
670
|
+
f"in {doc['checkout']} ({counts['applied']} written now, {counts['done_before']} by an earlier run); "
|
|
671
|
+
f"{doc['ledger_only']} approved items change the ledger alone and are S12's"]
|
|
672
|
+
lines += [f" {path}" for path in doc["paths"]]
|
|
673
|
+
if doc["owner_commands"]:
|
|
674
|
+
lines += ["This stage ran no git and no installer. The two commands are yours to run:",
|
|
675
|
+
f" {doc['owner_commands']['commit']}", f" {doc['owner_commands']['install']}"]
|
|
676
|
+
else:
|
|
677
|
+
lines.append("No file of the checkout changed, so there is nothing to commit or install.")
|
|
678
|
+
return lines
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
# ---- self-test ---------------------------------------------------------------------------------------
|
|
682
|
+
|
|
683
|
+
def self_test():
|
|
684
|
+
"""The suite under the release scope `all`: the contract as designed, which release 1 holds closed
|
|
685
|
+
(`placement.scoped`), so the path the redesign reopens stays held by its controls. Release 1's own controls
|
|
686
|
+
run inside it under `release_1`."""
|
|
687
|
+
with placement.scoped("all"):
|
|
688
|
+
return _self_test_all()
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def _self_test_all():
|
|
692
|
+
failures, ran, reporting = [], [], []
|
|
693
|
+
try:
|
|
694
|
+
_self_test_body(failures, ran, reporting)
|
|
695
|
+
except Exception as exc: # noqa: BLE001 - a suite that dies says so by name
|
|
696
|
+
if reporting:
|
|
697
|
+
raise
|
|
698
|
+
failures.append(("the suite ran to its end", f"{type(exc).__name__}: {exc}"[:600]))
|
|
699
|
+
ran.append("the suite ran to its end")
|
|
700
|
+
if failures:
|
|
701
|
+
for name, detail in failures:
|
|
702
|
+
print(f"stage_apply --self-test [FAIL] {name}: {detail}", file=sys.stderr)
|
|
703
|
+
print(f"stage_apply --self-test: FAILED ({len(failures)} of {len(ran)} controls)", file=sys.stderr)
|
|
704
|
+
return 1
|
|
705
|
+
print(f"stage_apply --self-test: OK ({len(ran)} controls: the write itself - staged before the last check, links, "
|
|
706
|
+
f"FIFOs, second names, spellings and outside paths refused - and the stage in its two parts: the plan "
|
|
707
|
+
f"recorded and held to the confirmed set, the effects through the journal, an edited plan, a corrupt "
|
|
708
|
+
f"journal, an amendment mid-run, a re-run and an unreconciled write)")
|
|
709
|
+
return 0
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
def _self_test_body(failures, ran, reporting):
|
|
713
|
+
import shutil
|
|
714
|
+
import tempfile
|
|
715
|
+
|
|
716
|
+
def control(name, got, want):
|
|
717
|
+
if reporting:
|
|
718
|
+
raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}")
|
|
719
|
+
ran.append(name)
|
|
720
|
+
if got != want:
|
|
721
|
+
failures.append((name, f"expected {want!r}, got {got!r}"[:900]))
|
|
722
|
+
|
|
723
|
+
def said(call):
|
|
724
|
+
try:
|
|
725
|
+
call()
|
|
726
|
+
except Refused as exc:
|
|
727
|
+
return str(exc).split(":")[0].split()[0]
|
|
728
|
+
except Exception as exc: # noqa: BLE001 - the exception IS the answer here
|
|
729
|
+
return f"RAISED {type(exc).__name__}: {exc}"
|
|
730
|
+
return ""
|
|
731
|
+
|
|
732
|
+
# release 1 writes no library file (D-20261116-7853bc): the items S11's plan and effects take are none
|
|
733
|
+
one_change = ({"F": [{"item_id": "k"}], "sequencing": {"sequenced": True, "order": ["k"]}, "approval_ids": ["a"]},
|
|
734
|
+
{"rows": [{"item_id": "k", "proposal": {"operations": [{"type": "edit", "target": "g/a.md"}]}}]},
|
|
735
|
+
[{"item_id": "k", "approval_id": "a"}])
|
|
736
|
+
no_change = ({"F": [], "sequencing": {"sequenced": None, "order": []}, "approval_ids": ["a"]},
|
|
737
|
+
{"rows": [{"item_id": "k"}]}, [{"item_id": "k", "approval_id": "a"}])
|
|
738
|
+
control("under the design's scope the confirmed item is S11's to write (the fixture is otherwise valid)",
|
|
739
|
+
[i["item_id"] for i in items_of(*one_change)], ["k"])
|
|
740
|
+
with placement.scoped("release_1"):
|
|
741
|
+
control("in release 1 a confirmed set that holds a change is refused by name before any plan or effect",
|
|
742
|
+
said(lambda: items_of(*one_change)), "RELEASE_1_NO_LIBRARY_CHANGE")
|
|
743
|
+
control("and a confirmed set that holds none gives S11 nothing to write", items_of(*no_change), [])
|
|
744
|
+
|
|
745
|
+
doc = "# Guide\n\nintro\n\n## One\n\nfirst body\n\n### Deep\n\ndeep body\n\n## Two\n\nsecond body\n"
|
|
746
|
+
files = {"g/a.md": doc.encode(), "g/b.md": b"# B\n\nbody of b\n", "g/r.md": b"# Routes\n"}
|
|
747
|
+
A, B_, R = (hashlib.sha256(files[k]).hexdigest() for k in ("g/a.md", "g/b.md", "g/r.md"))
|
|
748
|
+
control("the text rules are `operations.py`'s, and this stage plans with that module's plan",
|
|
749
|
+
[plan_of is operations.plan_of, split_target("g/a.md#One")], [True, ("g/a.md", "One")])
|
|
750
|
+
control("two planned paths that spell one directory differently are refused before anything is written",
|
|
751
|
+
[[p.split()[0] for p in spelling_problems(["Upper/a.md", "upper/b.md"], True)],
|
|
752
|
+
spelling_problems(["Upper/a.md", "Upper/b.md", "lower/c.md"], True)], [["APPLY_SPELLING_CONFLICT"], []])
|
|
753
|
+
control("whether two cases are one name is the filesystem's to say: where it does not fold case they are two "
|
|
754
|
+
"directories, where it did not say the set is refused rather than guessed, and two canonical forms of "
|
|
755
|
+
"one name are one name everywhere",
|
|
756
|
+
[spelling_problems(["Upper/a.md", "upper/b.md"], False),
|
|
757
|
+
[p.split()[0] for p in spelling_problems(["Upper/a.md", "upper/b.md"], None)],
|
|
758
|
+
spelling_problems(["caf\u00e9/a.md", "cafe\u0301/b.md"], True)],
|
|
759
|
+
[[], ["APPLY_SPELLING_UNDECIDED"], []])
|
|
760
|
+
|
|
761
|
+
# ---- the files -------------------------------------------------------------------------------
|
|
762
|
+
root = pathlib.Path(tempfile.mkdtemp(prefix="s11-"))
|
|
763
|
+
try:
|
|
764
|
+
checkout = root / "checkout"
|
|
765
|
+
(checkout / "g").mkdir(parents=True)
|
|
766
|
+
for name, data in files.items():
|
|
767
|
+
(checkout / name).write_bytes(data)
|
|
768
|
+
outside = root / "outside.md"
|
|
769
|
+
outside.write_text("outside\n")
|
|
770
|
+
|
|
771
|
+
def effect(path, data, before=None):
|
|
772
|
+
return {"path": path, "data": data, "after": sha_of(data),
|
|
773
|
+
"before": before if before is not None else sha_of(files.get(path))}
|
|
774
|
+
|
|
775
|
+
with Checkout(checkout) as tree:
|
|
776
|
+
control("the plan's reader gives a file's bytes and None for an absent one",
|
|
777
|
+
[tree.read("g/b.md"), tree.read("g/none.md"), tree.read("none/none.md")],
|
|
778
|
+
[files["g/b.md"], None, None])
|
|
779
|
+
tree.take(effect("g/b.md", b"changed\n"))
|
|
780
|
+
control("a write replaces the file, keeps its mode and leaves no temp file beside it",
|
|
781
|
+
[(checkout / "g/b.md").read_bytes(), sorted(p.name for p in (checkout / "g").iterdir()),
|
|
782
|
+
stat.S_IMODE((checkout / "g/b.md").stat().st_mode) == stat.S_IMODE(
|
|
783
|
+
(checkout / "g/a.md").stat().st_mode)],
|
|
784
|
+
[b"changed\n", ["a.md", "b.md", "r.md"], True])
|
|
785
|
+
tree.take(effect("new/deep/n.md", b"n\n"))
|
|
786
|
+
control("a create makes the directories it needs", (checkout / "new/deep/n.md").read_bytes(), b"n\n")
|
|
787
|
+
tree.take(effect("new/deep/n.md", None, before=sha_of(b"n\n")))
|
|
788
|
+
control("a removal removes the file", (checkout / "new/deep/n.md").exists(), False)
|
|
789
|
+
control("a file that is not at the plan's before-state at the write is refused and left as it is",
|
|
790
|
+
[said(lambda: tree.take(effect("g/a.md", b"x", before=B_))), (checkout / "g/a.md").read_bytes()],
|
|
791
|
+
["APPLY_BEFORE_MISMATCH", files["g/a.md"]])
|
|
792
|
+
control("bytes that are not the planned after-state are never installed: the staged file is held to "
|
|
793
|
+
"it before the rename",
|
|
794
|
+
[said(lambda: tree.take({**effect("g/a.md", b"y"), "after": B_})),
|
|
795
|
+
(checkout / "g/a.md").read_bytes()], ["APPLY_STAGING_MOVED", files["g/a.md"]])
|
|
796
|
+
(checkout / "g/a.md").write_bytes(files["g/a.md"])
|
|
797
|
+
os.symlink(outside, checkout / "g" / "link.md")
|
|
798
|
+
control("a target that is a symbolic link is refused, and what it points at is untouched",
|
|
799
|
+
[said(lambda: tree.take(effect("g/link.md", b"x", before=sha_of(b"outside\n")))),
|
|
800
|
+
outside.read_text()], ["APPLY_TARGET_UNOPENABLE", "outside\n"])
|
|
801
|
+
os.symlink(root, checkout / "away")
|
|
802
|
+
control("a directory in the path that is a symbolic link is refused",
|
|
803
|
+
said(lambda: tree.take(effect("away/outside.md", b"x", before=sha_of(b"outside\n")))),
|
|
804
|
+
"JOURNAL_SYMLINK_COMPONENT")
|
|
805
|
+
os.link(checkout / "g/r.md", root / "second-name.md")
|
|
806
|
+
control("a file with two names is refused, and the other name keeps its bytes",
|
|
807
|
+
[said(lambda: tree.take(effect("g/r.md", b"x"))), (root / "second-name.md").read_bytes()],
|
|
808
|
+
["APPLY_TARGET_HARD_LINKED", files["g/r.md"]])
|
|
809
|
+
control("a path that leaves the checkout is refused",
|
|
810
|
+
said(lambda: tree.read("../outside.md")), "JOURNAL_OUTSIDE_ROOT")
|
|
811
|
+
finally:
|
|
812
|
+
shutil.rmtree(root, ignore_errors=True)
|
|
813
|
+
|
|
814
|
+
control("the two commands name the checkout and the changed files, quoted",
|
|
815
|
+
commands_of("/c o", ["a.md", "it's.md"]),
|
|
816
|
+
{"commit": "git -C '/c o' add -- 'a.md' 'it'\\''s.md' && git -C '/c o' commit",
|
|
817
|
+
"install": "bash '/c o'/install.sh install --non-interactive"})
|
|
818
|
+
# ---- the stage: S10's real parse, S10b's build and confirm, then the apply -----------------------
|
|
819
|
+
from grammar import owner_lines
|
|
820
|
+
from runlib import declare
|
|
821
|
+
K = b"# K\n\nold\n"
|
|
822
|
+
|
|
823
|
+
def fx(name, place="claude/guides/g.md"):
|
|
824
|
+
"""A run parsed over two approved items - a create (at `place`) and a delete - and its own checkout."""
|
|
825
|
+
base = pathlib.Path(tempfile.mkdtemp(prefix=f"s11-{name}-"))
|
|
826
|
+
made.append(base)
|
|
827
|
+
checkout = base / "checkout"
|
|
828
|
+
(checkout / "claude" / "guides").mkdir(parents=True)
|
|
829
|
+
(checkout / "claude" / "guides" / "k.md").write_bytes(K)
|
|
830
|
+
declaration = declare.fixture()
|
|
831
|
+
declaration["destinations"]["checkout"] = str(checkout)
|
|
832
|
+
|
|
833
|
+
def edit(rows_doc):
|
|
834
|
+
for row in rows_doc["rows"]:
|
|
835
|
+
for operation in (row.get("proposal") or {}).get("operations") or []:
|
|
836
|
+
if operation["target"] == "claude/guides/k.md":
|
|
837
|
+
operation["before_state_sha256"] = sha_of(K)
|
|
838
|
+
if operation["target"] == "claude/guides/g.md":
|
|
839
|
+
operation["target"] = place
|
|
840
|
+
run_dir = stage_confirm.fx_run(base, declaration, edit)
|
|
841
|
+
copy = run_dir / "decisions.ko.v1.md"
|
|
842
|
+
held = copy.read_text(encoding="utf-8").split("\n")
|
|
843
|
+
for ident, lines in {"k-place": ["결정: 승인"],
|
|
844
|
+
"k-reduce": ["결정: 승인", "keep 해제: R-1 사용자가 직접 줄인다"]}.items():
|
|
845
|
+
start = next(i for i, x in enumerate(held) if x.startswith(f"<!-- owner-block review item={ident} "))
|
|
846
|
+
end = next(i for i in range(start + 1, len(held)) if held[i] == owner_lines.CLOSE)
|
|
847
|
+
held = held[:start + 1] + lines + held[end:]
|
|
848
|
+
copy.write_text("\n".join(held), encoding="utf-8")
|
|
849
|
+
stage_approvals.run(run_dir, 1)
|
|
850
|
+
return base, run_dir, checkout
|
|
851
|
+
|
|
852
|
+
def confirmed(name, **over):
|
|
853
|
+
base, run_dir, checkout = fx(name, **over)
|
|
854
|
+
stage_confirm.build(run_dir)
|
|
855
|
+
page = run_dir / stage_confirm.copy_name(1)
|
|
856
|
+
page.write_text(page.read_text(encoding="utf-8").replace("확인:\n", "확인: 확정\n", 1), encoding="utf-8")
|
|
857
|
+
stage_confirm.confirm(run_dir)
|
|
858
|
+
return base, run_dir, checkout
|
|
859
|
+
|
|
860
|
+
def refusal(call):
|
|
861
|
+
try:
|
|
862
|
+
call()
|
|
863
|
+
except Refused as exc:
|
|
864
|
+
return str(exc)
|
|
865
|
+
except Exception as exc: # noqa: BLE001 - the exception IS the answer here
|
|
866
|
+
return f"RAISED {type(exc).__name__}: {exc}"
|
|
867
|
+
return ""
|
|
868
|
+
|
|
869
|
+
def tree_of(checkout):
|
|
870
|
+
return sorted(str(p.relative_to(checkout)) for p in checkout.rglob("*") if p.is_file())
|
|
871
|
+
|
|
872
|
+
made, kept = [], []
|
|
873
|
+
def section(title, body):
|
|
874
|
+
"""One scenario: a break inside it fails under ITS name, and the scenarios after it still run."""
|
|
875
|
+
try:
|
|
876
|
+
body()
|
|
877
|
+
except Exception as exc: # noqa: BLE001 - reported by name, never swallowed
|
|
878
|
+
control(title, f"{type(exc).__name__}: {exc}"[:600], "ran to its end")
|
|
879
|
+
|
|
880
|
+
def code(call):
|
|
881
|
+
return (refusal(call).split() or [""])[0]
|
|
882
|
+
|
|
883
|
+
try:
|
|
884
|
+
def scenario_0():
|
|
885
|
+
base, run_dir, checkout = fx("unconfirmed")
|
|
886
|
+
control("an unconfirmed final set is not applied", refusal(lambda: run(run_dir)).split(":")[0],
|
|
887
|
+
"CONFIRMATION_ABSENT S11")
|
|
888
|
+
section('an unconfirmed final set (section)', scenario_0)
|
|
889
|
+
|
|
890
|
+
def scenario_1():
|
|
891
|
+
base, run_dir, checkout = confirmed("applied")
|
|
892
|
+
out = run(run_dir)
|
|
893
|
+
control("the confirmed set is written: the create is there, the delete is gone, and nothing else moved",
|
|
894
|
+
[tree_of(checkout), (checkout / "claude/guides/g.md").read_bytes()], [["claude/guides/g.md"], b"text"])
|
|
895
|
+
control("apply.json counts what was written and names the files",
|
|
896
|
+
[out["counts"], sorted(out["paths"]), [r["state"] for r in out["effects"]]],
|
|
897
|
+
[{"items": 2, "effects": 2, "applied": 2, "done_before": 0, "files": 2},
|
|
898
|
+
["claude/guides/g.md", "claude/guides/k.md"], ["applied", "applied"]])
|
|
899
|
+
held = journal.read(run_dir / JOURNAL)["records"]
|
|
900
|
+
control("every write has its plan record before it and its done record after, with both states",
|
|
901
|
+
[[r["kind"] for r in held], sorted({(r["target"], r["before_sha256"], r["after_sha256"]) for r in held})],
|
|
902
|
+
[["planned", "done", "planned", "done"],
|
|
903
|
+
sorted([("claude/guides/g.md", ABSENT, sha_of(b"text")), ("claude/guides/k.md", sha_of(K), ABSENT)])])
|
|
904
|
+
control("the stage names the two commands and says what it did not do",
|
|
905
|
+
[out["owner_commands"]["commit"].startswith(f"git -C '{checkout}' add -- "),
|
|
906
|
+
out["owner_commands"]["install"], out["not_done_by_this_stage"]],
|
|
907
|
+
[True, f"bash '{checkout}'/install.sh install --non-interactive",
|
|
908
|
+
["git", "install", "personal layers", "state roots"]])
|
|
909
|
+
rec = records.stage_records(run_dir).get(STAGE) or {}
|
|
910
|
+
control("the stage's record has two parts: the plan is the plan part's output, and the journal and "
|
|
911
|
+
"apply.json the effects part's, which took the plan as a recorded input",
|
|
912
|
+
[rec.get("status"),
|
|
913
|
+
{name: sorted(o["artifact"] for o in part.get("outputs") or [])
|
|
914
|
+
for name, part in (rec.get("parts") or {}).items()},
|
|
915
|
+
PLAN in [i["artifact"] for i in ((rec.get("parts") or {}).get(EFFECTS_PART) or {}).get("inputs") or []]],
|
|
916
|
+
["complete", {PLAN_PART: [PLAN], EFFECTS_PART: sorted([JOURNAL, OUTPUT, COMMITMENT])}, True])
|
|
917
|
+
again = refusal(lambda: kept.append(run(run_dir)))
|
|
918
|
+
control("a second apply writes nothing: every write is the journal's already",
|
|
919
|
+
[again, (kept[-1]["counts"] if kept else None), tree_of(checkout)],
|
|
920
|
+
["", {"items": 2, "effects": 2, "applied": 0, "done_before": 2, "files": 2}, ["claude/guides/g.md"]])
|
|
921
|
+
with open(run_dir / JOURNAL, "ab") as handle:
|
|
922
|
+
handle.write(b"not a journal line\n")
|
|
923
|
+
control("a journal that does not parse is refused on a re-run, even when every write is already done",
|
|
924
|
+
code(lambda: run(run_dir)), "APPLY_JOURNAL_CORRUPT")
|
|
925
|
+
section('the apply of a confirmed set (section)', scenario_1)
|
|
926
|
+
|
|
927
|
+
def scenario_2():
|
|
928
|
+
base, run_dir, checkout = confirmed("moved")
|
|
929
|
+
(checkout / "claude/guides/k.md").write_bytes(b"# K\n\nchanged by the owner\n")
|
|
930
|
+
control("a file that moved after the proposal is refused before ANY write: the create is not made either",
|
|
931
|
+
[code(lambda: run(run_dir)), tree_of(checkout), (run_dir / JOURNAL).exists()],
|
|
932
|
+
["APPLY_BEFORE_MISMATCH", ["claude/guides/k.md"], False])
|
|
933
|
+
section('a file that moved after the proposal (section)', scenario_2)
|
|
934
|
+
|
|
935
|
+
def scenario_3():
|
|
936
|
+
base, run_dir, checkout = confirmed("edited")
|
|
937
|
+
manifest = run_dir / stage_confirm.manifest_rel(1)
|
|
938
|
+
manifest.write_text(manifest.read_text(encoding="utf-8").replace("k-place", "k-other"), encoding="utf-8")
|
|
939
|
+
control("a manifest edited after the confirmation is refused before anything is read from it",
|
|
940
|
+
[code(lambda: run(run_dir)), tree_of(checkout)],
|
|
941
|
+
["INPUT_INVALID", ["claude/guides/k.md"]])
|
|
942
|
+
section('a manifest edited after the confirmation (section)', scenario_3)
|
|
943
|
+
|
|
944
|
+
def scenario_4():
|
|
945
|
+
base, run_dir, checkout = confirmed("linked")
|
|
946
|
+
(checkout / "claude/guides/k.md").unlink()
|
|
947
|
+
(base / "elsewhere.md").write_bytes(K)
|
|
948
|
+
os.symlink(base / "elsewhere.md", checkout / "claude/guides/k.md")
|
|
949
|
+
control("a target that became a link is refused by the target contract, with nothing written",
|
|
950
|
+
[bool(refusal(lambda: run(run_dir))), (base / "elsewhere.md").read_bytes(),
|
|
951
|
+
(checkout / "claude/guides/g.md").exists()], [True, K, False])
|
|
952
|
+
section('a target that became a link (section)', scenario_4)
|
|
953
|
+
|
|
954
|
+
def scenario_5():
|
|
955
|
+
base, run_dir, checkout = confirmed("global", place="claude/CLAUDE.md")
|
|
956
|
+
control("an addition to the always-loaded file that S7b did not judge a faithful merge is refused, "
|
|
957
|
+
"with nothing written",
|
|
958
|
+
[code(lambda: run(run_dir)), tree_of(checkout)],
|
|
959
|
+
["GLOBAL_OP_UNJUDGED", ["claude/guides/k.md"]])
|
|
960
|
+
section('an unjudged addition to the always-loaded file (section)', scenario_5)
|
|
961
|
+
|
|
962
|
+
def scenario_6():
|
|
963
|
+
base, run_dir, checkout = confirmed("cut")
|
|
964
|
+
real_take = Checkout.take
|
|
965
|
+
|
|
966
|
+
def cut(self, effect):
|
|
967
|
+
if effect["path"].endswith("k.md"):
|
|
968
|
+
raise Refused("FIXTURE_CUT the write did not end")
|
|
969
|
+
return real_take(self, effect)
|
|
970
|
+
Checkout.take = cut
|
|
971
|
+
try:
|
|
972
|
+
first = code(lambda: run(run_dir))
|
|
973
|
+
finally:
|
|
974
|
+
Checkout.take = real_take
|
|
975
|
+
second = refusal(lambda: run(run_dir))
|
|
976
|
+
control("a write that did not end is not run again: the re-run names the file and the state it is at",
|
|
977
|
+
[first, second.split(":")[0], "its before-state" in second, (checkout / "claude/guides/k.md").exists()],
|
|
978
|
+
["FIXTURE_CUT", "APPLY_UNRECONCILED claude/guides/k.md", True, True])
|
|
979
|
+
section('a write that did not end (section)', scenario_6)
|
|
980
|
+
|
|
981
|
+
def scenario_6b():
|
|
982
|
+
# a completed prefix, then the REMAINING effect changed with its record made to agree: refused, and
|
|
983
|
+
# refused again - the refusal itself must not become the next attempt's authority
|
|
984
|
+
base, run_dir, checkout = confirmed("prefix")
|
|
985
|
+
real_take, calls = Checkout.take, []
|
|
986
|
+
|
|
987
|
+
def stop_after_first(self, effect):
|
|
988
|
+
calls.append(effect["path"])
|
|
989
|
+
if len(calls) == 2:
|
|
990
|
+
raise Refused("FIXTURE_STOP before the second effect")
|
|
991
|
+
return real_take(self, effect)
|
|
992
|
+
Checkout.take = stop_after_first
|
|
993
|
+
try:
|
|
994
|
+
first = code(lambda: run(run_dir))
|
|
995
|
+
finally:
|
|
996
|
+
Checkout.take = real_take
|
|
997
|
+
# the second effect was planned and not done, so the journal's last record is taken back as a real
|
|
998
|
+
# stop before it would have left it: a completed prefix and nothing after
|
|
999
|
+
lines = (run_dir / JOURNAL).read_bytes().split(b"\n")
|
|
1000
|
+
(run_dir / JOURNAL).write_bytes(b"\n".join(lines[:2]) + b"\n")
|
|
1001
|
+
held = records.read_json(run_dir / PLAN)
|
|
1002
|
+
original = (run_dir / PLAN).read_bytes()
|
|
1003
|
+
changed = dict(held["effects"][1])
|
|
1004
|
+
changed.update(type=held["effects"][1]["type"], data_b64=base64.b64encode(b"UNAPPROVED").decode("ascii"),
|
|
1005
|
+
after=sha_of(b"UNAPPROVED"))
|
|
1006
|
+
changed["operation_id"] = operation_id(held["confirmation_id"], changed, 1)
|
|
1007
|
+
(run_dir / PLAN).write_text(json.dumps({**held, "effects": [held["effects"][0], changed]}),
|
|
1008
|
+
encoding="utf-8")
|
|
1009
|
+
record_file = records.record_path(run_dir, STAGE)
|
|
1010
|
+
doc = json.loads(record_file.read_bytes())
|
|
1011
|
+
for output in doc["parts"][PLAN_PART]["outputs"]:
|
|
1012
|
+
if output["artifact"] == PLAN:
|
|
1013
|
+
output["sha256"] = records.sha256_file(run_dir / PLAN)
|
|
1014
|
+
record_file.write_text(json.dumps(doc), encoding="utf-8")
|
|
1015
|
+
before_tree = {str(p.relative_to(checkout)): p.read_bytes() for p in checkout.rglob("*") if p.is_file()}
|
|
1016
|
+
answers = [code(lambda: run(run_dir)), code(lambda: run(run_dir)), code(lambda: run(run_dir))]
|
|
1017
|
+
control("after a completed prefix, a changed remainder is refused on every retry: a refused attempt does "
|
|
1018
|
+
"not become the next one's authority, and nothing more is written",
|
|
1019
|
+
[first, [a in ("PLAN_CHANGED", "PLAN_EFFECT_UNCONFIRMED", "APPLY_JOURNAL_FOREIGN") for a in answers],
|
|
1020
|
+
len(set(answers)),
|
|
1021
|
+
{str(p.relative_to(checkout)): p.read_bytes() for p in checkout.rglob("*") if p.is_file()}
|
|
1022
|
+
== before_tree, records.read_json(run_dir / COMMITMENT)["plan_sha256"]
|
|
1023
|
+
== hashlib.sha256(original).hexdigest()],
|
|
1024
|
+
["FIXTURE_STOP", [True, True, True], 1, True, True])
|
|
1025
|
+
section('a changed remainder after a completed prefix (section)', scenario_6b)
|
|
1026
|
+
|
|
1027
|
+
def scenario_7():
|
|
1028
|
+
base, run_dir, checkout = confirmed("planted")
|
|
1029
|
+
plan(run_dir)
|
|
1030
|
+
held = records.read_json(run_dir / PLAN)
|
|
1031
|
+
foreign = {"item_id": "k-place", "approval_id": held["effects"][0]["approval_id"], "operation": 0,
|
|
1032
|
+
"type": "create", "path": "unapproved.md", "before": ABSENT, "after": sha_of(b"FOREIGN"),
|
|
1033
|
+
"data_b64": base64.b64encode(b"FOREIGN").decode("ascii")}
|
|
1034
|
+
foreign["operation_id"] = operation_id(held["confirmation_id"], foreign, 0)
|
|
1035
|
+
original = (run_dir / PLAN).read_bytes()
|
|
1036
|
+
answers = []
|
|
1037
|
+
for effects in ([foreign], []):
|
|
1038
|
+
(run_dir / PLAN).write_text(json.dumps({**held, "effects": effects}), encoding="utf-8")
|
|
1039
|
+
answers.append(code(lambda: run(run_dir)))
|
|
1040
|
+
control("a plan changed after it was recorded - an unapproved file put in, the approved effects taken "
|
|
1041
|
+
"out - is refused before any write: the effects part reads the plan the plan part recorded",
|
|
1042
|
+
[answers, tree_of(checkout), (run_dir / JOURNAL).exists()],
|
|
1043
|
+
[["INPUT_INVALID", "INPUT_INVALID"], ["claude/guides/k.md"], False])
|
|
1044
|
+
# ... and when the record is made to agree with the planted plan, what the plan SAYS is still held
|
|
1045
|
+
# to the confirmed set
|
|
1046
|
+
(run_dir / PLAN).write_text(json.dumps({**held, "effects": [foreign]}), encoding="utf-8")
|
|
1047
|
+
record_file = records.record_path(run_dir, STAGE)
|
|
1048
|
+
record_held = record_file.read_bytes()
|
|
1049
|
+
doc = json.loads(record_held)
|
|
1050
|
+
for output in doc["parts"][PLAN_PART]["outputs"]:
|
|
1051
|
+
output["sha256"] = records.sha256_file(run_dir / PLAN)
|
|
1052
|
+
record_file.write_text(json.dumps(doc), encoding="utf-8")
|
|
1053
|
+
control("a planted plan whose record was made to agree is refused by what it says: its effect is not "
|
|
1054
|
+
"the confirmed set's",
|
|
1055
|
+
[code(lambda: run(run_dir)), tree_of(checkout), (run_dir / JOURNAL).exists()],
|
|
1056
|
+
["PLAN_EFFECT_UNCONFIRMED", ["claude/guides/k.md"], False])
|
|
1057
|
+
answers = []
|
|
1058
|
+
for effects in ([], held["effects"][:1], list(reversed(held["effects"]))):
|
|
1059
|
+
(run_dir / PLAN).write_text(json.dumps({**held, "effects": effects}), encoding="utf-8")
|
|
1060
|
+
doc = json.loads(record_held)
|
|
1061
|
+
for output in doc["parts"][PLAN_PART]["outputs"]:
|
|
1062
|
+
output["sha256"] = records.sha256_file(run_dir / PLAN)
|
|
1063
|
+
record_file.write_text(json.dumps(doc), encoding="utf-8")
|
|
1064
|
+
answers.append(code(lambda: run(run_dir)))
|
|
1065
|
+
control("a plan that is empty, a subset or a reordering of the confirmed set's - each row valid - is "
|
|
1066
|
+
"refused: the confirmed operations planned again must give this plan whole",
|
|
1067
|
+
[answers, tree_of(checkout), (run_dir / JOURNAL).exists()],
|
|
1068
|
+
[["PLAN_NOT_THE_CONFIRMED_SET", "PLAN_NOT_THE_CONFIRMED_SET", "PLAN_CHANGED"],
|
|
1069
|
+
["claude/guides/k.md"], False])
|
|
1070
|
+
record_file.write_bytes(record_held)
|
|
1071
|
+
(run_dir / PLAN).write_bytes(original)
|
|
1072
|
+
real_bound = globals()["_bound"]
|
|
1073
|
+
|
|
1074
|
+
def swapped_after_admission(*args):
|
|
1075
|
+
(run_dir / PLAN).write_text(json.dumps({**held, "effects": [foreign]}), encoding="utf-8")
|
|
1076
|
+
return real_bound(*args)
|
|
1077
|
+
globals()["_bound"] = swapped_after_admission
|
|
1078
|
+
try:
|
|
1079
|
+
after_admission = code(lambda: run(run_dir))
|
|
1080
|
+
finally:
|
|
1081
|
+
globals()["_bound"] = real_bound
|
|
1082
|
+
control("plan bytes replaced AFTER the part was admitted are not the bytes admission checked",
|
|
1083
|
+
[after_admission, tree_of(checkout)], ["PLAN_CHANGED", ["claude/guides/k.md"]])
|
|
1084
|
+
(run_dir / PLAN).write_bytes(original)
|
|
1085
|
+
control("and the recorded plan, put back, applies", [refusal(lambda: run(run_dir)), tree_of(checkout)],
|
|
1086
|
+
["", ["claude/guides/g.md"]])
|
|
1087
|
+
section('a plan changed after it was recorded (section)', scenario_7)
|
|
1088
|
+
|
|
1089
|
+
def scenario_7b():
|
|
1090
|
+
base, run_dir, checkout = confirmed("spelled", place="Claude/guides/g.md")
|
|
1091
|
+
said_all = refusal(lambda: run(run_dir))
|
|
1092
|
+
control("a confirmed set whose paths spell one directory two ways is refused before any write",
|
|
1093
|
+
["APPLY_SPELLING_CONFLICT claude and Claude" in said_all
|
|
1094
|
+
or "APPLY_SPELLING_CONFLICT Claude and claude" in said_all, tree_of(checkout)],
|
|
1095
|
+
[True, ["claude/guides/k.md"]])
|
|
1096
|
+
section('two spellings of one directory in a confirmed set (section)', scenario_7b)
|
|
1097
|
+
|
|
1098
|
+
def scenario_8():
|
|
1099
|
+
items = [{"item_id": "i1", "approval_id": "P-1", "operations": [
|
|
1100
|
+
{"type": "create", "target": "a.md", "before_state_sha256": ABSENT, "content": "one\n"},
|
|
1101
|
+
{"type": "edit", "target": "a.md", "before_state_sha256": ABSENT, "content": "two\n"}]}]
|
|
1102
|
+
# the second operation is held to the state the proposal read, so plan each alone and join them
|
|
1103
|
+
effects = [{"item_id": "i1", "approval_id": "P-1", "operation": 0, "type": "create", "path": "a.md",
|
|
1104
|
+
"before": ABSENT, "after": sha_of(b"one\n"), "data": b"one\n"},
|
|
1105
|
+
{"item_id": "i1", "approval_id": "P-1", "operation": 1, "type": "edit", "path": "a.md",
|
|
1106
|
+
"before": sha_of(b"one\n"), "after": sha_of(b"two\n"), "data": b"two\n"}]
|
|
1107
|
+
good = _plan_doc("C-1", effects)
|
|
1108
|
+
|
|
1109
|
+
def changed(index, **over):
|
|
1110
|
+
rows = [dict(r) for r in good["effects"]]
|
|
1111
|
+
rows[index].update(over)
|
|
1112
|
+
return [p.split()[0] for p in plan_problems({**good, "effects": rows}, "C-1", items)]
|
|
1113
|
+
control("a plan read back is held to the confirmed set: the item and its approval, the operation, a path "
|
|
1114
|
+
"that operation names, the bytes, the operation id, and each file's chain",
|
|
1115
|
+
[plan_problems(good, "C-1", items),
|
|
1116
|
+
[p.split()[0] for p in plan_problems(good, "C-2", items)],
|
|
1117
|
+
changed(0, item_id="other"), changed(0, approval_id="P-9"), changed(0, operation=7),
|
|
1118
|
+
changed(0, path="b.md"), changed(0, type="delete"),
|
|
1119
|
+
changed(0, data_b64=base64.b64encode(b"FOREIGN").decode("ascii")),
|
|
1120
|
+
changed(1, before=ABSENT), changed(0, data_b64="!")],
|
|
1121
|
+
[[], ["PLAN_UNBOUND"], ["PLAN_EFFECT_UNCONFIRMED"], ["PLAN_EFFECT_UNCONFIRMED"],
|
|
1122
|
+
["PLAN_EFFECT_UNCONFIRMED"], ["PLAN_EFFECT_UNCONFIRMED"], ["PLAN_EFFECT_UNCONFIRMED"],
|
|
1123
|
+
["PLAN_CHANGED"], ["PLAN_CHANGED", "PLAN_CHANGED"], ["PLAN_CHANGED"]])
|
|
1124
|
+
planned_rows = _effects_in(good)
|
|
1125
|
+
row = journal.planned(planned_rows[0]["operation_id"], "a.md", ABSENT, sha_of(b"one\n"), "i1", "P-1")
|
|
1126
|
+
second_row = journal.planned(planned_rows[1]["operation_id"], "a.md", sha_of(b"one\n"), sha_of(b"two\n"),
|
|
1127
|
+
"i1", "P-1")
|
|
1128
|
+
control("a journal is this plan's only when every record it holds is one of the plan's effects",
|
|
1129
|
+
[journal_problems({"records": [row]}, planned_rows),
|
|
1130
|
+
[p.split()[0] for p in journal_problems({"records": [second_row, {**second_row, "kind": "done"},
|
|
1131
|
+
row, {**row, "kind": "done"}]},
|
|
1132
|
+
planned_rows)], # two completed pairs, swapped
|
|
1133
|
+
[p.split()[0] for p in journal_problems({"records": [row, second_row, {**second_row, "kind": "done"},
|
|
1134
|
+
{**row, "kind": "done"}]},
|
|
1135
|
+
planned_rows)], # two effects interleaved
|
|
1136
|
+
journal_problems({"records": [row, {**row, "kind": "done"}, second_row]}, planned_rows),
|
|
1137
|
+
[p.split()[0] for p in journal_problems({"records": [{**row, "target": "b.md"}]}, planned_rows)],
|
|
1138
|
+
[p.split()[0] for p in journal_problems({"records": [{**row, "operation_id": "A-x"}]}, planned_rows)],
|
|
1139
|
+
[p.split()[0] for p in journal_problems({"records": [{**row, "kind": "done"}]}, planned_rows)],
|
|
1140
|
+
[p.split()[0] for p in journal_problems({"records": [{**row, "kind": "garbage"}]}, planned_rows)],
|
|
1141
|
+
[p.split()[0] for p in journal_problems({"records": [row, row]}, planned_rows)],
|
|
1142
|
+
[p.split()[0] for p in journal_problems({"records": [
|
|
1143
|
+
journal.planned(planned_rows[1]["operation_id"], "a.md", sha_of(b"one\n"), sha_of(b"two\n"),
|
|
1144
|
+
"i1", "P-1")]}, planned_rows)],
|
|
1145
|
+
journal_problems({"records": [row, {**row, "kind": "done"}]}, planned_rows),
|
|
1146
|
+
[p.split()[0] for p in journal_problems({"records": [], "torn": [1]}, planned_rows)],
|
|
1147
|
+
[p.split()[0] for p in journal_problems({"records": [], "problems": ["line 3"]}, planned_rows)]],
|
|
1148
|
+
[[], ["APPLY_JOURNAL_CORRUPT"], ["APPLY_JOURNAL_CORRUPT"], [],
|
|
1149
|
+
["APPLY_JOURNAL_FOREIGN"], ["APPLY_JOURNAL_FOREIGN"],
|
|
1150
|
+
["APPLY_JOURNAL_CORRUPT"], # a done record with no plan before it
|
|
1151
|
+
["APPLY_JOURNAL_CORRUPT"], # a kind this stage does not read
|
|
1152
|
+
["APPLY_JOURNAL_CORRUPT"], # a plan record twice
|
|
1153
|
+
["APPLY_JOURNAL_CORRUPT"], # the plan's second effect and not its first
|
|
1154
|
+
[], ["APPLY_JOURNAL_CORRUPT"], ["APPLY_JOURNAL_CORRUPT"]])
|
|
1155
|
+
section('a plan and a journal held to the confirmed set (section)', scenario_8)
|
|
1156
|
+
|
|
1157
|
+
def scenario_9():
|
|
1158
|
+
base, run_dir, checkout = confirmed("amended")
|
|
1159
|
+
real_take, calls, during = Checkout.take, [], []
|
|
1160
|
+
|
|
1161
|
+
def amend_during(self, effect):
|
|
1162
|
+
calls.append(effect["path"])
|
|
1163
|
+
if len(calls) == 1:
|
|
1164
|
+
try:
|
|
1165
|
+
declare.amend(run_dir, [("budget.per_stage.S8", 10_000)], "an amendment while S11 writes",
|
|
1166
|
+
scope=["S8"])
|
|
1167
|
+
during.append("the amendment landed")
|
|
1168
|
+
except stagelock.Locked as exc:
|
|
1169
|
+
during.append((str(exc).split() or [""])[0])
|
|
1170
|
+
return real_take(self, effect)
|
|
1171
|
+
Checkout.take = amend_during
|
|
1172
|
+
try:
|
|
1173
|
+
answer = refusal(lambda: run(run_dir))
|
|
1174
|
+
finally:
|
|
1175
|
+
Checkout.take = real_take
|
|
1176
|
+
control("an amendment cannot land DURING a write: the declaration's lock is held from the check through "
|
|
1177
|
+
"the effect, so the amendment is refused and the apply ends on the declaration it began on",
|
|
1178
|
+
[during, answer, len(calls), (run_dir / OUTPUT).exists()], [["STAGE_LOCKED"], "", 2, True])
|
|
1179
|
+
base, run_dir, checkout = confirmed("amended-between")
|
|
1180
|
+
real_read, done = journal.read, []
|
|
1181
|
+
|
|
1182
|
+
def amend_after_admission(path):
|
|
1183
|
+
if not done:
|
|
1184
|
+
done.append(declare.amend(run_dir, [("budget.per_stage.S8", 10_000)],
|
|
1185
|
+
"an amendment after S11 was admitted", scope=["S8"]))
|
|
1186
|
+
return real_read(path)
|
|
1187
|
+
journal.read = amend_after_admission
|
|
1188
|
+
try:
|
|
1189
|
+
answer = code(lambda: run(run_dir))
|
|
1190
|
+
finally:
|
|
1191
|
+
journal.read = real_read
|
|
1192
|
+
control("an amendment that landed after admission stops the effects: no file is written",
|
|
1193
|
+
[answer, tree_of(checkout), (run_dir / OUTPUT).exists()],
|
|
1194
|
+
["DECLARATION_MOVED", ["claude/guides/k.md"], False])
|
|
1195
|
+
base, run_dir, checkout = confirmed("amended-last")
|
|
1196
|
+
real_journalled, seen = journal.journalled, []
|
|
1197
|
+
|
|
1198
|
+
def amend_after_last(path, record, root, effect):
|
|
1199
|
+
out = real_journalled(path, record, root, effect)
|
|
1200
|
+
seen.append(record["operation_id"])
|
|
1201
|
+
return out
|
|
1202
|
+
real_held = globals()["_held_declaration"]
|
|
1203
|
+
|
|
1204
|
+
def moved_before_the_end(directory, admitted):
|
|
1205
|
+
if len(seen) == 2: # both effects are done; the check before the stage says complete
|
|
1206
|
+
raise Refused("DECLARATION_MOVED S11: (fixture) the declaration moved before the end")
|
|
1207
|
+
return real_held(directory, admitted)
|
|
1208
|
+
journal.journalled = amend_after_last
|
|
1209
|
+
globals()["_held_declaration"] = moved_before_the_end
|
|
1210
|
+
try:
|
|
1211
|
+
answer = code(lambda: run(run_dir))
|
|
1212
|
+
finally:
|
|
1213
|
+
journal.journalled = real_journalled
|
|
1214
|
+
globals()["_held_declaration"] = real_held
|
|
1215
|
+
control("the declaration is held once more before the stage says it is complete",
|
|
1216
|
+
[answer, len(seen), (run_dir / OUTPUT).exists()], ["DECLARATION_MOVED", 2, False])
|
|
1217
|
+
section('an amendment while the effects run (section)', scenario_9)
|
|
1218
|
+
|
|
1219
|
+
def scenario_10():
|
|
1220
|
+
base = pathlib.Path(tempfile.mkdtemp(prefix="s11-staging-"))
|
|
1221
|
+
made.append(base)
|
|
1222
|
+
checkout = base / "checkout"
|
|
1223
|
+
checkout.mkdir()
|
|
1224
|
+
(checkout / "a.md").write_bytes(b"planned from\n")
|
|
1225
|
+
effect = {"path": "a.md", "data": b"planned\n", "before": sha_of(b"planned from\n"),
|
|
1226
|
+
"after": sha_of(b"planned\n")}
|
|
1227
|
+
real_state, real_named, seen = Checkout._state, Checkout._named, []
|
|
1228
|
+
|
|
1229
|
+
def owner_writes_during_staging(self, parent, leaf, path):
|
|
1230
|
+
seen.append(leaf)
|
|
1231
|
+
if len(seen) == 2: # the check that follows the staging
|
|
1232
|
+
(checkout / "a.md").write_bytes(b"OWNER CHANGED\n")
|
|
1233
|
+
return real_state(self, parent, leaf, path)
|
|
1234
|
+
Checkout._state = owner_writes_during_staging
|
|
1235
|
+
try:
|
|
1236
|
+
with Checkout(checkout) as tree:
|
|
1237
|
+
first = code(lambda: tree.take(effect))
|
|
1238
|
+
finally:
|
|
1239
|
+
Checkout._state = real_state
|
|
1240
|
+
control("a target changed while the new bytes were being staged is not overwritten, and no temporary is "
|
|
1241
|
+
"left beside it",
|
|
1242
|
+
[first, (checkout / "a.md").read_bytes(), sorted(p.name for p in checkout.iterdir())],
|
|
1243
|
+
["APPLY_BEFORE_MISMATCH", b"OWNER CHANGED\n", ["a.md"]])
|
|
1244
|
+
(checkout / "a.md").write_bytes(b"planned from\n")
|
|
1245
|
+
seen.clear()
|
|
1246
|
+
|
|
1247
|
+
def staged_file_changed_in_place(self, parent, leaf, path):
|
|
1248
|
+
seen.append(leaf)
|
|
1249
|
+
if len(seen) == 2:
|
|
1250
|
+
for held_temp in checkout.glob(".a.md.s11-*.tmp"):
|
|
1251
|
+
with open(held_temp, "r+b") as handle: # the same inode, other bytes
|
|
1252
|
+
handle.write(b"NOT PLANNED")
|
|
1253
|
+
return real_state(self, parent, leaf, path)
|
|
1254
|
+
Checkout._state = staged_file_changed_in_place
|
|
1255
|
+
try:
|
|
1256
|
+
with Checkout(checkout) as tree:
|
|
1257
|
+
in_place = code(lambda: tree.take(effect))
|
|
1258
|
+
finally:
|
|
1259
|
+
Checkout._state = real_state
|
|
1260
|
+
control("a staged file changed in place before the rename is not installed: its bytes are read back "
|
|
1261
|
+
"through the descriptor that wrote them",
|
|
1262
|
+
[in_place, (checkout / "a.md").read_bytes(), sorted(p.name for p in checkout.iterdir())],
|
|
1263
|
+
["APPLY_STAGING_MOVED", b"planned from\n", ["a.md"]])
|
|
1264
|
+
|
|
1265
|
+
(checkout / "a.md").write_bytes(b"planned from\n")
|
|
1266
|
+
seen.clear()
|
|
1267
|
+
|
|
1268
|
+
def name_given_to_a_rival(self, parent, leaf, path):
|
|
1269
|
+
seen.append(leaf)
|
|
1270
|
+
held_state = real_state(self, parent, leaf, path) # the OLD file's bytes, read to the end
|
|
1271
|
+
if len(seen) == 2:
|
|
1272
|
+
(checkout / "rival.md").write_bytes(b"RIVAL\n")
|
|
1273
|
+
os.replace(checkout / "rival.md", checkout / "a.md")
|
|
1274
|
+
return held_state
|
|
1275
|
+
Checkout._state = name_given_to_a_rival
|
|
1276
|
+
try:
|
|
1277
|
+
with Checkout(checkout) as tree:
|
|
1278
|
+
rival = code(lambda: tree.take(effect))
|
|
1279
|
+
finally:
|
|
1280
|
+
Checkout._state = real_state
|
|
1281
|
+
control("a rival file put under the target's name while the old one was being read is not overwritten",
|
|
1282
|
+
[rival, (checkout / "a.md").read_bytes(), sorted(p.name for p in checkout.iterdir())],
|
|
1283
|
+
["APPLY_BEFORE_MISMATCH", b"RIVAL\n", ["a.md"]])
|
|
1284
|
+
(checkout / "a.md").write_bytes(b"planned from\n")
|
|
1285
|
+
real_pread, reads = os.pread, []
|
|
1286
|
+
|
|
1287
|
+
def changed_during_the_scan(fd, length, offset):
|
|
1288
|
+
out = real_pread(fd, length, offset)
|
|
1289
|
+
if not reads:
|
|
1290
|
+
reads.append(True)
|
|
1291
|
+
for held_temp in checkout.glob(".a.md.s11-*.tmp"):
|
|
1292
|
+
with open(held_temp, "r+b") as handle:
|
|
1293
|
+
handle.write(b"XXXXXXX\n")
|
|
1294
|
+
return out
|
|
1295
|
+
os.pread = changed_during_the_scan
|
|
1296
|
+
try:
|
|
1297
|
+
with Checkout(checkout) as tree:
|
|
1298
|
+
during = code(lambda: tree.take(effect))
|
|
1299
|
+
finally:
|
|
1300
|
+
os.pread = real_pread
|
|
1301
|
+
control("a staged file changed WHILE it was being read back is not installed: the scan must have read "
|
|
1302
|
+
"a file standing still",
|
|
1303
|
+
[during, (checkout / "a.md").read_bytes(), sorted(p.name for p in checkout.iterdir())],
|
|
1304
|
+
["APPLY_STAGING_MOVED", b"planned from\n", ["a.md"]])
|
|
1305
|
+
with Checkout(checkout) as tree:
|
|
1306
|
+
absent_parent = code(lambda: tree.take({"path": "nodir/x.md", "data": b"x\n",
|
|
1307
|
+
"before": sha_of(b"was there\n"), "after": sha_of(b"x\n")}))
|
|
1308
|
+
control("a refused replacement leaves no directory behind: directories are made only for a file that "
|
|
1309
|
+
"is not there yet",
|
|
1310
|
+
[bool(absent_parent), sorted(p.name for p in checkout.iterdir())], [True, ["a.md"]])
|
|
1311
|
+
|
|
1312
|
+
def swapped(parent, name):
|
|
1313
|
+
if name.endswith(".tmp"):
|
|
1314
|
+
os.unlink(name, dir_fd=parent)
|
|
1315
|
+
handle = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644, dir_fd=parent)
|
|
1316
|
+
os.write(handle, b"NOT PLANNED\n")
|
|
1317
|
+
os.close(handle)
|
|
1318
|
+
return real_named(parent, name)
|
|
1319
|
+
Checkout._named = staticmethod(swapped)
|
|
1320
|
+
try:
|
|
1321
|
+
with Checkout(checkout) as tree:
|
|
1322
|
+
second = code(lambda: tree.take(effect))
|
|
1323
|
+
finally:
|
|
1324
|
+
Checkout._named = staticmethod(real_named)
|
|
1325
|
+
control("a temporary whose name was given to another file is not installed",
|
|
1326
|
+
[second, (checkout / "a.md").read_bytes(), sorted(p.name for p in checkout.iterdir())],
|
|
1327
|
+
["APPLY_STAGING_MOVED", b"planned from\n", ["a.md"]])
|
|
1328
|
+
# a FIFO where the file is named: asked on another thread and held to a deadline, so a blocking
|
|
1329
|
+
# open fails this control by name instead of hanging the suite
|
|
1330
|
+
import threading
|
|
1331
|
+
os.mkfifo(checkout / "pipe.md")
|
|
1332
|
+
answered = []
|
|
1333
|
+
|
|
1334
|
+
def ask():
|
|
1335
|
+
with Checkout(checkout) as tree:
|
|
1336
|
+
answered.append(code(lambda: tree.read("pipe.md")))
|
|
1337
|
+
asking = threading.Thread(target=ask, daemon=True)
|
|
1338
|
+
asking.start()
|
|
1339
|
+
asking.join(10)
|
|
1340
|
+
waited = asking.is_alive() # an answer that came only after the release is not "at once"
|
|
1341
|
+
if waited:
|
|
1342
|
+
released = os.open(checkout / "pipe.md", os.O_WRONLY | os.O_NONBLOCK)
|
|
1343
|
+
asking.join(10)
|
|
1344
|
+
os.close(released)
|
|
1345
|
+
control("a FIFO named as a target is refused at once: its open does not wait for a writer",
|
|
1346
|
+
[waited, answered[:1]], [False, ["APPLY_TARGET_NOT_FILE"]])
|
|
1347
|
+
(checkout / "Upper").mkdir()
|
|
1348
|
+
folds = (checkout / "UPPER").exists()
|
|
1349
|
+
with Checkout(checkout) as tree:
|
|
1350
|
+
alias = code(lambda: tree.take({"path": "upper/b.md", "data": b"b\n", "before": ABSENT,
|
|
1351
|
+
"after": sha_of(b"b\n")}))
|
|
1352
|
+
control("where the filesystem folds case, a write through another spelling of a directory is refused "
|
|
1353
|
+
"(where it does not, the directory is simply another one)",
|
|
1354
|
+
[alias, (checkout / "Upper" / "b.md").exists()],
|
|
1355
|
+
["APPLY_SPELLING_ON_DISK" if folds else "", False])
|
|
1356
|
+
section('the write itself: staging, a FIFO, a spelling (section)', scenario_10)
|
|
1357
|
+
|
|
1358
|
+
finally:
|
|
1359
|
+
for base in made:
|
|
1360
|
+
shutil.rmtree(base, ignore_errors=True)
|
|
1361
|
+
|
|
1362
|
+
source = pathlib.Path(__file__).read_text(encoding="utf-8")
|
|
1363
|
+
body = source.split("# ---- self-test ----")[0]
|
|
1364
|
+
control("the stage starts no process: its source names no subprocess, os.system, exec or spawn",
|
|
1365
|
+
[word for word in ("subprocess", "os.system", "os.exec", "os.spawn", "os.popen", "pty.")
|
|
1366
|
+
if word in body.split('"""', 2)[2]], [])
|
|
1367
|
+
reporting.append(True)
|
|
1368
|
+
|
|
1369
|
+
|
|
1370
|
+
def main(argv):
|
|
1371
|
+
if argv[1:] == ["--self-test"]:
|
|
1372
|
+
return self_test()
|
|
1373
|
+
print(__doc__)
|
|
1374
|
+
return 2
|
|
1375
|
+
|
|
1376
|
+
|
|
1377
|
+
if __name__ == "__main__":
|
|
1378
|
+
sys.exit(main(sys.argv))
|