prizmkit 1.1.191 → 1.1.192

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 (169) hide show
  1. package/bundled/VERSION.json +3 -3
  2. package/bundled/adapters/antigravity/skill-adapter.js +13 -4
  3. package/bundled/adapters/codex/skill-adapter.js +28 -8
  4. package/bundled/adapters/cursor/skill-adapter.js +13 -4
  5. package/bundled/adapters/pi/skill-adapter.js +28 -7
  6. package/bundled/dev-pipeline/.env.example +4 -12
  7. package/bundled/dev-pipeline/README.md +5 -10
  8. package/bundled/dev-pipeline/assets/skill-subagent-integration.md +3 -6
  9. package/bundled/dev-pipeline/prizmkit_runtime/atomic_io.py +48 -0
  10. package/bundled/dev-pipeline/prizmkit_runtime/checkpoint_state.py +66 -23
  11. package/bundled/dev-pipeline/prizmkit_runtime/cli.py +10 -7
  12. package/bundled/dev-pipeline/prizmkit_runtime/commands.py +2 -21
  13. package/bundled/dev-pipeline/prizmkit_runtime/config.py +24 -76
  14. package/bundled/dev-pipeline/prizmkit_runtime/daemon.py +125 -67
  15. package/bundled/dev-pipeline/prizmkit_runtime/gitops.py +77 -430
  16. package/bundled/dev-pipeline/prizmkit_runtime/heartbeat.py +93 -49
  17. package/bundled/dev-pipeline/prizmkit_runtime/interoperability.py +1 -3
  18. package/bundled/dev-pipeline/prizmkit_runtime/paths.py +0 -6
  19. package/bundled/dev-pipeline/prizmkit_runtime/platform_detection.py +36 -14
  20. package/bundled/dev-pipeline/prizmkit_runtime/processes.py +206 -151
  21. package/bundled/dev-pipeline/prizmkit_runtime/reset.py +2 -23
  22. package/bundled/dev-pipeline/prizmkit_runtime/reset_preserve.py +15 -134
  23. package/bundled/dev-pipeline/prizmkit_runtime/results.py +25 -0
  24. package/bundled/dev-pipeline/prizmkit_runtime/runner_bookkeeping.py +68 -83
  25. package/bundled/dev-pipeline/prizmkit_runtime/runner_classification.py +15 -5
  26. package/bundled/dev-pipeline/prizmkit_runtime/runner_models.py +1 -29
  27. package/bundled/dev-pipeline/prizmkit_runtime/runner_prompts.py +0 -2
  28. package/bundled/dev-pipeline/prizmkit_runtime/runner_status.py +7 -2
  29. package/bundled/dev-pipeline/prizmkit_runtime/runners.py +276 -217
  30. package/bundled/dev-pipeline/prizmkit_runtime/runtime_commit.py +124 -122
  31. package/bundled/dev-pipeline/prizmkit_runtime/runtime_helper.py +90 -9
  32. package/bundled/dev-pipeline/prizmkit_runtime/sessions.py +183 -130
  33. package/bundled/dev-pipeline/prizmkit_runtime/status.py +1 -3
  34. package/bundled/dev-pipeline/prizmkit_runtime/stream_progress.py +2780 -0
  35. package/bundled/dev-pipeline/prizmkit_runtime/task_checkout.py +27 -101
  36. package/bundled/dev-pipeline/prizmkit_runtime/test_result.py +58 -4
  37. package/bundled/dev-pipeline/scripts/check-session-status.py +43 -19
  38. package/bundled/dev-pipeline/scripts/continuation.py +6 -4
  39. package/bundled/dev-pipeline/scripts/detect-stuck.py +28 -28
  40. package/bundled/dev-pipeline/scripts/generate-bootstrap-prompt.py +7 -2
  41. package/bundled/dev-pipeline/scripts/generate-bugfix-prompt.py +7 -2
  42. package/bundled/dev-pipeline/scripts/init-bugfix-pipeline.py +10 -7
  43. package/bundled/dev-pipeline/scripts/init-change-artifact.py +8 -2
  44. package/bundled/dev-pipeline/scripts/init-pipeline.py +14 -69
  45. package/bundled/dev-pipeline/scripts/parse-stream-progress.py +31 -2616
  46. package/bundled/dev-pipeline/scripts/patch-completion-notes.py +4 -24
  47. package/bundled/dev-pipeline/scripts/prompt_framework.py +56 -9
  48. package/bundled/dev-pipeline/scripts/status_common.py +591 -0
  49. package/bundled/dev-pipeline/scripts/update-bug-status.py +85 -463
  50. package/bundled/dev-pipeline/scripts/update-checkpoint.py +227 -65
  51. package/bundled/dev-pipeline/scripts/update-feature-status.py +76 -509
  52. package/bundled/dev-pipeline/scripts/utils.py +5 -12
  53. package/bundled/dev-pipeline/templates/bootstrap-tier3.md +4 -4
  54. package/bundled/dev-pipeline/templates/bug-fix-list-schema.json +7 -0
  55. package/bundled/dev-pipeline/templates/bugfix-bootstrap-prompt.md +1 -1
  56. package/bundled/dev-pipeline/templates/sections/artifact-manifest.md +1 -1
  57. package/bundled/dev-pipeline/templates/sections/bugfix-phase-manual-verification.md +1 -1
  58. package/bundled/dev-pipeline/templates/sections/bugfix-phase-review.md +1 -1
  59. package/bundled/dev-pipeline/templates/sections/bugfix-phase-test.md +2 -1
  60. package/bundled/dev-pipeline/templates/sections/checkpoint-system.md +1 -1
  61. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-auto.md +1 -1
  62. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-opencli.md +2 -2
  63. package/bundled/dev-pipeline/templates/sections/phase-browser-verification.md +2 -2
  64. package/bundled/dev-pipeline/templates/sections/phase-prizmkit-test.md +2 -1
  65. package/bundled/dev-pipeline/templates/sections/phase-review-full.md +1 -1
  66. package/bundled/dev-pipeline/templates/sections/phase-specify-plan-full.md +3 -6
  67. package/bundled/dev-pipeline/templates/session-status-schema.json +2 -5
  68. package/bundled/dev-pipeline/tests/_helpers.py +418 -0
  69. package/bundled/dev-pipeline/tests/conftest.py +45 -1
  70. package/bundled/dev-pipeline/tests/test_auto_skip.py +4 -69
  71. package/bundled/dev-pipeline/tests/test_checkpoint_state.py +126 -1
  72. package/bundled/dev-pipeline/tests/test_daemon_and_scripts.py +257 -0
  73. package/bundled/dev-pipeline/tests/test_e2e_pipeline_run.py +500 -0
  74. package/bundled/dev-pipeline/tests/test_generate_bootstrap_prompt.py +59 -117
  75. package/bundled/dev-pipeline/tests/test_generate_bugfix_prompt.py +12 -10
  76. package/bundled/dev-pipeline/tests/test_python_runner_parity.py +431 -3099
  77. package/bundled/dev-pipeline/tests/test_recovery_workflow.py +7 -8
  78. package/bundled/dev-pipeline/tests/test_repository_bootstrap.py +0 -1
  79. package/bundled/dev-pipeline/tests/test_reset_modes.py +15 -27
  80. package/bundled/dev-pipeline/tests/test_reset_preserve.py +54 -139
  81. package/bundled/dev-pipeline/tests/test_runner_bookkeeping.py +766 -0
  82. package/bundled/dev-pipeline/tests/test_runner_lifecycle.py +1257 -0
  83. package/bundled/dev-pipeline/tests/test_runtime_helper.py +97 -20
  84. package/bundled/dev-pipeline/tests/test_session_launch.py +1101 -0
  85. package/bundled/dev-pipeline/tests/test_stream_progress.py +585 -0
  86. package/bundled/dev-pipeline/tests/test_unified_cli.py +155 -2034
  87. package/bundled/dev-pipeline/tests/test_utils.py +3 -3
  88. package/bundled/skills/_metadata.json +9 -63
  89. package/bundled/skills/app-planner/SKILL.md +32 -303
  90. package/bundled/skills/app-planner/references/app-design-guide.md +0 -4
  91. package/bundled/skills/app-planner/references/generated-plan-review.md +2 -1
  92. package/bundled/skills/app-planner/references/project-brief-guide.md +14 -0
  93. package/bundled/skills/app-planner/references/project-conventions-discovery.md +4 -6
  94. package/bundled/skills/app-planner/references/project-state-detection.md +2 -3
  95. package/bundled/skills/bug-fix-workflow/SKILL.md +1 -2
  96. package/bundled/skills/bug-fix-workflow/references/bug-diagnosis.md +4 -7
  97. package/bundled/skills/bug-planner/SKILL.md +54 -435
  98. package/bundled/skills/bug-planner/references/generated-plan-review.md +3 -2
  99. package/bundled/skills/bug-planner/references/input-formats.md +32 -0
  100. package/bundled/skills/bugfix-pipeline-launcher/SKILL.md +4 -6
  101. package/bundled/skills/bugfix-pipeline-launcher/references/configuration.md +4 -28
  102. package/bundled/skills/feature-pipeline-launcher/SKILL.md +4 -6
  103. package/bundled/skills/feature-pipeline-launcher/references/configuration.md +4 -28
  104. package/bundled/skills/feature-planner/SKILL.md +60 -439
  105. package/bundled/skills/feature-planner/assets/planning-guide.md +1 -1
  106. package/bundled/skills/feature-planner/references/completeness-review.md +34 -0
  107. package/bundled/skills/feature-planner/references/decomposition-patterns.md +2 -2
  108. package/bundled/skills/feature-planner/references/error-recovery.md +1 -1
  109. package/bundled/skills/feature-planner/references/generated-plan-review.md +3 -2
  110. package/bundled/skills/feature-planner/references/incremental-feature-planning.md +3 -1
  111. package/bundled/skills/feature-workflow/SKILL.md +1 -2
  112. package/bundled/skills/prizmkit/SKILL.md +7 -1
  113. package/bundled/skills/prizmkit-code-review/SKILL.md +14 -6
  114. package/bundled/skills/prizmkit-code-review/references/independent-code-review.md +7 -4
  115. package/bundled/skills/prizmkit-code-review/references/review-report-template.md +16 -0
  116. package/bundled/skills/prizmkit-code-review/scripts/render_review_report.py +58 -20
  117. package/bundled/skills/prizmkit-implement/SKILL.md +1 -1
  118. package/bundled/skills/prizmkit-init/SKILL.md +24 -127
  119. package/bundled/skills/prizmkit-init/assets/project-brief-template.md +3 -3
  120. package/bundled/skills/prizmkit-plan/SKILL.md +6 -8
  121. package/bundled/skills/prizmkit-plan/references/clarify-guide.md +1 -1
  122. package/bundled/skills/prizmkit-plan/references/independent-plan-review.md +5 -2
  123. package/bundled/skills/prizmkit-plan/references/review-plan-spec-loop.md +6 -5
  124. package/bundled/skills/prizmkit-prizm-docs/SKILL.md +1 -13
  125. package/bundled/skills/prizmkit-prizm-docs/references/op-update.md +1 -1
  126. package/bundled/skills/prizmkit-retrospective/SKILL.md +6 -4
  127. package/bundled/skills/prizmkit-test/SKILL.md +25 -133
  128. package/bundled/skills/prizmkit-test/references/independent-test-review.md +5 -2
  129. package/bundled/skills/prizmkit-test/references/test-coverage-model.md +6 -0
  130. package/bundled/skills/prizmkit-workflow/SKILL.md +2 -3
  131. package/bundled/skills/prizmkit-workflow/references/workflow-state-protocol.md +4 -3
  132. package/bundled/skills/recovery-workflow/SKILL.md +7 -7
  133. package/bundled/skills/recovery-workflow/evals/evals.json +1 -1
  134. package/bundled/skills/recovery-workflow/references/detection.md +1 -3
  135. package/bundled/skills/recovery-workflow/scripts/detect-recovery-state.py +0 -6
  136. package/bundled/templates/project-memory-template.md +1 -2
  137. package/package.json +1 -1
  138. package/src/scaffold.js +28 -7
  139. package/bundled/dev-pipeline/SCHEMA_ANALYSIS.md +0 -53
  140. package/bundled/dev-pipeline/scripts/generate-refactor-prompt.py +0 -649
  141. package/bundled/dev-pipeline/scripts/init-refactor-pipeline.py +0 -463
  142. package/bundled/dev-pipeline/scripts/update-refactor-status.py +0 -1512
  143. package/bundled/dev-pipeline/templates/refactor-bootstrap-prompt.md +0 -240
  144. package/bundled/dev-pipeline/templates/refactor-list-schema.json +0 -266
  145. package/bundled/dev-pipeline/templates/sections/refactor-critical-paths.md +0 -15
  146. package/bundled/dev-pipeline/templates/sections/refactor-mission.md +0 -9
  147. package/bundled/dev-pipeline/templates/sections/refactor-phase-commit-report.md +0 -24
  148. package/bundled/dev-pipeline/templates/sections/refactor-phase-implement.md +0 -16
  149. package/bundled/dev-pipeline/templates/sections/refactor-phase-init.md +0 -9
  150. package/bundled/dev-pipeline/templates/sections/refactor-phase-plan.md +0 -22
  151. package/bundled/dev-pipeline/templates/sections/refactor-phase-review.md +0 -19
  152. package/bundled/dev-pipeline/templates/sections/refactor-phase-test.md +0 -24
  153. package/bundled/dev-pipeline/templates/sections/refactor-reminders.md +0 -12
  154. package/bundled/dev-pipeline/templates/sections/refactor-session-context.md +0 -6
  155. package/bundled/dev-pipeline/templates/sections/refactor-task-contract.md +0 -52
  156. package/bundled/dev-pipeline/tests/test_generate_refactor_prompt.py +0 -478
  157. package/bundled/skills/feature-planner/assets/evaluation-guide.md +0 -44
  158. package/bundled/skills/refactor-pipeline-launcher/SKILL.md +0 -219
  159. package/bundled/skills/refactor-pipeline-launcher/references/configuration.md +0 -78
  160. package/bundled/skills/refactor-planner/SKILL.md +0 -467
  161. package/bundled/skills/refactor-planner/assets/planning-guide.md +0 -291
  162. package/bundled/skills/refactor-planner/references/behavior-preservation.md +0 -187
  163. package/bundled/skills/refactor-planner/references/error-recovery.md +0 -45
  164. package/bundled/skills/refactor-planner/references/fast-path.md +0 -59
  165. package/bundled/skills/refactor-planner/references/generated-plan-review.md +0 -107
  166. package/bundled/skills/refactor-planner/references/planning-phases.md +0 -172
  167. package/bundled/skills/refactor-planner/references/refactor-scoping-guide.md +0 -230
  168. package/bundled/skills/refactor-planner/scripts/validate-and-generate-refactor.py +0 -1120
  169. package/bundled/skills/refactor-workflow/SKILL.md +0 -205
@@ -12,6 +12,8 @@ from pathlib import Path
12
12
 
13
13
  import pytest
14
14
 
15
+ from _helpers import load_progress_parser_module as _load_progress_parser_module
16
+
15
17
  REPO_ROOT = Path(__file__).resolve().parents[2]
16
18
  PIPELINE_ROOT = REPO_ROOT / "dev-pipeline"
17
19
  CLI_PATH = PIPELINE_ROOT / "cli.py"
@@ -43,17 +45,6 @@ def run_cli(*args, env=None):
43
45
  )
44
46
 
45
47
 
46
- def _load_progress_parser_module():
47
- import importlib.util
48
-
49
- parser_path = PIPELINE_ROOT / "scripts" / "parse-stream-progress.py"
50
- spec = importlib.util.spec_from_file_location("parse_stream_progress", parser_path)
51
- module = importlib.util.module_from_spec(spec)
52
- assert spec.loader is not None
53
- spec.loader.exec_module(module)
54
- return module
55
-
56
-
57
48
  def test_cli_help_exposes_only_operation_first_public_namespaces():
58
49
  result = run_cli("--help")
59
50
 
@@ -62,7 +53,7 @@ def test_cli_help_exposes_only_operation_first_public_namespaces():
62
53
  assert "operation-first" in result.stdout
63
54
  for group in ["run", "status", "reset", "daemon", "diagnostics", "helper"]:
64
55
  assert group in result.stdout
65
- for removed in ["feature", "bugfix", "refactor", "recovery"]:
56
+ for removed in ["feature", "bugfix", "recovery"]:
66
57
  assert removed not in result.stdout.lower()
67
58
  assert "Traceback" not in result.stderr
68
59
 
@@ -99,7 +90,6 @@ def test_module_entrypoint_help_exposes_same_cli():
99
90
  ("run", "--help"),
100
91
  ("run", "feature", "--help"),
101
92
  ("run", "bugfix", "--help"),
102
- ("run", "refactor", "--help"),
103
93
  ("status", "--help"),
104
94
  ("status", "feature", "--help"),
105
95
  ("status", "all", "--help"),
@@ -109,7 +99,6 @@ def test_module_entrypoint_help_exposes_same_cli():
109
99
  ("daemon", "feature", "--help"),
110
100
  ("daemon", "feature", "start", "--help"),
111
101
  ("daemon", "bugfix", "stop", "--help"),
112
- ("daemon", "refactor", "status", "--help"),
113
102
  ("daemon", "feature", "logs", "--help"),
114
103
  ("daemon", "feature", "restart", "--help"),
115
104
  ("diagnostics", "--help"),
@@ -186,11 +175,6 @@ def test_former_recovery_invocation_never_reaches_dispatch(monkeypatch):
186
175
  ("bugfix", "reset"),
187
176
  ("bugfix", "unskip"),
188
177
  ("bugfix", "describe"),
189
- ("refactor", "run"),
190
- ("refactor", "status"),
191
- ("refactor", "reset"),
192
- ("refactor", "unskip"),
193
- ("refactor", "describe"),
194
178
  ("reset", "describe"),
195
179
  ("daemon", "feature", "describe"),
196
180
  ("diagnostics", "describe"),
@@ -239,7 +223,6 @@ def test_runtime_paths_support_framework_source_layout():
239
223
  assert paths.prizmkit_dir == REPO_ROOT / ".prizmkit"
240
224
  assert paths.feature_plan == paths.plans_dir / "feature-list.json"
241
225
  assert paths.bugfix_plan == paths.plans_dir / "bug-fix-list.json"
242
- assert paths.refactor_plan == paths.plans_dir / "refactor-list.json"
243
226
  assert paths.feature_state_dir == paths.state_dir / "features"
244
227
  assert paths.specs_dir == paths.prizmkit_dir / "specs"
245
228
  assert not hasattr(paths, "recovery_state_dir")
@@ -468,17 +451,16 @@ def test_runtime_config_supplied_env_does_not_leak_ambient_path(tmp_path):
468
451
  assert config.ai_client.source == "unresolved"
469
452
 
470
453
 
471
-
472
454
  def test_runtime_command_registry_contains_only_executing_operation_first_entries():
473
455
  from prizmkit_runtime.commands import find_runtime_command, list_runtime_commands
474
456
 
475
457
  command_keys = {command.key for command in list_runtime_commands()}
476
458
  expected = {
477
- *(('run', family, 'run') for family in ('feature', 'bugfix', 'refactor')),
478
- *(('status', family, 'status') for family in ('feature', 'bugfix', 'refactor', 'all')),
479
- *(('reset', family, 'reset') for family in ('feature', 'bugfix', 'refactor')),
459
+ *(('run', family, 'run') for family in ('feature', 'bugfix')),
460
+ *(('status', family, 'status') for family in ('feature', 'bugfix', 'all')),
461
+ *(('reset', family, 'reset') for family in ('feature', 'bugfix')),
480
462
  *(('daemon', family, action)
481
- for family in ('feature', 'bugfix', 'refactor')
463
+ for family in ('feature', 'bugfix')
482
464
  for action in ('start', 'stop', 'status', 'logs', 'restart')),
483
465
  *(('diagnostics', None, action)
484
466
  for action in ('paths', 'entrypoints', 'version', 'ai-cli')),
@@ -488,7 +470,7 @@ def test_runtime_command_registry_contains_only_executing_operation_first_entrie
488
470
  assert command_keys == expected
489
471
  assert all(command.current_entrypoint for command in list_runtime_commands())
490
472
  assert all(command.action != "describe" for command in list_runtime_commands())
491
- assert all(command.group not in {"feature", "bugfix", "refactor", "recovery"} for command in list_runtime_commands())
473
+ assert all(command.group not in {"feature", "bugfix", "recovery"} for command in list_runtime_commands())
492
474
  for removed in [
493
475
  ("feature", "run", None),
494
476
  ("feature", "test-cli", None),
@@ -576,7 +558,6 @@ def test_pipeline_mode_option_is_rejected():
576
558
  [
577
559
  ("feature", "F-007", ("--features", "F-007", "--dry-run")),
578
560
  ("bugfix", "B-007", ("--max-retries", "4")),
579
- ("refactor", "R-007", ("--resume-phase", "6", "--max-infra-retries", "5")),
580
561
  ],
581
562
  )
582
563
  def test_run_family_dispatch_preserves_each_family_argument_tail(
@@ -599,7 +580,7 @@ def test_run_family_dispatch_preserves_each_family_argument_tail(
599
580
  assert captured == [("run", "run", family, (task_id, *extra_args))]
600
581
 
601
582
 
602
- @pytest.mark.parametrize("family", ("feature", "bugfix", "refactor"))
583
+ @pytest.mark.parametrize("family", ("feature", "bugfix"))
603
584
  @pytest.mark.parametrize("legacy_action", ("reset", "un" + "skip"))
604
585
  def test_family_level_reset_aliases_are_not_public_commands(family, legacy_action):
605
586
  result = run_cli(family, legacy_action)
@@ -676,7 +657,6 @@ def _write_family_status_plan(paths, family, task_id):
676
657
  plan_path, key = {
677
658
  "feature": (paths.feature_plan, "features"),
678
659
  "bugfix": (paths.bugfix_plan, "bugs"),
679
- "refactor": (paths.refactor_plan, "refactors"),
680
660
  }[family]
681
661
  plan_path.parent.mkdir(parents=True, exist_ok=True)
682
662
  plan_path.write_text(json.dumps({key: [{"id": task_id, "status": "pending"}]}), encoding="utf-8")
@@ -687,7 +667,6 @@ def _write_family_runtime_status(paths, family, task_id):
687
667
  state_dir = {
688
668
  "feature": paths.feature_state_dir,
689
669
  "bugfix": paths.bugfix_state_dir,
690
- "refactor": paths.refactor_state_dir,
691
670
  }[family]
692
671
  status_path = state_dir / task_id / "status.json"
693
672
  status_path.parent.mkdir(parents=True, exist_ok=True)
@@ -697,7 +676,6 @@ def _write_family_runtime_status(paths, family, task_id):
697
676
  {
698
677
  "feature": "feature_id",
699
678
  "bugfix": "bug_id",
700
- "refactor": "refactor_id",
701
679
  }[family]: task_id,
702
680
  "retry_count": 0,
703
681
  "sessions": [],
@@ -728,7 +706,6 @@ def test_status_all_aggregates_configured_families_in_fixed_order_and_missing_is
728
706
 
729
707
  paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path)
730
708
  _write_family_status_plan(paths, "feature", "F-001")
731
- _write_family_status_plan(paths, "refactor", "R-001")
732
709
  before = _file_bytes_under(tmp_path)
733
710
  calls = []
734
711
 
@@ -742,18 +719,14 @@ def test_status_all_aggregates_configured_families_in_fixed_order_and_missing_is
742
719
 
743
720
  assert result.exit_code == 0
744
721
  assert rendered.index("FEATURE\n=======") < rendered.index("BUGFIX\n======")
745
- assert rendered.index("BUGFIX\n======") < rendered.index("REFACTOR\n========")
746
722
  assert "normal feature status" in rendered
747
- assert "normal refactor status" in rendered
748
723
  assert "BUGFIX\n======\nnot configured: plan list not found" in rendered
749
724
  assert [(family, action, args) for family, action, args, _paths in calls] == [
750
725
  ("feature", "status", ()),
751
- ("refactor", "status", ()),
752
726
  ]
753
727
  assert _file_bytes_under(tmp_path) == before
754
728
  assert not paths.feature_state_dir.exists()
755
729
  assert not paths.bugfix_state_dir.exists()
756
- assert not paths.refactor_state_dir.exists()
757
730
 
758
731
 
759
732
  def test_status_all_uses_real_family_status_handlers_without_filesystem_mutation(tmp_path):
@@ -763,7 +736,6 @@ def test_status_all_uses_real_family_status_handlers_without_filesystem_mutation
763
736
  configured = {
764
737
  "feature": "F-001",
765
738
  "bugfix": "B-001",
766
- "refactor": "R-001",
767
739
  }
768
740
  for family, task_id in configured.items():
769
741
  _write_family_status_plan(paths, family, task_id)
@@ -777,8 +749,6 @@ def test_status_all_uses_real_family_status_handlers_without_filesystem_mutation
777
749
  assert "Python feature status" in result.stdout
778
750
  assert "BUGFIX\n======" in result.stdout
779
751
  assert "Python bugfix status" in result.stdout
780
- assert "REFACTOR\n========" in result.stdout
781
- assert "Python refactor status" in result.stdout
782
752
  assert _file_bytes_under(tmp_path) == before
783
753
 
784
754
 
@@ -789,16 +759,13 @@ def test_status_all_reports_plan_and_handler_errors_but_renders_unaffected_secti
789
759
  from prizmkit_runtime.commands import CommandResult, handle_runtime_command
790
760
  from prizmkit_runtime.paths import resolve_runtime_paths
791
761
 
792
- paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path)
762
+ paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path / "malformed-plan")
793
763
  _write_family_status_plan(paths, "feature", "F-001")
794
764
  paths.bugfix_plan.parent.mkdir(parents=True, exist_ok=True)
795
765
  paths.bugfix_plan.write_text("{malformed", encoding="utf-8")
796
- _write_family_status_plan(paths, "refactor", "R-001")
797
766
 
798
767
  def fake_status(family, action, legacy_args, runtime_paths):
799
768
  assert action == "status"
800
- if family == "refactor":
801
- raise RuntimeError("family handler exploded")
802
769
  return CommandResult(0, f"Python {family} status", f"normal {family} status")
803
770
 
804
771
  monkeypatch.setattr(runners, "run_pipeline_command", fake_status)
@@ -808,7 +775,24 @@ def test_status_all_reports_plan_and_handler_errors_but_renders_unaffected_secti
808
775
  assert result.exit_code != 0
809
776
  assert "FEATURE\n=======\nPython feature status\nnormal feature status" in rendered
810
777
  assert "BUGFIX\n======\nerror: malformed plan list:" in rendered
811
- assert "REFACTOR\n========\nerror: family handler exploded" in rendered
778
+
779
+ handler_paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path / "handler-error")
780
+ _write_family_status_plan(handler_paths, "feature", "F-001")
781
+ _write_family_status_plan(handler_paths, "bugfix", "B-001")
782
+
783
+ def fake_status_exploding(family, action, legacy_args, runtime_paths):
784
+ assert action == "status"
785
+ if family == "bugfix":
786
+ raise RuntimeError("family handler exploded")
787
+ return CommandResult(0, f"Python {family} status", f"normal {family} status")
788
+
789
+ monkeypatch.setattr(runners, "run_pipeline_command", fake_status_exploding)
790
+ handler_result = handle_runtime_command("status", "status", target="all", paths=handler_paths)
791
+ handler_rendered = handler_result.render()
792
+
793
+ assert handler_result.exit_code != 0
794
+ assert "FEATURE\n=======\nPython feature status\nnormal feature status" in handler_rendered
795
+ assert "BUGFIX\n======\nerror: family handler exploded" in handler_rendered
812
796
 
813
797
 
814
798
  def test_status_all_reports_malformed_runtime_unparseable_and_nonzero_results(
@@ -818,10 +802,9 @@ def test_status_all_reports_malformed_runtime_unparseable_and_nonzero_results(
818
802
  from prizmkit_runtime.commands import CommandResult, handle_runtime_command
819
803
  from prizmkit_runtime.paths import resolve_runtime_paths
820
804
 
821
- paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path)
805
+ paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path / "malformed-unparseable")
822
806
  _write_family_status_plan(paths, "feature", "F-001")
823
807
  _write_family_status_plan(paths, "bugfix", "B-001")
824
- _write_family_status_plan(paths, "refactor", "R-001")
825
808
  malformed_state = paths.feature_state_dir / "F-001" / "status.json"
826
809
  malformed_state.parent.mkdir(parents=True, exist_ok=True)
827
810
  malformed_state.write_text("not-json", encoding="utf-8")
