agent-bios 0.19.4 → 0.20.1

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 (162) hide show
  1. package/DEPENDENCIES.md +20 -5
  2. package/README.md +14 -19
  3. package/claude/agents/frontier.md +1 -1
  4. package/claude/guides/claude-prompting.md +475 -234
  5. package/claude/guides/cli-multi-model-workflow.md +8 -7
  6. package/claude/guides/gpt-prompting.md +319 -144
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/agents/frontier.toml +1 -1
  10. package/codex/agents/reviewer.toml +1 -1
  11. package/codex/agents/workhorse.toml +1 -1
  12. package/codex/guides/claude-prompting.md +475 -234
  13. package/codex/guides/cli-multi-model-workflow.md +8 -7
  14. package/codex/guides/gpt-prompting.md +319 -144
  15. package/codex/guides/session-distill-workflow.md +93 -43
  16. package/codex/guides/tooling-gotchas.md +3 -1
  17. package/compose/assemble.py +4 -1
  18. package/compose/canary.sh +8 -6
  19. package/compose/host_platform.py +158 -15
  20. package/compose/instructions-state.py +183 -41
  21. package/compose/instructions_install.py +222 -27
  22. package/compose/instructions_session.py +250 -75
  23. package/compose/instructions_setup_cli.py +2 -36
  24. package/compose/instructions_store.py +160 -3
  25. package/compose/instructions_transaction.py +29 -5
  26. package/docs/advanced-launch.md +5 -1
  27. package/docs/releases/0.20.0.md +102 -0
  28. package/docs/releases/0.20.1.md +76 -0
  29. package/install.sh +42 -14
  30. package/launch/agent-launch.py +152 -18
  31. package/launch/agent-launch.toml +28 -16
  32. package/launch/agent-launch.zsh +104 -13
  33. package/launch/claude_subcommands.py +179 -0
  34. package/launch/shell_integration.py +7 -1
  35. package/learn/collect-learning.py +60 -9
  36. package/learn/migrate-learnings.py +70 -4
  37. package/learn/redact.py +2 -1
  38. package/package.json +36 -3
  39. package/provenance.json +1 -1
  40. package/session-cost.py +80 -9
  41. package/session-distill/coverage.json +6 -0
  42. package/session-distill/distill.py +2575 -0
  43. package/session-distill/grammar/__init__.py +0 -0
  44. package/session-distill/grammar/owner_lines.py +874 -0
  45. package/session-distill/originators.json +9 -0
  46. package/session-distill/packets/cross_review.md +31 -0
  47. package/session-distill/packets/form.md +86 -0
  48. package/session-distill/packets/judge.md +81 -0
  49. package/session-distill/packets/placement_contract.md +90 -0
  50. package/session-distill/packets/propose.md +124 -0
  51. package/session-distill/packets/read.md +57 -0
  52. package/session-distill/packets/reconsider.md +53 -0
  53. package/session-distill/packets/s7b.md +65 -0
  54. package/session-distill/packets/s9b.md +39 -0
  55. package/session-distill/packets/stitch.md +35 -0
  56. package/session-distill/packets/sweep.md +33 -0
  57. package/session-distill/runlib/__init__.py +0 -0
  58. package/session-distill/runlib/bound.py +1102 -0
  59. package/session-distill/runlib/breaker.py +467 -0
  60. package/session-distill/runlib/census.py +2347 -0
  61. package/session-distill/runlib/claims.py +420 -0
  62. package/session-distill/runlib/controls.py +902 -0
  63. package/session-distill/runlib/coverage.py +881 -0
  64. package/session-distill/runlib/declare.py +888 -0
  65. package/session-distill/runlib/delivery_evidence.py +1145 -0
  66. package/session-distill/runlib/derive.py +812 -0
  67. package/session-distill/runlib/destinations.py +3072 -0
  68. package/session-distill/runlib/dispatch.py +7940 -0
  69. package/session-distill/runlib/drift.py +1077 -0
  70. package/session-distill/runlib/entry.py +401 -0
  71. package/session-distill/runlib/evidence.py +890 -0
  72. package/session-distill/runlib/exposure.py +1162 -0
  73. package/session-distill/runlib/gate.py +2727 -0
  74. package/session-distill/runlib/gitread.py +79 -0
  75. package/session-distill/runlib/inventory.py +19624 -0
  76. package/session-distill/runlib/journal.py +1919 -0
  77. package/session-distill/runlib/ledger.py +3210 -0
  78. package/session-distill/runlib/ledger_compat.py +101 -0
  79. package/session-distill/runlib/ledger_migration.py +190 -0
  80. package/session-distill/runlib/lifecycle_intake.py +693 -0
  81. package/session-distill/runlib/lineage.py +454 -0
  82. package/session-distill/runlib/measures.py +249 -0
  83. package/session-distill/runlib/monitor.py +1180 -0
  84. package/session-distill/runlib/operations.py +522 -0
  85. package/session-distill/runlib/packet.py +838 -0
  86. package/session-distill/runlib/placement.py +1769 -0
  87. package/session-distill/runlib/projection.py +4090 -0
  88. package/session-distill/runlib/ranking.py +740 -0
  89. package/session-distill/runlib/receipts.py +200 -0
  90. package/session-distill/runlib/records.py +1965 -0
  91. package/session-distill/runlib/search.py +249 -0
  92. package/session-distill/runlib/sequencing.py +829 -0
  93. package/session-distill/runlib/sources.py +641 -0
  94. package/session-distill/runlib/stage_adjudicate.py +845 -0
  95. package/session-distill/runlib/stage_apply.py +1378 -0
  96. package/session-distill/runlib/stage_approvals.py +758 -0
  97. package/session-distill/runlib/stage_close.py +1220 -0
  98. package/session-distill/runlib/stage_confirm.py +929 -0
  99. package/session-distill/runlib/stage_delivery.py +3080 -0
  100. package/session-distill/runlib/stage_form.py +2576 -0
  101. package/session-distill/runlib/stage_judge.py +4248 -0
  102. package/session-distill/runlib/stage_propose.py +3307 -0
  103. package/session-distill/runlib/stage_read.py +5179 -0
  104. package/session-distill/runlib/stage_render.py +2739 -0
  105. package/session-distill/runlib/stage_retrieve.py +924 -0
  106. package/session-distill/runlib/stage_review_korean.py +1002 -0
  107. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  108. package/session-distill/runlib/stagelock.py +412 -0
  109. package/session-distill/runlib/stop.py +1061 -0
  110. package/session-distill/runlib/targets.py +809 -0
  111. package/session-distill/runlib/usage.py +280 -0
  112. package/session-distill/runlib/validate.py +319 -0
  113. package/session-distill/runlib/views.py +4327 -0
  114. package/session-distill/schemas/adjudication.schema.json +35 -0
  115. package/session-distill/schemas/approval.schema.json +35 -0
  116. package/session-distill/schemas/census.schema.json +128 -0
  117. package/session-distill/schemas/checks.schema.json +207 -0
  118. package/session-distill/schemas/claim.schema.json +16 -0
  119. package/session-distill/schemas/confirmation.schema.json +24 -0
  120. package/session-distill/schemas/coverage.schema.json +66 -0
  121. package/session-distill/schemas/cross_review.schema.json +24 -0
  122. package/session-distill/schemas/event.schema.json +20 -0
  123. package/session-distill/schemas/evidence.schema.json +20 -0
  124. package/session-distill/schemas/expected_observation.schema.json +18 -0
  125. package/session-distill/schemas/form.schema.json +103 -0
  126. package/session-distill/schemas/intake.schema.json +71 -0
  127. package/session-distill/schemas/inventory.schema.json +872 -0
  128. package/session-distill/schemas/judge.schema.json +77 -0
  129. package/session-distill/schemas/ledger.schema.json +313 -0
  130. package/session-distill/schemas/observation.schema.json +16 -0
  131. package/session-distill/schemas/propose.schema.json +555 -0
  132. package/session-distill/schemas/read.schema.json +76 -0
  133. package/session-distill/schemas/reconsider.schema.json +122 -0
  134. package/session-distill/schemas/run.schema.json +150 -0
  135. package/session-distill/schemas/s7b.schema.json +200 -0
  136. package/session-distill/schemas/s9b.schema.json +28 -0
  137. package/session-distill/schemas/stitch.schema.json +25 -0
  138. package/session-distill/schemas/sweep.schema.json +25 -0
  139. package/session-distill/seats.json +149 -0
  140. package/session-distill/tables/allowed_pairs.json +257 -0
  141. package/session-distill/tables/controls.json +30 -0
  142. package/session-distill/tables/delivery_evidence.json +36 -0
  143. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  144. package/session-distill/tables/destinations.json +684 -0
  145. package/session-distill/tables/drift_layers.json +68 -0
  146. package/session-distill/tables/exposure_rules.json +192 -0
  147. package/session-distill/tables/placement_rules.json +148 -0
  148. package/session-distill/tables/propose_fixtures.json +154 -0
  149. package/session-distill/tables/ranking.json +194 -0
  150. package/session-distill/tables/redundancy.json +10 -0
  151. package/session-distill/tables/structural_rules.json +44 -0
  152. package/session-distill/tables/transition_fixtures.json +398 -0
  153. package/session-distill/tables/transitions.json +69 -0
  154. package/session-distill/tables/unit_outcome.json +67 -0
  155. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  156. package/wrappers/claude-run.sh +481 -33
  157. package/wrappers/claude_hermetic_evidence.py +1423 -0
  158. package/wrappers/codex-helm.sh +46 -15
  159. package/wrappers/codex-run.sh +183 -20
  160. package/wrappers/codex_frame_filter.py +1199 -0
  161. package/wrappers/codex_protocol.py +737 -0
  162. package/wrappers/jsonl_lines.py +65 -0
@@ -5,23 +5,29 @@ records and pins; no global instructions, auth, or discovery registration is cop
5
5
  """
6
6
  from __future__ import annotations
7
7
  try:
8
- from host_platform import sync_directory, cli_argv
8
+ from host_platform import codex_protocol_for, sync_directory, cli_argv
9
9
  except ImportError:
10
- from .host_platform import sync_directory, cli_argv
10
+ from .host_platform import codex_protocol_for, sync_directory, cli_argv
11
11
 
12
12
  import hashlib
13
13
  import json
14
14
  import os
15
15
  import pathlib
16
- import queue
17
16
  import re
17
+ import shutil
18
+ import sqlite3
18
19
  import subprocess
19
20
  import sys
20
- import threading
21
+ import tempfile
21
22
  import time
22
23
  import uuid
23
24
  import unicodedata
24
25
 
26
+ # What a Codex activation's `rollout_method` says when it tried to resolve the rollout the host
27
+ # writes and could not. A pin that carries no rollout keys at all was written before this binding
28
+ # existed, which is a different fact and must never share this name.
29
+ ROLLOUT_UNRESOLVED = 'rollout_unresolved'
30
+
25
31
 
26
32
  class SessionError(RuntimeError):
27
33
  pass
@@ -160,77 +166,61 @@ def atomic_json(path, data):
160
166
  tmp.unlink(missing_ok=True)
161
167
 
162
168
 
169
+ def raise_on_termination():
170
+ """For the launcher, before it composes or resumes a session: a SIGTERM or SIGHUP that arrives while
171
+ a CodexServer is open ends the server's process group before the launcher ends by that signal, and
172
+ one that arrives at any other time ends the launcher as before (codex_protocol.raise_on_termination)."""
173
+ codex_protocol_for(__file__).raise_on_termination()
174
+
175
+
176
+ def _no_server_running():
177
+ """Refuse to open the user's session while a Codex app-server this process started is unreaped. The
178
+ launcher's SIGTERM and SIGHUP end the process at once only while it owns no such server, and the
179
+ session must see them so (codex_protocol.raise_on_termination): a server left open would turn them
180
+ into an exception that subprocess.call answers by killing the session."""
181
+ left = codex_protocol_for(__file__).unreaped()
182
+ if left:
183
+ raise SessionError(f"a Codex app-server this launch started is still running (process "
184
+ f"{', '.join(str(pid) for pid in left)}), so the session does not start")
185
+
186
+
163
187
  class CodexServer:
164
- """One owned stdio server. No turn/start or model generation is used."""
188
+ """One owned stdio server. No turn/start or model generation is used.
189
+
190
+ Before it starts, the installed Codex's generated protocol schema must carry every name the
191
+ session code uses (wrappers/codex_protocol.py, D-20261102-d8310f); the verdict is kept under the
192
+ state root when the caller names one. Every result is checked for the shape its reader expects."""
165
193
 
166
- def __init__(self, command, config_args=(), cwd=None, env=None):
194
+ def __init__(self, command, config_args=(), cwd=None, env=None, state_root=None):
167
195
  self.command, self.config_args, self.cwd, self.env = command, config_args, cwd, env
168
- self.sequence = 0
169
- self.events = queue.Queue()
196
+ self.state_root = state_root
197
+ self.protocol = codex_protocol_for(__file__)
170
198
 
171
199
  def __enter__(self):
172
- self.proc = subprocess.Popen(
173
- [self.command, *self.config_args, 'app-server', '--stdio'],
174
- stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
175
- cwd=self.cwd, env=self.env, text=True, encoding='utf-8',
176
- )
177
- self.reader = threading.Thread(target=self._read, daemon=True)
178
- self.reader.start()
200
+ cache = pathlib.Path(self.state_root) / 'codex-protocol' if self.state_root is not None else None
201
+ try:
202
+ self.protocol.ensure_schema(self.command, self.env, cache)
203
+ except self.protocol.ProtocolError as exc:
204
+ raise SessionError(str(exc)) from exc
205
+ self.client = self.protocol.Client([self.command, *self.config_args, 'app-server', '--stdio'],
206
+ cwd=self.cwd, env=self.env)
179
207
  try:
180
208
  self.call('initialize', {'clientInfo': {'name': 'agent-bios', 'version': '1'},
181
209
  'capabilities': {'experimentalApi': True}})
182
- self.proc.stdin.write('{"method":"initialized"}\n')
183
- self.proc.stdin.flush()
210
+ self.client.notify('initialized')
184
211
  return self
185
212
  except BaseException:
186
213
  self.__exit__(None, None, None)
187
214
  raise
188
215
 
189
- def _read(self):
190
- try:
191
- for line in self.proc.stdout:
192
- try:
193
- self.events.put(json.loads(line))
194
- except ValueError:
195
- self.events.put({'transport_error': 'invalid app-server JSON'})
196
- finally:
197
- self.events.put({'transport_error': 'app-server closed before its response'})
198
-
199
216
  def call(self, method, params, timeout=45):
200
- self.sequence += 1
201
- request_id = self.sequence
202
- self.proc.stdin.write(json.dumps({'id': request_id, 'method': method, 'params': params}) + '\n')
203
- self.proc.stdin.flush()
204
- deadline = time.monotonic() + timeout
205
- while time.monotonic() < deadline:
206
- try:
207
- message = self.events.get(timeout=max(0.01, deadline - time.monotonic()))
208
- except queue.Empty as exc:
209
- raise SessionError(f"app-server timed out: {method}") from exc
210
- if 'transport_error' in message:
211
- raise SessionError(message['transport_error'])
212
- if message.get('id') != request_id:
213
- continue
214
- if 'error' in message:
215
- raise SessionError(f"app-server {method}: {message['error'].get('message', 'refused')}")
216
- return message['result']
217
- raise SessionError(f"app-server timed out: {method}")
217
+ try:
218
+ return self.protocol.check_result(method, self.client.call(method, params, timeout))
219
+ except self.protocol.ProtocolError as exc:
220
+ raise SessionError(str(exc)) from exc
218
221
 
219
222
  def __exit__(self, *unused):
220
- if self.proc.stdin:
221
- self.proc.stdin.close()
222
- try:
223
- self.proc.wait(timeout=5)
224
- except subprocess.TimeoutExpired:
225
- self.proc.terminate()
226
- try:
227
- self.proc.wait(timeout=5)
228
- except subprocess.TimeoutExpired:
229
- self.proc.kill()
230
- self.proc.wait(timeout=5)
231
- if self.proc.stdout:
232
- self.proc.stdout.close()
233
- self.reader.join(timeout=2)
223
+ self.client.close()
234
224
 
235
225
 
236
226
  def config_flags(argv, exclude_developer=False):
@@ -409,14 +399,14 @@ def _with_codex_hooks(argv, hooks, config):
409
399
  return [*argv[:boundary], *flags, *argv[boundary:]]
410
400
 
411
401
 
412
- def validate_codex_hooks(command, snapshot, argv, cwd, env):
402
+ def validate_codex_hooks(command, snapshot, argv, cwd, env, state_root=None):
413
403
  """Prove discovery on this runtime; preserve native enablement and trust."""
414
404
  hooks = _codex_hook_config(snapshot)
415
405
  if not hooks:
416
406
  return
417
407
  expected = {(event[0].lower() + event[1:], group['matcher'], handler['command'])
418
408
  for event, groups in hooks.items() for group in groups for handler in group['hooks']}
419
- with CodexServer(command, config_flags(argv), cwd, env) as server:
409
+ with CodexServer(command, config_flags(argv), cwd, env, state_root) as server:
420
410
  result = server.call('hooks/list', {'cwds': [str(cwd)]})
421
411
  config = server.call('config/read', {'cwd': str(cwd), 'includeLayers': False})
422
412
  rows = result.get('data')
@@ -471,7 +461,7 @@ def _verified_launch_snapshot(state_root, snapshot):
471
461
  'assets': verified['output'].get('assets', {})}
472
462
 
473
463
 
474
- def compose_argv(command, argv, host, snapshot, cwd=None, env=None, include_global_instructions=True):
464
+ def compose_argv(command, argv, host, snapshot, cwd=None, env=None, include_global_instructions=True, state_root=None):
475
465
  """Preserve native instructions before the selected instructions and launch contract."""
476
466
  validate_working_directory_argv(host, argv)
477
467
  _global_instruction_choice(host, include_global_instructions)
@@ -499,11 +489,14 @@ def compose_argv(command, argv, host, snapshot, cwd=None, env=None, include_glob
499
489
  'profile semantics'
500
490
  )
501
491
  hooks = _codex_hook_config(snapshot)
502
- with CodexServer(command, config_flags(argv, exclude_developer=True), cwd, env) as server:
503
- config = server.call('config/read', {'cwd': str(cwd or pathlib.Path.cwd()), 'includeLayers': bool(hooks)})
504
- native = config.get('config', {}).get('developer_instructions') or ''
505
- if not isinstance(native, str):
506
- raise SessionError('effective developer_instructions are not text')
492
+ with CodexServer(command, config_flags(argv, exclude_developer=True), cwd, env, state_root) as server:
493
+ config = server.call('config/read', {'cwd': str(cwd or pathlib.Path.cwd()), 'includeLayers': True})
494
+ # Held to the layers that state it (D-20261102-efc529): null and "" are the user's none and
495
+ # empty value; an omitted key, or a value the layers do not give, refuses by name.
496
+ try:
497
+ native = server.protocol.developer_instructions(config)
498
+ except server.protocol.ProtocolError as exc:
499
+ raise SessionError(str(exc)) from exc
507
500
  result = replace_developer(argv, '\n\n'.join(x for x in (native, content, contract) if x))
508
501
  return _with_codex_hooks(result, hooks, config)
509
502
  boundary = argv.index('--') if '--' in argv else len(argv)
@@ -632,6 +625,179 @@ def recorded_cwd(record):
632
625
  return value
633
626
 
634
627
 
628
+ def resolve_codex_rollout(state_root, host_id, thread, env):
629
+ """The rollout file the Codex CLI writes for this thread: `{'path', 'id', 'how'}`, or None.
630
+
631
+ Without this, a pin named only by the app-server's thread id names no transcript a reader can find,
632
+ and a session's selection and delivery can only ever be reported unknown — measured over the
633
+ owner's state on 2026-10-23: 15 pins, 2,631 rollouts, 0 joins.
634
+
635
+ Order (lead, 2026-11-11, from the measurement under a temporary CODEX_HOME): `thread.path` first,
636
+ because with the installed host it IS the rollout and no file has to be read to say so; the host's
637
+ thread index second, for a host that gives no usable path; `rollout_unresolved` last, naming both
638
+ attempts. A time-window or cwd match is ruled out at every step: a wrong join attributes one
639
+ session's delivered bytes to another, which is worse than unknown, and nothing in the data tells a
640
+ right guess from a wrong one.
641
+
642
+ `rollout_id` is taken from the file NAME, never by reading the rollout: an activation that read the
643
+ file would be reading the host's transcript to write its own pin. The census keeps its own rule
644
+ (the first record's `session_meta.id`, else the name), so a census id that differs from the pinned
645
+ one — a fork, a rename — is a named reason there rather than a silent miss here.
646
+ """
647
+ rejected = []
648
+ # (1) The path the thread itself returned, and (2) the host's index row for exactly this thread id.
649
+ # BOTH go through the same test, because the index gives a path and nothing more: a path alone is not
650
+ # an association (X r1 F2), and neither is a name inside a directory that only looks like the
651
+ # configured home (X r2 F6).
652
+ for step, candidate in (('thread.path', (thread or {}).get('path')),
653
+ ('index', codex_index_rollout(env, host_id))):
654
+ accepted, why = _rollout_of_thread(candidate, host_id, env)
655
+ if accepted:
656
+ return {**accepted, 'how': step}
657
+ rejected.append(f'{step}: {why}')
658
+ print('agent-bios: no rollout resolved for this Codex thread; its pin records no transcript. '
659
+ + '; '.join(rejected), file=sys.stderr)
660
+ return None
661
+
662
+
663
+ def _rollout_of_thread(path, host_id, env):
664
+ """`({'path', 'id'}, None)` when `path` is PROVABLY this thread's rollout inside the configured
665
+ home, else `(None, why not)`.
666
+
667
+ Four things are asked, and each was a way in that the first realization left open:
668
+ the file exists and is named as a rollout; it lies inside the *resolved* configured home's sessions
669
+ tree, reached through a sessions root that resolves to that home's own (a `sessions` symlink
670
+ otherwise makes any foreign tree the boundary); it has exactly one link, since a hard link makes one
671
+ file two threads' with nothing on disk to tell them apart; and its name carries exactly one id,
672
+ which is this thread's, compared without case because a uuid is the same id in either case.
673
+
674
+ The last check is applied to the index row too. The row IS an association, but it carries only a
675
+ path, so a row naming a fork-shaped file costs this resolution a miss — the safe direction, since a
676
+ wrong join attributes one session's delivered bytes to another.
677
+ """
678
+ found = rollout_identity(path)
679
+ if found is None:
680
+ return None, 'no existing rollout file was named'
681
+ resolved, ids = found
682
+ home = native_home('codex', env or {})
683
+ try:
684
+ sessions = (home / 'sessions')
685
+ anchored = sessions.resolve() == (home.resolve() / 'sessions')
686
+ links = pathlib.Path(resolved).stat().st_nlink
687
+ except OSError as problem:
688
+ return None, f'its home or the file could not be read ({type(problem).__name__})'
689
+ if not anchored:
690
+ return None, "the configured home's sessions root resolves elsewhere, so it bounds nothing"
691
+ if not _under(resolved, sessions):
692
+ return None, 'it resolves outside the configured home'
693
+ if links > 1:
694
+ return None, f'it has {links} links, so which thread it belongs to is not decided'
695
+ if len(ids) != 1:
696
+ return None, f'its name carries {len(ids)} ids, so which thread it belongs to is not decided'
697
+ if ids[0].lower() != str(host_id).lower():
698
+ return None, "its name is another thread's id"
699
+ return {'path': resolved, 'id': ids[0]}, None
700
+
701
+
702
+ # A rollout as the host names it on disk. Declared here and not imported: the reader that owns this
703
+ # shape (session distill's `runlib/sources.py`) is author-side and the payload may not depend on it.
704
+ ROLLOUT_NAME = re.compile(r'^rollout-.*\.jsonl(\.zst)?$')
705
+ ROLLOUT_UUID = re.compile(r'[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}')
706
+
707
+
708
+ def rollout_identity(path):
709
+ """`(resolved path, [ids its name carries])` when `path` names an existing rollout file, else None.
710
+
711
+ Every id in the name is returned, not just one: a fork is written as two ids in one name, and
712
+ which thread such a file belongs to is for the caller to decide rather than for this to guess.
713
+ The comparison is by resolved path because a temporary or linked home answers through a symlink
714
+ (macOS `/var` is one), and an unresolved string compares unequal to the same file.
715
+ """
716
+ if not isinstance(path, str) or not path:
717
+ return None
718
+ try:
719
+ here = pathlib.Path(path).resolve()
720
+ except OSError:
721
+ return None
722
+ if not ROLLOUT_NAME.match(here.name) or not here.is_file():
723
+ return None
724
+ found = ROLLOUT_UUID.findall(here.name)
725
+ return (str(here), found) if found else None
726
+
727
+
728
+ def _under(path, directory):
729
+ """Is `path` (already resolved) inside `directory`, comparing both as the filesystem resolves them?"""
730
+ try:
731
+ return pathlib.Path(path).resolve().is_relative_to(pathlib.Path(directory).resolve())
732
+ except OSError:
733
+ return False
734
+
735
+
736
+ STATE_DATABASE = re.compile(r'^state_(\d+)\.sqlite$')
737
+
738
+
739
+ def codex_state_databases(home):
740
+ """The host's thread databases, the highest version first.
741
+
742
+ The version is PARSED, not sorted as text: `state_9.sqlite` sorts after `state_10.sqlite`
743
+ lexically, which would have read provenance out of an older store (X r1 F7).
744
+ """
745
+ found = []
746
+ for path in home.glob('state_*.sqlite') if home.is_dir() else []:
747
+ match = STATE_DATABASE.match(path.name)
748
+ if match and path.is_file() and not path.is_symlink():
749
+ found.append((int(match.group(1)), path))
750
+ return [path for _version, path in sorted(found, key=lambda row: row[0], reverse=True)]
751
+
752
+
753
+ def codex_index_rollout(env, host_id):
754
+ """The `rollout_path` the host's own thread index holds for this thread id, or None.
755
+
756
+ The index is read from a COPY. A read-only sqlite open of a live WAL database still moves the
757
+ host's `-shm` file, and this module writes nothing outside its own activation records and pins, so
758
+ the database and its sidecars are copied into a temporary directory and the copy is opened. A copy
759
+ taken while the host writes can be a moment old; that costs this resolution a miss, never a wrong
760
+ join, and the miss is reported as `rollout_unresolved`.
761
+ """
762
+ home = native_home('codex', env or {})
763
+ for database in codex_state_databases(home):
764
+ with tempfile.TemporaryDirectory(prefix='agent-bios-threads-') as scratch:
765
+ copy = pathlib.Path(scratch) / database.name
766
+ try:
767
+ for part in (database, *(database.with_name(database.name + suffix) for suffix in ('-wal', '-shm'))):
768
+ if part.is_file() and not part.is_symlink():
769
+ shutil.copy2(part, pathlib.Path(scratch) / part.name)
770
+ connection = sqlite3.connect(f'file:{copy}?mode=ro', uri=True, timeout=5)
771
+ except (OSError, sqlite3.Error):
772
+ continue # a database this process cannot read says nothing, so the next is asked
773
+ try:
774
+ if not connection.execute("select name from sqlite_master where type='table' "
775
+ "and name='threads'").fetchone():
776
+ continue
777
+ row = connection.execute('select rollout_path from threads where id = ?', (host_id,)).fetchone()
778
+ except sqlite3.Error:
779
+ continue
780
+ finally:
781
+ connection.close()
782
+ # The highest version this process could READ is the authority, whether or not it holds the
783
+ # thread: an older store's row for a thread the current one does not list is a stale
784
+ # association, and reading it resurrected one (X r2 F7).
785
+ return row[0] if row and isinstance(row[0], str) else None
786
+ return None
787
+
788
+
789
+ def pin_codex_rollout(record, rollout):
790
+ """Record on the activation what rollout it resolved, and how — null fields when it resolved none.
791
+
792
+ The keys are always written for a Codex activation, because their ABSENCE is what tells a reader
793
+ that a pin predates this binding, and their presence with null values that the activation tried.
794
+ """
795
+ record['rollout_path'] = (rollout or {}).get('path')
796
+ record['rollout_id'] = (rollout or {}).get('id')
797
+ record['rollout_method'] = (rollout or {}).get('how') or ROLLOUT_UNRESOLVED
798
+ return record
799
+
800
+
635
801
  def observe_and_pin(state_root, record, host_id, evidence):
636
802
  if not isinstance(record.get('intent_id'), str) or not re.fullmatch('[0-9a-f]{32}', record['intent_id']):
637
803
  raise SessionError('invalid activation journal identity')
@@ -737,10 +903,14 @@ def recover_activations(state_root, command=None, host=None, env=None):
737
903
  validate_session_id(requested)
738
904
  try:
739
905
  native_env = restore_environment(record, env)
740
- with CodexServer(command, config_flags(record['argv']), record['cwd'], native_env) as server:
906
+ with CodexServer(command, config_flags(record['argv']), record['cwd'], native_env, state_root) as server:
741
907
  observed = server.call('thread/read', {'threadId': requested, 'includeTurns': False})
742
908
  if observed.get('thread', {}).get('id') == requested:
743
- evidence = {'method': 'recovered-thread/read'}
909
+ # A recovered activation resolves the rollout too, or its pin would carry no
910
+ # rollout keys and read as one written before this binding existed.
911
+ pin_codex_rollout(record, resolve_codex_rollout(
912
+ state_root, requested, observed.get('thread', {}), native_env))
913
+ evidence = {'method': 'recovered-thread/read+' + record['rollout_method']}
744
914
  except SessionError as exc:
745
915
  print(f"agent-bios: activation {record['intent_id']} remains pending: {exc}", file=sys.stderr)
746
916
  if evidence:
@@ -753,7 +923,7 @@ def recover_activations(state_root, command=None, host=None, env=None):
753
923
 
754
924
  def create_codex_session(command, argv, state_root, record, cwd, env):
755
925
  validate_working_directory_argv('codex', argv)
756
- with CodexServer(command, config_flags(argv), cwd, env) as server:
926
+ with CodexServer(command, config_flags(argv), cwd, env, state_root) as server:
757
927
  params = {'cwd': str(cwd), 'developerInstructions': instruction_value(argv, 'codex'),
758
928
  'ephemeral': False, 'experimentalRawEvents': False}
759
929
  for index, token in enumerate(argv[:-1]):
@@ -771,12 +941,14 @@ def create_codex_session(command, argv, state_root, record, cwd, env):
771
941
  server.call('thread/inject_items', {'threadId': host_id, 'items': [
772
942
  {'type': 'message', 'role': 'developer', 'content': [
773
943
  {'type': 'input_text', 'text': f"agent-bios session snapshot: {record['content_ref']}"}]}]})
774
- with CodexServer(command, config_flags(argv), cwd, env) as server:
944
+ with CodexServer(command, config_flags(argv), cwd, env, state_root) as server:
775
945
  persisted = server.call('thread/read', {'threadId': host_id, 'includeTurns': False})
776
946
  if persisted.get('thread', {}).get('id') != host_id:
777
947
  raise SessionError('host did not persist the requested instructions session')
948
+ pin_codex_rollout(record, resolve_codex_rollout(state_root, host_id, thread, env))
778
949
  observe_and_pin(state_root, record, host_id,
779
- {'method': 'thread/start+inject_items+read', 'thread_path': thread.get('path')})
950
+ {'method': 'thread/start+inject_items+read+' + record['rollout_method'],
951
+ 'thread_path': thread.get('path')})
780
952
  return host_id
781
953
 
782
954
 
@@ -808,14 +980,15 @@ def launch(command, argv, state_root, host, snapshot, cwd=None, env=None, resume
808
980
  if host == 'claude':
809
981
  validate_claude_plugins(command, pinned, record['cwd'], env)
810
982
  else:
811
- validate_codex_hooks(command, pinned, record['argv'], record['cwd'], env)
983
+ validate_codex_hooks(command, pinned, record['argv'], record['cwd'], env, state_root)
812
984
  argv = record['argv']
813
985
  native = ['resume', resume_id, *argv] if host == 'codex' else ['--resume', resume_id, *argv]
986
+ _no_server_running()
814
987
  return subprocess.call([command, *native], cwd=record['cwd'], env=env)
815
988
  snapshot = _verified_launch_snapshot(state_root, snapshot)
816
- argv = compose_argv(command, argv, host, snapshot, cwd, env, include_global_instructions)
989
+ argv = compose_argv(command, argv, host, snapshot, cwd, env, include_global_instructions, state_root)
817
990
  if host == 'codex':
818
- validate_codex_hooks(command, snapshot, argv, cwd, env)
991
+ validate_codex_hooks(command, snapshot, argv, cwd, env, state_root)
819
992
  if host == 'claude':
820
993
  validate_claude_plugins(command, snapshot, cwd, env)
821
994
  record = prepare(state_root, host, snapshot, argv, cwd, env, include_global_instructions)
@@ -824,12 +997,14 @@ def launch(command, argv, state_root, host, snapshot, cwd=None, env=None, resume
824
997
  # id comes from the real host and is pinned before any user turn is possible.
825
998
  create_codex_session(command, argv, state_root, record, cwd, env)
826
999
  native = ['resume', record['session_id'], *argv]
1000
+ _no_server_running()
827
1001
  return subprocess.call([command, *native], cwd=cwd, env=env)
828
1002
  requested_id = str(uuid.uuid4())
829
1003
  record['requested_session_id'] = requested_id
830
1004
  intents, _ = session_paths(state_root)
831
1005
  atomic_json(intents / record['intent_id'] / 'journal.json', record)
832
1006
  native = ['--session-id', requested_id, *argv]
1007
+ _no_server_running()
833
1008
  child = subprocess.Popen([command, *native], cwd=cwd, env=env)
834
1009
  try:
835
1010
  while True:
@@ -21,9 +21,9 @@ if __name__ == "__main__":
21
21
  sys.dont_write_bytecode = True
22
22
 
23
23
  try:
24
- from host_platform import sync_directory, cli_argv, python_argv, runtime_environment
24
+ from host_platform import sync_directory, cli_argv, python_argv, runtime_environment, process_identity as _process_identity
25
25
  except ImportError:
26
- from .host_platform import sync_directory, cli_argv, python_argv, runtime_environment
26
+ from .host_platform import sync_directory, cli_argv, python_argv, runtime_environment, process_identity as _process_identity
27
27
 
28
28
  try:
29
29
  from instructions_install import InstructionsInstaller
@@ -95,40 +95,6 @@ def _identity() -> dict[str, Any]:
95
95
  "uid": os.getuid() if hasattr(os, "getuid") else None}
96
96
 
97
97
 
98
- def _process_identity(pid: int) -> str | None:
99
- if os.name == "nt":
100
- import ctypes
101
- from ctypes import wintypes
102
- kernel = ctypes.WinDLL("kernel32", use_last_error=True)
103
- kernel.OpenProcess.restype = wintypes.HANDLE
104
- kernel.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
105
- kernel.GetProcessTimes.argtypes = [wintypes.HANDLE] + [ctypes.POINTER(wintypes.FILETIME)] * 4
106
- kernel.CloseHandle.argtypes = [wintypes.HANDLE]
107
- handle = kernel.OpenProcess(0x1000, False, pid)
108
- if not handle:
109
- return None
110
- try:
111
- times = [wintypes.FILETIME() for _ in range(4)]
112
- if not kernel.GetProcessTimes(handle, *(ctypes.byref(t) for t in times)):
113
- return None
114
- return str((times[0].dwHighDateTime << 32) | times[0].dwLowDateTime)
115
- finally:
116
- kernel.CloseHandle(handle)
117
- if sys.platform.startswith("linux"):
118
- try:
119
- fields = (Path("/proc") / str(pid) / "stat").read_text().rsplit(")", 1)[1].split()
120
- return fields[19]
121
- except (OSError, IndexError):
122
- return None
123
- try:
124
- result = subprocess.run(["/bin/ps", "-p", str(pid), "-o", "lstart="], stdin=subprocess.DEVNULL,
125
- capture_output=True, text=True, timeout=3,
126
- env={**os.environ, "LC_ALL": "C", "TZ": "UTC"})
127
- return result.stdout.strip() if result.returncode == 0 and result.stdout.strip() else None
128
- except (OSError, subprocess.SubprocessError):
129
- return None
130
-
131
-
132
98
  def _read_json(path: Path) -> dict[str, Any]:
133
99
  reject_symlink_ancestors(path)
134
100
  if not path.is_file() or path.stat().st_size > 8 * 1024 * 1024: