prizmkit 1.1.190 → 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 (189) hide show
  1. package/bin/create-prizmkit.js +4 -4
  2. package/bundled/VERSION.json +3 -3
  3. package/bundled/adapters/antigravity/assets/prizmkit-hook.cjs +150 -0
  4. package/bundled/adapters/antigravity/hooks-adapter.js +195 -0
  5. package/bundled/adapters/antigravity/paths.js +14 -0
  6. package/bundled/adapters/antigravity/rules-adapter.js +54 -0
  7. package/bundled/adapters/antigravity/skill-adapter.js +38 -0
  8. package/bundled/adapters/codex/skill-adapter.js +28 -8
  9. package/bundled/adapters/cursor/skill-adapter.js +13 -4
  10. package/bundled/adapters/pi/skill-adapter.js +28 -7
  11. package/bundled/dev-pipeline/.env.example +4 -12
  12. package/bundled/dev-pipeline/README.md +21 -15
  13. package/bundled/dev-pipeline/assets/skill-subagent-integration.md +3 -6
  14. package/bundled/dev-pipeline/prizmkit_runtime/atomic_io.py +48 -0
  15. package/bundled/dev-pipeline/prizmkit_runtime/checkpoint_state.py +66 -23
  16. package/bundled/dev-pipeline/prizmkit_runtime/cli.py +10 -7
  17. package/bundled/dev-pipeline/prizmkit_runtime/commands.py +2 -21
  18. package/bundled/dev-pipeline/prizmkit_runtime/config.py +29 -70
  19. package/bundled/dev-pipeline/prizmkit_runtime/daemon.py +125 -67
  20. package/bundled/dev-pipeline/prizmkit_runtime/gitops.py +89 -442
  21. package/bundled/dev-pipeline/prizmkit_runtime/heartbeat.py +93 -49
  22. package/bundled/dev-pipeline/prizmkit_runtime/interoperability.py +1 -3
  23. package/bundled/dev-pipeline/prizmkit_runtime/paths.py +0 -6
  24. package/bundled/dev-pipeline/prizmkit_runtime/platform_detection.py +49 -18
  25. package/bundled/dev-pipeline/prizmkit_runtime/processes.py +206 -151
  26. package/bundled/dev-pipeline/prizmkit_runtime/reset.py +2 -23
  27. package/bundled/dev-pipeline/prizmkit_runtime/reset_preserve.py +15 -134
  28. package/bundled/dev-pipeline/prizmkit_runtime/results.py +25 -0
  29. package/bundled/dev-pipeline/prizmkit_runtime/runner_bookkeeping.py +68 -83
  30. package/bundled/dev-pipeline/prizmkit_runtime/runner_classification.py +15 -5
  31. package/bundled/dev-pipeline/prizmkit_runtime/runner_models.py +1 -29
  32. package/bundled/dev-pipeline/prizmkit_runtime/runner_prompts.py +0 -2
  33. package/bundled/dev-pipeline/prizmkit_runtime/runner_status.py +7 -2
  34. package/bundled/dev-pipeline/prizmkit_runtime/runners.py +282 -217
  35. package/bundled/dev-pipeline/prizmkit_runtime/runtime_commit.py +124 -122
  36. package/bundled/dev-pipeline/prizmkit_runtime/runtime_helper.py +90 -9
  37. package/bundled/dev-pipeline/prizmkit_runtime/sessions.py +369 -154
  38. package/bundled/dev-pipeline/prizmkit_runtime/status.py +3 -3
  39. package/bundled/dev-pipeline/prizmkit_runtime/stream_progress.py +2780 -0
  40. package/bundled/dev-pipeline/prizmkit_runtime/task_checkout.py +27 -101
  41. package/bundled/dev-pipeline/prizmkit_runtime/test_result.py +58 -4
  42. package/bundled/dev-pipeline/scripts/check-session-status.py +43 -19
  43. package/bundled/dev-pipeline/scripts/continuation.py +6 -4
  44. package/bundled/dev-pipeline/scripts/detect-stuck.py +28 -28
  45. package/bundled/dev-pipeline/scripts/generate-bootstrap-prompt.py +7 -2
  46. package/bundled/dev-pipeline/scripts/generate-bugfix-prompt.py +7 -2
  47. package/bundled/dev-pipeline/scripts/init-bugfix-pipeline.py +10 -7
  48. package/bundled/dev-pipeline/scripts/init-change-artifact.py +8 -2
  49. package/bundled/dev-pipeline/scripts/init-pipeline.py +14 -69
  50. package/bundled/dev-pipeline/scripts/parse-stream-progress.py +31 -2328
  51. package/bundled/dev-pipeline/scripts/patch-completion-notes.py +4 -24
  52. package/bundled/dev-pipeline/scripts/prompt_framework.py +56 -9
  53. package/bundled/dev-pipeline/scripts/status_common.py +591 -0
  54. package/bundled/dev-pipeline/scripts/update-bug-status.py +85 -463
  55. package/bundled/dev-pipeline/scripts/update-checkpoint.py +227 -65
  56. package/bundled/dev-pipeline/scripts/update-feature-status.py +76 -509
  57. package/bundled/dev-pipeline/scripts/utils.py +10 -15
  58. package/bundled/dev-pipeline/templates/bootstrap-tier3.md +4 -4
  59. package/bundled/dev-pipeline/templates/bug-fix-list-schema.json +7 -0
  60. package/bundled/dev-pipeline/templates/bugfix-bootstrap-prompt.md +1 -1
  61. package/bundled/dev-pipeline/templates/sections/artifact-manifest.md +1 -1
  62. package/bundled/dev-pipeline/templates/sections/bugfix-phase-manual-verification.md +1 -1
  63. package/bundled/dev-pipeline/templates/sections/bugfix-phase-review.md +1 -1
  64. package/bundled/dev-pipeline/templates/sections/bugfix-phase-test.md +2 -1
  65. package/bundled/dev-pipeline/templates/sections/checkpoint-system.md +1 -1
  66. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-auto.md +1 -1
  67. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-opencli.md +2 -2
  68. package/bundled/dev-pipeline/templates/sections/phase-browser-verification.md +2 -2
  69. package/bundled/dev-pipeline/templates/sections/phase-prizmkit-test.md +2 -1
  70. package/bundled/dev-pipeline/templates/sections/phase-review-full.md +1 -1
  71. package/bundled/dev-pipeline/templates/sections/phase-specify-plan-full.md +3 -6
  72. package/bundled/dev-pipeline/templates/session-status-schema.json +2 -5
  73. package/bundled/dev-pipeline/tests/_helpers.py +418 -0
  74. package/bundled/dev-pipeline/tests/conftest.py +45 -1
  75. package/bundled/dev-pipeline/tests/live_ai_cli_log_smoke.py +1 -0
  76. package/bundled/dev-pipeline/tests/test_auto_skip.py +4 -69
  77. package/bundled/dev-pipeline/tests/test_checkpoint_state.py +126 -1
  78. package/bundled/dev-pipeline/tests/test_daemon_and_scripts.py +257 -0
  79. package/bundled/dev-pipeline/tests/test_e2e_pipeline_run.py +500 -0
  80. package/bundled/dev-pipeline/tests/test_generate_bootstrap_prompt.py +59 -117
  81. package/bundled/dev-pipeline/tests/test_generate_bugfix_prompt.py +12 -10
  82. package/bundled/dev-pipeline/tests/test_python_runner_parity.py +561 -3094
  83. package/bundled/dev-pipeline/tests/test_recovery_workflow.py +7 -8
  84. package/bundled/dev-pipeline/tests/test_repository_bootstrap.py +0 -1
  85. package/bundled/dev-pipeline/tests/test_reset_modes.py +15 -27
  86. package/bundled/dev-pipeline/tests/test_reset_preserve.py +54 -139
  87. package/bundled/dev-pipeline/tests/test_runner_bookkeeping.py +766 -0
  88. package/bundled/dev-pipeline/tests/test_runner_lifecycle.py +1257 -0
  89. package/bundled/dev-pipeline/tests/test_runtime_helper.py +97 -20
  90. package/bundled/dev-pipeline/tests/test_session_launch.py +1101 -0
  91. package/bundled/dev-pipeline/tests/test_stream_progress.py +585 -0
  92. package/bundled/dev-pipeline/tests/test_unified_cli.py +490 -2006
  93. package/bundled/dev-pipeline/tests/test_utils.py +3 -3
  94. package/bundled/rules/USAGE.md +1 -0
  95. package/bundled/skills/_metadata.json +9 -63
  96. package/bundled/skills/app-planner/SKILL.md +32 -303
  97. package/bundled/skills/app-planner/references/app-design-guide.md +0 -4
  98. package/bundled/skills/app-planner/references/generated-plan-review.md +2 -1
  99. package/bundled/skills/app-planner/references/project-brief-guide.md +14 -0
  100. package/bundled/skills/app-planner/references/project-conventions-discovery.md +4 -6
  101. package/bundled/skills/app-planner/references/project-state-detection.md +2 -3
  102. package/bundled/skills/bug-fix-workflow/SKILL.md +1 -2
  103. package/bundled/skills/bug-fix-workflow/references/bug-diagnosis.md +4 -7
  104. package/bundled/skills/bug-planner/SKILL.md +54 -435
  105. package/bundled/skills/bug-planner/references/generated-plan-review.md +3 -2
  106. package/bundled/skills/bug-planner/references/input-formats.md +32 -0
  107. package/bundled/skills/bugfix-pipeline-launcher/SKILL.md +4 -6
  108. package/bundled/skills/bugfix-pipeline-launcher/references/configuration.md +4 -28
  109. package/bundled/skills/feature-pipeline-launcher/SKILL.md +4 -6
  110. package/bundled/skills/feature-pipeline-launcher/references/configuration.md +4 -28
  111. package/bundled/skills/feature-planner/SKILL.md +60 -439
  112. package/bundled/skills/feature-planner/assets/planning-guide.md +1 -1
  113. package/bundled/skills/feature-planner/references/completeness-review.md +34 -0
  114. package/bundled/skills/feature-planner/references/decomposition-patterns.md +2 -2
  115. package/bundled/skills/feature-planner/references/error-recovery.md +1 -1
  116. package/bundled/skills/feature-planner/references/generated-plan-review.md +3 -2
  117. package/bundled/skills/feature-planner/references/incremental-feature-planning.md +3 -1
  118. package/bundled/skills/feature-workflow/SKILL.md +1 -2
  119. package/bundled/skills/prizmkit/SKILL.md +7 -1
  120. package/bundled/skills/prizmkit-code-review/SKILL.md +14 -6
  121. package/bundled/skills/prizmkit-code-review/references/independent-code-review.md +7 -4
  122. package/bundled/skills/prizmkit-code-review/references/review-report-template.md +16 -0
  123. package/bundled/skills/prizmkit-code-review/scripts/render_review_report.py +58 -20
  124. package/bundled/skills/prizmkit-implement/SKILL.md +1 -1
  125. package/bundled/skills/prizmkit-init/SKILL.md +25 -128
  126. package/bundled/skills/prizmkit-init/assets/project-brief-template.md +3 -3
  127. package/bundled/skills/prizmkit-init/references/config-schema.md +2 -2
  128. package/bundled/skills/prizmkit-plan/SKILL.md +6 -8
  129. package/bundled/skills/prizmkit-plan/references/clarify-guide.md +1 -1
  130. package/bundled/skills/prizmkit-plan/references/independent-plan-review.md +5 -2
  131. package/bundled/skills/prizmkit-plan/references/review-plan-spec-loop.md +6 -5
  132. package/bundled/skills/prizmkit-prizm-docs/SKILL.md +1 -13
  133. package/bundled/skills/prizmkit-prizm-docs/assets/prizm-docs-format.md +1 -1
  134. package/bundled/skills/prizmkit-prizm-docs/references/op-init.md +1 -1
  135. package/bundled/skills/prizmkit-prizm-docs/references/op-update.md +1 -1
  136. package/bundled/skills/prizmkit-retrospective/SKILL.md +6 -4
  137. package/bundled/skills/prizmkit-test/SKILL.md +25 -133
  138. package/bundled/skills/prizmkit-test/references/independent-test-review.md +5 -2
  139. package/bundled/skills/prizmkit-test/references/test-coverage-model.md +6 -0
  140. package/bundled/skills/prizmkit-workflow/SKILL.md +2 -3
  141. package/bundled/skills/prizmkit-workflow/references/workflow-state-protocol.md +4 -3
  142. package/bundled/skills/recovery-workflow/SKILL.md +7 -7
  143. package/bundled/skills/recovery-workflow/evals/evals.json +1 -1
  144. package/bundled/skills/recovery-workflow/references/detection.md +1 -3
  145. package/bundled/skills/recovery-workflow/scripts/detect-recovery-state.py +0 -6
  146. package/bundled/templates/project-memory-template.md +1 -2
  147. package/package.json +1 -1
  148. package/src/ai-cli-launch.js +1 -1
  149. package/src/clean.js +40 -4
  150. package/src/config.js +64 -4
  151. package/src/detect-platform.js +10 -6
  152. package/src/external-skills.js +2 -2
  153. package/src/index.js +1 -0
  154. package/src/manifest.js +1 -1
  155. package/src/platforms.js +6 -2
  156. package/src/prompts.js +11 -3
  157. package/src/scaffold.js +87 -11
  158. package/src/upgrade.js +9 -3
  159. package/bundled/dev-pipeline/SCHEMA_ANALYSIS.md +0 -53
  160. package/bundled/dev-pipeline/scripts/generate-refactor-prompt.py +0 -649
  161. package/bundled/dev-pipeline/scripts/init-refactor-pipeline.py +0 -463
  162. package/bundled/dev-pipeline/scripts/update-refactor-status.py +0 -1512
  163. package/bundled/dev-pipeline/templates/refactor-bootstrap-prompt.md +0 -240
  164. package/bundled/dev-pipeline/templates/refactor-list-schema.json +0 -266
  165. package/bundled/dev-pipeline/templates/sections/refactor-critical-paths.md +0 -15
  166. package/bundled/dev-pipeline/templates/sections/refactor-mission.md +0 -9
  167. package/bundled/dev-pipeline/templates/sections/refactor-phase-commit-report.md +0 -24
  168. package/bundled/dev-pipeline/templates/sections/refactor-phase-implement.md +0 -16
  169. package/bundled/dev-pipeline/templates/sections/refactor-phase-init.md +0 -9
  170. package/bundled/dev-pipeline/templates/sections/refactor-phase-plan.md +0 -22
  171. package/bundled/dev-pipeline/templates/sections/refactor-phase-review.md +0 -19
  172. package/bundled/dev-pipeline/templates/sections/refactor-phase-test.md +0 -24
  173. package/bundled/dev-pipeline/templates/sections/refactor-reminders.md +0 -12
  174. package/bundled/dev-pipeline/templates/sections/refactor-session-context.md +0 -6
  175. package/bundled/dev-pipeline/templates/sections/refactor-task-contract.md +0 -52
  176. package/bundled/dev-pipeline/tests/test_generate_refactor_prompt.py +0 -478
  177. package/bundled/skills/feature-planner/assets/evaluation-guide.md +0 -44
  178. package/bundled/skills/refactor-pipeline-launcher/SKILL.md +0 -219
  179. package/bundled/skills/refactor-pipeline-launcher/references/configuration.md +0 -78
  180. package/bundled/skills/refactor-planner/SKILL.md +0 -467
  181. package/bundled/skills/refactor-planner/assets/planning-guide.md +0 -291
  182. package/bundled/skills/refactor-planner/references/behavior-preservation.md +0 -187
  183. package/bundled/skills/refactor-planner/references/error-recovery.md +0 -45
  184. package/bundled/skills/refactor-planner/references/fast-path.md +0 -59
  185. package/bundled/skills/refactor-planner/references/generated-plan-review.md +0 -107
  186. package/bundled/skills/refactor-planner/references/planning-phases.md +0 -172
  187. package/bundled/skills/refactor-planner/references/refactor-scoping-guide.md +0 -230
  188. package/bundled/skills/refactor-planner/scripts/validate-and-generate-refactor.py +0 -1120
  189. 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
 
