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,5 +1,5 @@
1
1
  {
2
- "frameworkVersion": "1.1.192",
3
- "bundledAt": "2026-11-20T11:42:56.779Z",
4
- "bundledFrom": "abe9a23"
2
+ "frameworkVersion": "1.1.193",
3
+ "bundledAt": "2026-11-20T17:06:40.257Z",
4
+ "bundledFrom": "0d8a62e"
5
5
  }
@@ -502,33 +502,22 @@ Imported by all Python scripts. Provides:
502
502
 
503
503
  ## Python Runtime Modules
504
504
 
505
- ### `prizmkit_runtime/config.py` — CLI Detection & Shared Helpers
505
+ ### `prizmkit_runtime/config.py` — AI CLI & Environment Resolution
506
506
 
507
- Sourced by daemon and runner scripts. Provides:
507
+ Provides `load_runtime_config()`, `load_env_file()`, and `resolve_ai_client()`. Precedence: `AI_CLI` env > `config.json` `ai_cli` > manifest/config platform (`manifest:platform` > `config:platform`) > `CODEBUDDY_CLI` > installed PrizmKit artifacts > `PATH`. `load_env_file()` ignores `#` comment suffixes only outside quotes and stores normalized `effort` from `validate_effort()`.
508
508
 
509
- | Function | Description |
510
- |----------|-------------|
511
- | `prizm_detect_cli_and_platform()` | Sets `CLI_CMD` and `PLATFORM`. Priority: `AI_CLI` env > `config.json` `ai_cli` > manifest/config platform > `CODEBUDDY_CLI` > installed PrizmKit artifacts > PATH |
512
- | `prizm_check_common_dependencies(cli_cmd)` | Verifies jq, python3, and CLI are installed |
513
-
514
- Also exports: `log_info`, `log_warn`, `log_error`, `log_success` (with timestamps), and color constants.
515
-
516
- ### `prizmkit_runtime/gitops.py` — Git Branch Lifecycle
509
+ ### `prizmkit_runtime/gitops.py` — Git Repository & Branch Lifecycle
517
510
 
518
511
  | Function | Description |
519
512
  |----------|-------------|
520
- | `branch_create(project_root, branch_name, source_branch)` | Create & checkout feature branch. Reuses if exists. Returns 0/1. |
521
- | `branch_return(project_root, original_branch)` | Checkout back to original branch |
513
+ | `ensure_git_repository(project_root)` / `ensure_branch_has_commit(project_root)` | Initialize Git automatically when invoked outside a repository and create an initial commit with fallback Git identity when needed |
514
+ | `safe_task_branch_prefix(project_root, nominal)` | Avoid Git D/F ref collisions when an existing branch equals or shares a prefix with the nominal task prefix |
515
+ | `branch_create_plan(context)` / `branch_ensure_return(project_root, base, task)` | Create/reuse task branch cleanly and return to the original non-task `base_branch` without hardcoding `main` |
516
+ | `branch_merge_plan(context, ...)` | Fast-forward or rebase + merge task branch back into `base_branch` with fallback Git identity injected for commit/rebase/merge |
522
517
 
523
- ### `prizmkit_runtime/heartbeat.py` — Heartbeat & Progress Monitoring
518
+ ### `prizmkit_runtime/heartbeat.py` & `sessions.py` — Session I/O & Heartbeat Monitoring
524
519
 
525
- | Function | Description |
526
- |----------|-------------|
527
- | `start_heartbeat(cli_pid, session_log, progress_json, interval)` | Start background heartbeat monitor. Sets `_HEARTBEAT_PID`. |
528
- | `stop_heartbeat(heartbeat_pid)` | Kill heartbeat process |
529
- | `start_progress_parser(session_log, progress_json, scripts_dir)` | Spawn `parse-stream-progress.py` if stream-json supported. Sets `_PARSER_PID`. |
530
- | `stop_progress_parser(parser_pid)` | Kill parser process |
531
- | `detect_stream_json_support(cli_cmd)` | Sets `USE_STREAM_JSON=true\|false` |
520
+ `AISessionLauncher` starts the log reader thread and `HeartbeatMonitor` (which initializes `logs/heartbeat.json` with valid JSON atomically) before streaming prompt text on a daemon `stdin` writer thread, and terminates child process trees cleanly on interruption or launcher errors. `detect_stream_json_support(cli_cmd, platform)` verifies provider `stream-json` capabilities before mutating repository state.
532
521
 
533
522
  ---
534
523
 
@@ -889,22 +878,26 @@ cli.py run bugfix command
889
878
  +-- README.md # This file
890
879
  +-- .gitignore # Ignores .prizmkit/state/, __pycache__/
891
880
  |
892
- +-- lib/
893
- | +-- common.sh # CLI detection, deps check, logging helpers
894
- | +-- branch.sh # Git branch create/return lifecycle
895
- | +-- heartbeat.sh # Heartbeat monitor + progress parser management
881
+ +-- prizmkit_runtime/ # Canonical Python runtime modules
882
+ | +-- gitops.py # Repo auto-init, fallback Git identity, branch create/return/merge
883
+ | +-- runners.py # Foreground sequential execution loop
884
+ | +-- runtime_commit.py # Request validation, commit finalization, state/metadata exclusions
885
+ | +-- reset.py / reset_preserve.py # Explicit state-only, fresh-checkout, clean, and preserve-runtime recovery
886
+ | +-- sessions.py / heartbeat.py # Subprocess launch, stdin writer, reader, JSON heartbeat monitor
887
+ | +-- daemon.py / processes.py # Background daemon lifecycle & cross-platform PID/tree cleanup
896
888
  |
897
889
  +-- scripts/
898
- | +-- utils.py # Shared Python utilities (JSON I/O, logging)
890
+ | +-- utils.py # Shared Python utilities (atomic JSON I/O, logging)
899
891
  | +-- init-pipeline.py # Validate .prizmkit/plans/feature-list.json + create .prizmkit/state/features/
900
892
  | +-- init-bugfix-pipeline.py # Validate .prizmkit/plans/bug-fix-list.json + create .prizmkit/state/bugfix/
901
- | +-- init-change-artifact.py # Create .prizmkit/specs/{slug}/ directories
893
+ | +-- init-change-artifact.py # Create .prizmkit/specs/{slug}/ directories safely
902
894
  | +-- generate-bootstrap-prompt.py # Render feature session prompt from template
903
895
  | +-- generate-bugfix-prompt.py # Render bugfix session prompt from template
904
896
  | +-- check-session-status.py # Parse session-status.json outcome
905
- | +-- update-feature-status.py # Feature state machine (8 actions)
906
- | +-- update-bug-status.py # Bug state machine (6 actions)
907
- | +-- detect-stuck.py # Detect stuck/stale features
897
+ | +-- update-checkpoint.py # Validate and atomically update workflow-checkpoint.json
898
+ | +-- update-feature-status.py # Feature state machine
899
+ | +-- update-bug-status.py # Bug state machine
900
+ | +-- detect-stuck.py # Detect stuck/stale sessions (logs/heartbeat.json & last_seen_epoch)
908
901
  | +-- parse-stream-progress.py # Real-time stream-json progress parser
909
902
  |
910
903
  +-- templates/
@@ -920,11 +913,7 @@ cli.py run bugfix command
920
913
  | +-- feature-list-example.json # Example feature list
921
914
  | +-- skill-subagent-integration.md # Pipeline + skill-owned subagent integration docs
922
915
  |
923
- +-- tests/
924
- | +-- conftest.py # Pytest configuration
925
- | +-- test_generate_bootstrap_prompt.py # Tests for prompt generation
926
- | +-- test_generate_bugfix_prompt.py # Tests for bugfix prompt generation
927
- | +-- test_utils.py # Tests for shared utilities
916
+ +-- tests/ # Repository pytest suite (excluded from installed bundled package)
928
917
  |
929
918
  +-- .prizmkit/state/features/ # Feature pipeline runtime state (gitignored)
930
919
  | +-- pipeline.json
@@ -117,7 +117,6 @@
117
117
  "tech_stack": "Next.js 14 + Express.js + PostgreSQL + Prisma ORM",
118
118
  "design_system": "shadcn/ui + Tailwind CSS",
119
119
  "testing_strategy": "Jest (unit) + Playwright (e2e)",
120
- "deployment": "Docker + Vercel (frontend) + Railway (backend)",
121
120
  "language": "TypeScript"
122
121
  }
123
122
  }
@@ -66,6 +66,9 @@ Located at `.prizmkit/dev-pipeline/scripts/`:
66
66
  | `check-session-status.py` | Read and validate session-status output |
67
67
  | `detect-stuck.py` | Detect stuck or stale pipeline sessions |
68
68
  | `parse-stream-progress.py` | Parse AI CLI output stream for progress tracking |
69
+ | `update-checkpoint.py` | Validate and atomically update `workflow-checkpoint.json` steps and semantic state |
70
+ | `patch-completion-notes.py` | Patch completion notes onto plan items |
71
+ | `prizmkit-runtime-helper.py` | Helper CLI for platform/port/process/checkpoint text checks |
69
72
  | `utils.py` | Shared utility functions for pipeline scripts |
70
73
 
71
74
  ## Session Lifecycle
@@ -106,6 +106,28 @@ class RuntimeConfigError(ValueError):
106
106
  """Raised when runtime configuration cannot be represented safely."""
107
107
 
108
108
 
109
+ def _strip_env_comment(line: str) -> str:
110
+ """Strip an unquoted `#` comment suffix from a single env line."""
111
+ quote_char: str | None = None
112
+ escaped = False
113
+ for index, char in enumerate(line):
114
+ if escaped:
115
+ escaped = False
116
+ continue
117
+ if char == "\\" and quote_char == '"':
118
+ escaped = True
119
+ continue
120
+ if char in ("'", '"'):
121
+ if quote_char is None:
122
+ quote_char = char
123
+ elif quote_char == char:
124
+ quote_char = None
125
+ continue
126
+ if char == "#" and quote_char is None:
127
+ return line[:index].strip()
128
+ return line.strip()
129
+
130
+
109
131
  def load_env_file(path: Path, base_env: Mapping[str, str] | None = None) -> dict[str, str]:
110
132
  """Load a simple shell-style .env file without overriding base values.
111
133
 
@@ -126,7 +148,7 @@ def load_env_file(path: Path, base_env: Mapping[str, str] | None = None) -> dict
126
148
  line = raw_line.strip()
127
149
  if not line or line.startswith("#"):
128
150
  continue
129
- line = line.split("#", 1)[0].strip()
151
+ line = _strip_env_comment(line)
130
152
  if not line or "=" not in line:
131
153
  continue
132
154
  key, value = line.split("=", 1)
@@ -508,7 +530,7 @@ def load_runtime_config(paths: RuntimePaths, env: Mapping[str, str] | None = Non
508
530
  heartbeat_interval_seconds=_int_from_env(runtime_env, "HEARTBEAT_INTERVAL", _int_from_env(runtime_env, "HEARTBEAT_INTERVAL_SECONDS", 30)),
509
531
  heartbeat_timeout_seconds=_int_from_env(runtime_env, "HEARTBEAT_STALE_THRESHOLD", _int_from_env(runtime_env, "HEARTBEAT_TIMEOUT_SECONDS", 600)),
510
532
  model=runtime_env.get("MODEL"),
511
- effort=effort,
533
+ effort=effort_validation.effort,
512
534
  effort_validation=effort_validation,
513
535
  env_values=dict(runtime_env),
514
536
  )
@@ -88,6 +88,8 @@ def run_daemon_command(kind: str, action: str, legacy_args: tuple[str, ...], pat
88
88
  return _logs(family, daemon_paths, legacy_args)
89
89
  if action == "restart":
90
90
  stop_result = _stop(family, daemon_paths)
91
+ if stop_result.exit_code != 0:
92
+ return stop_result
91
93
  start_result = _start(family, daemon_paths, legacy_args, paths)
92
94
  stderr = "\n".join(part for part in (stop_result.stderr, start_result.stderr) if part)
93
95
  return CommandResult(start_result.exit_code, start_result.title, start_result.message, stdout=start_result.render(), stderr=stderr)
@@ -25,6 +25,8 @@ PIPELINE_METADATA_EXCLUDES = (
25
25
  ":(top,exclude).prizmkit/manifest.json",
26
26
  ":(top,exclude,glob).prizmkit/specs/**/workflow-checkpoint.json",
27
27
  ":(top,exclude,glob).prizmkit/specs/**/runtime-commit-request.json",
28
+ ":(top,exclude,glob).prizmkit/bugfix/**/workflow-checkpoint.json",
29
+ ":(top,exclude,glob).prizmkit/bugfix/**/runtime-commit-request.json",
28
30
  )
29
31
 
30
32
  HIDDEN_TOOL_WORKTREE_EXCLUDES = (
@@ -134,7 +136,7 @@ class GitCommand:
134
136
 
135
137
  @dataclass(frozen=True)
136
138
  class GitCommandPlan:
137
- """A deterministic branch/worktree command plan."""
139
+ """A deterministic branch command plan."""
138
140
 
139
141
  name: str
140
142
  commands: tuple[GitCommand, ...]
@@ -225,18 +227,6 @@ def branch_create_plan(context: BranchContext) -> GitCommandPlan:
225
227
  )
226
228
 
227
229
 
228
- def branch_return_plan(context: BranchContext) -> GitCommandPlan:
229
- """Plan shell-equivalent branch_return intent."""
230
- return GitCommandPlan(
231
- name="branch_return",
232
- commands=(
233
- _git("rev-parse", "--abbrev-ref", "HEAD", description="detect current branch"),
234
- _git("checkout", context.base_branch, allow_failure=True, description="checkout original branch if needed"),
235
- ),
236
- notes=("Safe when already on the original branch.",),
237
- )
238
-
239
-
240
230
  def branch_fast_forward_possible(project_root: Path, context: BranchContext) -> bool:
241
231
  """Return whether the base branch is an ancestor of the committed task branch."""
242
232
  return run_git_command(
@@ -494,7 +484,7 @@ def visible_task_paths(project_root: Path) -> tuple[tuple[str, ...], GitCommandR
494
484
  if result.return_code != 0:
495
485
  return (), result
496
486
 
497
- # Platform payloads copied into a task worktree stay hidden, but existing
487
+ # Platform payloads copied into a task checkout stay hidden, but existing
498
488
  # tracked Cursor/Antigravity/Codex project configuration remains part of
499
489
  # complete-workspace commit semantics. `--untracked-files=no` admits only
500
490
  # Git-owned changes and cannot sweep materialized support files into a task commit.
@@ -812,9 +802,6 @@ def commit_identity_global_args(project_root: Path) -> tuple[str, ...]:
812
802
  return tuple(global_args)
813
803
 
814
804
 
815
- _commit_identity_global_args = commit_identity_global_args
816
-
817
-
818
805
  def commit_args_without_signing(args: tuple[str, ...]) -> tuple[str, ...]:
819
806
  """Add ``--no-gpg-sign`` to pipeline ``git commit`` invocations unless explicitly signed."""
820
807
  explicit_signing = any(
@@ -826,16 +813,14 @@ def commit_args_without_signing(args: tuple[str, ...]) -> tuple[str, ...]:
826
813
  return ("commit", "--no-gpg-sign", *args[1:])
827
814
 
828
815
 
829
- _commit_args_without_signing = commit_args_without_signing
830
-
831
-
832
816
  def run_git_command(project_root: Path, args: Sequence[str]) -> GitCommandResult:
833
817
  """Run one git command in a project root and capture output."""
834
818
  command_args = tuple(map(str, args))
835
819
  global_args: tuple[str, ...] = ()
836
820
  executable_args = command_args
837
- if command_args and command_args[0] == "commit":
821
+ if command_args and command_args[0] in {"commit", "rebase", "merge"}:
838
822
  global_args = commit_identity_global_args(project_root)
823
+ if command_args and command_args[0] == "commit":
839
824
  executable_args = commit_args_without_signing(command_args)
840
825
  completed = subprocess.run(
841
826
  ["git", *global_args, "-C", str(project_root), *executable_args],
@@ -898,12 +883,26 @@ class ResetBranchCleanupResult:
898
883
  warnings: tuple[str, ...] = ()
899
884
 
900
885
 
901
- _TASK_BRANCH_PREFIXES = ("dev/", "bugfix/")
886
+ _TASK_BRANCH_PATTERN = re.compile(
887
+ r"^(?:prizmkit/|prizmkit-)?(?:dev/(?:feature/)?F-[0-9]+(?:-.*)?|bugfix/(?:bugfix/)?B-[0-9]+(?:-.*)?)$"
888
+ )
902
889
 
903
890
 
904
891
  def _is_generated_task_branch(branch: str) -> bool:
905
892
  """Return whether a branch name is a generated task branch."""
906
- return any(branch.startswith(prefix) for prefix in _TASK_BRANCH_PREFIXES)
893
+ return bool(_TASK_BRANCH_PATTERN.fullmatch(branch))
894
+
895
+
896
+ def safe_task_branch_prefix(project_root: Path, base_prefix: str) -> str:
897
+ """Return a task branch prefix that avoids Git ref collisions with existing branches."""
898
+ prefix = base_prefix.strip().strip("/") or "dev"
899
+ if not local_branch_exists(project_root, prefix):
900
+ return prefix
901
+ if not local_branch_exists(project_root, "prizmkit") and not local_branch_exists(
902
+ project_root, f"prizmkit/{prefix}"
903
+ ):
904
+ return f"prizmkit/{prefix}"
905
+ return f"prizmkit-{prefix}"
907
906
 
908
907
 
909
908
  def _origin_default_name(project_root: Path) -> str:
@@ -1004,16 +1003,22 @@ def reset_branch_pattern(prefix: str, item_id: str) -> str:
1004
1003
 
1005
1004
 
1006
1005
  def list_reset_branches(project_root: Path, prefix: str, item_id: str) -> tuple[str, ...]:
1007
- """List dev branches that shell reset helpers would clean for an item."""
1008
- result = run_git_command(project_root, ("branch", "--list", reset_branch_pattern(prefix, item_id)))
1009
- if result.return_code != 0:
1010
- return ()
1011
- branches = []
1012
- for line in result.stdout.splitlines():
1013
- branch = line.strip().lstrip("* ").strip()
1014
- if branch:
1015
- branches.append(branch)
1016
- return tuple(branches)
1006
+ """List dev branches that reset helpers would clean for an item."""
1007
+ patterns = (
1008
+ reset_branch_pattern(prefix, item_id),
1009
+ reset_branch_pattern(f"prizmkit/{prefix}", item_id),
1010
+ reset_branch_pattern(f"prizmkit-{prefix}", item_id),
1011
+ )
1012
+ branches: list[str] = []
1013
+ for pattern in patterns:
1014
+ result = run_git_command(project_root, ("branch", "--list", pattern))
1015
+ if result.return_code != 0:
1016
+ continue
1017
+ for line in result.stdout.splitlines():
1018
+ branch = line.strip().lstrip("* ").strip()
1019
+ if branch:
1020
+ branches.append(branch)
1021
+ return tuple(dict.fromkeys(branches))
1017
1022
 
1018
1023
 
1019
1024
  def reset_cleanup_branch(project_root: Path, branch: str, *, return_branch: str, delete: bool) -> ResetBranchCleanupResult:
@@ -1024,22 +1029,66 @@ def reset_cleanup_branch(project_root: Path, branch: str, *, return_branch: str,
1024
1029
  cleaned = False
1025
1030
 
1026
1031
  if active == branch:
1032
+ if not return_branch or not local_branch_exists(project_root, return_branch):
1033
+ warnings.append(
1034
+ f"cannot safely reset active branch {branch}: return branch {return_branch or '(empty)'} does not exist"
1035
+ )
1036
+ return ResetBranchCleanupResult(
1037
+ branch=branch,
1038
+ cleaned=False,
1039
+ deleted=False,
1040
+ returned_to=restored,
1041
+ checkout_discarded=False,
1042
+ branch_preserved=True,
1043
+ warnings=tuple(warnings),
1044
+ )
1027
1045
  run_git_command(project_root, ("reset", "HEAD"))
1028
1046
  run_git_command(project_root, ("checkout", "--", "."))
1029
- run_git_command(project_root, ("clean", "-fd"))
1047
+ run_git_command(
1048
+ project_root,
1049
+ (
1050
+ "clean",
1051
+ "-fd",
1052
+ "-e",
1053
+ ".prizmkit/",
1054
+ "-e",
1055
+ ".claude/",
1056
+ "-e",
1057
+ ".codebuddy/",
1058
+ "-e",
1059
+ ".codex/",
1060
+ "-e",
1061
+ ".agents/",
1062
+ "-e",
1063
+ ".cursor/",
1064
+ "-e",
1065
+ ".pi/",
1066
+ ),
1067
+ )
1030
1068
  checkout = run_git_command(project_root, ("checkout", return_branch))
1031
1069
  if checkout.return_code != 0:
1032
1070
  warnings.append(f"failed to checkout {return_branch}")
1033
1071
  restored = branch
1034
- else:
1035
- restored = return_branch
1036
- cleaned = True
1072
+ return ResetBranchCleanupResult(
1073
+ branch=branch,
1074
+ cleaned=False,
1075
+ deleted=False,
1076
+ returned_to=restored,
1077
+ checkout_discarded=False,
1078
+ branch_preserved=True,
1079
+ warnings=tuple(warnings),
1080
+ )
1081
+ restored = return_branch
1082
+ cleaned = True
1037
1083
 
1038
1084
  deleted = False
1039
1085
  if delete:
1040
- deleted = run_git_command(project_root, ("branch", "-D", branch)).return_code == 0
1041
- if not deleted:
1042
- warnings.append(f"failed to delete branch {branch}")
1086
+ if not local_branch_exists(project_root, branch):
1087
+ cleaned = True
1088
+ else:
1089
+ deleted = run_git_command(project_root, ("branch", "-D", branch)).return_code == 0
1090
+ if not deleted:
1091
+ warnings.append(f"failed to delete branch {branch}")
1043
1092
  elif active != branch:
1044
1093
  cleaned = True
1045
1094
 
@@ -249,7 +249,15 @@ class HeartbeatMonitor:
249
249
  if self._thread is not None:
250
250
  return
251
251
  self.config.heartbeat_file.parent.mkdir(parents=True, exist_ok=True)
252
- self.config.heartbeat_file.write_text("started\n", encoding="utf-8")
252
+ write_json_atomic(
253
+ self.config.heartbeat_file,
254
+ {
255
+ "last_seen_epoch": time.time(),
256
+ "stale": False,
257
+ "stale_seconds": 0.0,
258
+ "details": "started",
259
+ },
260
+ )
253
261
  self._thread = threading.Thread(target=self._run, name="prizmkit-heartbeat", daemon=True)
254
262
  self._thread.start()
255
263
 
@@ -2,9 +2,6 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import os
6
- import subprocess
7
- import sys
8
5
  from collections.abc import Mapping, Sequence
9
6
  from dataclasses import dataclass, field
10
7
  from pathlib import Path
@@ -86,22 +83,3 @@ def describe_existing_entrypoint(
86
83
  entrypoint_kind=kind,
87
84
  entrypoint_name=name,
88
85
  )
89
-
90
-
91
- def run_existing_entrypoint(invocation: ScriptInvocation) -> subprocess.CompletedProcess[str]:
92
- """Run a Python utility entrypoint through a standard-library subprocess bridge."""
93
- process_env = None
94
- if invocation.environment_overrides:
95
- process_env = {**os.environ, **invocation.environment_overrides}
96
- command = invocation.command_line()
97
- if invocation.script_path.suffix == ".py":
98
- command = (sys.executable, *command)
99
- return subprocess.run(
100
- command,
101
- cwd=invocation.cwd,
102
- env=process_env,
103
- text=True,
104
- stdout=subprocess.PIPE,
105
- stderr=subprocess.PIPE,
106
- check=False,
107
- )
@@ -222,7 +222,10 @@ def resolve_platform(project_root: str | Path, env: Mapping[str, str] | None = N
222
222
  return PlatformResolution(explicit, "environment:PRIZMKIT_PLATFORM")
223
223
 
224
224
  for env_name in ("AI_CLI", "CLAUDECODE", "CLAUDE_CODE", "CODEBUDDY_CLI"):
225
- detected = platform_from_command(environment.get(env_name, ""))
225
+ raw_env = environment.get(env_name, "")
226
+ if env_name in {"CLAUDECODE", "CLAUDE_CODE"} and str(raw_env).strip().lower() in {"1", "true", "yes"}:
227
+ return PlatformResolution("claude", f"environment:{env_name}")
228
+ detected = platform_from_command(raw_env)
226
229
  if detected:
227
230
  return PlatformResolution(detected, f"environment:{env_name}")
228
231
 
@@ -231,12 +234,6 @@ def resolve_platform(project_root: str | Path, env: Mapping[str, str] | None = N
231
234
  detected = platform_from_command(config.get(key, ""))
232
235
  if detected:
233
236
  return PlatformResolution(detected, f"config:{key}")
234
- try:
235
- detected = prompt_host_from_platform_field(config.get("platform", ""), environment)
236
- except PlatformSelectionError as exc:
237
- return PlatformResolution("", "unresolved:config:platform", (str(exc),))
238
- if detected:
239
- return PlatformResolution(detected, "config:platform")
240
237
 
241
238
  manifest = read_json_object(root / ".prizmkit" / "manifest.json")
242
239
  options = manifest.get("options", {}) if isinstance(manifest.get("options"), dict) else {}
@@ -251,6 +248,13 @@ def resolve_platform(project_root: str | Path, env: Mapping[str, str] | None = N
251
248
  if detected:
252
249
  return PlatformResolution(detected, "manifest:platform")
253
250
 
251
+ try:
252
+ detected = prompt_host_from_platform_field(config.get("platform", ""), environment)
253
+ except PlatformSelectionError as exc:
254
+ return PlatformResolution("", "unresolved:config:platform", (str(exc),))
255
+ if detected:
256
+ return PlatformResolution(detected, "config:platform")
257
+
254
258
  for platform in SUPPORTED_PLATFORMS:
255
259
  for marker in _PLATFORM_MARKERS[platform]:
256
260
  if (root / marker).is_dir():
@@ -72,7 +72,7 @@ def exclusive_pid_lock(
72
72
  if not acquired:
73
73
  raise PidLockError(f"Cannot acquire {error_label} {lock_path}")
74
74
  try:
75
- (lock_path / "owner.json").write_text(json.dumps({"pid": os.getpid()}) + "\n", encoding="utf-8")
75
+ write_text_atomic(lock_path / "owner.json", json.dumps({"pid": os.getpid()}) + "\n")
76
76
  yield
77
77
  finally:
78
78
  owner_pid = _lock_owner_pid(lock_path)
@@ -320,7 +320,6 @@ def _terminate_tree_impl(
320
320
  if grace > 0:
321
321
  completed = _run_windows_taskkill(pid, force=False)
322
322
  details.append(f"taskkill_graceful_exit={completed.returncode}")
323
- taskkill_ok = completed.returncode == 0
324
323
  deadline = time.monotonic() + grace
325
324
  while still_running() and time.monotonic() < deadline:
326
325
  time.sleep(0.05)
@@ -328,15 +327,20 @@ def _terminate_tree_impl(
328
327
  forced = True
329
328
  completed = _run_windows_taskkill(pid, force=True)
330
329
  details.append(f"taskkill_exit={completed.returncode}")
331
- taskkill_ok = taskkill_ok or (completed.returncode == 0)
332
- force_deadline = time.monotonic() + min(grace, 2.0)
333
- while still_running() and time.monotonic() < force_deadline:
334
- time.sleep(0.05)
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
335
  else:
336
336
  forced = True
337
337
  completed = _run_windows_taskkill(pid, force=True)
338
338
  details.append(f"taskkill_exit={completed.returncode}")
339
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)
340
344
  else:
341
345
  _signal_posix_tree(pid, signal.SIGTERM, "sigterm", details)
342
346
  deadline = time.monotonic() + grace
@@ -395,6 +399,12 @@ def _windows_pid_running(pid: int) -> bool:
395
399
  return False
396
400
  return True
397
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
398
408
  process_query_limited_information = 0x1000
399
409
  still_active = 259
400
410
  error_access_denied = 5
@@ -402,7 +412,7 @@ def _windows_pid_running(pid: int) -> bool:
402
412
  if not handle:
403
413
  return ctypes.get_last_error() == error_access_denied
404
414
  try:
405
- exit_code = ctypes.c_ulong()
415
+ exit_code = ctypes.c_uint32()
406
416
  if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)):
407
417
  return False
408
418
  return exit_code.value == still_active
@@ -416,6 +426,15 @@ def is_pid_running(pid: int | None) -> bool:
416
426
  return False
417
427
  if os.name == "nt":
418
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
419
438
  try:
420
439
  os.kill(pid, 0)
421
440
  except ProcessLookupError:
@@ -424,14 +443,6 @@ def is_pid_running(pid: int | None) -> bool:
424
443
  return True
425
444
  except OSError:
426
445
  return False
427
- try:
428
- waited_pid, _status = os.waitpid(pid, os.WNOHANG)
429
- except ChildProcessError:
430
- return True
431
- except OSError:
432
- return True
433
- if waited_pid == pid:
434
- return False
435
446
  return True
436
447
 
437
448
 
@@ -512,8 +523,3 @@ def platform_termination_strategy() -> tuple[str, ...]:
512
523
  if os.name == "nt":
513
524
  return ("CREATE_NEW_PROCESS_GROUP", "taskkill /PID <pid> /T /F")
514
525
  return ("setsid", "killpg(SIGTERM)", "killpg(SIGKILL)")
515
-
516
-
517
- def describe_command(command: Sequence[str]) -> str:
518
- """Return a deterministic command description for tests."""
519
- return " ".join(str(part) for part in command)