prizmkit 1.1.192 → 1.1.193

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 (56) hide show
  1. package/bundled/VERSION.json +3 -3
  2. package/bundled/dev-pipeline/README.md +23 -34
  3. package/bundled/dev-pipeline/assets/feature-list-example.json +0 -1
  4. package/bundled/dev-pipeline/assets/skill-subagent-integration.md +3 -0
  5. package/bundled/dev-pipeline/prizmkit_runtime/config.py +24 -2
  6. package/bundled/dev-pipeline/prizmkit_runtime/daemon.py +2 -0
  7. package/bundled/dev-pipeline/prizmkit_runtime/gitops.py +89 -40
  8. package/bundled/dev-pipeline/prizmkit_runtime/heartbeat.py +9 -1
  9. package/bundled/dev-pipeline/prizmkit_runtime/interoperability.py +0 -22
  10. package/bundled/dev-pipeline/prizmkit_runtime/platform_detection.py +11 -7
  11. package/bundled/dev-pipeline/prizmkit_runtime/processes.py +26 -20
  12. package/bundled/dev-pipeline/prizmkit_runtime/reset.py +37 -4
  13. package/bundled/dev-pipeline/prizmkit_runtime/reset_preserve.py +20 -41
  14. package/bundled/dev-pipeline/prizmkit_runtime/runner_bookkeeping.py +74 -36
  15. package/bundled/dev-pipeline/prizmkit_runtime/runner_models.py +0 -66
  16. package/bundled/dev-pipeline/prizmkit_runtime/runners.py +271 -52
  17. package/bundled/dev-pipeline/prizmkit_runtime/runtime_commit.py +51 -13
  18. package/bundled/dev-pipeline/prizmkit_runtime/sessions.py +43 -15
  19. package/bundled/dev-pipeline/prizmkit_runtime/stream_progress.py +27 -24
  20. package/bundled/dev-pipeline/prizmkit_runtime/task_checkout.py +0 -1
  21. package/bundled/dev-pipeline/scripts/check-session-status.py +13 -1
  22. package/bundled/dev-pipeline/scripts/continuation.py +2 -3
  23. package/bundled/dev-pipeline/scripts/detect-stuck.py +19 -5
  24. package/bundled/dev-pipeline/scripts/generate-bootstrap-prompt.py +6 -14
  25. package/bundled/dev-pipeline/scripts/generate-bugfix-prompt.py +13 -8
  26. package/bundled/dev-pipeline/scripts/init-change-artifact.py +17 -2
  27. package/bundled/dev-pipeline/scripts/prompt_framework.py +39 -21
  28. package/bundled/dev-pipeline/scripts/update-checkpoint.py +27 -0
  29. package/bundled/dev-pipeline/templates/bootstrap-tier3.md +1 -1
  30. package/bundled/dev-pipeline/templates/bugfix-bootstrap-prompt.md +6 -6
  31. package/bundled/dev-pipeline/templates/sections/bugfix-phase-test.md +1 -1
  32. package/bundled/dev-pipeline/templates/sections/phase-prizmkit-test.md +1 -1
  33. package/bundled/skills/_metadata.json +1 -1
  34. package/package.json +1 -1
  35. package/bundled/dev-pipeline/tests/_helpers.py +0 -418
  36. package/bundled/dev-pipeline/tests/conftest.py +0 -73
  37. package/bundled/dev-pipeline/tests/live_ai_cli_log_smoke.py +0 -208
  38. package/bundled/dev-pipeline/tests/test_auto_skip.py +0 -1806
  39. package/bundled/dev-pipeline/tests/test_checkpoint_state.py +0 -1439
  40. package/bundled/dev-pipeline/tests/test_daemon_and_scripts.py +0 -257
  41. package/bundled/dev-pipeline/tests/test_e2e_pipeline_run.py +0 -500
  42. package/bundled/dev-pipeline/tests/test_generate_bootstrap_prompt.py +0 -1654
  43. package/bundled/dev-pipeline/tests/test_generate_bugfix_prompt.py +0 -629
  44. package/bundled/dev-pipeline/tests/test_python_runner_parity.py +0 -2973
  45. package/bundled/dev-pipeline/tests/test_recovery_workflow.py +0 -321
  46. package/bundled/dev-pipeline/tests/test_repository_bootstrap.py +0 -251
  47. package/bundled/dev-pipeline/tests/test_reset_modes.py +0 -1196
  48. package/bundled/dev-pipeline/tests/test_reset_preserve.py +0 -872
  49. package/bundled/dev-pipeline/tests/test_runner_bookkeeping.py +0 -766
  50. package/bundled/dev-pipeline/tests/test_runner_lifecycle.py +0 -1257
  51. package/bundled/dev-pipeline/tests/test_runtime_commit.py +0 -1113
  52. package/bundled/dev-pipeline/tests/test_runtime_helper.py +0 -380
  53. package/bundled/dev-pipeline/tests/test_session_launch.py +0 -1101
  54. package/bundled/dev-pipeline/tests/test_stream_progress.py +0 -585
  55. package/bundled/dev-pipeline/tests/test_unified_cli.py +0 -3625
  56. package/bundled/dev-pipeline/tests/test_utils.py +0 -170
@@ -1,3625 +0,0 @@
1
- """Tests for the unified Python CLI architecture skeleton."""
2
-
3
- import json
4
- import os
5
- import re
6
- import shutil
7
- import subprocess
8
- import sys
9
- import time
10
- from dataclasses import FrozenInstanceError
11
- from pathlib import Path
12
-
13
- import pytest
14
-
15
- from _helpers import load_progress_parser_module as _load_progress_parser_module
16
-
17
- REPO_ROOT = Path(__file__).resolve().parents[2]
18
- PIPELINE_ROOT = REPO_ROOT / "dev-pipeline"
19
- CLI_PATH = PIPELINE_ROOT / "cli.py"
20
- def _python_310_plus() -> str:
21
- if sys.version_info >= (3, 10):
22
- return sys.executable
23
- for executable in ("python3.12", "python3.11", "python3.10"):
24
- resolved = shutil.which(executable)
25
- if resolved:
26
- return resolved
27
- return sys.executable
28
-
29
-
30
- PYTHON_310_PLUS = _python_310_plus()
31
-
32
- if str(PIPELINE_ROOT) not in sys.path:
33
- sys.path.insert(0, str(PIPELINE_ROOT))
34
-
35
-
36
- def run_cli(*args, env=None):
37
- return subprocess.run(
38
- [PYTHON_310_PLUS, str(CLI_PATH), *args],
39
- cwd=REPO_ROOT,
40
- env=env,
41
- text=True,
42
- stdout=subprocess.PIPE,
43
- stderr=subprocess.PIPE,
44
- check=False,
45
- )
46
-
47
-
48
- def test_cli_help_exposes_only_operation_first_public_namespaces():
49
- result = run_cli("--help")
50
-
51
- assert result.returncode == 0
52
- assert "canonical Python runtime CLI" in result.stdout
53
- assert "operation-first" in result.stdout
54
- for group in ["run", "status", "reset", "daemon", "diagnostics", "helper"]:
55
- assert group in result.stdout
56
- for removed in ["feature", "bugfix", "recovery"]:
57
- assert removed not in result.stdout.lower()
58
- assert "Traceback" not in result.stderr
59
-
60
-
61
- def test_cli_help_preserves_runtime_identity_at_narrow_terminal_width():
62
- result = run_cli("--help", env={**os.environ, "COLUMNS": "24"})
63
-
64
- assert result.returncode == 0
65
- assert "canonical Python runtime CLI" in result.stdout
66
- assert "operation-first" in result.stdout
67
-
68
-
69
- def test_module_entrypoint_help_exposes_same_cli():
70
- env = {**os.environ, "PYTHONPATH": str(PIPELINE_ROOT)}
71
- result = subprocess.run(
72
- [PYTHON_310_PLUS, "-m", "prizmkit_runtime", "--help"],
73
- cwd=REPO_ROOT,
74
- env=env,
75
- text=True,
76
- stdout=subprocess.PIPE,
77
- stderr=subprocess.PIPE,
78
- check=False,
79
- )
80
-
81
- assert result.returncode == 0
82
- assert "canonical Python runtime CLI" in result.stdout
83
- assert "diagnostics" in result.stdout
84
-
85
-
86
- @pytest.mark.parametrize(
87
- "args",
88
- [
89
- ("--help",),
90
- ("run", "--help"),
91
- ("run", "feature", "--help"),
92
- ("run", "bugfix", "--help"),
93
- ("status", "--help"),
94
- ("status", "feature", "--help"),
95
- ("status", "all", "--help"),
96
- ("reset", "--help"),
97
- ("reset", "feature", "--help"),
98
- ("daemon", "--help"),
99
- ("daemon", "feature", "--help"),
100
- ("daemon", "feature", "start", "--help"),
101
- ("daemon", "bugfix", "stop", "--help"),
102
- ("daemon", "feature", "logs", "--help"),
103
- ("daemon", "feature", "restart", "--help"),
104
- ("diagnostics", "--help"),
105
- ("diagnostics", "ai-cli", "--help"),
106
- ("helper", "--help"),
107
- ],
108
- )
109
- def test_help_at_every_namespace_depth_is_parser_owned_and_never_dispatches(monkeypatch, args):
110
- from prizmkit_runtime import cli as runtime_cli
111
-
112
- dispatched = []
113
- monkeypatch.setattr(runtime_cli, "ensure_supported_python", lambda: None)
114
- monkeypatch.setattr(runtime_cli, "_dispatch", lambda parsed: dispatched.append(parsed))
115
-
116
- with pytest.raises(SystemExit) as exc_info:
117
- runtime_cli.main(list(args))
118
-
119
- assert exc_info.value.code == 0
120
- assert dispatched == []
121
-
122
-
123
- def test_invalid_arguments_report_usage_without_traceback():
124
- result = run_cli("unknown-command")
125
-
126
- assert result.returncode == 2
127
- assert "usage:" in result.stderr
128
- assert "invalid choice" in result.stderr
129
- assert "Traceback" not in result.stderr
130
-
131
-
132
- @pytest.mark.parametrize(
133
- "args",
134
- [
135
- ("recovery",),
136
- ("recovery", "detect"),
137
- ("recovery", "run"),
138
- ("recovery", "describe"),
139
- ("recovery", "run", "--dry-run"),
140
- ],
141
- )
142
- def test_former_recovery_invocations_are_unknown_commands(args):
143
- result = run_cli(*args)
144
-
145
- assert result.returncode == 2
146
- assert "invalid choice: 'recovery'" in result.stderr
147
- assert "Traceback" not in result.stderr
148
-
149
-
150
- def test_former_recovery_invocation_never_reaches_dispatch(monkeypatch):
151
- from prizmkit_runtime import cli as runtime_cli
152
-
153
- dispatched = []
154
- monkeypatch.setattr(runtime_cli, "ensure_supported_python", lambda: None)
155
- monkeypatch.setattr(runtime_cli, "_dispatch", lambda args: dispatched.append(args))
156
-
157
- with pytest.raises(SystemExit) as exc_info:
158
- runtime_cli.main(["recovery", "run", "--dry-run"])
159
-
160
- assert exc_info.value.code == 2
161
- assert dispatched == []
162
-
163
-
164
- @pytest.mark.parametrize(
165
- "args",
166
- [
167
- ("feature", "run"),
168
- ("feature", "status"),
169
- ("feature", "reset"),
170
- ("feature", "unskip"),
171
- ("feature", "test-cli"),
172
- ("feature", "describe"),
173
- ("bugfix", "run"),
174
- ("bugfix", "status"),
175
- ("bugfix", "reset"),
176
- ("bugfix", "unskip"),
177
- ("bugfix", "describe"),
178
- ("reset", "describe"),
179
- ("daemon", "feature", "describe"),
180
- ("diagnostics", "describe"),
181
- ("status", "all", "custom-plan.json"),
182
- ("run", "feature", "--unknown-option"),
183
- ("run", "feature", "F-001", "plan.json", "extra"),
184
- ("daemon", "feature", "status", "extra"),
185
- ],
186
- )
187
- def test_removed_or_invalid_forms_fail_in_parser_without_runtime_dispatch(monkeypatch, args):
188
- from prizmkit_runtime import cli as runtime_cli
189
-
190
- dispatched = []
191
- monkeypatch.setattr(runtime_cli, "ensure_supported_python", lambda: None)
192
- monkeypatch.setattr(runtime_cli, "_dispatch", lambda parsed: dispatched.append(parsed))
193
-
194
- with pytest.raises(SystemExit) as exc_info:
195
- runtime_cli.main(list(args))
196
-
197
- assert exc_info.value.code == 2
198
- assert dispatched == []
199
-
200
-
201
- def test_python_version_guard_mentions_required_version():
202
- from prizmkit_runtime.compat import UnsupportedPythonVersion, ensure_supported_python
203
-
204
- ensure_supported_python((3, 10, 0))
205
- ensure_supported_python((3, 11, 1))
206
-
207
- with pytest.raises(UnsupportedPythonVersion) as exc_info:
208
- ensure_supported_python((3, 9, 18))
209
-
210
- assert "Python 3.10+" in str(exc_info.value)
211
- assert "detected Python 3.9" in str(exc_info.value)
212
-
213
-
214
- def test_runtime_paths_support_framework_source_layout():
215
- from prizmkit_runtime.paths import RuntimePaths, resolve_runtime_paths
216
-
217
- paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT)
218
-
219
- assert isinstance(paths, RuntimePaths)
220
- assert paths.layout == "framework-source"
221
- assert paths.pipeline_root == PIPELINE_ROOT.resolve()
222
- assert paths.project_root == REPO_ROOT.resolve()
223
- assert paths.prizmkit_dir == REPO_ROOT / ".prizmkit"
224
- assert paths.feature_plan == paths.plans_dir / "feature-list.json"
225
- assert paths.bugfix_plan == paths.plans_dir / "bug-fix-list.json"
226
- assert paths.feature_state_dir == paths.state_dir / "features"
227
- assert paths.specs_dir == paths.prizmkit_dir / "specs"
228
- assert not hasattr(paths, "recovery_state_dir")
229
- assert all(isinstance(value, Path) for value in paths.path_values())
230
-
231
-
232
- def test_runtime_paths_support_installed_layout(tmp_path):
233
- from prizmkit_runtime.paths import resolve_runtime_paths
234
-
235
- installed_pipeline = tmp_path / "project" / ".prizmkit" / "dev-pipeline"
236
- installed_pipeline.mkdir(parents=True)
237
-
238
- paths = resolve_runtime_paths(pipeline_root=installed_pipeline)
239
-
240
- assert paths.layout == "installed"
241
- assert paths.project_root == tmp_path / "project"
242
- assert paths.prizmkit_dir == tmp_path / "project" / ".prizmkit"
243
- assert paths.pipeline_root == installed_pipeline.resolve()
244
- assert paths.logs_dir == paths.state_dir / "logs"
245
-
246
-
247
- def test_runtime_diagnostics_leave_historical_recovery_state_untouched(tmp_path):
248
- project = tmp_path / "project"
249
- historical = project / ".prizmkit" / "state" / "recovery" / "historical-session"
250
- historical.mkdir(parents=True)
251
- marker = historical / "marker.json"
252
- marker.write_bytes(b'{"preserve": true}\n')
253
- before = {path.relative_to(project).as_posix(): path.read_bytes() for path in historical.rglob("*") if path.is_file()}
254
-
255
- result = run_cli("--project-root", str(project), "diagnostics", "paths")
256
-
257
- after = {path.relative_to(project).as_posix(): path.read_bytes() for path in historical.rglob("*") if path.is_file()}
258
- assert result.returncode == 0
259
- assert before == after
260
- assert marker.is_file()
261
-
262
-
263
- def test_runtime_config_models_environment_and_ai_resolution():
264
- from prizmkit_runtime.config import AIClientResolution, RuntimeEnvironment, load_runtime_config
265
- from prizmkit_runtime.paths import resolve_runtime_paths
266
-
267
- paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT)
268
- config = load_runtime_config(
269
- paths,
270
- env={
271
- "AI_CLI": "claude",
272
- "PRIZMKIT_PLATFORM": "codex",
273
- "MODEL": "claude-sonnet-4.6",
274
- "PRIZMKIT_EFFORT": "full",
275
- "MAX_RETRIES": "5",
276
- "PATH": "/usr/bin:/bin",
277
- },
278
- )
279
-
280
- assert config.max_retries == 5
281
- assert config.model == "claude-sonnet-4.6"
282
- assert config.effort == "full"
283
- assert isinstance(config.environment, RuntimeEnvironment)
284
- assert isinstance(config.ai_client, AIClientResolution)
285
- assert config.ai_client.command == "claude"
286
- assert config.ai_client.platform == "claude"
287
- assert config.ai_client.source == "environment:AI_CLI"
288
- assert "AI_CLI" in config.ai_client.precedence
289
- assert ".prizmkit/config.json:ai_cli" in config.ai_client.precedence
290
- assert config.runtime_mode == "python-runtime-canonical"
291
-
292
-
293
- def test_runtime_config_matches_canonical_ai_cli_precedence(tmp_path):
294
- from prizmkit_runtime.config import load_runtime_config
295
- from prizmkit_runtime.paths import resolve_runtime_paths
296
-
297
- project = tmp_path / "project"
298
- pipeline = project / ".prizmkit" / "dev-pipeline"
299
- pipeline.mkdir(parents=True)
300
- prizmkit_dir = project / ".prizmkit"
301
- (prizmkit_dir / "config.json").write_text(json.dumps({"ai_cli": "cbc", "platform": "claude"}), encoding="utf-8")
302
- (prizmkit_dir / "manifest.json").write_text(json.dumps({"platform": "codex"}), encoding="utf-8")
303
- paths = resolve_runtime_paths(pipeline_root=pipeline)
304
-
305
- config_cli = load_runtime_config(paths, env={"PATH": ""}).ai_client
306
- assert config_cli.command == "cbc"
307
- assert config_cli.platform == "codebuddy"
308
- assert config_cli.source == "prizmkit-config:ai_cli"
309
-
310
- (prizmkit_dir / "config.json").write_text(json.dumps({"platform": "claude"}), encoding="utf-8")
311
- manifest_platform = load_runtime_config(paths, env={"PATH": ""}).ai_client
312
- assert manifest_platform.command is None
313
- assert manifest_platform.platform == "codex"
314
- assert manifest_platform.source == "unresolved:prizmkit-manifest:platform"
315
- assert "codex" in manifest_platform.notes[0]
316
-
317
- (prizmkit_dir / "manifest.json").unlink()
318
- (prizmkit_dir / "config.json").write_text("{}", encoding="utf-8")
319
- legacy_alias = load_runtime_config(paths, env={"CODEBUDDY_CLI": "custom-cbc", "PATH": ""}).ai_client
320
- assert legacy_alias.command == "custom-cbc"
321
- assert legacy_alias.platform == "codebuddy"
322
- assert legacy_alias.source == "environment:CODEBUDDY_CLI"
323
-
324
-
325
- def test_runtime_config_resolves_comma_separated_manifest_platform(tmp_path, monkeypatch):
326
- import prizmkit_runtime.config as runtime_config
327
- from prizmkit_runtime.config import resolve_ai_client
328
- from prizmkit_runtime.paths import resolve_runtime_paths
329
-
330
- project = tmp_path / "project"
331
- pipeline = project / ".prizmkit" / "dev-pipeline"
332
- pipeline.mkdir(parents=True)
333
- (project / ".prizmkit" / "manifest.json").write_text(
334
- json.dumps({"platform": "claude,cursor"}), encoding="utf-8"
335
- )
336
- paths = resolve_runtime_paths(pipeline_root=pipeline)
337
- monkeypatch.setattr(
338
- runtime_config.shutil,
339
- "which",
340
- lambda name, path=None: "/tools/claude" if name == "claude" else None,
341
- )
342
-
343
- resolved = resolve_ai_client(paths, env={"PATH": "/tools"})
344
- assert resolved.command == "claude"
345
- assert resolved.platform == "claude"
346
- assert resolved.source == "prizmkit-manifest:platform"
347
-
348
-
349
- def test_runtime_config_rejects_legacy_both_manifest_without_path_fallback(tmp_path, monkeypatch):
350
- import prizmkit_runtime.config as runtime_config
351
- from prizmkit_runtime.config import resolve_ai_client
352
- from prizmkit_runtime.paths import resolve_runtime_paths
353
-
354
- project = tmp_path / "project"
355
- pipeline = project / ".prizmkit" / "dev-pipeline"
356
- pipeline.mkdir(parents=True)
357
- (project / ".prizmkit" / "manifest.json").write_text(
358
- json.dumps({"platform": "both"}), encoding="utf-8"
359
- )
360
- paths = resolve_runtime_paths(pipeline_root=pipeline)
361
- monkeypatch.setattr(
362
- runtime_config.shutil,
363
- "which",
364
- lambda name, path=None: "/tools/claude" if name == "claude" else None,
365
- )
366
-
367
- rejected = resolve_ai_client(paths, env={"PATH": "/tools"})
368
- assert rejected.command is None
369
- assert rejected.source == "unresolved:prizmkit-manifest:platform"
370
- assert "both" in rejected.notes[0]
371
-
372
-
373
- def test_runtime_config_resolves_custom_ai_cli_launch_profile(tmp_path):
374
- from prizmkit_runtime.config import RuntimeConfigError, load_runtime_config
375
- from prizmkit_runtime.paths import resolve_runtime_paths
376
-
377
- project = tmp_path / "project"
378
- pipeline = project / ".prizmkit" / "dev-pipeline"
379
- pipeline.mkdir(parents=True)
380
- prizmkit_dir = project / ".prizmkit"
381
- (prizmkit_dir / "config.json").write_text(
382
- json.dumps(
383
- {
384
- "ai_cli": "tclaude",
385
- "ai_cli_launch": {
386
- "profile": "custom",
387
- "prompt_arg": "-i",
388
- "extra_args": ["--verbose", "--path", "two words"],
389
- },
390
- }
391
- ),
392
- encoding="utf-8",
393
- )
394
- paths = resolve_runtime_paths(pipeline_root=pipeline)
395
-
396
- config = load_runtime_config(paths, env={"PATH": ""})
397
-
398
- assert config.ai_client.command == "tclaude"
399
- assert config.ai_client.platform == "custom"
400
- assert config.ai_client.source == "prizmkit-config:ai_cli_launch"
401
- assert config.ai_client.launch_profile is not None
402
- assert config.ai_client.launch_profile.prompt_arg == "-i"
403
- assert config.ai_client.launch_profile.extra_args == ("--verbose", "--path", "two words")
404
-
405
- (prizmkit_dir / "config.json").write_text(json.dumps({"ai_cli": "tclaude"}), encoding="utf-8")
406
- with pytest.raises(RuntimeConfigError, match="prompt injection argument"):
407
- load_runtime_config(paths, env={"PATH": ""})
408
-
409
-
410
- (prizmkit_dir / "config.json").write_text(
411
- json.dumps(
412
- {
413
- "ai_cli": "claude",
414
- "ai_cli_launch": {"profile": "custom", "prompt_arg": "-i", "extra_args": ["--stale"]},
415
- }
416
- ),
417
- encoding="utf-8",
418
- )
419
- built_in = load_runtime_config(paths, env={"PATH": ""}).ai_client
420
- assert built_in.command == "claude"
421
- assert built_in.platform == "claude"
422
- assert built_in.source == "prizmkit-config:ai_cli"
423
- assert built_in.launch_profile is None
424
-
425
- (prizmkit_dir / "config.json").write_text(
426
- json.dumps({"ai_cli": "tclaude", "ai_cli_launch": {"prompt_arg": "-i"}}),
427
- encoding="utf-8",
428
- )
429
- with pytest.raises(RuntimeConfigError, match="profile"):
430
- load_runtime_config(paths, env={"PATH": ""})
431
-
432
-
433
- env_override = load_runtime_config(paths, env={"AI_CLI": "claude", "PATH": ""}).ai_client
434
- assert env_override.command == "claude"
435
- assert env_override.platform == "claude"
436
- assert env_override.source == "environment:AI_CLI"
437
- assert env_override.launch_profile is None
438
-
439
-
440
- def test_runtime_config_supplied_env_does_not_leak_ambient_path(tmp_path):
441
- from prizmkit_runtime.config import load_runtime_config
442
- from prizmkit_runtime.paths import resolve_runtime_paths
443
-
444
- isolated_pipeline = tmp_path / "project" / ".prizmkit" / "dev-pipeline"
445
- isolated_pipeline.mkdir(parents=True)
446
- paths = resolve_runtime_paths(pipeline_root=isolated_pipeline)
447
- config = load_runtime_config(paths, env={})
448
-
449
- assert config.environment.path_entries == ()
450
- assert config.ai_client.command is None
451
- assert config.ai_client.source == "unresolved"
452
-
453
-
454
- def test_runtime_command_registry_contains_only_executing_operation_first_entries():
455
- from prizmkit_runtime.commands import find_runtime_command, list_runtime_commands
456
-
457
- command_keys = {command.key for command in list_runtime_commands()}
458
- expected = {
459
- *(('run', family, 'run') for family in ('feature', 'bugfix')),
460
- *(('status', family, 'status') for family in ('feature', 'bugfix', 'all')),
461
- *(('reset', family, 'reset') for family in ('feature', 'bugfix')),
462
- *(('daemon', family, action)
463
- for family in ('feature', 'bugfix')
464
- for action in ('start', 'stop', 'status', 'logs', 'restart')),
465
- *(('diagnostics', None, action)
466
- for action in ('paths', 'entrypoints', 'version', 'ai-cli')),
467
- ('helper', None, 'run'),
468
- }
469
-
470
- assert command_keys == expected
471
- assert all(command.current_entrypoint for command in list_runtime_commands())
472
- assert all(command.action != "describe" for command in list_runtime_commands())
473
- assert all(command.group not in {"feature", "bugfix", "recovery"} for command in list_runtime_commands())
474
- for removed in [
475
- ("feature", "run", None),
476
- ("feature", "test-cli", None),
477
- ("reset", "describe", None),
478
- ("daemon", "describe", "feature"),
479
- ("recovery", "detect", None),
480
- ]:
481
- with pytest.raises(KeyError, match="Unknown runtime command"):
482
- find_runtime_command(removed[0], removed[1], removed[2])
483
-
484
-
485
- def test_removed_describe_commands_are_rejected():
486
- for args in [
487
- ("feature", "describe"),
488
- ("reset", "describe"),
489
- ("daemon", "feature", "describe"),
490
- ("diagnostics", "describe"),
491
- ]:
492
- result = run_cli(*args)
493
- assert result.returncode == 2
494
- assert "invalid choice" in result.stderr
495
- assert "Python runtime command contract" not in result.stdout
496
-
497
-
498
- def test_operation_first_runtime_arguments_are_validated_then_forwarded_exactly(monkeypatch):
499
- from prizmkit_runtime import cli as runtime_cli
500
-
501
- captured = []
502
-
503
- def fake_handle(group, action, *, target=None, paths=None, legacy_args=()):
504
- captured.append((group, action, target, legacy_args))
505
- return runtime_cli.CommandResult(0, "ok", "ok")
506
-
507
- monkeypatch.setattr(runtime_cli, "ensure_supported_python", lambda: None)
508
- monkeypatch.setattr(runtime_cli, "handle_runtime_command", fake_handle)
509
-
510
- run_args = [
511
- "run", "feature", "F-001", "custom.json", "--features", "F-001:F-005",
512
- "--max-retries", "5", "--max-infra-retries", "4",
513
- "--resume-phase", "6", "--dry-run",
514
- ]
515
- assert runtime_cli.main(run_args) == 0
516
- assert captured[-1] == ("run", "run", "feature", tuple(run_args[2:]))
517
-
518
- assert runtime_cli.main(["status", "bugfix", "bugs.json"]) == 0
519
- assert captured[-1] == ("status", "status", "bugfix", ("bugs.json",))
520
-
521
- assert runtime_cli.main(["daemon", "feature", "start"]) == 0
522
- assert captured[-1] == ("daemon", "start", "feature", ())
523
-
524
- assert runtime_cli.main(["daemon", "feature", "logs", "--follow"]) == 0
525
- assert captured[-1] == ("daemon", "logs", "feature", ("--follow",))
526
-
527
- assert runtime_cli.main(["reset", "feature", "--failed", "--preserve-runtime"]) == 0
528
- assert captured[-1] == ("reset", "reset", "feature", ("--failed", "--preserve-runtime"))
529
-
530
- interspersed_reset = ["reset", "feature", "F-001", "--fresh-checkout", "custom.json"]
531
- assert runtime_cli.main(interspersed_reset) == 0
532
- assert captured[-1] == (
533
- "reset", "reset", "feature", ("F-001", "--fresh-checkout", "custom.json")
534
- )
535
-
536
- interspersed_daemon = ["daemon", "feature", "start", "custom.json"]
537
- assert runtime_cli.main(interspersed_daemon) == 0
538
- assert captured[-1] == (
539
- "daemon", "start", "feature", ("custom.json",)
540
- )
541
-
542
- assert runtime_cli.main(["--project-root", "feature", "run", "feature", "--dry-run"]) == 0
543
- assert captured[-1] == ("run", "run", "feature", ("--dry-run",))
544
-
545
-
546
- def test_pipeline_mode_option_is_rejected():
547
- foreground = run_cli("run", "feature", "--mode", "full")
548
- daemon = run_cli("daemon", "feature", "start", "--mode", "full")
549
-
550
- assert foreground.returncode == 2
551
- assert daemon.returncode == 2
552
- assert "unrecognized arguments" in foreground.stderr
553
- assert "unrecognized arguments" in daemon.stderr
554
-
555
-
556
- @pytest.mark.parametrize(
557
- ("family", "task_id", "extra_args"),
558
- [
559
- ("feature", "F-007", ("--features", "F-007", "--dry-run")),
560
- ("bugfix", "B-007", ("--max-retries", "4")),
561
- ],
562
- )
563
- def test_run_family_dispatch_preserves_each_family_argument_tail(
564
- monkeypatch, family, task_id, extra_args
565
- ):
566
- from prizmkit_runtime import cli as runtime_cli
567
-
568
- captured = []
569
- monkeypatch.setattr(runtime_cli, "ensure_supported_python", lambda: None)
570
- monkeypatch.setattr(
571
- runtime_cli,
572
- "handle_runtime_command",
573
- lambda group, action, **kwargs: captured.append(
574
- (group, action, kwargs["target"], kwargs["legacy_args"])
575
- ) or runtime_cli.CommandResult(0, "ok", "ok"),
576
- )
577
- argv = ["run", family, task_id, *extra_args]
578
-
579
- assert runtime_cli.main(argv) == 0
580
- assert captured == [("run", "run", family, (task_id, *extra_args))]
581
-
582
-
583
- @pytest.mark.parametrize("family", ("feature", "bugfix"))
584
- @pytest.mark.parametrize("legacy_action", ("reset", "un" + "skip"))
585
- def test_family_level_reset_aliases_are_not_public_commands(family, legacy_action):
586
- result = run_cli(family, legacy_action)
587
-
588
- assert result.returncode == 2
589
- assert "invalid choice" in result.stderr
590
-
591
-
592
- def test_diagnostics_ai_cli_reports_family_neutral_resolution(monkeypatch):
593
- from prizmkit_runtime import config
594
- from prizmkit_runtime.commands import handle_diagnostics
595
- from prizmkit_runtime.paths import resolve_runtime_paths
596
-
597
- class FakeAIClient:
598
- command = "claude"
599
- platform = "claude"
600
- source = "test"
601
- notes = ("configured globally",)
602
-
603
- class FakeConfig:
604
- ai_client = FakeAIClient()
605
- runtime_mode = "python-runtime-canonical"
606
- model = "claude-sonnet-4.6"
607
-
608
- monkeypatch.setattr(config, "load_runtime_config", lambda paths: FakeConfig())
609
- paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT)
610
-
611
- result = handle_diagnostics("ai-cli", paths)
612
- rendered = result.render()
613
-
614
- assert result.exit_code == 0
615
- assert result.title == "Python runtime AI CLI diagnostics"
616
- assert "detected_cli: claude" in rendered
617
- assert "platform: claude" in rendered
618
- assert "source: test" in rendered
619
- assert "runtime_mode: python-runtime-canonical" in rendered
620
- assert "model: claude-sonnet-4.6" in rendered
621
- assert "note: configured globally" in rendered
622
- assert "feature" not in result.title.lower()
623
-
624
-
625
- def test_diagnostics_help_exposes_only_real_diagnostic_actions():
626
- result = run_cli("diagnostics", "--help")
627
-
628
- assert result.returncode == 0
629
- for action in ("paths", "entrypoints", "version", "ai-cli"):
630
- assert action in result.stdout
631
- assert "describe" not in result.stdout
632
- assert "commands" not in result.stdout
633
- assert "test-cli" not in result.stdout
634
-
635
-
636
- def test_diagnostics_paths_and_entrypoints_are_standard_library_cli_actions():
637
- paths_result = run_cli("diagnostics", "paths")
638
- entrypoints_result = run_cli("diagnostics", "entrypoints")
639
-
640
- assert paths_result.returncode == 0
641
- assert "Runtime path diagnostics" in paths_result.stdout
642
- assert "pipeline_root:" in paths_result.stdout
643
- assert entrypoints_result.returncode == 0
644
- assert "Python runtime entrypoint inventory" in entrypoints_result.stdout
645
- assert "runtime:cli:" in entrypoints_result.stdout
646
- assert "command:run:feature: python3 dev-pipeline/cli.py run feature" in entrypoints_result.stdout
647
- assert "command:status:all: python3 dev-pipeline/cli.py status all" in entrypoints_result.stdout
648
- assert "command:diagnostics:ai-cli:" in entrypoints_result.stdout
649
- assert " describe" not in entrypoints_result.stdout
650
- assert "test-cli" not in entrypoints_result.stdout
651
- assert "run-feature.sh" not in entrypoints_result.stdout
652
- assert "generate-bootstrap-prompt.py" in entrypoints_result.stdout
653
- assert "generate-recovery-prompt.py" not in entrypoints_result.stdout
654
-
655
-
656
- def _write_family_status_plan(paths, family, task_id):
657
- plan_path, key = {
658
- "feature": (paths.feature_plan, "features"),
659
- "bugfix": (paths.bugfix_plan, "bugs"),
660
- }[family]
661
- plan_path.parent.mkdir(parents=True, exist_ok=True)
662
- plan_path.write_text(json.dumps({key: [{"id": task_id, "status": "pending"}]}), encoding="utf-8")
663
- return plan_path
664
-
665
-
666
- def _write_family_runtime_status(paths, family, task_id):
667
- state_dir = {
668
- "feature": paths.feature_state_dir,
669
- "bugfix": paths.bugfix_state_dir,
670
- }[family]
671
- status_path = state_dir / task_id / "status.json"
672
- status_path.parent.mkdir(parents=True, exist_ok=True)
673
- status_path.write_text(
674
- json.dumps(
675
- {
676
- {
677
- "feature": "feature_id",
678
- "bugfix": "bug_id",
679
- }[family]: task_id,
680
- "retry_count": 0,
681
- "sessions": [],
682
- "resume_from_phase": 9,
683
- }
684
- ),
685
- encoding="utf-8",
686
- )
687
- return status_path
688
-
689
-
690
- def _file_bytes_under(root):
691
- if not root.exists():
692
- return {}
693
- return {
694
- path.relative_to(root).as_posix(): path.read_bytes()
695
- for path in root.rglob("*")
696
- if path.is_file()
697
- }
698
-
699
-
700
- def test_status_all_aggregates_configured_families_in_fixed_order_and_missing_is_nonfatal(
701
- tmp_path, monkeypatch
702
- ):
703
- from prizmkit_runtime import runners
704
- from prizmkit_runtime.commands import CommandResult, handle_runtime_command
705
- from prizmkit_runtime.paths import resolve_runtime_paths
706
-
707
- paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path)
708
- _write_family_status_plan(paths, "feature", "F-001")
709
- before = _file_bytes_under(tmp_path)
710
- calls = []
711
-
712
- def fake_status(family, action, legacy_args, runtime_paths):
713
- calls.append((family, action, legacy_args, runtime_paths))
714
- return CommandResult(0, f"Python {family} status", f"normal {family} status")
715
-
716
- monkeypatch.setattr(runners, "run_pipeline_command", fake_status)
717
- result = handle_runtime_command("status", "status", target="all", paths=paths)
718
- rendered = result.render()
719
-
720
- assert result.exit_code == 0
721
- assert rendered.index("FEATURE\n=======") < rendered.index("BUGFIX\n======")
722
- assert "normal feature status" in rendered
723
- assert "BUGFIX\n======\nnot configured: plan list not found" in rendered
724
- assert [(family, action, args) for family, action, args, _paths in calls] == [
725
- ("feature", "status", ()),
726
- ]
727
- assert _file_bytes_under(tmp_path) == before
728
- assert not paths.feature_state_dir.exists()
729
- assert not paths.bugfix_state_dir.exists()
730
-
731
-
732
- def test_status_all_uses_real_family_status_handlers_without_filesystem_mutation(tmp_path):
733
- from prizmkit_runtime.paths import resolve_runtime_paths
734
-
735
- paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path)
736
- configured = {
737
- "feature": "F-001",
738
- "bugfix": "B-001",
739
- }
740
- for family, task_id in configured.items():
741
- _write_family_status_plan(paths, family, task_id)
742
- _write_family_runtime_status(paths, family, task_id)
743
- before = _file_bytes_under(tmp_path)
744
-
745
- result = run_cli("--project-root", str(tmp_path), "status", "all")
746
-
747
- assert result.returncode == 0, result.stderr
748
- assert "FEATURE\n=======" in result.stdout
749
- assert "Python feature status" in result.stdout
750
- assert "BUGFIX\n======" in result.stdout
751
- assert "Python bugfix status" in result.stdout
752
- assert _file_bytes_under(tmp_path) == before
753
-
754
-
755
- def test_status_all_reports_plan_and_handler_errors_but_renders_unaffected_sections(
756
- tmp_path, monkeypatch
757
- ):
758
- from prizmkit_runtime import runners
759
- from prizmkit_runtime.commands import CommandResult, handle_runtime_command
760
- from prizmkit_runtime.paths import resolve_runtime_paths
761
-
762
- paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path / "malformed-plan")
763
- _write_family_status_plan(paths, "feature", "F-001")
764
- paths.bugfix_plan.parent.mkdir(parents=True, exist_ok=True)
765
- paths.bugfix_plan.write_text("{malformed", encoding="utf-8")
766
-
767
- def fake_status(family, action, legacy_args, runtime_paths):
768
- assert action == "status"
769
- return CommandResult(0, f"Python {family} status", f"normal {family} status")
770
-
771
- monkeypatch.setattr(runners, "run_pipeline_command", fake_status)
772
- result = handle_runtime_command("status", "status", target="all", paths=paths)
773
- rendered = result.render()
774
-
775
- assert result.exit_code != 0
776
- assert "FEATURE\n=======\nPython feature status\nnormal feature status" in rendered
777
- assert "BUGFIX\n======\nerror: malformed plan list:" in rendered
778
-
779
- handler_paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path / "handler-error")
780
- _write_family_status_plan(handler_paths, "feature", "F-001")
781
- _write_family_status_plan(handler_paths, "bugfix", "B-001")
782
-
783
- def fake_status_exploding(family, action, legacy_args, runtime_paths):
784
- assert action == "status"
785
- if family == "bugfix":
786
- raise RuntimeError("family handler exploded")
787
- return CommandResult(0, f"Python {family} status", f"normal {family} status")
788
-
789
- monkeypatch.setattr(runners, "run_pipeline_command", fake_status_exploding)
790
- handler_result = handle_runtime_command("status", "status", target="all", paths=handler_paths)
791
- handler_rendered = handler_result.render()
792
-
793
- assert handler_result.exit_code != 0
794
- assert "FEATURE\n=======\nPython feature status\nnormal feature status" in handler_rendered
795
- assert "BUGFIX\n======\nerror: family handler exploded" in handler_rendered
796
-
797
-
798
- def test_status_all_reports_malformed_runtime_unparseable_and_nonzero_results(
799
- tmp_path, monkeypatch
800
- ):
801
- from prizmkit_runtime import runners
802
- from prizmkit_runtime.commands import CommandResult, handle_runtime_command
803
- from prizmkit_runtime.paths import resolve_runtime_paths
804
-
805
- paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path / "malformed-unparseable")
806
- _write_family_status_plan(paths, "feature", "F-001")
807
- _write_family_status_plan(paths, "bugfix", "B-001")
808
- malformed_state = paths.feature_state_dir / "F-001" / "status.json"
809
- malformed_state.parent.mkdir(parents=True, exist_ok=True)
810
- malformed_state.write_text("not-json", encoding="utf-8")
811
-
812
- def fake_status(family, action, legacy_args, runtime_paths):
813
- if family == "bugfix":
814
- return object()
815
- return CommandResult(0, f"Python {family} status", "status output")
816
-
817
- monkeypatch.setattr(runners, "run_pipeline_command", fake_status)
818
- result = handle_runtime_command("status", "status", target="all", paths=paths)
819
- rendered = result.render()
820
-
821
- assert result.exit_code != 0
822
- assert "FEATURE\n=======\nerror: malformed runtime state F-001/status.json" in rendered
823
- assert "BUGFIX\n======\nerror: unparseable configured family result" in rendered
824
-
825
- nonzero_paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path / "nonzero")
826
- _write_family_status_plan(nonzero_paths, "feature", "F-001")
827
- _write_family_status_plan(nonzero_paths, "bugfix", "B-001")
828
-
829
- def fake_status_nonzero(family, action, legacy_args, runtime_paths):
830
- return CommandResult(7 if family == "bugfix" else 0, f"Python {family} status", "status output")
831
-
832
- monkeypatch.setattr(runners, "run_pipeline_command", fake_status_nonzero)
833
- nonzero_result = handle_runtime_command("status", "status", target="all", paths=nonzero_paths)
834
- nonzero_rendered = nonzero_result.render()
835
-
836
- assert nonzero_result.exit_code != 0
837
- assert "FEATURE\n=======\nPython feature status\nstatus output" in nonzero_rendered
838
- assert "BUGFIX\n======\nerror: Python bugfix status\nstatus output" in nonzero_rendered
839
-
840
-
841
- def test_status_all_direct_api_rejects_family_specific_arguments_without_calling_handlers(
842
- tmp_path, monkeypatch
843
- ):
844
- from prizmkit_runtime import runners
845
- from prizmkit_runtime.commands import handle_runtime_command
846
- from prizmkit_runtime.paths import resolve_runtime_paths
847
-
848
- paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT, project_root=tmp_path)
849
- called = []
850
- monkeypatch.setattr(runners, "run_pipeline_command", lambda *args: called.append(args))
851
-
852
- result = handle_runtime_command(
853
- "status", "status", target="all", paths=paths, legacy_args=("custom.json",)
854
- )
855
-
856
- assert result.exit_code == 2
857
- assert "does not accept a plan path" in result.render()
858
- assert called == []
859
-
860
-
861
- def test_interoperability_preserves_existing_utility_mapping():
862
- from prizmkit_runtime.interoperability import (
863
- UTILITY_ENTRYPOINTS,
864
- UTILITY_LIBRARY_ONLY,
865
- describe_existing_entrypoint,
866
- )
867
- from prizmkit_runtime.paths import resolve_runtime_paths
868
-
869
- paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT)
870
- invocation = describe_existing_entrypoint("utility", "generate-bootstrap-prompt", paths=paths)
871
-
872
- assert invocation.script_path == PIPELINE_ROOT / "scripts" / "generate-bootstrap-prompt.py"
873
- assert invocation.arguments == ()
874
- assert invocation.cwd == paths.project_root
875
-
876
- help_result = subprocess.run(
877
- [sys.executable, str(invocation.script_path), "--help"],
878
- cwd=REPO_ROOT,
879
- text=True,
880
- stdout=subprocess.PIPE,
881
- stderr=subprocess.PIPE,
882
- check=False,
883
- )
884
- assert help_result.returncode == 0
885
- assert "--feature-list" in help_result.stdout
886
-
887
- actual_scripts = {path.name for path in (PIPELINE_ROOT / "scripts").glob("*.py")}
888
- mapped_scripts = {Path(relative_path).name for relative_path in UTILITY_ENTRYPOINTS.values()}
889
- explicitly_library_only = set(UTILITY_LIBRARY_ONLY)
890
-
891
- assert actual_scripts == mapped_scripts | explicitly_library_only
892
- assert explicitly_library_only == {"continuation.py", "prompt_framework.py", "status_common.py", "utils.py"}
893
- assert "parse-stream-progress.py" in mapped_scripts
894
- assert "generate-recovery-prompt" not in UTILITY_ENTRYPOINTS
895
- assert "prizmkit-test-gate.py" not in mapped_scripts
896
-
897
-
898
- def test_obsolete_runtime_recovery_ai_session_sources_are_absent():
899
- assert not (PIPELINE_ROOT / "prizmkit_runtime" / "runner_recovery.py").exists()
900
- assert not (PIPELINE_ROOT / "scripts" / "generate-recovery-prompt.py").exists()
901
-
902
- forbidden_by_source = {
903
- "prizmkit_runtime/cli.py": ('"recovery"',),
904
- "prizmkit_runtime/commands.py": ('"recovery": ("run"', 'group == "recovery"'),
905
- "prizmkit_runtime/runners.py": ("runner_recovery", "run_recovery_command"),
906
- "prizmkit_runtime/paths.py": ("recovery_state_dir",),
907
- "prizmkit_runtime/interoperability.py": ("generate-recovery-prompt",),
908
- }
909
- for relative_path, forbidden_tokens in forbidden_by_source.items():
910
- content = (PIPELINE_ROOT / relative_path).read_text(encoding="utf-8")
911
- for token in forbidden_tokens:
912
- assert token not in content, f"{relative_path} still contains {token}"
913
-
914
-
915
- @pytest.mark.parametrize(
916
- ("path", "ordinary_command"),
917
- [
918
- (REPO_ROOT / "README.md", "python3 ./.prizmkit/dev-pipeline/cli.py run feature F-003"),
919
- (
920
- REPO_ROOT / "core" / "templates" / "project-memory-template.md",
921
- "python3 ./.prizmkit/dev-pipeline/cli.py run <family> <task-id>",
922
- ),
923
- (
924
- REPO_ROOT
925
- / "core"
926
- / "skills"
927
- / "orchestration-skill"
928
- / "workflows"
929
- / "recovery-workflow"
930
- / "SKILL.md",
931
- "python3 ./.prizmkit/dev-pipeline/cli.py run feature F-001",
932
- ),
933
- ],
934
- )
935
- def test_canonical_interrupted_task_guidance_uses_recovery_workflow(path, ordinary_command):
936
- content = path.read_text(encoding="utf-8")
937
-
938
- assert "recovery-workflow" in content
939
- assert ordinary_command in content
940
- assert "cli.py recovery" not in content
941
-
942
-
943
- def test_boundary_dataclasses_are_cohesive_and_frozen():
944
- from prizmkit_runtime.gitops import BranchContext
945
- from prizmkit_runtime.heartbeat import HeartbeatConfig, HeartbeatState
946
- from prizmkit_runtime.paths import resolve_runtime_paths
947
- from prizmkit_runtime.processes import ProcessHandle, ProcessSpec
948
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
949
- from prizmkit_runtime.status import StatusTarget, StatusUpdateRequest, default_status_targets
950
-
951
- paths = resolve_runtime_paths(pipeline_root=PIPELINE_ROOT)
952
- session = AISessionConfig(
953
- cli_command="claude",
954
- platform="claude",
955
- model="claude-sonnet-4.6",
956
- prompt_path=paths.state_dir / "prompt.md",
957
- cwd=paths.project_root,
958
- )
959
- process = ProcessSpec(command=("python3", "-m", "prizmkit_runtime"), cwd=paths.project_root)
960
- handle = ProcessHandle(pid=1234, spec=process, status="described")
961
- heartbeat = HeartbeatConfig(heartbeat_file=paths.state_dir / ".heartbeat")
962
- heartbeat_state = HeartbeatState(last_seen_epoch=1.0, stale=False, details="fresh")
963
- branch = BranchContext(base_branch="main", working_branch="dev/example", project_root=paths.project_root)
964
- targets = default_status_targets(paths)
965
- status_target = StatusTarget(kind="feature", plan_path=paths.feature_plan, state_dir=paths.feature_state_dir)
966
- status_request = StatusUpdateRequest(target=status_target, action="status")
967
-
968
- assert AISessionLauncher(session).describe().startswith("AI session launch boundary")
969
- assert handle.spec == process
970
- assert heartbeat_state.details == "fresh"
971
- assert branch.project_root == paths.project_root
972
- assert targets["feature"].plan_path == paths.feature_plan
973
- assert status_request.target == status_target
974
-
975
- with pytest.raises(FrozenInstanceError):
976
- session.model = "other"
977
- with pytest.raises(FrozenInstanceError):
978
- heartbeat.interval_seconds = 10
979
-
980
-
981
- def test_runtime_config_loads_prizmkit_env_and_validates_effort(tmp_path):
982
- from prizmkit_runtime.config import load_runtime_config, validate_effort
983
- from prizmkit_runtime.paths import resolve_runtime_paths
984
-
985
- project = tmp_path / "project"
986
- pipeline = project / ".prizmkit" / "dev-pipeline"
987
- pipeline.mkdir(parents=True)
988
- prizmkit_dir = project / ".prizmkit"
989
- (prizmkit_dir / ".env").write_text(
990
- "AI_CLI=claude\nPRIZMKIT_EFFORT=max\nMODEL=env-model\n",
991
- encoding="utf-8",
992
- )
993
- paths = resolve_runtime_paths(pipeline_root=pipeline)
994
-
995
- config = load_runtime_config(paths, env={"PATH": ""})
996
-
997
- assert config.ai_client.command == "claude"
998
- assert config.ai_client.platform == "claude"
999
- assert config.ai_client.source == "environment:AI_CLI"
1000
- assert config.model == "env-model"
1001
- assert config.effort_validation.valid is True
1002
- assert validate_effort("max", "codex").valid is False
1003
- assert "Codex" in validate_effort("max", "codex").message
1004
- assert validate_effort("max", "pi").valid is True
1005
- assert validate_effort("minimal", "pi").valid is True
1006
-
1007
-
1008
- def test_runtime_config_resolves_pi_from_config_and_installed_marker(tmp_path):
1009
- from prizmkit_runtime.config import resolve_ai_client
1010
- from prizmkit_runtime.paths import resolve_runtime_paths
1011
-
1012
- project = tmp_path / "project"
1013
- pipeline = project / ".prizmkit" / "dev-pipeline"
1014
- pipeline.mkdir(parents=True)
1015
- (project / ".prizmkit" / "config.json").write_text('{"ai_cli":"pi"}', encoding="utf-8")
1016
- paths = resolve_runtime_paths(pipeline_root=pipeline)
1017
- configured = resolve_ai_client(paths, env={"PATH": ""})
1018
- assert configured.command == "pi"
1019
- assert configured.platform == "pi"
1020
- assert configured.launch_profile is None
1021
-
1022
- (project / ".prizmkit" / "config.json").unlink()
1023
- marker = project / ".pi" / "skills" / "prizmkit"
1024
- marker.mkdir(parents=True)
1025
- (marker / "SKILL.md").write_text("---\nname: prizmkit\ndescription: test\n---\n", encoding="utf-8")
1026
- unresolved = resolve_ai_client(paths, env={"PATH": ""})
1027
- assert unresolved.command is None
1028
-
1029
-
1030
- def test_runtime_config_resolves_and_validates_cursor_agent(tmp_path, monkeypatch):
1031
- import prizmkit_runtime.config as runtime_config
1032
- from prizmkit_runtime.config import resolve_ai_client, validate_effort
1033
- from prizmkit_runtime.paths import resolve_runtime_paths
1034
- from prizmkit_runtime.platform_detection import platform_from_command
1035
-
1036
- assert platform_from_command(r"C:\Tools\agent.exe") == "cursor"
1037
- assert platform_from_command(r"C:\Program Files\Cursor\agent.cmd") == "cursor"
1038
-
1039
- project = tmp_path / "project"
1040
- pipeline = project / ".prizmkit" / "dev-pipeline"
1041
- pipeline.mkdir(parents=True)
1042
- paths = resolve_runtime_paths(pipeline_root=pipeline)
1043
-
1044
- (project / ".prizmkit" / "config.json").write_text('{"ai_cli":"agent"}', encoding="utf-8")
1045
- configured = resolve_ai_client(paths, env={"PATH": ""})
1046
- assert configured.command == "agent"
1047
- assert configured.platform == "cursor"
1048
- assert configured.launch_profile is None
1049
- effort = validate_effort("high", "cursor")
1050
- assert effort.valid is False
1051
- assert effort.supported_values == ()
1052
- assert "no documented effort parameter" in effort.message
1053
-
1054
- (project / ".prizmkit" / "config.json").unlink()
1055
- (project / ".prizmkit" / "manifest.json").write_text('{"platform":"cursor"}', encoding="utf-8")
1056
- monkeypatch.setattr(runtime_config.shutil, "which", lambda name, path=None: "/tools/agent" if name == "agent" else None)
1057
- monkeypatch.setattr(
1058
- runtime_config.subprocess,
1059
- "run",
1060
- lambda *args, **kwargs: subprocess.CompletedProcess(
1061
- args[0], 0, "Cursor Agent\n--print --force --trust --output-format", ""
1062
- ),
1063
- )
1064
- detected = resolve_ai_client(paths, env={"PATH": "/tools"})
1065
- assert detected.command == "agent"
1066
- assert detected.platform == "cursor"
1067
- assert detected.source == "prizmkit-manifest:platform"
1068
-
1069
- monkeypatch.setattr(
1070
- runtime_config.subprocess,
1071
- "run",
1072
- lambda *args, **kwargs: subprocess.CompletedProcess(
1073
- args[0], 1, "Cursor Agent --print --force --trust --output-format", "",
1074
- ),
1075
- )
1076
- rejected_nonzero = resolve_ai_client(paths, env={"PATH": "/tools"})
1077
- assert rejected_nonzero.command is None
1078
-
1079
- monkeypatch.setattr(
1080
- runtime_config.subprocess,
1081
- "run",
1082
- lambda *args, **kwargs: subprocess.CompletedProcess(args[0], 0, "unrelated agent", ""),
1083
- )
1084
- rejected = resolve_ai_client(paths, env={"PATH": "/tools"})
1085
- assert rejected.command is None
1086
- assert rejected.platform == "cursor"
1087
- assert rejected.source == "unresolved:prizmkit-manifest:platform"
1088
-
1089
- # Adding Cursor markers must not displace the established installed-host
1090
- # precedence when legacy metadata is absent.
1091
- (project / ".prizmkit" / "manifest.json").unlink()
1092
- (project / ".claude" / "commands").mkdir(parents=True)
1093
- (project / ".claude" / "commands" / "prizmkit.md").write_text("fixture\n", encoding="utf-8")
1094
- (project / ".cursor" / "skills" / "prizmkit").mkdir(parents=True)
1095
- (project / ".cursor" / "skills" / "prizmkit" / "SKILL.md").write_text("fixture\n", encoding="utf-8")
1096
- monkeypatch.setattr(
1097
- runtime_config.shutil,
1098
- "which",
1099
- lambda name, path=None: f"/tools/{name}" if name in {"claude", "agent"} else None,
1100
- )
1101
- preserved = resolve_ai_client(paths, env={"PATH": "/tools"})
1102
- assert preserved.command == "claude"
1103
- assert preserved.platform == "claude"
1104
- assert preserved.source == "installed-platform:claude"
1105
-
1106
-
1107
- def test_runtime_config_resolves_and_validates_antigravity_agy(tmp_path, monkeypatch):
1108
- import prizmkit_runtime.config as runtime_config
1109
- from prizmkit_runtime.config import resolve_ai_client, validate_effort
1110
- from prizmkit_runtime.paths import resolve_runtime_paths
1111
- from prizmkit_runtime.platform_detection import platform_from_command
1112
-
1113
- assert platform_from_command("agy") == "antigravity"
1114
- assert platform_from_command("antigravity") == "antigravity"
1115
- assert platform_from_command(r"C:\Tools\agy.exe") == "antigravity"
1116
-
1117
- project = tmp_path / "agy-project"
1118
- pipeline = project / ".prizmkit" / "dev-pipeline"
1119
- pipeline.mkdir(parents=True)
1120
- paths = resolve_runtime_paths(pipeline_root=pipeline)
1121
-
1122
- (project / ".prizmkit" / "config.json").write_text('{"ai_cli":"agy"}', encoding="utf-8")
1123
- configured = resolve_ai_client(paths, env={"PATH": ""})
1124
- assert configured.command == "agy"
1125
- assert configured.platform == "antigravity"
1126
- assert configured.launch_profile is None
1127
-
1128
- for valid_level in ("low", "medium", "high", "xhigh", "max"):
1129
- assert validate_effort(valid_level, "antigravity").valid is True
1130
- invalid_effort = validate_effort("off", "antigravity")
1131
- assert invalid_effort.valid is False
1132
- assert invalid_effort.supported_values == ("low", "medium", "high", "xhigh", "max")
1133
- assert "Antigravity" in invalid_effort.message
1134
-
1135
- (project / ".prizmkit" / "config.json").unlink()
1136
- (project / ".prizmkit" / "manifest.json").write_text('{"platform":"antigravity"}', encoding="utf-8")
1137
- monkeypatch.setattr(
1138
- runtime_config.shutil,
1139
- "which",
1140
- lambda name, path=None: "/tools/agy" if name == "agy" else None,
1141
- )
1142
- from_manifest = resolve_ai_client(paths, env={"PATH": "/tools"})
1143
- assert from_manifest.command == "agy"
1144
- assert from_manifest.platform == "antigravity"
1145
- assert from_manifest.source == "prizmkit-manifest:platform"
1146
-
1147
- (project / ".prizmkit" / "manifest.json").unlink()
1148
- plugin_skill = project / ".agents" / "plugins" / "prizmkit" / "skills" / "prizmkit" / "SKILL.md"
1149
- plugin_skill.parent.mkdir(parents=True)
1150
- plugin_skill.write_text("fixture\n", encoding="utf-8")
1151
- from_marker = resolve_ai_client(paths, env={"PATH": "/tools"})
1152
- assert from_marker.command == "agy"
1153
- assert from_marker.platform == "antigravity"
1154
- assert from_marker.source == "installed-platform:antigravity"
1155
-
1156
- plugin_skill.unlink()
1157
- from_path = resolve_ai_client(paths, env={"PATH": "/tools"})
1158
- assert from_path.command == "agy"
1159
- assert from_path.platform == "antigravity"
1160
- assert from_path.source == "PATH:agy"
1161
-
1162
-
1163
- def test_stream_json_support_detection_matches_provider_rules(monkeypatch):
1164
- import prizmkit_runtime.sessions as sessions
1165
- from prizmkit_runtime.sessions import detect_stream_json_support
1166
-
1167
- def help_runner(command):
1168
- if tuple(command) == ("codex", "exec", "--help"):
1169
- return "Usage: codex exec --json"
1170
- if tuple(command) == ("claude", "--help"):
1171
- return "--output-format stream-json"
1172
- if tuple(command) == ("pi", "--help"):
1173
- return "--mode --approve --no-session --tools --model --thinking"
1174
- if tuple(command) == ("agent", "--version"):
1175
- return "Cursor Agent 2026.1"
1176
- if tuple(command) == ("agent", "--help"):
1177
- return "Cursor Agent --print --force --trust --output-format stream-json"
1178
- if tuple(command) == ("agy", "--help"):
1179
- return "agy --print --dangerously-skip-permissions --input-format --output-format stream-json"
1180
- return ""
1181
-
1182
- codebuddy = detect_stream_json_support("cbc", "codebuddy", help_runner)
1183
- codex = detect_stream_json_support("codex", "codex", help_runner)
1184
- claude = detect_stream_json_support("claude", "claude", help_runner)
1185
- pi = detect_stream_json_support("pi", "pi", help_runner)
1186
- cursor = detect_stream_json_support("agent", "cursor", help_runner)
1187
- antigravity = detect_stream_json_support("agy", "antigravity", help_runner)
1188
- unsupported = detect_stream_json_support("other", "claude", lambda _cmd: "plain help")
1189
-
1190
- assert codebuddy.enabled and codebuddy.format == "stream-json"
1191
- assert codex.enabled and codex.format == "codex-json"
1192
- assert claude.enabled and claude.format == "stream-json"
1193
- assert pi.enabled and pi.format == "pi-json"
1194
- assert cursor.enabled and cursor.format == "cursor-stream-json"
1195
- assert antigravity.enabled and antigravity.format == "antigravity-stream-json"
1196
- assert detect_stream_json_support("agy", "antigravity", lambda _cmd: "--print").enabled is False
1197
- assert detect_stream_json_support("agent", "cursor", lambda _cmd: "unrelated --output-format").enabled is False
1198
- monkeypatch.setattr(
1199
- sessions.subprocess,
1200
- "run",
1201
- lambda *args, **kwargs: subprocess.CompletedProcess(
1202
- args[0], 1, "Cursor Agent --print --force --trust --output-format", "",
1203
- ),
1204
- )
1205
- assert detect_stream_json_support("agent", "cursor").enabled is False
1206
- assert detect_stream_json_support("pi", "pi", lambda _cmd: "--mode").enabled is False
1207
- assert unsupported.enabled is False
1208
-
1209
-
1210
- def test_ai_session_command_builders_match_unix_runtime_snapshot(tmp_path):
1211
- from prizmkit_runtime.sessions import AISessionConfig, build_ai_session_command
1212
-
1213
- snapshot = json.loads((REPO_ROOT / "tests" / "fixtures" / "dev-pipeline-behavior-snapshots" / "unix-runtime.json").read_text(encoding="utf-8"))
1214
- prompt = tmp_path / "prompt.md"
1215
- prompt.write_text("hello", encoding="utf-8")
1216
- project = tmp_path / "project"
1217
- project.mkdir()
1218
-
1219
- claude = build_ai_session_command(
1220
- AISessionConfig(
1221
- cli_command="claude",
1222
- platform="claude",
1223
- model="sonnet",
1224
- prompt_path=prompt,
1225
- cwd=project,
1226
- effort="high",
1227
- )
1228
- )
1229
- expected_claude = tuple(snapshot["aiCliCommands"]["claudeCommand"]["argv"])
1230
- assert claude.argv[1:] == expected_claude
1231
- assert claude.stdin_text is None
1232
-
1233
- codex = build_ai_session_command(
1234
- AISessionConfig(
1235
- cli_command="codex",
1236
- platform="codex",
1237
- model="codex-model",
1238
- prompt_path=prompt,
1239
- cwd=project,
1240
- effort="xhigh",
1241
- use_stream_json=True,
1242
- )
1243
- )
1244
- expected_prefix = tuple(snapshot["aiCliCommands"]["codexCommand"]["argvPrefix"])
1245
- assert codex.argv[1 : 1 + len(expected_prefix)] == expected_prefix
1246
- assert "--cd" in codex.argv
1247
- assert str(project) in codex.argv
1248
- assert "--json" in codex.argv
1249
- effort_index = codex.argv.index("model_reasoning_effort=xhigh")
1250
- assert codex.argv[effort_index - 1] == "--config"
1251
- assert codex.argv[-1] == "-"
1252
- assert codex.stdin_text == "hello"
1253
-
1254
- codebuddy = build_ai_session_command(
1255
- AISessionConfig(
1256
- cli_command="custom-cbc",
1257
- platform="codebuddy",
1258
- model="codebuddy-model",
1259
- prompt_path=prompt,
1260
- cwd=project,
1261
- effort="medium",
1262
- )
1263
- )
1264
- expected_codebuddy = tuple(snapshot["aiCliCommands"]["customWrapperCommand"]["argv"])
1265
- assert codebuddy.argv[1:] == expected_codebuddy
1266
- assert codebuddy.stdin_text == "hello"
1267
-
1268
- pi = build_ai_session_command(
1269
- AISessionConfig(
1270
- cli_command="pi",
1271
- platform="pi",
1272
- model="anthropic/sonnet",
1273
- prompt_path=prompt,
1274
- cwd=project,
1275
- effort="max",
1276
- use_stream_json=True,
1277
- )
1278
- )
1279
- assert pi.argv == (
1280
- "pi", "--mode", "json", "--approve", "--no-session", "--tools",
1281
- "read,bash,edit,write,grep,find,ls", "--model", "anthropic/sonnet",
1282
- "--thinking", "max",
1283
- )
1284
- assert pi.stdin_text == "hello"
1285
- assert pi.prompt_mode == "stdin"
1286
- assert "hello" not in pi.argv
1287
- assert not ({"--effort", "--sandbox", "--output-format", "--disallowedTools", "-y"} & set(pi.argv))
1288
-
1289
- cursor = build_ai_session_command(
1290
- AISessionConfig(
1291
- cli_command="agent",
1292
- platform="cursor",
1293
- model="cursor-model",
1294
- prompt_path=prompt,
1295
- cwd=project,
1296
- use_stream_json=True,
1297
- )
1298
- )
1299
- assert cursor.argv == (
1300
- "agent", "--print", "--force", "--trust", "--output-format", "stream-json",
1301
- "--model", "cursor-model",
1302
- )
1303
- assert cursor.stdin_text == "hello"
1304
- assert cursor.prompt_mode == "stdin"
1305
- assert "hello" not in cursor.argv
1306
- assert not ({"--effort", "--sandbox", "--worktree", "--disallowedTools", "-y", "--yolo"} & set(cursor.argv))
1307
-
1308
- agy = build_ai_session_command(
1309
- AISessionConfig(
1310
- cli_command="agy",
1311
- platform="antigravity",
1312
- model="gemini-3-pro",
1313
- effort="xhigh",
1314
- prompt_path=prompt,
1315
- cwd=project,
1316
- use_stream_json=True,
1317
- )
1318
- )
1319
- assert agy.argv == (
1320
- "agy", "--dangerously-skip-permissions", "--input-format", "stream-json",
1321
- "--output-format", "stream-json", "--model", "gemini-3-pro", "--effort", "xhigh",
1322
- )
1323
- assert json.loads(agy.stdin_text) == {"event": "user", "message": {"content": "hello"}}
1324
- assert agy.prompt_mode == "stdin"
1325
- assert "hello" not in agy.argv
1326
-
1327
- agy_text = build_ai_session_command(
1328
- AISessionConfig(
1329
- cli_command="agy",
1330
- platform="antigravity",
1331
- model=None,
1332
- prompt_path=prompt,
1333
- cwd=project,
1334
- use_stream_json=False,
1335
- )
1336
- )
1337
- assert agy_text.argv == ("agy", "-p", "hello", "--dangerously-skip-permissions")
1338
- assert agy_text.stdin_text is None
1339
- assert agy_text.prompt_mode == "argument"
1340
-
1341
-
1342
- def test_custom_ai_session_command_builder_injects_prompt_and_tokenizes_extra_args(tmp_path):
1343
- from prizmkit_runtime.launch_profiles import HeadlessLaunchProfile
1344
- from prizmkit_runtime.sessions import AISessionConfig, build_ai_session_command
1345
-
1346
- prompt = tmp_path / "prompt.md"
1347
- prompt.write_text("injected prompt", encoding="utf-8")
1348
- project = tmp_path / "project"
1349
- project.mkdir()
1350
-
1351
- command = build_ai_session_command(
1352
- AISessionConfig(
1353
- cli_command="tclaude",
1354
- platform="custom",
1355
- model="ignored-model",
1356
- prompt_path=prompt,
1357
- cwd=project,
1358
- effort="ignored-effort",
1359
- use_stream_json=True,
1360
- launch_profile=HeadlessLaunchProfile(
1361
- profile="custom",
1362
- prompt_arg="-i",
1363
- extra_args=("--verbose", "--path", "two words"),
1364
- ),
1365
- )
1366
- )
1367
-
1368
- assert command.argv == ("tclaude", "-i", "injected prompt", "--verbose", "--path", "two words")
1369
- assert command.stdin_text is None
1370
- assert command.provider == "custom"
1371
- assert command.prompt_mode == "argument"
1372
-
1373
-
1374
- def test_start_command_serialization_redacts_prompt_and_preserves_provider_flags(tmp_path):
1375
- from prizmkit_runtime.launch_profiles import HeadlessLaunchProfile
1376
- from prizmkit_runtime.sessions import AISessionConfig, build_ai_session_command, format_start_command
1377
-
1378
- prompt = tmp_path / "prompt.md"
1379
- secret_prompt = "secret prompt body with spaces"
1380
- prompt.write_text(secret_prompt, encoding="utf-8")
1381
- project = tmp_path / "project"
1382
- project.mkdir()
1383
-
1384
- claude = format_start_command(
1385
- build_ai_session_command(
1386
- AISessionConfig(
1387
- cli_command="claude",
1388
- platform="claude",
1389
- model=None,
1390
- prompt_path=prompt,
1391
- cwd=project,
1392
- )
1393
- )
1394
- )
1395
- assert "claude -p <prompt>" in claude
1396
- assert "--disallowedTools EnterWorktree" in claude
1397
- assert secret_prompt not in claude
1398
-
1399
- codebuddy = format_start_command(
1400
- build_ai_session_command(
1401
- AISessionConfig(
1402
- cli_command="cbc",
1403
- platform="codebuddy",
1404
- model=None,
1405
- prompt_path=prompt,
1406
- cwd=project,
1407
- )
1408
- )
1409
- )
1410
- assert codebuddy.startswith("cbc --print -y")
1411
- assert "--disallowedTools EnterWorktree" in codebuddy
1412
- assert secret_prompt not in codebuddy
1413
-
1414
- codex = format_start_command(
1415
- build_ai_session_command(
1416
- AISessionConfig(
1417
- cli_command="codex",
1418
- platform="codex",
1419
- model=None,
1420
- prompt_path=prompt,
1421
- cwd=project,
1422
- )
1423
- )
1424
- )
1425
- assert "--profile no-worktree" in codex
1426
- assert "exec --cd" in codex
1427
- assert codex.endswith(" -")
1428
- assert secret_prompt not in codex
1429
-
1430
- pi = format_start_command(
1431
- build_ai_session_command(
1432
- AISessionConfig(
1433
- cli_command="pi",
1434
- platform="pi",
1435
- model=None,
1436
- prompt_path=prompt,
1437
- cwd=project,
1438
- )
1439
- )
1440
- )
1441
- assert pi.startswith("pi --mode json --approve --no-session")
1442
- assert secret_prompt not in pi
1443
-
1444
- cursor = format_start_command(
1445
- build_ai_session_command(
1446
- AISessionConfig(
1447
- cli_command="agent",
1448
- platform="cursor",
1449
- model=None,
1450
- prompt_path=prompt,
1451
- cwd=project,
1452
- use_stream_json=True,
1453
- )
1454
- )
1455
- )
1456
- assert cursor == "agent --print --force --trust --output-format stream-json"
1457
- assert secret_prompt not in cursor
1458
-
1459
- custom = format_start_command(
1460
- build_ai_session_command(
1461
- AISessionConfig(
1462
- cli_command="tclaude",
1463
- platform="custom",
1464
- model=None,
1465
- prompt_path=prompt,
1466
- cwd=project,
1467
- launch_profile=HeadlessLaunchProfile(
1468
- profile="custom",
1469
- prompt_arg="-i",
1470
- extra_args=("--custom-flag", "two words", secret_prompt),
1471
- ),
1472
- )
1473
- )
1474
- )
1475
- assert custom == "tclaude -i <prompt> --custom-flag 'two words' <prompt>"
1476
- assert custom.count("<prompt>") == 2
1477
- assert secret_prompt not in custom
1478
-
1479
-
1480
- def test_session_preamble_writes_redacted_start_command_for_all_launch_profiles(tmp_path, monkeypatch):
1481
- import prizmkit_runtime.sessions as sessions
1482
- from prizmkit_runtime.launch_profiles import HeadlessLaunchProfile
1483
-
1484
- fake_cli = tmp_path / "fake_cli.py"
1485
- fake_cli.write_text(
1486
- "#!/usr/bin/env python3\n"
1487
- "import json, sys\n"
1488
- "_stdin = sys.stdin.read()\n"
1489
- "print(json.dumps({'type':'result','subtype':'success','usage':{'tokens':1},'result':'ok'}), flush=True)\n",
1490
- encoding="utf-8",
1491
- )
1492
- fake_cli.chmod(0o755)
1493
-
1494
- backup_texts = {}
1495
- original_recover = sessions.recover_session_log
1496
-
1497
- def spy_recover(primary, backup, min_size=1024):
1498
- if backup.is_file():
1499
- backup_texts[str(backup)] = backup.read_text(encoding="utf-8")
1500
- return original_recover(primary, backup, min_size)
1501
-
1502
- monkeypatch.setattr(sessions, "recover_session_log", spy_recover)
1503
-
1504
- cases = [
1505
- ("claude", "claude", None, "--disallowedTools EnterWorktree", "-p <prompt>"),
1506
- ("codebuddy", "codebuddy", None, "--disallowedTools EnterWorktree", "--print -y"),
1507
- ("codex", "codex", None, "--profile no-worktree", "exec --cd"),
1508
- (
1509
- "custom",
1510
- "custom",
1511
- HeadlessLaunchProfile(profile="custom", prompt_arg="-i", extra_args=("--custom-flag", "two words")),
1512
- "--custom-flag 'two words'",
1513
- "-i <prompt>",
1514
- ),
1515
- ]
1516
-
1517
- for label, platform, launch_profile, expected_flag, expected_prompt_marker in cases:
1518
- secret_prompt = f"secret prompt body for {label}"
1519
- prompt = tmp_path / f"{label}-prompt.md"
1520
- prompt.write_text(secret_prompt, encoding="utf-8")
1521
- session_log = tmp_path / "state" / "sessions" / f"sess-{label}" / "logs" / "session.log"
1522
- backup_log = tmp_path / "home" / ".prizmkit" / "session-backups" / f"sess-{label}.log"
1523
-
1524
- result = sessions.AISessionLauncher(
1525
- sessions.AISessionConfig(
1526
- cli_command=str(fake_cli),
1527
- platform=platform,
1528
- model=None,
1529
- prompt_path=prompt,
1530
- cwd=tmp_path,
1531
- log_path=session_log,
1532
- backup_log_path=backup_log,
1533
- launch_profile=launch_profile,
1534
- )
1535
- ).run()
1536
-
1537
- assert result.exit_code == 0
1538
- primary_text = session_log.read_text(encoding="utf-8")
1539
- backup_text = backup_texts[str(backup_log)]
1540
- for text in (primary_text, backup_text):
1541
- lines = text.splitlines()
1542
- assert lines[0] == "=== PRIZMKIT SESSION START ==="
1543
- assert lines[1] == "Prompt: <prompt>"
1544
- assert lines[2] == "Model: default"
1545
- assert lines[3].startswith("StartCommand: ")
1546
- assert expected_flag in lines[3]
1547
- assert expected_prompt_marker in lines[3]
1548
- assert lines[4].startswith("Started at epoch: ")
1549
- assert lines[5] == "--- OUTPUT BELOW ---"
1550
- assert secret_prompt not in "\n".join(lines[:6])
1551
- assert str(prompt) not in "\n".join(lines[:6])
1552
-
1553
-
1554
- def test_headless_review_guidance_maps_stage_local_skill_result():
1555
- headless_guidance_files = [
1556
- REPO_ROOT / "dev-pipeline" / "templates" / "sections" / "phase-review-full.md",
1557
- REPO_ROOT / "dev-pipeline" / "templates" / "bootstrap-tier3.md",
1558
- ]
1559
- skill_path = (
1560
- REPO_ROOT
1561
- / "core"
1562
- / "skills"
1563
- / "prizmkit-skill"
1564
- / "prizmkit-code-review"
1565
- / "SKILL.md"
1566
- )
1567
-
1568
- for path in headless_guidance_files:
1569
- text = path.read_text(encoding="utf-8")
1570
- assert "returns only `PASS` or `NEEDS_FIXES`" in text, path
1571
- assert "this injected session" in text, path
1572
- assert "text final-verdict" in text, path
1573
- assert "follow the skill's current review contract" not in text, path
1574
- assert "low=0" not in text and "Reviewer 3" not in text, path
1575
- assert "forced-worktree changed-content fallback" not in text, path
1576
- assert "isolation:" not in text, path
1577
-
1578
- skill_text = skill_path.read_text(encoding="utf-8")
1579
- assert "the staged diff, and the unstaged diff" in skill_text
1580
- assert "non-ignored untracked, deleted, renamed, and copied paths" in skill_text
1581
- assert "Do not maintain excluded-path metadata" in skill_text
1582
- assert "complete current Git-visible workspace" in skill_text
1583
- assert "accepted = 0" in skill_text
1584
- assert "ten completed review rounds" in skill_text
1585
- assert "## Phase 3: Independent Code Review" in skill_text
1586
- assert "maximum five Reviewer responses" in skill_text
1587
- assert "## Final Result" in skill_text
1588
- assert "PASS | NEEDS_FIXES" in skill_text
1589
- assert "Verdict: <PASS | NEEDS_FIXES | BLOCKED>" not in skill_text
1590
- assert "Reviewer 2" not in skill_text
1591
- assert "reviewer-workspace-protocol.md" not in skill_text
1592
- assert "reviewer-execution-protocol.md" not in skill_text
1593
- assert "WORKSPACE_MISMATCH" not in skill_text
1594
-
1595
-
1596
- def test_live_smoke_harness_reports_capability_skips_without_running(tmp_path, monkeypatch, capsys):
1597
- import importlib.util
1598
-
1599
- script = PIPELINE_ROOT / "tests" / "live_ai_cli_log_smoke.py"
1600
- spec = importlib.util.spec_from_file_location("live_ai_cli_log_smoke_test", script)
1601
- module = importlib.util.module_from_spec(spec)
1602
- assert spec.loader is not None
1603
- sys.modules[spec.name] = module
1604
- try:
1605
- spec.loader.exec_module(module)
1606
- finally:
1607
- sys.modules.pop(spec.name, None)
1608
-
1609
- fake_command = tmp_path / "fake-cli"
1610
- fake_command.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
1611
- fake_command.chmod(0o755)
1612
- profile = module.SmokeProfile("example", str(fake_command), "custom")
1613
- monkeypatch.setattr(module, "discover_profiles", lambda: ([profile], [module.SmokeResult("missing", "skipped", "executable not found")]))
1614
- monkeypatch.delenv("PRIZMKIT_RUN_LIVE_AI_SMOKE", raising=False)
1615
-
1616
- code = module.main([])
1617
- payload = json.loads(capsys.readouterr().out)
1618
-
1619
- assert code == 0
1620
- assert {item["name"]: item["status"] for item in payload["results"]} == {
1621
- "example": "skipped",
1622
- "missing": "skipped",
1623
- }
1624
- reasons = {item["name"]: item["reason"] for item in payload["results"]}
1625
- assert "not authorized" in reasons["example"]
1626
- assert "executable not found" in reasons["missing"]
1627
- assert "Do not read, create, edit, or delete project files" in module.smoke_prompt()
1628
- assert module._looks_capability_blocked("login required") is True
1629
- assert module._looks_capability_blocked("network is unreachable") is True
1630
- assert module._looks_capability_blocked("model not found") is True
1631
- assert module._looks_capability_blocked("ordinary tool failure") is False
1632
-
1633
-
1634
- def test_session_dual_writes_progress_and_recovers_backup(tmp_path):
1635
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher, recover_session_log
1636
-
1637
- fake_cli = tmp_path / "fake_cli.py"
1638
- fake_cli.write_text(
1639
- "#!/usr/bin/env python3\n"
1640
- "import json, sys\n"
1641
- "print(json.dumps({'type':'system','subtype':'init','session_id':'s1'}), flush=True)\n"
1642
- "print(json.dumps({'type':'result','subtype':'success','stop_reason':'end_turn','usage':{'tokens':1},'result':'ok'}), flush=True)\n",
1643
- encoding="utf-8",
1644
- )
1645
- fake_cli.chmod(0o755)
1646
- prompt = tmp_path / "prompt.md"
1647
- prompt.write_text("hello", encoding="utf-8")
1648
- session_log = tmp_path / "state" / "sessions" / "sess-1" / "logs" / "session.log"
1649
- backup_log = tmp_path / "home" / ".prizmkit" / "session-backups" / "sess-1.log"
1650
- progress = session_log.with_name("progress.json")
1651
-
1652
- result = AISessionLauncher(
1653
- AISessionConfig(
1654
- cli_command=str(fake_cli),
1655
- platform="codebuddy",
1656
- model=None,
1657
- prompt_path=prompt,
1658
- cwd=tmp_path,
1659
- log_path=session_log,
1660
- backup_log_path=backup_log,
1661
- progress_path=progress,
1662
- )
1663
- ).run()
1664
-
1665
- assert result.exit_code == 0
1666
- assert session_log.exists()
1667
- assert progress.exists()
1668
- progress_data = json.loads(progress.read_text(encoding="utf-8"))
1669
- assert progress_data["event_type_counts"]["result"] == 1
1670
- assert progress_data["claude_session_id"] == "s1"
1671
- assert progress_data["has_usage"] is True
1672
- assert result.log_recovery is not None
1673
-
1674
- second_backup = tmp_path / "backup.log"
1675
- second_log = tmp_path / "main.log"
1676
- second_log.write_text("tiny", encoding="utf-8")
1677
- second_backup.write_text("larger recovered log", encoding="utf-8")
1678
- recovery = recover_session_log(second_log, second_backup)
1679
- assert recovery.recovered is True
1680
- assert recovery.cleaned_backup is True
1681
- assert not second_backup.exists()
1682
- assert second_log.read_text(encoding="utf-8") == "larger recovered log"
1683
-
1684
-
1685
- def test_heartbeat_fatal_error_writes_shell_compatible_markers(tmp_path):
1686
- from prizmkit_runtime.heartbeat import HeartbeatConfig, HeartbeatMonitor
1687
- from prizmkit_runtime.processes import ProcessSpec, launch_process
1688
-
1689
- sleeper = tmp_path / "fatal_sleep.py"
1690
- sleeper.write_text("import time\ntime.sleep(5)\n", encoding="utf-8")
1691
- progress = tmp_path / "progress.json"
1692
- progress.write_text(
1693
- '{"current_tool":"bash","fatal_error_code":"context_overflow"}\n',
1694
- encoding="utf-8",
1695
- )
1696
- handle = launch_process(ProcessSpec(command=(sys.executable, str(sleeper)), cwd=tmp_path))
1697
- monitor = HeartbeatMonitor(
1698
- handle,
1699
- HeartbeatConfig(
1700
- heartbeat_file=tmp_path / "heartbeat.json",
1701
- session_log=tmp_path / "session.log",
1702
- progress_file=progress,
1703
- marker_dir=tmp_path,
1704
- interval_seconds=0.05,
1705
- stale_after_seconds=10,
1706
- kill_after_seconds=10,
1707
- grace_seconds=0.1,
1708
- ),
1709
- )
1710
- monitor.start()
1711
- deadline = time.time() + 3
1712
- while time.time() < deadline and not (tmp_path / "fatal-error.json").exists():
1713
- time.sleep(0.05)
1714
- result = monitor.stop()
1715
-
1716
- fatal = json.loads((tmp_path / "fatal-error.json").read_text(encoding="utf-8"))
1717
- stale = json.loads((tmp_path / "stale-kill.json").read_text(encoding="utf-8"))
1718
- assert result.killed is True
1719
- assert result.reason == "context_overflow"
1720
- assert fatal["killed_at"].endswith("Z")
1721
- assert fatal["fatal_error_code"] == "context_overflow"
1722
- assert stale["reason"] == "context_overflow"
1723
-
1724
-
1725
- from prizmkit_runtime.heartbeat import HeartbeatConfig, write_stale_marker
1726
- from prizmkit_runtime.processes import ProcessSpec, platform_termination_strategy, run_process_with_capture
1727
-
1728
- sleeper = tmp_path / "sleep.py"
1729
- sleeper.write_text("import time\ntime.sleep(5)\n", encoding="utf-8")
1730
- result = run_process_with_capture(
1731
- ProcessSpec(command=(sys.executable, str(sleeper)), cwd=tmp_path),
1732
- timeout_seconds=0.2,
1733
- grace_seconds=0.1,
1734
- )
1735
-
1736
- assert result.timed_out is True
1737
- assert result.termination is not None
1738
- assert result.termination.reason == "timeout"
1739
- assert platform_termination_strategy()
1740
-
1741
- marker = write_stale_marker(tmp_path, reason="stale_session", stale_seconds=3, threshold=2)
1742
- marker_data = json.loads(marker.read_text(encoding="utf-8"))
1743
- assert marker_data["reason"] == "stale_session"
1744
- assert marker_data["threshold"] == 2
1745
- assert HeartbeatConfig(heartbeat_file=tmp_path / "heartbeat").interval_seconds == 30
1746
-
1747
-
1748
- def test_git_branch_plans_preserve_shell_invariants(tmp_path):
1749
- from prizmkit_runtime.gitops import (
1750
- BranchContext,
1751
- GitCommandResult,
1752
- GitPlanResult,
1753
- branch_create_plan,
1754
- branch_ensure_return_plan,
1755
- branch_merge_plan,
1756
- branch_save_wip,
1757
- branch_save_wip_plan,
1758
- )
1759
-
1760
- context = BranchContext(base_branch="main", working_branch="dev/example", project_root=tmp_path)
1761
- create = branch_create_plan(context)
1762
- merge = branch_merge_plan(context, auto_push=True)
1763
- save_wip = branch_save_wip_plan(context)
1764
- ensure = branch_ensure_return_plan(context)
1765
-
1766
- assert create.name == "branch_create"
1767
- assert any(command.args[:2] == ("checkout", "-b") for command in create.commands)
1768
- assert not any(command.args and command.args[0] == "stash" for command in merge.commands)
1769
- assert any(command.args[:2] == ("status", "--porcelain") for command in merge.commands)
1770
- assert any(command.args[:2] == ("merge", "--ff-only") for command in merge.commands)
1771
- push_index = next(index for index, command in enumerate(merge.commands) if command.args == ("push",))
1772
- merge_index = next(index for index, command in enumerate(merge.commands) if command.args[:2] == ("merge", "--ff-only"))
1773
- assert merge_index < push_index
1774
- assert save_wip.never_fails is False
1775
- assert ensure.never_fails is False
1776
- assert any(command.args[:2] == ("rebase", "--abort") for command in ensure.commands)
1777
- assert any(command.args[:2] == ("add", "-A") for command in ensure.commands)
1778
- assert not any(command.args and command.args[0] == "stash" for command in ensure.commands)
1779
- assert not any(command.args and command.args[0] in {"merge", "push"} for command in save_wip.commands + ensure.commands)
1780
- assert not any(command.args[:2] == ("branch", "-d") for command in save_wip.commands + ensure.commands)
1781
- assert ensure.never_fails is False
1782
- assert any(command.args == ("add", "-A", "--", ".") for command in save_wip.commands)
1783
- assert not any(
1784
- "exclude" in arg
1785
- for command in save_wip.commands
1786
- if command.args[:2] == ("add", "-A")
1787
- for arg in command.args
1788
- )
1789
-
1790
- allowed_failure_result = GitPlanResult(
1791
- plan=create,
1792
- results=(
1793
- GitCommandResult(create.commands[0].args, 1, "", "missing"),
1794
- GitCommandResult(create.commands[1].args, 0, "", ""),
1795
- ),
1796
- )
1797
- assert allowed_failure_result.ok is True
1798
-
1799
- failed_branch_change = GitPlanResult(
1800
- plan=create,
1801
- results=(
1802
- GitCommandResult(create.commands[0].args, 1, "", "missing"),
1803
- GitCommandResult(create.commands[1].args, 1, "", "bad base"),
1804
- GitCommandResult(create.commands[2].args, 1, "", "missing branch"),
1805
- ),
1806
- )
1807
- assert failed_branch_change.ok is False
1808
-
1809
- skipped_wip = branch_save_wip(tmp_path, "dev/example")
1810
- assert skipped_wip.ok is True
1811
- assert skipped_wip.results == ()
1812
-
1813
-
1814
- def test_runtime_source_constructs_no_git_stash_commands():
1815
- runtime = PIPELINE_ROOT / "prizmkit_runtime"
1816
- source_files = sorted(runtime.glob("*.py"))
1817
- assert source_files
1818
- matches = []
1819
- for path in source_files:
1820
- text = path.read_text(encoding="utf-8")
1821
- if re.search(r'["\']stash["\']', text):
1822
- matches.append(path.as_posix())
1823
-
1824
- assert matches == []
1825
-
1826
-
1827
- def _init_merge_repo(project_root):
1828
- subprocess.run(["git", "init", "-b", "main"], cwd=project_root, check=True, stdout=subprocess.DEVNULL)
1829
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=project_root, check=True)
1830
- subprocess.run(["git", "config", "user.name", "Test"], cwd=project_root, check=True)
1831
- manifest = project_root / ".prizmkit" / "manifest.json"
1832
- manifest.parent.mkdir(parents=True)
1833
- manifest.write_text('{"version":"current"}\n', encoding="utf-8")
1834
- (project_root / "app.txt").write_text("base\n", encoding="utf-8")
1835
- subprocess.run(["git", "add", "."], cwd=project_root, check=True)
1836
- subprocess.run(["git", "commit", "-m", "base"], cwd=project_root, check=True, stdout=subprocess.DEVNULL)
1837
-
1838
-
1839
- def _stash_oids(project_root):
1840
- output = subprocess.run(
1841
- ["git", "stash", "list", "--format=%H"],
1842
- cwd=project_root,
1843
- check=True,
1844
- stdout=subprocess.PIPE,
1845
- text=True,
1846
- ).stdout
1847
- return tuple(line for line in output.splitlines() if line)
1848
-
1849
-
1850
- def _commit_runtime_wip(project_root, subject, *body_paragraphs):
1851
- subprocess.run(["git", "add", "-A", "--", "."], cwd=project_root, check=True)
1852
- command = ["git", "commit", "--no-verify", "-m", subject]
1853
- for paragraph in body_paragraphs:
1854
- command.extend(["-m", paragraph])
1855
- subprocess.run(command, cwd=project_root, check=True, stdout=subprocess.DEVNULL)
1856
- return subprocess.run(
1857
- ["git", "rev-parse", "HEAD"],
1858
- cwd=project_root,
1859
- check=True,
1860
- stdout=subprocess.PIPE,
1861
- text=True,
1862
- ).stdout.strip()
1863
-
1864
-
1865
- def test_restore_runtime_wip_rehydrates_complete_failure_commit(tmp_path):
1866
- from prizmkit_runtime.gitops import restore_runtime_wip
1867
-
1868
- _init_merge_repo(tmp_path)
1869
- (tmp_path / "delete me.txt").write_text("delete\n", encoding="utf-8")
1870
- (tmp_path / "rename source.txt").write_text("rename\n", encoding="utf-8")
1871
- subprocess.run(
1872
- ["git", "add", "delete me.txt", "rename source.txt"],
1873
- cwd=tmp_path,
1874
- check=True,
1875
- )
1876
- subprocess.run(
1877
- ["git", "commit", "-m", "add restoration matrix"],
1878
- cwd=tmp_path,
1879
- check=True,
1880
- stdout=subprocess.DEVNULL,
1881
- )
1882
- subprocess.run(
1883
- ["git", "checkout", "-b", "dev/F-005-runtime-wip"],
1884
- cwd=tmp_path,
1885
- check=True,
1886
- stdout=subprocess.DEVNULL,
1887
- )
1888
- parent = subprocess.run(
1889
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
1890
- ).stdout.strip()
1891
- (tmp_path / "app.txt").write_text("recovered feature\n", encoding="utf-8")
1892
- (tmp_path / "delete me.txt").unlink()
1893
- subprocess.run(
1894
- ["git", "mv", "rename source.txt", "renamed [literal]*.txt"],
1895
- cwd=tmp_path,
1896
- check=True,
1897
- )
1898
- (tmp_path / "new [literal]*.txt").write_text("new\n", encoding="utf-8")
1899
- wip_head = _commit_runtime_wip(
1900
- tmp_path,
1901
- "wip(F-005): preserve feature failed state",
1902
- "Pipeline preserved task branch work without merging it to the base branch.",
1903
- )
1904
-
1905
- result = restore_runtime_wip(
1906
- tmp_path,
1907
- family_kind="feature",
1908
- item_id="F-005",
1909
- working_branch="dev/F-005-runtime-wip",
1910
- )
1911
-
1912
- assert result.ok is True
1913
- assert result.restored is True
1914
- assert result.reason == "runtime_wip_restored"
1915
- assert result.wip_head == wip_head
1916
- assert result.restored_head == parent
1917
- assert subprocess.run(
1918
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
1919
- ).stdout.strip() == parent
1920
- status = subprocess.run(
1921
- ["git", "status", "--porcelain=v1"],
1922
- cwd=tmp_path,
1923
- check=True,
1924
- stdout=subprocess.PIPE,
1925
- text=True,
1926
- ).stdout
1927
- assert "app.txt" in status
1928
- assert "delete me.txt" in status
1929
- assert "rename source.txt" in status
1930
- assert "renamed [literal]*.txt" in status
1931
- assert "new [literal]*.txt" in status
1932
- assert (tmp_path / "app.txt").read_text(encoding="utf-8") == "recovered feature\n"
1933
- assert not (tmp_path / "delete me.txt").exists()
1934
- assert (tmp_path / "renamed [literal]*.txt").read_text(encoding="utf-8") == "rename\n"
1935
- assert (tmp_path / "new [literal]*.txt").read_text(encoding="utf-8") == "new\n"
1936
-
1937
- status_before_repeat = status
1938
- repeated = restore_runtime_wip(
1939
- tmp_path,
1940
- family_kind="feature",
1941
- item_id="F-005",
1942
- working_branch="dev/F-005-runtime-wip",
1943
- )
1944
- assert repeated.ok is True
1945
- assert repeated.restored is False
1946
- assert repeated.reason == "runtime_wip_not_found"
1947
- assert repeated.restored_head == parent
1948
- assert subprocess.run(
1949
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
1950
- ).stdout.strip() == parent
1951
- assert subprocess.run(
1952
- ["git", "status", "--porcelain=v1"],
1953
- cwd=tmp_path,
1954
- check=True,
1955
- stdout=subprocess.PIPE,
1956
- text=True,
1957
- ).stdout == status_before_repeat
1958
-
1959
-
1960
- def test_restore_runtime_wip_accepts_exact_interruption_identity(tmp_path):
1961
- from prizmkit_runtime.gitops import branch_save_wip, restore_runtime_wip
1962
-
1963
- _init_merge_repo(tmp_path)
1964
- branch = "dev/F-005-interrupted"
1965
- subprocess.run(["git", "checkout", "-b", branch], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
1966
- parent = subprocess.run(
1967
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
1968
- ).stdout.strip()
1969
- (tmp_path / "app.txt").write_text("interrupted\n", encoding="utf-8")
1970
- preserved = branch_save_wip(tmp_path, branch)
1971
- assert preserved.ok is True
1972
- assert any(command.args[:1] == ("commit",) for command in preserved.plan.commands)
1973
-
1974
- result = restore_runtime_wip(
1975
- tmp_path,
1976
- family_kind="feature",
1977
- item_id="F-005",
1978
- working_branch=branch,
1979
- )
1980
-
1981
- assert result.ok is True
1982
- assert result.restored is True
1983
- assert result.restored_head == parent
1984
- assert (tmp_path / "app.txt").read_text(encoding="utf-8") == "interrupted\n"
1985
-
1986
-
1987
- @pytest.mark.parametrize(
1988
- ("subject", "body"),
1989
- (
1990
- ("feat(F-005): completed work", ""),
1991
- (
1992
- "wip(F-005): preserve feature failed state",
1993
- "User-authored lookalike without the canonical Runtime body.",
1994
- ),
1995
- (
1996
- "wip(F-999): preserve feature failed state",
1997
- "Pipeline preserved task branch work without merging it to the base branch.",
1998
- ),
1999
- ),
2000
- )
2001
- def test_restore_runtime_wip_leaves_non_owned_tip_unchanged(tmp_path, subject, body):
2002
- from prizmkit_runtime.gitops import restore_runtime_wip
2003
-
2004
- _init_merge_repo(tmp_path)
2005
- branch = "dev/F-005-owned-only"
2006
- subprocess.run(["git", "checkout", "-b", branch], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2007
- (tmp_path / "app.txt").write_text("committed\n", encoding="utf-8")
2008
- head = _commit_runtime_wip(tmp_path, subject, *([body] if body else []))
2009
-
2010
- result = restore_runtime_wip(
2011
- tmp_path,
2012
- family_kind="feature",
2013
- item_id="F-005",
2014
- working_branch=branch,
2015
- )
2016
-
2017
- assert result.ok is True
2018
- assert result.restored is False
2019
- assert result.reason == "runtime_wip_not_found"
2020
- assert subprocess.run(
2021
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2022
- ).stdout.strip() == head
2023
- assert subprocess.run(
2024
- ["git", "status", "--porcelain"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2025
- ).stdout == ""
2026
-
2027
-
2028
- def test_restore_runtime_wip_leaves_staged_work_on_non_wip_tip_unchanged(tmp_path):
2029
- from prizmkit_runtime.gitops import restore_runtime_wip
2030
-
2031
- _init_merge_repo(tmp_path)
2032
- branch = "dev/F-005-ordinary-staged"
2033
- subprocess.run(["git", "checkout", "-b", branch], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2034
- head = subprocess.run(
2035
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2036
- ).stdout.strip()
2037
- (tmp_path / "app.txt").write_text("staged recovery work\n", encoding="utf-8")
2038
- subprocess.run(["git", "add", "app.txt"], cwd=tmp_path, check=True)
2039
- staged_before = subprocess.run(
2040
- ["git", "diff", "--cached", "--", "app.txt"],
2041
- cwd=tmp_path,
2042
- check=True,
2043
- stdout=subprocess.PIPE,
2044
- text=True,
2045
- ).stdout
2046
-
2047
- result = restore_runtime_wip(
2048
- tmp_path,
2049
- family_kind="feature",
2050
- item_id="F-005",
2051
- working_branch=branch,
2052
- )
2053
-
2054
- assert result.ok is True
2055
- assert result.restored is False
2056
- assert result.reason == "runtime_wip_not_found"
2057
- assert subprocess.run(
2058
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2059
- ).stdout.strip() == head
2060
- assert subprocess.run(
2061
- ["git", "diff", "--cached", "--", "app.txt"],
2062
- cwd=tmp_path,
2063
- check=True,
2064
- stdout=subprocess.PIPE,
2065
- text=True,
2066
- ).stdout == staged_before
2067
-
2068
-
2069
- def test_restore_runtime_wip_rejects_staged_overlay_without_moving_wip_tip(tmp_path):
2070
- from prizmkit_runtime.gitops import restore_runtime_wip
2071
-
2072
- _init_merge_repo(tmp_path)
2073
- branch = "dev/F-005-staged-overlay"
2074
- subprocess.run(["git", "checkout", "-b", branch], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2075
- (tmp_path / "app.txt").write_text("preserved\n", encoding="utf-8")
2076
- wip_head = _commit_runtime_wip(
2077
- tmp_path,
2078
- "wip(F-005): preserve feature failed state",
2079
- "Pipeline preserved task branch work without merging it to the base branch.",
2080
- )
2081
- (tmp_path / "post-wip.txt").write_text("staged after preservation\n", encoding="utf-8")
2082
- subprocess.run(["git", "add", "post-wip.txt"], cwd=tmp_path, check=True)
2083
- staged_before = subprocess.run(
2084
- ["git", "diff", "--cached", "--binary"],
2085
- cwd=tmp_path,
2086
- check=True,
2087
- stdout=subprocess.PIPE,
2088
- text=True,
2089
- ).stdout
2090
-
2091
- result = restore_runtime_wip(
2092
- tmp_path,
2093
- family_kind="feature",
2094
- item_id="F-005",
2095
- working_branch=branch,
2096
- )
2097
-
2098
- assert result.ok is False
2099
- assert result.reason == "runtime_wip_staged_changes"
2100
- assert result.wip_head == wip_head
2101
- assert result.restored_head == wip_head
2102
- assert subprocess.run(
2103
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2104
- ).stdout.strip() == wip_head
2105
- assert subprocess.run(
2106
- ["git", "diff", "--cached", "--binary"],
2107
- cwd=tmp_path,
2108
- check=True,
2109
- stdout=subprocess.PIPE,
2110
- text=True,
2111
- ).stdout == staged_before
2112
- assert (tmp_path / "app.txt").read_text(encoding="utf-8") == "preserved\n"
2113
- assert (tmp_path / "post-wip.txt").read_text(encoding="utf-8") == "staged after preservation\n"
2114
-
2115
-
2116
- def test_restore_runtime_wip_rejects_recorded_branch_mismatch_without_moving_head(tmp_path):
2117
- from prizmkit_runtime.gitops import restore_runtime_wip
2118
-
2119
- _init_merge_repo(tmp_path)
2120
- branch = "dev/F-005-actual"
2121
- subprocess.run(["git", "checkout", "-b", branch], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2122
- (tmp_path / "app.txt").write_text("preserved\n", encoding="utf-8")
2123
- head = _commit_runtime_wip(
2124
- tmp_path,
2125
- "wip(F-005): preserve feature failed state",
2126
- "Pipeline preserved task branch work without merging it to the base branch.",
2127
- )
2128
-
2129
- result = restore_runtime_wip(
2130
- tmp_path,
2131
- family_kind="feature",
2132
- item_id="F-005",
2133
- working_branch="dev/F-005-recorded",
2134
- )
2135
-
2136
- assert result.ok is False
2137
- assert result.reason == "runtime_wip_branch_mismatch"
2138
- assert subprocess.run(
2139
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2140
- ).stdout.strip() == head
2141
-
2142
-
2143
- def test_restore_runtime_wip_rejects_merge_state_without_moving_head(tmp_path):
2144
- from prizmkit_runtime.gitops import restore_runtime_wip
2145
-
2146
- _init_merge_repo(tmp_path)
2147
- branch = "dev/F-005-conflicted"
2148
- subprocess.run(["git", "checkout", "-b", branch], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2149
- (tmp_path / "app.txt").write_text("preserved side\n", encoding="utf-8")
2150
- wip_head = _commit_runtime_wip(
2151
- tmp_path,
2152
- "wip(F-005): preserve feature failed state",
2153
- "Pipeline preserved task branch work without merging it to the base branch.",
2154
- )
2155
- subprocess.run(["git", "checkout", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2156
- (tmp_path / "app.txt").write_text("base side\n", encoding="utf-8")
2157
- subprocess.run(["git", "commit", "-am", "advance conflicting base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2158
- subprocess.run(["git", "checkout", branch], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2159
- merge = subprocess.run(
2160
- ["git", "merge", "main"],
2161
- cwd=tmp_path,
2162
- check=False,
2163
- stdout=subprocess.PIPE,
2164
- stderr=subprocess.PIPE,
2165
- text=True,
2166
- )
2167
- assert merge.returncode != 0
2168
-
2169
- result = restore_runtime_wip(
2170
- tmp_path,
2171
- family_kind="feature",
2172
- item_id="F-005",
2173
- working_branch=branch,
2174
- )
2175
-
2176
- assert result.ok is False
2177
- assert result.reason == "runtime_wip_unresolved_merge"
2178
- assert subprocess.run(
2179
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2180
- ).stdout.strip() == wip_head
2181
- assert subprocess.run(
2182
- ["git", "ls-files", "-u"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2183
- ).stdout.strip()
2184
-
2185
-
2186
- def test_restore_runtime_wip_rejects_exact_merge_commit_identity(tmp_path):
2187
- from prizmkit_runtime.gitops import restore_runtime_wip
2188
-
2189
- _init_merge_repo(tmp_path)
2190
- subprocess.run(["git", "checkout", "-b", "wip-side"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2191
- (tmp_path / "side.txt").write_text("side\n", encoding="utf-8")
2192
- subprocess.run(["git", "add", "side.txt"], cwd=tmp_path, check=True)
2193
- subprocess.run(["git", "commit", "-m", "side commit"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2194
- subprocess.run(["git", "checkout", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2195
- branch = "dev/F-005-merge-wip"
2196
- subprocess.run(["git", "checkout", "-b", branch], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2197
- (tmp_path / "app.txt").write_text("task side\n", encoding="utf-8")
2198
- subprocess.run(["git", "commit", "-am", "task commit"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2199
- subprocess.run(
2200
- [
2201
- "git",
2202
- "merge",
2203
- "--no-ff",
2204
- "wip-side",
2205
- "-m",
2206
- "wip(F-005): preserve feature failed state",
2207
- "-m",
2208
- "Pipeline preserved task branch work without merging it to the base branch.",
2209
- ],
2210
- cwd=tmp_path,
2211
- check=True,
2212
- stdout=subprocess.DEVNULL,
2213
- )
2214
- head = subprocess.run(
2215
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2216
- ).stdout.strip()
2217
-
2218
- result = restore_runtime_wip(
2219
- tmp_path,
2220
- family_kind="feature",
2221
- item_id="F-005",
2222
- working_branch=branch,
2223
- )
2224
-
2225
- assert result.ok is False
2226
- assert result.reason == "runtime_wip_parent_invalid"
2227
- assert subprocess.run(
2228
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2229
- ).stdout.strip() == head
2230
-
2231
-
2232
- def test_restore_runtime_wip_rolls_back_tip_when_postcondition_fails(monkeypatch, tmp_path):
2233
- from prizmkit_runtime import gitops
2234
-
2235
- _init_merge_repo(tmp_path)
2236
- branch = "dev/F-005-rollback"
2237
- subprocess.run(["git", "checkout", "-b", branch], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2238
- (tmp_path / "app.txt").write_text("preserved\n", encoding="utf-8")
2239
- wip_head = _commit_runtime_wip(
2240
- tmp_path,
2241
- "wip(F-005): preserve feature failed state",
2242
- "Pipeline preserved task branch work without merging it to the base branch.",
2243
- )
2244
- monkeypatch.setattr(
2245
- gitops,
2246
- "visible_task_paths",
2247
- lambda _root: (
2248
- (),
2249
- gitops.GitCommandResult(("status",), 0, "", ""),
2250
- ),
2251
- )
2252
-
2253
- result = gitops.restore_runtime_wip(
2254
- tmp_path,
2255
- family_kind="feature",
2256
- item_id="F-005",
2257
- working_branch=branch,
2258
- )
2259
-
2260
- assert result.ok is False
2261
- assert result.reason == "runtime_wip_restore_verification_failed"
2262
- assert result.restored_head == wip_head
2263
- assert subprocess.run(
2264
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2265
- ).stdout.strip() == wip_head
2266
- assert subprocess.run(
2267
- ["git", "status", "--porcelain"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2268
- ).stdout == ""
2269
- assert (tmp_path / "app.txt").read_text(encoding="utf-8") == "preserved\n"
2270
-
2271
-
2272
- def test_branch_merge_preserves_preexisting_stash_when_workspace_is_clean(tmp_path):
2273
- from prizmkit_runtime.gitops import BranchContext, branch_merge_plan, run_git_plan
2274
-
2275
- _init_merge_repo(tmp_path)
2276
- manifest = tmp_path / ".prizmkit" / "manifest.json"
2277
- manifest.write_text('{"version":"stale"}\n', encoding="utf-8")
2278
- subprocess.run(["git", "stash", "push", "-m", "stale-install", "--", ".prizmkit/manifest.json"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2279
- stale_stashes = _stash_oids(tmp_path)
2280
- subprocess.run(["git", "checkout", "-b", "dev/example"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2281
- (tmp_path / "feature.txt").write_text("done\n", encoding="utf-8")
2282
- subprocess.run(["git", "add", "feature.txt"], cwd=tmp_path, check=True)
2283
- subprocess.run(["git", "commit", "-m", "feature"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2284
-
2285
- result = run_git_plan(
2286
- tmp_path,
2287
- branch_merge_plan(BranchContext("main", "dev/example", tmp_path)),
2288
- )
2289
-
2290
- assert result.ok is True
2291
- assert _stash_oids(tmp_path) == stale_stashes
2292
- assert json.loads(manifest.read_text(encoding="utf-8"))["version"] == "current"
2293
- assert (tmp_path / "feature.txt").read_text(encoding="utf-8") == "done\n"
2294
-
2295
-
2296
- def test_branch_merge_fast_forwards_with_dirty_prizmkit_internal_state(tmp_path):
2297
- from prizmkit_runtime.gitops import (
2298
- BranchContext,
2299
- branch_fast_forward_possible,
2300
- branch_merge_plan,
2301
- run_git_plan,
2302
- )
2303
-
2304
- _init_merge_repo(tmp_path)
2305
- context = BranchContext("main", "dev/example", tmp_path)
2306
- subprocess.run(
2307
- ["git", "checkout", "-b", context.working_branch],
2308
- cwd=tmp_path,
2309
- check=True,
2310
- stdout=subprocess.DEVNULL,
2311
- )
2312
- (tmp_path / "feature.txt").write_text("done\n", encoding="utf-8")
2313
- subprocess.run(["git", "add", "feature.txt"], cwd=tmp_path, check=True)
2314
- subprocess.run(
2315
- ["git", "commit", "-m", "feature"],
2316
- cwd=tmp_path,
2317
- check=True,
2318
- stdout=subprocess.DEVNULL,
2319
- )
2320
- manifest = tmp_path / ".prizmkit" / "manifest.json"
2321
- manifest.write_text('{"version":"session-local"}\n', encoding="utf-8")
2322
-
2323
- assert branch_fast_forward_possible(tmp_path, context) is True
2324
- result = run_git_plan(
2325
- tmp_path,
2326
- branch_merge_plan(context, rebase=False),
2327
- )
2328
-
2329
- assert result.ok is True
2330
- assert not any(command.args and command.args[0] == "rebase" for command in result.plan.commands)
2331
- assert subprocess.run(
2332
- ["git", "branch", "--show-current"],
2333
- cwd=tmp_path,
2334
- check=True,
2335
- stdout=subprocess.PIPE,
2336
- text=True,
2337
- ).stdout.strip() == "main"
2338
- assert (tmp_path / "feature.txt").read_text(encoding="utf-8") == "done\n"
2339
- assert json.loads(manifest.read_text(encoding="utf-8"))["version"] == "session-local"
2340
- assert ".prizmkit/manifest.json" in subprocess.run(
2341
- ["git", "status", "--short"],
2342
- cwd=tmp_path,
2343
- check=True,
2344
- stdout=subprocess.PIPE,
2345
- text=True,
2346
- ).stdout
2347
- assert _stash_oids(tmp_path) == ()
2348
-
2349
-
2350
- def test_branch_merge_rejects_dirty_task_checkout_without_touching_stashes(tmp_path):
2351
- from prizmkit_runtime.gitops import BranchContext, branch_merge_plan, run_git_plan
2352
-
2353
- _init_merge_repo(tmp_path)
2354
- manifest = tmp_path / ".prizmkit" / "manifest.json"
2355
- manifest.write_text('{"version":"stale"}\n', encoding="utf-8")
2356
- subprocess.run(["git", "stash", "push", "-m", "user-stash", "--", ".prizmkit/manifest.json"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2357
- stale_stashes = _stash_oids(tmp_path)
2358
- subprocess.run(["git", "checkout", "-b", "dev/example"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2359
- (tmp_path / "feature.txt").write_text("done\n", encoding="utf-8")
2360
- subprocess.run(["git", "add", "feature.txt"], cwd=tmp_path, check=True)
2361
- subprocess.run(["git", "commit", "-m", "feature"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2362
- (tmp_path / "app.txt").write_text("local visible change\n", encoding="utf-8")
2363
-
2364
- result = run_git_plan(
2365
- tmp_path,
2366
- branch_merge_plan(BranchContext("main", "dev/example", tmp_path)),
2367
- )
2368
-
2369
- assert result.ok is False
2370
- assert _stash_oids(tmp_path) == stale_stashes
2371
- assert (tmp_path / "app.txt").read_text(encoding="utf-8") == "local visible change\n"
2372
- assert json.loads(manifest.read_text(encoding="utf-8"))["version"] == "current"
2373
- assert subprocess.run(
2374
- ["git", "branch", "--show-current"],
2375
- cwd=tmp_path,
2376
- check=True,
2377
- stdout=subprocess.PIPE,
2378
- text=True,
2379
- ).stdout.strip() == "dev/example"
2380
-
2381
-
2382
- def test_branch_merge_rebases_committed_task_without_stash_restore_conflict(tmp_path):
2383
- from prizmkit_runtime.gitops import BranchContext, branch_merge_plan, run_git_plan
2384
-
2385
- _init_merge_repo(tmp_path)
2386
- subprocess.run(["git", "checkout", "-b", "dev/example"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2387
- (tmp_path / "feature.txt").write_text("done\n", encoding="utf-8")
2388
- subprocess.run(["git", "add", "feature.txt"], cwd=tmp_path, check=True)
2389
- subprocess.run(["git", "commit", "-m", "feature"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2390
- subprocess.run(["git", "checkout", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2391
- (tmp_path / "app.txt").write_text("main changed\n", encoding="utf-8")
2392
- subprocess.run(["git", "commit", "-am", "advance main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2393
- subprocess.run(["git", "checkout", "dev/example"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2394
-
2395
- result = run_git_plan(
2396
- tmp_path,
2397
- branch_merge_plan(BranchContext("main", "dev/example", tmp_path)),
2398
- )
2399
-
2400
- assert result.ok is True
2401
- assert _stash_oids(tmp_path) == ()
2402
- assert (tmp_path / "app.txt").read_text(encoding="utf-8") == "main changed\n"
2403
- assert subprocess.run(
2404
- ["git", "branch", "--show-current"],
2405
- cwd=tmp_path,
2406
- check=True,
2407
- stdout=subprocess.PIPE,
2408
- text=True,
2409
- ).stdout.strip() == "main"
2410
-
2411
-
2412
- def test_branch_return_commits_wip_without_touching_user_stashes(tmp_path):
2413
- from prizmkit_runtime.gitops import branch_ensure_return
2414
-
2415
- _init_merge_repo(tmp_path)
2416
- manifest = tmp_path / ".prizmkit" / "manifest.json"
2417
- manifest.write_text('{"version":"stale"}\n', encoding="utf-8")
2418
- subprocess.run(["git", "stash", "push", "-m", "user-stash", "--", ".prizmkit/manifest.json"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2419
- user_stashes = _stash_oids(tmp_path)
2420
- subprocess.run(["git", "checkout", "-b", "dev/interrupted"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2421
- (tmp_path / "app.txt").write_text("interrupted work\n", encoding="utf-8")
2422
-
2423
- result = branch_ensure_return(tmp_path, "main", "dev/interrupted")
2424
-
2425
- assert result.ok is True
2426
- assert _stash_oids(tmp_path) == user_stashes
2427
- assert subprocess.run(
2428
- ["git", "branch", "--show-current"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2429
- ).stdout.strip() == "main"
2430
- assert subprocess.run(
2431
- ["git", "show", "dev/interrupted:app.txt"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2432
- ).stdout == "interrupted work\n"
2433
-
2434
-
2435
- def test_branch_return_ignores_installed_runtime_paths_without_blocking_wip_commit(tmp_path):
2436
- from prizmkit_runtime.gitops import branch_ensure_return
2437
-
2438
- _init_merge_repo(tmp_path)
2439
- (tmp_path / ".gitignore").write_text(
2440
- ".prizmkit/*\n.claude/\n.codebuddy/\n.agents/\n.pi\n",
2441
- encoding="utf-8",
2442
- )
2443
- subprocess.run(["git", "add", ".gitignore"], cwd=tmp_path, check=True)
2444
- subprocess.run(["git", "commit", "-m", "ignore installed runtime"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2445
- ignored_files = (
2446
- tmp_path / ".prizmkit" / "dev-pipeline" / "cli.py",
2447
- tmp_path / ".claude" / "runtime.json",
2448
- tmp_path / ".codebuddy" / "runtime.json",
2449
- tmp_path / ".agents" / "runtime.json",
2450
- tmp_path / ".pi" / "runtime.json",
2451
- )
2452
- for ignored_file in ignored_files:
2453
- ignored_file.parent.mkdir(parents=True, exist_ok=True)
2454
- ignored_file.write_text("ignored support\n", encoding="utf-8")
2455
- manifest = tmp_path / ".prizmkit" / "manifest.json"
2456
- manifest.write_text('{}\n', encoding="utf-8")
2457
- subprocess.run(["git", "checkout", "-b", "dev/interrupted"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2458
- (tmp_path / "interrupted.txt").write_text("preserved\n", encoding="utf-8")
2459
- (tmp_path / "interrupted [literal]*.txt").write_text("special path\n", encoding="utf-8")
2460
-
2461
- result = branch_ensure_return(tmp_path, "main", "dev/interrupted")
2462
-
2463
- assert result.ok is True
2464
- assert subprocess.run(
2465
- ["git", "branch", "--show-current"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2466
- ).stdout.strip() == "main"
2467
- assert subprocess.run(
2468
- ["git", "show", "dev/interrupted:interrupted.txt"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2469
- ).stdout == "preserved\n"
2470
- assert subprocess.run(
2471
- ["git", "show", "dev/interrupted:interrupted [literal]*.txt"],
2472
- cwd=tmp_path,
2473
- check=True,
2474
- stdout=subprocess.PIPE,
2475
- text=True,
2476
- ).stdout == "special path\n"
2477
- committed_paths = subprocess.run(
2478
- ["git", "ls-tree", "-r", "--name-only", "dev/interrupted"],
2479
- cwd=tmp_path,
2480
- check=True,
2481
- stdout=subprocess.PIPE,
2482
- text=True,
2483
- ).stdout.splitlines()
2484
- assert not any(path.startswith((".claude/", ".codebuddy/", ".agents/", ".pi/")) for path in committed_paths)
2485
-
2486
-
2487
- def test_clean_branch_return_skips_wip_commit_and_checks_out_base(tmp_path):
2488
- from prizmkit_runtime.gitops import branch_ensure_return
2489
-
2490
- _init_merge_repo(tmp_path)
2491
- base_head = subprocess.run(
2492
- ["git", "rev-parse", "HEAD"],
2493
- cwd=tmp_path,
2494
- check=True,
2495
- stdout=subprocess.PIPE,
2496
- text=True,
2497
- ).stdout.strip()
2498
- subprocess.run(["git", "checkout", "-b", "dev/clean-interrupt"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2499
-
2500
- result = branch_ensure_return(tmp_path, "main", "dev/clean-interrupt")
2501
-
2502
- assert result.ok is True
2503
- assert not any(command_result.args[:1] == ("commit",) for command_result in result.results)
2504
- assert subprocess.run(
2505
- ["git", "branch", "--show-current"],
2506
- cwd=tmp_path,
2507
- check=True,
2508
- stdout=subprocess.PIPE,
2509
- text=True,
2510
- ).stdout.strip() == "main"
2511
- assert subprocess.run(
2512
- ["git", "rev-parse", "dev/clean-interrupt"],
2513
- cwd=tmp_path,
2514
- check=True,
2515
- stdout=subprocess.PIPE,
2516
- text=True,
2517
- ).stdout.strip() == base_head
2518
-
2519
-
2520
- def test_branch_return_commits_staged_unstaged_deleted_renamed_and_special_paths(tmp_path):
2521
- from prizmkit_runtime.gitops import branch_ensure_return
2522
-
2523
- _init_merge_repo(tmp_path)
2524
- tracked_paths = {
2525
- "mixed.txt": "base mixed\n",
2526
- "delete me.txt": "delete me\n",
2527
- "rename source.txt": "rename me\n",
2528
- }
2529
- for relative, content in tracked_paths.items():
2530
- (tmp_path / relative).write_text(content, encoding="utf-8")
2531
- subprocess.run(["git", "add", "--", *tracked_paths], cwd=tmp_path, check=True)
2532
- subprocess.run(["git", "commit", "-m", "wip matrix base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2533
- subprocess.run(["git", "checkout", "-b", "dev/wip-matrix"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2534
-
2535
- (tmp_path / "mixed.txt").write_text("staged version\n", encoding="utf-8")
2536
- subprocess.run(["git", "add", "mixed.txt"], cwd=tmp_path, check=True)
2537
- (tmp_path / "mixed.txt").write_text("final unstaged version\n", encoding="utf-8")
2538
- (tmp_path / "delete me.txt").unlink()
2539
- subprocess.run(["git", "mv", "rename source.txt", "renamed [literal]*.txt"], cwd=tmp_path, check=True)
2540
- (tmp_path / "new [literal]*.txt").write_text("new special\n", encoding="utf-8")
2541
-
2542
- result = branch_ensure_return(tmp_path, "main", "dev/wip-matrix")
2543
-
2544
- assert result.ok is True
2545
- assert subprocess.run(
2546
- ["git", "branch", "--show-current"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2547
- ).stdout.strip() == "main"
2548
- assert subprocess.run(
2549
- ["git", "show", "dev/wip-matrix:mixed.txt"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2550
- ).stdout == "final unstaged version\n"
2551
- assert subprocess.run(
2552
- ["git", "show", "dev/wip-matrix:renamed [literal]*.txt"],
2553
- cwd=tmp_path,
2554
- check=True,
2555
- stdout=subprocess.PIPE,
2556
- text=True,
2557
- ).stdout == "rename me\n"
2558
- assert subprocess.run(
2559
- ["git", "show", "dev/wip-matrix:new [literal]*.txt"],
2560
- cwd=tmp_path,
2561
- check=True,
2562
- stdout=subprocess.PIPE,
2563
- text=True,
2564
- ).stdout == "new special\n"
2565
- task_tree = subprocess.run(
2566
- ["git", "ls-tree", "-r", "--name-only", "dev/wip-matrix"],
2567
- cwd=tmp_path,
2568
- check=True,
2569
- stdout=subprocess.PIPE,
2570
- text=True,
2571
- ).stdout.splitlines()
2572
- assert "delete me.txt" not in task_tree
2573
- assert "rename source.txt" not in task_tree
2574
-
2575
-
2576
- def test_branch_return_rejects_unmerged_paths_without_commit_or_checkout(tmp_path):
2577
- from prizmkit_runtime.gitops import branch_ensure_return
2578
-
2579
- _init_merge_repo(tmp_path)
2580
- subprocess.run(["git", "checkout", "-b", "dev/conflicted"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2581
- (tmp_path / "app.txt").write_text("task side\n", encoding="utf-8")
2582
- subprocess.run(["git", "commit", "-am", "task side"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2583
- subprocess.run(["git", "checkout", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2584
- (tmp_path / "app.txt").write_text("base side\n", encoding="utf-8")
2585
- subprocess.run(["git", "commit", "-am", "base side"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2586
- subprocess.run(["git", "checkout", "dev/conflicted"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2587
- merge = subprocess.run(
2588
- ["git", "merge", "main"],
2589
- cwd=tmp_path,
2590
- check=False,
2591
- stdout=subprocess.PIPE,
2592
- stderr=subprocess.PIPE,
2593
- text=True,
2594
- )
2595
- assert merge.returncode != 0
2596
- head_before = subprocess.run(
2597
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2598
- ).stdout.strip()
2599
-
2600
- result = branch_ensure_return(tmp_path, "main", "dev/conflicted")
2601
-
2602
- assert result.ok is False
2603
- assert "unresolved Git paths" in result.results[-1].stderr
2604
- assert subprocess.run(
2605
- ["git", "branch", "--show-current"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2606
- ).stdout.strip() == "dev/conflicted"
2607
- assert subprocess.run(
2608
- ["git", "rev-parse", "HEAD"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2609
- ).stdout.strip() == head_before
2610
- assert subprocess.run(
2611
- ["git", "ls-files", "-u"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True,
2612
- ).stdout.strip()
2613
-
2614
-
2615
- def test_branch_save_wip_rejects_clean_recorded_branch_mismatch(tmp_path):
2616
- from prizmkit_runtime.gitops import branch_save_wip
2617
-
2618
- _init_merge_repo(tmp_path)
2619
- subprocess.run(["git", "checkout", "-b", "dev/unrelated"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2620
-
2621
- result = branch_save_wip(tmp_path, "dev/recorded-task")
2622
-
2623
- assert result.ok is False
2624
- assert result.results[-1].stderr == "Active branch dev/unrelated does not match task branch dev/recorded-task"
2625
- assert subprocess.run(
2626
- ["git", "branch", "--show-current"],
2627
- cwd=tmp_path,
2628
- check=True,
2629
- stdout=subprocess.PIPE,
2630
- text=True,
2631
- ).stdout.strip() == "dev/unrelated"
2632
-
2633
-
2634
- def test_branch_return_commit_failure_does_not_checkout_base(monkeypatch, tmp_path):
2635
- from prizmkit_runtime import gitops
2636
-
2637
- calls = []
2638
-
2639
- def fake_run(_root, args):
2640
- args = tuple(args)
2641
- calls.append(args)
2642
- if args[:3] == ("rev-parse", "--abbrev-ref", "HEAD"):
2643
- return gitops.GitCommandResult(args, 0, "dev/interrupted\n", "")
2644
- if args and args[0] == "commit":
2645
- return gitops.GitCommandResult(args, 1, "", "commit failed")
2646
- if args[:2] == ("status", "--porcelain"):
2647
- return gitops.GitCommandResult(args, 0, " M app.txt\n", "")
2648
- return gitops.GitCommandResult(args, 0, "", "")
2649
-
2650
- monkeypatch.setattr(gitops, "run_git_command", fake_run)
2651
-
2652
- result = gitops.branch_ensure_return(tmp_path, "main", "dev/interrupted")
2653
-
2654
- assert result.ok is False
2655
- assert not any(args[:2] == ("checkout", "main") for args in calls)
2656
- assert not any(args and args[0] == "stash" for args in calls)
2657
-
2658
-
2659
- def test_non_current_reset_preserves_dirty_workspace_and_user_stashes(tmp_path):
2660
- from prizmkit_runtime.gitops import reset_cleanup_branch
2661
-
2662
- _init_merge_repo(tmp_path)
2663
- subprocess.run(["git", "branch", "dev/other"], cwd=tmp_path, check=True)
2664
- manifest = tmp_path / ".prizmkit" / "manifest.json"
2665
- manifest.write_text('{"version":"stale"}\n', encoding="utf-8")
2666
- subprocess.run(["git", "stash", "push", "-m", "user-stash", "--", ".prizmkit/manifest.json"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
2667
- user_stashes = _stash_oids(tmp_path)
2668
- (tmp_path / "app.txt").write_text("unstaged\n", encoding="utf-8")
2669
- (tmp_path / "staged.txt").write_text("staged\n", encoding="utf-8")
2670
- subprocess.run(["git", "add", "staged.txt"], cwd=tmp_path, check=True)
2671
- (tmp_path / "untracked.txt").write_text("untracked\n", encoding="utf-8")
2672
- before = subprocess.run(["git", "status", "--porcelain"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout
2673
-
2674
- reset_result = reset_cleanup_branch(tmp_path, "dev/other", return_branch="main", delete=False)
2675
-
2676
- assert reset_result.branch_preserved is True
2677
- assert reset_result.checkout_discarded is False
2678
- assert subprocess.run(["git", "branch", "--show-current"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout.strip() == "main"
2679
- assert subprocess.run(["git", "status", "--porcelain"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout == before
2680
- assert _stash_oids(tmp_path) == user_stashes
2681
- assert subprocess.run(["git", "show-ref", "--verify", "refs/heads/dev/other"], cwd=tmp_path, check=False).returncode == 0
2682
-
2683
- clean_result = reset_cleanup_branch(tmp_path, "dev/other", return_branch="main", delete=True)
2684
-
2685
- assert clean_result.deleted is True
2686
- assert subprocess.run(["git", "status", "--porcelain"], cwd=tmp_path, check=True, stdout=subprocess.PIPE, text=True).stdout == before
2687
- assert _stash_oids(tmp_path) == user_stashes
2688
-
2689
-
2690
- def test_git_status_safe_ignores_worktree_support_assets(monkeypatch, tmp_path):
2691
- from prizmkit_runtime.gitops import HIDDEN_TOOL_WORKTREE_EXCLUDES, git_status_safe
2692
-
2693
- captured = []
2694
-
2695
- def fake_run(project_root, args):
2696
- captured.append(tuple(args))
2697
- return type("Result", (), {"return_code": 0, "stdout": ""})()
2698
-
2699
- monkeypatch.setattr("prizmkit_runtime.gitops.run_git_command", fake_run)
2700
-
2701
- assert git_status_safe(tmp_path) == ""
2702
- status_args = captured[0]
2703
- joined = " ".join(status_args)
2704
- assert ":(top,exclude).prizmkit-worktree" in status_args
2705
- assert ":(top,exclude).claude" in status_args
2706
- assert ":(top,exclude).prizmkit" not in status_args
2707
- assert ":(top,exclude,glob).prizmkit/**" not in status_args
2708
- assert ":(top,exclude,glob).prizmkit/dev-pipeline/**" in status_args
2709
- assert ":(top,exclude,glob).prizmkit/state/**" in status_args
2710
- assert ":(top,exclude,glob).prizmkit/specs/**/workflow-checkpoint.json" in status_args
2711
- assert all(exclude in status_args for exclude in HIDDEN_TOOL_WORKTREE_EXCLUDES)
2712
- assert ".prizmkit-worktree" in joined
2713
-
2714
-
2715
- def _init_temp_repo(repo, *, configure_identity=True):
2716
- repo.mkdir(parents=True, exist_ok=True)
2717
- subprocess.run(["git", "init", "-b", "main"], cwd=repo, check=True, stdout=subprocess.DEVNULL)
2718
- if configure_identity:
2719
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=repo, check=True)
2720
- subprocess.run(["git", "config", "user.name", "Test"], cwd=repo, check=True)
2721
- (repo / "base.txt").write_text("base\n", encoding="utf-8")
2722
- subprocess.run(["git", "add", "base.txt"], cwd=repo, check=True)
2723
- subprocess.run(
2724
- [
2725
- "git",
2726
- "-c",
2727
- "user.email=test@example.com",
2728
- "-c",
2729
- "user.name=Test",
2730
- "commit",
2731
- "-m",
2732
- "base",
2733
- ],
2734
- cwd=repo,
2735
- check=True,
2736
- stdout=subprocess.DEVNULL,
2737
- )
2738
-
2739
-
2740
- def _head_commit_message(repo):
2741
- return subprocess.run(
2742
- ["git", "log", "-1", "--format=%s"],
2743
- cwd=repo,
2744
- check=True,
2745
- stdout=subprocess.PIPE,
2746
- text=True,
2747
- ).stdout.strip()
2748
-
2749
-
2750
- def _head_files(repo):
2751
- return set(
2752
- subprocess.run(
2753
- ["git", "show", "--name-only", "--format=", "HEAD"],
2754
- cwd=repo,
2755
- check=True,
2756
- stdout=subprocess.PIPE,
2757
- text=True,
2758
- ).stdout.split()
2759
- )
2760
-
2761
-
2762
- def _short_status(repo):
2763
- return subprocess.run(
2764
- ["git", "status", "--short"],
2765
- cwd=repo,
2766
- check=True,
2767
- stdout=subprocess.PIPE,
2768
- text=True,
2769
- ).stdout
2770
-
2771
-
2772
- def test_preflight_ready_commit_preserves_dirty_unstaged_visible_changes(tmp_path):
2773
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
2774
-
2775
- repo = tmp_path / "repo"
2776
- _init_temp_repo(repo)
2777
- (repo / "visible.txt").write_text("dirty\n", encoding="utf-8")
2778
-
2779
- result = commit_preflight_ready_changes(repo, "F-001")
2780
-
2781
- assert result.committed
2782
- assert _head_commit_message(repo) == "chore: ready for F-001"
2783
- assert _head_files(repo) == {"visible.txt"}
2784
- assert _short_status(repo) == ""
2785
-
2786
-
2787
- def test_preflight_ready_commit_preserves_dirty_staged_visible_changes(tmp_path):
2788
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
2789
-
2790
- repo = tmp_path / "repo"
2791
- _init_temp_repo(repo)
2792
- (repo / "staged.txt").write_text("staged\n", encoding="utf-8")
2793
- subprocess.run(["git", "add", "staged.txt"], cwd=repo, check=True)
2794
-
2795
- result = commit_preflight_ready_changes(repo, "B-002")
2796
-
2797
- assert result.committed
2798
- assert _head_commit_message(repo) == "chore: ready for B-002"
2799
- assert _head_files(repo) == {"staged.txt"}
2800
- assert _short_status(repo) == ""
2801
-
2802
-
2803
- def test_preflight_ready_commit_skips_clean_workspace(tmp_path):
2804
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
2805
-
2806
- repo = tmp_path / "repo"
2807
- _init_temp_repo(repo)
2808
- before = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
2809
-
2810
- result = commit_preflight_ready_changes(repo, "F-003")
2811
-
2812
- after = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
2813
- assert not result.attempted
2814
- assert not result.committed
2815
- assert after == before
2816
-
2817
-
2818
- def test_preflight_ready_commit_skips_hidden_support_asset_only_changes(tmp_path):
2819
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
2820
-
2821
- repo = tmp_path / "repo"
2822
- _init_temp_repo(repo)
2823
- (repo / ".claude").mkdir()
2824
- (repo / ".claude" / "settings.local.json").write_text("{}\n", encoding="utf-8")
2825
- before = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
2826
-
2827
- result = commit_preflight_ready_changes(repo, "F-004")
2828
-
2829
- after = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo, check=True, stdout=subprocess.PIPE, text=True).stdout.strip()
2830
- assert not result.attempted
2831
- assert after == before
2832
- assert (repo / ".claude" / "settings.local.json").is_file()
2833
-
2834
-
2835
- def test_preflight_ready_commit_includes_explicitly_staged_support_assets(tmp_path):
2836
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
2837
-
2838
- repo = tmp_path / "repo"
2839
- _init_temp_repo(repo)
2840
- (repo / ".claude").mkdir()
2841
- (repo / ".claude" / "agent.md").write_text("hidden\n", encoding="utf-8")
2842
- subprocess.run(["git", "add", "-f", ".claude/agent.md"], cwd=repo, check=True)
2843
- (repo / "visible.txt").write_text("visible\n", encoding="utf-8")
2844
-
2845
- result = commit_preflight_ready_changes(repo, "F-005")
2846
-
2847
- assert result.committed
2848
- assert _head_commit_message(repo) == "chore: ready for F-005"
2849
- assert _head_files(repo) == {".claude/agent.md", "visible.txt"}
2850
- assert _short_status(repo) == ""
2851
-
2852
-
2853
- def test_preflight_ready_commit_excludes_ignored_tool_worktree_directories(tmp_path):
2854
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
2855
-
2856
- repo = tmp_path / "repo"
2857
- _init_temp_repo(repo)
2858
- (repo / ".cache" / "worktrees" / "agent").mkdir(parents=True)
2859
- (repo / ".cache" / "worktrees" / "agent" / "artifact.txt").write_text("tool\n", encoding="utf-8")
2860
- (repo / "visible.txt").write_text("visible\n", encoding="utf-8")
2861
-
2862
- result = commit_preflight_ready_changes(repo, "F-006")
2863
-
2864
- assert result.committed
2865
- assert _head_files(repo) == {"visible.txt"}
2866
- assert (repo / ".cache" / "worktrees" / "agent" / "artifact.txt").is_file()
2867
-
2868
-
2869
- def test_preflight_ready_commit_preserves_dirty_changes_without_repo_git_identity(tmp_path, monkeypatch):
2870
- from prizmkit_runtime.gitops import PIPELINE_FALLBACK_GIT_EMAIL, PIPELINE_FALLBACK_GIT_NAME
2871
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
2872
-
2873
- repo = tmp_path / "repo"
2874
- monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(tmp_path / "missing-global-gitconfig"))
2875
- monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")
2876
- for key in ("GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL"):
2877
- monkeypatch.delenv(key, raising=False)
2878
- _init_temp_repo(repo, configure_identity=False)
2879
- (repo / "visible.txt").write_text("dirty\n", encoding="utf-8")
2880
-
2881
- result = commit_preflight_ready_changes(repo, "F-007")
2882
- author = subprocess.run(
2883
- ["git", "log", "-1", "--format=%an <%ae>"],
2884
- cwd=repo,
2885
- check=True,
2886
- stdout=subprocess.PIPE,
2887
- text=True,
2888
- ).stdout.strip()
2889
-
2890
- assert result.committed
2891
- assert _head_commit_message(repo) == "chore: ready for F-007"
2892
- assert _head_files(repo) == {"visible.txt"}
2893
- assert author == f"{PIPELINE_FALLBACK_GIT_NAME} <{PIPELINE_FALLBACK_GIT_EMAIL}>"
2894
- assert _short_status(repo) == ""
2895
-
2896
-
2897
- def test_preflight_ready_commit_force_stages_visible_file_when_prizmkit_dir_is_ignored(tmp_path):
2898
- from prizmkit_runtime.runner_bookkeeping import commit_preflight_ready_changes
2899
-
2900
- repo = tmp_path / "repo"
2901
- _init_temp_repo(repo)
2902
- (repo / ".gitignore").write_text(".prizmkit/*\n", encoding="utf-8")
2903
- subprocess.run(["git", "add", ".gitignore"], cwd=repo, check=True)
2904
- subprocess.run(["git", "commit", "-m", "ignore prizmkit"], cwd=repo, check=True, stdout=subprocess.DEVNULL)
2905
- (repo / ".prizmkit" / "dev-pipeline" / "templates").mkdir(parents=True)
2906
- (repo / ".prizmkit" / "dev-pipeline" / "templates" / "bootstrap-prompt.md").write_text("ignored runtime\n", encoding="utf-8")
2907
- (repo / "visible.txt").write_text("dirty\n", encoding="utf-8")
2908
-
2909
- result = commit_preflight_ready_changes(repo, "F-008")
2910
-
2911
- assert result.committed
2912
- assert _head_commit_message(repo) == "chore: ready for F-008"
2913
- assert _head_files(repo) == {"visible.txt"}
2914
- assert _short_status(repo) == ""
2915
-
2916
-
2917
- def test_load_task_checkout_rejects_retired_worktree_mode(tmp_path):
2918
- from prizmkit_runtime.task_checkout import (
2919
- CHECKOUT_MODE_BRANCH,
2920
- TaskCheckout,
2921
- TaskCheckoutError,
2922
- load_task_checkout,
2923
- task_checkout_path,
2924
- )
2925
-
2926
- state_dir = tmp_path / "state"
2927
- checkout_file = task_checkout_path(state_dir, "F-001")
2928
- checkout_file.parent.mkdir(parents=True)
2929
- checkout_file.write_text(
2930
- json.dumps(
2931
- {
2932
- "task_type": "feature",
2933
- "task_id": "F-001",
2934
- "state": "active",
2935
- "active_dev_branch": "dev/F-001-legacy",
2936
- "base_branch": "main",
2937
- "checkout_mode": "worktree",
2938
- "worktree_path": str(tmp_path / "wt" / "F-001"),
2939
- }
2940
- ),
2941
- encoding="utf-8",
2942
- )
2943
- with pytest.raises(TaskCheckoutError, match="retired worktree checkout mode"):
2944
- load_task_checkout(state_dir, "feature", "F-001")
2945
-
2946
- with pytest.raises(TaskCheckoutError, match="Unsupported task checkout mode"):
2947
- TaskCheckout.active(
2948
- "feature",
2949
- "F-001",
2950
- "dev/F-001-legacy",
2951
- "main",
2952
- checkout_mode="worktree",
2953
- )
2954
-
2955
- valid = TaskCheckout.active(
2956
- "feature",
2957
- "F-001",
2958
- "dev/F-001-branch",
2959
- "main",
2960
- checkout_mode=CHECKOUT_MODE_BRANCH,
2961
- )
2962
- assert valid.checkout_mode == CHECKOUT_MODE_BRANCH
2963
-
2964
-
2965
- def test_daemon_status_cli_preserves_pure_json_stdout(tmp_path):
2966
- project = tmp_path / "project"
2967
- (project / ".prizmkit" / "state" / "features").mkdir(parents=True)
2968
- result = run_cli("--project-root", str(project), "daemon", "feature", "status")
2969
-
2970
- assert result.returncode == 1
2971
- assert json.loads(result.stdout) == {"running": False}
2972
- assert "Pipeline is not running" in result.stderr
2973
- assert "Python feature daemon" not in result.stdout
2974
- assert "Transition command contract" not in result.stdout
2975
-
2976
-
2977
- def test_active_checkout_replacement_is_guarded_and_never_writes_reset_tombstone(tmp_path):
2978
- from prizmkit_runtime.task_checkout import (
2979
- TaskCheckout,
2980
- TaskCheckoutError,
2981
- load_task_checkout,
2982
- persist_task_checkout,
2983
- replace_active_task_checkout_locked,
2984
- )
2985
-
2986
- state_dir = tmp_path / "state"
2987
- expected = TaskCheckout.active("feature", "F-001", "dev/F-001-old", "main")
2988
- replacement = TaskCheckout.active("feature", "F-001", "dev/F-001-resume", "main")
2989
- persist_task_checkout(state_dir, expected)
2990
-
2991
- path = replace_active_task_checkout_locked(state_dir, expected, replacement)
2992
-
2993
- assert path == state_dir / "F-001" / "checkout.json"
2994
- loaded = load_task_checkout(state_dir, "feature", "F-001")
2995
- assert loaded == replacement
2996
- assert loaded is not None and loaded.is_reset is False
2997
- with pytest.raises(TaskCheckoutError, match="changed before recovery replacement"):
2998
- replace_active_task_checkout_locked(state_dir, expected, replacement)
2999
-
3000
-
3001
- def test_checkpoint_rewind_preserves_planning_and_resets_implementation_downstream():
3002
- from prizmkit_runtime.checkpoint_state import (
3003
- rewind_checkpoint_for_implementation,
3004
- validate_checkpoint_data,
3005
- )
3006
-
3007
- skills = [
3008
- "prizmkit-plan",
3009
- "prizmkit-implement",
3010
- "prizmkit-code-review",
3011
- "prizmkit-test",
3012
- "completion-summary",
3013
- "prizmkit-retrospective",
3014
- "prizmkit-committer",
3015
- ]
3016
- steps = []
3017
- previous = None
3018
- for index, skill in enumerate(skills, start=1):
3019
- status = "pending"
3020
- stage_result = None
3021
- if skill == "prizmkit-plan":
3022
- status, stage_result = "completed", "PLAN_READY"
3023
- elif skill == "prizmkit-implement":
3024
- status, stage_result = "completed", "IMPLEMENTED"
3025
- elif skill == "prizmkit-code-review":
3026
- status, stage_result = "failed", "REVIEW_NEEDS_FIXES"
3027
- step = {
3028
- "id": f"S{index:02d}",
3029
- "skill": skill,
3030
- "name": skill,
3031
- "status": status,
3032
- "depends_on": previous,
3033
- "required_artifacts": [],
3034
- }
3035
- if stage_result:
3036
- step["stage_result"] = stage_result
3037
- steps.append(step)
3038
- previous = step["id"]
3039
- payload = {
3040
- "version": 1,
3041
- "workflow_type": "feature-pipeline",
3042
- "steps": steps,
3043
- "feature_state": {
3044
- "schema_version": 1,
3045
- "artifact_dir": ".prizmkit/specs/example",
3046
- "orchestrator": "pipeline-runtime",
3047
- "stage": "code-review",
3048
- "current_stage": "prizmkit-code-review",
3049
- "status": "failed",
3050
- "stage_result": "REVIEW_NEEDS_FIXES",
3051
- "repair_scope": "production",
3052
- "repair_round": 2,
3053
- "next_stage": "prizmkit-implement",
3054
- "resume_from": "prizmkit-implement",
3055
- "blocked_reason": "review_needs_fixes",
3056
- "terminal_status": "WORKFLOW_BLOCKED",
3057
- "completed_stages": ["plan", "implement"],
3058
- },
3059
- }
3060
-
3061
- rewound = rewind_checkpoint_for_implementation(payload)
3062
-
3063
- assert rewound is not payload
3064
- assert rewound["steps"][0] == payload["steps"][0]
3065
- assert all(step["status"] == "pending" for step in rewound["steps"][1:])
3066
- assert all("stage_result" not in step for step in rewound["steps"][1:])
3067
- semantic = rewound["feature_state"]
3068
- assert semantic["stage"] == "implement"
3069
- assert semantic["current_stage"] == "prizmkit-implement"
3070
- assert semantic["status"] == "pending"
3071
- assert semantic["repair_round"] == 0
3072
- assert semantic["completed_stages"] == ["plan"]
3073
- assert semantic["blocked_reason"] is None
3074
- assert semantic["terminal_status"] is None
3075
- assert "stage_result" not in semantic
3076
- validated = validate_checkpoint_data(rewound)
3077
- assert validated.valid is True
3078
- assert validated.current_step is not None
3079
- assert validated.current_step.skill == "prizmkit-implement"
3080
-
3081
-
3082
- def test_git_recovery_helpers_create_branch_without_checkout_and_report_registration(tmp_path):
3083
- from prizmkit_runtime.gitops import (
3084
- create_branch_from_base,
3085
- local_branch_exists,
3086
- registered_worktrees,
3087
- )
3088
-
3089
- subprocess.run(["git", "init", "-b", "main"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3090
- subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=tmp_path, check=True)
3091
- subprocess.run(["git", "config", "user.name", "Test"], cwd=tmp_path, check=True)
3092
- (tmp_path / "base.txt").write_text("base\n", encoding="utf-8")
3093
- subprocess.run(["git", "add", "base.txt"], cwd=tmp_path, check=True)
3094
- subprocess.run(["git", "commit", "-m", "base"], cwd=tmp_path, check=True, stdout=subprocess.DEVNULL)
3095
-
3096
- assert local_branch_exists(tmp_path, "main") is True
3097
- assert local_branch_exists(tmp_path, "missing") is False
3098
- result = create_branch_from_base(tmp_path, "dev/F-001-resume", "main")
3099
-
3100
- assert result.return_code == 0
3101
- assert local_branch_exists(tmp_path, "dev/F-001-resume") is True
3102
- assert subprocess.run(
3103
- ["git", "branch", "--show-current"],
3104
- cwd=tmp_path,
3105
- check=True,
3106
- stdout=subprocess.PIPE,
3107
- text=True,
3108
- ).stdout.strip() == "main"
3109
- registrations = registered_worktrees(tmp_path)
3110
- assert any(
3111
- registration.path == tmp_path.resolve() and registration.branch == "main"
3112
- for registration in registrations
3113
- )
3114
-
3115
-
3116
- def test_cursor_stream_json_progress_and_semantic_log_contract(tmp_path):
3117
- parser = _load_progress_parser_module()
3118
- tracker = parser.ProgressTracker(tmp_path / "session.log")
3119
- normalizer = parser.SemanticLogNormalizer()
3120
- events = [
3121
- {
3122
- "type": "system",
3123
- "subtype": "init",
3124
- "apiKeySource": "login",
3125
- "cwd": str(tmp_path),
3126
- "session_id": "cursor-session",
3127
- "model": "Cursor Model",
3128
- "permissionMode": "default",
3129
- },
3130
- {
3131
- "type": "assistant",
3132
- "message": {"role": "assistant", "content": [{"type": "text", "text": "Reading the file"}]},
3133
- "session_id": "cursor-session",
3134
- },
3135
- {
3136
- "type": "tool_call",
3137
- "subtype": "started",
3138
- "call_id": "read-1",
3139
- "tool_call": {"readToolCall": {"args": {"path": "README.md"}}},
3140
- "session_id": "cursor-session",
3141
- },
3142
- {
3143
- "type": "tool_call",
3144
- "subtype": "completed",
3145
- "call_id": "read-1",
3146
- "tool_call": {
3147
- "readToolCall": {
3148
- "args": {"path": "README.md"},
3149
- "result": {"success": {"content": "large file content", "totalLines": 10}},
3150
- }
3151
- },
3152
- "session_id": "cursor-session",
3153
- },
3154
- {
3155
- "type": "tool_call",
3156
- "subtype": "started",
3157
- "call_id": "task-1",
3158
- "tool_call": {"function": {"name": "Task", "arguments": "{\"prompt\":\"inspect\"}"}},
3159
- "session_id": "cursor-session",
3160
- },
3161
- {
3162
- "type": "tool_call",
3163
- "subtype": "completed",
3164
- "call_id": "task-1",
3165
- "tool_call": {"function": {"name": "Task", "arguments": "{}", "result": {"success": "done"}}},
3166
- "session_id": "cursor-session",
3167
- },
3168
- {
3169
- "type": "result",
3170
- "subtype": "success",
3171
- "is_error": False,
3172
- "result": "Done",
3173
- "session_id": "cursor-session",
3174
- "unknown_future_field": {"safe": True},
3175
- },
3176
- ]
3177
-
3178
- rendered = ""
3179
- for event in events:
3180
- tracker.process_event(event)
3181
- rendered += normalizer.process_event(event)
3182
- rendered += normalizer.finish()
3183
- data = tracker.to_dict()
3184
-
3185
- assert data["event_format"] == "cursor-stream-json"
3186
- assert data["cursor_session_id"] == "cursor-session"
3187
- assert data["claude_session_id"] == ""
3188
- assert data["result_subtype"] == "success"
3189
- assert data["total_tool_calls"] == 2
3190
- tool_counts = {item["name"]: item["count"] for item in data["tool_calls"]}
3191
- assert tool_counts["Read"] == 1
3192
- assert tool_counts["Task"] == 1
3193
- assert data["subagent_statistics"]["spawned"] == 1
3194
- assert data["terminal_result_text"] == "Done"
3195
- assert "[ACTION] Read" in rendered
3196
- assert "[OBSERVATION] Read" in rendered
3197
- assert "<18 chars>" in rendered
3198
- assert "[SESSION_END] status=success" in rendered
3199
-
3200
-
3201
- def test_claude_init_with_shared_fields_is_not_misclassified_as_cursor(tmp_path):
3202
- from prizmkit_runtime.sessions import parse_stream_progress_lines
3203
-
3204
- parser = _load_progress_parser_module()
3205
- tracker = parser.ProgressTracker(tmp_path / "session.log", provider_hint="claude")
3206
- event = {
3207
- "type": "system",
3208
- "subtype": "init",
3209
- "apiKeySource": "login",
3210
- "permissionMode": "bypassPermissions",
3211
- "session_id": "claude-session",
3212
- }
3213
- tracker.process_event(event)
3214
- data = tracker.to_dict()
3215
- assert data["event_format"] == "stream-json"
3216
- assert data["claude_session_id"] == "claude-session"
3217
- assert data["cursor_session_id"] == ""
3218
-
3219
- summary = parse_stream_progress_lines((json.dumps(event),), provider_hint="claude")
3220
- assert summary.claude_session_id == "claude-session"
3221
- assert summary.cursor_session_id == ""
3222
-
3223
-
3224
- def test_cursor_stream_errors_and_malformed_lines_fail_safely(tmp_path):
3225
- from prizmkit_runtime.sessions import parse_stream_progress_lines
3226
-
3227
- parser = _load_progress_parser_module()
3228
- tracker = parser.ProgressTracker(tmp_path / "session.log")
3229
- tracker.process_event({
3230
- "type": "system",
3231
- "subtype": "init",
3232
- "apiKeySource": "env",
3233
- "session_id": "cursor-error-session",
3234
- })
3235
- tracker.process_event({
3236
- "type": "tool_call",
3237
- "subtype": "completed",
3238
- "call_id": "write-1",
3239
- "tool_call": {
3240
- "writeToolCall": {
3241
- "args": {"path": "blocked.txt", "fileText": "secret"},
3242
- "result": {"failure": {"message": "permission denied"}},
3243
- }
3244
- },
3245
- "session_id": "cursor-error-session",
3246
- })
3247
- tracker.process_event({
3248
- "type": "error",
3249
- "message": "Cursor Agent permission denied by policy",
3250
- "session_id": "cursor-error-session",
3251
- })
3252
- data = tracker.to_dict()
3253
- assert data["event_format"] == "cursor-stream-json"
3254
- assert data["cursor_session_id"] == "cursor-error-session"
3255
- assert data["current_tool"] is None
3256
- assert any("permission denied" in str(item) for item in data["errors"])
3257
- assert data["result_subtype"] == ""
3258
-
3259
- summary = parse_stream_progress_lines((
3260
- "not-json",
3261
- json.dumps({
3262
- "type": "system",
3263
- "subtype": "init",
3264
- "apiKeySource": "login",
3265
- "session_id": "cursor-summary",
3266
- }),
3267
- json.dumps({"type": "error", "message": "permission denied by user", "session_id": "cursor-summary"}),
3268
- ), provider_hint="cursor")
3269
- assert summary.cursor_session_id == "cursor-summary"
3270
- assert summary.claude_session_id == ""
3271
- assert summary.permission_denial_count == 1
3272
- assert summary.result_subtype == ""
3273
-
3274
-
3275
- def test_cursor_session_launcher_uses_stdin_and_task_checkout(tmp_path):
3276
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
3277
-
3278
- checkout = tmp_path / "checkout"
3279
- checkout.mkdir()
3280
- prompt = tmp_path / "prompt.md"
3281
- prompt_text = "cursor coordinator prompt " * 1000
3282
- prompt.write_text(prompt_text, encoding="utf-8")
3283
- fake_agent = tmp_path / "agent"
3284
- fake_agent.write_text(
3285
- "#!/usr/bin/env python3\n"
3286
- "import json, pathlib, sys\n"
3287
- "pathlib.Path('cursor-argv.json').write_text(json.dumps(sys.argv[1:]))\n"
3288
- "pathlib.Path('cursor-stdin.txt').write_text(sys.stdin.read())\n"
3289
- "print(json.dumps({'type':'system','subtype':'init','apiKeySource':'login','cwd':str(pathlib.Path.cwd()),'session_id':'cursor-live','model':'fake','permissionMode':'default'}), flush=True)\n"
3290
- "print(json.dumps({'type':'result','subtype':'success','is_error':False,'result':'ok','session_id':'cursor-live'}), flush=True)\n",
3291
- encoding="utf-8",
3292
- )
3293
- fake_agent.chmod(0o755)
3294
- session_log = tmp_path / "session.log"
3295
- progress = tmp_path / "progress.json"
3296
-
3297
- result = AISessionLauncher(
3298
- AISessionConfig(
3299
- cli_command=str(fake_agent),
3300
- platform="cursor",
3301
- model="fake-model",
3302
- prompt_path=prompt,
3303
- cwd=checkout,
3304
- log_path=session_log,
3305
- progress_path=progress,
3306
- use_stream_json=True,
3307
- )
3308
- ).run()
3309
-
3310
- argv = json.loads((checkout / "cursor-argv.json").read_text(encoding="utf-8"))
3311
- assert argv == ["--print", "--force", "--trust", "--output-format", "stream-json", "--model", "fake-model"]
3312
- assert prompt_text not in json.dumps(argv)
3313
- assert (checkout / "cursor-stdin.txt").read_text(encoding="utf-8") == prompt_text
3314
- assert result.exit_code == 0
3315
- assert result.progress_summary.result_subtype == "success"
3316
- assert result.progress_summary.cursor_session_id == "cursor-live"
3317
- assert result.progress_summary.claude_session_id == ""
3318
- assert "cursor coordinator prompt" not in session_log.read_text(encoding="utf-8")
3319
-
3320
-
3321
- def test_cursor_support_is_hidden_but_tracked_project_configuration_is_committable(tmp_path):
3322
- from prizmkit_runtime.gitops import (
3323
- HIDDEN_TOOL_WORKTREE_EXCLUDES,
3324
- WORKTREE_PLATFORM_SUPPORT_DIRS,
3325
- git_status_safe,
3326
- visible_task_paths,
3327
- )
3328
-
3329
- assert ".cursor" in WORKTREE_PLATFORM_SUPPORT_DIRS
3330
- assert ":(top,exclude).cursor" in HIDDEN_TOOL_WORKTREE_EXCLUDES
3331
- assert ":(top,exclude,glob).cursor/**" in HIDDEN_TOOL_WORKTREE_EXCLUDES
3332
-
3333
- project = tmp_path / "project"
3334
- project.mkdir()
3335
- subprocess.run(["git", "init", "-q"], cwd=project, check=True)
3336
- subprocess.run(["git", "config", "user.name", "Test User"], cwd=project, check=True)
3337
- subprocess.run(["git", "config", "user.email", "test@example.invalid"], cwd=project, check=True)
3338
- tracked_rule = project / ".cursor" / "rules" / "user-owned.mdc"
3339
- tracked_rule.parent.mkdir(parents=True)
3340
- tracked_rule.write_text("tracked\n", encoding="utf-8")
3341
- subprocess.run(["git", "add", ".cursor/rules/user-owned.mdc"], cwd=project, check=True)
3342
- subprocess.run(["git", "commit", "-qm", "fixture"], cwd=project, check=True)
3343
-
3344
- tracked_rule.write_text("changed\n", encoding="utf-8")
3345
- materialized = project / ".cursor" / "skills" / "prizmkit" / "SKILL.md"
3346
- materialized.parent.mkdir(parents=True)
3347
- materialized.write_text("support\n", encoding="utf-8")
3348
-
3349
- paths, result = visible_task_paths(project)
3350
- assert result.return_code == 0
3351
- assert ".cursor/rules/user-owned.mdc" in paths
3352
- assert ".cursor/skills/prizmkit/SKILL.md" not in paths
3353
- safe_status = git_status_safe(project)
3354
- assert ".cursor/rules/user-owned.mdc" in safe_status
3355
- assert ".cursor/skills/prizmkit/SKILL.md" not in safe_status
3356
-
3357
-
3358
- def test_antigravity_stream_json_progress_and_semantic_log_contract(tmp_path):
3359
- parser = _load_progress_parser_module()
3360
- tracker = parser.ProgressTracker(tmp_path / "session.log", provider_hint="antigravity")
3361
- normalizer = parser.SemanticLogNormalizer()
3362
- events = [
3363
- {"event": "init", "conversation_id": "agy-conv-1", "model": "gemini-pro"},
3364
- {
3365
- "event": "step_update",
3366
- "conversation_id": "agy-conv-1",
3367
- "step_update": {
3368
- "step_index": 1,
3369
- "step_type": "thinking",
3370
- "state": "RUNNING",
3371
- "thinking_delta": "Inspecting module...",
3372
- },
3373
- },
3374
- {
3375
- "event": "step_update",
3376
- "conversation_id": "agy-conv-1",
3377
- "step_update": {"step_index": 1, "step_type": "thinking", "state": "DONE"},
3378
- },
3379
- {
3380
- "event": "step_update",
3381
- "conversation_id": "agy-conv-1",
3382
- "step_update": {
3383
- "step_index": 2,
3384
- "step_type": "tool",
3385
- "state": "RUNNING",
3386
- "tool_info": {
3387
- "name": "write_to_file",
3388
- "parameters": {"TargetFile": "app.py", "CodeContent": "print('secret body')\n"},
3389
- },
3390
- },
3391
- },
3392
- {
3393
- "event": "step_update",
3394
- "conversation_id": "agy-conv-1",
3395
- "step_update": {
3396
- "step_index": 2,
3397
- "step_type": "tool",
3398
- "state": "DONE",
3399
- "tool_info": {
3400
- "name": "write_to_file",
3401
- "parameters": {"TargetFile": "app.py"},
3402
- "output": {"content": "wrote file successfully"},
3403
- },
3404
- },
3405
- },
3406
- {
3407
- "event": "step_update",
3408
- "conversation_id": "agy-conv-1",
3409
- "step_update": {
3410
- "step_index": 3,
3411
- "step_type": "tool",
3412
- "state": "DONE",
3413
- "tool_info": {
3414
- "name": "invoke_subagent",
3415
- "parameters": {"prompt": "audit"},
3416
- "output": "verified",
3417
- },
3418
- },
3419
- },
3420
- {
3421
- "event": "step_update",
3422
- "conversation_id": "agy-conv-1",
3423
- "step_update": {
3424
- "step_index": 4,
3425
- "step_type": "agent_response",
3426
- "state": "RUNNING",
3427
- "text_delta": "Implementation ",
3428
- },
3429
- },
3430
- {
3431
- "event": "step_update",
3432
- "conversation_id": "agy-conv-1",
3433
- "step_update": {
3434
- "step_index": 4,
3435
- "step_type": "agent_response",
3436
- "state": "DONE",
3437
- "text_delta": "complete.",
3438
- },
3439
- },
3440
- {
3441
- "event": "result",
3442
- "conversation_id": "agy-conv-1",
3443
- "result": {"status": "success", "response": "Done", "usage": {"total_tokens": 120}},
3444
- },
3445
- ]
3446
-
3447
- rendered = ""
3448
- for event in events:
3449
- tracker.process_event(event)
3450
- rendered += normalizer.process_event(event)
3451
- rendered += normalizer.finish()
3452
- data = tracker.to_dict()
3453
-
3454
- assert data["event_format"] == "antigravity-stream-json"
3455
- assert data["antigravity_session_id"] == "agy-conv-1"
3456
- assert data["claude_session_id"] == ""
3457
- assert data["cursor_session_id"] == ""
3458
- assert data["result_subtype"] == "success"
3459
- assert data["has_usage"] is True
3460
- assert data["total_tool_calls"] == 2
3461
- tool_counts = {item["name"]: item["count"] for item in data["tool_calls"]}
3462
- assert tool_counts["write_to_file"] == 1
3463
- assert tool_counts["invoke_subagent"] == 1
3464
- assert data["subagent_statistics"]["spawned"] == 1
3465
- assert data["terminal_result_text"] == "Done"
3466
- assert "[THINK] Inspecting module..." in rendered
3467
- assert "[ACTION] write_to_file" in rendered
3468
- assert "[OBSERVATION] write_to_file" in rendered
3469
- assert "<21 chars>" in rendered
3470
- assert "[FINAL] Implementation complete." in rendered
3471
- assert "[SESSION_END] status=success" in rendered
3472
-
3473
-
3474
- def test_antigravity_stream_errors_and_malformed_lines_fail_safely(tmp_path):
3475
- from prizmkit_runtime.sessions import parse_stream_progress_lines
3476
-
3477
- parser = _load_progress_parser_module()
3478
- tracker = parser.ProgressTracker(tmp_path / "session.log", provider_hint="antigravity")
3479
- tracker.process_event({"event": "init", "conversation_id": "agy-err-1"})
3480
- tracker.process_event({
3481
- "event": "step_update",
3482
- "step_update": {
3483
- "step_index": 1,
3484
- "step_type": "tool",
3485
- "state": "ERROR",
3486
- "tool_info": {
3487
- "name": "run_command",
3488
- "parameters": {"CommandLine": "rm -rf /"},
3489
- "error": "permission denied by user policy",
3490
- },
3491
- },
3492
- })
3493
- tracker.process_event({
3494
- "event": "error",
3495
- "error": {"code": "rate_limit_exceeded", "message": "API rate limit exceeded"},
3496
- })
3497
- data = tracker.to_dict()
3498
- assert data["event_format"] == "antigravity-stream-json"
3499
- assert data["antigravity_session_id"] == "agy-err-1"
3500
- assert data["current_tool"] is None
3501
- assert data["permission_denial_count"] >= 1
3502
- assert any("rate limit exceeded" in str(item).lower() for item in data["errors"])
3503
- assert data["result_subtype"] == ""
3504
-
3505
- tracker.process_event({
3506
- "event": "error",
3507
- "error": {
3508
- "code": "context_length_exceeded",
3509
- "message": "Prompt is too long: maximum context length exceeded",
3510
- },
3511
- })
3512
- overflow_data = tracker.to_dict()
3513
- assert overflow_data["fatal_error_code"] != ""
3514
- assert overflow_data["last_result_is_error"] is True
3515
-
3516
- summary = parse_stream_progress_lines((
3517
- "not-json",
3518
- json.dumps({"event": "init", "conversation_id": "agy-err-summary"}),
3519
- json.dumps({
3520
- "event": "result",
3521
- "result": {"status": "error", "error": {"message": "permission denied", "code": "denied"}},
3522
- }),
3523
- ), provider_hint="antigravity")
3524
- assert summary.antigravity_session_id == "agy-err-summary"
3525
- assert summary.claude_session_id == ""
3526
- assert summary.result_subtype == "error"
3527
- assert summary.permission_denial_count >= 1
3528
-
3529
-
3530
- def test_antigravity_session_launcher_uses_ndjson_stdin_and_task_checkout(tmp_path):
3531
- from prizmkit_runtime.sessions import AISessionConfig, AISessionLauncher
3532
-
3533
- checkout = tmp_path / "checkout"
3534
- checkout.mkdir()
3535
- prompt = tmp_path / "prompt.md"
3536
- prompt_text = "antigravity coordinator prompt " * 500
3537
- prompt.write_text(prompt_text, encoding="utf-8")
3538
- fake_agy = tmp_path / "agy"
3539
- fake_agy.write_text(
3540
- "#!/usr/bin/env python3\n"
3541
- "import json, pathlib, sys\n"
3542
- "pathlib.Path('agy-argv.json').write_text(json.dumps(sys.argv[1:]))\n"
3543
- "line = sys.stdin.readline()\n"
3544
- "pathlib.Path('agy-stdin.txt').write_text(line)\n"
3545
- "print(json.dumps({'event':'init','conversation_id':'agy-live','model':'fake-model'}), flush=True)\n"
3546
- "print(json.dumps({'event':'result','conversation_id':'agy-live','result':{'status':'success','response':'ok'}}), flush=True)\n",
3547
- encoding="utf-8",
3548
- )
3549
- fake_agy.chmod(0o755)
3550
- session_log = tmp_path / "session.log"
3551
- progress = tmp_path / "progress.json"
3552
-
3553
- result = AISessionLauncher(
3554
- AISessionConfig(
3555
- cli_command=str(fake_agy),
3556
- platform="antigravity",
3557
- model="fake-model",
3558
- effort="xhigh",
3559
- prompt_path=prompt,
3560
- cwd=checkout,
3561
- log_path=session_log,
3562
- progress_path=progress,
3563
- use_stream_json=True,
3564
- )
3565
- ).run()
3566
-
3567
- argv = json.loads((checkout / "agy-argv.json").read_text(encoding="utf-8"))
3568
- assert argv == [
3569
- "--dangerously-skip-permissions",
3570
- "--input-format",
3571
- "stream-json",
3572
- "--output-format",
3573
- "stream-json",
3574
- "--model",
3575
- "fake-model",
3576
- "--effort",
3577
- "xhigh",
3578
- ]
3579
- assert prompt_text not in json.dumps(argv)
3580
- stdin_msg = json.loads((checkout / "agy-stdin.txt").read_text(encoding="utf-8"))
3581
- assert stdin_msg == {"event": "user", "message": {"content": prompt_text}}
3582
- assert result.exit_code == 0
3583
- assert result.progress_summary.result_subtype == "success"
3584
- assert result.progress_summary.antigravity_session_id == "agy-live"
3585
- assert result.progress_summary.claude_session_id == ""
3586
- assert "antigravity coordinator prompt" not in session_log.read_text(encoding="utf-8")
3587
-
3588
-
3589
- def test_antigravity_support_is_hidden_but_tracked_agents_config_is_committable(tmp_path):
3590
- from prizmkit_runtime.gitops import (
3591
- HIDDEN_TOOL_WORKTREE_EXCLUDES,
3592
- WORKTREE_PLATFORM_SUPPORT_DIRS,
3593
- git_status_safe,
3594
- visible_task_paths,
3595
- )
3596
-
3597
- assert ".agents" in WORKTREE_PLATFORM_SUPPORT_DIRS
3598
- assert ":(top,exclude).agents" in HIDDEN_TOOL_WORKTREE_EXCLUDES
3599
- assert ":(top,exclude,glob).agents/**" in HIDDEN_TOOL_WORKTREE_EXCLUDES
3600
-
3601
- project = tmp_path / "project"
3602
- project.mkdir()
3603
- subprocess.run(["git", "init", "-q"], cwd=project, check=True)
3604
- subprocess.run(["git", "config", "user.name", "Test User"], cwd=project, check=True)
3605
- subprocess.run(["git", "config", "user.email", "test@example.invalid"], cwd=project, check=True)
3606
- tracked_plugin = project / ".agents" / "plugins" / "custom-user" / "plugin.json"
3607
- tracked_plugin.parent.mkdir(parents=True)
3608
- tracked_plugin.write_text('{"name":"custom"}\n', encoding="utf-8")
3609
- subprocess.run(["git", "add", ".agents/plugins/custom-user/plugin.json"], cwd=project, check=True)
3610
- subprocess.run(["git", "commit", "-qm", "fixture"], cwd=project, check=True)
3611
-
3612
- tracked_plugin.write_text('{"name":"custom","version":"2"}\n', encoding="utf-8")
3613
- materialized = project / ".agents" / "plugins" / "prizmkit" / "skills" / "prizmkit" / "SKILL.md"
3614
- materialized.parent.mkdir(parents=True)
3615
- materialized.write_text("support\n", encoding="utf-8")
3616
-
3617
- paths, result = visible_task_paths(project)
3618
- assert result.return_code == 0
3619
- assert ".agents/plugins/custom-user/plugin.json" in paths
3620
- assert ".agents/plugins/prizmkit/skills/prizmkit/SKILL.md" not in paths
3621
- safe_status = git_status_safe(project)
3622
- assert ".agents/plugins/custom-user/plugin.json" in safe_status
3623
- assert ".agents/plugins/prizmkit/skills/prizmkit/SKILL.md" not in safe_status
3624
-
3625
-