prizmkit 1.1.190 → 1.1.192

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/bin/create-prizmkit.js +4 -4
  2. package/bundled/VERSION.json +3 -3
  3. package/bundled/adapters/antigravity/assets/prizmkit-hook.cjs +150 -0
  4. package/bundled/adapters/antigravity/hooks-adapter.js +195 -0
  5. package/bundled/adapters/antigravity/paths.js +14 -0
  6. package/bundled/adapters/antigravity/rules-adapter.js +54 -0
  7. package/bundled/adapters/antigravity/skill-adapter.js +38 -0
  8. package/bundled/adapters/codex/skill-adapter.js +28 -8
  9. package/bundled/adapters/cursor/skill-adapter.js +13 -4
  10. package/bundled/adapters/pi/skill-adapter.js +28 -7
  11. package/bundled/dev-pipeline/.env.example +4 -12
  12. package/bundled/dev-pipeline/README.md +21 -15
  13. package/bundled/dev-pipeline/assets/skill-subagent-integration.md +3 -6
  14. package/bundled/dev-pipeline/prizmkit_runtime/atomic_io.py +48 -0
  15. package/bundled/dev-pipeline/prizmkit_runtime/checkpoint_state.py +66 -23
  16. package/bundled/dev-pipeline/prizmkit_runtime/cli.py +10 -7
  17. package/bundled/dev-pipeline/prizmkit_runtime/commands.py +2 -21
  18. package/bundled/dev-pipeline/prizmkit_runtime/config.py +29 -70
  19. package/bundled/dev-pipeline/prizmkit_runtime/daemon.py +125 -67
  20. package/bundled/dev-pipeline/prizmkit_runtime/gitops.py +89 -442
  21. package/bundled/dev-pipeline/prizmkit_runtime/heartbeat.py +93 -49
  22. package/bundled/dev-pipeline/prizmkit_runtime/interoperability.py +1 -3
  23. package/bundled/dev-pipeline/prizmkit_runtime/paths.py +0 -6
  24. package/bundled/dev-pipeline/prizmkit_runtime/platform_detection.py +49 -18
  25. package/bundled/dev-pipeline/prizmkit_runtime/processes.py +206 -151
  26. package/bundled/dev-pipeline/prizmkit_runtime/reset.py +2 -23
  27. package/bundled/dev-pipeline/prizmkit_runtime/reset_preserve.py +15 -134
  28. package/bundled/dev-pipeline/prizmkit_runtime/results.py +25 -0
  29. package/bundled/dev-pipeline/prizmkit_runtime/runner_bookkeeping.py +68 -83
  30. package/bundled/dev-pipeline/prizmkit_runtime/runner_classification.py +15 -5
  31. package/bundled/dev-pipeline/prizmkit_runtime/runner_models.py +1 -29
  32. package/bundled/dev-pipeline/prizmkit_runtime/runner_prompts.py +0 -2
  33. package/bundled/dev-pipeline/prizmkit_runtime/runner_status.py +7 -2
  34. package/bundled/dev-pipeline/prizmkit_runtime/runners.py +282 -217
  35. package/bundled/dev-pipeline/prizmkit_runtime/runtime_commit.py +124 -122
  36. package/bundled/dev-pipeline/prizmkit_runtime/runtime_helper.py +90 -9
  37. package/bundled/dev-pipeline/prizmkit_runtime/sessions.py +369 -154
  38. package/bundled/dev-pipeline/prizmkit_runtime/status.py +3 -3
  39. package/bundled/dev-pipeline/prizmkit_runtime/stream_progress.py +2780 -0
  40. package/bundled/dev-pipeline/prizmkit_runtime/task_checkout.py +27 -101
  41. package/bundled/dev-pipeline/prizmkit_runtime/test_result.py +58 -4
  42. package/bundled/dev-pipeline/scripts/check-session-status.py +43 -19
  43. package/bundled/dev-pipeline/scripts/continuation.py +6 -4
  44. package/bundled/dev-pipeline/scripts/detect-stuck.py +28 -28
  45. package/bundled/dev-pipeline/scripts/generate-bootstrap-prompt.py +7 -2
  46. package/bundled/dev-pipeline/scripts/generate-bugfix-prompt.py +7 -2
  47. package/bundled/dev-pipeline/scripts/init-bugfix-pipeline.py +10 -7
  48. package/bundled/dev-pipeline/scripts/init-change-artifact.py +8 -2
  49. package/bundled/dev-pipeline/scripts/init-pipeline.py +14 -69
  50. package/bundled/dev-pipeline/scripts/parse-stream-progress.py +31 -2328
  51. package/bundled/dev-pipeline/scripts/patch-completion-notes.py +4 -24
  52. package/bundled/dev-pipeline/scripts/prompt_framework.py +56 -9
  53. package/bundled/dev-pipeline/scripts/status_common.py +591 -0
  54. package/bundled/dev-pipeline/scripts/update-bug-status.py +85 -463
  55. package/bundled/dev-pipeline/scripts/update-checkpoint.py +227 -65
  56. package/bundled/dev-pipeline/scripts/update-feature-status.py +76 -509
  57. package/bundled/dev-pipeline/scripts/utils.py +10 -15
  58. package/bundled/dev-pipeline/templates/bootstrap-tier3.md +4 -4
  59. package/bundled/dev-pipeline/templates/bug-fix-list-schema.json +7 -0
  60. package/bundled/dev-pipeline/templates/bugfix-bootstrap-prompt.md +1 -1
  61. package/bundled/dev-pipeline/templates/sections/artifact-manifest.md +1 -1
  62. package/bundled/dev-pipeline/templates/sections/bugfix-phase-manual-verification.md +1 -1
  63. package/bundled/dev-pipeline/templates/sections/bugfix-phase-review.md +1 -1
  64. package/bundled/dev-pipeline/templates/sections/bugfix-phase-test.md +2 -1
  65. package/bundled/dev-pipeline/templates/sections/checkpoint-system.md +1 -1
  66. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-auto.md +1 -1
  67. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-opencli.md +2 -2
  68. package/bundled/dev-pipeline/templates/sections/phase-browser-verification.md +2 -2
  69. package/bundled/dev-pipeline/templates/sections/phase-prizmkit-test.md +2 -1
  70. package/bundled/dev-pipeline/templates/sections/phase-review-full.md +1 -1
  71. package/bundled/dev-pipeline/templates/sections/phase-specify-plan-full.md +3 -6
  72. package/bundled/dev-pipeline/templates/session-status-schema.json +2 -5
  73. package/bundled/dev-pipeline/tests/_helpers.py +418 -0
  74. package/bundled/dev-pipeline/tests/conftest.py +45 -1
  75. package/bundled/dev-pipeline/tests/live_ai_cli_log_smoke.py +1 -0
  76. package/bundled/dev-pipeline/tests/test_auto_skip.py +4 -69
  77. package/bundled/dev-pipeline/tests/test_checkpoint_state.py +126 -1
  78. package/bundled/dev-pipeline/tests/test_daemon_and_scripts.py +257 -0
  79. package/bundled/dev-pipeline/tests/test_e2e_pipeline_run.py +500 -0
  80. package/bundled/dev-pipeline/tests/test_generate_bootstrap_prompt.py +59 -117
  81. package/bundled/dev-pipeline/tests/test_generate_bugfix_prompt.py +12 -10
  82. package/bundled/dev-pipeline/tests/test_python_runner_parity.py +561 -3094
  83. package/bundled/dev-pipeline/tests/test_recovery_workflow.py +7 -8
  84. package/bundled/dev-pipeline/tests/test_repository_bootstrap.py +0 -1
  85. package/bundled/dev-pipeline/tests/test_reset_modes.py +15 -27
  86. package/bundled/dev-pipeline/tests/test_reset_preserve.py +54 -139
  87. package/bundled/dev-pipeline/tests/test_runner_bookkeeping.py +766 -0
  88. package/bundled/dev-pipeline/tests/test_runner_lifecycle.py +1257 -0
  89. package/bundled/dev-pipeline/tests/test_runtime_helper.py +97 -20
  90. package/bundled/dev-pipeline/tests/test_session_launch.py +1101 -0
  91. package/bundled/dev-pipeline/tests/test_stream_progress.py +585 -0
  92. package/bundled/dev-pipeline/tests/test_unified_cli.py +490 -2006
  93. package/bundled/dev-pipeline/tests/test_utils.py +3 -3
  94. package/bundled/rules/USAGE.md +1 -0
  95. package/bundled/skills/_metadata.json +9 -63
  96. package/bundled/skills/app-planner/SKILL.md +32 -303
  97. package/bundled/skills/app-planner/references/app-design-guide.md +0 -4
  98. package/bundled/skills/app-planner/references/generated-plan-review.md +2 -1
  99. package/bundled/skills/app-planner/references/project-brief-guide.md +14 -0
  100. package/bundled/skills/app-planner/references/project-conventions-discovery.md +4 -6
  101. package/bundled/skills/app-planner/references/project-state-detection.md +2 -3
  102. package/bundled/skills/bug-fix-workflow/SKILL.md +1 -2
  103. package/bundled/skills/bug-fix-workflow/references/bug-diagnosis.md +4 -7
  104. package/bundled/skills/bug-planner/SKILL.md +54 -435
  105. package/bundled/skills/bug-planner/references/generated-plan-review.md +3 -2
  106. package/bundled/skills/bug-planner/references/input-formats.md +32 -0
  107. package/bundled/skills/bugfix-pipeline-launcher/SKILL.md +4 -6
  108. package/bundled/skills/bugfix-pipeline-launcher/references/configuration.md +4 -28
  109. package/bundled/skills/feature-pipeline-launcher/SKILL.md +4 -6
  110. package/bundled/skills/feature-pipeline-launcher/references/configuration.md +4 -28
  111. package/bundled/skills/feature-planner/SKILL.md +60 -439
  112. package/bundled/skills/feature-planner/assets/planning-guide.md +1 -1
  113. package/bundled/skills/feature-planner/references/completeness-review.md +34 -0
  114. package/bundled/skills/feature-planner/references/decomposition-patterns.md +2 -2
  115. package/bundled/skills/feature-planner/references/error-recovery.md +1 -1
  116. package/bundled/skills/feature-planner/references/generated-plan-review.md +3 -2
  117. package/bundled/skills/feature-planner/references/incremental-feature-planning.md +3 -1
  118. package/bundled/skills/feature-workflow/SKILL.md +1 -2
  119. package/bundled/skills/prizmkit/SKILL.md +7 -1
  120. package/bundled/skills/prizmkit-code-review/SKILL.md +14 -6
  121. package/bundled/skills/prizmkit-code-review/references/independent-code-review.md +7 -4
  122. package/bundled/skills/prizmkit-code-review/references/review-report-template.md +16 -0
  123. package/bundled/skills/prizmkit-code-review/scripts/render_review_report.py +58 -20
  124. package/bundled/skills/prizmkit-implement/SKILL.md +1 -1
  125. package/bundled/skills/prizmkit-init/SKILL.md +25 -128
  126. package/bundled/skills/prizmkit-init/assets/project-brief-template.md +3 -3
  127. package/bundled/skills/prizmkit-init/references/config-schema.md +2 -2
  128. package/bundled/skills/prizmkit-plan/SKILL.md +6 -8
  129. package/bundled/skills/prizmkit-plan/references/clarify-guide.md +1 -1
  130. package/bundled/skills/prizmkit-plan/references/independent-plan-review.md +5 -2
  131. package/bundled/skills/prizmkit-plan/references/review-plan-spec-loop.md +6 -5
  132. package/bundled/skills/prizmkit-prizm-docs/SKILL.md +1 -13
  133. package/bundled/skills/prizmkit-prizm-docs/assets/prizm-docs-format.md +1 -1
  134. package/bundled/skills/prizmkit-prizm-docs/references/op-init.md +1 -1
  135. package/bundled/skills/prizmkit-prizm-docs/references/op-update.md +1 -1
  136. package/bundled/skills/prizmkit-retrospective/SKILL.md +6 -4
  137. package/bundled/skills/prizmkit-test/SKILL.md +25 -133
  138. package/bundled/skills/prizmkit-test/references/independent-test-review.md +5 -2
  139. package/bundled/skills/prizmkit-test/references/test-coverage-model.md +6 -0
  140. package/bundled/skills/prizmkit-workflow/SKILL.md +2 -3
  141. package/bundled/skills/prizmkit-workflow/references/workflow-state-protocol.md +4 -3
  142. package/bundled/skills/recovery-workflow/SKILL.md +7 -7
  143. package/bundled/skills/recovery-workflow/evals/evals.json +1 -1
  144. package/bundled/skills/recovery-workflow/references/detection.md +1 -3
  145. package/bundled/skills/recovery-workflow/scripts/detect-recovery-state.py +0 -6
  146. package/bundled/templates/project-memory-template.md +1 -2
  147. package/package.json +1 -1
  148. package/src/ai-cli-launch.js +1 -1
  149. package/src/clean.js +40 -4
  150. package/src/config.js +64 -4
  151. package/src/detect-platform.js +10 -6
  152. package/src/external-skills.js +2 -2
  153. package/src/index.js +1 -0
  154. package/src/manifest.js +1 -1
  155. package/src/platforms.js +6 -2
  156. package/src/prompts.js +11 -3
  157. package/src/scaffold.js +87 -11
  158. package/src/upgrade.js +9 -3
  159. package/bundled/dev-pipeline/SCHEMA_ANALYSIS.md +0 -53
  160. package/bundled/dev-pipeline/scripts/generate-refactor-prompt.py +0 -649
  161. package/bundled/dev-pipeline/scripts/init-refactor-pipeline.py +0 -463
  162. package/bundled/dev-pipeline/scripts/update-refactor-status.py +0 -1512
  163. package/bundled/dev-pipeline/templates/refactor-bootstrap-prompt.md +0 -240
  164. package/bundled/dev-pipeline/templates/refactor-list-schema.json +0 -266
  165. package/bundled/dev-pipeline/templates/sections/refactor-critical-paths.md +0 -15
  166. package/bundled/dev-pipeline/templates/sections/refactor-mission.md +0 -9
  167. package/bundled/dev-pipeline/templates/sections/refactor-phase-commit-report.md +0 -24
  168. package/bundled/dev-pipeline/templates/sections/refactor-phase-implement.md +0 -16
  169. package/bundled/dev-pipeline/templates/sections/refactor-phase-init.md +0 -9
  170. package/bundled/dev-pipeline/templates/sections/refactor-phase-plan.md +0 -22
  171. package/bundled/dev-pipeline/templates/sections/refactor-phase-review.md +0 -19
  172. package/bundled/dev-pipeline/templates/sections/refactor-phase-test.md +0 -24
  173. package/bundled/dev-pipeline/templates/sections/refactor-reminders.md +0 -12
  174. package/bundled/dev-pipeline/templates/sections/refactor-session-context.md +0 -6
  175. package/bundled/dev-pipeline/templates/sections/refactor-task-contract.md +0 -52
  176. package/bundled/dev-pipeline/tests/test_generate_refactor_prompt.py +0 -478
  177. package/bundled/skills/feature-planner/assets/evaluation-guide.md +0 -44
  178. package/bundled/skills/refactor-pipeline-launcher/SKILL.md +0 -219
  179. package/bundled/skills/refactor-pipeline-launcher/references/configuration.md +0 -78
  180. package/bundled/skills/refactor-planner/SKILL.md +0 -467
  181. package/bundled/skills/refactor-planner/assets/planning-guide.md +0 -291
  182. package/bundled/skills/refactor-planner/references/behavior-preservation.md +0 -187
  183. package/bundled/skills/refactor-planner/references/error-recovery.md +0 -45
  184. package/bundled/skills/refactor-planner/references/fast-path.md +0 -59
  185. package/bundled/skills/refactor-planner/references/generated-plan-review.md +0 -107
  186. package/bundled/skills/refactor-planner/references/planning-phases.md +0 -172
  187. package/bundled/skills/refactor-planner/references/refactor-scoping-guide.md +0 -230
  188. package/bundled/skills/refactor-planner/scripts/validate-and-generate-refactor.py +0 -1120
  189. package/bundled/skills/refactor-workflow/SKILL.md +0 -205
@@ -1,1512 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Core state machine for updating refactor status in the refactor pipeline.
3
-
4
- Handles eight actions:
5
- - get_next: Find the next refactor to process based on dependency order, priority, complexity
6
- - start: Mark a refactor as in_progress when a session starts
7
- - update: Update a refactor's status based on session outcome
8
- - status: Print a formatted overview of all refactors
9
- - pause: Save pipeline state for graceful shutdown
10
- - reset: Reset a refactor to pending (status + retry count)
11
- - clean: Reset + delete session history + delete refactor artifacts
12
- - reset_state: Recover blocking roots and causally recoverable auto-skipped descendants
13
-
14
- Usage:
15
- python3 update-refactor-status.py \
16
- --refactor-list <path> --state-dir <path> \
17
- --action <get_next|start|update|status|pause|reset|clean|reset_state> \
18
- [--refactor-id <id>] [--session-status <status>] \
19
- [--session-id <id>] [--max-retries <n>] [--max-infra-retries <n>]
20
- """
21
-
22
- import argparse
23
- import json
24
- import os
25
- import shutil
26
- import sys
27
- from datetime import datetime, timezone
28
-
29
- from utils import (
30
- load_json_file,
31
- write_json_file,
32
- error_out,
33
- pad_right,
34
- _build_progress_bar,
35
- read_checkpoint_cursor,
36
- dependency_rank_map,
37
- causal_reset_selection,
38
- orphaned_auto_skipped_ids,
39
- )
40
-
41
-
42
- SESSION_STATUS_VALUES = [
43
- "success",
44
- "partial_resumable",
45
- "partial_not_resumable",
46
- "failed",
47
- "crashed",
48
- "timed_out",
49
- "infra_error",
50
- "context_overflow",
51
- "stalled_context_continuation",
52
- "workflow_blocked",
53
- "workflow_skipped",
54
- "commit_missing",
55
- "docs_missing",
56
- "merge_conflict",
57
- ]
58
-
59
- TERMINAL_STATUSES = {"completed", "failed", "skipped", "auto_skipped"}
60
- RESET_BLOCKING_ROOT_STATUSES = {"failed", "skipped"}
61
-
62
- # Artifact directory names (relative to project root)
63
- REFACTOR_ARTIFACTS_REL = os.path.join(".prizmkit", "refactor")
64
- DEV_TEAM_DIR_NAME = ".dev-team"
65
-
66
- # Priority ordering (lower number = higher priority)
67
- PRIORITY_ORDER = {
68
- "critical": 0,
69
- "high": 1,
70
- "medium": 2,
71
- "low": 3,
72
- }
73
-
74
- # Complexity ordering (lower number = simpler, processed first)
75
- COMPLEXITY_ORDER = {
76
- "low": 0,
77
- "medium": 1,
78
- "high": 2,
79
- }
80
-
81
-
82
- def parse_args():
83
- parser = argparse.ArgumentParser(
84
- description="Core state machine for refactor pipeline status management."
85
- )
86
- parser.add_argument("--refactor-list", required=True, help="Path to the .prizmkit/plans/refactor-list.json file")
87
- parser.add_argument("--state-dir", required=True, help="Path to the state directory (default: .prizmkit/state/refactor)")
88
- parser.add_argument(
89
- "--action", required=True,
90
- choices=["get_next", "start", "update", "status", "pause", "reset", "clean", "reset_state", "complete"],
91
- help="Action to perform",
92
- )
93
- parser.add_argument("--refactor-id", default=None, help="Refactor ID (required for 'update'/'reset'/'clean' actions)")
94
- parser.add_argument(
95
- "--session-status", default=None, choices=SESSION_STATUS_VALUES,
96
- help="Session outcome status (required for 'update' action)",
97
- )
98
- parser.add_argument("--session-id", default=None, help="Session ID (optional, for 'update' action)")
99
- parser.add_argument("--max-retries", type=int, default=3, help="Maximum code retry count (default: 3)")
100
- parser.add_argument("--max-infra-retries", type=int, default=3, help="Maximum infrastructure retry count (default: 3)")
101
- parser.add_argument("--project-root", default=None, help="Project root directory. Required for 'clean' action.")
102
- parser.add_argument("--active-dev-branch", default=None, help="Development branch preserved for continuation after context overflow.")
103
- parser.add_argument("--base-branch", default=None, help="Original/base branch for continuation branch reuse.")
104
- parser.add_argument("--last-fatal-error-code", default=None, help="Fatal runtime error code associated with continuation.")
105
- parser.add_argument("--continuation-summary-path", default=None, help="Optional continuation summary artifact path.")
106
- parser.add_argument("--no-progress-count", type=int, default=None, help="Consecutive context-overflow sessions without objective progress.")
107
- parser.add_argument("--progress-fingerprint", default=None, help="JSON progress fingerprint captured after the session.")
108
- parser.add_argument("--checkpoint-state", default=None, help="JSON semantic pipeline checkpoint snapshot captured after the session.")
109
- return parser.parse_args()
110
-
111
-
112
- def now_iso():
113
- return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
114
-
115
-
116
- def _default_status(refactor_id):
117
- """Create a default refactor runtime status object (no status field)."""
118
- now = now_iso()
119
- return {
120
- "refactor_id": refactor_id,
121
- "retry_count": 0,
122
- "max_retries": 3,
123
- "max_infra_retries": 3,
124
- "infra_error_count": 0,
125
- "last_infra_error_session_id": None,
126
- "sessions": [],
127
- "last_session_id": None,
128
- "resume_from_phase": None,
129
- "created_at": now,
130
- "updated_at": now,
131
- }
132
-
133
-
134
- def load_refactor_status(state_dir, refactor_id):
135
- """Load runtime state from status.json for a refactor.
136
-
137
- Returns runtime fields only (retry_count, sessions, etc.).
138
- The 'status' field is NOT included — status lives exclusively
139
- in refactor-list.json.
140
- """
141
- status_path = os.path.join(state_dir, refactor_id, "status.json")
142
- if not os.path.isfile(status_path):
143
- return _default_status(refactor_id)
144
- data, err = load_json_file(status_path)
145
- if err:
146
- return _default_status(refactor_id)
147
- # Defensively remove status if present (legacy data)
148
- data.pop("status", None)
149
- return data
150
-
151
-
152
- def save_refactor_status(state_dir, refactor_id, status_data):
153
- """Write the status.json for a refactor (runtime fields only)."""
154
- # Defensively strip status — it belongs in refactor-list.json
155
- status_data.pop("status", None)
156
- status_path = os.path.join(state_dir, refactor_id, "status.json")
157
- return write_json_file(status_path, status_data)
158
-
159
-
160
- def get_refactor_status_from_list(refactor_list_path, refactor_id):
161
- """Read a single refactor's status from refactor-list.json."""
162
- data, err = load_json_file(refactor_list_path)
163
- if err:
164
- return "pending"
165
- for r in data.get("refactors", []):
166
- if isinstance(r, dict) and r.get("id") == refactor_id:
167
- return r.get("status", "pending")
168
- return "pending"
169
-
170
-
171
- def update_refactor_in_list(refactor_list_path, refactor_id, new_status):
172
- data, err = load_json_file(refactor_list_path)
173
- if err:
174
- return err
175
- refactors = data.get("refactors", [])
176
- found = False
177
- for refactor in refactors:
178
- if isinstance(refactor, dict) and refactor.get("id") == refactor_id:
179
- refactor["status"] = new_status
180
- found = True
181
- break
182
- if not found:
183
- return "Refactor '{}' not found in .prizmkit/plans/refactor-list.json".format(refactor_id)
184
- return write_json_file(refactor_list_path, data)
185
-
186
-
187
- CONTINUATION_PENDING_FIELDS = [
188
- "active_dev_branch",
189
- "base_branch",
190
- "continuation_pending",
191
- "continuation_reason",
192
- "last_context_overflow_session_id",
193
- "previous_session_id",
194
- "last_fatal_error_code",
195
- "continuation_summary_path",
196
- "no_progress_count",
197
- "last_progress_fingerprint",
198
- "needs_attention",
199
- "stalled_context_continuation",
200
- "stalled_reason",
201
- ]
202
-
203
- CONTINUATION_COUNTER_FIELDS = [
204
- "context_overflow_count",
205
- "continuation_count",
206
- ]
207
-
208
-
209
- def has_pending_continuation_metadata(status_data):
210
- """Return True when runtime state still has pending continuation metadata."""
211
- return any(key in status_data for key in CONTINUATION_PENDING_FIELDS)
212
-
213
-
214
- def clear_pending_continuation_metadata(status_data):
215
- """Clear branch/pending continuation fields while preserving observability counters."""
216
- for key in CONTINUATION_PENDING_FIELDS:
217
- status_data.pop(key, None)
218
-
219
-
220
- def reset_continuation_metadata(status_data):
221
- """Clear all continuation runtime metadata, including manual-reset counters."""
222
- clear_pending_continuation_metadata(status_data)
223
- for key in CONTINUATION_COUNTER_FIELDS:
224
- status_data.pop(key, None)
225
-
226
-
227
- STALL_REASON = "context_overflow_without_git_checkpoint_or_artifact_progress"
228
-
229
-
230
- def _read_refactor_checkpoint_phase(project_root, refactor_id):
231
- """Read the phase index from the refactor checkpoint file."""
232
- checkpoint_path = os.path.join(
233
- os.path.abspath(project_root) if project_root else _default_project_root(),
234
- ".prizmkit", "refactor", refactor_id, "workflow-checkpoint.json",
235
- )
236
- return read_checkpoint_cursor(checkpoint_path)
237
-
238
-
239
- def _checkpoint_phase_or_cached(project_root, refactor_id, status_data):
240
- """Return live checkpoint phase from the authoritative checkpoint only."""
241
- return _read_refactor_checkpoint_phase(project_root, refactor_id)
242
-
243
-
244
- def _sync_checkpoint_phase(project_root, refactor_id, status_data):
245
- """Cache live checkpoint phase in status.json runtime data."""
246
- status_data["resume_from_phase"] = _read_refactor_checkpoint_phase(
247
- project_root, refactor_id,
248
- )
249
- return status_data.get("resume_from_phase")
250
-
251
-
252
- def _load_progress_fingerprint(raw):
253
- if not raw:
254
- return None
255
- try:
256
- return json.loads(raw)
257
- except (TypeError, ValueError):
258
- return {"unparsed": str(raw)}
259
-
260
-
261
- SEMANTIC_CHECKPOINT_FIELDS = (
262
- "current_stage",
263
- "next_stage",
264
- "stage_result",
265
- "repair_scope",
266
- "repair_round",
267
- "blocked_reason",
268
- "terminal_status",
269
- )
270
-
271
-
272
- def _load_checkpoint_state(raw):
273
- if not raw:
274
- return {}
275
- try:
276
- data = json.loads(raw)
277
- except (TypeError, ValueError):
278
- return {}
279
- if not isinstance(data, dict):
280
- return {}
281
- return {key: data.get(key) for key in SEMANTIC_CHECKPOINT_FIELDS}
282
-
283
-
284
- def _sync_semantic_checkpoint(status_data, args):
285
- semantic = _load_checkpoint_state(getattr(args, "checkpoint_state", None))
286
- if semantic:
287
- status_data.update(semantic)
288
- return {key: status_data.get(key) for key in SEMANTIC_CHECKPOINT_FIELDS}
289
-
290
-
291
- def _set_continuation_common(status_data, args, session_id):
292
- if args.active_dev_branch:
293
- status_data["active_dev_branch"] = args.active_dev_branch
294
- if args.base_branch:
295
- status_data["base_branch"] = args.base_branch
296
- status_data["last_context_overflow_session_id"] = session_id
297
- status_data["previous_session_id"] = session_id
298
- status_data["last_fatal_error_code"] = args.last_fatal_error_code or "context_overflow"
299
- if args.continuation_summary_path:
300
- status_data["continuation_summary_path"] = args.continuation_summary_path
301
- else:
302
- status_data.pop("continuation_summary_path", None)
303
- if args.no_progress_count is not None:
304
- status_data["no_progress_count"] = max(0, args.no_progress_count)
305
- fingerprint = _load_progress_fingerprint(args.progress_fingerprint)
306
- if fingerprint is not None:
307
- status_data["last_progress_fingerprint"] = fingerprint
308
- status_data["last_infra_error_session_id"] = None
309
- status_data["resume_from_phase"] = None
310
- if session_id:
311
- status_data["last_session_id"] = session_id
312
-
313
-
314
- def _set_ai_error_continuation_metadata(status_data, args, session_id, reason):
315
- """Preserve durable task/session state for any retryable launched AI error."""
316
- if args.active_dev_branch:
317
- status_data["active_dev_branch"] = args.active_dev_branch
318
- if args.base_branch:
319
- status_data["base_branch"] = args.base_branch
320
- status_data["continuation_pending"] = True
321
- status_data["continuation_reason"] = reason
322
- status_data["continuation_count"] = status_data.get("continuation_count", 0) + 1
323
- status_data["previous_session_id"] = session_id
324
- status_data["last_fatal_error_code"] = args.last_fatal_error_code or reason
325
- if args.continuation_summary_path:
326
- status_data["continuation_summary_path"] = args.continuation_summary_path
327
- if args.no_progress_count is not None:
328
- status_data["no_progress_count"] = max(0, args.no_progress_count)
329
- fingerprint = _load_progress_fingerprint(args.progress_fingerprint)
330
- if fingerprint is not None:
331
- status_data["last_progress_fingerprint"] = fingerprint
332
- status_data["resume_from_phase"] = None
333
- if session_id:
334
- sessions = status_data.get("sessions", [])
335
- if session_id not in sessions:
336
- sessions.append(session_id)
337
- status_data["sessions"] = sessions
338
- status_data["last_session_id"] = session_id
339
-
340
-
341
- def set_context_overflow_continuation_metadata(status_data, args, session_id):
342
- """Record continuation metadata for a context-overflow outcome in status.json."""
343
- status_data["context_overflow_count"] = status_data.get("context_overflow_count", 0) + 1
344
- status_data["continuation_count"] = status_data.get("continuation_count", 0) + 1
345
- status_data["continuation_pending"] = True
346
- status_data["continuation_reason"] = "context_overflow"
347
- status_data.pop("needs_attention", None)
348
- status_data.pop("stalled_context_continuation", None)
349
- status_data.pop("stalled_reason", None)
350
- _set_continuation_common(status_data, args, session_id)
351
-
352
-
353
- def set_stalled_context_continuation_metadata(status_data, args, session_id):
354
- """Record no-progress context-overflow stall without consuming retry budgets."""
355
- status_data["context_overflow_count"] = status_data.get("context_overflow_count", 0) + 1
356
- status_data["continuation_count"] = status_data.get("continuation_count", 0) + 1
357
- _set_continuation_common(status_data, args, session_id)
358
- status_data["continuation_pending"] = False
359
- status_data["continuation_reason"] = STALL_REASON
360
- status_data["needs_attention"] = True
361
- status_data["stalled_context_continuation"] = True
362
- status_data["stalled_reason"] = STALL_REASON
363
- if args.no_progress_count is None or args.no_progress_count < 2:
364
- status_data["no_progress_count"] = 2
365
-
366
-
367
- def continuation_metadata_summary(status_data):
368
- """Return additive continuation fields for CLI JSON outputs."""
369
- return {
370
- "active_dev_branch": status_data.get("active_dev_branch"),
371
- "base_branch": status_data.get("base_branch"),
372
- "continuation_pending": status_data.get("continuation_pending", False),
373
- "continuation_reason": status_data.get("continuation_reason"),
374
- "last_context_overflow_session_id": status_data.get("last_context_overflow_session_id"),
375
- "last_fatal_error_code": status_data.get("last_fatal_error_code"),
376
- "previous_session_id": status_data.get("previous_session_id"),
377
- "context_overflow_count": status_data.get("context_overflow_count", 0),
378
- "continuation_count": status_data.get("continuation_count", 0),
379
- "no_progress_count": status_data.get("no_progress_count", 0),
380
- "last_progress_fingerprint": status_data.get("last_progress_fingerprint"),
381
- "needs_attention": status_data.get("needs_attention", False),
382
- "stalled_context_continuation": status_data.get("stalled_context_continuation", False),
383
- "stalled_reason": status_data.get("stalled_reason"),
384
- "continuation_summary_path": status_data.get("continuation_summary_path"),
385
- }
386
-
387
-
388
- # ---------------------------------------------------------------------------
389
- # Action: get_next
390
- # ---------------------------------------------------------------------------
391
-
392
-
393
- def _dependencies_met(refactor, completed_set):
394
- """Check if all dependencies for a refactor are completed."""
395
- deps = refactor.get("dependencies", [])
396
- if not deps or not isinstance(deps, list):
397
- return True
398
- return all(dep in completed_set for dep in deps)
399
-
400
-
401
- def action_get_next(
402
- refactor_list_data,
403
- state_dir,
404
- project_root=None,
405
- refactor_list_path=None,
406
- ):
407
- """Find the next refactor to process.
408
-
409
- Priority logic:
410
- 1. Skip terminal statuses (completed, failed, skipped)
411
- 2. Only consider refactors whose dependencies are completed
412
- 3. Prefer in_progress refactors (interrupted session resume) over pending
413
- 4. Within each status class, use stable topological list order
414
- """
415
- if refactor_list_path:
416
- try:
417
- recovered = reconcile_orphaned_auto_skipped_refactors(
418
- refactor_list_path, state_dir
419
- )
420
- except ValueError:
421
- print("PIPELINE_BLOCKED")
422
- return
423
- except RuntimeError as exc:
424
- error_out(str(exc))
425
- return
426
- if recovered:
427
- refactor_list_data, err = load_json_file(refactor_list_path)
428
- if err:
429
- error_out("Cannot reload refactor list after orphan recovery: {}".format(err))
430
- return
431
-
432
- refactors = refactor_list_data.get("refactors", [])
433
- if not refactors:
434
- print("PIPELINE_COMPLETE")
435
- return
436
-
437
- # Build status map from refactor-list.json (single source of truth)
438
- status_map = {}
439
- status_data_map = {}
440
- for r in refactors:
441
- if not isinstance(r, dict):
442
- continue
443
- rid = r.get("id")
444
- if not rid:
445
- continue
446
- status_map[rid] = r.get("status", "pending")
447
- rs = load_refactor_status(state_dir, rid)
448
- status_data_map[rid] = rs
449
-
450
- completed_set = {rid for rid, st in status_map.items() if st == "completed"}
451
- topo_rank, topo_errors = dependency_rank_map(
452
- refactors,
453
- id_key="id",
454
- dependencies_key="dependencies",
455
- item_label="Refactor",
456
- )
457
- if topo_errors:
458
- print("PIPELINE_BLOCKED")
459
- return
460
-
461
- # Check if all refactors are terminal
462
- non_terminal = [
463
- r for r in refactors
464
- if isinstance(r, dict) and r.get("id")
465
- and status_map.get(r["id"], "pending") not in TERMINAL_STATUSES
466
- ]
467
- if not non_terminal:
468
- print("PIPELINE_COMPLETE")
469
- return
470
-
471
- # Filter to only those with met dependencies
472
- eligible = [r for r in non_terminal if _dependencies_met(r, completed_set)]
473
- if not eligible:
474
- print("PIPELINE_BLOCKED")
475
- return
476
-
477
- # Separate in_progress from pending
478
- in_progress_refactors = []
479
- pending_refactors = []
480
- for r in eligible:
481
- rid = r.get("id")
482
- rstatus = status_map.get(rid, "pending")
483
- if rstatus == "in_progress":
484
- in_progress_refactors.append(r)
485
- elif rstatus == "pending":
486
- pending_refactors.append(r)
487
-
488
- if in_progress_refactors:
489
- candidates = sorted(
490
- in_progress_refactors,
491
- key=lambda r: topo_rank.get(r.get("id"), len(refactors))
492
- )
493
- elif pending_refactors:
494
- candidates = sorted(
495
- pending_refactors,
496
- key=lambda r: topo_rank.get(r.get("id"), len(refactors))
497
- )
498
- else:
499
- print("PIPELINE_BLOCKED")
500
- return
501
-
502
- chosen = candidates[0]
503
- chosen_id = chosen["id"]
504
- chosen_status_data = status_data_map.get(chosen_id, {})
505
- project_root = os.path.abspath(project_root) if project_root else _default_project_root()
506
- resume_phase = _checkpoint_phase_or_cached(
507
- project_root, chosen_id, chosen_status_data,
508
- )
509
-
510
- result = {
511
- "refactor_id": chosen_id,
512
- "title": chosen.get("title", ""),
513
- "type": chosen.get("type", "restructure"),
514
- "priority": chosen.get("priority", "medium"),
515
- "complexity": chosen.get("complexity", "medium"),
516
- "retry_count": chosen_status_data.get("retry_count", 0),
517
- "infra_error_count": chosen_status_data.get("infra_error_count", 0),
518
- "resume_from_phase": resume_phase,
519
- }
520
- result.update(continuation_metadata_summary(chosen_status_data))
521
- print(json.dumps(result, indent=2, ensure_ascii=False))
522
-
523
-
524
- # ---------------------------------------------------------------------------
525
- # Action: update
526
- # ---------------------------------------------------------------------------
527
-
528
- def action_update(args, refactor_list_path, state_dir):
529
- refactor_id = args.refactor_id
530
- session_status = args.session_status
531
- session_id = args.session_id
532
- max_retries = args.max_retries
533
- max_infra_retries = args.max_infra_retries
534
-
535
- if not refactor_id:
536
- error_out("--refactor-id is required for 'update' action")
537
- return
538
- if not session_status:
539
- error_out("--session-status is required for 'update' action")
540
- return
541
-
542
- rs = load_refactor_status(state_dir, refactor_id)
543
-
544
- current_list_status = get_refactor_status_from_list(refactor_list_path, refactor_id)
545
- rs["max_retries"] = max_retries
546
- rs["max_infra_retries"] = max_infra_retries
547
-
548
- # Track what status we write to refactor-list.json
549
- new_status = current_list_status
550
- if args.active_dev_branch:
551
- rs["active_dev_branch"] = args.active_dev_branch
552
- if args.base_branch:
553
- rs["base_branch"] = args.base_branch
554
- if args.last_fatal_error_code:
555
- rs["last_fatal_error_code"] = args.last_fatal_error_code
556
- if args.continuation_summary_path:
557
- rs["continuation_summary_path"] = args.continuation_summary_path
558
- fingerprint = _load_progress_fingerprint(args.progress_fingerprint)
559
- if fingerprint is not None:
560
- rs["last_progress_fingerprint"] = fingerprint
561
- semantic_checkpoint = _sync_semantic_checkpoint(rs, args)
562
-
563
-
564
- if session_status == "success":
565
- rs["infra_error_count"] = 0
566
- rs["last_infra_error_session_id"] = None
567
- clear_pending_continuation_metadata(rs)
568
- new_status = "completed"
569
- rs["resume_from_phase"] = None
570
- err = update_refactor_in_list(refactor_list_path, refactor_id, "completed")
571
- if err:
572
- error_out("Failed to update .prizmkit/plans/refactor-list.json: {}".format(err))
573
- return
574
- elif session_status in ("commit_missing", "docs_missing", "merge_conflict"):
575
- rs["retry_count"] = rs.get("retry_count", 0) + 1
576
-
577
- if rs["retry_count"] >= max_retries:
578
- new_status = "failed"
579
- else:
580
- new_status = "pending"
581
-
582
- rs["degraded_reason"] = session_status
583
- rs["resume_from_phase"] = None
584
- rs["sessions"] = []
585
- rs["last_session_id"] = None
586
-
587
- err = update_refactor_in_list(refactor_list_path, refactor_id, new_status)
588
- if err:
589
- error_out("Failed to update .prizmkit/plans/refactor-list.json: {}".format(err))
590
- return
591
- elif session_status == "infra_error":
592
- # AI CLI/provider outage, auth failure, gateway error, etc.
593
- # Infra failures do not consume the code retry budget, but they still
594
- # need their own bounded budget so a flaky provider cannot loop forever.
595
- infra_error_count = rs.get("infra_error_count", 0) + 1
596
- rs["infra_error_count"] = infra_error_count
597
- rs["last_infra_error_session_id"] = session_id
598
- rs["max_infra_retries"] = max_infra_retries
599
- rs["degraded_reason"] = session_status
600
- if session_id:
601
- rs["last_session_id"] = session_id
602
- rs["resume_from_phase"] = None
603
-
604
- if infra_error_count >= max_infra_retries:
605
- new_status = "failed"
606
- rs["continuation_pending"] = False
607
- rs["continuation_reason"] = session_status
608
- rs["needs_attention"] = True
609
- if session_id:
610
- rs["last_failed_session_id"] = session_id
611
- else:
612
- new_status = "in_progress"
613
- _set_ai_error_continuation_metadata(rs, args, session_id, session_status)
614
-
615
- err = update_refactor_in_list(refactor_list_path, refactor_id, new_status)
616
- if err:
617
- error_out("Failed to update .prizmkit/plans/refactor-list.json: {}".format(err))
618
- return
619
- elif session_status == "context_overflow":
620
- # Preserve resumable context metadata, but every relaunched AI session
621
- # must consume the existing bounded retry budget.
622
- set_context_overflow_continuation_metadata(rs, args, session_id)
623
- rs["retry_count"] = rs.get("retry_count", 0) + 1
624
- if rs["retry_count"] >= max_retries:
625
- new_status = "failed"
626
- rs["continuation_pending"] = False
627
- rs["needs_attention"] = True
628
- if session_id:
629
- rs["last_failed_session_id"] = session_id
630
- else:
631
- new_status = "in_progress"
632
- if current_list_status != new_status:
633
- err = update_refactor_in_list(refactor_list_path, refactor_id, new_status)
634
- if err:
635
- error_out("Failed to update .prizmkit/plans/refactor-list.json: {}".format(err))
636
- return
637
- elif session_status == "workflow_skipped":
638
- # A completed AI CLI session without authoritative workflow evidence is
639
- # skipped, not crashed. Preserve diagnostics and spend no retry budget.
640
- new_status = "skipped"
641
- rs["continuation_pending"] = False
642
- rs.pop("continuation_reason", None)
643
- rs.pop("terminal_status", None)
644
- rs.pop("blocked_reason", None)
645
- rs["needs_attention"] = True
646
- rs["skipped_reason"] = "workflow_completion_evidence_invalid"
647
- err = update_refactor_in_list(refactor_list_path, refactor_id, new_status)
648
- if err:
649
- error_out("Failed to update .prizmkit/plans/refactor-list.json: {}".format(err))
650
- return
651
- elif session_status == "workflow_blocked":
652
- # Semantic terminal state: preserve partial work without consuming any retry budget.
653
- new_status = "failed"
654
- rs["continuation_pending"] = False
655
- rs["needs_attention"] = True
656
- rs["terminal_status"] = "WORKFLOW_BLOCKED"
657
- rs["blocked_reason"] = (
658
- semantic_checkpoint.get("blocked_reason") or "workflow_blocked"
659
- )
660
- err = update_refactor_in_list(refactor_list_path, refactor_id, new_status)
661
- if err:
662
- error_out("Failed to update .prizmkit/plans/refactor-list.json: {}".format(err))
663
- return
664
- elif session_status == "stalled_context_continuation":
665
- # No-progress context-overflow stall pauses automation without consuming retry budgets.
666
- set_stalled_context_continuation_metadata(rs, args, session_id)
667
- new_status = "failed"
668
- err = update_refactor_in_list(refactor_list_path, refactor_id, new_status)
669
- if err:
670
- error_out("Failed to update .prizmkit/plans/refactor-list.json: {}".format(err))
671
- return
672
- else:
673
- rs["retry_count"] = rs.get("retry_count", 0) + 1
674
-
675
- if rs["retry_count"] >= max_retries:
676
- new_status = "failed"
677
- rs["continuation_pending"] = False
678
- rs["continuation_reason"] = session_status
679
- rs["needs_attention"] = True
680
- else:
681
- new_status = "in_progress"
682
- _set_ai_error_continuation_metadata(rs, args, session_id, session_status)
683
-
684
- rs["resume_from_phase"] = None
685
- if session_id:
686
- rs["last_failed_session_id"] = session_id
687
-
688
- err = update_refactor_in_list(refactor_list_path, refactor_id, new_status)
689
- if err:
690
- error_out("Failed to update .prizmkit/plans/refactor-list.json: {}".format(err))
691
- return
692
-
693
- if session_id:
694
- sessions = rs.get("sessions", [])
695
- if session_id not in sessions:
696
- sessions.append(session_id)
697
- rs["sessions"] = sessions
698
- rs["last_session_id"] = session_id
699
-
700
- rs["updated_at"] = now_iso()
701
- # Completed tasks are terminal even when their accepted checkpoint evidence
702
- # remains incomplete; only non-completed outcomes expose a resume cursor.
703
- if new_status == "completed":
704
- rs["resume_from_phase"] = None
705
- else:
706
- _sync_checkpoint_phase(
707
- args.project_root or _default_project_root(), refactor_id, rs,
708
- )
709
-
710
- err = save_refactor_status(state_dir, refactor_id, rs)
711
- if err:
712
- error_out("Failed to save refactor status: {}".format(err))
713
- return
714
-
715
- # Auto-skip downstream refactors for current blockers; otherwise converge
716
- # descendants whose complete transitive blocker set is now empty.
717
- auto_skipped_refactors = []
718
- recovered_auto_skipped = []
719
- if new_status in RESET_BLOCKING_ROOT_STATUSES:
720
- auto_skipped_refactors = auto_skip_blocked_refactors(
721
- refactor_list_path, state_dir, refactor_id
722
- )
723
- else:
724
- try:
725
- recovered_auto_skipped = reconcile_orphaned_auto_skipped_refactors(
726
- refactor_list_path, state_dir
727
- )
728
- except (ValueError, RuntimeError) as exc:
729
- error_out(str(exc))
730
- return
731
-
732
- summary = {
733
- "action": "update",
734
- "refactor_id": refactor_id,
735
- "session_status": session_status,
736
- "new_status": new_status,
737
- "retry_count": rs["retry_count"],
738
- "infra_error_count": rs.get("infra_error_count", 0),
739
- "max_infra_retries": max_infra_retries,
740
- "resume_from_phase": rs.get("resume_from_phase"),
741
- "checkpoint_state": semantic_checkpoint,
742
- "updated_at": rs["updated_at"],
743
- }
744
- if auto_skipped_refactors:
745
- summary["auto_skipped"] = [info["refactor_id"] for info in auto_skipped_refactors]
746
- if recovered_auto_skipped:
747
- summary["recovered_auto_skipped"] = recovered_auto_skipped
748
- if session_status in ("commit_missing", "docs_missing", "merge_conflict"):
749
- summary["degraded_reason"] = session_status
750
- summary["restart_policy"] = "finalization_retry"
751
- elif session_status == "infra_error":
752
- summary["restart_policy"] = "in_process_ai_error_continuation" if new_status == "in_progress" else "needs_attention"
753
- summary["infra_error_count"] = rs.get("infra_error_count", 0)
754
- summary.update(continuation_metadata_summary(rs))
755
- summary["artifacts_preserved"] = True
756
- elif session_status == "context_overflow":
757
- summary["restart_policy"] = "context_overflow_continuation" if new_status == "in_progress" else "needs_attention"
758
- summary.update(continuation_metadata_summary(rs))
759
- summary["artifacts_preserved"] = True
760
- elif session_status == "workflow_skipped":
761
- summary["restart_policy"] = "terminal_skipped"
762
- summary.update(continuation_metadata_summary(rs))
763
- summary["checkpoint_state"] = semantic_checkpoint
764
- summary["artifacts_preserved"] = True
765
- elif session_status == "workflow_blocked":
766
- summary["restart_policy"] = "terminal_blocked"
767
- summary.update(continuation_metadata_summary(rs))
768
- summary["checkpoint_state"] = semantic_checkpoint
769
- summary["artifacts_preserved"] = True
770
- elif session_status == "stalled_context_continuation":
771
- summary["restart_policy"] = "needs_attention"
772
- summary.update(continuation_metadata_summary(rs))
773
- summary["artifacts_preserved"] = True
774
- elif session_status != "success":
775
- summary["restart_policy"] = "in_process_ai_error_continuation" if new_status == "in_progress" else "needs_attention"
776
- summary.update(continuation_metadata_summary(rs))
777
- summary["artifacts_preserved"] = True
778
-
779
- print(json.dumps(summary, indent=2, ensure_ascii=False))
780
-
781
-
782
- def _default_project_root():
783
- env = os.environ.get("PROJECT_ROOT")
784
- if env:
785
- return os.path.abspath(env)
786
- script_dir = os.path.dirname(os.path.abspath(__file__))
787
- pipeline_dir = os.path.dirname(script_dir)
788
- pipeline_parent = os.path.dirname(pipeline_dir)
789
- if os.path.basename(pipeline_parent) == ".prizmkit":
790
- return os.path.dirname(pipeline_parent)
791
- return pipeline_parent
792
-
793
-
794
- def cleanup_refactor_artifacts(state_dir, refactor_id, project_root=None):
795
- """Delete intermediate artifacts for a failed refactor run."""
796
- if not project_root:
797
- project_root = _default_project_root()
798
-
799
- cleaned = []
800
-
801
- # 1) Remove all session history
802
- sessions_dir = os.path.join(state_dir, refactor_id, "sessions")
803
- sessions_deleted = 0
804
- if os.path.isdir(sessions_dir):
805
- for entry in os.listdir(sessions_dir):
806
- entry_path = os.path.join(sessions_dir, entry)
807
- if os.path.isdir(entry_path):
808
- shutil.rmtree(entry_path)
809
- sessions_deleted += 1
810
- cleaned.append("Deleted {} session(s) from {}".format(sessions_deleted, sessions_dir))
811
-
812
- # 2) Remove transient files under refactor dir (keep status.json)
813
- refactor_dir = os.path.join(state_dir, refactor_id)
814
- if os.path.isdir(refactor_dir):
815
- for entry in os.listdir(refactor_dir):
816
- if entry == "status.json" or entry == "sessions":
817
- continue
818
- entry_path = os.path.join(refactor_dir, entry)
819
- if os.path.isdir(entry_path):
820
- shutil.rmtree(entry_path)
821
- cleaned.append("Deleted directory {}".format(entry_path))
822
- elif os.path.isfile(entry_path):
823
- os.remove(entry_path)
824
- cleaned.append("Deleted file {}".format(entry_path))
825
-
826
- # 3) Remove refactor artifacts
827
- refactor_artifact_dir = os.path.join(project_root, REFACTOR_ARTIFACTS_REL, refactor_id)
828
- if os.path.isdir(refactor_artifact_dir):
829
- shutil.rmtree(refactor_artifact_dir)
830
- cleaned.append("Deleted {}".format(refactor_artifact_dir))
831
-
832
- # 4) Remove shared dev-team workspace
833
- dev_team_dir = os.path.join(project_root, DEV_TEAM_DIR_NAME)
834
- if os.path.isdir(dev_team_dir):
835
- shutil.rmtree(dev_team_dir)
836
- cleaned.append("Deleted {}".format(dev_team_dir))
837
-
838
- return cleaned
839
-
840
-
841
- def _resolve_project_file(project_root, path):
842
- if not path:
843
- return None
844
- if os.path.isabs(path):
845
- target = os.path.abspath(path)
846
- else:
847
- target = os.path.abspath(os.path.join(project_root, path))
848
- root = os.path.abspath(project_root)
849
- try:
850
- rel = os.path.relpath(target, root)
851
- except ValueError:
852
- return None
853
- if rel == os.pardir or rel.startswith(os.pardir + os.sep):
854
- return None
855
- return target
856
-
857
-
858
- def cleanup_continuation_artifacts(project_root, status_data, candidate_paths=None):
859
- """Delete durable continuation handoff files for a manual clean reset."""
860
- candidates = []
861
- if isinstance(status_data, dict):
862
- candidates.append(status_data.get("continuation_summary_path"))
863
- candidates.extend(candidate_paths or [])
864
-
865
- cleaned = []
866
- seen = set()
867
- for candidate in candidates:
868
- target = _resolve_project_file(project_root, candidate)
869
- if not target or target in seen:
870
- continue
871
- seen.add(target)
872
- if os.path.basename(target) != "continuation-summary.md":
873
- continue
874
- if os.path.isfile(target):
875
- os.remove(target)
876
- cleaned.append("Deleted continuation artifact {}".format(target))
877
- return cleaned
878
-
879
-
880
- def load_session_status(state_dir, refactor_id, session_id):
881
- session_status_path = os.path.join(state_dir, refactor_id, "sessions",
882
- session_id, "session-status.json"
883
- )
884
- data, err = load_json_file(session_status_path)
885
- if err:
886
- return None, err
887
- return data, None
888
-
889
-
890
- # ---------------------------------------------------------------------------
891
- # Auto-skip: cascade failure to blocked downstream refactors
892
- # ---------------------------------------------------------------------------
893
-
894
- def auto_skip_blocked_refactors(refactor_list_path, state_dir, failed_refactor_id):
895
- """Recursively mark all downstream refactors blocked by a failed refactor as auto_skipped.
896
-
897
- When a refactor is marked as failed, any refactor whose dependency chain includes
898
- the failed refactor can never be executed. This function propagates the failure
899
- by marking those blocked refactors as auto_skipped, allowing the pipeline to
900
- continue processing unblocked refactors and eventually reach PIPELINE_COMPLETE.
901
-
902
- Re-reads .prizmkit/plans/refactor-list.json from disk to get the latest state (including the
903
- just-written failed status from update_refactor_in_list).
904
-
905
- NOTE: This function performs a read-modify-write on .prizmkit/plans/refactor-list.json without
906
- file locking. The caller (action_update) also writes to .prizmkit/plans/refactor-list.json
907
- immediately before calling this. Safe for single-pipeline execution, but if
908
- multiple pipeline instances share the same .prizmkit/plans/refactor-list.json concurrently,
909
- a race condition may cause lost writes. Add file locking if parallel pipelines
910
- are introduced.
911
- """
912
- data, err = load_json_file(refactor_list_path)
913
- if err:
914
- return []
915
- refactors = data.get("refactors", [])
916
-
917
- # Build current status map
918
- status_map = {}
919
- for r in refactors:
920
- if isinstance(r, dict) and r.get("id"):
921
- status_map[r["id"]] = r.get("status", "pending")
922
-
923
- # Collect all refactors to auto-skip (recursive propagation)
924
- to_skip = set()
925
- changed = True
926
- while changed:
927
- changed = False
928
- for r in refactors:
929
- if not isinstance(r, dict):
930
- continue
931
- rid = r.get("id")
932
- if not rid or rid in to_skip:
933
- continue
934
- current = status_map.get(rid, "pending")
935
- if current in TERMINAL_STATUSES:
936
- continue
937
- deps = r.get("dependencies", [])
938
- for dep_id in deps:
939
- dep_status = status_map.get(dep_id, "pending")
940
- if dep_status in ("failed", "skipped", "auto_skipped") or dep_id in to_skip:
941
- to_skip.add(rid)
942
- status_map[rid] = "auto_skipped"
943
- changed = True
944
- break
945
-
946
- if not to_skip:
947
- return []
948
-
949
- # Batch-write to .prizmkit/plans/refactor-list.json
950
- for r in refactors:
951
- if isinstance(r, dict) and r.get("id") in to_skip:
952
- r["status"] = "auto_skipped"
953
- write_json_file(refactor_list_path, data)
954
-
955
- # Update timestamps in status.json for each auto-skipped refactor
956
- for rid in to_skip:
957
- rs = load_refactor_status(state_dir, rid)
958
- rs["updated_at"] = now_iso()
959
- save_refactor_status(state_dir, rid, rs)
960
-
961
- # Build blocking reason map for logging
962
- skipped_info = []
963
- for r in refactors:
964
- if not isinstance(r, dict):
965
- continue
966
- rid = r.get("id")
967
- if rid not in to_skip:
968
- continue
969
- deps = r.get("dependencies", [])
970
- blockers = [
971
- d for d in deps
972
- if d == failed_refactor_id or d in to_skip
973
- ]
974
- skipped_info.append({
975
- "refactor_id": rid,
976
- "title": r.get("title", ""),
977
- "blocked_by": blockers,
978
- })
979
-
980
- print(
981
- "[auto-skip] {} refactor(s) auto-skipped due to failed {}:".format(
982
- len(skipped_info), failed_refactor_id
983
- ),
984
- file=sys.stderr,
985
- )
986
- for info in skipped_info:
987
- print(
988
- " {} ({}) — blocked by {}".format(
989
- info["refactor_id"],
990
- info["title"],
991
- ", ".join(info["blocked_by"]),
992
- ),
993
- file=sys.stderr,
994
- )
995
-
996
- return skipped_info
997
-
998
-
999
- def reconcile_orphaned_auto_skipped_refactors(refactor_list_path, state_dir):
1000
- """Restore auto-skipped refactors that have no current blocking root."""
1001
- data, err = load_json_file(refactor_list_path)
1002
- if err:
1003
- raise RuntimeError("Cannot load refactor list for orphan recovery: {}".format(err))
1004
- refactors = data.get("refactors", [])
1005
- orphan_ids = orphaned_auto_skipped_ids(
1006
- refactors,
1007
- blocking_root_statuses=RESET_BLOCKING_ROOT_STATUSES,
1008
- item_label="Refactor",
1009
- )
1010
- if not orphan_ids:
1011
- return []
1012
-
1013
- orphan_set = set(orphan_ids)
1014
- for refactor in refactors:
1015
- if isinstance(refactor, dict) and refactor.get("id") in orphan_set:
1016
- refactor["status"] = "pending"
1017
- err = write_json_file(refactor_list_path, data)
1018
- if err:
1019
- raise RuntimeError("Failed to recover orphaned refactors: {}".format(err))
1020
-
1021
- for refactor_id in orphan_ids:
1022
- rs = load_refactor_status(state_dir, refactor_id)
1023
- rs["updated_at"] = now_iso()
1024
- err = save_refactor_status(state_dir, refactor_id, rs)
1025
- if err:
1026
- raise RuntimeError("Failed to save recovered refactor status: {}".format(err))
1027
-
1028
- print(
1029
- "[auto-skip] recovered {} orphaned refactor(s): {}".format(
1030
- len(orphan_ids), ", ".join(orphan_ids)
1031
- ),
1032
- file=sys.stderr,
1033
- )
1034
- return list(orphan_ids)
1035
-
1036
-
1037
- # ---------------------------------------------------------------------------
1038
- # Action: status
1039
- # ---------------------------------------------------------------------------
1040
-
1041
- COLOR_GREEN = "\033[92m"
1042
- COLOR_YELLOW = "\033[93m"
1043
- COLOR_RED = "\033[91m"
1044
- COLOR_GRAY = "\033[90m"
1045
- COLOR_MAGENTA = "\033[95m"
1046
- COLOR_CYAN = "\033[96m"
1047
- COLOR_BOLD = "\033[1m"
1048
- COLOR_RESET = "\033[0m"
1049
-
1050
- BOX_WIDTH = 72
1051
-
1052
- TYPE_ICONS = {
1053
- "extract": "📦",
1054
- "rename": "🏷️",
1055
- "restructure": "🏗️",
1056
- "simplify": "✂️",
1057
- "decouple": "🔗",
1058
- "migrate": "🚀",
1059
- }
1060
-
1061
- COMPLEXITY_BADGES = {
1062
- "low": COLOR_GREEN + "[LOW]" + COLOR_RESET,
1063
- "medium": COLOR_YELLOW + "[MED]" + COLOR_RESET,
1064
- "high": COLOR_RED + "[HI]" + COLOR_RESET,
1065
- }
1066
-
1067
-
1068
- def action_status(refactor_list_data, state_dir, project_root=None):
1069
- refactors = refactor_list_data.get("refactors", [])
1070
- project_name = refactor_list_data.get("project_name", "Unknown")
1071
- project_root = os.path.abspath(project_root) if project_root else _default_project_root()
1072
-
1073
- counts = {"completed": 0, "in_progress": 0, "failed": 0, "pending": 0, "skipped": 0, "auto_skipped": 0}
1074
- try:
1075
- orphaned_ids = set(orphaned_auto_skipped_ids(
1076
- refactors,
1077
- blocking_root_statuses=RESET_BLOCKING_ROOT_STATUSES,
1078
- item_label="Refactor",
1079
- ))
1080
- except ValueError:
1081
- orphaned_ids = set()
1082
- refactor_lines = []
1083
-
1084
- for r in refactors:
1085
- if not isinstance(r, dict):
1086
- continue
1087
- rid = r.get("id")
1088
- title = r.get("title", "Untitled")
1089
- rtype = r.get("type", "restructure")
1090
- complexity = r.get("complexity", "medium")
1091
- if not rid:
1092
- continue
1093
-
1094
- rstatus = r.get("status", "pending")
1095
- rs = load_refactor_status(state_dir, rid)
1096
- retry_count = rs.get("retry_count", 0)
1097
- max_retries_val = rs.get("max_retries", 3)
1098
- # Read the authoritative checkpoint cursor without mutating cached runtime state.
1099
- resume_phase = _checkpoint_phase_or_cached(project_root, rid, rs)
1100
-
1101
- if rstatus in counts:
1102
- counts[rstatus] += 1
1103
- else:
1104
- counts["pending"] += 1
1105
-
1106
- # Status icon
1107
- if rstatus == "completed":
1108
- icon = COLOR_GREEN + "[✓]" + COLOR_RESET
1109
- elif rstatus == "in_progress":
1110
- icon = COLOR_YELLOW + "[→]" + COLOR_RESET
1111
- elif rstatus == "failed":
1112
- icon = COLOR_RED + "[✗]" + COLOR_RESET
1113
- elif rstatus == "skipped":
1114
- icon = COLOR_GRAY + "[—]" + COLOR_RESET
1115
- elif rstatus == "auto_skipped":
1116
- icon = COLOR_GRAY + "[⊘]" + COLOR_RESET
1117
- else:
1118
- icon = COLOR_GRAY + "[ ]" + COLOR_RESET
1119
-
1120
- # Type badge
1121
- type_icon = TYPE_ICONS.get(rtype, "🔧")
1122
- type_badge = "[{}]".format(rtype[:6].upper())
1123
-
1124
- # Complexity badge
1125
- cmplx_badge = COMPLEXITY_BADGES.get(complexity, "[MED]")
1126
-
1127
- # Detail
1128
- detail = ""
1129
- if rstatus == "in_progress":
1130
- parts = []
1131
- if retry_count > 0:
1132
- parts.append("retry {}/{}".format(retry_count, max_retries_val))
1133
- if resume_phase is not None:
1134
- parts.append("CP-RF-{}".format(resume_phase))
1135
- if parts:
1136
- detail = " ({})".format(", ".join(parts))
1137
- elif rstatus == "failed":
1138
- detail = " (failed after {} retries)".format(retry_count)
1139
- elif rstatus == "auto_skipped" and rid in orphaned_ids:
1140
- detail = " (orphaned: no blocking dependency)"
1141
-
1142
- # Colorize title based on status
1143
- if rstatus == "completed":
1144
- colored_title = COLOR_GREEN + title + COLOR_RESET
1145
- elif rstatus == "in_progress":
1146
- colored_title = COLOR_YELLOW + title + COLOR_RESET
1147
- elif rstatus == "failed":
1148
- colored_title = COLOR_RED + title + COLOR_RESET
1149
- else:
1150
- colored_title = COLOR_GRAY + title + COLOR_RESET
1151
-
1152
- line_content = "{} {} {} {} {} {} {}{}".format(
1153
- rid, icon, type_badge, cmplx_badge, type_icon, colored_title, "", detail
1154
- )
1155
-
1156
- refactor_lines.append(line_content)
1157
-
1158
- total = len(refactors)
1159
- completed = counts["completed"]
1160
- percent = round(completed / total * 100, 1) if total > 0 else 0.0
1161
- progress_bar = _build_progress_bar(percent, width=24)
1162
-
1163
- summary_line = "Total: {} refactors | Completed: {} | In Progress: {}".format(
1164
- total, completed, counts["in_progress"]
1165
- )
1166
- summary_line2 = "Failed: {} | Pending: {} | Skipped: {} | Auto-skipped: {}".format(
1167
- counts["failed"], counts["pending"], counts["skipped"], counts["auto_skipped"]
1168
- )
1169
-
1170
- inner = BOX_WIDTH - 2
1171
- print("╔" + "═" * BOX_WIDTH + "╗")
1172
- print("║" + pad_right(COLOR_BOLD + " Refactor Pipeline Status" + COLOR_RESET, inner) + " ║")
1173
- print("╠" + "═" * BOX_WIDTH + "╣")
1174
- print("║" + pad_right(" Project: {}".format(project_name), inner) + " ║")
1175
- print("║" + pad_right(" {}".format(summary_line), inner) + " ║")
1176
- print("║" + pad_right(" {}".format(summary_line2), inner) + " ║")
1177
- print("╠" + "─" * BOX_WIDTH + "╣")
1178
- print("║" + pad_right(" Progress: {}".format(progress_bar), inner) + " ║")
1179
- print("╠" + "═" * BOX_WIDTH + "╣")
1180
- for line in refactor_lines:
1181
- print("║" + pad_right(" {}".format(line), inner) + " ║")
1182
- print("╚" + "═" * BOX_WIDTH + "╝")
1183
-
1184
-
1185
- # ---------------------------------------------------------------------------
1186
- # Action: reset
1187
- # ---------------------------------------------------------------------------
1188
-
1189
- def action_reset(args, refactor_list_path, state_dir):
1190
- refactor_id = args.refactor_id
1191
- if not refactor_id:
1192
- error_out("--refactor-id is required for 'reset' action")
1193
- return
1194
-
1195
- rs = load_refactor_status(state_dir, refactor_id)
1196
- old_status = get_refactor_status_from_list(refactor_list_path, refactor_id)
1197
- old_retry = rs.get("retry_count", 0)
1198
-
1199
- rs["retry_count"] = 0
1200
- rs["infra_error_count"] = 0
1201
- rs["last_infra_error_session_id"] = None
1202
- rs["sessions"] = []
1203
- rs["last_session_id"] = None
1204
- rs["resume_from_phase"] = None
1205
- reset_continuation_metadata(rs)
1206
- rs["updated_at"] = now_iso()
1207
-
1208
- err = save_refactor_status(state_dir, refactor_id, rs)
1209
- if err:
1210
- error_out("Failed to save refactor status: {}".format(err))
1211
- return
1212
-
1213
- err = update_refactor_in_list(refactor_list_path, refactor_id, "pending")
1214
- if err:
1215
- error_out("Failed to update .prizmkit/plans/refactor-list.json: {}".format(err))
1216
- return
1217
-
1218
- result = {
1219
- "action": "reset",
1220
- "refactor_id": refactor_id,
1221
- "old_status": old_status,
1222
- "old_retry_count": old_retry,
1223
- "new_status": "pending",
1224
- }
1225
- print(json.dumps(result, indent=2, ensure_ascii=False))
1226
-
1227
-
1228
- # ---------------------------------------------------------------------------
1229
- # Action: clean
1230
- # ---------------------------------------------------------------------------
1231
-
1232
- def action_clean(args, refactor_list_path, state_dir):
1233
- refactor_id = args.refactor_id
1234
- project_root = args.project_root
1235
-
1236
- if not refactor_id:
1237
- error_out("--refactor-id is required for 'clean' action")
1238
- return
1239
- if not project_root:
1240
- error_out("--project-root is required for 'clean' action")
1241
- return
1242
-
1243
- cleaned = []
1244
-
1245
- # 1. Delete session history
1246
- sessions_dir = os.path.join(state_dir, refactor_id, "sessions")
1247
- sessions_deleted = 0
1248
- if os.path.isdir(sessions_dir):
1249
- for entry in os.listdir(sessions_dir):
1250
- entry_path = os.path.join(sessions_dir, entry)
1251
- if os.path.isdir(entry_path):
1252
- shutil.rmtree(entry_path)
1253
- sessions_deleted += 1
1254
- cleaned.append("Deleted {} session(s) from {}".format(sessions_deleted, sessions_dir))
1255
-
1256
- # 2. Delete refactor artifacts for this refactor
1257
- refactor_artifact_dir = os.path.join(project_root, REFACTOR_ARTIFACTS_REL, refactor_id)
1258
- if os.path.isdir(refactor_artifact_dir):
1259
- shutil.rmtree(refactor_artifact_dir)
1260
- cleaned.append("Deleted {}".format(refactor_artifact_dir))
1261
-
1262
- # 3. Delete shared dev-team workspace
1263
- dev_team_dir = os.path.join(project_root, DEV_TEAM_DIR_NAME)
1264
- if os.path.isdir(dev_team_dir):
1265
- shutil.rmtree(dev_team_dir)
1266
- cleaned.append("Deleted {}".format(dev_team_dir))
1267
-
1268
- # 4. Reset status
1269
- rs = load_refactor_status(state_dir, refactor_id)
1270
- old_status = get_refactor_status_from_list(refactor_list_path, refactor_id)
1271
- old_retry = rs.get("retry_count", 0)
1272
-
1273
- continuation_candidates = [
1274
- os.path.join(".prizmkit", "refactor", refactor_id, "continuation-summary.md"),
1275
- os.path.join(".prizmkit", "specs", refactor_id, "continuation-summary.md"),
1276
- ]
1277
- cleaned.extend(cleanup_continuation_artifacts(project_root, rs, continuation_candidates))
1278
-
1279
- rs["retry_count"] = 0
1280
- rs["infra_error_count"] = 0
1281
- rs["last_infra_error_session_id"] = None
1282
- rs["sessions"] = []
1283
- rs["last_session_id"] = None
1284
- rs["resume_from_phase"] = None
1285
- reset_continuation_metadata(rs)
1286
- rs["updated_at"] = now_iso()
1287
-
1288
- err = save_refactor_status(state_dir, refactor_id, rs)
1289
- if err:
1290
- error_out("Failed to save refactor status: {}".format(err))
1291
- return
1292
-
1293
- err = update_refactor_in_list(refactor_list_path, refactor_id, "pending")
1294
- if err:
1295
- error_out("Failed to update .prizmkit/plans/refactor-list.json: {}".format(err))
1296
- return
1297
-
1298
- result = {
1299
- "action": "clean",
1300
- "refactor_id": refactor_id,
1301
- "old_status": old_status,
1302
- "old_retry_count": old_retry,
1303
- "new_status": "pending",
1304
- "sessions_deleted": sessions_deleted,
1305
- "cleaned": cleaned,
1306
- }
1307
- print(json.dumps(result, indent=2, ensure_ascii=False))
1308
-
1309
-
1310
- # ---------------------------------------------------------------------------
1311
- # Action: pause
1312
- # ---------------------------------------------------------------------------
1313
-
1314
- def action_pause(state_dir):
1315
- pipeline_path = os.path.join(state_dir, "pipeline.json")
1316
- data, err = load_json_file(pipeline_path)
1317
- if err:
1318
- data = {"status": "paused", "paused_at": now_iso()}
1319
- else:
1320
- data["status"] = "paused"
1321
- data["paused_at"] = now_iso()
1322
-
1323
- err = write_json_file(pipeline_path, data)
1324
- if err:
1325
- error_out("Failed to write pipeline.json: {}".format(err))
1326
- return
1327
-
1328
- result = {
1329
- "action": "pause",
1330
- "status": "paused",
1331
- "paused_at": data["paused_at"],
1332
- }
1333
- print(json.dumps(result, indent=2, ensure_ascii=False))
1334
-
1335
-
1336
- # ---------------------------------------------------------------------------
1337
- # Action: start
1338
- # ---------------------------------------------------------------------------
1339
-
1340
- def action_start(args, refactor_list_path, state_dir):
1341
- """Mark a refactor as in_progress when a session starts.
1342
-
1343
- This keeps refactor-list.json/state status in sync during execution,
1344
- instead of only updating after session end.
1345
- """
1346
- refactor_id = args.refactor_id
1347
- if not refactor_id:
1348
- error_out("--refactor-id is required for 'start' action")
1349
- return
1350
-
1351
- rs = load_refactor_status(state_dir, refactor_id)
1352
- old_status = get_refactor_status_from_list(refactor_list_path, refactor_id)
1353
-
1354
- rs["max_retries"] = args.max_retries
1355
- rs["max_infra_retries"] = args.max_infra_retries
1356
- rs["updated_at"] = now_iso()
1357
-
1358
- err = save_refactor_status(state_dir, refactor_id, rs)
1359
- if err:
1360
- error_out("Failed to save refactor status: {}".format(err))
1361
- return
1362
-
1363
- if old_status != "in_progress":
1364
- err = update_refactor_in_list(refactor_list_path, refactor_id, "in_progress")
1365
- if err:
1366
- error_out("Failed to update .prizmkit/plans/refactor-list.json: {}".format(err))
1367
- return
1368
-
1369
- try:
1370
- recovered_auto_skipped = reconcile_orphaned_auto_skipped_refactors(
1371
- refactor_list_path, state_dir
1372
- )
1373
- except (ValueError, RuntimeError) as exc:
1374
- error_out(str(exc))
1375
- return
1376
-
1377
- result = {
1378
- "action": "start",
1379
- "refactor_id": refactor_id,
1380
- "old_status": old_status,
1381
- "new_status": "in_progress",
1382
- "retry_count": rs.get("retry_count", 0),
1383
- "infra_error_count": rs.get("infra_error_count", 0),
1384
- "updated_at": rs["updated_at"],
1385
- }
1386
- if recovered_auto_skipped:
1387
- result["recovered_auto_skipped"] = recovered_auto_skipped
1388
- print(json.dumps(result, indent=2, ensure_ascii=False))
1389
-
1390
-
1391
- # ---------------------------------------------------------------------------
1392
- # Action: reset_state
1393
- # ---------------------------------------------------------------------------
1394
-
1395
- def action_reset_state(args, refactor_list_path, state_dir):
1396
- """Reset one causal refactor closure, or every recoverable closure, to pending."""
1397
- data, err = load_json_file(refactor_list_path)
1398
- if err:
1399
- error_out("Cannot load refactor list: {}".format(err))
1400
- return
1401
- refactors = data.get("refactors", [])
1402
-
1403
- try:
1404
- recovery_ids = causal_reset_selection(
1405
- refactors,
1406
- selected_id=args.refactor_id,
1407
- blocking_root_statuses=RESET_BLOCKING_ROOT_STATUSES,
1408
- item_label="Refactor",
1409
- )
1410
- except ValueError as exc:
1411
- error_out(str(exc))
1412
- return
1413
-
1414
- to_reset = set(recovery_ids)
1415
- reset_details = []
1416
- for refactor in refactors:
1417
- if isinstance(refactor, dict) and refactor.get("id") in to_reset:
1418
- old_status = refactor.get("status", "unknown")
1419
- refactor["status"] = "pending"
1420
- reset_details.append({
1421
- "refactor_id": refactor["id"],
1422
- "title": refactor.get("title", ""),
1423
- "old_status": old_status,
1424
- })
1425
-
1426
- err = write_json_file(refactor_list_path, data)
1427
- if err:
1428
- error_out("Failed to write .prizmkit/plans/refactor-list.json: {}".format(err))
1429
- return
1430
-
1431
- for refactor_id in recovery_ids:
1432
- rs = load_refactor_status(state_dir, refactor_id)
1433
- checkout_identity = {
1434
- key: rs[key]
1435
- for key in ("active_dev_branch", "base_branch")
1436
- if key in rs
1437
- }
1438
- rs["retry_count"] = 0
1439
- rs["infra_error_count"] = 0
1440
- rs["last_infra_error_session_id"] = None
1441
- rs["sessions"] = []
1442
- rs["last_session_id"] = None
1443
- rs["last_failed_session_id"] = None
1444
- rs["resume_from_phase"] = None
1445
- reset_continuation_metadata(rs)
1446
- rs.update(checkout_identity)
1447
- rs["updated_at"] = now_iso()
1448
- err = save_refactor_status(state_dir, refactor_id, rs)
1449
- if err:
1450
- error_out("Failed to save refactor status: {}".format(err))
1451
- return
1452
-
1453
- result = {
1454
- "action": "reset_state",
1455
- "reset_count": len(recovery_ids),
1456
- "refactors": reset_details,
1457
- }
1458
- print(json.dumps(result, indent=2, ensure_ascii=False))
1459
-
1460
-
1461
- # ---------------------------------------------------------------------------
1462
- # Main
1463
- # ---------------------------------------------------------------------------
1464
-
1465
- def main():
1466
- args = parse_args()
1467
-
1468
- if args.action == "update":
1469
- if not args.refactor_id:
1470
- error_out("--refactor-id is required for 'update' action")
1471
- if not args.session_status:
1472
- error_out("--session-status is required for 'update' action")
1473
- if args.action in ("start", "reset", "clean", "complete"):
1474
- if not args.refactor_id:
1475
- error_out("--refactor-id is required for '{}' action".format(args.action))
1476
- if args.action == "clean":
1477
- if not args.project_root:
1478
- error_out("--project-root is required for 'clean' action")
1479
-
1480
- refactor_list_data, err = load_json_file(args.refactor_list)
1481
- if err:
1482
- error_out("Cannot load refactor list: {}".format(err))
1483
-
1484
- if args.action == "get_next":
1485
- action_get_next(
1486
- refactor_list_data,
1487
- args.state_dir,
1488
- args.project_root,
1489
- args.refactor_list,
1490
- )
1491
- elif args.action == "update":
1492
- action_update(args, args.refactor_list, args.state_dir)
1493
- elif args.action == "status":
1494
- action_status(refactor_list_data, args.state_dir, args.project_root)
1495
- elif args.action == "reset":
1496
- action_reset(args, args.refactor_list, args.state_dir)
1497
- elif args.action == "clean":
1498
- action_clean(args, args.refactor_list, args.state_dir)
1499
- elif args.action == "start":
1500
- action_start(args, args.refactor_list, args.state_dir)
1501
- elif args.action == "pause":
1502
- action_pause(args.state_dir)
1503
- elif args.action == "reset_state":
1504
- action_reset_state(args, args.refactor_list, args.state_dir)
1505
- elif args.action == "complete":
1506
- # Shortcut: 'complete' is equivalent to 'update --session-status success'
1507
- args.session_status = "success"
1508
- action_update(args, args.refactor_list, args.state_dir)
1509
-
1510
-
1511
- if __name__ == "__main__":
1512
- main()