@tyroneross/build-loop 0.30.3 → 0.35.0

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 (171) hide show
  1. package/.agents/plugins/marketplace.json +2 -2
  2. package/.claude-plugin/marketplace.json +4 -4
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.codex-plugin/plugin.json +1 -1
  5. package/AGENTS.md +11 -2
  6. package/README.md +8 -7
  7. package/agents/advisor.md +111 -0
  8. package/agents/alignment-checker.md +11 -0
  9. package/agents/assessment-orchestrator.md +1 -1
  10. package/agents/build-orchestrator.md +28 -33
  11. package/agents/fact-checker.md +1 -1
  12. package/agents/fix-critique.md +1 -1
  13. package/agents/independent-auditor.md +1 -1
  14. package/agents/overfitting-reviewer.md +1 -1
  15. package/agents/plan-critic.md +8 -6
  16. package/agents/promotion-reviewer.md +1 -1
  17. package/agents/retrospective-synthesizer.md +20 -3
  18. package/agents/scope-auditor.md +1 -1
  19. package/agents/security-reviewer.md +1 -1
  20. package/agents/self-improvement-architect.md +1 -1
  21. package/commands/{handoff.md → compose-handoff.md} +4 -4
  22. package/commands/{optimize.md → optimize-run.md} +1 -1
  23. package/commands/{agent-rally-point.md → rally-point.md} +3 -3
  24. package/commands/{research.md → research-run.md} +1 -1
  25. package/commands/setup-memory.md +32 -0
  26. package/commands/{plan-verify.md → verify-plan.md} +1 -1
  27. package/docs/agent-surface-policy.md +38 -20
  28. package/docs/memory-setup.md +19 -14
  29. package/hooks/_resolve_python.sh +28 -0
  30. package/hooks/closeout.sh +58 -0
  31. package/hooks/git/pre-push +69 -6
  32. package/hooks/hooks.json +34 -13
  33. package/hooks/post-push-closeout.sh +73 -0
  34. package/hooks/session-start-closeout.sh +69 -0
  35. package/hooks/session-start-memory.sh +27 -0
  36. package/hooks/session-start-plugin-heal.sh +33 -0
  37. package/hooks/test_closeout.sh +124 -0
  38. package/package.json +7 -4
  39. package/plugin-artifacts/codex/.codex-plugin/plugin.json +41 -0
  40. package/plugin-artifacts/codex/AGENTS.md +507 -0
  41. package/plugin-artifacts/codex/BUILD-ARTIFACT.md +5 -0
  42. package/plugin-artifacts/codex/LICENSE +202 -0
  43. package/plugin-artifacts/codex/README.md +404 -0
  44. package/plugin-artifacts/codex/docs/agent-surface-policy.md +63 -0
  45. package/plugin-artifacts/codex/references/advisor-dispatch-ladder.md +62 -0
  46. package/plugin-artifacts/codex/references/agent-role-taxonomy.md +135 -0
  47. package/plugin-artifacts/codex/references/autonomous-and-per-commit-modes.md +161 -0
  48. package/plugin-artifacts/codex/references/autonomy-config.md +231 -0
  49. package/plugin-artifacts/codex/references/capability-routing.md +182 -0
  50. package/plugin-artifacts/codex/references/codex-subagents.md +106 -0
  51. package/plugin-artifacts/codex/references/coordination-file-template.md +181 -0
  52. package/plugin-artifacts/codex/references/coordination-rules.md +283 -0
  53. package/plugin-artifacts/codex/references/dogfood-reload-checkpoint.md +112 -0
  54. package/plugin-artifacts/codex/references/halt-and-ask-protocol.md +102 -0
  55. package/plugin-artifacts/codex/references/implementer-envelope-schema.md +302 -0
  56. package/plugin-artifacts/codex/references/intent-capability-pack.md +257 -0
  57. package/plugin-artifacts/codex/references/intent-exploration-prompts.md +96 -0
  58. package/plugin-artifacts/codex/references/leadership.md +72 -0
  59. package/plugin-artifacts/codex/references/memory-systems.md +238 -0
  60. package/plugin-artifacts/codex/references/memory.md +299 -0
  61. package/plugin-artifacts/codex/references/model-tier-mapping.md +257 -0
  62. package/plugin-artifacts/codex/references/modular-systems-pack.md +96 -0
  63. package/plugin-artifacts/codex/references/phase-1-assess.md +231 -0
  64. package/plugin-artifacts/codex/references/phase-2-plan.md +78 -0
  65. package/plugin-artifacts/codex/references/phase-3-execute.md +49 -0
  66. package/plugin-artifacts/codex/references/phase-4-review.md +322 -0
  67. package/plugin-artifacts/codex/references/phase-5-iterate.md +71 -0
  68. package/plugin-artifacts/codex/references/phase-6-learn.md +56 -0
  69. package/plugin-artifacts/codex/references/recent-design-structures.md +274 -0
  70. package/plugin-artifacts/codex/references/research-trigger-policy.md +140 -0
  71. package/plugin-artifacts/codex/references/runtime-smoke-triggers.md +42 -0
  72. package/plugin-artifacts/codex/references/self-review.md +234 -0
  73. package/plugin-artifacts/codex/references/single-writer-commit-protocol.md +90 -0
  74. package/plugin-artifacts/codex/references/task-capture-policy.md +68 -0
  75. package/plugin-artifacts/codex/references/ui-io-contract.md +116 -0
  76. package/plugin-artifacts/codex/references/ui-spotcheck-protocol.md +65 -0
  77. package/plugin-artifacts/codex/skills/build-loop/SKILL.md +372 -0
  78. package/plugin-artifacts/codex/skills/build-loop/detect-plugins.mjs +82 -0
  79. package/plugin-artifacts/codex/skills/build-loop/eval-guide.md +65 -0
  80. package/plugin-artifacts/codex/skills/build-loop/fallbacks.md +549 -0
  81. package/plugin-artifacts/codex/skills/build-loop/phases/fact-check.md +42 -0
  82. package/plugin-artifacts/codex/skills/build-loop/phases/ui-validation.md +267 -0
  83. package/plugin-artifacts/codex/skills/build-loop/references/advisor-dispatch-ladder.md +62 -0
  84. package/plugin-artifacts/codex/skills/build-loop/references/apple-native-planning.md +439 -0
  85. package/plugin-artifacts/codex/skills/build-loop/references/autonomous-and-per-commit-modes.md +161 -0
  86. package/plugin-artifacts/codex/skills/build-loop/references/capability-routing.md +182 -0
  87. package/plugin-artifacts/codex/skills/build-loop/references/codex-subagents.md +106 -0
  88. package/plugin-artifacts/codex/skills/build-loop/references/coordination.md +161 -0
  89. package/plugin-artifacts/codex/skills/build-loop/references/correction-aware-capture.md +177 -0
  90. package/plugin-artifacts/codex/skills/build-loop/references/independent-auditor.md +72 -0
  91. package/plugin-artifacts/codex/skills/build-loop/references/intent-capability-pack.md +257 -0
  92. package/plugin-artifacts/codex/skills/build-loop/references/intent-exploration-prompts.md +96 -0
  93. package/plugin-artifacts/codex/skills/build-loop/references/leadership.md +72 -0
  94. package/plugin-artifacts/codex/skills/build-loop/references/memory.md +299 -0
  95. package/plugin-artifacts/codex/skills/build-loop/references/modular-systems-pack.md +96 -0
  96. package/plugin-artifacts/codex/skills/build-loop/references/output-style.md +129 -0
  97. package/plugin-artifacts/codex/skills/build-loop/references/pay-it-forward-arch.md +98 -0
  98. package/plugin-artifacts/codex/skills/build-loop/references/phase-1-assess.md +231 -0
  99. package/plugin-artifacts/codex/skills/build-loop/references/phase-2-plan.md +78 -0
  100. package/plugin-artifacts/codex/skills/build-loop/references/phase-3-execute.md +49 -0
  101. package/plugin-artifacts/codex/skills/build-loop/references/phase-4-review.md +322 -0
  102. package/plugin-artifacts/codex/skills/build-loop/references/phase-5-iterate.md +71 -0
  103. package/plugin-artifacts/codex/skills/build-loop/references/phase-6-learn.md +56 -0
  104. package/plugin-artifacts/codex/skills/build-loop/references/recent-design-structures.md +274 -0
  105. package/plugin-artifacts/codex/skills/build-loop/references/refactor-history/ASSESSMENT.md +85 -0
  106. package/plugin-artifacts/codex/skills/build-loop/references/refactor-history/STANDALONE_TEST_RUN.md +149 -0
  107. package/plugin-artifacts/codex/skills/build-loop/references/refactor-history/scenarios/01-simple-bugfix.md +32 -0
  108. package/plugin-artifacts/codex/skills/build-loop/references/refactor-history/scenarios/02-ui-build-with-iteration.md +48 -0
  109. package/plugin-artifacts/codex/skills/build-loop/references/refactor-history/scenarios/03-multi-failure-escalation.md +60 -0
  110. package/plugin-artifacts/codex/skills/build-loop/references/refactor-history/scenarios/04-ui-build-ibr-absent.md +51 -0
  111. package/plugin-artifacts/codex/skills/build-loop/references/refactor-history/scenarios/05-refactor-navgator-absent.md +71 -0
  112. package/plugin-artifacts/codex/skills/build-loop/references/refactor-history/scenarios/06-recurring-bug-debugger-absent.md +52 -0
  113. package/plugin-artifacts/codex/skills/build-loop/references/refactor-history/trace-comparison.md +202 -0
  114. package/plugin-artifacts/codex/skills/build-loop/references/self-recursive-dev.md +77 -0
  115. package/plugin-artifacts/codex/skills/build-loop/references/self-review.md +234 -0
  116. package/plugin-artifacts/codex/skills/build-loop/references/ui-io-contract.md +116 -0
  117. package/plugin-artifacts/codex/skills/build-loop/scanners/audit-design-rules.mjs +476 -0
  118. package/plugin-artifacts/codex/skills/build-loop/scanners/require-visual-evidence.mjs +239 -0
  119. package/plugin-artifacts/codex/skills/build-loop/templates/backlog-item.md +35 -0
  120. package/plugin-artifacts/codex/skills/build-loop/templates/codex-worker-prompt.md +100 -0
  121. package/plugin-artifacts/codex/skills/build-loop/templates/ui-subagent-prompt.md +179 -0
  122. package/plugin-artifacts/codex/skills/build-loop/templates/ux-fix-plan.md +40 -0
  123. package/scripts/_paths.py +59 -13
  124. package/scripts/build_codex_plugin_artifact.py +314 -0
  125. package/scripts/check_cache_sync.py +1 -1
  126. package/scripts/install_memory.py +11 -3
  127. package/scripts/prune_plugin_cache.py +225 -11
  128. package/scripts/sync_navgator_lessons.py +25 -0
  129. package/scripts/sync_plugin_cache.py +66 -36
  130. package/skills/agent-rally-point/SKILL.md +1 -1
  131. package/skills/agent-rally-watcher/SKILL.md +1 -1
  132. package/skills/build-loop/SKILL.md +11 -155
  133. package/skills/build-loop/references/advisor-dispatch-ladder.md +62 -0
  134. package/skills/build-loop/references/autonomous-and-per-commit-modes.md +161 -0
  135. package/skills/build-loop/references/capability-routing.md +4 -3
  136. package/skills/build-loop/references/codex-subagents.md +8 -0
  137. package/skills/build-loop/references/coordination.md +1 -1
  138. package/skills/build-loop/references/intent-capability-pack.md +88 -1
  139. package/skills/build-loop/references/memory.md +17 -2
  140. package/skills/build-loop/references/phase-1-assess.md +13 -0
  141. package/skills/build-loop/references/phase-2-plan.md +2 -1
  142. package/skills/build-loop/references/phase-3-execute.md +4 -2
  143. package/skills/build-loop/references/phase-4-review.md +12 -0
  144. package/skills/build-loop/references/phase-6-learn.md +1 -1
  145. package/skills/build-loop/references/self-review.md +4 -2
  146. package/skills/build-loop/templates/codex-worker-prompt.md +45 -34
  147. package/skills/handoff/SKILL.md +3 -3
  148. package/skills/loop-builder/SKILL.md +98 -0
  149. package/skills/loop-builder/presets/active-project-evidence.yaml +97 -0
  150. package/skills/loop-builder/presets/generic-artifact-loop.yaml +95 -0
  151. package/skills/loop-builder/presets/presentation-audit.yaml +96 -0
  152. package/skills/loop-builder/presets/research-synthesis.yaml +96 -0
  153. package/skills/loop-builder/presets/source-ingestion-raw-data-audit.yaml +96 -0
  154. package/skills/loop-builder/references/spec-format.md +80 -0
  155. package/skills/loop-builder/scripts/loop_builder.py +346 -0
  156. package/skills/model-tiering/SKILL.md +65 -40
  157. package/skills/optimize/SKILL.md +2 -2
  158. package/skills/plan-verify/SKILL.md +1 -1
  159. package/skills/plugin-builder/references/distribution.md +8 -0
  160. package/skills/research/SKILL.md +33 -6
  161. package/skills/runtime-parity-verification/SKILL.md +51 -0
  162. package/skills/spec-writing/SKILL.md +19 -0
  163. package/templates/memory/README.md +65 -0
  164. package/templates/memory/charter.md.template +46 -0
  165. package/templates/memory/manifest.json +24 -4
  166. package/codex-skills/debug-loop/SKILL.md +0 -18
  167. package/codex-skills/handoff/SKILL.md +0 -22
  168. package/codex-skills/knowledge/SKILL.md +0 -21
  169. package/codex-skills/optimize/SKILL.md +0 -18
  170. package/codex-skills/research/SKILL.md +0 -18
  171. /package/commands/{knowledge-review.md → review-knowledge.md} +0 -0
@@ -0,0 +1,231 @@
1
+ <!-- SPDX-FileCopyrightText: 2025-2026 Tyrone Ross, Jr <46267523+tyroneross@users.noreply.github.com> | SPDX-License-Identifier: Apache-2.0 -->
2
+
3
+ # Phase 1: Assess (full protocol)
4
+
5
+ > Loaded from `skills/build-loop/SKILL.md` summary. Contains the full Assess phase: state understanding, goal definition, and scoring criteria.
6
+
7
+ ## Phase 1: Assess — State, Goal, and Criteria
8
+
9
+ **Goal**: Know what exists AND what success looks like before writing any code. Combines situational awareness with goal definition so the plan phase has everything it needs.
10
+
11
+ ### Understand current state
12
+
13
+ 0. **Peer-detection (cheap fail-fast — runs BEFORE plugin detection so a peer collision is surfaced before any other Phase 1 cost is paid).** Bash, ≤4 commands; output goes into the assess report. **The check is automated end-to-end — never pauses to ask the user.** Any non-empty line is written to `state.json.assess.peerDetect[]` and surfaces in `## Notes from judges`. Phase 2 Plan auto-routes per default policy: if scope overlap is detected, the orchestrator fast-forwards (`git merge --ff-only`) when ancestry allows, otherwise splits the affected chunks out and continues, logging `WARN: peer_collision_<kind>` either way. Operator reviews the report post-hoc. Complements Rally Point session-presence (§"Multi-session concurrency" in `agents/build-orchestrator.md`) — Rally Point covers active *sessions*; this covers dormant *artifacts* (coordination notes, stale worktrees, unmerged branches) those sessions leave behind.
14
+
15
+ ```bash
16
+ ls .build-loop/coordination/*.md 2>/dev/null | grep -v /archived/ # live coordination notes
17
+ git worktree list --porcelain # all worktrees
18
+ git worktree list --porcelain | awk '/^worktree /{print $2}' \
19
+ | while read -r wt; do [ -d "$wt" ] && echo "$wt dirty=$(git -C "$wt" status --porcelain 2>/dev/null | wc -l | tr -d ' ')"; done # per-worktree dirty (Codex addition: dirty is stronger signal than branch merge status)
20
+ git branch -a --no-merged main | grep -vE 'archive|HEAD' # unmerged branches
21
+ ```
22
+
23
+ Helper errors (`grep -v`/`awk` non-zero) are NOT a failure — empty output means clean. Any non-empty line surfaces in the assess report for Phase 2 to reason about.
24
+
25
+ 0a. **Credential preflight** (fail-soft, names only — no values ever surfaced): run
26
+
27
+ ```bash
28
+ python3 "${CLAUDE_PLUGIN_ROOT}/scripts/credential_preflight.py" \
29
+ --workdir "$PWD" --json
30
+ ```
31
+
32
+ Write the result to `.build-loop/state.json.assess.credentialPreflight`. If `missing[]` is non-empty, surface each name as `[CREDENTIAL REQUIRED] <name>` in the Assess summary and repeat verbatim in the end-of-run readback. A missing credential is a "genuine inability to proceed" under the autonomy policy: log it, continue all work that does not require the key, and surface it in the readback — do NOT stop-and-ask. Script failure (non-zero exit / bad JSON) → log one warning line; never blocks Assess.
33
+
34
+ 0b. **Stale-context triage** (fail-soft, proactive drift notice): run
35
+
36
+ ```bash
37
+ python3 "${CLAUDE_PLUGIN_ROOT}/scripts/stale_context_check.py" \
38
+ --workdir "$PWD" --json
39
+ ```
40
+
41
+ Write the result to `.build-loop/state.json.assess.staleContext`. For each path in `docs[]` where the doc is flagged stale, surface it as `[STALE CONTEXT] <path>` in the Assess summary so the agent notes drift before relying on a handoff/orchestration/continuation doc. The user should never have to ask "is this still relevant?" Script failure → log one warning line; never blocks Assess.
42
+
43
+ 0c. **Memory-staleness triage** (fail-soft, proactive drift notice): run
44
+
45
+ ```bash
46
+ python3 "${CLAUDE_PLUGIN_ROOT}/scripts/memory_staleness_check.py" \
47
+ --workdir "$PWD" --json
48
+ ```
49
+
50
+ Write the result to `.build-loop/state.json.assess.memoryStaleness`. When `stale: true`, surface `[MEMORY STALE] <slug> N commits behind HEAD — append a milestone/decision` in the Assess summary. Log the finding and continue — do NOT stop. The run should append a milestone or decision entry during Phase 6 Learn (or inline if the goal is memory-focused). Script failure → log one warning line; never blocks Assess.
51
+
52
+ 1. **Detect available plugins and personal skills**: Run `node ${CLAUDE_PLUGIN_ROOT}/skills/build-loop/detect-plugins.mjs`. Write the JSON result into `.build-loop/state.json` under `availablePlugins`. All subsequent routing consults this object.
53
+ 2. **Detect project type**: web app, API, library, mobile, CLI, monorepo, **Claude Code plugin**, one-shot new app, existing-app iteration. A plugin is detected by the presence of `.claude-plugin/plugin.json`, `hooks/hooks.json`, `skills/*/SKILL.md`, `commands/*.md`, `agents/*.md`, or `.mcp.json`. If detected, mark the build as "plugin work" in state.json and plan to load the `plugin-dev:*` skills before any manifest/hook/skill/agent/MCP/command/**scripts/** edits. **Any change to a file referenced via `${CLAUDE_PLUGIN_ROOT}/...` counts as plugin work** — this includes `scripts/*.py`, `references/*`, or anything else the plugin manifests, agents, or skills invoke at runtime. These files live in `~/.claude/plugins/cache/<marketplace>/<plugin>/<version>/` at run time; editing only the source repo without syncing the cache leaves the runtime invocation broken (Lessons §5 + §5a in `plugin-hygiene-lessons.md`).
54
+ 3. **Set sub-routers**: `uiTarget` (web / mobile / **macos** / null), `platform` (web / apple / react-native / null), `migrationSource` (replit / lovable / bolt / v0 / null). See the Capability Routing §Sub-routers rules. **macOS desktop is a first-class `uiTarget`** — distinct from `mobile` — because macOS has no simulator and routes visual-verify to `native-ax-driver` (or IBR `scan_macos` when present), never to `xcrun simctl`. Folding macOS into `mobile` was the routing bug from session-findings 2026-06-04.
55
+ 4. **Detect available tools**: test runners (`package.json` scripts, `pytest.ini`, etc.), linters, deploy targets.
56
+ - **Deployment policy**: read `.build-loop/config.json.deploymentPolicy` if present. Defaults are `preview: auto`, `testflight: auto`, `production: confirm`, `unknown: confirm`. Use `python3 ${CLAUDE_PLUGIN_ROOT}/scripts/deployment_policy.py --workdir "$PWD" --command "<candidate push/deploy command>"` before any push/deploy. Treat helper errors as `confirm`.
57
+ 5. **Map architecture** using best available approach:
58
+ - If `.navgator/architecture/index.json` exists → invoke `Skill("build-loop:architecture-scan")` to refresh data, then `Skill("build-loop:architecture-impact")` on up to 5 highest-risk components for blast-radius. Output goes to `.build-loop/state.json.architecture.{scan,impact}`. Phase 2 Plan consults this for scoping. Flags high-fan-in hotspots, 2-hop dependents, layer-crossing risks, and prompts-in-scope when `triggers.promptAuthoring` is true.
59
+ - Else if `gator:*` is available → use those commands.
60
+ - Else → Explore agents → file reading.
61
+ 5a. **Architecture portable handoff** (read on resume; write on fresh scan): after the architecture baseline above, the scan result must also be written to `.build-loop/architecture/handoff.md` as a self-contained snapshot — component map, key connections, runtime topology, LLM use-cases, and data flows — that a FRESH session can consume WITHOUT re-scanning. On a resumed or fresh session, Phase 1 reads `.build-loop/architecture/handoff.md` if it exists and its `updated_at` timestamp is within the staleness threshold (default: same as stale-context check), and skips the full re-scan. The format and field schema are specified in `agents/build-orchestrator.md` (architecture-scout section); this step only wires the read/write reference. Write failure → log one warning; never blocks.
62
+
63
+ 5b. **Reads-from dependency enumeration**: For each component the build will change or add, enumerate every data path, contract, or invariant it reads (config files, state keys, schema fields, API contracts). For each, verify something writes it — grep the repo, check test fixtures, or confirm the schema. Record results in `.build-loop/state.json.assess.readsDependencies[]` as `{path, writer_found: true|false}`. Any path with `writer_found: false` is a BLOCKING unknown that must appear as `unverified` in the plan's `## Depends-on (reads-from)` section and be resolved before Phase 3.
64
+
65
+ 6. **Observability baseline** (informational, no changes): run a stack-appropriate grep to classify the project's logging level (well-instrumented / print-only / silent) and write to `.build-loop/state.json.observability.level`. The orchestrator handles this inline — `Skill("build-loop:logging-tracer")` is reactive only and is loaded later if Review-B / Iterate hits a silent failure.
66
+ 6b. **Attribution-layers detection** (informational, advisory only — never blocks, never pauses): run `python3 ${CLAUDE_PLUGIN_ROOT}/scripts/detect_attribution_layers.py --workdir "$PWD"` when the repo has a GitHub origin remote. Write the result to `.build-loop/state.json.attribution`. When `should_advise: true`, surface the returned `advisory` line in the Phase 1 Assess report under `## Notes from judges`. Phase 2 Plan queues an automatic chunk to run `scripts/attribution_stamp.py` when the build scope is ≥ S; smaller scopes only surface the advisory and let the user run it manually. Per `feedback_advisory_checks_are_automated`: this routes to the run report, never to AskUserQuestion or `## Held`. Helper failure → treat as `should_advise: false` and log a one-line warning. The full procedure for stamping is in `skills/attribution-standard/SKILL.md`.
67
+
68
+ 6a. **Runtime-server detection** (informational, no changes): run `python3 ${CLAUDE_PLUGIN_ROOT}/scripts/detect_runtime_server.py --workdir "$PWD" --json` and write the result to `.build-loop/state.json.triggers.runtimeServer` (boolean) plus `.build-loop/state.json.runtimeServerInfo` (full envelope: `server_module`, `sse_route`, `default_port`, `embedded_ui_module`, `event_handler_locations[]`, `evidence[]`). Phase 4 sub-step B Validate consults these for the live HTTP/SSE smoke gate. Helper failure → treat as `runtimeServer: false` and log a one-line warning; never blocks. Silent default for CLIs, libraries, plugins, and static-render web apps. Implements decision `_unscoped/0003` (live smoke required when build-loop touches a runtime server) — closes the pytest-with-mocks blind spot that let example-app ship 27 commits with two real bugs.
69
+ 7. **Debugger context priming** (always; native to build-loop): invoke `Skill("build-loop:debugging-memory")` with `{ intent: "list-recent", project: "<current>" }` to summarize recent incidents in this project. One-line output; no action. If cross-project Coding Debugger is installed, the skill may use it; otherwise it falls through to `fallbacks.md#bug-memory`.
70
+ 8. **Capture UI state** (if web/mobile): host browser/screenshot tooling or simulator/native-AX evidence when available → showcase capture → manual screenshot. Do not route to IBR unless the user explicitly requested it.
71
+ 8a. **UI input/output inventory** (if `uiTarget != null`): load `skills/build-loop/references/ui-io-contract.md` and identify every affected user input and system output before component choices are made. Classify each by structural type, content format, persistence intent, operation/domain verb, component mapping, state matrix, modality fallback, validation/security layer, and traceability. Mirror a compact summary to `.build-loop/state.json.uiIOContract` when practical; the full contract is finalized in Phase 2.
72
+
73
+ 8b. **Load short-term working context (Pillar 0 — structurally loaded first, inside memory bootstrap)**: `context_bootstrap.build_packet()` calls `load_current(workdir)` at its very entry, before any heavier memory work, and attaches the result as `packet['working_context']` (a serialized `WorkingContextEnvelope`). The working context is therefore available as part of the Phase-1 packet without a separate CLI step.
74
+
75
+ Consume it directly from the packet:
76
+
77
+ ```python
78
+ wc = packet["working_context"] # {exists, path, warm_read_latency_ms, parsed, reasons}
79
+ ```
80
+
81
+ Use `wc["parsed"]["links_down"]` as the entry pointers DOWN into long-term memory (P1 hybrid recall + P4 prior-art). Missing / corrupt `current.md` → `wc["exists"] == False` + `wc["reasons"]`; never blocks Phase 1 or bootstrap. Mirror `wc["warm_read_latency_ms"]` into `.build-loop/state.json.assess.workingContextLatencyMs` for the Phase 4G report.
82
+
83
+ The standalone CLI (`python3 ${CLAUDE_PLUGIN_ROOT}/scripts/load_current.py --workdir "$PWD" --json`) remains available for manual inspection but is no longer a required Phase-1 step — the enforced path is via `build_packet()`.
84
+
85
+ 9. **Load memory**: Run the automatic context bootstrap before planning:
86
+
87
+ ```bash
88
+ python3 ${CLAUDE_PLUGIN_ROOT}/scripts/context_bootstrap.py \
89
+ --workdir "$PWD" \
90
+ --query "<goal-keywords>" \
91
+ --output "$PWD/.build-loop/context-bootstrap.json" \
92
+ --json
93
+ ```
94
+
95
+ The packet must include canonical `build-loop-memory` root/project `MEMORY.md` and `constitution.md` files, indexed recall, repo-local `.build-loop/feedback.md`, `.build-loop/state.json`, current plan/goal/intent, Codex memory registry `~/.codex/memories/MEMORY.md` plus linked rollout summaries, and best-effort Rally/coordination state when coordination context exists. If the root constitution is absent, `context_bootstrap.py` seeds it once from the shipped template before reading; it never overwrites existing root or project constitution files. Missing surfaces are recorded in `sources.*.reasons[]`; they do not block Phase 1 by themselves. See `references/memory-systems.md` §"Read protocol — Phase 1 Assess".
96
+
97
+ **Cross-project prior art (P4 — payoff)**: the bootstrap also emits `packet.prior_art`, a compact cross-project digest of prior implementations + linked decisions for the task's classified capability. Powered by `scripts/capability_classifier.py` (deterministic, host-LLM-refinable) and `scripts/prior_art.py` (reuses P1 hybrid recall + scans `projects/<slug>/decisions/` and `projects/<slug>/lessons/` across other projects). The digest is compact (hard char cap — `prior_art.DEFAULT_MAX_TOTAL_CHARS`, 4000 chars) and absence-tolerant (empty memory → empty payload, never blocks). `build_packet()` **enforces** the write by calling `context_bootstrap.write_prior_art_to_intent(workdir, digest_text)` immediately after building the packet: when the digest is non-empty AND `<workdir>/.build-loop/` exists, it appends (or idempotently replaces) a `<!-- prior-art:start -->`…`<!-- prior-art:end -->` block in `.build-loop/intent.md` (creating the file when absent). Re-running replaces the block — never duplicates. The agent brief still carries the compact pointer line for quick orientation; the full digest body is in the file. Disable via `BUILD_LOOP_PRIOR_ART=0`.
98
+
99
+ Then write the first live handoff snapshot:
100
+
101
+ ```bash
102
+ python3 ${CLAUDE_PLUGIN_ROOT}/scripts/context_snapshot.py \
103
+ --workdir "$PWD" \
104
+ --trigger phase_transition \
105
+ --phase assess \
106
+ --message "Phase 1 context bootstrap complete" \
107
+ --if-changed \
108
+ --json
109
+ ```
110
+
111
+ This refreshes `.build-loop/context/current.md` for later agents. Snapshot failure is a context-quality warning, not a Phase 1 blocker.
112
+
113
+ 9a. **Run identity + multi-session presence (Rally Point)** (always; runs at the Phase 1 preamble before any Rally Point write):
114
+ 1. Generate or resume durable run identity + isolated worktree: `execution = scripts/rally_point/build_loop_id.generate_or_resume(workdir="$PWD", tool="<tool-id>", session_id="<session-id>", provision_worktree=True)`. This writes `state.execution.build_loop_id` and `state.execution.run_label` when missing, preserves them on resume, and updates only `current_session_id`. **`provision_worktree=True` is mandatory: it provisions `.build-loop/worktrees/run-<id>` on `bl/run-<id>` (fail-closed; aborts the run rather than touch the canonical checkout) and records `state.execution.run_worktree_path` for all downstream git/file ops. Structural fix for shared-checkout contamination — see `docs/SPEC-run-worktree-isolation.md`.**
115
+ 2. Resolve the channel: `slug = scripts/rally_point/channel_paths.app_slug(cwd="$PWD")` (D1: worktree/clone-independent — main checkout and every worktree share one channel). Do NOT reimplement slug derivation.
116
+ 3. Write presence: `scripts/rally_point/presence.write_presence(channel, session_id=..., tool="claude_code", model=..., run_id="$RUN_ID", app_slug=slug, phase="assess", files_in_flight=[])`. Codex / Gemini / other hosts substitute their `tool` value. Fire-and-forget. The writer attaches top-level `build_loop_id` and `build_loop_run_label` from `state.execution`.
117
+ 4. Read active peers: `peers = scripts/rally_point/presence.read_active_presence(channel, exclude_session=...)` (also reaps stale presence past the heartbeat window — no daemon).
118
+ 5. Route per `agents/build-orchestrator.md` §Multi-session concurrency — **awareness only, never a hard block (D4)**:
119
+ - No peers / no `files_in_flight` overlap → log one line per peer (tool, run_id, phase); continue.
120
+ - Overlap with a peer's `files_in_flight` → surface a `soft-claim` WARNING (peer, files, phase); continue with awareness. Interactive MAY additionally `AskUserQuestion` to coordinate; headless logs + proceeds. No SAFE-STOP sentinel, no non-zero exit.
121
+ 6. Initialize the memory-index cursor: capture the current top-of-log timestamp from `python3 ${CLAUDE_PLUGIN_ROOT}/scripts/memory_index.py tail --limit 1 --json` (used by `--since` in subsequent phases to surface new peer learnings).
122
+
123
+ **Supersedes** the legacy `ps aux | grep -c "[c]laude$"` advisory below — Rally Point presence is the canonical signal. Keep the legacy line as a fallback only when Rally Point is unavailable (older plugin cache without `scripts/rally_point/`).
124
+
125
+ 10. **Load PRD if present** (strategic frame check): load `build-loop:prd-bridge`, run its Phase 1 Assess step. If `docs/prd-*.md` exists, the bridge reads frontmatter (`core_principles`, `load_when`, `evolves_when`), Navigation Map, and Section Index, mirrors them to `.build-loop/state.json.prd`, and surfaces staleness signals. If no PRD exists, the bridge writes a one-line recommendation in `state.json.prd.recommendation` pointing to `prd-builder` skill / `/build-loop:start-prd` command — surfaces in Sub-step G Report's `## Held` section, doesn't block. Step 11 below uses PRD as primary source of truth when present; falls back to fresh capture when absent.
126
+ 11. **Capture north star + update intent**: When `state.json.prd.core_principles` is non-empty (a PRD was loaded by step 10), use it as the strategic frame; `intent.md` cites the PRD path + revision rather than re-deriving. Otherwise use `references/intent-capability-pack.md` to identify app/repo purpose, primary users, core jobs, update intent, user value, and non-goals fresh. Write `.build-loop/intent.md` and mirror compact fields to `.build-loop/state.json.intent`.
127
+
128
+ **Intent restatement protocol (always-on, LLM-judged)**: as part of writing `intent.md`, follow `references/intent-capability-pack.md` § Intent restatement protocol — write a one-line concrete restatement always; when the orchestrator LLM judges the goal genuinely ambiguous (per Step A heuristics), extend with 1-3 approach options + tradeoffs + tagged assumptions. The judgment is the orchestrator LLM's, not a regex or detector script. For a concrete unambiguous goal this is one line and the flow moves on immediately — zero fast-path friction. Never `AskUserQuestion`, never `## Held`, never blocks Phase 1. Fail-safe: any error here is logged as one line; the build continues. Phase 2 Plan's "fork on uncertainty" rule consumes `state.json.intent.approach_options` when the LLM's confidence stays medium/low AND Phase 2 surfaces 2+ viable approaches.
129
+
130
+ 12. **Assess modular structure**: Use `references/modular-systems-pack.md`. Identify current module boundaries, stable interfaces, coupling risks, likely MECE work partitions, and any justified modularity exception. Mirror compact fields to `.build-loop/state.json.structure`.
131
+ 12a. **Capture approach lenses**: For any non-trivial architecture, workflow, dependency, UI/product, or long-lived interface recommendation, assess two separate answers before planning:
132
+ - **Clean-sheet best approach**: what would be best for the use case if prior repo decisions, accumulated tech debt, and current implementation constraints did not exist.
133
+ - **Current-constraints best approach**: what is best given the repo's existing code, dependencies, tools, debt, team/runtime constraints, migration cost, and delivery horizon.
134
+ - **Bridge/backcast**: the smallest credible path from current state toward the clean-sheet target, including debt retired, dependencies added/removed, and decision points.
135
+
136
+ Prior decisions are evidence, not axioms. Do not discard current constraints; isolate them so Phase 2 can decide whether they justify a compromise. Mirror the compact summary to `.build-loop/state.json.approachLenses` with `clean_sheet`, `current_constraints`, `constraint_delta`, and `bridge_backcast` fields.
137
+ 13. **Check prior state**: Read `.build-loop/issues/` and `.build-loop/feedback.md` if they exist. Surface relevant items. If any issue affects the current user's experience, add it to the plan unless too large or risky; otherwise log and defer with user impact.
138
+ 14. **Research trigger + depth gate**: run the deterministic classifier and cache the result:
139
+
140
+ ```bash
141
+ python3 "${CLAUDE_PLUGIN_ROOT}/scripts/research_trigger.py" \
142
+ --workdir "$PWD" \
143
+ --task "<goal text>" \
144
+ --effort "<XS|S|M|L|XL>" \
145
+ --cache-into-state \
146
+ --json
147
+ ```
148
+
149
+ This writes `.build-loop/state.json.researchGate`. Use
150
+ `references/research-trigger-policy.md` for trigger policy and t-shirt depth
151
+ lower bounds. If `research_required: true`, run the Research plugin at the
152
+ returned depth (`light`/`standard`/`deep`) or record why it was unavailable.
153
+ If `blocks_final_claims: true`, final current/external/API claims need
154
+ citations or an explicit unavailable/unverified note.
155
+
156
+ **Reference capture (default-on, any phase/mode):** whenever this run fetches
157
+ external info (WebSearch/WebFetch/Context7/api-registry/official docs) AND uses
158
+ it in a decision, persist the EXTRACTED findings (not raw HTML) via
159
+ `python3 "${CLAUDE_PLUGIN_ROOT}/scripts/reference_capture.py" capture --workdir
160
+ "$PWD" --run-id "<run_id>" --topic "<topic>" --findings "<distilled>" --source
161
+ "<url>|<T1..T4>" --decision "<what it informed>" --json`. Routes through the
162
+ canonical memory writer into the project `research` lane with `retrieved_at` +
163
+ a per-content-class `refresh_after` horizon; the store is uncommitted by
164
+ default. `context_bootstrap.py` flags references past their horizon as
165
+ `stale-needs-refresh` in the brief (`packet.reference_freshness`, advisory).
166
+ Do not ask — capture is a default. Policy: `references/research-trigger-policy.md`
167
+ §"Reference Capture".
168
+ 14a. **Active task surface**: when the user asks what remains, when Phase 1
169
+ surfaces open work, or before queue-continuation decisions, run:
170
+
171
+ ```bash
172
+ python3 "${CLAUDE_PLUGIN_ROOT}/scripts/task_surface.py" \
173
+ --workdir "$PWD" \
174
+ --json
175
+ ```
176
+
177
+ This is the canonical active view over existing state, queue, and
178
+ project-scoped memory backlog surfaces. Do not create a second task ledger by
179
+ default. See `references/task-capture-policy.md`.
180
+ 15. **Recovery check**: This used to be a phase-level marker. As of v0.11 the canonical recovery surface is the `--resume` argument and the heartbeat-staleness path documented under §Resume Protocol. The pre-Assess resolver already ran by the time Phase 1 starts; if it returned `decision: "prompt_user"` and the user chose "fresh", proceed normally; if they chose `--resume`, you're not in this code path (the agent is in §0 Resume mode instead).
181
+ 16. **Workspace concurrency check** (advisory, no blocking — surface as one-line notes):
182
+ - **Concurrent sessions**: `ps aux | grep -c "[c]laude$"`. If `>1`, warn that other sessions on this repo can silently revert each other's work; the checkpoint reactions (severity + reason) tell you whether overlap is `merged_residue` / `squash_landed` / `active_conflict`. See `agents/build-orchestrator.md` §Multi-session concurrency.
183
+ - **Branch divergence**: `git rev-list --count HEAD..origin/main` and `origin/main..HEAD`. If local main is ahead of origin AND a feature branch will be cut, recommend branching from `origin/main` directly (`git checkout -b <name> origin/main`) so unpushed local commits don't ride into the eventual squash and bundle under a misleading title.
184
+ - **Recovery if symptoms appear during build** (file writes vanish, system reminders flag "intentional" reverts, `git status` clean): pause edits, run `ps aux | grep claude` + `git log --oneline -- <affected paths>` to identify the colliding session/squash, then re-apply dropped work on a fresh branch from `origin/main`.
185
+
186
+ ### UI scope and mockup pre-flight (when uiTarget != null)
187
+
188
+ **UI pre-flight**: If project has `mockups/` or `.mockup-gallery/` and goal references selected mockups, run the design-rule scanner against the mockup HTML/CSS first to surface conflicts before coding:
189
+ ```
190
+ node "${CLAUDE_PLUGIN_ROOT}/skills/build-loop/scanners/audit-design-rules.mjs" --root=<mockups_dir> --platform=html --json
191
+ ```
192
+ Log conflicts to `.build-loop/issues/mockup-rule-conflicts.md`. Don't block — agents need to know upfront which rules trump the mockup. Mockups are intent, rules are law. See `phases/ui-validation.md` for full guidance.
193
+
194
+ ### Define goal and scoring criteria
195
+
196
+ 14. **State the goal** in concrete, measurable terms.
197
+ 15. **Suggest 3-5 scoring criteria** from: functionality, code quality, UX, performance, security, accessibility, test coverage — select what's relevant to the project and goal. Include intent fidelity/user value when the change affects user experience or product behavior. Include modularity/MECE/scalability when the change spans modules, agents, domains, repo areas, data boundaries, or long-lived interfaces. Show for confirmation.
198
+
199
+ **Warning/lint criteria MUST be relative, not absolute** (R4 from the 2026-05-19 iOS retro). An absolute "zero warnings tagged X" criterion false-fires on pre-existing warnings, forcing subagents to either lie, exit-fail honest work, or write apologetic prose. Author as **"no NEW warnings matching `<filter>` vs `git merge-base origin/main HEAD` using the same build command, destination, SDK, and filter"** (Codex correction: baseline only valid when capture and current invocations match). Inline diff helper:
200
+ `comm -23 <(<current> 2>&1 | grep -E 'warning:' | grep -E '<filter>' | sort -u) <(<baseline> ... | sort -u)`. Persist baselines as plain text under `.build-loop/baselines/warnings-<base-sha>-<filter-slug>.txt` only when one is needed; ad-hoc capture is fine.
201
+
202
+ **When `uiTarget != null`, the following criteria are REQUIRED and added automatically (not optional)**:
203
+ - **UI-1 Design-rule compliance**: scanner exits 0 on changed files (must-fix=0). Grader: code (`audit-design-rules.mjs`).
204
+ - **UI-2 Reduce Motion compliance**: every animation gated on platform's reduce-motion API. Grader: code (scanner rule `animation-without-reducemotion`).
205
+ - **UI-3 Theme token usage**: no raw color literals or hardcoded radii outside theme files. Grader: code (scanner rules `uicolor-rgb-outside-theme`, `literal-corner-radius`, `hex-color-outside-theme`).
206
+ - **UI-4 Accessibility labels**: icon-only graphics have explicit labels. Grader: code (scanner rule `sf-symbol-without-label` or web equivalent).
207
+ - **UI-5 Input/output contract coverage**: every changed UI surface has a plan row naming user inputs, system outputs, data taxonomy, operation/domain verb, component mapping, states, modality fallback, validation/security, and traceability. Grader: code/document check (`check_checklist.py` Item 17 plus Review read).
208
+
209
+ These exist because mockup-parity ≠ design-rule compliance, and component polish does not prove the UI handles the right data. Code that matches the mockup but omits an input, output, state, validation layer, or fallback is not production-ready. See `phases/ui-validation.md` and `references/ui-io-contract.md`.
210
+
211
+ 16. **Design eval graders per criterion** using the grading hierarchy:
212
+ - **Prefer code-based graders** (fast, deterministic, cheap): test suite pass/fail, lint/type check, build succeeds, schema validation, accessibility audit
213
+ - **Use LLM-as-judge graders** when code can't check the criterion:
214
+ - Binary pass/fail only — no Likert scales
215
+ - One evaluator per dimension — no multi-dimension God Evaluator
216
+ - Judge reasons in thinking tags, outputs only pass/fail
217
+ - Use the running host model/session as judge
218
+ - Each criterion gets: `description | grading method | pass condition | evidence required`
219
+ - Load `eval-guide.md` in this skill directory for judge prompt template and scorecard format if needed.
220
+ 17. **Write goal file**: Save to `.build-loop/goal.md` in the project directory.
221
+ 18. **Synthesis-density routing** (REVISED 2026-05-07 round-4 — Phase 1 routing with explicit speed/quality lanes): if a plan file already exists, count its `synthesis_dimensions:` entries via `count_synthesis_dimensions()` in `scripts/plan_verify.py` (shared parser; do NOT write a second). Resolve tier in this priority order:
222
+ 1. **Explicit override** — `.build-loop/config.json.modelOverrides.thinking` or `state.json.config.modelOverrides.thinking` set OR plan/chunk frontmatter declares `tier: thinking` → route to thinking-tier.
223
+ 2. **Auto-escalate on density** — `count > 5` (6+ entries) → `tier: thinking` (synthesis-dense at commit level; fan-out loses cross-dimension coherence).
224
+ 3. **Default — Sonnet fan-out for speed** — `count` 1–5 OR `count == 0` → fan-out. Sonnet's ~33% wall-clock and ~28% token savings are real; C3-C5 backstops catch the residual recall gap.
225
+ 4. **Per-chunk override** — individual chunks may declare `tier: thinking` even when plan-level was fan-out.
226
+
227
+ Write to `state.json.synthesisDensity` as `{count, escalated, reason}`. Routing target is `tier: thinking`, **never a hardcoded model name** (`scripts/model_overrides.py`: repo config → state snapshot → orchestrator frontmatter fallback → fail-loud). When `escalated == true`, do NOT fan out; execute inline at thinking-tier.
228
+
229
+ **Why this shape:** n=6 A/B experiment (2026-05-07, `~/dev/research/topics/synthesis-decision-delegation/experiment-2026-05-07/`) showed β catches ~40% of α's novels — real quality gap — but also showed β saves ~33% wall-clock and ~28% tokens, and the C3-C5 backstops catch some leaks. Defaulting Opus universally would erase β's velocity; the `> 5` threshold matches the empirical inflection point where β's recall collapses (C5 at 5 dims surfaced 0 novels vs α's 5). Below that, fan-out is the right speed choice; above it, depth dominates. Plan/chunk-level overrides let the operator pick quality > speed when needed without changing the default. See `agents/build-orchestrator.md` Phase 1 for full procedure.
230
+
231
+ **Output**: Structured state summary + `.build-loop/intent.md` + `.build-loop/goal.md` with criteria. Brief.
@@ -0,0 +1,78 @@
1
+ <!-- SPDX-FileCopyrightText: 2025-2026 Tyrone Ross, Jr <46267523+tyroneross@users.noreply.github.com> | SPDX-License-Identifier: Apache-2.0 -->
2
+
3
+ # Phase 2: Plan (full protocol)
4
+
5
+ > Loaded from `skills/build-loop/SKILL.md` summary. Contains the full Plan phase: task breakdown, dependency graph, mockup gate, and plan acceptance.
6
+
7
+ ## Phase 2: Plan — Steps & Optimization
8
+
9
+ **Goal**: Break work into executable steps, then optimize the plan before execution.
10
+
11
+ 0. **If no plan exists yet**: check whether `.build-loop/plan.md` is absent or empty. If so, invoke `Skill("build-loop:spec-writing")` to draft a build-loop-compatible plan markdown before proceeding. The spec-writing skill walks the completeness checklist (auth guard, external API contracts, rate-limit criterion, discoverability surfaces, server/client boundary, concurrency mechanism, observability events, input validation, UI input/output contract when UI is in scope, and routing-risk fields) and runs `check_checklist.py` + `plan-critic` on the output. It writes the plan to `docs/plans/<feature-slug>.md` and commits it before any implementation branches are cut. Only continue to step 1 once the spec-writing skill returns a plan path. Skip this step when a valid plan already exists and passed `plan-verify` on the previous run.
12
+
13
+ 1. **Invoke `writing-plans` skill** for detailed task breakdown
14
+ 2. **Identify parallel-safe tasks** vs sequential dependencies — build a dependency graph
15
+ - If the graph has 2+ independent / parallel-safe chunks, write `parallel_batch:` naming the chunks that will dispatch together.
16
+ - If the graph appears parallelizable but execution must serialize, write `parallel_skipped_reason:` with the specific dependency, tool limit, or coordination constraint.
17
+ 3. **Map each task to intent**: state which user workflow, user-value rule, and north-star outcome it supports. Remove tasks that add complexity without clear user value.
18
+ 3a. **Approach Lenses section**: For non-trivial architecture, workflow, dependency, UI/product, or long-lived interface decisions, add `## Approach Lenses` before the task list. Use the Phase 1 `.build-loop/state.json.approachLenses` summary and include:
19
+ - **Clean-sheet best approach**: the use-case-first answer if no prior implementation debt or historical decisions constrained the design.
20
+ - **Current-constraints approach**: the best practical answer given the repo's existing code, dependencies, tools, debt, migration risk, and delivery horizon.
21
+ - **Bridge/backcast**: the smallest credible migration path from current state toward the clean-sheet target.
22
+ - **Recommendation**: what to execute now and why. If choosing the constrained path, name the constraint that justifies not taking the clean-sheet path now.
23
+
24
+ Skip only for narrow single-file fixes, pure config changes, or decisions where the two answers are identical; in that case write `Approach Lenses: n/a - <reason>`.
25
+ 3b. **Depends-on (reads-from) section**: For any plan that ships code, add a `## Depends-on (reads-from)` section listing every data path, contract, or invariant the new/changed code reads. Each entry takes the form `- \`<path-or-contract>\` — verified` or `- \`<path-or-contract>\` — unverified`. Mark `verified` when you can confirm something in the repo writes that path or holds that invariant (grep, schema inspection, or test fixture confirms it); mark `unverified` when no writer exists or you cannot confirm. Any `unverified` entry is a BLOCKING unknown that must be resolved — either add the missing writer to the plan, remove the read, or add `override: reads-from-dependency` with rationale. This section is exempt for doc-only and config-only plans that name no source-code paths. Enforced by `plan-verify` rule `reads-from-dependency`.
26
+ 3c. **Activation Map section**: For any plan that proposes a new *event-driven or call-site-dependent* component — a stop/SessionStart/PreToolUse/PostToolUse hook, a cron/launchd job, a watcher, a git hook (pre-commit/post-commit), a webhook, or a gate that fires on a host event — add an `## Activation Map` section. This converts build-loop's recurring failure class (machinery built, activation path never verified — a dormant WARN gated on a dict that int()'d to 0, state_finalize reading the wrong phase key, repo-level codex hooks that never fired, run-identity reuse silently skipping records) into a structural plan requirement. Each entry takes the form `- <component> — trigger: <event-or-call-site> — verified-live: yes|pending`. The `trigger:` must name the *concrete* host event or call site (e.g. `PostToolUse:Bash matcher in hooks/hooks.json`, `SessionStart hook`, `pre-commit hook in .pre-commit-config.yaml`), not an aspiration ("runs at review time"). Mark `verified-live: yes` only when you have confirmed the trigger actually fires (a live run exercised it, or a test asserts the host event reaches the handler); mark `verified-live: pending` otherwise. Any `pending` entry must map to a verification task before Report — the plan does not close while a component's activation is unconfirmed. This section is exempt for plans that propose no new event-driven machinery (doc-only, refactor-only, pure inline-logic changes); a `## Activation Map` is not required there. Add `override: activation-map-exempt` with rationale only when the section genuinely does not apply. Enforced by `plan-verify` rule `activation-map-required` (BLOCKER: missing section on a dormant-risk plan, or any entry that names a `trigger:` without a `verified-live:` key).
27
+
28
+ 4. **Partition tasks and files MECE**: Use one grouping dimension per level (domain, layer, workflow, bounded context, adapter, or test surface). Every changed file gets exactly one owner; every required behavior, state, migration, test, and user-facing surface gets an owner.
29
+ 5. **Define subagent integration points**: Where do agents need to coordinate? Where must outputs be tested together? Record interface contracts and checkpoints for every boundary.
30
+ 6. **Codex delegation gate**: If running in Codex, record whether the user explicitly authorized subagents/parallel delegation. If not, keep all execution local even when the graph contains parallel-safe groups.
31
+ 7. **Research Context gate**: read `.build-loop/state.json.researchGate`. If
32
+ `research_required: true`, add `## Research Context` to the plan with the
33
+ returned `depth`, `packet_path`, source policy, and
34
+ `blocks_final_claims` value. If `packet_path` is non-null, state whether
35
+ the packet already exists, will be created before Execute, or is unavailable
36
+ with rationale. For current/external/API claims, verify current docs before
37
+ coding and do not carry uncited claims into the final report.
38
+ 8. **UI input/output contract gate**: If `uiTarget != null`, load `references/ui-io-contract.md` and add a `## UI Input/Output Contract` section to the plan before mockups or implementation. The section must cover every affected screen/component and name: user inputs, system outputs, data taxonomy, CRUD/domain operation, component mapping, state matrix, modality fallback, validation/security, and traceability. If a planned UI component has no named input/output, remove it or mark it decorative with rationale; decorative controls are usually a scope error.
39
+ 8a. **Calm Precision core-consideration gate**: If `uiTarget != null`, the design direction must treat Calm Precision as a core decision gate before selecting structure, style mode, motion, or interaction behavior. The resulting `.build-loop/app-contract/ui.md` must include `## Calm Precision Core Considerations` with relevant principles, perceptual foundations, implementation effects, and explicit exceptions.
40
+ 8b. **Recent design structures gate**: If `uiTarget != null`, load `references/recent-design-structures.md` before dispatching `design-contract-specialist`. The specialist, not the planner, selects the structure. The plan should pass the file path and any relevant mockup/screenshot/design artifacts; it should not force a named structure unless the user explicitly requested one.
41
+ 9. **Mockup-first gate for major UI work**: If the plan introduces a *new page/screen* or makes a *major redesign* (changes navigation graph, primary user flow, or replaces ≥40% of an existing screen), pause Plan and invoke `mockup-gallery:mockup-session-new` to draft black-and-white mockups before any UI is written. Wait for user feedback via `mockup-gallery:mockup-feedback`; carry the selected mockup into Execute as a reference. Skip for cosmetic tweaks, copy edits, or single-component swaps. This is the documented exception to build-loop's "actions/functions only, no UI surfaces" plugin-bridging policy — mockup drafting is itself the action.
42
+
43
+ **Optimization checklist** (review the plan for these before proceeding):
44
+ - Can more tasks run in parallel? Unnecessary sequential bottlenecks?
45
+ - Can subagent context be smaller? Shared reads that should be done once?
46
+ - Missing dependencies, interface mismatches, env assumptions?
47
+ - Changes that could conflict with each other (oscillation risk)?
48
+ - Is the recommendation accidentally anchored to current tech debt when a cleaner use-case-first answer exists?
49
+ - If the plan chooses the current-constraints approach, is the bridge/backcast explicit enough to prevent the compromise from becoming permanent architecture by default?
50
+ - Define coordination checkpoints where subagents must sync
51
+ - UI/API/data choices that add options, mocks, or complexity without user value?
52
+ - UI plans missing input/output coverage, state coverage, modality fallbacks, validation/security layers, or schema/API traceability?
53
+ - MECE gaps or overlaps: unowned responsibilities, shared file ownership, or mixed grouping dimensions?
54
+ - Boundaries that are too tight, too broad, or missing a stable interface?
55
+ - If the plan chooses a simpler/integrated path over modularity, is there a documented `MODULARITY EXCEPTION`?
56
+
57
+ **Plan acceptance gate** — required before "Output: Plan file":
58
+
59
+ **Readback discipline**: build-loop runs `plan-verify` and `plan-critic` automatically and prefixes every plan presentation with a one-line gaps-readback. The user should never have to ask "anything missing?" — the answer is always shown first.
60
+
61
+ Readback format (one line, mandatory, before the plan body):
62
+ - `✓ Plan gaps-checked (plan-verify + plan-critic): none` — when both passes are clean.
63
+ - `⚠ Plan gaps: <N> — <comma-separated list of findings>` — when findings exist, with each item marked `resolved` or `surfaced` (resolved = fixed in this plan revision; surfaced = carried as open for user awareness).
64
+
65
+ 8. **Run `plan-verify`** (deterministic, grep-checkable rules; now includes `no-stop-language` rule):
66
+ ```bash
67
+ python3 ${CLAUDE_PLUGIN_ROOT}/scripts/plan_verify.py <plan.md> --repo "$PWD" --json
68
+ ```
69
+ - Exit 0 → proceed to step 9.
70
+ - Exit 1 → revise the plan to address each BLOCKER, or document an explicit override in `.build-loop/state.json.planVerifyOverride[]` with rationale before proceeding.
71
+ - Exit 2 → treat as verifier outage; log and proceed with `plan-critic` alone plus a state.json warning.
72
+ - `parallel-decision-record` is a BLOCKER: plans that name independent / parallel-safe multi-chunk work must include `parallel_batch:` or `parallel_skipped_reason:`.
73
+ - Full rule list and contract: `${CLAUDE_PLUGIN_ROOT}/skills/plan-verify/SKILL.md`.
74
+ 9. **Dispatch `plan-critic` agent** (non-deterministic checks): pass the plan + the JSON from step 8 so the critic doesn't re-derive deterministic findings. Critic surfaces alternatives-considered, MECE scope, marker adequacy, headline drift. The critic's emitted severity caps at WARN. **Gating is stakes-conditional (decided by the orchestrator, not the critic):** on high-stakes plans (`synthesisDensity > 5`, `triggers.riskSurfaceChange`, `stakes >= medium`, or `dispatch_tier: frontier`) those WARNs are **blocking** — Phase 2 does not finish until each is revised or explicitly overridden; otherwise they are **advisory** (today's behavior). The gate advances on objective signals only, never self-reported confidence. See `references/advisor-dispatch-ladder.md`.
75
+ 10. **Emit gaps-readback** using the combined output of steps 8–9. Populate the one-line readback prefix before presenting the plan. Both passes must complete before the plan is shown to the user — never present a plan without the readback line.
76
+ 11. **Dispatch `scope-auditor` agent** (Plan→Execute boundary): pass the plan + extracted commit table (with `modifies_api` per commit). The auditor is Opus + read-only; it traces every caller-site of every modified-API symbol via project-wide grep, classifies callers as in-scope / out-of-scope, and emits a `## Caller Audit (Scope Auditor)` JSON section appended to the plan. Verdict `scope_gap_found` requires plan revision (absorb missing callers into the right commit's owned-files) before Phase 3, OR explicit acceptance in `state.json.scopeGapAccepted[]` with rationale. Skip ONLY when the plan has zero `modifies_api` entries (doc-only commits). Prevents the fan-out scope-blindness defect class — see `agents/scope-auditor.md`.
77
+
78
+ **Output**: Plan file with dependency graph, integration points, optimization notes, plan-verify JSON, plan-critic findings, gaps-readback line, and scope-auditor caller audit.
@@ -0,0 +1,49 @@
1
+ <!-- SPDX-FileCopyrightText: 2025-2026 Tyrone Ross, Jr <46267523+tyroneross@users.noreply.github.com> | SPDX-License-Identifier: Apache-2.0 -->
2
+
3
+ # Phase 3: Execute (full protocol)
4
+
5
+ > Loaded from `skills/build-loop/SKILL.md` summary. Contains the full Execute phase: parallel subagent dispatch, single-writer git contract, and C5 halt-and-ask backstop.
6
+
7
+ ## Phase 3: Execute — Build With Agents
8
+
9
+ **Goal**: Implement the plan using parallel subagents where possible.
10
+
11
+ 1. **Use `subagent-driven-development`** — dispatch subagents per task
12
+ 2. **Model assignment**: Default implementer `model: sonnet`, `effort: medium`. Consult `Skill("build-loop:model-tiering")` for task-specific defaults and escalation triggers
13
+ 3. **Parallel agents** where dependency graph allows. build-loop dispatches up to `effective_max` parallel subagents, where `effective_max = scripts/parallelism.py effective_max_implementers(workdir)` — machine-aware (default 8; `min(config.parallelism.maxImplementers, cpu_count−2, hard ceiling 12)`). Decompose the plan into as many independent MECE chunks as the dependency graph allows so the wider fan-out is filled; dispatch in batches via `plan_batches()` when chunk count exceeds `effective_max`.
14
+
15
+ **Maximize parallel-safe chunks**: the partition should expose the maximum number of independent chunks (one file-owner each) so fan-out scales to the available `effective_max`. Serializing parallelizable work requires a `parallel_skipped_reason:` entry in the plan record.
16
+
17
+ **MECE pre-dispatch gate (NEW)**: before fanning out, validate the partition is *mutually exclusive* — `python3 scripts/parallelism.py --check-partition <{agent:[owned_paths]} JSON>` (exit 1 + overlap report if any file is claimed by >1 agent). A non-empty overlap means two writers would race the shared worktree — fix the partition (or give the overlapping agent `isolation:"worktree"`) before dispatch. Complements `brief_mece_validator.py` (which checks a single brief *has* the seven ownership fields) by checking they are disjoint *across* the fan-out — closing the file-race / fan-out scope-blindness class.
18
+ 4. **Each agent gets**: minimal context + clear integration contract + relevant doc context for external APIs + the intent packet from `.build-loop/intent.md` + the MECE ownership packet from the plan (`owns`, `does not own`, `interface contract`, `integration checkpoint`, `allowed tools`, `denied tools`, `acceptance criteria`)
19
+
20
+ **`acceptance criteria` (7th field)**: the testable conditions the returning envelope must satisfy — a per-chunk oracle the verifier reads instead of re-deriving one from the diff. Linted by `scripts/brief_mece_validator.py`; a write-handoff brief missing it now lints invalid. *Recovery-path was deliberately rejected as an 8th field — recovery stays centralized in the orchestrator's status-routing + stuck-cascade, not duplicated per handoff.*
21
+ 4a. **Implementers do NOT commit** (NEW 2026-05-07 — single-writer git contract). Implementers modify the working tree and return `files_changed` + `commit_subject` + `commit_body` in their envelope. The orchestrator commits sequentially after each parallel batch returns: `git add -- <files>` + `git commit -m <subject> -m <body>`, one implementer at a time through the pre-commit hook. This prevents the parallel-commit race that lost 3 of 4 commits in example-app round 3 (2026-05-07). See `agents/build-orchestrator.md` §"Phase 3 commit step" for the full procedure.
22
+ 4b. **Halt-and-ask backstop for architectural-class decisions** (NEW — C5). When an implementer encounters a synthesis-class decision NOT in the plan's `synthesis_dimensions` AND it's architectural-class (where a phase lives, defensive contract shape, error-propagation policy, persistence boundary, hard-fail counters), the implementer returns `status: "blocked"` with the decision in `novel_decisions[]` and does NOT commit. The orchestrator dispatches each blocked decision to the configured Thinking-tier resolver (per `references/model-tier-mapping.md` — never a hardcoded model name), persists resolutions to `state.json.novelDecisionResolutions[]`, and re-dispatches the implementer with resolutions appended to its brief. Hard-fail counter N=3 per chunk; exhausted chunks surface as ❓ Unfixed in Review-F. C3's attestation lint and C4's synthesis-critic still cover what they can grade — C5 catches what falls outside both. Full procedure: `agents/build-orchestrator.md` §"Phase 3 halt-and-ask branch".
23
+ 5. **Codex execution adapter**: If running in Codex, load `references/codex-subagents.md` before any spawn decision. Spawn `explorer` or `worker` subagents only when the Codex permission gate passed; otherwise execute locally. When spawning a worker, use `templates/codex-worker-prompt.md`, prefer explicit prompt packets over full context forks, and require the worker return changed files, validation, unresolved risks, and integration notes.
24
+ 6. **UI work (when `uiTarget != null`)**: Every UI subagent prompt MUST be prepended with the verbatim contents of `templates/ui-subagent-prompt.md` (loaded as raw text, not as a link). The template injects:
25
+ - Mandate to load `calm-precision`, read `.build-loop/app-contract/ui.md` when present, and use external platform/design skills only when explicitly requested by the orchestrator
26
+ - Mandate to apply the plan's `## UI Input/Output Contract` from `references/ui-io-contract.md`
27
+ - Mockup-vs-rule conflict policy: rule wins; subagent must report `RULE BEATS MOCKUP:` decisions
28
+ - Inline anti-pattern checklist (status pills, ungated animations, theme-token bypass, Dynamic Type, accessibility labels, touch targets, VoiceOver consistency, no fake buttons)
29
+ - Required env hooks (e.g. `@Environment(\.accessibilityReduceMotion)` on SwiftUI animations)
30
+ - Self-verification: run scanner before returning, zero must-fix on changed files
31
+
32
+ Subagents cannot rely on parent context — knowledge that doesn't enter the prompt doesn't reach the code. The template entering the prompt is non-negotiable. Plus also load `calm-precision` skill at the orchestrator level for cross-cutting decisions. Apply "beauty in the basics": every visible element needs a purpose, working behavior, clear hierarchy, useful states, accurate data, and an explicit input/output contract.
33
+ 7. **Surface pre-existing issues**: Don't silently ignore problems discovered during implementation. If an issue affects users and is local to the current build, plan and fix it automatically. If it is too large/risky, log to `.build-loop/issues/` with user impact and proposed fix.
34
+ 7a. **Simplify as you go**: remove dead code AND prefer the clearest, equal-or-better-performing logic/architecture — never just deletion; preserve behavior + correctness.
35
+ 7b. **Visual-evidence gate (BL-1)** — REQUIRED at chunk-close when `uiTarget != null` AND the chunk's `files_changed` includes any UI file (`Views/`, `*.swift`, `*.tsx`, `*.jsx`, `*.vue`, `*.svelte`, `components/*`, `pages/*`, `app/*.ts(x)`). After the implementer returns and before the commit step, build an envelope `{ uiTarget, files_changed, verification, evidence_paths }` from the return packet and run:
36
+
37
+ ```bash
38
+ node "${CLAUDE_PLUGIN_ROOT}/skills/build-loop/scanners/require-visual-evidence.mjs" \
39
+ --envelope-file "$PWD/.build-loop/visual-evidence-<chunk>.json"
40
+ ```
41
+
42
+ Exit-code routing:
43
+ - `0` (pass) → proceed to commit step
44
+ - `1` (warn) → re-prompt the implementer for a screenshot / AX-tree dump / scan result; do NOT commit yet
45
+ - `2` (reject) → **BLOCK the commit**; route the chunk back to Phase 5 Iterate with `status: fail` and the gate's `reason` as the rubric. Symbol/string-only evidence (`nm`, `strings`, `git grep`, "compiles cleanly", "identifier present") is NOT a substitute for visual/AX verification. Required: render the running app (pid-anchored) and capture a screenshot, AX-tree dump, or scan result.
46
+ - `3` (malformed) → log a one-line warn and proceed (infra defect, not a build defect — capture in `.build-loop/feedback.md`)
47
+
48
+ This gate exists because "visual-verify REQUIRED" was historical prose that a bad dispatch brief could override (session-findings 2026-06-04: brief blessed `nm`/`strings` → chunks shipped with non-rendering UI). The gate replaces prose with an enforced exit-code check.
49
+ 8. **Coordination checkpoints**: At defined sync points, verify agent outputs align before continuing