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
@@ -11,6 +11,15 @@ from types import SimpleNamespace
11
11
 
12
12
  import pytest
13
13
 
14
+ from _helpers import (
15
+ _init_bookkeeping_repo,
16
+ _install_runner_session_fakes,
17
+ _make_paths,
18
+ _write_family_plan,
19
+ _write_feature_list,
20
+ _write_semantic_completion_checkpoint,
21
+ )
22
+
14
23
  REPO_ROOT = Path(__file__).resolve().parents[2]
15
24
  PIPELINE_ROOT = REPO_ROOT / "dev-pipeline"
16
25
  CLI_PATH = PIPELINE_ROOT / "cli.py"
@@ -37,45 +46,6 @@ def _load_unix_runtime_snapshot():
37
46
  return json.loads(UNIX_RUNTIME_SNAPSHOT.read_text(encoding="utf-8"))
38
47
 
39
48
 
40
- def _make_paths(tmp_path):
41
- from prizmkit_runtime.paths import resolve_runtime_paths
42
-
43
- project = tmp_path / "project"
44
- (project / ".prizmkit" / "plans").mkdir(parents=True)
45
- return resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=project)
46
-
47
-
48
- def _write_feature_list(paths):
49
- paths.feature_plan.write_text(
50
- json.dumps(
51
- {
52
- "$schema": "dev-pipeline-feature-list-v1",
53
- "project_name": "Fake",
54
- "features": [
55
- {"id": "F-001", "title": "Low", "status": "pending", "priority": "low", "dependencies": []},
56
- {"id": "F-002", "title": "Critical", "status": "pending", "priority": "critical", "dependencies": []},
57
- {"id": "F-003", "title": "Blocked", "status": "pending", "priority": "high", "dependencies": ["F-001"]},
58
- ],
59
- }
60
- ),
61
- encoding="utf-8",
62
- )
63
-
64
-
65
- def _write_family_plan(paths, kind, items):
66
- plan_config = {
67
- "feature": (paths.feature_plan, "features", "dev-pipeline-feature-list-v1"),
68
- "bugfix": (paths.bugfix_plan, "bugs", "dev-pipeline-bug-fix-list-v1"),
69
- "refactor": (paths.refactor_plan, "refactors", "dev-pipeline-refactor-list-v1"),
70
- }
71
- plan_path, list_key, schema = plan_config[kind]
72
- plan_path.write_text(
73
- json.dumps({"$schema": schema, "project_name": "Fake", list_key: items}),
74
- encoding="utf-8",
75
- )
76
- return plan_path
77
-
78
-
79
49
  @pytest.mark.parametrize(
80
50
  ("kind", "item_id", "filename", "list_key", "schema", "item"),
81
51
  [
@@ -99,18 +69,6 @@ def _write_family_plan(paths, kind, items):
99
69
  "acceptance_criteria": ["Prompt validates"], "status": "pending",
100
70
  },
101
71
  ),
102
- (
103
- "refactor", "R-001", "refactor-list.json", "refactors",
104
- "dev-pipeline-refactor-list-v1",
105
- {
106
- "id": "R-001", "title": "Preview Refactor", "description": "Preview only",
107
- "scope": {"files": ["src/example.js"], "modules": ["example"]},
108
- "type": "simplify", "priority": "high", "complexity": "low",
109
- "behavior_preservation": {"strategy": "test-gate", "existing_tests": True},
110
- "acceptance_criteria": ["Prompt validates"],
111
- "dependencies": [], "status": "pending",
112
- },
113
- ),
114
72
  ],
115
73
  )
116
74
  def test_actual_dry_run_is_read_only_and_successful(
@@ -169,7 +127,6 @@ def test_actual_dry_run_is_read_only_and_successful(
169
127
  assert not (project / ".prizmkit" / "state").exists()
170
128
  assert not (project / ".prizmkit" / "specs").exists()
171
129
  assert not (project / ".prizmkit" / "bugfix").exists()
172
- assert not (project / ".prizmkit" / "refactor").exists()
173
130
 
174
131
 
175
132
  def _get_next_result(kind, paths):
@@ -183,138 +140,19 @@ def _get_next_result(kind, paths):
183
140
 
184
141
 
185
142
  def _item_id_from_next_result(kind, result):
186
- key = {"feature": "feature_id", "bugfix": "bug_id", "refactor": "refactor_id"}[kind]
143
+ key = {"feature": "feature_id", "bugfix": "bug_id"}[kind]
187
144
  return result.data[key]
188
145
 
189
146
 
190
- def _write_semantic_completion_checkpoint(project_root, artifact_dir, workflow_type="feature-pipeline"):
191
- contracts = {
192
- "feature-pipeline": (
193
- "feature_state",
194
- [
195
- "prizmkit-implement", "prizmkit-code-review", "prizmkit-test",
196
- "completion-summary", "prizmkit-retrospective", "prizmkit-committer",
197
- ],
198
- ),
199
- "bugfix-pipeline": (
200
- "bugfix_state",
201
- [
202
- "prizmkit-implement", "prizmkit-code-review", "prizmkit-test",
203
- "bug-report", "prizmkit-retrospective", "prizmkit-committer",
204
- ],
205
- ),
206
- "refactor-pipeline": (
207
- "refactor_state",
208
- [
209
- "prizmkit-implement", "prizmkit-code-review", "prizmkit-test",
210
- "refactor-report", "completion-summary", "prizmkit-retrospective",
211
- "prizmkit-committer",
212
- ],
213
- ),
214
- }
215
- state_key, skills = contracts[workflow_type]
216
- steps = []
217
- previous = None
218
- for index, skill in enumerate(skills, start=1):
219
- step = {
220
- "id": f"S{index:02d}",
221
- "skill": skill,
222
- "name": skill,
223
- "status": "completed",
224
- "required_artifacts": [],
225
- "depends_on": previous,
226
- }
227
- if skill == "prizmkit-implement":
228
- step["stage_result"] = "IMPLEMENTED"
229
- if skill == "prizmkit-code-review":
230
- step["stage_result"] = "REVIEW_PASS"
231
- if skill == "prizmkit-test":
232
- step["stage_result"] = "TEST_PASS"
233
- relative_artifact = artifact_dir.relative_to(project_root)
234
- step["required_artifacts"] = [
235
- str(relative_artifact / "test-report.md"),
236
- str(relative_artifact / "test-result.json"),
237
- ]
238
- if skill == "prizmkit-retrospective":
239
- step["stage_result"] = "RETRO_COMPLETE"
240
- if skill == "prizmkit-committer":
241
- step["stage_result"] = "COMMITTED"
242
- steps.append(step)
243
- previous = step["id"]
244
- artifact_dir.mkdir(parents=True, exist_ok=True)
245
- (artifact_dir / "test-report.md").write_text(
246
- "# Test Report\n\n## Final Result\n\n- Result: TEST_PASS\n",
247
- encoding="utf-8",
248
- )
249
- (artifact_dir / "test-result.json").write_text(
250
- json.dumps({
251
- "schema_version": 1,
252
- "result": "TEST_PASS",
253
- "report": "test-report.md",
254
- "main_review_rounds": 1,
255
- "independent_review": {
256
- "status": "downgraded",
257
- "responses": 0,
258
- "downgrade_reason": "read-only continuation capability unavailable",
259
- "final_state_rechecked": False,
260
- },
261
- "repair_rounds": 0,
262
- "production_changed": False,
263
- "unresolved_items": [],
264
- }),
265
- encoding="utf-8",
266
- )
267
- runtime_commit_hash = "b" * 40
268
- runtime_base_head = "a" * 40
269
- head = subprocess.run(
270
- ["git", "rev-parse", "HEAD"],
271
- cwd=project_root,
272
- stdout=subprocess.PIPE,
273
- stderr=subprocess.DEVNULL,
274
- text=True,
275
- check=False,
276
- )
277
- parent = subprocess.run(
278
- ["git", "rev-parse", "HEAD^"],
279
- cwd=project_root,
280
- stdout=subprocess.PIPE,
281
- stderr=subprocess.DEVNULL,
282
- text=True,
283
- check=False,
284
- )
285
- if head.returncode == 0 and parent.returncode == 0:
286
- runtime_commit_hash = head.stdout.strip()
287
- runtime_base_head = parent.stdout.strip()
288
- checkpoint = artifact_dir / "workflow-checkpoint.json"
289
- checkpoint.write_text(
290
- json.dumps({
291
- "version": 1,
292
- "workflow_type": workflow_type,
293
- "steps": steps,
294
- state_key: {
295
- "repair_round": 0,
296
- "terminal_status": "WORKFLOW_COMPLETED",
297
- "runtime_base_head": runtime_base_head,
298
- "runtime_commit_hash": runtime_commit_hash,
299
- },
300
- }),
301
- encoding="utf-8",
302
- )
303
- return checkpoint
304
-
305
-
306
147
  def test_retired_shell_runtime_files_are_absent_from_source():
307
148
  retired = [
308
149
  "run-feature.sh",
309
150
  "run-bugfix.sh",
310
- "run-refactor.sh",
311
151
  "run-recovery.sh",
312
152
  "launch-feature-daemon.sh",
313
153
  "launch-bugfix-daemon.sh",
314
- "launch-refactor-daemon.sh",
315
154
  "reset-feature.sh",
316
155
  "reset-bug.sh",
317
- "reset-refactor.sh",
318
156
  "lib/branch.sh",
319
157
  "lib/common.sh",
320
158
  "lib/heartbeat.sh",
@@ -326,17 +164,19 @@ def test_retired_shell_runtime_files_are_absent_from_source():
326
164
 
327
165
  def test_python_parity_suite_declares_coverage_for_all_legacy_unix_snapshot_scenarios():
328
166
  """Keep the F-011 snapshot as an explicit oracle without reviving shell sources."""
167
+ import ast
168
+
329
169
  snapshot = _load_unix_runtime_snapshot()
330
- suite_text = "\n".join(
331
- [
332
- Path(__file__).read_text(encoding="utf-8"),
333
- (PIPELINE_ROOT / "tests" / "test_unified_cli.py").read_text(encoding="utf-8"),
334
- (PIPELINE_ROOT / "tests" / "test_auto_skip.py").read_text(encoding="utf-8"),
335
- ]
336
- )
170
+ test_names: set[str] = set()
171
+ for test_file in sorted((PIPELINE_ROOT / "tests").glob("test_*.py")):
172
+ tree = ast.parse(test_file.read_text(encoding="utf-8"), filename=str(test_file))
173
+ for node in ast.walk(tree):
174
+ if isinstance(node, ast.FunctionDef) and node.name.startswith("test_"):
175
+ test_names.add(node.name)
176
+
337
177
  coverage_tokens = {
338
178
  "entrypointContracts": {
339
- "runnerHelpContracts": ["test_cli_help_exposes_python_runtime_command_groups"],
179
+ "runnerHelpContracts": ["test_cli_help_exposes_only_operation_first_public_namespaces"],
340
180
  "runnerMissingListErrors": ["test_python_runner_missing_list_errors_match_snapshot_contract"],
341
181
  "resetHelpContracts": ["test_reset_and_daemon_entrypoint_contracts_match_snapshot_contracts"],
342
182
  "daemonStatusContracts": ["test_reset_and_daemon_entrypoint_contracts_match_snapshot_contracts"],
@@ -344,8 +184,8 @@ def test_python_parity_suite_declares_coverage_for_all_legacy_unix_snapshot_scen
344
184
  "envResolution": {
345
185
  "verboseAndStreamJson": ["test_python_env_resolution_scenarios_match_snapshot_contracts"],
346
186
  "effortModelAndCli": ["test_ai_session_command_builders_match_unix_runtime_snapshot"],
347
- "worktreeIgnored": ["test_runner_environment_disables_worktree_by_default_and_accepts_truthy_opt_in"],
348
- "autoPushFlag": ["test_successful_worktree_session_merges_cleans_branch_and_honors_auto_push"],
187
+ "worktreeIgnored": ["test_runner_environment_retires_use_worktree_and_ignores_env"],
188
+ "autoPushFlag": ["test_successful_branch_session_merges_and_honors_auto_push"],
349
189
  },
350
190
  "aiCliCommands": {
351
191
  "claudeCommand": ["test_ai_session_command_builders_match_unix_runtime_snapshot"],
@@ -354,7 +194,7 @@ def test_python_parity_suite_declares_coverage_for_all_legacy_unix_snapshot_scen
354
194
  },
355
195
  "fakeCliOutcomes": {
356
196
  "success": ["test_session_dual_writes_progress_and_recovers_backup"],
357
- "contextOverflowContinuation": ["test_context_overflow_reuses_worktree_and_skips_cleanup_until_terminal_outcome"],
197
+ "contextOverflowContinuation": ["test_context_overflow_reuses_branch_and_skips_cleanup_until_terminal_outcome"],
358
198
  "infraErrorRetry": ["test_status_updater_behavior_matches_unix_runtime_snapshot"],
359
199
  "crashFailure": ["test_status_updater_behavior_matches_unix_runtime_snapshot"],
360
200
  "timeoutStaleKill": ["test_heartbeat_fatal_error_writes_shell_compatible_markers"],
@@ -373,7 +213,7 @@ def test_python_parity_suite_declares_coverage_for_all_legacy_unix_snapshot_scen
373
213
  },
374
214
  "continuationBehavior": {
375
215
  "noProgressStall": ["test_status_updater_behavior_matches_unix_runtime_snapshot"],
376
- "branchAndArtifactReuse": ["test_context_overflow_reuses_worktree_and_skips_cleanup_until_terminal_outcome"],
216
+ "branchAndArtifactReuse": ["test_context_overflow_reuses_branch_and_skips_cleanup_until_terminal_outcome"],
377
217
  },
378
218
  "statusUpdaterBehavior": {
379
219
  "contextOverflowMetadata": ["test_status_updater_behavior_matches_unix_runtime_snapshot"],
@@ -390,14 +230,14 @@ def test_python_parity_suite_declares_coverage_for_all_legacy_unix_snapshot_scen
390
230
  for scenario_name, tokens in coverage_tokens[section].items():
391
231
  assert tokens, f"{section}.{scenario_name} has no coverage tokens"
392
232
  for token in tokens:
393
- assert token in suite_text, f"{section}.{scenario_name} coverage token missing: {token}"
233
+ assert token in test_names, f"{section}.{scenario_name} coverage test missing: {token}"
394
234
 
395
235
 
396
236
  def test_python_runner_missing_list_errors_match_snapshot_contract(tmp_path):
397
237
  from prizmkit_runtime.runners import run_pipeline_command
398
238
 
399
239
  snapshot = _load_unix_runtime_snapshot()["entrypointContracts"]["runnerMissingListErrors"]
400
- for kind in ("feature", "bugfix", "refactor"):
240
+ for kind in ("feature", "bugfix"):
401
241
  paths = _make_paths(tmp_path / f"missing-{kind}")
402
242
  result = run_pipeline_command(kind, "run", (), paths)
403
243
 
@@ -413,7 +253,7 @@ def test_reset_and_daemon_entrypoint_contracts_match_snapshot_contracts(tmp_path
413
253
  snapshot = _load_unix_runtime_snapshot()["entrypointContracts"]
414
254
  paths = _make_paths(tmp_path / "entrypoints")
415
255
 
416
- for kind in ("feature", "bugfix", "refactor"):
256
+ for kind in ("feature", "bugfix"):
417
257
  reset = run_reset_command(kind, ("--help",), paths)
418
258
  assert reset.exit_code == snapshot["resetHelpContracts"][kind]["exitCode"]
419
259
  assert "Usage: prizmkit-runtime reset" in reset.render()
@@ -487,6 +327,47 @@ def test_python_env_resolution_scenarios_match_snapshot_contracts(tmp_path):
487
327
  assert cursor_support.enabled is True
488
328
  assert cursor_support.format == "cursor-stream-json"
489
329
 
330
+ agy = build_ai_session_command(
331
+ AISessionConfig(
332
+ cli_command="agy",
333
+ platform="antigravity",
334
+ model="gemini-model",
335
+ effort="xhigh",
336
+ prompt_path=prompt,
337
+ cwd=tmp_path,
338
+ use_stream_json=True,
339
+ )
340
+ )
341
+ assert agy.argv == (
342
+ "agy", "--dangerously-skip-permissions", "--input-format", "stream-json",
343
+ "--output-format", "stream-json", "--model", "gemini-model", "--effort", "xhigh",
344
+ )
345
+ assert json.loads(agy.stdin_text) == {"event": "user", "message": {"content": "hello"}}
346
+ assert agy.prompt_mode == "stdin"
347
+ assert "hello" not in agy.argv
348
+
349
+ agy_fallback = build_ai_session_command(
350
+ AISessionConfig(
351
+ cli_command="agy",
352
+ platform="antigravity",
353
+ model=None,
354
+ prompt_path=prompt,
355
+ cwd=tmp_path,
356
+ use_stream_json=False,
357
+ )
358
+ )
359
+ assert agy_fallback.argv == ("agy", "-p", "hello", "--dangerously-skip-permissions")
360
+ assert agy_fallback.stdin_text is None
361
+ assert agy_fallback.prompt_mode == "argument"
362
+
363
+ agy_support = detect_stream_json_support(
364
+ "agy",
365
+ "antigravity",
366
+ lambda command: "--print --dangerously-skip-permissions --input-format --output-format stream-json",
367
+ )
368
+ assert agy_support.enabled is True
369
+ assert agy_support.format == "antigravity-stream-json"
370
+
490
371
 
491
372
  def test_windows_structural_paths_use_installed_python_runtime_layout(tmp_path):
492
373
  from prizmkit_runtime.paths import resolve_runtime_paths
@@ -560,7 +441,6 @@ def test_runner_models_parse_legacy_args_and_environment(tmp_path):
560
441
  "VERBOSE": "1",
561
442
  "STALE_KILL_THRESHOLD": "9",
562
443
  "MAX_RETRIES": "9",
563
- "STRICT_BEHAVIOR_CHECK": "false",
564
444
  }
565
445
  )
566
446
 
@@ -575,22 +455,17 @@ def test_runner_models_parse_legacy_args_and_environment(tmp_path):
575
455
  assert env.dev_branch == "dev/custom"
576
456
  assert env.stale_kill_threshold_seconds == 9
577
457
  assert env.max_retries == 9
578
- assert env.strict_behavior_check is False
579
458
  assert not hasattr(env, "enable_deploy")
580
459
  assert not hasattr(env, "max_" + "log_size")
581
460
 
582
461
 
583
- def test_runner_environment_disables_worktree_by_default_and_accepts_truthy_opt_in():
462
+ def test_runner_environment_retires_use_worktree_and_ignores_env():
584
463
  from prizmkit_runtime.runner_models import RunnerEnvironment
585
464
 
586
- assert RunnerEnvironment.from_env({}).use_worktree is False
587
- assert RunnerEnvironment.from_env({"USE_WORKTREE": "unexpected"}).use_worktree is False
588
-
589
- for truthy in ("1", "true", "yes", "on"):
590
- assert RunnerEnvironment.from_env({"USE_WORKTREE": truthy}).use_worktree is True
591
-
592
- for falsey in ("0", "false", "no", "off"):
593
- assert RunnerEnvironment.from_env({"USE_WORKTREE": falsey}).use_worktree is False
465
+ for raw in ({}, {"USE_WORKTREE": "1"}, {"USE_WORKTREE": "true"}):
466
+ env = RunnerEnvironment.from_env(raw)
467
+ assert not hasattr(env, "use_worktree")
468
+ assert env.auto_push is False
594
469
 
595
470
 
596
471
  def test_status_bridge_preserves_feature_filter_selection(tmp_path):
@@ -631,11 +506,6 @@ def test_status_bridge_uses_stable_dependency_order_across_pipeline_families(tmp
631
506
  {"id": "B-002", "title": "First", "status": "pending", "severity": "low", "priority": "low", "error_source": {"type": "user_report"}, "verification_type": "manual", "acceptance_criteria": ["fixed"], "dependencies": []},
632
507
  {"id": "B-003", "title": "Independent", "status": "pending", "severity": "high", "priority": "high", "error_source": {"type": "user_report"}, "verification_type": "manual", "acceptance_criteria": ["fixed"], "dependencies": []},
633
508
  ],
634
- "refactor": [
635
- {"id": "R-001", "title": "Blocked", "description": "blocked", "scope": {}, "type": "restructure", "priority": "critical", "complexity": "high", "behavior_preservation": {"strategy": "test-gate"}, "acceptance_criteria": ["done"], "dependencies": ["R-002"], "status": "pending"},
636
- {"id": "R-002", "title": "First", "description": "first", "scope": {}, "type": "extract", "priority": "low", "complexity": "low", "behavior_preservation": {"strategy": "test-gate"}, "acceptance_criteria": ["done"], "dependencies": [], "status": "pending"},
637
- {"id": "R-003", "title": "Independent", "description": "independent", "scope": {}, "type": "simplify", "priority": "high", "complexity": "medium", "behavior_preservation": {"strategy": "test-gate"}, "acceptance_criteria": ["done"], "dependencies": [], "status": "pending"},
638
- ],
639
509
  }
640
510
 
641
511
  for kind, items in cases.items():
@@ -645,7 +515,7 @@ def test_status_bridge_uses_stable_dependency_order_across_pipeline_families(tmp
645
515
  result = _get_next_result(kind, paths)
646
516
 
647
517
  assert result.ok
648
- assert _item_id_from_next_result(kind, result) == {"feature": "F-002", "bugfix": "B-002", "refactor": "R-002"}[kind]
518
+ assert _item_id_from_next_result(kind, result) == {"feature": "F-002", "bugfix": "B-002"}[kind]
649
519
 
650
520
 
651
521
  def test_status_bridge_prefers_in_progress_items_with_satisfied_dependencies(tmp_path):
@@ -660,11 +530,6 @@ def test_status_bridge_prefers_in_progress_items_with_satisfied_dependencies(tmp
660
530
  {"id": "B-002", "title": "Resume", "status": "in_progress", "severity": "low", "priority": "low", "error_source": {"type": "user_report"}, "verification_type": "manual", "acceptance_criteria": ["fixed"], "dependencies": ["B-001"]},
661
531
  {"id": "B-003", "title": "Pending", "status": "pending", "severity": "critical", "priority": "high", "error_source": {"type": "user_report"}, "verification_type": "manual", "acceptance_criteria": ["fixed"], "dependencies": []},
662
532
  ],
663
- "refactor": [
664
- {"id": "R-001", "title": "Done", "description": "done", "scope": {}, "type": "extract", "priority": "low", "complexity": "low", "behavior_preservation": {"strategy": "test-gate"}, "acceptance_criteria": ["done"], "dependencies": [], "status": "completed"},
665
- {"id": "R-002", "title": "Resume", "description": "resume", "scope": {}, "type": "extract", "priority": "low", "complexity": "low", "behavior_preservation": {"strategy": "test-gate"}, "acceptance_criteria": ["done"], "dependencies": ["R-001"], "status": "in_progress"},
666
- {"id": "R-003", "title": "Pending", "description": "pending", "scope": {}, "type": "migrate", "priority": "critical", "complexity": "high", "behavior_preservation": {"strategy": "test-gate"}, "acceptance_criteria": ["done"], "dependencies": [], "status": "pending"},
667
- ],
668
533
  }
669
534
 
670
535
  for kind, items in cases.items():
@@ -674,32 +539,13 @@ def test_status_bridge_prefers_in_progress_items_with_satisfied_dependencies(tmp
674
539
  result = _get_next_result(kind, paths)
675
540
 
676
541
  assert result.ok
677
- assert _item_id_from_next_result(kind, result) == {"feature": "F-002", "bugfix": "B-002", "refactor": "R-002"}[kind]
678
-
679
-
680
- def test_refactor_dependencies_require_completed_not_other_terminal_statuses(tmp_path):
681
- paths = _make_paths(tmp_path)
682
- _write_family_plan(
683
- paths,
684
- "refactor",
685
- [
686
- {"id": "R-001", "title": "Failed Dependency", "description": "failed", "scope": {}, "type": "extract", "priority": "high", "complexity": "low", "behavior_preservation": {"strategy": "test-gate"}, "acceptance_criteria": ["done"], "dependencies": [], "status": "failed"},
687
- {"id": "R-002", "title": "Blocked", "description": "blocked", "scope": {}, "type": "restructure", "priority": "high", "complexity": "medium", "behavior_preservation": {"strategy": "test-gate"}, "acceptance_criteria": ["done"], "dependencies": ["R-001"], "status": "pending"},
688
- ],
689
- )
690
-
691
- result = _get_next_result("refactor", paths)
692
-
693
- assert result.ok
694
- assert result.text == "PIPELINE_BLOCKED"
695
- assert result.data is None
542
+ assert _item_id_from_next_result(kind, result) == {"feature": "F-002", "bugfix": "B-002"}[kind]
696
543
 
697
544
 
698
545
  def test_init_scripts_reject_missing_self_and_cycle_dependencies(tmp_path):
699
546
  script_config = {
700
547
  "feature": ("init-pipeline.py", "--feature-list", "F-", "missing dependency"),
701
548
  "bugfix": ("init-bugfix-pipeline.py", "--bug-list", "B-", "missing dependency"),
702
- "refactor": ("init-refactor-pipeline.py", "--refactor-list", "R-", "missing dependency"),
703
549
  }
704
550
  scenarios = {
705
551
  "missing": lambda kind, prefix: _family_items(kind, [
@@ -748,7 +594,6 @@ def test_init_scripts_reject_unknown_item_fields(tmp_path):
748
594
  script_config = {
749
595
  "feature": ("init-pipeline.py", "--feature-list", "F-"),
750
596
  "bugfix": ("init-bugfix-pipeline.py", "--bug-list", "B-"),
751
- "refactor": ("init-refactor-pipeline.py", "--refactor-list", "R-"),
752
597
  }
753
598
 
754
599
  for kind, (script_name, list_arg, prefix) in script_config.items():
@@ -816,7 +661,6 @@ def test_init_scripts_reject_unknown_list_fields(tmp_path, location):
816
661
  script_config = {
817
662
  "feature": ("init-pipeline.py", "--feature-list", "F-"),
818
663
  "bugfix": ("init-bugfix-pipeline.py", "--bug-list", "B-"),
819
- "refactor": ("init-refactor-pipeline.py", "--refactor-list", "R-"),
820
664
  }
821
665
 
822
666
  for kind, (script_name, list_arg, prefix) in script_config.items():
@@ -869,13 +713,6 @@ def test_planner_validators_reject_unknown_item_fields():
869
713
  "dev-pipeline-bug-fix-list-v1",
870
714
  "B-",
871
715
  ),
872
- "refactor": (
873
- "core/skills/orchestration-skill/pipelines/refactor-planner/scripts/validate-and-generate-refactor.py",
874
- "validate_refactor_list",
875
- "refactors",
876
- "dev-pipeline-refactor-list-v1",
877
- "R-",
878
- ),
879
716
  }
880
717
 
881
718
  for kind, (relative_path, function_name, list_key, schema, prefix) in planner_config.items():
@@ -940,10 +777,6 @@ def test_planner_validators_reject_unknown_list_fields(location):
940
777
  "core/skills/orchestration-skill/pipelines/bug-planner/scripts/validate-bug-list.py",
941
778
  "validate", "bugs", "dev-pipeline-bug-fix-list-v1", "B-",
942
779
  ),
943
- "refactor": (
944
- "core/skills/orchestration-skill/pipelines/refactor-planner/scripts/validate-and-generate-refactor.py",
945
- "validate_refactor_list", "refactors", "dev-pipeline-refactor-list-v1", "R-",
946
- ),
947
780
  }
948
781
 
949
782
  for kind, (relative_path, function_name, list_key, schema, prefix) in planner_config.items():
@@ -1008,7 +841,6 @@ def test_bug_planner_validator_rejects_dependency_cycles():
1008
841
  assert any("Dependency cycle detected" in error for error in result["errors"])
1009
842
 
1010
843
 
1011
-
1012
844
  def _family_items(kind, entries):
1013
845
  items = []
1014
846
  for item_id, dependencies, status in entries:
@@ -1036,19 +868,7 @@ def _family_items(kind, entries):
1036
868
  "status": status,
1037
869
  })
1038
870
  else:
1039
- items.append({
1040
- "id": item_id,
1041
- "title": item_id,
1042
- "description": "Refactor description",
1043
- "scope": {},
1044
- "type": "extract",
1045
- "priority": "medium",
1046
- "complexity": "low",
1047
- "behavior_preservation": {"strategy": "test-gate"},
1048
- "acceptance_criteria": ["done"],
1049
- "dependencies": dependencies,
1050
- "status": status,
1051
- })
871
+ raise ValueError(f"Unsupported family kind: {kind}")
1052
872
  return items
1053
873
 
1054
874
 
@@ -1083,7 +903,7 @@ def test_status_bridge_passes_max_retries_from_invocation_or_environment(monkeyp
1083
903
 
1084
904
  @pytest.mark.parametrize(
1085
905
  ("kind", "item_key"),
1086
- (("feature", "feature_id"), ("bugfix", "bug_id"), ("refactor", "refactor_id")),
906
+ (("feature", "feature_id"), ("bugfix", "bug_id")),
1087
907
  )
1088
908
  def test_pipeline_aggregate_reselection_keeps_first_seen_details_and_stops(monkeypatch, tmp_path, kind, item_key):
1089
909
  from prizmkit_runtime import runners
@@ -1115,7 +935,7 @@ def test_pipeline_aggregate_reselection_keeps_first_seen_details_and_stops(monke
1115
935
 
1116
936
  @pytest.mark.parametrize(
1117
937
  ("kind", "item_key"),
1118
- (("feature", "feature_id"), ("bugfix", "bug_id"), ("refactor", "refactor_id")),
938
+ (("feature", "feature_id"), ("bugfix", "bug_id")),
1119
939
  )
1120
940
  def test_pipeline_aggregate_keeps_distinct_unresolved_item_blocking(monkeypatch, tmp_path, kind, item_key):
1121
941
  from prizmkit_runtime import runners
@@ -1146,7 +966,7 @@ def test_pipeline_aggregate_keeps_distinct_unresolved_item_blocking(monkeypatch,
1146
966
 
1147
967
  @pytest.mark.parametrize(
1148
968
  ("kind", "item_key"),
1149
- (("feature", "feature_id"), ("bugfix", "bug_id"), ("refactor", "refactor_id")),
969
+ (("feature", "feature_id"), ("bugfix", "bug_id")),
1150
970
  )
1151
971
  def test_full_list_stops_after_newly_skipped_item(monkeypatch, tmp_path, kind, item_key):
1152
972
  from prizmkit_runtime import runners
@@ -1185,7 +1005,7 @@ def test_full_list_stops_after_newly_skipped_item(monkeypatch, tmp_path, kind, i
1185
1005
 
1186
1006
  @pytest.mark.parametrize(
1187
1007
  ("kind", "item_key"),
1188
- (("feature", "feature_id"), ("bugfix", "bug_id"), ("refactor", "refactor_id")),
1008
+ (("feature", "feature_id"), ("bugfix", "bug_id")),
1189
1009
  )
1190
1010
  def test_full_list_rejects_reselected_processed_item_before_second_launch(monkeypatch, tmp_path, kind, item_key):
1191
1011
  from prizmkit_runtime import runners
@@ -1220,7 +1040,7 @@ def test_full_list_rejects_reselected_processed_item_before_second_launch(monkey
1220
1040
  assert result.details == ("X-001:completed",)
1221
1041
 
1222
1042
 
1223
- @pytest.mark.parametrize("kind", ("feature", "bugfix", "refactor"))
1043
+ @pytest.mark.parametrize("kind", ("feature", "bugfix"))
1224
1044
  def test_pipeline_aggregate_empty_authoritative_completion(monkeypatch, tmp_path, kind):
1225
1045
  from prizmkit_runtime import runners
1226
1046
  from prizmkit_runtime.runner_models import family_for, parse_invocation
@@ -1259,10 +1079,6 @@ def test_pipeline_aggregate_empty_authoritative_completion(monkeypatch, tmp_path
1259
1079
  ("bugfix", "skipped", False),
1260
1080
  ("bugfix", "auto_skipped", False),
1261
1081
  ("bugfix", "split", False),
1262
- ("refactor", "completed", True),
1263
- ("refactor", "skipped", False),
1264
- ("refactor", "auto_skipped", False),
1265
- ("refactor", "split", False),
1266
1082
  ),
1267
1083
  )
1268
1084
  def test_pipeline_aggregate_completion_compatible_statuses(monkeypatch, tmp_path, kind, status, expected_completed):
@@ -1272,7 +1088,7 @@ def test_pipeline_aggregate_completion_compatible_statuses(monkeypatch, tmp_path
1272
1088
  paths = _make_paths(tmp_path)
1273
1089
  family = family_for(kind, paths)
1274
1090
  invocation = parse_invocation(family, "run", ())
1275
- item_key = {"feature": "feature_id", "bugfix": "bug_id", "refactor": "refactor_id"}[kind]
1091
+ item_key = {"feature": "feature_id", "bugfix": "bug_id"}[kind]
1276
1092
  queue = [
1277
1093
  SimpleNamespace(ok=True, stdout="", data={item_key: "X-001"}, text=""),
1278
1094
  SimpleNamespace(ok=True, stdout="PIPELINE_COMPLETE\n", data=None, text="PIPELINE_COMPLETE"),
@@ -1294,7 +1110,7 @@ def test_pipeline_aggregate_completion_compatible_statuses(monkeypatch, tmp_path
1294
1110
  assert result.details == (f"X-001:{status}",)
1295
1111
 
1296
1112
 
1297
- @pytest.mark.parametrize("kind", ("feature", "bugfix", "refactor"))
1113
+ @pytest.mark.parametrize("kind", ("feature", "bugfix"))
1298
1114
  def test_run_pipeline_command_omits_empty_last_status_detail(monkeypatch, tmp_path, kind):
1299
1115
  from prizmkit_runtime import runners
1300
1116
  from prizmkit_runtime.runner_models import PipelineRunResult
@@ -1303,7 +1119,6 @@ def test_run_pipeline_command_omits_empty_last_status_detail(monkeypatch, tmp_pa
1303
1119
  plan_path = {
1304
1120
  "feature": paths.feature_plan,
1305
1121
  "bugfix": paths.bugfix_plan,
1306
- "refactor": paths.refactor_plan,
1307
1122
  }[kind]
1308
1123
  plan_path.write_text("{}", encoding="utf-8")
1309
1124
  monkeypatch.setattr(
@@ -1319,7 +1134,7 @@ def test_run_pipeline_command_omits_empty_last_status_detail(monkeypatch, tmp_pa
1319
1134
  assert result.details == ()
1320
1135
 
1321
1136
 
1322
- @pytest.mark.parametrize("kind", ("feature", "bugfix", "refactor"))
1137
+ @pytest.mark.parametrize("kind", ("feature", "bugfix"))
1323
1138
  def test_run_pipeline_command_returns_nonzero_for_terminal_skipped_item(monkeypatch, tmp_path, kind):
1324
1139
  from prizmkit_runtime import runners
1325
1140
  from prizmkit_runtime.runner_models import PipelineRunResult
@@ -1328,7 +1143,6 @@ def test_run_pipeline_command_returns_nonzero_for_terminal_skipped_item(monkeypa
1328
1143
  plan_path = {
1329
1144
  "feature": paths.feature_plan,
1330
1145
  "bugfix": paths.bugfix_plan,
1331
- "refactor": paths.refactor_plan,
1332
1146
  }[kind]
1333
1147
  plan_path.write_text("{}", encoding="utf-8")
1334
1148
  monkeypatch.setattr(
@@ -1521,156 +1335,6 @@ def test_prompt_generation_passes_explicit_execution_root_to_generator(monkeypat
1521
1335
  assert result.artifact_path == execution_root / ".prizmkit" / "specs" / "001-low"
1522
1336
 
1523
1337
 
1524
- def _install_runner_session_fakes(monkeypatch, runners, *, statuses=("success",), update_status="completed", max_retries=3):
1525
- from prizmkit_runtime.runner_models import PromptGenerationResult, SessionClassification
1526
-
1527
- prompt_calls = []
1528
- launch_cwds = []
1529
- launch_configs = []
1530
- updates = []
1531
- cleanup_calls = []
1532
- merge_calls = []
1533
- wip_calls = []
1534
- restore_calls = []
1535
- events = []
1536
- status_queue = list(statuses)
1537
-
1538
- monkeypatch.setattr(
1539
- runners,
1540
- "load_runtime_config",
1541
- lambda paths: SimpleNamespace(
1542
- ai_client=SimpleNamespace(command="fake-ai", platform="codebuddy"),
1543
- model="fallback-model",
1544
- effort=None,
1545
- ),
1546
- )
1547
- monkeypatch.setattr(runners, "detect_stream_json_support", lambda command, platform: SimpleNamespace(enabled=False))
1548
- monkeypatch.setattr(runners, "start_item", lambda *args, **kwargs: SimpleNamespace(ok=True, text="", data={"new_status": "in_progress"}))
1549
- monkeypatch.setattr(runners, "commit_preflight_ready_changes", lambda *args, **kwargs: SimpleNamespace(attempted=False, committed=False, ok=True, result=None))
1550
- monkeypatch.setattr(runners, "commit_pre_branch_bookkeeping", lambda *args, **kwargs: None)
1551
- monkeypatch.setattr(runners, "commit_final_bookkeeping", lambda *args, **kwargs: None)
1552
- monkeypatch.setattr(runners, "commit_task_branch_changes", lambda *args, **kwargs: None)
1553
- monkeypatch.setattr(
1554
- runners,
1555
- "finalize_accepted_workspace_commit",
1556
- lambda *args, **kwargs: SimpleNamespace(
1557
- status="not_needed",
1558
- reason="accepted_workspace_clean",
1559
- committed=False,
1560
- commit_hash="",
1561
- ),
1562
- )
1563
- monkeypatch.setattr(runners, "current_branch", lambda _root: "main")
1564
- monkeypatch.setattr(runners, "_session_id", lambda item_id: f"{item_id}-session-{len(prompt_calls) + 1}")
1565
- monkeypatch.setattr(
1566
- runners,
1567
- "run_git_command",
1568
- lambda project_root, args: SimpleNamespace(return_code=0, stdout="base-head\n", stderr="", args=tuple(args)),
1569
- )
1570
-
1571
- def fake_generate_prompt(family, invocation, **kwargs):
1572
- events.append("prompt")
1573
- prompt_calls.append(kwargs)
1574
- session_paths = kwargs["session_paths"]
1575
- execution_root = kwargs.get("execution_root") or kwargs["project_root"]
1576
- return PromptGenerationResult(
1577
- output_path=session_paths.prompt_path,
1578
- model="per-item-model",
1579
- checkpoint_path=execution_root / ".prizmkit" / "specs" / "001-low" / "workflow-checkpoint.json",
1580
- artifact_path=execution_root / ".prizmkit" / "specs" / "001-low",
1581
- raw={},
1582
- )
1583
-
1584
- class FakeLauncher:
1585
- def __init__(self, config):
1586
- self.config = config
1587
-
1588
- def run(self):
1589
- launch_cwds.append(self.config.cwd)
1590
- launch_configs.append(self.config)
1591
- return SimpleNamespace(progress_summary=SimpleNamespace(), fatal_error_code="")
1592
-
1593
- def fake_classify(*args, **kwargs):
1594
- status = status_queue.pop(0)
1595
- return SessionClassification(
1596
- status,
1597
- reason=status,
1598
- fatal_error_code="context_overflow" if status == "context_overflow" else "",
1599
- progress_fingerprint={"head_commit": status},
1600
- no_progress_count=0,
1601
- )
1602
-
1603
- def fake_update(family, invocation, item_id, session_status, session_id, project_root, **metadata):
1604
- updates.append((session_status, session_id, metadata))
1605
- normal_retry_count = sum(
1606
- status in {"context_overflow", "crashed", "timed_out", "failed"}
1607
- for status, *_ in updates
1608
- )
1609
- infra_error_count = sum(status == "infra_error" for status, *_ in updates)
1610
- current_update_status = update_status
1611
- if session_status in {"context_overflow", "crashed", "timed_out", "failed"}:
1612
- if normal_retry_count >= max_retries:
1613
- current_update_status = "failed"
1614
- elif len(status_queue) > 0:
1615
- current_update_status = "in_progress"
1616
- elif session_status == "infra_error" and len(status_queue) > 0:
1617
- current_update_status = "in_progress"
1618
- return SimpleNamespace(
1619
- ok=True,
1620
- text="",
1621
- data={
1622
- "new_status": current_update_status,
1623
- "retry_count": normal_retry_count,
1624
- "infra_error_count": infra_error_count,
1625
- "continuation_count": len(updates),
1626
- "context_overflow_count": sum(status == "context_overflow" for status, *_ in updates),
1627
- },
1628
- )
1629
-
1630
- def fake_cleanup(runtime, *, delete_branch=True):
1631
- cleanup_calls.append((runtime, delete_branch))
1632
- return SimpleNamespace(ok=True, reason="")
1633
-
1634
- def fake_merge(runtime, *, auto_push=False):
1635
- merge_calls.append((runtime, auto_push))
1636
- return SimpleNamespace(ok=True, reason="", runtime=runtime, results=())
1637
-
1638
- def fake_save_wip(runtime):
1639
- wip_calls.append(runtime)
1640
- return SimpleNamespace(ok=True, plan=None, results=())
1641
-
1642
- def fake_restore_wip(project_root, **kwargs):
1643
- events.append("restore")
1644
- restore_calls.append((project_root, kwargs))
1645
- return SimpleNamespace(
1646
- ok=True,
1647
- restored=False,
1648
- reason="runtime_wip_not_found",
1649
- wip_head="",
1650
- restored_head="",
1651
- )
1652
-
1653
- monkeypatch.setattr(runners, "generate_prompt", fake_generate_prompt)
1654
- monkeypatch.setattr(runners, "AISessionLauncher", FakeLauncher)
1655
- monkeypatch.setattr(runners, "classify_session", fake_classify)
1656
- monkeypatch.setattr(runners, "update_item", fake_update)
1657
- monkeypatch.setattr(runners, "guarded_worktree_remove", fake_cleanup, raising=False)
1658
- monkeypatch.setattr(runners, "merge_linked_worktree", fake_merge, raising=False)
1659
- monkeypatch.setattr(runners, "worktree_save_wip", fake_save_wip, raising=False)
1660
- monkeypatch.setattr(runners, "restore_runtime_wip", fake_restore_wip, raising=False)
1661
- return SimpleNamespace(
1662
- prompt_calls=prompt_calls,
1663
- launch_cwds=launch_cwds,
1664
- launch_configs=launch_configs,
1665
- updates=updates,
1666
- cleanup_calls=cleanup_calls,
1667
- merge_calls=merge_calls,
1668
- wip_calls=wip_calls,
1669
- restore_calls=restore_calls,
1670
- events=events,
1671
- )
1672
-
1673
-
1674
1338
  def test_runner_does_not_restore_wip_for_first_checkout(monkeypatch, tmp_path):
1675
1339
  from prizmkit_runtime import runners
1676
1340
  from prizmkit_runtime.runner_models import family_for, parse_invocation
@@ -1730,34 +1394,18 @@ def test_runner_restores_wip_before_prompt_for_reused_branch_checkout(monkeypatc
1730
1394
  ]
1731
1395
 
1732
1396
 
1733
- def test_runner_restores_wip_before_prompt_for_reused_worktree_checkout(monkeypatch, tmp_path):
1397
+ def test_runner_restores_wip_before_prompt_for_reused_branch_checkout(monkeypatch, tmp_path):
1734
1398
  from prizmkit_runtime import runners
1735
- from prizmkit_runtime.gitops import (
1736
- BranchContext,
1737
- WorktreePolicy,
1738
- worktree_runtime_context,
1739
- )
1740
1399
  from prizmkit_runtime.runner_models import family_for, parse_invocation
1741
1400
  from prizmkit_runtime.task_checkout import (
1742
- CHECKOUT_MODE_WORKTREE,
1401
+ CHECKOUT_MODE_BRANCH,
1743
1402
  TaskCheckout,
1744
1403
  persist_task_checkout,
1745
1404
  )
1746
1405
 
1747
- monkeypatch.setenv("USE_WORKTREE", "1")
1748
- paths = _make_paths(tmp_path / "reused-worktree-wip-restore")
1406
+ paths = _make_paths(tmp_path / "reused-branch-wip-restore")
1749
1407
  family = family_for("feature", paths)
1750
1408
  branch = "dev/feature/F-001-preserved"
1751
- expected_runtime = worktree_runtime_context(
1752
- BranchContext("main", branch, paths.project_root),
1753
- WorktreePolicy(
1754
- use_worktree=True,
1755
- cleanup_on_success=True,
1756
- preserve_on_failure=True,
1757
- worktree_root=paths.state_dir / "worktrees",
1758
- ),
1759
- )
1760
- worktree_path = expected_runtime.worktree_path
1761
1409
  persist_task_checkout(
1762
1410
  family.state_dir,
1763
1411
  TaskCheckout.active(
@@ -1765,30 +1413,23 @@ def test_runner_restores_wip_before_prompt_for_reused_worktree_checkout(monkeypa
1765
1413
  "F-001",
1766
1414
  branch,
1767
1415
  "main",
1768
- checkout_mode=CHECKOUT_MODE_WORKTREE,
1769
- worktree_path=str(worktree_path),
1416
+ checkout_mode=CHECKOUT_MODE_BRANCH,
1770
1417
  ),
1771
1418
  )
1772
1419
  invocation = parse_invocation(family, "run", ())
1773
1420
  invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
1774
1421
  observed = _install_runner_session_fakes(monkeypatch, runners)
1775
-
1776
- def fake_setup(runtime):
1777
- runtime.worktree_path.mkdir(parents=True, exist_ok=True)
1778
- return SimpleNamespace(ok=True, runtime=runtime, reason="")
1779
-
1780
- monkeypatch.setattr(runners, "ensure_linked_worktree", fake_setup)
1781
1422
  monkeypatch.setattr(
1782
1423
  runners,
1783
- "materialize_worktree_support_assets",
1784
- lambda *args, **kwargs: SimpleNamespace(ok=True, reason=""),
1424
+ "run_git_plan",
1425
+ lambda project_root, plan: SimpleNamespace(ok=True, plan=plan, results=()),
1785
1426
  )
1786
1427
 
1787
1428
  status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
1788
1429
 
1789
1430
  assert status == "completed"
1790
1431
  assert observed.events == ["restore", "prompt"]
1791
- assert observed.restore_calls[0][0] == worktree_path.resolve()
1432
+ assert observed.restore_calls[0][0] == paths.project_root.resolve()
1792
1433
  assert observed.restore_calls[0][1] == {
1793
1434
  "family_kind": "feature",
1794
1435
  "item_id": "F-001",
@@ -1896,14 +1537,108 @@ def test_outer_runner_routes_cursor_through_native_preflight_and_session_config(
1896
1537
  assert launch.cwd == paths.project_root
1897
1538
 
1898
1539
 
1540
+ def test_outer_runner_routes_antigravity_through_native_preflight_and_session_config(monkeypatch, tmp_path):
1541
+ from prizmkit_runtime import runners
1542
+ from prizmkit_runtime.runner_models import family_for, parse_invocation
1543
+
1544
+ paths = _make_paths(tmp_path / "agy-outer-runtime")
1545
+ family = family_for("feature", paths)
1546
+ invocation = parse_invocation(family, "run", ())
1547
+ invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
1548
+ observed = _install_runner_session_fakes(
1549
+ monkeypatch,
1550
+ runners,
1551
+ statuses=("workflow_skipped",),
1552
+ update_status="completed",
1553
+ )
1554
+ monkeypatch.setattr(
1555
+ runners,
1556
+ "load_runtime_config",
1557
+ lambda _paths: SimpleNamespace(
1558
+ ai_client=SimpleNamespace(command="agy", platform="antigravity", launch_profile=None),
1559
+ model="agy-model",
1560
+ effort="xhigh",
1561
+ effort_validation=SimpleNamespace(valid=True, message=""),
1562
+ ),
1563
+ )
1564
+ probes = []
1565
+
1566
+ def agy_preflight(command, platform):
1567
+ probes.append((command, platform))
1568
+ return SimpleNamespace(enabled=True, notes=())
1569
+
1570
+ monkeypatch.setattr(runners, "detect_stream_json_support", agy_preflight)
1571
+ monkeypatch.setattr(
1572
+ runners,
1573
+ "run_git_plan",
1574
+ lambda *args, **kwargs: SimpleNamespace(ok=True, reason="", results=()),
1575
+ )
1576
+
1577
+ status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
1578
+
1579
+ assert status == "completed"
1580
+ assert probes == [("agy", "antigravity")]
1581
+ assert len(observed.launch_configs) == 1
1582
+ launch = observed.launch_configs[0]
1583
+ assert launch.platform == "antigravity"
1584
+ assert launch.cli_command == "agy"
1585
+ assert launch.use_stream_json is True
1586
+ assert launch.effort == "xhigh"
1587
+ assert launch.model == "per-item-model"
1588
+ assert launch.cwd == paths.project_root
1589
+
1590
+ monkeypatch.setattr(
1591
+ runners,
1592
+ "load_runtime_config",
1593
+ lambda _paths: SimpleNamespace(
1594
+ ai_client=SimpleNamespace(command="agy", platform="antigravity", launch_profile=None),
1595
+ model="agy-model",
1596
+ effort="invalid-effort",
1597
+ effort_validation=SimpleNamespace(valid=False, message="Unsupported Antigravity PRIZMKIT_EFFORT=invalid-effort"),
1598
+ ),
1599
+ )
1600
+ with pytest.raises(RuntimeError, match="Unsupported Antigravity PRIZMKIT_EFFORT=invalid-effort"):
1601
+ runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
1602
+
1603
+ incompatible_paths = _make_paths(tmp_path / "agy-outer-incompatible")
1604
+ incompatible_family = family_for("feature", incompatible_paths)
1605
+ incompatible_invocation = parse_invocation(incompatible_family, "run", ())
1606
+ incompatible_invocation = incompatible_invocation.__class__(
1607
+ **{**incompatible_invocation.__dict__, "list_path": incompatible_paths.feature_plan}
1608
+ )
1609
+ monkeypatch.setattr(
1610
+ runners,
1611
+ "load_runtime_config",
1612
+ lambda _paths: SimpleNamespace(
1613
+ ai_client=SimpleNamespace(command="agy", platform="antigravity", launch_profile=None),
1614
+ model="agy-model",
1615
+ effort="high",
1616
+ effort_validation=SimpleNamespace(valid=True, message=""),
1617
+ ),
1618
+ )
1619
+ monkeypatch.setattr(
1620
+ runners,
1621
+ "detect_stream_json_support",
1622
+ lambda _cmd, _plat: SimpleNamespace(enabled=False, notes=("--input-format not found",)),
1623
+ )
1624
+ with pytest.raises(RuntimeError, match="Antigravity CLI is incompatible with PrizmKit headless execution"):
1625
+ runners._process_item(
1626
+ incompatible_family,
1627
+ incompatible_invocation,
1628
+ "F-001",
1629
+ incompatible_paths,
1630
+ initial_metadata={},
1631
+ )
1632
+
1633
+
1899
1634
  def test_workflow_skipped_is_finalized_as_completed_with_one_warning(monkeypatch, tmp_path, capsys):
1900
1635
  from prizmkit_runtime import runners
1901
1636
  from prizmkit_runtime.runner_models import family_for, parse_invocation
1902
1637
 
1903
1638
  paths = _make_paths(tmp_path / "accepted-workflow-skip")
1904
- family = family_for("refactor", paths)
1639
+ family = family_for("feature", paths)
1905
1640
  invocation = parse_invocation(family, "run", ())
1906
- invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.refactor_plan})
1641
+ invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
1907
1642
  observed = _install_runner_session_fakes(
1908
1643
  monkeypatch,
1909
1644
  runners,
@@ -1935,7 +1670,7 @@ def test_workflow_skipped_is_finalized_as_completed_with_one_warning(monkeypatch
1935
1670
  lambda *args, **kwargs: (wip_calls.append((args, kwargs)) or SimpleNamespace(ok=True)),
1936
1671
  )
1937
1672
 
1938
- status = runners._process_item(family, invocation, "R-001", paths, initial_metadata={})
1673
+ status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
1939
1674
  captured = capsys.readouterr()
1940
1675
 
1941
1676
  assert status == "completed"
@@ -1947,16 +1682,16 @@ def test_workflow_skipped_is_finalized_as_completed_with_one_warning(monkeypatch
1947
1682
  assert accepted_kwargs["base_head"] == "base-head"
1948
1683
  assert accepted_kwargs["artifact_dir"] == paths.project_root / ".prizmkit" / "specs" / "001-low"
1949
1684
  assert accepted_kwargs["checkpoint_path"] == accepted_kwargs["artifact_dir"] / "workflow-checkpoint.json"
1950
- assert "R-001" in accepted_kwargs["commit_message"]
1685
+ assert "F-001" in accepted_kwargs["commit_message"]
1951
1686
  assert observed.updates[0][0] == "success"
1952
1687
  assert "classification_reason" not in observed.updates[0][2]
1953
1688
  assert "accept_workflow_skipped" not in observed.updates[0][2]
1954
1689
  session_status = json.loads(
1955
1690
  (
1956
- paths.refactor_state_dir
1957
- / "R-001"
1691
+ paths.feature_state_dir
1692
+ / "F-001"
1958
1693
  / "sessions"
1959
- / "R-001-session-1"
1694
+ / "F-001-session-1"
1960
1695
  / "session-status.json"
1961
1696
  ).read_text(encoding="utf-8")
1962
1697
  )
@@ -1967,13 +1702,12 @@ def test_workflow_skipped_is_finalized_as_completed_with_one_warning(monkeypatch
1967
1702
  assert "Reason: workflow_skipped" in captured.err
1968
1703
 
1969
1704
 
1970
- def test_workflow_skipped_uses_successful_worktree_merge_path(monkeypatch, tmp_path, capsys):
1705
+ def test_workflow_skipped_uses_successful_branch_merge_path(monkeypatch, tmp_path, capsys):
1971
1706
  from prizmkit_runtime import runners
1972
1707
  from prizmkit_runtime.runner_models import family_for, parse_invocation
1973
1708
 
1974
- monkeypatch.setenv("USE_WORKTREE", "1")
1975
1709
  monkeypatch.setenv("DEV_BRANCH", "dev/F-001-accepted")
1976
- paths = _make_paths(tmp_path / "accepted-worktree-skip")
1710
+ paths = _make_paths(tmp_path / "accepted-branch-skip")
1977
1711
  family = family_for("feature", paths)
1978
1712
  invocation = parse_invocation(family, "run", ())
1979
1713
  invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
@@ -1983,16 +1717,18 @@ def test_workflow_skipped_uses_successful_worktree_merge_path(monkeypatch, tmp_p
1983
1717
  statuses=("workflow_skipped",),
1984
1718
  update_status="completed",
1985
1719
  )
1720
+ plan_names = []
1721
+ wip_calls = []
1986
1722
 
1987
- def fake_setup(runtime):
1988
- runtime.worktree_path.mkdir(parents=True, exist_ok=True)
1989
- return SimpleNamespace(ok=True, runtime=runtime, reason="")
1723
+ def fake_run_git_plan(project_root, plan):
1724
+ plan_names.append(plan.name)
1725
+ return SimpleNamespace(ok=True, plan=plan, results=())
1990
1726
 
1991
- monkeypatch.setattr(runners, "ensure_linked_worktree", fake_setup)
1727
+ monkeypatch.setattr(runners, "run_git_plan", fake_run_git_plan)
1992
1728
  monkeypatch.setattr(
1993
1729
  runners,
1994
- "materialize_worktree_support_assets",
1995
- lambda *args, **kwargs: SimpleNamespace(ok=True, reason=""),
1730
+ "commit_wip_changes",
1731
+ lambda *args, **kwargs: wip_calls.append(args) or SimpleNamespace(ok=True),
1996
1732
  )
1997
1733
 
1998
1734
  status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
@@ -2000,8 +1736,8 @@ def test_workflow_skipped_uses_successful_worktree_merge_path(monkeypatch, tmp_p
2000
1736
 
2001
1737
  assert status == "completed"
2002
1738
  assert observed.updates[0][0] == "success"
2003
- assert len(observed.merge_calls) == 1
2004
- assert observed.wip_calls == []
1739
+ assert "branch_merge" in plan_names
1740
+ assert wip_calls == []
2005
1741
  assert captured.err.count("[WARN]") == 1
2006
1742
  assert captured.err.count("accepted with incomplete workflow evidence") == 1
2007
1743
 
@@ -2011,9 +1747,9 @@ def test_workflow_skipped_safety_failure_stays_hard_without_acceptance_warning(m
2011
1747
  from prizmkit_runtime.runner_models import family_for, parse_invocation
2012
1748
 
2013
1749
  paths = _make_paths(tmp_path / "rejected-workflow-skip")
2014
- family = family_for("refactor", paths)
1750
+ family = family_for("feature", paths)
2015
1751
  invocation = parse_invocation(family, "run", ())
2016
- invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.refactor_plan})
1752
+ invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
2017
1753
  observed = _install_runner_session_fakes(
2018
1754
  monkeypatch,
2019
1755
  runners,
@@ -2049,7 +1785,7 @@ def test_workflow_skipped_safety_failure_stays_hard_without_acceptance_warning(m
2049
1785
  lambda *args, **kwargs: SimpleNamespace(ok=True),
2050
1786
  )
2051
1787
 
2052
- status = runners._process_item(family, invocation, "R-001", paths, initial_metadata={})
1788
+ status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
2053
1789
  captured = capsys.readouterr()
2054
1790
 
2055
1791
  assert status == "pending"
@@ -2089,7 +1825,7 @@ def test_runner_launch_config_preserves_artifact_paths_live_output_and_split_thr
2089
1825
 
2090
1826
 
2091
1827
  @pytest.mark.parametrize(("kind", "item_id", "branch"), [("feature", "F-001", "dev/F-001-test"), ("bugfix", "B-001", "bugfix/B-001-test")])
2092
- def test_feature_and_bugfix_explicit_worktree_launches_from_worktree_and_renders_worktree_root(monkeypatch, tmp_path, kind, item_id, branch):
1828
+ def test_feature_and_bugfix_branch_checkout_launches_from_project_root_even_with_legacy_env(monkeypatch, tmp_path, kind, item_id, branch):
2093
1829
  from prizmkit_runtime import runners
2094
1830
  from prizmkit_runtime.runner_models import family_for, parse_invocation
2095
1831
 
@@ -2100,246 +1836,158 @@ def test_feature_and_bugfix_explicit_worktree_launches_from_worktree_and_renders
2100
1836
  invocation = parse_invocation(family, "run", ())
2101
1837
  invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan if kind == "feature" else paths.bugfix_plan})
2102
1838
  observed = _install_runner_session_fakes(monkeypatch, runners)
2103
- setup_calls = []
2104
1839
  lifecycle_order = []
2105
1840
 
2106
- def fake_setup(runtime):
2107
- lifecycle_order.append("worktree_setup")
2108
- setup_calls.append(runtime)
2109
- runtime.worktree_path.mkdir(parents=True, exist_ok=True)
2110
- return SimpleNamespace(ok=True, runtime=runtime, reason="")
1841
+ def fake_run_git_plan(project_root, plan):
1842
+ lifecycle_order.append(plan.name)
1843
+ return SimpleNamespace(ok=True, plan=plan, results=())
2111
1844
 
2112
1845
  def fake_preflight(*args, **kwargs):
2113
1846
  lifecycle_order.append("preflight")
2114
1847
  return SimpleNamespace(attempted=False, committed=False, ok=True, result=None)
2115
1848
 
2116
1849
  monkeypatch.setattr(runners, "commit_preflight_ready_changes", fake_preflight)
2117
- monkeypatch.setattr(runners, "ensure_linked_worktree", fake_setup, raising=False)
1850
+ monkeypatch.setattr(runners, "run_git_plan", fake_run_git_plan)
2118
1851
 
2119
1852
  status = runners._process_item(family, invocation, item_id, paths, initial_metadata={})
2120
1853
 
2121
- expected_worktree = paths.state_dir / "worktrees" / branch.replace("/", "-")
2122
1854
  assert status == "completed"
2123
- assert lifecycle_order[:2] == ["preflight", "worktree_setup"]
2124
- assert setup_calls[0].worktree_path == expected_worktree.resolve()
2125
- assert observed.launch_cwds == [expected_worktree.resolve()]
1855
+ assert lifecycle_order[:2] == ["preflight", "branch_create"]
1856
+ assert observed.launch_cwds == [paths.project_root]
2126
1857
  assert observed.prompt_calls[0]["project_root"] == paths.project_root
2127
- assert observed.prompt_calls[0]["execution_root"] == expected_worktree.resolve()
1858
+ assert observed.prompt_calls[0]["execution_root"] == paths.project_root
1859
+ checkout = json.loads((family.state_dir / item_id / "checkout.json").read_text(encoding="utf-8"))
1860
+ assert checkout["checkout_mode"] == "branch"
2128
1861
 
2129
1862
 
2130
- def test_worktree_checkout_mode_and_path_survive_environment_changes(monkeypatch, tmp_path):
1863
+ def test_legacy_worktree_checkout_identity_fails_fast_before_launch(monkeypatch, tmp_path):
2131
1864
  from prizmkit_runtime import runners
2132
1865
  from prizmkit_runtime.runner_models import family_for, parse_invocation
2133
- from prizmkit_runtime.task_checkout import CHECKOUT_MODE_WORKTREE, TaskCheckout, persist_task_checkout
1866
+ from prizmkit_runtime.task_checkout import TaskCheckoutError, task_checkout_path
2134
1867
 
2135
1868
  paths = _make_paths(tmp_path)
2136
1869
  family = family_for("feature", paths)
2137
1870
  invocation = parse_invocation(family, "run", ())
2138
1871
  invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
2139
- branch = "dev/F-001-worktree-resume"
2140
- worktree_path = (paths.state_dir / "worktrees" / "dev-F-001-worktree-resume").resolve()
2141
- persist_task_checkout(
2142
- family.state_dir,
2143
- TaskCheckout.active(
2144
- "feature",
2145
- "F-001",
2146
- branch,
2147
- "main",
2148
- checkout_mode=CHECKOUT_MODE_WORKTREE,
2149
- worktree_path=str(worktree_path),
1872
+ legacy_path = task_checkout_path(family.state_dir, "F-001")
1873
+ legacy_path.parent.mkdir(parents=True, exist_ok=True)
1874
+ legacy_path.write_text(
1875
+ json.dumps(
1876
+ {
1877
+ "task_type": "feature",
1878
+ "task_id": "F-001",
1879
+ "state": "active",
1880
+ "active_dev_branch": "dev/F-001-worktree-resume",
1881
+ "base_branch": "main",
1882
+ "checkout_mode": "worktree",
1883
+ "worktree_path": str((paths.state_dir / "worktrees" / "dev-F-001-worktree-resume").resolve()),
1884
+ }
2150
1885
  ),
1886
+ encoding="utf-8",
2151
1887
  )
2152
1888
  observed = _install_runner_session_fakes(monkeypatch, runners)
2153
- setup_calls = []
2154
-
2155
- def fake_setup(runtime):
2156
- setup_calls.append(runtime)
2157
- runtime.worktree_path.mkdir(parents=True, exist_ok=True)
2158
- return SimpleNamespace(ok=True, runtime=runtime, reason="")
2159
-
2160
1889
  monkeypatch.delenv("USE_WORKTREE", raising=False)
2161
1890
  monkeypatch.delenv("DEV_BRANCH", raising=False)
2162
- monkeypatch.setattr(runners, "ensure_linked_worktree", fake_setup)
2163
1891
 
2164
- status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
1892
+ with pytest.raises(TaskCheckoutError, match="retired worktree checkout mode"):
1893
+ runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
2165
1894
 
2166
- assert status == "completed"
2167
- assert setup_calls[0].worktree_path == worktree_path
2168
- assert observed.launch_cwds == [worktree_path]
1895
+ assert observed.launch_cwds == []
2169
1896
 
2170
1897
 
2171
- def test_successful_worktree_session_merges_cleans_branch_and_honors_auto_push(monkeypatch, tmp_path):
1898
+ def test_successful_branch_session_merges_and_honors_auto_push(monkeypatch, tmp_path):
2172
1899
  from prizmkit_runtime import runners
2173
1900
  from prizmkit_runtime.runner_models import family_for, parse_invocation
2174
1901
 
2175
- monkeypatch.setenv("USE_WORKTREE", "1")
2176
1902
  monkeypatch.setenv("DEV_BRANCH", "dev/F-001-test")
2177
1903
  monkeypatch.setenv("AUTO_PUSH", "1")
2178
1904
  paths = _make_paths(tmp_path)
2179
1905
  family = family_for("feature", paths)
2180
1906
  invocation = parse_invocation(family, "run", ())
2181
1907
  invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
2182
- observed = _install_runner_session_fakes(monkeypatch, runners)
2183
- monkeypatch.setattr(runners, "ensure_linked_worktree", lambda runtime: SimpleNamespace(ok=True, runtime=runtime, reason=""), raising=False)
1908
+ _install_runner_session_fakes(monkeypatch, runners)
1909
+ plans = []
1910
+ monkeypatch.setattr(
1911
+ runners,
1912
+ "run_git_plan",
1913
+ lambda project_root, plan: plans.append(plan) or SimpleNamespace(ok=True, plan=plan, results=()),
1914
+ )
2184
1915
 
2185
1916
  status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
2186
1917
 
2187
1918
  assert status == "completed"
2188
- assert observed.merge_calls and observed.merge_calls[0][1] is True
2189
- assert observed.cleanup_calls and observed.cleanup_calls[0][1] is True
1919
+ merge_plans = [plan for plan in plans if plan.name == "branch_merge"]
1920
+ assert merge_plans
1921
+ assert any(command.args == ("push",) for command in merge_plans[-1].commands)
2190
1922
  checkout = json.loads((paths.feature_state_dir / "F-001" / "checkout.json").read_text(encoding="utf-8"))
2191
1923
  assert checkout["state"] == "completed"
1924
+ assert checkout["checkout_mode"] == "branch"
2192
1925
  assert checkout["active_dev_branch"] == "dev/F-001-test"
2193
1926
 
2194
1927
 
2195
- def test_worktree_merge_conflict_writes_session_status_and_updates_merge_conflict(monkeypatch, tmp_path):
1928
+ def test_branch_merge_conflict_writes_session_status_and_updates_merge_conflict(monkeypatch, tmp_path):
2196
1929
  from prizmkit_runtime import runners
2197
1930
  from prizmkit_runtime.runner_models import family_for, parse_invocation
2198
1931
 
2199
- monkeypatch.setenv("USE_WORKTREE", "1")
2200
1932
  monkeypatch.setenv("DEV_BRANCH", "dev/F-001-test")
2201
1933
  paths = _make_paths(tmp_path)
2202
1934
  family = family_for("feature", paths)
2203
1935
  invocation = parse_invocation(family, "run", ())
2204
1936
  invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
2205
1937
  observed = _install_runner_session_fakes(monkeypatch, runners)
2206
- monkeypatch.setattr(runners, "ensure_linked_worktree", lambda runtime: SimpleNamespace(ok=True, runtime=runtime, reason=""), raising=False)
2207
- monkeypatch.setattr(runners, "merge_linked_worktree", lambda runtime, *, auto_push=False: SimpleNamespace(ok=False, reason="merge_conflict", runtime=runtime, results=()), raising=False)
1938
+
1939
+ def fake_run_git_plan(project_root, plan):
1940
+ if plan.name == "branch_merge":
1941
+ return SimpleNamespace(ok=False, plan=plan, results=())
1942
+ return SimpleNamespace(ok=True, plan=plan, results=())
1943
+
1944
+ monkeypatch.setattr(runners, "run_git_plan", fake_run_git_plan)
1945
+ monkeypatch.setattr(runners, "commit_wip_changes", lambda *args, **kwargs: SimpleNamespace(ok=True))
1946
+ monkeypatch.setattr(runners, "branch_ensure_return", lambda *args, **kwargs: SimpleNamespace(ok=True))
2208
1947
 
2209
1948
  status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
2210
1949
 
2211
1950
  assert status == "completed"
2212
1951
  assert observed.updates[-1][0] == "merge_conflict"
2213
- assert observed.cleanup_calls == []
2214
1952
  checkout = json.loads((paths.feature_state_dir / "F-001" / "checkout.json").read_text(encoding="utf-8"))
2215
1953
  assert checkout["state"] == "active"
2216
- assert checkout["checkout_mode"] == "worktree"
1954
+ assert checkout["checkout_mode"] == "branch"
2217
1955
  session_status = json.loads((paths.feature_state_dir / "F-001" / "sessions" / "F-001-session-1" / "session-status.json").read_text(encoding="utf-8"))
2218
1956
  assert session_status["status"] == "merge_conflict"
2219
1957
  assert session_status["task_id"] == "F-001"
2220
1958
  assert session_status["task_type"] == "feature"
2221
1959
  assert session_status["base_branch"] == "main"
2222
1960
  assert session_status["active_dev_branch"] == "dev/F-001-test"
2223
- assert session_status["worktree_path"].endswith("dev-F-001-test")
1961
+ assert "worktree_path" not in session_status
2224
1962
 
2225
1963
 
2226
- def test_terminal_worktree_failure_saves_wip_and_preserves_checkout(monkeypatch, tmp_path):
1964
+ def test_terminal_branch_failure_saves_wip_and_preserves_checkout(monkeypatch, tmp_path):
2227
1965
  from prizmkit_runtime import runners
2228
1966
  from prizmkit_runtime.runner_models import family_for, parse_invocation
2229
1967
 
2230
- monkeypatch.setenv("USE_WORKTREE", "1")
2231
1968
  monkeypatch.setenv("DEV_BRANCH", "dev/F-001-test")
2232
1969
  paths = _make_paths(tmp_path)
2233
1970
  family = family_for("feature", paths)
2234
1971
  invocation = parse_invocation(family, "run", ())
2235
1972
  invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
2236
1973
  observed = _install_runner_session_fakes(monkeypatch, runners, statuses=("crashed",), update_status="failed")
2237
- monkeypatch.setattr(runners, "ensure_linked_worktree", lambda runtime: SimpleNamespace(ok=True, runtime=runtime, reason=""), raising=False)
1974
+ wip_calls = []
1975
+ return_calls = []
1976
+ monkeypatch.setattr(runners, "run_git_plan", lambda project_root, plan: SimpleNamespace(ok=True, plan=plan, results=()))
1977
+ monkeypatch.setattr(runners, "commit_wip_changes", lambda *args, **kwargs: wip_calls.append(args) or SimpleNamespace(ok=True))
1978
+ monkeypatch.setattr(runners, "branch_ensure_return", lambda *args, **kwargs: return_calls.append(args) or SimpleNamespace(ok=True))
2238
1979
 
2239
1980
  status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
2240
1981
 
2241
1982
  assert status == "failed"
2242
- assert observed.wip_calls
2243
- assert observed.cleanup_calls == []
1983
+ assert wip_calls
1984
+ assert return_calls == [(paths.project_root, "main", "dev/F-001-test")]
2244
1985
  checkout = json.loads((paths.feature_state_dir / "F-001" / "checkout.json").read_text(encoding="utf-8"))
2245
1986
  assert checkout["state"] == "active"
2246
- assert checkout["checkout_mode"] == "worktree"
1987
+ assert checkout["checkout_mode"] == "branch"
2247
1988
  assert observed.updates[-1][0] == "crashed"
2248
1989
 
2249
1990
 
2250
- def test_explicit_worktree_materializes_ignored_support_assets_before_prompt_and_launch(monkeypatch, tmp_path):
2251
- from prizmkit_runtime import runners
2252
- from prizmkit_runtime.paths import resolve_runtime_paths
2253
- from prizmkit_runtime.runner_models import PromptGenerationResult, SessionClassification, family_for, parse_invocation
2254
-
2255
- project = tmp_path / "repo"
2256
- project.mkdir()
2257
- subprocess.run(["git", "init", "-b", "main"], cwd=project, check=True, stdout=subprocess.DEVNULL)
2258
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=project, check=True)
2259
- subprocess.run(["git", "config", "user.name", "Test"], cwd=project, check=True)
2260
- (project / ".gitignore").write_text(".claude/\n.prizmkit/\n", encoding="utf-8")
2261
- (project / "tracked.txt").write_text("tracked\n", encoding="utf-8")
2262
- subprocess.run(["git", "add", ".gitignore", "tracked.txt"], cwd=project, check=True)
2263
- subprocess.run(["git", "commit", "-m", "base"], cwd=project, check=True, stdout=subprocess.DEVNULL)
2264
-
2265
- (project / ".claude" / "commands").mkdir(parents=True)
2266
- (project / ".claude" / "commands" / "prizmkit.md").write_text("skill", encoding="utf-8")
2267
- (project / ".prizmkit" / "prizm-docs").mkdir(parents=True)
2268
- (project / ".prizmkit" / "prizm-docs" / "root.prizm").write_text("PRIZM_VERSION: 1\n", encoding="utf-8")
2269
- (project / ".prizmkit" / "dev-pipeline" / "scripts").mkdir(parents=True)
2270
- (project / ".prizmkit" / "dev-pipeline" / "scripts" / "init-change-artifact.py").write_text("# init", encoding="utf-8")
2271
- (project / ".prizmkit" / "config.json").write_text(json.dumps({"completion_notes": ["Completed durable workflow"]}), encoding="utf-8")
2272
- (project / ".prizmkit" / "manifest.json").write_text(json.dumps({"completion_notes": ["Completed durable workflow"]}), encoding="utf-8")
2273
-
2274
- paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=project)
2275
- family = family_for("feature", paths)
2276
- invocation = parse_invocation(family, "run", ())
2277
- invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
2278
- launch_cwds = []
2279
-
2280
- monkeypatch.setenv("USE_WORKTREE", "1")
2281
- monkeypatch.setenv("DEV_BRANCH", "dev/F-001-support-assets")
2282
- monkeypatch.setattr(
2283
- runners,
2284
- "load_runtime_config",
2285
- lambda paths: SimpleNamespace(
2286
- ai_client=SimpleNamespace(command="fake-ai", platform="codebuddy"),
2287
- model="fallback-model",
2288
- effort=None,
2289
- ),
2290
- )
2291
- monkeypatch.setattr(runners, "detect_stream_json_support", lambda command, platform: SimpleNamespace(enabled=False))
2292
- monkeypatch.setattr(runners, "start_item", lambda *args, **kwargs: SimpleNamespace(ok=True, text="", data={"new_status": "in_progress"}))
2293
- monkeypatch.setattr(runners, "commit_preflight_ready_changes", lambda *args, **kwargs: SimpleNamespace(attempted=False, committed=False, ok=True, result=None))
2294
- monkeypatch.setattr(runners, "commit_pre_branch_bookkeeping", lambda *args, **kwargs: None)
2295
- monkeypatch.setattr(runners, "commit_final_bookkeeping", lambda *args, **kwargs: None)
2296
- monkeypatch.setattr(runners, "_session_id", lambda item_id: f"{item_id}-session")
2297
- monkeypatch.setattr(runners, "update_item", lambda *args, **kwargs: SimpleNamespace(ok=True, text="", data={"new_status": "completed"}))
2298
-
2299
- def fake_generate_prompt(family, invocation, **kwargs):
2300
- execution_root = kwargs["execution_root"]
2301
- assert execution_root != project
2302
- assert (execution_root / ".claude" / "commands" / "prizmkit.md").is_file()
2303
- assert (execution_root / ".prizmkit" / "prizm-docs" / "root.prizm").is_file()
2304
- assert (execution_root / ".prizmkit" / "config.json").is_file()
2305
- assert (execution_root / ".prizmkit" / "manifest.json").is_file()
2306
- assert (execution_root / ".prizmkit" / "dev-pipeline" / "scripts" / "init-change-artifact.py").is_file()
2307
- assert not (execution_root / ".prizmkit" / "dev-pipeline" / "run-feature.sh").exists()
2308
- session_paths = kwargs["session_paths"]
2309
- return PromptGenerationResult(
2310
- output_path=session_paths.prompt_path,
2311
- model="",
2312
- checkpoint_path=execution_root / ".prizmkit" / "specs" / "001-support" / "workflow-checkpoint.json",
2313
- artifact_path=execution_root / ".prizmkit" / "specs" / "001-support",
2314
- raw={},
2315
- )
2316
-
2317
- class FakeLauncher:
2318
- def __init__(self, config):
2319
- self.config = config
2320
-
2321
- def run(self):
2322
- launch_cwds.append(self.config.cwd)
2323
- return SimpleNamespace(progress_summary=SimpleNamespace(), fatal_error_code="")
2324
-
2325
- monkeypatch.setattr(runners, "generate_prompt", fake_generate_prompt)
2326
- monkeypatch.setattr(runners, "AISessionLauncher", FakeLauncher)
2327
- monkeypatch.setattr(
2328
- runners,
2329
- "classify_session",
2330
- lambda *args, **kwargs: SessionClassification(
2331
- "success", reason="success", fatal_error_code="",
2332
- progress_fingerprint={"head_commit": "success"}, no_progress_count=0,
2333
- ),
2334
- )
2335
-
2336
- status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
2337
-
2338
- assert status == "completed"
2339
- assert launch_cwds and launch_cwds[0] == paths.state_dir / "worktrees" / "dev-F-001-support-assets"
2340
- assert not launch_cwds[0].exists()
2341
-
2342
-
2343
1991
  def test_default_no_worktree_preserves_main_worktree_branch_launch(monkeypatch, tmp_path):
2344
1992
  from prizmkit_runtime import runners
2345
1993
  from prizmkit_runtime.runner_models import family_for, parse_invocation
@@ -2491,66 +2139,6 @@ def test_no_worktree_recovers_completed_pending_branch_before_new_session(monkey
2491
2139
  assert "branch_merge" in events
2492
2140
 
2493
2141
 
2494
- def test_worktree_recovers_completed_pending_branch_from_base_session_history(monkeypatch, tmp_path):
2495
- from prizmkit_runtime import runners
2496
- from prizmkit_runtime.runner_models import family_for, parse_invocation
2497
-
2498
- monkeypatch.setenv("USE_WORKTREE", "1")
2499
- paths = _make_paths(tmp_path)
2500
- family = family_for("feature", paths)
2501
- invocation = parse_invocation(family, "run", ())
2502
- invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
2503
- base_session_dir = paths.feature_state_dir / "F-001" / "sessions" / "F-001-session-old"
2504
- base_session_dir.mkdir(parents=True)
2505
- (base_session_dir / "session-status.json").write_text(
2506
- json.dumps({"base_branch": "main", "active_dev_branch": "dev/F-001-worktree"}),
2507
- encoding="utf-8",
2508
- )
2509
- updates = []
2510
- cleanup_calls = []
2511
- merge_calls = []
2512
-
2513
- monkeypatch.setattr(
2514
- runners,
2515
- "load_runtime_config",
2516
- lambda paths: SimpleNamespace(ai_client=SimpleNamespace(command="fake-ai", platform="codebuddy"), model="", effort=None),
2517
- )
2518
- monkeypatch.setattr(runners, "current_branch", lambda _root: "main")
2519
- monkeypatch.setattr(runners, "ensure_linked_worktree", lambda runtime: SimpleNamespace(ok=True, runtime=runtime, reason=""), raising=False)
2520
- monkeypatch.setattr(runners, "materialize_worktree_support_assets", lambda runtime: SimpleNamespace(ok=True, reason=""), raising=False)
2521
- monkeypatch.setattr(runners, "has_completed_artifact_path", lambda artifact: True)
2522
- monkeypatch.setattr(runners, "has_branch_completion_evidence", lambda *args, **kwargs: True)
2523
- monkeypatch.setattr(runners, "start_item", lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("should not restart completed work")))
2524
- monkeypatch.setattr(runners, "generate_prompt", lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("should not launch prompt")))
2525
- monkeypatch.setattr(runners, "commit_final_bookkeeping", lambda *args, **kwargs: None)
2526
- monkeypatch.setattr(runners, "commit_task_branch_changes", lambda *args, **kwargs: None)
2527
- monkeypatch.setattr(runners, "commit_preflight_ready_changes", lambda *args, **kwargs: SimpleNamespace(attempted=False, committed=False, ok=True, result=None))
2528
-
2529
- def fake_update(family, invocation, item_id, session_status, session_id, project_root, **metadata):
2530
- updates.append((session_status, session_id, project_root, metadata))
2531
- return SimpleNamespace(ok=True, text="", data={"new_status": "completed"})
2532
-
2533
- def fake_merge(runtime, *, auto_push=False):
2534
- merge_calls.append((runtime, auto_push))
2535
- return SimpleNamespace(ok=True, reason="", runtime=runtime, results=())
2536
-
2537
- def fake_cleanup(runtime, *, delete_branch=True):
2538
- cleanup_calls.append((runtime, delete_branch))
2539
- return SimpleNamespace(ok=True, reason="")
2540
-
2541
- monkeypatch.setattr(runners, "update_item", fake_update)
2542
- monkeypatch.setattr(runners, "merge_linked_worktree", fake_merge, raising=False)
2543
- monkeypatch.setattr(runners, "guarded_worktree_remove", fake_cleanup, raising=False)
2544
-
2545
- status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={"title": "Low"})
2546
-
2547
- assert status == "completed"
2548
- assert updates[0][0] == "success"
2549
- assert updates[0][1] == "F-001-session-old"
2550
- assert updates[0][2] != paths.project_root
2551
- assert merge_calls and cleanup_calls[-1][1] is True
2552
-
2553
-
2554
2142
  def test_success_final_commit_failure_preserves_checkout_without_merge(monkeypatch, tmp_path):
2555
2143
  from prizmkit_runtime import runners
2556
2144
  from prizmkit_runtime.runner_models import family_for, parse_invocation
@@ -2633,7 +2221,6 @@ def test_default_branch_names_keep_timestamp_for_each_runner_family(monkeypatch,
2633
2221
 
2634
2222
  assert runners._default_branch_name(family_for("feature", paths), "F-001") == "dev/F-001-20260707010203"
2635
2223
  assert runners._default_branch_name(family_for("bugfix", paths), "B-001") == "bugfix/B-001-20260707010203"
2636
- assert runners._default_branch_name(family_for("refactor", paths), "R-001") == "refactor/R-001-20260707010203"
2637
2224
 
2638
2225
 
2639
2226
  @pytest.mark.parametrize(
@@ -2641,7 +2228,6 @@ def test_default_branch_names_keep_timestamp_for_each_runner_family(monkeypatch,
2641
2228
  [
2642
2229
  ("feature", "F-001", "dev/F-001-20260707010203"),
2643
2230
  ("bugfix", "B-001", "bugfix/B-001-20260707010203"),
2644
- ("refactor", "R-001", "refactor/R-001-20260707010203"),
2645
2231
  ],
2646
2232
  )
2647
2233
  def test_no_worktree_exhausted_failure_stays_on_task_branch_without_merge_for_all_families(monkeypatch, tmp_path, kind, item_id, branch):
@@ -2652,7 +2238,7 @@ def test_no_worktree_exhausted_failure_stays_on_task_branch_without_merge_for_al
2652
2238
  paths = _make_paths(tmp_path / kind)
2653
2239
  family = family_for(kind, paths)
2654
2240
  invocation = parse_invocation(family, "run", ())
2655
- plan_path = {"feature": paths.feature_plan, "bugfix": paths.bugfix_plan, "refactor": paths.refactor_plan}[kind]
2241
+ plan_path = {"feature": paths.feature_plan, "bugfix": paths.bugfix_plan}[kind]
2656
2242
  invocation = invocation.__class__(**{**invocation.__dict__, "list_path": plan_path})
2657
2243
  _install_runner_session_fakes(monkeypatch, runners, statuses=("crashed",), update_status="failed")
2658
2244
  events = []
@@ -2728,19 +2314,17 @@ def test_no_worktree_runner_ignores_recovery_side_effect_branch(monkeypatch, tmp
2728
2314
  [
2729
2315
  ("feature", "F-001", "dev/F-001-preflight-fail"),
2730
2316
  ("bugfix", "B-001", "bugfix/B-001-preflight-fail"),
2731
- ("refactor", "R-001", "refactor/R-001-preflight-fail"),
2732
2317
  ],
2733
2318
  )
2734
- def test_preflight_commit_failure_aborts_before_branch_worktree_or_status_for_all_families(monkeypatch, tmp_path, kind, item_id, branch):
2319
+ def test_preflight_commit_failure_aborts_before_branch_or_status_for_all_families(monkeypatch, tmp_path, kind, item_id, branch):
2735
2320
  from prizmkit_runtime import runners
2736
2321
  from prizmkit_runtime.runner_models import family_for, parse_invocation
2737
2322
 
2738
2323
  monkeypatch.setenv("DEV_BRANCH", branch)
2739
- monkeypatch.setenv("USE_WORKTREE", "1")
2740
2324
  paths = _make_paths(tmp_path / kind)
2741
2325
  family = family_for(kind, paths)
2742
2326
  invocation = parse_invocation(family, "run", ())
2743
- plan_path = {"feature": paths.feature_plan, "bugfix": paths.bugfix_plan, "refactor": paths.refactor_plan}[kind]
2327
+ plan_path = {"feature": paths.feature_plan, "bugfix": paths.bugfix_plan}[kind]
2744
2328
  invocation = invocation.__class__(**{**invocation.__dict__, "list_path": plan_path})
2745
2329
  events = []
2746
2330
 
@@ -2752,7 +2336,6 @@ def test_preflight_commit_failure_aborts_before_branch_worktree_or_status_for_al
2752
2336
  monkeypatch.setattr(runners, "current_branch", lambda _root: "main")
2753
2337
  monkeypatch.setattr(runners, "commit_preflight_ready_changes", lambda *args, **kwargs: SimpleNamespace(attempted=True, committed=False, result=SimpleNamespace(stderr="commit failed\n", stdout="")))
2754
2338
  monkeypatch.setattr(runners, "run_git_plan", lambda *args, **kwargs: events.append("branch_create"))
2755
- monkeypatch.setattr(runners, "ensure_linked_worktree", lambda *args, **kwargs: events.append("worktree_create"), raising=False)
2756
2339
  monkeypatch.setattr(runners, "start_item", lambda *args, **kwargs: events.append("start_item"))
2757
2340
 
2758
2341
  with pytest.raises(RuntimeError, match="Preflight dirty workspace preservation failed"):
@@ -2952,56 +2535,6 @@ def test_interrupt_return_failure_is_reported_without_forcing_checkout(monkeypat
2952
2535
  assert "After resolving the Git blocker" not in captured.err
2953
2536
 
2954
2537
 
2955
- def test_worktree_interrupt_uses_same_wip_and_base_return_contract(monkeypatch, tmp_path, capsys):
2956
- from prizmkit_runtime import runners
2957
- from prizmkit_runtime.runner_models import family_for, parse_invocation
2958
-
2959
- monkeypatch.setenv("USE_WORKTREE", "1")
2960
- monkeypatch.setenv("DEV_BRANCH", "dev/F-001-interrupt")
2961
- paths = _make_paths(tmp_path)
2962
- family = family_for("feature", paths)
2963
- invocation = parse_invocation(family, "run", ())
2964
- invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
2965
- observed = _install_runner_session_fakes(monkeypatch, runners)
2966
- monkeypatch.setattr(
2967
- runners,
2968
- "ensure_linked_worktree",
2969
- lambda runtime: SimpleNamespace(ok=True, runtime=runtime, reason=""),
2970
- )
2971
- preserve_calls = []
2972
- return_calls = []
2973
- monkeypatch.setattr(
2974
- runners,
2975
- "branch_save_wip",
2976
- lambda root, branch: preserve_calls.append((root, branch)) or SimpleNamespace(ok=True, results=()),
2977
- )
2978
- monkeypatch.setattr(
2979
- runners,
2980
- "branch_ensure_return",
2981
- lambda *args: return_calls.append(args) or SimpleNamespace(ok=True, results=()),
2982
- )
2983
-
2984
- class InterruptingLauncher:
2985
- def __init__(self, config):
2986
- self.config = config
2987
-
2988
- def run(self):
2989
- raise KeyboardInterrupt
2990
-
2991
- monkeypatch.setattr(runners, "AISessionLauncher", InterruptingLauncher)
2992
-
2993
- with pytest.raises(KeyboardInterrupt):
2994
- runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
2995
-
2996
- captured = capsys.readouterr()
2997
- assert preserve_calls and preserve_calls[0][0] != paths.project_root
2998
- assert return_calls == [(paths.project_root, "main", "dev/F-001-interrupt")]
2999
- assert "Interrupted task F-001: no WIP commit needed" in captured.err
3000
- assert "caller checkout returned to main; no merge or push performed" in captured.err
3001
- assert observed.merge_calls == []
3002
- assert observed.cleanup_calls == []
3003
-
3004
-
3005
2538
  def test_run_pipeline_command_bridges_sigterm_and_restores_handler(monkeypatch, tmp_path):
3006
2539
  from prizmkit_runtime import runners
3007
2540
  from prizmkit_runtime.processes import describe_interruption
@@ -3053,7 +2586,6 @@ def test_interruption_cleanup_shield_ignores_and_restores_signals():
3053
2586
  [
3054
2587
  ("feature", "F-001", "dev/F-001-interrupt"),
3055
2588
  ("bugfix", "B-001", "bugfix/B-001-interrupt"),
3056
- ("refactor", "R-001", "refactor/R-001-interrupt"),
3057
2589
  ],
3058
2590
  )
3059
2591
  def test_interrupted_task_reuses_durable_checkout_on_next_process(monkeypatch, tmp_path, kind, item_id, branch):
@@ -3063,7 +2595,7 @@ def test_interrupted_task_reuses_durable_checkout_on_next_process(monkeypatch, t
3063
2595
 
3064
2596
  paths = _make_paths(tmp_path / kind)
3065
2597
  family = family_for(kind, paths)
3066
- plan_path = {"feature": paths.feature_plan, "bugfix": paths.bugfix_plan, "refactor": paths.refactor_plan}[kind]
2598
+ plan_path = {"feature": paths.feature_plan, "bugfix": paths.bugfix_plan}[kind]
3067
2599
  invocation = parse_invocation(family, "run", ())
3068
2600
  invocation = invocation.__class__(**{**invocation.__dict__, "list_path": plan_path})
3069
2601
  persist_task_checkout(family.state_dir, TaskCheckout.active(kind, item_id, branch, "main"))
@@ -3084,2423 +2616,358 @@ def test_interrupted_task_reuses_durable_checkout_on_next_process(monkeypatch, t
3084
2616
  assert observed.launch_cwds == [paths.project_root]
3085
2617
 
3086
2618
 
3087
- def _init_bookkeeping_repo(project_root, *, configure_identity=True):
3088
- subprocess.run(["git", "init", "-b", "main"], cwd=project_root, check=True, stdout=subprocess.DEVNULL)
3089
- if configure_identity:
3090
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=project_root, check=True)
3091
- subprocess.run(["git", "config", "user.name", "Test"], cwd=project_root, check=True)
3092
- (project_root / "staged.txt").write_text("base staged\n", encoding="utf-8")
3093
- (project_root / "unstaged.txt").write_text("base unstaged\n", encoding="utf-8")
3094
- subprocess.run(["git", "add", "staged.txt", "unstaged.txt"], cwd=project_root, check=True)
3095
- subprocess.run(
3096
- [
3097
- "git",
3098
- "-c",
3099
- "user.email=test@example.com",
3100
- "-c",
3101
- "user.name=Test",
3102
- "commit",
3103
- "-m",
3104
- "base",
3105
- ],
3106
- cwd=project_root,
3107
- check=True,
3108
- stdout=subprocess.DEVNULL,
3109
- )
3110
-
2619
+ def test_context_overflow_reuses_branch_and_skips_cleanup_until_terminal_outcome(monkeypatch, tmp_path):
2620
+ from prizmkit_runtime import runners
2621
+ from prizmkit_runtime.runner_models import family_for, parse_invocation
3111
2622
 
3112
- def _head_commit_count(project_root):
3113
- return int(
3114
- subprocess.run(
3115
- ["git", "rev-list", "--count", "HEAD"],
3116
- cwd=project_root,
3117
- check=True,
3118
- stdout=subprocess.PIPE,
3119
- text=True,
3120
- ).stdout.strip()
2623
+ monkeypatch.setenv("DEV_BRANCH", "dev/F-001-test")
2624
+ paths = _make_paths(tmp_path)
2625
+ family = family_for("feature", paths)
2626
+ invocation = parse_invocation(family, "run", ())
2627
+ invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
2628
+ observed = _install_runner_session_fakes(monkeypatch, runners, statuses=("context_overflow", "success"))
2629
+ sleep_calls = []
2630
+ monkeypatch.setattr(runners.time, "sleep", lambda seconds: sleep_calls.append(seconds))
2631
+ plan_names = []
2632
+ monkeypatch.setattr(
2633
+ runners,
2634
+ "run_git_plan",
2635
+ lambda project_root, plan: plan_names.append(plan.name) or SimpleNamespace(ok=True, plan=plan, results=()),
3121
2636
  )
3122
2637
 
2638
+ status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
3123
2639
 
3124
- def _head_message(project_root):
3125
- return subprocess.run(
3126
- ["git", "log", "-1", "--format=%s"],
3127
- cwd=project_root,
3128
- check=True,
3129
- stdout=subprocess.PIPE,
3130
- text=True,
3131
- ).stdout.strip()
3132
-
3133
-
3134
- def _head_files(project_root):
3135
- return set(
3136
- subprocess.run(
3137
- ["git", "show", "--name-only", "--format=", "HEAD"],
3138
- cwd=project_root,
3139
- check=True,
3140
- stdout=subprocess.PIPE,
3141
- text=True,
3142
- ).stdout.splitlines()
3143
- )
2640
+ assert status == "completed"
2641
+ assert plan_names == ["branch_create", "branch_merge"]
2642
+ assert observed.launch_cwds == [paths.project_root, paths.project_root]
2643
+ assert observed.prompt_calls[0]["execution_root"] == observed.prompt_calls[1]["execution_root"]
2644
+ assert observed.prompt_calls[0].get("continuation") is None
2645
+ assert observed.prompt_calls[1]["continuation"]["previous_session_id"] == "F-001-session-1"
2646
+ assert observed.updates[0][0] == "context_overflow"
2647
+ assert sleep_calls == [5]
3144
2648
 
3145
2649
 
3146
- @pytest.mark.parametrize(
3147
- ("scenario", "expected_files"),
3148
- [
3149
- ("staged_only", {"staged.txt"}),
3150
- ("unstaged_only", {"unstaged.txt"}),
3151
- ("mixed", {"staged.txt", "unstaged.txt", "new-visible.txt"}),
3152
- ],
3153
- )
3154
- def test_preflight_ready_commit_preserves_staged_unstaged_and_mixed_visible_changes(tmp_path, scenario, expected_files):
3155
- from prizmkit_runtime.gitops import HIDDEN_TOOL_WORKTREE_EXCLUDES
3156
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
3157
-
3158
- _init_bookkeeping_repo(tmp_path)
3159
- if scenario in {"staged_only", "mixed"}:
3160
- (tmp_path / "staged.txt").write_text("staged change\n", encoding="utf-8")
3161
- subprocess.run(["git", "add", "staged.txt"], cwd=tmp_path, check=True)
3162
- if scenario in {"unstaged_only", "mixed"}:
3163
- (tmp_path / "unstaged.txt").write_text("unstaged change\n", encoding="utf-8")
3164
- if scenario == "mixed":
3165
- (tmp_path / "new-visible.txt").write_text("new visible\n", encoding="utf-8")
3166
-
3167
- before_count = _head_commit_count(tmp_path)
3168
- result = commit_preflight_ready_changes(tmp_path, "F-123")
3169
- visible_status = subprocess.run(
3170
- ["git", "status", "--porcelain", "--", ".", *HIDDEN_TOOL_WORKTREE_EXCLUDES],
3171
- cwd=tmp_path,
3172
- check=True,
2650
+ def test_cli_family_status_uses_python_dispatch_not_transition_description(tmp_path):
2651
+ paths = _make_paths(tmp_path)
2652
+ _write_feature_list(paths)
2653
+ result = subprocess.run(
2654
+ [PYTHON_310_PLUS, str(CLI_PATH), "--project-root", str(paths.project_root), "status", "feature"],
2655
+ cwd=REPO_ROOT,
3173
2656
  stdout=subprocess.PIPE,
2657
+ stderr=subprocess.PIPE,
3174
2658
  text=True,
3175
- ).stdout
3176
-
3177
- assert result.attempted is True
3178
- assert result.committed is True
3179
- assert _head_commit_count(tmp_path) == before_count + 1
3180
- assert _head_message(tmp_path) == "chore: ready for F-123"
3181
- assert expected_files.issubset(_head_files(tmp_path))
3182
- assert visible_status == ""
3183
-
3184
-
3185
- def test_preflight_ready_commit_handles_exact_special_and_renamed_paths(tmp_path):
3186
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
3187
-
3188
- _init_bookkeeping_repo(tmp_path)
3189
- old_path = tmp_path / "old name -> café.txt"
3190
- old_path.write_text("old\n", encoding="utf-8")
3191
- subprocess.run(["git", "add", old_path.name], cwd=tmp_path, check=True)
3192
- subprocess.run(["git", "commit", "-m", "track special path"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3193
- new_path = tmp_path / 'new "quoted" \\ 名称.txt'
3194
- old_path.rename(new_path)
3195
- untracked_path = tmp_path / "untracked -> line\nbreak.txt"
3196
- untracked_path.write_text("new\n", encoding="utf-8")
3197
- colon_path = tmp_path / ":(glob)**.txt"
3198
- colon_path.write_text("literal pathspec\n", encoding="utf-8")
3199
-
3200
- result = commit_preflight_ready_changes(tmp_path, "R-001")
3201
- committed_files = set(
3202
- filter(
3203
- None,
3204
- subprocess.run(
3205
- ["git", "diff-tree", "--no-commit-id", "--name-only", "-r", "-z", "HEAD"],
3206
- cwd=tmp_path,
3207
- check=True,
3208
- stdout=subprocess.PIPE,
3209
- ).stdout.decode().split("\0"),
3210
- )
2659
+ check=False,
3211
2660
  )
3212
2661
 
3213
- assert result.committed is True
3214
- assert old_path.name in committed_files
3215
- assert new_path.name in committed_files
3216
- assert untracked_path.name in committed_files
3217
- assert colon_path.name in committed_files
3218
- assert _head_message(tmp_path) == "chore: ready for R-001"
3219
-
3220
-
3221
- @pytest.mark.parametrize("staged", [False, True])
3222
- def test_preflight_ready_commit_rejects_tracked_local_settings_before_checkout(tmp_path, staged):
3223
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
3224
-
3225
- _init_bookkeeping_repo(tmp_path)
3226
- local_settings = tmp_path / ".claude" / "settings.local.json"
3227
- local_settings.parent.mkdir(parents=True)
3228
- local_settings.write_text('{"permissions": []}\n', encoding="utf-8")
3229
- subprocess.run(["git", "add", "-f", ".claude/settings.local.json"], cwd=tmp_path, check=True)
3230
- subprocess.run(["git", "commit", "-m", "track local settings"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3231
- local_settings.write_text('{"permissions": ["secret"]}\n', encoding="utf-8")
3232
- if staged:
3233
- subprocess.run(["git", "add", ".claude/settings.local.json"], cwd=tmp_path, check=True)
3234
-
3235
- result = commit_preflight_ready_changes(tmp_path, "B-001")
3236
-
3237
- assert result.attempted is True
3238
- assert result.committed is False
3239
- assert result.result is not None
3240
- assert "Refusing to auto-commit local-only platform settings" in result.result.stderr
3241
- assert _head_message(tmp_path) == "track local settings"
3242
-
3243
-
3244
- def test_preflight_ready_commit_excludes_untracked_python_cache_outside_support_dirs(tmp_path):
3245
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
3246
-
3247
- _init_bookkeeping_repo(tmp_path)
3248
- (tmp_path / "visible.txt").write_text("visible\n", encoding="utf-8")
3249
- cache_paths = [
3250
- tmp_path / "__pycache__" / "top.cpython-312.pyc",
3251
- tmp_path / "src" / "package" / "__pycache__" / "module.cpython-312.pyc",
3252
- tmp_path / "src" / "standalone.pyo",
3253
- ]
3254
- for path in cache_paths:
3255
- path.parent.mkdir(parents=True, exist_ok=True)
3256
- path.write_text("compiled\n", encoding="utf-8")
2662
+ assert result.returncode == 0
2663
+ assert "Python feature status" in result.stdout
2664
+ assert "Transition command contract" not in result.stdout
3257
2665
 
3258
- result = commit_preflight_ready_changes(tmp_path, "F-001")
3259
- committed_files = _head_files(tmp_path)
3260
2666
 
3261
- assert result.committed is True
3262
- assert committed_files == {"visible.txt"}
3263
- assert all(path.is_file() for path in cache_paths)
2667
+ def _write_family_case(paths, kind, item_id=""):
2668
+ item_id = item_id or {"feature": "F-001", "bugfix": "B-001"}[kind]
2669
+ if kind == "feature":
2670
+ paths.feature_plan.write_text(json.dumps({"features": [{"id": item_id, "title": "Reset Thing", "status": "failed", "dependencies": []}]}), encoding="utf-8")
2671
+ state_dir = paths.feature_state_dir
2672
+ plan = paths.feature_plan
2673
+ elif kind == "bugfix":
2674
+ paths.bugfix_plan.write_text(json.dumps({"bugs": [{"id": item_id, "title": "Reset Bug", "description": "d", "severity": "medium", "priority": "medium", "status": "failed"}]}), encoding="utf-8")
2675
+ state_dir = paths.bugfix_state_dir
2676
+ plan = paths.bugfix_plan
2677
+ else:
2678
+ raise ValueError(f"Unsupported family kind: {kind}")
2679
+ state_dir.mkdir(parents=True, exist_ok=True)
2680
+ (state_dir / "pipeline.json").write_text(json.dumps({"completion_notes": ["Completed durable workflow"]}), encoding="utf-8")
2681
+ item_state = state_dir / item_id
2682
+ item_state.mkdir(parents=True, exist_ok=True)
2683
+ (item_state / "status.json").write_text(
2684
+ json.dumps(
2685
+ {
2686
+ "status": "in_progress",
2687
+ "retry_count": 2,
2688
+ "infra_error_count": 1,
2689
+ "last_infra_error_session_id": "infra-1",
2690
+ "last_session_id": "sess-1",
2691
+ "sessions": ["sess-1"],
2692
+ "continuation_pending": True,
2693
+ "continuation_reason": "context_overflow",
2694
+ "active_dev_branch": f"{kind}/{item_id}-branch",
2695
+ "continuation_summary_path": str(paths.project_root / ".prizmkit" / ("specs" if kind == "feature" else kind) / item_id / "continuation-summary.md"),
2696
+ }
2697
+ ),
2698
+ encoding="utf-8",
2699
+ )
2700
+ return plan, state_dir, item_state / "status.json"
3264
2701
 
3265
2702
 
3266
- def test_tracked_python_cache_remains_visible_to_task_commit(tmp_path):
3267
- from prizmkit_runtime.runner_bookkeeping import commit_task_branch_changes
2703
+ def test_python_reset_warns_before_mutation_and_matches_snapshot_cleanup(tmp_path):
2704
+ from prizmkit_runtime.reset import run_reset_command
3268
2705
  from prizmkit_runtime.runner_models import family_for
2706
+ from prizmkit_runtime.task_checkout import load_task_checkout
3269
2707
 
3270
- paths = _make_paths(tmp_path)
3271
- _init_bookkeeping_repo(paths.project_root)
3272
- tracked_cache = paths.project_root / "src" / "__pycache__" / "module.pyc"
3273
- tracked_cache.parent.mkdir(parents=True)
3274
- tracked_cache.write_text("baseline\n", encoding="utf-8")
3275
- subprocess.run(["git", "add", tracked_cache.relative_to(paths.project_root).as_posix()], cwd=paths.project_root, check=True)
3276
- subprocess.run(["git", "commit", "-m", "track cache"], cwd=paths.project_root, check=True, stdout=subprocess.DEVNULL)
3277
- tracked_cache.write_text("task change\n", encoding="utf-8")
3278
-
3279
- result = commit_task_branch_changes(paths.project_root, family_for("bugfix", paths), "B-001", "completed")
2708
+ snapshot = json.loads((REPO_ROOT / "tests" / "fixtures" / "dev-pipeline-behavior-snapshots" / "unix-runtime.json").read_text(encoding="utf-8"))
2709
+ for kind, item_id in [("feature", "F-001"), ("bugfix", "B-001")]:
2710
+ paths = _make_paths(tmp_path / kind)
2711
+ _plan, _state_dir, status_file = _write_family_case(paths, kind, item_id)
2712
+ result = run_reset_command(kind, (item_id, "--fresh-checkout"), paths)
2713
+ output = result.render()
2714
+ reset_marker = f"Resetting {item_id} status"
3280
2715
 
3281
- assert result.committed is True
3282
- assert tracked_cache.relative_to(paths.project_root).as_posix() in _head_files(paths.project_root)
3283
- assert subprocess.run(
3284
- ["git", "status", "--short", "--untracked-files=no"],
3285
- cwd=paths.project_root,
3286
- check=True,
3287
- stdout=subprocess.PIPE,
3288
- text=True,
3289
- ).stdout == ""
2716
+ assert result.exit_code == snapshot["resetBehavior"]["manualResetWarningOrder"][kind]["exitCode"]
2717
+ assert "Continuation pending" in output
2718
+ assert "Pending continuation branch" in output
2719
+ assert output.index("Continuation pending") < output.index(reset_marker)
2720
+ runtime = json.loads(status_file.read_text(encoding="utf-8"))
2721
+ expected_runtime = snapshot["statusUpdaterBehavior"]["resetCleanMetadataCleanup"][kind]["reset"]["runtime"]
2722
+ for key, value in expected_runtime.items():
2723
+ assert runtime.get(key) == value
2724
+ assert "continuation_pending" not in runtime
2725
+ family = family_for(kind, paths)
2726
+ checkout = load_task_checkout(family.state_dir, family.task_type, item_id)
2727
+ assert checkout is not None
2728
+ assert checkout.is_reset
2729
+ assert checkout.active_dev_branch == ""
2730
+ assert checkout.base_branch == ""
3290
2731
 
3291
2732
 
3292
- @pytest.mark.parametrize("helper_name", ["commit_task_branch_changes", "commit_wip_changes"])
3293
- def test_task_commit_helpers_propagate_staging_failure_without_commit(monkeypatch, tmp_path, helper_name):
3294
- from prizmkit_runtime import runner_bookkeeping
3295
- from prizmkit_runtime.gitops import GitCommandResult
2733
+ def test_python_reset_cleans_authoritative_custom_branch_before_reset_marker(monkeypatch, tmp_path):
2734
+ from prizmkit_runtime import reset as reset_runtime
2735
+ from prizmkit_runtime.reset import run_reset_command
3296
2736
  from prizmkit_runtime.runner_models import family_for
2737
+ from prizmkit_runtime.task_checkout import TaskCheckout, load_task_checkout, persist_task_checkout
3297
2738
 
3298
2739
  paths = _make_paths(tmp_path)
3299
- family = family_for("bugfix", paths)
3300
- status_result = GitCommandResult(("status",), 0, " M app.txt\0", "")
3301
- indexed_result = GitCommandResult(("ls-files",), 0, "app.txt\0", "")
3302
- monkeypatch.setattr(
3303
- runner_bookkeeping,
3304
- "visible_task_paths",
3305
- lambda _root: (("app.txt",), status_result),
3306
- )
2740
+ _write_family_case(paths, "feature", "F-001")
2741
+ family = family_for("feature", paths)
2742
+ custom_branch = "custom/feature-checkout"
2743
+ persist_task_checkout(family.state_dir, TaskCheckout.active("feature", "F-001", custom_branch, "main"))
2744
+ cleanup_calls = []
2745
+
2746
+ monkeypatch.setattr(reset_runtime, "list_reset_branches", lambda *args: ())
3307
2747
  monkeypatch.setattr(
3308
- runner_bookkeeping,
3309
- "addable_task_paths",
3310
- lambda _root, _paths: (("app.txt",), indexed_result),
2748
+ reset_runtime,
2749
+ "reset_cleanup_branch",
2750
+ lambda project_root, branch, *, return_branch, delete: cleanup_calls.append((branch, delete))
2751
+ or SimpleNamespace(branch=branch, cleaned=True, deleted=False, returned_to=return_branch, warnings=()),
3311
2752
  )
3312
- calls = []
3313
2753
 
3314
- def fail_add(_root, args):
3315
- args = tuple(args)
3316
- calls.append(args)
3317
- assert args[0] != "commit"
3318
- return GitCommandResult(args, 1, "", "staging failed")
2754
+ result = run_reset_command("feature", ("F-001", "--fresh-checkout"), paths)
3319
2755
 
3320
- monkeypatch.setattr(runner_bookkeeping, "run_git_command", fail_add)
3321
- helper = getattr(runner_bookkeeping, helper_name)
2756
+ assert result.exit_code == 0
2757
+ assert cleanup_calls == [(custom_branch, False)]
2758
+ checkout = load_task_checkout(family.state_dir, family.task_type, "F-001")
2759
+ assert checkout is not None and checkout.is_reset
3322
2760
 
3323
- result = helper(paths.project_root, family, "B-001", "failed")
3324
2761
 
3325
- assert result.attempted is True
3326
- assert result.committed is False
3327
- assert result.result is not None and result.result.stderr == "staging failed"
3328
- assert calls and all(args[0] != "commit" for args in calls)
2762
+ def test_python_reset_failure_keeps_authoritative_checkout_active(monkeypatch, tmp_path):
2763
+ from prizmkit_runtime import reset as reset_runtime
2764
+ from prizmkit_runtime.reset import run_reset_command
2765
+ from prizmkit_runtime.runner_models import family_for
2766
+ from prizmkit_runtime.task_checkout import TaskCheckout, load_task_checkout, persist_task_checkout
3329
2767
 
2768
+ paths = _make_paths(tmp_path)
2769
+ _write_family_case(paths, "feature", "F-001")
2770
+ family = family_for("feature", paths)
2771
+ checkout = TaskCheckout.active("feature", "F-001", "custom/feature-checkout", "main")
2772
+ persist_task_checkout(family.state_dir, checkout)
2773
+ monkeypatch.setattr(reset_runtime, "list_reset_branches", lambda *args: ())
2774
+ monkeypatch.setattr(
2775
+ reset_runtime,
2776
+ "reset_cleanup_branch",
2777
+ lambda *args, **kwargs: SimpleNamespace(
2778
+ branch="custom/feature-checkout",
2779
+ cleaned=False,
2780
+ deleted=False,
2781
+ returned_to="main",
2782
+ warnings=("could not checkout custom/feature-checkout",),
2783
+ ),
2784
+ )
3330
2785
 
3331
- def test_preflight_ready_commit_includes_tracked_state_but_excludes_untracked_state(tmp_path):
3332
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
2786
+ result = run_reset_command("feature", ("F-001", "--fresh-checkout"), paths)
3333
2787
 
3334
- _init_bookkeeping_repo(tmp_path)
3335
- tracked_state = tmp_path / ".prizmkit" / "state" / "bugfix" / "B-001" / "tracked.json"
3336
- tracked_state.parent.mkdir(parents=True)
3337
- tracked_state.write_text("baseline\n", encoding="utf-8")
3338
- subprocess.run(["git", "add", "-f", tracked_state.relative_to(tmp_path).as_posix()], cwd=tmp_path, check=True)
3339
- subprocess.run(["git", "commit", "-m", "track state"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3340
- tracked_state.write_text("changed\n", encoding="utf-8")
3341
- untracked_state = tracked_state.parent / "untracked.json"
3342
- untracked_state.write_text("transient\n", encoding="utf-8")
2788
+ assert result.exit_code == 1
2789
+ assert load_task_checkout(family.state_dir, family.task_type, "F-001") == checkout
3343
2790
 
3344
- result = commit_preflight_ready_changes(tmp_path, "B-001")
3345
2791
 
3346
- assert result.committed is True
3347
- assert tracked_state.relative_to(tmp_path).as_posix() in _head_files(tmp_path)
3348
- assert untracked_state.relative_to(tmp_path).as_posix() not in _head_files(tmp_path)
2792
+ def test_python_clean_reset_deletes_continuation_artifacts_for_all_families(tmp_path):
2793
+ from prizmkit_runtime.reset import run_reset_command
3349
2794
 
2795
+ snapshot = json.loads((REPO_ROOT / "tests" / "fixtures" / "dev-pipeline-behavior-snapshots" / "unix-runtime.json").read_text(encoding="utf-8"))
2796
+ cases = [("feature", "F-001", "specs", "001-reset-thing"), ("bugfix", "B-001", "bugfix", "B-001")]
2797
+ for kind, item_id, artifact_root, artifact_name in cases:
2798
+ paths = _make_paths(tmp_path / f"clean-{kind}")
2799
+ _plan, _state_dir, status_file = _write_family_case(paths, kind, item_id)
2800
+ artifact_dir = paths.project_root / ".prizmkit" / artifact_root / artifact_name
2801
+ artifact_dir.mkdir(parents=True, exist_ok=True)
2802
+ continuation = artifact_dir / "continuation-summary.md"
2803
+ continuation.write_text("summary", encoding="utf-8")
2804
+ args = (item_id, "--clean")
2805
+ result = run_reset_command(kind, args, paths)
3350
2806
 
3351
- def _track_manifest(project_root):
3352
- manifest_path = project_root / ".prizmkit" / "manifest.json"
3353
- manifest_path.parent.mkdir(parents=True, exist_ok=True)
3354
- manifest_path.write_text('{"version":"baseline"}\n', encoding="utf-8")
3355
- subprocess.run(["git", "add", ".prizmkit/manifest.json"], cwd=project_root, check=True)
3356
- subprocess.run(["git", "commit", "-m", "track manifest"], cwd=project_root, check=True, stdout=subprocess.DEVNULL)
3357
- return manifest_path
2807
+ assert result.exit_code == snapshot["resetBehavior"]["cleanResetDeletesContinuationArtifacts"][kind]["exitCode"]
2808
+ assert continuation.exists() is False
2809
+ runtime = json.loads(status_file.read_text(encoding="utf-8"))
2810
+ assert runtime.get("retry_count") == 0
2811
+ assert runtime.get("infra_error_count") == 0
2812
+ assert "continuation_pending" not in runtime
3358
2813
 
3359
2814
 
3360
- @pytest.mark.parametrize(
3361
- ("scenario", "expected_content"),
3362
- [
3363
- ("staged_only", '{"version":"staged"}\n'),
3364
- ("unstaged_only", '{"version":"unstaged"}\n'),
3365
- ("staged_and_unstaged", '{"version":"working-tree"}\n'),
3366
- ],
3367
- )
3368
- def test_preflight_ready_commit_preserves_tracked_manifest_modification_state(tmp_path, scenario, expected_content):
3369
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
3370
-
3371
- _init_bookkeeping_repo(tmp_path)
3372
- manifest_path = _track_manifest(tmp_path)
3373
- if scenario == "staged_only":
3374
- manifest_path.write_text(expected_content, encoding="utf-8")
3375
- subprocess.run(["git", "add", ".prizmkit/manifest.json"], cwd=tmp_path, check=True)
3376
- elif scenario == "unstaged_only":
3377
- manifest_path.write_text(expected_content, encoding="utf-8")
3378
- else:
3379
- manifest_path.write_text('{"version":"index"}\n', encoding="utf-8")
3380
- subprocess.run(["git", "add", ".prizmkit/manifest.json"], cwd=tmp_path, check=True)
3381
- manifest_path.write_text(expected_content, encoding="utf-8")
3382
-
3383
- before_count = _head_commit_count(tmp_path)
3384
- result = commit_preflight_ready_changes(tmp_path, "F-003")
3385
- committed_content = subprocess.run(
3386
- ["git", "show", "HEAD:.prizmkit/manifest.json"],
3387
- cwd=tmp_path,
3388
- check=True,
3389
- stdout=subprocess.PIPE,
3390
- text=True,
3391
- ).stdout
3392
-
3393
- assert result.attempted is True
3394
- assert result.committed is True
3395
- assert _head_commit_count(tmp_path) == before_count + 1
3396
- assert _head_message(tmp_path) == "chore: ready for F-003"
3397
- assert _head_files(tmp_path) == {".prizmkit/manifest.json"}
3398
- assert committed_content == expected_content
3399
- assert subprocess.run(
3400
- ["git", "status", "--short", "--untracked-files=no"],
3401
- cwd=tmp_path,
3402
- check=True,
3403
- stdout=subprocess.PIPE,
3404
- text=True,
3405
- ).stdout == ""
3406
-
3407
-
3408
- @pytest.mark.parametrize("staged", [False, True])
3409
- def test_preflight_ready_commit_preserves_tracked_manifest_deletion(tmp_path, staged):
3410
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
3411
-
3412
- _init_bookkeeping_repo(tmp_path)
3413
- manifest_path = _track_manifest(tmp_path)
3414
- manifest_path.unlink()
3415
- if staged:
3416
- subprocess.run(["git", "add", "-u", "--", ".prizmkit/manifest.json"], cwd=tmp_path, check=True)
3417
- (tmp_path / "unstaged.txt").write_text("coexisting tracked change\n", encoding="utf-8")
3418
- (tmp_path / "coexisting.txt").write_text("coexisting untracked change\n", encoding="utf-8")
3419
-
3420
- before_count = _head_commit_count(tmp_path)
3421
- result = commit_preflight_ready_changes(tmp_path, "B-003")
3422
- manifest_at_head = subprocess.run(
3423
- ["git", "cat-file", "-e", "HEAD:.prizmkit/manifest.json"],
3424
- cwd=tmp_path,
3425
- stdout=subprocess.DEVNULL,
3426
- stderr=subprocess.DEVNULL,
3427
- )
2815
+ def test_python_context_overflow_runner_path_does_not_import_reset():
2816
+ runner_text = (PIPELINE_ROOT / "prizmkit_runtime" / "runners.py").read_text(encoding="utf-8")
3428
2817
 
3429
- assert result.attempted is True
3430
- assert result.committed is True
3431
- assert _head_commit_count(tmp_path) == before_count + 1
3432
- assert _head_message(tmp_path) == "chore: ready for B-003"
3433
- assert _head_files(tmp_path) == {".prizmkit/manifest.json", "coexisting.txt", "unstaged.txt"}
3434
- assert manifest_at_head.returncode != 0
3435
- assert subprocess.run(
3436
- ["git", "status", "--short", "--untracked-files=all"],
3437
- cwd=tmp_path,
3438
- check=True,
3439
- stdout=subprocess.PIPE,
3440
- text=True,
3441
- ).stdout == ""
2818
+ assert "from .reset" not in runner_text
2819
+ assert "run_reset_command" not in runner_text
2820
+ assert '"context_overflow"' in runner_text
2821
+ assert "update_item" in runner_text
3442
2822
 
3443
2823
 
3444
- @pytest.mark.parametrize(
3445
- ("payload", "expected_error"),
3446
- [
3447
- ("{not-json\n", "not valid JSON"),
3448
- ("[]\n", "not a JSON object"),
3449
- ],
3450
- )
3451
- def test_preflight_ready_commit_rejects_unsafe_tracked_manifest_before_any_commit(tmp_path, payload, expected_error):
3452
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
3453
-
3454
- _init_bookkeeping_repo(tmp_path)
3455
- manifest_path = _track_manifest(tmp_path)
3456
- manifest_path.write_text(payload, encoding="utf-8")
3457
- (tmp_path / "eligible.txt").write_text("must remain uncommitted\n", encoding="utf-8")
3458
- before_count = _head_commit_count(tmp_path)
3459
-
3460
- result = commit_preflight_ready_changes(tmp_path, "R-003")
3461
-
3462
- assert result.attempted is True
3463
- assert result.committed is False
3464
- assert result.result is not None
3465
- assert expected_error in result.result.stderr
3466
- assert _head_commit_count(tmp_path) == before_count
3467
- assert "eligible.txt" not in _head_files(tmp_path)
3468
- assert subprocess.run(
3469
- ["git", "status", "--short", "--untracked-files=all"],
3470
- cwd=tmp_path,
3471
- check=True,
3472
- stdout=subprocess.PIPE,
3473
- text=True,
3474
- ).stdout.splitlines() == [" M .prizmkit/manifest.json", "?? eligible.txt"]
2824
+ def test_python_daemon_stale_pid_matches_snapshot(tmp_path):
2825
+ from prizmkit_runtime.daemon import run_daemon_command
3475
2826
 
2827
+ snapshot = json.loads((REPO_ROOT / "tests" / "fixtures" / "dev-pipeline-behavior-snapshots" / "unix-runtime.json").read_text(encoding="utf-8"))
2828
+ for kind in ("feature", "bugfix"):
2829
+ paths = _make_paths(tmp_path / f"daemon-{kind}")
2830
+ family_state = {"feature": paths.feature_state_dir, "bugfix": paths.bugfix_state_dir}[kind]
2831
+ family_state.mkdir(parents=True, exist_ok=True)
2832
+ pid_file = family_state / ".pipeline.pid"
2833
+ pid_file.write_text("999999\n", encoding="utf-8")
2834
+ result = run_daemon_command(kind, "status", (), paths)
2835
+ expected = snapshot["daemonBehavior"]["stalePidStatusByTaskType"][kind]
3476
2836
 
3477
- def test_preflight_ready_commit_preserves_tracked_manifest_with_other_tracked_support(tmp_path):
3478
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
2837
+ assert result.exit_code == expected["exitCode"]
2838
+ assert json.loads(result.render())["running"] is False
2839
+ assert pid_file.exists() is False
2840
+ assert "Cleaned stale PID file" in (result.stderr or "")
3479
2841
 
3480
- _init_bookkeeping_repo(tmp_path)
3481
- manifest_path = tmp_path / ".prizmkit" / "manifest.json"
3482
- tracked_support_paths = [
3483
- tmp_path / ".prizmkit" / "dev-pipeline" / "prizmkit_runtime" / "runners.py",
3484
- tmp_path / ".claude" / "commands" / "prizmkit.md",
3485
- ]
3486
- manifest_path.parent.mkdir(parents=True, exist_ok=True)
3487
- manifest_path.write_text('{"version":"1.1.127"}\n', encoding="utf-8")
3488
- for path in tracked_support_paths:
3489
- path.parent.mkdir(parents=True, exist_ok=True)
3490
- path.write_text("installed\n", encoding="utf-8")
3491
- tracked_paths = [manifest_path, *tracked_support_paths]
3492
- subprocess.run(
3493
- ["git", "add", *(path.relative_to(tmp_path).as_posix() for path in tracked_paths)],
3494
- cwd=tmp_path,
3495
- check=True,
3496
- )
3497
- subprocess.run(["git", "commit", "-m", "track support"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3498
- manifest_path.write_text('{"version":"1.1.128"}\n', encoding="utf-8")
3499
- for path in tracked_support_paths:
3500
- path.write_text("upgraded\n", encoding="utf-8")
3501
- visible_path = tmp_path / "visible.txt"
3502
- visible_path.write_text("eligible untracked change\n", encoding="utf-8")
3503
-
3504
- untracked_support_paths = [
3505
- tmp_path / ".claude" / "settings.local.json",
3506
- tmp_path / ".prizmkit" / "dev-pipeline" / "scripts" / "__pycache__" / "runtime.pyc",
3507
- tmp_path / ".prizmkit" / "state" / "bugfix" / "B-001" / "status.json",
3508
- ]
3509
- for path in untracked_support_paths:
3510
- path.parent.mkdir(parents=True, exist_ok=True)
3511
- path.write_text("transient\n", encoding="utf-8")
3512
-
3513
- before_count = _head_commit_count(tmp_path)
3514
- result = commit_preflight_ready_changes(tmp_path, "B-001")
3515
-
3516
- assert result.attempted is True
3517
- assert result.committed is True
3518
- assert _head_commit_count(tmp_path) == before_count + 1
3519
- assert _head_message(tmp_path) == "chore: ready for B-001"
3520
- assert _head_files(tmp_path) == {
3521
- *(path.relative_to(tmp_path).as_posix() for path in tracked_paths),
3522
- visible_path.relative_to(tmp_path).as_posix(),
3523
- }
3524
- assert subprocess.run(
3525
- ["git", "status", "--short", "--untracked-files=no"],
3526
- cwd=tmp_path,
3527
- check=True,
3528
- stdout=subprocess.PIPE,
3529
- text=True,
3530
- ).stdout == ""
3531
2842
 
2843
+ def test_python_daemon_controlled_start_status_stop_matches_snapshot(tmp_path):
2844
+ from prizmkit_runtime.daemon import run_daemon_command
2845
+ from prizmkit_runtime.paths import resolve_runtime_paths
3532
2846
 
3533
- def test_preflight_manifest_deletion_is_absent_from_linked_worktree_created_from_updated_head(tmp_path):
3534
- from prizmkit_runtime.gitops import (
3535
- BranchContext,
3536
- WorktreePolicy,
3537
- ensure_linked_worktree,
3538
- guarded_worktree_remove,
3539
- worktree_runtime_context,
3540
- )
3541
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
3542
-
3543
- _init_bookkeeping_repo(tmp_path)
3544
- manifest_path = _track_manifest(tmp_path)
3545
- manifest_path.unlink()
3546
-
3547
- result = commit_preflight_ready_changes(tmp_path, "B-003")
3548
- runtime = worktree_runtime_context(
3549
- BranchContext("main", "bugfix/B-003-ready", tmp_path),
3550
- WorktreePolicy(
3551
- use_worktree=True,
3552
- cleanup_on_success=True,
3553
- preserve_on_failure=True,
3554
- worktree_root=tmp_path.parent / f"{tmp_path.name}-worktrees",
3555
- ),
2847
+ snapshot = json.loads((REPO_ROOT / "tests" / "fixtures" / "dev-pipeline-behavior-snapshots" / "unix-runtime.json").read_text(encoding="utf-8"))["daemonBehavior"]["controlledStartStop"]
2848
+ project = tmp_path / "project"
2849
+ pipeline = tmp_path / "runtime"
2850
+ pipeline.mkdir(parents=True)
2851
+ cli = pipeline / "cli.py"
2852
+ cli.write_text(
2853
+ "#!/usr/bin/env python3\n"
2854
+ "import os, sys, time\n"
2855
+ "print('payload env=' + os.environ.get('FOO', ''))\n"
2856
+ "print('payload live=' + os.environ.get('PRIZMKIT_LIVE_OUTPUT', ''))\n"
2857
+ "print('payload args=' + ' '.join(sys.argv[1:]))\n"
2858
+ "sys.stdout.flush()\n"
2859
+ "time.sleep(30)\n",
2860
+ encoding="utf-8",
3556
2861
  )
3557
- setup = ensure_linked_worktree(runtime)
2862
+ cli.chmod(0o755)
2863
+ paths = resolve_runtime_paths(pipeline_root=pipeline, project_root=project)
2864
+ paths.plans_dir.mkdir(parents=True)
2865
+ paths.feature_plan.write_text(json.dumps({"features": [{"id": "F-001", "title": "A", "status": "pending"}]}), encoding="utf-8")
3558
2866
 
3559
- assert result.committed is True
3560
- assert setup.ok
2867
+ start = run_daemon_command("feature", "start", ("--env", "FOO=bar", "--features", "F-001"), paths)
3561
2868
  try:
3562
- assert not manifest_path.exists()
3563
- assert not (runtime.worktree_path / ".prizmkit" / "manifest.json").exists()
3564
- assert subprocess.run(
3565
- ["git", "status", "--short", "--untracked-files=no"],
3566
- cwd=tmp_path,
3567
- check=True,
3568
- stdout=subprocess.PIPE,
3569
- text=True,
3570
- ).stdout == ""
2869
+ start_payload = json.loads(start.render())
2870
+ status = run_daemon_command("feature", "status", (), paths)
2871
+ status_payload = json.loads(status.render())
3571
2872
  finally:
3572
- assert guarded_worktree_remove(runtime).ok
3573
-
3574
-
3575
- def test_preflight_ready_commit_excludes_untracked_support_assets_and_state(tmp_path):
3576
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
3577
-
3578
- _init_bookkeeping_repo(tmp_path)
3579
- (tmp_path / "unstaged.txt").write_text("visible change\n", encoding="utf-8")
3580
- hidden_paths = [
3581
- tmp_path / ".claude" / "settings.json",
3582
- tmp_path / ".codebuddy" / "skills" / "local.md",
3583
- tmp_path / ".agents" / "skills" / "local.md",
3584
- tmp_path / ".codex" / "config.toml",
3585
- tmp_path / ".prizmkit" / "state" / "features" / "F-001" / "status.json",
3586
- tmp_path / ".claude" / "worktrees" / "agent" / "scratch.txt",
3587
- ]
3588
- for path in hidden_paths:
3589
- path.parent.mkdir(parents=True, exist_ok=True)
3590
- path.write_text("hidden support\n", encoding="utf-8")
3591
-
3592
- result = commit_preflight_ready_changes(tmp_path, "F-124")
3593
- committed_files = _head_files(tmp_path)
3594
- hidden_status = subprocess.run(
3595
- ["git", "status", "--porcelain", "--", ".claude", ".codebuddy", ".agents", ".codex", ".prizmkit/state"],
3596
- cwd=tmp_path,
3597
- check=True,
3598
- stdout=subprocess.PIPE,
3599
- text=True,
3600
- ).stdout
3601
-
3602
- assert result.committed is True
3603
- assert committed_files == {"unstaged.txt"}
3604
- assert ".claude" in hidden_status or ".prizmkit/state" in hidden_status
3605
-
2873
+ stop = run_daemon_command("feature", "stop", (), paths)
3606
2874
 
3607
- def test_preflight_ready_commit_rejects_unmerged_index(tmp_path):
3608
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
2875
+ assert start.exit_code == snapshot["startExitCode"]
2876
+ assert start_payload["success"] is snapshot["startSuccess"]
2877
+ assert isinstance(start_payload["pid"], int)
2878
+ assert (paths.feature_state_dir / ".pipeline.pid").exists() is snapshot["pidFileExistsAfterStop"]
2879
+ assert status.exit_code == snapshot["statusWhileRunningExitCode"]
2880
+ assert status_payload["running"] is snapshot["statusWhileRunningReportsRunning"]
2881
+ assert isinstance(status_payload["pid"], int)
2882
+ assert status_payload["log_file"].endswith("pipeline-daemon.log")
2883
+ assert stop.exit_code == snapshot["stopExitCode"]
2884
+ assert json.loads(stop.render())["message"] in {"stopped", "already exited", "not running"}
2885
+ log_text = (paths.feature_state_dir / "pipeline-daemon.log").read_text(encoding="utf-8")
2886
+ assert "FOO=bar" in log_text or "payload env=bar" in log_text
2887
+ assert "payload live=0" in log_text
2888
+ assert "--project-root" in log_text
3609
2889
 
3610
- _init_bookkeeping_repo(tmp_path)
3611
- subprocess.run(["git", "checkout", "-b", "other"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3612
- (tmp_path / "staged.txt").write_text("other\n", encoding="utf-8")
3613
- subprocess.run(["git", "commit", "-am", "other"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3614
- subprocess.run(["git", "checkout", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3615
- (tmp_path / "staged.txt").write_text("main\n", encoding="utf-8")
3616
- subprocess.run(["git", "commit", "-am", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3617
- subprocess.run(["git", "merge", "other"], cwd=tmp_path, check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
3618
- before_count = _head_commit_count(tmp_path)
3619
2890
 
3620
- result = commit_preflight_ready_changes(tmp_path, "F-126")
2891
+ def test_python_reset_stalled_filter_selects_stalled_context_items(tmp_path):
2892
+ from prizmkit_runtime.reset import run_reset_command
3621
2893
 
3622
- assert result.attempted is True
3623
- assert result.committed is False
3624
- assert result.result is not None
3625
- assert "unmerged Git paths" in result.result.stderr
3626
- assert _head_commit_count(tmp_path) == before_count
2894
+ status_by_kind = {
2895
+ "feature": ("features", "F-001"),
2896
+ "bugfix": ("bugs", "B-001"),
2897
+ }
2898
+ for kind, (_collection, item_id) in status_by_kind.items():
2899
+ paths = _make_paths(tmp_path / f"stalled-{kind}")
2900
+ plan, _state_dir, status_file = _write_family_case(paths, kind, item_id)
2901
+ data = json.loads(plan.read_text(encoding="utf-8"))
2902
+ data[{"feature": "features", "bugfix": "bugs"}[kind]][0]["status"] = "stalled_context_continuation"
2903
+ plan.write_text(json.dumps(data), encoding="utf-8")
3627
2904
 
2905
+ result = run_reset_command(kind, ("--stalled", "--fresh-checkout"), paths)
3628
2906
 
3629
- def test_preflight_ready_commit_rejects_conflict_markers_and_malformed_manifest(tmp_path):
3630
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
2907
+ assert result.exit_code == 0
2908
+ assert f"Reset: {item_id}" in result.render()
2909
+ runtime = json.loads(status_file.read_text(encoding="utf-8"))
2910
+ assert runtime.get("retry_count") == 0
2911
+ assert "continuation_pending" not in runtime
2912
+ updated = json.loads(plan.read_text(encoding="utf-8"))
2913
+ assert updated[{"feature": "features", "bugfix": "bugs"}[kind]][0]["status"] == "pending"
3631
2914
 
3632
- _init_bookkeeping_repo(tmp_path)
3633
- (tmp_path / "unstaged.txt").write_text("<<<<<<< Updated upstream\ncurrent\n=======\nstashed\n>>>>>>> Stashed changes\n", encoding="utf-8")
3634
2915
 
3635
- marker_result = commit_preflight_ready_changes(tmp_path, "F-127")
2916
+ def test_python_daemon_progress_uses_list_status_without_runtime_files(tmp_path):
2917
+ from prizmkit_runtime.daemon import _progress_summary
2918
+ from prizmkit_runtime.runner_models import family_for
3636
2919
 
3637
- assert marker_result.committed is False
3638
- assert marker_result.result is not None
3639
- assert "unresolved conflict markers" in marker_result.result.stderr
2920
+ for kind in ("feature", "bugfix"):
2921
+ paths = _make_paths(tmp_path / f"progress-{kind}")
2922
+ if kind == "feature":
2923
+ paths.feature_plan.write_text(
2924
+ json.dumps({"features": [
2925
+ {"id": "F-001", "title": "Done", "status": "completed"},
2926
+ {"id": "F-002", "title": "Failed", "status": "failed"},
2927
+ {"id": "F-003", "title": "Skipped", "status": "auto_skipped"},
2928
+ ]}),
2929
+ encoding="utf-8",
2930
+ )
2931
+ plan = paths.feature_plan
2932
+ else:
2933
+ paths.bugfix_plan.write_text(
2934
+ json.dumps({"bugs": [
2935
+ {"id": "B-001", "title": "Done", "status": "completed"},
2936
+ {"id": "B-002", "title": "Failed", "status": "failed"},
2937
+ {"id": "B-003", "title": "Needs Info", "status": "needs_info"},
2938
+ {"id": "B-004", "title": "Blocked", "status": "auto_skipped"},
2939
+ ]}),
2940
+ encoding="utf-8",
2941
+ )
2942
+ plan = paths.bugfix_plan
3640
2943
 
3641
- (tmp_path / "unstaged.txt").write_text("safe\n", encoding="utf-8")
3642
- manifest = tmp_path / ".prizmkit" / "manifest.json"
3643
- manifest.parent.mkdir(parents=True, exist_ok=True)
3644
- manifest.write_text("<<<<<<< Updated upstream\n{}\n", encoding="utf-8")
2944
+ summary = _progress_summary(family_for(kind, paths), plan)
3645
2945
 
3646
- manifest_result = commit_preflight_ready_changes(tmp_path, "F-128")
2946
+ assert summary["total"] == (4 if kind == "bugfix" else 3)
2947
+ assert summary["completed"] == 1
2948
+ assert summary["failed"] == 1
2949
+ assert summary["percent"] == (25.0 if kind == "bugfix" else 33.3)
2950
+ if kind == "bugfix":
2951
+ assert summary["needs_info"] == 1
2952
+ assert summary["auto_skipped"] == 1
2953
+ else:
2954
+ assert summary["auto_skipped"] == 1
3647
2955
 
3648
- assert manifest_result.committed is False
3649
- assert manifest_result.result is not None
3650
- assert ".prizmkit/manifest.json" in manifest_result.result.stderr
3651
- assert "valid JSON" in manifest_result.result.stderr
3652
2956
 
2957
+ def test_session_status_parser_preserves_current_runtime_outcomes():
2958
+ import importlib.util
3653
2959
 
3654
- def test_preflight_ready_commit_noops_when_workspace_has_no_visible_dirty_content(tmp_path):
3655
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
2960
+ script = PIPELINE_ROOT / "scripts" / "check-session-status.py"
2961
+ spec = importlib.util.spec_from_file_location("check_session_status_contract", script)
2962
+ module = importlib.util.module_from_spec(spec)
2963
+ spec.loader.exec_module(module)
3656
2964
 
3657
- _init_bookkeeping_repo(tmp_path)
3658
- (tmp_path / ".claude" / "worktrees" / "agent").mkdir(parents=True)
3659
- (tmp_path / ".claude" / "worktrees" / "agent" / "scratch.txt").write_text("hidden only\n", encoding="utf-8")
3660
- before_count = _head_commit_count(tmp_path)
3661
-
3662
- result = commit_preflight_ready_changes(tmp_path, "F-125")
3663
-
3664
- assert result.attempted is False
3665
- assert result.committed is False
3666
- assert _head_commit_count(tmp_path) == before_count
3667
-
3668
-
3669
- @pytest.mark.parametrize(
3670
- ("kind", "item_id", "branch"),
3671
- [
3672
- ("feature", "F-001", "dev/F-001-ready"),
3673
- ("bugfix", "B-001", "bugfix/B-001-ready"),
3674
- ("refactor", "R-001", "refactor/R-001-ready"),
3675
- ],
3676
- )
3677
- def test_process_item_creates_one_ready_commit_before_branch_setup_for_all_families(
3678
- monkeypatch,
3679
- tmp_path,
3680
- kind,
3681
- item_id,
3682
- branch,
3683
- ):
3684
- from prizmkit_runtime import runner_bookkeeping, runners
3685
- from prizmkit_runtime.gitops import HIDDEN_TOOL_WORKTREE_EXCLUDES
3686
- from prizmkit_runtime.runner_models import family_for, parse_invocation
3687
-
3688
- paths = _make_paths(tmp_path / kind)
3689
- _init_bookkeeping_repo(paths.project_root)
3690
- manifest_path = _track_manifest(paths.project_root)
3691
- manifest_path.write_text('{"version":"ready"}\n', encoding="utf-8")
3692
- (paths.project_root / "staged.txt").write_text("staged before run\n", encoding="utf-8")
3693
- subprocess.run(["git", "add", "staged.txt"], cwd=paths.project_root, check=True)
3694
- (paths.project_root / "unstaged.txt").write_text("unstaged before run\n", encoding="utf-8")
3695
- (paths.project_root / "untracked.txt").write_text("untracked before run\n", encoding="utf-8")
3696
- before_count = _head_commit_count(paths.project_root)
3697
- branch_events = []
3698
-
3699
- monkeypatch.setenv("DEV_BRANCH", branch)
3700
- family = family_for(kind, paths)
3701
- invocation = parse_invocation(family, "run", ())
3702
- invocation = invocation.__class__(**{**invocation.__dict__, "list_path": family.plan_path})
3703
- _install_runner_session_fakes(monkeypatch, runners)
3704
- monkeypatch.setattr(runners, "commit_preflight_ready_changes", runner_bookkeeping.commit_preflight_ready_changes)
3705
-
3706
- def fake_run_git_plan(project_root, plan):
3707
- if plan.name == "branch_create":
3708
- branch_events.append(
3709
- {
3710
- "commit_count": _head_commit_count(project_root),
3711
- "message": _head_message(project_root),
3712
- "manifest_content": subprocess.run(
3713
- ["git", "show", "HEAD:.prizmkit/manifest.json"],
3714
- cwd=project_root,
3715
- check=True,
3716
- stdout=subprocess.PIPE,
3717
- text=True,
3718
- ).stdout,
3719
- "visible_status": subprocess.run(
3720
- ["git", "status", "--porcelain", "--", ".", *HIDDEN_TOOL_WORKTREE_EXCLUDES],
3721
- cwd=project_root,
3722
- check=True,
3723
- stdout=subprocess.PIPE,
3724
- text=True,
3725
- ).stdout,
3726
- }
3727
- )
3728
- return SimpleNamespace(ok=True, plan=plan, results=())
3729
-
3730
- monkeypatch.setattr(runners, "run_git_plan", fake_run_git_plan)
3731
-
3732
- status = runners._process_item(family, invocation, item_id, paths, initial_metadata={})
3733
-
3734
- assert status == "completed"
3735
- assert branch_events == [
3736
- {
3737
- "commit_count": before_count + 1,
3738
- "message": f"chore: ready for {item_id}",
3739
- "manifest_content": '{"version":"ready"}\n',
3740
- "visible_status": "",
3741
- }
3742
- ]
3743
- assert _head_commit_count(paths.project_root) == before_count + 1
3744
- assert {".prizmkit/manifest.json", "staged.txt", "unstaged.txt", "untracked.txt"}.issubset(
3745
- _head_files(paths.project_root)
3746
- )
3747
-
3748
-
3749
-
3750
- def test_process_item_ready_commit_uses_fallback_identity_before_branch_setup(monkeypatch, tmp_path):
3751
- from prizmkit_runtime import runner_bookkeeping, runners
3752
- from prizmkit_runtime.gitops import HIDDEN_TOOL_WORKTREE_EXCLUDES, PIPELINE_FALLBACK_GIT_EMAIL, PIPELINE_FALLBACK_GIT_NAME
3753
- from prizmkit_runtime.runner_models import family_for, parse_invocation
3754
-
3755
- monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(tmp_path / "missing-global-gitconfig"))
3756
- monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")
3757
- for key in ("GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL"):
3758
- monkeypatch.delenv(key, raising=False)
3759
- paths = _make_paths(tmp_path)
3760
- _init_bookkeeping_repo(paths.project_root, configure_identity=False)
3761
- (paths.project_root / "new-visible.txt").write_text("dirty before run\n", encoding="utf-8")
3762
- before_count = _head_commit_count(paths.project_root)
3763
- branch_events = []
3764
-
3765
- monkeypatch.setenv("DEV_BRANCH", "dev/F-001-ready-no-identity")
3766
- family = family_for("feature", paths)
3767
- invocation = parse_invocation(family, "run", ())
3768
- invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
3769
- _install_runner_session_fakes(monkeypatch, runners)
3770
- monkeypatch.setattr(runners, "commit_preflight_ready_changes", runner_bookkeeping.commit_preflight_ready_changes)
3771
-
3772
- def fake_run_git_plan(project_root, plan):
3773
- if plan.name == "branch_create":
3774
- author = subprocess.run(
3775
- ["git", "log", "-1", "--format=%an <%ae>"],
3776
- cwd=project_root,
3777
- check=True,
3778
- stdout=subprocess.PIPE,
3779
- text=True,
3780
- ).stdout.strip()
3781
- branch_events.append(
3782
- {
3783
- "commit_count": _head_commit_count(project_root),
3784
- "message": _head_message(project_root),
3785
- "author": author,
3786
- "visible_status": subprocess.run(
3787
- ["git", "status", "--porcelain", "--", ".", *HIDDEN_TOOL_WORKTREE_EXCLUDES],
3788
- cwd=project_root,
3789
- check=True,
3790
- stdout=subprocess.PIPE,
3791
- text=True,
3792
- ).stdout,
3793
- }
3794
- )
3795
- return SimpleNamespace(ok=True, plan=plan, results=())
3796
-
3797
- monkeypatch.setattr(runners, "run_git_plan", fake_run_git_plan)
3798
-
3799
- status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
3800
-
3801
- assert status == "completed"
3802
- assert branch_events == [
3803
- {
3804
- "commit_count": before_count + 1,
3805
- "message": "chore: ready for F-001",
3806
- "author": f"{PIPELINE_FALLBACK_GIT_NAME} <{PIPELINE_FALLBACK_GIT_EMAIL}>",
3807
- "visible_status": "",
3808
- }
3809
- ]
3810
- assert "new-visible.txt" in _head_files(paths.project_root)
3811
-
3812
-
3813
- def test_bookkeeping_commits_only_runner_owned_paths(tmp_path):
3814
- from prizmkit_runtime.runner_bookkeeping import commit_final_bookkeeping
3815
- from prizmkit_runtime.runner_models import RunnerFamily
3816
-
3817
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3818
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
3819
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
3820
- plans = tmp_path / ".prizmkit" / "plans"
3821
- state = tmp_path / ".prizmkit" / "state" / "features"
3822
- item_state = state / "F-001"
3823
- plans.mkdir(parents=True)
3824
- item_state.mkdir(parents=True)
3825
- plan = plans / "feature-list.json"
3826
- plan.write_text('{"features": []}', encoding="utf-8")
3827
- (item_state / "status.json").write_text(json.dumps({"completion_notes": ["Completed durable workflow"]}), encoding="utf-8")
3828
- source = tmp_path / "src.txt"
3829
- source.write_text("base", encoding="utf-8")
3830
- subprocess.run(["git", "add", ".prizmkit/plans/feature-list.json", ".prizmkit/state/features/F-001/status.json", "src.txt"], cwd=tmp_path, check=True)
3831
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3832
- plan.write_text('{"features": [{"id": "F-001", "status": "completed"}]}', encoding="utf-8")
3833
- (item_state / "status.json").write_text('{"last_session_id": "s1"}', encoding="utf-8")
3834
- source.write_text("dirty source change", encoding="utf-8")
3835
- family = RunnerFamily(
3836
- kind="feature",
3837
- id_prefix="F-",
3838
- list_key="features",
3839
- list_arg="--feature-list",
3840
- item_id_arg="--feature-id",
3841
- state_dir=state,
3842
- plan_path=plan,
3843
- updater_script=tmp_path / "update-feature-status.py",
3844
- prompt_script=tmp_path / "generate-bootstrap-prompt.py",
3845
- branch_prefix="dev",
3846
- artifact_root_name="specs",
3847
- )
3848
-
3849
- result = commit_final_bookkeeping(tmp_path, family, "F-001", "completed")
3850
- committed_files = subprocess.run(
3851
- ["git", "show", "--name-only", "--format=", "HEAD"],
3852
- cwd=tmp_path,
3853
- check=True,
3854
- stdout=subprocess.PIPE,
3855
- text=True,
3856
- ).stdout.splitlines()
3857
- dirty_files = subprocess.run(
3858
- ["git", "status", "--porcelain", "--", "src.txt"],
3859
- cwd=tmp_path,
3860
- check=True,
3861
- stdout=subprocess.PIPE,
3862
- text=True,
3863
- ).stdout
3864
-
3865
- assert result.committed is True
3866
- assert committed_files == [".prizmkit/plans/feature-list.json", ".prizmkit/state/features/F-001/status.json"]
3867
- assert dirty_files.startswith(" M src.txt")
3868
-
3869
-
3870
- def test_context_overflow_reuses_worktree_and_skips_cleanup_until_terminal_outcome(monkeypatch, tmp_path):
3871
- from prizmkit_runtime import runners
3872
- from prizmkit_runtime.runner_models import family_for, parse_invocation
3873
-
3874
- monkeypatch.setenv("USE_WORKTREE", "1")
3875
- monkeypatch.setenv("DEV_BRANCH", "dev/F-001-test")
3876
- paths = _make_paths(tmp_path)
3877
- family = family_for("feature", paths)
3878
- invocation = parse_invocation(family, "run", ())
3879
- invocation = invocation.__class__(**{**invocation.__dict__, "list_path": paths.feature_plan})
3880
- observed = _install_runner_session_fakes(monkeypatch, runners, statuses=("context_overflow", "success"))
3881
- sleep_calls = []
3882
- monkeypatch.setattr(runners.time, "sleep", lambda seconds: sleep_calls.append(seconds))
3883
- setup_calls = []
3884
- monkeypatch.setattr(runners, "ensure_linked_worktree", lambda runtime: (setup_calls.append(runtime) or SimpleNamespace(ok=True, runtime=runtime, reason="")), raising=False)
3885
-
3886
- status = runners._process_item(family, invocation, "F-001", paths, initial_metadata={})
3887
-
3888
- assert status == "completed"
3889
- assert len(setup_calls) == 1
3890
- assert observed.launch_cwds[0] == observed.launch_cwds[1]
3891
- assert observed.prompt_calls[0]["execution_root"] == observed.prompt_calls[1]["execution_root"]
3892
- assert observed.prompt_calls[0].get("continuation") is None
3893
- assert observed.prompt_calls[1]["continuation"]["previous_session_id"] == "F-001-session-1"
3894
- assert observed.updates[0][0] == "context_overflow"
3895
- assert sleep_calls == [5]
3896
- assert len(observed.cleanup_calls) == 1
3897
- assert observed.cleanup_calls[0][1] is True
3898
-
3899
-
3900
- def test_classification_accepts_late_infra_error_with_completed_checkpoint_and_commit(tmp_path):
3901
- from prizmkit_runtime.runner_classification import classify_session
3902
- from prizmkit_runtime.runner_models import PromptGenerationResult
3903
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
3904
- from prizmkit_runtime.status import ProgressSummary
3905
-
3906
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3907
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
3908
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
3909
- (tmp_path / "base.txt").write_text("base", encoding="utf-8")
3910
- subprocess.run(["git", "add", "base.txt"], cwd=tmp_path, check=True)
3911
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3912
- base_head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
3913
- (tmp_path / "done.txt").write_text("done", encoding="utf-8")
3914
- subprocess.run(["git", "add", "done.txt"], cwd=tmp_path, check=True)
3915
- subprocess.run(["git", "commit", "-m", "done"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3916
- artifact_dir = tmp_path / ".prizmkit" / "specs" / "001-done"
3917
- checkpoint = _write_semantic_completion_checkpoint(tmp_path, artifact_dir)
3918
- log = tmp_path / "session.log"
3919
- log.write_text("model quota exceeded; API error after commit", encoding="utf-8")
3920
- raw = AISessionResult(
3921
- command=AISessionCommand(("fake",), None, "codebuddy", "stdin"),
3922
- exit_code=1,
3923
- timed_out=False,
3924
- termination_reason=None,
3925
- stale_marker=None,
3926
- fatal_error_code="api_error",
3927
- progress_summary=ProgressSummary(terminal_result_text="quota exceeded"),
3928
- session_log=log,
3929
- backup_log=tmp_path / "backup.log",
3930
- log_recovery=None,
3931
- started_epoch=0,
3932
- ended_epoch=1,
3933
- )
3934
- prompt = PromptGenerationResult(output_path=tmp_path / "prompt.md", checkpoint_path=checkpoint, artifact_path=artifact_dir)
3935
-
3936
- classification = classify_session(raw, project_root=tmp_path, base_head=base_head, prompt=prompt)
3937
-
3938
- assert classification.session_status == "success"
3939
- assert classification.reason == "semantic_checkpoint_with_late_runtime_error"
3940
-
3941
-
3942
- def test_classification_accepts_final_success_after_internal_stream_retry(tmp_path):
3943
- import importlib.util
3944
-
3945
- from prizmkit_runtime.runner_classification import classify_session
3946
- from prizmkit_runtime.runner_models import PromptGenerationResult
3947
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
3948
- from prizmkit_runtime.status import ProgressSummary
3949
-
3950
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3951
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
3952
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
3953
- (tmp_path / "base.txt").write_text("base", encoding="utf-8")
3954
- subprocess.run(["git", "add", "base.txt"], cwd=tmp_path, check=True)
3955
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3956
- base_head = subprocess.run(
3957
- ["git", "rev-parse", "HEAD"],
3958
- cwd=tmp_path,
3959
- check=True,
3960
- stdout=subprocess.PIPE,
3961
- text=True,
3962
- ).stdout.strip()
3963
- (tmp_path / "done.txt").write_text("done", encoding="utf-8")
3964
- subprocess.run(["git", "add", "done.txt"], cwd=tmp_path, check=True)
3965
- subprocess.run(
3966
- ["git", "commit", "-m", "done"],
3967
- cwd=tmp_path,
3968
- check=True,
3969
- stdout=subprocess.DEVNULL,
3970
- )
3971
- artifact_dir = tmp_path / ".prizmkit" / "bugfix" / "B-004"
3972
- checkpoint = _write_semantic_completion_checkpoint(tmp_path, artifact_dir, "bugfix-pipeline")
3973
-
3974
- parser_path = PIPELINE_ROOT / "scripts" / "parse-stream-progress.py"
3975
- spec = importlib.util.spec_from_file_location("retry_progress_parser", parser_path)
3976
- module = importlib.util.module_from_spec(spec)
3977
- assert spec.loader is not None
3978
- spec.loader.exec_module(module)
3979
- tracker = module.ProgressTracker()
3980
- events = [
3981
- {"type": "session", "id": "pi-session"},
3982
- {"type": "agent_start"},
3983
- {"type": "message_end", "message": {"role": "assistant", "content": [], "stopReason": "error", "errorMessage": "Error Code internal_server_error: unexpected EOF"}},
3984
- {"type": "agent_end", "willRetry": True, "messages": []},
3985
- {"type": "auto_retry_start", "attempt": 1, "errorMessage": "Error Code internal_server_error: unexpected EOF"},
3986
- {"type": "agent_start"},
3987
- {"type": "auto_retry_end", "attempt": 1},
3988
- {"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "WORKFLOW_COMPLETED"}], "stopReason": "stop"}},
3989
- {"type": "agent_end", "willRetry": False, "messages": [{"role": "assistant", "content": [{"type": "text", "text": "WORKFLOW_COMPLETED"}], "stopReason": "stop"}]},
3990
- ]
3991
- for event in events:
3992
- tracker.process_event(event)
3993
- data = tracker.to_dict()
3994
- log = tmp_path / "session.log"
3995
- log.write_text("[ERROR] transient unexpected EOF\n[SESSION_END] status=success\n", encoding="utf-8")
3996
- raw = AISessionResult(
3997
- command=AISessionCommand(("fake",), None, "custom", "stdin"),
3998
- exit_code=0,
3999
- timed_out=False,
4000
- termination_reason=None,
4001
- stale_marker=None,
4002
- fatal_error_code=str(data.get("fatal_error_code") or ""),
4003
- progress_summary=ProgressSummary(
4004
- result_subtype=str(data.get("result_subtype") or ""),
4005
- stop_reason=str(data.get("stop_reason") or ""),
4006
- fatal_error_code=str(data.get("fatal_error_code") or ""),
4007
- terminal_result_text=str(data.get("terminal_result_text") or ""),
4008
- errors=tuple(str(item) for item in data.get("errors", [])),
4009
- ),
4010
- session_log=log,
4011
- backup_log=tmp_path / "backup.log",
4012
- log_recovery=None,
4013
- started_epoch=0,
4014
- ended_epoch=1,
4015
- )
4016
-
4017
- classification = classify_session(
4018
- raw,
4019
- project_root=tmp_path,
4020
- base_head=base_head,
4021
- prompt=PromptGenerationResult(
4022
- output_path=tmp_path / "prompt.md",
4023
- checkpoint_path=checkpoint,
4024
- artifact_path=artifact_dir,
4025
- ),
4026
- )
4027
-
4028
- assert data["last_result_is_error"] is False
4029
- assert any("unexpected EOF" in str(error) for error in data["errors"])
4030
- assert classification.session_status == "success"
4031
- assert classification.reason == "terminal_success_with_semantic_checkpoint"
4032
-
4033
-
4034
- def test_classification_rejects_late_infra_with_completion_summary_only(tmp_path):
4035
- from prizmkit_runtime.runner_classification import classify_session
4036
- from prizmkit_runtime.runner_models import PromptGenerationResult
4037
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
4038
- from prizmkit_runtime.status import ProgressSummary
4039
-
4040
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4041
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
4042
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
4043
- (tmp_path / "base.txt").write_text("base", encoding="utf-8")
4044
- subprocess.run(["git", "add", "base.txt"], cwd=tmp_path, check=True)
4045
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4046
- subprocess.run(["git", "checkout", "-b", "side"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4047
- (tmp_path / "side.txt").write_text("side", encoding="utf-8")
4048
- subprocess.run(["git", "add", "side.txt"], cwd=tmp_path, check=True)
4049
- subprocess.run(["git", "commit", "-m", "side"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4050
- side_head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
4051
- subprocess.run(["git", "checkout", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4052
- (tmp_path / "main.txt").write_text("main", encoding="utf-8")
4053
- subprocess.run(["git", "add", "main.txt"], cwd=tmp_path, check=True)
4054
- subprocess.run(["git", "commit", "-m", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4055
- subprocess.run(["git", "checkout", "side"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4056
- artifact_dir = tmp_path / ".prizmkit" / "specs" / "001-done"
4057
- artifact_dir.mkdir(parents=True)
4058
- (artifact_dir / "completion-summary.json").write_text(json.dumps({"completion_notes": ["Completed durable workflow"]}), encoding="utf-8")
4059
- log = tmp_path / "session.log"
4060
- log.write_text("quota exceeded", encoding="utf-8")
4061
- raw = AISessionResult(
4062
- command=AISessionCommand(("fake",), None, "codebuddy", "stdin"),
4063
- exit_code=1,
4064
- timed_out=False,
4065
- termination_reason=None,
4066
- stale_marker=None,
4067
- fatal_error_code="api_error",
4068
- progress_summary=ProgressSummary(terminal_result_text="quota exceeded"),
4069
- session_log=log,
4070
- backup_log=tmp_path / "backup.log",
4071
- log_recovery=None,
4072
- started_epoch=0,
4073
- ended_epoch=1,
4074
- )
4075
- prompt = PromptGenerationResult(output_path=tmp_path / "prompt.md", artifact_path=artifact_dir)
4076
-
4077
- classification = classify_session(raw, project_root=tmp_path, base_head=side_head, prompt=prompt)
4078
-
4079
- assert classification.session_status == "infra_error"
4080
- assert classification.reason == "ai_runtime_or_provider_error"
4081
-
4082
-
4083
- def test_classification_keeps_pre_completion_provider_error_as_infra_error(tmp_path):
4084
- from prizmkit_runtime.runner_classification import classify_session
4085
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
4086
- from prizmkit_runtime.status import ProgressSummary
4087
-
4088
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4089
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
4090
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
4091
- (tmp_path / "base.txt").write_text("base", encoding="utf-8")
4092
- subprocess.run(["git", "add", "base.txt"], cwd=tmp_path, check=True)
4093
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4094
- base_head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
4095
- log = tmp_path / "session.log"
4096
- log.write_text("authentication failed", encoding="utf-8")
4097
- raw = AISessionResult(
4098
- command=AISessionCommand(("fake",), None, "codebuddy", "stdin"),
4099
- exit_code=1,
4100
- timed_out=False,
4101
- termination_reason=None,
4102
- stale_marker=None,
4103
- fatal_error_code="authentication_error",
4104
- progress_summary=ProgressSummary(terminal_result_text="authentication failed"),
4105
- session_log=log,
4106
- backup_log=tmp_path / "backup.log",
4107
- log_recovery=None,
4108
- started_epoch=0,
4109
- ended_epoch=1,
4110
- )
4111
-
4112
- classification = classify_session(raw, project_root=tmp_path, base_head=base_head)
4113
-
4114
- assert classification.session_status == "infra_error"
4115
- assert classification.reason == "ai_runtime_or_provider_error"
4116
-
4117
-
4118
- def test_classification_rejects_completed_checkpoint_without_runtime_git_receipt(tmp_path):
4119
- from prizmkit_runtime.runner_classification import classify_session
4120
- from prizmkit_runtime.runner_models import PromptGenerationResult
4121
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
4122
- from prizmkit_runtime.status import ProgressSummary
4123
-
4124
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4125
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
4126
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
4127
- (tmp_path / ".gitignore").write_text(".prizmkit/*\n", encoding="utf-8")
4128
- (tmp_path / "base.txt").write_text("base", encoding="utf-8")
4129
- subprocess.run(["git", "add", ".gitignore", "base.txt"], cwd=tmp_path, check=True)
4130
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4131
- base_head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
4132
- artifact_dir = tmp_path / ".prizmkit" / "specs" / "001-done"
4133
- checkpoint = _write_semantic_completion_checkpoint(tmp_path, artifact_dir)
4134
- (artifact_dir / "completion-summary.json").write_text(json.dumps({"completion_notes": ["Completed durable workflow"]}), encoding="utf-8")
4135
- log = tmp_path / "session.log"
4136
- log.write_text("terminal success", encoding="utf-8")
4137
- raw = AISessionResult(
4138
- command=AISessionCommand(("fake",), None, "claude", "stdin"),
4139
- exit_code=0,
4140
- timed_out=False,
4141
- termination_reason=None,
4142
- stale_marker=None,
4143
- fatal_error_code="",
4144
- progress_summary=ProgressSummary(result_subtype="success", terminal_result_text="Completed; working tree clean"),
4145
- session_log=log,
4146
- backup_log=tmp_path / "backup.log",
4147
- log_recovery=None,
4148
- started_epoch=0,
4149
- ended_epoch=1,
4150
- )
4151
- prompt = PromptGenerationResult(
4152
- output_path=tmp_path / "prompt.md",
4153
- checkpoint_path=checkpoint,
4154
- artifact_path=artifact_dir,
4155
- )
4156
-
4157
- classification = classify_session(raw, project_root=tmp_path, base_head=base_head, prompt=prompt)
4158
- assert classification.session_status == "commit_missing"
4159
- assert classification.reason == "runtime_commit_receipt_mismatch"
4160
-
4161
-
4162
- def test_classification_preserves_success_before_context_overflow(tmp_path):
4163
- from prizmkit_runtime.runner_classification import classify_session
4164
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
4165
- from prizmkit_runtime.status import ProgressSummary
4166
-
4167
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4168
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
4169
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
4170
- (tmp_path / "base.txt").write_text("base", encoding="utf-8")
4171
- subprocess.run(["git", "add", "base.txt"], cwd=tmp_path, check=True)
4172
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4173
- base_head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
4174
- (tmp_path / "done.txt").write_text("done", encoding="utf-8")
4175
- subprocess.run(["git", "add", "done.txt"], cwd=tmp_path, check=True)
4176
- subprocess.run(["git", "commit", "-m", "done"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4177
- log = tmp_path / "session.log"
4178
- log.write_text("API Error: input exceeds the context window", encoding="utf-8")
4179
-
4180
- raw = AISessionResult(
4181
- command=AISessionCommand(("fake",), None, "codebuddy", "stdin"),
4182
- exit_code=1,
4183
- timed_out=False,
4184
- termination_reason=None,
4185
- stale_marker=None,
4186
- fatal_error_code="context_overflow",
4187
- progress_summary=ProgressSummary(fatal_error_code="context_overflow"),
4188
- session_log=log,
4189
- backup_log=tmp_path / "backup.log",
4190
- log_recovery=None,
4191
- started_epoch=0,
4192
- ended_epoch=1,
4193
- )
4194
-
4195
- classification = classify_session(raw, project_root=tmp_path, base_head=base_head)
4196
- assert classification.session_status == "context_overflow"
4197
- assert classification.reason == "context_overflow"
4198
-
4199
-
4200
- def test_classification_crash_with_commit_since_base_does_not_become_success(tmp_path):
4201
- from prizmkit_runtime.runner_classification import classify_session
4202
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
4203
- from prizmkit_runtime.status import ProgressSummary
4204
-
4205
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4206
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
4207
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
4208
- (tmp_path / "base.txt").write_text("base", encoding="utf-8")
4209
- subprocess.run(["git", "add", "base.txt"], cwd=tmp_path, check=True)
4210
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4211
- base_head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
4212
- (tmp_path / "done.txt").write_text("done", encoding="utf-8")
4213
- subprocess.run(["git", "add", "done.txt"], cwd=tmp_path, check=True)
4214
- subprocess.run(["git", "commit", "-m", "done"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4215
- log = tmp_path / "session.log"
4216
- log.write_text("hard failure", encoding="utf-8")
4217
- raw = AISessionResult(
4218
- command=AISessionCommand(("fake",), None, "codebuddy", "stdin"),
4219
- exit_code=1,
4220
- timed_out=False,
4221
- termination_reason=None,
4222
- stale_marker=None,
4223
- fatal_error_code="",
4224
- progress_summary=ProgressSummary(terminal_result_text="hard failure"),
4225
- session_log=log,
4226
- backup_log=tmp_path / "backup.log",
4227
- log_recovery=None,
4228
- started_epoch=0,
4229
- ended_epoch=1,
4230
- )
4231
-
4232
- classification = classify_session(raw, project_root=tmp_path, base_head=base_head)
4233
- assert classification.session_status == "crashed"
4234
- assert classification.reason == "exit_code=1"
4235
-
4236
-
4237
- def test_classification_stalls_after_repeated_no_progress_context_overflow(tmp_path):
4238
- from prizmkit_runtime.runner_classification import classify_session, progress_fingerprint
4239
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
4240
- from prizmkit_runtime.status import ProgressSummary
4241
-
4242
- log = tmp_path / "session.log"
4243
- log.write_text("PRIZMKIT_FATAL_ERROR=context_overflow", encoding="utf-8")
4244
- raw = AISessionResult(
4245
- command=AISessionCommand(("fake",), None, "codebuddy", "stdin"),
4246
- exit_code=1,
4247
- timed_out=False,
4248
- termination_reason=None,
4249
- stale_marker=None,
4250
- fatal_error_code="context_overflow",
4251
- progress_summary=ProgressSummary(fatal_error_code="context_overflow"),
4252
- session_log=log,
4253
- backup_log=tmp_path / "backup.log",
4254
- log_recovery=None,
4255
- started_epoch=0,
4256
- ended_epoch=1,
4257
- )
4258
- previous = progress_fingerprint(tmp_path)
4259
-
4260
- classification = classify_session(
4261
- raw,
4262
- project_root=tmp_path,
4263
- base_head="",
4264
- previous_fingerprint=previous,
4265
- previous_no_progress_count=1,
4266
- )
4267
-
4268
- assert classification.session_status == "stalled_context_continuation"
4269
- assert classification.no_progress_count == 2
4270
-
4271
-
4272
- def test_cli_family_status_uses_python_dispatch_not_transition_description(tmp_path):
4273
- paths = _make_paths(tmp_path)
4274
- _write_feature_list(paths)
4275
- result = subprocess.run(
4276
- [PYTHON_310_PLUS, str(CLI_PATH), "--project-root", str(paths.project_root), "status", "feature"],
4277
- cwd=REPO_ROOT,
4278
- stdout=subprocess.PIPE,
4279
- stderr=subprocess.PIPE,
4280
- text=True,
4281
- check=False,
4282
- )
4283
-
4284
- assert result.returncode == 0
4285
- assert "Python feature status" in result.stdout
4286
- assert "Transition command contract" not in result.stdout
4287
-
4288
-
4289
- def _write_family_case(paths, kind, item_id=""):
4290
- item_id = item_id or {"feature": "F-001", "bugfix": "B-001", "refactor": "R-001"}[kind]
4291
- if kind == "feature":
4292
- paths.feature_plan.write_text(json.dumps({"features": [{"id": item_id, "title": "Reset Thing", "status": "failed", "dependencies": []}]}), encoding="utf-8")
4293
- state_dir = paths.feature_state_dir
4294
- plan = paths.feature_plan
4295
- elif kind == "bugfix":
4296
- paths.bugfix_plan.write_text(json.dumps({"bugs": [{"id": item_id, "title": "Reset Bug", "description": "d", "severity": "medium", "priority": "medium", "status": "failed"}]}), encoding="utf-8")
4297
- state_dir = paths.bugfix_state_dir
4298
- plan = paths.bugfix_plan
4299
- else:
4300
- paths.refactor_plan.write_text(json.dumps({"refactors": [{"id": item_id, "title": "Reset Refactor", "description": "d", "complexity": "medium", "priority": "medium", "status": "failed", "dependencies": []}]}), encoding="utf-8")
4301
- state_dir = paths.refactor_state_dir
4302
- plan = paths.refactor_plan
4303
- state_dir.mkdir(parents=True, exist_ok=True)
4304
- (state_dir / "pipeline.json").write_text(json.dumps({"completion_notes": ["Completed durable workflow"]}), encoding="utf-8")
4305
- item_state = state_dir / item_id
4306
- item_state.mkdir(parents=True, exist_ok=True)
4307
- (item_state / "status.json").write_text(
4308
- json.dumps(
4309
- {
4310
- "status": "in_progress",
4311
- "retry_count": 2,
4312
- "infra_error_count": 1,
4313
- "last_infra_error_session_id": "infra-1",
4314
- "last_session_id": "sess-1",
4315
- "sessions": ["sess-1"],
4316
- "continuation_pending": True,
4317
- "continuation_reason": "context_overflow",
4318
- "active_dev_branch": f"{kind}/{item_id}-branch",
4319
- "continuation_summary_path": str(paths.project_root / ".prizmkit" / ("specs" if kind == "feature" else kind) / item_id / "continuation-summary.md"),
4320
- }
4321
- ),
4322
- encoding="utf-8",
4323
- )
4324
- return plan, state_dir, item_state / "status.json"
4325
-
4326
-
4327
- def test_python_reset_warns_before_mutation_and_matches_snapshot_cleanup(tmp_path):
4328
- from prizmkit_runtime.reset import run_reset_command
4329
- from prizmkit_runtime.runner_models import family_for
4330
- from prizmkit_runtime.task_checkout import load_task_checkout
4331
-
4332
- snapshot = json.loads((REPO_ROOT / "tests" / "fixtures" / "dev-pipeline-behavior-snapshots" / "unix-runtime.json").read_text(encoding="utf-8"))
4333
- for kind, item_id in [("feature", "F-001"), ("bugfix", "B-001"), ("refactor", "R-001")]:
4334
- paths = _make_paths(tmp_path / kind)
4335
- _plan, _state_dir, status_file = _write_family_case(paths, kind, item_id)
4336
- result = run_reset_command(kind, (item_id, "--fresh-checkout"), paths)
4337
- output = result.render()
4338
- reset_marker = f"Resetting {item_id} status"
4339
-
4340
- assert result.exit_code == snapshot["resetBehavior"]["manualResetWarningOrder"][kind]["exitCode"]
4341
- assert "Continuation pending" in output
4342
- assert "Pending continuation branch" in output
4343
- assert output.index("Continuation pending") < output.index(reset_marker)
4344
- runtime = json.loads(status_file.read_text(encoding="utf-8"))
4345
- expected_runtime = snapshot["statusUpdaterBehavior"]["resetCleanMetadataCleanup"][kind]["reset"]["runtime"]
4346
- for key, value in expected_runtime.items():
4347
- assert runtime.get(key) == value
4348
- assert "continuation_pending" not in runtime
4349
- family = family_for(kind, paths)
4350
- checkout = load_task_checkout(family.state_dir, family.task_type, item_id)
4351
- assert checkout is not None
4352
- assert checkout.is_reset
4353
- assert checkout.active_dev_branch == ""
4354
- assert checkout.base_branch == ""
4355
-
4356
-
4357
- def test_python_reset_cleans_authoritative_custom_branch_before_reset_marker(monkeypatch, tmp_path):
4358
- from prizmkit_runtime import reset as reset_runtime
4359
- from prizmkit_runtime.reset import run_reset_command
4360
- from prizmkit_runtime.runner_models import family_for
4361
- from prizmkit_runtime.task_checkout import TaskCheckout, load_task_checkout, persist_task_checkout
4362
-
4363
- paths = _make_paths(tmp_path)
4364
- _write_family_case(paths, "feature", "F-001")
4365
- family = family_for("feature", paths)
4366
- custom_branch = "custom/feature-checkout"
4367
- persist_task_checkout(family.state_dir, TaskCheckout.active("feature", "F-001", custom_branch, "main"))
4368
- cleanup_calls = []
4369
-
4370
- monkeypatch.setattr(reset_runtime, "list_reset_branches", lambda *args: ())
4371
- monkeypatch.setattr(
4372
- reset_runtime,
4373
- "reset_cleanup_branch",
4374
- lambda project_root, branch, *, return_branch, delete: cleanup_calls.append((branch, delete))
4375
- or SimpleNamespace(branch=branch, cleaned=True, deleted=False, returned_to=return_branch, warnings=()),
4376
- )
4377
-
4378
- result = run_reset_command("feature", ("F-001", "--fresh-checkout"), paths)
4379
-
4380
- assert result.exit_code == 0
4381
- assert cleanup_calls == [(custom_branch, False)]
4382
- checkout = load_task_checkout(family.state_dir, family.task_type, "F-001")
4383
- assert checkout is not None and checkout.is_reset
4384
-
4385
-
4386
- def test_python_reset_failure_keeps_authoritative_checkout_active(monkeypatch, tmp_path):
4387
- from prizmkit_runtime import reset as reset_runtime
4388
- from prizmkit_runtime.reset import run_reset_command
4389
- from prizmkit_runtime.runner_models import family_for
4390
- from prizmkit_runtime.task_checkout import TaskCheckout, load_task_checkout, persist_task_checkout
4391
-
4392
- paths = _make_paths(tmp_path)
4393
- _write_family_case(paths, "feature", "F-001")
4394
- family = family_for("feature", paths)
4395
- checkout = TaskCheckout.active("feature", "F-001", "custom/feature-checkout", "main")
4396
- persist_task_checkout(family.state_dir, checkout)
4397
- monkeypatch.setattr(reset_runtime, "list_reset_branches", lambda *args: ())
4398
- monkeypatch.setattr(
4399
- reset_runtime,
4400
- "reset_cleanup_branch",
4401
- lambda *args, **kwargs: SimpleNamespace(
4402
- branch="custom/feature-checkout",
4403
- cleaned=False,
4404
- deleted=False,
4405
- returned_to="main",
4406
- warnings=("could not checkout custom/feature-checkout",),
4407
- ),
4408
- )
4409
-
4410
- result = run_reset_command("feature", ("F-001", "--fresh-checkout"), paths)
4411
-
4412
- assert result.exit_code == 1
4413
- assert load_task_checkout(family.state_dir, family.task_type, "F-001") == checkout
4414
-
4415
-
4416
- def test_python_clean_reset_deletes_continuation_artifacts_for_all_families(tmp_path):
4417
- from prizmkit_runtime.reset import run_reset_command
4418
-
4419
- snapshot = json.loads((REPO_ROOT / "tests" / "fixtures" / "dev-pipeline-behavior-snapshots" / "unix-runtime.json").read_text(encoding="utf-8"))
4420
- cases = [("feature", "F-001", "specs", "001-reset-thing"), ("bugfix", "B-001", "bugfix", "B-001"), ("refactor", "R-001", "refactor", "R-001")]
4421
- for kind, item_id, artifact_root, artifact_name in cases:
4422
- paths = _make_paths(tmp_path / f"clean-{kind}")
4423
- _plan, _state_dir, status_file = _write_family_case(paths, kind, item_id)
4424
- artifact_dir = paths.project_root / ".prizmkit" / artifact_root / artifact_name
4425
- artifact_dir.mkdir(parents=True, exist_ok=True)
4426
- continuation = artifact_dir / "continuation-summary.md"
4427
- continuation.write_text("summary", encoding="utf-8")
4428
- args = (item_id, "--clean")
4429
- result = run_reset_command(kind, args, paths)
4430
-
4431
- assert result.exit_code == snapshot["resetBehavior"]["cleanResetDeletesContinuationArtifacts"][kind]["exitCode"]
4432
- assert continuation.exists() is False
4433
- runtime = json.loads(status_file.read_text(encoding="utf-8"))
4434
- assert runtime.get("retry_count") == 0
4435
- assert runtime.get("infra_error_count") == 0
4436
- assert "continuation_pending" not in runtime
4437
-
4438
-
4439
- def test_python_context_overflow_runner_path_does_not_import_reset():
4440
- runner_text = (PIPELINE_ROOT / "prizmkit_runtime" / "runners.py").read_text(encoding="utf-8")
4441
-
4442
- assert "from .reset" not in runner_text
4443
- assert "run_reset_command" not in runner_text
4444
- assert '"context_overflow"' in runner_text
4445
- assert "update_item" in runner_text
4446
-
4447
-
4448
- def test_python_daemon_stale_pid_matches_snapshot(tmp_path):
4449
- from prizmkit_runtime.daemon import run_daemon_command
4450
-
4451
- snapshot = json.loads((REPO_ROOT / "tests" / "fixtures" / "dev-pipeline-behavior-snapshots" / "unix-runtime.json").read_text(encoding="utf-8"))
4452
- for kind in ("feature", "bugfix", "refactor"):
4453
- paths = _make_paths(tmp_path / f"daemon-{kind}")
4454
- family_state = {"feature": paths.feature_state_dir, "bugfix": paths.bugfix_state_dir, "refactor": paths.refactor_state_dir}[kind]
4455
- family_state.mkdir(parents=True, exist_ok=True)
4456
- pid_file = family_state / ".pipeline.pid"
4457
- pid_file.write_text("999999\n", encoding="utf-8")
4458
- result = run_daemon_command(kind, "status", (), paths)
4459
- expected = snapshot["daemonBehavior"]["stalePidStatusByTaskType"][kind]
4460
-
4461
- assert result.exit_code == expected["exitCode"]
4462
- assert json.loads(result.render())["running"] is False
4463
- assert pid_file.exists() is False
4464
- assert "Cleaned stale PID file" in (result.stderr or "")
4465
-
4466
-
4467
- def test_python_daemon_controlled_start_status_stop_matches_snapshot(tmp_path):
4468
- from prizmkit_runtime.daemon import run_daemon_command
4469
- from prizmkit_runtime.paths import resolve_runtime_paths
4470
-
4471
- snapshot = json.loads((REPO_ROOT / "tests" / "fixtures" / "dev-pipeline-behavior-snapshots" / "unix-runtime.json").read_text(encoding="utf-8"))["daemonBehavior"]["controlledStartStop"]
4472
- project = tmp_path / "project"
4473
- pipeline = tmp_path / "runtime"
4474
- pipeline.mkdir(parents=True)
4475
- cli = pipeline / "cli.py"
4476
- cli.write_text(
4477
- "#!/usr/bin/env python3\n"
4478
- "import os, sys, time\n"
4479
- "print('payload env=' + os.environ.get('FOO', ''))\n"
4480
- "print('payload live=' + os.environ.get('PRIZMKIT_LIVE_OUTPUT', ''))\n"
4481
- "print('payload args=' + ' '.join(sys.argv[1:]))\n"
4482
- "sys.stdout.flush()\n"
4483
- "time.sleep(30)\n",
4484
- encoding="utf-8",
4485
- )
4486
- cli.chmod(0o755)
4487
- paths = resolve_runtime_paths(pipeline_root=pipeline, project_root=project)
4488
- paths.plans_dir.mkdir(parents=True)
4489
- paths.feature_plan.write_text(json.dumps({"features": [{"id": "F-001", "title": "A", "status": "pending"}]}), encoding="utf-8")
4490
-
4491
- start = run_daemon_command("feature", "start", ("--env", "FOO=bar", "--features", "F-001"), paths)
4492
- try:
4493
- start_payload = json.loads(start.render())
4494
- status = run_daemon_command("feature", "status", (), paths)
4495
- status_payload = json.loads(status.render())
4496
- finally:
4497
- stop = run_daemon_command("feature", "stop", (), paths)
4498
-
4499
- assert start.exit_code == snapshot["startExitCode"]
4500
- assert start_payload["success"] is snapshot["startSuccess"]
4501
- assert isinstance(start_payload["pid"], int)
4502
- assert (paths.feature_state_dir / ".pipeline.pid").exists() is snapshot["pidFileExistsAfterStop"]
4503
- assert status.exit_code == snapshot["statusWhileRunningExitCode"]
4504
- assert status_payload["running"] is snapshot["statusWhileRunningReportsRunning"]
4505
- assert isinstance(status_payload["pid"], int)
4506
- assert status_payload["log_file"].endswith("pipeline-daemon.log")
4507
- assert stop.exit_code == snapshot["stopExitCode"]
4508
- assert json.loads(stop.render())["message"] in {"stopped", "already exited", "not running"}
4509
- log_text = (paths.feature_state_dir / "pipeline-daemon.log").read_text(encoding="utf-8")
4510
- assert "FOO=bar" in log_text or "payload env=bar" in log_text
4511
- assert "payload live=0" in log_text
4512
- assert "--project-root" in log_text
4513
-
4514
-
4515
- def test_python_reset_stalled_filter_selects_stalled_context_items(tmp_path):
4516
- from prizmkit_runtime.reset import run_reset_command
4517
-
4518
- status_by_kind = {
4519
- "feature": ("features", "F-001"),
4520
- "bugfix": ("bugs", "B-001"),
4521
- "refactor": ("refactors", "R-001"),
4522
- }
4523
- for kind, (_collection, item_id) in status_by_kind.items():
4524
- paths = _make_paths(tmp_path / f"stalled-{kind}")
4525
- plan, _state_dir, status_file = _write_family_case(paths, kind, item_id)
4526
- data = json.loads(plan.read_text(encoding="utf-8"))
4527
- data[{"feature": "features", "bugfix": "bugs", "refactor": "refactors"}[kind]][0]["status"] = "stalled_context_continuation"
4528
- plan.write_text(json.dumps(data), encoding="utf-8")
4529
-
4530
- result = run_reset_command(kind, ("--stalled", "--fresh-checkout"), paths)
4531
-
4532
- assert result.exit_code == 0
4533
- assert f"Reset: {item_id}" in result.render()
4534
- runtime = json.loads(status_file.read_text(encoding="utf-8"))
4535
- assert runtime.get("retry_count") == 0
4536
- assert "continuation_pending" not in runtime
4537
- updated = json.loads(plan.read_text(encoding="utf-8"))
4538
- assert updated[{"feature": "features", "bugfix": "bugs", "refactor": "refactors"}[kind]][0]["status"] == "pending"
4539
-
4540
-
4541
- def test_python_daemon_progress_uses_list_status_without_runtime_files(tmp_path):
4542
- from prizmkit_runtime.daemon import _progress_summary
4543
- from prizmkit_runtime.runner_models import family_for
4544
-
4545
- for kind in ("feature", "bugfix", "refactor"):
4546
- paths = _make_paths(tmp_path / f"progress-{kind}")
4547
- if kind == "feature":
4548
- paths.feature_plan.write_text(
4549
- json.dumps({"features": [
4550
- {"id": "F-001", "title": "Done", "status": "completed"},
4551
- {"id": "F-002", "title": "Failed", "status": "failed"},
4552
- {"id": "F-003", "title": "Skipped", "status": "auto_skipped"},
4553
- ]}),
4554
- encoding="utf-8",
4555
- )
4556
- plan = paths.feature_plan
4557
- elif kind == "bugfix":
4558
- paths.bugfix_plan.write_text(
4559
- json.dumps({"bugs": [
4560
- {"id": "B-001", "title": "Done", "status": "completed"},
4561
- {"id": "B-002", "title": "Failed", "status": "failed"},
4562
- {"id": "B-003", "title": "Needs Info", "status": "needs_info"},
4563
- {"id": "B-004", "title": "Blocked", "status": "auto_skipped"},
4564
- ]}),
4565
- encoding="utf-8",
4566
- )
4567
- plan = paths.bugfix_plan
4568
- else:
4569
- paths.refactor_plan.write_text(
4570
- json.dumps({"refactors": [
4571
- {"id": "R-001", "title": "Done", "status": "completed"},
4572
- {"id": "R-002", "title": "Failed", "status": "failed"},
4573
- {"id": "R-003", "title": "Skipped", "status": "auto_skipped"},
4574
- ]}),
4575
- encoding="utf-8",
4576
- )
4577
- plan = paths.refactor_plan
4578
-
4579
- summary = _progress_summary(family_for(kind, paths), plan)
4580
-
4581
- assert summary["total"] == (4 if kind == "bugfix" else 3)
4582
- assert summary["completed"] == 1
4583
- assert summary["failed"] == 1
4584
- assert summary["percent"] == (25.0 if kind == "bugfix" else 33.3)
4585
- if kind == "bugfix":
4586
- assert summary["needs_info"] == 1
4587
- assert summary["auto_skipped"] == 1
4588
- else:
4589
- assert summary["auto_skipped"] == 1
4590
-
4591
-
4592
-
4593
- def _init_git_repo_for_invalid_checkpoint_test(tmp_path):
4594
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4595
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
4596
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
4597
- (tmp_path / "base.txt").write_text("base", encoding="utf-8")
4598
- subprocess.run(["git", "add", "base.txt"], cwd=tmp_path, check=True)
4599
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
4600
- return subprocess.run(["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
4601
-
4602
-
4603
- def _terminal_success_result(tmp_path):
4604
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
4605
- from prizmkit_runtime.status import ProgressSummary
4606
-
4607
- log = tmp_path / "session.log"
4608
- log.write_text("terminal success", encoding="utf-8")
4609
- return AISessionResult(
4610
- command=AISessionCommand(("fake",), None, "claude", "stdin"),
4611
- exit_code=0,
4612
- timed_out=False,
4613
- termination_reason=None,
4614
- stale_marker=None,
4615
- fatal_error_code="",
4616
- progress_summary=ProgressSummary(result_subtype="success", terminal_result_text="Completed"),
4617
- session_log=log,
4618
- backup_log=tmp_path / "backup.log",
4619
- log_recovery=None,
4620
- started_epoch=0,
4621
- ended_epoch=1,
4622
- )
4623
-
4624
-
4625
- def test_session_status_parser_preserves_current_runtime_outcomes():
4626
- import importlib.util
4627
-
4628
- script = PIPELINE_ROOT / "scripts" / "check-session-status.py"
4629
- spec = importlib.util.spec_from_file_location("check_session_status_contract", script)
4630
- module = importlib.util.module_from_spec(spec)
4631
- spec.loader.exec_module(module)
4632
-
4633
- for status in (
4634
- "infra_error",
4635
- "stalled_context_continuation",
4636
- "workflow_blocked",
4637
- "workflow_skipped",
4638
- ):
4639
- assert module.determine_status({"status": status}) == status
4640
-
4641
-
4642
- def test_terminal_success_without_semantic_completion_is_skipped(tmp_path):
4643
- from prizmkit_runtime.runner_classification import classify_session
4644
- from prizmkit_runtime.runner_models import PromptGenerationResult
4645
-
4646
- base_head = _init_git_repo_for_invalid_checkpoint_test(tmp_path)
4647
- artifact_dir = tmp_path / ".prizmkit" / "specs" / "001-incomplete"
4648
- checkpoint = _write_semantic_completion_checkpoint(tmp_path, artifact_dir)
4649
- payload = json.loads(checkpoint.read_text(encoding="utf-8"))
4650
- payload["steps"][2]["required_artifacts"] = [
4651
- ".prizmkit/specs/001-incomplete/test-report.md",
4652
- ".prizmkit/specs/001-incomplete/missing-test-result.json",
4653
- ]
4654
- checkpoint.write_text(json.dumps(payload), encoding="utf-8")
4655
- prompt = PromptGenerationResult(
4656
- output_path=tmp_path / "prompt.md",
4657
- checkpoint_path=checkpoint,
4658
- artifact_path=artifact_dir,
4659
- )
4660
-
4661
- classification = classify_session(
4662
- _terminal_success_result(tmp_path),
4663
- project_root=tmp_path,
4664
- base_head=base_head,
4665
- prompt=prompt,
4666
- )
4667
-
4668
- assert classification.session_status == "workflow_skipped"
4669
- assert classification.reason == "no_semantic_completion:incomplete_semantic_evidence"
4670
- assert classification.fatal_error_code == ""
4671
-
4672
-
4673
- def test_pi_length_stop_with_nonzero_exit_uses_bounded_crash_path(tmp_path):
4674
- from dataclasses import replace
4675
-
4676
- from prizmkit_runtime.runner_classification import classify_session
4677
- from prizmkit_runtime.status import ProgressSummary
4678
-
4679
- base_head = _init_git_repo_for_invalid_checkpoint_test(tmp_path)
4680
- raw = replace(
4681
- _terminal_success_result(tmp_path),
4682
- exit_code=143,
4683
- progress_summary=ProgressSummary(result_subtype="success", stop_reason="length"),
4684
- )
4685
-
4686
- classification = classify_session(raw, project_root=tmp_path, base_head=base_head)
4687
-
4688
- assert classification.session_status == "crashed"
4689
- assert classification.reason == "exit_code=143"
4690
- assert classification.fatal_error_code == ""
4691
-
4692
-
4693
- def test_pi_length_stop_with_zero_exit_and_no_checkpoint_uses_recoverable_continuation(tmp_path):
4694
- from dataclasses import replace
4695
-
4696
- from prizmkit_runtime.runner_classification import classify_session
4697
- from prizmkit_runtime.status import ProgressSummary
4698
-
4699
- base_head = _init_git_repo_for_invalid_checkpoint_test(tmp_path)
4700
- raw = replace(
4701
- _terminal_success_result(tmp_path),
4702
- progress_summary=ProgressSummary(result_subtype="success", stop_reason="length"),
4703
- )
4704
-
4705
- classification = classify_session(raw, project_root=tmp_path, base_head=base_head)
4706
-
4707
- assert classification.session_status == "context_overflow"
4708
- assert classification.reason == "context_overflow"
4709
- assert classification.fatal_error_code == "context_overflow"
4710
-
4711
-
4712
- def test_pi_length_stop_with_in_progress_checkpoint_uses_recoverable_continuation(tmp_path):
4713
- from dataclasses import replace
4714
-
4715
- from prizmkit_runtime.runner_classification import classify_session
4716
- from prizmkit_runtime.runner_models import PromptGenerationResult
4717
- from prizmkit_runtime.status import ProgressSummary
4718
-
4719
- base_head = _init_git_repo_for_invalid_checkpoint_test(tmp_path)
4720
- artifact_dir = tmp_path / ".prizmkit" / "specs" / "001-length-in-progress"
4721
- artifact_dir.mkdir(parents=True)
4722
- checkpoint = artifact_dir / "workflow-checkpoint.json"
4723
- checkpoint.write_text(
4724
- json.dumps({
4725
- "version": 1,
4726
- "workflow_type": "feature-pipeline",
4727
- "steps": [
4728
- {
4729
- "id": "S01",
4730
- "skill": "context-snapshot-and-plan",
4731
- "name": "Specify & Plan",
4732
- "status": "completed",
4733
- "required_artifacts": [],
4734
- "depends_on": None,
4735
- "stage_result": "PLAN_READY",
4736
- },
4737
- {
4738
- "id": "S02",
4739
- "skill": "prizmkit-implement",
4740
- "name": "Implement",
4741
- "status": "completed",
4742
- "required_artifacts": [],
4743
- "depends_on": "S01",
4744
- "stage_result": "IMPLEMENTED",
4745
- },
4746
- {
4747
- "id": "S03",
4748
- "skill": "prizmkit-code-review",
4749
- "name": "Code Review",
4750
- "status": "in_progress",
4751
- "required_artifacts": [],
4752
- "depends_on": "S02",
4753
- },
4754
- {
4755
- "id": "S04",
4756
- "skill": "prizmkit-test",
4757
- "name": "Test",
4758
- "status": "pending",
4759
- "required_artifacts": [],
4760
- "depends_on": "S03",
4761
- },
4762
- {
4763
- "id": "S05",
4764
- "skill": "completion-summary",
4765
- "name": "Completion Summary",
4766
- "status": "pending",
4767
- "required_artifacts": [],
4768
- "depends_on": "S04",
4769
- },
4770
- {
4771
- "id": "S06",
4772
- "skill": "prizmkit-retrospective",
4773
- "name": "Retrospective",
4774
- "status": "pending",
4775
- "required_artifacts": [],
4776
- "depends_on": "S05",
4777
- },
4778
- {
4779
- "id": "S07",
4780
- "skill": "prizmkit-committer",
4781
- "name": "Runtime Commit Handoff",
4782
- "status": "pending",
4783
- "required_artifacts": [],
4784
- "depends_on": "S06",
4785
- },
4786
- ],
4787
- "feature_state": {
4788
- "stage": "code-review",
4789
- "current_stage": "prizmkit-code-review",
4790
- "status": "in_progress",
4791
- "repair_scope": None,
4792
- "repair_round": 0,
4793
- "next_stage": "prizmkit-code-review",
4794
- "blocked_reason": None,
4795
- "terminal_status": None,
4796
- },
4797
- }),
4798
- encoding="utf-8",
4799
- )
4800
- prompt = PromptGenerationResult(
4801
- output_path=tmp_path / "prompt.md",
4802
- checkpoint_path=checkpoint,
4803
- artifact_path=artifact_dir,
4804
- )
4805
- raw = replace(
4806
- _terminal_success_result(tmp_path),
4807
- progress_summary=ProgressSummary(result_subtype="success", stop_reason="length"),
4808
- )
4809
-
4810
- classification = classify_session(
4811
- raw,
4812
- project_root=tmp_path,
4813
- base_head=base_head,
4814
- prompt=prompt,
4815
- )
4816
-
4817
- assert classification.session_status == "context_overflow"
4818
- assert classification.reason == "context_overflow"
4819
- assert classification.fatal_error_code == "context_overflow"
4820
- assert classification.checkpoint_state["current_stage"] == "prizmkit-code-review"
4821
-
4822
-
4823
- def test_pi_length_stop_does_not_override_completed_checkpoint(tmp_path):
4824
- from dataclasses import replace
4825
-
4826
- from prizmkit_runtime.runner_classification import classify_session
4827
- from prizmkit_runtime.runner_models import PromptGenerationResult
4828
- from prizmkit_runtime.status import ProgressSummary
4829
-
4830
- base_head = _init_git_repo_for_invalid_checkpoint_test(tmp_path)
4831
- (tmp_path / "done.txt").write_text("done", encoding="utf-8")
4832
- subprocess.run(["git", "add", "done.txt"], cwd=tmp_path, check=True)
4833
- subprocess.run(
4834
- ["git", "commit", "-m", "done"],
4835
- cwd=tmp_path,
4836
- check=True,
4837
- stdout=subprocess.DEVNULL,
4838
- )
4839
- artifact_dir = tmp_path / ".prizmkit" / "specs" / "001-length-complete"
4840
- checkpoint = _write_semantic_completion_checkpoint(tmp_path, artifact_dir)
4841
- prompt = PromptGenerationResult(
4842
- output_path=tmp_path / "prompt.md",
4843
- checkpoint_path=checkpoint,
4844
- artifact_path=artifact_dir,
4845
- )
4846
- raw = replace(
4847
- _terminal_success_result(tmp_path),
4848
- progress_summary=ProgressSummary(result_subtype="success", stop_reason="length"),
4849
- )
4850
-
4851
- classification = classify_session(raw, project_root=tmp_path, base_head=base_head, prompt=prompt)
4852
-
4853
- assert classification.session_status == "success"
4854
- assert classification.reason == "terminal_success_with_semantic_checkpoint"
4855
- assert classification.fatal_error_code == ""
4856
-
4857
-
4858
- def test_terminal_success_text_does_not_hide_provider_failure(tmp_path):
4859
- from prizmkit_runtime.runner_classification import classify_session
4860
- from prizmkit_runtime.runner_models import PromptGenerationResult
4861
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
4862
- from prizmkit_runtime.status import ProgressSummary
4863
-
4864
- base_head = _init_git_repo_for_invalid_checkpoint_test(tmp_path)
4865
- artifact_dir = tmp_path / ".prizmkit" / "specs" / "001-provider-error"
4866
- checkpoint = _write_semantic_completion_checkpoint(tmp_path, artifact_dir)
4867
- payload = json.loads(checkpoint.read_text(encoding="utf-8"))
4868
- payload["steps"][2]["required_artifacts"] = [
4869
- ".prizmkit/specs/001-provider-error/test-report.md",
4870
- ".prizmkit/specs/001-provider-error/missing-test-result.json",
4871
- ]
4872
- checkpoint.write_text(json.dumps(payload), encoding="utf-8")
4873
- log = tmp_path / "provider-error.log"
4874
- log.write_text("gateway failure after output", encoding="utf-8")
4875
- raw = AISessionResult(
4876
- command=AISessionCommand(("fake",), None, "claude", "stdin"),
4877
- exit_code=0,
4878
- timed_out=False,
4879
- termination_reason=None,
4880
- stale_marker=None,
4881
- fatal_error_code="provider_error",
4882
- progress_summary=ProgressSummary(result_subtype="success"),
4883
- session_log=log,
4884
- backup_log=tmp_path / "backup.log",
4885
- log_recovery=None,
4886
- started_epoch=0,
4887
- ended_epoch=1,
4888
- )
4889
-
4890
- classification = classify_session(
4891
- raw,
4892
- project_root=tmp_path,
4893
- base_head=base_head,
4894
- prompt=PromptGenerationResult(
4895
- output_path=tmp_path / "prompt.md",
4896
- checkpoint_path=checkpoint,
4897
- artifact_path=artifact_dir,
4898
- ),
4899
- )
4900
-
4901
- assert classification.session_status == "infra_error"
4902
- assert classification.reason == "ai_runtime_or_provider_error"
4903
-
4904
-
4905
- @pytest.mark.parametrize(
4906
- ("kind", "item_id"),
4907
- [("feature", "F-001"), ("bugfix", "B-001"), ("refactor", "R-001")],
4908
- )
4909
- def test_family_success_completion_is_terminal_without_warning_metadata(
4910
- tmp_path, kind, item_id
4911
- ):
4912
- from prizmkit_runtime.runner_models import family_for, parse_invocation
4913
- from prizmkit_runtime.runner_status import start_item, update_item
4914
-
4915
- paths = _make_paths(tmp_path / kind)
4916
- item = {
4917
- "id": item_id,
4918
- "title": "Skip invalid completion evidence",
4919
- "status": "pending",
4920
- "priority": "high",
4921
- "dependencies": [],
4922
- }
4923
- if kind == "bugfix":
4924
- item.update(severity="high", description="invalid evidence", reproduction_steps=["run"])
4925
- elif kind == "refactor":
4926
- item.update(description="invalid evidence", targets=["src"], goals=["preserve"])
4927
- _write_family_plan(paths, kind, [item])
4928
- family = family_for(kind, paths)
4929
- invocation = parse_invocation(family, "run", ())
4930
- invocation = invocation.__class__(**{**invocation.__dict__, "list_path": family.plan_path})
4931
- assert start_item(family, invocation, item_id, paths.project_root).ok is True
4932
-
4933
- result = update_item(
4934
- family,
4935
- invocation,
4936
- item_id,
4937
- "success",
4938
- "session-1",
4939
- paths.project_root,
4940
- checkpoint_state={},
4941
- )
4942
- status = json.loads((family.state_dir / item_id / "status.json").read_text(encoding="utf-8"))
4943
-
4944
- assert result.ok is True
4945
- assert result.data["new_status"] == "completed"
4946
- assert status["retry_count"] == 0
4947
- assert status["infra_error_count"] == 0
4948
- assert "completion_warning" not in status
4949
- assert "completion_warning_reason" not in status
4950
- assert status["resume_from_phase"] is None
4951
-
4952
-
4953
- @pytest.mark.parametrize(
4954
- ("kind", "item_id"),
4955
- [("feature", "F-001"), ("bugfix", "B-001"), ("refactor", "R-001")],
4956
- )
4957
- def test_family_status_preserves_direct_raw_workflow_skip(
4958
- tmp_path, kind, item_id
4959
- ):
4960
- from prizmkit_runtime.runner_models import family_for, parse_invocation
4961
- from prizmkit_runtime.runner_status import start_item, update_item
4962
-
4963
- paths = _make_paths(tmp_path / f"historical-{kind}")
4964
- item = {
4965
- "id": item_id,
4966
- "title": "Historical workflow skip",
4967
- "status": "pending",
4968
- "priority": "high",
4969
- "dependencies": [],
4970
- }
4971
- if kind == "bugfix":
4972
- item.update(severity="high", description="invalid evidence", reproduction_steps=["run"])
4973
- elif kind == "refactor":
4974
- item.update(description="invalid evidence", targets=["src"], goals=["preserve"])
4975
- _write_family_plan(paths, kind, [item])
4976
- family = family_for(kind, paths)
4977
- invocation = parse_invocation(family, "run", ())
4978
- invocation = invocation.__class__(**{**invocation.__dict__, "list_path": family.plan_path})
4979
- assert start_item(family, invocation, item_id, paths.project_root).ok is True
4980
-
4981
- result = update_item(
4982
- family,
4983
- invocation,
4984
- item_id,
2965
+ for status in (
2966
+ "infra_error",
2967
+ "stalled_context_continuation",
2968
+ "workflow_blocked",
4985
2969
  "workflow_skipped",
4986
- "historical-session",
4987
- paths.project_root,
4988
- )
4989
-
4990
- assert result.ok is True
4991
- assert result.data["new_status"] == "skipped"
4992
- assert result.data["restart_policy"] == "terminal_skipped"
4993
-
4994
-
4995
- def test_invalid_existing_checkpoint_skips_terminal_success_with_completion_summary(tmp_path):
4996
- from prizmkit_runtime.runner_classification import classify_session
4997
- from prizmkit_runtime.runner_models import PromptGenerationResult
4998
-
4999
- base_head = _init_git_repo_for_invalid_checkpoint_test(tmp_path)
5000
- artifact_dir = tmp_path / ".prizmkit" / "specs" / "001-invalid"
5001
- artifact_dir.mkdir(parents=True)
5002
- checkpoint = artifact_dir / "workflow-checkpoint.json"
5003
- checkpoint.write_text(json.dumps({"steps": [{"id": "S01", "skill": "done", "name": "Done", "status": "not-valid"}]}), encoding="utf-8")
5004
- (artifact_dir / "completion-summary.json").write_text(json.dumps({"completion_notes": ["Completed durable workflow"]}), encoding="utf-8")
5005
- prompt = PromptGenerationResult(output_path=tmp_path / "prompt.md", checkpoint_path=checkpoint, artifact_path=artifact_dir)
5006
-
5007
- classification = classify_session(_terminal_success_result(tmp_path), project_root=tmp_path, base_head=base_head, prompt=prompt)
5008
-
5009
- assert classification.session_status == "workflow_skipped"
5010
- assert classification.reason == "invalid_workflow_checkpoint:invalid_status"
5011
-
5012
-
5013
- def test_invalid_existing_checkpoint_blocks_runtime_failure_with_head_change(tmp_path):
5014
- from prizmkit_runtime.runner_classification import classify_session
5015
- from prizmkit_runtime.runner_models import PromptGenerationResult
5016
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
5017
- from prizmkit_runtime.status import ProgressSummary
5018
-
5019
- base_head = _init_git_repo_for_invalid_checkpoint_test(tmp_path)
5020
- (tmp_path / "done.txt").write_text("done", encoding="utf-8")
5021
- subprocess.run(["git", "add", "done.txt"], cwd=tmp_path, check=True)
5022
- subprocess.run(["git", "commit", "-m", "done"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
5023
- artifact_dir = tmp_path / ".prizmkit" / "specs" / "001-invalid"
5024
- artifact_dir.mkdir(parents=True)
5025
- checkpoint = artifact_dir / "workflow-checkpoint.json"
5026
- checkpoint.write_text(json.dumps({"steps": [{"id": "bad", "skill": "done", "name": "Done", "status": "completed"}]}), encoding="utf-8")
5027
- raw = AISessionResult(
5028
- command=AISessionCommand(("fake",), None, "claude", "stdin"),
5029
- exit_code=1,
5030
- timed_out=False,
5031
- termination_reason=None,
5032
- stale_marker=None,
5033
- fatal_error_code="context_overflow",
5034
- progress_summary=ProgressSummary(fatal_error_code="context_overflow"),
5035
- session_log=tmp_path / "session.log",
5036
- backup_log=tmp_path / "backup.log",
5037
- log_recovery=None,
5038
- started_epoch=0,
5039
- ended_epoch=1,
5040
- )
5041
- raw.session_log.write_text("context overflow", encoding="utf-8")
5042
- prompt = PromptGenerationResult(output_path=tmp_path / "prompt.md", checkpoint_path=checkpoint, artifact_path=artifact_dir)
5043
-
5044
- classification = classify_session(raw, project_root=tmp_path, base_head=base_head, prompt=prompt)
5045
-
5046
- assert classification.session_status == "crashed"
5047
- assert classification.reason == "invalid_workflow_checkpoint:malformed_step_id"
5048
-
5049
-
5050
- def test_invalid_existing_checkpoint_blocks_ambiguous_clean_exit(tmp_path):
5051
- from prizmkit_runtime.runner_classification import classify_session
5052
- from prizmkit_runtime.runner_models import PromptGenerationResult
5053
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
5054
- from prizmkit_runtime.status import ProgressSummary
5055
-
5056
- base_head = _init_git_repo_for_invalid_checkpoint_test(tmp_path)
5057
- artifact_dir = tmp_path / ".prizmkit" / "specs" / "001-invalid"
5058
- artifact_dir.mkdir(parents=True)
5059
- checkpoint = artifact_dir / "workflow-checkpoint.json"
5060
- checkpoint.write_text(json.dumps({"steps": []}), encoding="utf-8")
5061
- (tmp_path / "dirty.txt").write_text("dirty", encoding="utf-8")
5062
- log = tmp_path / "session.log"
5063
- log.write_text("clean exit but dirty workspace", encoding="utf-8")
5064
- raw = AISessionResult(
5065
- command=AISessionCommand(("fake",), None, "claude", "stdin"),
5066
- exit_code=0,
5067
- timed_out=False,
5068
- termination_reason=None,
5069
- stale_marker=None,
5070
- fatal_error_code="",
5071
- progress_summary=ProgressSummary(result_subtype="", terminal_result_text=""),
5072
- session_log=log,
5073
- backup_log=tmp_path / "backup.log",
5074
- log_recovery=None,
5075
- started_epoch=0,
5076
- ended_epoch=1,
5077
- )
5078
- prompt = PromptGenerationResult(output_path=tmp_path / "prompt.md", checkpoint_path=checkpoint, artifact_path=artifact_dir)
5079
-
5080
- classification = classify_session(raw, project_root=tmp_path, base_head=base_head, prompt=prompt)
5081
-
5082
- assert classification.session_status == "crashed"
5083
- assert classification.reason == "invalid_workflow_checkpoint:empty_steps"
5084
-
5085
-
5086
- @pytest.mark.parametrize(
5087
- ("kind", "item_id", "branch"),
5088
- [
5089
- ("feature", "F-001", "dev/F-001-ai-retry"),
5090
- ("bugfix", "B-001", "bugfix/B-001-ai-retry"),
5091
- ("refactor", "R-001", "refactor/R-001-ai-retry"),
5092
- ],
5093
- )
5094
- @pytest.mark.parametrize("retry_status", ["infra_error", "crashed", "timed_out"])
5095
- def test_retryable_ai_errors_continue_in_process_for_all_families(monkeypatch, tmp_path, kind, item_id, branch, retry_status):
5096
- from prizmkit_runtime import runners
5097
- from prizmkit_runtime.runner_models import family_for, parse_invocation
5098
-
5099
- monkeypatch.setenv("DEV_BRANCH", branch)
5100
- paths = _make_paths(tmp_path / kind / retry_status)
5101
- family = family_for(kind, paths)
5102
- invocation = parse_invocation(family, "run", ())
5103
- plan_path = {"feature": paths.feature_plan, "bugfix": paths.bugfix_plan, "refactor": paths.refactor_plan}[kind]
5104
- invocation = invocation.__class__(**{**invocation.__dict__, "list_path": plan_path})
5105
- observed = _install_runner_session_fakes(monkeypatch, runners, statuses=(retry_status, "success"))
5106
- sleep_calls = []
5107
- branch_plans = []
5108
- monkeypatch.setattr(runners.time, "sleep", lambda seconds: sleep_calls.append(seconds))
5109
- monkeypatch.setattr(
5110
- runners,
5111
- "run_git_plan",
5112
- lambda project_root, plan: (branch_plans.append(plan.name) or SimpleNamespace(ok=True, plan=plan, results=())),
5113
- )
5114
-
5115
- status = runners._process_item(family, invocation, item_id, paths, initial_metadata={})
5116
-
5117
- assert status == "completed"
5118
- assert sleep_calls == [5]
5119
- assert len(observed.launch_cwds) == 2
5120
- assert observed.launch_cwds[0] == observed.launch_cwds[1]
5121
- assert branch_plans.count("branch_create") == 1
5122
- assert observed.updates[0][0] == retry_status
5123
- continuation = observed.prompt_calls[1]["continuation"]
5124
- assert continuation["previous_session_id"].endswith("session-1")
5125
- assert continuation["failure_classification"] == retry_status
5126
- assert continuation["active_dev_branch"] == branch
5127
-
5128
-
5129
- @pytest.mark.parametrize(
5130
- ("kind", "item_id", "branch"),
5131
- [
5132
- ("feature", "F-001", "dev/F-001-context-budget"),
5133
- ("bugfix", "B-001", "bugfix/B-001-context-budget"),
5134
- ("refactor", "R-001", "refactor/R-001-context-budget"),
5135
- ],
5136
- )
5137
- def test_context_overflow_retry_budget_prevents_session_n_plus_one(monkeypatch, tmp_path, kind, item_id, branch):
5138
- from prizmkit_runtime import runners
5139
- from prizmkit_runtime.runner_models import family_for, parse_invocation
5140
-
5141
- monkeypatch.setenv("DEV_BRANCH", branch)
5142
- paths = _make_paths(tmp_path / kind)
5143
- family = family_for(kind, paths)
5144
- invocation = parse_invocation(family, "run", ())
5145
- plan_path = {"feature": paths.feature_plan, "bugfix": paths.bugfix_plan, "refactor": paths.refactor_plan}[kind]
5146
- invocation = invocation.__class__(**{**invocation.__dict__, "list_path": plan_path})
5147
- observed = _install_runner_session_fakes(
5148
- monkeypatch,
5149
- runners,
5150
- statuses=("context_overflow", "context_overflow", "context_overflow", "context_overflow"),
5151
- max_retries=3,
5152
- )
5153
- sleep_calls = []
5154
- monkeypatch.setattr(runners.time, "sleep", lambda seconds: sleep_calls.append(seconds))
5155
- monkeypatch.setattr(
5156
- runners,
5157
- "run_git_plan",
5158
- lambda project_root, plan: SimpleNamespace(ok=True, plan=plan, results=()),
5159
- )
5160
-
5161
- status = runners._process_item(family, invocation, item_id, paths, initial_metadata={})
5162
-
5163
- assert status == "failed"
5164
- assert len(observed.launch_cwds) == 3
5165
- assert len(observed.updates) == 3
5166
- assert sleep_calls == [5, 5]
5167
-
5168
-
5169
- def test_unique_session_ids_do_not_collide_when_wall_clock_second_is_frozen(monkeypatch):
5170
- from prizmkit_runtime import runners
5171
-
5172
- monkeypatch.setattr(runners.time, "strftime", lambda _fmt: "20260711030000")
5173
- values = iter((101, 102))
5174
- monkeypatch.setattr(runners.time, "time_ns", lambda: next(values))
5175
-
5176
- first = runners._session_id("F-001")
5177
- second = runners._session_id("F-001")
5178
-
5179
- assert first != second
5180
- assert first.endswith("-101")
5181
- assert second.endswith("-102")
5182
-
5183
-
5184
- @pytest.mark.parametrize("summary_text", ["{}", "{not-json", '{"completion_notes": []}', '{"completion_notes": [""]}'])
5185
- def test_invalid_completion_summary_does_not_prove_late_runtime_success(tmp_path, summary_text):
5186
- from prizmkit_runtime.runner_classification import classify_session
5187
- from prizmkit_runtime.runner_models import PromptGenerationResult
5188
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
5189
- from prizmkit_runtime.status import ProgressSummary
5190
-
5191
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
5192
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
5193
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
5194
- (tmp_path / "base.txt").write_text("base", encoding="utf-8")
5195
- subprocess.run(["git", "add", "base.txt"], cwd=tmp_path, check=True)
5196
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
5197
- base_head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
5198
- artifact_dir = tmp_path / ".prizmkit" / "specs" / "001-invalid"
5199
- artifact_dir.mkdir(parents=True)
5200
- (artifact_dir / "completion-summary.json").write_text(summary_text, encoding="utf-8")
5201
- log = tmp_path / "session.log"
5202
- log.write_text("quota exceeded", encoding="utf-8")
5203
- result = AISessionResult(
5204
- command=AISessionCommand(("fake",), None, "codebuddy", "stdin"),
5205
- exit_code=1,
5206
- timed_out=False,
5207
- termination_reason=None,
5208
- stale_marker=None,
5209
- fatal_error_code="api_error",
5210
- progress_summary=ProgressSummary(terminal_result_text="quota exceeded"),
5211
- session_log=log,
5212
- backup_log=tmp_path / "backup.log",
5213
- log_recovery=None,
5214
- started_epoch=0,
5215
- ended_epoch=1,
5216
- )
5217
-
5218
- classification = classify_session(
5219
- result,
5220
- project_root=tmp_path,
5221
- base_head=base_head,
5222
- prompt=PromptGenerationResult(output_path=tmp_path / "prompt.md", artifact_path=artifact_dir),
5223
- )
5224
-
5225
- assert classification.session_status == "infra_error"
5226
-
5227
-
5228
- def test_non_utf8_completion_summary_does_not_abort_classification(tmp_path):
5229
- from prizmkit_runtime.runner_classification import classify_session
5230
- from prizmkit_runtime.runner_models import PromptGenerationResult
5231
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
5232
- from prizmkit_runtime.status import ProgressSummary
5233
-
5234
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
5235
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
5236
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
5237
- (tmp_path / "base.txt").write_text("base", encoding="utf-8")
5238
- subprocess.run(["git", "add", "base.txt"], cwd=tmp_path, check=True)
5239
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
5240
- base_head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
5241
- artifact_dir = tmp_path / ".prizmkit" / "specs" / "001-corrupt"
5242
- artifact_dir.mkdir(parents=True)
5243
- (artifact_dir / "completion-summary.json").write_bytes(b"\xff\xfe")
5244
- log = tmp_path / "session.log"
5245
- log.write_text("quota exceeded", encoding="utf-8")
5246
- result = AISessionResult(
5247
- command=AISessionCommand(("fake",), None, "codebuddy", "stdin"),
5248
- exit_code=1,
5249
- timed_out=False,
5250
- termination_reason=None,
5251
- stale_marker=None,
5252
- fatal_error_code="api_error",
5253
- progress_summary=ProgressSummary(terminal_result_text="quota exceeded"),
5254
- session_log=log,
5255
- backup_log=tmp_path / "backup.log",
5256
- log_recovery=None,
5257
- started_epoch=0,
5258
- ended_epoch=1,
5259
- )
5260
-
5261
- classification = classify_session(
5262
- result,
5263
- project_root=tmp_path,
5264
- base_head=base_head,
5265
- prompt=PromptGenerationResult(output_path=tmp_path / "prompt.md", artifact_path=artifact_dir),
5266
- )
5267
-
5268
- assert classification.session_status == "infra_error"
5269
-
5270
-
5271
- @pytest.mark.parametrize(
5272
- ("timed_out", "termination_reason", "expected_status", "expected_reason"),
5273
- [
5274
- (True, "timeout", "timed_out", "timeout"),
5275
- (False, "stale_session", "crashed", "stale_session"),
5276
- ],
5277
- )
5278
- def test_timeout_and_stale_termination_override_provider_error_markers(tmp_path, timed_out, termination_reason, expected_status, expected_reason):
5279
- from prizmkit_runtime.runner_classification import classify_session
5280
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
5281
- from prizmkit_runtime.status import ProgressSummary
5282
-
5283
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
5284
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
5285
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
5286
- (tmp_path / "base.txt").write_text("base", encoding="utf-8")
5287
- subprocess.run(["git", "add", "base.txt"], cwd=tmp_path, check=True)
5288
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
5289
- base_head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
5290
- log = tmp_path / "session.log"
5291
- log.write_text("gateway API error", encoding="utf-8")
5292
- result = AISessionResult(
5293
- command=AISessionCommand(("fake",), None, "codebuddy", "stdin"),
5294
- exit_code=1,
5295
- timed_out=timed_out,
5296
- termination_reason=termination_reason,
5297
- stale_marker=None,
5298
- fatal_error_code="api_error",
5299
- progress_summary=ProgressSummary(terminal_result_text="provider gateway error"),
5300
- session_log=log,
5301
- backup_log=tmp_path / "backup.log",
5302
- log_recovery=None,
5303
- started_epoch=0,
5304
- ended_epoch=1,
5305
- )
5306
-
5307
- classification = classify_session(result, project_root=tmp_path, base_head=base_head)
5308
-
5309
- assert classification.session_status == expected_status
5310
- assert classification.reason == expected_reason
5311
-
5312
-
5313
-
5314
- @pytest.mark.parametrize("workflow_type", ["feature-pipeline", "bugfix-pipeline", "refactor-pipeline"])
5315
- def test_semantic_completion_classification_has_cross_family_parity(tmp_path, workflow_type):
5316
- from prizmkit_runtime.runner_classification import classify_session
5317
- from prizmkit_runtime.runner_models import PromptGenerationResult
5318
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
5319
- from prizmkit_runtime.status import ProgressSummary
5320
-
5321
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
5322
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
5323
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
5324
- (tmp_path / "base.txt").write_text("base", encoding="utf-8")
5325
- subprocess.run(["git", "add", "base.txt"], cwd=tmp_path, check=True)
5326
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
5327
- base_head = subprocess.run(
5328
- ["git", "rev-parse", "HEAD"],
5329
- cwd=tmp_path,
5330
- check=True,
5331
- stdout=subprocess.PIPE,
5332
- text=True,
5333
- ).stdout.strip()
5334
- (tmp_path / "done.txt").write_text("done", encoding="utf-8")
5335
- subprocess.run(["git", "add", "done.txt"], cwd=tmp_path, check=True)
5336
- subprocess.run(
5337
- ["git", "commit", "-m", "done"],
5338
- cwd=tmp_path,
5339
- check=True,
5340
- stdout=subprocess.DEVNULL,
5341
- )
5342
- artifact = tmp_path / ".prizmkit" / "artifacts" / workflow_type
5343
- checkpoint = _write_semantic_completion_checkpoint(tmp_path, artifact, workflow_type)
5344
- log = tmp_path / f"{workflow_type}.log"
5345
- log.write_text("success", encoding="utf-8")
5346
- raw = AISessionResult(
5347
- command=AISessionCommand(("fake",), None, "claude", "stdin"),
5348
- exit_code=0,
5349
- timed_out=False,
5350
- termination_reason=None,
5351
- stale_marker=None,
5352
- fatal_error_code="",
5353
- progress_summary=ProgressSummary(result_subtype="success"),
5354
- session_log=log,
5355
- backup_log=tmp_path / "backup.log",
5356
- log_recovery=None,
5357
- started_epoch=0,
5358
- ended_epoch=1,
5359
- )
5360
-
5361
- classification = classify_session(
5362
- raw,
5363
- project_root=tmp_path,
5364
- base_head=base_head,
5365
- prompt=PromptGenerationResult(
5366
- output_path=tmp_path / "prompt.md",
5367
- checkpoint_path=checkpoint,
5368
- artifact_path=artifact,
5369
- ),
5370
- )
5371
-
5372
- assert classification.session_status == "success"
5373
- assert classification.checkpoint_state["terminal_status"] == "WORKFLOW_COMPLETED"
5374
-
5375
-
5376
- def test_semantic_blocked_classification_is_terminal_and_retry_neutral(tmp_path):
5377
- from prizmkit_runtime.runner_classification import classify_session
5378
- from prizmkit_runtime.runner_models import PromptGenerationResult
5379
- from prizmkit_runtime.sessions import AISessionCommand, AISessionResult
5380
- from prizmkit_runtime.status import ProgressSummary
5381
-
5382
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
5383
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
5384
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
5385
- (tmp_path / "base.txt").write_text("base", encoding="utf-8")
5386
- subprocess.run(["git", "add", "base.txt"], cwd=tmp_path, check=True)
5387
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
5388
- artifact = tmp_path / ".prizmkit" / "specs" / "blocked"
5389
- checkpoint = _write_semantic_completion_checkpoint(tmp_path, artifact)
5390
- data = json.loads(checkpoint.read_text(encoding="utf-8"))
5391
- data["feature_state"].update(
5392
- terminal_status="WORKFLOW_BLOCKED",
5393
- blocked_reason="repair_round_limit",
5394
- repair_round=3,
5395
- )
5396
- checkpoint.write_text(json.dumps(data), encoding="utf-8")
5397
- log = tmp_path / "blocked.log"
5398
- log.write_text("ambiguous failure", encoding="utf-8")
5399
- raw = AISessionResult(
5400
- command=AISessionCommand(("fake",), None, "codebuddy", "stdin"),
5401
- exit_code=1,
5402
- timed_out=False,
5403
- termination_reason=None,
5404
- stale_marker=None,
5405
- fatal_error_code="",
5406
- progress_summary=ProgressSummary(terminal_result_text="ambiguous failure"),
5407
- session_log=log,
5408
- backup_log=tmp_path / "backup.log",
5409
- log_recovery=None,
5410
- started_epoch=0,
5411
- ended_epoch=1,
5412
- )
5413
-
5414
- classification = classify_session(
5415
- raw,
5416
- project_root=tmp_path,
5417
- base_head="",
5418
- prompt=PromptGenerationResult(
5419
- output_path=tmp_path / "prompt.md",
5420
- checkpoint_path=checkpoint,
5421
- artifact_path=artifact,
5422
- ),
5423
- )
5424
-
5425
- assert classification.session_status == "workflow_blocked"
5426
- assert classification.reason == "repair_round_limit"
5427
- assert classification.checkpoint_state["repair_round"] == 3
5428
-
5429
-
5430
- def test_runtime_semantic_paths_do_not_invoke_composite_workflow():
5431
- sources = [
5432
- PIPELINE_ROOT / "prizmkit_runtime" / "checkpoint_state.py",
5433
- PIPELINE_ROOT / "prizmkit_runtime" / "runner_classification.py",
5434
- PIPELINE_ROOT / "prizmkit_runtime" / "runners.py",
5435
- ]
5436
-
5437
- for source in sources:
5438
- assert "prizmkit-workflow" not in source.read_text(encoding="utf-8")
5439
-
5440
-
5441
-
5442
- @pytest.mark.parametrize(
5443
- ("kind", "item_id", "blocked_status"),
5444
- [("feature", "F-001", "failed"), ("bugfix", "B-001", "needs_info"), ("refactor", "R-001", "failed")],
5445
- )
5446
- def test_family_status_persists_identical_semantic_blocked_snapshot_without_retry_spend(
5447
- tmp_path, kind, item_id, blocked_status
5448
- ):
5449
- from prizmkit_runtime.runner_models import family_for, parse_invocation
5450
- from prizmkit_runtime.runner_status import start_item, update_item
2970
+ ):
2971
+ assert module.determine_status({"status": status}) == status
5451
2972
 
5452
- paths = _make_paths(tmp_path)
5453
- item = {
5454
- "id": item_id,
5455
- "title": "Semantic blocked",
5456
- "status": "pending",
5457
- "priority": "high",
5458
- "dependencies": [],
5459
- }
5460
- if kind == "bugfix":
5461
- item.update(severity="high", description="blocked", reproduction_steps=["run"])
5462
- elif kind == "refactor":
5463
- item.update(description="blocked", targets=["src"], goals=["preserve"])
5464
- _write_family_plan(paths, kind, [item])
5465
- family = family_for(kind, paths)
5466
- invocation = parse_invocation(family, "run", ())
5467
- invocation = invocation.__class__(**{**invocation.__dict__, "list_path": family.plan_path})
5468
- assert start_item(family, invocation, item_id, paths.project_root).ok is True
5469
- semantic = {
5470
- "current_stage": None,
5471
- "next_stage": None,
5472
- "stage_result": "TEST_BLOCKED",
5473
- "repair_scope": "production",
5474
- "repair_round": 2,
5475
- "blocked_reason": "test_blocked",
5476
- "terminal_status": "WORKFLOW_BLOCKED",
5477
- }
5478
2973
 
5479
- result = update_item(
5480
- family,
5481
- invocation,
5482
- item_id,
5483
- "workflow_blocked",
5484
- "session-1",
5485
- paths.project_root,
5486
- checkpoint_state=semantic,
5487
- )
5488
- status = json.loads((family.state_dir / item_id / "status.json").read_text(encoding="utf-8"))
5489
-
5490
- assert result.ok is True
5491
- assert result.data["new_status"] == blocked_status
5492
- assert result.data["checkpoint_state"] == semantic
5493
- assert result.data["restart_policy"] == "terminal_blocked"
5494
- assert status["retry_count"] == 0
5495
- assert status["infra_error_count"] == 0
5496
- for key, value in semantic.items():
5497
- assert status[key] == value
5498
-
5499
-
5500
- def test_runtime_sources_do_not_depend_on_direct_lifecycle_composite():
5501
- runtime_root = REPO_ROOT / "dev-pipeline"
5502
- source_files = list(runtime_root.rglob("*.py"))
5503
- for source in source_files:
5504
- if "__pycache__" in source.parts or "tests" in source.parts or not source.is_file():
5505
- continue
5506
- assert "prizmkit-workflow" not in source.read_text(encoding="utf-8")