prizmkit 1.1.69 → 1.1.72

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 (57) hide show
  1. package/bundled/VERSION.json +3 -3
  2. package/bundled/dev-pipeline/lib/common.sh +427 -0
  3. package/bundled/dev-pipeline/lib/heartbeat.sh +36 -0
  4. package/bundled/dev-pipeline/run-feature.sh +109 -29
  5. package/bundled/dev-pipeline/scripts/generate-bootstrap-prompt.py +11 -12
  6. package/bundled/dev-pipeline/scripts/parse-stream-progress.py +160 -3
  7. package/bundled/dev-pipeline/scripts/update-feature-status.py +27 -3
  8. package/bundled/dev-pipeline/templates/agent-prompts/dev-implement.md +36 -22
  9. package/bundled/dev-pipeline/templates/agent-prompts/reviewer-review.md +1 -1
  10. package/bundled/dev-pipeline/templates/bugfix-bootstrap-prompt.md +24 -21
  11. package/bundled/dev-pipeline/templates/refactor-bootstrap-prompt.md +13 -26
  12. package/bundled/dev-pipeline/templates/sections/ac-verification-checklist.md +4 -10
  13. package/bundled/dev-pipeline/templates/sections/context-budget-rules.md +1 -0
  14. package/bundled/dev-pipeline/templates/sections/feature-context.md +16 -11
  15. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-auto.md +17 -26
  16. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-opencli.md +1 -1
  17. package/bundled/dev-pipeline/templates/sections/phase-browser-verification.md +1 -1
  18. package/bundled/dev-pipeline/templates/sections/phase-commit-full.md +11 -0
  19. package/bundled/dev-pipeline/templates/sections/phase-commit.md +11 -0
  20. package/bundled/dev-pipeline/templates/sections/phase-context-snapshot-base.md +1 -1
  21. package/bundled/dev-pipeline/templates/sections/phase-implement-agent.md +2 -9
  22. package/bundled/dev-pipeline/templates/sections/phase-implement-full.md +2 -9
  23. package/bundled/dev-pipeline/templates/sections/phase-implement-lite.md +8 -17
  24. package/bundled/dev-pipeline/templates/sections/phase-plan-lite.md +1 -1
  25. package/bundled/dev-pipeline/templates/sections/phase-review-full.md +1 -1
  26. package/bundled/dev-pipeline/templates/sections/phase-specify-plan-full.md +1 -1
  27. package/bundled/dev-pipeline/templates/sections/task-contract.md +34 -0
  28. package/bundled/dev-pipeline/templates/sections/test-failure-recovery-agent.md +27 -46
  29. package/bundled/dev-pipeline/templates/sections/test-failure-recovery-lite.md +27 -37
  30. package/bundled/dev-pipeline/tests/test_generate_bootstrap_prompt.py +13 -0
  31. package/bundled/dev-pipeline-windows/lib/common.ps1 +61 -1
  32. package/bundled/dev-pipeline-windows/lib/pipeline.ps1 +299 -14
  33. package/bundled/dev-pipeline-windows/scripts/generate-bootstrap-prompt.py +11 -12
  34. package/bundled/dev-pipeline-windows/scripts/parse-stream-progress.py +160 -3
  35. package/bundled/dev-pipeline-windows/scripts/update-feature-status.py +27 -3
  36. package/bundled/dev-pipeline-windows/templates/agent-prompts/dev-implement.md +36 -22
  37. package/bundled/dev-pipeline-windows/templates/agent-prompts/reviewer-review.md +1 -1
  38. package/bundled/dev-pipeline-windows/templates/bugfix-bootstrap-prompt.md +24 -21
  39. package/bundled/dev-pipeline-windows/templates/refactor-bootstrap-prompt.md +13 -26
  40. package/bundled/dev-pipeline-windows/templates/sections/ac-verification-checklist.md +4 -10
  41. package/bundled/dev-pipeline-windows/templates/sections/context-budget-rules.md +1 -0
  42. package/bundled/dev-pipeline-windows/templates/sections/feature-context.md +16 -11
  43. package/bundled/dev-pipeline-windows/templates/sections/phase-browser-verification-auto.md +22 -10
  44. package/bundled/dev-pipeline-windows/templates/sections/phase-commit-full.md +11 -0
  45. package/bundled/dev-pipeline-windows/templates/sections/phase-commit.md +11 -0
  46. package/bundled/dev-pipeline-windows/templates/sections/phase-context-snapshot-base.md +1 -1
  47. package/bundled/dev-pipeline-windows/templates/sections/phase-implement-agent.md +2 -9
  48. package/bundled/dev-pipeline-windows/templates/sections/phase-implement-full.md +2 -9
  49. package/bundled/dev-pipeline-windows/templates/sections/phase-implement-lite.md +8 -19
  50. package/bundled/dev-pipeline-windows/templates/sections/phase-plan-lite.md +1 -1
  51. package/bundled/dev-pipeline-windows/templates/sections/phase-review-full.md +1 -1
  52. package/bundled/dev-pipeline-windows/templates/sections/phase-specify-plan-full.md +1 -1
  53. package/bundled/dev-pipeline-windows/templates/sections/task-contract.md +34 -0
  54. package/bundled/dev-pipeline-windows/templates/sections/test-failure-recovery-agent.md +27 -46
  55. package/bundled/dev-pipeline-windows/templates/sections/test-failure-recovery-lite.md +27 -37
  56. package/bundled/skills/_metadata.json +1 -1
  57. package/package.json +1 -1
@@ -77,13 +77,16 @@ FEATURE_LIST=""
77
77
  # Branch tracking (for cleanup on interrupt)
78
78
  _ORIGINAL_BRANCH=""
79
79
  _DEV_BRANCH_NAME=""
80
+ _SPAWN_FEATURE_SLUG=""
81
+ _SPAWN_EXIT_CODE=0
80
82
 
81
83
  # ============================================================
82
84
  # Shared: Spawn an AI CLI session and wait for result
83
85
  # ============================================================
84
86
 
85
87
  # Spawns an AI CLI session with heartbeat + timeout, waits for completion,
86
- # checks session status, and updates feature status.
88
+ # and checks session status. Canonical status updates happen after the caller
89
+ # returns to the original branch.
87
90
  #
88
91
  # Arguments:
89
92
  # $1 - feature_id
@@ -105,6 +108,9 @@ spawn_and_wait_session() {
105
108
  local session_log="$session_dir/logs/session.log"
106
109
  local progress_json="$session_dir/logs/progress.json"
107
110
 
111
+ _SPAWN_FEATURE_SLUG=""
112
+ _SPAWN_EXIT_CODE=0
113
+
108
114
  local effective_model="${feature_model:-$MODEL}"
109
115
  local cbc_pid
110
116
  prizm_start_ai_session "$bootstrap_prompt" "$session_log" "$effective_model"
@@ -144,6 +150,7 @@ spawn_and_wait_session() {
144
150
  if [[ $exit_code -eq 143 ]]; then
145
151
  exit_code=124
146
152
  fi
153
+ _SPAWN_EXIT_CODE="$exit_code"
147
154
 
148
155
  # Check for stale-kill marker (heartbeat killed the process due to no progress)
149
156
  local stale_kill_marker="$session_dir/logs/stale-kill.json"
@@ -174,7 +181,28 @@ spawn_and_wait_session() {
174
181
  project_root="$PROJECT_ROOT"
175
182
  local default_branch="$base_branch"
176
183
 
177
- if [[ $exit_code -eq 124 ]]; then
184
+ local semantic_finalized=false
185
+ local semantic_feature_slug=""
186
+ local semantic_commit_sha=""
187
+ local was_ai_runtime_error=false
188
+ if prizm_detect_ai_runtime_error "$session_log" "$progress_json"; then
189
+ was_ai_runtime_error=true
190
+ fi
191
+
192
+ if prizm_feature_semantically_complete "$feature_list" "$feature_id" "$project_root" "$default_branch" "$PRIZMKIT_DIR"; then
193
+ semantic_finalized=true
194
+ semantic_feature_slug="$PRIZM_SEMANTIC_FEATURE_SLUG"
195
+ semantic_commit_sha="$PRIZM_SEMANTIC_COMMIT_SHA"
196
+ if [[ $exit_code -ne 0 || "$was_stale_killed" == true || "$was_ai_runtime_error" == true ]]; then
197
+ log_warn "Session ended with a failure signal after semantic completion; treating as finalized success"
198
+ log_warn "Semantic completion commit: ${semantic_commit_sha:-unknown}"
199
+ fi
200
+ session_status="success"
201
+ elif [[ "$was_ai_runtime_error" == true ]]; then
202
+ log_warn "Session failed due to structured AI runtime/context error"
203
+ log_warn "AI runtime errors are retried without consuming code retry budget"
204
+ session_status="infra_error"
205
+ elif [[ $exit_code -eq 124 ]]; then
178
206
  log_warn "Session timed out after ${SESSION_TIMEOUT}s"
179
207
  session_status="timed_out"
180
208
  elif [[ "$was_infra_error" == true ]]; then
@@ -222,15 +250,31 @@ spawn_and_wait_session() {
222
250
  # ── Post-success validation ──────────────────────────────────────────
223
251
  if [[ "$session_status" == "success" ]]; then
224
252
  if git -C "$project_root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
225
- # Auto-commit any remaining dirty files produced during the session
226
253
  local dirty_files=""
227
254
  dirty_files=$(git -C "$project_root" status --porcelain 2>/dev/null || true)
228
255
  if [[ -n "$dirty_files" ]]; then
229
- log_info "Auto-committing remaining session artifacts..."
230
- git -C "$project_root" add -A 2>/dev/null || true
231
- git -C "$project_root" commit --no-verify --amend --no-edit 2>/dev/null \
232
- || git -C "$project_root" commit --no-verify -m "chore($feature_id): include remaining session artifacts" 2>/dev/null \
233
- || true
256
+ if [[ "$semantic_finalized" == true ]]; then
257
+ local post_completion_slug="$semantic_feature_slug"
258
+ if [[ -z "$post_completion_slug" ]]; then
259
+ post_completion_slug=$(prizm_feature_slug_from_list "$feature_list" "$feature_id" 2>/dev/null || true)
260
+ fi
261
+ if [[ -n "$post_completion_slug" ]] && prizm_preserve_post_completion_dirty "$project_root" "$PRIZMKIT_DIR/specs/${post_completion_slug}" "$feature_id" "$session_id"; then
262
+ log_warn "Post-completion dirty changes preserved under $PRIZMKIT_DIR/specs/${post_completion_slug}/"
263
+ log_warn "They were not included in the finalized feature commit."
264
+ else
265
+ log_warn "Could not safely preserve post-completion dirty changes; preserving dev branch for manual finalization"
266
+ session_status="finalization_needed"
267
+ fi
268
+ else
269
+ # Auto-commit any remaining dirty files produced during a normal
270
+ # clean success path. Semantic finalization explicitly avoids this
271
+ # so delayed post-commit findings cannot be merged into main.
272
+ log_info "Auto-committing remaining session artifacts..."
273
+ git -C "$project_root" add -A 2>/dev/null || true
274
+ git -C "$project_root" commit --no-verify --amend --no-edit 2>/dev/null \
275
+ || git -C "$project_root" commit --no-verify -m "chore($feature_id): include remaining session artifacts" 2>/dev/null \
276
+ || true
277
+ fi
234
278
  fi
235
279
  fi
236
280
  fi
@@ -242,7 +286,10 @@ spawn_and_wait_session() {
242
286
 
243
287
  # Write lightweight session summary for post-session inspection
244
288
  local feature_slug
245
- feature_slug=$(python3 -c "
289
+ if [[ -n "$semantic_feature_slug" ]]; then
290
+ feature_slug="$semantic_feature_slug"
291
+ else
292
+ feature_slug=$(python3 -c "
246
293
  import json, re, sys
247
294
  flist, fid = sys.argv[1], sys.argv[2]
248
295
  with open(flist) as f:
@@ -258,9 +305,11 @@ for feat in data.get('features', []):
258
305
  sys.exit(0)
259
306
  sys.exit(1)
260
307
  " "$feature_list" "$feature_id" 2>/dev/null) || {
261
- log_warn "Could not resolve feature slug for $feature_id — session summary and artifact validation will be skipped"
262
- feature_slug=""
263
- }
308
+ log_warn "Could not resolve feature slug for $feature_id — session summary and artifact validation will be skipped"
309
+ feature_slug=""
310
+ }
311
+ fi
312
+ _SPAWN_FEATURE_SLUG="$feature_slug"
264
313
 
265
314
  # Validate key artifacts exist after successful session
266
315
  if [[ "$session_status" == "success" && -n "$feature_slug" ]]; then
@@ -315,16 +364,6 @@ sys.exit(0)
315
364
  fi
316
365
  fi
317
366
 
318
- # Check if session produced a failure-log for future retries
319
- if [[ "$session_status" != "success" && -n "$feature_slug" ]]; then
320
- local failure_log="$PRIZMKIT_DIR/specs/${feature_slug}/failure-log.md"
321
- if [[ -f "$failure_log" ]]; then
322
- log_info "FAILURE_LOG: Session wrote failure-log.md — will be available to next retry"
323
- else
324
- log_info "FAILURE_LOG: No failure-log.md written by session"
325
- fi
326
- fi
327
-
328
367
  # Propagate completion notes for dependency context (only on success)
329
368
  if [[ "$session_status" == "success" && -n "$feature_slug" ]]; then
330
369
  local summary_path="$PRIZMKIT_DIR/specs/$feature_slug/completion-summary.json"
@@ -342,7 +381,45 @@ sys.exit(0)
342
381
  fi
343
382
  fi
344
383
 
345
- # Update feature status (do NOT commit on dev branch — commit happens after merge)
384
+ # Return status via global variable (avoids $() swallowing stdout)
385
+ _SPAWN_RESULT="$session_status"
386
+ }
387
+
388
+ finalize_feature_status_after_branch_return() {
389
+ local feature_id="$1"
390
+ local feature_list="$2"
391
+ local session_id="$3"
392
+ local session_status="$4"
393
+ local max_retries="$5"
394
+ local session_dir="$6"
395
+ local base_branch="${7:-main}"
396
+
397
+ local feature_slug="${_SPAWN_FEATURE_SLUG:-}"
398
+ local progress_json="$session_dir/logs/progress.json"
399
+ local stale_kill_marker="$session_dir/logs/stale-kill.json"
400
+ local exit_code="${_SPAWN_EXIT_CODE:-0}"
401
+
402
+ # Check if session produced a failure-log for future retries; synthesize one
403
+ # after branch return so canonical diagnostics live on the original branch.
404
+ if [[ "$session_status" != "success" && -n "$feature_slug" ]]; then
405
+ local failure_log="$PRIZMKIT_DIR/specs/${feature_slug}/failure-log.md"
406
+ local checkpoint_file_for_failure="$PRIZMKIT_DIR/specs/${feature_slug}/workflow-checkpoint.json"
407
+ if [[ -f "$failure_log" ]]; then
408
+ log_info "FAILURE_LOG: Session wrote failure-log.md — will be available to next retry"
409
+ else
410
+ prizm_synthesize_failure_log \
411
+ "$failure_log" "$feature_id" "$session_id" "$session_status" "$exit_code" \
412
+ "$stale_kill_marker" "$progress_json" "$checkpoint_file_for_failure" "$PROJECT_ROOT" "$base_branch"
413
+ if [[ -f "$failure_log" ]]; then
414
+ log_info "FAILURE_LOG: Runtime synthesized failure-log.md — will be available to next retry"
415
+ else
416
+ log_info "FAILURE_LOG: No failure-log.md written by session"
417
+ fi
418
+ fi
419
+ fi
420
+
421
+ # Update feature status on the original branch. The caller commits the
422
+ # resulting feature-list diff immediately after this helper returns.
346
423
  local update_output
347
424
  update_output=$(python3 "$SCRIPTS_DIR/update-feature-status.py" \
348
425
  --feature-list "$feature_list" \
@@ -357,9 +434,6 @@ sys.exit(0)
357
434
  }
358
435
 
359
436
  _SPAWN_ITEM_STATUS="$(printf '%s' "$update_output" | prizm_extract_update_new_status)"
360
-
361
- # Return status via global variable (avoids $() swallowing stdout)
362
- _SPAWN_RESULT="$session_status"
363
437
  }
364
438
 
365
439
  # ============================================================
@@ -896,7 +970,7 @@ else:
896
970
  else
897
971
  log_warn "Auto-merge failed — dev branch preserved: $_DEV_BRANCH_NAME"
898
972
  log_warn "Merge manually: git checkout $_ORIGINAL_BRANCH && git rebase $_DEV_BRANCH_NAME"
899
- _DEV_BRANCH_NAME=""
973
+ session_status="merge_conflict"
900
974
  fi
901
975
  elif [[ -n "$_DEV_BRANCH_NAME" ]]; then
902
976
  # Session failed — preserve dev branch for inspection
@@ -907,6 +981,9 @@ else:
907
981
  # GUARANTEED: always return to original branch regardless of success/failure/merge outcome
908
982
  branch_ensure_return "$_proj_root" "$_ORIGINAL_BRANCH"
909
983
 
984
+ finalize_feature_status_after_branch_return \
985
+ "$feature_id" "$feature_list" "$session_id" "$session_status" 999 "$session_dir" "$_ORIGINAL_BRANCH"
986
+
910
987
  # Commit feature status update on the original branch (after guaranteed return)
911
988
  if ! git -C "$_proj_root" diff --quiet "$feature_list" 2>/dev/null; then
912
989
  git -C "$_proj_root" add "$feature_list"
@@ -1318,7 +1395,6 @@ DEPLOY_PROMPT_EOF
1318
1395
  "$feature_id" "$feature_list" "$session_id" \
1319
1396
  "$bootstrap_prompt" "$session_dir" "$MAX_RETRIES" "$feature_model" "$_ORIGINAL_BRANCH"
1320
1397
  local session_status="$_SPAWN_RESULT"
1321
- local item_status_after_session="${_SPAWN_ITEM_STATUS:-}"
1322
1398
 
1323
1399
  # Merge per-feature dev branch back to original on success
1324
1400
  if [[ "$session_status" == "success" && -n "$_DEV_BRANCH_NAME" ]]; then
@@ -1327,7 +1403,7 @@ DEPLOY_PROMPT_EOF
1327
1403
  else
1328
1404
  log_warn "Auto-merge failed — dev branch preserved: $_DEV_BRANCH_NAME"
1329
1405
  log_warn "Merge manually: git checkout $_ORIGINAL_BRANCH && git rebase $_DEV_BRANCH_NAME"
1330
- _DEV_BRANCH_NAME=""
1406
+ session_status="merge_conflict"
1331
1407
  fi
1332
1408
  elif [[ -n "$_DEV_BRANCH_NAME" ]]; then
1333
1409
  # Session failed — preserve dev branch for inspection
@@ -1338,6 +1414,10 @@ DEPLOY_PROMPT_EOF
1338
1414
  # GUARANTEED: always return to original branch regardless of success/failure/merge outcome
1339
1415
  branch_ensure_return "$_proj_root" "$_ORIGINAL_BRANCH"
1340
1416
 
1417
+ finalize_feature_status_after_branch_return \
1418
+ "$feature_id" "$feature_list" "$session_id" "$session_status" "$MAX_RETRIES" "$session_dir" "$_ORIGINAL_BRANCH"
1419
+ local item_status_after_session="${_SPAWN_ITEM_STATUS:-}"
1420
+
1341
1421
  # Commit feature status update on the original branch (after guaranteed return)
1342
1422
  if ! git -C "$_proj_root" diff --quiet "$feature_list" 2>/dev/null; then
1343
1423
  git -C "$_proj_root" add "$feature_list"
@@ -248,7 +248,7 @@ def extract_baseline_failures(test_cmd, project_root):
248
248
  def format_ac_checklist(acceptance_criteria):
249
249
  """Format acceptance criteria as a markdown checkbox list."""
250
250
  if not acceptance_criteria:
251
- return "- [ ] (no acceptance criteria specified)"
251
+ return "- (no Verification Gates specified)"
252
252
  lines = []
253
253
  for item in acceptance_criteria:
254
254
  lines.append("- [ ] {}".format(item))
@@ -285,10 +285,10 @@ def format_user_context(user_context):
285
285
  if not items:
286
286
  return ""
287
287
  lines = [
288
- "### User-Provided Context (HIGHEST PRIORITY)",
289
- "",
290
- "> The following materials were provided by the user. "
291
- "They take precedence over AI inference.",
288
+ "> These materials were provided by the user and are authoritative "
289
+ "when they clarify or constrain this feature. They do not expand "
290
+ "the current scope by themselves; use the Task Contract to decide "
291
+ "what belongs to this session.",
292
292
  "",
293
293
  ]
294
294
  for item in items:
@@ -932,6 +932,10 @@ def assemble_sections(pipeline_mode, sections_dir, init_done, is_resume,
932
932
  mission += "\n\n" + tier_desc
933
933
  sections.append(("mission", mission))
934
934
 
935
+ # --- Task Contract: single source of current scope and gates ---
936
+ sections.append(("task-contract",
937
+ load_section(sections_dir, "task-contract.md")))
938
+
935
939
  # --- Feature Context (XML-wrapped, optimization 3) ---
936
940
  sections.append(("feature-context",
937
941
  load_section(sections_dir, "feature-context.md")))
@@ -1041,13 +1045,8 @@ def assemble_sections(pipeline_mode, sections_dir, init_done, is_resume,
1041
1045
  load_section(sections_dir,
1042
1046
  "test-failure-recovery-agent.md")))
1043
1047
 
1044
- # --- AC Verification Checklist (all tiers) ---
1045
- ac_checklist_path = os.path.join(sections_dir, "ac-verification-checklist.md")
1046
- if os.path.isfile(ac_checklist_path):
1047
- sections.append(("ac-verification-checklist",
1048
- load_section(sections_dir,
1049
- "ac-verification-checklist.md")))
1050
-
1048
+ # Verification Gates are included in Task Contract. Keep AC in one place so
1049
+ # background context and implementation prompts cannot redefine scope.
1051
1050
  # --- Review (only for agent tiers) ---
1052
1051
  if pipeline_mode == "full":
1053
1052
  sections.append(("phase-review",
@@ -17,6 +17,7 @@ The script runs until:
17
17
  import argparse
18
18
  import json
19
19
  import os
20
+ import re
20
21
  import signal
21
22
  import sys
22
23
  import tempfile
@@ -59,6 +60,58 @@ PHASE_KEYWORDS = {
59
60
  },
60
61
  }
61
62
 
63
+ CONTEXT_ERROR_PATTERNS = [
64
+ re.compile(pattern, re.IGNORECASE)
65
+ for pattern in (
66
+ r"context_too_large",
67
+ r"model_context_window_exceeded",
68
+ r"Your input exceeds the context window",
69
+ r"input exceeds the context window",
70
+ r"context window of this model",
71
+ r"context window exceeded",
72
+ r"invalid_request_error.*context window",
73
+ r"context window.*invalid_request_error",
74
+ )
75
+ ]
76
+
77
+ ERROR_CONTEXT_PATTERNS = [
78
+ re.compile(pattern, re.IGNORECASE)
79
+ for pattern in (
80
+ r"\bapi error\b",
81
+ r"invalid_request_error",
82
+ r"\bstatus\s*[:=]?\s*(400|413)\b",
83
+ r"\bapi_error_status\b",
84
+ r"\bapi_error_code\b",
85
+ r"\blast_result_is_error\b\s*[\"':=]*\s*true\b",
86
+ r"\bis_error\b\s*[\"':=]*\s*true\b",
87
+ )
88
+ ]
89
+
90
+
91
+ def _has_error_context(text):
92
+ """Return true when free text looks like a runtime/provider error."""
93
+ if not text:
94
+ return False
95
+ return any(pattern.search(text) for pattern in ERROR_CONTEXT_PATTERNS)
96
+
97
+
98
+ def detect_api_error_code(text, require_error_context=False):
99
+ """Return a normalized fatal/runtime error code from terminal text.
100
+
101
+ Structured terminal result/error events and raw stderr can be matched
102
+ directly. Ordinary assistant prose is noisier: it may mention the phrase
103
+ "input exceeds the context window" while explaining a test or recovery
104
+ rule, so callers can require additional error-like context there.
105
+ """
106
+ if not text:
107
+ return ""
108
+ if require_error_context and not _has_error_context(text):
109
+ return ""
110
+ for pattern in CONTEXT_ERROR_PATTERNS:
111
+ if pattern.search(text):
112
+ return "context_too_large"
113
+ return ""
114
+
62
115
 
63
116
  class ProgressTracker:
64
117
  """Tracks progress state from stream-json events."""
@@ -73,6 +126,12 @@ class ProgressTracker:
73
126
  self.tool_call_counts = Counter()
74
127
  self.total_tool_calls = 0
75
128
  self.last_text_snippet = ""
129
+ self.last_result_is_error = False
130
+ self.api_error_status = None
131
+ self.api_error_code = ""
132
+ self.terminal_result_text = ""
133
+ self.terminal_success_at = ""
134
+ self.fatal_error_code = ""
76
135
  self.is_active = True
77
136
  self.errors = []
78
137
  self.event_format = ""
@@ -164,11 +223,13 @@ class ProgressTracker:
164
223
  elif event_type == "turn.failed":
165
224
  error = event.get("error") or event.get("message") or "Codex turn failed"
166
225
  self.errors.append(str(error))
226
+ self._detect_terminal_error(str(error))
167
227
  self.current_tool = None
168
228
 
169
229
  elif event_type == "error":
170
230
  error = event.get("error") or event.get("message") or "Unknown error"
171
231
  self.errors.append(str(error))
232
+ self._detect_terminal_error(str(error))
172
233
 
173
234
  return
174
235
 
@@ -196,6 +257,7 @@ class ProgressTracker:
196
257
  if text.strip():
197
258
  self.last_text_snippet = text.strip()[:120]
198
259
  self._detect_phase(text)
260
+ self._detect_terminal_error(text, require_error_context=True)
199
261
 
200
262
  elif event_type == "tool_result" or event_type == "user":
201
263
  # tool_result contains output from tool execution
@@ -274,6 +336,28 @@ class ProgressTracker:
274
336
  state.setdefault("subagent_type", "")
275
337
  self._update_claude_subagent_status_counts()
276
338
 
339
+ elif event_type == "result":
340
+ self.event_format = self.event_format or "stream-json"
341
+ self.is_active = False
342
+ result_text = event.get("result") or event.get("message") or ""
343
+ error_obj = event.get("error")
344
+ if isinstance(error_obj, dict):
345
+ error_text = " ".join(
346
+ str(error_obj.get(key) or "")
347
+ for key in ("type", "code", "message")
348
+ if error_obj.get(key)
349
+ )
350
+ result_text = " ".join(part for part in (str(result_text), error_text) if part)
351
+ api_error_code = event.get("api_error_code") or event.get("error_code") or ""
352
+ if isinstance(error_obj, dict) and not api_error_code:
353
+ api_error_code = error_obj.get("code") or error_obj.get("type") or ""
354
+ self._record_terminal_result(
355
+ text=str(result_text or ""),
356
+ is_error=bool(event.get("is_error")),
357
+ api_error_status=event.get("api_error_status"),
358
+ api_error_code=str(api_error_code or ""),
359
+ )
360
+
277
361
  # ── Claude API raw stream format ────────────────────────────
278
362
  elif event_type == "message_start":
279
363
  self.event_format = self.event_format or "stream-json"
@@ -316,6 +400,7 @@ class ProgressTracker:
316
400
  self.last_text_snippet = stripped[:120]
317
401
  # Try to detect phase from text
318
402
  self._detect_phase(text)
403
+ self._detect_terminal_error(text, require_error_context=True)
319
404
 
320
405
  elif delta_type == "input_json_delta":
321
406
  partial = delta.get("partial_json", "")
@@ -331,21 +416,73 @@ class ProgressTracker:
331
416
  self._extract_tool_summary(full_input)
332
417
  self._detect_phase(full_input)
333
418
  else:
334
- # Text block finished - detect phase from accumulated text
419
+ # Text block finished - detect phase and terminal errors from accumulated text
335
420
  if self._text_buffer:
336
421
  self._detect_phase(self._text_buffer)
422
+ self._detect_terminal_error(
423
+ self._text_buffer,
424
+ require_error_context=True,
425
+ )
337
426
  self._in_tool_use = False
338
427
  self._current_tool_input_parts = []
339
428
 
340
429
  elif event_type == "error":
341
430
  error_msg = event.get("error", {}).get("message", "Unknown error")
342
431
  self.errors.append(error_msg)
432
+ self._detect_terminal_error(str(error_msg))
343
433
 
344
434
  # Check for subagent indicator
345
435
  if event.get("parent_tool_use_id"):
346
436
  # This is a sub-agent event; tool name is still tracked normally
347
437
  pass
348
438
 
439
+ def _record_terminal_result(self, text="", is_error=False, api_error_status=None, api_error_code=""):
440
+ """Record a Claude Code terminal result event."""
441
+ terminal_text = str(text or "")
442
+ self.last_result_is_error = bool(is_error)
443
+ if api_error_status not in (None, ""):
444
+ try:
445
+ self.api_error_status = int(api_error_status)
446
+ except (TypeError, ValueError):
447
+ self.api_error_status = api_error_status
448
+ error_like_result = (
449
+ self.last_result_is_error
450
+ or api_error_status not in (None, "")
451
+ or bool(api_error_code)
452
+ or _has_error_context(terminal_text)
453
+ )
454
+ normalized_code = detect_api_error_code(
455
+ " ".join([str(api_error_code or ""), terminal_text]),
456
+ require_error_context=not error_like_result,
457
+ )
458
+ if normalized_code:
459
+ self.api_error_code = normalized_code
460
+ self.fatal_error_code = normalized_code
461
+ elif api_error_code:
462
+ self.api_error_code = str(api_error_code)
463
+ self.terminal_result_text = terminal_text[:1000]
464
+ if terminal_text.strip():
465
+ self.last_text_snippet = terminal_text.strip()[:120]
466
+ if not self.last_result_is_error and not self.fatal_error_code:
467
+ self.terminal_success_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
468
+ elif self.fatal_error_code:
469
+ self.errors.append(self.fatal_error_code)
470
+
471
+ def _detect_terminal_error(self, text, require_error_context=False):
472
+ """Detect fatal context-window errors from unstructured text."""
473
+ code = detect_api_error_code(
474
+ str(text or ""),
475
+ require_error_context=require_error_context,
476
+ )
477
+ if not code:
478
+ return
479
+ self.last_result_is_error = True
480
+ self.api_error_code = code
481
+ self.fatal_error_code = code
482
+ self.terminal_result_text = str(text or "")[:1000]
483
+ if text:
484
+ self.last_text_snippet = str(text).strip()[:120]
485
+
349
486
  def _detect_phase(self, text):
350
487
  """Detect pipeline phase from text content.
351
488
 
@@ -692,6 +829,12 @@ class ProgressTracker:
692
829
  "child_activity_signature": self.child_activity_signature,
693
830
  "last_child_activity_at": self.last_child_activity_at,
694
831
  "last_text_snippet": self.last_text_snippet,
832
+ "last_result_is_error": self.last_result_is_error,
833
+ "api_error_status": self.api_error_status,
834
+ "api_error_code": self.api_error_code,
835
+ "terminal_result_text": self.terminal_result_text,
836
+ "terminal_success_at": self.terminal_success_at,
837
+ "fatal_error_code": self.fatal_error_code,
695
838
  "is_active": self.is_active,
696
839
  "errors": self.errors[-10:], # Keep last 10 errors
697
840
  }
@@ -728,6 +871,12 @@ def tail_and_parse(session_log, progress_file, poll_interval=0.5):
728
871
  state["current_phase"],
729
872
  state["total_tool_calls"],
730
873
  state.get("child_activity_signature", ""),
874
+ state.get("last_result_is_error"),
875
+ state.get("api_error_status"),
876
+ state.get("api_error_code", ""),
877
+ state.get("fatal_error_code", ""),
878
+ state.get("terminal_result_text", ""),
879
+ tuple(state.get("errors", [])),
731
880
  )
732
881
 
733
882
  # Wait for log file to appear
@@ -752,11 +901,19 @@ def tail_and_parse(session_log, progress_file, poll_interval=0.5):
752
901
  event = json.loads(line)
753
902
  tracker.process_event(event)
754
903
  except json.JSONDecodeError:
755
- # Not a JSON line (could be stderr mixed in)
756
- # Use it as a text snippet if meaningful
904
+ # Not a JSON line (could be stderr mixed in). Use it as a
905
+ # text snippet and only treat it as terminal when it has a
906
+ # strong API/runtime error marker; ordinary assistant prose
907
+ # can discuss context limits without being fatal.
757
908
  stripped = line.strip()
758
909
  if stripped and len(stripped) > 5:
759
910
  tracker.last_text_snippet = stripped[:120]
911
+ tracker._detect_terminal_error(stripped, require_error_context=True)
912
+ current_state = tracker.to_dict()
913
+ current_state_key = state_key(current_state)
914
+ if current_state_key != last_write_state:
915
+ atomic_write_json(current_state, progress_file)
916
+ last_write_state = current_state_key
760
917
  continue
761
918
 
762
919
  # Write progress if state changed
@@ -49,6 +49,7 @@ SESSION_STATUS_VALUES = [
49
49
  "commit_missing",
50
50
  "docs_missing",
51
51
  "merge_conflict",
52
+ "finalization_needed",
52
53
  ]
53
54
 
54
55
  TERMINAL_STATUSES = {"completed", "failed", "skipped", "auto_skipped", "split"}
@@ -644,7 +645,25 @@ def action_update(args, feature_list_path, state_dir):
644
645
  fs["degraded_reason"] = session_status
645
646
  fs["resume_from_phase"] = None
646
647
  fs["sessions"] = []
647
- fs["last_session_id"] = None
648
+ if session_id:
649
+ fs["last_session_id"] = session_id
650
+ fs["last_failed_session_id"] = session_id
651
+
652
+ err = update_feature_in_list(feature_list_path, feature_id, new_status)
653
+ if err:
654
+ error_out("Failed to update .prizmkit/plans/feature-list.json: {}".format(err))
655
+ return
656
+ elif session_status == "finalization_needed":
657
+ # Runtime preserved dirty post-completion changes but could not safely
658
+ # clean them for automatic merge. Preserve the dev branch and stop for
659
+ # manual finalization instead of spending code retry budget.
660
+ new_status = "failed"
661
+ fs["degraded_reason"] = session_status
662
+ fs["resume_from_phase"] = None
663
+ fs["finalization_needed_count"] = fs.get("finalization_needed_count", 0) + 1
664
+ if session_id:
665
+ fs["last_session_id"] = session_id
666
+ fs["last_failed_session_id"] = session_id
648
667
 
649
668
  err = update_feature_in_list(feature_list_path, feature_id, new_status)
650
669
  if err:
@@ -657,6 +676,8 @@ def action_update(args, feature_list_path, state_dir):
657
676
  new_status = "pending"
658
677
  fs["infra_error_count"] = fs.get("infra_error_count", 0) + 1
659
678
  fs["last_infra_error_session_id"] = session_id
679
+ if session_id:
680
+ fs["last_session_id"] = session_id
660
681
  fs["resume_from_phase"] = None
661
682
 
662
683
  err = update_feature_in_list(feature_list_path, feature_id, new_status)
@@ -673,6 +694,9 @@ def action_update(args, feature_list_path, state_dir):
673
694
  new_status = "pending"
674
695
 
675
696
  fs["resume_from_phase"] = None
697
+ if session_id:
698
+ fs["last_session_id"] = session_id
699
+ fs["last_failed_session_id"] = session_id
676
700
  # Keep sessions list and last_session_id for debugging
677
701
 
678
702
  err = update_feature_in_list(feature_list_path, feature_id, new_status)
@@ -712,9 +736,9 @@ def action_update(args, feature_list_path, state_dir):
712
736
  }
713
737
  if auto_skipped_features:
714
738
  summary["auto_skipped"] = [info["feature_id"] for info in auto_skipped_features]
715
- if session_status in ("commit_missing", "docs_missing", "merge_conflict"):
739
+ if session_status in ("commit_missing", "docs_missing", "merge_conflict", "finalization_needed"):
716
740
  summary["degraded_reason"] = session_status
717
- summary["restart_policy"] = "finalization_retry"
741
+ summary["restart_policy"] = "manual_finalization" if session_status == "finalization_needed" else "finalization_retry"
718
742
  elif session_status == "infra_error":
719
743
  summary["restart_policy"] = "infra_retry"
720
744
  summary["infra_error_count"] = fs.get("infra_error_count", 0)