agent-bios 0.19.1 → 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 +53 -26
  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 +5 -5
  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 -1847
  36. package/compose/corpus_session.py +16 -848
  37. package/compose/corpus_setup.py +16 -672
  38. package/compose/corpus_setup_cli.py +15 -580
  39. package/compose/corpus_setup_i18n.py +20 -324
  40. package/compose/corpus_setup_ui.py +18 -645
  41. package/compose/corpus_store.py +16 -1664
  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 -671
  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 +11 -11
  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 +10 -10
  69. package/docs/releases/0.19.2.md +38 -0
  70. package/docs/session-model.md +23 -20
  71. package/docs/setup.md +27 -26
  72. package/docs/understand.md +6 -6
  73. package/install.sh +70 -69
  74. package/launch/agent-launch.py +298 -290
  75. package/launch/agent-launch.toml +2 -2
  76. package/launch/i18n/en.toml +55 -55
  77. package/launch/i18n/ja.toml +56 -56
  78. package/launch/i18n/ko.toml +56 -56
  79. package/launch/shell_integration.py +4 -4
  80. package/learn/collect-learning.py +10 -10
  81. package/learn/learning.schema.json +1 -1
  82. package/learn/migrate-learnings.py +51 -51
  83. package/package.json +27 -11
  84. package/provenance.json +1 -1
  85. /package/docs/assets/{corpus-studio.svg → instructions-studio.svg} +0 -0
@@ -0,0 +1,306 @@
1
+ """Shared lock and durable pending-operation visibility for instructions state.
2
+
3
+ The instructions store owns source bytes and the installer owns projections. Neither
4
+ may publish independently while an install, reset or migration is incomplete: a reader
5
+ must see the completed generation or a clear recovery requirement, never a
6
+ mixture. Journals deliberately contain no token bytes.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import base64
12
+ import fcntl
13
+ import hashlib
14
+ import json
15
+ import os
16
+ from pathlib import Path
17
+ import stat
18
+ import sys
19
+ import threading
20
+ from typing import Any, Iterator
21
+
22
+
23
+ PENDING_STATES = frozenset({"PREPARED", "APPLYING", "NEEDS_RECOVERY"})
24
+ _local = threading.local()
25
+
26
+ # Both public import spellings must share the same reentrant lock and operation
27
+ # scope. Separate module objects can deadlock when a new installer calls an old
28
+ # release's store while already holding this process's lock.
29
+ if __name__ in {"instructions_transaction", "compose.instructions_transaction"}:
30
+ for _alias in ("instructions_transaction", "compose.instructions_transaction",
31
+ "corpus_transaction", "compose.corpus_transaction"):
32
+ sys.modules[_alias] = sys.modules[__name__]
33
+
34
+
35
+ class TransactionError(RuntimeError):
36
+ pass
37
+
38
+
39
+ class TransactionPendingError(TransactionError):
40
+ pass
41
+
42
+
43
+ def environment_value(env, canonical: str, legacy: str, default=None):
44
+ """Resolve one renamed environment setting without silently splitting state."""
45
+ current, previous = env.get(canonical), env.get(legacy)
46
+ if current is not None and previous is not None and current != previous:
47
+ raise TransactionError(f"conflicting {canonical} and {legacy}; set one value")
48
+ return current if current is not None else previous if previous is not None else default
49
+
50
+
51
+ def reject_symlink_ancestors(path: Path) -> None:
52
+ """Refuse redirected user paths, allowing only macOS's fixed system aliases.
53
+
54
+ /var, /tmp and /etc are root-owned aliases to /private on macOS. They precede
55
+ ordinary temporary HOME/state roots and are not user-controlled redirections.
56
+ The exception names their exact destinations and never applies to the leaf,
57
+ a same-named link elsewhere, or a user-owned link.
58
+ """
59
+ for ancestor in (path, *path.parents):
60
+ if not ancestor.is_symlink():
61
+ continue
62
+ system_alias = (sys.platform == "darwin" and ancestor != path
63
+ and ancestor in {Path("/var"), Path("/tmp"), Path("/etc")}
64
+ and ancestor.lstat().st_uid == 0
65
+ and ancestor.parent / os.readlink(ancestor) == Path("/private") / ancestor.name)
66
+ if not system_alias:
67
+ raise TransactionError(f"refusing symlink transaction target: {ancestor}")
68
+
69
+
70
+ def _key(state_root: Path) -> str:
71
+ return str(Path(state_root).expanduser().resolve())
72
+
73
+
74
+ def _depths(name: str) -> dict[str, int]:
75
+ value = getattr(_local, name, None)
76
+ if value is None:
77
+ value = {}
78
+ setattr(_local, name, value)
79
+ return value
80
+
81
+
82
+ @contextlib.contextmanager
83
+ def _transaction_lock(state_root: Path, *, readonly: bool) -> Iterator[bool]:
84
+ root = Path(state_root).expanduser()
85
+ if root.is_symlink():
86
+ raise TransactionError(f"unsafe instructions state root: {root}")
87
+ if readonly:
88
+ reject_symlink_ancestors(root)
89
+ key = _key(root)
90
+ depths = _depths("lock_depths")
91
+ if depths.get(key, 0):
92
+ depths[key] += 1
93
+ try:
94
+ yield True
95
+ finally:
96
+ depths[key] -= 1
97
+ return
98
+ if not readonly:
99
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
100
+ # Schema-v1 lock identity is retained so old and new writers serialize together.
101
+ lock = root / ".corpus-store.lock"
102
+ if lock.is_symlink():
103
+ raise TransactionError(f"unsafe instructions transaction lock: {lock}")
104
+ flags = (os.O_RDONLY | os.O_NONBLOCK if readonly else os.O_CREAT | os.O_RDWR) | getattr(os, "O_NOFOLLOW", 0)
105
+ try:
106
+ descriptor = os.open(lock, flags, 0o600)
107
+ except FileNotFoundError:
108
+ if not readonly:
109
+ raise
110
+ yield False
111
+ return
112
+ try:
113
+ if readonly and not stat.S_ISREG(os.fstat(descriptor).st_mode):
114
+ raise TransactionError(f"unsafe instructions transaction lock: {lock}")
115
+ try:
116
+ fcntl.flock(descriptor, fcntl.LOCK_EX | (fcntl.LOCK_NB if readonly else 0))
117
+ except BlockingIOError:
118
+ if not readonly:
119
+ raise
120
+ yield False
121
+ return
122
+ depths[key] = 1
123
+ try:
124
+ yield True
125
+ finally:
126
+ depths.pop(key, None)
127
+ fcntl.flock(descriptor, fcntl.LOCK_UN)
128
+ finally:
129
+ os.close(descriptor)
130
+
131
+
132
+ @contextlib.contextmanager
133
+ def transaction_lock(state_root: Path) -> Iterator[None]:
134
+ """The single re-entrant cross-process lock for store and installer work."""
135
+ with _transaction_lock(state_root, readonly=False):
136
+ yield
137
+
138
+
139
+ @contextlib.contextmanager
140
+ def try_transaction_lock(state_root: Path) -> Iterator[bool]:
141
+ """Observe under the existing lock, or defer without blocking or creating state."""
142
+ with _transaction_lock(state_root, readonly=True) as acquired:
143
+ yield acquired
144
+
145
+
146
+ @contextlib.contextmanager
147
+ def operation_scope(state_root: Path) -> Iterator[None]:
148
+ """Permit the coordinating writer to inspect its own pending journal."""
149
+ key = _key(Path(state_root))
150
+ depths = _depths("operation_depths")
151
+ depths[key] = depths.get(key, 0) + 1
152
+ try:
153
+ yield
154
+ finally:
155
+ remaining = depths[key] - 1
156
+ if remaining:
157
+ depths[key] = remaining
158
+ else:
159
+ depths.pop(key, None)
160
+
161
+
162
+ def operation_scope_active(state_root: Path) -> bool:
163
+ return bool(_depths("operation_depths").get(_key(Path(state_root)), 0))
164
+
165
+
166
+ def _journal_records(state_root: Path, *, coordinator_only: bool = False) -> list[dict[str, Any]]:
167
+ root = Path(state_root).expanduser() / "runtime"
168
+ records: list[dict[str, Any]] = []
169
+ # ``resets`` predates the unified transaction directory and remains visible
170
+ # so an old interrupted reset is never silently treated as complete.
171
+ for directory in (root / "transactions", root / "installer-transactions", root / "resets", root / "migrations"):
172
+ if not directory.exists():
173
+ continue
174
+ if directory.is_symlink() or not directory.is_dir():
175
+ raise TransactionError(f"unsafe transaction journal root: {directory}")
176
+ for journal in sorted(directory.glob("*/journal.json")):
177
+ if journal.parent.is_symlink() or journal.is_symlink() or not journal.is_file():
178
+ raise TransactionError(f"unsafe transaction journal: {journal}")
179
+ try:
180
+ value = json.loads(journal.read_text(encoding="utf-8"))
181
+ except (OSError, ValueError) as exc:
182
+ raise TransactionError(f"unreadable transaction journal: {journal}") from exc
183
+ if not isinstance(value, dict):
184
+ raise TransactionError(f"invalid transaction journal: {journal}")
185
+ # Store owns its source-only install journal. It can safely finish
186
+ # its own PREPARED source pair under the same lock; launcher/config
187
+ # readers must only block on the wider installer/reset coordinator.
188
+ coordinator = directory.name in {"installer-transactions", "resets", "migrations"} or value.get("owner") == "installer"
189
+ if value.get("state") in PENDING_STATES and (not coordinator_only or coordinator):
190
+ fallback = "migrate" if directory.name == "migrations" else "reset" if coordinator else "source"
191
+ records.append({"path": str(journal), "kind": value.get("kind", fallback),
192
+ "owner": "installer" if coordinator else "store",
193
+ "state": value.get("state"), "phase": value.get("phase")})
194
+ return records
195
+
196
+
197
+ def pending_status(state_root: Path) -> dict[str, Any]:
198
+ records = _journal_records(state_root)
199
+ return {"pending": bool(records), "transactions": records}
200
+
201
+
202
+ def pending_operations(state_root: Path) -> list[dict[str, Any]]:
203
+ """Return pending journals for source readers and management views."""
204
+ return pending_status(state_root)["transactions"]
205
+
206
+
207
+ def guard_pending(state_root: Path) -> None:
208
+ """Fail before a config/source reader consumes an incomplete publication."""
209
+ key = _key(Path(state_root))
210
+ if _depths("operation_depths").get(key, 0):
211
+ return
212
+ pending = _journal_records(state_root, coordinator_only=True)
213
+ if pending:
214
+ first = pending[0]
215
+ raise TransactionPendingError(
216
+ "instructions install/reset/migration needs recovery before reading current configuration: "
217
+ f"{first['path']} ({first['state']})"
218
+ )
219
+
220
+
221
+ def _valid_release(state_root: Path, record: dict[str, Any]) -> Path:
222
+ raw = record.get("package_root")
223
+ digest = record.get("release_digest")
224
+ if not isinstance(raw, str) or not isinstance(digest, str):
225
+ raise TransactionPendingError("private install record has no confirmed immutable release")
226
+ root = (Path(state_root).expanduser() / "runtime" / "releases").absolute()
227
+ release = Path(raw)
228
+ try:
229
+ release.absolute().relative_to(root)
230
+ except ValueError as exc:
231
+ raise TransactionPendingError("private install record points outside immutable releases") from exc
232
+ if release.name != digest or release.is_symlink() or not release.is_dir():
233
+ raise TransactionPendingError("private install record has an invalid immutable release")
234
+ entries = record.get("installed_files")
235
+ if not isinstance(entries, list) or not entries:
236
+ raise TransactionPendingError("private install record has no release inventory")
237
+ # The release digest is the digest of the ordered path+bytes stream. The
238
+ # installer computes it before any pointer publication, so this is a cheap
239
+ # structural confirmation suitable for a config reader; full verification
240
+ # remains InstructionsInstaller.verify's responsibility.
241
+ actual = hashlib.sha256()
242
+ for entry in entries:
243
+ if not isinstance(entry, dict) or not isinstance(entry.get("path"), str):
244
+ raise TransactionPendingError("private install record has invalid release inventory")
245
+ relative = Path(entry["path"])
246
+ if relative.is_absolute() or ".." in relative.parts:
247
+ raise TransactionPendingError("private install record has unsafe release inventory")
248
+ member = release / relative
249
+ if member.is_symlink() or not member.is_file():
250
+ raise TransactionPendingError("confirmed release member is unavailable")
251
+ data = member.read_bytes()
252
+ actual.update(entry["path"].encode("utf-8") + b"\0" + data + b"\0")
253
+ if actual.hexdigest() != digest:
254
+ raise TransactionPendingError("confirmed release digest does not match inventory")
255
+ return release
256
+
257
+
258
+ def confirmed_release(state_root: Path) -> Path:
259
+ """Return the last fully confirmed release while a coordinator is pending.
260
+
261
+ A pending update's ``after`` record is deliberately not trusted. The
262
+ journal's exact ``before`` private-install bytes identify the previous
263
+ generation; a first installation has none and therefore fails closed.
264
+ """
265
+ root = Path(state_root).expanduser()
266
+ pending = _journal_records(root, coordinator_only=True)
267
+ migration = next((item for item in pending if item["kind"] == "migrate"), None)
268
+ if migration is not None:
269
+ try:
270
+ value = json.loads(Path(migration["path"]).read_text(encoding="utf-8"))
271
+ before = value["prior_install"]
272
+ encoded = before.get("bytes_b64") if isinstance(before, dict) else None
273
+ if not isinstance(encoded, str):
274
+ raise ValueError("no prior private install")
275
+ record = json.loads(base64.b64decode(encoded.encode("ascii"), validate=True))
276
+ except (KeyError, OSError, ValueError, TypeError) as exc:
277
+ raise TransactionPendingError("pending migration has no confirmed prior private install") from exc
278
+ if not isinstance(record, dict):
279
+ raise TransactionPendingError("prior migration install record is invalid")
280
+ return _valid_release(root, record)
281
+ install = next((item for item in pending if item["kind"] == "install"), None)
282
+ if install is not None:
283
+ journal = Path(install["path"])
284
+ try:
285
+ value = json.loads(journal.read_text(encoding="utf-8"))
286
+ record_entry = next(entry for entry in value.get("paths", [])
287
+ if isinstance(entry, dict) and str(entry.get("path", "")).endswith(
288
+ "/runtime/private-install.json"))
289
+ before = record_entry.get("before", {})
290
+ encoded = before.get("bytes_b64") if isinstance(before, dict) else None
291
+ if not isinstance(encoded, str):
292
+ raise ValueError("no prior private-install record")
293
+ record = json.loads(base64.b64decode(encoded.encode("ascii"), validate=True))
294
+ except (StopIteration, ValueError, TypeError, json.JSONDecodeError) as exc:
295
+ raise TransactionPendingError("first or incomplete install has no confirmed prior release") from exc
296
+ if not isinstance(record, dict):
297
+ raise TransactionPendingError("prior private-install record is invalid")
298
+ return _valid_release(root, record)
299
+ path = root / "runtime" / "private-install.json"
300
+ try:
301
+ record = json.loads(path.read_text(encoding="utf-8"))
302
+ except (OSError, ValueError) as exc:
303
+ raise TransactionPendingError("pending reset has no confirmed private install") from exc
304
+ if not isinstance(record, dict):
305
+ raise TransactionPendingError("confirmed private install is invalid")
306
+ return _valid_release(root, record)