agent-bios 0.19.3 → 0.20.0

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 (172) hide show
  1. package/DEPENDENCIES.md +62 -20
  2. package/INSTALL.md +1 -1
  3. package/README.md +16 -21
  4. package/claude/agents/frontier.md +1 -1
  5. package/claude/agents/sweep.md +2 -1
  6. package/claude/agents/workhorse.md +2 -2
  7. package/claude/guides/claude-prompting.md +494 -167
  8. package/claude/guides/cli-multi-model-workflow.md +8 -7
  9. package/claude/guides/gpt-prompting.md +241 -111
  10. package/claude/guides/session-distill-workflow.md +93 -43
  11. package/claude/guides/tooling-gotchas.md +3 -1
  12. package/codex/agents/reviewer.toml +2 -2
  13. package/codex/agents/sweep.toml +1 -1
  14. package/codex/agents/workhorse.toml +2 -2
  15. package/codex/guides/claude-prompting.md +494 -167
  16. package/codex/guides/cli-multi-model-workflow.md +8 -7
  17. package/codex/guides/gpt-prompting.md +241 -111
  18. package/codex/guides/session-distill-workflow.md +93 -43
  19. package/codex/guides/tooling-gotchas.md +3 -1
  20. package/compose/assemble.py +4 -1
  21. package/compose/canary.sh +8 -6
  22. package/compose/host_platform.py +158 -15
  23. package/compose/instructions-state.py +183 -41
  24. package/compose/instructions_app.py +2 -2
  25. package/compose/instructions_install.py +222 -27
  26. package/compose/instructions_session.py +250 -75
  27. package/compose/instructions_setup.py +6 -6
  28. package/compose/instructions_setup_cli.py +2 -36
  29. package/compose/instructions_setup_i18n.py +3 -3
  30. package/compose/instructions_store.py +160 -3
  31. package/compose/instructions_transaction.py +29 -5
  32. package/compose/instructions_ui_runtime.py +2 -2
  33. package/compose/setup/START.md +1 -1
  34. package/docs/advanced-launch.md +4 -0
  35. package/docs/releases/0.19.4.md +99 -0
  36. package/docs/releases/0.20.0.md +102 -0
  37. package/docs/setup.md +4 -4
  38. package/install.sh +54 -20
  39. package/launch/agent-launch.py +171 -22
  40. package/launch/agent-launch.toml +64 -29
  41. package/launch/agent-launch.zsh +104 -13
  42. package/launch/claude_subcommands.py +179 -0
  43. package/launch/provision-venv.sh +1 -1
  44. package/launch/shell_integration.py +7 -1
  45. package/learn/collect-learning.py +60 -9
  46. package/learn/migrate-learnings.py +70 -4
  47. package/learn/redact.py +2 -1
  48. package/package.json +37 -4
  49. package/provenance.json +1 -1
  50. package/session-cost.py +141 -18
  51. package/session-distill/coverage.json +6 -0
  52. package/session-distill/distill.py +2575 -0
  53. package/session-distill/grammar/__init__.py +0 -0
  54. package/session-distill/grammar/owner_lines.py +874 -0
  55. package/session-distill/originators.json +9 -0
  56. package/session-distill/packets/cross_review.md +31 -0
  57. package/session-distill/packets/form.md +86 -0
  58. package/session-distill/packets/judge.md +81 -0
  59. package/session-distill/packets/placement_contract.md +90 -0
  60. package/session-distill/packets/propose.md +124 -0
  61. package/session-distill/packets/read.md +57 -0
  62. package/session-distill/packets/reconsider.md +53 -0
  63. package/session-distill/packets/s7b.md +65 -0
  64. package/session-distill/packets/s9b.md +39 -0
  65. package/session-distill/packets/stitch.md +35 -0
  66. package/session-distill/packets/sweep.md +33 -0
  67. package/session-distill/runlib/__init__.py +0 -0
  68. package/session-distill/runlib/bound.py +1102 -0
  69. package/session-distill/runlib/breaker.py +467 -0
  70. package/session-distill/runlib/census.py +2347 -0
  71. package/session-distill/runlib/claims.py +420 -0
  72. package/session-distill/runlib/controls.py +902 -0
  73. package/session-distill/runlib/coverage.py +881 -0
  74. package/session-distill/runlib/declare.py +888 -0
  75. package/session-distill/runlib/delivery_evidence.py +1145 -0
  76. package/session-distill/runlib/derive.py +812 -0
  77. package/session-distill/runlib/destinations.py +3072 -0
  78. package/session-distill/runlib/dispatch.py +7939 -0
  79. package/session-distill/runlib/drift.py +1077 -0
  80. package/session-distill/runlib/entry.py +401 -0
  81. package/session-distill/runlib/evidence.py +890 -0
  82. package/session-distill/runlib/exposure.py +1162 -0
  83. package/session-distill/runlib/gate.py +2727 -0
  84. package/session-distill/runlib/gitread.py +79 -0
  85. package/session-distill/runlib/inventory.py +19624 -0
  86. package/session-distill/runlib/journal.py +1919 -0
  87. package/session-distill/runlib/ledger.py +3210 -0
  88. package/session-distill/runlib/ledger_compat.py +101 -0
  89. package/session-distill/runlib/ledger_migration.py +190 -0
  90. package/session-distill/runlib/lifecycle_intake.py +693 -0
  91. package/session-distill/runlib/lineage.py +454 -0
  92. package/session-distill/runlib/measures.py +249 -0
  93. package/session-distill/runlib/monitor.py +1180 -0
  94. package/session-distill/runlib/operations.py +522 -0
  95. package/session-distill/runlib/packet.py +838 -0
  96. package/session-distill/runlib/placement.py +1769 -0
  97. package/session-distill/runlib/projection.py +4090 -0
  98. package/session-distill/runlib/ranking.py +740 -0
  99. package/session-distill/runlib/receipts.py +200 -0
  100. package/session-distill/runlib/records.py +1965 -0
  101. package/session-distill/runlib/search.py +249 -0
  102. package/session-distill/runlib/sequencing.py +829 -0
  103. package/session-distill/runlib/sources.py +641 -0
  104. package/session-distill/runlib/stage_adjudicate.py +845 -0
  105. package/session-distill/runlib/stage_apply.py +1378 -0
  106. package/session-distill/runlib/stage_approvals.py +758 -0
  107. package/session-distill/runlib/stage_close.py +1220 -0
  108. package/session-distill/runlib/stage_confirm.py +929 -0
  109. package/session-distill/runlib/stage_delivery.py +3080 -0
  110. package/session-distill/runlib/stage_form.py +2576 -0
  111. package/session-distill/runlib/stage_judge.py +4248 -0
  112. package/session-distill/runlib/stage_propose.py +3307 -0
  113. package/session-distill/runlib/stage_read.py +5179 -0
  114. package/session-distill/runlib/stage_render.py +2739 -0
  115. package/session-distill/runlib/stage_retrieve.py +924 -0
  116. package/session-distill/runlib/stage_review_korean.py +1002 -0
  117. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  118. package/session-distill/runlib/stagelock.py +412 -0
  119. package/session-distill/runlib/stop.py +1061 -0
  120. package/session-distill/runlib/targets.py +809 -0
  121. package/session-distill/runlib/usage.py +280 -0
  122. package/session-distill/runlib/validate.py +319 -0
  123. package/session-distill/runlib/views.py +4327 -0
  124. package/session-distill/schemas/adjudication.schema.json +35 -0
  125. package/session-distill/schemas/approval.schema.json +35 -0
  126. package/session-distill/schemas/census.schema.json +128 -0
  127. package/session-distill/schemas/checks.schema.json +207 -0
  128. package/session-distill/schemas/claim.schema.json +16 -0
  129. package/session-distill/schemas/confirmation.schema.json +24 -0
  130. package/session-distill/schemas/coverage.schema.json +66 -0
  131. package/session-distill/schemas/cross_review.schema.json +24 -0
  132. package/session-distill/schemas/event.schema.json +20 -0
  133. package/session-distill/schemas/evidence.schema.json +20 -0
  134. package/session-distill/schemas/expected_observation.schema.json +18 -0
  135. package/session-distill/schemas/form.schema.json +103 -0
  136. package/session-distill/schemas/intake.schema.json +71 -0
  137. package/session-distill/schemas/inventory.schema.json +872 -0
  138. package/session-distill/schemas/judge.schema.json +77 -0
  139. package/session-distill/schemas/ledger.schema.json +313 -0
  140. package/session-distill/schemas/observation.schema.json +16 -0
  141. package/session-distill/schemas/propose.schema.json +555 -0
  142. package/session-distill/schemas/read.schema.json +76 -0
  143. package/session-distill/schemas/reconsider.schema.json +122 -0
  144. package/session-distill/schemas/run.schema.json +150 -0
  145. package/session-distill/schemas/s7b.schema.json +200 -0
  146. package/session-distill/schemas/s9b.schema.json +28 -0
  147. package/session-distill/schemas/stitch.schema.json +25 -0
  148. package/session-distill/schemas/sweep.schema.json +25 -0
  149. package/session-distill/seats.json +149 -0
  150. package/session-distill/tables/allowed_pairs.json +257 -0
  151. package/session-distill/tables/controls.json +30 -0
  152. package/session-distill/tables/delivery_evidence.json +36 -0
  153. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  154. package/session-distill/tables/destinations.json +684 -0
  155. package/session-distill/tables/drift_layers.json +68 -0
  156. package/session-distill/tables/exposure_rules.json +192 -0
  157. package/session-distill/tables/placement_rules.json +148 -0
  158. package/session-distill/tables/propose_fixtures.json +154 -0
  159. package/session-distill/tables/ranking.json +194 -0
  160. package/session-distill/tables/redundancy.json +10 -0
  161. package/session-distill/tables/structural_rules.json +44 -0
  162. package/session-distill/tables/transition_fixtures.json +398 -0
  163. package/session-distill/tables/transitions.json +69 -0
  164. package/session-distill/tables/unit_outcome.json +67 -0
  165. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  166. package/wrappers/claude-run.sh +481 -33
  167. package/wrappers/claude_hermetic_evidence.py +1423 -0
  168. package/wrappers/codex-helm.sh +44 -13
  169. package/wrappers/codex-run.sh +183 -20
  170. package/wrappers/codex_frame_filter.py +1199 -0
  171. package/wrappers/codex_protocol.py +737 -0
  172. package/wrappers/jsonl_lines.py +65 -0
