prizmkit 1.1.193 → 1.1.195

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 (79) hide show
  1. package/bin/create-prizmkit.js +43 -12
  2. package/bundled/VERSION.json +3 -3
  3. package/bundled/dev-pipeline/.env.example +5 -0
  4. package/bundled/dev-pipeline/README.md +2 -1
  5. package/bundled/dev-pipeline/prizmkit_runtime/checkpoint_state.py +111 -30
  6. package/bundled/dev-pipeline/prizmkit_runtime/cli.py +44 -3
  7. package/bundled/dev-pipeline/prizmkit_runtime/commands.py +29 -9
  8. package/bundled/dev-pipeline/prizmkit_runtime/config.py +121 -44
  9. package/bundled/dev-pipeline/prizmkit_runtime/daemon.py +190 -37
  10. package/bundled/dev-pipeline/prizmkit_runtime/interoperability.py +1 -0
  11. package/bundled/dev-pipeline/prizmkit_runtime/iterate.py +2480 -0
  12. package/bundled/dev-pipeline/prizmkit_runtime/paths.py +3 -0
  13. package/bundled/dev-pipeline/prizmkit_runtime/runner_bookkeeping.py +32 -8
  14. package/bundled/dev-pipeline/prizmkit_runtime/runners.py +29 -12
  15. package/bundled/dev-pipeline/prizmkit_runtime/runtime_commit.py +13 -5
  16. package/bundled/dev-pipeline/prizmkit_runtime/status.py +166 -0
  17. package/bundled/dev-pipeline/scripts/feature_list_contract.py +964 -0
  18. package/bundled/dev-pipeline/scripts/generate-bootstrap-prompt.py +18 -40
  19. package/bundled/dev-pipeline/scripts/generate-bugfix-prompt.py +24 -19
  20. package/bundled/dev-pipeline/scripts/prompt_framework.py +24 -8
  21. package/bundled/dev-pipeline/templates/bootstrap-tier3.md +1 -63
  22. package/bundled/dev-pipeline/templates/bug-fix-list-schema.json +8 -6
  23. package/bundled/dev-pipeline/templates/bugfix-bootstrap-prompt.md +0 -10
  24. package/bundled/dev-pipeline/templates/feature-list-schema.json +8 -6
  25. package/bundled/dev-pipeline/templates/iterate/evaluate-prompt.md +97 -0
  26. package/bundled/dev-pipeline/templates/iterate/evaluation-schema.json +538 -0
  27. package/bundled/dev-pipeline/templates/iterate/headless-plan-prompt.md +66 -0
  28. package/bundled/dev-pipeline/templates/sections/phase-specify-plan-full.md +2 -2
  29. package/bundled/dev-pipeline/templates/sections/runtime-commit-handoff.md +13 -4
  30. package/bundled/rules/USAGE.md +15 -48
  31. package/bundled/rules/_rules-metadata.json +7 -14
  32. package/bundled/rules/general/coding-baseline.md +23 -0
  33. package/bundled/rules/prizm/prizm-progressive-loading.md +2 -2
  34. package/bundled/skills/_metadata.json +12 -42
  35. package/bundled/skills/app-planner/SKILL.md +2 -2
  36. package/bundled/skills/app-planner/references/generated-plan-review.md +2 -2
  37. package/bundled/skills/app-planner/references/project-state-detection.md +1 -1
  38. package/bundled/skills/app-planner/references/rules-configuration.md +158 -88
  39. package/bundled/skills/app-planner/scripts/validate-rules-configuration.py +543 -12
  40. package/bundled/skills/bug-planner/references/verification.md +4 -5
  41. package/bundled/skills/bugfix-pipeline-launcher/SKILL.md +20 -14
  42. package/bundled/skills/bugfix-pipeline-launcher/references/configuration.md +49 -9
  43. package/bundled/skills/feature-pipeline-launcher/SKILL.md +20 -14
  44. package/bundled/skills/feature-pipeline-launcher/references/configuration.md +49 -9
  45. package/bundled/skills/feature-planner/SKILL.md +3 -3
  46. package/bundled/skills/feature-planner/references/browser-interaction.md +9 -29
  47. package/bundled/skills/iterate-pipeline-launcher/SKILL.md +273 -0
  48. package/bundled/skills/iterate-pipeline-launcher/references/configuration.md +105 -0
  49. package/bundled/skills/prizmkit-code-review/SKILL.md +10 -8
  50. package/bundled/skills/prizmkit-code-review/references/independent-code-review.md +4 -1
  51. package/bundled/skills/prizmkit-code-review/references/review-report-template.md +2 -1
  52. package/bundled/skills/prizmkit-code-review/scripts/render_review_report.py +12 -8
  53. package/bundled/skills/prizmkit-implement/SKILL.md +2 -2
  54. package/bundled/skills/prizmkit-init/SKILL.md +10 -10
  55. package/bundled/skills/prizmkit-init/references/brownfield-deep-init.md +81 -0
  56. package/bundled/skills/prizmkit-plan/SKILL.md +2 -1
  57. package/bundled/skills/prizmkit-plan/assets/plan-template.md +2 -0
  58. package/bundled/skills/prizmkit-prizm-docs/SKILL.md +8 -4
  59. package/bundled/skills/prizmkit-prizm-docs/assets/prizm-docs-format.md +8 -7
  60. package/bundled/skills/prizmkit-prizm-docs/references/op-init.md +33 -16
  61. package/bundled/skills/prizmkit-prizm-docs/references/op-validate.md +1 -1
  62. package/bundled/skills/prizmkit-retrospective/SKILL.md +29 -12
  63. package/bundled/skills/prizmkit-retrospective/references/retrospective-result-schema.json +126 -2
  64. package/bundled/skills/prizmkit-retrospective/references/rule-evolution-steps.md +86 -0
  65. package/bundled/skills/prizmkit-test/SKILL.md +2 -1
  66. package/bundled/skills/prizmkit-workflow/SKILL.md +8 -0
  67. package/bundled/skills/prizmkit-workflow/references/cold-start-rules.md +84 -0
  68. package/bundled/templates/project-memory-template.md +3 -3
  69. package/package.json +1 -1
  70. package/src/clean.js +2 -3
  71. package/src/config.js +52 -39
  72. package/src/index.js +29 -111
  73. package/src/prompts.js +20 -87
  74. package/src/runtime-passthrough.js +324 -0
  75. package/src/scaffold.js +41 -294
  76. package/src/upgrade.js +7 -39
  77. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-auto.md +0 -127
  78. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-opencli.md +0 -124
  79. package/src/external-skills.js +0 -103
@@ -0,0 +1,2480 @@
1
+ """Autonomous strictly serial product-iteration runtime loop."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import importlib.util
7
+ import json
8
+ import os
9
+ import signal
10
+ import sys
11
+ import tempfile
12
+ import threading
13
+ from collections.abc import Mapping, Sequence
14
+ from contextlib import contextmanager
15
+ from dataclasses import dataclass
16
+ from datetime import datetime, timezone
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from .atomic_io import write_json_atomic, write_text_atomic
21
+ from .config import load_env_file, load_runtime_config
22
+ from .gitops import ensure_branch_has_commit, ensure_git_repository, run_git_command
23
+ from .paths import RuntimePaths
24
+ from .processes import PidLockError, RuntimeInterruption, exclusive_pid_lock, shield_interruption_signals
25
+ from .results import CommandResult
26
+ from .runner_models import RunnerEnvironment
27
+ from .runners import run_pipeline_command
28
+ from .sessions import AISessionConfig, AISessionLauncher, detect_stream_json_support
29
+
30
+ EVALUATION_SCHEMA_VERSION = "prizmkit-iterate-evaluation-v1"
31
+ DEFAULT_SAFETY_CAP = 10
32
+ DEFAULT_CHECKPOINT_EVERY = 5
33
+ MAX_PLAN_REPAIR_RETRIES = 2
34
+ MAX_CONSECUTIVE_FAILURES = 2
35
+ MAX_CONSECUTIVE_NO_PROGRESS = 2
36
+
37
+ PRODUCT_SHAPES = frozenset({"web_saas", "cli_devtool", "mobile", "api_sdk", "internal_ops"})
38
+ EVIDENCE_MODES = frozenset({"live_walkthrough", "source_only"})
39
+ EVIDENCE_TIERS = frozenset({"fact", "inference", "taste"})
40
+ PAIN_LENSES = frozenset(
41
+ {
42
+ "stall",
43
+ "hollow_success",
44
+ "trust_and_control",
45
+ "power_and_limits",
46
+ "failure",
47
+ "second_use",
48
+ }
49
+ )
50
+ DIVERGENT_LENSES = frozenset(
51
+ {
52
+ "adjacent_wish",
53
+ "seeing_others",
54
+ "time_and_ritual",
55
+ "stretch_idea",
56
+ }
57
+ )
58
+ ALL_LENSES = PAIN_LENSES | DIVERGENT_LENSES
59
+ BLAST_RADIUS_LEVELS = frozenset({"low", "medium", "high"})
60
+ BLAST_RADIUS_FLAGS = frozenset(
61
+ {
62
+ "schema_migration",
63
+ "heavy_dependency",
64
+ "paid_external_api",
65
+ "breaking_contract",
66
+ "major_ia_redesign",
67
+ "over_3_features",
68
+ }
69
+ )
70
+ VERDICTS = frozenset(
71
+ {
72
+ "CONTINUE_WITH_CANDIDATES",
73
+ "PAUSE_FOR_USER_CONFIRM",
74
+ "STOP_GOAL_REACHED",
75
+ "STOP_NO_HIGH_VALUE",
76
+ }
77
+ )
78
+
79
+ _EVAL_ROOT_KEYS = frozenset(
80
+ {
81
+ "schema_version",
82
+ "product_shapes",
83
+ "evidence_mode",
84
+ "walkthrough_notes",
85
+ "candidates_discovered",
86
+ "approved_candidates",
87
+ "requires_user_confirm",
88
+ "rejected_candidates",
89
+ "verdict",
90
+ "summary",
91
+ }
92
+ )
93
+ _WALKTHROUGH_KEYS = frozenset({"target_attempted", "server_cleanup_confirmed", "reason"})
94
+ _DISCOVERED_KEYS = frozenset(
95
+ {
96
+ "id",
97
+ "title",
98
+ "lens",
99
+ "evidence_tier",
100
+ "evidence",
101
+ "problem",
102
+ "desired_outcome",
103
+ "blast_radius",
104
+ "blast_radius_flags",
105
+ "gate_results",
106
+ "disposition_reason",
107
+ }
108
+ )
109
+ _GATE_RESULT_KEYS = frozenset(
110
+ {
111
+ "gate1_scope_dedupe",
112
+ "gate2_fact_admission",
113
+ "gate3_blast_radius",
114
+ "gate4_selected",
115
+ }
116
+ )
117
+ _APPROVED_KEYS = frozenset(
118
+ {
119
+ "id",
120
+ "title",
121
+ "lens",
122
+ "evidence_tier",
123
+ "evidence",
124
+ "problem",
125
+ "desired_outcome",
126
+ "blast_radius",
127
+ "blast_radius_flags",
128
+ "target_paths",
129
+ "acceptance_hints",
130
+ "ui_affected",
131
+ }
132
+ )
133
+ _CONFIRM_KEYS = frozenset(
134
+ {
135
+ "id",
136
+ "title",
137
+ "evidence_tier",
138
+ "lens",
139
+ "blast_radius_flags",
140
+ "problem",
141
+ "proposal",
142
+ "decision_needed",
143
+ "evidence",
144
+ }
145
+ )
146
+ _REJECTED_KEYS = frozenset(
147
+ {
148
+ "id",
149
+ "title",
150
+ "evidence_tier",
151
+ "lens",
152
+ "rejected_by_gate",
153
+ "reason",
154
+ }
155
+ )
156
+
157
+ _WORKSPACE_READONLY_EXCLUDES = (
158
+ ":(top,exclude).prizmkit/state",
159
+ ":(top,exclude,glob).prizmkit/state/**",
160
+ ":(top,exclude,glob)**/__pycache__",
161
+ ":(top,exclude,glob)**/__pycache__/**",
162
+ ":(top,exclude,glob)**/*.py[cod]",
163
+ )
164
+
165
+ _PROGRESS_BOOKKEEPING_EXCLUDES = (
166
+ ":(top,exclude).prizmkit/plans/feature-list.json",
167
+ ":(top,exclude).prizmkit/state",
168
+ ":(top,exclude,glob).prizmkit/state/**",
169
+ ":(top,exclude,glob)**/__pycache__",
170
+ ":(top,exclude,glob)**/__pycache__/**",
171
+ ":(top,exclude,glob)**/*.py[cod]",
172
+ )
173
+
174
+
175
+ @dataclass(frozen=True)
176
+ class IterateLimits:
177
+ """Cohesive round control and circuit-breaker limits for iterate runs."""
178
+
179
+ max_rounds: int | None = None
180
+ safety_cap: int = DEFAULT_SAFETY_CAP
181
+ checkpoint_every: int = DEFAULT_CHECKPOINT_EVERY
182
+ checkpoint_every_explicit: bool = False
183
+ no_checkpoint: bool = False
184
+ max_consecutive_failures: int = MAX_CONSECUTIVE_FAILURES
185
+ max_consecutive_no_progress: int = MAX_CONSECUTIVE_NO_PROGRESS
186
+
187
+ def to_dict(self) -> dict[str, object]:
188
+ return {
189
+ "max_rounds": self.max_rounds,
190
+ "safety_cap": self.safety_cap,
191
+ "checkpoint_every": self.checkpoint_every,
192
+ "no_checkpoint": self.no_checkpoint,
193
+ "max_consecutive_failures": self.max_consecutive_failures,
194
+ "max_consecutive_no_progress": self.max_consecutive_no_progress,
195
+ }
196
+
197
+
198
+ @dataclass(frozen=True)
199
+ class IterateOptions:
200
+ """Parsed foreground options for `run iterate`."""
201
+
202
+ limits: IterateLimits
203
+ focus: str = ""
204
+ dry_run: bool = False
205
+ help_requested: bool = False
206
+ unknown_args: tuple[str, ...] = ()
207
+
208
+
209
+ @dataclass(frozen=True)
210
+ class IteratePaths:
211
+ """Filesystem contract under `.prizmkit/state/iterate/`."""
212
+
213
+ state_dir: Path
214
+ state_file: Path
215
+ ledger_file: Path
216
+ events_file: Path
217
+ lock_path: Path
218
+ pending_decisions_file: Path
219
+ summary_file: Path
220
+ rounds_dir: Path
221
+
222
+ @classmethod
223
+ def from_runtime_paths(cls, paths: RuntimePaths) -> "IteratePaths":
224
+ root = paths.iterate_state_dir
225
+ return cls(
226
+ state_dir=root,
227
+ state_file=root / "state.json",
228
+ ledger_file=root / "ledger.json",
229
+ events_file=root / "events.jsonl",
230
+ lock_path=root / ".iterate.lock",
231
+ pending_decisions_file=root / "pending-decisions.md",
232
+ summary_file=root / "summary.md",
233
+ rounds_dir=root / "rounds",
234
+ )
235
+
236
+
237
+ @dataclass(frozen=True)
238
+ class WorkspaceFingerprint:
239
+ """Deterministic snapshot of Git HEAD, index, working tree, and non-state .prizmkit files."""
240
+
241
+ head: str
242
+ staged_digest: str
243
+ entries: tuple[tuple[str, str, str], ...]
244
+ prizmkit_entries: tuple[tuple[str, str], ...] = ()
245
+
246
+
247
+ def _utc_iso() -> str:
248
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
249
+
250
+
251
+ def _emit_log(message: str, *, level: str = "INFO") -> None:
252
+ print(f"[iterate:{level}] {message}", file=sys.stderr, flush=True)
253
+
254
+
255
+ def _parse_positive_int(raw: str, label: str) -> int:
256
+ try:
257
+ value = int(str(raw).strip())
258
+ except ValueError as exc:
259
+ raise ValueError(f"{label} must be a positive integer, got {raw!r}") from exc
260
+ if value < 1:
261
+ raise ValueError(f"{label} must be >= 1, got {value}")
262
+ return value
263
+
264
+
265
+ def parse_iterate_options(
266
+ legacy_args: Sequence[str],
267
+ env_values: Mapping[str, str] | None = None,
268
+ ) -> IterateOptions:
269
+ """Parse `run iterate` CLI arguments with environment fallbacks."""
270
+ env = dict(os.environ if env_values is None else env_values)
271
+ args = tuple(str(arg) for arg in legacy_args)
272
+
273
+ max_rounds: int | None = None
274
+ focus: str | None = None
275
+ checkpoint_every: int | None = None
276
+ checkpoint_every_explicit = False
277
+ no_checkpoint = False
278
+ dry_run = False
279
+ help_requested = False
280
+ unknown: list[str] = []
281
+
282
+ index = 0
283
+ while index < len(args):
284
+ arg = args[index]
285
+ if arg in {"--help", "-h"}:
286
+ help_requested = True
287
+ elif arg == "--dry-run":
288
+ dry_run = True
289
+ elif arg == "--no-checkpoint":
290
+ no_checkpoint = True
291
+ elif arg == "--max-rounds":
292
+ if index + 1 >= len(args):
293
+ raise ValueError("--max-rounds requires a positive integer")
294
+ index += 1
295
+ max_rounds = _parse_positive_int(args[index], "--max-rounds")
296
+ elif arg.startswith("--max-rounds="):
297
+ max_rounds = _parse_positive_int(arg.split("=", 1)[1], "--max-rounds")
298
+ elif arg == "--focus":
299
+ if index + 1 >= len(args):
300
+ raise ValueError("--focus requires a value")
301
+ index += 1
302
+ focus = args[index]
303
+ elif arg.startswith("--focus="):
304
+ focus = arg.split("=", 1)[1]
305
+ elif arg == "--checkpoint-every":
306
+ if index + 1 >= len(args):
307
+ raise ValueError("--checkpoint-every requires a positive integer")
308
+ index += 1
309
+ checkpoint_every = _parse_positive_int(args[index], "--checkpoint-every")
310
+ checkpoint_every_explicit = True
311
+ elif arg.startswith("--checkpoint-every="):
312
+ checkpoint_every = _parse_positive_int(arg.split("=", 1)[1], "--checkpoint-every")
313
+ checkpoint_every_explicit = True
314
+ else:
315
+ unknown.append(arg)
316
+ index += 1
317
+
318
+ if max_rounds is None:
319
+ env_max_rounds = str(env.get("MAX_ROUNDS") or "").strip()
320
+ if env_max_rounds:
321
+ max_rounds = _parse_positive_int(env_max_rounds, "MAX_ROUNDS")
322
+
323
+ if focus is None:
324
+ focus = str(env.get("ITERATE_FOCUS") or "").strip()
325
+
326
+ env_safety_cap = str(env.get("PRIZMKIT_ITERATE_SAFETY_CAP") or "").strip()
327
+ safety_cap = (
328
+ _parse_positive_int(env_safety_cap, "PRIZMKIT_ITERATE_SAFETY_CAP")
329
+ if env_safety_cap
330
+ else DEFAULT_SAFETY_CAP
331
+ )
332
+
333
+ resolved_checkpoint = DEFAULT_CHECKPOINT_EVERY if checkpoint_every is None else checkpoint_every
334
+ limits = IterateLimits(
335
+ max_rounds=max_rounds,
336
+ safety_cap=safety_cap,
337
+ checkpoint_every=resolved_checkpoint,
338
+ checkpoint_every_explicit=checkpoint_every_explicit,
339
+ no_checkpoint=no_checkpoint,
340
+ )
341
+ return IterateOptions(
342
+ limits=limits,
343
+ focus=focus,
344
+ dry_run=dry_run,
345
+ help_requested=help_requested,
346
+ unknown_args=tuple(unknown),
347
+ )
348
+
349
+
350
+ def _help_text() -> str:
351
+ return (
352
+ "Usage: prizmkit-runtime run iterate "
353
+ "[--max-rounds N] [--focus TEXT] [--checkpoint-every N] [--no-checkpoint] [--dry-run]\n"
354
+ "Runs the autonomous strictly serial product-iteration outer loop."
355
+ )
356
+
357
+
358
+ def _interrupt_from_sigterm(signal_number: int, _frame: Any) -> None:
359
+ raise RuntimeInterruption(signal_number)
360
+
361
+
362
+ @contextmanager
363
+ def _bridge_sigterm_to_interrupt():
364
+ if threading.current_thread() is not threading.main_thread():
365
+ yield
366
+ return
367
+ previous_handler = signal.getsignal(signal.SIGTERM)
368
+ try:
369
+ signal.signal(signal.SIGTERM, _interrupt_from_sigterm)
370
+ yield
371
+ finally:
372
+ signal.signal(signal.SIGTERM, previous_handler)
373
+
374
+
375
+ def _load_feature_list_contract_module(pipeline_root: Path):
376
+ script_path = pipeline_root / "scripts" / "feature_list_contract.py"
377
+ module_name = f"prizmkit_feature_list_contract_{abs(hash(str(script_path)))}"
378
+ if module_name in sys.modules:
379
+ return sys.modules[module_name]
380
+ spec = importlib.util.spec_from_file_location(module_name, script_path)
381
+ if spec is None or spec.loader is None:
382
+ raise RuntimeError(f"Cannot load feature_list_contract module from {script_path}")
383
+ module = importlib.util.module_from_spec(spec)
384
+ sys.modules[module_name] = module
385
+ spec.loader.exec_module(module)
386
+ return module
387
+
388
+
389
+ # ---------------------------------------------------------------------------
390
+ # Git workspace fingerprinting & progress helpers
391
+ # ---------------------------------------------------------------------------
392
+
393
+
394
+ def _current_head_sha(project_root: Path) -> str:
395
+ res = run_git_command(project_root, ("rev-parse", "--verify", "HEAD"))
396
+ return res.stdout.strip() if res.return_code == 0 else ""
397
+
398
+
399
+ def _hash_path_content(project_root: Path, rel_path: str) -> str:
400
+ target = project_root / rel_path
401
+ if target.is_symlink():
402
+ try:
403
+ return f"SYMLINK:{os.readlink(target)}"
404
+ except OSError:
405
+ return "SYMLINK:UNREADABLE"
406
+ if not target.exists():
407
+ return "MISSING"
408
+ if target.is_dir():
409
+ return "DIR"
410
+ digest = hashlib.sha256()
411
+ try:
412
+ with target.open("rb") as fh:
413
+ for chunk in iter(lambda: fh.read(65536), b""):
414
+ digest.update(chunk)
415
+ except OSError:
416
+ return "UNREADABLE"
417
+ return digest.hexdigest()
418
+
419
+
420
+ def _parse_porcelain_z_entries(stdout: str) -> tuple[tuple[str, str], ...]:
421
+ records = stdout.split("\0")
422
+ parsed: list[tuple[str, str]] = []
423
+ index = 0
424
+ while index < len(records):
425
+ record = records[index]
426
+ index += 1
427
+ if not record or len(record) < 4 or record[2] != " ":
428
+ continue
429
+ status = record[:2]
430
+ rel_path = record[3:]
431
+ parsed.append((status, rel_path))
432
+ if ("R" in status or "C" in status) and index < len(records) and records[index]:
433
+ parsed.append((status, records[index]))
434
+ index += 1
435
+ return tuple(parsed)
436
+
437
+
438
+ def _snapshot_prizmkit_non_state_files(
439
+ project_root: Path,
440
+ prizmkit_dir: Path | None = None,
441
+ ) -> tuple[tuple[str, str], ...]:
442
+ """Hash all files under .prizmkit/ outside .prizmkit/state/ (including gitignored plans/docs/config)."""
443
+ root = (prizmkit_dir or (project_root / ".prizmkit")).resolve()
444
+ project_resolved = project_root.resolve()
445
+ if not root.is_dir():
446
+ return ()
447
+ state_dir = (root / "state").resolve()
448
+ records: list[tuple[str, str]] = []
449
+ for dirpath, dirnames, filenames in os.walk(root):
450
+ current_dir = Path(dirpath).resolve()
451
+ # Prune .prizmkit/state and Python bytecode directories
452
+ pruned: list[str] = []
453
+ for dirname in sorted(dirnames):
454
+ candidate = (current_dir / dirname).resolve()
455
+ if candidate == state_dir or dirname == "__pycache__":
456
+ continue
457
+ pruned.append(dirname)
458
+ dirnames[:] = pruned
459
+ for filename in sorted(filenames):
460
+ if filename.endswith((".pyc", ".pyo", ".pyd")):
461
+ continue
462
+ file_path = current_dir / filename
463
+ try:
464
+ rel_posix = file_path.relative_to(project_resolved).as_posix()
465
+ except ValueError:
466
+ rel_posix = f".prizmkit/{file_path.relative_to(root).as_posix()}"
467
+ records.append((rel_posix, _hash_path_content(file_path.parent, file_path.name)))
468
+ return tuple(sorted(records))
469
+
470
+
471
+ def capture_workspace_fingerprint(
472
+ project_root: Path,
473
+ prizmkit_dir: Path | None = None,
474
+ ) -> WorkspaceFingerprint:
475
+ """Snapshot HEAD, staged index, working-tree files, and gitignored .prizmkit files outside .prizmkit/state."""
476
+ head = _current_head_sha(project_root)
477
+ status_res = run_git_command(
478
+ project_root,
479
+ (
480
+ "status",
481
+ "--porcelain=v1",
482
+ "-z",
483
+ "--untracked-files=all",
484
+ "--",
485
+ ".",
486
+ *_WORKSPACE_READONLY_EXCLUDES,
487
+ ),
488
+ )
489
+ if status_res.return_code != 0:
490
+ raise RuntimeError(
491
+ f"Failed to inspect Git workspace status: {(status_res.stderr or status_res.stdout).strip()}"
492
+ )
493
+ staged_res = run_git_command(
494
+ project_root,
495
+ ("diff", "--cached", "--raw", "-z", "--", ".", *_WORKSPACE_READONLY_EXCLUDES),
496
+ )
497
+ staged_digest = hashlib.sha256((staged_res.stdout or "").encode("utf-8")).hexdigest()
498
+ raw_entries = _parse_porcelain_z_entries(status_res.stdout)
499
+ entries = tuple(
500
+ sorted(
501
+ (status, rel_path, _hash_path_content(project_root, rel_path))
502
+ for status, rel_path in raw_entries
503
+ )
504
+ )
505
+ prizmkit_entries = _snapshot_prizmkit_non_state_files(project_root, prizmkit_dir)
506
+ return WorkspaceFingerprint(
507
+ head=head,
508
+ staged_digest=staged_digest,
509
+ entries=entries,
510
+ prizmkit_entries=prizmkit_entries,
511
+ )
512
+
513
+
514
+ def diff_workspace_fingerprints(
515
+ before: WorkspaceFingerprint,
516
+ after: WorkspaceFingerprint,
517
+ ) -> tuple[str, ...]:
518
+ """Return paths (or HEAD/INDEX markers) that changed between two fingerprints."""
519
+ changed: list[str] = []
520
+ if before.head != after.head:
521
+ changed.append("HEAD")
522
+ before_map = {rel_path: (status, digest) for status, rel_path, digest in before.entries}
523
+ after_map = {rel_path: (status, digest) for status, rel_path, digest in after.entries}
524
+ for rel_path in sorted(set(before_map) | set(after_map)):
525
+ if before_map.get(rel_path) != after_map.get(rel_path):
526
+ changed.append(rel_path)
527
+ before_pk = dict(before.prizmkit_entries)
528
+ after_pk = dict(after.prizmkit_entries)
529
+ for rel_path in sorted(set(before_pk) | set(after_pk)):
530
+ if before_pk.get(rel_path) != after_pk.get(rel_path) and rel_path not in changed:
531
+ changed.append(rel_path)
532
+ if not changed and before.staged_digest != after.staged_digest:
533
+ changed.append("INDEX")
534
+ return tuple(changed)
535
+
536
+
537
+ def _round_made_real_progress(project_root: Path, head_before: str, head_after: str) -> bool:
538
+ """Return True only when HEAD advanced with non-bookkeeping repository changes."""
539
+ if not head_before or not head_after or head_before == head_after:
540
+ return False
541
+ diff_res = run_git_command(
542
+ project_root,
543
+ (
544
+ "diff",
545
+ "--name-only",
546
+ head_before,
547
+ head_after,
548
+ "--",
549
+ ".",
550
+ *_PROGRESS_BOOKKEEPING_EXCLUDES,
551
+ ),
552
+ )
553
+ if diff_res.return_code != 0:
554
+ return False
555
+ return bool(diff_res.stdout.strip())
556
+
557
+
558
+ # ---------------------------------------------------------------------------
559
+ # Strict Phase A Two-Stage Evaluation Validator
560
+ # ---------------------------------------------------------------------------
561
+
562
+
563
+ def _is_non_empty_str(value: object) -> bool:
564
+ return isinstance(value, str) and bool(value.strip())
565
+
566
+
567
+ def _is_str_list(value: object, *, min_items: int = 0) -> bool:
568
+ return (
569
+ isinstance(value, list)
570
+ and len(value) >= min_items
571
+ and all(_is_non_empty_str(item) for item in value)
572
+ )
573
+
574
+
575
+ def _check_exact_keys(
576
+ obj: Mapping[str, Any],
577
+ expected: frozenset[str],
578
+ label: str,
579
+ errors: list[str],
580
+ ) -> None:
581
+ keys = set(obj.keys())
582
+ missing = expected - keys
583
+ unknown = keys - expected
584
+ if missing:
585
+ errors.append(f"{label} missing required keys: {', '.join(sorted(missing))}")
586
+ if unknown:
587
+ errors.append(f"{label} has unknown keys: {', '.join(sorted(unknown))}")
588
+
589
+
590
+ def validate_evaluation_payload(data: Any) -> tuple[bool, tuple[str, ...]]:
591
+ """Validate Phase A evaluation.json against the strict two-stage value funnel contract."""
592
+ errors: list[str] = []
593
+ if not isinstance(data, dict):
594
+ return False, ("evaluation.json root must be a JSON object",)
595
+
596
+ _check_exact_keys(data, _EVAL_ROOT_KEYS, "evaluation", errors)
597
+
598
+ if data.get("schema_version") != EVALUATION_SCHEMA_VERSION:
599
+ errors.append(
600
+ f"schema_version must be '{EVALUATION_SCHEMA_VERSION}', got {data.get('schema_version')!r}"
601
+ )
602
+
603
+ product_shapes = data.get("product_shapes")
604
+ if (
605
+ not isinstance(product_shapes, list)
606
+ or not (1 <= len(product_shapes) <= 2)
607
+ or not all(isinstance(shape, str) and shape in PRODUCT_SHAPES for shape in product_shapes)
608
+ or len(set(product_shapes)) != len(product_shapes)
609
+ ):
610
+ errors.append(
611
+ "product_shapes must be 1-2 unique values from "
612
+ f"{sorted(PRODUCT_SHAPES)}, got {product_shapes!r}"
613
+ )
614
+
615
+ evidence_mode = data.get("evidence_mode")
616
+ if evidence_mode not in EVIDENCE_MODES:
617
+ errors.append(
618
+ f"evidence_mode must be one of {sorted(EVIDENCE_MODES)}, got {evidence_mode!r}"
619
+ )
620
+
621
+ walkthrough = data.get("walkthrough_notes")
622
+ if not isinstance(walkthrough, dict):
623
+ errors.append("walkthrough_notes must be an object")
624
+ else:
625
+ _check_exact_keys(walkthrough, _WALKTHROUGH_KEYS, "walkthrough_notes", errors)
626
+ if not isinstance(walkthrough.get("target_attempted"), bool):
627
+ errors.append("walkthrough_notes.target_attempted must be a boolean")
628
+ if not isinstance(walkthrough.get("server_cleanup_confirmed"), bool):
629
+ errors.append("walkthrough_notes.server_cleanup_confirmed must be a boolean")
630
+ if not _is_non_empty_str(walkthrough.get("reason")):
631
+ errors.append("walkthrough_notes.reason must be a non-empty string")
632
+ if evidence_mode == "live_walkthrough":
633
+ if walkthrough.get("target_attempted") is not True:
634
+ errors.append(
635
+ "evidence_mode='live_walkthrough' requires walkthrough_notes.target_attempted=true"
636
+ )
637
+ if walkthrough.get("server_cleanup_confirmed") is not True:
638
+ errors.append(
639
+ "evidence_mode='live_walkthrough' requires walkthrough_notes.server_cleanup_confirmed=true"
640
+ )
641
+
642
+ discovered = data.get("candidates_discovered")
643
+ if not isinstance(discovered, list):
644
+ errors.append("candidates_discovered must be an array")
645
+ else:
646
+ for idx, item in enumerate(discovered):
647
+ label = f"candidates_discovered[{idx}]"
648
+ if not isinstance(item, dict):
649
+ errors.append(f"{label} must be an object")
650
+ continue
651
+ _check_exact_keys(item, _DISCOVERED_KEYS, label, errors)
652
+ for field in ("id", "title", "problem", "desired_outcome", "disposition_reason"):
653
+ if not _is_non_empty_str(item.get(field)):
654
+ errors.append(f"{label}.{field} must be a non-empty string")
655
+ if item.get("lens") not in ALL_LENSES:
656
+ errors.append(f"{label}.lens invalid: {item.get('lens')!r}")
657
+ if item.get("evidence_tier") not in EVIDENCE_TIERS:
658
+ errors.append(f"{label}.evidence_tier invalid: {item.get('evidence_tier')!r}")
659
+ if not _is_str_list(item.get("evidence"), min_items=1):
660
+ errors.append(f"{label}.evidence must be a non-empty array of strings")
661
+ if item.get("blast_radius") not in BLAST_RADIUS_LEVELS:
662
+ errors.append(f"{label}.blast_radius invalid: {item.get('blast_radius')!r}")
663
+ flags = item.get("blast_radius_flags")
664
+ if (
665
+ not isinstance(flags, list)
666
+ or not all(isinstance(f, str) and f in BLAST_RADIUS_FLAGS for f in flags)
667
+ or len(set(flags)) != len(flags)
668
+ ):
669
+ errors.append(f"{label}.blast_radius_flags invalid: {flags!r}")
670
+ gates = item.get("gate_results")
671
+ if not isinstance(gates, dict):
672
+ errors.append(f"{label}.gate_results must be an object")
673
+ else:
674
+ _check_exact_keys(gates, _GATE_RESULT_KEYS, f"{label}.gate_results", errors)
675
+ if gates.get("gate1_scope_dedupe") not in {"pass", "fail"}:
676
+ errors.append(f"{label}.gate_results.gate1_scope_dedupe invalid")
677
+ if gates.get("gate2_fact_admission") not in {"pass", "fail"}:
678
+ errors.append(f"{label}.gate_results.gate2_fact_admission invalid")
679
+ if gates.get("gate3_blast_radius") not in {"auto_safe", "requires_user_confirm"}:
680
+ errors.append(f"{label}.gate_results.gate3_blast_radius invalid")
681
+ if gates.get("gate4_selected") not in {"approved", "deferred_for_user", "rejected"}:
682
+ errors.append(f"{label}.gate_results.gate4_selected invalid")
683
+
684
+ approved = data.get("approved_candidates")
685
+ if not isinstance(approved, list):
686
+ errors.append("approved_candidates must be an array")
687
+ else:
688
+ if len(approved) > 3:
689
+ errors.append(f"approved_candidates exceeds maximum of 3 items (got {len(approved)})")
690
+ for idx, item in enumerate(approved):
691
+ label = f"approved_candidates[{idx}]"
692
+ if not isinstance(item, dict):
693
+ errors.append(f"{label} must be an object")
694
+ continue
695
+ _check_exact_keys(item, _APPROVED_KEYS, label, errors)
696
+ for field in ("id", "title", "problem", "desired_outcome"):
697
+ if not _is_non_empty_str(item.get(field)):
698
+ errors.append(f"{label}.{field} must be a non-empty string")
699
+ if item.get("lens") not in PAIN_LENSES:
700
+ errors.append(
701
+ f"{label}.lens must be one of the 6 high-signal pain lenses "
702
+ f"{sorted(PAIN_LENSES)}, got {item.get('lens')!r}"
703
+ )
704
+ if item.get("evidence_tier") != "fact":
705
+ errors.append(
706
+ f"{label}.evidence_tier must be 'fact' for autonomous admission, "
707
+ f"got {item.get('evidence_tier')!r}"
708
+ )
709
+ if not _is_str_list(item.get("evidence"), min_items=1):
710
+ errors.append(f"{label}.evidence must be a non-empty array of strings")
711
+ if item.get("blast_radius") not in {"low", "medium"}:
712
+ errors.append(
713
+ f"{label}.blast_radius must be 'low' or 'medium', got {item.get('blast_radius')!r}"
714
+ )
715
+ flags = item.get("blast_radius_flags")
716
+ if not isinstance(flags, list) or len(flags) != 0:
717
+ errors.append(f"{label}.blast_radius_flags must be empty for auto-safe candidates")
718
+ if not _is_str_list(item.get("target_paths"), min_items=0):
719
+ errors.append(f"{label}.target_paths must be an array of non-empty strings")
720
+ if not _is_str_list(item.get("acceptance_hints"), min_items=1):
721
+ errors.append(f"{label}.acceptance_hints must be a non-empty array of strings")
722
+ if not isinstance(item.get("ui_affected"), bool):
723
+ errors.append(f"{label}.ui_affected must be a boolean")
724
+
725
+ confirm = data.get("requires_user_confirm")
726
+ if not isinstance(confirm, list):
727
+ errors.append("requires_user_confirm must be an array")
728
+ else:
729
+ for idx, item in enumerate(confirm):
730
+ label = f"requires_user_confirm[{idx}]"
731
+ if not isinstance(item, dict):
732
+ errors.append(f"{label} must be an object")
733
+ continue
734
+ _check_exact_keys(item, _CONFIRM_KEYS, label, errors)
735
+ for field in ("id", "title", "problem", "proposal", "decision_needed"):
736
+ if not _is_non_empty_str(item.get(field)):
737
+ errors.append(f"{label}.{field} must be a non-empty string")
738
+ if item.get("evidence_tier") not in EVIDENCE_TIERS:
739
+ errors.append(f"{label}.evidence_tier invalid: {item.get('evidence_tier')!r}")
740
+ if item.get("lens") not in ALL_LENSES:
741
+ errors.append(f"{label}.lens invalid: {item.get('lens')!r}")
742
+ flags = item.get("blast_radius_flags")
743
+ if (
744
+ not isinstance(flags, list)
745
+ or not all(isinstance(f, str) and f in BLAST_RADIUS_FLAGS for f in flags)
746
+ or len(set(flags)) != len(flags)
747
+ ):
748
+ errors.append(f"{label}.blast_radius_flags invalid: {flags!r}")
749
+ if not _is_str_list(item.get("evidence"), min_items=1):
750
+ errors.append(f"{label}.evidence must be a non-empty array of strings")
751
+
752
+ rejected = data.get("rejected_candidates")
753
+ if not isinstance(rejected, list):
754
+ errors.append("rejected_candidates must be an array")
755
+ else:
756
+ for idx, item in enumerate(rejected):
757
+ label = f"rejected_candidates[{idx}]"
758
+ if not isinstance(item, dict):
759
+ errors.append(f"{label} must be an object")
760
+ continue
761
+ _check_exact_keys(item, _REJECTED_KEYS, label, errors)
762
+ for field in ("id", "title", "reason"):
763
+ if not _is_non_empty_str(item.get(field)):
764
+ errors.append(f"{label}.{field} must be a non-empty string")
765
+ if item.get("evidence_tier") not in EVIDENCE_TIERS:
766
+ errors.append(f"{label}.evidence_tier invalid: {item.get('evidence_tier')!r}")
767
+ if item.get("lens") not in ALL_LENSES:
768
+ errors.append(f"{label}.lens invalid: {item.get('lens')!r}")
769
+ if item.get("rejected_by_gate") not in {"gate1", "gate2", "gate3", "gate4"}:
770
+ errors.append(f"{label}.rejected_by_gate invalid: {item.get('rejected_by_gate')!r}")
771
+
772
+ verdict = data.get("verdict")
773
+ if verdict not in VERDICTS:
774
+ errors.append(f"verdict must be one of {sorted(VERDICTS)}, got {verdict!r}")
775
+
776
+ if not _is_non_empty_str(data.get("summary")):
777
+ errors.append("summary must be a non-empty string")
778
+
779
+ # Cross-field verdict invariants
780
+ if isinstance(approved, list) and isinstance(confirm, list) and verdict in VERDICTS:
781
+ if verdict == "CONTINUE_WITH_CANDIDATES" and not (1 <= len(approved) <= 3):
782
+ errors.append(
783
+ f"verdict='CONTINUE_WITH_CANDIDATES' requires 1-3 approved_candidates (got {len(approved)})"
784
+ )
785
+ if verdict == "PAUSE_FOR_USER_CONFIRM":
786
+ if len(approved) != 0:
787
+ errors.append(
788
+ f"verdict='PAUSE_FOR_USER_CONFIRM' requires 0 approved_candidates (got {len(approved)})"
789
+ )
790
+ if len(confirm) < 1:
791
+ errors.append(
792
+ "verdict='PAUSE_FOR_USER_CONFIRM' requires at least 1 requires_user_confirm item"
793
+ )
794
+ if verdict in {"STOP_GOAL_REACHED", "STOP_NO_HIGH_VALUE"} and len(approved) != 0:
795
+ errors.append(
796
+ f"verdict='{verdict}' requires 0 approved_candidates (got {len(approved)})"
797
+ )
798
+
799
+ return len(errors) == 0, tuple(errors)
800
+
801
+
802
+ # ---------------------------------------------------------------------------
803
+ # State / Ledger / Events / Markdown Persistence
804
+ # ---------------------------------------------------------------------------
805
+
806
+
807
+ def _load_or_init_ledger(ledger_file: Path) -> dict[str, Any]:
808
+ if ledger_file.is_file():
809
+ try:
810
+ data = json.loads(ledger_file.read_text(encoding="utf-8"))
811
+ if isinstance(data, dict) and isinstance(data.get("rounds"), list):
812
+ data.setdefault("schema_version", 1)
813
+ data.setdefault("backlog_drains", [])
814
+ return data
815
+ except (OSError, json.JSONDecodeError):
816
+ pass
817
+ return {"schema_version": 1, "rounds": [], "backlog_drains": []}
818
+
819
+
820
+ def _next_round_number(ledger: Mapping[str, Any]) -> int:
821
+ rounds = ledger.get("rounds")
822
+ if not isinstance(rounds, list) or not rounds:
823
+ return 1
824
+ numbers = [
825
+ int(entry["round"])
826
+ for entry in rounds
827
+ if isinstance(entry, dict) and isinstance(entry.get("round"), int)
828
+ ]
829
+ return max(numbers, default=0) + 1
830
+
831
+
832
+ def _append_event(
833
+ iterate_paths: IteratePaths,
834
+ event: str,
835
+ *,
836
+ round_num: int = 0,
837
+ phase: str = "",
838
+ details: Mapping[str, object] | None = None,
839
+ ) -> None:
840
+ iterate_paths.events_file.parent.mkdir(parents=True, exist_ok=True)
841
+ record = {
842
+ "timestamp": _utc_iso(),
843
+ "event": event,
844
+ "round": round_num,
845
+ "phase": phase,
846
+ "details": dict(details or {}),
847
+ }
848
+ with iterate_paths.events_file.open("a", encoding="utf-8") as fh:
849
+ fh.write(json.dumps(record, ensure_ascii=False) + "\n")
850
+ fh.flush()
851
+
852
+
853
+ def _write_state(
854
+ iterate_paths: IteratePaths,
855
+ *,
856
+ status: str,
857
+ phase: str,
858
+ current_round: int,
859
+ completed_rounds: int,
860
+ active_feature_id: str | None,
861
+ stop_reason: str | None,
862
+ pause_reason: str | None,
863
+ options: IterateOptions,
864
+ consecutive_failures: int,
865
+ consecutive_no_progress: int,
866
+ started_at: str,
867
+ last_verdict: str | None,
868
+ last_evidence_mode: str | None,
869
+ summary: str,
870
+ ) -> None:
871
+ payload = {
872
+ "schema_version": 1,
873
+ "status": status,
874
+ "phase": phase,
875
+ "current_round": current_round,
876
+ "completed_rounds": completed_rounds,
877
+ "active_feature_id": active_feature_id,
878
+ "stop_reason": stop_reason,
879
+ "pause_reason": pause_reason,
880
+ "focus": options.focus,
881
+ "limits": options.limits.to_dict(),
882
+ "consecutive_failures": consecutive_failures,
883
+ "consecutive_no_progress": consecutive_no_progress,
884
+ "started_at": started_at,
885
+ "updated_at": _utc_iso(),
886
+ "last_verdict": last_verdict,
887
+ "last_evidence_mode": last_evidence_mode,
888
+ "summary": summary,
889
+ }
890
+ write_json_atomic(iterate_paths.state_file, payload)
891
+
892
+
893
+ def _write_pending_decisions(
894
+ iterate_paths: IteratePaths,
895
+ round_num: int,
896
+ proposals: Sequence[Mapping[str, Any]],
897
+ summary: str,
898
+ ) -> None:
899
+ lines = [
900
+ "# Pending Product Iteration Decisions",
901
+ "",
902
+ f"- **Round**: {round_num}",
903
+ f"- **Updated**: {_utc_iso()}",
904
+ f"- **Summary**: {summary}",
905
+ "",
906
+ "The autonomous iteration loop paused because these proposals require explicit user confirmation before implementation:",
907
+ "",
908
+ ]
909
+ for idx, item in enumerate(proposals, start=1):
910
+ flags = item.get("blast_radius_flags") or []
911
+ flags_text = ", ".join(str(f) for f in flags) if flags else "none (taste/direction)"
912
+ lines.extend(
913
+ [
914
+ f"## {idx}. {item.get('title', 'Untitled Proposal')} (`{item.get('id', f'P-{idx}')}`)",
915
+ f"- **Evidence Tier**: `{item.get('evidence_tier', 'unknown')}`",
916
+ f"- **Lens**: `{item.get('lens', 'unknown')}`",
917
+ f"- **Blast Radius Flags**: {flags_text}",
918
+ f"- **Problem**: {item.get('problem', '')}",
919
+ f"- **Proposal**: {item.get('proposal', '')}",
920
+ f"- **Decision Needed**: {item.get('decision_needed', '')}",
921
+ "- **Evidence**:",
922
+ ]
923
+ )
924
+ for ev in item.get("evidence") or []:
925
+ lines.append(f" - {ev}")
926
+ lines.append("")
927
+ write_text_atomic(iterate_paths.pending_decisions_file, "\n".join(lines).rstrip() + "\n")
928
+
929
+
930
+ def _write_final_summary(
931
+ iterate_paths: IteratePaths,
932
+ *,
933
+ reason: str,
934
+ status: str,
935
+ ledger: Mapping[str, Any],
936
+ summary: str,
937
+ ) -> None:
938
+ rounds = ledger.get("rounds") if isinstance(ledger.get("rounds"), list) else []
939
+ lines = [
940
+ "# Autonomous Product Iteration Summary",
941
+ "",
942
+ f"- **Final Status**: `{status}`",
943
+ f"- **Reason**: `{reason}`",
944
+ f"- **Completed At**: {_utc_iso()}",
945
+ f"- **Total Recorded Rounds**: {len(rounds)}",
946
+ f"- **Summary**: {summary}",
947
+ "",
948
+ ]
949
+ if rounds:
950
+ lines.append("## Round History")
951
+ for entry in rounds:
952
+ if not isinstance(entry, dict):
953
+ continue
954
+ rnum = entry.get("round")
955
+ verdict = entry.get("verdict")
956
+ mode = entry.get("evidence_mode")
957
+ appended = ", ".join(entry.get("appended_ids") or []) or "none"
958
+ completed = ", ".join(entry.get("completed_ids") or []) or "none"
959
+ lines.append(
960
+ f"- Round {rnum}: verdict=`{verdict}` evidence_mode=`{mode}` "
961
+ f"appended=[{appended}] completed=[{completed}]"
962
+ )
963
+ lines.append("")
964
+ write_text_atomic(iterate_paths.summary_file, "\n".join(lines).rstrip() + "\n")
965
+
966
+
967
+ # ---------------------------------------------------------------------------
968
+ # Prompt Rendering (NEVER discloses round quota / max_rounds / safety_cap)
969
+ # ---------------------------------------------------------------------------
970
+
971
+
972
+ def _format_ledger_summary(ledger: Mapping[str, Any]) -> str:
973
+ rounds = ledger.get("rounds")
974
+ if not isinstance(rounds, list) or not rounds:
975
+ return "No prior iteration rounds recorded."
976
+ lines: list[str] = []
977
+ for entry in rounds[-10:]:
978
+ if not isinstance(entry, dict):
979
+ continue
980
+ rnum = entry.get("round")
981
+ verdict = entry.get("verdict")
982
+ completed = entry.get("completed_ids") or []
983
+ failed = entry.get("failed_ids") or []
984
+ deferred = [
985
+ item.get("title")
986
+ for item in (entry.get("deferred_for_user") or [])
987
+ if isinstance(item, dict) and item.get("title")
988
+ ]
989
+ rejected = [
990
+ item.get("title")
991
+ for item in (entry.get("rejected_candidates") or [])
992
+ if isinstance(item, dict) and item.get("title")
993
+ ]
994
+ lines.append(
995
+ f"- Round {rnum}: verdict={verdict}, completed={completed}, failed={failed}, "
996
+ f"deferred={deferred}, rejected={rejected}"
997
+ )
998
+ return "\n".join(lines) if lines else "No prior iteration rounds recorded."
999
+
1000
+
1001
+ def _format_prizm_context_hint(paths: RuntimePaths) -> str:
1002
+ hints: list[str] = []
1003
+ root_prizm = paths.prizmkit_dir / "prizm-docs" / "root.prizm"
1004
+ brief_path = paths.plans_dir / "project-brief.md"
1005
+ if root_prizm.is_file():
1006
+ hints.append(f"- Prizm root documentation available: `{root_prizm}` (read first, then relevant pointed module/detail docs).")
1007
+ else:
1008
+ hints.append("- No `.prizmkit/prizm-docs/root.prizm` found; inspect README, manifests, and core entrypoints directly.")
1009
+ if brief_path.is_file():
1010
+ hints.append(f"- Project brief available: `{brief_path}` (treat as intent claims; shipped code takes precedence).")
1011
+ return "\n".join(hints)
1012
+
1013
+
1014
+ def render_evaluate_prompt(
1015
+ paths: RuntimePaths,
1016
+ *,
1017
+ round_dir: Path,
1018
+ output_path: Path,
1019
+ focus: str,
1020
+ ledger: Mapping[str, Any],
1021
+ ) -> str:
1022
+ """Render Phase A evaluate-prompt.md without disclosing any round quota or cap."""
1023
+ template_path = paths.pipeline_root / "templates" / "iterate" / "evaluate-prompt.md"
1024
+ schema_path = paths.pipeline_root / "templates" / "iterate" / "evaluation-schema.json"
1025
+ helper_script = paths.pipeline_root / "scripts" / "prizmkit-runtime-helper.py"
1026
+ template = template_path.read_text(encoding="utf-8")
1027
+
1028
+ focus_section = (
1029
+ focus.strip()
1030
+ if focus.strip()
1031
+ else "No narrow focus restriction; evaluate core user-facing journeys end to end."
1032
+ )
1033
+ replacements = {
1034
+ "{{PROJECT_ROOT}}": str(paths.project_root),
1035
+ "{{OUTPUT_PATH}}": str(output_path),
1036
+ "{{SCHEMA_PATH}}": str(schema_path),
1037
+ "{{RUNTIME_HELPER_CMD}}": f"{sys.executable} {helper_script}",
1038
+ "{{ROUND_DIR}}": str(round_dir),
1039
+ "{{FOCUS_SECTION}}": focus_section,
1040
+ "{{LEDGER_SUMMARY}}": _format_ledger_summary(ledger),
1041
+ "{{PRIZM_CONTEXT_HINT}}": _format_prizm_context_hint(paths),
1042
+ }
1043
+ rendered = template
1044
+ for placeholder, value in replacements.items():
1045
+ rendered = rendered.replace(placeholder, value)
1046
+ return rendered
1047
+
1048
+
1049
+ def render_headless_plan_prompt(
1050
+ paths: RuntimePaths,
1051
+ *,
1052
+ mode: str,
1053
+ context_path: Path,
1054
+ candidates_path: Path,
1055
+ draft_output_path: Path,
1056
+ repair_errors: Sequence[str] = (),
1057
+ ) -> str:
1058
+ """Render Phase B headless-plan-prompt.md for append or generate mode."""
1059
+ template_path = paths.pipeline_root / "templates" / "iterate" / "headless-plan-prompt.md"
1060
+ schema_path = paths.pipeline_root / "templates" / "feature-list-schema.json"
1061
+ template = template_path.read_text(encoding="utf-8")
1062
+
1063
+ if repair_errors:
1064
+ error_lines = "\n".join(f"- {err}" for err in repair_errors)
1065
+ repair_feedback = (
1066
+ "## Deterministic Validation Repair Required\n\n"
1067
+ "Your previous draft failed deterministic `feature-list.json` schema/DAG validation. "
1068
+ "Fix every error below and rewrite a clean valid JSON draft to "
1069
+ f"`{draft_output_path}`:\n\n{error_lines}"
1070
+ )
1071
+ else:
1072
+ repair_feedback = ""
1073
+
1074
+ replacements = {
1075
+ "{{PROJECT_ROOT}}": str(paths.project_root),
1076
+ "{{MODE}}": mode,
1077
+ "{{CONTEXT_PATH}}": str(context_path),
1078
+ "{{CANDIDATES_PATH}}": str(candidates_path),
1079
+ "{{DRAFT_OUTPUT_PATH}}": str(draft_output_path),
1080
+ "{{SCHEMA_PATH}}": str(schema_path),
1081
+ "{{REPAIR_FEEDBACK}}": repair_feedback,
1082
+ }
1083
+ rendered = template
1084
+ for placeholder, value in replacements.items():
1085
+ rendered = rendered.replace(placeholder, value)
1086
+ return rendered
1087
+
1088
+
1089
+ # ---------------------------------------------------------------------------
1090
+ # AI Session & Feature List Inspection Helpers
1091
+ # ---------------------------------------------------------------------------
1092
+
1093
+
1094
+ def _validate_ai_readiness(paths: RuntimePaths):
1095
+ config = load_runtime_config(paths)
1096
+ if not config.ai_client.command:
1097
+ notes = "; ".join(config.ai_client.notes) if config.ai_client.notes else "No supported AI CLI command was found"
1098
+ raise RuntimeError(notes)
1099
+ effort_validation = getattr(config, "effort_validation", None)
1100
+ if effort_validation is not None and not effort_validation.valid:
1101
+ raise RuntimeError(effort_validation.message)
1102
+ if getattr(config.ai_client, "launch_profile", None) is not None:
1103
+ stream_json = False
1104
+ else:
1105
+ support = detect_stream_json_support(config.ai_client.command, config.ai_client.platform)
1106
+ stream_json = bool(getattr(support, "enabled", False))
1107
+ notes = getattr(support, "notes", ()) or ()
1108
+ if config.ai_client.platform in {"cursor", "antigravity"} and not stream_json:
1109
+ detail = "; ".join(notes) or "required stream-json flags were not found"
1110
+ raise RuntimeError(
1111
+ f"{config.ai_client.platform.title()} CLI is incompatible with PrizmKit headless execution: {detail}"
1112
+ )
1113
+ return config, stream_json
1114
+
1115
+
1116
+ def _launch_fresh_session(
1117
+ paths: RuntimePaths,
1118
+ config,
1119
+ *,
1120
+ stream_json: bool,
1121
+ prompt_path: Path,
1122
+ logs_dir: Path,
1123
+ ):
1124
+ runner_env = RunnerEnvironment.from_env(config.env_values)
1125
+ logs_dir.mkdir(parents=True, exist_ok=True)
1126
+ session_config = AISessionConfig(
1127
+ cli_command=config.ai_client.command,
1128
+ platform=config.ai_client.platform or "codebuddy",
1129
+ model=config.model,
1130
+ effort=config.effort,
1131
+ prompt_path=prompt_path,
1132
+ cwd=paths.project_root,
1133
+ log_path=logs_dir / "session.log",
1134
+ progress_path=logs_dir / "progress.json",
1135
+ heartbeat_path=logs_dir / "heartbeat.json",
1136
+ verbose=runner_env.verbose,
1137
+ live_output=runner_env.live_output,
1138
+ use_stream_json=stream_json,
1139
+ stale_kill_threshold_seconds=runner_env.stale_kill_threshold_seconds,
1140
+ heartbeat_stale_threshold_seconds=runner_env.heartbeat_stale_threshold_seconds,
1141
+ live_progress_interval_seconds=runner_env.heartbeat_interval_seconds,
1142
+ live_banner=False,
1143
+ suppress_stream_output=True,
1144
+ launch_profile=config.ai_client.launch_profile,
1145
+ )
1146
+ return AISessionLauncher(session_config).run()
1147
+
1148
+
1149
+ def _session_failure_reason(session_result: Any) -> str | None:
1150
+ """Return a concise failure diagnostic when AISessionResult reports an abnormal exit."""
1151
+ if session_result is None:
1152
+ return None
1153
+ if getattr(session_result, "timed_out", False):
1154
+ return "AI session timed out before producing valid output"
1155
+ termination_reason = getattr(session_result, "termination_reason", None)
1156
+ if termination_reason:
1157
+ return f"AI session terminated abnormally ({termination_reason})"
1158
+ fatal_error_code = str(getattr(session_result, "fatal_error_code", "") or "").strip()
1159
+ if fatal_error_code:
1160
+ return f"AI session reported fatal error ({fatal_error_code})"
1161
+ exit_code = getattr(session_result, "exit_code", 0)
1162
+ if exit_code not in (None, 0):
1163
+ return f"AI session exited with non-zero exit code {exit_code}"
1164
+ return None
1165
+
1166
+
1167
+ def _validate_phase_b_draft_pending_statuses(draft_path: Path) -> tuple[str, ...]:
1168
+ """Ensure every newly drafted Phase B feature uses status 'pending' (or omitted default)."""
1169
+ try:
1170
+ draft = json.loads(draft_path.read_text(encoding="utf-8"))
1171
+ except (OSError, json.JSONDecodeError) as exc:
1172
+ return (f"Unable to re-read Phase B draft for status check: {exc}",)
1173
+ features = draft.get("features") if isinstance(draft, dict) else None
1174
+ if not isinstance(features, list):
1175
+ return ("Phase B draft must contain a 'features' array",)
1176
+ errors: list[str] = []
1177
+ for idx, feature in enumerate(features):
1178
+ if not isinstance(feature, dict):
1179
+ continue
1180
+ status = feature.get("status")
1181
+ if status is not None and status != "pending":
1182
+ fid = feature.get("id", f"index-{idx}")
1183
+ errors.append(
1184
+ f"features[{idx}] ({fid}): newly planned Phase B feature must have status 'pending', got {status!r}"
1185
+ )
1186
+ return tuple(errors)
1187
+
1188
+
1189
+ def _incomplete_feature_ids(feature_plan: Path) -> list[str]:
1190
+ if not feature_plan.is_file():
1191
+ return []
1192
+ try:
1193
+ data = json.loads(feature_plan.read_text(encoding="utf-8"))
1194
+ except (OSError, json.JSONDecodeError) as exc:
1195
+ raise RuntimeError(f"Existing feature-list.json is unreadable or malformed: {exc}") from exc
1196
+ features = data.get("features") if isinstance(data, dict) else None
1197
+ if not isinstance(features, list):
1198
+ raise RuntimeError("Existing feature-list.json must contain a 'features' array")
1199
+ return [
1200
+ str(item.get("id"))
1201
+ for item in features
1202
+ if isinstance(item, dict)
1203
+ and item.get("id")
1204
+ and str(item.get("status") or "pending") in {"pending", "in_progress"}
1205
+ ]
1206
+
1207
+
1208
+ def _feature_status_map(feature_plan: Path) -> dict[str, str]:
1209
+ if not feature_plan.is_file():
1210
+ return {}
1211
+ try:
1212
+ data = json.loads(feature_plan.read_text(encoding="utf-8"))
1213
+ except (OSError, json.JSONDecodeError):
1214
+ return {}
1215
+ features = data.get("features") if isinstance(data, dict) else None
1216
+ if not isinstance(features, list):
1217
+ return {}
1218
+ return {
1219
+ str(item["id"]): str(item.get("status") or "pending")
1220
+ for item in features
1221
+ if isinstance(item, dict) and item.get("id")
1222
+ }
1223
+
1224
+
1225
+ def _build_initial_plan_context(paths: RuntimePaths) -> dict[str, Any]:
1226
+ global_context: dict[str, str] = {}
1227
+ config_file = paths.prizmkit_dir / "config.json"
1228
+ if config_file.is_file():
1229
+ try:
1230
+ cfg = json.loads(config_file.read_text(encoding="utf-8"))
1231
+ tech = cfg.get("tech_stack") if isinstance(cfg, dict) else None
1232
+ if isinstance(tech, dict):
1233
+ key_map = {
1234
+ "language": "language",
1235
+ "runtime": "runtime",
1236
+ "frontend_framework": "frontend_framework",
1237
+ "frontend_styling": "frontend_styling",
1238
+ "backend_framework": "backend_framework",
1239
+ "database": "database",
1240
+ "orm": "orm",
1241
+ "design_system": "design_system",
1242
+ "testing": "testing_strategy",
1243
+ "testing_strategy": "testing_strategy",
1244
+ "bundler": "bundler",
1245
+ "project_type": "project_type",
1246
+ "tech_stack": "tech_stack",
1247
+ }
1248
+ for src_key, dst_key in key_map.items():
1249
+ val = tech.get(src_key)
1250
+ if isinstance(val, str) and val.strip():
1251
+ global_context[dst_key] = val.strip()
1252
+ except (OSError, json.JSONDecodeError):
1253
+ pass
1254
+ return {
1255
+ "mode": "generate",
1256
+ "project_name": paths.project_root.name or "project",
1257
+ "project_description": "",
1258
+ "global_context": global_context,
1259
+ "task_count": 0,
1260
+ "next_id": "F-001",
1261
+ "recent_tasks": [],
1262
+ }
1263
+
1264
+
1265
+ # ---------------------------------------------------------------------------
1266
+ # Dry-Run Preview
1267
+ # ---------------------------------------------------------------------------
1268
+
1269
+
1270
+ def _run_dry_run(paths: RuntimePaths, options: IterateOptions) -> CommandResult:
1271
+ try:
1272
+ config, _stream_json = _validate_ai_readiness(paths)
1273
+ except Exception as exc:
1274
+ return CommandResult(1, "Python iterate dry-run failed", str(exc))
1275
+
1276
+ git_probe = run_git_command(paths.project_root, ("rev-parse", "--is-inside-work-tree"))
1277
+ git_ready = git_probe.return_code == 0 and git_probe.stdout.strip() == "true"
1278
+ try:
1279
+ backlog_ids = _incomplete_feature_ids(paths.feature_plan)
1280
+ except RuntimeError as exc:
1281
+ return CommandResult(1, "Python iterate dry-run failed", str(exc))
1282
+
1283
+ ledger = _load_or_init_ledger(IteratePaths.from_runtime_paths(paths).ledger_file)
1284
+ with tempfile.TemporaryDirectory(prefix="prizmkit-iterate-dry-run-") as tmp_dir:
1285
+ tmp_round = Path(tmp_dir) / "round-preview"
1286
+ prompt_text = render_evaluate_prompt(
1287
+ paths,
1288
+ round_dir=tmp_round,
1289
+ output_path=tmp_round / "evaluation.json",
1290
+ focus=options.focus,
1291
+ ledger=ledger,
1292
+ )
1293
+ prompt_bytes = len(prompt_text.encode("utf-8"))
1294
+
1295
+ mode_label = (
1296
+ f"bounded(max_rounds={options.limits.max_rounds})"
1297
+ if options.limits.max_rounds is not None
1298
+ else f"autonomous(safety_cap={options.limits.safety_cap}, checkpoint_every={'off' if options.limits.no_checkpoint else options.limits.checkpoint_every})"
1299
+ )
1300
+ details = (
1301
+ f"ai_cli: {config.ai_client.command} ({config.ai_client.platform or 'unknown'})",
1302
+ f"git_repo_ready: {git_ready}",
1303
+ f"feature_list_exists: {paths.feature_plan.is_file()}",
1304
+ f"backlog_pending_count: {len(backlog_ids)}",
1305
+ f"mode: {mode_label}",
1306
+ f"focus: {options.focus or '(none)'}",
1307
+ f"evaluate_prompt_bytes: {prompt_bytes}",
1308
+ "mutations: none (dry-run validated readiness and rendered disposable Phase A prompt only)",
1309
+ )
1310
+ return CommandResult(
1311
+ 0,
1312
+ "Python iterate dry-run",
1313
+ "Dry-run readiness checks passed; no AI session, Git, plan, or state mutations occurred.",
1314
+ details=details,
1315
+ )
1316
+
1317
+
1318
+ # ---------------------------------------------------------------------------
1319
+ # Main Outer Loop
1320
+ # ---------------------------------------------------------------------------
1321
+
1322
+
1323
+ def run_iterate_command(
1324
+ legacy_args: Sequence[str],
1325
+ paths: RuntimePaths,
1326
+ ) -> CommandResult:
1327
+ """Entrypoint for `dev-pipeline/cli.py run iterate`."""
1328
+ env_values = load_env_file(paths.prizmkit_dir / ".env", os.environ)
1329
+ try:
1330
+ options = parse_iterate_options(legacy_args, env_values)
1331
+ except ValueError as exc:
1332
+ return CommandResult(2, "Python iterate runner", str(exc), stderr=str(exc))
1333
+
1334
+ if options.help_requested:
1335
+ return CommandResult(0, "Python iterate runner", _help_text())
1336
+ if options.unknown_args:
1337
+ message = "Unsupported option(s): " + ", ".join(options.unknown_args)
1338
+ return CommandResult(2, "Python iterate runner", message, stderr=message)
1339
+
1340
+ if options.dry_run:
1341
+ return _run_dry_run(paths, options)
1342
+
1343
+ try:
1344
+ with _bridge_sigterm_to_interrupt():
1345
+ return run_iterate_loop(paths, options)
1346
+ except PidLockError as exc:
1347
+ return CommandResult(1, "Python iterate runner", str(exc), stderr=str(exc))
1348
+ except Exception as exc:
1349
+ detail = str(exc).strip()
1350
+ message = f"{type(exc).__name__}: {detail}" if detail else type(exc).__name__
1351
+ return CommandResult(1, "Python iterate runner failed", message, stderr=message)
1352
+
1353
+
1354
+ def run_iterate_loop(paths: RuntimePaths, options: IterateOptions) -> CommandResult:
1355
+ """Execute the autonomous serial product-iteration loop under `.iterate.lock`."""
1356
+ config, stream_json = _validate_ai_readiness(paths)
1357
+
1358
+ repo_res = ensure_git_repository(paths.project_root)
1359
+ if repo_res.return_code != 0:
1360
+ detail = (repo_res.stderr or repo_res.stdout).strip() or "git init failed"
1361
+ raise RuntimeError(f"Cannot initialize Git repository before iterate: {detail}")
1362
+ born_res = ensure_branch_has_commit(paths.project_root)
1363
+ if born_res.return_code != 0:
1364
+ detail = (born_res.stderr or born_res.stdout).strip() or "initial commit failed"
1365
+ raise RuntimeError(f"Cannot create initial commit before iterate: {detail}")
1366
+
1367
+ contract_mod = _load_feature_list_contract_module(paths.pipeline_root)
1368
+ iterate_paths = IteratePaths.from_runtime_paths(paths)
1369
+ iterate_paths.state_dir.mkdir(parents=True, exist_ok=True)
1370
+
1371
+ with exclusive_pid_lock(
1372
+ iterate_paths.lock_path,
1373
+ busy_message="Iterate loop is already running (PID {pid})",
1374
+ error_label="iterate lock",
1375
+ ):
1376
+ started_at = _utc_iso()
1377
+ ledger = _load_or_init_ledger(iterate_paths.ledger_file)
1378
+ write_json_atomic(iterate_paths.ledger_file, ledger)
1379
+
1380
+ total_completed_rounds = sum(
1381
+ 1
1382
+ for entry in ledger.get("rounds", [])
1383
+ if isinstance(entry, dict)
1384
+ and entry.get("verdict") == "CONTINUE_WITH_CANDIDATES"
1385
+ and not entry.get("failed_ids")
1386
+ and bool(entry.get("completed_ids"))
1387
+ )
1388
+ rounds_executed_in_run = 0
1389
+ completed_rounds_in_run = 0
1390
+ consecutive_failures = 0
1391
+ consecutive_no_progress = 0
1392
+ current_round = 0
1393
+ last_verdict: str | None = None
1394
+ last_evidence_mode: str | None = None
1395
+
1396
+ _write_state(
1397
+ iterate_paths,
1398
+ status="running",
1399
+ phase="evaluating",
1400
+ current_round=0,
1401
+ completed_rounds=total_completed_rounds,
1402
+ active_feature_id=None,
1403
+ stop_reason=None,
1404
+ pause_reason=None,
1405
+ options=options,
1406
+ consecutive_failures=0,
1407
+ consecutive_no_progress=0,
1408
+ started_at=started_at,
1409
+ last_verdict=None,
1410
+ last_evidence_mode=None,
1411
+ summary="Iterate session started.",
1412
+ )
1413
+ _append_event(
1414
+ iterate_paths,
1415
+ "iterate_started",
1416
+ round_num=0,
1417
+ phase="evaluating",
1418
+ details={
1419
+ "focus": options.focus,
1420
+ "limits": options.limits.to_dict(),
1421
+ "feature_list_exists": paths.feature_plan.is_file(),
1422
+ },
1423
+ )
1424
+
1425
+ try:
1426
+ # Startup Existing Backlog Seam
1427
+ backlog_ids = _incomplete_feature_ids(paths.feature_plan)
1428
+ if backlog_ids:
1429
+ _emit_log(f"Draining {len(backlog_ids)} existing incomplete feature(s): {', '.join(backlog_ids)}")
1430
+ _write_state(
1431
+ iterate_paths,
1432
+ status="running",
1433
+ phase="drain_backlog",
1434
+ current_round=0,
1435
+ completed_rounds=total_completed_rounds,
1436
+ active_feature_id=backlog_ids[0],
1437
+ stop_reason=None,
1438
+ pause_reason=None,
1439
+ options=options,
1440
+ consecutive_failures=0,
1441
+ consecutive_no_progress=0,
1442
+ started_at=started_at,
1443
+ last_verdict=None,
1444
+ last_evidence_mode=None,
1445
+ summary=f"Draining existing backlog ({len(backlog_ids)} incomplete features).",
1446
+ )
1447
+ _append_event(
1448
+ iterate_paths,
1449
+ "backlog_drain_started",
1450
+ round_num=0,
1451
+ phase="drain_backlog",
1452
+ details={"pending_ids": backlog_ids},
1453
+ )
1454
+ drain_started_at = _utc_iso()
1455
+ drain_head_before = _current_head_sha(paths.project_root)
1456
+ drain_result = run_pipeline_command("feature", "run", (str(paths.feature_plan),), paths)
1457
+ if drain_result.exit_code != 0 and "stopped_reason=interrupted" in (drain_result.message or ""):
1458
+ raise KeyboardInterrupt("Backlog drain interrupted")
1459
+ drain_head_after = _current_head_sha(paths.project_root)
1460
+ status_after_drain = _feature_status_map(paths.feature_plan)
1461
+ drain_completed = [
1462
+ fid for fid in backlog_ids if status_after_drain.get(fid) in {"completed", "split"}
1463
+ ]
1464
+ drain_failed = [fid for fid in backlog_ids if fid not in drain_completed]
1465
+ ledger["backlog_drains"].append(
1466
+ {
1467
+ "started_at": drain_started_at,
1468
+ "ended_at": _utc_iso(),
1469
+ "pending_before": backlog_ids,
1470
+ "completed_ids": drain_completed,
1471
+ "failed_ids": drain_failed,
1472
+ "exit_code": drain_result.exit_code,
1473
+ "head_before": drain_head_before,
1474
+ "head_after": drain_head_after,
1475
+ }
1476
+ )
1477
+ write_json_atomic(iterate_paths.ledger_file, ledger)
1478
+ _append_event(
1479
+ iterate_paths,
1480
+ "backlog_drain_finished",
1481
+ round_num=0,
1482
+ phase="drain_backlog",
1483
+ details={
1484
+ "exit_code": drain_result.exit_code,
1485
+ "completed_ids": drain_completed,
1486
+ "failed_ids": drain_failed,
1487
+ },
1488
+ )
1489
+ if drain_result.exit_code != 0 or drain_failed:
1490
+ drain_detail = (drain_result.stderr or drain_result.message or "").strip()
1491
+ if drain_detail:
1492
+ _emit_log(f"Backlog drain error: {drain_detail}", level="ERROR")
1493
+ reason = "STOP_BACKLOG_DRAIN_FAILED"
1494
+ summary = (
1495
+ f"Existing backlog drain failed (exit_code={drain_result.exit_code}, "
1496
+ f"failed_ids={drain_failed})."
1497
+ )
1498
+ _write_state(
1499
+ iterate_paths,
1500
+ status="failed",
1501
+ phase="stopped",
1502
+ current_round=0,
1503
+ completed_rounds=total_completed_rounds,
1504
+ active_feature_id=None,
1505
+ stop_reason=reason,
1506
+ pause_reason=None,
1507
+ options=options,
1508
+ consecutive_failures=0,
1509
+ consecutive_no_progress=0,
1510
+ started_at=started_at,
1511
+ last_verdict=None,
1512
+ last_evidence_mode=None,
1513
+ summary=summary,
1514
+ )
1515
+ _write_final_summary(
1516
+ iterate_paths,
1517
+ reason=reason,
1518
+ status="failed",
1519
+ ledger=ledger,
1520
+ summary=summary,
1521
+ )
1522
+ _append_event(
1523
+ iterate_paths,
1524
+ "iterate_failed",
1525
+ round_num=0,
1526
+ phase="stopped",
1527
+ details={"reason": reason, "summary": summary},
1528
+ )
1529
+ return CommandResult(1, "Python iterate runner", f"{reason}: {summary}")
1530
+
1531
+ # Main Serial Round Loop
1532
+ while True:
1533
+ round_num = _next_round_number(ledger)
1534
+ current_round = round_num
1535
+ round_started_at = _utc_iso()
1536
+ round_dir = iterate_paths.rounds_dir / f"round-{round_num:03d}"
1537
+ round_dir.mkdir(parents=True, exist_ok=True)
1538
+ head_before = _current_head_sha(paths.project_root)
1539
+
1540
+ # ---------------- Phase A: Read-Only Evaluation ----------------
1541
+ _emit_log(f"Round {round_num} — Phase A: Read-only product evaluation")
1542
+ _write_state(
1543
+ iterate_paths,
1544
+ status="running",
1545
+ phase="evaluating",
1546
+ current_round=round_num,
1547
+ completed_rounds=total_completed_rounds,
1548
+ active_feature_id=None,
1549
+ stop_reason=None,
1550
+ pause_reason=None,
1551
+ options=options,
1552
+ consecutive_failures=consecutive_failures,
1553
+ consecutive_no_progress=consecutive_no_progress,
1554
+ started_at=started_at,
1555
+ last_verdict=last_verdict,
1556
+ last_evidence_mode=last_evidence_mode,
1557
+ summary=f"Round {round_num}: running Phase A read-only evaluation.",
1558
+ )
1559
+ _append_event(iterate_paths, "round_started", round_num=round_num, phase="evaluating")
1560
+ _append_event(iterate_paths, "phase_a_started", round_num=round_num, phase="evaluating")
1561
+
1562
+ eval_output_path = round_dir / "evaluation.json"
1563
+ eval_prompt_path = round_dir / "evaluate-prompt.md"
1564
+ eval_prompt = render_evaluate_prompt(
1565
+ paths,
1566
+ round_dir=round_dir,
1567
+ output_path=eval_output_path,
1568
+ focus=options.focus,
1569
+ ledger=ledger,
1570
+ )
1571
+ write_text_atomic(eval_prompt_path, eval_prompt)
1572
+
1573
+ eval_output_path.unlink(missing_ok=True)
1574
+ fp_before_eval = capture_workspace_fingerprint(paths.project_root, paths.prizmkit_dir)
1575
+ eval_session = _launch_fresh_session(
1576
+ paths,
1577
+ config,
1578
+ stream_json=stream_json,
1579
+ prompt_path=eval_prompt_path,
1580
+ logs_dir=round_dir / "evaluate-logs",
1581
+ )
1582
+ fp_after_eval = capture_workspace_fingerprint(paths.project_root, paths.prizmkit_dir)
1583
+ dirty_paths = diff_workspace_fingerprints(fp_before_eval, fp_after_eval)
1584
+ if dirty_paths:
1585
+ reason = "STOP_EVAL_DIRTY_WORKSPACE"
1586
+ summary = (
1587
+ "Phase A read-only evaluation modified repository state outside .prizmkit/state/: "
1588
+ + ", ".join(dirty_paths)
1589
+ )
1590
+ head_after_dirty = _current_head_sha(paths.project_root)
1591
+ ledger["rounds"].append(
1592
+ {
1593
+ "round": round_num,
1594
+ "started_at": round_started_at,
1595
+ "ended_at": _utc_iso(),
1596
+ "verdict": reason,
1597
+ "evidence_mode": None,
1598
+ "product_shapes": [],
1599
+ "appended_ids": [],
1600
+ "completed_ids": [],
1601
+ "failed_ids": [],
1602
+ "deferred_for_user": [],
1603
+ "rejected_candidates": [],
1604
+ "dirty_paths": list(dirty_paths),
1605
+ "head_before": head_before,
1606
+ "head_after": head_after_dirty,
1607
+ "progressed": False,
1608
+ "stop_or_pause_reason": reason,
1609
+ "summary": summary,
1610
+ }
1611
+ )
1612
+ write_json_atomic(iterate_paths.ledger_file, ledger)
1613
+ _write_state(
1614
+ iterate_paths,
1615
+ status="failed",
1616
+ phase="stopped",
1617
+ current_round=round_num,
1618
+ completed_rounds=total_completed_rounds,
1619
+ active_feature_id=None,
1620
+ stop_reason=reason,
1621
+ pause_reason=None,
1622
+ options=options,
1623
+ consecutive_failures=consecutive_failures,
1624
+ consecutive_no_progress=consecutive_no_progress,
1625
+ started_at=started_at,
1626
+ last_verdict=reason,
1627
+ last_evidence_mode=last_evidence_mode,
1628
+ summary=summary,
1629
+ )
1630
+ _write_final_summary(
1631
+ iterate_paths,
1632
+ reason=reason,
1633
+ status="failed",
1634
+ ledger=ledger,
1635
+ summary=summary,
1636
+ )
1637
+ _append_event(
1638
+ iterate_paths,
1639
+ "iterate_failed",
1640
+ round_num=round_num,
1641
+ phase="stopped",
1642
+ details={"reason": reason, "dirty_paths": list(dirty_paths)},
1643
+ )
1644
+ return CommandResult(1, "Python iterate runner", f"{reason}: {summary}")
1645
+
1646
+ eval_data: Any = None
1647
+ eval_errors: tuple[str, ...] = ()
1648
+ eval_session_error = _session_failure_reason(eval_session)
1649
+ if eval_session_error:
1650
+ eval_errors = (f"Phase A session failed: {eval_session_error}",)
1651
+ elif not eval_output_path.is_file():
1652
+ eval_errors = (f"Phase A did not produce evaluation output at {eval_output_path}",)
1653
+ else:
1654
+ try:
1655
+ eval_data = json.loads(eval_output_path.read_text(encoding="utf-8"))
1656
+ except (OSError, json.JSONDecodeError) as exc:
1657
+ eval_errors = (f"Invalid JSON in {eval_output_path}: {exc}",)
1658
+ else:
1659
+ valid_eval, eval_errors = validate_evaluation_payload(eval_data)
1660
+ if not valid_eval:
1661
+ eval_data = None
1662
+
1663
+ if eval_data is None:
1664
+ reason = "STOP_EVAL_INVALID"
1665
+ summary = "Phase A evaluation validation failed: " + "; ".join(eval_errors)
1666
+ ledger["rounds"].append(
1667
+ {
1668
+ "round": round_num,
1669
+ "started_at": round_started_at,
1670
+ "ended_at": _utc_iso(),
1671
+ "verdict": reason,
1672
+ "evidence_mode": None,
1673
+ "product_shapes": [],
1674
+ "appended_ids": [],
1675
+ "completed_ids": [],
1676
+ "failed_ids": [],
1677
+ "deferred_for_user": [],
1678
+ "rejected_candidates": [],
1679
+ "validation_errors": list(eval_errors),
1680
+ "head_before": head_before,
1681
+ "head_after": head_before,
1682
+ "progressed": False,
1683
+ "stop_or_pause_reason": reason,
1684
+ "summary": summary,
1685
+ }
1686
+ )
1687
+ write_json_atomic(iterate_paths.ledger_file, ledger)
1688
+ _write_state(
1689
+ iterate_paths,
1690
+ status="failed",
1691
+ phase="stopped",
1692
+ current_round=round_num,
1693
+ completed_rounds=total_completed_rounds,
1694
+ active_feature_id=None,
1695
+ stop_reason=reason,
1696
+ pause_reason=None,
1697
+ options=options,
1698
+ consecutive_failures=consecutive_failures,
1699
+ consecutive_no_progress=consecutive_no_progress,
1700
+ started_at=started_at,
1701
+ last_verdict=reason,
1702
+ last_evidence_mode=last_evidence_mode,
1703
+ summary=summary,
1704
+ )
1705
+ _write_final_summary(
1706
+ iterate_paths,
1707
+ reason=reason,
1708
+ status="failed",
1709
+ ledger=ledger,
1710
+ summary=summary,
1711
+ )
1712
+ _append_event(
1713
+ iterate_paths,
1714
+ "iterate_failed",
1715
+ round_num=round_num,
1716
+ phase="stopped",
1717
+ details={"reason": reason, "errors": list(eval_errors)},
1718
+ )
1719
+ return CommandResult(1, "Python iterate runner", f"{reason}: {summary}")
1720
+
1721
+ verdict = str(eval_data["verdict"])
1722
+ evidence_mode = str(eval_data["evidence_mode"])
1723
+ product_shapes = list(eval_data["product_shapes"])
1724
+ approved_candidates = list(eval_data["approved_candidates"])
1725
+ requires_user_confirm = list(eval_data["requires_user_confirm"])
1726
+ rejected_candidates = list(eval_data["rejected_candidates"])
1727
+ eval_summary = str(eval_data["summary"])
1728
+ last_verdict = verdict
1729
+ last_evidence_mode = evidence_mode
1730
+
1731
+ _append_event(
1732
+ iterate_paths,
1733
+ "phase_a_finished",
1734
+ round_num=round_num,
1735
+ phase="evaluating",
1736
+ details={
1737
+ "verdict": verdict,
1738
+ "evidence_mode": evidence_mode,
1739
+ "approved_count": len(approved_candidates),
1740
+ "confirm_count": len(requires_user_confirm),
1741
+ "rejected_count": len(rejected_candidates),
1742
+ },
1743
+ )
1744
+
1745
+ # Early clean stop verdicts (never run Phase B/C)
1746
+ if verdict in {"STOP_GOAL_REACHED", "STOP_NO_HIGH_VALUE"}:
1747
+ ledger["rounds"].append(
1748
+ {
1749
+ "round": round_num,
1750
+ "started_at": round_started_at,
1751
+ "ended_at": _utc_iso(),
1752
+ "verdict": verdict,
1753
+ "evidence_mode": evidence_mode,
1754
+ "product_shapes": product_shapes,
1755
+ "appended_ids": [],
1756
+ "completed_ids": [],
1757
+ "failed_ids": [],
1758
+ "deferred_for_user": requires_user_confirm,
1759
+ "rejected_candidates": rejected_candidates,
1760
+ "head_before": head_before,
1761
+ "head_after": head_before,
1762
+ "progressed": False,
1763
+ "stop_or_pause_reason": verdict,
1764
+ "summary": eval_summary,
1765
+ }
1766
+ )
1767
+ write_json_atomic(iterate_paths.ledger_file, ledger)
1768
+ _write_state(
1769
+ iterate_paths,
1770
+ status="stopped",
1771
+ phase="stopped",
1772
+ current_round=round_num,
1773
+ completed_rounds=total_completed_rounds,
1774
+ active_feature_id=None,
1775
+ stop_reason=verdict,
1776
+ pause_reason=None,
1777
+ options=options,
1778
+ consecutive_failures=consecutive_failures,
1779
+ consecutive_no_progress=consecutive_no_progress,
1780
+ started_at=started_at,
1781
+ last_verdict=verdict,
1782
+ last_evidence_mode=evidence_mode,
1783
+ summary=eval_summary,
1784
+ )
1785
+ _write_final_summary(
1786
+ iterate_paths,
1787
+ reason=verdict,
1788
+ status="stopped",
1789
+ ledger=ledger,
1790
+ summary=eval_summary,
1791
+ )
1792
+ _append_event(
1793
+ iterate_paths,
1794
+ "round_finished",
1795
+ round_num=round_num,
1796
+ phase="stopped",
1797
+ details={"verdict": verdict, "reason": verdict},
1798
+ )
1799
+ _append_event(
1800
+ iterate_paths,
1801
+ "iterate_stopped",
1802
+ round_num=round_num,
1803
+ phase="stopped",
1804
+ details={"reason": verdict, "summary": eval_summary},
1805
+ )
1806
+ return CommandResult(
1807
+ 0,
1808
+ "Python iterate runner",
1809
+ f"{verdict}: {eval_summary}",
1810
+ details=(
1811
+ f"round: {round_num}",
1812
+ f"evidence_mode: {evidence_mode}",
1813
+ f"summary_file: {iterate_paths.summary_file}",
1814
+ ),
1815
+ )
1816
+
1817
+ # User confirmation pause (zero code / feature-list mutation)
1818
+ if verdict == "PAUSE_FOR_USER_CONFIRM":
1819
+ _write_pending_decisions(
1820
+ iterate_paths,
1821
+ round_num,
1822
+ requires_user_confirm,
1823
+ eval_summary,
1824
+ )
1825
+ ledger["rounds"].append(
1826
+ {
1827
+ "round": round_num,
1828
+ "started_at": round_started_at,
1829
+ "ended_at": _utc_iso(),
1830
+ "verdict": verdict,
1831
+ "evidence_mode": evidence_mode,
1832
+ "product_shapes": product_shapes,
1833
+ "appended_ids": [],
1834
+ "completed_ids": [],
1835
+ "failed_ids": [],
1836
+ "deferred_for_user": requires_user_confirm,
1837
+ "rejected_candidates": rejected_candidates,
1838
+ "head_before": head_before,
1839
+ "head_after": head_before,
1840
+ "progressed": False,
1841
+ "stop_or_pause_reason": verdict,
1842
+ "summary": eval_summary,
1843
+ }
1844
+ )
1845
+ write_json_atomic(iterate_paths.ledger_file, ledger)
1846
+ _write_state(
1847
+ iterate_paths,
1848
+ status="paused_awaiting_user",
1849
+ phase="paused",
1850
+ current_round=round_num,
1851
+ completed_rounds=total_completed_rounds,
1852
+ active_feature_id=None,
1853
+ stop_reason=None,
1854
+ pause_reason=verdict,
1855
+ options=options,
1856
+ consecutive_failures=consecutive_failures,
1857
+ consecutive_no_progress=consecutive_no_progress,
1858
+ started_at=started_at,
1859
+ last_verdict=verdict,
1860
+ last_evidence_mode=evidence_mode,
1861
+ summary=eval_summary,
1862
+ )
1863
+ _write_final_summary(
1864
+ iterate_paths,
1865
+ reason=verdict,
1866
+ status="paused_awaiting_user",
1867
+ ledger=ledger,
1868
+ summary=eval_summary,
1869
+ )
1870
+ _append_event(
1871
+ iterate_paths,
1872
+ "round_finished",
1873
+ round_num=round_num,
1874
+ phase="paused",
1875
+ details={"verdict": verdict, "deferred_count": len(requires_user_confirm)},
1876
+ )
1877
+ _append_event(
1878
+ iterate_paths,
1879
+ "iterate_paused",
1880
+ round_num=round_num,
1881
+ phase="paused",
1882
+ details={
1883
+ "reason": verdict,
1884
+ "pending_decisions_file": str(iterate_paths.pending_decisions_file),
1885
+ },
1886
+ )
1887
+ return CommandResult(
1888
+ 0,
1889
+ "Python iterate runner",
1890
+ f"{verdict}: {eval_summary}",
1891
+ details=(
1892
+ f"round: {round_num}",
1893
+ "status: paused_awaiting_user",
1894
+ f"pending_decisions: {iterate_paths.pending_decisions_file}",
1895
+ ),
1896
+ )
1897
+
1898
+ # Secondary deferred proposals alongside approved candidates
1899
+ if requires_user_confirm:
1900
+ _write_pending_decisions(
1901
+ iterate_paths,
1902
+ round_num,
1903
+ requires_user_confirm,
1904
+ eval_summary,
1905
+ )
1906
+
1907
+ # ---------------- Phase B: Headless Feature Planning ----------------
1908
+ _emit_log(
1909
+ f"Round {round_num} — Phase B: Headless feature planning "
1910
+ f"({len(approved_candidates)} approved candidate(s))"
1911
+ )
1912
+ _write_state(
1913
+ iterate_paths,
1914
+ status="running",
1915
+ phase="planning",
1916
+ current_round=round_num,
1917
+ completed_rounds=total_completed_rounds,
1918
+ active_feature_id=None,
1919
+ stop_reason=None,
1920
+ pause_reason=None,
1921
+ options=options,
1922
+ consecutive_failures=consecutive_failures,
1923
+ consecutive_no_progress=consecutive_no_progress,
1924
+ started_at=started_at,
1925
+ last_verdict=verdict,
1926
+ last_evidence_mode=evidence_mode,
1927
+ summary=f"Round {round_num}: running Phase B headless feature planning.",
1928
+ )
1929
+ _append_event(
1930
+ iterate_paths,
1931
+ "phase_b_started",
1932
+ round_num=round_num,
1933
+ phase="planning",
1934
+ details={"approved_count": len(approved_candidates)},
1935
+ )
1936
+
1937
+ plan_mode = "append" if paths.feature_plan.is_file() else "generate"
1938
+ context_path = round_dir / "plan-context.json"
1939
+ candidates_path = round_dir / "approved-candidates.json"
1940
+ draft_path = round_dir / "draft.json"
1941
+
1942
+ if plan_mode == "append":
1943
+ bounded_ctx, ctx_code, ctx_errors = contract_mod.extract_context(paths.feature_plan)
1944
+ if ctx_code != 0 or bounded_ctx is None:
1945
+ reason = "STOP_PLAN_INVALID"
1946
+ summary = "Failed to extract bounded context from existing feature-list.json: " + "; ".join(ctx_errors)
1947
+ _record_plan_failure(
1948
+ iterate_paths,
1949
+ ledger,
1950
+ options=options,
1951
+ round_num=round_num,
1952
+ round_started_at=round_started_at,
1953
+ started_at=started_at,
1954
+ total_completed_rounds=total_completed_rounds,
1955
+ consecutive_failures=consecutive_failures,
1956
+ consecutive_no_progress=consecutive_no_progress,
1957
+ verdict=verdict,
1958
+ evidence_mode=evidence_mode,
1959
+ product_shapes=product_shapes,
1960
+ requires_user_confirm=requires_user_confirm,
1961
+ rejected_candidates=rejected_candidates,
1962
+ head_before=head_before,
1963
+ reason=reason,
1964
+ summary=summary,
1965
+ )
1966
+ return CommandResult(1, "Python iterate runner", f"{reason}: {summary}")
1967
+ bounded_ctx["mode"] = "append"
1968
+ else:
1969
+ bounded_ctx = _build_initial_plan_context(paths)
1970
+
1971
+ write_json_atomic(context_path, bounded_ctx)
1972
+ write_json_atomic(candidates_path, {"approved_candidates": approved_candidates})
1973
+
1974
+ dry_run_op = None
1975
+ repair_errors: tuple[str, ...] = ()
1976
+ plan_dirty_paths: tuple[str, ...] = ()
1977
+ for attempt in range(MAX_PLAN_REPAIR_RETRIES + 1):
1978
+ prompt_name = (
1979
+ "headless-plan-prompt.md"
1980
+ if attempt == 0
1981
+ else f"headless-plan-prompt-retry-{attempt}.md"
1982
+ )
1983
+ plan_prompt_path = round_dir / prompt_name
1984
+ plan_prompt = render_headless_plan_prompt(
1985
+ paths,
1986
+ mode=plan_mode,
1987
+ context_path=context_path,
1988
+ candidates_path=candidates_path,
1989
+ draft_output_path=draft_path,
1990
+ repair_errors=repair_errors,
1991
+ )
1992
+ write_text_atomic(plan_prompt_path, plan_prompt)
1993
+
1994
+ draft_path.unlink(missing_ok=True)
1995
+ plan_fp_before = capture_workspace_fingerprint(paths.project_root, paths.prizmkit_dir)
1996
+ plan_session = _launch_fresh_session(
1997
+ paths,
1998
+ config,
1999
+ stream_json=stream_json,
2000
+ prompt_path=plan_prompt_path,
2001
+ logs_dir=round_dir / ("plan-logs" if attempt == 0 else f"plan-logs-retry-{attempt}"),
2002
+ )
2003
+ plan_fp_after = capture_workspace_fingerprint(paths.project_root, paths.prizmkit_dir)
2004
+ plan_dirty_paths = diff_workspace_fingerprints(plan_fp_before, plan_fp_after)
2005
+ if plan_dirty_paths:
2006
+ repair_errors = (
2007
+ "Phase B directly modified repository files outside .prizmkit/state/: "
2008
+ + ", ".join(plan_dirty_paths),
2009
+ )
2010
+ dry_run_op = None
2011
+ break
2012
+
2013
+ plan_session_error = _session_failure_reason(plan_session)
2014
+ if plan_session_error:
2015
+ dry_run_op = None
2016
+ repair_errors = (f"Phase B session failed: {plan_session_error}",)
2017
+ else:
2018
+ if plan_mode == "append":
2019
+ dry_run_op = contract_mod.append_feature_list(
2020
+ draft_path,
2021
+ paths.feature_plan,
2022
+ dry_run=True,
2023
+ )
2024
+ else:
2025
+ dry_run_op = contract_mod.generate_feature_list(
2026
+ draft_path,
2027
+ paths.feature_plan,
2028
+ dry_run=True,
2029
+ require_sequential_ids=True,
2030
+ default_created_by="prizmkit-iterate",
2031
+ )
2032
+
2033
+ if dry_run_op.ok:
2034
+ pending_errors = _validate_phase_b_draft_pending_statuses(draft_path)
2035
+ if pending_errors:
2036
+ repair_errors = pending_errors
2037
+ dry_run_op = None
2038
+ elif not (1 <= len(dry_run_op.appended_ids) <= 3):
2039
+ repair_errors = (
2040
+ "Phase B draft must contain 1-3 contract-bounded features matching "
2041
+ f"Phase A approved candidates (got {len(dry_run_op.appended_ids)})",
2042
+ )
2043
+ dry_run_op = None
2044
+ else:
2045
+ break
2046
+ else:
2047
+ repair_errors = dry_run_op.errors
2048
+ if attempt < MAX_PLAN_REPAIR_RETRIES:
2049
+ _emit_log(
2050
+ f"Round {round_num} — Phase B validation failed (attempt {attempt + 1}), "
2051
+ "retrying headless plan"
2052
+ )
2053
+ _append_event(
2054
+ iterate_paths,
2055
+ "phase_b_retry",
2056
+ round_num=round_num,
2057
+ phase="planning",
2058
+ details={"attempt": attempt + 1, "errors": list(repair_errors)},
2059
+ )
2060
+
2061
+ if plan_dirty_paths or dry_run_op is None or not dry_run_op.ok:
2062
+ reason = "STOP_PLAN_INVALID"
2063
+ summary = "Phase B headless planning failed validation: " + "; ".join(repair_errors)
2064
+ _record_plan_failure(
2065
+ iterate_paths,
2066
+ ledger,
2067
+ options=options,
2068
+ round_num=round_num,
2069
+ round_started_at=round_started_at,
2070
+ started_at=started_at,
2071
+ total_completed_rounds=total_completed_rounds,
2072
+ consecutive_failures=consecutive_failures,
2073
+ consecutive_no_progress=consecutive_no_progress,
2074
+ verdict=verdict,
2075
+ evidence_mode=evidence_mode,
2076
+ product_shapes=product_shapes,
2077
+ requires_user_confirm=requires_user_confirm,
2078
+ rejected_candidates=rejected_candidates,
2079
+ head_before=head_before,
2080
+ reason=reason,
2081
+ summary=summary,
2082
+ )
2083
+ return CommandResult(1, "Python iterate runner", f"{reason}: {summary}")
2084
+
2085
+ # Runtime-owned single atomic write
2086
+ if plan_mode == "append":
2087
+ write_op = contract_mod.append_feature_list(
2088
+ draft_path,
2089
+ paths.feature_plan,
2090
+ dry_run=False,
2091
+ )
2092
+ else:
2093
+ write_op = contract_mod.generate_feature_list(
2094
+ draft_path,
2095
+ paths.feature_plan,
2096
+ dry_run=False,
2097
+ require_sequential_ids=True,
2098
+ default_created_by="prizmkit-iterate",
2099
+ )
2100
+
2101
+ if not write_op.ok or not write_op.appended_ids:
2102
+ reason = "STOP_PLAN_INVALID"
2103
+ summary = "Runtime atomic feature-list write failed: " + "; ".join(write_op.errors)
2104
+ _record_plan_failure(
2105
+ iterate_paths,
2106
+ ledger,
2107
+ options=options,
2108
+ round_num=round_num,
2109
+ round_started_at=round_started_at,
2110
+ started_at=started_at,
2111
+ total_completed_rounds=total_completed_rounds,
2112
+ consecutive_failures=consecutive_failures,
2113
+ consecutive_no_progress=consecutive_no_progress,
2114
+ verdict=verdict,
2115
+ evidence_mode=evidence_mode,
2116
+ product_shapes=product_shapes,
2117
+ requires_user_confirm=requires_user_confirm,
2118
+ rejected_candidates=rejected_candidates,
2119
+ head_before=head_before,
2120
+ reason=reason,
2121
+ summary=summary,
2122
+ )
2123
+ return CommandResult(1, "Python iterate runner", f"{reason}: {summary}")
2124
+
2125
+ appended_ids = list(write_op.appended_ids)
2126
+ _append_event(
2127
+ iterate_paths,
2128
+ "phase_b_finished",
2129
+ round_num=round_num,
2130
+ phase="planning",
2131
+ details={"mode": plan_mode, "appended_ids": appended_ids},
2132
+ )
2133
+
2134
+ # ---------------- Phase C: Scoped Serial Delivery ----------------
2135
+ feature_range = f"{appended_ids[0]}:{appended_ids[-1]}"
2136
+ _emit_log(
2137
+ f"Round {round_num} — Phase C: Serial delivery for --features {feature_range}"
2138
+ )
2139
+ _write_state(
2140
+ iterate_paths,
2141
+ status="running",
2142
+ phase="delivering",
2143
+ current_round=round_num,
2144
+ completed_rounds=total_completed_rounds,
2145
+ active_feature_id=appended_ids[0],
2146
+ stop_reason=None,
2147
+ pause_reason=None,
2148
+ options=options,
2149
+ consecutive_failures=consecutive_failures,
2150
+ consecutive_no_progress=consecutive_no_progress,
2151
+ started_at=started_at,
2152
+ last_verdict=verdict,
2153
+ last_evidence_mode=evidence_mode,
2154
+ summary=f"Round {round_num}: delivering features {feature_range}.",
2155
+ )
2156
+ _append_event(
2157
+ iterate_paths,
2158
+ "phase_c_started",
2159
+ round_num=round_num,
2160
+ phase="delivering",
2161
+ details={"feature_range": feature_range, "appended_ids": appended_ids},
2162
+ )
2163
+
2164
+ delivery_result = run_pipeline_command(
2165
+ "feature",
2166
+ "run",
2167
+ (str(paths.feature_plan), "--features", feature_range),
2168
+ paths,
2169
+ )
2170
+ if delivery_result.exit_code != 0 and "stopped_reason=interrupted" in (delivery_result.message or ""):
2171
+ raise KeyboardInterrupt("Phase C delivery interrupted")
2172
+ status_map = _feature_status_map(paths.feature_plan)
2173
+ completed_ids = [
2174
+ fid for fid in appended_ids if status_map.get(fid) in {"completed", "split"}
2175
+ ]
2176
+ failed_ids = [fid for fid in appended_ids if fid not in completed_ids]
2177
+ if delivery_result.exit_code != 0:
2178
+ delivery_detail = (delivery_result.stderr or delivery_result.message or "").strip()
2179
+ if delivery_detail:
2180
+ _emit_log(f"Round {round_num} delivery error: {delivery_detail}", level="ERROR")
2181
+
2182
+ _append_event(
2183
+ iterate_paths,
2184
+ "phase_c_finished",
2185
+ round_num=round_num,
2186
+ phase="delivering",
2187
+ details={
2188
+ "exit_code": delivery_result.exit_code,
2189
+ "completed_ids": completed_ids,
2190
+ "failed_ids": failed_ids,
2191
+ },
2192
+ )
2193
+
2194
+ # ---------------- Phase D: Ledger Writeback & Circuit Breakers ----------------
2195
+ head_after = _current_head_sha(paths.project_root)
2196
+ progressed = _round_made_real_progress(paths.project_root, head_before, head_after)
2197
+ round_failed = bool(failed_ids) or delivery_result.exit_code != 0
2198
+ rounds_executed_in_run += 1
2199
+
2200
+ if round_failed:
2201
+ consecutive_failures += 1
2202
+ else:
2203
+ consecutive_failures = 0
2204
+ completed_rounds_in_run += 1
2205
+ total_completed_rounds += 1
2206
+
2207
+ if not progressed:
2208
+ consecutive_no_progress += 1
2209
+ else:
2210
+ consecutive_no_progress = 0
2211
+
2212
+ halt = _evaluate_post_round_guards(
2213
+ limits=options.limits,
2214
+ rounds_executed_in_run=rounds_executed_in_run,
2215
+ completed_rounds_in_run=completed_rounds_in_run,
2216
+ consecutive_failures=consecutive_failures,
2217
+ consecutive_no_progress=consecutive_no_progress,
2218
+ )
2219
+
2220
+ halt_reason = halt[2] if halt is not None else None
2221
+ ledger["rounds"].append(
2222
+ {
2223
+ "round": round_num,
2224
+ "started_at": round_started_at,
2225
+ "ended_at": _utc_iso(),
2226
+ "verdict": verdict,
2227
+ "evidence_mode": evidence_mode,
2228
+ "product_shapes": product_shapes,
2229
+ "appended_ids": appended_ids,
2230
+ "completed_ids": completed_ids,
2231
+ "failed_ids": failed_ids,
2232
+ "deferred_for_user": requires_user_confirm,
2233
+ "rejected_candidates": rejected_candidates,
2234
+ "head_before": head_before,
2235
+ "head_after": head_after,
2236
+ "progressed": progressed,
2237
+ "stop_or_pause_reason": halt_reason,
2238
+ "summary": eval_summary,
2239
+ }
2240
+ )
2241
+ write_json_atomic(iterate_paths.ledger_file, ledger)
2242
+ _append_event(
2243
+ iterate_paths,
2244
+ "round_finished",
2245
+ round_num=round_num,
2246
+ phase="delivering",
2247
+ details={
2248
+ "appended_ids": appended_ids,
2249
+ "completed_ids": completed_ids,
2250
+ "failed_ids": failed_ids,
2251
+ "progressed": progressed,
2252
+ "halt_reason": halt_reason,
2253
+ },
2254
+ )
2255
+
2256
+ if halt is not None:
2257
+ final_status, final_phase, reason, exit_code = halt
2258
+ stop_reason = reason if final_phase == "stopped" else None
2259
+ pause_reason = reason if final_phase == "paused" else None
2260
+ final_summary = (
2261
+ f"Round {round_num} finished ({len(completed_ids)}/{len(appended_ids)} features completed); "
2262
+ f"halted with {reason}."
2263
+ )
2264
+ _write_state(
2265
+ iterate_paths,
2266
+ status=final_status,
2267
+ phase=final_phase,
2268
+ current_round=round_num,
2269
+ completed_rounds=total_completed_rounds,
2270
+ active_feature_id=None,
2271
+ stop_reason=stop_reason,
2272
+ pause_reason=pause_reason,
2273
+ options=options,
2274
+ consecutive_failures=consecutive_failures,
2275
+ consecutive_no_progress=consecutive_no_progress,
2276
+ started_at=started_at,
2277
+ last_verdict=verdict,
2278
+ last_evidence_mode=evidence_mode,
2279
+ summary=final_summary,
2280
+ )
2281
+ _write_final_summary(
2282
+ iterate_paths,
2283
+ reason=reason,
2284
+ status=final_status,
2285
+ ledger=ledger,
2286
+ summary=final_summary,
2287
+ )
2288
+ event_name = (
2289
+ "iterate_paused"
2290
+ if final_phase == "paused"
2291
+ else ("iterate_failed" if exit_code != 0 else "iterate_stopped")
2292
+ )
2293
+ _append_event(
2294
+ iterate_paths,
2295
+ event_name,
2296
+ round_num=round_num,
2297
+ phase=final_phase,
2298
+ details={"reason": reason, "summary": final_summary},
2299
+ )
2300
+ return CommandResult(
2301
+ exit_code,
2302
+ "Python iterate runner",
2303
+ f"{reason}: {final_summary}",
2304
+ details=(
2305
+ f"round: {round_num}",
2306
+ f"status: {final_status}",
2307
+ f"completed_rounds: {total_completed_rounds}",
2308
+ ),
2309
+ )
2310
+ except KeyboardInterrupt:
2311
+ with shield_interruption_signals():
2312
+ reason = "STOP_INTERRUPTED"
2313
+ summary = f"Iterate loop interrupted during round {current_round}."
2314
+ _write_state(
2315
+ iterate_paths,
2316
+ status="failed",
2317
+ phase="stopped",
2318
+ current_round=current_round,
2319
+ completed_rounds=total_completed_rounds,
2320
+ active_feature_id=None,
2321
+ stop_reason=reason,
2322
+ pause_reason=None,
2323
+ options=options,
2324
+ consecutive_failures=consecutive_failures,
2325
+ consecutive_no_progress=consecutive_no_progress,
2326
+ started_at=started_at,
2327
+ last_verdict=last_verdict,
2328
+ last_evidence_mode=last_evidence_mode,
2329
+ summary=summary,
2330
+ )
2331
+ _append_event(
2332
+ iterate_paths,
2333
+ "iterate_failed",
2334
+ round_num=current_round,
2335
+ phase="stopped",
2336
+ details={"reason": reason},
2337
+ )
2338
+ return CommandResult(1, "Python iterate runner", f"{reason}: {summary}")
2339
+ except Exception as exc:
2340
+ reason = "STOP_RUNTIME_ERROR"
2341
+ detail = str(exc).strip()
2342
+ summary = f"{type(exc).__name__}: {detail}" if detail else type(exc).__name__
2343
+ _emit_log(f"Unexpected iterate runtime error: {summary}", level="ERROR")
2344
+ _write_state(
2345
+ iterate_paths,
2346
+ status="failed",
2347
+ phase="stopped",
2348
+ current_round=current_round,
2349
+ completed_rounds=total_completed_rounds,
2350
+ active_feature_id=None,
2351
+ stop_reason=reason,
2352
+ pause_reason=None,
2353
+ options=options,
2354
+ consecutive_failures=consecutive_failures,
2355
+ consecutive_no_progress=consecutive_no_progress,
2356
+ started_at=started_at,
2357
+ last_verdict=last_verdict,
2358
+ last_evidence_mode=last_evidence_mode,
2359
+ summary=summary,
2360
+ )
2361
+ _write_final_summary(
2362
+ iterate_paths,
2363
+ reason=reason,
2364
+ status="failed",
2365
+ ledger=ledger,
2366
+ summary=summary,
2367
+ )
2368
+ _append_event(
2369
+ iterate_paths,
2370
+ "iterate_failed",
2371
+ round_num=current_round,
2372
+ phase="stopped",
2373
+ details={"reason": reason, "summary": summary},
2374
+ )
2375
+ return CommandResult(1, "Python iterate runner", f"{reason}: {summary}", stderr=summary)
2376
+
2377
+
2378
+ def _evaluate_post_round_guards(
2379
+ *,
2380
+ limits: IterateLimits,
2381
+ rounds_executed_in_run: int,
2382
+ completed_rounds_in_run: int,
2383
+ consecutive_failures: int,
2384
+ consecutive_no_progress: int,
2385
+ ) -> tuple[str, str, str, int] | None:
2386
+ """Return (status, phase, reason, exit_code) when a post-round breaker fires."""
2387
+ if consecutive_failures >= limits.max_consecutive_failures:
2388
+ return ("failed", "stopped", "STOP_CONSECUTIVE_FAILURES", 1)
2389
+ if consecutive_no_progress >= limits.max_consecutive_no_progress:
2390
+ return ("failed", "stopped", "STOP_NO_PROGRESS", 1)
2391
+ if limits.max_rounds is not None and rounds_executed_in_run >= limits.max_rounds:
2392
+ return ("stopped", "stopped", "STOP_MAX_ROUNDS", 0)
2393
+ if limits.max_rounds is None and rounds_executed_in_run >= limits.safety_cap:
2394
+ return ("paused", "paused", "PAUSE_SAFETY_CAP", 0)
2395
+ checkpoint_active = (
2396
+ not limits.no_checkpoint
2397
+ and limits.checkpoint_every > 0
2398
+ and (limits.max_rounds is None or limits.checkpoint_every_explicit)
2399
+ )
2400
+ if (
2401
+ checkpoint_active
2402
+ and completed_rounds_in_run > 0
2403
+ and completed_rounds_in_run % limits.checkpoint_every == 0
2404
+ ):
2405
+ return ("paused", "paused", "PAUSE_CHECKPOINT_REVIEW", 0)
2406
+ return None
2407
+
2408
+
2409
+ def _record_plan_failure(
2410
+ iterate_paths: IteratePaths,
2411
+ ledger: dict[str, Any],
2412
+ *,
2413
+ options: IterateOptions,
2414
+ round_num: int,
2415
+ round_started_at: str,
2416
+ started_at: str,
2417
+ total_completed_rounds: int,
2418
+ consecutive_failures: int,
2419
+ consecutive_no_progress: int,
2420
+ verdict: str,
2421
+ evidence_mode: str,
2422
+ product_shapes: list[str],
2423
+ requires_user_confirm: list[dict[str, Any]],
2424
+ rejected_candidates: list[dict[str, Any]],
2425
+ head_before: str,
2426
+ reason: str,
2427
+ summary: str,
2428
+ ) -> None:
2429
+ ledger["rounds"].append(
2430
+ {
2431
+ "round": round_num,
2432
+ "started_at": round_started_at,
2433
+ "ended_at": _utc_iso(),
2434
+ "verdict": verdict,
2435
+ "evidence_mode": evidence_mode,
2436
+ "product_shapes": product_shapes,
2437
+ "appended_ids": [],
2438
+ "completed_ids": [],
2439
+ "failed_ids": [],
2440
+ "deferred_for_user": requires_user_confirm,
2441
+ "rejected_candidates": rejected_candidates,
2442
+ "head_before": head_before,
2443
+ "head_after": head_before,
2444
+ "progressed": False,
2445
+ "stop_or_pause_reason": reason,
2446
+ "summary": summary,
2447
+ }
2448
+ )
2449
+ write_json_atomic(iterate_paths.ledger_file, ledger)
2450
+ _write_state(
2451
+ iterate_paths,
2452
+ status="failed",
2453
+ phase="stopped",
2454
+ current_round=round_num,
2455
+ completed_rounds=total_completed_rounds,
2456
+ active_feature_id=None,
2457
+ stop_reason=reason,
2458
+ pause_reason=None,
2459
+ options=options,
2460
+ consecutive_failures=consecutive_failures,
2461
+ consecutive_no_progress=consecutive_no_progress,
2462
+ started_at=started_at,
2463
+ last_verdict=verdict,
2464
+ last_evidence_mode=evidence_mode,
2465
+ summary=summary,
2466
+ )
2467
+ _write_final_summary(
2468
+ iterate_paths,
2469
+ reason=reason,
2470
+ status="failed",
2471
+ ledger=ledger,
2472
+ summary=summary,
2473
+ )
2474
+ _append_event(
2475
+ iterate_paths,
2476
+ "iterate_failed",
2477
+ round_num=round_num,
2478
+ phase="stopped",
2479
+ details={"reason": reason, "summary": summary},
2480
+ )