Parse a TRD and create a beads hierarchy (epic -> stories -> tasks) before
any implementation begins. Drive execution order through bv --robot-next (with
br ready fallback) rather than TRD re-parsing. Record all state transitions
in br beads so the implementation is resumable across sessions without access
to local state files.
This command wraps the implement-trd-enhanced execution model with a full
beads project management layer powered by br (beads_rust) and bv (beads_viewer).
It transforms TRD-structured work into a persistent, queryable beads hierarchy
and drives execution order through bv --robot-next — enabling cross-session
resumability, graph-aware triage, and parallel execution planning.
- NOTE: This Execute phase implements the same execution engine as /ensemble:beads-build. If you have raw beads (not from a TRD), use /ensemble:beads-build instead. beads-build also accepts --trd to enable TRD augmentations on any bead hierarchy.
- Resume check: If TASK_TRACEABILITY is empty (cross-session resume — Scaffold phase did not run this session), re-parse TRD content to rebuild TASK_TRACEABILITY before processing tasks:
- Run: node "$TRD_CLI" parse "<TRD_FILE_PATH>" and rebuild TASK_TRACEABILITY from trd.tasksById exactly as in Scaffold Step 1 (same field mapping). This is the deterministic resume rebuild; do not hand-parse.
- d. Print 'NOTE: TASK_TRACEABILITY rebuilt from TRD (cross-session resume). Tasks: '
- e. After rebuild: if rebuilt TASK_TRACEABILITY is empty AND TRD content was successfully read AND TRD is non-empty: print 'WARNING: TRD re-parse found no traceability annotations. Requirement audit comments will not be written. If this is a legacy TRD without [satisfies] annotations, this is expected.' If TRD file could not be read: print 'ERROR: Cannot read TRD file at <TRD_PATH> during cross-session resume. Verify file exists and is readable.' and HALT.
- Non-Interactive Progress Policy (applies to both TEAM_MODE=true and TEAM_MODE=false):
- Do NOT stop, pause, ask for acknowledgement, or end the assistant turn for routine progress summaries, context checkpoints, or task-count milestones. The execution loop must continue automatically until Completion or until a real user decision is required.
- A real user decision means one of: invalid/cyclic graph needing edge choice, failed quality gate needing fix/skip/abort, exhausted debug/review/rejection retries, dirty working tree before branch creation, failed br/git command requiring recovery, or missing required tool/config.
- After every 10 task completions, at most print one terse non-blocking line: 'Progress: tasks completed; continuing automatically.' Do not print multi-line reports or compact/new-session suggestions unless the user explicitly asks for status.
- If output from a task exceeds 500 lines, summarize it into a br comment and continue; do not stop for context-budget advice.
- TEAM_MODE Gate (evaluated once at the start of the Execute phase):
- if TEAM_MODE == false:
-
- Use the existing v2.1.0 Execute loop (all steps 1-6 unchanged)
-
- Skip all team-specific steps (reviewer delegation, QA delegation, rejection loop, parallel builders)
-
- Quality Gate phase: run full scope (current behavior)
-
- Continue to LOOP below
- if TEAM_MODE == true:
-
- Replace the standard execution loop with the Lead Orchestration Loop below (TRD-013, AC: FR-LL-1, AC-LL-1)
-
- Reviewer delegation: enabled (TRD-016)
-
- QA delegation: enabled if QA_ENABLED=true (TRD-017)
-
- Parallel builder slots: active (TRD-025)
-
- Quality Gate phase: reduced scope if QA_ENABLED=true (TRD-031)
-
- Note: Scaffold phase is IDENTICAL in both modes (no team awareness in scaffold)
-
- Note: Completion phase is IDENTICAL in both modes
-
- Note: v2.1.0 beads without status: comments are treated as in_progress (builder stage) — safe default for backward compat (TRD-038)
-
- RETURN (team loop handles all remaining execution; skip LOOP below)
-
LEAD ORCHESTRATION LOOP (TEAM_MODE=true):
-
Variables: active_builders = {} (bead_id -> builder_agent)
-
LOOP:
-
1. br sync --flush-only (ensure JSONL current)
-
2. Check in-flight tasks (tasks with br native status=in_progress that have sub-states in_review or in_qa):
-
- Run: br list --status=in_progress --json, filter by TRD slug
-
- For each in-progress bead: call get_sub_state(bead_id)
-
- If sub_state == 'in_review': proceed to Reviewer Delegation step (TRD-016)
-
- If sub_state == 'in_qa': proceed to QA Delegation step (TRD-017)
-
- If sub_state == 'in_progress': task is with builder (normal)
-
3. Count available slots: available_slots = max_parallel - len(active_builders)
-
(default max_parallel=1, increased by 'max parallel N' argument)
-
4. If available_slots > 0:
-
- Get next tasks: if EXECUTE_ONLY=true or BV_AVAILABLE, run bv --robot-next --format toon (returns top unblocked task; bv is guaranteed available when EXECUTE_ONLY=true)
-
Else (EXECUTE_ONLY=false AND not BV_AVAILABLE): run br ready, filter by [trd:<TRD_SLUG>:task:] prefix
-
- Phase-strict selection: bv --robot-next / br ready return BEAD records titled [trd:<TRD_SLUG>:task:<TRD-NNN>]. Extract the TRD-NNN id from each ready bead's title to form READY_TRD_IDS, and form CLOSED_TRD_IDS = the TRD-NNN ids of all currently-closed task beads (the same set used by phase-status). Run: node "$TRD_CLI" next-task "<TRD_FILE_PATH>" --ready "<comma-joined READY_TRD_IDS>" --closed "<comma-joined CLOSED_TRD_IDS>" --max <available_slots or 1>. If ok is false or the process exits non-zero: print the error and HALT (do NOT dispatch on undefined selection). The returned selected[] are TRD-NNN ids; map each back to its bead id via TRD_TO_BEAD_MAP and dispatch ONLY those beads. This deterministically enforces the phase boundary (later-phase tasks filtered when PR_FORMAT=true); do NOT hand-filter.
-
- For each task (up to available_slots):
-
a. (TRD-021) Architecture Review: check task description for keywords:
-
'architecture', 'design', 'system', 'cross-cutting', 'multi-component', 'orchestrat'
-
If ANY keyword found:
-
- Lead performs brief architectural review (read TRD context, consider phase impact)
-
- Generate guidance notes (key design decisions, patterns to use, pitfalls to avoid)
-
- Record: br comment add <bead_id> 'architecture-review lead:<agent> guidance:<url_encoded_summary>'
-
- Include guidance in builder prompt: 'Architecture guidance from lead: <guidance_notes>'
-
If NO keywords: skip architecture review, proceed normally
-
b. (TRD-020) Lead Skip Decision: evaluate task characteristics before delegating to builder:
-
- If task description contains ONLY documentation/comments (no code changes expected):
-
SKIP_REVIEW=true, SKIP_QA=true
-
- If REVIEWER_ENABLED=false: SKIP_REVIEW=true (per TRD-023)
-
- If QA_ENABLED=false: SKIP_QA=true (per TRD-023)
-
- Lead can also skip based on judgment (low-risk configuration, etc.)
-
Record skip decisions:
-
- If SKIP_REVIEW: br comment add <bead_id> 'status:skip-review lead:<agent> reason:<rationale>'
-
- If SKIP_QA: br comment add <bead_id> 'status:skip-qa lead:<agent> reason:<rationale>'
-
Transition directly:
-
- Both review and QA skipped: validate_transition(bead_id, 'closed') directly after builder
-
- Only review skipped: validate_transition(bead_id, 'in_qa') -> QA delegation after builder
-
- No skips: normal flow (in_progress -> in_review -> in_qa -> closed)
-
AC: FR-LL-6, FR-LL-7, FR-LL-10, AC-LL-3, AC-LL-4, AC-LL-5, AC-LL-6
-
c. (TRD-022) Sibling Task Context: collect completed sibling tasks in same phase:
-
- Query br list --status=closed --json filtered by TRD slug, then restrict to task ids in PHASE_TASK_IDS[N] (task beads carry no phase/pr title segment — do NOT filter by a [trd:<TRD_SLUG>:phase:<N>] prefix, which never matches)
-
- For each closed task in this phase: read br comment list, find last implementation summary
-
- Limit to 5 most recently closed siblings
-
- If sibling context found, add to builder prompt:
-
'Previously completed tasks in this phase:'
-
'[TRD-XXX]: <implementation_summary_first_200_chars>'
-
'[TRD-YYY]: <implementation_summary_first_200_chars>'
-
- If no siblings completed yet: omit this section from prompt
-
AC: FR-LL-9
-
d. Select builder from TEAM_ROLES.builder.agents using keyword matching (TRD-014)
-
e. validate_transition(bead_id, 'in_progress') -- write status comment
-
f. Delegate to builder via Task(subagent_type=<builder>, prompt=<builder_prompt>) (TRD-015)
-
g. active_builders[bead_id] = builder
-
--- Parallel Builder Execution (TRD-025) ---
-
When available_slots > 1 AND multiple tasks are ready, apply parallel dispatch:
-
TRD-025-1. Set BUILDER_SLOTS = max_parallel (default 1, overridden by 'max parallel N' argument)
-
TRD-025-2. Query available tasks for parallel dispatch:
-
- If EXECUTE_ONLY=true or BV_AVAILABLE: run bv --robot-plan --format toon to get parallel execution tracks
-
Extract up to BUILDER_SLOTS tasks from the top-priority track(s)
-
- Else (EXECUTE_ONLY=false AND not BV_AVAILABLE): run br ready, filter by [trd:<TRD_SLUG>:task:] prefix, take up to BUILDER_SLOTS entries
-
- Candidate task list: CANDIDATE_TASKS = up to BUILDER_SLOTS ready tasks
-
TRD-025-3. File conflict detection: prevent assigning tasks with overlapping file targets
-
- For each task in CANDIDATE_TASKS:
-
a. Extract target file paths from the bead description
-
(look for 'File:', file path patterns like src/*, and file mentions in action items)
-
b. Build FILE_MAP: task_id -> [file_path, ...]
-
- Build SEEN_FILES = {} (file_path -> first task_id that claims it)
-
- Iterate CANDIDATE_TASKS in order:
-
For each task: check if ANY of its file paths are already in SEEN_FILES
-
- If NO overlap: add task to CONFLICT_FREE set, add its files to SEEN_FILES
-
- If overlap found: discard this task (keep first occurrence); log discarded task_id
-
- CONFLICT_FREE = ordered list of tasks with no file overlaps (up to BUILDER_SLOTS)
-
TRD-025-4. Launch concurrent Task() delegations for CONFLICT_FREE task set:
-
Phase A — Pre-flight (sequential, per task):
-
For each task in CONFLICT_FREE: run steps 4a-4e (architecture review, skip decision,
-
sibling context, builder selection, validate_transition) to prepare builder prompt.
-
Phase B — Concurrent dispatch:
-
Issue all Task() calls (step 4f) for CONFLICT_FREE simultaneously (parallel invocation).
-
Each builder works independently on its assigned task.
-
Phase C — Post-dispatch bookkeeping (sequential, per task):
-
For each dispatched task: run step 4g (active_builders[bead_id] = builder).
-
TRD-025-5. Wait for all parallel builders to complete:
-
- Block until ALL concurrent Task() delegations from TRD-025-4 return results
-
- Collect structured builder summaries (files_changed, implementation_description, etc.)
-
TRD-025-6. Process each builder result sequentially (after all parallel builders finish):
-
- For each completed builder result in CONFLICT_FREE order:
-
a. On builder success: run Reviewer Delegation step (step 3a) for this task
-
b. On reviewer approval: run QA Delegation step (step 3b) for this task
-
c. On any rejection: run Rejection Loop (step 3c) for this task
-
(Review and QA remain sequential per task even when builders ran in parallel)
-
- Remove each completed task from active_builders after its full pipeline finishes
-
--- Sequential Commit Ordering (TRD-026) ---
-
When parallel builders complete and their full pipelines (review+QA) pass, the lead serializes git commit operations:
-
TRD-026-1. Maintain COMMIT_QUEUE = ordered list of tasks whose pipelines completed successfully (in completion order).
-
TRD-026-2. For each task in COMMIT_QUEUE (process one at a time):
-
a. Run: git diff --name-only HEAD to see current staged changes
-
b. If no file conflicts with prior commits in this batch: commit immediately
-
- git commit with message referencing task ID and bead ID
-
- br comment add <bead_id> 'commit-order:<N> commit:<sha>'
-
- N = position in COMMIT_QUEUE (1-indexed)
-
c. If file conflict detected (same file modified by prior commit):
-
- One retry: builder re-applies its changes on top of the current HEAD
-
- If retry succeeds: commit normally, record commit-order:<N>
-
- If retry fails: br update <bead_id> --status=open; br comment add <bead_id> 'status:open commit-conflict-unresolved: returned to open'; continue to next task in COMMIT_QUEUE
-
TRD-026-3. After all commits: br sync --flush-only
-
--- Parallel Builder Failure Isolation (TRD-027) ---
-
If one builder fails (Task() returns error or structured failure summary) during parallel execution:
-
TRD-027-1. Reset that task: br update <bead_id> --status=open
-
TRD-027-2. Record failure (pure audit record — no state prefix): br comment add <bead_id> 'verdict:failed builder:<agent_type> reason:<error_summary>'
-
Note: NO status: prefix — this is a failure audit comment, not a state transition. validate_transition is NOT called.
-
The bead is already open (reset in step 1); a status: prefix would mislead get_sub_state() on the next loop iteration.
-
TRD-027-3. Other parallel builders continue unaffected (do not interrupt them).
-
TRD-027-4. The failed task enters the debug loop (Execute step 5: Debug Loop) on the NEXT loop iteration OR is eligible for re-assignment to another builder.
-
TRD-027-5. Lead tracks builder slot count: when a builder fails, its slot is freed immediately (active_builders count decremented).
-
TRD-027-6. Lead refills available slots on the next loop iteration by querying bv --robot-next / br ready again.
-
5. Check loop exit:
-
- If no tasks returned by bv/br AND no active_builders AND no in-flight tasks: break to Completion
-
- If no tasks returned but tasks exist in_review or in_qa: wait (check in-flight tasks next iteration)
-
6. br sync --flush-only
-
7. Continue LOOP
- LOOP:
- Run: br sync --flush-only (ensure JSONL current before bv call)
- If EXECUTE_ONLY=true: run bv --robot-next --format toon to get single top-priority task (bv is guaranteed available)
- If EXECUTE_ONLY=false AND BV_AVAILABLE: run bv --robot-next --format toon to get single top-priority task
- If EXECUTE_ONLY=false AND not BV_AVAILABLE: run br ready, filter by title prefix [trd:<TRD_SLUG>:task:]
- Phase-strict selection: bv --robot-next / br ready return BEAD records titled [trd:<TRD_SLUG>:task:<TASK_ID>]. Extract TASK_ID from the title prefix (between ':task:' and ']'); valid IDs include TRD-NNN, TRD-NNN-TEST, AC-NNN, AC-NNN-M, AC-NNNa, and XC-NNN synthetic validation tasks. Form READY_TRD_IDS from those extracted TASK_ID values, and form CLOSED_TRD_IDS from all currently-closed task bead title prefixes the same way. Run: node "$TRD_CLI" next-task "<TRD_FILE_PATH>" --ready "" --closed "" --max <available_slots or 1>. If ok is false or the process exits non-zero: print the error and HALT (do NOT dispatch on undefined selection). The returned selected[] are TASK_ID values; map each back to its bead id via TRD_TO_BEAD_MAP and dispatch ONLY those beads. This deterministically enforces the phase boundary (later-phase tasks filtered when PR_FORMAT=true); do NOT hand-filter.
- If no tasks returned: run br list --status=open --json filtered by TRD slug; if no open tasks remain break to Completion; else PAUSE (possible dependency cycle)
- If max_parallel==1 or single task ready: execute_single_task
- Else if EXECUTE_ONLY=true: use bv --robot-plan --format toon for parallel tracks; take up to max_parallel candidates; run file conflict detection; execute conflict-free group in parallel
- Else if EXECUTE_ONLY=false AND BV_AVAILABLE: use bv --robot-plan --format toon for parallel tracks; take up to max_parallel candidates; run file conflict detection; execute conflict-free group in parallel
- Else if EXECUTE_ONLY=false AND not BV_AVAILABLE: run br ready, filter by TRD slug, take up to max_parallel candidates; run file conflict detection; execute conflict-free group in parallel
- After each task (or parallel group): br sync --flush-only, update internal completed/open counters, and continue the loop. Do NOT call trd_progress() here and do NOT print a multi-line progress report after routine task completions; trd_progress() is reserved for --status, resume start, explicit user status requests, and final completion.