@@ -22,9 +22,9 @@ import io
22
22
  import json
23
23
  import contextlib
24
24
  try:
25
- from host_platform import file_locks as fcntl
25
+ from host_platform import LockWaitExpired, file_locks as fcntl, lock_within
26
26
  except ImportError:
27
- from .host_platform import file_locks as fcntl
27
+ from .host_platform import LockWaitExpired, file_locks as fcntl, lock_within
28
28
  import os
29
29
  import pathlib
30
30
  import shutil
@@ -160,7 +160,9 @@ def domains_projection(repo: pathlib.Path) -> dict:
160
160
  return {"available": available, "applied": applied}
161
161
 
162
162
 
163
- def cmd_project(args: argparse.Namespace) -> int:
163
+ def cmd_project(args: argparse.Namespace, status_locked: bool = False) -> int:
164
+ """Project the instructions status. `status_locked`: the caller already holds the status lock
165
+ (a rollback, which takes it before its first live write and keeps it to its last status write)."""
164
166
  repo = repo_root(args.repo)
165
167
  versions_doc = load_versions(repo)
166
168
  versions = versions_doc["versions"] if versions_doc is not None else None
@@ -169,7 +171,7 @@ def cmd_project(args: argparse.Namespace) -> int:
169
171
  deployed_instructions = None
