prizmkit 1.1.191 → 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 (165) 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 +28 -44
  8. package/bundled/dev-pipeline/assets/feature-list-example.json +0 -1
  9. package/bundled/dev-pipeline/assets/skill-subagent-integration.md +6 -6
  10. package/bundled/dev-pipeline/prizmkit_runtime/atomic_io.py +48 -0
  11. package/bundled/dev-pipeline/prizmkit_runtime/checkpoint_state.py +66 -23
  12. package/bundled/dev-pipeline/prizmkit_runtime/cli.py +10 -7
  13. package/bundled/dev-pipeline/prizmkit_runtime/commands.py +2 -21
  14. package/bundled/dev-pipeline/prizmkit_runtime/config.py +48 -78
  15. package/bundled/dev-pipeline/prizmkit_runtime/daemon.py +127 -67
  16. package/bundled/dev-pipeline/prizmkit_runtime/gitops.py +158 -462
  17. package/bundled/dev-pipeline/prizmkit_runtime/heartbeat.py +102 -50
  18. package/bundled/dev-pipeline/prizmkit_runtime/interoperability.py +1 -25
  19. package/bundled/dev-pipeline/prizmkit_runtime/paths.py +0 -6
  20. package/bundled/dev-pipeline/prizmkit_runtime/platform_detection.py +47 -21
  21. package/bundled/dev-pipeline/prizmkit_runtime/processes.py +217 -156
  22. package/bundled/dev-pipeline/prizmkit_runtime/reset.py +39 -27
  23. package/bundled/dev-pipeline/prizmkit_runtime/reset_preserve.py +34 -174
  24. package/bundled/dev-pipeline/prizmkit_runtime/results.py +25 -0
  25. package/bundled/dev-pipeline/prizmkit_runtime/runner_bookkeeping.py +133 -110
  26. package/bundled/dev-pipeline/prizmkit_runtime/runner_classification.py +15 -5
  27. package/bundled/dev-pipeline/prizmkit_runtime/runner_models.py +1 -95
  28. package/bundled/dev-pipeline/prizmkit_runtime/runner_prompts.py +0 -2
  29. package/bundled/dev-pipeline/prizmkit_runtime/runner_status.py +7 -2
  30. package/bundled/dev-pipeline/prizmkit_runtime/runners.py +540 -262
  31. package/bundled/dev-pipeline/prizmkit_runtime/runtime_commit.py +175 -135
  32. package/bundled/dev-pipeline/prizmkit_runtime/runtime_helper.py +90 -9
  33. package/bundled/dev-pipeline/prizmkit_runtime/sessions.py +214 -133
  34. package/bundled/dev-pipeline/prizmkit_runtime/status.py +1 -3
  35. package/bundled/dev-pipeline/prizmkit_runtime/stream_progress.py +2783 -0
  36. package/bundled/dev-pipeline/prizmkit_runtime/task_checkout.py +27 -102
  37. package/bundled/dev-pipeline/prizmkit_runtime/test_result.py +58 -4
  38. package/bundled/dev-pipeline/scripts/check-session-status.py +56 -20
  39. package/bundled/dev-pipeline/scripts/continuation.py +8 -7
  40. package/bundled/dev-pipeline/scripts/detect-stuck.py +47 -33
  41. package/bundled/dev-pipeline/scripts/generate-bootstrap-prompt.py +13 -16
  42. package/bundled/dev-pipeline/scripts/generate-bugfix-prompt.py +20 -10
  43. package/bundled/dev-pipeline/scripts/init-bugfix-pipeline.py +10 -7
  44. package/bundled/dev-pipeline/scripts/init-change-artifact.py +25 -4
  45. package/bundled/dev-pipeline/scripts/init-pipeline.py +14 -69
  46. package/bundled/dev-pipeline/scripts/parse-stream-progress.py +31 -2616
  47. package/bundled/dev-pipeline/scripts/patch-completion-notes.py +4 -24
  48. package/bundled/dev-pipeline/scripts/prompt_framework.py +85 -20
  49. package/bundled/dev-pipeline/scripts/status_common.py +591 -0
  50. package/bundled/dev-pipeline/scripts/update-bug-status.py +85 -463
  51. package/bundled/dev-pipeline/scripts/update-checkpoint.py +254 -65
  52. package/bundled/dev-pipeline/scripts/update-feature-status.py +76 -509
  53. package/bundled/dev-pipeline/scripts/utils.py +5 -12
  54. package/bundled/dev-pipeline/templates/bootstrap-tier3.md +5 -5
  55. package/bundled/dev-pipeline/templates/bug-fix-list-schema.json +7 -0
  56. package/bundled/dev-pipeline/templates/bugfix-bootstrap-prompt.md +7 -7
  57. package/bundled/dev-pipeline/templates/sections/artifact-manifest.md +1 -1
  58. package/bundled/dev-pipeline/templates/sections/bugfix-phase-manual-verification.md +1 -1
  59. package/bundled/dev-pipeline/templates/sections/bugfix-phase-review.md +1 -1
  60. package/bundled/dev-pipeline/templates/sections/bugfix-phase-test.md +2 -1
  61. package/bundled/dev-pipeline/templates/sections/checkpoint-system.md +1 -1
  62. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-auto.md +1 -1
  63. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-opencli.md +2 -2
  64. package/bundled/dev-pipeline/templates/sections/phase-browser-verification.md +2 -2
  65. package/bundled/dev-pipeline/templates/sections/phase-prizmkit-test.md +2 -1
  66. package/bundled/dev-pipeline/templates/sections/phase-review-full.md +1 -1
  67. package/bundled/dev-pipeline/templates/sections/phase-specify-plan-full.md +3 -6
  68. package/bundled/dev-pipeline/templates/session-status-schema.json +2 -5
  69. package/bundled/skills/_metadata.json +9 -63
  70. package/bundled/skills/app-planner/SKILL.md +32 -303
  71. package/bundled/skills/app-planner/references/app-design-guide.md +0 -4
  72. package/bundled/skills/app-planner/references/generated-plan-review.md +2 -1
  73. package/bundled/skills/app-planner/references/project-brief-guide.md +14 -0
  74. package/bundled/skills/app-planner/references/project-conventions-discovery.md +4 -6
  75. package/bundled/skills/app-planner/references/project-state-detection.md +2 -3
  76. package/bundled/skills/bug-fix-workflow/SKILL.md +1 -2
  77. package/bundled/skills/bug-fix-workflow/references/bug-diagnosis.md +4 -7
  78. package/bundled/skills/bug-planner/SKILL.md +54 -435
  79. package/bundled/skills/bug-planner/references/generated-plan-review.md +3 -2
  80. package/bundled/skills/bug-planner/references/input-formats.md +32 -0
  81. package/bundled/skills/bugfix-pipeline-launcher/SKILL.md +4 -6
  82. package/bundled/skills/bugfix-pipeline-launcher/references/configuration.md +4 -28
  83. package/bundled/skills/feature-pipeline-launcher/SKILL.md +4 -6
  84. package/bundled/skills/feature-pipeline-launcher/references/configuration.md +4 -28
  85. package/bundled/skills/feature-planner/SKILL.md +60 -439
  86. package/bundled/skills/feature-planner/assets/planning-guide.md +1 -1
  87. package/bundled/skills/feature-planner/references/completeness-review.md +34 -0
  88. package/bundled/skills/feature-planner/references/decomposition-patterns.md +2 -2
  89. package/bundled/skills/feature-planner/references/error-recovery.md +1 -1
  90. package/bundled/skills/feature-planner/references/generated-plan-review.md +3 -2
  91. package/bundled/skills/feature-planner/references/incremental-feature-planning.md +3 -1
  92. package/bundled/skills/feature-workflow/SKILL.md +1 -2
  93. package/bundled/skills/prizmkit/SKILL.md +7 -1
  94. package/bundled/skills/prizmkit-code-review/SKILL.md +14 -6
  95. package/bundled/skills/prizmkit-code-review/references/independent-code-review.md +7 -4
  96. package/bundled/skills/prizmkit-code-review/references/review-report-template.md +16 -0
  97. package/bundled/skills/prizmkit-code-review/scripts/render_review_report.py +58 -20
  98. package/bundled/skills/prizmkit-implement/SKILL.md +1 -1
  99. package/bundled/skills/prizmkit-init/SKILL.md +24 -127
  100. package/bundled/skills/prizmkit-init/assets/project-brief-template.md +3 -3
  101. package/bundled/skills/prizmkit-plan/SKILL.md +6 -8
  102. package/bundled/skills/prizmkit-plan/references/clarify-guide.md +1 -1
  103. package/bundled/skills/prizmkit-plan/references/independent-plan-review.md +5 -2
  104. package/bundled/skills/prizmkit-plan/references/review-plan-spec-loop.md +6 -5
  105. package/bundled/skills/prizmkit-prizm-docs/SKILL.md +1 -13
  106. package/bundled/skills/prizmkit-prizm-docs/references/op-update.md +1 -1
  107. package/bundled/skills/prizmkit-retrospective/SKILL.md +6 -4
  108. package/bundled/skills/prizmkit-test/SKILL.md +25 -133
  109. package/bundled/skills/prizmkit-test/references/independent-test-review.md +5 -2
  110. package/bundled/skills/prizmkit-test/references/test-coverage-model.md +6 -0
  111. package/bundled/skills/prizmkit-workflow/SKILL.md +2 -3
  112. package/bundled/skills/prizmkit-workflow/references/workflow-state-protocol.md +4 -3
  113. package/bundled/skills/recovery-workflow/SKILL.md +7 -7
  114. package/bundled/skills/recovery-workflow/evals/evals.json +1 -1
  115. package/bundled/skills/recovery-workflow/references/detection.md +1 -3
  116. package/bundled/skills/recovery-workflow/scripts/detect-recovery-state.py +0 -6
  117. package/bundled/templates/project-memory-template.md +1 -2
  118. package/package.json +1 -1
  119. package/src/scaffold.js +28 -7
  120. package/bundled/dev-pipeline/SCHEMA_ANALYSIS.md +0 -53
  121. package/bundled/dev-pipeline/scripts/generate-refactor-prompt.py +0 -649
  122. package/bundled/dev-pipeline/scripts/init-refactor-pipeline.py +0 -463
  123. package/bundled/dev-pipeline/scripts/update-refactor-status.py +0 -1512
  124. package/bundled/dev-pipeline/templates/refactor-bootstrap-prompt.md +0 -240
  125. package/bundled/dev-pipeline/templates/refactor-list-schema.json +0 -266
  126. package/bundled/dev-pipeline/templates/sections/refactor-critical-paths.md +0 -15
  127. package/bundled/dev-pipeline/templates/sections/refactor-mission.md +0 -9
  128. package/bundled/dev-pipeline/templates/sections/refactor-phase-commit-report.md +0 -24
  129. package/bundled/dev-pipeline/templates/sections/refactor-phase-implement.md +0 -16
  130. package/bundled/dev-pipeline/templates/sections/refactor-phase-init.md +0 -9
  131. package/bundled/dev-pipeline/templates/sections/refactor-phase-plan.md +0 -22
  132. package/bundled/dev-pipeline/templates/sections/refactor-phase-review.md +0 -19
  133. package/bundled/dev-pipeline/templates/sections/refactor-phase-test.md +0 -24
  134. package/bundled/dev-pipeline/templates/sections/refactor-reminders.md +0 -12
  135. package/bundled/dev-pipeline/templates/sections/refactor-session-context.md +0 -6
  136. package/bundled/dev-pipeline/templates/sections/refactor-task-contract.md +0 -52
  137. package/bundled/dev-pipeline/tests/conftest.py +0 -29
  138. package/bundled/dev-pipeline/tests/live_ai_cli_log_smoke.py +0 -208
  139. package/bundled/dev-pipeline/tests/test_auto_skip.py +0 -1871
  140. package/bundled/dev-pipeline/tests/test_checkpoint_state.py +0 -1314
  141. package/bundled/dev-pipeline/tests/test_generate_bootstrap_prompt.py +0 -1712
  142. package/bundled/dev-pipeline/tests/test_generate_bugfix_prompt.py +0 -627
  143. package/bundled/dev-pipeline/tests/test_generate_refactor_prompt.py +0 -478
  144. package/bundled/dev-pipeline/tests/test_python_runner_parity.py +0 -5641
  145. package/bundled/dev-pipeline/tests/test_recovery_workflow.py +0 -322
  146. package/bundled/dev-pipeline/tests/test_repository_bootstrap.py +0 -252
  147. package/bundled/dev-pipeline/tests/test_reset_modes.py +0 -1208
  148. package/bundled/dev-pipeline/tests/test_reset_preserve.py +0 -957
  149. package/bundled/dev-pipeline/tests/test_runtime_commit.py +0 -1113
  150. package/bundled/dev-pipeline/tests/test_runtime_helper.py +0 -303
  151. package/bundled/dev-pipeline/tests/test_unified_cli.py +0 -5504
  152. package/bundled/dev-pipeline/tests/test_utils.py +0 -170
  153. package/bundled/skills/feature-planner/assets/evaluation-guide.md +0 -44
  154. package/bundled/skills/refactor-pipeline-launcher/SKILL.md +0 -219
  155. package/bundled/skills/refactor-pipeline-launcher/references/configuration.md +0 -78
  156. package/bundled/skills/refactor-planner/SKILL.md +0 -467
  157. package/bundled/skills/refactor-planner/assets/planning-guide.md +0 -291
  158. package/bundled/skills/refactor-planner/references/behavior-preservation.md +0 -187
  159. package/bundled/skills/refactor-planner/references/error-recovery.md +0 -45
  160. package/bundled/skills/refactor-planner/references/fast-path.md +0 -59
  161. package/bundled/skills/refactor-planner/references/generated-plan-review.md +0 -107
  162. package/bundled/skills/refactor-planner/references/planning-phases.md +0 -172
  163. package/bundled/skills/refactor-planner/references/refactor-scoping-guide.md +0 -230
  164. package/bundled/skills/refactor-planner/scripts/validate-and-generate-refactor.py +0 -1120
  165. package/bundled/skills/refactor-workflow/SKILL.md +0 -205
@@ -2,7 +2,10 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import ctypes
6
+ import json
5
7
  import os
8
+ import shutil
6
9
  import signal
7
10
  import subprocess
8
11
  import sys
@@ -13,6 +16,69 @@ from contextlib import contextmanager
13
16
  from dataclasses import dataclass, field
14
17
  from pathlib import Path
15
18
 
19
+ from .atomic_io import write_text_atomic
20
+
21
+
22
+ class PidLockError(RuntimeError):
23
+ """Raised when an exclusive PID directory lock is held or cannot be acquired."""
24
+
25
+
26
+ def _lock_owner_pid(lock_path: Path) -> int:
27
+ for _attempt in range(5):
28
+ try:
29
+ data = json.loads((lock_path / "owner.json").read_text(encoding="utf-8"))
30
+ return int(data.get("pid") or 0) if isinstance(data, dict) else 0
31
+ except FileNotFoundError:
32
+ time.sleep(0.01)
33
+ except (OSError, ValueError, json.JSONDecodeError):
34
+ return 0
35
+ return 0
36
+
37
+
38
+ def _remove_stale_pid_lock(lock_path: Path, error_label: str) -> None:
39
+ stale_path = lock_path.with_name(f"{lock_path.name}.stale-{os.getpid()}-{os.urandom(6).hex()}")
40
+ try:
41
+ os.rename(lock_path, stale_path)
42
+ except FileNotFoundError:
43
+ return
44
+ except OSError as exc:
45
+ raise PidLockError(f"Cannot claim stale {error_label} {lock_path}: {exc}") from exc
46
+ shutil.rmtree(stale_path, ignore_errors=True)
47
+
48
+
49
+ @contextmanager
50
+ def exclusive_pid_lock(
51
+ lock_path: Path,
52
+ *,
53
+ busy_message: str | None = None,
54
+ error_label: str = "lock",
55
+ ) -> Iterator[None]:
56
+ """Acquire an exclusive directory lock, reclaiming locks from exited PIDs."""
57
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
58
+ acquired = False
59
+ for _attempt in range(3):
60
+ try:
61
+ lock_path.mkdir()
62
+ acquired = True
63
+ break
64
+ except FileExistsError:
65
+ owner_pid = _lock_owner_pid(lock_path)
66
+ if is_pid_running(owner_pid):
67
+ message = busy_message or f"{error_label} is already held (PID {owner_pid})"
68
+ raise PidLockError(message.format(pid=owner_pid))
69
+ _remove_stale_pid_lock(lock_path, error_label)
70
+ except OSError as exc:
71
+ raise PidLockError(f"Cannot acquire {error_label} {lock_path}: {exc}") from exc
72
+ if not acquired:
73
+ raise PidLockError(f"Cannot acquire {error_label} {lock_path}")
74
+ try:
75
+ write_text_atomic(lock_path / "owner.json", json.dumps({"pid": os.getpid()}) + "\n")
76
+ yield
77
+ finally:
78
+ owner_pid = _lock_owner_pid(lock_path)
79
+ if owner_pid in {0, os.getpid()}:
80
+ shutil.rmtree(lock_path, ignore_errors=True)
81
+
16
82
 
17
83
  @dataclass(frozen=True)
18
84
  class InterruptionDetails:
@@ -98,6 +164,7 @@ class ProcessSpec:
98
164
  pid_file: Path | None = None
99
165
  stdin_text: str | None = None
100
166
  start_new_process_group: bool = True
167
+ detached: bool = False
101
168
 
102
169
 
103
170
  @dataclass(frozen=True)
@@ -153,20 +220,18 @@ def shield_interruption_signals() -> Iterator[None]:
153
220
  signal.signal(signal_number, handler)
154
221
 
155
222
 
156
- def _creationflags_for_platform(start_new_process_group: bool) -> int:
157
- if os.name != "nt" or not start_new_process_group:
223
+ def _creationflags_for_platform(start_new_process_group: bool, *, detached: bool = False) -> int:
224
+ if os.name != "nt":
158
225
  return 0
159
226
  flags = 0
160
- flags |= getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
227
+ if start_new_process_group:
228
+ flags |= getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
229
+ if detached:
230
+ flags |= getattr(subprocess, "DETACHED_PROCESS", 0)
231
+ flags |= getattr(subprocess, "CREATE_NO_WINDOW", 0)
161
232
  return flags
162
233
 
163
234
 
164
- def _preexec_fn_for_platform(start_new_process_group: bool):
165
- if os.name == "nt" or not start_new_process_group:
166
- return None
167
- return os.setsid
168
-
169
-
170
235
  def _process_env(overrides: Mapping[str, str], unsets: Sequence[str] = ()) -> dict[str, str]:
171
236
  env = dict(os.environ)
172
237
  for key in unsets:
@@ -183,8 +248,9 @@ def launch_process(
183
248
  stdin=subprocess.PIPE,
184
249
  text: bool = True,
185
250
  ) -> ProcessHandle:
186
- """Launch a child process with POSIX group or Windows process flags."""
251
+ """Launch a child process with POSIX session or Windows process flags."""
187
252
  spec.cwd.mkdir(parents=True, exist_ok=True)
253
+ text_kwargs = {"encoding": "utf-8", "errors": "replace"} if text else {}
188
254
  process = subprocess.Popen(
189
255
  [str(part) for part in spec.command],
190
256
  cwd=spec.cwd,
@@ -193,12 +259,12 @@ def launch_process(
193
259
  stdout=stdout,
194
260
  stderr=stderr,
195
261
  text=text,
196
- preexec_fn=_preexec_fn_for_platform(spec.start_new_process_group),
197
- creationflags=_creationflags_for_platform(spec.start_new_process_group),
262
+ start_new_session=(os.name != "nt" and spec.start_new_process_group),
263
+ creationflags=_creationflags_for_platform(spec.start_new_process_group, detached=spec.detached),
264
+ **text_kwargs,
198
265
  )
199
266
  if spec.pid_file is not None:
200
- spec.pid_file.parent.mkdir(parents=True, exist_ok=True)
201
- spec.pid_file.write_text(f"{process.pid}\n", encoding="utf-8")
267
+ write_text_atomic(spec.pid_file, f"{process.pid}\n")
202
268
  return ProcessHandle(pid=process.pid, spec=spec, status="running", popen=process)
203
269
 
204
270
 
@@ -206,96 +272,169 @@ def is_process_running(handle: ProcessHandle) -> bool:
206
272
  """Return true when the process appears alive."""
207
273
  if handle.popen is not None:
208
274
  return handle.popen.poll() is None
209
- if handle.pid is None:
210
- return False
275
+ return is_pid_running(handle.pid)
276
+
277
+
278
+ def _signal_posix_tree(pid: int, sig: int, label: str, details: list[str]) -> None:
211
279
  try:
212
- os.kill(handle.pid, 0)
213
- except OSError:
214
- return False
215
- return True
280
+ os.killpg(pid, sig)
281
+ details.append(f"{label}_process_group")
282
+ except OSError as exc:
283
+ details.append(f"{label}_group_failed={type(exc).__name__}")
284
+ try:
285
+ os.kill(pid, sig)
286
+ details.append(f"{label}_process")
287
+ except OSError as inner:
288
+ details.append(f"{label}_process_failed={type(inner).__name__}")
289
+
290
+
291
+ def _run_windows_taskkill(pid: int, *, force: bool) -> subprocess.CompletedProcess[str]:
292
+ command = ["taskkill", "/PID", str(pid), "/T"]
293
+ if force:
294
+ command.append("/F")
295
+ return subprocess.run(
296
+ command,
297
+ stdout=subprocess.PIPE,
298
+ stderr=subprocess.PIPE,
299
+ text=True,
300
+ encoding="utf-8",
301
+ errors="replace",
302
+ check=False,
303
+ )
216
304
 
217
305
 
218
- def terminate_process_tree(
219
- handle: ProcessHandle,
306
+ def _terminate_tree_impl(
307
+ pid: int,
308
+ *,
220
309
  reason: str,
221
- grace_seconds: float = 10.0,
310
+ grace_seconds: float,
311
+ process: subprocess.Popen[str] | None = None,
222
312
  ) -> ProcessTerminationResult:
223
- """Terminate a process tree without relying on shell runtime logic.
224
-
225
- POSIX uses the process group created at launch. Windows uses taskkill-style
226
- tree termination when available. Both paths are best effort and safe for
227
- tests with short-lived fake processes.
228
- """
229
- pid = handle.pid
230
- if pid is None:
231
- return ProcessTerminationResult(pid=None, reason=reason, terminated=False, forced=False, return_code=None)
232
-
313
+ still_running = (lambda: process.poll() is None) if process is not None else (lambda: is_pid_running(pid))
233
314
  details: list[str] = []
234
315
  forced = False
235
- process = handle.popen
316
+ taskkill_ok = False
317
+ grace = max(0.0, grace_seconds)
236
318
 
237
319
  if os.name == "nt":
238
- completed = subprocess.run(
239
- ["taskkill", "/PID", str(pid), "/T", "/F"],
240
- stdout=subprocess.PIPE,
241
- stderr=subprocess.PIPE,
242
- text=True,
243
- check=False,
244
- )
245
- details.append(f"taskkill_exit={completed.returncode}")
246
- forced = True
320
+ if grace > 0:
321
+ completed = _run_windows_taskkill(pid, force=False)
322
+ details.append(f"taskkill_graceful_exit={completed.returncode}")
323
+ deadline = time.monotonic() + grace
324
+ while still_running() and time.monotonic() < deadline:
325
+ time.sleep(0.05)
326
+ if still_running():
327
+ forced = True
328
+ completed = _run_windows_taskkill(pid, force=True)
329
+ details.append(f"taskkill_exit={completed.returncode}")
330
+ taskkill_ok = completed.returncode == 0
331
+ if not taskkill_ok:
332
+ force_deadline = time.monotonic() + min(grace, 2.0)
333
+ while still_running() and time.monotonic() < force_deadline:
334
+ time.sleep(0.05)
335
+ else:
336
+ forced = True
337
+ completed = _run_windows_taskkill(pid, force=True)
338
+ details.append(f"taskkill_exit={completed.returncode}")
339
+ taskkill_ok = completed.returncode == 0
340
+ if not taskkill_ok:
341
+ force_deadline = time.monotonic() + 2.0
342
+ while still_running() and time.monotonic() < force_deadline:
343
+ time.sleep(0.05)
247
344
  else:
248
- try:
249
- os.killpg(pid, signal.SIGTERM)
250
- details.append("sigterm_process_group")
251
- except ProcessLookupError:
252
- pass
253
- except OSError as exc:
254
- details.append(f"sigterm_group_failed={type(exc).__name__}")
255
- try:
256
- os.kill(pid, signal.SIGTERM)
257
- details.append("sigterm_process")
258
- except OSError as inner:
259
- details.append(f"sigterm_process_failed={type(inner).__name__}")
260
-
261
- deadline = time.monotonic() + max(0.0, grace_seconds)
262
- while process is not None and process.poll() is None and time.monotonic() < deadline:
345
+ _signal_posix_tree(pid, signal.SIGTERM, "sigterm", details)
346
+ deadline = time.monotonic() + grace
347
+ while still_running() and time.monotonic() < deadline:
263
348
  time.sleep(0.05)
264
- if process is not None and process.poll() is None:
349
+ if still_running():
265
350
  forced = True
266
- try:
267
- os.killpg(pid, signal.SIGKILL)
268
- details.append("sigkill_process_group")
269
- except ProcessLookupError:
270
- pass
271
- except OSError as exc:
272
- details.append(f"sigkill_group_failed={type(exc).__name__}")
273
- try:
274
- os.kill(pid, signal.SIGKILL)
275
- details.append("sigkill_process")
276
- except OSError as inner:
277
- details.append(f"sigkill_process_failed={type(inner).__name__}")
351
+ _signal_posix_tree(pid, signal.SIGKILL, "sigkill", details)
352
+ if grace > 0:
353
+ force_deadline = time.monotonic() + min(grace, 2.0)
354
+ while still_running() and time.monotonic() < force_deadline:
355
+ time.sleep(0.05)
278
356
 
279
357
  return_code = None
280
358
  if process is not None:
281
359
  try:
282
- return_code = process.wait(timeout=max(0.1, grace_seconds))
360
+ return_code = process.wait(timeout=max(0.1, grace))
283
361
  except subprocess.TimeoutExpired:
284
362
  return_code = process.poll()
363
+
364
+ terminated = (taskkill_ok or (not still_running())) if os.name == "nt" else (not still_running())
285
365
  return ProcessTerminationResult(
286
366
  pid=pid,
287
367
  reason=reason,
288
- terminated=True,
368
+ terminated=terminated,
289
369
  forced=forced,
290
370
  return_code=return_code,
291
371
  details=tuple(details),
292
372
  )
293
373
 
294
374
 
375
+ def terminate_process_tree(
376
+ handle: ProcessHandle,
377
+ reason: str,
378
+ grace_seconds: float = 10.0,
379
+ ) -> ProcessTerminationResult:
380
+ """Terminate a process tree without relying on shell runtime logic.
381
+
382
+ POSIX uses the process group/session created at launch. Windows tries
383
+ graceful taskkill before forced ``taskkill /T /F`` when grace > 0.
384
+ """
385
+ pid = handle.pid
386
+ if pid is None:
387
+ return ProcessTerminationResult(pid=None, reason=reason, terminated=False, forced=False, return_code=None)
388
+ return _terminate_tree_impl(pid, reason=reason, grace_seconds=grace_seconds, process=handle.popen)
389
+
390
+
391
+ def _windows_pid_running(pid: int) -> bool:
392
+ win_dll = getattr(ctypes, "WinDLL", None)
393
+ if win_dll is None:
394
+ try:
395
+ os.kill(pid, 0)
396
+ except PermissionError:
397
+ return True
398
+ except OSError:
399
+ return False
400
+ return True
401
+ kernel32 = win_dll("kernel32", use_last_error=True)
402
+ kernel32.OpenProcess.argtypes = [ctypes.c_uint32, ctypes.c_int, ctypes.c_uint32]
403
+ kernel32.OpenProcess.restype = ctypes.c_void_p
404
+ kernel32.GetExitCodeProcess.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint32)]
405
+ kernel32.GetExitCodeProcess.restype = ctypes.c_int
406
+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
407
+ kernel32.CloseHandle.restype = ctypes.c_int
408
+ process_query_limited_information = 0x1000
409
+ still_active = 259
410
+ error_access_denied = 5
411
+ handle = kernel32.OpenProcess(process_query_limited_information, False, int(pid))
412
+ if not handle:
413
+ return ctypes.get_last_error() == error_access_denied
414
+ try:
415
+ exit_code = ctypes.c_uint32()
416
+ if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)):
417
+ return False
418
+ return exit_code.value == still_active
419
+ finally:
420
+ kernel32.CloseHandle(handle)
421
+
422
+
295
423
  def is_pid_running(pid: int | None) -> bool:
296
424
  """Return true when a PID appears alive."""
297
425
  if pid is None or pid <= 0:
298
426
  return False
427
+ if os.name == "nt":
428
+ return _windows_pid_running(pid)
429
+ try:
430
+ waited_pid, _status = os.waitpid(pid, os.WNOHANG)
431
+ except ChildProcessError:
432
+ pass
433
+ except OSError:
434
+ pass
435
+ else:
436
+ if waited_pid == pid:
437
+ return False
299
438
  try:
300
439
  os.kill(pid, 0)
301
440
  except ProcessLookupError:
@@ -304,15 +443,6 @@ def is_pid_running(pid: int | None) -> bool:
304
443
  return True
305
444
  except OSError:
306
445
  return False
307
- if os.name != "nt":
308
- try:
309
- waited_pid, _status = os.waitpid(pid, os.WNOHANG)
310
- except ChildProcessError:
311
- return True
312
- except OSError:
313
- return True
314
- if waited_pid == pid:
315
- return False
316
446
  return True
317
447
 
318
448
 
@@ -321,83 +451,19 @@ def terminate_pid_tree(
321
451
  reason: str,
322
452
  grace_seconds: float = 10.0,
323
453
  ) -> ProcessTerminationResult:
324
- """Terminate a PID-backed process tree without requiring a live Popen.
325
-
326
- Daemon stop commands reconstruct process state from a PID file, so the
327
- original ``subprocess.Popen`` object is not available. POSIX daemons are
328
- launched in a process group whose id is the daemon PID; Windows uses the
329
- same taskkill-style tree termination strategy as ``terminate_process_tree``.
330
- """
454
+ """Terminate a PID-backed process tree without requiring a live Popen."""
331
455
  if pid is None or pid <= 0:
332
456
  return ProcessTerminationResult(pid=pid, reason=reason, terminated=False, forced=False, return_code=None)
333
-
334
- details: list[str] = []
335
- forced = False
336
457
  if not is_pid_running(pid):
337
- return ProcessTerminationResult(pid=pid, reason=reason, terminated=False, forced=False, return_code=None, details=("not_running",))
338
-
339
- if os.name == "nt":
340
- completed = subprocess.run(
341
- ["taskkill", "/PID", str(pid), "/T", "/F"],
342
- stdout=subprocess.PIPE,
343
- stderr=subprocess.PIPE,
344
- text=True,
345
- check=False,
346
- )
347
- details.append(f"taskkill_exit={completed.returncode}")
348
458
  return ProcessTerminationResult(
349
459
  pid=pid,
350
460
  reason=reason,
351
- terminated=completed.returncode == 0,
352
- forced=True,
461
+ terminated=False,
462
+ forced=False,
353
463
  return_code=None,
354
- details=tuple(details),
464
+ details=("not_running",),
355
465
  )
356
-
357
- try:
358
- os.killpg(pid, signal.SIGTERM)
359
- details.append("sigterm_process_group")
360
- except ProcessLookupError:
361
- pass
362
- except OSError as exc:
363
- details.append(f"sigterm_group_failed={type(exc).__name__}")
364
- try:
365
- os.kill(pid, signal.SIGTERM)
366
- details.append("sigterm_process")
367
- except OSError as inner:
368
- details.append(f"sigterm_process_failed={type(inner).__name__}")
369
-
370
- deadline = time.monotonic() + max(0.0, grace_seconds)
371
- while is_pid_running(pid) and time.monotonic() < deadline:
372
- time.sleep(0.05)
373
-
374
- if is_pid_running(pid):
375
- forced = True
376
- try:
377
- os.killpg(pid, signal.SIGKILL)
378
- details.append("sigkill_process_group")
379
- except ProcessLookupError:
380
- pass
381
- except OSError as exc:
382
- details.append(f"sigkill_group_failed={type(exc).__name__}")
383
- try:
384
- os.kill(pid, signal.SIGKILL)
385
- details.append("sigkill_process")
386
- except OSError as inner:
387
- details.append(f"sigkill_process_failed={type(inner).__name__}")
388
-
389
- deadline = time.monotonic() + max(0.0, min(grace_seconds, 2.0))
390
- while is_pid_running(pid) and time.monotonic() < deadline:
391
- time.sleep(0.05)
392
-
393
- return ProcessTerminationResult(
394
- pid=pid,
395
- reason=reason,
396
- terminated=not is_pid_running(pid),
397
- forced=forced,
398
- return_code=None,
399
- details=tuple(details),
400
- )
466
+ return _terminate_tree_impl(pid, reason=reason, grace_seconds=grace_seconds)
401
467
 
402
468
 
403
469
 
@@ -457,8 +523,3 @@ def platform_termination_strategy() -> tuple[str, ...]:
457
523
  if os.name == "nt":
458
524
  return ("CREATE_NEW_PROCESS_GROUP", "taskkill /PID <pid> /T /F")
459
525
  return ("setsid", "killpg(SIGTERM)", "killpg(SIGKILL)")
460
-
461
-
462
- def describe_command(command: Sequence[str]) -> str:
463
- """Return a deterministic command description for tests."""
464
- return " ".join(str(part) for part in command)
@@ -7,23 +7,19 @@ import re
7
7
  import subprocess
8
8
  import sys
9
9
  from collections.abc import Sequence
10
+ from contextlib import ExitStack
10
11
  from dataclasses import dataclass
11
12
  from pathlib import Path
12
13
 
13
- from .commands import CommandResult # type: ignore # runtime boundary import
14
14
  from .gitops import (
15
- BranchContext,
16
- WorktreePolicy,
17
15
  default_branch,
18
- guarded_worktree_remove,
19
16
  list_reset_branches,
17
+ local_branch_exists,
20
18
  reset_cleanup_branch,
21
- worktree_runtime_context,
22
19
  )
20
+ from .results import CommandResult
23
21
  from .runner_models import RunnerFamily, family_for
24
22
  from .task_checkout import (
25
- CHECKOUT_MODE_WORKTREE,
26
- TaskCheckout,
27
23
  load_task_checkout,
28
24
  mark_task_checkout_reset_locked,
29
25
  task_checkout_guard,
@@ -60,7 +56,6 @@ class ResetItem:
60
56
  FAMILY_LABELS = {
61
57
  "feature": "feature",
62
58
  "bugfix": "bug",
63
- "refactor": "refactor",
64
59
  }
65
60
 
66
61
  FILTER_FLAGS = {
@@ -73,21 +68,18 @@ FILTER_FLAGS = {
73
68
  ID_FIELD_BY_KIND = {
74
69
  "feature": "id",
75
70
  "bugfix": "id",
76
- "refactor": "id",
77
71
  }
78
72
 
79
73
 
80
74
  TITLE_FIELD_BY_KIND = {
81
75
  "feature": "title",
82
76
  "bugfix": "title",
83
- "refactor": "title",
84
77
  }
85
78
 
86
79
 
87
80
  BRANCH_PREFIX_BY_KIND = {
88
81
  "feature": "dev",
89
82
  "bugfix": "bugfix",
90
- "refactor": "refactor",
91
83
  }
92
84
 
93
85
  STALLED_FILTER_STATUSES = {
@@ -100,7 +92,7 @@ STALLED_FILTER_STATUSES = {
100
92
 
101
93
 
102
94
  def run_reset_command(kind: str, legacy_args: tuple[str, ...], paths) -> CommandResult:
103
- """Run a manual reset command for feature, bugfix, or refactor."""
95
+ """Run a manual reset command for feature or bugfix."""
104
96
  family = family_for(kind, paths)
105
97
  try:
106
98
  options = _parse_reset_args(family, legacy_args)
@@ -147,7 +139,28 @@ def run_reset_command(kind: str, legacy_args: tuple[str, ...], paths) -> Command
147
139
  stdout=text,
148
140
  )
149
141
  if options.state_only:
150
- state_result = _run_state_only_updater(family, options, paths.project_root)
142
+ guard_ids: list[str] = []
143
+ if options.item_id:
144
+ guard_ids.append(options.item_id)
145
+ elif family.state_dir.is_dir():
146
+ guard_ids.extend(
147
+ sorted(
148
+ entry.name
149
+ for entry in family.state_dir.iterdir()
150
+ if entry.is_dir() and not entry.name.startswith(".")
151
+ )
152
+ )
153
+ try:
154
+ with ExitStack() as stack:
155
+ for gid in guard_ids:
156
+ stack.enter_context(task_checkout_guard(family.state_dir, gid))
157
+ state_result = _run_state_only_updater(family, options, paths.project_root)
158
+ except RuntimeError as exc:
159
+ return CommandResult(
160
+ 1,
161
+ f"Python {kind} reset --state-only",
162
+ f"ERROR: Reset could not acquire checkout lifecycle: {exc}",
163
+ )
151
164
  text = state_result.stdout.strip() or state_result.stderr.strip() or "State-only reset failed"
152
165
  ok = state_result.returncode == 0 and _json_without_error(state_result.stdout)
153
166
  return CommandResult(
@@ -373,25 +386,20 @@ def _reset_one(family: RunnerFamily, item: ResetItem, options: ResetOptions, pro
373
386
  lines.append(f"Current status: {item.status} (no runtime state file)")
374
387
 
375
388
  checkout = load_task_checkout(family.state_dir, family.task_type, item.item_id)
389
+ effective_return_branch = return_branch
390
+ if (
391
+ checkout is not None
392
+ and checkout.base_branch
393
+ and local_branch_exists(project_root, checkout.base_branch)
394
+ ):
395
+ effective_return_branch = checkout.base_branch
376
396
  branches = list(list_reset_branches(project_root, BRANCH_PREFIX_BY_KIND[family.kind], item.item_id))
377
397
  if checkout is not None and (checkout.is_active or checkout.is_completed):
378
398
  if checkout.active_dev_branch not in branches:
379
399
  branches.insert(0, checkout.active_dev_branch)
380
- if checkout.checkout_mode == CHECKOUT_MODE_WORKTREE:
381
- runtime = worktree_runtime_context(
382
- BranchContext(checkout.base_branch, checkout.active_dev_branch, project_root),
383
- WorktreePolicy(True, True, True, Path(checkout.worktree_path).parent),
384
- )
385
- if runtime.worktree_path != Path(checkout.worktree_path).resolve():
386
- lines.append(f"ERROR: Reset {item.item_id} worktree identity resolves to an unexpected path")
387
- return False
388
- removal = guarded_worktree_remove(runtime, delete_branch=False)
389
- if not removal.ok:
390
- lines.append(f"ERROR: Reset {item.item_id} could not remove linked worktree: {removal.reason}")
391
- return False
392
400
 
393
401
  for branch in branches:
394
- cleanup = reset_cleanup_branch(project_root, branch, return_branch=return_branch, delete=options.clean)
402
+ cleanup = reset_cleanup_branch(project_root, branch, return_branch=effective_return_branch, delete=options.clean)
395
403
  if getattr(cleanup, "checkout_discarded", False):
396
404
  lines.append(f"Discarded uncommitted changes on current dev branch: {cleanup.branch}")
397
405
  elif getattr(cleanup, "branch_preserved", False):
@@ -524,7 +532,11 @@ def _slug_for_item(family: RunnerFamily, item_id: str, title: str) -> str:
524
532
 
525
533
 
526
534
  def _looks_like_item_id(value: str, prefix: str) -> bool:
527
- return value.upper().startswith(prefix.upper())
535
+ return (
536
+ ":" not in value
537
+ and value.upper().startswith(prefix.upper())
538
+ and bool(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]*", value[len(prefix) :]))
539
+ )
528
540
 
529
541
 
530
542
  def _looks_like_range(value: str, prefix: str) -> bool: