agent-bios 0.19.1 → 0.19.3

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 (106) hide show
  1. package/DEPENDENCIES.md +58 -30
  2. package/INSTALL.md +4 -4
  3. package/README.md +105 -28
  4. package/claude/CLAUDE.md +1 -1
  5. package/claude/guides/claude-prompting.md +1 -1
  6. package/claude/guides/cli-multi-model-workflow.md +4 -4
  7. package/claude/guides/coding-staged-workflow.md +17 -0
  8. package/claude/guides/documentation-hygiene.md +3 -0
  9. package/claude/guides/gpt-prompting.md +1 -1
  10. package/claude/guides/korean-writing.md +153 -0
  11. package/claude/guides/learning-flow.md +4 -4
  12. package/claude/guides/llm-capability-boundary.md +7 -1
  13. package/claude/guides/session-distill-workflow.md +8 -8
  14. package/claude/guides/slide-writing/RUNBOOK.md +5 -5
  15. package/claude/guides/tooling-gotchas.md +20 -1
  16. package/claude/guides/ui-design/visual-direction.md +88 -0
  17. package/claude/guides/ui-design.md +90 -0
  18. package/claude/guides/verification-discipline.md +10 -1
  19. package/claude/hooks/tooling-gotchas-hook.py +41 -0
  20. package/claude/skills/repo-charter/SKILL.md +3 -3
  21. package/claude/skills/understand/SKILL.md +5 -5
  22. package/codex/AGENTS.md +1 -1
  23. package/codex/guides/claude-prompting.md +1 -1
  24. package/codex/guides/cli-multi-model-workflow.md +4 -4
  25. package/codex/guides/coding-staged-workflow.md +17 -0
  26. package/codex/guides/documentation-hygiene.md +3 -0
  27. package/codex/guides/gpt-prompting.md +1 -1
  28. package/codex/guides/korean-writing.md +153 -0
  29. package/codex/guides/learning-flow.md +4 -4
  30. package/codex/guides/llm-capability-boundary.md +7 -1
  31. package/codex/guides/session-distill-workflow.md +8 -8
  32. package/codex/guides/slide-writing/RUNBOOK.md +5 -5
  33. package/codex/guides/tooling-gotchas.md +20 -1
  34. package/codex/guides/ui-design/visual-direction.md +88 -0
  35. package/codex/guides/ui-design.md +90 -0
  36. package/codex/guides/verification-discipline.md +10 -1
  37. package/compose/app_bridge/SKILL.md +12 -12
  38. package/compose/app_bridge/scripts/bridge.py +35 -10
  39. package/compose/app_desktop/server.py +250 -0
  40. package/compose/assemble.py +5 -5
  41. package/compose/bootstrap/SKILL.md +18 -18
  42. package/compose/canary.sh +4 -4
  43. package/compose/check-domains.py +6 -6
  44. package/compose/corpus-state.py +16 -1168
  45. package/compose/corpus.py +13 -402
  46. package/compose/corpus_app.py +14 -450
  47. package/compose/corpus_catalog.py +15 -926
  48. package/compose/corpus_import.py +14 -523
  49. package/compose/corpus_install.py +14 -1847
  50. package/compose/corpus_session.py +16 -848
  51. package/compose/corpus_setup.py +16 -672
  52. package/compose/corpus_setup_cli.py +15 -580
  53. package/compose/corpus_setup_i18n.py +20 -324
  54. package/compose/corpus_setup_ui.py +18 -645
  55. package/compose/corpus_store.py +16 -1664
  56. package/compose/corpus_transaction.py +15 -284
  57. package/compose/corpus_ui.py +17 -972
  58. package/compose/corpus_ui_runtime.py +16 -274
  59. package/compose/corpus_understand.py +13 -671
  60. package/compose/domains.json +3 -1
  61. package/compose/host_platform.py +121 -0
  62. package/compose/instructions-state.py +1178 -0
  63. package/compose/instructions.py +409 -0
  64. package/compose/instructions_app.py +697 -0
  65. package/compose/instructions_catalog.py +931 -0
  66. package/compose/instructions_import.py +537 -0
  67. package/compose/instructions_install.py +1932 -0
  68. package/compose/instructions_session.py +852 -0
  69. package/compose/instructions_setup.py +713 -0
  70. package/compose/instructions_setup_cli.py +607 -0
  71. package/compose/instructions_setup_i18n.py +327 -0
  72. package/compose/instructions_setup_ui.py +647 -0
  73. package/compose/instructions_store.py +1668 -0
  74. package/compose/instructions_transaction.py +308 -0
  75. package/compose/instructions_ui.py +975 -0
  76. package/compose/instructions_ui_runtime.py +279 -0
  77. package/compose/instructions_understand.py +678 -0
  78. package/compose/native_cli.py +52 -0
  79. package/compose/register-hooks.py +1 -1
  80. package/compose/runtime_entry.py +58 -0
  81. package/compose/setup/START.md +11 -11
  82. package/compose/windows_deploy.py +719 -0
  83. package/docs/advanced-launch.md +11 -11
  84. package/docs/instructions-compatibility.md +86 -0
  85. package/docs/{corpus.md → instructions.md} +36 -8
  86. package/docs/recovery.md +10 -10
  87. package/docs/releases/0.19.2.md +38 -0
  88. package/docs/releases/0.19.3.md +107 -0
  89. package/docs/session-model.md +31 -20
  90. package/docs/setup.md +63 -26
  91. package/docs/understand.md +6 -6
  92. package/docs/windows.md +99 -0
  93. package/install.sh +71 -69
  94. package/launch/agent-launch.py +309 -293
  95. package/launch/agent-launch.toml +2 -2
  96. package/launch/agent-launch.zsh +11 -1
  97. package/launch/i18n/en.toml +55 -55
  98. package/launch/i18n/ja.toml +56 -56
  99. package/launch/i18n/ko.toml +56 -56
  100. package/launch/shell_integration.py +4 -4
  101. package/learn/collect-learning.py +10 -10
  102. package/learn/learning.schema.json +1 -1
  103. package/learn/migrate-learnings.py +51 -51
  104. package/package.json +33 -12
  105. package/provenance.json +1 -1
  106. /package/docs/assets/{corpus-studio.svg → instructions-studio.svg} +0 -0
@@ -0,0 +1,1932 @@
1
+ #!/usr/bin/env python3
2
+ """Private instructions installation and explicit legacy migration.
3
+
4
+ This command owns package-at-rest installation. It deliberately has no host
5
+ activation path: installed instructions are stored and verifiable, while a launcher
6
+ activation creates the per-session snapshot and pin.
7
+ """
8
+ from __future__ import annotations
9
+ try:
10
+ from host_platform import WINDOWS, runtime_environment
11
+ except ImportError:
12
+ from .host_platform import WINDOWS, runtime_environment
13
+
14
+ import argparse
15
+ import base64
16
+ import contextlib
17
+ import hashlib
18
+ import importlib
19
+ import importlib.util
20
+ import json
21
+ import os
22
+ from pathlib import Path, PurePosixPath
23
+ import re
24
+ import shlex
25
+ import shutil
26
+ import sys
27
+ import tempfile
28
+ import time
29
+ import tomllib
30
+ import uuid
31
+ from typing import Any
32
+
33
+ if __name__ == "__main__":
34
+ sys.dont_write_bytecode = True
35
+
36
+ from instructions_transaction import (
37
+ environment_value,
38
+ _valid_release,
39
+ TransactionError,
40
+ guard_pending,
41
+ operation_scope,
42
+ operation_scope_active,
43
+ pending_status,
44
+ reject_symlink_ancestors,
45
+ transaction_lock,
46
+ )
47
+
48
+
49
+ SCHEMA_VERSION = 1
50
+ PRIVATE_RECORD = "private-install.json"
51
+ CENTRAL_START = "<!-- agent-bios:central:start -->"
52
+ CENTRAL_END = "<!-- agent-bios:central:end -->"
53
+ PERSONAL_START = "<!-- agent-bios:personal-learnings:start -->"
54
+ PERSONAL_END = "<!-- agent-bios:personal-learnings:end -->"
55
+ CLAUDE_IMPORTS = frozenset(("@central/bundle.md", "@personal/learnings.md"))
56
+ ZSH_HOOK = '[ -r "$HOME/.config/agent-launch/shell.zsh" ] && source "$HOME/.config/agent-launch/shell.zsh"'
57
+ LEARNING_ID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
58
+
59
+
60
+ class InstallError(RuntimeError):
61
+ pass
62
+
63
+
64
+ def _serialized(method):
65
+ """Keep installer metadata and its owned paths one transaction at a time."""
66
+ def wrapped(self, *args, **kwargs):
67
+ name = method.__name__
68
+ dry = bool(kwargs.get("dry_run", False))
69
+ if name == "install" and len(args) >= 2:
70
+ dry = dry or bool(args[1])
71
+ elif name in {"uninstall"} and args:
72
+ dry = dry or bool(args[0])
73
+ apply = bool(args[0]) if args and name in {"migrate", "reset"} else bool(kwargs.get("apply", False))
74
+ if name == "status" or dry or (name in {"migrate", "reset"} and not apply):
75
+ return method(self, *args, **kwargs)
76
+ with self._installer_lock():
77
+ if name in {"install", "uninstall", "reset"} and not operation_scope_active(self.state_root):
78
+ if any(row["kind"] == "migrate" for row in pending_status(self.state_root)["transactions"]):
79
+ raise InstallError("pending migration requires agent-bios migrate --apply --yes before other writes")
80
+ return method(self, *args, **kwargs)
81
+ return wrapped
82
+
83
+
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
+ def _atomic_bytes(path: Path, data: bytes, mode: int | None = None) -> None:
97
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
98
+ if path.is_symlink():
99
+ raise InstallError(f"refusing symlink output: {path}")
100
+ descriptor, raw = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
101
+ temporary = Path(raw)
102
+ try:
103
+ with os.fdopen(descriptor, "wb") as target:
104
+ target.write(data)
105
+ target.flush()
106
+ os.fsync(target.fileno())
107
+ if mode is not None:
108
+ temporary.chmod(mode)
109
+ elif path.exists():
110
+ temporary.chmod(path.stat().st_mode & 0o777)
111
+ os.replace(temporary, path)
112
+ finally:
113
+ temporary.unlink(missing_ok=True)
114
+
115
+
116
+ def _atomic_json(path: Path, value: Any) -> None:
117
+ _atomic_bytes(path, _canonical(value) + b"\n", 0o600)
118
+
119
+
120
+ def _read_json(path: Path) -> dict[str, Any]:
121
+ if path.is_symlink() or not path.is_file():
122
+ raise InstallError(f"missing or unsafe JSON record: {path}")
123
+ try:
124
+ data = json.loads(path.read_text(encoding="utf-8"))
125
+ except (OSError, ValueError) as exc:
126
+ raise InstallError(f"cannot read JSON record {path}: {exc}") from exc
127
+ if not isinstance(data, dict):
128
+ raise InstallError(f"JSON record must be an object: {path}")
129
+ return data
130
+
131
+
132
+ def _relative(value: str, label: str) -> str:
133
+ if not isinstance(value, str) or not value:
134
+ raise InstallError(f"{label} must be a non-empty relative path")
135
+ path = PurePosixPath(value.rstrip("/"))
136
+ if path.is_absolute() or not path.parts or any(part in {"", ".", ".."} for part in path.parts):
137
+ raise InstallError(f"unsafe {label}: {value!r}")
138
+ return path.as_posix()
139
+
140
+
141
+ def _inside(path: Path, root: Path) -> bool:
142
+ try:
143
+ path.absolute().relative_to(root.absolute())
144
+ return True
145
+ except ValueError:
146
+ return False
147
+
148
+
149
+ def _active_import_lines(body: str) -> list[int]:
150
+ """Line numbers of real import directives, excluding fenced examples."""
151
+ result: list[int] = []
152
+ fenced = False
153
+ for index, line in enumerate(body.splitlines(keepends=True)):
154
+ stripped = line.strip()
155
+ if stripped.startswith(("```", "~~~")):
156
+ fenced = not fenced
157
+ continue
158
+ if not fenced and stripped in CLAUDE_IMPORTS:
159
+ result.append(index)
160
+ return result
161
+
162
+
163
+ def _remove_claude_imports(body: str) -> tuple[str, list[str]]:
164
+ lines = body.splitlines(keepends=True)
165
+ indexes = set(_active_import_lines(body))
166
+ removed = [lines[index].strip() for index in sorted(indexes)]
167
+ return "".join(line for index, line in enumerate(lines) if index not in indexes), removed
168
+
169
+
170
+ def _remove_spans(body: str) -> tuple[str | None, list[str]]:
171
+ """Strip exact, non-overlapping managed marker spans or report ambiguity."""
172
+ spans = ((CENTRAL_START, CENTRAL_END, "central"), (PERSONAL_START, PERSONAL_END, "personal-learnings"))
173
+ found: list[tuple[int, int, str]] = []
174
+ for start, end, label in spans:
175
+ starts = [index for index in range(len(body)) if body.startswith(start, index)]
176
+ ends = [index for index in range(len(body)) if body.startswith(end, index)]
177
+ if not starts and not ends:
178
+ continue
179
+ if len(starts) != 1 or len(ends) != 1 or starts[0] >= ends[0]:
180
+ return None, [f"malformed {label} marker span"]
181
+ found.append((starts[0], ends[0] + len(end), label))
182
+ if len(found) == 2 and not (found[0][1] <= found[1][0] or found[1][1] <= found[0][0]):
183
+ return None, ["overlapping managed marker spans"]
184
+ text = body
185
+ removed: list[str] = []
186
+ for start, end, label in sorted(found, reverse=True):
187
+ text = text[:start] + text[end:]
188
+ removed.append(label)
189
+ return text.lstrip("\n"), list(reversed(removed))
190
+
191
+
192
+ def _strip_codex_config_additions(body: str) -> tuple[str | None, bool]:
193
+ """Remove only the exact legacy config block and tagged feature line."""
194
+ begin, end, tag = "# >>> agent-bios additions >>>", "# <<< agent-bios additions <<<", "# agent-bios"
195
+ starts = body.count(begin)
196
+ ends = body.count(end)
197
+ if starts != ends or starts > 1:
198
+ return None, False
199
+ skipping = False
200
+ changed = False
201
+ lines: list[str] = []
202
+ for line in body.splitlines(keepends=True):
203
+ stripped = line.strip()
204
+ if stripped == begin:
205
+ skipping, changed = True, True
206
+ continue
207
+ if stripped == end:
208
+ skipping = False
209
+ continue
210
+ if skipping:
211
+ continue
212
+ if stripped.endswith(tag) and "multi_agent" in stripped:
213
+ changed = True
214
+ continue
215
+ lines.append(line)
216
+ result = "".join(lines)
217
+ if changed:
218
+ try:
219
+ tomllib.loads(result)
220
+ except tomllib.TOMLDecodeError:
221
+ return None, False
222
+ return result, changed
223
+
224
+
225
+ class InstructionsInstaller:
226
+ """Private install state plus carefully scoped legacy cleanup."""
227
+
228
+ def __init__(self, repo: Path, environ: dict[str, str] | None = None):
229
+ self.repo = Path(repo).resolve()
230
+ self.env = dict(os.environ if environ is None else environ)
231
+ home = Path(self.env.get("HOME", str(Path.home()))).expanduser()
232
+ self.state_root = Path(self.env.get("AGENT_BIOS_STATE_DIR", str(home / ".local/share/agent-bios"))).expanduser()
233
+ self.user_root = Path(environment_value(self.env, "AGENT_BIOS_INSTRUCTIONS_DIR", "AGENT_BIOS_CORPUS_DIR", str(home / ".config/agent-bios/corpus"))).expanduser()
234
+ self.claude_root = Path(self.env.get("CLAUDE_CONFIG_DIR", str(home / ".claude"))).expanduser()
235
+ self.codex_root = Path(self.env.get("CODEX_HOME", str(home / ".codex"))).expanduser()
236
+ self.zdotdir = Path(self.env.get("ZDOTDIR", str(home))).expanduser()
237
+ self.launch_root = home / ".config" / "agent-launch"
238
+ self.bin_root = home / ".local" / "bin"
239
+ self._installer_lock_depth = 0
240
+
241
+ @property
242
+ def runtime(self) -> Path:
243
+ return self.state_root / "runtime"
244
+
245
+ @property
246
+ def record_path(self) -> Path:
247
+ return self.runtime / PRIVATE_RECORD
248
+
249
+ @contextlib.contextmanager
250
+ def _installer_lock(self):
251
+ """Use the store's lock; lock ordering cannot diverge by caller."""
252
+ try:
253
+ with transaction_lock(self.state_root):
254
+ yield
255
+ except TransactionError as exc:
256
+ raise InstallError(str(exc)) from exc
257
+
258
+ def _package_manifest(self) -> dict[str, Any]:
259
+ return _read_json(self.repo / "package.json")
260
+
261
+ def _package_files(self) -> list[str]:
262
+ manifest = self._package_manifest()
263
+ listed = manifest.get("files")
264
+ if not isinstance(listed, list) or not listed:
265
+ raise InstallError("package.json files must declare the private runtime payload")
266
+ paths: set[str] = {"package.json"} # npm includes this manifest even when files[] omits it.
267
+ prohibited = ("gates/", "design/", "benchmarks/", "research/", "packages/", "session-distill/")
268
+ for raw in listed:
269
+ relative = _relative(raw, "package files entry")
270
+ if relative.startswith(prohibited):
271
+ raise InstallError(f"author-only path is not a private runtime payload: {relative}")
272
+ source = self.repo / relative
273
+ # npm's prepack stamps this author-side provenance receipt. A
274
+ # checkout after postpack legitimately lacks it and no private
275
+ # runtime path consumes it, so it is not an installation blocker.
276
+ if relative == "provenance.json" and not source.exists():
277
+ continue
278
+ if source.is_symlink() or not source.exists():
279
+ raise InstallError(f"declared package file is missing or symlinked: {relative}")
280
+ if source.is_file():
281
+ paths.add(relative)
282
+ continue
283
+ if not source.is_dir():
284
+ raise InstallError(f"declared package entry is not file or directory: {relative}")
285
+ for child in sorted(source.rglob("*")):
286
+ if child.is_symlink():
287
+ raise InstallError(f"package payload contains symlink: {child}")
288
+ if child.is_file():
289
+ child_relative = child.relative_to(self.repo).as_posix()
290
+ if "/test_" in child_relative or child_relative.startswith("tests/"):
291
+ raise InstallError(f"test file is not a runtime payload: {child_relative}")
292
+ paths.add(child_relative)
293
+ return sorted(paths)
294
+
295
+ def _release_digest(self, files: list[str]) -> str:
296
+ digest = hashlib.sha256()
297
+ for relative in files:
298
+ source = self.repo / relative
299
+ digest.update(relative.encode("utf-8") + b"\0" + source.read_bytes() + b"\0")
300
+ return digest.hexdigest()
301
+
302
+ def _copy_release(self, files: list[str], dry_run: bool) -> tuple[Path, list[dict[str, str]], str]:
303
+ digest = self._release_digest(files)
304
+ release = self.runtime / "releases" / digest
305
+ entries = [{"path": relative, "sha256": _sha256(self.repo / relative)} for relative in files]
306
+ if dry_run:
307
+ return release, entries, digest
308
+ if release.exists():
309
+ if release.is_symlink() or not release.is_dir():
310
+ raise InstallError(f"immutable release path is unsafe: {release}")
311
+ self._verify_release(release, entries)
312
+ return release, entries, digest
313
+ release.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
314
+ staging = Path(tempfile.mkdtemp(prefix=f".{digest}.", dir=release.parent))
315
+ try:
316
+ for entry in entries:
317
+ source = self.repo / entry["path"]
318
+ target = staging / entry["path"]
319
+ target.parent.mkdir(parents=True, exist_ok=True)
320
+ shutil.copy2(source, target)
321
+ self._verify_release(staging, entries)
322
+ os.replace(staging, release)
323
+ except BaseException:
324
+ shutil.rmtree(staging, ignore_errors=True)
325
+ raise
326
+ return release, entries, digest
327
+
328
+ def _verify_release(self, release: Path, entries: list[dict[str, str]]) -> None:
329
+ for entry in entries:
330
+ target = release / _relative(entry.get("path", ""), "installed file")
331
+ if target.is_symlink() or not target.is_file() or _sha256(target) != entry.get("sha256"):
332
+ raise InstallError(f"private package release drifted: {target}")
333
+
334
+ def _private_module(self, package_root: Path, stem: str):
335
+ # An old store must participate in this manager's reentrant transaction,
336
+ # not load a second copy of the old module-local lock/operation scope.
337
+ import instructions_transaction
338
+ sys.modules["corpus_transaction"] = instructions_transaction
339
+ compose = str(package_root / "compose")
340
+ if compose not in sys.path:
341
+ sys.path.insert(0, compose)
342
+ path = package_root / "compose" / f"{stem}.py"
343
+ if not path.exists() and stem.startswith("instructions"):
344
+ path = package_root / "compose" / f"{stem.replace('instructions', 'corpus', 1)}.py"
345
+ if not path.is_file() or path.is_symlink():
346
+ raise InstallError(f"private package lacks compose/{stem}.py")
347
+ name = f"agent_bios_private_{stem}_{hashlib.sha256(str(package_root).encode()).hexdigest()[:12]}"
348
+ spec = importlib.util.spec_from_file_location(name, path)
349
+ if spec is None or spec.loader is None:
350
+ raise InstallError(f"cannot load private {stem}")
351
+ module = importlib.util.module_from_spec(spec)
352
+ sys.modules[name] = module
353
+ spec.loader.exec_module(module)
354
+ return module
355
+
356
+ def _store(self, package_root: Path):
357
+ module = self._private_module(package_root, "instructions_store")
358
+ store_type = getattr(module, "InstructionsStore", None) or module.CorpusStore
359
+ store = store_type(package_root, self.state_root, self.user_root)
360
+ # InstructionsStore delegates compile/load to a module name for normal package
361
+ # execution. Bind this instance to the release's exact catalog so a
362
+ # long-lived manager cannot retain an older release through sys.modules.
363
+ catalog = self._private_module(package_root, "instructions_catalog")
364
+ store._catalog_module = lambda: catalog
365
+ return store
366
+
367
+ def _catalog(self, package_root: Path) -> dict[str, Any]:
368
+ """Load the catalog from the immutable release being verified."""
369
+ module = self._private_module(package_root, "instructions_catalog")
370
+ return module.load_catalog(package_root)
371
+
372
+ def _normalized_domains(self, raw: str | None) -> list[str]:
373
+ if raw is None or raw.strip() in {"", "all"}:
374
+ return ["all"]
375
+ catalog_path = self.repo / "compose" / "domains.json"
376
+ manifest = _read_json(catalog_path)
377
+ package_id = manifest.get("package_id", "@agent-bios/core")
378
+ known = set((manifest.get("domains") or {}).keys())
379
+ names = [value.strip() for value in raw.split(",") if value.strip()]
380
+ if names == ["none"]:
381
+ return []
382
+ if "none" in names:
383
+ raise InstallError("--domains none must be the only selection value")
384
+ unknown = sorted(set(names) - known)
385
+ if unknown:
386
+ raise InstallError(f"unknown domains: {', '.join(unknown)}")
387
+ return [f"{package_id}/{name}" for name in sorted(set(names))]
388
+
389
+ def _write_launcher_status(self, package_root: Path, selection: list[str]) -> None:
390
+ """Keep the legacy launcher panel readable without claiming activation."""
391
+ manifest = _read_json(package_root / "compose" / "domains.json")
392
+ available = sorted((manifest.get("domains") or {}).keys())
393
+ package_id = manifest.get("package_id", "@agent-bios/core")
394
+ applied = available if "all" in selection or package_id in selection else [
395
+ name for name in available if f"{package_id}/{name}" in selection]
396
+ _atomic_json(self.state_root / "corpus-status.json", {
397
+ "repo": str(package_root), "current_version": None, "latest_version": None,
398
+ "rolled_back_to": None, "versions": None, "summary": None,
399
+ "domains": {"available": available, "applied": applied}, "last_apply": None,
400
+ "deployed_corpus": None, "generated": int(time.time()),
401
+ "mode": "private-session-scoped",
402
+ })
403
+
404
+ def _launcher_status_bytes(self, package_root: Path, selection: list[str], generated: int | None = None) -> bytes:
405
+ """The status projection is part of the same publication as its record."""
406
+ manifest = _read_json(package_root / "compose" / "domains.json")
407
+ available = sorted((manifest.get("domains") or {}).keys())
408
+ package_id = manifest.get("package_id", "@agent-bios/core")
409
+ applied = available if "all" in selection or package_id in selection else [
410
+ name for name in available if f"{package_id}/{name}" in selection]
411
+ return _canonical({
412
+ "repo": str(package_root), "current_version": None, "latest_version": None,
413
+ "rolled_back_to": None, "versions": None, "summary": None,
414
+ "domains": {"available": available, "applied": applied}, "last_apply": None,
415
+ "deployed_corpus": None, "generated": int(time.time()) if generated is None else generated,
416
+ "mode": "private-session-scoped",
417
+ }) + b"\n"
418
+
419
+ @staticmethod
420
+ def _safe_transaction_target(path: Path) -> None:
421
+ try:
422
+ reject_symlink_ancestors(path)
423
+ except TransactionError as exc:
424
+ raise InstallError(str(exc)) from exc
425
+
426
+ @staticmethod
427
+ def _file_version(path: Path, *, allow_bytes: bool = True) -> dict[str, Any]:
428
+ """A journaled exact-state predicate; secrets use hash-only predicates."""
429
+ InstructionsInstaller._safe_transaction_target(path)
430
+ if not path.exists():
431
+ return {"exists": False}
432
+ if not path.is_file():
433
+ raise InstallError(f"transaction target is not a regular file: {path}")
434
+ data = path.read_bytes()
435
+ result: dict[str, Any] = {"exists": True, "sha256": hashlib.sha256(data).hexdigest()}
436
+ if allow_bytes:
437
+ result["bytes_b64"] = base64.b64encode(data).decode("ascii")
438
+ return result
439
+
440
+ @staticmethod
441
+ def _planned_version(data: bytes | None) -> dict[str, Any]:
442
+ if data is None:
443
+ return {"exists": False}
444
+ return {"exists": True, "sha256": hashlib.sha256(data).hexdigest(),
445
+ "bytes_b64": base64.b64encode(data).decode("ascii")}
446
+
447
+ @staticmethod
448
+ def _matches_version(path: Path, version: dict[str, Any]) -> bool:
449
+ try:
450
+ InstructionsInstaller._safe_transaction_target(path)
451
+ except InstallError:
452
+ return False
453
+ if not version.get("exists"):
454
+ return not path.exists()
455
+ return path.is_file() and _sha256(path) == version.get("sha256")
456
+
457
+ def _transaction_path(self, transaction_id: str) -> Path:
458
+ if not re.fullmatch(r"[A-Za-z0-9._-]+", transaction_id):
459
+ raise InstallError("unsafe transaction id")
460
+ # Store keeps its source-only candidate at ``transactions/<id>``.
461
+ # The installer must never overwrite that source journal.
462
+ return self.runtime / "installer-transactions" / transaction_id / "journal.json"
463
+
464
+ def _journal_write(self, journal: Path, value: dict[str, Any]) -> None:
465
+ _atomic_json(journal, value)
466
+
467
+ def _write_planned(self, path: Path, version: dict[str, Any], mode: int) -> None:
468
+ self._safe_transaction_target(path)
469
+ encoded = version.get("bytes_b64")
470
+ if not isinstance(encoded, str):
471
+ if not version.get("exists"):
472
+ path.unlink(missing_ok=True)
473
+ return
474
+ raise InstallError(f"journal has no replay bytes for {path}")
475
+ _atomic_bytes(path, base64.b64decode(encoded.encode("ascii"), validate=True), mode)
476
+
477
+ def _assert_preflight_paths(self, paths: list[dict[str, Any]]) -> None:
478
+ for entry in paths:
479
+ self._safe_transaction_target(Path(entry["path"]))
480
+ conflicts = [entry["path"] for entry in paths
481
+ if not self._matches_version(Path(entry["path"]), entry["before"])
482
+ and not self._matches_version(Path(entry["path"]), entry["after"])]
483
+ if conflicts:
484
+ raise InstallError("owned path changed during transaction preflight: " + ", ".join(conflicts))
485
+
486
+ def _projection_matches(self, entry: dict[str, Any]) -> bool:
487
+ path, after = Path(entry["path"]), entry["after"]
488
+ return self._matches_version(path, after) and (
489
+ not after.get("exists") or WINDOWS or path.stat().st_mode & 0o777 == int(entry["mode"]))
490
+
491
+ def _old_record(self) -> dict[str, Any] | None:
492
+ return _read_json(self.record_path) if self.record_path.exists() else None
493
+
494
+ def _safe_owned_path(self, path: Path, root: Path) -> None:
495
+ """An ownership record cannot redirect writes through a symlinked parent."""
496
+ if not _inside(path, root):
497
+ raise InstallError(f"owned path is outside its private destination: {path}")
498
+ current = root.absolute()
499
+ if current.is_symlink():
500
+ raise InstallError(f"owned destination root is symlinked: {current}")
501
+ relative = path.absolute().relative_to(current)
502
+ for part in relative.parts:
503
+ current = current / part
504
+ if current.is_symlink():
505
+ raise InstallError(f"owned destination has symlink ancestor: {current}")
506
+
507
+ def _expected_owned(self, release: Path, launcher_runtime=None) -> dict[str, str]:
508
+ expected = {str(self.bin_root / ("agent-launch.cmd" if WINDOWS else "agent-launch")): hashlib.sha256(self._launcher_body(release, launcher_runtime=launcher_runtime, current=False)).hexdigest(),
509
+ str(self.launch_root / "profiles.toml"): _sha256(release / "launch" / "agent-launch.toml")}
510
+ i18n = release / "launch" / "i18n"
511
+ for source in sorted(i18n.glob("*.toml")):
512
+ expected[str(self.launch_root / "i18n" / source.name)] = _sha256(source)
513
+ return expected
514
+
515
+ def _validate_owned_record(self, record: dict[str, Any], release: Path) -> None:
516
+ expected = self._expected_owned(release, record.get("launcher_runtime"))
517
+ launcher = record.get("launcher")
518
+ if launcher is not None:
519
+ if not isinstance(launcher, dict) or launcher.get("path") != str(self.bin_root / ("agent-launch.cmd" if WINDOWS else "agent-launch")) \
520
+ or launcher.get("sha256") != expected[str(self.bin_root / ("agent-launch.cmd" if WINDOWS else "agent-launch"))]:
521
+ raise InstallError("private install record has an invalid launcher ownership claim")
522
+ self._safe_owned_path(Path(launcher["path"]), self.bin_root)
523
+ seen: set[str] = set()
524
+ for entry in record.get("config_files") or []:
525
+ if not isinstance(entry, dict) or not isinstance(entry.get("path"), str) or entry["path"] in seen:
526
+ raise InstallError("private install record has invalid config ownership entries")
527
+ seen.add(entry["path"])
528
+ if entry["path"] not in expected or entry.get("sha256") != expected[entry["path"]]:
529
+ raise InstallError(f"private install record has an invalid config ownership claim: {entry['path']}")
530
+ self._safe_owned_path(Path(entry["path"]), self.launch_root)
531
+
532
+ def _owned_hash(self, record: dict[str, Any] | None, path: Path) -> str | None:
533
+ if not record:
534
+ return None
535
+ for entry in [record.get("launcher"), *(record.get("config_files") or [])]:
536
+ if isinstance(entry, dict) and entry.get("path") == str(path):
537
+ value = entry.get("sha256")
538
+ return value if isinstance(value, str) else None
539
+ return None
540
+
541
+ def _write_owned(self, path: Path, content: bytes, old: dict[str, Any] | None, mode: int) -> dict[str, str] | None:
542
+ root = self.bin_root if path == self.bin_root / ("agent-launch.cmd" if WINDOWS else "agent-launch") else self.launch_root
543
+ self._safe_owned_path(path, root)
544
+ expected = self._owned_hash(old, path)
545
+ if path.exists() and (path.is_symlink() or (expected is None and _sha256(path) != hashlib.sha256(content).hexdigest())
546
+ or (expected is not None and _sha256(path) != expected)):
547
+ return None
548
+ _atomic_bytes(path, content, mode)
549
+ return {"path": str(path), "sha256": hashlib.sha256(content).hexdigest()}
550
+
551
+ def _current_launcher_runtime(self):
552
+ if not WINDOWS:
553
+ return None
554
+ env = runtime_environment(self.env)
555
+ return {'schema_version': 1, 'python': env.get('AGENT_BIOS_PYTHON_EXECUTABLE', str(Path(sys.executable).resolve())),
556
+ 'environment': env}
557
+
558
+ def _launcher_body(self, package_root: Path, *, launcher_runtime=None, current=True) -> bytes:
559
+ if WINDOWS:
560
+ spec = self._current_launcher_runtime() if current else launcher_runtime
561
+ if spec is None:
562
+ # Exact pre-binding Windows source format, for existing receipts.
563
+ return ('@echo off\r\n"' + sys.executable + '" "' + str(package_root / "compose/native_cli.py") + '" launch %*\r\n').encode("utf-8")
564
+ if (not isinstance(spec, dict) or set(spec) != {'schema_version', 'python', 'environment'}
565
+ or spec['schema_version'] != 1 or not isinstance(spec['python'], str)
566
+ or not Path(spec['python']).is_absolute() or not isinstance(spec['environment'], dict)):
567
+ raise InstallError('invalid recorded launcher runtime')
568
+ env = spec['environment']
569
+ allowed = {'AGENT_BIOS_PYTHON_ENTRY', 'AGENT_BIOS_PYTHON_DEPS', 'AGENT_BIOS_PYTHON_EXECUTABLE'}
570
+ if env and (set(env) != allowed or any(not isinstance(v, str) or not Path(v).is_absolute() for v in env.values())):
571
+ raise InstallError('invalid recorded launcher dependency binding')
572
+ argv = [spec['python']]
573
+ if env:
574
+ argv += ['-I', '-X', 'utf8', env['AGENT_BIOS_PYTHON_ENTRY'], '--dependencies', env['AGENT_BIOS_PYTHON_DEPS'], '--script']
575
+ argv += [str(package_root / 'compose/native_cli.py'), 'launch']
576
+ if any(any(c in value for c in '\r\n\0"') for value in argv):
577
+ raise InstallError('unsafe launcher runtime argument')
578
+ command = ' '.join('"' + value.replace('%', '%%') + '"' for value in argv)
579
+ return ('@echo off\r\nsetlocal DisableDelayedExpansion\r\nchcp 65001 >nul\r\n' + command + ' %*\r\n').encode('utf-8')
580
+ quoted = shlex.quote(str(package_root))
581
+ # Verify historical ownership using the exact released launcher vocabulary.
582
+ canonical = (package_root / "compose/instructions_store.py").is_file()
583
+ activation = ("unset AGENT_BIOS_PRIVATE_CORPUS\nexport AGENT_BIOS_PRIVATE_INSTRUCTIONS=1\n"
584
+ if canonical else "export AGENT_BIOS_PRIVATE_CORPUS=1\n")
585
+ return ("#!/bin/sh\n"
586
+ + activation
587
+ + f"export AGENT_BIOS_PACKAGE_ROOT={quoted}\n"
588
+ "exec python3 \"$AGENT_BIOS_PACKAGE_ROOT/launch/agent-launch.py\" \"$@\"\n").encode("utf-8")
589
+
590
+ def _shell_manager(self):
591
+ path = Path(__file__).resolve().parent.parent / "launch/shell_integration.py"
592
+ spec = importlib.util.spec_from_file_location("agent_bios_shell_integration", path)
593
+ if spec is None or spec.loader is None:
594
+ raise InstallError("shell connection manager is unavailable")
595
+ module = importlib.util.module_from_spec(spec)
596
+ spec.loader.exec_module(module)
597
+ return module.ShellIntegration(self.env, self.repo)
598
+
599
+ def launcher_reachability(self) -> dict[str, Any]:
600
+ """Report whether the launcher this install deposits can actually be typed.
601
+
602
+ Both answers are known here and invisible in the installed tree: install
603
+ writes the launcher into a directory the caller's PATH may not carry, and
604
+ the shell connection that reaches it for bare host commands is opt-in. A
605
+ completion summary that omits them reports a success the caller cannot use.
606
+ Read-only, and never raises: a summary is not worth failing an install
607
+ that succeeded, and reporting must not become a reason to write.
608
+ """
609
+ launcher = self.bin_root / ("agent-launch.cmd" if WINDOWS else "agent-launch")
610
+ connected: bool | None = None
611
+ if not WINDOWS:
612
+ # zsh is the only shell this connection speaks; elsewhere the question
613
+ # has no answer rather than a negative one.
614
+ try:
615
+ connected = bool(self._shell_manager().status().get("enabled"))
616
+ except (InstallError, OSError, RuntimeError, ValueError):
617
+ connected = False
618
+ try:
619
+ target = os.path.normcase(os.path.realpath(self.bin_root))
620
+ # No expanduser: a shell does not tilde-expand PATH entries when it
621
+ # searches, so a literal ~ there really does not find the command.
622
+ on_path = any(os.path.normcase(os.path.realpath(part)) == target
623
+ for part in self.env.get("PATH", "").split(os.pathsep) if part)
624
+ except (OSError, ValueError):
625
+ on_path = True # Undecidable; do not tell the caller PATH is wrong on a guess.
626
+ return {"path": str(launcher), "directory": str(self.bin_root),
627
+ "on_path": on_path, "shell_connected": connected}
628
+
629
+ def setup_catalog(self) -> dict[str, Any]:
630
+ return self._catalog(self.repo)
631
+
632
+ def setup_local_instructions(self) -> list[dict[str, Any]]:
633
+ """Describe existing private content independently of installation choices."""
634
+ try:
635
+ counts = self._store(self.repo).local_item_counts()
636
+ except (OSError, RuntimeError, ValueError) as exc:
637
+ raise InstallError(str(exc)) from exc
638
+ rows = []
639
+ for package_id, label in (("@local/personal", "Personal instructions"),
640
+ ("@local/learnings-claude", "Claude learning records"),
641
+ ("@local/learnings-codex", "Codex learning records")):
642
+ if counts.get(package_id):
643
+ rows.append({"target": package_id, "label": label, "item_count": counts[package_id]})
644
+ return rows
645
+
646
+ def setup_discover(self, project_roots=None) -> dict[str, Any]:
647
+ try:
648
+ from .instructions_import import discover
649
+ except ImportError:
650
+ from instructions_import import discover
651
+ return discover(environ=self.env, project_roots=project_roots)
652
+
653
+ def setup_revision(self) -> str:
654
+ """Bind an installation review to the current private selection and authoring."""
655
+ paths = (self.record_path, self.runtime / "state.json", self.user_root / "state.json")
656
+ return hashlib.sha256(_canonical({str(path): self._file_version(path) for path in paths})).hexdigest()
657
+
658
+ def _app_manager(self):
659
+ try:
660
+ from .instructions_app import AppBridge
661
+ except ImportError:
662
+ from instructions_app import AppBridge
663
+ return AppBridge(self.repo, self.env)
664
+
665
+ def _app_lifecycle(self, action: str, dry_run: bool = False) -> dict[str, Any]:
666
+ try:
667
+ manager = self._app_manager()
668
+ if action == "remove":
669
+ return (manager.unregister(dry_run) if manager.has_owned_registration()
670
+ else manager.managed_status())
671
+ return manager.refresh_registration()
672
+ except (OSError, RuntimeError) as exc:
673
+ return {"changed": False, "needs_action": [str(exc)]}
674
+
675
+ def setup_extras(self, plan: dict[str, Any], dry_run: bool = False) -> dict[str, Any]:
676
+ try:
677
+ from .instructions_import import capture
678
+ except ImportError:
679
+ from instructions_import import capture
680
+ result: dict[str, Any] = {}
681
+ if plan.get("app_bridge"):
682
+ bridge = self._app_manager()
683
+ status = bridge.status()
684
+ if status.get("needs_action"):
685
+ raise InstallError("; ".join(status["needs_action"]))
686
+ result["app_bridge"] = ({"requested": True, "dry_run": True} if dry_run
687
+ else bridge.register())
688
+ paths = plan.get("import_paths") or []
689
+ if paths:
690
+ discovered = self.setup_discover(plan.get("project_roots"))
691
+ allowed = {row["path"] for row in discovered["sources"]}
692
+ if not set(paths) <= allowed:
693
+ raise InstallError("instruction import selection is not in the reviewed discovery set")
694
+ if dry_run:
695
+ result["import"] = {"paths": paths, "classification": "requires model review", "dry_run": True}
696
+ else:
697
+ record = self._old_record()
698
+ if record is None:
699
+ raise InstallError("install the private runtime before capturing instructions")
700
+ try:
701
+ captured = capture(self._store(Path(record["package_root"])), paths,
702
+ environ=self.env, project_roots=plan.get("project_roots"),
703
+ expected_source_digests=plan.get("_expected_source_digests"))
704
+ except (OSError, RuntimeError, ValueError) as exc:
705
+ failure = InstallError(str(exc))
706
+ failure.completed_extras = result
707
+ raise failure from exc
708
+ result["import"] = {"capture_id": captured["capture_id"], "source_count": len(captured["sources"]),
709
+ "classification": "requires model review",
710
+ "next_command": "agent-bios import prompt " + captured["capture_id"],
711
+ "app_request": "Use $agent-bios to import capture " + captured["capture_id"]}
712
+ return result
713
+
714
+ def _shell_paths(self, action: str) -> list[dict[str, Any]]:
715
+ if WINDOWS:
716
+ return []
717
+ try:
718
+ manager = self._shell_manager()
719
+ # A receipt-less managed script may survive an interrupted opt-in.
720
+ # With neither, do not inspect or claim the user's startup file.
721
+ if not manager.has_connection():
722
+ return []
723
+ # Install owns and validates the upcoming launcher projection; it
724
+ # must also be able to repair a missing/non-executable entrypoint.
725
+ changes = manager.plan(action, installing=action == "restore")["changes"]
726
+ except (OSError, RuntimeError) as exc:
727
+ raise InstallError(str(exc)) from exc
728
+ return [{"path": str(row["path"]), "before": self._planned_version(row["before"]),
729
+ "after": self._planned_version(row["after"]), "mode": row["mode"], "archive": False}
730
+ for row in changes]
731
+
732
+ @_serialized
733
+ def install(self, domains: str | None = None, dry_run: bool = False, *,
734
+ selection_mode: str | None = None, targets: list[str] | None = None) -> dict[str, Any]:
735
+ files = self._package_files()
736
+ explicit_selection = domains is not None or selection_mode is not None or targets is not None
737
+ if domains is not None and selection_mode is None:
738
+ selection_mode = "default"
739
+ if selection_mode not in {None, "default", "selected", "none"}:
740
+ raise InstallError("selection_mode must be default, selected, or none")
741
+ if targets is not None and (not isinstance(targets, list) or not all(isinstance(x, str) for x in targets)):
742
+ raise InstallError("instructions targets must be a list of qualified names")
743
+ if domains is not None and targets is not None:
744
+ raise InstallError("use domain flags or instructions targets, not both")
745
+ if domains is not None and selection_mode == "none":
746
+ raise InstallError("no-instructions installation cannot include domain flags")
747
+ requested = list(targets) if targets is not None else ([] if selection_mode == "none" else self._normalized_domains(domains))
748
+ if selection_mode == "none" and requested:
749
+ raise InstallError("no-instructions installation cannot include targets")
750
+ if selection_mode == "selected" and not requested:
751
+ raise InstallError("selected instructions installation needs at least one target")
752
+ prior = self._old_record()
753
+ # An update without an explicit selection must not broaden a saved
754
+ # core-only or domain-limited environment back to every domain.
755
+ if domains is None and not explicit_selection and isinstance((prior or {}).get("selection"), list):
756
+ requested = prior["selection"]
757
+ selection_mode = prior.get("selection_mode")
758
+ if selection_mode is not None:
759
+ preview_store = self._store(self.repo)
760
+ catalog = self.setup_catalog()
761
+ try:
762
+ available = list(catalog["items"])
763
+ runtime = preview_store._runtime_state()
764
+ if runtime.get("selected_baseline_ref"):
765
+ user = preview_store._user_state()
766
+ for host in ("claude", "codex"):
767
+ available.extend(item for item in preview_store._effective_items(runtime, user, host=host)[0]
768
+ if item["package_id"].startswith("@local/") and item.get("active", True))
769
+ preview_store._validate_snapshot_selection(requested, catalog, available)
770
+ except (ValueError, RuntimeError) as exc:
771
+ raise InstallError(str(exc)) from exc
772
+ # A preview is strictly read-only. A real install first refuses an
773
+ # unrelated reset, then finishes only its own pending install before
774
+ # creating an immutable release directory.
775
+ if not dry_run:
776
+ pending = pending_status(self.state_root)["transactions"]
777
+ if any(row["owner"] == "installer" and row["kind"] == "reset" for row in pending):
778
+ raise InstallError("pending reset requires recovery before install")
779
+ with operation_scope(self.state_root):
780
+ self._recover_pending_transactions()
781
+ release, entries, digest = self._copy_release(files, dry_run)
782
+ if dry_run:
783
+ return {"dry_run": True, "release": str(release), "release_digest": digest,
784
+ "files": len(entries), "selection": requested, "selection_mode": selection_mode or "default",
785
+ "corpus_storage": "packaged library retained privately; selection controls delivery"}
786
+ shell_paths = self._shell_paths("restore")
787
+ # Stage the immutable baseline before publishing either source pointers
788
+ # or launcher projections. Store owns those source pointers; this
789
+ # coordinator owns all cross-owner ordering.
790
+ store = self._store(release)
791
+ prepare = getattr(store, "prepare_install", None)
792
+ if not callable(prepare):
793
+ raise InstallError("private instructions store does not support staged install recovery")
794
+ candidate = (prepare(requested, selection_mode=selection_mode, replace_selection=explicit_selection)
795
+ if selection_mode is not None else prepare(requested))
796
+ if not isinstance(candidate, dict) or not isinstance(candidate.get("details"), dict):
797
+ raise InstallError("private instructions store returned an invalid install candidate")
798
+ details = candidate["details"]
799
+ baseline_ref = details.get("baseline_ref")
800
+ if not isinstance(baseline_ref, str):
801
+ raise InstallError("private instructions store candidate has no baseline ref")
802
+ owned: list[tuple[Path, bytes, int]] = [
803
+ (self.bin_root / ("agent-launch.cmd" if WINDOWS else "agent-launch"), self._launcher_body(release), 0o755),
804
+ (self.launch_root / "profiles.toml", (release / "launch" / "agent-launch.toml").read_bytes(), 0o644),
805
+ ]
806
+ owned.extend((self.launch_root / "i18n" / source.name, source.read_bytes(), 0o644)
807
+ for source in sorted((release / "launch" / "i18n").glob("*.toml")))
808
+ conflicts: list[str] = []
809
+ for path, content, _mode in owned:
810
+ current = self._file_version(path)
811
+ expected = self._owned_hash(prior, path)
812
+ if current["exists"] and current.get("sha256") != hashlib.sha256(content).hexdigest() and \
813
+ (expected is None or current.get("sha256") != expected):
814
+ conflicts.append(str(path))
815
+ if conflicts:
816
+ raise InstallError("private install cannot replace user-owned paths: " + ", ".join(conflicts))
817
+ launcher = {"path": str(owned[0][0]), "sha256": hashlib.sha256(owned[0][1]).hexdigest()}
818
+ config = [{"path": str(path), "sha256": hashlib.sha256(content).hexdigest()}
819
+ for path, content, _mode in owned[1:]]
820
+ record = {
821
+ "schema_version": SCHEMA_VERSION, "package_root": str(release), "release_digest": digest,
822
+ "installed_files": entries, "selection": requested, "baseline_ref": baseline_ref,
823
+ "launcher": launcher, "config_files": config, "created_at": int(time.time()),
824
+ "mode": "private-session-scoped", "needs_action": [],
825
+ }
826
+ if WINDOWS:
827
+ record["launcher_runtime"] = self._current_launcher_runtime()
828
+ if selection_mode is not None:
829
+ record["selection_mode"] = selection_mode
830
+ paths = [{"path": str(path), "before": self._file_version(path),
831
+ "after": self._planned_version(content), "mode": mode}
832
+ for path, content, mode in owned]
833
+ paths.extend(shell_paths)
834
+ paths.extend([
835
+ {"path": str(self.record_path), "before": self._file_version(self.record_path),
836
+ "after": self._planned_version(_canonical(record) + b"\n"), "mode": 0o600},
837
+ {"path": str(self.state_root / "corpus-status.json"),
838
+ "before": self._file_version(self.state_root / "corpus-status.json"),
839
+ "after": self._planned_version(self._launcher_status_bytes(release, requested)), "mode": 0o600},
840
+ ])
841
+ transaction_id = str(candidate.get("transaction_id") or uuid.uuid4().hex)
842
+ journal = self._transaction_path(transaction_id)
843
+ # Source candidates are persisted by InstructionsStore under the transaction
844
+ # id. Keep only hashes here: personal source text is free-form and
845
+ # must never be accidentally archived by the installer journal.
846
+ association = {"transaction_id": transaction_id, "baseline_ref": baseline_ref,
847
+ "selected_baseline_ref": details.get("selected_baseline_ref"),
848
+ "items": details.get("items"),
849
+ "source_before_sha256": hashlib.sha256(_canonical(candidate.get("before"))).hexdigest(),
850
+ "source_after_sha256": hashlib.sha256(_canonical(candidate.get("after"))).hexdigest()}
851
+ journal_data = {"schema_version": SCHEMA_VERSION, "owner": "installer", "kind": "install", "state": "PREPARED",
852
+ "phase": "preflight", "candidate": association, "paths": paths,
853
+ "created_at": int(time.time())}
854
+ self._journal_write(journal, journal_data)
855
+ try:
856
+ with operation_scope(self.state_root):
857
+ self._finish_install_transaction(journal, journal_data, store, candidate)
858
+ return {"dry_run": False, "stored": True, "activation": "unverified", "record": record,
859
+ "app_bridge": self._app_lifecycle("refresh")}
860
+ except BaseException as exc:
861
+ journal_data["state"] = "NEEDS_RECOVERY"
862
+ journal_data["error"] = type(exc).__name__
863
+ self._journal_write(journal, journal_data)
864
+ raise
865
+
866
+ def _finish_install_transaction(self, journal: Path, data: dict[str, Any], store: Any,
867
+ candidate: dict[str, Any] | None) -> None:
868
+ self._assert_preflight_paths(data["paths"])
869
+ data["state"], data["phase"] = "APPLYING", "projections"
870
+ self._journal_write(journal, data)
871
+ # Write candidate projections before source publication. A crash here
872
+ # is harmless to readers because the journal guard is already durable.
873
+ for entry in data["paths"]:
874
+ path = Path(entry["path"])
875
+ if not self._projection_matches(entry):
876
+ self._write_planned(path, entry["after"], int(entry["mode"]))
877
+ data["phase"] = "source"
878
+ self._journal_write(journal, data)
879
+ commit = getattr(store, "commit_install", None)
880
+ if not callable(commit):
881
+ raise InstallError("private instructions store does not support staged install commit")
882
+ if candidate is None:
883
+ # The store persists the complete source candidate under this id;
884
+ # passing only it prevents installer journals from duplicating user
885
+ # authoring bytes (which could include sensitive free text).
886
+ commit({"transaction_id": data["candidate"]["transaction_id"]})
887
+ else:
888
+ commit(candidate)
889
+ data["phase"] = "verify"
890
+ self._journal_write(journal, data)
891
+ # The record/status are included in paths and now exact. Verify the
892
+ # installed source and every owned projection before success is visible.
893
+ self._verify_transaction_install(data)
894
+ data["state"], data["phase"], data["committed_at"] = "COMMITTED", "complete", int(time.time())
895
+ self._journal_write(journal, data)
896
+
897
+ def _verify_transaction_install(self, data: dict[str, Any]) -> None:
898
+ for entry in data["paths"]:
899
+ if not self._projection_matches(entry):
900
+ raise InstallError(f"transaction projection did not verify: {entry['path']}")
901
+ record = _read_json(self.record_path)
902
+ release = Path(record["package_root"])
903
+ self._verify_release(release, record["installed_files"])
904
+ self._validate_owned_record(record, release)
905
+ source = _read_json(self.runtime / "state.json")
906
+ if source.get("last_successful_install_ref") != record.get("baseline_ref"):
907
+ raise InstallError("staged instructions baseline was not published")
908
+
909
+ def _recover_pending_transactions(self) -> None:
910
+ root = self.runtime / "installer-transactions"
911
+ if not root.exists():
912
+ return
913
+ for journal in sorted(root.glob("*/journal.json")):
914
+ data = _read_json(journal)
915
+ if data.get("state") not in {"PREPARED", "APPLYING", "NEEDS_RECOVERY"}:
916
+ continue
917
+ if data.get("kind") != "install" or not isinstance(data.get("candidate"), dict) \
918
+ or not isinstance(data.get("paths"), list):
919
+ raise InstallError(f"unrecoverable transaction journal: {journal}")
920
+ association = data["candidate"]
921
+ release_record = next((entry for entry in data["paths"] if entry.get("path") == str(self.record_path)), None)
922
+ if not isinstance(release_record, dict):
923
+ raise InstallError(f"transaction journal lacks install record: {journal}")
924
+ encoded = release_record.get("after", {}).get("bytes_b64")
925
+ if not isinstance(encoded, str):
926
+ raise InstallError(f"transaction journal lacks record bytes: {journal}")
927
+ record = json.loads(base64.b64decode(encoded.encode("ascii"), validate=True))
928
+ release = Path(record.get("package_root", ""))
929
+ if not release.is_dir() or release.is_symlink():
930
+ raise InstallError(f"transaction release is unavailable: {journal}")
931
+ try:
932
+ with operation_scope(self.state_root):
933
+ self._finish_install_transaction(journal, data, self._store(release), None)
934
+ except BaseException as exc:
935
+ data["state"], data["error"] = "NEEDS_RECOVERY", type(exc).__name__
936
+ self._journal_write(journal, data)
937
+ raise InstallError(f"pending install requires recovery: {journal}") from exc
938
+
939
+ @_serialized
940
+ def verify(self) -> dict[str, Any]:
941
+ try:
942
+ guard_pending(self.state_root)
943
+ except TransactionError as exc:
944
+ raise InstallError(str(exc)) from exc
945
+ record = self._old_record()
946
+ if record is None:
947
+ raise InstallError("no private install record")
948
+ if record.get("schema_version") != SCHEMA_VERSION:
949
+ raise InstallError("private install record schema mismatch")
950
+ if record.get("needs_action"):
951
+ raise InstallError("private install is incomplete; resolve owned-path conflicts: "
952
+ + ", ".join(str(path) for path in record["needs_action"]))
953
+ release = Path(record.get("package_root", ""))
954
+ releases = self.runtime / "releases"
955
+ if not _inside(release, releases) or release.is_symlink() or not release.is_dir():
956
+ raise InstallError("private install record has unsafe package root")
957
+ entries = record.get("installed_files")
958
+ if not isinstance(entries, list) or not entries:
959
+ raise InstallError("private install record has no installed files")
960
+ self._verify_release(release, entries)
961
+ self._validate_owned_record(record, release)
962
+ catalog = self._catalog(release)
963
+ if not catalog.get("items"):
964
+ raise InstallError("private catalog is empty")
965
+ source_state = _read_json(self.runtime / "state.json")
966
+ if source_state.get("last_successful_install_ref") != record.get("baseline_ref"):
967
+ raise InstallError("private baseline does not match install record")
968
+ for entry in [record.get("launcher"), *(record.get("config_files") or [])]:
969
+ if not isinstance(entry, dict):
970
+ continue
971
+ path = Path(entry.get("path", ""))
972
+ if path.is_symlink() or not path.is_file() or _sha256(path) != entry.get("sha256"):
973
+ raise InstallError(f"private owned file drifted: {path}")
974
+ launcher_status = _read_json(self.state_root / "corpus-status.json")
975
+ domains = launcher_status.get("domains")
976
+ if launcher_status.get("repo") != str(release) or not isinstance(domains, dict) or \
977
+ not isinstance(domains.get("available"), list) or not isinstance(domains.get("applied"), list):
978
+ raise InstallError("launcher instructions-status projection is missing or malformed")
979
+ return {"stored": True, "catalog_items": len(catalog["items"]), "baseline_ref": record["baseline_ref"],
980
+ "activation": "unverified"}
981
+
982
+ @_serialized
983
+ def status(self) -> dict[str, Any]:
984
+ try:
985
+ pending = pending_status(self.state_root)
986
+ except TransactionError as exc:
987
+ raise InstallError(str(exc)) from exc
988
+ record = self._old_record()
989
+ if not record:
990
+ return {"installed": False, "activation": "unverified", **pending}
991
+ return {"installed": True, "package_root": record.get("package_root"),
992
+ "baseline_ref": record.get("baseline_ref"), "needs_action": record.get("needs_action", []),
993
+ "activation": "unverified", **pending}
994
+
995
+ def _active_intents(self) -> list[Path]:
996
+ root = self.runtime / "activations"
997
+ if not root.is_dir():
998
+ return []
999
+ active = []
1000
+ for journal in root.glob("*/journal.json"):
1001
+ with contextlib.suppress(InstallError):
1002
+ data = _read_json(journal)
1003
+ if data.get("state") in {"PREPARED", "HOST_OBSERVED"}:
1004
+ active.append(journal)
1005
+ return active
1006
+
1007
+ @_serialized
1008
+ def uninstall(self, dry_run: bool = False) -> dict[str, Any]:
1009
+ record = self._old_record()
1010
+ if record is not None:
1011
+ release = Path(record.get("package_root", ""))
1012
+ if not _inside(release, self.runtime / "releases") or release.is_symlink() or not release.is_dir():
1013
+ raise InstallError("private install record has unsafe package root")
1014
+ self._validate_owned_record(record, release)
1015
+ shell_removed: list[str] = []
1016
+ try:
1017
+ manager = self._shell_manager()
1018
+ if manager.has_connection():
1019
+ shell_removed = manager.apply("remove", dry_run)["changed_paths"]
1020
+ except (OSError, RuntimeError) as exc:
1021
+ raise InstallError(str(exc)) from exc
1022
+ if record is None:
1023
+ app = self._app_lifecycle("remove", dry_run)
1024
+ return {"removed": shell_removed, "preserved": ["no private install record"], "app_bridge": app}
1025
+ removed: list[str] = list(shell_removed)
1026
+ preserved: list[str] = []
1027
+ for entry in [record.get("launcher"), *(record.get("config_files") or [])]:
1028
+ if not isinstance(entry, dict):
1029
+ continue
1030
+ path = Path(entry.get("path", ""))
1031
+ expected = entry.get("sha256")
1032
+ if path.is_file() and not path.is_symlink() and isinstance(expected, str) and _sha256(path) == expected:
1033
+ if not dry_run:
1034
+ path.unlink()
1035
+ removed.append(str(path))
1036
+ elif path.exists():
1037
+ preserved.append(str(path))
1038
+ intents = self._active_intents()
1039
+ if intents:
1040
+ preserved.extend(str(path) for path in intents)
1041
+ elif _inside(release, self.runtime / "releases") and release.is_dir() and not release.is_symlink():
1042
+ if not dry_run:
1043
+ shutil.rmtree(release)
1044
+ removed.append(str(release))
1045
+ else:
1046
+ preserved.append(str(release))
1047
+ if not intents and not dry_run:
1048
+ self.record_path.unlink(missing_ok=True)
1049
+ # User package/overlays/learnings and session snapshots/pins are purposely
1050
+ # not enumerated or deleted here. No whole state-root removal occurs.
1051
+ app = self._app_lifecycle("remove", dry_run)
1052
+ return {"removed": removed, "preserved": preserved, "app_bridge": app,
1053
+ "retained": [str(self.user_root), str(self.state_root / "sessions")]}
1054
+
1055
+ def _reset_layout(self, record: dict[str, Any], release: Path) -> tuple[list[Path], Path, Path, list[tuple[Path, bytes, int]]]:
1056
+ local = [self.launch_root / name for name in ("presets.local.toml", "review-methods.local.toml", "launcher.local.toml")]
1057
+ connections = self.launch_root.parent / "agent-bios"
1058
+ cleanup = [*local, connections / "ingest-url", self.user_root / "understand" / "state.json"]
1059
+ owned = [(self.bin_root / ("agent-launch.cmd" if WINDOWS else "agent-launch"), self._launcher_body(release, launcher_runtime=record.get("launcher_runtime"), current=False), 0o755),
1060
+ (self.launch_root / "profiles.toml", (release / "launch" / "agent-launch.toml").read_bytes(), 0o644)]
1061
+ owned.extend((self.launch_root / "i18n" / p.name, p.read_bytes(), 0o644)
1062
+ for p in sorted((release / "launch" / "i18n").glob("*.toml")))
1063
+ return cleanup, connections / "token", connections, owned
1064
+
1065
+ def _learning_versions(self) -> dict[str, dict[str, Any]]:
1066
+ """Learning events are authoring input, not reset-owned cleanup."""
1067
+ return {host: self._file_version(self.user_root / "learnings" / host / "events.jsonl")
1068
+ for host in ("claude", "codex")}
1069
+
1070
+ def _reset_preview(self) -> dict[str, Any]:
1071
+ record = self._old_record()
1072
+ if record is None:
1073
+ raise InstallError("cannot reset before private install")
1074
+ release = Path(record.get("package_root", ""))
1075
+ if not _inside(release, self.runtime / "releases") or release.is_symlink() or not release.is_dir():
1076
+ raise InstallError("private install record has unsafe package root")
1077
+ self._validate_owned_record(record, release)
1078
+ cleanup, secret, _connections, owned = self._reset_layout(record, release)
1079
+ targets = [{"path": str(path), "before": self._file_version(path), "after": {"exists": False}, "mode": 0o600,
1080
+ "archive": True} for path in cleanup]
1081
+ targets.extend(self._shell_paths("remove"))
1082
+ targets.extend({"path": str(path), "before": self._file_version(path), "after": self._planned_version(body),
1083
+ "mode": mode, "archive": False} for path, body, mode in owned)
1084
+ status_path = self.state_root / "corpus-status.json"
1085
+ targets.append({"path": str(status_path), "before": self._file_version(status_path),
1086
+ "after": self._planned_version(self._launcher_status_bytes(
1087
+ release, record["selection"], record.get("created_at") if isinstance(record.get("created_at"), int) else 0)),
1088
+ "mode": 0o600, "archive": False})
1089
+ secret_before = self._file_version(secret, allow_bytes=False)
1090
+ pending = pending_status(self.state_root)
1091
+ learning = self._learning_versions()
1092
+ fingerprint = hashlib.sha256(_canonical({"record": _sha256(self.record_path), "runtime": self._file_version(self.runtime / "state.json"),
1093
+ "user": self._file_version(self.user_root / "state.json"), "targets": targets,
1094
+ "secret": secret_before, "learning": learning, "pending": pending["transactions"]})).hexdigest()
1095
+ return {"preview": True, "expected_revision": fingerprint, "pending": pending,
1096
+ "archive": [entry["path"] for entry in targets if entry["archive"] and entry["before"]["exists"]],
1097
+ "delete_without_archive": [str(secret)] if secret_before["exists"] else [],
1098
+ "restore_defaults": [entry["path"] for entry in targets if not entry["archive"]],
1099
+ "retained": [str(self.state_root / "sessions"), str(self.user_root / "learnings")],
1100
+ "record": record, "release": release, "targets": targets, "secret_before": secret_before,
1101
+ "learning_before": learning}
1102
+
1103
+ @_serialized
1104
+ def reset(self, apply: bool = False, yes: bool = False, expected_revision: str | None = None) -> dict[str, Any]:
1105
+ """Preview first; an apply accepts exactly that observed generation."""
1106
+ preview = self._reset_preview()
1107
+ if not apply:
1108
+ return {key: value for key, value in preview.items() if key not in {"record", "release", "targets", "secret_before", "learning_before"}}
1109
+ if not yes or not isinstance(expected_revision, str):
1110
+ raise InstallError("reset apply requires --yes and preview expected_revision")
1111
+ pending = [row for row in preview["pending"]["transactions"] if row["owner"] == "installer"]
1112
+ if any(row["kind"] == "install" for row in pending):
1113
+ raise InstallError("pending install requires recovery before reset")
1114
+ for row in pending:
1115
+ data = _read_json(Path(row["path"]))
1116
+ if data.get("owner") != "installer" or data.get("kind") != "reset":
1117
+ raise InstallError(f"pending reset requires fresh preview: {row['path']}")
1118
+ if data.get("intent", {}).get("accepted_revision") == expected_revision:
1119
+ return self._recover_reset(Path(row["path"]), data)
1120
+ if preview["expected_revision"] != expected_revision:
1121
+ raise InstallError("reset preview is stale; preview again before applying")
1122
+ record, release, targets = preview["record"], preview["release"], preview["targets"]
1123
+ with operation_scope(self.state_root):
1124
+ plan = self._store(release).plan({"operation": "reset"})
1125
+ reset_id = f"{int(time.time())}-{uuid.uuid4().hex[:12]}"
1126
+ journal = self.runtime / "resets" / reset_id / "journal.json"
1127
+ archive = self.user_root / "history" / reset_id / "launcher-config"
1128
+ data = {"schema_version": SCHEMA_VERSION, "owner": "installer", "kind": "reset", "state": "PREPARED", "phase": "preflight",
1129
+ "archive": str(archive), "targets": targets, "secret_before": preview["secret_before"], "learning_before": preview["learning_before"],
1130
+ "intent": {"plan_id": plan["plan_id"], "expected_revision": plan["expected_revision"],
1131
+ "accepted_revision": expected_revision, "record_sha256": _sha256(self.record_path)},
1132
+ "retained": preview["retained"], "created_at": int(time.time())}
1133
+ _atomic_json(journal, data)
1134
+ # Keep the old publication guard until the replacement intent is durable.
1135
+ for row in pending:
1136
+ prior = _read_json(Path(row["path"]))
1137
+ prior["state"] = "SUPERSEDED"
1138
+ _atomic_json(Path(row["path"]), prior)
1139
+ return self._recover_reset(journal, data)
1140
+
1141
+ def _source_pair_ok(self, data: dict[str, Any]) -> bool:
1142
+ plan_path = self.runtime / "transactions" / data["intent"]["plan_id"] / "journal.json"
1143
+ plan = _read_json(plan_path).get("plan", {})
1144
+ before, after = plan.get("before", {}), plan.get("after", {})
1145
+ runtime, user = _read_json(self.runtime / "state.json"), _read_json(self.user_root / "state.json")
1146
+ return runtime in (before.get("runtime"), after.get("runtime")) and user in (before.get("user"), after.get("user"))
1147
+
1148
+ def _recover_reset(self, journal: Path, data: dict[str, Any]) -> dict[str, Any]:
1149
+ """Preflight every target and source pair before changing one byte."""
1150
+ try:
1151
+ if data["intent"].get("record_sha256") != _sha256(self.record_path) or not self._source_pair_ok(data):
1152
+ raise InstallError("reset state changed; obtain a fresh preview")
1153
+ if data.get("learning_before") != self._learning_versions():
1154
+ raise InstallError("reset learning source changed; obtain a fresh preview")
1155
+ targets = data.get("targets")
1156
+ if not isinstance(targets, list):
1157
+ raise InstallError("pending reset requires fresh preview")
1158
+ for entry in targets:
1159
+ if not (self._matches_version(Path(entry["path"]), entry["before"]) or self._matches_version(Path(entry["path"]), entry["after"])):
1160
+ raise InstallError(f"reset target changed; obtain a fresh preview: {entry['path']}")
1161
+ secret = self.launch_root.parent / "agent-bios" / "token"; prior = data.get("secret_before", {"exists": False})
1162
+ if not (self._matches_version(secret, prior) or not secret.exists()):
1163
+ raise InstallError("reset token changed; obtain a fresh preview")
1164
+ release = Path(self._old_record()["package_root"])
1165
+ archive = Path(data["archive"])
1166
+ data.update({"state": "APPLYING", "phase": "archive"}); _atomic_json(journal, data)
1167
+ for entry in targets:
1168
+ path = Path(entry["path"])
1169
+ if entry.get("archive") and entry["before"].get("exists"):
1170
+ target = archive / path.name
1171
+ if not target.exists(): self._write_planned(target, entry["before"], 0o600)
1172
+ if entry.get("archive") and not self._matches_version(path, entry["after"]): self._write_planned(path, entry["after"], int(entry["mode"]))
1173
+ data["phase"] = "source"; _atomic_json(journal, data)
1174
+ with operation_scope(self.state_root):
1175
+ result = self._store(release).apply(data["intent"]["plan_id"], data["intent"]["expected_revision"])
1176
+ data["result"] = result; data["phase"] = "projections"; _atomic_json(journal, data)
1177
+ for entry in targets:
1178
+ if not entry.get("archive") and not self._projection_matches(entry): self._write_planned(Path(entry["path"]), entry["after"], int(entry["mode"]))
1179
+ if prior.get("exists"):
1180
+ if self._matches_version(secret, prior):
1181
+ secret.unlink()
1182
+ elif secret.exists():
1183
+ raise InstallError("reset token changed; obtain a fresh preview")
1184
+ data.update({"state": "COMMITTED", "phase": "complete", "committed_at": int(time.time())}); _atomic_json(journal, data)
1185
+ return {"preview": False, "reset": data["result"], "archive": data["archive"], "retained": data["retained"], "recovered": True}
1186
+ except BaseException as exc:
1187
+ data.update({"state": "NEEDS_RECOVERY", "error": type(exc).__name__}); _atomic_json(journal, data); raise
1188
+
1189
+ def _legacy_manifest_files(self, needs_action: list[str], read=None) -> list[Path]:
1190
+ manifest = self.state_root / "manifest.txt"
1191
+ if manifest.is_symlink():
1192
+ needs_action.append(f"unsafe legacy manifest symlink: {manifest}")
1193
+ return []
1194
+ content = read(manifest) if read else manifest.read_bytes() if manifest.is_file() else None
1195
+ if content is None:
1196
+ return []
1197
+ private = self._old_record()
1198
+ protected: set[str] = set()
1199
+ if private is not None:
1200
+ self._validate_owned_record(private, Path(private.get("package_root", "")))
1201
+ protected = {str(entry["path"]) for entry in
1202
+ [private["launcher"], *private.get("config_files", [])]}
1203
+ owned = self._legacy_manifest_destinations()
1204
+ paths: list[Path] = []
1205
+ body = content.decode("utf-8")
1206
+ for raw in body.splitlines():
1207
+ if not raw.strip():
1208
+ continue
1209
+ path = Path(raw.strip())
1210
+ if str(path) in protected:
1211
+ continue
1212
+ if not path.is_absolute() or path in {self.claude_root / "CLAUDE.md", self.codex_root / "AGENTS.md"}:
1213
+ needs_action.append(f"unowned legacy manifest target: {path}")
1214
+ continue
1215
+ if path.is_symlink():
1216
+ needs_action.append(f"unsafe legacy manifest target: {path}")
1217
+ continue
1218
+ try:
1219
+ self._migration_target_root(path)
1220
+ except InstallError as exc:
1221
+ needs_action.append(str(exc))
1222
+ continue
1223
+ if path not in owned:
1224
+ # A prior installer wrote broad directory walks into its manifest.
1225
+ # Root containment proves only where a file lives, never who wrote it.
1226
+ # A stale absent entry is harmless; an existing unknown file is not.
1227
+ if path.exists():
1228
+ needs_action.append(f"unowned legacy manifest target: {path}")
1229
+ continue
1230
+ if path.exists() and not path.is_file():
1231
+ needs_action.append(f"legacy manifest target is not a regular file: {path}")
1232
+ continue
1233
+ paths.append(path)
1234
+ return paths
1235
+
1236
+ def _legacy_manifest_destinations(self, package_root: Path | None = None) -> set[Path]:
1237
+ """Return only paths a legacy installer could derive from this source.
1238
+
1239
+ The old manifest included a recursive scan of ``central``. This map is
1240
+ deliberately source-derived instead of treating a shared native root as
1241
+ a claim of ownership, so a same-directory user file remains protected.
1242
+ """
1243
+ source_root = (package_root or self.repo).resolve()
1244
+ owned: set[Path] = {
1245
+ self.state_root / "version.json",
1246
+ self.claude_root / "central" / "bundle.md",
1247
+ self.claude_root / "personal" / "learnings.jsonl",
1248
+ self.codex_root / "personal" / "learnings.jsonl",
1249
+ }
1250
+
1251
+ def source_file(relative: str) -> Path | None:
1252
+ path = source_root / relative
1253
+ return path if path.is_file() and not path.is_symlink() else None
1254
+
1255
+ native = (
1256
+ ("wrappers/codex-run.sh", self.codex_root / "bin" / "codex-run"),
1257
+ ("wrappers/codex-helm.sh", self.codex_root / "bin" / "codex-helm"),
1258
+ ("wrappers/claude-run.sh", self.claude_root / "bin" / "claude-run"),
1259
+ ("launch/agent-launch.py", self.bin_root / ("agent-launch.cmd" if WINDOWS else "agent-launch")),
1260
+ ("launch/agent-launch.toml", self.launch_root / "profiles.toml"),
1261
+ ("launch/agent-launch.zsh", self.launch_root / "shell.zsh"),
1262
+ )
1263
+ owned.update(destination for source, destination in native if source_file(source) is not None)
1264
+ i18n = source_root / "launch" / "i18n"
1265
+ if i18n.is_dir() and not i18n.is_symlink():
1266
+ owned.update(self.launch_root / "i18n" / source.name
1267
+ for source in i18n.glob("*.toml") if source.is_file() and not source.is_symlink())
1268
+
1269
+ catalog = self._catalog(source_root)
1270
+ for item in catalog.get("items", []):
1271
+ if not isinstance(item, dict):
1272
+ continue
1273
+ kind = item.get("kind")
1274
+ origin = item.get("origin")
1275
+ source = origin.get("source_path") if isinstance(origin, dict) else None
1276
+ members = item.get("members")
1277
+ if not isinstance(source, str) or not isinstance(members, dict):
1278
+ continue
1279
+ for member in members:
1280
+ if not isinstance(member, str):
1281
+ continue
1282
+ relative = PurePosixPath(member)
1283
+ if relative.is_absolute() or ".." in relative.parts or len(relative.parts) < 2:
1284
+ continue
1285
+ tail = Path(*relative.parts[1:])
1286
+ if kind == "guide" and source.startswith("claude/guides/") and relative.parts[0] == "guides":
1287
+ owned.update({self.claude_root / "guides" / tail,
1288
+ self.claude_root / "central" / "guides" / tail,
1289
+ self.codex_root / "guides" / tail})
1290
+ elif kind == "hook" and source.startswith("claude/hooks/") and relative.parts[0] == "hooks":
1291
+ owned.add(self.claude_root / "central" / "hooks" / tail)
1292
+ elif kind == "agent" and source.startswith("claude/agents/") and relative.parts[0] == "agents":
1293
+ owned.add(self.claude_root / "central" / "agents" / tail)
1294
+ elif kind == "skill" and source.startswith("claude/skills/") and relative.parts[0] == "skills":
1295
+ owned.update({self.claude_root / "skills" / tail,
1296
+ self.codex_root / "skills" / tail})
1297
+
1298
+ agents = source_root / "codex" / "agents"
1299
+ if agents.is_dir() and not agents.is_symlink():
1300
+ owned.update(self.codex_root / "agents" / source.name
1301
+ for source in agents.glob("*.toml") if source.is_file() and not source.is_symlink())
1302
+ return owned
1303
+
1304
+ def _migration_cleanup_destinations(self, release: Path) -> set[Path]:
1305
+ """The pinned release plus bounded native edits define replay authority."""
1306
+ return self._legacy_manifest_destinations(release) | {
1307
+ self.state_root / "manifest.txt",
1308
+ self.claude_root / "CLAUDE.md",
1309
+ self.claude_root / "personal" / "learnings.md",
1310
+ self.claude_root / "settings.json",
1311
+ self.codex_root / "AGENTS.md",
1312
+ self.codex_root / "config.toml",
1313
+ self.zdotdir / ".zshrc",
1314
+ self.zdotdir / ".zshenv",
1315
+ self.zdotdir / ".zprofile",
1316
+ }
1317
+
1318
+ def _has_legacy_learning_projection(self, host: str, prose: Path, read=None) -> bool:
1319
+ if prose.is_symlink():
1320
+ return True
1321
+ body = read(prose) if read else prose.read_bytes() if prose.is_file() else None
1322
+ if body is None:
1323
+ return False
1324
+ if host == "codex":
1325
+ return PERSONAL_START.encode() in body or PERSONAL_END.encode() in body
1326
+ # The published legacy installer seeds this exact empty automation-owned file.
1327
+ assembler = self._private_module(self.repo, "assemble")
1328
+ return body != assembler.PERSONAL_LEARNINGS_HEADER.encode("utf-8")
1329
+
1330
+ def _legacy_events(self, host: str, needs_action: list[str], read=None) -> tuple[list[dict[str, str]], Path | None]:
1331
+ home = self.claude_root if host == "claude" else self.codex_root
1332
+ source = home / "personal" / "learnings.jsonl"
1333
+ prose = home / "personal" / "learnings.md" if host == "claude" else home / "AGENTS.md"
1334
+ projection = self._has_legacy_learning_projection(host, prose, read)
1335
+ if source.is_symlink():
1336
+ needs_action.append(f"legacy {host} learning JSONL is symlinked: {source}")
1337
+ return [], None
1338
+ content = read(source) if read else source.read_bytes() if source.is_file() else None
1339
+ if projection and content is None:
1340
+ needs_action.append(f"legacy {host} learning projection has no immutable JSONL source: {prose}")
1341
+ return [], None
1342
+ if content is None:
1343
+ return [], None
1344
+ schema = _read_json(self.repo / "learn" / "learning.schema.json")
1345
+ allowed = set((schema.get("properties") or {}).keys())
1346
+ required = set(schema.get("required") or [])
1347
+ events: list[dict[str, str]] = []
1348
+ seen: dict[str, str] = {}
1349
+ body = content.decode("utf-8")
1350
+ for number, line in enumerate(body.splitlines(), 1):
1351
+ if not line.strip():
1352
+ continue
1353
+ try:
1354
+ raw = json.loads(line)
1355
+ except ValueError:
1356
+ needs_action.append(f"invalid legacy {host} learning JSONL at {source}:{number}")
1357
+ continue
1358
+ if (not isinstance(raw, dict) or set(raw) - allowed or required - set(raw)
1359
+ or raw.get("schema_version") != 1 or not isinstance(raw.get("learning_id"), str)
1360
+ or not LEARNING_ID.fullmatch(raw["learning_id"])
1361
+ or not isinstance(raw.get("lesson"), str) or not isinstance(raw.get("domain"), str)
1362
+ or not isinstance(raw.get("created"), str) or not isinstance(raw.get("supporting_sessions"), list)
1363
+ or not all(isinstance(value, str) for value in raw["supporting_sessions"])):
1364
+ needs_action.append(f"invalid collector v1 {host} learning record at {source}:{number}")
1365
+ continue
1366
+ prior = seen.get(raw["learning_id"])
1367
+ if prior is not None:
1368
+ if prior != line:
1369
+ needs_action.append(f"same learning_id has different legacy bytes at {source}:{number}")
1370
+ continue
1371
+ seen[raw["learning_id"]] = line
1372
+ events.append({"learning_id": raw["learning_id"], "raw": line})
1373
+ return events, source
1374
+
1375
+ def _event_destination_conflicts(self, host: str, events: list[dict[str, str]], needs_action: list[str]) -> None:
1376
+ target = self.user_root / "learnings" / host / "events.jsonl"
1377
+ if not target.exists():
1378
+ return
1379
+ if target.is_symlink():
1380
+ needs_action.append(f"unsafe private {host} learning event symlink: {target}")
1381
+ return
1382
+ existing: dict[str, str] = {}
1383
+ for number, line in enumerate(target.read_text(encoding="utf-8").splitlines(), 1):
1384
+ if not line.strip():
1385
+ continue
1386
+ try:
1387
+ record = json.loads(line)
1388
+ except ValueError:
1389
+ needs_action.append(f"invalid private {host} learning JSONL at {target}:{number}")
1390
+ continue
1391
+ learning_id = record.get("learning_id") if isinstance(record, dict) else None
1392
+ if not isinstance(learning_id, str):
1393
+ needs_action.append(f"invalid private {host} learning record at {target}:{number}")
1394
+ continue
1395
+ previous = existing.get(learning_id)
1396
+ if previous is not None and previous != line:
1397
+ needs_action.append(f"same learning_id has different private bytes at {target}:{number}")
1398
+ existing[learning_id] = line
1399
+ for event in events:
1400
+ current = existing.get(event["learning_id"])
1401
+ if current is not None and current != event["raw"]:
1402
+ needs_action.append(f"same learning_id has different source/private bytes: {event['learning_id']}")
1403
+
1404
+ def _legacy_hook_registration_needed(self, needs_action: list[str], read=None) -> bool:
1405
+ """Use the assembler's exact command-ownership rule, after parse proof."""
1406
+ settings = self.claude_root / "settings.json"
1407
+ if settings.is_symlink():
1408
+ needs_action.append(f"unsafe Claude settings symlink: {settings}")
1409
+ return False
1410
+ content = read(settings) if read else settings.read_bytes() if settings.is_file() else None
1411
+ if content is None:
1412
+ return False
1413
+ try:
1414
+ data = json.loads(content.decode("utf-8"))
1415
+ except ValueError:
1416
+ needs_action.append(f"unreadable Claude settings for legacy hook removal: {settings}")
1417
+ return False
1418
+ hooks = data.get("hooks") if isinstance(data, dict) else None
1419
+ if not isinstance(hooks, dict):
1420
+ return False
1421
+ names = set((_read_json(self.repo / "compose" / "domains.json").get("hooks") or {}).keys())
1422
+ for entries in hooks.values():
1423
+ if not isinstance(entries, list):
1424
+ continue
1425
+ for entry in entries:
1426
+ for hook in entry.get("hooks", []) if isinstance(entry, dict) else []:
1427
+ command = hook.get("command", "") if isinstance(hook, dict) else ""
1428
+ if isinstance(command, str) and any(f"/hooks/{name}" in command for name in names):
1429
+ return True
1430
+ return False
1431
+
1432
+ def _legacy_hook_settings(self, release: Path, before: bytes) -> bytes:
1433
+ """Plan the assembler's exact ownership-sensitive edit without touching the host."""
1434
+ module = self._private_module(release, "assemble")
1435
+ manifest = _read_json(release / "compose" / "domains.json")
1436
+ with tempfile.TemporaryDirectory(prefix="instructions-hook-plan-") as raw:
1437
+ root = Path(raw)
1438
+ _atomic_bytes(root / "settings.json", before, 0o600)
1439
+ module.merge_settings(root, [], release / "claude" / "settings.template.json",
1440
+ owned_names=manifest.get("hooks", {}))
1441
+ return (root / "settings.json").read_bytes()
1442
+
1443
+ def migration_plan(self) -> dict[str, Any]:
1444
+ return self._plan_migration()[0]
1445
+
1446
+ def _plan_migration(self) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
1447
+ # A transformation and its version predicate must describe the same read.
1448
+ inputs: dict[str, dict[str, Any]] = {}
1449
+
1450
+ def read(path: Path) -> bytes | None:
1451
+ raw = str(path)
1452
+ if raw not in inputs:
1453
+ self._migration_target_root(path)
1454
+ inputs[raw] = self._file_version(path)
1455
+ if not inputs[raw]["exists"]:
1456
+ return None
1457
+ return base64.b64decode(inputs[raw]["bytes_b64"].encode("ascii"), validate=True)
1458
+
1459
+ needs_action: list[str] = []
1460
+
1461
+ def text(path: Path) -> str | None:
1462
+ if path.is_symlink():
1463
+ needs_action.append(f"unsafe native migration input symlink: {path}")
1464
+ return None
1465
+ content = read(path)
1466
+ return content.decode("utf-8") if content is not None else None
1467
+
1468
+ writes: list[dict[str, str]] = []
1469
+ claude_entry = self.claude_root / "CLAUDE.md"
1470
+ body = text(claude_entry)
1471
+ if body is not None:
1472
+ new, removed = _remove_claude_imports(body)
1473
+ if removed:
1474
+ writes.append({"path": str(claude_entry), "content": new, "kind": "claude-imports"})
1475
+ codex_entry = self.codex_root / "AGENTS.md"
1476
+ body = text(codex_entry)
1477
+ if body is not None:
1478
+ new, outcome = _remove_spans(body)
1479
+ if new is None:
1480
+ needs_action.extend(f"{codex_entry}: {message}" for message in outcome)
1481
+ elif outcome:
1482
+ writes.append({"path": str(codex_entry), "content": new, "kind": "codex-markers"})
1483
+ codex_config = self.codex_root / "config.toml"
1484
+ body = text(codex_config)
1485
+ if body is not None:
1486
+ stripped, changed = _strip_codex_config_additions(body)
1487
+ if stripped is None:
1488
+ needs_action.append(f"cannot safely remove legacy Codex config additions: {codex_config}")
1489
+ elif changed:
1490
+ writes.append({"path": str(codex_config), "content": stripped, "kind": "codex-config-additions"})
1491
+ for startup in (self.zdotdir / ".zshrc", self.zdotdir / ".zshenv", self.zdotdir / ".zprofile"):
1492
+ body = text(startup)
1493
+ if body is not None:
1494
+ lines = body.splitlines(keepends=True)
1495
+ changed = [line for line in lines if line.strip() == ZSH_HOOK]
1496
+ if changed:
1497
+ writes.append({"path": str(startup), "content": "".join(line for line in lines if line.strip() != ZSH_HOOK), "kind": "zsh-hook"})
1498
+ events: dict[str, list[dict[str, str]]] = {}
1499
+ learning_sources: dict[str, Path] = {}
1500
+ for host in ("claude", "codex"):
1501
+ captured, source = self._legacy_events(host, needs_action, read)
1502
+ if captured:
1503
+ events[host] = captured
1504
+ self._event_destination_conflicts(host, captured, needs_action)
1505
+ if source is not None:
1506
+ learning_sources[host] = source
1507
+ deletes = self._legacy_manifest_files(needs_action, read)
1508
+ manifest = self.state_root / "manifest.txt"
1509
+ if not manifest.is_symlink() and read(manifest) is not None:
1510
+ deletes.append(manifest)
1511
+ seed = self.claude_root / "personal" / "learnings.md"
1512
+ if not seed.is_symlink() and read(seed) is not None and not self._has_legacy_learning_projection("claude", seed, read):
1513
+ deletes.append(seed)
1514
+ # Legacy learning projections are removed only when their immutable source
1515
+ # was successfully parsed and is scheduled for the private event store.
1516
+ for host, source in learning_sources.items():
1517
+ deletes.append(Path(source))
1518
+ if host == "claude":
1519
+ projection = self.claude_root / "personal" / "learnings.md"
1520
+ if not projection.is_symlink() and read(projection) is not None:
1521
+ deletes.append(projection)
1522
+ remove_hooks = self._legacy_hook_registration_needed(needs_action, read)
1523
+ if not needs_action:
1524
+ for path in deletes:
1525
+ read(path)
1526
+ plan = {"schema_version": SCHEMA_VERSION, "writes": writes, "deletes": sorted({str(p) for p in deletes}),
1527
+ "events": events, "remove_hook_registrations": remove_hooks, "needs_action": needs_action}
1528
+ return plan, inputs
1529
+
1530
+ def _backup(self, root: Path, path: Path) -> Path:
1531
+ target = root / "files" / str(path).lstrip("/")
1532
+ _atomic_bytes(target, path.read_bytes(), 0o600)
1533
+ return target
1534
+
1535
+ def _migration_target_root(self, path: Path) -> Path:
1536
+ if not path.is_absolute() or ".." in path.parts:
1537
+ raise InstallError(f"unsafe migration target: {path}")
1538
+ roots = (self.claude_root, self.codex_root, self.launch_root, self.bin_root)
1539
+ if path in {self.state_root / name for name in ("manifest.txt", "version.json")}:
1540
+ root = self.state_root
1541
+ elif path in {self.zdotdir / name for name in (".zshrc", ".zshenv", ".zprofile")}:
1542
+ root = self.zdotdir
1543
+ else:
1544
+ root = next((r for r in roots if path != r and _inside(path, r)), None)
1545
+ if root is None:
1546
+ raise InstallError(f"migration target is outside owned roots: {path}")
1547
+ self._safe_owned_path(path, root)
1548
+ return root
1549
+
1550
+ def _migration_paths(self, plan: dict[str, Any], release: Path,
1551
+ inputs: dict[str, dict[str, Any]]) -> list[dict[str, Any]]:
1552
+ changes: dict[str, bytes | None] = {raw: None for raw in plan["deletes"]}
1553
+ for item in plan["writes"]:
1554
+ if item["path"] in changes:
1555
+ raise InstallError(f"migration both rewrites and deletes {item['path']}")
1556
+ changes[item["path"]] = item["content"].encode("utf-8")
1557
+ if plan["remove_hook_registrations"]:
1558
+ path = str(self.claude_root / "settings.json")
1559
+ if path in changes:
1560
+ raise InstallError("legacy manifest conflicts with managed hook settings")
1561
+ before = base64.b64decode(inputs[path]["bytes_b64"].encode("ascii"), validate=True)
1562
+ changes[path] = self._legacy_hook_settings(release, before)
1563
+ result = []
1564
+ for raw, content in sorted(changes.items()):
1565
+ path = Path(raw)
1566
+ self._migration_target_root(path)
1567
+ before = {key: value for key, value in inputs[raw].items() if key != "bytes_b64"}
1568
+ result.append({"path": raw, "before": before,
1569
+ "after": self._planned_version(content),
1570
+ "mode": (path.stat().st_mode & 0o777) if path.exists() else 0o600})
1571
+ return result
1572
+
1573
+ def _validate_migration(self, journal: Path, data: dict[str, Any]) -> Path:
1574
+ self._safe_owned_path(journal, self.runtime / "migrations")
1575
+ phases = {"preflight", "cleanup", "install", "verify", "complete"}
1576
+ if data.get("kind") != "migrate" or data.get("phase") not in phases or \
1577
+ not isinstance(data.get("paths"), list) or not isinstance(data.get("plan"), dict) or \
1578
+ not isinstance(data.get("inputs"), dict):
1579
+ raise InstallError(f"legacy migration journal has no safe replay plan; recover its backup first: {journal}")
1580
+ release_record = data.get("release")
1581
+ if not isinstance(release_record, dict):
1582
+ raise InstallError(f"migration journal lacks its pinned release: {journal}")
1583
+ try:
1584
+ release = _valid_release(self.state_root, release_record)
1585
+ except TransactionError as exc:
1586
+ raise InstallError(f"invalid migration release: {journal}: {exc}") from exc
1587
+ self._safe_owned_path(release, self.runtime / "releases")
1588
+ if data.get("backup_root") != str(journal.parent / "backup"):
1589
+ raise InstallError(f"unsafe migration backup root: {journal}")
1590
+ self._safe_owned_path(Path(data["backup_root"]), journal.parent)
1591
+ cleanup_destinations = self._migration_cleanup_destinations(release)
1592
+ seen = set()
1593
+ path_names = {entry.get("path") for entry in data["paths"] if isinstance(entry, dict)}
1594
+ for raw, version in data["inputs"].items():
1595
+ self._migration_target_root(Path(raw))
1596
+ if not isinstance(version, dict) or not isinstance(version.get("exists"), bool):
1597
+ raise InstallError(f"invalid migration input version: {journal}")
1598
+ encoded = version.get("bytes_b64")
1599
+ if encoded is not None:
1600
+ if raw in path_names:
1601
+ raise InstallError(f"migration target input retains duplicate replay bytes: {journal}")
1602
+ if not version["exists"] or not isinstance(encoded, str):
1603
+ raise InstallError(f"invalid retained migration input bytes: {journal}")
1604
+ try:
1605
+ body = base64.b64decode(encoded.encode("ascii"), validate=True)
1606
+ except (ValueError, AttributeError) as exc:
1607
+ raise InstallError(f"invalid retained migration input bytes: {journal}") from exc
1608
+ if hashlib.sha256(body).hexdigest() != version.get("sha256"):
1609
+ raise InstallError(f"retained migration input digest mismatch: {journal}")
1610
+ for entry in data["paths"]:
1611
+ if not isinstance(entry, dict) or not isinstance(entry.get("path"), str) or entry["path"] in seen:
1612
+ raise InstallError(f"invalid migration path entries: {journal}")
1613
+ seen.add(entry["path"])
1614
+ if data["inputs"].get(entry["path"]) != entry.get("before"):
1615
+ raise InstallError(f"migration input and target versions disagree: {journal}")
1616
+ path = Path(entry["path"])
1617
+ self._migration_target_root(path)
1618
+ if path not in cleanup_destinations:
1619
+ raise InstallError(f"migration target is not a pinned legacy cleanup destination: {path}")
1620
+ if not all(isinstance(entry.get(k), dict) for k in ("before", "after")):
1621
+ raise InstallError(f"migration path lacks exact state: {journal}")
1622
+ for key in ("before", "after"):
1623
+ version = entry[key]
1624
+ if not isinstance(version.get("exists"), bool):
1625
+ raise InstallError(f"invalid migration file state: {journal}")
1626
+ if version["exists"]:
1627
+ if not re.fullmatch(r"[0-9a-f]{64}", str(version.get("sha256", ""))):
1628
+ raise InstallError(f"invalid migration file digest: {journal}")
1629
+ if key == "after":
1630
+ try:
1631
+ body = base64.b64decode(version["bytes_b64"].encode("ascii"), validate=True)
1632
+ except (KeyError, TypeError, ValueError, AttributeError) as exc:
1633
+ raise InstallError(f"invalid migration replay bytes: {journal}") from exc
1634
+ if hashlib.sha256(body).hexdigest() != version["sha256"]:
1635
+ raise InstallError(f"migration replay digest mismatch: {journal}")
1636
+ elif set(version) != {"exists"}:
1637
+ raise InstallError(f"absent migration file carries replay data: {journal}")
1638
+ return release
1639
+
1640
+ def _verify_transferred_events(self, plan: dict[str, Any]) -> None:
1641
+ """Keep every planned legacy event byte-for-byte present until commit."""
1642
+ for host, events in plan.get("events", {}).items():
1643
+ target = self.user_root / "learnings" / host / "events.jsonl"
1644
+ self._safe_owned_path(target, self.user_root)
1645
+ if target.is_symlink() or not target.is_file():
1646
+ raise InstallError(f"legacy learning transfer changed: {target}")
1647
+ conflicts: list[str] = []
1648
+ self._event_destination_conflicts(host, events, conflicts)
1649
+ if conflicts:
1650
+ raise InstallError("legacy learning transfer changed: " + "; ".join(conflicts))
1651
+ lines = set(target.read_text(encoding="utf-8").splitlines())
1652
+ missing = [event["learning_id"] for event in events if event["raw"] not in lines]
1653
+ if missing:
1654
+ raise InstallError(f"legacy learning transfer changed: {target}: " + ", ".join(missing))
1655
+
1656
+ def _verify_migration_native_state(self, release: Path, data: dict[str, Any], *, child_required: bool) -> None:
1657
+ """Check cleanup outputs and untouched native inputs before a resume commits.
1658
+
1659
+ The private child owns only its recorded launcher/config projections.
1660
+ Those exact paths may move from the migration's retired state to the
1661
+ child state; every other native path must remain at the journaled state.
1662
+ """
1663
+ child = InstructionsInstaller(release, self.env)
1664
+ child_owned = set(child._expected_owned(release))
1665
+ targets = {entry["path"]: entry for entry in data["paths"]}
1666
+ changed_inputs = [raw for raw, before in data["inputs"].items()
1667
+ if raw not in targets and not self._matches_version(Path(raw), before)]
1668
+ if changed_inputs:
1669
+ raise InstallError("migration input changed after cleanup: " + ", ".join(changed_inputs))
1670
+
1671
+ child_needs_verification = False
1672
+ for raw, entry in targets.items():
1673
+ path = Path(raw)
1674
+ if raw in child_owned:
1675
+ if not self._matches_version(path, entry["after"]):
1676
+ child_needs_verification = True
1677
+ continue
1678
+ if not self._matches_version(path, entry["after"]):
1679
+ raise InstallError(f"migration target changed after cleanup: {path}")
1680
+
1681
+ if not child_required and not child_needs_verification:
1682
+ return
1683
+ child_pending = any(row["kind"] == "install" for row in pending_status(self.state_root)["transactions"])
1684
+ if child_pending:
1685
+ if child_required:
1686
+ raise InstallError("pending private install prevents migration verification")
1687
+ # ``install`` below owns replaying this child journal. Its preflight
1688
+ # validates its exact projections before it writes any of them.
1689
+ return
1690
+ record = child._old_record()
1691
+ if record is None or record.get("package_root") != str(release):
1692
+ raise InstallError("migration private install is missing its pinned release")
1693
+ child.verify()
1694
+
1695
+ def _finish_migration(self, journal: Path, data: dict[str, Any]) -> dict[str, Any]:
1696
+ release = self._validate_migration(journal, data)
1697
+ plan, paths = data["plan"], data["paths"]
1698
+ try:
1699
+ with operation_scope(self.state_root):
1700
+ if data["phase"] in {"preflight", "cleanup"}:
1701
+ self._assert_preflight_paths(paths)
1702
+ targets = {entry["path"] for entry in paths}
1703
+ for raw, before in data["inputs"].items():
1704
+ if raw not in targets and not self._matches_version(Path(raw), before):
1705
+ raise InstallError(f"migration input changed: {raw}")
1706
+ for entry in paths:
1707
+ path = Path(entry["path"])
1708
+ if not entry["before"].get("exists"):
1709
+ continue
1710
+ backup = Path(data["backup_root"]) / "files" / str(path).lstrip("/")
1711
+ self._safe_owned_path(backup, journal.parent)
1712
+ if not self._matches_version(backup, entry["before"]):
1713
+ if not self._matches_version(path, entry["before"]):
1714
+ raise InstallError(f"original migration backup is missing or changed: {path}")
1715
+ self._backup(Path(data["backup_root"]), path)
1716
+ for host, events in plan["events"].items():
1717
+ conflicts: list[str] = []
1718
+ self._event_destination_conflicts(host, events, conflicts)
1719
+ if conflicts:
1720
+ raise InstallError("; ".join(conflicts))
1721
+ target = self.user_root / "learnings" / host / "events.jsonl"
1722
+ self._safe_owned_path(target, self.user_root)
1723
+ prior = target.read_text(encoding="utf-8").splitlines() if target.is_file() else []
1724
+ known = {json.loads(line)["learning_id"] for line in prior if line.strip()}
1725
+ additions = [event["raw"] for event in events if event["learning_id"] not in known]
1726
+ if additions:
1727
+ _atomic_bytes(target, ("\n".join(prior + additions) + "\n").encode("utf-8"), 0o600)
1728
+ self._verify_transferred_events(plan)
1729
+ data["state"], data["phase"] = "APPLYING", "cleanup"
1730
+ self._journal_write(journal, data)
1731
+ for entry in paths:
1732
+ path = Path(entry["path"])
1733
+ if not self._matches_version(path, entry["after"]):
1734
+ if not self._matches_version(path, entry["before"]):
1735
+ raise InstallError(f"migration target changed: {path}")
1736
+ self._write_planned(path, entry["after"], int(entry["mode"]))
1737
+ # This durable boundary prevents any retry from deleting a new projection.
1738
+ data["phase"] = "install"
1739
+ self._journal_write(journal, data)
1740
+ if data["phase"] == "install":
1741
+ self._verify_migration_native_state(release, data, child_required=False)
1742
+ self._verify_transferred_events(plan)
1743
+ installer = InstructionsInstaller(release, self.env)
1744
+ current = installer._old_record()
1745
+ child_pending = any(row["kind"] == "install" for row in
1746
+ pending_status(self.state_root)["transactions"])
1747
+ if current is not None and current.get("package_root") == str(release) and not child_pending:
1748
+ # A lost parent receipt must not publish a second installation.
1749
+ installer.verify()
1750
+ else:
1751
+ installer.install()
1752
+ data["phase"] = "verify"
1753
+ self._journal_write(journal, data)
1754
+ self._verify_migration_native_state(release, data, child_required=True)
1755
+ self._verify_transferred_events(plan)
1756
+ self.verify()
1757
+ # The last pre-commit observation is deliberately repeated: a
1758
+ # cooperative old collector or native writer can race a resume.
1759
+ # It cannot make a noncooperating producer atomic after this check.
1760
+ self._verify_migration_native_state(release, data, child_required=True)
1761
+ self._verify_transferred_events(plan)
1762
+ data.update(state="COMMITTED", phase="complete", committed_at=int(time.time()))
1763
+ self._journal_write(journal, data)
1764
+ return {"preview": False, "migration_id": journal.parent.name,
1765
+ "backup_root": data["backup_root"], "package_root": str(release), **plan}
1766
+ except BaseException as exc:
1767
+ data.update(state="NEEDS_RECOVERY", error=type(exc).__name__)
1768
+ self._journal_write(journal, data)
1769
+ raise
1770
+
1771
+ @_serialized
1772
+ def migrate(self, apply: bool = False, yes: bool = False) -> dict[str, Any]:
1773
+ pending = pending_status(self.state_root)["transactions"]
1774
+ migrations = [item for item in pending if item["kind"] == "migrate"]
1775
+ if len(migrations) > 1:
1776
+ raise InstallError("multiple pending migration journals require explicit recovery")
1777
+ if migrations:
1778
+ journal = Path(migrations[0]["path"])
1779
+ data = _read_json(journal)
1780
+ self._validate_migration(journal, data)
1781
+ if not apply:
1782
+ return {"preview": True, **data["plan"], "recovery_journal": str(journal), "phase": data["phase"]}
1783
+ if not yes:
1784
+ raise InstallError("migration apply requires --yes")
1785
+ return self._finish_migration(journal, data)
1786
+ if apply:
1787
+ try:
1788
+ guard_pending(self.state_root)
1789
+ except TransactionError as exc:
1790
+ raise InstallError(str(exc)) from exc
1791
+ plan, inputs = self._plan_migration()
1792
+ if not apply:
1793
+ return {"preview": True, **plan}
1794
+ if not yes:
1795
+ raise InstallError("migration apply requires --yes")
1796
+ if plan["needs_action"]:
1797
+ raise InstallError("legacy migration has unresolved ownership: " + "; ".join(plan["needs_action"]))
1798
+ release, entries, digest = self._copy_release(self._package_files(), False)
1799
+ paths = self._migration_paths(plan, release, inputs)
1800
+ changed = [raw for raw, before in inputs.items() if not self._matches_version(Path(raw), before)]
1801
+ if changed:
1802
+ raise InstallError("migration input changed during planning; retry with a fresh plan: " + ", ".join(changed))
1803
+ # Refuse an unlisted/user-edited shared destination before retiring anything.
1804
+ prior = self._old_record()
1805
+ retiring = set(plan["deletes"])
1806
+ for raw, expected in self._expected_owned(release).items():
1807
+ path = Path(raw)
1808
+ self._safe_owned_path(path, self.bin_root if path.parent == self.bin_root else self.launch_root)
1809
+ if raw not in retiring and path.exists() and _sha256(path) != expected and \
1810
+ _sha256(path) != self._owned_hash(prior, path):
1811
+ raise InstallError(f"private install cannot replace user-owned paths: {path}")
1812
+ migration_id = f"{int(time.time())}-{uuid.uuid4().hex[:12]}"
1813
+ journal = self.runtime / "migrations" / migration_id / "journal.json"
1814
+ backup_root = journal.parent / "backup"
1815
+ path_inputs = {entry["path"] for entry in paths}
1816
+ journal_data = {"schema_version": SCHEMA_VERSION, "owner": "installer", "kind": "migrate",
1817
+ "state": "PREPARED", "phase": "preflight", "plan": plan, "paths": paths,
1818
+ "inputs": {raw: ({k: v for k, v in before.items() if k != "bytes_b64"}
1819
+ if raw in path_inputs else before)
1820
+ for raw, before in inputs.items()},
1821
+ "prior_install": self._file_version(self.record_path),
1822
+ "release": {"package_root": str(release), "installed_files": entries, "release_digest": digest},
1823
+ "backup_root": str(backup_root), "created_at": int(time.time())}
1824
+ self._journal_write(journal, journal_data)
1825
+ return self._finish_migration(journal, journal_data)
1826
+
1827
+
1828
+ def main(argv: list[str] | None = None) -> int:
1829
+ parser = argparse.ArgumentParser(prog="agent-bios")
1830
+ parser.add_argument("--repo", help=argparse.SUPPRESS)
1831
+ subparsers = parser.add_subparsers(dest="command", required=True)
1832
+ install = subparsers.add_parser("install")
1833
+ install.add_argument("--domains")
1834
+ install.add_argument("--dry-run", action="store_true")
1835
+ install.add_argument("--with", dest="with_capabilities")
1836
+ onboard = subparsers.add_parser("onboard")
1837
+ onboard.add_argument("--domains")
1838
+ onboard.add_argument("--dry-run", action="store_true")
1839
+ onboard.add_argument("--with", dest="with_capabilities")
1840
+ for command in (install, onboard):
1841
+ interaction = command.add_mutually_exclusive_group()
1842
+ interaction.add_argument("--interactive", action="store_true", help="open the Textual installation wizard (default)")
1843
+ interaction.add_argument("--non-interactive", action="store_true", help="run without the wizard and return JSON")
1844
+ command.add_argument("--instructions", "--corpus", choices=("all", "none", "selected"),
1845
+ help="active instructions policy; none retains library assets privately but delivers no instructions")
1846
+ command.add_argument("--select", action="append", default=[], metavar="TARGET",
1847
+ help="package/domain/item target; repeat for multiple targets")
1848
+ subparsers.add_parser("verify")
1849
+ subparsers.add_parser("status")
1850
+ uninstall = subparsers.add_parser("uninstall")
1851
+ uninstall.add_argument("--dry-run", action="store_true")
1852
+ migrate = subparsers.add_parser("migrate")
1853
+ migrate.add_argument("--dry-run", action="store_true")
1854
+ migrate.add_argument("--apply", action="store_true")
1855
+ migrate.add_argument("--yes", action="store_true")
1856
+ reset = subparsers.add_parser("reset")
1857
+ reset.add_argument("--dry-run", action="store_true")
1858
+ reset.add_argument("--apply", action="store_true")
1859
+ reset.add_argument("--yes", action="store_true")
1860
+ reset.add_argument("--expected-revision", help="reset preview generation to accept")
1861
+ args = parser.parse_args(argv)
1862
+ installer = InstructionsInstaller(Path(args.repo) if args.repo else Path(__file__).resolve().parent.parent)
1863
+ interactive = False
1864
+ try:
1865
+ if args.command in {"install", "onboard"}:
1866
+ if args.with_capabilities:
1867
+ raise InstallError("use --interactive to select dependency installation; --with is legacy-only")
1868
+ interactive = not args.non_interactive
1869
+ if args.select and args.instructions != "selected":
1870
+ raise InstallError("--select requires --instructions selected")
1871
+ if interactive and args.domains is not None:
1872
+ raise InstallError("--domains is a compatibility selection flag; use --non-interactive or choose instructions in the wizard")
1873
+ if interactive:
1874
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
1875
+ raise InstallError("interactive installation needs an input/output terminal; use --non-interactive for automation or app tool calls")
1876
+ if os.environ.get("TERM") == "dumb":
1877
+ raise InstallError("this terminal cannot display the Textual wizard; use a capable terminal or --non-interactive")
1878
+ try:
1879
+ from .instructions_ui_runtime import activate_ui_runtime
1880
+ except ImportError:
1881
+ from instructions_ui_runtime import activate_ui_runtime
1882
+ activate_ui_runtime(installer.repo)
1883
+ try:
1884
+ from .instructions_setup_ui import run_setup_ui
1885
+ except ImportError:
1886
+ from instructions_setup_ui import run_setup_ui
1887
+ initial = None
1888
+ if args.instructions is not None:
1889
+ mode = "none" if args.instructions == "none" else "selected"
1890
+ targets = ["all"] if args.instructions == "all" else list(args.select) if args.instructions == "selected" else []
1891
+ initial = {"selection_mode": mode, "targets": targets, "dependencies": [],
1892
+ "app_bridge": False, "import_paths": [], "project_roots": []}
1893
+ result = run_setup_ui(installer, dry_run=args.dry_run, initial_plan=initial)
1894
+ else:
1895
+ mode = "none" if args.instructions == "none" else "selected" if args.instructions else None
1896
+ targets = ["all"] if args.instructions == "all" else args.select if args.instructions == "selected" else None
1897
+ result = installer.install(args.domains, args.dry_run, selection_mode=mode, targets=targets)
1898
+ elif args.command == "verify":
1899
+ result = installer.verify()
1900
+ elif args.command == "status":
1901
+ result = installer.status()
1902
+ elif args.command == "uninstall":
1903
+ result = installer.uninstall(args.dry_run)
1904
+ elif args.command == "reset":
1905
+ result = installer.reset(apply=args.apply and not args.dry_run, yes=args.yes,
1906
+ expected_revision=args.expected_revision)
1907
+ else:
1908
+ result = installer.migrate(apply=args.apply and not args.dry_run, yes=args.yes)
1909
+ if interactive:
1910
+ try:
1911
+ from .instructions_setup import format_setup_result
1912
+ except ImportError:
1913
+ from instructions_setup import format_setup_result
1914
+ print(format_setup_result(result, language=result.get("ui_language", "en")))
1915
+ else:
1916
+ print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
1917
+ return 1 if result.get("dependency_failed") or result.get("extras_error") or result.get("installation_error") or result.get("error") else 0
1918
+ except (InstallError, RuntimeError, ValueError, OSError) as exc:
1919
+ message = str(exc)
1920
+ language = getattr(exc, "ui_language", "en")
1921
+ if interactive and language != "en":
1922
+ try:
1923
+ from .instructions_setup_i18n import translate
1924
+ except ImportError:
1925
+ from instructions_setup_i18n import translate
1926
+ message = translate(language, "Setup could not finish. Details: {detail}", detail=message)
1927
+ print(f"instructions-install: {message}", file=sys.stderr)
1928
+ return 1
1929
+
1930
+
1931
+ if __name__ == "__main__":
1932
+ raise SystemExit(main())