170
172
  # Read and write under one lock: unlocked, a concurrent record-apply or
171
173
  # rollback landing between this read and the write below is reverted whole.
172
- with _status_lock():
174
+ with contextlib.nullcontext() if status_locked else _status_lock():
173
175
  if STATUS.is_file():
174
176
  try:
175
177
  prior = json.load(STATUS.open())
@@ -424,7 +426,26 @@ def _locked_rollback(args: argparse.Namespace, repo: pathlib.Path,
424
426
  print(f"refusing rollback to {args.version}: {exc} — nothing was written.",
425
427
  file=sys.stderr)
426
428
  return 1
427
- written = removed = 0
429
+ # The status is part of the transaction. Its lock is taken here, before the first live
430
+ # write, and held to the last status write: taken after the files had moved, a lock that
431
+ # refused at its bound left them deployed while the status still named the previous
432
+ # version and file inventory. Waiting here refuses with nothing written.
433
+ with contextlib.ExitStack() as held:
434
+ if not args.dry_run:
435
+ try:
436
+ held.enter_context(_status_lock())
437
+ except SystemExit as exc:
438
+ print(f"refusing rollback to {args.version}: {exc.code} — nothing was written.",
439
+ file=sys.stderr)
440
+ return 1
441
+ return _rollback_transaction(args, repo, commit, target_files, removal_candidates, backup,
442
+ bundle, codex_central)
443
+
444
+
445
+ def _rollback_transaction(args: argparse.Namespace, repo: pathlib.Path, commit: str, target_files: list[str],
446
+ removal_candidates: list[str], backup: pathlib.Path, bundle: bytes,
447
+ codex_central: str) -> int:
448
+ """The live half of a rollback, run under the status lock: every file, then the status."""
428
449
  # Every step is recorded so it can be undone. A instructions are a SET of files that agree
429
450
  # about which version they are: a run that stopped in the middle left nine files at
430
451
  # the target and twenty-six at the previous one, wrote no status, and reported a raw
@@ -433,9 +454,15 @@ def _locked_rollback(args: argparse.Namespace, repo: pathlib.Path,
433
454
  # makes putting it back the cheap half of this; saying so when even that fails is
434
455
  # the half that matters.
435
456
  undo: list[tuple[pathlib.Path, pathlib.Path | None]] = []
457
+ try:
458
+ status_before = STATUS.read_bytes() if STATUS.is_file() else None
459
+ except OSError as exc:
460
+ print(f"refusing rollback to {args.version}: the status at {STATUS} is unreadable ({exc}) "
461
+ "— nothing was written.", file=sys.stderr)
462
+ return 1
436
463
 
437
464
  def restore() -> list[str]:
438
- """Put every applied file back. Returns the ones that could not be restored."""
465
+ """Put every applied file, and the status, back. Returns the ones that could not be restored."""
439
466
  stuck = []
440
467
  for target, saved in reversed(undo):
441
468
  try:
@@ -445,8 +472,16 @@ def _locked_rollback(args: argparse.Namespace, repo: pathlib.Path,
445
472
  target.write_bytes(saved.read_bytes())
446
473
  except OSError:
447
474
  stuck.append(str(target))
475
+ try:
476
+ if status_before is None:
477
+ STATUS.unlink(missing_ok=True)
478
+ elif not STATUS.is_file() or STATUS.read_bytes() != status_before:
479
+ replace_atomically(STATUS, status_before)
480
+ except OSError:
481
+ stuck.append(str(STATUS))
448
482
  return stuck
449
483
 
484
+ written = removed = 0
450
485
  try:
451
486
  for rel in target_files:
452
487
  dst = deploy_target(rel)
@@ -465,8 +500,10 @@ def _locked_rollback(args: argparse.Namespace, repo: pathlib.Path,
465
500
  bak.parent.mkdir(parents=True, exist_ok=True)
466
501
  bak.write_bytes(dst.read_bytes())
467
502
  dst.parent.mkdir(parents=True, exist_ok=True)
468
- dst.write_bytes(content)
503
+ # Registered before the write: a write that fails partway has already changed the file
504
+ # (truncated, or half its new bytes), and only a recorded entry puts it back.
469
505
  undo.append((dst, bak))
506
+ dst.write_bytes(content)
470
507
  if rel.startswith("claude/hooks/"):
471
508
  dst.chmod(0o755)
472
509
  written += 1
@@ -480,8 +517,8 @@ def _locked_rollback(args: argparse.Namespace, repo: pathlib.Path,
480
517
  bak = backup / rel
481
518
  bak.parent.mkdir(parents=True, exist_ok=True)
482
519
  bak.write_bytes(dst.read_bytes())
483
- dst.unlink()
484
520
  undo.append((dst, bak))
521
+ dst.unlink()
485
522
  removed += 1
486
523
  # The assembled surfaces land LAST: the bundle is what the agent reads, so
487
524
  # it names the target version only once every guide it references has.
@@ -495,8 +532,8 @@ def _locked_rollback(args: argparse.Namespace, repo: pathlib.Path,
495
532
  bak.parent.mkdir(parents=True, exist_ok=True)
496
533
  bak.write_bytes(bundle_dst.read_bytes())
497
534
  bundle_dst.parent.mkdir(parents=True, exist_ok=True)
498
- bundle_dst.write_bytes(bundle)
499
535
  undo.append((bundle_dst, bak))
536
+ bundle_dst.write_bytes(bundle)
500
537
  written += 1
501
538
  codex_dst = CODEX_DIR / "AGENTS.md"
502
539
  if args.dry_run:
@@ -511,10 +548,24 @@ def _locked_rollback(args: argparse.Namespace, repo: pathlib.Path,
511
548
  # install uses — atomic, mode-preserving, marker-bounded — never a
512
549
  # whole-file write of a snapshot: an edit the user landed while the
513
550
  # guides were copying rides through; only the region is ours to move.
514
- merge_codex(CODEX_DIR, codex_central)
515
551
  undo.append((codex_dst, bak))
552
+ merge_codex(CODEX_DIR, codex_central)
516
553
  written += 1
517
- except (OSError, subprocess.CalledProcessError) as exc:
554
+ if not args.dry_run:
555
+ # Re-project, then mark the rollback (a plain project would report latest), both
556
+ # under the lock this rollback already holds; a status that cannot be written puts
557
+ # every file back with it.
558
+ cmd_project(args, status_locked=True)
559
+ status = json.loads(STATUS.read_text())
560
+ status["current_version"] = args.version
561
+ status["rolled_back_to"] = None if args.version == status["latest_version"] else args.version
562
+ # The next rollback's removal operand: exactly what is deployed now.
563
+ status["deployed_corpus"] = {
564
+ "version": args.version,
565
+ "files": sorted(rel for rel in target_files if deploy_target(rel) is not None),
566
+ }
567
+ _write_status(status)
568
+ except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as exc:
518
569
  stuck = restore()
519
570
  if stuck:
520
571
  print(
@@ -525,27 +576,13 @@ def _locked_rollback(args: argparse.Namespace, repo: pathlib.Path,
525
576
  )
526
577
  return 1
527
578
  print(
528
- f"rollback to {args.version} failed ({exc}); every file it had already written "
529
- f"was restored, so the instructions are unchanged. Nothing is split.",
579
+ f"rollback to {args.version} failed ({exc}); every file it had already written, "
580
+ f"and the status, were restored, so the instructions are unchanged. Nothing is split.",
530
581
  file=sys.stderr,
531
582
  )
532
583
  return 1
533
584
  if args.dry_run:
534
585
  return 0
535
- # Re-project, then mark the rollback (a plain project would report latest).
536
- cmd_project(args)
537
- # Sequential with cmd_project's lock, never nested inside it: flock on a
538
- # second open of the same lock file would deadlock this process.
539
- with _status_lock():
540
- status = json.load(STATUS.open())
541
- status["current_version"] = args.version
542
- status["rolled_back_to"] = None if args.version == status["latest_version"] else args.version
543
- # The next rollback's removal operand: exactly what is deployed now.
544
- status["deployed_corpus"] = {
545
- "version": args.version,
546
- "files": sorted(rel for rel in target_files if deploy_target(rel) is not None),
547
- }
548
- _write_status(status)
549
586
  print(
550
587
  f"instructions rolled back to {args.version} ({commit[:12]}): "
551
588
  f"{written} files written, {removed} removed; backup at {backup}. "
@@ -559,14 +596,18 @@ APPLY_OUTCOMES = ("applied", "canary_failed", "install_failed")
559
596
 
560
597
 
561
598
  @contextlib.contextmanager
562
- def _flock(lock_path: pathlib.Path):
563
- """Exclusive advisory lock at `lock_path`, held for the with-block."""
599
+ def _flock(lock_path: pathlib.Path, name: str):
600
+ """Exclusive advisory lock at `lock_path`, held for the with-block. Waits at most the shared
601
+ bound (host_platform.lock_within), then refuses naming `name` and the path."""
564
602
  lock_path.parent.mkdir(parents=True, exist_ok=True)
565
603
  # O_NOFOLLOW and no truncation: a "w" open follows a planted symlink and
566
604
  # truncates its target merely by running the command.
567
605
  fd = os.open(str(lock_path), os.O_CREAT | os.O_WRONLY | getattr(os, "O_NOFOLLOW", 0), 0o600)
568
606
  with os.fdopen(fd, "w") as handle:
569
- fcntl.flock(handle, fcntl.LOCK_EX)
607
+ try:
608
+ lock_within(handle, f"{name} ({lock_path})")
609
+ except LockWaitExpired as exc:
610
+ raise SystemExit(f"instructions-state: {exc}") from exc
570
611
  yield
571
612
 
572
613
 
@@ -574,7 +615,7 @@ def _status_lock():
574
615
  """Exclusive advisory lock over instructions-status writes. `project` and
575
616
  `record-apply` both read-modify-write the whole file; unlocked, whichever
576
617
  writes second silently reverts the other's fields."""
577
- return _flock(STATUS.with_name(STATUS.name + ".lock"))
618
+ return _flock(STATUS.with_name(STATUS.name + ".lock"), "the instructions status lock")
578
619
 
579
620
 
580
621
  def _deploy_lock():
@@ -583,7 +624,7 @@ def _deploy_lock():
583
624
  rollbacks both report success over a split instructions. A DIFFERENT file from the
584
625
  status lock, deliberately — rollback takes the status lock inside this one,
585
626
  and flock on a second open of one file deadlocks a single process."""
586
- return _flock(STATUS.with_name(STATUS.name + ".deploy.lock"))
627
+ return _flock(STATUS.with_name(STATUS.name + ".deploy.lock"), "the instructions deploy lock")
587
628
 
588
629
 
589
630
  def _write_status(status: dict) -> None:
@@ -814,8 +855,9 @@ agents.write_text(body)
814
855
  codex_seed = ("<!-- agent-bios:central:start -->\nCODEX two\n"
815
856
  "<!-- agent-bios:central:end -->\n\n## Personal\nMY OWN CODEX LINE\n")
816
857
 
817
- def attempt(fail_at):
818
- home = root / f"home-{fail_at}"
858
+ def attempt(fail_at, refuse_lock_at=None, break_status=False, partial=None):
859
+ home = root / (f"home-{fail_at}" if refuse_lock_at is None and not break_status and partial is None
860
+ else f"home-{fail_at}-lock{refuse_lock_at}-status{int(break_status)}-{partial}")
819
861
  claude = home / ".claude"
820
862
  codex_home = home / ".codex"
821
863
  saved_claude = globals()["CLAUDE_DIR"]
@@ -832,7 +874,7 @@ agents.write_text(body)
832
874
  (codex_home / "AGENTS.md").write_text(codex_seed)
833
875
  # A user-restricted mode must ride through the region merge.
834
876
  (codex_home / "AGENTS.md").chmod(0o600)
835
- counter = [0]
877
+ counter, broke = [0], []
836
878
  real_write = pathlib.Path.write_bytes
837
879
 
838
880
  def flaky(self, data):
@@ -840,6 +882,11 @@ agents.write_text(body)
840
882
  counter[0] += 1
841
883
  if counter[0] == fail_at:
842
884
  raise OSError("self-test write failure")
885
+ if partial is not None and self.name == partial and not broke:
886
+ # A disk filling up mid-write, once: the file already holds two bytes of the new content.
887
+ broke.append(self)
888
+ real_write(self, data[:2])
889
+ raise OSError(28, "self-test: no space left on device after a partial write")
843
890
  return real_write(self, data)
844
891
 
845
892
  real_assemble_at = globals()["_assemble_at"]
@@ -854,9 +901,39 @@ agents.write_text(body)
854
901
  "MY OWN CODEX LINE", "MY OWN CODEX LINE\nMID-FLIGHT EDIT"))
855
902
  return result
856
903
 
904
+ real_status_lock = globals()["_status_lock"]
905
+ taken = [0]
906
+
907
+ def contended():
908
+ # The status lock refusing at its bound on the `refuse_lock_at`-th acquisition,
909
+ # as _flock refuses: a SystemExit naming the lock.
910
+ taken[0] += 1
911
+ if taken[0] == refuse_lock_at:
912
+ raise SystemExit("instructions-state: the instructions status lock (planted) is still "
913
+ "held after 30 s; another agent-bios process holds it")
914
+ return real_status_lock()
915
+
916
+ real_write_status = globals()["_write_status"]
917
+ writes = [0]
918
+
919
+ def broken_write_status(status):
920
+ # The projection's write lands; the rollback's mark, the next one, fails.
921
+ writes[0] += 1
922
+ if writes[0] > 1:
923
+ raise OSError("self-test status write failure")
924
+ real_write_status(status)
925
+
926
+ def projecting(_args, status_locked=False):
927
+ # The projection's own use of the status lock and its status write, without the ledger
928
+ # it would read: it carries the record forward under a version of its own.
929
+ with contextlib.nullcontext() if status_locked else _status_lock():
930
+ _write_status({**json.loads(globals()["STATUS"].read_text()), "current_version": "projected"})
931
+ return 0
932
+
857
933
  saved = (globals()["CLAUDE_DIR"], globals()["CODEX_DIR"],
858
934
  globals()["STATE_DIR"], globals()["STATUS"],
859
- globals()["cmd_project"], globals()["_assemble_at"])
935
+ globals()["cmd_project"], globals()["_assemble_at"], globals()["_status_lock"],
936
+ real_write_status)
860
937
  globals()["CLAUDE_DIR"] = claude
861
938
  globals()["CODEX_DIR"] = codex_home
862
939
  globals()["STATE_DIR"] = home / "state"
@@ -869,7 +946,10 @@ agents.write_text(body)
869
946
  json.dumps({"version": 1, "domains": []}))
870
947
  globals()["STATUS"].write_text(json.dumps(
871
948
  {"current_version": "before", "latest_version": "t1"}))
872
- globals()["cmd_project"] = lambda _args: 0
949
+ globals()["cmd_project"] = projecting
950
+ globals()["_status_lock"] = contended
951
+ if break_status:
952
+ globals()["_write_status"] = broken_write_status
873
953
  globals()["_assemble_at"] = editing_assemble_at
874
954
  pathlib.Path.write_bytes = flaky
875
955
  try:
@@ -877,21 +957,25 @@ agents.write_text(body)
877
957
  repo=str(repo), version="t1", dry_run=False))
878
958
  except Exception as exc: # a raise is itself the defect this asserts against
879
959
  code = f"raised {type(exc).__name__}"
960
+ except SystemExit as exc:
961
+ code = f"exited {exc.code!r}"
880
962
  finally:
881
963
  pathlib.Path.write_bytes = real_write
882
964
  (globals()["CLAUDE_DIR"], globals()["CODEX_DIR"],
883
965
  globals()["STATE_DIR"], globals()["STATUS"],
884
- globals()["cmd_project"], globals()["_assemble_at"]) = saved
966
+ globals()["cmd_project"], globals()["_assemble_at"], globals()["_status_lock"],
967
+ globals()["_write_status"]) = saved
885
968
  landed = sorted(q.name for q in seeded.parent.glob("*.md"))
886
969
  return (code, landed, seeded.read_text(),
887
970
  (claude / "central" / "bundle.md").read_text(),
888
971
  (codex_home / "AGENTS.md").read_text(),
889
- (codex_home / "AGENTS.md").stat().st_mode & 0o777)
972
+ (codex_home / "AGENTS.md").stat().st_mode & 0o777,
973
+ json.loads((home / "state" / "corpus-status.json").read_text()))
890
974
 
891
975
  # `cmd_rollback` reads the fixture through `git -C <repo>`, which the hook's
892
976
  # GIT_DIR would redirect at the real repository — same scrub, same reason.
893
977
  with own_repo_env():
894
- code, landed, seeded, bundle_text, agents_text, agents_mode = attempt(0)
978
+ code, landed, seeded, bundle_text, agents_text, agents_mode, _ = attempt(0)
895
979
  if code != 0 or len(landed) < 6 or seeded.strip() != "TARGET 0":
896
980
  problems.append(
897
981
  f"clean rollback did not apply the instructions (code={code} files={len(landed)})")
@@ -918,7 +1002,7 @@ agents.write_text(body)
918
1002
  if "MY OWN CODEX LINE" not in agents_text:
919
1003
  problems.append("rollback destroyed the user's text outside the codex markers")
920
1004
  with own_repo_env():
921
- code, landed, seeded, bundle_text, agents_text, agents_mode = attempt(3)
1005
+ code, landed, seeded, bundle_text, agents_text, agents_mode, _ = attempt(3)
922
1006
  if code == 0:
923
1007
  problems.append("a rollback whose write failed reported success")
924
1008
  elif not isinstance(code, int):
@@ -931,6 +1015,38 @@ agents.write_text(body)
931
1015
  "a failed rollback moved the live bundle — the reader surface is split")
932
1016
  if "CODEX two" not in agents_text or "MY OWN CODEX LINE" not in agents_text:
933
1017
  problems.append("a failed rollback did not leave the codex surface as it was")
1018
+ # A write that changes the file before it fails, an existing guide's and the live bundle's: the
1019
+ # rollback puts back the bytes the write had already replaced, the status stays the previous
1020
+ # version, and the refusal says the instructions are unchanged, which is then true.
1021
+ for name in ("g0.md", "bundle.md"):
1022
+ said = io.StringIO()
1023
+ with own_repo_env(), contextlib.redirect_stderr(said):
1024
+ code, landed, seeded, bundle_text, agents_text, _, status = attempt(0, partial=name)
1025
+ if (code == 0 or seeded != "PREVIOUS\n" or bundle_text != "LIVE BUNDLE\n" or landed != ["g0.md"]
1026
+ or "CODEX two" not in agents_text or status.get("current_version") != "before"
1027
+ or "were restored, so the instructions are unchanged" not in said.getvalue()):
1028
+ problems.append(
1029
+ f"a write to {name} that changed the file before it failed was not undone: code={code}, guide "
1030
+ f"{seeded[:12]!r}, bundle {bundle_text[:12]!r}, guides {landed}, status "
1031
+ f"{status.get('current_version')!r}, said {said.getvalue().strip()[-120:]!r}")
1032
+ # The status lock refusing at its bound, at each acquisition the rollback once made after
1033
+ # its files had moved (the projection's, then the mark's), and a status write that fails:
1034
+ # the files and the status must end at one version, and a rollback left at the previous one
1035
+ # must not report success.
1036
+ for refused, broken in ((1, False), (2, False), (None, True)):
1037
+ with own_repo_env():
1038
+ code, _, seeded, bundle_text, _, _, status = attempt(0, refuse_lock_at=refused, break_status=broken)
1039
+ files = ("previous" if (seeded.strip(), bundle_text.strip()) == ("PREVIOUS", "LIVE BUNDLE") else
1040
+ "target" if (seeded.strip(), bundle_text.strip()) == ("TARGET 0", "BUNDLE one") else "split")
1041
+ recorded = {"before": "previous", "t1": "target"}.get(status.get("current_version"), "other")
1042
+ if files != recorded:
1043
+ problems.append(
1044
+ f"a {'status write that failed' if broken else f'status lock refused at acquisition {refused}'} "
1045
+ f"left the files at the {files} version and the status at the {recorded} one (code={code}) "
1046
+ "— deployed but unrecorded")
1047
+ elif files == "previous" and code == 0:
1048
+ problems.append(f"a rollback refused at {'its status write' if broken else f'status-lock acquisition {refused}'} "
1049
+ "reported success")
934
1050
 
935
1051
  # ---- The real CLI end to end, subprocess-driven against one fixture. ----
936
1052
  fx_home = root / "fx-home"
@@ -1128,6 +1244,32 @@ agents.write_text(body)
1128
1244
  if after is not None and after != seeded_status:
1129
1245
  problems.append("an interrupted status write altered the recorded status")
1130
1246
  (globals()["STATE_DIR"], globals()["STATUS"]) = saved_state
1247
+
1248
+ # ---- A lock held past the bound is refused BY NAME, not waited on forever. ----
1249
+ # The bounds are scaled; the holder is a child that lets go after 8 s, so a writer that
1250
+ # waits without a bound returns late and is caught here rather than hanging the suite.
1251
+ bounds = sys.modules[lock_within.__module__]
1252
+ saved_bounds = (bounds.LOCK_WAIT_S, bounds.LOCK_NOTICE_S)
1253
+ held_path = root / "held.lock"
1254
+ holder = subprocess.Popen([sys.executable, "-c", "import fcntl, sys, time; f = open(sys.argv[1], 'a'); "
1255
+ "fcntl.flock(f, fcntl.LOCK_EX); print('held', flush=True); time.sleep(8)",
1256
+ str(held_path)], stdout=subprocess.PIPE, text=True)
1257
+ notice = io.StringIO()
1258
+ try:
1259
+ holder.stdout.readline()
1260
+ bounds.LOCK_WAIT_S, bounds.LOCK_NOTICE_S = 0.6, 0.2
1261
+ with contextlib.redirect_stderr(notice), _flock(held_path, "the planted lock"):
1262
+ problems.append("a writer took a lock another holder still held")
1263
+ except SystemExit as exc:
1264
+ if f"the planted lock ({held_path}) is still held after 0.6 s" not in str(exc.code):
1265
+ problems.append(f"a lock held past the bound was refused without naming it: {exc.code!r}")
1266
+ if "waiting for the planted lock" not in notice.getvalue():
1267
+ problems.append("a writer waiting on a held lock did not say what it waited for")
1268
+ finally:
1269
+ bounds.LOCK_WAIT_S, bounds.LOCK_NOTICE_S = saved_bounds
1270
+ holder.kill()
1271
+ holder.wait()
1272
+ holder.stdout.close()
1131
1273
  except subprocess.CalledProcessError as exc:
1132
1274
  # A fixture command failing outside the control above is the same defect seen
1133
1275
  # from the main run — named here so the gate reports it instead of a traceback.
@@ -535,8 +535,8 @@ class DesktopBundle:
535
535
  def _interpreter(self, binding: dict[str, str]) -> str:
536
536
  if binding:
537
537
  return binding["AGENT_BIOS_PYTHON_EXECUTABLE"]
538
- if sys.version_info < (3, 11):
539
- raise AppError(f"the Desktop bundle needs Python 3.11 or newer; this is {sys.version.split()[0]} at {sys.executable}")
538
+ if sys.version_info < (3, 12):
539
+ raise AppError(f"the Desktop bundle needs Python 3.12 or newer; this is {sys.version.split()[0]} at {sys.executable}")
540
540
  if not sys.executable or not Path(sys.executable).is_absolute():
541
541
  raise AppError("cannot name an absolute Python interpreter for the Desktop bundle")
542
542
  return sys.executable