prizmkit 1.1.191 → 1.1.192

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/bundled/VERSION.json +3 -3
  2. package/bundled/adapters/antigravity/skill-adapter.js +13 -4
  3. package/bundled/adapters/codex/skill-adapter.js +28 -8
  4. package/bundled/adapters/cursor/skill-adapter.js +13 -4
  5. package/bundled/adapters/pi/skill-adapter.js +28 -7
  6. package/bundled/dev-pipeline/.env.example +4 -12
  7. package/bundled/dev-pipeline/README.md +5 -10
  8. package/bundled/dev-pipeline/assets/skill-subagent-integration.md +3 -6
  9. package/bundled/dev-pipeline/prizmkit_runtime/atomic_io.py +48 -0
  10. package/bundled/dev-pipeline/prizmkit_runtime/checkpoint_state.py +66 -23
  11. package/bundled/dev-pipeline/prizmkit_runtime/cli.py +10 -7
  12. package/bundled/dev-pipeline/prizmkit_runtime/commands.py +2 -21
  13. package/bundled/dev-pipeline/prizmkit_runtime/config.py +24 -76
  14. package/bundled/dev-pipeline/prizmkit_runtime/daemon.py +125 -67
  15. package/bundled/dev-pipeline/prizmkit_runtime/gitops.py +77 -430
  16. package/bundled/dev-pipeline/prizmkit_runtime/heartbeat.py +93 -49
  17. package/bundled/dev-pipeline/prizmkit_runtime/interoperability.py +1 -3
  18. package/bundled/dev-pipeline/prizmkit_runtime/paths.py +0 -6
  19. package/bundled/dev-pipeline/prizmkit_runtime/platform_detection.py +36 -14
  20. package/bundled/dev-pipeline/prizmkit_runtime/processes.py +206 -151
  21. package/bundled/dev-pipeline/prizmkit_runtime/reset.py +2 -23
  22. package/bundled/dev-pipeline/prizmkit_runtime/reset_preserve.py +15 -134
  23. package/bundled/dev-pipeline/prizmkit_runtime/results.py +25 -0
  24. package/bundled/dev-pipeline/prizmkit_runtime/runner_bookkeeping.py +68 -83
  25. package/bundled/dev-pipeline/prizmkit_runtime/runner_classification.py +15 -5
  26. package/bundled/dev-pipeline/prizmkit_runtime/runner_models.py +1 -29
  27. package/bundled/dev-pipeline/prizmkit_runtime/runner_prompts.py +0 -2
  28. package/bundled/dev-pipeline/prizmkit_runtime/runner_status.py +7 -2
  29. package/bundled/dev-pipeline/prizmkit_runtime/runners.py +276 -217
  30. package/bundled/dev-pipeline/prizmkit_runtime/runtime_commit.py +124 -122
  31. package/bundled/dev-pipeline/prizmkit_runtime/runtime_helper.py +90 -9
  32. package/bundled/dev-pipeline/prizmkit_runtime/sessions.py +183 -130
  33. package/bundled/dev-pipeline/prizmkit_runtime/status.py +1 -3
  34. package/bundled/dev-pipeline/prizmkit_runtime/stream_progress.py +2780 -0
  35. package/bundled/dev-pipeline/prizmkit_runtime/task_checkout.py +27 -101
  36. package/bundled/dev-pipeline/prizmkit_runtime/test_result.py +58 -4
  37. package/bundled/dev-pipeline/scripts/check-session-status.py +43 -19
  38. package/bundled/dev-pipeline/scripts/continuation.py +6 -4
  39. package/bundled/dev-pipeline/scripts/detect-stuck.py +28 -28
  40. package/bundled/dev-pipeline/scripts/generate-bootstrap-prompt.py +7 -2
  41. package/bundled/dev-pipeline/scripts/generate-bugfix-prompt.py +7 -2
  42. package/bundled/dev-pipeline/scripts/init-bugfix-pipeline.py +10 -7
  43. package/bundled/dev-pipeline/scripts/init-change-artifact.py +8 -2
  44. package/bundled/dev-pipeline/scripts/init-pipeline.py +14 -69
  45. package/bundled/dev-pipeline/scripts/parse-stream-progress.py +31 -2616
  46. package/bundled/dev-pipeline/scripts/patch-completion-notes.py +4 -24
  47. package/bundled/dev-pipeline/scripts/prompt_framework.py +56 -9
  48. package/bundled/dev-pipeline/scripts/status_common.py +591 -0
  49. package/bundled/dev-pipeline/scripts/update-bug-status.py +85 -463
  50. package/bundled/dev-pipeline/scripts/update-checkpoint.py +227 -65
  51. package/bundled/dev-pipeline/scripts/update-feature-status.py +76 -509
  52. package/bundled/dev-pipeline/scripts/utils.py +5 -12
  53. package/bundled/dev-pipeline/templates/bootstrap-tier3.md +4 -4
  54. package/bundled/dev-pipeline/templates/bug-fix-list-schema.json +7 -0
  55. package/bundled/dev-pipeline/templates/bugfix-bootstrap-prompt.md +1 -1
  56. package/bundled/dev-pipeline/templates/sections/artifact-manifest.md +1 -1
  57. package/bundled/dev-pipeline/templates/sections/bugfix-phase-manual-verification.md +1 -1
  58. package/bundled/dev-pipeline/templates/sections/bugfix-phase-review.md +1 -1
  59. package/bundled/dev-pipeline/templates/sections/bugfix-phase-test.md +2 -1
  60. package/bundled/dev-pipeline/templates/sections/checkpoint-system.md +1 -1
  61. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-auto.md +1 -1
  62. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-opencli.md +2 -2
  63. package/bundled/dev-pipeline/templates/sections/phase-browser-verification.md +2 -2
  64. package/bundled/dev-pipeline/templates/sections/phase-prizmkit-test.md +2 -1
  65. package/bundled/dev-pipeline/templates/sections/phase-review-full.md +1 -1
  66. package/bundled/dev-pipeline/templates/sections/phase-specify-plan-full.md +3 -6
  67. package/bundled/dev-pipeline/templates/session-status-schema.json +2 -5
  68. package/bundled/dev-pipeline/tests/_helpers.py +418 -0
  69. package/bundled/dev-pipeline/tests/conftest.py +45 -1
  70. package/bundled/dev-pipeline/tests/test_auto_skip.py +4 -69
  71. package/bundled/dev-pipeline/tests/test_checkpoint_state.py +126 -1
  72. package/bundled/dev-pipeline/tests/test_daemon_and_scripts.py +257 -0
  73. package/bundled/dev-pipeline/tests/test_e2e_pipeline_run.py +500 -0
  74. package/bundled/dev-pipeline/tests/test_generate_bootstrap_prompt.py +59 -117
  75. package/bundled/dev-pipeline/tests/test_generate_bugfix_prompt.py +12 -10
  76. package/bundled/dev-pipeline/tests/test_python_runner_parity.py +431 -3099
  77. package/bundled/dev-pipeline/tests/test_recovery_workflow.py +7 -8
  78. package/bundled/dev-pipeline/tests/test_repository_bootstrap.py +0 -1
  79. package/bundled/dev-pipeline/tests/test_reset_modes.py +15 -27
  80. package/bundled/dev-pipeline/tests/test_reset_preserve.py +54 -139
  81. package/bundled/dev-pipeline/tests/test_runner_bookkeeping.py +766 -0
  82. package/bundled/dev-pipeline/tests/test_runner_lifecycle.py +1257 -0
  83. package/bundled/dev-pipeline/tests/test_runtime_helper.py +97 -20
  84. package/bundled/dev-pipeline/tests/test_session_launch.py +1101 -0
  85. package/bundled/dev-pipeline/tests/test_stream_progress.py +585 -0
  86. package/bundled/dev-pipeline/tests/test_unified_cli.py +155 -2034
  87. package/bundled/dev-pipeline/tests/test_utils.py +3 -3
  88. package/bundled/skills/_metadata.json +9 -63
  89. package/bundled/skills/app-planner/SKILL.md +32 -303
  90. package/bundled/skills/app-planner/references/app-design-guide.md +0 -4
  91. package/bundled/skills/app-planner/references/generated-plan-review.md +2 -1
  92. package/bundled/skills/app-planner/references/project-brief-guide.md +14 -0
  93. package/bundled/skills/app-planner/references/project-conventions-discovery.md +4 -6
  94. package/bundled/skills/app-planner/references/project-state-detection.md +2 -3
  95. package/bundled/skills/bug-fix-workflow/SKILL.md +1 -2
  96. package/bundled/skills/bug-fix-workflow/references/bug-diagnosis.md +4 -7
  97. package/bundled/skills/bug-planner/SKILL.md +54 -435
  98. package/bundled/skills/bug-planner/references/generated-plan-review.md +3 -2
  99. package/bundled/skills/bug-planner/references/input-formats.md +32 -0
  100. package/bundled/skills/bugfix-pipeline-launcher/SKILL.md +4 -6
  101. package/bundled/skills/bugfix-pipeline-launcher/references/configuration.md +4 -28
  102. package/bundled/skills/feature-pipeline-launcher/SKILL.md +4 -6
  103. package/bundled/skills/feature-pipeline-launcher/references/configuration.md +4 -28
  104. package/bundled/skills/feature-planner/SKILL.md +60 -439
  105. package/bundled/skills/feature-planner/assets/planning-guide.md +1 -1
  106. package/bundled/skills/feature-planner/references/completeness-review.md +34 -0
  107. package/bundled/skills/feature-planner/references/decomposition-patterns.md +2 -2
  108. package/bundled/skills/feature-planner/references/error-recovery.md +1 -1
  109. package/bundled/skills/feature-planner/references/generated-plan-review.md +3 -2
  110. package/bundled/skills/feature-planner/references/incremental-feature-planning.md +3 -1
  111. package/bundled/skills/feature-workflow/SKILL.md +1 -2
  112. package/bundled/skills/prizmkit/SKILL.md +7 -1
  113. package/bundled/skills/prizmkit-code-review/SKILL.md +14 -6
  114. package/bundled/skills/prizmkit-code-review/references/independent-code-review.md +7 -4
  115. package/bundled/skills/prizmkit-code-review/references/review-report-template.md +16 -0
  116. package/bundled/skills/prizmkit-code-review/scripts/render_review_report.py +58 -20
  117. package/bundled/skills/prizmkit-implement/SKILL.md +1 -1
  118. package/bundled/skills/prizmkit-init/SKILL.md +24 -127
  119. package/bundled/skills/prizmkit-init/assets/project-brief-template.md +3 -3
  120. package/bundled/skills/prizmkit-plan/SKILL.md +6 -8
  121. package/bundled/skills/prizmkit-plan/references/clarify-guide.md +1 -1
  122. package/bundled/skills/prizmkit-plan/references/independent-plan-review.md +5 -2
  123. package/bundled/skills/prizmkit-plan/references/review-plan-spec-loop.md +6 -5
  124. package/bundled/skills/prizmkit-prizm-docs/SKILL.md +1 -13
  125. package/bundled/skills/prizmkit-prizm-docs/references/op-update.md +1 -1
  126. package/bundled/skills/prizmkit-retrospective/SKILL.md +6 -4
  127. package/bundled/skills/prizmkit-test/SKILL.md +25 -133
  128. package/bundled/skills/prizmkit-test/references/independent-test-review.md +5 -2
  129. package/bundled/skills/prizmkit-test/references/test-coverage-model.md +6 -0
  130. package/bundled/skills/prizmkit-workflow/SKILL.md +2 -3
  131. package/bundled/skills/prizmkit-workflow/references/workflow-state-protocol.md +4 -3
  132. package/bundled/skills/recovery-workflow/SKILL.md +7 -7
  133. package/bundled/skills/recovery-workflow/evals/evals.json +1 -1
  134. package/bundled/skills/recovery-workflow/references/detection.md +1 -3
  135. package/bundled/skills/recovery-workflow/scripts/detect-recovery-state.py +0 -6
  136. package/bundled/templates/project-memory-template.md +1 -2
  137. package/package.json +1 -1
  138. package/src/scaffold.js +28 -7
  139. package/bundled/dev-pipeline/SCHEMA_ANALYSIS.md +0 -53
  140. package/bundled/dev-pipeline/scripts/generate-refactor-prompt.py +0 -649
  141. package/bundled/dev-pipeline/scripts/init-refactor-pipeline.py +0 -463
  142. package/bundled/dev-pipeline/scripts/update-refactor-status.py +0 -1512
  143. package/bundled/dev-pipeline/templates/refactor-bootstrap-prompt.md +0 -240
  144. package/bundled/dev-pipeline/templates/refactor-list-schema.json +0 -266
  145. package/bundled/dev-pipeline/templates/sections/refactor-critical-paths.md +0 -15
  146. package/bundled/dev-pipeline/templates/sections/refactor-mission.md +0 -9
  147. package/bundled/dev-pipeline/templates/sections/refactor-phase-commit-report.md +0 -24
  148. package/bundled/dev-pipeline/templates/sections/refactor-phase-implement.md +0 -16
  149. package/bundled/dev-pipeline/templates/sections/refactor-phase-init.md +0 -9
  150. package/bundled/dev-pipeline/templates/sections/refactor-phase-plan.md +0 -22
  151. package/bundled/dev-pipeline/templates/sections/refactor-phase-review.md +0 -19
  152. package/bundled/dev-pipeline/templates/sections/refactor-phase-test.md +0 -24
  153. package/bundled/dev-pipeline/templates/sections/refactor-reminders.md +0 -12
  154. package/bundled/dev-pipeline/templates/sections/refactor-session-context.md +0 -6
  155. package/bundled/dev-pipeline/templates/sections/refactor-task-contract.md +0 -52
  156. package/bundled/dev-pipeline/tests/test_generate_refactor_prompt.py +0 -478
  157. package/bundled/skills/feature-planner/assets/evaluation-guide.md +0 -44
  158. package/bundled/skills/refactor-pipeline-launcher/SKILL.md +0 -219
  159. package/bundled/skills/refactor-pipeline-launcher/references/configuration.md +0 -78
  160. package/bundled/skills/refactor-planner/SKILL.md +0 -467
  161. package/bundled/skills/refactor-planner/assets/planning-guide.md +0 -291
  162. package/bundled/skills/refactor-planner/references/behavior-preservation.md +0 -187
  163. package/bundled/skills/refactor-planner/references/error-recovery.md +0 -45
  164. package/bundled/skills/refactor-planner/references/fast-path.md +0 -59
  165. package/bundled/skills/refactor-planner/references/generated-plan-review.md +0 -107
  166. package/bundled/skills/refactor-planner/references/planning-phases.md +0 -172
  167. package/bundled/skills/refactor-planner/references/refactor-scoping-guide.md +0 -230
  168. package/bundled/skills/refactor-planner/scripts/validate-and-generate-refactor.py +0 -1120
  169. package/bundled/skills/refactor-workflow/SKILL.md +0 -205
@@ -8,12 +8,20 @@ import shlex
8
8
  import shutil
9
9
  import subprocess
10
10
  from collections.abc import Mapping
11
- from dataclasses import dataclass
11
+ from dataclasses import dataclass, field
12
12
  from pathlib import Path
13
13
 
14
14
  from .launch_profiles import HeadlessLaunchProfile
15
15
  from .paths import RuntimePaths
16
- from .platform_detection import PlatformSelectionError, parse_platform_selection
16
+ from .platform_detection import (
17
+ CLI_BY_PLATFORM,
18
+ INSTALLED_MARKER_DIRS,
19
+ INSTALLED_PLATFORM_ORDER,
20
+ INSTALLED_SKILL_MARKERS,
21
+ PlatformSelectionError,
22
+ parse_platform_selection,
23
+ platform_from_command,
24
+ )
17
25
 
18
26
 
19
27
  @dataclass(frozen=True)
@@ -65,6 +73,7 @@ class RuntimeConfig:
65
73
  effort: str | None
66
74
  effort_validation: EffortValidationResult
67
75
  runtime_mode: str = "python-runtime-canonical"
76
+ env_values: Mapping[str, str] = field(default_factory=dict)
68
77
 
69
78
 
70
79
  AI_CLIENT_PRECEDENCE = (
@@ -177,50 +186,11 @@ def _cli_names_for_platform(platform: str | None) -> tuple[str, ...]:
177
186
  hosts = parse_platform_selection(normalized)
178
187
  except PlatformSelectionError:
179
188
  return ()
180
- cli_by_host = {
181
- "codex": ("codex",),
182
- "claude": ("claude",),
183
- "codebuddy": ("cbc",),
184
- "pi": ("pi",),
185
- "cursor": ("agent",),
186
- "antigravity": ("agy",),
187
- }
188
- names: list[str] = []
189
- for host in hosts:
190
- names.extend(cli_by_host[host])
191
- return tuple(names)
189
+ return tuple(CLI_BY_PLATFORM[host] for host in hosts)
192
190
 
193
191
 
194
192
  def _known_platform_from_cli(cli_command: str | None) -> str | None:
195
- if not cli_command or not cli_command.strip():
196
- return None
197
- raw = cli_command.strip()
198
- unquoted = raw[1:-1] if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in "'\"" else raw
199
- if len(unquoted) >= 3 and unquoted[1:3] in {":\\", ":/"} and unquoted.lower().endswith((".exe", ".cmd", ".bat")):
200
- token = unquoted
201
- else:
202
- try:
203
- token = shlex.split(raw)[0]
204
- except (ValueError, IndexError):
205
- token = raw.split()[0].strip("'\"")
206
- name = token.replace("\\", "/").rsplit("/", 1)[-1].lower()
207
- for suffix in (".exe", ".cmd", ".bat"):
208
- if name.endswith(suffix):
209
- name = name[: -len(suffix)]
210
- break
211
- if name == "claude":
212
- return "claude"
213
- if name == "codex":
214
- return "codex"
215
- if name == "pi":
216
- return "pi"
217
- if name == "agent":
218
- return "cursor"
219
- if name in {"agy", "antigravity"}:
220
- return "antigravity"
221
- if name in {"cbc", "codebuddy"}:
222
- return "codebuddy"
223
- return None
193
+ return platform_from_command(cli_command, allow_substring=False) or None
224
194
 
225
195
 
226
196
  def _concrete_platform(platform: str | None) -> str | None:
@@ -236,6 +206,8 @@ def _cursor_agent_is_verified(executable: str) -> bool:
236
206
  completed = subprocess.run(
237
207
  [executable, argument],
238
208
  text=True,
209
+ encoding="utf-8",
210
+ errors="replace",
239
211
  stdout=subprocess.PIPE,
240
212
  stderr=subprocess.STDOUT,
241
213
  check=False,
@@ -260,7 +232,7 @@ def _resolve_cli_name(cli_name: str, env: Mapping[str, str]) -> str | None:
260
232
  return None
261
233
  if cli_name == "agent" and not _cursor_agent_is_verified(resolved):
262
234
  return None
263
- return cli_name
235
+ return resolved if os.name == "nt" else cli_name
264
236
 
265
237
 
266
238
  def _cli_for_platform(platform: str | None, env: Mapping[str, str]) -> str | None:
@@ -328,30 +300,12 @@ def _installed_platform_cli(
328
300
  paths: RuntimePaths,
329
301
  env: Mapping[str, str],
330
302
  ) -> tuple[str | None, str | None]:
331
- if (paths.project_root / ".pi" / "skills" / "prizmkit" / "SKILL.md").is_file():
332
- resolved = _resolve_cli_name("pi", env)
333
- if resolved:
334
- return resolved, "installed-platform:pi"
335
- if (paths.project_root / ".agents" / "skills" / "prizmkit" / "SKILL.md").is_file():
336
- resolved = _resolve_cli_name("codex", env)
337
- if resolved:
338
- return resolved, "installed-platform:codex"
339
- if (paths.project_root / ".claude" / "commands" / "prizmkit.md").is_file():
340
- resolved = _resolve_cli_name("claude", env)
341
- if resolved:
342
- return resolved, "installed-platform:claude"
343
- if (paths.project_root / ".codebuddy" / "skills" / "prizmkit" / "SKILL.md").is_file():
344
- resolved = _resolve_cli_name("cbc", env)
345
- if resolved:
346
- return resolved, "installed-platform:codebuddy"
347
- if (paths.project_root / ".cursor" / "skills" / "prizmkit" / "SKILL.md").is_file():
348
- resolved = _resolve_cli_name("agent", env)
349
- if resolved:
350
- return resolved, "installed-platform:cursor"
351
- if (paths.project_root / ".agents" / "plugins" / "prizmkit" / "skills" / "prizmkit" / "SKILL.md").is_file():
352
- resolved = _resolve_cli_name("agy", env)
353
- if resolved:
354
- return resolved, "installed-platform:antigravity"
303
+ for platform in INSTALLED_PLATFORM_ORDER:
304
+ marker_path = paths.project_root / INSTALLED_SKILL_MARKERS[platform]
305
+ if marker_path.is_file():
306
+ resolved = _resolve_cli_name(CLI_BY_PLATFORM[platform], env)
307
+ if resolved:
308
+ return resolved, f"installed-platform:{platform}"
355
309
  return None, None
356
310
 
357
311
 
@@ -541,14 +495,7 @@ def load_runtime_config(paths: RuntimePaths, env: Mapping[str, str] | None = Non
541
495
  env_file=paths.prizmkit_dir / ".env",
542
496
  config_file=paths.prizmkit_dir / "config.json",
543
497
  manifest_file=paths.prizmkit_dir / "manifest.json",
544
- installed_platform_markers=(
545
- paths.project_root / ".codebuddy",
546
- paths.project_root / ".claude",
547
- paths.project_root / ".codex",
548
- paths.project_root / ".pi",
549
- paths.project_root / ".cursor",
550
- paths.project_root / ".agents" / "plugins" / "prizmkit",
551
- ),
498
+ installed_platform_markers=tuple(paths.project_root / rel for rel in INSTALLED_MARKER_DIRS),
552
499
  path_entries=_path_entries(runtime_env),
553
500
  sources=("environment", "prizmkit-env", "prizmkit-config", "installed-platform-markers", "PATH"),
554
501
  )
@@ -563,4 +510,5 @@ def load_runtime_config(paths: RuntimePaths, env: Mapping[str, str] | None = Non
563
510
  model=runtime_env.get("MODEL"),
564
511
  effort=effort,
565
512
  effort_validation=effort_validation,
513
+ env_values=dict(runtime_env),
566
514
  )
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import os
7
+ import re
7
8
  import shlex
8
9
  import subprocess
9
10
  import sys
@@ -12,13 +13,15 @@ from dataclasses import dataclass
12
13
  from datetime import datetime, timezone
13
14
  from pathlib import Path
14
15
 
15
- from .commands import CommandResult # type: ignore # runtime boundary import
16
- from .processes import ProcessSpec, is_pid_running, launch_process, terminate_pid_tree
16
+ from .atomic_io import write_json_atomic
17
+ from .processes import PidLockError, ProcessSpec, exclusive_pid_lock, is_pid_running, launch_process, terminate_pid_tree
18
+ from .results import CommandResult
17
19
  from .runner_models import RunnerFamily, family_for
18
20
 
19
21
 
20
22
  LOG_ROTATE_BYTES = 50 * 1024 * 1024
21
23
  START_VERIFY_SECONDS = 2.0
24
+ _ENV_KEY_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
22
25
 
23
26
 
24
27
  @dataclass(frozen=True)
@@ -29,6 +32,7 @@ class DaemonPaths:
29
32
  pid_file: Path
30
33
  log_file: Path
31
34
  meta_file: Path
35
+ start_lock: Path
32
36
 
33
37
 
34
38
  @dataclass(frozen=True)
@@ -52,30 +56,26 @@ class DaemonLogOptions:
52
56
  LIST_META_KEY_BY_KIND = {
53
57
  "feature": "feature_list",
54
58
  "bugfix": "bug_list",
55
- "refactor": "refactor_list",
56
59
  }
57
60
 
58
61
  ITEMS_KEY_BY_KIND = {
59
62
  "feature": "features",
60
63
  "bugfix": "bugs",
61
- "refactor": "refactors",
62
64
  }
63
65
 
64
66
  ID_KEY_BY_KIND = {
65
67
  "feature": "id",
66
68
  "bugfix": "id",
67
- "refactor": "id",
68
69
  }
69
70
 
70
71
  PROGRESS_COUNTS_BY_KIND = {
71
72
  "feature": ("completed", "in_progress", "failed", "pending", "skipped", "auto_skipped"),
72
73
  "bugfix": ("completed", "in_progress", "failed", "pending", "needs_info", "skipped", "auto_skipped"),
73
- "refactor": ("completed", "in_progress", "failed", "pending", "skipped", "auto_skipped"),
74
74
  }
75
75
 
76
76
 
77
77
  def run_daemon_command(kind: str, action: str, legacy_args: tuple[str, ...], paths) -> CommandResult:
78
- """Run a daemon lifecycle command for feature, bugfix, or refactor."""
78
+ """Run a daemon lifecycle command for feature or bugfix."""
79
79
  family = family_for(kind, paths)
80
80
  daemon_paths = _daemon_paths(family)
81
81
  if action == "start":
@@ -100,6 +100,7 @@ def _daemon_paths(family: RunnerFamily) -> DaemonPaths:
100
100
  pid_file=family.state_dir / ".pipeline.pid",
101
101
  log_file=family.state_dir / "pipeline-daemon.log",
102
102
  meta_file=family.state_dir / ".pipeline-meta.json",
103
+ start_lock=family.state_dir / ".daemon-start.lock",
103
104
  )
104
105
 
105
106
 
@@ -113,52 +114,78 @@ def _start(family: RunnerFamily, daemon_paths: DaemonPaths, legacy_args: tuple[s
113
114
  return CommandResult(2, f"Python {family.kind} daemon", stderr, stdout="", stderr=stderr)
114
115
 
115
116
  daemon_paths.state_dir.mkdir(parents=True, exist_ok=True)
116
- stale_warning = _clean_stale_pid(daemon_paths)
117
- stderr_lines = [stale_warning] if stale_warning else []
118
- running_pid = _read_pid(daemon_paths.pid_file)
119
- if is_pid_running(running_pid):
120
- message = f"Pipeline is already running (PID: {running_pid})"
121
- return CommandResult(1, f"Python {family.kind} daemon", message, stdout="", stderr=message)
122
-
123
- rotated = _rotate_log_if_needed(daemon_paths.log_file)
124
- if rotated:
125
- stderr_lines.append(f"Log rotated: {rotated}")
126
-
127
- started_at = _utc_iso()
128
- _write_log_separator(family, daemon_paths.log_file, list_path, started_at, options)
129
- command = _payload_command(family, paths, list_path, options)
130
- env = _daemon_env(options)
131
- spec = ProcessSpec(
132
- command=tuple(command),
133
- cwd=paths.project_root,
134
- environment_overrides=env,
135
- environment_unsets=("CLAUDECODE",),
136
- pid_file=daemon_paths.pid_file,
137
- )
138
- log_handle = daemon_paths.log_file.open("a", encoding="utf-8")
139
117
  try:
140
- handle = launch_process(spec, stdout=log_handle, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, text=True)
141
- finally:
142
- log_handle.close()
143
-
144
- pid = int(handle.pid or 0)
145
- _write_meta(family, daemon_paths.meta_file, pid, started_at, list_path, options, daemon_paths.log_file)
146
- time.sleep(_start_verify_seconds())
147
- if not is_pid_running(pid):
148
- daemon_paths.pid_file.unlink(missing_ok=True)
149
- message = f"Pipeline process died immediately after launch. Check log for errors: {daemon_paths.log_file}"
150
- return CommandResult(1, f"Python {family.kind} daemon", message, stdout="", stderr="\n".join([*stderr_lines, message]))
151
-
152
- stderr_lines.extend(
153
- [
154
- f"Launching {family.kind} pipeline...",
155
- f"{family.kind} list: {list_path}",
156
- f"Log file: {daemon_paths.log_file}",
157
- f"Pipeline started successfully (PID: {pid})",
158
- ]
159
- )
160
- payload = {"success": True, "pid": pid, "log_file": str(daemon_paths.log_file), "started_at": started_at}
161
- return CommandResult(0, f"Python {family.kind} daemon", "started", stdout=json.dumps(payload), stderr="\n".join(stderr_lines))
118
+ with exclusive_pid_lock(
119
+ daemon_paths.start_lock,
120
+ busy_message="Pipeline daemon start is already in progress (PID {pid})",
121
+ error_label="daemon start lock",
122
+ ):
123
+ stale_warning = _clean_stale_pid(daemon_paths)
124
+ stderr_lines = [stale_warning] if stale_warning else []
125
+ running_pid = _read_pid(daemon_paths.pid_file)
126
+ if is_pid_running(running_pid):
127
+ message = f"Pipeline is already running (PID: {running_pid})"
128
+ return CommandResult(1, f"Python {family.kind} daemon", message, stdout="", stderr=message)
129
+
130
+ rotated = _rotate_log_if_needed(daemon_paths.log_file)
131
+ if rotated:
132
+ stderr_lines.append(f"Log rotated: {rotated}")
133
+
134
+ started_at = _utc_iso()
135
+ _write_log_separator(family, daemon_paths.log_file, list_path, started_at, options)
136
+ command = _payload_command(family, paths, list_path, options)
137
+ env = _daemon_env(options)
138
+ spec = ProcessSpec(
139
+ command=tuple(command),
140
+ cwd=paths.project_root,
141
+ environment_overrides=env,
142
+ environment_unsets=("CLAUDECODE",),
143
+ pid_file=daemon_paths.pid_file,
144
+ detached=True,
145
+ )
146
+ with daemon_paths.log_file.open("a", encoding="utf-8") as log_handle:
147
+ handle = launch_process(spec, stdout=log_handle, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, text=True)
148
+
149
+ pid = int(handle.pid or 0)
150
+ _write_meta(family, daemon_paths.meta_file, pid, started_at, list_path, options, daemon_paths.log_file)
151
+ time.sleep(_start_verify_seconds())
152
+ exit_code = handle.popen.poll() if handle.popen is not None else None
153
+ if exit_code == 0:
154
+ daemon_paths.pid_file.unlink(missing_ok=True)
155
+ message = f"Pipeline process completed cleanly (exit 0) within startup window. Log: {daemon_paths.log_file}"
156
+ payload = {
157
+ "success": True,
158
+ "pid": pid,
159
+ "completed": True,
160
+ "exit_code": 0,
161
+ "log_file": str(daemon_paths.log_file),
162
+ "started_at": started_at,
163
+ }
164
+ return CommandResult(0, f"Python {family.kind} daemon", "completed", stdout=json.dumps(payload), stderr="\n".join([*stderr_lines, message]))
165
+ if exit_code is not None or not is_pid_running(pid):
166
+ daemon_paths.pid_file.unlink(missing_ok=True)
167
+ exit_label = f" (exit_code={exit_code})" if exit_code is not None else ""
168
+ message = f"Pipeline process died immediately after launch{exit_label}. Check log for errors: {daemon_paths.log_file}"
169
+ tail = _tail_lines(daemon_paths.log_file, 10)
170
+ failure_stderr = [*stderr_lines, message]
171
+ if tail:
172
+ failure_stderr.append("--- Last log lines ---")
173
+ failure_stderr.extend(tail)
174
+ return CommandResult(1, f"Python {family.kind} daemon", message, stdout="", stderr="\n".join(failure_stderr))
175
+
176
+ stderr_lines.extend(
177
+ [
178
+ f"Launching {family.kind} pipeline...",
179
+ f"{family.kind} list: {list_path}",
180
+ f"Log file: {daemon_paths.log_file}",
181
+ f"Pipeline started successfully (PID: {pid})",
182
+ ]
183
+ )
184
+ payload = {"success": True, "pid": pid, "log_file": str(daemon_paths.log_file), "started_at": started_at}
185
+ return CommandResult(0, f"Python {family.kind} daemon", "started", stdout=json.dumps(payload), stderr="\n".join(stderr_lines))
186
+ except PidLockError as exc:
187
+ message = str(exc)
188
+ return CommandResult(1, f"Python {family.kind} daemon", message, stdout="", stderr=message)
162
189
 
163
190
 
164
191
  def _status(family: RunnerFamily, daemon_paths: DaemonPaths) -> CommandResult:
@@ -174,6 +201,10 @@ def _status(family: RunnerFamily, daemon_paths: DaemonPaths) -> CommandResult:
174
201
  stderr_lines.append("Pipeline is not running")
175
202
  if daemon_paths.log_file.is_file():
176
203
  stderr_lines.append(f"Last log: {daemon_paths.log_file} ({daemon_paths.log_file.stat().st_size // 1024}KB)")
204
+ tail = _tail_lines(daemon_paths.log_file, 5)
205
+ if tail:
206
+ stderr_lines.append("--- Last 5 log lines ---")
207
+ stderr_lines.extend(tail)
177
208
  return CommandResult(1, f"Python {family.kind} daemon status", "not running", stdout=json.dumps({"running": False}), stderr="\n".join(stderr_lines))
178
209
 
179
210
  list_key = LIST_META_KEY_BY_KIND[family.kind]
@@ -239,7 +270,6 @@ def _logs(family: RunnerFamily, daemon_paths: DaemonPaths, legacy_args: tuple[st
239
270
 
240
271
 
241
272
  def _parse_start_args(family: RunnerFamily, legacy_args: tuple[str, ...]) -> DaemonStartOptions:
242
- list_path = family.plan_path
243
273
  env_overrides = ""
244
274
  features_filter = ""
245
275
  help_requested = False
@@ -249,10 +279,14 @@ def _parse_start_args(family: RunnerFamily, legacy_args: tuple[str, ...]) -> Dae
249
279
  arg = legacy_args[index]
250
280
  if arg in {"--help", "-h"}:
251
281
  help_requested = True
252
- elif arg == "--env" and index + 1 < len(legacy_args):
282
+ elif arg == "--env":
283
+ if index + 1 >= len(legacy_args):
284
+ raise ValueError("--env requires a KEY=VALUE string")
253
285
  index += 1
254
286
  env_overrides = legacy_args[index]
255
- elif arg == "--features" and index + 1 < len(legacy_args):
287
+ elif arg == "--features":
288
+ if index + 1 >= len(legacy_args):
289
+ raise ValueError("--features requires a value")
256
290
  index += 1
257
291
  features_filter = legacy_args[index]
258
292
  elif arg.startswith("-"):
@@ -260,9 +294,10 @@ def _parse_start_args(family: RunnerFamily, legacy_args: tuple[str, ...]) -> Dae
260
294
  else:
261
295
  positional.append(arg)
262
296
  index += 1
263
- if positional:
264
- list_path = Path(positional[0]).expanduser()
265
- return DaemonStartOptions(list_path=list_path, env_overrides=env_overrides, features_filter=features_filter, help_requested=help_requested)
297
+ options = DaemonStartOptions(list_path=Path(positional[0]).expanduser() if positional else family.plan_path, env_overrides=env_overrides, features_filter=features_filter, help_requested=help_requested)
298
+ if not options.help_requested:
299
+ _daemon_env(options)
300
+ return options
266
301
 
267
302
 
268
303
  def _parse_log_args(legacy_args: tuple[str, ...]) -> DaemonLogOptions:
@@ -302,11 +337,19 @@ def _payload_command(family: RunnerFamily, paths, list_path: Path, options: Daem
302
337
 
303
338
  def _daemon_env(options: DaemonStartOptions) -> dict[str, str]:
304
339
  env: dict[str, str] = {"PRIZMKIT_LIVE_OUTPUT": "0"}
305
- for token in shlex.split(options.env_overrides):
306
- if "=" in token:
307
- key, value = token.split("=", 1)
308
- if key:
309
- env[key] = value
340
+ if not options.env_overrides.strip():
341
+ return env
342
+ try:
343
+ tokens = shlex.split(options.env_overrides, posix=(os.name != "nt"))
344
+ except ValueError as exc:
345
+ raise ValueError(f"Invalid --env syntax: {exc}") from exc
346
+ for token in tokens:
347
+ if "=" not in token:
348
+ raise ValueError(f"Invalid --env token (expected KEY=VALUE): {token}")
349
+ key, value = token.split("=", 1)
350
+ if not _ENV_KEY_PATTERN.fullmatch(key):
351
+ raise ValueError(f"Invalid --env variable name: {key!r}")
352
+ env[key] = value
310
353
  return env
311
354
 
312
355
 
@@ -339,9 +382,7 @@ def _write_meta(family: RunnerFamily, path: Path, pid: int, started_at: str, lis
339
382
  "env_overrides": options.env_overrides,
340
383
  "log_file": str(log_file),
341
384
  }
342
- tmp = path.with_suffix(path.suffix + ".tmp")
343
- tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
344
- tmp.replace(path)
385
+ write_json_atomic(path, data)
345
386
 
346
387
 
347
388
  def _read_meta(path: Path) -> dict[str, object]:
@@ -412,7 +453,24 @@ def _tail_lines(path: Path, count: int) -> list[str]:
412
453
  if count <= 0 or not path.is_file():
413
454
  return []
414
455
  try:
415
- return path.read_text(encoding="utf-8", errors="replace").splitlines()[-count:]
456
+ with path.open("rb") as handle:
457
+ handle.seek(0, os.SEEK_END)
458
+ file_size = handle.tell()
459
+ if file_size == 0:
460
+ return []
461
+ chunk_size = 8192
462
+ position = file_size
463
+ chunks: list[bytes] = []
464
+ newlines_seen = 0
465
+ while position > 0 and newlines_seen <= count:
466
+ read_size = min(chunk_size, position)
467
+ position -= read_size
468
+ handle.seek(position, os.SEEK_SET)
469
+ chunk = handle.read(read_size)
470
+ chunks.append(chunk)
471
+ newlines_seen += chunk.count(b"\n")
472
+ text = b"".join(reversed(chunks)).decode("utf-8", errors="replace")
473
+ return text.splitlines()[-count:]
416
474
  except OSError:
417
475
  return []
418
476