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.
Files changed (172) hide show
  1. package/DEPENDENCIES.md +62 -20
  2. package/INSTALL.md +1 -1
  3. package/README.md +16 -21
  4. package/claude/agents/frontier.md +1 -1
  5. package/claude/agents/sweep.md +2 -1
  6. package/claude/agents/workhorse.md +2 -2
  7. package/claude/guides/claude-prompting.md +494 -167
  8. package/claude/guides/cli-multi-model-workflow.md +8 -7
  9. package/claude/guides/gpt-prompting.md +241 -111
  10. package/claude/guides/session-distill-workflow.md +93 -43
  11. package/claude/guides/tooling-gotchas.md +3 -1
  12. package/codex/agents/reviewer.toml +2 -2
  13. package/codex/agents/sweep.toml +1 -1
  14. package/codex/agents/workhorse.toml +2 -2
  15. package/codex/guides/claude-prompting.md +494 -167
  16. package/codex/guides/cli-multi-model-workflow.md +8 -7
  17. package/codex/guides/gpt-prompting.md +241 -111
  18. package/codex/guides/session-distill-workflow.md +93 -43
  19. package/codex/guides/tooling-gotchas.md +3 -1
  20. package/compose/assemble.py +4 -1
  21. package/compose/canary.sh +8 -6
  22. package/compose/host_platform.py +158 -15
  23. package/compose/instructions-state.py +183 -41
  24. package/compose/instructions_app.py +2 -2
  25. package/compose/instructions_install.py +222 -27
  26. package/compose/instructions_session.py +250 -75
  27. package/compose/instructions_setup.py +6 -6
  28. package/compose/instructions_setup_cli.py +2 -36
  29. package/compose/instructions_setup_i18n.py +3 -3
  30. package/compose/instructions_store.py +160 -3
  31. package/compose/instructions_transaction.py +29 -5
  32. package/compose/instructions_ui_runtime.py +2 -2
  33. package/compose/setup/START.md +1 -1
  34. package/docs/advanced-launch.md +4 -0
  35. package/docs/releases/0.19.4.md +99 -0
  36. package/docs/releases/0.20.0.md +102 -0
  37. package/docs/setup.md +4 -4
  38. package/install.sh +54 -20
  39. package/launch/agent-launch.py +171 -22
  40. package/launch/agent-launch.toml +64 -29
  41. package/launch/agent-launch.zsh +104 -13
  42. package/launch/claude_subcommands.py +179 -0
  43. package/launch/provision-venv.sh +1 -1
  44. package/launch/shell_integration.py +7 -1
  45. package/learn/collect-learning.py +60 -9
  46. package/learn/migrate-learnings.py +70 -4
  47. package/learn/redact.py +2 -1
  48. package/package.json +37 -4
  49. package/provenance.json +1 -1
  50. package/session-cost.py +141 -18
  51. package/session-distill/coverage.json +6 -0
  52. package/session-distill/distill.py +2575 -0
  53. package/session-distill/grammar/__init__.py +0 -0
  54. package/session-distill/grammar/owner_lines.py +874 -0
  55. package/session-distill/originators.json +9 -0
  56. package/session-distill/packets/cross_review.md +31 -0
  57. package/session-distill/packets/form.md +86 -0
  58. package/session-distill/packets/judge.md +81 -0
  59. package/session-distill/packets/placement_contract.md +90 -0
  60. package/session-distill/packets/propose.md +124 -0
  61. package/session-distill/packets/read.md +57 -0
  62. package/session-distill/packets/reconsider.md +53 -0
  63. package/session-distill/packets/s7b.md +65 -0
  64. package/session-distill/packets/s9b.md +39 -0
  65. package/session-distill/packets/stitch.md +35 -0
  66. package/session-distill/packets/sweep.md +33 -0
  67. package/session-distill/runlib/__init__.py +0 -0
  68. package/session-distill/runlib/bound.py +1102 -0
  69. package/session-distill/runlib/breaker.py +467 -0
  70. package/session-distill/runlib/census.py +2347 -0
  71. package/session-distill/runlib/claims.py +420 -0
  72. package/session-distill/runlib/controls.py +902 -0
  73. package/session-distill/runlib/coverage.py +881 -0
  74. package/session-distill/runlib/declare.py +888 -0
  75. package/session-distill/runlib/delivery_evidence.py +1145 -0
  76. package/session-distill/runlib/derive.py +812 -0
  77. package/session-distill/runlib/destinations.py +3072 -0
  78. package/session-distill/runlib/dispatch.py +7939 -0
  79. package/session-distill/runlib/drift.py +1077 -0
  80. package/session-distill/runlib/entry.py +401 -0
  81. package/session-distill/runlib/evidence.py +890 -0
  82. package/session-distill/runlib/exposure.py +1162 -0
  83. package/session-distill/runlib/gate.py +2727 -0
  84. package/session-distill/runlib/gitread.py +79 -0
  85. package/session-distill/runlib/inventory.py +19624 -0
  86. package/session-distill/runlib/journal.py +1919 -0
  87. package/session-distill/runlib/ledger.py +3210 -0
  88. package/session-distill/runlib/ledger_compat.py +101 -0
  89. package/session-distill/runlib/ledger_migration.py +190 -0
  90. package/session-distill/runlib/lifecycle_intake.py +693 -0
  91. package/session-distill/runlib/lineage.py +454 -0
  92. package/session-distill/runlib/measures.py +249 -0
  93. package/session-distill/runlib/monitor.py +1180 -0
  94. package/session-distill/runlib/operations.py +522 -0
  95. package/session-distill/runlib/packet.py +838 -0
  96. package/session-distill/runlib/placement.py +1769 -0
  97. package/session-distill/runlib/projection.py +4090 -0
  98. package/session-distill/runlib/ranking.py +740 -0
  99. package/session-distill/runlib/receipts.py +200 -0
  100. package/session-distill/runlib/records.py +1965 -0
  101. package/session-distill/runlib/search.py +249 -0
  102. package/session-distill/runlib/sequencing.py +829 -0
  103. package/session-distill/runlib/sources.py +641 -0
  104. package/session-distill/runlib/stage_adjudicate.py +845 -0
  105. package/session-distill/runlib/stage_apply.py +1378 -0
  106. package/session-distill/runlib/stage_approvals.py +758 -0
  107. package/session-distill/runlib/stage_close.py +1220 -0
  108. package/session-distill/runlib/stage_confirm.py +929 -0
  109. package/session-distill/runlib/stage_delivery.py +3080 -0
  110. package/session-distill/runlib/stage_form.py +2576 -0
  111. package/session-distill/runlib/stage_judge.py +4248 -0
  112. package/session-distill/runlib/stage_propose.py +3307 -0
  113. package/session-distill/runlib/stage_read.py +5179 -0
  114. package/session-distill/runlib/stage_render.py +2739 -0
  115. package/session-distill/runlib/stage_retrieve.py +924 -0
  116. package/session-distill/runlib/stage_review_korean.py +1002 -0
  117. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  118. package/session-distill/runlib/stagelock.py +412 -0
  119. package/session-distill/runlib/stop.py +1061 -0
  120. package/session-distill/runlib/targets.py +809 -0
  121. package/session-distill/runlib/usage.py +280 -0
  122. package/session-distill/runlib/validate.py +319 -0
  123. package/session-distill/runlib/views.py +4327 -0
  124. package/session-distill/schemas/adjudication.schema.json +35 -0
  125. package/session-distill/schemas/approval.schema.json +35 -0
  126. package/session-distill/schemas/census.schema.json +128 -0
  127. package/session-distill/schemas/checks.schema.json +207 -0
  128. package/session-distill/schemas/claim.schema.json +16 -0
  129. package/session-distill/schemas/confirmation.schema.json +24 -0
  130. package/session-distill/schemas/coverage.schema.json +66 -0
  131. package/session-distill/schemas/cross_review.schema.json +24 -0
  132. package/session-distill/schemas/event.schema.json +20 -0
  133. package/session-distill/schemas/evidence.schema.json +20 -0
  134. package/session-distill/schemas/expected_observation.schema.json +18 -0
  135. package/session-distill/schemas/form.schema.json +103 -0
  136. package/session-distill/schemas/intake.schema.json +71 -0
  137. package/session-distill/schemas/inventory.schema.json +872 -0
  138. package/session-distill/schemas/judge.schema.json +77 -0
  139. package/session-distill/schemas/ledger.schema.json +313 -0
  140. package/session-distill/schemas/observation.schema.json +16 -0
  141. package/session-distill/schemas/propose.schema.json +555 -0
  142. package/session-distill/schemas/read.schema.json +76 -0
  143. package/session-distill/schemas/reconsider.schema.json +122 -0
  144. package/session-distill/schemas/run.schema.json +150 -0
  145. package/session-distill/schemas/s7b.schema.json +200 -0
  146. package/session-distill/schemas/s9b.schema.json +28 -0
  147. package/session-distill/schemas/stitch.schema.json +25 -0
  148. package/session-distill/schemas/sweep.schema.json +25 -0
  149. package/session-distill/seats.json +149 -0
  150. package/session-distill/tables/allowed_pairs.json +257 -0
  151. package/session-distill/tables/controls.json +30 -0
  152. package/session-distill/tables/delivery_evidence.json +36 -0
  153. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  154. package/session-distill/tables/destinations.json +684 -0
  155. package/session-distill/tables/drift_layers.json +68 -0
  156. package/session-distill/tables/exposure_rules.json +192 -0
  157. package/session-distill/tables/placement_rules.json +148 -0
  158. package/session-distill/tables/propose_fixtures.json +154 -0
  159. package/session-distill/tables/ranking.json +194 -0
  160. package/session-distill/tables/redundancy.json +10 -0
  161. package/session-distill/tables/structural_rules.json +44 -0
  162. package/session-distill/tables/transition_fixtures.json +398 -0
  163. package/session-distill/tables/transitions.json +69 -0
  164. package/session-distill/tables/unit_outcome.json +67 -0
  165. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  166. package/wrappers/claude-run.sh +481 -33
  167. package/wrappers/claude_hermetic_evidence.py +1423 -0
  168. package/wrappers/codex-helm.sh +44 -13
  169. package/wrappers/codex-run.sh +183 -20
  170. package/wrappers/codex_frame_filter.py +1199 -0
  171. package/wrappers/codex_protocol.py +737 -0
  172. package/wrappers/jsonl_lines.py +65 -0
@@ -6,20 +6,73 @@ activation path: installed instructions are stored and verifiable, while a launc
6
6
  activation creates the per-session snapshot and pin.
7
7
  """
8
8
  from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ from pathlib import Path, PurePosixPath
13
+ from typing import Any
14
+
15
+ # The files this installer executes from its own tree, relative to that tree. The set is
16
+ # DECLARED rather than discovered because `launch/shell_integration.py` is loaded by path and
17
+ # never enters `sys.modules`, so a `sys.modules` walk would miss code that ran.
18
+ INSTALLER_CODE = ("compose/instructions_install.py", "compose/instructions_transaction.py",
19
+ "compose/host_platform.py", "launch/shell_integration.py")
20
+
21
+
22
+ def _sha256(path: Path) -> str:
23
+ digest = hashlib.sha256()
24
+ with path.open("rb") as source:
25
+ for chunk in iter(lambda: source.read(1024 * 1024), b""):
26
+ digest.update(chunk)
27
+ return digest.hexdigest()
28
+
29
+
30
+ def _canonical(value: Any) -> bytes:
31
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
32
+
33
+
34
+ def _installer_code() -> dict[str, Any]:
35
+ """Hash, from disk, the files this process runs its installer from (not the package it installs)."""
36
+ root = Path(__file__).resolve().parent.parent
37
+ files = []
38
+ for relative in INSTALLER_CODE:
39
+ try:
40
+ files.append({"path": relative, "sha256": _sha256(root / relative)})
41
+ except OSError:
42
+ files.append({"path": relative, "sha256": None}) # a layout without the file must not stop the installer
43
+ return {"root": str(root), "files": files, "digest": hashlib.sha256(_canonical(files)).hexdigest()}
44
+
45
+
46
+ def _installer_build() -> str | None:
47
+ """The version the installer's own tree declares, read at receipt time; None when it declares none.
48
+
49
+ The digest identifies the code; this names it the way a person reads a release. A checkout
50
+ between releases declares the version it last published, so the digest remains the identity.
51
+ """
52
+ try:
53
+ manifest = json.loads((Path(__file__).resolve().parent.parent / "package.json").read_text(encoding="utf-8"))
54
+ except (OSError, ValueError):
55
+ return None
56
+ version = manifest.get("version") if isinstance(manifest, dict) else None
57
+ return version if isinstance(version, str) and version else None
58
+
59
+
60
+ # Taken at import and deliberately BEFORE the sibling imports below: a declared file replaced
61
+ # after its own import (an npm or git update while a wizard is open) must read as a difference
62
+ # instead of being hashed into the receipt as if the new bytes had run.
63
+ _CODE_AT_START = _installer_code()
64
+
9
65
  try:
10
- from host_platform import WINDOWS, runtime_environment
66
+ from host_platform import WINDOWS, jsonl_lines_for, runtime_environment
11
67
  except ImportError:
12
- from .host_platform import WINDOWS, runtime_environment
68
+ from .host_platform import WINDOWS, jsonl_lines_for, runtime_environment
13
69
 
14
70
  import argparse
15
71
  import base64
16
72
  import contextlib
17
- import hashlib
18
73
  import importlib
19
74
  import importlib.util
20
- import json
21
75
  import os
22
- from pathlib import Path, PurePosixPath
23
76
  import re
24
77
  import shlex
25
78
  import shutil
@@ -28,7 +81,6 @@ import tempfile
28
81
  import time
29
82
  import tomllib
30
83
  import uuid
31
- from typing import Any
32
84
 
33
85
  if __name__ == "__main__":
34
86
  sys.dont_write_bytecode = True
@@ -48,6 +100,11 @@ from instructions_transaction import (
48
100
 
49
101
  SCHEMA_VERSION = 1
50
102
  PRIVATE_RECORD = "private-install.json"
103
+ RECEIPT_DIR = "receipts"
104
+ RECEIPT_SCHEMA = "InstallationReceipt/v1"
105
+ # A receipt's id is the sha256 of its canonical body and lives OUTSIDE the body — in the file name and
106
+ # in what `installation_binding()` returns — so no field of the body may carry it.
107
+ RECEIPT_RESERVED = ("receipt_id",)
51
108
  CENTRAL_START = "<!-- agent-bios:central:start -->"
52
109
  CENTRAL_END = "<!-- agent-bios:central:end -->"
53
110
  PERSONAL_START = "<!-- agent-bios:personal-learnings:start -->"
@@ -81,18 +138,6 @@ def _serialized(method):
81
138
  return wrapped
82
139
 
83
140
 
84
- def _sha256(path: Path) -> str:
85
- digest = hashlib.sha256()
86
- with path.open("rb") as source:
87
- for chunk in iter(lambda: source.read(1024 * 1024), b""):
88
- digest.update(chunk)
89
- return digest.hexdigest()
90
-
91
-
92
- def _canonical(value: Any) -> bytes:
93
- return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
94
-
95
-
96
141
  def _atomic_bytes(path: Path, data: bytes, mode: int | None = None) -> None:
97
142
  path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
98
143
  if path.is_symlink():
@@ -138,6 +183,55 @@ def _relative(value: str, label: str) -> str:
138
183
  return path.as_posix()
139
184
 
140
185
 
186
+ # The ONLY `files[]` negations this package supports, as literal spellings.
187
+ #
188
+ # A negation is npm's one honoured exclusion once `files[]` exists, and it excludes from the
189
+ # TARBALL — not from this installer, which applies `_is_bytecode` below, and not from the gates,
190
+ # which scan what the tarball carries. Review Y r2 #2 showed what that difference costs: adding
191
+ # `!README.md` removed README from the content and endpoint scans while npm force-included the
192
+ # file anyway, so a forbidden identifier and a live endpoint in it became invisible with no
193
+ # payload disagreement to notice. A negation can only be safe where every path it can exclude is
194
+ # bytecode, and whether an arbitrary pattern has that property is not decidable by inspection —
195
+ # so the supported set is enumerated instead, and `gates/check-package.sh` refuses any other
196
+ # (`FILES_NEGATION_UNSUPPORTED`). This tuple is the authority the gates import; nothing re-models it.
197
+ SUPPORTED_NEGATIONS = (
198
+ "__pycache__", "__pycache__/", "__pycache__/**",
199
+ "**/__pycache__", "**/__pycache__/**",
200
+ "*.pyc", "**/*.pyc", "*.pyo", "**/*.pyo",
201
+ )
202
+
203
+
204
+ def negation_supported(entry: str) -> bool:
205
+ """Whether a `files[]` entry is a negation this package supports (bytecode, and nothing else)."""
206
+ if not isinstance(entry, str) or not entry.startswith("!"):
207
+ return False
208
+ return entry[1:].strip() in SUPPORTED_NEGATIONS
209
+
210
+
211
+ def _is_bytecode(relative: str) -> bool:
212
+ """Compiled Python, which is the author's and never the package's.
213
+
214
+ One predicate for every way a path can enter the payload — an explicit `files[]` entry and a
215
+ child of a listed directory alike. It was only on the directory branch, so naming a `.pyc`
216
+ outright still put it in the release inventory and in the release digest (review Y #4).
217
+
218
+ Skipped rather than refused: the author cannot be asked to clear a cache before every install,
219
+ the source beside it is the payload, and a stale `.pyc` shadowing source it no longer matches is
220
+ the worst shape to hand a user.
221
+
222
+ `.pyo` is here because SUPPORTED_NEGATIONS already admits `!*.pyo` and `!**/*.pyo`: an
223
+ allowlist that accepts a spelling this predicate cannot recognise is a pair that disagrees, and
224
+ `gates/check-package.sh` asks npm whether the two agree.
225
+
226
+ Uppercase `.PYC` is NOT covered, deliberately. Nothing in this toolchain writes one — CPython
227
+ writes lowercase names into `__pycache__` — and npm matches a `files[]` pattern
228
+ case-sensitively, so `!**/*.pyc` would not exclude one either. Both sides therefore give the
229
+ same answer about it, which is what the npm leg checks; teaching one side alone would be the
230
+ divergence. The day something produces such a file, both sides learn it together."""
231
+ parts = PurePosixPath(relative).parts
232
+ return relative.endswith((".pyc", ".pyo")) or "__pycache__" in parts
233
+
234
+
141
235
  def _inside(path: Path, root: Path) -> bool:
142
236
  try:
143
237
  path.absolute().relative_to(root.absolute())
@@ -264,10 +358,31 @@ class InstructionsInstaller:
264
358
  if not isinstance(listed, list) or not listed:
265
359
  raise InstallError("package.json files must declare the private runtime payload")
266
360
  paths: set[str] = {"package.json"} # npm includes this manifest even when files[] omits it.
267
- prohibited = ("gates/", "design/", "benchmarks/", "research/", "packages/", "session-distill/")
361
+ # NEGATED entries (`!pattern`) are npm's exclusions, and they are why they exist here at
362
+ # all: with `files[]` present npm-packlist nulls the root `.npmignore`, so the one place a
363
+ # cache can be excluded from the TARBALL is `files[]` itself (measured on npm 12.0.2:
364
+ # 226 entries with the caches, 224 without). This installer does not implement npm's
365
+ # pattern language — it applies its own cache rule below, and `gates/check-package.sh`
366
+ # holds the two expansions equal against `npm pack --dry-run --json`, so a negation that
367
+ # excludes anything else is a gate failure rather than a silent divergence.
368
+ listed = [entry for entry in listed
369
+ if not (isinstance(entry, str) and entry.startswith("!"))]
370
+ if not listed:
371
+ raise InstallError("package.json files declares only exclusions, so it promises no payload")
372
+ # The driver (`session-distill/`) is runtime payload since WP-24: a private install stores it
373
+ # like `wrappers/` or `session-cost.py`, because a user who cannot run it cannot distill
374
+ # their own sessions. The author-side trees stay refused by name — a release carrying
375
+ # `gates/` would ship this repo's own judgement machinery to every adopter.
376
+ #
377
+ # Compared on the FIRST SEGMENT of the normalised path, not as a prefix with a slash.
378
+ # `_relative` strips the trailing slash, so `"gates/"` arrived here as `"gates"` and
379
+ # `startswith("gates/")` was false: the check fired only for an entry naming a file inside
380
+ # one of these trees, and never for the directory entry that packs the whole tree — the one
381
+ # shape npm actually uses. The refusal existed and could not fire where it mattered.
382
+ prohibited = ("gates", "design", "benchmarks", "research", "packages")
268
383
  for raw in listed:
269
384
  relative = _relative(raw, "package files entry")
270
- if relative.startswith(prohibited):
385
+ if relative.split("/", 1)[0] in prohibited:
271
386
  raise InstallError(f"author-only path is not a private runtime payload: {relative}")
272
387
  source = self.repo / relative
273
388
  # npm's prepack stamps this author-side provenance receipt. A
@@ -278,6 +393,8 @@ class InstructionsInstaller:
278
393
  if source.is_symlink() or not source.exists():
279
394
  raise InstallError(f"declared package file is missing or symlinked: {relative}")
280
395
  if source.is_file():
396
+ if _is_bytecode(relative):
397
+ continue
281
398
  paths.add(relative)
282
399
  continue
283
400
  if not source.is_dir():
@@ -289,6 +406,8 @@ class InstructionsInstaller:
289
406
  child_relative = child.relative_to(self.repo).as_posix()
290
407
  if "/test_" in child_relative or child_relative.startswith("tests/"):
291
408
  raise InstallError(f"test file is not a runtime payload: {child_relative}")
409
+ if _is_bytecode(child_relative):
410
+ continue
292
411
  paths.add(child_relative)
293
412
  return sorted(paths)
294
413
 
@@ -817,8 +936,12 @@ class InstructionsInstaller:
817
936
  launcher = {"path": str(owned[0][0]), "sha256": hashlib.sha256(owned[0][1]).hexdigest()}
818
937
  config = [{"path": str(path), "sha256": hashlib.sha256(content).hexdigest()}
819
938
  for path, content, _mode in owned[1:]]
939
+ # Derived before the record so the record can carry it: the receipt binds a snapshot to one
940
+ # transaction, and the store reaches the transaction through the record it installed.
941
+ transaction_id = str(candidate.get("transaction_id") or uuid.uuid4().hex)
820
942
  record = {
821
- "schema_version": SCHEMA_VERSION, "package_root": str(release), "release_digest": digest,
943
+ "schema_version": SCHEMA_VERSION, "transaction_id": transaction_id,
944
+ "package_root": str(release), "release_digest": digest,
822
945
  "installed_files": entries, "selection": requested, "baseline_ref": baseline_ref,
823
946
  "launcher": launcher, "config_files": config, "created_at": int(time.time()),
824
947
  "mode": "private-session-scoped", "needs_action": [],
@@ -838,7 +961,6 @@ class InstructionsInstaller:
838
961
  "before": self._file_version(self.state_root / "corpus-status.json"),
839
962
  "after": self._planned_version(self._launcher_status_bytes(release, requested)), "mode": 0o600},
840
963
  ])
841
- transaction_id = str(candidate.get("transaction_id") or uuid.uuid4().hex)
842
964
  journal = self._transaction_path(transaction_id)
843
965
  # Source candidates are persisted by InstructionsStore under the transaction
844
966
  # id. Keep only hashes here: personal source text is free-form and
@@ -850,7 +972,7 @@ class InstructionsInstaller:
850
972
  "source_after_sha256": hashlib.sha256(_canonical(candidate.get("after"))).hexdigest()}
851
973
  journal_data = {"schema_version": SCHEMA_VERSION, "owner": "installer", "kind": "install", "state": "PREPARED",
852
974
  "phase": "preflight", "candidate": association, "paths": paths,
853
- "created_at": int(time.time())}
975
+ "installer_digest": _CODE_AT_START["digest"], "created_at": int(time.time())}
854
976
  self._journal_write(journal, journal_data)
855
977
  try:
856
978
  with operation_scope(self.state_root):
@@ -891,9 +1013,82 @@ class InstructionsInstaller:
891
1013
  # The record/status are included in paths and now exact. Verify the
892
1014
  # installed source and every owned projection before success is visible.
893
1015
  self._verify_transaction_install(data)
1016
+ # The receipt is written after verification and before the COMMITTED marker, so a receipt
1017
+ # can exist without a commit (the install is then recovered) but never the reverse.
1018
+ # An earlier attempt's receipt id is dropped FIRST: a recovery whose own receipt is refused
1019
+ # must commit unbound, not carry forward a claim made by the installer that failed.
1020
+ data.pop("receipt_id", None)
1021
+ receipt_id = self._write_receipt(data)
1022
+ if receipt_id:
1023
+ data["receipt_id"] = receipt_id
894
1024
  data["state"], data["phase"], data["committed_at"] = "COMMITTED", "complete", int(time.time())
895
1025
  self._journal_write(journal, data)
896
1026
 
1027
+ def _loaded_package_modules(self, release: Path, hashes: dict[str, str]) -> list[dict[str, str]]:
1028
+ """Package modules that ran inside this installer process (the store, catalog, assembler and so on).
1029
+
1030
+ An old installer runs the NEW package's store and catalog, so exposure to a store or catalog
1031
+ change is read from here (or from the snapshot's digests), never from the installer digest.
1032
+ """
1033
+ found: dict[str, str] = {}
1034
+ for module in list(sys.modules.values()):
1035
+ location = getattr(module, "__file__", None)
1036
+ if not location:
1037
+ continue
1038
+ with contextlib.suppress(ValueError, OSError):
1039
+ relative = Path(location).resolve().relative_to(release.resolve()).as_posix()
1040
+ found[relative] = hashes.get(relative, "<not in release inventory>")
1041
+ return [{"path": path, "sha256": found[path]} for path in sorted(found)]
1042
+
1043
+ def _receipt_body(self, data: dict[str, Any], record: dict[str, Any], now: dict[str, Any]) -> dict[str, Any]:
1044
+ """The canonical receipt body. Its sha256 is the receipt id, which is why nothing here may carry one."""
1045
+ release = Path(record["package_root"])
1046
+ hashes = {entry["path"]: entry["sha256"] for entry in record["installed_files"]}
1047
+ begun_by = data.get("installer_digest")
1048
+ return {
1049
+ "schema": RECEIPT_SCHEMA, "result": "success",
1050
+ "transaction_id": data["candidate"]["transaction_id"],
1051
+ "installer": {"digest_at_import": _CODE_AT_START["digest"], "digest": now["digest"],
1052
+ "build": _installer_build(), "root": now["root"], "files": now["files"],
1053
+ "package_modules_run": self._loaded_package_modules(release, hashes)},
1054
+ # Only when a recovery was finished by a different installer than the one that began it;
1055
+ # §11 judges installer exposure against both digests.
1056
+ "begun_by_installer_digest": begun_by if begun_by != now["digest"] else None,
1057
+ "release_digest": record["release_digest"], "baseline_ref": record["baseline_ref"],
1058
+ "selection": record["selection"],
1059
+ # One flat list, each row naming its role, so a consumer reads the artifacts without knowing
1060
+ # how the install record groups them: `release` rows are the immutable release's files,
1061
+ # `owned` rows the launcher and config files the install wrote into the user's own paths.
1062
+ "artifacts": [{"path": entry["path"], "sha256": entry["sha256"], "role": "release"}
1063
+ for entry in record["installed_files"]]
1064
+ + [{"path": entry["path"], "sha256": entry["sha256"], "role": "owned"}
1065
+ for entry in [record.get("launcher"), *(record.get("config_files") or [])] if entry],
1066
+ "at": int(time.time()),
1067
+ }
1068
+
1069
+ def _write_receipt(self, data: dict[str, Any]) -> str | None:
1070
+ """Called only after the transaction verified; a failed transaction never reaches it."""
1071
+ now = _installer_code()
1072
+ if now != _CODE_AT_START or any(entry["sha256"] is None for entry in now["files"]):
1073
+ # The install itself is sound; only the claim about which code ran is not, so no receipt is
1074
+ # written and the sessions this install serves stay unbound instead of the install failing.
1075
+ print("instructions-install: installer code changed or is unreadable; no installation receipt written",
1076
+ file=sys.stderr)
1077
+ return None
1078
+ record = _read_json(self.record_path)
1079
+ if record.get("transaction_id") is None:
1080
+ return None # planned by an installer that wrote no transaction id: it can finish, but cannot be bound
1081
+ if record["transaction_id"] != data["candidate"]["transaction_id"]:
1082
+ raise InstallError("install record does not belong to this transaction")
1083
+ body = self._receipt_body(data, record, now)
1084
+ carried = [key for key in RECEIPT_RESERVED if key in body]
1085
+ if carried:
1086
+ raise InstallError("installation receipt body must not carry its own id: " + ", ".join(carried))
1087
+ raw = _canonical(body)
1088
+ receipt_id = hashlib.sha256(raw).hexdigest()
1089
+ _atomic_bytes(self.runtime / RECEIPT_DIR / f"{receipt_id}.json", raw, 0o600)
1090
+ return receipt_id
1091
+
897
1092
  def _verify_transaction_install(self, data: dict[str, Any]) -> None:
898
1093
  for entry in data["paths"]:
899
1094
  if not self._projection_matches(entry):
@@ -1347,7 +1542,7 @@ class InstructionsInstaller:
1347
1542
  events: list[dict[str, str]] = []
1348
1543
  seen: dict[str, str] = {}
1349
1544
  body = content.decode("utf-8")
1350
- for number, line in enumerate(body.splitlines(), 1):
1545
+ for number, line in enumerate(jsonl_lines_for(__file__).split(body), 1):
1351
1546
  if not line.strip():
1352
1547
  continue
1353
1548
  try:
@@ -1380,7 +1575,7 @@ class InstructionsInstaller:
1380
1575
  needs_action.append(f"unsafe private {host} learning event symlink: {target}")
1381
1576
  return
1382
1577
  existing: dict[str, str] = {}
1383
- for number, line in enumerate(target.read_text(encoding="utf-8").splitlines(), 1):
1578
+ for number, line in enumerate(jsonl_lines_for(__file__).read(target), 1):
1384
1579
  if not line.strip():
1385
1580
  continue
1386
1581
  try:
@@ -1648,7 +1843,7 @@ class InstructionsInstaller:
1648
1843
  self._event_destination_conflicts(host, events, conflicts)
1649
1844
  if conflicts:
1650
1845
  raise InstallError("legacy learning transfer changed: " + "; ".join(conflicts))
1651
- lines = set(target.read_text(encoding="utf-8").splitlines())
1846
+ lines = set(jsonl_lines_for(__file__).read(target))
1652
1847
  missing = [event["learning_id"] for event in events if event["raw"] not in lines]
1653
1848
  if missing:
1654
1849
  raise InstallError(f"legacy learning transfer changed: {target}: " + ", ".join(missing))
@@ -1720,7 +1915,7 @@ class InstructionsInstaller:
1720
1915
  raise InstallError("; ".join(conflicts))
1721
1916
  target = self.user_root / "learnings" / host / "events.jsonl"
1722
1917
  self._safe_owned_path(target, self.user_root)
1723
- prior = target.read_text(encoding="utf-8").splitlines() if target.is_file() else []
1918
+ prior = jsonl_lines_for(__file__).read(target) if target.is_file() else []
1724
1919
  known = {json.loads(line)["learning_id"] for line in prior if line.strip()}
1725
1920
  additions = [event["raw"] for event in events if event["learning_id"] not in known]
1726
1921
  if additions: