agent-bios 0.19.0 → 0.19.2

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