@@ -1109,6 +1104,62 @@ def test_runtime_config_resolves_and_validates_cursor_agent(tmp_path, monkeypatc
1109
1104
  assert preserved.source == "installed-platform:claude"
1110
1105
 
1111
1106
 
1107
+ def test_runtime_config_resolves_and_validates_antigravity_agy(tmp_path, monkeypatch):
1108
+ import prizmkit_runtime.config as runtime_config
1109
+ from prizmkit_runtime.config import resolve_ai_client, validate_effort
1110
+ from prizmkit_runtime.paths import resolve_runtime_paths
1111
+ from prizmkit_runtime.platform_detection import platform_from_command
1112
+
1113
+ assert platform_from_command("agy") == "antigravity"
1114
+ assert platform_from_command("antigravity") == "antigravity"
1115
+ assert platform_from_command(r"C:\Tools\agy.exe") == "antigravity"
1116
+
1117
+ project = tmp_path / "agy-project"
1118
+ pipeline = project / ".prizmkit" / "dev-pipeline"
1119
+ pipeline.mkdir(parents=True)
1120
+ paths = resolve_runtime_paths(pipeline_root=pipeline)
1121
+
1122
+ (project / ".prizmkit" / "config.json").write_text('{"ai_cli":"agy"}', encoding="utf-8")
1123
+ configured = resolve_ai_client(paths, env={"PATH": ""})
1124
+ assert configured.command == "agy"
1125
+ assert configured.platform == "antigravity"
1126
+ assert configured.launch_profile is None
1127
+
1128
+ for valid_level in ("low", "medium", "high", "xhigh", "max"):
1129
+ assert validate_effort(valid_level, "antigravity").valid is True
1130
+ invalid_effort = validate_effort("off", "antigravity")
1131
+ assert invalid_effort.valid is False
1132
+ assert invalid_effort.supported_values == ("low", "medium", "high", "xhigh", "max")
1133
+ assert "Antigravity" in invalid_effort.message
1134
+
1135
+ (project / ".prizmkit" / "config.json").unlink()
1136
+ (project / ".prizmkit" / "manifest.json").write_text('{"platform":"antigravity"}', encoding="utf-8")
1137
+ monkeypatch.setattr(
1138
+ runtime_config.shutil,
1139
+ "which",
1140
+ lambda name, path=None: "/tools/agy" if name == "agy" else None,
1141
+ )
1142
+ from_manifest = resolve_ai_client(paths, env={"PATH": "/tools"})
1143
+ assert from_manifest.command == "agy"
1144
+ assert from_manifest.platform == "antigravity"
1145
+ assert from_manifest.source == "prizmkit-manifest:platform"
1146
+
1147
+ (project / ".prizmkit" / "manifest.json").unlink()
1148
+ plugin_skill = project / ".agents" / "plugins" / "prizmkit" / "skills" / "prizmkit" / "SKILL.md"
1149
+ plugin_skill.parent.mkdir(parents=True)
1150
+ plugin_skill.write_text("fixture\n", encoding="utf-8")
1151
+ from_marker = resolve_ai_client(paths, env={"PATH": "/tools"})
1152
+ assert from_marker.command == "agy"
1153
+ assert from_marker.platform == "antigravity"
1154
+ assert from_marker.source == "installed-platform:antigravity"
1155
+
1156
+ plugin_skill.unlink()
1157
+ from_path = resolve_ai_client(paths, env={"PATH": "/tools"})
1158
+ assert from_path.command == "agy"
1159
+ assert from_path.platform == "antigravity"
1160
+ assert from_path.source == "PATH:agy"
1161
+
1162
+
1112
1163
  def test_stream_json_support_detection_matches_provider_rules(monkeypatch):
1113
1164
  import prizmkit_runtime.sessions as sessions
1114
1165
  from prizmkit_runtime.sessions import detect_stream_json_support
@@ -1124,6 +1175,8 @@ def test_stream_json_support_detection_matches_provider_rules(monkeypatch):
1124
1175
  return "Cursor Agent 2026.1"
1125
1176
  if tuple(command) == ("agent", "--help"):
1126
1177
  return "Cursor Agent --print --force --trust --output-format stream-json"
1178
+ if tuple(command) == ("agy", "--help"):
1179
+ return "agy --print --dangerously-skip-permissions --input-format --output-format stream-json"
1127
1180
  return ""
1128
1181
 
1129
1182
  codebuddy = detect_stream_json_support("cbc", "codebuddy", help_runner)
@@ -1131,6 +1184,7 @@ def test_stream_json_support_detection_matches_provider_rules(monkeypatch):
1131
1184
  claude = detect_stream_json_support("claude", "claude", help_runner)
1132
1185
  pi = detect_stream_json_support("pi", "pi", help_runner)
1133
1186
  cursor = detect_stream_json_support("agent", "cursor", help_runner)
1187
+ antigravity = detect_stream_json_support("agy", "antigravity", help_runner)
1134
1188
  unsupported = detect_stream_json_support("other", "claude", lambda _cmd: "plain help")
1135
1189
 
1136
1190
  assert codebuddy.enabled and codebuddy.format == "stream-json"
@@ -1138,6 +1192,8 @@ def test_stream_json_support_detection_matches_provider_rules(monkeypatch):
1138
1192
  assert claude.enabled and claude.format == "stream-json"
1139
1193
  assert pi.enabled and pi.format == "pi-json"
1140
1194
  assert cursor.enabled and cursor.format == "cursor-stream-json"
1195
+ assert antigravity.enabled and antigravity.format == "antigravity-stream-json"
1196
+ assert detect_stream_json_support("agy", "antigravity", lambda _cmd: "--print").enabled is False
1141
1197
  assert detect_stream_json_support("agent", "cursor", lambda _cmd: "unrelated --output-format").enabled is False
1142
1198
  monkeypatch.setattr(
1143
1199
  sessions.subprocess,
@@ -1249,6 +1305,39 @@ def test_ai_session_command_builders_match_unix_runtime_snapshot(tmp_path):
1249
1305
  assert "hello" not in cursor.argv
1250
1306
  assert not ({"--effort", "--sandbox", "--worktree", "--disallowedTools", "-y", "--yolo"} & set(cursor.argv))
1251
1307
 
1308
+ agy = build_ai_session_command(
1309
+ AISessionConfig(
1310
+ cli_command="agy",
1311
+ platform="antigravity",
1312
+ model="gemini-3-pro",
1313
+ effort="xhigh",
1314
+ prompt_path=prompt,
1315
+ cwd=project,
1316
+ use_stream_json=True,
1317
+ )
1318
+ )
1319
+ assert agy.argv == (
1320
+ "agy", "--dangerously-skip-permissions", "--input-format", "stream-json",
1321
+ "--output-format", "stream-json", "--model", "gemini-3-pro", "--effort", "xhigh",
1322
+ )
1323
+ assert json.loads(agy.stdin_text) == {"event": "user", "message": {"content": "hello"}}
1324
+ assert agy.prompt_mode == "stdin"
1325
+ assert "hello" not in agy.argv
1326
+
1327
+ agy_text = build_ai_session_command(
1328
+ AISessionConfig(
1329
+ cli_command="agy",
1330
+ platform="antigravity",
1331
+ model=None,
1332
+ prompt_path=prompt,
1333
+ cwd=project,
1334
+ use_stream_json=False,
1335
+ )
1336
+ )
1337
+ assert agy_text.argv == ("agy", "-p", "hello", "--dangerously-skip-permissions")
1338
+ assert agy_text.stdin_text is None
1339
+ assert agy_text.prompt_mode == "argument"
1340
+
1252
1341
 
1253
1342
  def test_custom_ai_session_command_builder_injects_prompt_and_tokenizes_extra_args(tmp_path):
1254
1343
  from prizmkit_runtime.launch_profiles import HeadlessLaunchProfile
@@ -1504,432 +1593,6 @@ def test_headless_review_guidance_maps_stage_local_skill_result():
1504
1593
  assert "WORKSPACE_MISMATCH" not in skill_text
1505
1594
 
1506
1595
 
1507
- def test_progress_parser_adds_required_metadata(tmp_path):
1508
- import importlib.util
1509
-
1510
- parser_path = PIPELINE_ROOT / "scripts" / "parse-stream-progress.py"
1511
- spec = importlib.util.spec_from_file_location("parse_stream_progress", parser_path)
1512
- module = importlib.util.module_from_spec(spec)
1513
- assert spec.loader is not None
1514
- spec.loader.exec_module(module)
1515
-
1516
- tracker = module.ProgressTracker()
1517
- tracker.process_event({"type": "system", "subtype": "init", "session_id": "claude-session", "cwd": str(tmp_path)})
1518
- tracker.process_event({"type": "assistant", "message": {"content": [{"type": "text", "text": "working"}]}})
1519
- tracker.process_event({"type": "result", "subtype": "success", "stop_reason": "end_turn", "usage": {"input_tokens": 1}, "result": "done"})
1520
- tracker.process_event({"type": "error", "error": {"message": "permission denied by user"}})
1521
- data = tracker.to_dict()
1522
-
1523
- assert data["event_type_counts"]["system"] == 1
1524
- assert data["event_type_counts"]["assistant"] == 1
1525
- assert data["claude_session_id"] == "claude-session"
1526
- assert data["result_subtype"] == "success"
1527
- assert data["stop_reason"] == "end_turn"
1528
- assert data["has_usage"] is True
1529
- assert data["permission_denial_count"] == 1
1530
-
1531
-
1532
-
1533
- def test_progress_parser_normalizes_pi_json_events():
1534
- module = _load_progress_parser_module()
1535
- tracker = module.ProgressTracker()
1536
- tracker.process_event({"type": "session", "version": 3, "id": "pi-session", "cwd": "/tmp/project"})
1537
- tracker.process_event({"type": "agent_start"})
1538
- tracker.process_event({"type": "turn_start"})
1539
- tracker.process_event({
1540
- "type": "message_update",
1541
- "assistantMessageEvent": {"type": "text_delta", "delta": "Running prizmkit-implement"},
1542
- })
1543
- tracker.process_event({"type": "tool_execution_start", "toolName": "edit", "args": {"path": "src/a.js"}})
1544
- tracker.process_event({"type": "tool_execution_end", "toolName": "edit", "result": {"ok": True}, "isError": False})
1545
- tracker.process_event({"type": "compaction_start", "reason": "threshold"})
1546
- tracker.process_event({"type": "compaction_end", "reason": "threshold", "aborted": False, "willRetry": False})
1547
- tracker.process_event({"type": "agent_end", "messages": []})
1548
- data = tracker.to_dict()
1549
- assert data["event_format"] == "pi-json"
1550
- assert data["message_count"] == 1
1551
- assert data["total_tool_calls"] == 1
1552
- assert {item["name"]: item["count"] for item in data["tool_calls"]}["edit"] == 1
1553
- assert data["current_phase"] == "implement"
1554
- assert data["is_active"] is False
1555
- assert data["result_subtype"] == "success"
1556
- assert data["terminal_success_at"]
1557
-
1558
-
1559
- def test_progress_parser_does_not_mark_failed_pi_agent_end_as_success():
1560
- module = _load_progress_parser_module()
1561
- tracker = module.ProgressTracker()
1562
- tracker.process_event({"type": "session", "version": 3, "id": "pi-session", "cwd": "/tmp/project"})
1563
- tracker.process_event({"type": "agent_start"})
1564
- tracker.process_event({
1565
- "type": "message_end",
1566
- "message": {
1567
- "role": "assistant",
1568
- "content": [],
1569
- "stopReason": "error",
1570
- "errorMessage": "provider request failed",
1571
- },
1572
- })
1573
- tracker.process_event({"type": "agent_end", "messages": []})
1574
-
1575
- data = tracker.to_dict()
1576
-
1577
- assert data["event_format"] == "pi-json"
1578
- assert data["is_active"] is False
1579
- assert data["result_subtype"] == "error"
1580
- assert data["stop_reason"] == "error"
1581
- assert data["last_result_is_error"] is True
1582
- assert data["terminal_success_at"] == ""
1583
- assert "provider request failed" in data["errors"]
1584
-
1585
-
1586
- def test_progress_parser_keeps_pi_length_as_nonfatal_diagnostic_metadata():
1587
- module = _load_progress_parser_module()
1588
- tracker = module.ProgressTracker()
1589
- tracker.process_event({"type": "session", "version": 3, "id": "pi-session", "cwd": "/tmp/project"})
1590
- tracker.process_event({"type": "agent_start"})
1591
- message = {
1592
- "role": "assistant",
1593
- "content": [{"type": "thinking", "thinking": "Planning the next test"}],
1594
- "stopReason": "length",
1595
- }
1596
- tracker.process_event({"type": "message_end", "message": message})
1597
- tracker.process_event({"type": "agent_end", "willRetry": False, "messages": [message]})
1598
-
1599
- data = tracker.to_dict()
1600
-
1601
- assert data["result_subtype"] == "success"
1602
- assert data["stop_reason"] == "length"
1603
- assert data["last_result_is_error"] is False
1604
- assert data["api_error_code"] == ""
1605
- assert data["fatal_error_code"] == ""
1606
- assert data["terminal_success_at"]
1607
-
1608
-
1609
- @pytest.mark.parametrize("role", ("assistant", "toolResult"))
1610
- def test_progress_parser_does_not_promote_pi_diagnostic_content_to_fatal_error(role):
1611
- module = _load_progress_parser_module()
1612
- tracker = module.ProgressTracker()
1613
- tracker.process_event({"type": "session", "version": 3, "id": "pi-session", "cwd": "/tmp/project"})
1614
- tracker.process_event({"type": "agent_start"})
1615
- tracker.process_event({
1616
- "type": "message_end",
1617
- "message": {
1618
- "role": role,
1619
- "content": [{
1620
- "type": "text",
1621
- "text": 'continuation_reason = "context_overflow"\nerror = _error_text(result)',
1622
- }],
1623
- "stopReason": "toolUse",
1624
- },
1625
- })
1626
-
1627
- data = tracker.to_dict()
1628
-
1629
- assert data["api_error_code"] == ""
1630
- assert data["fatal_error_code"] == ""
1631
- assert data["last_result_is_error"] is False
1632
-
1633
-
1634
- def test_progress_parser_recovers_from_retrying_pi_attempt_before_final_success():
1635
- module = _load_progress_parser_module()
1636
- tracker = module.ProgressTracker()
1637
- tracker.process_event({"type": "session", "version": 3, "id": "pi-session", "cwd": "/tmp/project"})
1638
- tracker.process_event({"type": "agent_start"})
1639
- tracker.process_event({
1640
- "type": "message_end",
1641
- "message": {
1642
- "role": "assistant",
1643
- "content": [],
1644
- "stopReason": "error",
1645
- "errorMessage": "Error Code internal_server_error: unexpected EOF",
1646
- },
1647
- })
1648
- tracker.process_event({"type": "agent_end", "willRetry": True, "messages": []})
1649
- tracker.process_event({
1650
- "type": "auto_retry_start",
1651
- "attempt": 1,
1652
- "delayMs": 2000,
1653
- "errorMessage": "Error Code internal_server_error: unexpected EOF",
1654
- })
1655
- tracker.process_event({"type": "agent_start"})
1656
- tracker.process_event({"type": "auto_retry_end", "attempt": 1})
1657
- tracker.process_event({
1658
- "type": "message_end",
1659
- "message": {
1660
- "role": "assistant",
1661
- "content": [{"type": "text", "text": "WORKFLOW_COMPLETED"}],
1662
- "stopReason": "stop",
1663
- },
1664
- })
1665
- tracker.process_event({
1666
- "type": "agent_end",
1667
- "willRetry": False,
1668
- "messages": [{
1669
- "role": "assistant",
1670
- "content": [{"type": "text", "text": "WORKFLOW_COMPLETED"}],
1671
- "stopReason": "stop",
1672
- }],
1673
- })
1674
-
1675
- data = tracker.to_dict()
1676
-
1677
- assert data["result_subtype"] == "success"
1678
- assert data["last_result_is_error"] is False
1679
- assert data["stop_reason"] == "stop"
1680
- assert data["fatal_error_code"] == ""
1681
- assert data["terminal_success_at"]
1682
- assert any("unexpected EOF" in str(error) for error in data["errors"])
1683
-
1684
-
1685
- def test_progress_parser_keeps_final_error_after_internal_retry_exhausts():
1686
- module = _load_progress_parser_module()
1687
- tracker = module.ProgressTracker()
1688
- tracker.process_event({"type": "session", "id": "pi-session"})
1689
- tracker.process_event({"type": "agent_start"})
1690
- tracker.process_event({
1691
- "type": "message_end",
1692
- "message": {"role": "assistant", "content": [], "stopReason": "error", "errorMessage": "temporary error"},
1693
- })
1694
- tracker.process_event({"type": "agent_end", "willRetry": True, "messages": []})
1695
- tracker.process_event({"type": "auto_retry_start", "attempt": 1, "errorMessage": "temporary error"})
1696
- tracker.process_event({"type": "agent_start"})
1697
- tracker.process_event({
1698
- "type": "message_end",
1699
- "message": {"role": "assistant", "content": [], "stopReason": "error", "errorMessage": "final error"},
1700
- })
1701
- tracker.process_event({
1702
- "type": "agent_end",
1703
- "willRetry": False,
1704
- "messages": [{"role": "assistant", "content": [], "stopReason": "error", "errorMessage": "final error"}],
1705
- })
1706
-
1707
- data = tracker.to_dict()
1708
-
1709
- assert data["result_subtype"] == "error"
1710
- assert data["last_result_is_error"] is True
1711
- assert data["stop_reason"] == "error"
1712
- assert data["terminal_success_at"] == ""
1713
- assert "final error" in data["terminal_result_text"]
1714
-
1715
-
1716
- def test_progress_parser_clears_retrying_fatal_marker_on_new_pi_attempt():
1717
- module = _load_progress_parser_module()
1718
- tracker = module.ProgressTracker()
1719
- tracker.process_event({"type": "session", "id": "pi-session"})
1720
- tracker.process_event({"type": "agent_start"})
1721
- tracker.process_event({
1722
- "type": "message_end",
1723
- "message": {
1724
- "role": "assistant",
1725
- "content": [],
1726
- "stopReason": "error",
1727
- "errorMessage": "API Error: Your input exceeds the context window",
1728
- },
1729
- })
1730
- tracker.process_event({"type": "agent_end", "willRetry": True, "messages": []})
1731
- failed_attempt = tracker.to_dict()
1732
-
1733
- tracker.process_event({"type": "agent_start"})
1734
- next_attempt = tracker.to_dict()
1735
-
1736
- assert failed_attempt["fatal_error_code"] == "context_overflow"
1737
- assert failed_attempt["last_result_is_error"] is True
1738
- assert next_attempt["fatal_error_code"] == ""
1739
- assert next_attempt["result_subtype"] == ""
1740
- assert next_attempt["last_result_is_error"] is False
1741
- assert any("context window" in str(error) for error in next_attempt["errors"])
1742
- assert next_attempt["is_active"] is True
1743
-
1744
-
1745
- def test_semantic_log_normalizer_compacts_pi_cumulative_stream():
1746
- module = _load_progress_parser_module()
1747
- normalizer = module.SemanticLogNormalizer()
1748
- events = [
1749
- {"type": "session", "id": "session-1"},
1750
- {"type": "message_start", "message": {"role": "user"}},
1751
- {"type": "message_end", "message": {"role": "user", "content": [{"type": "text", "text": "SECRET PROMPT"}]}},
1752
- {"type": "turn_start"},
1753
- {"type": "message_update", "assistantMessageEvent": {"type": "thinking_start", "contentIndex": 0}},
1754
- {"type": "message_update", "assistantMessageEvent": {"type": "thinking_delta", "contentIndex": 0, "delta": "Inspecting"}},
1755
- {"type": "message_update", "assistantMessageEvent": {"type": "thinking_delta", "contentIndex": 0, "delta": " state"}},
1756
- {"type": "message_update", "assistantMessageEvent": {"type": "thinking_end", "contentIndex": 0, "content": "Inspecting state"}},
1757
- {"type": "tool_execution_start", "toolCallId": "call-1", "toolName": "bash", "args": {"command": "printf ABC"}},
1758
- {"type": "tool_execution_update", "toolCallId": "call-1", "toolName": "bash", "partialResult": {"content": [{"type": "text", "text": "A"}]}},
1759
- {"type": "tool_execution_update", "toolCallId": "call-1", "toolName": "bash", "partialResult": {"content": [{"type": "text", "text": "AB"}]}},
1760
- {"type": "tool_execution_update", "toolCallId": "call-1", "toolName": "bash", "partialResult": {"content": [{"type": "text", "text": "ABC"}]}},
1761
- {"type": "tool_execution_end", "toolCallId": "call-1", "toolName": "bash", "result": {"content": [{"type": "text", "text": "ABC"}]}, "isError": False},
1762
- {"type": "message_start", "message": {"role": "toolResult"}},
1763
- {"type": "message_end", "message": {"role": "toolResult", "toolCallId": "call-1", "toolName": "bash", "content": [{"type": "text", "text": "ABC"}]}},
1764
- {"type": "message_update", "assistantMessageEvent": {"type": "text_start", "contentIndex": 1}},
1765
- {"type": "message_update", "assistantMessageEvent": {"type": "text_delta", "contentIndex": 1, "delta": "Done"}},
1766
- {"type": "message_update", "assistantMessageEvent": {"type": "text_end", "contentIndex": 1, "content": "Done"}},
1767
- {"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Done"}], "stopReason": "stop"}},
1768
- {"type": "turn_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Done"}], "stopReason": "stop"}},
1769
- {"type": "agent_end", "willRetry": False, "messages": [{"role": "assistant", "content": [{"type": "text", "text": "Done"}], "stopReason": "stop"}]},
1770
- {"type": "agent_settled"},
1771
- ]
1772
-
1773
- rendered = "".join(normalizer.process_event(event) for event in events) + normalizer.finish()
1774
-
1775
- assert rendered.count("[THINK]") == 1
1776
- assert "[THINK] Inspecting state\n" in rendered
1777
- assert rendered.count("[ACTION]") == 1
1778
- assert "bash" in rendered and "printf ABC" in rendered
1779
- assert rendered.count("[OBSERVATION]") == 1
1780
- assert "[OBSERVATION] ABC\n" in rendered
1781
- assert rendered.count("[FINAL]") == 1
1782
- assert "[FINAL] Done\n" in rendered
1783
- assert rendered.count("[SESSION_END]") == 1
1784
- assert "message_update" not in rendered
1785
- assert "SECRET PROMPT" not in rendered
1786
-
1787
-
1788
- def test_semantic_log_normalizer_ignores_user_prompt_but_keeps_nested_tool_results():
1789
- module = _load_progress_parser_module()
1790
- normalizer = module.SemanticLogNormalizer()
1791
- rendered = normalizer.process_event({
1792
- "type": "user",
1793
- "message": {
1794
- "content": [
1795
- {"type": "text", "text": "SECRET PROMPT"},
1796
- {"type": "tool_result", "tool_use_id": "tool-1", "content": "tool output"},
1797
- ]
1798
- },
1799
- })
1800
- rendered += normalizer.finish()
1801
-
1802
- assert "SECRET PROMPT" not in rendered
1803
- assert "[OBSERVATION] tool output" in rendered
1804
-
1805
-
1806
- def test_semantic_log_normalizer_preserves_repeated_plain_and_tool_output_records():
1807
- module = _load_progress_parser_module()
1808
- normalizer = module.SemanticLogNormalizer()
1809
- rendered = normalizer.process_text("same\n")
1810
- rendered += normalizer.process_text("same\n")
1811
- rendered += normalizer.process_event({"type": "function_call_result", "id": "one", "output": "same result"})
1812
- rendered += normalizer.process_event({"type": "function_call_result", "id": "two", "output": "same result"})
1813
- rendered += normalizer.finish()
1814
-
1815
- assert rendered.count("[OUTPUT] same") == 2
1816
- assert rendered.count("[OBSERVATION] same result") == 2
1817
-
1818
-
1819
- def test_semantic_log_normalizer_emits_terminal_metadata_once():
1820
- module = _load_progress_parser_module()
1821
- normalizer = module.SemanticLogNormalizer()
1822
- rendered = normalizer.process_event({"type": "turn.completed"})
1823
- rendered += normalizer.process_event({"type": "result", "subtype": "success", "result": "Done"})
1824
- rendered += normalizer.finish()
1825
-
1826
- assert rendered.count("[SESSION_END]") == 1
1827
- assert "[FINAL] Done" in rendered
1828
-
1829
-
1830
- def test_semantic_log_normalizer_does_not_promote_pi_length_to_context_overflow():
1831
- module = _load_progress_parser_module()
1832
- normalizer = module.SemanticLogNormalizer()
1833
- rendered = normalizer.process_event({
1834
- "type": "agent_end",
1835
- "willRetry": False,
1836
- "messages": [{"role": "assistant", "content": [], "stopReason": "length"}],
1837
- })
1838
- rendered += normalizer.finish()
1839
-
1840
- assert rendered.count("[SESSION_END]") == 1
1841
- assert "status=success stop_reason=length" in rendered
1842
- assert "status=context_overflow" not in rendered
1843
-
1844
-
1845
- def test_semantic_log_normalizer_preserves_identical_text_from_distinct_turns():
1846
- module = _load_progress_parser_module()
1847
- normalizer = module.SemanticLogNormalizer()
1848
- events = [
1849
- {"type": "turn_start"},
1850
- {"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Done"}], "stopReason": "stop"}},
1851
- {"type": "turn_start"},
1852
- {"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Done"}], "stopReason": "stop"}},
1853
- ]
1854
-
1855
- rendered = "".join(normalizer.process_event(event) for event in events) + normalizer.finish()
1856
-
1857
- assert rendered.count("[FINAL] Done") == 2
1858
-
1859
-
1860
- def test_semantic_log_normalizer_size_tracks_unique_cumulative_content():
1861
- module = _load_progress_parser_module()
1862
- normalizer = module.SemanticLogNormalizer()
1863
- chunks = []
1864
- payload = ""
1865
- chunks.append(normalizer.process_event({"type": "tool_execution_start", "toolCallId": "call-1", "toolName": "read", "args": {"path": "sample"}}))
1866
- for index in range(1, 501):
1867
- payload += chr(64 + ((index - 1) % 26) + 1)
1868
- chunks.append(normalizer.process_event({
1869
- "type": "tool_execution_update",
1870
- "toolCallId": "call-1",
1871
- "toolName": "read",
1872
- "partialResult": {"content": [{"type": "text", "text": payload}]},
1873
- }))
1874
- assert sum(len(value) for value in normalizer._snapshots.values()) == len(payload)
1875
- assert not any(stream_id.startswith("tool:call-1:output") for stream_id in normalizer._stream_buffers)
1876
- chunks.append(normalizer.process_event({
1877
- "type": "tool_execution_end",
1878
- "toolCallId": "call-1",
1879
- "toolName": "read",
1880
- "result": {"content": [{"type": "text", "text": payload}]},
1881
- "isError": False,
1882
- }))
1883
- rendered = "".join(chunks) + normalizer.finish()
1884
-
1885
- assert rendered.count(payload) == 1
1886
- assert len(rendered.encode("utf-8")) <= len(payload.encode("utf-8")) + 256
1887
-
1888
-
1889
- @pytest.mark.parametrize(
1890
- ("events", "expected_labels"),
1891
- [
1892
- (
1893
- [
1894
- {"type": "assistant", "message": {"content": [{"type": "text", "text": "Answer"}, {"type": "tool_use", "id": "tool-1", "name": "Read", "input": {"path": "a"}}]}},
1895
- {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": "tool-1", "content": "result"}]}},
1896
- {"type": "result", "subtype": "success", "stop_reason": "end_turn", "result": "Answer"},
1897
- ],
1898
- {"[FINAL]", "[ACTION]", "[OBSERVATION]", "[SESSION_END]"},
1899
- ),
1900
- (
1901
- [
1902
- {"type": "message", "sessionId": "cb-1", "role": "assistant", "content": [{"type": "text", "text": "Answer"}]},
1903
- {"type": "function_call", "sessionId": "cb-1", "id": "call-1", "name": "read", "arguments": "{\"path\":\"a\"}"},
1904
- {"type": "function_call_result", "sessionId": "cb-1", "id": "call-1", "output": "result"},
1905
- {"type": "result", "subtype": "success", "result": "Answer"},
1906
- ],
1907
- {"[FINAL]", "[ACTION]", "[OBSERVATION]", "[SESSION_END]"},
1908
- ),
1909
- (
1910
- [
1911
- {"type": "turn.started"},
1912
- {"type": "item.completed", "item": {"id": "reason-1", "type": "reasoning", "text": "Think"}},
1913
- {"type": "item.started", "item": {"id": "cmd-1", "type": "command_execution", "command": "printf result"}},
1914
- {"type": "item.completed", "item": {"id": "cmd-1", "type": "command_execution", "command": "printf result", "aggregated_output": "result", "status": "completed"}},
1915
- {"type": "item.completed", "item": {"id": "answer-1", "type": "agent_message", "text": "Answer"}},
1916
- {"type": "turn.completed", "usage": {"input_tokens": 1}},
1917
- ],
1918
- {"[THINK]", "[FINAL]", "[ACTION]", "[OBSERVATION]", "[SESSION_END]"},
1919
- ),
1920
- ],
1921
- )
1922
- def test_semantic_log_normalizer_has_cross_format_contract(events, expected_labels):
1923
- module = _load_progress_parser_module()
1924
- normalizer = module.SemanticLogNormalizer()
1925
-
1926
- rendered = "".join(normalizer.process_event(event) for event in events) + normalizer.finish()
1927
-
1928
- for label in expected_labels:
1929
- assert label in rendered
1930
- assert not any(json.dumps(event, ensure_ascii=False) in rendered for event in events)
1931
-
1932
-
1933
1596
  def test_live_smoke_harness_reports_capability_skips_without_running(tmp_path, monkeypatch, capsys):
1934
1597
  import importlib.util
1935
1598
 
@@ -1959,1282 +1622,32 @@ def test_live_smoke_harness_reports_capability_skips_without_running(tmp_path, m
1959
1622
  "missing": "skipped",
1960
1623
  }
1961
1624
  reasons = {item["name"]: item["reason"] for item in payload["results"]}
1962
- assert "not authorized" in reasons["example"]
1963
- assert "executable not found" in reasons["missing"]
1964
- assert "Do not read, create, edit, or delete project files" in module.smoke_prompt()
1965
- assert module._looks_capability_blocked("login required") is True
1966
- assert module._looks_capability_blocked("network is unreachable") is True
1967
- assert module._looks_capability_blocked("model not found") is True
1968
- assert module._looks_capability_blocked("ordinary tool failure") is False
1969
-
1970
-
1971
- def test_progress_parser_normalizes_claude_subagents_without_double_counting(tmp_path):
1972
- module = _load_progress_parser_module()
1973
- tracker = module.ProgressTracker()
1974
-
1975
- tracker.process_event({"type": "system", "subtype": "init", "session_id": "claude-session", "cwd": str(tmp_path)})
1976
- tracker.process_event({
1977
- "type": "assistant",
1978
- "message": {"content": [{
1979
- "type": "tool_use",
1980
- "id": "tool-1",
1981
- "name": "Agent",
1982
- "input": {"description": "review code", "prompt": "check", "subagent_type": "reviewer"},
1983
- }]},
1984
- })
1985
- tracker.process_event({
1986
- "type": "system",
1987
- "subtype": "task_started",
1988
- "task_id": "task-1",
1989
- "tool_use_id": "tool-1",
1990
- "task_type": "in_process_teammate",
1991
- "subagent_type": "reviewer",
1992
- "description": "review code",
1993
- })
1994
- tracker.process_event({"type": "assistant", "parent_tool_use_id": "tool-1", "message": {"content": [{"type": "text", "text": "child activity"}]}})
1995
- tracker.process_event({"type": "system", "subtype": "task_started", "task_id": "bash-1", "task_type": "local_bash", "description": "ls"})
1996
- tracker.process_event({"type": "system", "subtype": "task_notification", "task_id": "task-1", "tool_use_id": "tool-1", "status": "completed", "summary": "done"})
1997
-
1998
- data = tracker.to_dict()
1999
-
2000
- statistics = data["subagent_statistics"]
2001
- assert statistics["source"] == "session_log"
2002
- assert statistics["spawned"] == 1
2003
- assert statistics["active"] == 0
2004
- assert statistics["states"] == [{"status": "completed", "count": 1}]
2005
- assert "task-1" in statistics["observed_ids"]
2006
- assert "tool-1" in statistics["parent_activity_ids"]
2007
- assert all("bash" not in record["id"] for record in data["subagent_statistics"]["records"])
2008
-
2009
-
2010
- def test_progress_parser_normalizes_codebuddy_agent_tools_with_deduplication():
2011
- module = _load_progress_parser_module()
2012
- tracker = module.ProgressTracker()
2013
- args = {"prompt": "inspect", "description": "inspect", "subagent_type": "Explore"}
2014
-
2015
- tracker.process_event({
2016
- "type": "message",
2017
- "sessionId": "cb-session",
2018
- "cwd": "/tmp/project",
2019
- "role": "assistant",
2020
- "content": [{"type": "tool_use", "id": "call-1", "name": "Agent", "input": args}],
2021
- })
2022
- tracker.process_event({
2023
- "type": "function_call",
2024
- "sessionId": "cb-session",
2025
- "cwd": "/tmp/project",
2026
- "id": "call-1",
2027
- "name": "Agent",
2028
- "arguments": json.dumps(args),
2029
- })
2030
- tracker.process_event({
2031
- "type": "function_call",
2032
- "sessionId": "cb-session",
2033
- "cwd": "/tmp/project",
2034
- "id": "task-call",
2035
- "name": "TaskCreate",
2036
- "arguments": json.dumps({"description": "background", "subject": "status"}),
2037
- })
2038
-
2039
- data = tracker.to_dict()
2040
-
2041
- assert data["cb_session_id"] == "cb-session"
2042
- statistics = data["subagent_statistics"]
2043
- assert statistics["providers"] == ["codebuddy"]
2044
- assert statistics["spawned"] == 1
2045
- assert statistics["active"] == 1
2046
- assert {item["status"] for item in statistics["states"]} == {"running"}
2047
- assert len(statistics["records"]) == 1
2048
- assert data["subagent_statistics"]["records"][0]["metadata"]["tool"] == "Agent"
2049
-
2050
-
2051
- def test_progress_parser_normalizes_codex_collab_metadata_with_missing_fields():
2052
- module = _load_progress_parser_module()
2053
- tracker = module.ProgressTracker()
2054
-
2055
- tracker.process_event({"type": "thread.started", "thread_id": "parent"})
2056
- tracker.process_event({
2057
- "type": "item.started",
2058
- "item": {
2059
- "type": "collab_tool_call",
2060
- "tool": "delegate",
2061
- "receiver_thread_ids": ["thread-a", "thread-b"],
2062
- "agents_states": {
2063
- "thread-a": {"status": "running", "message": "working"},
2064
- "thread-b": {"status": "completed", "message": "done"},
2065
- },
2066
- },
2067
- })
2068
- tracker.process_event({"type": "item.completed", "item": {"type": "collab_tool_call", "tool": "delegate"}})
2069
- tracker.process_event({"type": "turn.completed", "usage": {"input_tokens": 1}})
2070
-
2071
- data = tracker.to_dict()
2072
-
2073
- assert data["event_format"] == "codex-json"
2074
- assert data["result_subtype"] == "success"
2075
- assert data["stop_reason"] == "completed"
2076
- assert data["is_active"] is False
2077
- assert data["child_thread_ids"] == ["thread-a", "thread-b"]
2078
- statistics = data["subagent_statistics"]
2079
- assert statistics["spawned"] == 2
2080
- assert statistics["active"] == 1
2081
- assert {state["status"]: state["count"] for state in statistics["states"]} == {"running": 1, "completed": 1}
2082
- assert statistics["child_activity_source"] == "filesystem_liveness_only"
2083
-
2084
-
2085
- def test_progress_parser_keeps_child_files_liveness_only(tmp_path, monkeypatch):
2086
- module = _load_progress_parser_module()
2087
- claude_home = tmp_path / "claude"
2088
- project_key = str(tmp_path).replace("\\", "-").replace("/", "-").replace(":", "")
2089
- subagents_dir = claude_home / "projects" / project_key / "parent-session" / "subagents"
2090
- subagents_dir.mkdir(parents=True)
2091
- child_log = subagents_dir / "agent-child.jsonl"
2092
- child_log.write_text("child activity", encoding="utf-8")
2093
- monkeypatch.setenv("CLAUDE_HOME", str(claude_home))
2094
-
2095
- tracker = module.ProgressTracker()
2096
- tracker.process_event({"type": "system", "subtype": "init", "session_id": "parent-session", "cwd": str(tmp_path)})
2097
- tracker.process_event({
2098
- "type": "system",
2099
- "subtype": "task_started",
2100
- "task_id": "task-1",
2101
- "tool_use_id": "tool-1",
2102
- "task_type": "in_process_teammate",
2103
- "description": "agent",
2104
- })
2105
- first = tracker.to_dict()
2106
- child_log.write_text("child activity grew", encoding="utf-8")
2107
- tracker.refresh_child_session_activity(force=True)
2108
- second = tracker.to_dict()
2109
-
2110
- assert first["subagent_statistics"]["spawned"] == 1
2111
- assert second["subagent_statistics"]["spawned"] == 1
2112
- assert second["child_total_bytes"] > first["child_total_bytes"]
2113
- assert second["child_session_files"]
2114
- assert second["child_activity_source"] == "filesystem_liveness_only"
2115
- assert second["subagent_statistics"]["source"] == "session_log"
2116
-
2117
- def test_session_dual_writes_progress_and_recovers_backup(tmp_path):
2118
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher, recover_session_log
2119
-
2120
- fake_cli = tmp_path / "fake_cli.py"
2121
- fake_cli.write_text(
2122
- "#!/usr/bin/env python3\n"
2123
- "import json, sys\n"
2124
- "print(json.dumps({'type':'system','subtype':'init','session_id':'s1'}), flush=True)\n"
2125
- "print(json.dumps({'type':'result','subtype':'success','stop_reason':'end_turn','usage':{'tokens':1},'result':'ok'}), flush=True)\n",
2126
- encoding="utf-8",
2127
- )
2128
- fake_cli.chmod(0o755)
2129
- prompt = tmp_path / "prompt.md"
2130
- prompt.write_text("hello", encoding="utf-8")
2131
- session_log = tmp_path / "state" / "sessions" / "sess-1" / "logs" / "session.log"
2132
- backup_log = tmp_path / "home" / ".prizmkit" / "session-backups" / "sess-1.log"
2133
- progress = session_log.with_name("progress.json")
2134
-
2135
- result = AISessionLauncher(
2136
- AISessionConfig(
2137
- cli_command=str(fake_cli),
2138
- platform="codebuddy",
2139
- model=None,
2140
- prompt_path=prompt,
2141
- cwd=tmp_path,
2142
- log_path=session_log,
2143
- backup_log_path=backup_log,
2144
- progress_path=progress,
2145
- )
2146
- ).run()
2147
-
2148
- assert result.exit_code == 0
2149
- assert session_log.exists()
2150
- assert progress.exists()
2151
- progress_data = json.loads(progress.read_text(encoding="utf-8"))
2152
- assert progress_data["event_type_counts"]["result"] == 1
2153
- assert progress_data["claude_session_id"] == "s1"
2154
- assert progress_data["has_usage"] is True
2155
- assert result.log_recovery is not None
2156
-
2157
- second_backup = tmp_path / "backup.log"
2158
- second_log = tmp_path / "main.log"
2159
- second_log.write_text("tiny", encoding="utf-8")
2160
- second_backup.write_text("larger recovered log", encoding="utf-8")
2161
- recovery = recover_session_log(second_log, second_backup)
2162
- assert recovery.recovered is True
2163
- assert recovery.cleaned_backup is True
2164
- assert not second_backup.exists()
2165
- assert second_log.read_text(encoding="utf-8") == "larger recovered log"
2166
-
2167
-
2168
- def test_session_reader_does_not_retain_or_reread_raw_history():
2169
- import inspect
2170
- import prizmkit_runtime.sessions as sessions
2171
-
2172
- reader_source = inspect.getsource(sessions._reader_thread)
2173
- run_source = inspect.getsource(sessions.AISessionLauncher.run)
2174
-
2175
- assert "lines.append" not in reader_source
2176
- assert "output_queue" not in reader_source
2177
- assert "session_log.read_text" not in run_source
2178
- assert "splitlines()" not in run_source
2179
- assert "maxsize=1" in run_source
2180
-
2181
-
2182
- def test_session_reader_contains_parser_failures_and_continues_draining(tmp_path, monkeypatch):
2183
- import io
2184
- import queue
2185
- import prizmkit_runtime.sessions as sessions
2186
-
2187
- class FailingTracker:
2188
- def __init__(self, _session_log):
2189
- pass
2190
-
2191
- def process_event(self, _event):
2192
- raise ValueError("unsupported shape")
2193
-
2194
- def to_dict(self):
2195
- return {"event_type_counts": {}, "errors": []}
2196
-
2197
- class FailingNormalizer:
2198
- def process_event(self, _event):
2199
- raise ValueError("unsupported shape")
2200
-
2201
- def process_text(self, text):
2202
- return f"[OUTPUT] {text.strip()}\n"
2203
-
2204
- def finish(self):
2205
- return "[SESSION_END] status=stream_closed\n"
2206
-
2207
- monkeypatch.setattr(sessions, "_load_stream_parser_classes", lambda: (FailingTracker, FailingNormalizer))
2208
- session_log = tmp_path / "session.log"
2209
- backup_log = tmp_path / "backup.log"
2210
- session_log.write_text("", encoding="utf-8")
2211
- backup_log.write_text("", encoding="utf-8")
2212
- result_queue = queue.Queue(maxsize=1)
2213
- pipe = io.StringIO('{"type":"result","subtype":"success","result":"done"}\nplain\n')
2214
-
2215
- sessions._reader_thread(pipe, session_log, backup_log, result_queue)
2216
-
2217
- text = session_log.read_text(encoding="utf-8")
2218
- assert "[ERROR] progress parser rejected event=result: ValueError" in text
2219
- assert "[ERROR] semantic log adapter rejected event=result: ValueError" in text
2220
- assert "[OUTPUT] done" in text
2221
- assert "[OUTPUT] plain" in text
2222
- assert "[SESSION_END] status=stream_closed" in text
2223
- assert backup_log.read_text(encoding="utf-8") == text
2224
- assert result_queue.get_nowait()["event_type_counts"] == {}
2225
-
2226
-
2227
- def test_session_persists_normalized_stream_without_raw_history(tmp_path, monkeypatch):
2228
- import prizmkit_runtime.sessions as sessions
2229
-
2230
- fake_cli = tmp_path / "pi_like_cli.py"
2231
- fake_cli.write_text(
2232
- "#!/usr/bin/env python3\n"
2233
- "import json, sys\n"
2234
- "_prompt = sys.stdin.read()\n"
2235
- "events = [\n"
2236
- " {'type':'session','id':'s1'},\n"
2237
- " {'type':'agent_start'},\n"
2238
- " {'type':'turn_start'},\n"
2239
- " {'type':'message_update','assistantMessageEvent':{'type':'thinking_start','contentIndex':0}},\n"
2240
- " {'type':'message_update','assistantMessageEvent':{'type':'thinking_delta','contentIndex':0,'delta':'Think'}},\n"
2241
- " {'type':'message_update','assistantMessageEvent':{'type':'thinking_end','contentIndex':0,'content':'Think'}},\n"
2242
- " {'type':'tool_execution_start','toolCallId':'c1','toolName':'bash','args':{'command':'printf ABC'}},\n"
2243
- " {'type':'tool_execution_update','toolCallId':'c1','toolName':'bash','partialResult':{'content':[{'type':'text','text':'A'}]}},\n"
2244
- " {'type':'tool_execution_update','toolCallId':'c1','toolName':'bash','partialResult':{'content':[{'type':'text','text':'ABC'}]}},\n"
2245
- " {'type':'tool_execution_end','toolCallId':'c1','toolName':'bash','result':{'content':[{'type':'text','text':'ABC'}]},'isError':False},\n"
2246
- " {'type':'message_update','assistantMessageEvent':{'type':'text_start','contentIndex':1}},\n"
2247
- " {'type':'message_update','assistantMessageEvent':{'type':'text_delta','contentIndex':1,'delta':'Done'}},\n"
2248
- " {'type':'message_update','assistantMessageEvent':{'type':'text_end','contentIndex':1,'content':'Done'}},\n"
2249
- " {'type':'message_end','message':{'role':'assistant','content':[{'type':'text','text':'Done'}],'stopReason':'stop'}},\n"
2250
- " {'type':'agent_end','willRetry':False,'messages':[{'role':'assistant','content':[{'type':'text','text':'Done'}],'stopReason':'stop'}]},\n"
2251
- "]\n"
2252
- "for event in events: print(json.dumps(event), flush=True)\n",
2253
- encoding="utf-8",
2254
- )
2255
- fake_cli.chmod(0o755)
2256
- prompt = tmp_path / "prompt.md"
2257
- prompt.write_text("hello", encoding="utf-8")
2258
- session_log = tmp_path / "state" / "sessions" / "sess-normalized" / "logs" / "session.log"
2259
- backup_log = tmp_path / "home" / ".prizmkit" / "session-backups" / "sess-normalized.log"
2260
- progress = session_log.with_name("progress.json")
2261
- captured_backup = {}
2262
- original_recover = sessions.recover_session_log
2263
-
2264
- def capture_recovery(primary, backup, min_size=1024):
2265
- captured_backup["text"] = backup.read_text(encoding="utf-8")
2266
- return original_recover(primary, backup, min_size)
2267
-
2268
- monkeypatch.setattr(sessions, "recover_session_log", capture_recovery)
2269
- result = sessions.AISessionLauncher(
2270
- sessions.AISessionConfig(
2271
- cli_command=str(fake_cli),
2272
- platform="pi",
2273
- model=None,
2274
- prompt_path=prompt,
2275
- cwd=tmp_path,
2276
- log_path=session_log,
2277
- backup_log_path=backup_log,
2278
- progress_path=progress,
2279
- )
2280
- ).run()
2281
-
2282
- text = session_log.read_text(encoding="utf-8")
2283
- assert result.exit_code == 0
2284
- assert result.progress_summary.result_subtype == "success"
2285
- assert "[THINK] Think" in text
2286
- assert "[ACTION] bash" in text
2287
- assert "[OBSERVATION] ABC" in text
2288
- assert "[FINAL] Done" in text
2289
- assert "[SESSION_END] status=success" in text
2290
- assert text.count("ABC") == 2 # one action argument and one observation
2291
- assert '"type": "message_update"' not in text
2292
- assert '"type":"message_update"' not in text
2293
- assert captured_backup["text"] == text
2294
- assert not backup_log.exists()
2295
-
2296
-
2297
- def test_pi_session_diagnostic_tool_output_does_not_trigger_fatal_termination(tmp_path):
2298
- import prizmkit_runtime.sessions as sessions
2299
-
2300
- fake_cli = tmp_path / "pi_diagnostic_cli.py"
2301
- fake_cli.write_text(
2302
- "#!/usr/bin/env python3\n"
2303
- "import json, sys, time\n"
2304
- "_prompt = sys.stdin.read()\n"
2305
- "source = 'continuation_reason = \\\"context_overflow\\\"\\nerror = _error_text(result)'\n"
2306
- "events = [\n"
2307
- " {'type':'session','id':'s1'},\n"
2308
- " {'type':'agent_start'},\n"
2309
- " {'type':'turn_start'},\n"
2310
- " {'type':'tool_execution_start','toolCallId':'c1','toolName':'read','args':{'path':'runtime.py'}},\n"
2311
- " {'type':'tool_execution_end','toolCallId':'c1','toolName':'read','result':{'content':[{'type':'text','text':source}]},'isError':False},\n"
2312
- " {'type':'message_end','message':{'role':'toolResult','toolCallId':'c1','content':[{'type':'text','text':source}],'stopReason':'toolUse'}},\n"
2313
- "]\n"
2314
- "for event in events: print(json.dumps(event), flush=True)\n"
2315
- "time.sleep(1.5)\n"
2316
- "message = {'role':'assistant','content':[{'type':'text','text':'Done'}],'stopReason':'stop'}\n"
2317
- "print(json.dumps({'type':'message_end','message':message}), flush=True)\n"
2318
- "print(json.dumps({'type':'agent_end','willRetry':False,'messages':[message]}), flush=True)\n",
2319
- encoding="utf-8",
2320
- )
2321
- fake_cli.chmod(0o755)
2322
- prompt = tmp_path / "prompt.md"
2323
- prompt.write_text("hello", encoding="utf-8")
2324
- session_log = tmp_path / "state" / "sessions" / "sess-diagnostic" / "logs" / "session.log"
2325
- progress = session_log.with_name("progress.json")
2326
-
2327
- result = sessions.AISessionLauncher(
2328
- sessions.AISessionConfig(
2329
- cli_command=str(fake_cli),
2330
- platform="pi",
2331
- model=None,
2332
- prompt_path=prompt,
2333
- cwd=tmp_path,
2334
- log_path=session_log,
2335
- progress_path=progress,
2336
- )
2337
- ).run()
2338
-
2339
- progress_data = json.loads(progress.read_text(encoding="utf-8"))
2340
- assert result.exit_code == 0
2341
- assert result.fatal_error_code == ""
2342
- assert result.progress_summary.result_subtype == "success"
2343
- assert progress_data["fatal_error_code"] == ""
2344
- assert not session_log.with_name("fatal-error.json").exists()
2345
- assert not session_log.with_name("stale-kill.json").exists()
2346
-
2347
-
2348
- def test_custom_session_launch_writes_existing_logs_and_progress(tmp_path):
2349
- from prizmkit_runtime.launch_profiles import HeadlessLaunchProfile
2350
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
2351
-
2352
- fake_cli = tmp_path / "custom_cli.py"
2353
- fake_cli.write_text(
2354
- "#!/usr/bin/env python3\n"
2355
- "import json, sys\n"
2356
- "assert sys.argv[1] == '-i'\n"
2357
- "assert sys.argv[2] == 'hello custom'\n"
2358
- "assert sys.argv[3:] == ['--verbose', '--path', 'two words']\n"
2359
- "print(json.dumps({'type':'result','subtype':'success','usage':{'tokens':1},'result':'ok'}), flush=True)\n",
2360
- encoding="utf-8",
2361
- )
2362
- fake_cli.chmod(0o755)
2363
- prompt = tmp_path / "prompt.md"
2364
- prompt.write_text("hello custom", encoding="utf-8")
2365
- session_log = tmp_path / "state" / "sessions" / "sess-custom" / "logs" / "session.log"
2366
- progress = session_log.with_name("progress.json")
2367
-
2368
- result = AISessionLauncher(
2369
- AISessionConfig(
2370
- cli_command=str(fake_cli),
2371
- platform="custom",
2372
- model=None,
2373
- prompt_path=prompt,
2374
- cwd=tmp_path,
2375
- log_path=session_log,
2376
- progress_path=progress,
2377
- launch_profile=HeadlessLaunchProfile(
2378
- profile="custom",
2379
- prompt_arg="-i",
2380
- extra_args=("--verbose", "--path", "two words"),
2381
- ),
2382
- )
2383
- ).run()
2384
-
2385
- assert result.exit_code == 0
2386
- assert result.command.argv[1:4] == ("-i", "hello custom", "--verbose")
2387
- assert session_log.exists()
2388
- assert progress.exists()
2389
- progress_data = json.loads(progress.read_text(encoding="utf-8"))
2390
- assert progress_data["event_type_counts"]["result"] == 1
2391
- assert progress_data["has_usage"] is True
2392
- assert progress_data["subagent_statistics"]["source"] == "session_log"
2393
- assert progress_data["subagent_statistics"]["spawned"] == 0
2394
- assert progress_data["subagent_statistics"]["providers"] == []
2395
- assert progress_data["child_activity_source"] == "filesystem_liveness_only"
2396
-
2397
-
2398
- @pytest.mark.parametrize("platform", ["claude", "codex", "codebuddy"])
2399
- def test_builtin_provider_launches_write_session_artifacts(tmp_path, platform):
2400
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
2401
-
2402
- fake_cli = tmp_path / f"{platform}_cli.py"
2403
- fake_cli.write_text(
2404
- "#!/usr/bin/env python3\n"
2405
- "import json, sys\n"
2406
- "_stdin = sys.stdin.read()\n"
2407
- "print(json.dumps({'type':'result','subtype':'success','usage':{'tokens':1},'result':'ok'}), flush=True)\n",
2408
- encoding="utf-8",
2409
- )
2410
- fake_cli.chmod(0o755)
2411
- prompt = tmp_path / f"{platform}-prompt.md"
2412
- prompt.write_text(f"hello {platform}", encoding="utf-8")
2413
- session_log = tmp_path / "state" / "sessions" / f"sess-{platform}" / "logs" / "session.log"
2414
- progress = session_log.with_name("progress.json")
2415
- heartbeat = session_log.with_name("heartbeat.json")
2416
-
2417
- result = AISessionLauncher(
2418
- AISessionConfig(
2419
- cli_command=str(fake_cli),
2420
- platform=platform,
2421
- model=None,
2422
- prompt_path=prompt,
2423
- cwd=tmp_path,
2424
- log_path=session_log,
2425
- progress_path=progress,
2426
- heartbeat_path=heartbeat,
2427
- use_stream_json=True,
2428
- )
2429
- ).run()
2430
-
2431
- progress_data = json.loads(progress.read_text(encoding="utf-8"))
2432
- assert result.exit_code == 0
2433
- assert session_log.exists()
2434
- assert heartbeat.exists()
2435
- assert progress_data["event_type_counts"]["result"] == 1
2436
- assert progress_data["has_usage"] is True
2437
-
2438
-
2439
- def test_session_live_output_prints_paths_and_verbose_cli_output(tmp_path, capsys):
2440
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
2441
-
2442
- fake_cli = tmp_path / "live_cli.py"
2443
- fake_cli.write_text(
2444
- "#!/usr/bin/env python3\n"
2445
- "print('live-line', flush=True)\n",
2446
- encoding="utf-8",
2447
- )
2448
- fake_cli.chmod(0o755)
2449
- prompt = tmp_path / "prompt.md"
2450
- prompt.write_text("hello", encoding="utf-8")
2451
- session_log = tmp_path / "state" / "sessions" / "sess-live" / "logs" / "session.log"
2452
- progress = session_log.with_name("progress.json")
2453
- heartbeat = session_log.with_name("heartbeat.json")
2454
-
2455
- result = AISessionLauncher(
2456
- AISessionConfig(
2457
- cli_command=str(fake_cli),
2458
- platform="codebuddy",
2459
- model=None,
2460
- prompt_path=prompt,
2461
- cwd=tmp_path,
2462
- log_path=session_log,
2463
- progress_path=progress,
2464
- heartbeat_path=heartbeat,
2465
- verbose=True,
2466
- live_output=True,
2467
- )
2468
- ).run()
2469
-
2470
- captured = capsys.readouterr()
2471
- assert result.exit_code == 0
2472
- assert "live-line" in captured.out
2473
- assert "[prizmkit] AI session started" in captured.err
2474
- assert f"[prizmkit] Prompt: {prompt}" in captured.err
2475
- assert f"[prizmkit] Session log: {session_log}" in captured.err
2476
- assert f"[prizmkit] Progress: {progress}" in captured.err
2477
- assert f"[prizmkit] Heartbeat: {heartbeat}" in captured.err
2478
- assert "[prizmkit] AI session finished" in captured.err
2479
-
2480
-
2481
- def test_compact_progress_line_hides_stale_until_no_progress(tmp_path):
2482
- from prizmkit_runtime.heartbeat import HeartbeatState
2483
- from prizmkit_runtime.sessions import _compact_progress_line
2484
-
2485
- session_log = tmp_path / "session.log"
2486
- progress = tmp_path / "progress.json"
2487
- checkpoint = tmp_path / "workflow-checkpoint.json"
2488
- progress.write_text(
2489
- json.dumps(
2490
- {
2491
- "child_total_bytes": 2 * 1024 * 1024,
2492
- "child_session_files": [{"path": "a"}, {"path": "b"}],
2493
- "subagent_statistics": {
2494
- "spawned": 5,
2495
- "active": 2,
2496
- "states": [{"status": "running", "count": 2}, {"status": "completed", "count": 3}],
2497
- },
2498
- "current_phase": "stream-derived-phase",
2499
- "current_tool": "Read",
2500
- "message_count": 465,
2501
- "total_tool_calls": 412,
2502
- }
2503
- ),
2504
- encoding="utf-8",
2505
- )
2506
- checkpoint.write_text(
2507
- json.dumps({"steps": [
2508
- {"id": "S01", "skill": "plan", "name": "Plan", "status": "completed"},
2509
- {"id": "S02", "skill": "retro", "name": "Retrospective", "status": "pending", "depends_on": "S01"},
2510
- ]}),
2511
- encoding="utf-8",
2512
- )
2513
- running = HeartbeatState(last_seen_epoch=1.0, stale=False, details="progress", stale_seconds=0, log_size=4 * 1024 * 1024)
2514
- brief_pause = HeartbeatState(last_seen_epoch=1.0, stale=False, details="no progress", stale_seconds=125, log_size=4 * 1024 * 1024)
2515
- paused = HeartbeatState(last_seen_epoch=1.0, stale=True, details="no progress", stale_seconds=15 * 60, log_size=4 * 1024 * 1024)
2516
- resumed = HeartbeatState(last_seen_epoch=3.0, stale=False, details="progress", stale_seconds=0, log_size=5 * 1024 * 1024)
2517
-
2518
- running_line = _compact_progress_line(0, session_log, progress, running, checkpoint_path=checkpoint, stale_threshold_seconds=15 * 60)
2519
- brief_pause_line = _compact_progress_line(0, session_log, progress, brief_pause, checkpoint_path=checkpoint, stale_threshold_seconds=15 * 60)
2520
- paused_line = _compact_progress_line(0, session_log, progress, paused, checkpoint_path=checkpoint, stale_threshold_seconds=15 * 60)
2521
- resumed_line = _compact_progress_line(0, session_log, progress, resumed, checkpoint_path=checkpoint, stale_threshold_seconds=15 * 60)
2522
-
2523
- assert "▶ [HEARTBEAT]" in running_line
2524
- assert "log: 4MB" in running_line
2525
- assert "subagents: spawned=5 active=2 states:running=2,completed=3" in running_line
2526
- assert "child logs: 2MB/2 files" in running_line
2527
- assert "child: 2MB/5" not in running_line
2528
- assert "phase: Retrospective" in running_line
2529
- assert "stream-derived-phase" not in running_line
2530
- assert "tool: Read" in running_line
2531
- assert "msgs: 465" in running_line
2532
- assert "412 tool calls" in running_line
2533
- assert "stale:" not in running_line
2534
- assert "▶ [HEARTBEAT]" in brief_pause_line
2535
- assert "stale:" not in brief_pause_line
2536
- assert "⏸ [HEARTBEAT]" in paused_line
2537
- assert "stale: 15m/15m" in paused_line
2538
- assert "▶ [HEARTBEAT]" in resumed_line
2539
- assert "log: 5MB" in resumed_line
2540
- assert "stale:" not in resumed_line
2541
-
2542
- def test_compact_progress_line_omits_phase_without_valid_checkpoint(tmp_path):
2543
- from prizmkit_runtime.heartbeat import HeartbeatState
2544
- from prizmkit_runtime.sessions import _compact_progress_line
2545
-
2546
- session_log = tmp_path / "session.log"
2547
- progress = tmp_path / "progress.json"
2548
- malformed = tmp_path / "bad-checkpoint.json"
2549
- invalid = tmp_path / "invalid-checkpoint.json"
2550
- progress.write_text(
2551
- json.dumps({"current_phase": "legacy-plan", "current_tool": "Edit"}),
2552
- encoding="utf-8",
2553
- )
2554
- malformed.write_text("{bad", encoding="utf-8")
2555
- invalid.write_text(json.dumps({"steps": [{"id": "S01", "skill": "x", "name": "X", "status": "done"}]}), encoding="utf-8")
2556
- state = HeartbeatState(last_seen_epoch=1.0, stale=False, details="progress", stale_seconds=0, log_size=12)
2557
-
2558
- missing_line = _compact_progress_line(0, session_log, progress, state, checkpoint_path=tmp_path / "missing.json")
2559
- malformed_line = _compact_progress_line(0, session_log, progress, state, checkpoint_path=malformed)
2560
- invalid_line = _compact_progress_line(0, session_log, progress, state, checkpoint_path=invalid)
2561
-
2562
- for line in (missing_line, malformed_line, invalid_line):
2563
- assert "phase:" not in line
2564
- assert "legacy-plan" not in line
2565
- assert "tool: Edit" in line
2566
-
2567
-
2568
- def test_heartbeat_observation_stale_accumulates_by_elapsed_time_and_resets_on_progress(tmp_path, monkeypatch):
2569
- import prizmkit_runtime.heartbeat as heartbeat
2570
- from prizmkit_runtime.heartbeat import HeartbeatConfig, observe_heartbeat_state
2571
-
2572
- session_log = tmp_path / "session.log"
2573
- progress = tmp_path / "progress.json"
2574
- session_log.write_text("initial\n", encoding="utf-8")
2575
- progress.write_text('{"current_phase":"plan","current_tool":null,"message_count":1,"total_tool_calls":1}\n', encoding="utf-8")
2576
- config = HeartbeatConfig(
2577
- heartbeat_file=tmp_path / "heartbeat.json",
2578
- session_log=session_log,
2579
- progress_file=progress,
2580
- interval_seconds=60,
2581
- stale_after_seconds=15 * 60,
2582
- )
2583
- ticks = iter([1000.0, 1025.0, 1090.0, 1095.0])
2584
- monkeypatch.setattr(heartbeat.time, "time", lambda: next(ticks))
2585
-
2586
- first = observe_heartbeat_state(config)
2587
- stale = observe_heartbeat_state(config, first)
2588
- older = observe_heartbeat_state(config, stale)
2589
- progress.write_text('{"current_phase":"plan","current_tool":"Edit","message_count":1,"total_tool_calls":2,"child_total_bytes":10}\n', encoding="utf-8")
2590
- reset = observe_heartbeat_state(config, older)
2591
-
2592
- assert first.details == "progress"
2593
- assert first.stale_seconds == 0
2594
- assert first.last_seen_epoch == 1000.0
2595
- assert stale.details == "no progress"
2596
- assert stale.stale_seconds == 25.0
2597
- assert older.stale_seconds == 90.0
2598
- assert reset.details == "progress"
2599
- assert reset.stale_seconds == 0
2600
- assert reset.last_seen_epoch == 1095.0
2601
-
2602
-
2603
- def test_heartbeat_observation_active_tool_resets_stale_until_tool_clears(tmp_path, monkeypatch):
2604
- import prizmkit_runtime.heartbeat as heartbeat
2605
- from prizmkit_runtime.heartbeat import HeartbeatConfig, observe_heartbeat_state
2606
-
2607
- progress = tmp_path / "progress.json"
2608
- progress.write_text(
2609
- '{"current_tool":"bash","message_count":1,"total_tool_calls":1}\n',
2610
- encoding="utf-8",
2611
- )
2612
- config = HeartbeatConfig(
2613
- heartbeat_file=tmp_path / "heartbeat.json",
2614
- progress_file=progress,
2615
- stale_after_seconds=60,
2616
- )
2617
- ticks = iter([1000.0, 1100.0, 1200.0, 1205.0, 1230.0])
2618
- monkeypatch.setattr(heartbeat.time, "time", lambda: next(ticks))
2619
-
2620
- first = observe_heartbeat_state(config)
2621
- active = observe_heartbeat_state(config, first)
2622
- still_active = observe_heartbeat_state(config, active)
2623
- progress.write_text(
2624
- '{"current_tool":null,"message_count":1,"total_tool_calls":1}\n',
2625
- encoding="utf-8",
2626
- )
2627
- tool_finished = observe_heartbeat_state(config, still_active)
2628
- idle = observe_heartbeat_state(config, tool_finished)
2629
-
2630
- assert active.details == "progress"
2631
- assert active.stale_seconds == 0
2632
- assert active.last_seen_epoch == 1100.0
2633
- assert still_active.details == "progress"
2634
- assert still_active.stale_seconds == 0
2635
- assert still_active.last_seen_epoch == 1200.0
2636
- assert tool_finished.details == "progress"
2637
- assert tool_finished.stale_seconds == 0
2638
- assert tool_finished.last_seen_epoch == 1205.0
2639
- assert idle.details == "no progress"
2640
- assert idle.stale_seconds == 25.0
2641
-
2642
-
2643
- @pytest.mark.parametrize("current_tool", [None, "", " ", 0, ["bash"]])
2644
- def test_heartbeat_observation_rejects_inactive_or_malformed_tool_values(
2645
- tmp_path,
2646
- monkeypatch,
2647
- current_tool,
2648
- ):
2649
- import prizmkit_runtime.heartbeat as heartbeat
2650
- from prizmkit_runtime.heartbeat import HeartbeatConfig, observe_heartbeat_state
2651
-
2652
- progress = tmp_path / "progress.json"
2653
- progress.write_text(json.dumps({"current_tool": current_tool}), encoding="utf-8")
2654
- config = HeartbeatConfig(
2655
- heartbeat_file=tmp_path / "heartbeat.json",
2656
- progress_file=progress,
2657
- stale_after_seconds=60,
2658
- )
2659
- ticks = iter([1000.0, 1070.0])
2660
- monkeypatch.setattr(heartbeat.time, "time", lambda: next(ticks))
2661
-
2662
- first = observe_heartbeat_state(config)
2663
- stale = observe_heartbeat_state(config, first)
2664
-
2665
- assert stale.details == "no progress"
2666
- assert stale.stale is True
2667
- assert stale.stale_seconds == 70.0
2668
-
2669
-
2670
- def test_heartbeat_state_tracks_progress_json_child_activity(tmp_path, monkeypatch):
2671
- import prizmkit_runtime.heartbeat as heartbeat
2672
- from prizmkit_runtime.heartbeat import HeartbeatConfig, observe_heartbeat_state
2673
-
2674
- progress = tmp_path / "progress.json"
2675
- progress.write_text(
2676
- json.dumps({"child_activity_signature": "child:1", "child_total_bytes": 10}),
2677
- encoding="utf-8",
2678
- )
2679
- config = HeartbeatConfig(
2680
- heartbeat_file=tmp_path / "heartbeat.json",
2681
- session_log=tmp_path / "missing-session.log",
2682
- progress_file=progress,
2683
- stale_after_seconds=60,
2684
- )
2685
- ticks = iter([10.0, 20.0, 25.0])
2686
- monkeypatch.setattr(heartbeat.time, "time", lambda: next(ticks))
2687
-
2688
- first = observe_heartbeat_state(config)
2689
- quiet = observe_heartbeat_state(config, first)
2690
- progress.write_text(
2691
- json.dumps({"child_activity_signature": "child:2", "child_total_bytes": 20}),
2692
- encoding="utf-8",
2693
- )
2694
- child_progress = observe_heartbeat_state(config, quiet)
2695
-
2696
- assert quiet.details == "no progress"
2697
- assert quiet.stale_seconds == 10.0
2698
- assert child_progress.details == "progress"
2699
- assert child_progress.stale_seconds == 0
2700
- assert child_progress.child_activity_signature == "child:2"
2701
-
2702
-
2703
- def test_heartbeat_monitor_stale_kill_uses_elapsed_no_progress_threshold(tmp_path):
2704
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
2705
-
2706
- fake_cli = tmp_path / "quiet_cli.py"
2707
- fake_cli.write_text(
2708
- "#!/usr/bin/env python3\n"
2709
- "import time\n"
2710
- "time.sleep(5)\n",
2711
- encoding="utf-8",
2712
- )
2713
- fake_cli.chmod(0o755)
2714
- prompt = tmp_path / "prompt.md"
2715
- prompt.write_text("hello", encoding="utf-8")
2716
- session_log = tmp_path / "state" / "sessions" / "sess-stale" / "logs" / "session.log"
2717
- progress = session_log.with_name("progress.json")
2718
- heartbeat = session_log.with_name("heartbeat.json")
2719
-
2720
- result = AISessionLauncher(
2721
- AISessionConfig(
2722
- cli_command=str(fake_cli),
2723
- platform="codebuddy",
2724
- model=None,
2725
- prompt_path=prompt,
2726
- cwd=tmp_path,
2727
- log_path=session_log,
2728
- progress_path=progress,
2729
- heartbeat_path=heartbeat,
2730
- stale_kill_threshold_seconds=0.3,
2731
- heartbeat_stale_threshold_seconds=0.2,
2732
- stale_kill_grace_seconds=0.1,
2733
- )
2734
- ).run()
2735
-
2736
- marker = session_log.parent / "stale-kill.json"
2737
- marker_data = json.loads(marker.read_text(encoding="utf-8"))
2738
- assert result.termination_reason == "stale_session"
2739
- assert result.stale_marker == marker
2740
- assert marker_data["reason"] == "stale_session"
2741
- assert marker_data["threshold"] == pytest.approx(0.3)
2742
- assert marker_data["stale_seconds"] >= 0
2743
-
2744
-
2745
- def test_heartbeat_monitor_active_tool_defers_stale_kill_until_tool_clears(tmp_path):
2746
- from prizmkit_runtime.heartbeat import HeartbeatConfig, HeartbeatMonitor
2747
- from prizmkit_runtime.processes import ProcessSpec, is_process_running, launch_process
2748
-
2749
- sleeper = tmp_path / "active_tool_sleep.py"
2750
- sleeper.write_text("import time\ntime.sleep(5)\n", encoding="utf-8")
2751
- progress = tmp_path / "progress.json"
2752
- progress.write_text('{"current_tool":"bash"}\n', encoding="utf-8")
2753
- handle = launch_process(ProcessSpec(command=(sys.executable, str(sleeper)), cwd=tmp_path))
2754
- monitor = HeartbeatMonitor(
2755
- handle,
2756
- HeartbeatConfig(
2757
- heartbeat_file=tmp_path / "heartbeat.json",
2758
- session_log=tmp_path / "session.log",
2759
- progress_file=progress,
2760
- marker_dir=tmp_path,
2761
- interval_seconds=0.05,
2762
- stale_after_seconds=0.1,
2763
- kill_after_seconds=0.2,
2764
- grace_seconds=0.1,
2765
- ),
2766
- )
2767
- monitor.start()
2768
-
2769
- time.sleep(0.5)
2770
- assert is_process_running(handle)
2771
- assert not (tmp_path / "stale-kill.json").exists()
2772
-
2773
- progress.write_text('{"current_tool":null}\n', encoding="utf-8")
2774
- deadline = time.time() + 3
2775
- while time.time() < deadline and not (tmp_path / "stale-kill.json").exists():
2776
- time.sleep(0.05)
2777
- result = monitor.stop()
2778
-
2779
- marker = json.loads((tmp_path / "stale-kill.json").read_text(encoding="utf-8"))
2780
- assert result.killed is True
2781
- assert result.reason == "stale_session"
2782
- assert marker["reason"] == "stale_session"
2783
-
2784
-
2785
- def test_pi_session_active_tool_stream_survives_stale_threshold(tmp_path, monkeypatch):
2786
- import prizmkit_runtime.sessions as sessions
2787
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
2788
-
2789
- parser_classes = sessions._load_stream_parser_classes()
2790
- monkeypatch.setattr(sessions, "_load_stream_parser_classes", lambda: parser_classes)
2791
-
2792
- fake_cli = tmp_path / "pi_active_tool_cli.py"
2793
- fake_cli.write_text(
2794
- "#!/usr/bin/env python3\n"
2795
- "import json, sys, time\n"
2796
- "_prompt = sys.stdin.read(5)\n"
2797
- "for event in [\n"
2798
- " {'type':'session','id':'active-tool-session'},\n"
2799
- " {'type':'agent_start'},\n"
2800
- " {'type':'turn_start'},\n"
2801
- " {'type':'tool_execution_start','toolCallId':'call-1','toolName':'long-running-tool','args':{}},\n"
2802
- "]:\n"
2803
- " print(json.dumps(event), flush=True)\n"
2804
- "time.sleep(3.0)\n"
2805
- "for event in [\n"
2806
- " {'type':'tool_execution_end','toolCallId':'call-1','toolName':'long-running-tool','result':{'content':[]},'isError':False},\n"
2807
- " {'type':'message_end','message':{'role':'assistant','content':[{'type':'text','text':'done'}],'stopReason':'stop'}},\n"
2808
- " {'type':'agent_end','willRetry':False,'messages':[{'role':'assistant','content':[{'type':'text','text':'done'}],'stopReason':'stop'}]},\n"
2809
- "]:\n"
2810
- " print(json.dumps(event), flush=True)\n",
2811
- encoding="utf-8",
2812
- )
2813
- fake_cli.chmod(0o755)
2814
- prompt = tmp_path / "prompt.md"
2815
- prompt.write_text("hello", encoding="utf-8")
2816
- session_log = tmp_path / "state" / "sessions" / "active-tool" / "logs" / "session.log"
2817
- progress = session_log.with_name("progress.json")
2818
-
2819
- result = AISessionLauncher(
2820
- AISessionConfig(
2821
- cli_command=str(fake_cli),
2822
- platform="pi",
2823
- model=None,
2824
- prompt_path=prompt,
2825
- cwd=tmp_path,
2826
- log_path=session_log,
2827
- progress_path=progress,
2828
- heartbeat_path=session_log.with_name("heartbeat.json"),
2829
- stale_kill_threshold_seconds=1.5,
2830
- heartbeat_stale_threshold_seconds=1.0,
2831
- stale_kill_grace_seconds=0.1,
2832
- live_progress_interval_seconds=0.05,
2833
- )
2834
- ).run()
2835
-
2836
- final_progress = json.loads(progress.read_text(encoding="utf-8"))
2837
- assert result.exit_code == 0
2838
- assert result.termination_reason is None
2839
- assert final_progress["current_tool"] is None
2840
- assert not (session_log.parent / "stale-kill.json").exists()
2841
-
2842
-
2843
- def test_stale_marker_preserves_subsecond_threshold(tmp_path):
2844
- from prizmkit_runtime.heartbeat import write_stale_marker
2845
-
2846
- marker = write_stale_marker(
2847
- tmp_path,
2848
- reason="stale_session",
2849
- stale_seconds=0.4,
2850
- threshold=0.3,
2851
- )
2852
- data = json.loads(marker.read_text(encoding="utf-8"))
2853
-
2854
- assert data["stale_seconds"] == pytest.approx(0.4)
2855
- assert data["threshold"] == pytest.approx(0.3)
2856
-
2857
-
2858
- def test_idle_progress_refresh_updates_child_activity_without_parent_output(tmp_path, monkeypatch):
2859
- import prizmkit_runtime.sessions as sessions
2860
-
2861
- progress = tmp_path / "progress.json"
2862
- tracker_lock = sessions.threading.Lock()
2863
- stop_event = sessions.threading.Event()
2864
-
2865
- class FakeTracker:
2866
- def __init__(self):
2867
- self.calls = 0
2868
-
2869
- def to_dict(self):
2870
- self.calls += 1
2871
- return {
2872
- "message_count": 1,
2873
- "event_type_counts": {},
2874
- "current_tool": "Task",
2875
- "current_phase": "implement",
2876
- "total_tool_calls": 1,
2877
- "subagent_statistics": {"active": 1, "spawned": 1},
2878
- "child_activity_signature": f"child:{self.calls}",
2879
- "child_total_bytes": self.calls,
2880
- "fatal_error_code": "",
2881
- "terminal_result_text": "",
2882
- "errors": [],
2883
- }
2884
-
2885
- thread, refresh = sessions._start_idle_progress_refresh(
2886
- progress,
2887
- FakeTracker(),
2888
- tracker_lock,
2889
- stop_event,
2890
- interval_seconds=0.1,
2891
- )
2892
- try:
2893
- refresh(True)
2894
- first = json.loads(progress.read_text(encoding="utf-8"))
2895
- time.sleep(0.25)
2896
- second = json.loads(progress.read_text(encoding="utf-8"))
2897
- finally:
2898
- stop_event.set()
2899
- thread.join(timeout=1)
2900
-
2901
- assert first["child_activity_signature"].startswith("child:")
2902
- assert second["child_activity_signature"] != first["child_activity_signature"]
2903
- assert second["child_total_bytes"] > first["child_total_bytes"]
2904
-
2905
- def test_compact_live_heartbeat_stays_out_of_primary_and_backup_logs(tmp_path, capsys, monkeypatch):
2906
- import prizmkit_runtime.sessions as sessions
2907
-
2908
- fake_cli = tmp_path / "slow_cli.py"
2909
- fake_cli.write_text(
2910
- "#!/usr/bin/env python3\n"
2911
- "import time\n"
2912
- "print('logged-payload', flush=True)\n"
2913
- "time.sleep(0.45)\n",
2914
- encoding="utf-8",
2915
- )
2916
- fake_cli.chmod(0o755)
2917
- prompt = tmp_path / "prompt.md"
2918
- prompt.write_text("hello", encoding="utf-8")
2919
- session_log = tmp_path / "state" / "sessions" / "sess-heartbeat" / "logs" / "session.log"
2920
- backup_log = tmp_path / "home" / ".prizmkit" / "session-backups" / "sess-heartbeat.log"
2921
- progress = session_log.with_name("progress.json")
2922
- backup_text = {}
2923
- original_recover = sessions.recover_session_log
2924
-
2925
- def spy_recover(primary, backup, min_size=1024):
2926
- if backup.is_file():
2927
- backup_text["content"] = backup.read_text(encoding="utf-8")
2928
- return original_recover(primary, backup, min_size)
2929
-
2930
- monkeypatch.setattr(sessions, "recover_session_log", spy_recover)
2931
- result = sessions.AISessionLauncher(
2932
- sessions.AISessionConfig(
2933
- cli_command=str(fake_cli),
2934
- platform="codebuddy",
2935
- model=None,
2936
- prompt_path=prompt,
2937
- cwd=tmp_path,
2938
- log_path=session_log,
2939
- backup_log_path=backup_log,
2940
- progress_path=progress,
2941
- live_output=True,
2942
- live_progress_interval_seconds=0.1,
2943
- stale_kill_threshold_seconds=15 * 60,
2944
- )
2945
- ).run()
2946
-
2947
- captured = capsys.readouterr()
2948
- primary_text = session_log.read_text(encoding="utf-8")
2949
- assert result.exit_code == 0
2950
- assert "[HEARTBEAT]" in captured.err
2951
- assert "logged-payload" in primary_text
2952
- assert "[HEARTBEAT]" not in primary_text
2953
- assert "stale:" not in primary_text
2954
- assert "[HEARTBEAT]" not in backup_text.get("content", "")
2955
- assert "stale:" not in backup_text.get("content", "")
2956
-
2957
-
2958
- def test_session_summary_reports_normalized_subagents_and_child_liveness(tmp_path, capsys):
2959
- import prizmkit_runtime.runners as runners
2960
- from prizmkit_runtime.runner_models import SessionPaths
2961
-
2962
- logs = tmp_path / "sessions" / "s1" / "logs"
2963
- logs.mkdir(parents=True)
2964
- session_log = logs / "session.log"
2965
- progress = logs / "progress.json"
2966
- session_log.write_text("one\ntwo\n", encoding="utf-8")
2967
- progress.write_text(
2968
- json.dumps({
2969
- "subagent_statistics": {
2970
- "spawned": 2,
2971
- "active": 1,
2972
- "states": [{"status": "running", "count": 1}, {"status": "completed", "count": 1}],
2973
- "providers": ["claude"],
2974
- "source": "session_log",
2975
- },
2976
- "child_total_bytes": 2048,
2977
- "child_session_files": [{"path": "child-a"}],
2978
- }),
2979
- encoding="utf-8",
2980
- )
2981
- paths = SessionPaths(
2982
- session_dir=logs.parent,
2983
- prompt_path=logs.parent / "bootstrap-prompt.md",
2984
- logs_dir=logs,
2985
- session_log=session_log,
2986
- progress_json=progress,
2987
- heartbeat_json=logs / "heartbeat.json",
2988
- session_status_json=logs / "session-status.json",
2989
- )
2990
- result = type("Result", (), {"exit_code": 0})()
2991
- classification = type("Classification", (), {"session_status": "success"})()
2992
-
2993
- runners._emit_session_summary(result, paths, classification)
2994
-
2995
- captured = capsys.readouterr()
2996
- assert "Subagents: spawned=2, active=1, states: running=1, completed=1 (claude; source=session.log)" in captured.err
2997
- assert "Child log activity: 2KB across 1 files (heartbeat liveness only)" in captured.err
2998
- assert "Subagent calls detected" not in captured.err
2999
-
3000
- def test_ai_interruption_diagnostics_are_detailed_console_only(tmp_path, capsys):
3001
- import signal
3002
-
3003
- from prizmkit_runtime.heartbeat import HeartbeatState
3004
- from prizmkit_runtime.processes import (
3005
- ProcessHandle,
3006
- ProcessSpec,
3007
- ProcessTerminationResult,
3008
- RuntimeInterruption,
3009
- )
3010
- from prizmkit_runtime.sessions import (
3011
- AISessionCommand,
3012
- _emit_ai_interruption_received,
3013
- _emit_ai_interruption_termination,
3014
- )
3015
-
3016
- session_log = tmp_path / "sessions" / "sess-interrupt" / "logs" / "session.log"
3017
- session_log.parent.mkdir(parents=True)
3018
- session_log.write_text("session activity\n", encoding="utf-8")
3019
- progress = session_log.with_name("progress.json")
3020
- progress.write_text(
3021
- json.dumps(
3022
- {
3023
- "current_phase": "implement",
3024
- "current_tool": "bash",
3025
- "current_tool_input_summary": "secret-command-must-not-be-logged",
3026
- "message_count": 455,
3027
- "total_tool_calls": 453,
3028
- "subagent_statistics": {"active": 0, "spawned": 0},
3029
- }
3030
- ),
3031
- encoding="utf-8",
3032
- )
3033
- handle = ProcessHandle(
3034
- pid=999_999,
3035
- spec=ProcessSpec(command=("fake-ai",), cwd=tmp_path),
3036
- status="running",
3037
- popen=None,
3038
- )
3039
- command = AISessionCommand(
3040
- argv=("fake-ai",),
3041
- stdin_text=None,
3042
- provider="pi",
3043
- prompt_mode="stdin",
3044
- )
3045
- heartbeat = HeartbeatState(
3046
- last_seen_epoch=time.time() - 1,
3047
- stale=False,
3048
- details="no progress",
3049
- stale_seconds=1.0,
3050
- log_size=2048,
3051
- )
3052
-
3053
- _emit_ai_interruption_received(
3054
- RuntimeInterruption(signal.SIGTERM),
3055
- command=command,
3056
- handle=handle,
3057
- started_epoch=time.time() - 120,
3058
- session_log=session_log,
3059
- progress_path=progress,
3060
- checkpoint_path=None,
3061
- heartbeat_state=heartbeat,
3062
- )
3063
- _emit_ai_interruption_termination(
3064
- ProcessTerminationResult(
3065
- pid=handle.pid,
3066
- reason="interrupted",
3067
- terminated=True,
3068
- forced=False,
3069
- return_code=-15,
3070
- details=("sigterm_process_group",),
3071
- )
3072
- )
3073
-
3074
- captured = capsys.readouterr()
3075
- assert "received trigger=platform_signal; platform_signal=SIGTERM(15)" in captured.err
3076
- assert "runner_pid=" in captured.err
3077
- assert "parent_pid=" in captured.err
3078
- assert "ai_pid=999999" in captured.err
3079
- assert "provider=pi" in captured.err
3080
- assert "phase=implement; tool=bash; messages=455; tool_calls=453" in captured.err
3081
- assert "heartbeat details=no progress; stale=False; age=1s" in captured.err
3082
- assert "process-tree termination completed" in captured.err
3083
- assert "forced=False; return_code=-15; details=sigterm_process_group" in captured.err
3084
- assert "secret-command-must-not-be-logged" not in captured.err
3085
- assert not session_log.with_name("session-status.json").exists()
3086
-
3087
-
3088
- def test_ai_session_interrupt_diagnostics_are_wired_before_existing_cleanup(monkeypatch, tmp_path, capsys):
3089
- import io
3090
-
3091
- from prizmkit_runtime import sessions
3092
- from prizmkit_runtime.processes import ProcessHandle, ProcessTerminationResult
3093
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
3094
-
3095
- prompt = tmp_path / "prompt.md"
3096
- prompt.write_text("hello", encoding="utf-8")
3097
- session_log = tmp_path / "sessions" / "sess-wired" / "logs" / "session.log"
3098
- termination_calls = []
3099
-
3100
- class InterruptingProcess:
3101
- def __init__(self):
3102
- self.stdout = io.StringIO("")
3103
- self.stdin = io.StringIO()
3104
- self.returncode = -2
3105
-
3106
- def wait(self, timeout=None):
3107
- raise KeyboardInterrupt
3108
-
3109
- def poll(self):
3110
- return self.returncode
3111
-
3112
- process = InterruptingProcess()
3113
-
3114
- def fake_launch(spec, **kwargs):
3115
- return ProcessHandle(pid=777_777, spec=spec, status="running", popen=process)
3116
-
3117
- def fake_terminate(handle, reason, grace_seconds=10):
3118
- termination_calls.append((handle.pid, reason, grace_seconds))
3119
- return ProcessTerminationResult(
3120
- pid=handle.pid,
3121
- reason=reason,
3122
- terminated=True,
3123
- forced=False,
3124
- return_code=process.returncode,
3125
- details=("sigterm_process_group",),
3126
- )
3127
-
3128
- monkeypatch.setattr(sessions, "launch_process", fake_launch)
3129
- monkeypatch.setattr(sessions, "terminate_process_tree", fake_terminate)
3130
-
3131
- with pytest.raises(KeyboardInterrupt):
3132
- AISessionLauncher(
3133
- AISessionConfig(
3134
- cli_command="fake-ai",
3135
- platform="pi",
3136
- model=None,
3137
- prompt_path=prompt,
3138
- cwd=tmp_path,
3139
- log_path=session_log,
3140
- stale_kill_grace_seconds=4,
3141
- )
3142
- ).run()
3143
-
3144
- captured = capsys.readouterr()
3145
- assert termination_calls == [(777_777, "interrupted", 4)]
3146
- assert "received trigger=keyboard_interrupt; platform_signal=SIGINT(2) (inferred)" in captured.err
3147
- assert "ai_pid=777777" in captured.err
3148
- assert "classification and retry accounting have not run for this AI session" in captured.err
3149
- assert "process-tree termination completed pid=777777" in captured.err
3150
- assert not session_log.with_name("session-status.json").exists()
3151
-
3152
-
3153
- def test_session_live_output_does_not_forward_cli_output_without_verbose(tmp_path, capsys):
3154
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
3155
-
3156
- fake_cli = tmp_path / "quiet_cli.py"
3157
- fake_cli.write_text(
3158
- "#!/usr/bin/env python3\n"
3159
- "print('hidden-line', flush=True)\n",
3160
- encoding="utf-8",
3161
- )
3162
- fake_cli.chmod(0o755)
3163
- prompt = tmp_path / "prompt.md"
3164
- prompt.write_text("hello", encoding="utf-8")
3165
- session_log = tmp_path / "state" / "sessions" / "sess-quiet" / "logs" / "session.log"
3166
-
3167
- result = AISessionLauncher(
3168
- AISessionConfig(
3169
- cli_command=str(fake_cli),
3170
- platform="codebuddy",
3171
- model=None,
3172
- prompt_path=prompt,
3173
- cwd=tmp_path,
3174
- log_path=session_log,
3175
- live_output=True,
3176
- )
3177
- ).run()
3178
-
3179
- captured = capsys.readouterr()
3180
- assert result.exit_code == 0
3181
- assert "hidden-line" not in captured.out
3182
- assert "hidden-line" in session_log.read_text(encoding="utf-8")
3183
- assert "[prizmkit] AI session started" in captured.err
3184
- assert "[prizmkit] AI session finished" in captured.err
3185
-
3186
-
3187
- def test_session_final_progress_merge_preserves_tracker_fatal_error(tmp_path):
3188
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
3189
-
3190
- fake_cli = tmp_path / "context_cli.py"
3191
- fake_cli.write_text(
3192
- "#!/usr/bin/env python3\n"
3193
- "import json\n"
3194
- "print(json.dumps({'type':'result','is_error':True,'result':'API Error: Your input exceeds the context window'}), flush=True)\n",
3195
- encoding="utf-8",
3196
- )
3197
- fake_cli.chmod(0o755)
3198
- prompt = tmp_path / "prompt.md"
3199
- prompt.write_text("hello", encoding="utf-8")
3200
- session_log = tmp_path / "state" / "sessions" / "sess-context" / "logs" / "session.log"
3201
- progress = session_log.with_name("progress.json")
3202
-
3203
- result = AISessionLauncher(
3204
- AISessionConfig(
3205
- cli_command=str(fake_cli),
3206
- platform="codebuddy",
3207
- model=None,
3208
- prompt_path=prompt,
3209
- cwd=tmp_path,
3210
- log_path=session_log,
3211
- progress_path=progress,
3212
- )
3213
- ).run()
3214
-
3215
- progress_data = json.loads(progress.read_text(encoding="utf-8"))
3216
- assert result.progress_summary.fatal_error_code == "context_overflow"
3217
- assert result.fatal_error_code == "context_overflow"
3218
- assert progress_data["fatal_error_code"] == "context_overflow"
1625
+ assert "not authorized" in reasons["example"]
1626
+ assert "executable not found" in reasons["missing"]
1627
+ assert "Do not read, create, edit, or delete project files" in module.smoke_prompt()
1628
+ assert module._looks_capability_blocked("login required") is True
1629
+ assert module._looks_capability_blocked("network is unreachable") is True
1630
+ assert module._looks_capability_blocked("model not found") is True
1631
+ assert module._looks_capability_blocked("ordinary tool failure") is False
3219
1632
 
3220
1633
 
3221
- def test_session_unsets_claudecode_and_merges_stderr_order(tmp_path, monkeypatch):
3222
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
1634
+ def test_session_dual_writes_progress_and_recovers_backup(tmp_path):
1635
+ from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher, recover_session_log
3223
1636
 
3224
- fake_cli = tmp_path / "env_cli.py"
1637
+ fake_cli = tmp_path / "fake_cli.py"
3225
1638
  fake_cli.write_text(
3226
1639
  "#!/usr/bin/env python3\n"
3227
- "import os, sys\n"
3228
- "print('stdout-before', flush=True)\n"
3229
- "print('claudecode=' + os.environ.get('CLAUDECODE', '<unset>'), flush=True)\n"
3230
- "print('stderr-after', file=sys.stderr, flush=True)\n",
1640
+ "import json, sys\n"
1641
+ "print(json.dumps({'type':'system','subtype':'init','session_id':'s1'}), flush=True)\n"
1642
+ "print(json.dumps({'type':'result','subtype':'success','stop_reason':'end_turn','usage':{'tokens':1},'result':'ok'}), flush=True)\n",
3231
1643
  encoding="utf-8",
3232
1644
  )
3233
1645
  fake_cli.chmod(0o755)
3234
- monkeypatch.setenv("CLAUDECODE", "1")
3235
1646
  prompt = tmp_path / "prompt.md"
3236
1647
  prompt.write_text("hello", encoding="utf-8")
3237
- session_log = tmp_path / "state" / "sessions" / "sess-env" / "logs" / "session.log"
1648
+ session_log = tmp_path / "state" / "sessions" / "sess-1" / "logs" / "session.log"
1649
+ backup_log = tmp_path / "home" / ".prizmkit" / "session-backups" / "sess-1.log"
1650
+ progress = session_log.with_name("progress.json")
3238
1651
 
3239
1652
  result = AISessionLauncher(
3240
1653
  AISessionConfig(
@@ -3244,13 +1657,29 @@ def test_session_unsets_claudecode_and_merges_stderr_order(tmp_path, monkeypatch
3244
1657
  prompt_path=prompt,
3245
1658
  cwd=tmp_path,
3246
1659
  log_path=session_log,
1660
+ backup_log_path=backup_log,
1661
+ progress_path=progress,
3247
1662
  )
3248
1663
  ).run()
3249
1664
 
3250
- text = session_log.read_text(encoding="utf-8")
3251
1665
  assert result.exit_code == 0
3252
- assert "claudecode=<unset>" in text
3253
- assert text.index("stdout-before") < text.index("stderr-after")
1666
+ assert session_log.exists()
1667
+ assert progress.exists()
1668
+ progress_data = json.loads(progress.read_text(encoding="utf-8"))
1669
+ assert progress_data["event_type_counts"]["result"] == 1
1670
+ assert progress_data["claude_session_id"] == "s1"
1671
+ assert progress_data["has_usage"] is True
1672
+ assert result.log_recovery is not None
1673
+
1674
+ second_backup = tmp_path / "backup.log"
1675
+ second_log = tmp_path / "main.log"
1676
+ second_log.write_text("tiny", encoding="utf-8")
1677
+ second_backup.write_text("larger recovered log", encoding="utf-8")
1678
+ recovery = recover_session_log(second_log, second_backup)
1679
+ assert recovery.recovered is True
1680
+ assert recovery.cleaned_backup is True
1681
+ assert not second_backup.exists()
1682
+ assert second_log.read_text(encoding="utf-8") == "larger recovered log"
3254
1683
 
3255
1684
 
3256
1685
  def test_heartbeat_fatal_error_writes_shell_compatible_markers(tmp_path):
@@ -3293,7 +1722,6 @@ def test_heartbeat_fatal_error_writes_shell_compatible_markers(tmp_path):
3293
1722
  assert stale["reason"] == "context_overflow"
3294
1723
 
3295
1724
 
3296
-
3297
1725
  from prizmkit_runtime.heartbeat import HeartbeatConfig, write_stale_marker
3298
1726
  from prizmkit_runtime.processes import ProcessSpec, platform_termination_strategy, run_process_with_capture
3299
1727
 
@@ -3317,18 +1745,16 @@ def test_heartbeat_fatal_error_writes_shell_compatible_markers(tmp_path):
3317
1745
  assert HeartbeatConfig(heartbeat_file=tmp_path / "heartbeat").interval_seconds == 30
3318
1746
 
3319
1747
 
3320
- def test_git_branch_worktree_plans_preserve_shell_invariants(tmp_path):
1748
+ def test_git_branch_plans_preserve_shell_invariants(tmp_path):
3321
1749
  from prizmkit_runtime.gitops import (
3322
1750
  BranchContext,
3323
1751
  GitCommandResult,
3324
1752
  GitPlanResult,
3325
- WorktreePolicy,
3326
1753
  branch_create_plan,
3327
1754
  branch_ensure_return_plan,
3328
1755
  branch_merge_plan,
3329
1756
  branch_save_wip,
3330
1757
  branch_save_wip_plan,
3331
- worktree_add_plan,
3332
1758
  )
3333
1759
 
3334
1760
  context = BranchContext(base_branch="main", working_branch="dev/example", project_root=tmp_path)
@@ -3336,7 +1762,6 @@ def test_git_branch_worktree_plans_preserve_shell_invariants(tmp_path):
3336
1762
  merge = branch_merge_plan(context, auto_push=True)
3337
1763
  save_wip = branch_save_wip_plan(context)
3338
1764
  ensure = branch_ensure_return_plan(context)
3339
- worktree = worktree_add_plan(context, WorktreePolicy(True, cleanup_on_success=False, preserve_on_failure=True))
3340
1765
 
3341
1766
  assert create.name == "branch_create"
3342
1767
  assert any(command.args[:2] == ("checkout", "-b") for command in create.commands)
@@ -3361,7 +1786,6 @@ def test_git_branch_worktree_plans_preserve_shell_invariants(tmp_path):
3361
1786
  if command.args[:2] == ("add", "-A")
3362
1787
  for arg in command.args
3363
1788
  )
3364
- assert worktree.commands[0].args[:2] == ("worktree", "add")
3365
1789
 
3366
1790
  allowed_failure_result = GitPlanResult(
3367
1791
  plan=create,
@@ -3388,9 +1812,11 @@ def test_git_branch_worktree_plans_preserve_shell_invariants(tmp_path):
3388
1812
 
3389
1813
 
3390
1814
  def test_runtime_source_constructs_no_git_stash_commands():
3391
- runtime = Path("dev-pipeline/prizmkit_runtime")
1815
+ runtime = PIPELINE_ROOT / "prizmkit_runtime"
1816
+ source_files = sorted(runtime.glob("*.py"))
1817
+ assert source_files
3392
1818
  matches = []
3393
- for path in runtime.glob("*.py"):
1819
+ for path in source_files:
3394
1820
  text = path.read_text(encoding="utf-8")
3395
1821
  if re.search(r'["\']stash["\']', text):
3396
1822
  matches.append(path.as_posix())
@@ -4261,122 +2687,6 @@ def test_non_current_reset_preserves_dirty_workspace_and_user_stashes(tmp_path):
4261
2687
  assert _stash_oids(tmp_path) == user_stashes
4262
2688
 
4263
2689
 
4264
- def test_worktree_runtime_context_uses_safe_deterministic_path(tmp_path):
4265
- from prizmkit_runtime.gitops import BranchContext, WorktreePolicy, worktree_runtime_context
4266
-
4267
- context = BranchContext(base_branch="main", working_branch="dev/F-001-example", project_root=tmp_path / "repo")
4268
- policy = WorktreePolicy(
4269
- use_worktree=True,
4270
- cleanup_on_success=True,
4271
- preserve_on_failure=False,
4272
- worktree_root=tmp_path / "state" / "worktrees",
4273
- )
4274
-
4275
- runtime = worktree_runtime_context(context, policy)
4276
-
4277
- assert runtime.worktree_root == (tmp_path / "state" / "worktrees").resolve()
4278
- assert runtime.worktree_path == runtime.worktree_root / "dev-F-001-example"
4279
- assert runtime.sentinel_path == runtime.worktree_path / ".prizmkit-worktree"
4280
- assert runtime.is_cleanup_path_safe() is True
4281
-
4282
- unsafe = runtime.__class__(
4283
- context=context,
4284
- policy=policy,
4285
- worktree_root=runtime.worktree_root,
4286
- worktree_path=tmp_path / "other" / "dev-F-001-example",
4287
- sentinel_path=tmp_path / "other" / "dev-F-001-example" / ".prizmkit-worktree",
4288
- )
4289
- assert unsafe.is_cleanup_path_safe() is False
4290
-
4291
-
4292
- def test_linked_worktree_plans_create_branch_without_checkout_and_cleanup_after_merge(tmp_path):
4293
- from prizmkit_runtime.gitops import (
4294
- BranchContext,
4295
- WorktreePolicy,
4296
- linked_worktree_setup_plan,
4297
- worktree_merge_plan,
4298
- worktree_remove_plan,
4299
- worktree_runtime_context,
4300
- )
4301
-
4302
- context = BranchContext(base_branch="main", working_branch="dev/F-001-example", project_root=tmp_path / "repo")
4303
- policy = WorktreePolicy(True, cleanup_on_success=True, preserve_on_failure=False, worktree_root=tmp_path / "worktrees")
4304
- runtime = worktree_runtime_context(context, policy)
4305
-
4306
- setup = linked_worktree_setup_plan(runtime)
4307
- merge = worktree_merge_plan(runtime, auto_push=True)
4308
- remove = worktree_remove_plan(runtime, delete_branch=True)
4309
-
4310
- assert setup.name == "linked_worktree_setup"
4311
- assert setup.commands[0].args[:2] == ("rev-parse", "--verify")
4312
- assert setup.commands[1].args[:4] == ("branch", context.working_branch, context.base_branch,)
4313
- assert setup.commands[2].args[:2] == ("worktree", "list")
4314
- assert setup.commands[3].args[:3] == ("worktree", "add", "--checkout")
4315
- assert all(command.args[0] != "checkout" for command in setup.commands)
4316
- assert setup.require_one_success == ((0, 1),)
4317
-
4318
- assert merge.commands[0].args[:2] == ("rebase", context.base_branch)
4319
- assert merge.commands[1].args == ("merge", "--ff-only", context.working_branch)
4320
- assert merge.commands[2].args == ("push",)
4321
- assert remove.commands[0].args[:2] == ("worktree", "remove")
4322
- assert remove.commands[1].args == ("branch", "-d", context.working_branch)
4323
-
4324
-
4325
- def test_guarded_worktree_removal_refuses_unregistered_or_unsafe_paths(monkeypatch, tmp_path):
4326
- from prizmkit_runtime.gitops import (
4327
- BranchContext,
4328
- GitCommandResult,
4329
- WorktreePolicy,
4330
- guarded_worktree_remove,
4331
- worktree_runtime_context,
4332
- )
4333
-
4334
- context = BranchContext(base_branch="main", working_branch="dev/F-001-example", project_root=tmp_path / "repo")
4335
- runtime = worktree_runtime_context(
4336
- context,
4337
- WorktreePolicy(True, cleanup_on_success=True, preserve_on_failure=False, worktree_root=tmp_path / "worktrees"),
4338
- )
4339
- runtime.worktree_path.mkdir(parents=True)
4340
-
4341
- calls = []
4342
-
4343
- def fake_run(project_root, args):
4344
- calls.append(tuple(args))
4345
- if tuple(args)[:2] == ("worktree", "list"):
4346
- return GitCommandResult(tuple(args), 0, "", "")
4347
- return GitCommandResult(tuple(args), 0, "", "")
4348
-
4349
- monkeypatch.setattr("prizmkit_runtime.gitops.run_git_command", fake_run)
4350
- result = guarded_worktree_remove(runtime, delete_branch=True)
4351
-
4352
- assert result.ok is False
4353
- assert result.reason == "missing_worktree_sentinel"
4354
- assert all(call[:2] != ("worktree", "remove") for call in calls)
4355
-
4356
- (runtime.sentinel_path).write_text(context.working_branch, encoding="utf-8")
4357
- calls.clear()
4358
- result = guarded_worktree_remove(runtime, delete_branch=True)
4359
-
4360
- assert result.ok is False
4361
- assert result.reason == "worktree_not_registered"
4362
- assert all(call[:2] != ("worktree", "remove") for call in calls)
4363
- calls.clear()
4364
-
4365
- def registered_run(project_root, args):
4366
- calls.append(tuple(args))
4367
- if tuple(args)[:2] == ("worktree", "list"):
4368
- return GitCommandResult(tuple(args), 0, str(runtime.worktree_path) + " abc [dev/F-001-example]\n", "")
4369
- return GitCommandResult(tuple(args), 0, "", "")
4370
-
4371
- monkeypatch.setattr("prizmkit_runtime.gitops.run_git_command", registered_run)
4372
- result = guarded_worktree_remove(runtime, delete_branch=True)
4373
-
4374
- assert result.ok is True
4375
- assert ("worktree", "remove", "--force", str(runtime.worktree_path)) in calls
4376
- assert ("branch", "-d", context.working_branch) in calls
4377
-
4378
-
4379
-
4380
2690
  def test_git_status_safe_ignores_worktree_support_assets(monkeypatch, tmp_path):
4381
2691
  from prizmkit_runtime.gitops import HIDDEN_TOOL_WORKTREE_EXCLUDES, git_status_safe
4382
2692
 
@@ -4497,7 +2807,7 @@ def test_preflight_ready_commit_skips_clean_workspace(tmp_path):
4497
2807
  _init_temp_repo(repo)
4498
2808
  before = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
4499
2809
 
4500
- result = commit_preflight_ready_changes(repo, "R-003")
2810
+ result = commit_preflight_ready_changes(repo, "F-003")
4501
2811
 
4502
2812
  after = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
4503
2813
  assert not result.attempted
@@ -4604,147 +2914,52 @@ def test_preflight_ready_commit_force_stages_visible_file_when_prizmkit_dir_is_i
4604
2914
  assert _short_status(repo) == ""
4605
2915
 
4606
2916
 
4607
- def test_materialize_worktree_support_assets_copies_ignored_assets_without_retired_shell_sources(tmp_path):
4608
- from prizmkit_runtime.gitops import (
4609
- BranchContext,
4610
- WorktreePolicy,
4611
- ensure_linked_worktree,
4612
- guarded_worktree_remove,
4613
- materialize_worktree_support_assets,
4614
- worktree_runtime_context,
4615
- )
4616
-
4617
- repo = tmp_path / "repo"
4618
- _init_temp_repo(repo)
4619
- (repo / ".gitignore").write_text(".claude/\n.prizmkit/\n", encoding="utf-8")
4620
- subprocess.run(["git", "add", ".gitignore"], cwd=repo, check=True)
4621
- subprocess.run(["git", "commit", "-m", "ignore support"], cwd=repo, check=True, stdout=subprocess.DEVNULL)
4622
-
4623
- (repo / ".claude" / "commands").mkdir(parents=True)
4624
- (repo / ".claude" / "commands" / "prizmkit.md").write_text("skill", encoding="utf-8")
4625
- (repo / ".prizmkit" / "prizm-docs").mkdir(parents=True)
4626
- (repo / ".prizmkit" / "prizm-docs" / "root.prizm").write_text("PRIZM_VERSION: 1\n", encoding="utf-8")
4627
- (repo / ".prizmkit" / "config.json").write_text("{}", encoding="utf-8")
4628
- (repo / ".prizmkit" / "manifest.json").write_text("{}", encoding="utf-8")
4629
- (repo / ".prizmkit" / "dev-pipeline" / "scripts").mkdir(parents=True)
4630
- (repo / ".prizmkit" / "dev-pipeline" / "scripts" / "update-checkpoint.py").write_text("# update", encoding="utf-8")
4631
- (repo / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime").mkdir(parents=True)
4632
- (repo / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime" / "__init__.py").write_text("", encoding="utf-8")
4633
- (repo / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime" / "runtime_helper.py").write_text("# helper", encoding="utf-8")
4634
- (repo / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime" / "task_checkout.py").write_text("# checkout", encoding="utf-8")
4635
- (repo / ".prizmkit" / "dev-pipeline" / "run-feature.sh").write_text("retired", encoding="utf-8")
4636
-
4637
- runtime = worktree_runtime_context(
4638
- BranchContext("main", "dev/support-assets", repo),
4639
- WorktreePolicy(True, cleanup_on_success=True, preserve_on_failure=True, worktree_root=tmp_path / "worktrees"),
4640
- )
4641
- setup = ensure_linked_worktree(runtime)
4642
- assert setup.ok
4643
- assert not (runtime.worktree_path / ".claude" / "commands" / "prizmkit.md").exists()
4644
-
4645
- result = materialize_worktree_support_assets(runtime)
4646
-
4647
- assert result.ok
4648
- assert (runtime.worktree_path / ".claude" / "commands" / "prizmkit.md").is_file()
4649
- assert (runtime.worktree_path / ".prizmkit" / "prizm-docs" / "root.prizm").is_file()
4650
- assert (runtime.worktree_path / ".prizmkit" / "config.json").is_file()
4651
- assert (runtime.worktree_path / ".prizmkit" / "manifest.json").is_file()
4652
- assert (runtime.worktree_path / ".prizmkit" / "dev-pipeline" / "scripts" / "update-checkpoint.py").is_file()
4653
- assert (runtime.worktree_path / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime" / "__init__.py").is_file()
4654
- assert (runtime.worktree_path / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime" / "runtime_helper.py").is_file()
4655
- assert (runtime.worktree_path / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime" / "task_checkout.py").is_file()
4656
- assert not (runtime.worktree_path / ".prizmkit" / "dev-pipeline" / "run-feature.sh").exists()
4657
-
4658
- assert guarded_worktree_remove(runtime, delete_branch=False).ok
4659
-
4660
-
4661
- def test_linked_worktree_rejects_dirty_tracked_prizmkit_config(tmp_path):
4662
- from prizmkit_runtime.gitops import (
4663
- BranchContext,
4664
- WorktreePolicy,
4665
- branch_fast_forward_possible,
4666
- ensure_linked_worktree,
4667
- guarded_worktree_remove,
4668
- merge_linked_worktree,
4669
- 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,
4670
2924
  )
4671
2925
 
4672
- repo = tmp_path / "repo"
4673
- _init_temp_repo(repo)
4674
- config = repo / ".prizmkit" / "config.json"
4675
- config.parent.mkdir(parents=True)
4676
- config.write_text('{"mode":"base"}\n', encoding="utf-8")
4677
- subprocess.run(["git", "add", ".prizmkit/config.json"], cwd=repo, check=True)
4678
- subprocess.run(
4679
- ["git", "commit", "-m", "track internal config"],
4680
- cwd=repo,
4681
- check=True,
4682
- stdout=subprocess.DEVNULL,
4683
- )
4684
- runtime = worktree_runtime_context(
4685
- BranchContext("main", "dev/internal-dirt", repo),
4686
- WorktreePolicy(
4687
- True,
4688
- cleanup_on_success=True,
4689
- preserve_on_failure=True,
4690
- 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
+ }
4691
2940
  ),
2941
+ encoding="utf-8",
4692
2942
  )
4693
- assert ensure_linked_worktree(runtime).ok
4694
- (runtime.worktree_path / "feature.txt").write_text("done\n", encoding="utf-8")
4695
- subprocess.run(["git", "add", "feature.txt"], cwd=runtime.worktree_path, check=True)
4696
- subprocess.run(
4697
- ["git", "commit", "-m", "feature"],
4698
- cwd=runtime.worktree_path,
4699
- check=True,
4700
- stdout=subprocess.DEVNULL,
4701
- )
4702
- worktree_config = runtime.worktree_path / ".prizmkit" / "config.json"
4703
- worktree_config.write_text('{"mode":"session-local"}\n', encoding="utf-8")
4704
-
4705
- assert branch_fast_forward_possible(repo, runtime.context) is True
4706
- result = merge_linked_worktree(runtime)
2943
+ with pytest.raises(TaskCheckoutError, match="retired worktree checkout mode"):
2944
+ load_task_checkout(state_dir, "feature", "F-001")
4707
2945
 
4708
- assert result.ok is False
4709
- assert result.reason == "dirty_task_checkout"
4710
- assert not (repo / "feature.txt").exists()
4711
- assert json.loads(worktree_config.read_text(encoding="utf-8"))["mode"] == "session-local"
4712
- worktree_config.write_text('{"mode":"base"}\n', encoding="utf-8")
4713
- assert guarded_worktree_remove(runtime, delete_branch=True).ok
4714
-
4715
-
4716
- def test_worktree_terminal_failure_wip_commit_preserves_dirty_changes_before_cleanup(tmp_path):
4717
- from prizmkit_runtime.gitops import (
4718
- BranchContext,
4719
- WorktreePolicy,
4720
- ensure_linked_worktree,
4721
- guarded_worktree_remove,
4722
- worktree_runtime_context,
4723
- worktree_save_wip,
4724
- )
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
+ )
4725
2954
 
4726
- repo = tmp_path / "repo"
4727
- _init_temp_repo(repo)
4728
- runtime = worktree_runtime_context(
4729
- BranchContext("main", "dev/crashed-work", repo),
4730
- 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,
4731
2961
  )
4732
- setup = ensure_linked_worktree(runtime)
4733
- assert setup.ok
4734
-
4735
- (runtime.worktree_path / "dirty.txt").write_text("dirty work\n", encoding="utf-8")
4736
- save = worktree_save_wip(runtime)
4737
- assert save.ok
4738
- assert any(result.args and result.args[0] == "commit" and result.return_code == 0 for result in save.results)
4739
-
4740
- removal = guarded_worktree_remove(runtime, delete_branch=False)
4741
- assert removal.ok
4742
- assert not runtime.worktree_path.exists()
4743
-
4744
- branches = subprocess.run(["git", "branch", "--list", "dev/crashed-work"], cwd=repo, check=True, stdout=subprocess.PIPE, text=True).stdout
4745
- assert "dev/crashed-work" in branches
4746
- show = subprocess.run(["git", "show", "dev/crashed-work:dirty.txt"], cwd=repo, check=True, stdout=subprocess.PIPE, text=True).stdout
4747
- assert show == "dirty work\n"
2962
+ assert valid.checkout_mode == CHECKOUT_MODE_BRANCH
4748
2963
 
4749
2964
 
4750
2965
  def test_daemon_status_cli_preserves_pure_json_stdout(tmp_path):
@@ -5139,3 +3354,272 @@ def test_cursor_support_is_hidden_but_tracked_project_configuration_is_committab
5139
3354
  assert ".cursor/rules/user-owned.mdc" in safe_status
5140
3355
  assert ".cursor/skills/prizmkit/SKILL.md" not in safe_status
5141
3356
 
3357
+
3358
+ def test_antigravity_stream_json_progress_and_semantic_log_contract(tmp_path):
3359
+ parser = _load_progress_parser_module()
3360
+ tracker = parser.ProgressTracker(tmp_path / "session.log", provider_hint="antigravity")
3361
+ normalizer = parser.SemanticLogNormalizer()
3362
+ events = [
3363
+ {"event": "init", "conversation_id": "agy-conv-1", "model": "gemini-pro"},
3364
+ {
3365
+ "event": "step_update",
3366
+ "conversation_id": "agy-conv-1",
3367
+ "step_update": {
3368
+ "step_index": 1,
3369
+ "step_type": "thinking",
3370
+ "state": "RUNNING",
3371
+ "thinking_delta": "Inspecting module...",
3372
+ },
3373
+ },
3374
+ {
3375
+ "event": "step_update",
3376
+ "conversation_id": "agy-conv-1",
3377
+ "step_update": {"step_index": 1, "step_type": "thinking", "state": "DONE"},
3378
+ },
3379
+ {
3380
+ "event": "step_update",
3381
+ "conversation_id": "agy-conv-1",
3382
+ "step_update": {
3383
+ "step_index": 2,
3384
+ "step_type": "tool",
3385
+ "state": "RUNNING",
3386
+ "tool_info": {
3387
+ "name": "write_to_file",
3388
+ "parameters": {"TargetFile": "app.py", "CodeContent": "print('secret body')\n"},
3389
+ },
3390
+ },
3391
+ },
3392
+ {
3393
+ "event": "step_update",
3394
+ "conversation_id": "agy-conv-1",
3395
+ "step_update": {
3396
+ "step_index": 2,
3397
+ "step_type": "tool",
3398
+ "state": "DONE",
3399
+ "tool_info": {
3400
+ "name": "write_to_file",
3401
+ "parameters": {"TargetFile": "app.py"},
3402
+ "output": {"content": "wrote file successfully"},
3403
+ },
3404
+ },
3405
+ },
3406
+ {
3407
+ "event": "step_update",
3408
+ "conversation_id": "agy-conv-1",
3409
+ "step_update": {
3410
+ "step_index": 3,
3411
+ "step_type": "tool",
3412
+ "state": "DONE",
3413
+ "tool_info": {
3414
+ "name": "invoke_subagent",
3415
+ "parameters": {"prompt": "audit"},
3416
+ "output": "verified",
3417
+ },
3418
+ },
3419
+ },
3420
+ {
3421
+ "event": "step_update",
3422
+ "conversation_id": "agy-conv-1",
3423
+ "step_update": {
3424
+ "step_index": 4,
3425
+ "step_type": "agent_response",
3426
+ "state": "RUNNING",
3427
+ "text_delta": "Implementation ",
3428
+ },
3429
+ },
3430
+ {
3431
+ "event": "step_update",
3432
+ "conversation_id": "agy-conv-1",
3433
+ "step_update": {
3434
+ "step_index": 4,
3435
+ "step_type": "agent_response",
3436
+ "state": "DONE",
3437
+ "text_delta": "complete.",
3438
+ },
3439
+ },
3440
+ {
3441
+ "event": "result",
3442
+ "conversation_id": "agy-conv-1",
3443
+ "result": {"status": "success", "response": "Done", "usage": {"total_tokens": 120}},
3444
+ },
3445
+ ]
3446
+
3447
+ rendered = ""
3448
+ for event in events:
3449
+ tracker.process_event(event)
3450
+ rendered += normalizer.process_event(event)
3451
+ rendered += normalizer.finish()
3452
+ data = tracker.to_dict()
3453
+
3454
+ assert data["event_format"] == "antigravity-stream-json"
3455
+ assert data["antigravity_session_id"] == "agy-conv-1"
3456
+ assert data["claude_session_id"] == ""
3457
+ assert data["cursor_session_id"] == ""
3458
+ assert data["result_subtype"] == "success"
3459
+ assert data["has_usage"] is True
3460
+ assert data["total_tool_calls"] == 2
3461
+ tool_counts = {item["name"]: item["count"] for item in data["tool_calls"]}
3462
+ assert tool_counts["write_to_file"] == 1
3463
+ assert tool_counts["invoke_subagent"] == 1
3464
+ assert data["subagent_statistics"]["spawned"] == 1
3465
+ assert data["terminal_result_text"] == "Done"
3466
+ assert "[THINK] Inspecting module..." in rendered
3467
+ assert "[ACTION] write_to_file" in rendered
3468
+ assert "[OBSERVATION] write_to_file" in rendered
3469
+ assert "<21 chars>" in rendered
3470
+ assert "[FINAL] Implementation complete." in rendered
3471
+ assert "[SESSION_END] status=success" in rendered
3472
+
3473
+
3474
+ def test_antigravity_stream_errors_and_malformed_lines_fail_safely(tmp_path):
3475
+ from prizmkit_runtime.sessions import parse_stream_progress_lines
3476
+
3477
+ parser = _load_progress_parser_module()
3478
+ tracker = parser.ProgressTracker(tmp_path / "session.log", provider_hint="antigravity")
3479
+ tracker.process_event({"event": "init", "conversation_id": "agy-err-1"})
3480
+ tracker.process_event({
3481
+ "event": "step_update",
3482
+ "step_update": {
3483
+ "step_index": 1,
3484
+ "step_type": "tool",
3485
+ "state": "ERROR",
3486
+ "tool_info": {
3487
+ "name": "run_command",
3488
+ "parameters": {"CommandLine": "rm -rf /"},
3489
+ "error": "permission denied by user policy",
3490
+ },
3491
+ },
3492
+ })
3493
+ tracker.process_event({
3494
+ "event": "error",
3495
+ "error": {"code": "rate_limit_exceeded", "message": "API rate limit exceeded"},
3496
+ })
3497
+ data = tracker.to_dict()
3498
+ assert data["event_format"] == "antigravity-stream-json"
3499
+ assert data["antigravity_session_id"] == "agy-err-1"
3500
+ assert data["current_tool"] is None
3501
+ assert data["permission_denial_count"] >= 1
3502
+ assert any("rate limit exceeded" in str(item).lower() for item in data["errors"])
3503
+ assert data["result_subtype"] == ""
3504
+
3505
+ tracker.process_event({
3506
+ "event": "error",
3507
+ "error": {
3508
+ "code": "context_length_exceeded",
3509
+ "message": "Prompt is too long: maximum context length exceeded",
3510
+ },
3511
+ })
3512
+ overflow_data = tracker.to_dict()
3513
+ assert overflow_data["fatal_error_code"] != ""
3514
+ assert overflow_data["last_result_is_error"] is True
3515
+
3516
+ summary = parse_stream_progress_lines((
3517
+ "not-json",
3518
+ json.dumps({"event": "init", "conversation_id": "agy-err-summary"}),
3519
+ json.dumps({
3520
+ "event": "result",
3521
+ "result": {"status": "error", "error": {"message": "permission denied", "code": "denied"}},
3522
+ }),
3523
+ ), provider_hint="antigravity")
3524
+ assert summary.antigravity_session_id == "agy-err-summary"
3525
+ assert summary.claude_session_id == ""
3526
+ assert summary.result_subtype == "error"
3527
+ assert summary.permission_denial_count >= 1
3528
+
3529
+
3530
+ def test_antigravity_session_launcher_uses_ndjson_stdin_and_task_checkout(tmp_path):
3531
+ from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
3532
+
3533
+ checkout = tmp_path / "checkout"
3534
+ checkout.mkdir()
3535
+ prompt = tmp_path / "prompt.md"
3536
+ prompt_text = "antigravity coordinator prompt " * 500
3537
+ prompt.write_text(prompt_text, encoding="utf-8")
3538
+ fake_agy = tmp_path / "agy"
3539
+ fake_agy.write_text(
3540
+ "#!/usr/bin/env python3\n"
3541
+ "import json, pathlib, sys\n"
3542
+ "pathlib.Path('agy-argv.json').write_text(json.dumps(sys.argv[1:]))\n"
3543
+ "line = sys.stdin.readline()\n"
3544
+ "pathlib.Path('agy-stdin.txt').write_text(line)\n"
3545
+ "print(json.dumps({'event':'init','conversation_id':'agy-live','model':'fake-model'}), flush=True)\n"
3546
+ "print(json.dumps({'event':'result','conversation_id':'agy-live','result':{'status':'success','response':'ok'}}), flush=True)\n",
3547
+ encoding="utf-8",
3548
+ )
3549
+ fake_agy.chmod(0o755)
3550
+ session_log = tmp_path / "session.log"
3551
+ progress = tmp_path / "progress.json"
3552
+
3553
+ result = AISessionLauncher(
3554
+ AISessionConfig(
3555
+ cli_command=str(fake_agy),
3556
+ platform="antigravity",
3557
+ model="fake-model",
3558
+ effort="xhigh",
3559
+ prompt_path=prompt,
3560
+ cwd=checkout,
3561
+ log_path=session_log,
3562
+ progress_path=progress,
3563
+ use_stream_json=True,
3564
+ )
3565
+ ).run()
3566
+
3567
+ argv = json.loads((checkout / "agy-argv.json").read_text(encoding="utf-8"))
3568
+ assert argv == [
3569
+ "--dangerously-skip-permissions",
3570
+ "--input-format",
3571
+ "stream-json",
3572
+ "--output-format",
3573
+ "stream-json",
3574
+ "--model",
3575
+ "fake-model",
3576
+ "--effort",
3577
+ "xhigh",
3578
+ ]
3579
+ assert prompt_text not in json.dumps(argv)
3580
+ stdin_msg = json.loads((checkout / "agy-stdin.txt").read_text(encoding="utf-8"))
3581
+ assert stdin_msg == {"event": "user", "message": {"content": prompt_text}}
3582
+ assert result.exit_code == 0
3583
+ assert result.progress_summary.result_subtype == "success"
3584
+ assert result.progress_summary.antigravity_session_id == "agy-live"
3585
+ assert result.progress_summary.claude_session_id == ""
3586
+ assert "antigravity coordinator prompt" not in session_log.read_text(encoding="utf-8")
3587
+
3588
+
3589
+ def test_antigravity_support_is_hidden_but_tracked_agents_config_is_committable(tmp_path):
3590
+ from prizmkit_runtime.gitops import (
3591
+ HIDDEN_TOOL_WORKTREE_EXCLUDES,
3592
+ WORKTREE_PLATFORM_SUPPORT_DIRS,
3593
+ git_status_safe,
3594
+ visible_task_paths,
3595
+ )
3596
+
3597
+ assert ".agents" in WORKTREE_PLATFORM_SUPPORT_DIRS
3598
+ assert ":(top,exclude).agents" in HIDDEN_TOOL_WORKTREE_EXCLUDES
3599
+ assert ":(top,exclude,glob).agents/**" in HIDDEN_TOOL_WORKTREE_EXCLUDES
3600
+
3601
+ project = tmp_path / "project"
3602
+ project.mkdir()
3603
+ subprocess.run(["git", "init", "-q"], cwd=project, check=True)
3604
+ subprocess.run(["git", "config", "user.name", "Test User"], cwd=project, check=True)
3605
+ subprocess.run(["git", "config", "user.email", "test@example.invalid"], cwd=project, check=True)
3606
+ tracked_plugin = project / ".agents" / "plugins" / "custom-user" / "plugin.json"
3607
+ tracked_plugin.parent.mkdir(parents=True)
3608
+ tracked_plugin.write_text('{"name":"custom"}\n', encoding="utf-8")
3609
+ subprocess.run(["git", "add", ".agents/plugins/custom-user/plugin.json"], cwd=project, check=True)
3610
+ subprocess.run(["git", "commit", "-qm", "fixture"], cwd=project, check=True)
3611
+
3612
+ tracked_plugin.write_text('{"name":"custom","version":"2"}\n', encoding="utf-8")
3613
+ materialized = project / ".agents" / "plugins" / "prizmkit" / "skills" / "prizmkit" / "SKILL.md"
3614
+ materialized.parent.mkdir(parents=True)
3615
+ materialized.write_text("support\n", encoding="utf-8")
3616
+
3617
+ paths, result = visible_task_paths(project)
3618
+ assert result.return_code == 0
3619
+ assert ".agents/plugins/custom-user/plugin.json" in paths
3620
+ assert ".agents/plugins/prizmkit/skills/prizmkit/SKILL.md" not in paths
3621
+ safe_status = git_status_safe(project)
3622
+ assert ".agents/plugins/custom-user/plugin.json" in safe_status
3623
+ assert ".agents/plugins/prizmkit/skills/prizmkit/SKILL.md" not in safe_status
3624
+
3625
+