@@ -829,7 +812,7 @@ def test_status_all_reports_malformed_runtime_unparseable_and_nonzero_results(
829
812
  def fake_status(family, action, legacy_args, runtime_paths):
830
813
  if family == "bugfix":
831
814
  return object()
832
- return CommandResult(7 if family == "refactor" else 0, f"Python {family} status", "status output")
815
+ return CommandResult(0, f"Python {family} status", "status output")
833
816
 
834
817
  monkeypatch.setattr(runners, "run_pipeline_command", fake_status)
835
818
  result = handle_runtime_command("status", "status", target="all", paths=paths)
@@ -838,7 +821,21 @@ def test_status_all_reports_malformed_runtime_unparseable_and_nonzero_results(
838
821
  assert result.exit_code != 0
839
822
  assert "FEATURE\n=======\nerror: malformed runtime state F-001/status.json" in rendered
840
823
  assert "BUGFIX\n======\nerror: unparseable configured family result" in rendered
841
- assert "REFACTOR\n========\nerror: Python refactor status\nstatus output" in rendered
824
+
825
+ nonzero_paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path / "nonzero")
826
+ _write_family_status_plan(nonzero_paths, "feature", "F-001")
827
+ _write_family_status_plan(nonzero_paths, "bugfix", "B-001")
828
+
829
+ def fake_status_nonzero(family, action, legacy_args, runtime_paths):
830
+ return CommandResult(7 if family == "bugfix" else 0, f"Python {family} status", "status output")
831
+
832
+ monkeypatch.setattr(runners, "run_pipeline_command", fake_status_nonzero)
833
+ nonzero_result = handle_runtime_command("status", "status", target="all", paths=nonzero_paths)
834
+ nonzero_rendered = nonzero_result.render()
835
+
836
+ assert nonzero_result.exit_code != 0
837
+ assert "FEATURE\n=======\nPython feature status\nstatus output" in nonzero_rendered
838
+ assert "BUGFIX\n======\nerror: Python bugfix status\nstatus output" in nonzero_rendered
842
839
 
843
840
 
844
841
  def test_status_all_direct_api_rejects_family_specific_arguments_without_calling_handlers(
@@ -892,7 +889,7 @@ def test_interoperability_preserves_existing_utility_mapping():
892
889
  explicitly_library_only = set(UTILITY_LIBRARY_ONLY)
893
890
 
894
891
  assert actual_scripts == mapped_scripts | explicitly_library_only
895
- assert explicitly_library_only == {"continuation.py", "prompt_framework.py", "utils.py"}
892
+ assert explicitly_library_only == {"continuation.py", "prompt_framework.py", "status_common.py", "utils.py"}
896
893
  assert "parse-stream-progress.py" in mapped_scripts
897
894
  assert "generate-recovery-prompt" not in UTILITY_ENTRYPOINTS
898
895
  assert "prizmkit-test-gate.py" not in mapped_scripts
@@ -944,7 +941,7 @@ def test_canonical_interrupted_task_guidance_uses_recovery_workflow(path, ordina
944
941
 
945
942
 
946
943
  def test_boundary_dataclasses_are_cohesive_and_frozen():
947
- from prizmkit_runtime.gitops import BranchContext, WorktreePolicy
944
+ from prizmkit_runtime.gitops import BranchContext
948
945
  from prizmkit_runtime.heartbeat import HeartbeatConfig, HeartbeatState
949
946
  from prizmkit_runtime.paths import resolve_runtime_paths
950
947
  from prizmkit_runtime.processes import ProcessHandle, ProcessSpec
@@ -964,7 +961,6 @@ def test_boundary_dataclasses_are_cohesive_and_frozen():
964
961
  heartbeat = HeartbeatConfig(heartbeat_file=paths.state_dir / ".heartbeat")
965
962
  heartbeat_state = HeartbeatState(last_seen_epoch=1.0, stale=False, details="fresh")
966
963
  branch = BranchContext(base_branch="main", working_branch="dev/example", project_root=paths.project_root)
967
- policy = WorktreePolicy(use_worktree=True, cleanup_on_success=False, preserve_on_failure=True)
968
964
  targets = default_status_targets(paths)
969
965
  status_target = StatusTarget(kind="feature", plan_path=paths.feature_plan, state_dir=paths.feature_state_dir)
970
966
  status_request = StatusUpdateRequest(target=status_target, action="status")
@@ -973,7 +969,6 @@ def test_boundary_dataclasses_are_cohesive_and_frozen():
973
969
  assert handle.spec == process
974
970
  assert heartbeat_state.details == "fresh"
975
971
  assert branch.project_root == paths.project_root
976
- assert policy.preserve_on_failure is True
977
972
  assert targets["feature"].plan_path == paths.feature_plan
978
973
  assert status_request.target == status_target
979
974
 
@@ -1598,432 +1593,6 @@ def test_headless_review_guidance_maps_stage_local_skill_result():
1598
1593
  assert "WORKSPACE_MISMATCH" not in skill_text
1599
1594
 
1600
1595
 
1601
- def test_progress_parser_adds_required_metadata(tmp_path):
1602
- import importlib.util
1603
-
1604
- parser_path = PIPELINE_ROOT / "scripts" / "parse-stream-progress.py"
1605
- spec = importlib.util.spec_from_file_location("parse_stream_progress", parser_path)
1606
- module = importlib.util.module_from_spec(spec)
1607
- assert spec.loader is not None
1608
- spec.loader.exec_module(module)
1609
-
1610
- tracker = module.ProgressTracker()
1611
- tracker.process_event({"type": "system", "subtype": "init", "session_id": "claude-session", "cwd": str(tmp_path)})
1612
- tracker.process_event({"type": "assistant", "message": {"content": [{"type": "text", "text": "working"}]}})
1613
- tracker.process_event({"type": "result", "subtype": "success", "stop_reason": "end_turn", "usage": {"input_tokens": 1}, "result": "done"})
1614
- tracker.process_event({"type": "error", "error": {"message": "permission denied by user"}})
1615
- data = tracker.to_dict()
1616
-
1617
- assert data["event_type_counts"]["system"] == 1
1618
- assert data["event_type_counts"]["assistant"] == 1
1619
- assert data["claude_session_id"] == "claude-session"
1620
- assert data["result_subtype"] == "success"
1621
- assert data["stop_reason"] == "end_turn"
1622
- assert data["has_usage"] is True
1623
- assert data["permission_denial_count"] == 1
1624
-
1625
-
1626
-
1627
- def test_progress_parser_normalizes_pi_json_events():
1628
- module = _load_progress_parser_module()
1629
- tracker = module.ProgressTracker()
1630
- tracker.process_event({"type": "session", "version": 3, "id": "pi-session", "cwd": "/tmp/project"})
1631
- tracker.process_event({"type": "agent_start"})
1632
- tracker.process_event({"type": "turn_start"})
1633
- tracker.process_event({
1634
- "type": "message_update",
1635
- "assistantMessageEvent": {"type": "text_delta", "delta": "Running prizmkit-implement"},
1636
- })
1637
- tracker.process_event({"type": "tool_execution_start", "toolName": "edit", "args": {"path": "src/a.js"}})
1638
- tracker.process_event({"type": "tool_execution_end", "toolName": "edit", "result": {"ok": True}, "isError": False})
1639
- tracker.process_event({"type": "compaction_start", "reason": "threshold"})
1640
- tracker.process_event({"type": "compaction_end", "reason": "threshold", "aborted": False, "willRetry": False})
1641
- tracker.process_event({"type": "agent_end", "messages": []})
1642
- data = tracker.to_dict()
1643
- assert data["event_format"] == "pi-json"
1644
- assert data["message_count"] == 1
1645
- assert data["total_tool_calls"] == 1
1646
- assert {item["name"]: item["count"] for item in data["tool_calls"]}["edit"] == 1
1647
- assert data["current_phase"] == "implement"
1648
- assert data["is_active"] is False
1649
- assert data["result_subtype"] == "success"
1650
- assert data["terminal_success_at"]
1651
-
1652
-
1653
- def test_progress_parser_does_not_mark_failed_pi_agent_end_as_success():
1654
- module = _load_progress_parser_module()
1655
- tracker = module.ProgressTracker()
1656
- tracker.process_event({"type": "session", "version": 3, "id": "pi-session", "cwd": "/tmp/project"})
1657
- tracker.process_event({"type": "agent_start"})
1658
- tracker.process_event({
1659
- "type": "message_end",
1660
- "message": {
1661
- "role": "assistant",
1662
- "content": [],
1663
- "stopReason": "error",
1664
- "errorMessage": "provider request failed",
1665
- },
1666
- })
1667
- tracker.process_event({"type": "agent_end", "messages": []})
1668
-
1669
- data = tracker.to_dict()
1670
-
1671
- assert data["event_format"] == "pi-json"
1672
- assert data["is_active"] is False
1673
- assert data["result_subtype"] == "error"
1674
- assert data["stop_reason"] == "error"
1675
- assert data["last_result_is_error"] is True
1676
- assert data["terminal_success_at"] == ""
1677
- assert "provider request failed" in data["errors"]
1678
-
1679
-
1680
- def test_progress_parser_keeps_pi_length_as_nonfatal_diagnostic_metadata():
1681
- module = _load_progress_parser_module()
1682
- tracker = module.ProgressTracker()
1683
- tracker.process_event({"type": "session", "version": 3, "id": "pi-session", "cwd": "/tmp/project"})
1684
- tracker.process_event({"type": "agent_start"})
1685
- message = {
1686
- "role": "assistant",
1687
- "content": [{"type": "thinking", "thinking": "Planning the next test"}],
1688
- "stopReason": "length",
1689
- }
1690
- tracker.process_event({"type": "message_end", "message": message})
1691
- tracker.process_event({"type": "agent_end", "willRetry": False, "messages": [message]})
1692
-
1693
- data = tracker.to_dict()
1694
-
1695
- assert data["result_subtype"] == "success"
1696
- assert data["stop_reason"] == "length"
1697
- assert data["last_result_is_error"] is False
1698
- assert data["api_error_code"] == ""
1699
- assert data["fatal_error_code"] == ""
1700
- assert data["terminal_success_at"]
1701
-
1702
-
1703
- @pytest.mark.parametrize("role", ("assistant", "toolResult"))
1704
- def test_progress_parser_does_not_promote_pi_diagnostic_content_to_fatal_error(role):
1705
- module = _load_progress_parser_module()
1706
- tracker = module.ProgressTracker()
1707
- tracker.process_event({"type": "session", "version": 3, "id": "pi-session", "cwd": "/tmp/project"})
1708
- tracker.process_event({"type": "agent_start"})
1709
- tracker.process_event({
1710
- "type": "message_end",
1711
- "message": {
1712
- "role": role,
1713
- "content": [{
1714
- "type": "text",
1715
- "text": 'continuation_reason = "context_overflow"\nerror = _error_text(result)',
1716
- }],
1717
- "stopReason": "toolUse",
1718
- },
1719
- })
1720
-
1721
- data = tracker.to_dict()
1722
-
1723
- assert data["api_error_code"] == ""
1724
- assert data["fatal_error_code"] == ""
1725
- assert data["last_result_is_error"] is False
1726
-
1727
-
1728
- def test_progress_parser_recovers_from_retrying_pi_attempt_before_final_success():
1729
- module = _load_progress_parser_module()
1730
- tracker = module.ProgressTracker()
1731
- tracker.process_event({"type": "session", "version": 3, "id": "pi-session", "cwd": "/tmp/project"})
1732
- tracker.process_event({"type": "agent_start"})
1733
- tracker.process_event({
1734
- "type": "message_end",
1735
- "message": {
1736
- "role": "assistant",
1737
- "content": [],
1738
- "stopReason": "error",
1739
- "errorMessage": "Error Code internal_server_error: unexpected EOF",
1740
- },
1741
- })
1742
- tracker.process_event({"type": "agent_end", "willRetry": True, "messages": []})
1743
- tracker.process_event({
1744
- "type": "auto_retry_start",
1745
- "attempt": 1,
1746
- "delayMs": 2000,
1747
- "errorMessage": "Error Code internal_server_error: unexpected EOF",
1748
- })
1749
- tracker.process_event({"type": "agent_start"})
1750
- tracker.process_event({"type": "auto_retry_end", "attempt": 1})
1751
- tracker.process_event({
1752
- "type": "message_end",
1753
- "message": {
1754
- "role": "assistant",
1755
- "content": [{"type": "text", "text": "WORKFLOW_COMPLETED"}],
1756
- "stopReason": "stop",
1757
- },
1758
- })
1759
- tracker.process_event({
1760
- "type": "agent_end",
1761
- "willRetry": False,
1762
- "messages": [{
1763
- "role": "assistant",
1764
- "content": [{"type": "text", "text": "WORKFLOW_COMPLETED"}],
1765
- "stopReason": "stop",
1766
- }],
1767
- })
1768
-
1769
- data = tracker.to_dict()
1770
-
1771
- assert data["result_subtype"] == "success"
1772
- assert data["last_result_is_error"] is False
1773
- assert data["stop_reason"] == "stop"
1774
- assert data["fatal_error_code"] == ""
1775
- assert data["terminal_success_at"]
1776
- assert any("unexpected EOF" in str(error) for error in data["errors"])
1777
-
1778
-
1779
- def test_progress_parser_keeps_final_error_after_internal_retry_exhausts():
1780
- module = _load_progress_parser_module()
1781
- tracker = module.ProgressTracker()
1782
- tracker.process_event({"type": "session", "id": "pi-session"})
1783
- tracker.process_event({"type": "agent_start"})
1784
- tracker.process_event({
1785
- "type": "message_end",
1786
- "message": {"role": "assistant", "content": [], "stopReason": "error", "errorMessage": "temporary error"},
1787
- })
1788
- tracker.process_event({"type": "agent_end", "willRetry": True, "messages": []})
1789
- tracker.process_event({"type": "auto_retry_start", "attempt": 1, "errorMessage": "temporary error"})
1790
- tracker.process_event({"type": "agent_start"})
1791
- tracker.process_event({
1792
- "type": "message_end",
1793
- "message": {"role": "assistant", "content": [], "stopReason": "error", "errorMessage": "final error"},
1794
- })
1795
- tracker.process_event({
1796
- "type": "agent_end",
1797
- "willRetry": False,
1798
- "messages": [{"role": "assistant", "content": [], "stopReason": "error", "errorMessage": "final error"}],
1799
- })
1800
-
1801
- data = tracker.to_dict()
1802
-
1803
- assert data["result_subtype"] == "error"
1804
- assert data["last_result_is_error"] is True
1805
- assert data["stop_reason"] == "error"
1806
- assert data["terminal_success_at"] == ""
1807
- assert "final error" in data["terminal_result_text"]
1808
-
1809
-
1810
- def test_progress_parser_clears_retrying_fatal_marker_on_new_pi_attempt():
1811
- module = _load_progress_parser_module()
1812
- tracker = module.ProgressTracker()
1813
- tracker.process_event({"type": "session", "id": "pi-session"})
1814
- tracker.process_event({"type": "agent_start"})
1815
- tracker.process_event({
1816
- "type": "message_end",
1817
- "message": {
1818
- "role": "assistant",
1819
- "content": [],
1820
- "stopReason": "error",
1821
- "errorMessage": "API Error: Your input exceeds the context window",
1822
- },
1823
- })
1824
- tracker.process_event({"type": "agent_end", "willRetry": True, "messages": []})
1825
- failed_attempt = tracker.to_dict()
1826
-
1827
- tracker.process_event({"type": "agent_start"})
1828
- next_attempt = tracker.to_dict()
1829
-
1830
- assert failed_attempt["fatal_error_code"] == "context_overflow"
1831
- assert failed_attempt["last_result_is_error"] is True
1832
- assert next_attempt["fatal_error_code"] == ""
1833
- assert next_attempt["result_subtype"] == ""
1834
- assert next_attempt["last_result_is_error"] is False
1835
- assert any("context window" in str(error) for error in next_attempt["errors"])
1836
- assert next_attempt["is_active"] is True
1837
-
1838
-
1839
- def test_semantic_log_normalizer_compacts_pi_cumulative_stream():
1840
- module = _load_progress_parser_module()
1841
- normalizer = module.SemanticLogNormalizer()
1842
- events = [
1843
- {"type": "session", "id": "session-1"},
1844
- {"type": "message_start", "message": {"role": "user"}},
1845
- {"type": "message_end", "message": {"role": "user", "content": [{"type": "text", "text": "SECRET PROMPT"}]}},
1846
- {"type": "turn_start"},
1847
- {"type": "message_update", "assistantMessageEvent": {"type": "thinking_start", "contentIndex": 0}},
1848
- {"type": "message_update", "assistantMessageEvent": {"type": "thinking_delta", "contentIndex": 0, "delta": "Inspecting"}},
1849
- {"type": "message_update", "assistantMessageEvent": {"type": "thinking_delta", "contentIndex": 0, "delta": " state"}},
1850
- {"type": "message_update", "assistantMessageEvent": {"type": "thinking_end", "contentIndex": 0, "content": "Inspecting state"}},
1851
- {"type": "tool_execution_start", "toolCallId": "call-1", "toolName": "bash", "args": {"command": "printf ABC"}},
1852
- {"type": "tool_execution_update", "toolCallId": "call-1", "toolName": "bash", "partialResult": {"content": [{"type": "text", "text": "A"}]}},
1853
- {"type": "tool_execution_update", "toolCallId": "call-1", "toolName": "bash", "partialResult": {"content": [{"type": "text", "text": "AB"}]}},
1854
- {"type": "tool_execution_update", "toolCallId": "call-1", "toolName": "bash", "partialResult": {"content": [{"type": "text", "text": "ABC"}]}},
1855
- {"type": "tool_execution_end", "toolCallId": "call-1", "toolName": "bash", "result": {"content": [{"type": "text", "text": "ABC"}]}, "isError": False},
1856
- {"type": "message_start", "message": {"role": "toolResult"}},
1857
- {"type": "message_end", "message": {"role": "toolResult", "toolCallId": "call-1", "toolName": "bash", "content": [{"type": "text", "text": "ABC"}]}},
1858
- {"type": "message_update", "assistantMessageEvent": {"type": "text_start", "contentIndex": 1}},
1859
- {"type": "message_update", "assistantMessageEvent": {"type": "text_delta", "contentIndex": 1, "delta": "Done"}},
1860
- {"type": "message_update", "assistantMessageEvent": {"type": "text_end", "contentIndex": 1, "content": "Done"}},
1861
- {"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Done"}], "stopReason": "stop"}},
1862
- {"type": "turn_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Done"}], "stopReason": "stop"}},
1863
- {"type": "agent_end", "willRetry": False, "messages": [{"role": "assistant", "content": [{"type": "text", "text": "Done"}], "stopReason": "stop"}]},
1864
- {"type": "agent_settled"},
1865
- ]
1866
-
1867
- rendered = "".join(normalizer.process_event(event) for event in events) + normalizer.finish()
1868
-
1869
- assert rendered.count("[THINK]") == 1
1870
- assert "[THINK] Inspecting state\n" in rendered
1871
- assert rendered.count("[ACTION]") == 1
1872
- assert "bash" in rendered and "printf ABC" in rendered
1873
- assert rendered.count("[OBSERVATION]") == 1
1874
- assert "[OBSERVATION] ABC\n" in rendered
1875
- assert rendered.count("[FINAL]") == 1
1876
- assert "[FINAL] Done\n" in rendered
1877
- assert rendered.count("[SESSION_END]") == 1
1878
- assert "message_update" not in rendered
1879
- assert "SECRET PROMPT" not in rendered
1880
-
1881
-
1882
- def test_semantic_log_normalizer_ignores_user_prompt_but_keeps_nested_tool_results():
1883
- module = _load_progress_parser_module()
1884
- normalizer = module.SemanticLogNormalizer()
1885
- rendered = normalizer.process_event({
1886
- "type": "user",
1887
- "message": {
1888
- "content": [
1889
- {"type": "text", "text": "SECRET PROMPT"},
1890
- {"type": "tool_result", "tool_use_id": "tool-1", "content": "tool output"},
1891
- ]
1892
- },
1893
- })
1894
- rendered += normalizer.finish()
1895
-
1896
- assert "SECRET PROMPT" not in rendered
1897
- assert "[OBSERVATION] tool output" in rendered
1898
-
1899
-
1900
- def test_semantic_log_normalizer_preserves_repeated_plain_and_tool_output_records():
1901
- module = _load_progress_parser_module()
1902
- normalizer = module.SemanticLogNormalizer()
1903
- rendered = normalizer.process_text("same\n")
1904
- rendered += normalizer.process_text("same\n")
1905
- rendered += normalizer.process_event({"type": "function_call_result", "id": "one", "output": "same result"})
1906
- rendered += normalizer.process_event({"type": "function_call_result", "id": "two", "output": "same result"})
1907
- rendered += normalizer.finish()
1908
-
1909
- assert rendered.count("[OUTPUT] same") == 2
1910
- assert rendered.count("[OBSERVATION] same result") == 2
1911
-
1912
-
1913
- def test_semantic_log_normalizer_emits_terminal_metadata_once():
1914
- module = _load_progress_parser_module()
1915
- normalizer = module.SemanticLogNormalizer()
1916
- rendered = normalizer.process_event({"type": "turn.completed"})
1917
- rendered += normalizer.process_event({"type": "result", "subtype": "success", "result": "Done"})
1918
- rendered += normalizer.finish()
1919
-
1920
- assert rendered.count("[SESSION_END]") == 1
1921
- assert "[FINAL] Done" in rendered
1922
-
1923
-
1924
- def test_semantic_log_normalizer_does_not_promote_pi_length_to_context_overflow():
1925
- module = _load_progress_parser_module()
1926
- normalizer = module.SemanticLogNormalizer()
1927
- rendered = normalizer.process_event({
1928
- "type": "agent_end",
1929
- "willRetry": False,
1930
- "messages": [{"role": "assistant", "content": [], "stopReason": "length"}],
1931
- })
1932
- rendered += normalizer.finish()
1933
-
1934
- assert rendered.count("[SESSION_END]") == 1
1935
- assert "status=success stop_reason=length" in rendered
1936
- assert "status=context_overflow" not in rendered
1937
-
1938
-
1939
- def test_semantic_log_normalizer_preserves_identical_text_from_distinct_turns():
1940
- module = _load_progress_parser_module()
1941
- normalizer = module.SemanticLogNormalizer()
1942
- events = [
1943
- {"type": "turn_start"},
1944
- {"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Done"}], "stopReason": "stop"}},
1945
- {"type": "turn_start"},
1946
- {"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Done"}], "stopReason": "stop"}},
1947
- ]
1948
-
1949
- rendered = "".join(normalizer.process_event(event) for event in events) + normalizer.finish()
1950
-
1951
- assert rendered.count("[FINAL] Done") == 2
1952
-
1953
-
1954
- def test_semantic_log_normalizer_size_tracks_unique_cumulative_content():
1955
- module = _load_progress_parser_module()
1956
- normalizer = module.SemanticLogNormalizer()
1957
- chunks = []
1958
- payload = ""
1959
- chunks.append(normalizer.process_event({"type": "tool_execution_start", "toolCallId": "call-1", "toolName": "read", "args": {"path": "sample"}}))
1960
- for index in range(1, 501):
1961
- payload += chr(64 + ((index - 1) % 26) + 1)
1962
- chunks.append(normalizer.process_event({
1963
- "type": "tool_execution_update",
1964
- "toolCallId": "call-1",
1965
- "toolName": "read",
1966
- "partialResult": {"content": [{"type": "text", "text": payload}]},
1967
- }))
1968
- assert sum(len(value) for value in normalizer._snapshots.values()) == len(payload)
1969
- assert not any(stream_id.startswith("tool:call-1:output") for stream_id in normalizer._stream_buffers)
1970
- chunks.append(normalizer.process_event({
1971
- "type": "tool_execution_end",
1972
- "toolCallId": "call-1",
1973
- "toolName": "read",
1974
- "result": {"content": [{"type": "text", "text": payload}]},
1975
- "isError": False,
1976
- }))
1977
- rendered = "".join(chunks) + normalizer.finish()
1978
-
1979
- assert rendered.count(payload) == 1
1980
- assert len(rendered.encode("utf-8")) <= len(payload.encode("utf-8")) + 256
1981
-
1982
-
1983
- @pytest.mark.parametrize(
1984
- ("events", "expected_labels"),
1985
- [
1986
- (
1987
- [
1988
- {"type": "assistant", "message": {"content": [{"type": "text", "text": "Answer"}, {"type": "tool_use", "id": "tool-1", "name": "Read", "input": {"path": "a"}}]}},
1989
- {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": "tool-1", "content": "result"}]}},
1990
- {"type": "result", "subtype": "success", "stop_reason": "end_turn", "result": "Answer"},
1991
- ],
1992
- {"[FINAL]", "[ACTION]", "[OBSERVATION]", "[SESSION_END]"},
1993
- ),
1994
- (
1995
- [
1996
- {"type": "message", "sessionId": "cb-1", "role": "assistant", "content": [{"type": "text", "text": "Answer"}]},
1997
- {"type": "function_call", "sessionId": "cb-1", "id": "call-1", "name": "read", "arguments": "{\"path\":\"a\"}"},
1998
- {"type": "function_call_result", "sessionId": "cb-1", "id": "call-1", "output": "result"},
1999
- {"type": "result", "subtype": "success", "result": "Answer"},
2000
- ],
2001
- {"[FINAL]", "[ACTION]", "[OBSERVATION]", "[SESSION_END]"},
2002
- ),
2003
- (
2004
- [
2005
- {"type": "turn.started"},
2006
- {"type": "item.completed", "item": {"id": "reason-1", "type": "reasoning", "text": "Think"}},
2007
- {"type": "item.started", "item": {"id": "cmd-1", "type": "command_execution", "command": "printf result"}},
2008
- {"type": "item.completed", "item": {"id": "cmd-1", "type": "command_execution", "command": "printf result", "aggregated_output": "result", "status": "completed"}},
2009
- {"type": "item.completed", "item": {"id": "answer-1", "type": "agent_message", "text": "Answer"}},
2010
- {"type": "turn.completed", "usage": {"input_tokens": 1}},
2011
- ],
2012
- {"[THINK]", "[FINAL]", "[ACTION]", "[OBSERVATION]", "[SESSION_END]"},
2013
- ),
2014
- ],
2015
- )
2016
- def test_semantic_log_normalizer_has_cross_format_contract(events, expected_labels):
2017
- module = _load_progress_parser_module()
2018
- normalizer = module.SemanticLogNormalizer()
2019
-
2020
- rendered = "".join(normalizer.process_event(event) for event in events) + normalizer.finish()
2021
-
2022
- for label in expected_labels:
2023
- assert label in rendered
2024
- assert not any(json.dumps(event, ensure_ascii=False) in rendered for event in events)
2025
-
2026
-
2027
1596
  def test_live_smoke_harness_reports_capability_skips_without_running(tmp_path, monkeypatch, capsys):
2028
1597
  import importlib.util
2029
1598
 
@@ -2062,152 +1631,6 @@ def test_live_smoke_harness_reports_capability_skips_without_running(tmp_path, m
2062
1631
  assert module._looks_capability_blocked("ordinary tool failure") is False
2063
1632
 
2064
1633
 
2065
- def test_progress_parser_normalizes_claude_subagents_without_double_counting(tmp_path):
2066
- module = _load_progress_parser_module()
2067
- tracker = module.ProgressTracker()
2068
-
2069
- tracker.process_event({"type": "system", "subtype": "init", "session_id": "claude-session", "cwd": str(tmp_path)})
2070
- tracker.process_event({
2071
- "type": "assistant",
2072
- "message": {"content": [{
2073
- "type": "tool_use",
2074
- "id": "tool-1",
2075
- "name": "Agent",
2076
- "input": {"description": "review code", "prompt": "check", "subagent_type": "reviewer"},
2077
- }]},
2078
- })
2079
- tracker.process_event({
2080
- "type": "system",
2081
- "subtype": "task_started",
2082
- "task_id": "task-1",
2083
- "tool_use_id": "tool-1",
2084
- "task_type": "in_process_teammate",
2085
- "subagent_type": "reviewer",
2086
- "description": "review code",
2087
- })
2088
- tracker.process_event({"type": "assistant", "parent_tool_use_id": "tool-1", "message": {"content": [{"type": "text", "text": "child activity"}]}})
2089
- tracker.process_event({"type": "system", "subtype": "task_started", "task_id": "bash-1", "task_type": "local_bash", "description": "ls"})
2090
- tracker.process_event({"type": "system", "subtype": "task_notification", "task_id": "task-1", "tool_use_id": "tool-1", "status": "completed", "summary": "done"})
2091
-
2092
- data = tracker.to_dict()
2093
-
2094
- statistics = data["subagent_statistics"]
2095
- assert statistics["source"] == "session_log"
2096
- assert statistics["spawned"] == 1
2097
- assert statistics["active"] == 0
2098
- assert statistics["states"] == [{"status": "completed", "count": 1}]
2099
- assert "task-1" in statistics["observed_ids"]
2100
- assert "tool-1" in statistics["parent_activity_ids"]
2101
- assert all("bash" not in record["id"] for record in data["subagent_statistics"]["records"])
2102
-
2103
-
2104
- def test_progress_parser_normalizes_codebuddy_agent_tools_with_deduplication():
2105
- module = _load_progress_parser_module()
2106
- tracker = module.ProgressTracker()
2107
- args = {"prompt": "inspect", "description": "inspect", "subagent_type": "Explore"}
2108
-
2109
- tracker.process_event({
2110
- "type": "message",
2111
- "sessionId": "cb-session",
2112
- "cwd": "/tmp/project",
2113
- "role": "assistant",
2114
- "content": [{"type": "tool_use", "id": "call-1", "name": "Agent", "input": args}],
2115
- })
2116
- tracker.process_event({
2117
- "type": "function_call",
2118
- "sessionId": "cb-session",
2119
- "cwd": "/tmp/project",
2120
- "id": "call-1",
2121
- "name": "Agent",
2122
- "arguments": json.dumps(args),
2123
- })
2124
- tracker.process_event({
2125
- "type": "function_call",
2126
- "sessionId": "cb-session",
2127
- "cwd": "/tmp/project",
2128
- "id": "task-call",
2129
- "name": "TaskCreate",
2130
- "arguments": json.dumps({"description": "background", "subject": "status"}),
2131
- })
2132
-
2133
- data = tracker.to_dict()
2134
-
2135
- assert data["cb_session_id"] == "cb-session"
2136
- statistics = data["subagent_statistics"]
2137
- assert statistics["providers"] == ["codebuddy"]
2138
- assert statistics["spawned"] == 1
2139
- assert statistics["active"] == 1
2140
- assert {item["status"] for item in statistics["states"]} == {"running"}
2141
- assert len(statistics["records"]) == 1
2142
- assert data["subagent_statistics"]["records"][0]["metadata"]["tool"] == "Agent"
2143
-
2144
-
2145
- def test_progress_parser_normalizes_codex_collab_metadata_with_missing_fields():
2146
- module = _load_progress_parser_module()
2147
- tracker = module.ProgressTracker()
2148
-
2149
- tracker.process_event({"type": "thread.started", "thread_id": "parent"})
2150
- tracker.process_event({
2151
- "type": "item.started",
2152
- "item": {
2153
- "type": "collab_tool_call",
2154
- "tool": "delegate",
2155
- "receiver_thread_ids": ["thread-a", "thread-b"],
2156
- "agents_states": {
2157
- "thread-a": {"status": "running", "message": "working"},
2158
- "thread-b": {"status": "completed", "message": "done"},
2159
- },
2160
- },
2161
- })
2162
- tracker.process_event({"type": "item.completed", "item": {"type": "collab_tool_call", "tool": "delegate"}})
2163
- tracker.process_event({"type": "turn.completed", "usage": {"input_tokens": 1}})
2164
-
2165
- data = tracker.to_dict()
2166
-
2167
- assert data["event_format"] == "codex-json"
2168
- assert data["result_subtype"] == "success"
2169
- assert data["stop_reason"] == "completed"
2170
- assert data["is_active"] is False
2171
- assert data["child_thread_ids"] == ["thread-a", "thread-b"]
2172
- statistics = data["subagent_statistics"]
2173
- assert statistics["spawned"] == 2
2174
- assert statistics["active"] == 1
2175
- assert {state["status"]: state["count"] for state in statistics["states"]} == {"running": 1, "completed": 1}
2176
- assert statistics["child_activity_source"] == "filesystem_liveness_only"
2177
-
2178
-
2179
- def test_progress_parser_keeps_child_files_liveness_only(tmp_path, monkeypatch):
2180
- module = _load_progress_parser_module()
2181
- claude_home = tmp_path / "claude"
2182
- project_key = str(tmp_path).replace("\\", "-").replace("/", "-").replace(":", "")
2183
- subagents_dir = claude_home / "projects" / project_key / "parent-session" / "subagents"
2184
- subagents_dir.mkdir(parents=True)
2185
- child_log = subagents_dir / "agent-child.jsonl"
2186
- child_log.write_text("child activity", encoding="utf-8")
2187
- monkeypatch.setenv("CLAUDE_HOME", str(claude_home))
2188
-
2189
- tracker = module.ProgressTracker()
2190
- tracker.process_event({"type": "system", "subtype": "init", "session_id": "parent-session", "cwd": str(tmp_path)})
2191
- tracker.process_event({
2192
- "type": "system",
2193
- "subtype": "task_started",
2194
- "task_id": "task-1",
2195
- "tool_use_id": "tool-1",
2196
- "task_type": "in_process_teammate",
2197
- "description": "agent",
2198
- })
2199
- first = tracker.to_dict()
2200
- child_log.write_text("child activity grew", encoding="utf-8")
2201
- tracker.refresh_child_session_activity(force=True)
2202
- second = tracker.to_dict()
2203
-
2204
- assert first["subagent_statistics"]["spawned"] == 1
2205
- assert second["subagent_statistics"]["spawned"] == 1
2206
- assert second["child_total_bytes"] > first["child_total_bytes"]
2207
- assert second["child_session_files"]
2208
- assert second["child_activity_source"] == "filesystem_liveness_only"
2209
- assert second["subagent_statistics"]["source"] == "session_log"
2210
-
2211
1634
  def test_session_dual_writes_progress_and_recovers_backup(tmp_path):
2212
1635
  from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher, recover_session_log
2213
1636
 
@@ -2259,1170 +1682,79 @@ def test_session_dual_writes_progress_and_recovers_backup(tmp_path):
2259
1682
  assert second_log.read_text(encoding="utf-8") == "larger recovered log"
2260
1683
 
2261
1684
 
2262
- def test_session_reader_does_not_retain_or_reread_raw_history():
2263
- import inspect
2264
- import prizmkit_runtime.sessions as sessions
2265
-
2266
- reader_source = inspect.getsource(sessions._reader_thread)
2267
- run_source = inspect.getsource(sessions.AISessionLauncher.run)
2268
-
2269
- assert "lines.append" not in reader_source
2270
- assert "output_queue" not in reader_source
2271
- assert "session_log.read_text" not in run_source
2272
- assert "splitlines()" not in run_source
2273
- assert "maxsize=1" in run_source
2274
-
2275
-
2276
- def test_session_reader_contains_parser_failures_and_continues_draining(tmp_path, monkeypatch):
2277
- import io
2278
- import queue
2279
- import prizmkit_runtime.sessions as sessions
2280
-
2281
- class FailingTracker:
2282
- def __init__(self, _session_log):
2283
- pass
2284
-
2285
- def process_event(self, _event):
2286
- raise ValueError("unsupported shape")
2287
-
2288
- def to_dict(self):
2289
- return {"event_type_counts": {}, "errors": []}
1685
+ def test_heartbeat_fatal_error_writes_shell_compatible_markers(tmp_path):
1686
+ from prizmkit_runtime.heartbeat import HeartbeatConfig, HeartbeatMonitor
1687
+ from prizmkit_runtime.processes import ProcessSpec, launch_process
2290
1688
 
2291
- class FailingNormalizer:
2292
- def process_event(self, _event):
2293
- raise ValueError("unsupported shape")
1689
+ sleeper = tmp_path / "fatal_sleep.py"
1690
+ sleeper.write_text("import time\ntime.sleep(5)\n", encoding="utf-8")
1691
+ progress = tmp_path / "progress.json"
1692
+ progress.write_text(
1693
+ '{"current_tool":"bash","fatal_error_code":"context_overflow"}\n',
1694
+ encoding="utf-8",
1695
+ )
1696
+ handle = launch_process(ProcessSpec(command=(sys.executable, str(sleeper)), cwd=tmp_path))
1697
+ monitor = HeartbeatMonitor(
1698
+ handle,
1699
+ HeartbeatConfig(
1700
+ heartbeat_file=tmp_path / "heartbeat.json",
1701
+ session_log=tmp_path / "session.log",
1702
+ progress_file=progress,
1703
+ marker_dir=tmp_path,
1704
+ interval_seconds=0.05,
1705
+ stale_after_seconds=10,
1706
+ kill_after_seconds=10,
1707
+ grace_seconds=0.1,
1708
+ ),
1709
+ )
1710
+ monitor.start()
1711
+ deadline = time.time() + 3
1712
+ while time.time() < deadline and not (tmp_path / "fatal-error.json").exists():
1713
+ time.sleep(0.05)
1714
+ result = monitor.stop()
2294
1715
 
2295
- def process_text(self, text):
2296
- return f"[OUTPUT] {text.strip()}\n"
1716
+ fatal = json.loads((tmp_path / "fatal-error.json").read_text(encoding="utf-8"))
1717
+ stale = json.loads((tmp_path / "stale-kill.json").read_text(encoding="utf-8"))
1718
+ assert result.killed is True
1719
+ assert result.reason == "context_overflow"
1720
+ assert fatal["killed_at"].endswith("Z")
1721
+ assert fatal["fatal_error_code"] == "context_overflow"
1722
+ assert stale["reason"] == "context_overflow"
2297
1723
 
2298
- def finish(self):
2299
- return "[SESSION_END] status=stream_closed\n"
2300
1724
 
2301
- monkeypatch.setattr(sessions, "_load_stream_parser_classes", lambda: (FailingTracker, FailingNormalizer))
2302
- session_log = tmp_path / "session.log"
2303
- backup_log = tmp_path / "backup.log"
2304
- session_log.write_text("", encoding="utf-8")
2305
- backup_log.write_text("", encoding="utf-8")
2306
- result_queue = queue.Queue(maxsize=1)
2307
- pipe = io.StringIO('{"type":"result","subtype":"success","result":"done"}\nplain\n')
1725
+ from prizmkit_runtime.heartbeat import HeartbeatConfig, write_stale_marker
1726
+ from prizmkit_runtime.processes import ProcessSpec, platform_termination_strategy, run_process_with_capture
2308
1727
 
2309
- sessions._reader_thread(pipe, session_log, backup_log, result_queue)
1728
+ sleeper = tmp_path / "sleep.py"
1729
+ sleeper.write_text("import time\ntime.sleep(5)\n", encoding="utf-8")
1730
+ result = run_process_with_capture(
1731
+ ProcessSpec(command=(sys.executable, str(sleeper)), cwd=tmp_path),
1732
+ timeout_seconds=0.2,
1733
+ grace_seconds=0.1,
1734
+ )
2310
1735
 
2311
- text = session_log.read_text(encoding="utf-8")
2312
- assert "[ERROR] progress parser rejected event=result: ValueError" in text
2313
- assert "[ERROR] semantic log adapter rejected event=result: ValueError" in text
2314
- assert "[OUTPUT] done" in text
2315
- assert "[OUTPUT] plain" in text
2316
- assert "[SESSION_END] status=stream_closed" in text
2317
- assert backup_log.read_text(encoding="utf-8") == text
2318
- assert result_queue.get_nowait()["event_type_counts"] == {}
1736
+ assert result.timed_out is True
1737
+ assert result.termination is not None
1738
+ assert result.termination.reason == "timeout"
1739
+ assert platform_termination_strategy()
2319
1740
 
1741
+ marker = write_stale_marker(tmp_path, reason="stale_session", stale_seconds=3, threshold=2)
1742
+ marker_data = json.loads(marker.read_text(encoding="utf-8"))
1743
+ assert marker_data["reason"] == "stale_session"
1744
+ assert marker_data["threshold"] == 2
1745
+ assert HeartbeatConfig(heartbeat_file=tmp_path / "heartbeat").interval_seconds == 30
2320
1746
 
2321
- def test_session_persists_normalized_stream_without_raw_history(tmp_path, monkeypatch):
2322
- import prizmkit_runtime.sessions as sessions
2323
1747
 
2324
- fake_cli = tmp_path / "pi_like_cli.py"
2325
- fake_cli.write_text(
2326
- "#!/usr/bin/env python3\n"
2327
- "import json, sys\n"
2328
- "_prompt = sys.stdin.read()\n"
2329
- "events = [\n"
2330
- " {'type':'session','id':'s1'},\n"
2331
- " {'type':'agent_start'},\n"
2332
- " {'type':'turn_start'},\n"
2333
- " {'type':'message_update','assistantMessageEvent':{'type':'thinking_start','contentIndex':0}},\n"
2334
- " {'type':'message_update','assistantMessageEvent':{'type':'thinking_delta','contentIndex':0,'delta':'Think'}},\n"
2335
- " {'type':'message_update','assistantMessageEvent':{'type':'thinking_end','contentIndex':0,'content':'Think'}},\n"
2336
- " {'type':'tool_execution_start','toolCallId':'c1','toolName':'bash','args':{'command':'printf ABC'}},\n"
2337
- " {'type':'tool_execution_update','toolCallId':'c1','toolName':'bash','partialResult':{'content':[{'type':'text','text':'A'}]}},\n"
2338
- " {'type':'tool_execution_update','toolCallId':'c1','toolName':'bash','partialResult':{'content':[{'type':'text','text':'ABC'}]}},\n"
2339
- " {'type':'tool_execution_end','toolCallId':'c1','toolName':'bash','result':{'content':[{'type':'text','text':'ABC'}]},'isError':False},\n"
2340
- " {'type':'message_update','assistantMessageEvent':{'type':'text_start','contentIndex':1}},\n"
2341
- " {'type':'message_update','assistantMessageEvent':{'type':'text_delta','contentIndex':1,'delta':'Done'}},\n"
2342
- " {'type':'message_update','assistantMessageEvent':{'type':'text_end','contentIndex':1,'content':'Done'}},\n"
2343
- " {'type':'message_end','message':{'role':'assistant','content':[{'type':'text','text':'Done'}],'stopReason':'stop'}},\n"
2344
- " {'type':'agent_end','willRetry':False,'messages':[{'role':'assistant','content':[{'type':'text','text':'Done'}],'stopReason':'stop'}]},\n"
2345
- "]\n"
2346
- "for event in events: print(json.dumps(event), flush=True)\n",
2347
- encoding="utf-8",
2348
- )
2349
- fake_cli.chmod(0o755)
2350
- prompt = tmp_path / "prompt.md"
2351
- prompt.write_text("hello", encoding="utf-8")
2352
- session_log = tmp_path / "state" / "sessions" / "sess-normalized" / "logs" / "session.log"
2353
- backup_log = tmp_path / "home" / ".prizmkit" / "session-backups" / "sess-normalized.log"
2354
- progress = session_log.with_name("progress.json")
2355
- captured_backup = {}
2356
- original_recover = sessions.recover_session_log
2357
-
2358
- def capture_recovery(primary, backup, min_size=1024):
2359
- captured_backup["text"] = backup.read_text(encoding="utf-8")
2360
- return original_recover(primary, backup, min_size)
2361
-
2362
- monkeypatch.setattr(sessions, "recover_session_log", capture_recovery)
2363
- result = sessions.AISessionLauncher(
2364
- sessions.AISessionConfig(
2365
- cli_command=str(fake_cli),
2366
- platform="pi",
2367
- model=None,
2368
- prompt_path=prompt,
2369
- cwd=tmp_path,
2370
- log_path=session_log,
2371
- backup_log_path=backup_log,
2372
- progress_path=progress,
2373
- )
2374
- ).run()
2375
-
2376
- text = session_log.read_text(encoding="utf-8")
2377
- assert result.exit_code == 0
2378
- assert result.progress_summary.result_subtype == "success"
2379
- assert "[THINK] Think" in text
2380
- assert "[ACTION] bash" in text
2381
- assert "[OBSERVATION] ABC" in text
2382
- assert "[FINAL] Done" in text
2383
- assert "[SESSION_END] status=success" in text
2384
- assert text.count("ABC") == 2 # one action argument and one observation
2385
- assert '"type": "message_update"' not in text
2386
- assert '"type":"message_update"' not in text
2387
- assert captured_backup["text"] == text
2388
- assert not backup_log.exists()
2389
-
2390
-
2391
- def test_pi_session_diagnostic_tool_output_does_not_trigger_fatal_termination(tmp_path):
2392
- import prizmkit_runtime.sessions as sessions
2393
-
2394
- fake_cli = tmp_path / "pi_diagnostic_cli.py"
2395
- fake_cli.write_text(
2396
- "#!/usr/bin/env python3\n"
2397
- "import json, sys, time\n"
2398
- "_prompt = sys.stdin.read()\n"
2399
- "source = 'continuation_reason = \\\"context_overflow\\\"\\nerror = _error_text(result)'\n"
2400
- "events = [\n"
2401
- " {'type':'session','id':'s1'},\n"
2402
- " {'type':'agent_start'},\n"
2403
- " {'type':'turn_start'},\n"
2404
- " {'type':'tool_execution_start','toolCallId':'c1','toolName':'read','args':{'path':'runtime.py'}},\n"
2405
- " {'type':'tool_execution_end','toolCallId':'c1','toolName':'read','result':{'content':[{'type':'text','text':source}]},'isError':False},\n"
2406
- " {'type':'message_end','message':{'role':'toolResult','toolCallId':'c1','content':[{'type':'text','text':source}],'stopReason':'toolUse'}},\n"
2407
- "]\n"
2408
- "for event in events: print(json.dumps(event), flush=True)\n"
2409
- "time.sleep(1.5)\n"
2410
- "message = {'role':'assistant','content':[{'type':'text','text':'Done'}],'stopReason':'stop'}\n"
2411
- "print(json.dumps({'type':'message_end','message':message}), flush=True)\n"
2412
- "print(json.dumps({'type':'agent_end','willRetry':False,'messages':[message]}), flush=True)\n",
2413
- encoding="utf-8",
2414
- )
2415
- fake_cli.chmod(0o755)
2416
- prompt = tmp_path / "prompt.md"
2417
- prompt.write_text("hello", encoding="utf-8")
2418
- session_log = tmp_path / "state" / "sessions" / "sess-diagnostic" / "logs" / "session.log"
2419
- progress = session_log.with_name("progress.json")
2420
-
2421
- result = sessions.AISessionLauncher(
2422
- sessions.AISessionConfig(
2423
- cli_command=str(fake_cli),
2424
- platform="pi",
2425
- model=None,
2426
- prompt_path=prompt,
2427
- cwd=tmp_path,
2428
- log_path=session_log,
2429
- progress_path=progress,
2430
- )
2431
- ).run()
2432
-
2433
- progress_data = json.loads(progress.read_text(encoding="utf-8"))
2434
- assert result.exit_code == 0
2435
- assert result.fatal_error_code == ""
2436
- assert result.progress_summary.result_subtype == "success"
2437
- assert progress_data["fatal_error_code"] == ""
2438
- assert not session_log.with_name("fatal-error.json").exists()
2439
- assert not session_log.with_name("stale-kill.json").exists()
2440
-
2441
-
2442
- def test_custom_session_launch_writes_existing_logs_and_progress(tmp_path):
2443
- from prizmkit_runtime.launch_profiles import HeadlessLaunchProfile
2444
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
2445
-
2446
- fake_cli = tmp_path / "custom_cli.py"
2447
- fake_cli.write_text(
2448
- "#!/usr/bin/env python3\n"
2449
- "import json, sys\n"
2450
- "assert sys.argv[1] == '-i'\n"
2451
- "assert sys.argv[2] == 'hello custom'\n"
2452
- "assert sys.argv[3:] == ['--verbose', '--path', 'two words']\n"
2453
- "print(json.dumps({'type':'result','subtype':'success','usage':{'tokens':1},'result':'ok'}), flush=True)\n",
2454
- encoding="utf-8",
2455
- )
2456
- fake_cli.chmod(0o755)
2457
- prompt = tmp_path / "prompt.md"
2458
- prompt.write_text("hello custom", encoding="utf-8")
2459
- session_log = tmp_path / "state" / "sessions" / "sess-custom" / "logs" / "session.log"
2460
- progress = session_log.with_name("progress.json")
2461
-
2462
- result = AISessionLauncher(
2463
- AISessionConfig(
2464
- cli_command=str(fake_cli),
2465
- platform="custom",
2466
- model=None,
2467
- prompt_path=prompt,
2468
- cwd=tmp_path,
2469
- log_path=session_log,
2470
- progress_path=progress,
2471
- launch_profile=HeadlessLaunchProfile(
2472
- profile="custom",
2473
- prompt_arg="-i",
2474
- extra_args=("--verbose", "--path", "two words"),
2475
- ),
2476
- )
2477
- ).run()
2478
-
2479
- assert result.exit_code == 0
2480
- assert result.command.argv[1:4] == ("-i", "hello custom", "--verbose")
2481
- assert session_log.exists()
2482
- assert progress.exists()
2483
- progress_data = json.loads(progress.read_text(encoding="utf-8"))
2484
- assert progress_data["event_type_counts"]["result"] == 1
2485
- assert progress_data["has_usage"] is True
2486
- assert progress_data["subagent_statistics"]["source"] == "session_log"
2487
- assert progress_data["subagent_statistics"]["spawned"] == 0
2488
- assert progress_data["subagent_statistics"]["providers"] == []
2489
- assert progress_data["child_activity_source"] == "filesystem_liveness_only"
2490
-
2491
-
2492
- @pytest.mark.parametrize("platform", ["claude", "codex", "codebuddy"])
2493
- def test_builtin_provider_launches_write_session_artifacts(tmp_path, platform):
2494
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
2495
-
2496
- fake_cli = tmp_path / f"{platform}_cli.py"
2497
- fake_cli.write_text(
2498
- "#!/usr/bin/env python3\n"
2499
- "import json, sys\n"
2500
- "_stdin = sys.stdin.read()\n"
2501
- "print(json.dumps({'type':'result','subtype':'success','usage':{'tokens':1},'result':'ok'}), flush=True)\n",
2502
- encoding="utf-8",
2503
- )
2504
- fake_cli.chmod(0o755)
2505
- prompt = tmp_path / f"{platform}-prompt.md"
2506
- prompt.write_text(f"hello {platform}", encoding="utf-8")
2507
- session_log = tmp_path / "state" / "sessions" / f"sess-{platform}" / "logs" / "session.log"
2508
- progress = session_log.with_name("progress.json")
2509
- heartbeat = session_log.with_name("heartbeat.json")
2510
-
2511
- result = AISessionLauncher(
2512
- AISessionConfig(
2513
- cli_command=str(fake_cli),
2514
- platform=platform,
2515
- model=None,
2516
- prompt_path=prompt,
2517
- cwd=tmp_path,
2518
- log_path=session_log,
2519
- progress_path=progress,
2520
- heartbeat_path=heartbeat,
2521
- use_stream_json=True,
2522
- )
2523
- ).run()
2524
-
2525
- progress_data = json.loads(progress.read_text(encoding="utf-8"))
2526
- assert result.exit_code == 0
2527
- assert session_log.exists()
2528
- assert heartbeat.exists()
2529
- assert progress_data["event_type_counts"]["result"] == 1
2530
- assert progress_data["has_usage"] is True
2531
-
2532
-
2533
- def test_session_live_output_prints_paths_and_verbose_cli_output(tmp_path, capsys):
2534
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
2535
-
2536
- fake_cli = tmp_path / "live_cli.py"
2537
- fake_cli.write_text(
2538
- "#!/usr/bin/env python3\n"
2539
- "print('live-line', flush=True)\n",
2540
- encoding="utf-8",
2541
- )
2542
- fake_cli.chmod(0o755)
2543
- prompt = tmp_path / "prompt.md"
2544
- prompt.write_text("hello", encoding="utf-8")
2545
- session_log = tmp_path / "state" / "sessions" / "sess-live" / "logs" / "session.log"
2546
- progress = session_log.with_name("progress.json")
2547
- heartbeat = session_log.with_name("heartbeat.json")
2548
-
2549
- result = AISessionLauncher(
2550
- AISessionConfig(
2551
- cli_command=str(fake_cli),
2552
- platform="codebuddy",
2553
- model=None,
2554
- prompt_path=prompt,
2555
- cwd=tmp_path,
2556
- log_path=session_log,
2557
- progress_path=progress,
2558
- heartbeat_path=heartbeat,
2559
- verbose=True,
2560
- live_output=True,
2561
- )
2562
- ).run()
2563
-
2564
- captured = capsys.readouterr()
2565
- assert result.exit_code == 0
2566
- assert "live-line" in captured.out
2567
- assert "[prizmkit] AI session started" in captured.err
2568
- assert f"[prizmkit] Prompt: {prompt}" in captured.err
2569
- assert f"[prizmkit] Session log: {session_log}" in captured.err
2570
- assert f"[prizmkit] Progress: {progress}" in captured.err
2571
- assert f"[prizmkit] Heartbeat: {heartbeat}" in captured.err
2572
- assert "[prizmkit] AI session finished" in captured.err
2573
-
2574
-
2575
- def test_compact_progress_line_hides_stale_until_no_progress(tmp_path):
2576
- from prizmkit_runtime.heartbeat import HeartbeatState
2577
- from prizmkit_runtime.sessions import _compact_progress_line
2578
-
2579
- session_log = tmp_path / "session.log"
2580
- progress = tmp_path / "progress.json"
2581
- checkpoint = tmp_path / "workflow-checkpoint.json"
2582
- progress.write_text(
2583
- json.dumps(
2584
- {
2585
- "child_total_bytes": 2 * 1024 * 1024,
2586
- "child_session_files": [{"path": "a"}, {"path": "b"}],
2587
- "subagent_statistics": {
2588
- "spawned": 5,
2589
- "active": 2,
2590
- "states": [{"status": "running", "count": 2}, {"status": "completed", "count": 3}],
2591
- },
2592
- "current_phase": "stream-derived-phase",
2593
- "current_tool": "Read",
2594
- "message_count": 465,
2595
- "total_tool_calls": 412,
2596
- }
2597
- ),
2598
- encoding="utf-8",
2599
- )
2600
- checkpoint.write_text(
2601
- json.dumps({"steps": [
2602
- {"id": "S01", "skill": "plan", "name": "Plan", "status": "completed"},
2603
- {"id": "S02", "skill": "retro", "name": "Retrospective", "status": "pending", "depends_on": "S01"},
2604
- ]}),
2605
- encoding="utf-8",
2606
- )
2607
- running = HeartbeatState(last_seen_epoch=1.0, stale=False, details="progress", stale_seconds=0, log_size=4 * 1024 * 1024)
2608
- brief_pause = HeartbeatState(last_seen_epoch=1.0, stale=False, details="no progress", stale_seconds=125, log_size=4 * 1024 * 1024)
2609
- paused = HeartbeatState(last_seen_epoch=1.0, stale=True, details="no progress", stale_seconds=15 * 60, log_size=4 * 1024 * 1024)
2610
- resumed = HeartbeatState(last_seen_epoch=3.0, stale=False, details="progress", stale_seconds=0, log_size=5 * 1024 * 1024)
2611
-
2612
- running_line = _compact_progress_line(0, session_log, progress, running, checkpoint_path=checkpoint, stale_threshold_seconds=15 * 60)
2613
- brief_pause_line = _compact_progress_line(0, session_log, progress, brief_pause, checkpoint_path=checkpoint, stale_threshold_seconds=15 * 60)
2614
- paused_line = _compact_progress_line(0, session_log, progress, paused, checkpoint_path=checkpoint, stale_threshold_seconds=15 * 60)
2615
- resumed_line = _compact_progress_line(0, session_log, progress, resumed, checkpoint_path=checkpoint, stale_threshold_seconds=15 * 60)
2616
-
2617
- assert "▶ [HEARTBEAT]" in running_line
2618
- assert "log: 4MB" in running_line
2619
- assert "subagents: spawned=5 active=2 states:running=2,completed=3" in running_line
2620
- assert "child logs: 2MB/2 files" in running_line
2621
- assert "child: 2MB/5" not in running_line
2622
- assert "phase: Retrospective" in running_line
2623
- assert "stream-derived-phase" not in running_line
2624
- assert "tool: Read" in running_line
2625
- assert "msgs: 465" in running_line
2626
- assert "412 tool calls" in running_line
2627
- assert "stale:" not in running_line
2628
- assert "▶ [HEARTBEAT]" in brief_pause_line
2629
- assert "stale:" not in brief_pause_line
2630
- assert "⏸ [HEARTBEAT]" in paused_line
2631
- assert "stale: 15m/15m" in paused_line
2632
- assert "▶ [HEARTBEAT]" in resumed_line
2633
- assert "log: 5MB" in resumed_line
2634
- assert "stale:" not in resumed_line
2635
-
2636
- def test_compact_progress_line_omits_phase_without_valid_checkpoint(tmp_path):
2637
- from prizmkit_runtime.heartbeat import HeartbeatState
2638
- from prizmkit_runtime.sessions import _compact_progress_line
2639
-
2640
- session_log = tmp_path / "session.log"
2641
- progress = tmp_path / "progress.json"
2642
- malformed = tmp_path / "bad-checkpoint.json"
2643
- invalid = tmp_path / "invalid-checkpoint.json"
2644
- progress.write_text(
2645
- json.dumps({"current_phase": "legacy-plan", "current_tool": "Edit"}),
2646
- encoding="utf-8",
2647
- )
2648
- malformed.write_text("{bad", encoding="utf-8")
2649
- invalid.write_text(json.dumps({"steps": [{"id": "S01", "skill": "x", "name": "X", "status": "done"}]}), encoding="utf-8")
2650
- state = HeartbeatState(last_seen_epoch=1.0, stale=False, details="progress", stale_seconds=0, log_size=12)
2651
-
2652
- missing_line = _compact_progress_line(0, session_log, progress, state, checkpoint_path=tmp_path / "missing.json")
2653
- malformed_line = _compact_progress_line(0, session_log, progress, state, checkpoint_path=malformed)
2654
- invalid_line = _compact_progress_line(0, session_log, progress, state, checkpoint_path=invalid)
2655
-
2656
- for line in (missing_line, malformed_line, invalid_line):
2657
- assert "phase:" not in line
2658
- assert "legacy-plan" not in line
2659
- assert "tool: Edit" in line
2660
-
2661
-
2662
- def test_heartbeat_observation_stale_accumulates_by_elapsed_time_and_resets_on_progress(tmp_path, monkeypatch):
2663
- import prizmkit_runtime.heartbeat as heartbeat
2664
- from prizmkit_runtime.heartbeat import HeartbeatConfig, observe_heartbeat_state
2665
-
2666
- session_log = tmp_path / "session.log"
2667
- progress = tmp_path / "progress.json"
2668
- session_log.write_text("initial\n", encoding="utf-8")
2669
- progress.write_text('{"current_phase":"plan","current_tool":null,"message_count":1,"total_tool_calls":1}\n', encoding="utf-8")
2670
- config = HeartbeatConfig(
2671
- heartbeat_file=tmp_path / "heartbeat.json",
2672
- session_log=session_log,
2673
- progress_file=progress,
2674
- interval_seconds=60,
2675
- stale_after_seconds=15 * 60,
2676
- )
2677
- ticks = iter([1000.0, 1025.0, 1090.0, 1095.0])
2678
- monkeypatch.setattr(heartbeat.time, "time", lambda: next(ticks))
2679
-
2680
- first = observe_heartbeat_state(config)
2681
- stale = observe_heartbeat_state(config, first)
2682
- older = observe_heartbeat_state(config, stale)
2683
- progress.write_text('{"current_phase":"plan","current_tool":"Edit","message_count":1,"total_tool_calls":2,"child_total_bytes":10}\n', encoding="utf-8")
2684
- reset = observe_heartbeat_state(config, older)
2685
-
2686
- assert first.details == "progress"
2687
- assert first.stale_seconds == 0
2688
- assert first.last_seen_epoch == 1000.0
2689
- assert stale.details == "no progress"
2690
- assert stale.stale_seconds == 25.0
2691
- assert older.stale_seconds == 90.0
2692
- assert reset.details == "progress"
2693
- assert reset.stale_seconds == 0
2694
- assert reset.last_seen_epoch == 1095.0
2695
-
2696
-
2697
- def test_heartbeat_observation_active_tool_resets_stale_until_tool_clears(tmp_path, monkeypatch):
2698
- import prizmkit_runtime.heartbeat as heartbeat
2699
- from prizmkit_runtime.heartbeat import HeartbeatConfig, observe_heartbeat_state
2700
-
2701
- progress = tmp_path / "progress.json"
2702
- progress.write_text(
2703
- '{"current_tool":"bash","message_count":1,"total_tool_calls":1}\n',
2704
- encoding="utf-8",
2705
- )
2706
- config = HeartbeatConfig(
2707
- heartbeat_file=tmp_path / "heartbeat.json",
2708
- progress_file=progress,
2709
- stale_after_seconds=60,
2710
- )
2711
- ticks = iter([1000.0, 1100.0, 1200.0, 1205.0, 1230.0])
2712
- monkeypatch.setattr(heartbeat.time, "time", lambda: next(ticks))
2713
-
2714
- first = observe_heartbeat_state(config)
2715
- active = observe_heartbeat_state(config, first)
2716
- still_active = observe_heartbeat_state(config, active)
2717
- progress.write_text(
2718
- '{"current_tool":null,"message_count":1,"total_tool_calls":1}\n',
2719
- encoding="utf-8",
2720
- )
2721
- tool_finished = observe_heartbeat_state(config, still_active)
2722
- idle = observe_heartbeat_state(config, tool_finished)
2723
-
2724
- assert active.details == "progress"
2725
- assert active.stale_seconds == 0
2726
- assert active.last_seen_epoch == 1100.0
2727
- assert still_active.details == "progress"
2728
- assert still_active.stale_seconds == 0
2729
- assert still_active.last_seen_epoch == 1200.0
2730
- assert tool_finished.details == "progress"
2731
- assert tool_finished.stale_seconds == 0
2732
- assert tool_finished.last_seen_epoch == 1205.0
2733
- assert idle.details == "no progress"
2734
- assert idle.stale_seconds == 25.0
2735
-
2736
-
2737
- @pytest.mark.parametrize("current_tool", [None, "", " ", 0, ["bash"]])
2738
- def test_heartbeat_observation_rejects_inactive_or_malformed_tool_values(
2739
- tmp_path,
2740
- monkeypatch,
2741
- current_tool,
2742
- ):
2743
- import prizmkit_runtime.heartbeat as heartbeat
2744
- from prizmkit_runtime.heartbeat import HeartbeatConfig, observe_heartbeat_state
2745
-
2746
- progress = tmp_path / "progress.json"
2747
- progress.write_text(json.dumps({"current_tool": current_tool}), encoding="utf-8")
2748
- config = HeartbeatConfig(
2749
- heartbeat_file=tmp_path / "heartbeat.json",
2750
- progress_file=progress,
2751
- stale_after_seconds=60,
2752
- )
2753
- ticks = iter([1000.0, 1070.0])
2754
- monkeypatch.setattr(heartbeat.time, "time", lambda: next(ticks))
2755
-
2756
- first = observe_heartbeat_state(config)
2757
- stale = observe_heartbeat_state(config, first)
2758
-
2759
- assert stale.details == "no progress"
2760
- assert stale.stale is True
2761
- assert stale.stale_seconds == 70.0
2762
-
2763
-
2764
- def test_heartbeat_state_tracks_progress_json_child_activity(tmp_path, monkeypatch):
2765
- import prizmkit_runtime.heartbeat as heartbeat
2766
- from prizmkit_runtime.heartbeat import HeartbeatConfig, observe_heartbeat_state
2767
-
2768
- progress = tmp_path / "progress.json"
2769
- progress.write_text(
2770
- json.dumps({"child_activity_signature": "child:1", "child_total_bytes": 10}),
2771
- encoding="utf-8",
2772
- )
2773
- config = HeartbeatConfig(
2774
- heartbeat_file=tmp_path / "heartbeat.json",
2775
- session_log=tmp_path / "missing-session.log",
2776
- progress_file=progress,
2777
- stale_after_seconds=60,
2778
- )
2779
- ticks = iter([10.0, 20.0, 25.0])
2780
- monkeypatch.setattr(heartbeat.time, "time", lambda: next(ticks))
2781
-
2782
- first = observe_heartbeat_state(config)
2783
- quiet = observe_heartbeat_state(config, first)
2784
- progress.write_text(
2785
- json.dumps({"child_activity_signature": "child:2", "child_total_bytes": 20}),
2786
- encoding="utf-8",
2787
- )
2788
- child_progress = observe_heartbeat_state(config, quiet)
2789
-
2790
- assert quiet.details == "no progress"
2791
- assert quiet.stale_seconds == 10.0
2792
- assert child_progress.details == "progress"
2793
- assert child_progress.stale_seconds == 0
2794
- assert child_progress.child_activity_signature == "child:2"
2795
-
2796
-
2797
- def test_heartbeat_monitor_stale_kill_uses_elapsed_no_progress_threshold(tmp_path):
2798
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
2799
-
2800
- fake_cli = tmp_path / "quiet_cli.py"
2801
- fake_cli.write_text(
2802
- "#!/usr/bin/env python3\n"
2803
- "import time\n"
2804
- "time.sleep(5)\n",
2805
- encoding="utf-8",
2806
- )
2807
- fake_cli.chmod(0o755)
2808
- prompt = tmp_path / "prompt.md"
2809
- prompt.write_text("hello", encoding="utf-8")
2810
- session_log = tmp_path / "state" / "sessions" / "sess-stale" / "logs" / "session.log"
2811
- progress = session_log.with_name("progress.json")
2812
- heartbeat = session_log.with_name("heartbeat.json")
2813
-
2814
- result = AISessionLauncher(
2815
- AISessionConfig(
2816
- cli_command=str(fake_cli),
2817
- platform="codebuddy",
2818
- model=None,
2819
- prompt_path=prompt,
2820
- cwd=tmp_path,
2821
- log_path=session_log,
2822
- progress_path=progress,
2823
- heartbeat_path=heartbeat,
2824
- stale_kill_threshold_seconds=0.3,
2825
- heartbeat_stale_threshold_seconds=0.2,
2826
- stale_kill_grace_seconds=0.1,
2827
- )
2828
- ).run()
2829
-
2830
- marker = session_log.parent / "stale-kill.json"
2831
- marker_data = json.loads(marker.read_text(encoding="utf-8"))
2832
- assert result.termination_reason == "stale_session"
2833
- assert result.stale_marker == marker
2834
- assert marker_data["reason"] == "stale_session"
2835
- assert marker_data["threshold"] == pytest.approx(0.3)
2836
- assert marker_data["stale_seconds"] >= 0
2837
-
2838
-
2839
- def test_heartbeat_monitor_active_tool_defers_stale_kill_until_tool_clears(tmp_path):
2840
- from prizmkit_runtime.heartbeat import HeartbeatConfig, HeartbeatMonitor
2841
- from prizmkit_runtime.processes import ProcessSpec, is_process_running, launch_process
2842
-
2843
- sleeper = tmp_path / "active_tool_sleep.py"
2844
- sleeper.write_text("import time\ntime.sleep(5)\n", encoding="utf-8")
2845
- progress = tmp_path / "progress.json"
2846
- progress.write_text('{"current_tool":"bash"}\n', encoding="utf-8")
2847
- handle = launch_process(ProcessSpec(command=(sys.executable, str(sleeper)), cwd=tmp_path))
2848
- monitor = HeartbeatMonitor(
2849
- handle,
2850
- HeartbeatConfig(
2851
- heartbeat_file=tmp_path / "heartbeat.json",
2852
- session_log=tmp_path / "session.log",
2853
- progress_file=progress,
2854
- marker_dir=tmp_path,
2855
- interval_seconds=0.05,
2856
- stale_after_seconds=0.1,
2857
- kill_after_seconds=0.2,
2858
- grace_seconds=0.1,
2859
- ),
2860
- )
2861
- monitor.start()
2862
-
2863
- time.sleep(0.5)
2864
- assert is_process_running(handle)
2865
- assert not (tmp_path / "stale-kill.json").exists()
2866
-
2867
- progress.write_text('{"current_tool":null}\n', encoding="utf-8")
2868
- deadline = time.time() + 3
2869
- while time.time() < deadline and not (tmp_path / "stale-kill.json").exists():
2870
- time.sleep(0.05)
2871
- result = monitor.stop()
2872
-
2873
- marker = json.loads((tmp_path / "stale-kill.json").read_text(encoding="utf-8"))
2874
- assert result.killed is True
2875
- assert result.reason == "stale_session"
2876
- assert marker["reason"] == "stale_session"
2877
-
2878
-
2879
- def test_pi_session_active_tool_stream_survives_stale_threshold(tmp_path, monkeypatch):
2880
- import prizmkit_runtime.sessions as sessions
2881
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
2882
-
2883
- parser_classes = sessions._load_stream_parser_classes()
2884
- monkeypatch.setattr(sessions, "_load_stream_parser_classes", lambda: parser_classes)
2885
-
2886
- fake_cli = tmp_path / "pi_active_tool_cli.py"
2887
- fake_cli.write_text(
2888
- "#!/usr/bin/env python3\n"
2889
- "import json, sys, time\n"
2890
- "_prompt = sys.stdin.read(5)\n"
2891
- "for event in [\n"
2892
- " {'type':'session','id':'active-tool-session'},\n"
2893
- " {'type':'agent_start'},\n"
2894
- " {'type':'turn_start'},\n"
2895
- " {'type':'tool_execution_start','toolCallId':'call-1','toolName':'long-running-tool','args':{}},\n"
2896
- "]:\n"
2897
- " print(json.dumps(event), flush=True)\n"
2898
- "time.sleep(3.0)\n"
2899
- "for event in [\n"
2900
- " {'type':'tool_execution_end','toolCallId':'call-1','toolName':'long-running-tool','result':{'content':[]},'isError':False},\n"
2901
- " {'type':'message_end','message':{'role':'assistant','content':[{'type':'text','text':'done'}],'stopReason':'stop'}},\n"
2902
- " {'type':'agent_end','willRetry':False,'messages':[{'role':'assistant','content':[{'type':'text','text':'done'}],'stopReason':'stop'}]},\n"
2903
- "]:\n"
2904
- " print(json.dumps(event), flush=True)\n",
2905
- encoding="utf-8",
2906
- )
2907
- fake_cli.chmod(0o755)
2908
- prompt = tmp_path / "prompt.md"
2909
- prompt.write_text("hello", encoding="utf-8")
2910
- session_log = tmp_path / "state" / "sessions" / "active-tool" / "logs" / "session.log"
2911
- progress = session_log.with_name("progress.json")
2912
-
2913
- result = AISessionLauncher(
2914
- AISessionConfig(
2915
- cli_command=str(fake_cli),
2916
- platform="pi",
2917
- model=None,
2918
- prompt_path=prompt,
2919
- cwd=tmp_path,
2920
- log_path=session_log,
2921
- progress_path=progress,
2922
- heartbeat_path=session_log.with_name("heartbeat.json"),
2923
- stale_kill_threshold_seconds=1.5,
2924
- heartbeat_stale_threshold_seconds=1.0,
2925
- stale_kill_grace_seconds=0.1,
2926
- live_progress_interval_seconds=0.05,
2927
- )
2928
- ).run()
2929
-
2930
- final_progress = json.loads(progress.read_text(encoding="utf-8"))
2931
- assert result.exit_code == 0
2932
- assert result.termination_reason is None
2933
- assert final_progress["current_tool"] is None
2934
- assert not (session_log.parent / "stale-kill.json").exists()
2935
-
2936
-
2937
- def test_stale_marker_preserves_subsecond_threshold(tmp_path):
2938
- from prizmkit_runtime.heartbeat import write_stale_marker
2939
-
2940
- marker = write_stale_marker(
2941
- tmp_path,
2942
- reason="stale_session",
2943
- stale_seconds=0.4,
2944
- threshold=0.3,
2945
- )
2946
- data = json.loads(marker.read_text(encoding="utf-8"))
2947
-
2948
- assert data["stale_seconds"] == pytest.approx(0.4)
2949
- assert data["threshold"] == pytest.approx(0.3)
2950
-
2951
-
2952
- def test_idle_progress_refresh_updates_child_activity_without_parent_output(tmp_path, monkeypatch):
2953
- import prizmkit_runtime.sessions as sessions
2954
-
2955
- progress = tmp_path / "progress.json"
2956
- tracker_lock = sessions.threading.Lock()
2957
- stop_event = sessions.threading.Event()
2958
-
2959
- class FakeTracker:
2960
- def __init__(self):
2961
- self.calls = 0
2962
-
2963
- def to_dict(self):
2964
- self.calls += 1
2965
- return {
2966
- "message_count": 1,
2967
- "event_type_counts": {},
2968
- "current_tool": "Task",
2969
- "current_phase": "implement",
2970
- "total_tool_calls": 1,
2971
- "subagent_statistics": {"active": 1, "spawned": 1},
2972
- "child_activity_signature": f"child:{self.calls}",
2973
- "child_total_bytes": self.calls,
2974
- "fatal_error_code": "",
2975
- "terminal_result_text": "",
2976
- "errors": [],
2977
- }
2978
-
2979
- thread, refresh = sessions._start_idle_progress_refresh(
2980
- progress,
2981
- FakeTracker(),
2982
- tracker_lock,
2983
- stop_event,
2984
- interval_seconds=0.1,
2985
- )
2986
- try:
2987
- refresh(True)
2988
- first = json.loads(progress.read_text(encoding="utf-8"))
2989
- time.sleep(0.25)
2990
- second = json.loads(progress.read_text(encoding="utf-8"))
2991
- finally:
2992
- stop_event.set()
2993
- thread.join(timeout=1)
2994
-
2995
- assert first["child_activity_signature"].startswith("child:")
2996
- assert second["child_activity_signature"] != first["child_activity_signature"]
2997
- assert second["child_total_bytes"] > first["child_total_bytes"]
2998
-
2999
- def test_compact_live_heartbeat_stays_out_of_primary_and_backup_logs(tmp_path, capsys, monkeypatch):
3000
- import prizmkit_runtime.sessions as sessions
3001
-
3002
- fake_cli = tmp_path / "slow_cli.py"
3003
- fake_cli.write_text(
3004
- "#!/usr/bin/env python3\n"
3005
- "import time\n"
3006
- "print('logged-payload', flush=True)\n"
3007
- "time.sleep(0.45)\n",
3008
- encoding="utf-8",
3009
- )
3010
- fake_cli.chmod(0o755)
3011
- prompt = tmp_path / "prompt.md"
3012
- prompt.write_text("hello", encoding="utf-8")
3013
- session_log = tmp_path / "state" / "sessions" / "sess-heartbeat" / "logs" / "session.log"
3014
- backup_log = tmp_path / "home" / ".prizmkit" / "session-backups" / "sess-heartbeat.log"
3015
- progress = session_log.with_name("progress.json")
3016
- backup_text = {}
3017
- original_recover = sessions.recover_session_log
3018
-
3019
- def spy_recover(primary, backup, min_size=1024):
3020
- if backup.is_file():
3021
- backup_text["content"] = backup.read_text(encoding="utf-8")
3022
- return original_recover(primary, backup, min_size)
3023
-
3024
- monkeypatch.setattr(sessions, "recover_session_log", spy_recover)
3025
- result = sessions.AISessionLauncher(
3026
- sessions.AISessionConfig(
3027
- cli_command=str(fake_cli),
3028
- platform="codebuddy",
3029
- model=None,
3030
- prompt_path=prompt,
3031
- cwd=tmp_path,
3032
- log_path=session_log,
3033
- backup_log_path=backup_log,
3034
- progress_path=progress,
3035
- live_output=True,
3036
- live_progress_interval_seconds=0.1,
3037
- stale_kill_threshold_seconds=15 * 60,
3038
- )
3039
- ).run()
3040
-
3041
- captured = capsys.readouterr()
3042
- primary_text = session_log.read_text(encoding="utf-8")
3043
- assert result.exit_code == 0
3044
- assert "[HEARTBEAT]" in captured.err
3045
- assert "logged-payload" in primary_text
3046
- assert "[HEARTBEAT]" not in primary_text
3047
- assert "stale:" not in primary_text
3048
- assert "[HEARTBEAT]" not in backup_text.get("content", "")
3049
- assert "stale:" not in backup_text.get("content", "")
3050
-
3051
-
3052
- def test_session_summary_reports_normalized_subagents_and_child_liveness(tmp_path, capsys):
3053
- import prizmkit_runtime.runners as runners
3054
- from prizmkit_runtime.runner_models import SessionPaths
3055
-
3056
- logs = tmp_path / "sessions" / "s1" / "logs"
3057
- logs.mkdir(parents=True)
3058
- session_log = logs / "session.log"
3059
- progress = logs / "progress.json"
3060
- session_log.write_text("one\ntwo\n", encoding="utf-8")
3061
- progress.write_text(
3062
- json.dumps({
3063
- "subagent_statistics": {
3064
- "spawned": 2,
3065
- "active": 1,
3066
- "states": [{"status": "running", "count": 1}, {"status": "completed", "count": 1}],
3067
- "providers": ["claude"],
3068
- "source": "session_log",
3069
- },
3070
- "child_total_bytes": 2048,
3071
- "child_session_files": [{"path": "child-a"}],
3072
- }),
3073
- encoding="utf-8",
3074
- )
3075
- paths = SessionPaths(
3076
- session_dir=logs.parent,
3077
- prompt_path=logs.parent / "bootstrap-prompt.md",
3078
- logs_dir=logs,
3079
- session_log=session_log,
3080
- progress_json=progress,
3081
- heartbeat_json=logs / "heartbeat.json",
3082
- session_status_json=logs / "session-status.json",
3083
- )
3084
- result = type("Result", (), {"exit_code": 0})()
3085
- classification = type("Classification", (), {"session_status": "success"})()
3086
-
3087
- runners._emit_session_summary(result, paths, classification)
3088
-
3089
- captured = capsys.readouterr()
3090
- assert "Subagents: spawned=2, active=1, states: running=1, completed=1 (claude; source=session.log)" in captured.err
3091
- assert "Child log activity: 2KB across 1 files (heartbeat liveness only)" in captured.err
3092
- assert "Subagent calls detected" not in captured.err
3093
-
3094
- def test_ai_interruption_diagnostics_are_detailed_console_only(tmp_path, capsys):
3095
- import signal
3096
-
3097
- from prizmkit_runtime.heartbeat import HeartbeatState
3098
- from prizmkit_runtime.processes import (
3099
- ProcessHandle,
3100
- ProcessSpec,
3101
- ProcessTerminationResult,
3102
- RuntimeInterruption,
3103
- )
3104
- from prizmkit_runtime.sessions import (
3105
- AISessionCommand,
3106
- _emit_ai_interruption_received,
3107
- _emit_ai_interruption_termination,
3108
- )
3109
-
3110
- session_log = tmp_path / "sessions" / "sess-interrupt" / "logs" / "session.log"
3111
- session_log.parent.mkdir(parents=True)
3112
- session_log.write_text("session activity\n", encoding="utf-8")
3113
- progress = session_log.with_name("progress.json")
3114
- progress.write_text(
3115
- json.dumps(
3116
- {
3117
- "current_phase": "implement",
3118
- "current_tool": "bash",
3119
- "current_tool_input_summary": "secret-command-must-not-be-logged",
3120
- "message_count": 455,
3121
- "total_tool_calls": 453,
3122
- "subagent_statistics": {"active": 0, "spawned": 0},
3123
- }
3124
- ),
3125
- encoding="utf-8",
3126
- )
3127
- handle = ProcessHandle(
3128
- pid=999_999,
3129
- spec=ProcessSpec(command=("fake-ai",), cwd=tmp_path),
3130
- status="running",
3131
- popen=None,
3132
- )
3133
- command = AISessionCommand(
3134
- argv=("fake-ai",),
3135
- stdin_text=None,
3136
- provider="pi",
3137
- prompt_mode="stdin",
3138
- )
3139
- heartbeat = HeartbeatState(
3140
- last_seen_epoch=time.time() - 1,
3141
- stale=False,
3142
- details="no progress",
3143
- stale_seconds=1.0,
3144
- log_size=2048,
3145
- )
3146
-
3147
- _emit_ai_interruption_received(
3148
- RuntimeInterruption(signal.SIGTERM),
3149
- command=command,
3150
- handle=handle,
3151
- started_epoch=time.time() - 120,
3152
- session_log=session_log,
3153
- progress_path=progress,
3154
- checkpoint_path=None,
3155
- heartbeat_state=heartbeat,
3156
- )
3157
- _emit_ai_interruption_termination(
3158
- ProcessTerminationResult(
3159
- pid=handle.pid,
3160
- reason="interrupted",
3161
- terminated=True,
3162
- forced=False,
3163
- return_code=-15,
3164
- details=("sigterm_process_group",),
3165
- )
3166
- )
3167
-
3168
- captured = capsys.readouterr()
3169
- assert "received trigger=platform_signal; platform_signal=SIGTERM(15)" in captured.err
3170
- assert "runner_pid=" in captured.err
3171
- assert "parent_pid=" in captured.err
3172
- assert "ai_pid=999999" in captured.err
3173
- assert "provider=pi" in captured.err
3174
- assert "phase=implement; tool=bash; messages=455; tool_calls=453" in captured.err
3175
- assert "heartbeat details=no progress; stale=False; age=1s" in captured.err
3176
- assert "process-tree termination completed" in captured.err
3177
- assert "forced=False; return_code=-15; details=sigterm_process_group" in captured.err
3178
- assert "secret-command-must-not-be-logged" not in captured.err
3179
- assert not session_log.with_name("session-status.json").exists()
3180
-
3181
-
3182
- def test_ai_session_interrupt_diagnostics_are_wired_before_existing_cleanup(monkeypatch, tmp_path, capsys):
3183
- import io
3184
-
3185
- from prizmkit_runtime import sessions
3186
- from prizmkit_runtime.processes import ProcessHandle, ProcessTerminationResult
3187
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
3188
-
3189
- prompt = tmp_path / "prompt.md"
3190
- prompt.write_text("hello", encoding="utf-8")
3191
- session_log = tmp_path / "sessions" / "sess-wired" / "logs" / "session.log"
3192
- termination_calls = []
3193
-
3194
- class InterruptingProcess:
3195
- def __init__(self):
3196
- self.stdout = io.StringIO("")
3197
- self.stdin = io.StringIO()
3198
- self.returncode = -2
3199
-
3200
- def wait(self, timeout=None):
3201
- raise KeyboardInterrupt
3202
-
3203
- def poll(self):
3204
- return self.returncode
3205
-
3206
- process = InterruptingProcess()
3207
-
3208
- def fake_launch(spec, **kwargs):
3209
- return ProcessHandle(pid=777_777, spec=spec, status="running", popen=process)
3210
-
3211
- def fake_terminate(handle, reason, grace_seconds=10):
3212
- termination_calls.append((handle.pid, reason, grace_seconds))
3213
- return ProcessTerminationResult(
3214
- pid=handle.pid,
3215
- reason=reason,
3216
- terminated=True,
3217
- forced=False,
3218
- return_code=process.returncode,
3219
- details=("sigterm_process_group",),
3220
- )
3221
-
3222
- monkeypatch.setattr(sessions, "launch_process", fake_launch)
3223
- monkeypatch.setattr(sessions, "terminate_process_tree", fake_terminate)
3224
-
3225
- with pytest.raises(KeyboardInterrupt):
3226
- AISessionLauncher(
3227
- AISessionConfig(
3228
- cli_command="fake-ai",
3229
- platform="pi",
3230
- model=None,
3231
- prompt_path=prompt,
3232
- cwd=tmp_path,
3233
- log_path=session_log,
3234
- stale_kill_grace_seconds=4,
3235
- )
3236
- ).run()
3237
-
3238
- captured = capsys.readouterr()
3239
- assert termination_calls == [(777_777, "interrupted", 4)]
3240
- assert "received trigger=keyboard_interrupt; platform_signal=SIGINT(2) (inferred)" in captured.err
3241
- assert "ai_pid=777777" in captured.err
3242
- assert "classification and retry accounting have not run for this AI session" in captured.err
3243
- assert "process-tree termination completed pid=777777" in captured.err
3244
- assert not session_log.with_name("session-status.json").exists()
3245
-
3246
-
3247
- def test_session_live_output_does_not_forward_cli_output_without_verbose(tmp_path, capsys):
3248
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
3249
-
3250
- fake_cli = tmp_path / "quiet_cli.py"
3251
- fake_cli.write_text(
3252
- "#!/usr/bin/env python3\n"
3253
- "print('hidden-line', flush=True)\n",
3254
- encoding="utf-8",
3255
- )
3256
- fake_cli.chmod(0o755)
3257
- prompt = tmp_path / "prompt.md"
3258
- prompt.write_text("hello", encoding="utf-8")
3259
- session_log = tmp_path / "state" / "sessions" / "sess-quiet" / "logs" / "session.log"
3260
-
3261
- result = AISessionLauncher(
3262
- AISessionConfig(
3263
- cli_command=str(fake_cli),
3264
- platform="codebuddy",
3265
- model=None,
3266
- prompt_path=prompt,
3267
- cwd=tmp_path,
3268
- log_path=session_log,
3269
- live_output=True,
3270
- )
3271
- ).run()
3272
-
3273
- captured = capsys.readouterr()
3274
- assert result.exit_code == 0
3275
- assert "hidden-line" not in captured.out
3276
- assert "hidden-line" in session_log.read_text(encoding="utf-8")
3277
- assert "[prizmkit] AI session started" in captured.err
3278
- assert "[prizmkit] AI session finished" in captured.err
3279
-
3280
-
3281
- def test_session_final_progress_merge_preserves_tracker_fatal_error(tmp_path):
3282
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
3283
-
3284
- fake_cli = tmp_path / "context_cli.py"
3285
- fake_cli.write_text(
3286
- "#!/usr/bin/env python3\n"
3287
- "import json\n"
3288
- "print(json.dumps({'type':'result','is_error':True,'result':'API Error: Your input exceeds the context window'}), flush=True)\n",
3289
- encoding="utf-8",
3290
- )
3291
- fake_cli.chmod(0o755)
3292
- prompt = tmp_path / "prompt.md"
3293
- prompt.write_text("hello", encoding="utf-8")
3294
- session_log = tmp_path / "state" / "sessions" / "sess-context" / "logs" / "session.log"
3295
- progress = session_log.with_name("progress.json")
3296
-
3297
- result = AISessionLauncher(
3298
- AISessionConfig(
3299
- cli_command=str(fake_cli),
3300
- platform="codebuddy",
3301
- model=None,
3302
- prompt_path=prompt,
3303
- cwd=tmp_path,
3304
- log_path=session_log,
3305
- progress_path=progress,
3306
- )
3307
- ).run()
3308
-
3309
- progress_data = json.loads(progress.read_text(encoding="utf-8"))
3310
- assert result.progress_summary.fatal_error_code == "context_overflow"
3311
- assert result.fatal_error_code == "context_overflow"
3312
- assert progress_data["fatal_error_code"] == "context_overflow"
3313
-
3314
-
3315
- def test_session_unsets_claudecode_and_merges_stderr_order(tmp_path, monkeypatch):
3316
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
3317
-
3318
- fake_cli = tmp_path / "env_cli.py"
3319
- fake_cli.write_text(
3320
- "#!/usr/bin/env python3\n"
3321
- "import os, sys\n"
3322
- "print('stdout-before', flush=True)\n"
3323
- "print('claudecode=' + os.environ.get('CLAUDECODE', '<unset>'), flush=True)\n"
3324
- "print('stderr-after', file=sys.stderr, flush=True)\n",
3325
- encoding="utf-8",
3326
- )
3327
- fake_cli.chmod(0o755)
3328
- monkeypatch.setenv("CLAUDECODE", "1")
3329
- prompt = tmp_path / "prompt.md"
3330
- prompt.write_text("hello", encoding="utf-8")
3331
- session_log = tmp_path / "state" / "sessions" / "sess-env" / "logs" / "session.log"
3332
-
3333
- result = AISessionLauncher(
3334
- AISessionConfig(
3335
- cli_command=str(fake_cli),
3336
- platform="codebuddy",
3337
- model=None,
3338
- prompt_path=prompt,
3339
- cwd=tmp_path,
3340
- log_path=session_log,
3341
- )
3342
- ).run()
3343
-
3344
- text = session_log.read_text(encoding="utf-8")
3345
- assert result.exit_code == 0
3346
- assert "claudecode=<unset>" in text
3347
- assert text.index("stdout-before") < text.index("stderr-after")
3348
-
3349
-
3350
- def test_heartbeat_fatal_error_writes_shell_compatible_markers(tmp_path):
3351
- from prizmkit_runtime.heartbeat import HeartbeatConfig, HeartbeatMonitor
3352
- from prizmkit_runtime.processes import ProcessSpec, launch_process
3353
-
3354
- sleeper = tmp_path / "fatal_sleep.py"
3355
- sleeper.write_text("import time\ntime.sleep(5)\n", encoding="utf-8")
3356
- progress = tmp_path / "progress.json"
3357
- progress.write_text(
3358
- '{"current_tool":"bash","fatal_error_code":"context_overflow"}\n',
3359
- encoding="utf-8",
3360
- )
3361
- handle = launch_process(ProcessSpec(command=(sys.executable, str(sleeper)), cwd=tmp_path))
3362
- monitor = HeartbeatMonitor(
3363
- handle,
3364
- HeartbeatConfig(
3365
- heartbeat_file=tmp_path / "heartbeat.json",
3366
- session_log=tmp_path / "session.log",
3367
- progress_file=progress,
3368
- marker_dir=tmp_path,
3369
- interval_seconds=0.05,
3370
- stale_after_seconds=10,
3371
- kill_after_seconds=10,
3372
- grace_seconds=0.1,
3373
- ),
3374
- )
3375
- monitor.start()
3376
- deadline = time.time() + 3
3377
- while time.time() < deadline and not (tmp_path / "fatal-error.json").exists():
3378
- time.sleep(0.05)
3379
- result = monitor.stop()
3380
-
3381
- fatal = json.loads((tmp_path / "fatal-error.json").read_text(encoding="utf-8"))
3382
- stale = json.loads((tmp_path / "stale-kill.json").read_text(encoding="utf-8"))
3383
- assert result.killed is True
3384
- assert result.reason == "context_overflow"
3385
- assert fatal["killed_at"].endswith("Z")
3386
- assert fatal["fatal_error_code"] == "context_overflow"
3387
- assert stale["reason"] == "context_overflow"
3388
-
3389
-
3390
-
3391
- from prizmkit_runtime.heartbeat import HeartbeatConfig, write_stale_marker
3392
- from prizmkit_runtime.processes import ProcessSpec, platform_termination_strategy, run_process_with_capture
3393
-
3394
- sleeper = tmp_path / "sleep.py"
3395
- sleeper.write_text("import time\ntime.sleep(5)\n", encoding="utf-8")
3396
- result = run_process_with_capture(
3397
- ProcessSpec(command=(sys.executable, str(sleeper)), cwd=tmp_path),
3398
- timeout_seconds=0.2,
3399
- grace_seconds=0.1,
3400
- )
3401
-
3402
- assert result.timed_out is True
3403
- assert result.termination is not None
3404
- assert result.termination.reason == "timeout"
3405
- assert platform_termination_strategy()
3406
-
3407
- marker = write_stale_marker(tmp_path, reason="stale_session", stale_seconds=3, threshold=2)
3408
- marker_data = json.loads(marker.read_text(encoding="utf-8"))
3409
- assert marker_data["reason"] == "stale_session"
3410
- assert marker_data["threshold"] == 2
3411
- assert HeartbeatConfig(heartbeat_file=tmp_path / "heartbeat").interval_seconds == 30
3412
-
3413
-
3414
- def test_git_branch_worktree_plans_preserve_shell_invariants(tmp_path):
3415
- from prizmkit_runtime.gitops import (
3416
- BranchContext,
3417
- GitCommandResult,
3418
- GitPlanResult,
3419
- WorktreePolicy,
3420
- branch_create_plan,
3421
- branch_ensure_return_plan,
3422
- branch_merge_plan,
3423
- branch_save_wip,
3424
- branch_save_wip_plan,
3425
- worktree_add_plan,
1748
+ def test_git_branch_plans_preserve_shell_invariants(tmp_path):
1749
+ from prizmkit_runtime.gitops import (
1750
+ BranchContext,
1751
+ GitCommandResult,
1752
+ GitPlanResult,
1753
+ branch_create_plan,
1754
+ branch_ensure_return_plan,
1755
+ branch_merge_plan,
1756
+ branch_save_wip,
1757
+ branch_save_wip_plan,
3426
1758
  )
3427
1759
 
3428
1760
  context = BranchContext(base_branch="main", working_branch="dev/example", project_root=tmp_path)
@@ -3430,7 +1762,6 @@ def test_git_branch_worktree_plans_preserve_shell_invariants(tmp_path):
3430
1762
  merge = branch_merge_plan(context, auto_push=True)
3431
1763
  save_wip = branch_save_wip_plan(context)
3432
1764
  ensure = branch_ensure_return_plan(context)
3433
- worktree = worktree_add_plan(context, WorktreePolicy(True, cleanup_on_success=False, preserve_on_failure=True))
3434
1765
 
3435
1766
  assert create.name == "branch_create"
3436
1767
  assert any(command.args[:2] == ("checkout", "-b") for command in create.commands)
@@ -3455,7 +1786,6 @@ def test_git_branch_worktree_plans_preserve_shell_invariants(tmp_path):
3455
1786
  if command.args[:2] == ("add", "-A")
3456
1787
  for arg in command.args
3457
1788
  )
3458
- assert worktree.commands[0].args[:2] == ("worktree", "add")
3459
1789
 
3460
1790
  allowed_failure_result = GitPlanResult(
3461
1791
  plan=create,
@@ -3482,9 +1812,11 @@ def test_git_branch_worktree_plans_preserve_shell_invariants(tmp_path):
3482
1812
 
3483
1813
 
3484
1814
  def test_runtime_source_constructs_no_git_stash_commands():
3485
- runtime = Path("dev-pipeline/prizmkit_runtime")
1815
+ runtime = PIPELINE_ROOT / "prizmkit_runtime"
1816
+ source_files = sorted(runtime.glob("*.py"))
1817
+ assert source_files
3486
1818
  matches = []
3487
- for path in runtime.glob("*.py"):
1819
+ for path in source_files:
3488
1820
  text = path.read_text(encoding="utf-8")
3489
1821
  if re.search(r'["\']stash["\']', text):
3490
1822
  matches.append(path.as_posix())
@@ -4355,122 +2687,6 @@ def test_non_current_reset_preserves_dirty_workspace_and_user_stashes(tmp_path):
4355
2687
  assert _stash_oids(tmp_path) == user_stashes
4356
2688
 
4357
2689
 
4358
- def test_worktree_runtime_context_uses_safe_deterministic_path(tmp_path):
4359
- from prizmkit_runtime.gitops import BranchContext, WorktreePolicy, worktree_runtime_context
4360
-
4361
- context = BranchContext(base_branch="main", working_branch="dev/F-001-example", project_root=tmp_path / "repo")
4362
- policy = WorktreePolicy(
4363
- use_worktree=True,
4364
- cleanup_on_success=True,
4365
- preserve_on_failure=False,
4366
- worktree_root=tmp_path / "state" / "worktrees",
4367
- )
4368
-
4369
- runtime = worktree_runtime_context(context, policy)
4370
-
4371
- assert runtime.worktree_root == (tmp_path / "state" / "worktrees").resolve()
4372
- assert runtime.worktree_path == runtime.worktree_root / "dev-F-001-example"
4373
- assert runtime.sentinel_path == runtime.worktree_path / ".prizmkit-worktree"
4374
- assert runtime.is_cleanup_path_safe() is True
4375
-
4376
- unsafe = runtime.__class__(
4377
- context=context,
4378
- policy=policy,
4379
- worktree_root=runtime.worktree_root,
4380
- worktree_path=tmp_path / "other" / "dev-F-001-example",
4381
- sentinel_path=tmp_path / "other" / "dev-F-001-example" / ".prizmkit-worktree",
4382
- )
4383
- assert unsafe.is_cleanup_path_safe() is False
4384
-
4385
-
4386
- def test_linked_worktree_plans_create_branch_without_checkout_and_cleanup_after_merge(tmp_path):
4387
- from prizmkit_runtime.gitops import (
4388
- BranchContext,
4389
- WorktreePolicy,
4390
- linked_worktree_setup_plan,
4391
- worktree_merge_plan,
4392
- worktree_remove_plan,
4393
- worktree_runtime_context,
4394
- )
4395
-
4396
- context = BranchContext(base_branch="main", working_branch="dev/F-001-example", project_root=tmp_path / "repo")
4397
- policy = WorktreePolicy(True, cleanup_on_success=True, preserve_on_failure=False, worktree_root=tmp_path / "worktrees")
4398
- runtime = worktree_runtime_context(context, policy)
4399
-
4400
- setup = linked_worktree_setup_plan(runtime)
4401
- merge = worktree_merge_plan(runtime, auto_push=True)
4402
- remove = worktree_remove_plan(runtime, delete_branch=True)
4403
-
4404
- assert setup.name == "linked_worktree_setup"
4405
- assert setup.commands[0].args[:2] == ("rev-parse", "--verify")
4406
- assert setup.commands[1].args[:4] == ("branch", context.working_branch, context.base_branch,)
4407
- assert setup.commands[2].args[:2] == ("worktree", "list")
4408
- assert setup.commands[3].args[:3] == ("worktree", "add", "--checkout")
4409
- assert all(command.args[0] != "checkout" for command in setup.commands)
4410
- assert setup.require_one_success == ((0, 1),)
4411
-
4412
- assert merge.commands[0].args[:2] == ("rebase", context.base_branch)
4413
- assert merge.commands[1].args == ("merge", "--ff-only", context.working_branch)
4414
- assert merge.commands[2].args == ("push",)
4415
- assert remove.commands[0].args[:2] == ("worktree", "remove")
4416
- assert remove.commands[1].args == ("branch", "-d", context.working_branch)
4417
-
4418
-
4419
- def test_guarded_worktree_removal_refuses_unregistered_or_unsafe_paths(monkeypatch, tmp_path):
4420
- from prizmkit_runtime.gitops import (
4421
- BranchContext,
4422
- GitCommandResult,
4423
- WorktreePolicy,
4424
- guarded_worktree_remove,
4425
- worktree_runtime_context,
4426
- )
4427
-
4428
- context = BranchContext(base_branch="main", working_branch="dev/F-001-example", project_root=tmp_path / "repo")
4429
- runtime = worktree_runtime_context(
4430
- context,
4431
- WorktreePolicy(True, cleanup_on_success=True, preserve_on_failure=False, worktree_root=tmp_path / "worktrees"),
4432
- )
4433
- runtime.worktree_path.mkdir(parents=True)
4434
-
4435
- calls = []
4436
-
4437
- def fake_run(project_root, args):
4438
- calls.append(tuple(args))
4439
- if tuple(args)[:2] == ("worktree", "list"):
4440
- return GitCommandResult(tuple(args), 0, "", "")
4441
- return GitCommandResult(tuple(args), 0, "", "")
4442
-
4443
- monkeypatch.setattr("prizmkit_runtime.gitops.run_git_command", fake_run)
4444
- result = guarded_worktree_remove(runtime, delete_branch=True)
4445
-
4446
- assert result.ok is False
4447
- assert result.reason == "missing_worktree_sentinel"
4448
- assert all(call[:2] != ("worktree", "remove") for call in calls)
4449
-
4450
- (runtime.sentinel_path).write_text(context.working_branch, encoding="utf-8")
4451
- calls.clear()
4452
- result = guarded_worktree_remove(runtime, delete_branch=True)
4453
-
4454
- assert result.ok is False
4455
- assert result.reason == "worktree_not_registered"
4456
- assert all(call[:2] != ("worktree", "remove") for call in calls)
4457
- calls.clear()
4458
-
4459
- def registered_run(project_root, args):
4460
- calls.append(tuple(args))
4461
- if tuple(args)[:2] == ("worktree", "list"):
4462
- return GitCommandResult(tuple(args), 0, str(runtime.worktree_path) + " abc [dev/F-001-example]\n", "")
4463
- return GitCommandResult(tuple(args), 0, "", "")
4464
-
4465
- monkeypatch.setattr("prizmkit_runtime.gitops.run_git_command", registered_run)
4466
- result = guarded_worktree_remove(runtime, delete_branch=True)
4467
-
4468
- assert result.ok is True
4469
- assert ("worktree", "remove", "--force", str(runtime.worktree_path)) in calls
4470
- assert ("branch", "-d", context.working_branch) in calls
4471
-
4472
-
4473
-
4474
2690
  def test_git_status_safe_ignores_worktree_support_assets(monkeypatch, tmp_path):
4475
2691
  from prizmkit_runtime.gitops import HIDDEN_TOOL_WORKTREE_EXCLUDES, git_status_safe
4476
2692
 
@@ -4591,7 +2807,7 @@ def test_preflight_ready_commit_skips_clean_workspace(tmp_path):
4591
2807
  _init_temp_repo(repo)
4592
2808
  before = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
4593
2809
 
4594
- result = commit_preflight_ready_changes(repo, "R-003")
2810
+ result = commit_preflight_ready_changes(repo, "F-003")
4595
2811
 
4596
2812
  after = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
4597
2813
  assert not result.attempted
@@ -4698,147 +2914,52 @@ def test_preflight_ready_commit_force_stages_visible_file_when_prizmkit_dir_is_i
4698
2914
  assert _short_status(repo) == ""
4699
2915
 
4700
2916
 
4701
- def test_materialize_worktree_support_assets_copies_ignored_assets_without_retired_shell_sources(tmp_path):
4702
- from prizmkit_runtime.gitops import (
4703
- BranchContext,
4704
- WorktreePolicy,
4705
- ensure_linked_worktree,
4706
- guarded_worktree_remove,
4707
- materialize_worktree_support_assets,
4708
- worktree_runtime_context,
4709
- )
4710
-
4711
- repo = tmp_path / "repo"
4712
- _init_temp_repo(repo)
4713
- (repo / ".gitignore").write_text(".claude/\n.prizmkit/\n", encoding="utf-8")
4714
- subprocess.run(["git", "add", ".gitignore"], cwd=repo, check=True)
4715
- subprocess.run(["git", "commit", "-m", "ignore support"], cwd=repo, check=True, stdout=subprocess.DEVNULL)
4716
-
4717
- (repo / ".claude" / "commands").mkdir(parents=True)
4718
- (repo / ".claude" / "commands" / "prizmkit.md").write_text("skill", encoding="utf-8")
4719
- (repo / ".prizmkit" / "prizm-docs").mkdir(parents=True)
4720
- (repo / ".prizmkit" / "prizm-docs" / "root.prizm").write_text("PRIZM_VERSION: 1\n", encoding="utf-8")
4721
- (repo / ".prizmkit" / "config.json").write_text("{}", encoding="utf-8")
4722
- (repo / ".prizmkit" / "manifest.json").write_text("{}", encoding="utf-8")
4723
- (repo / ".prizmkit" / "dev-pipeline" / "scripts").mkdir(parents=True)
4724
- (repo / ".prizmkit" / "dev-pipeline" / "scripts" / "update-checkpoint.py").write_text("# update", encoding="utf-8")
4725
- (repo / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime").mkdir(parents=True)
4726
- (repo / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime" / "__init__.py").write_text("", encoding="utf-8")
4727
- (repo / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime" / "runtime_helper.py").write_text("# helper", encoding="utf-8")
4728
- (repo / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime" / "task_checkout.py").write_text("# checkout", encoding="utf-8")
4729
- (repo / ".prizmkit" / "dev-pipeline" / "run-feature.sh").write_text("retired", encoding="utf-8")
4730
-
4731
- runtime = worktree_runtime_context(
4732
- BranchContext("main", "dev/support-assets", repo),
4733
- WorktreePolicy(True, cleanup_on_success=True, preserve_on_failure=True, worktree_root=tmp_path / "worktrees"),
4734
- )
4735
- setup = ensure_linked_worktree(runtime)
4736
- assert setup.ok
4737
- assert not (runtime.worktree_path / ".claude" / "commands" / "prizmkit.md").exists()
4738
-
4739
- result = materialize_worktree_support_assets(runtime)
4740
-
4741
- assert result.ok
4742
- assert (runtime.worktree_path / ".claude" / "commands" / "prizmkit.md").is_file()
4743
- assert (runtime.worktree_path / ".prizmkit" / "prizm-docs" / "root.prizm").is_file()
4744
- assert (runtime.worktree_path / ".prizmkit" / "config.json").is_file()
4745
- assert (runtime.worktree_path / ".prizmkit" / "manifest.json").is_file()
4746
- assert (runtime.worktree_path / ".prizmkit" / "dev-pipeline" / "scripts" / "update-checkpoint.py").is_file()
4747
- assert (runtime.worktree_path / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime" / "__init__.py").is_file()
4748
- assert (runtime.worktree_path / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime" / "runtime_helper.py").is_file()
4749
- assert (runtime.worktree_path / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime" / "task_checkout.py").is_file()
4750
- assert not (runtime.worktree_path / ".prizmkit" / "dev-pipeline" / "run-feature.sh").exists()
4751
-
4752
- assert guarded_worktree_remove(runtime, delete_branch=False).ok
4753
-
4754
-
4755
- def test_linked_worktree_rejects_dirty_tracked_prizmkit_config(tmp_path):
4756
- from prizmkit_runtime.gitops import (
4757
- BranchContext,
4758
- WorktreePolicy,
4759
- branch_fast_forward_possible,
4760
- ensure_linked_worktree,
4761
- guarded_worktree_remove,
4762
- merge_linked_worktree,
4763
- worktree_runtime_context,
2917
+ def test_load_task_checkout_rejects_retired_worktree_mode(tmp_path):
2918
+ from prizmkit_runtime.task_checkout import (
2919
+ CHECKOUT_MODE_BRANCH,
2920
+ TaskCheckout,
2921
+ TaskCheckoutError,
2922
+ load_task_checkout,
2923
+ task_checkout_path,
4764
2924
  )
4765
2925
 
4766
- repo = tmp_path / "repo"
4767
- _init_temp_repo(repo)
4768
- config = repo / ".prizmkit" / "config.json"
4769
- config.parent.mkdir(parents=True)
4770
- config.write_text('{"mode":"base"}\n', encoding="utf-8")
4771
- subprocess.run(["git", "add", ".prizmkit/config.json"], cwd=repo, check=True)
4772
- subprocess.run(
4773
- ["git", "commit", "-m", "track internal config"],
4774
- cwd=repo,
4775
- check=True,
4776
- stdout=subprocess.DEVNULL,
4777
- )
4778
- runtime = worktree_runtime_context(
4779
- BranchContext("main", "dev/internal-dirt", repo),
4780
- WorktreePolicy(
4781
- True,
4782
- cleanup_on_success=True,
4783
- preserve_on_failure=True,
4784
- worktree_root=tmp_path / "worktrees",
2926
+ state_dir = tmp_path / "state"
2927
+ checkout_file = task_checkout_path(state_dir, "F-001")
2928
+ checkout_file.parent.mkdir(parents=True)
2929
+ checkout_file.write_text(
2930
+ json.dumps(
2931
+ {
2932
+ "task_type": "feature",
2933
+ "task_id": "F-001",
2934
+ "state": "active",
2935
+ "active_dev_branch": "dev/F-001-legacy",
2936
+ "base_branch": "main",
2937
+ "checkout_mode": "worktree",
2938
+ "worktree_path": str(tmp_path / "wt" / "F-001"),
2939
+ }
4785
2940
  ),
2941
+ encoding="utf-8",
4786
2942
  )
4787
- assert ensure_linked_worktree(runtime).ok
4788
- (runtime.worktree_path / "feature.txt").write_text("done\n", encoding="utf-8")
4789
- subprocess.run(["git", "add", "feature.txt"], cwd=runtime.worktree_path, check=True)
4790
- subprocess.run(
4791
- ["git", "commit", "-m", "feature"],
4792
- cwd=runtime.worktree_path,
4793
- check=True,
4794
- stdout=subprocess.DEVNULL,
4795
- )
4796
- worktree_config = runtime.worktree_path / ".prizmkit" / "config.json"
4797
- worktree_config.write_text('{"mode":"session-local"}\n', encoding="utf-8")
4798
-
4799
- assert branch_fast_forward_possible(repo, runtime.context) is True
4800
- result = merge_linked_worktree(runtime)
4801
-
4802
- assert result.ok is False
4803
- assert result.reason == "dirty_task_checkout"
4804
- assert not (repo / "feature.txt").exists()
4805
- assert json.loads(worktree_config.read_text(encoding="utf-8"))["mode"] == "session-local"
4806
- worktree_config.write_text('{"mode":"base"}\n', encoding="utf-8")
4807
- assert guarded_worktree_remove(runtime, delete_branch=True).ok
4808
-
2943
+ with pytest.raises(TaskCheckoutError, match="retired worktree checkout mode"):
2944
+ load_task_checkout(state_dir, "feature", "F-001")
4809
2945
 
4810
- def test_worktree_terminal_failure_wip_commit_preserves_dirty_changes_before_cleanup(tmp_path):
4811
- from prizmkit_runtime.gitops import (
4812
- BranchContext,
4813
- WorktreePolicy,
4814
- ensure_linked_worktree,
4815
- guarded_worktree_remove,
4816
- worktree_runtime_context,
4817
- worktree_save_wip,
4818
- )
2946
+ with pytest.raises(TaskCheckoutError, match="Unsupported task checkout mode"):
2947
+ TaskCheckout.active(
2948
+ "feature",
2949
+ "F-001",
2950
+ "dev/F-001-legacy",
2951
+ "main",
2952
+ checkout_mode="worktree",
2953
+ )
4819
2954
 
4820
- repo = tmp_path / "repo"
4821
- _init_temp_repo(repo)
4822
- runtime = worktree_runtime_context(
4823
- BranchContext("main", "dev/crashed-work", repo),
4824
- WorktreePolicy(True, cleanup_on_success=True, preserve_on_failure=True, worktree_root=tmp_path / "worktrees"),
2955
+ valid = TaskCheckout.active(
2956
+ "feature",
2957
+ "F-001",
2958
+ "dev/F-001-branch",
2959
+ "main",
2960
+ checkout_mode=CHECKOUT_MODE_BRANCH,
4825
2961
  )
4826
- setup = ensure_linked_worktree(runtime)
4827
- assert setup.ok
4828
-
4829
- (runtime.worktree_path / "dirty.txt").write_text("dirty work\n", encoding="utf-8")
4830
- save = worktree_save_wip(runtime)
4831
- assert save.ok
4832
- assert any(result.args and result.args[0] == "commit" and result.return_code == 0 for result in save.results)
4833
-
4834
- removal = guarded_worktree_remove(runtime, delete_branch=False)
4835
- assert removal.ok
4836
- assert not runtime.worktree_path.exists()
4837
-
4838
- branches = subprocess.run(["git", "branch", "--list", "dev/crashed-work"], cwd=repo, check=True, stdout=subprocess.PIPE, text=True).stdout
4839
- assert "dev/crashed-work" in branches
4840
- show = subprocess.run(["git", "show", "dev/crashed-work:dirty.txt"], cwd=repo, check=True, stdout=subprocess.PIPE, text=True).stdout
4841
- assert show == "dirty work\n"
2962
+ assert valid.checkout_mode == CHECKOUT_MODE_BRANCH
4842
2963
 
4843
2964
 
4844
2965
  def test_daemon_status_cli_preserves_pure_json_stdout(tmp_path):