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