Implement Feature (SAM Workflow Execution)
This workflow continues from add-new-feature. It executes tasks from the selected provider until complete or blocked.
<plan_ref>$ARGUMENTS</plan_ref>
<sam_cli> uv run "${CLAUDE_PLUGIN_ROOT}/sam_schema/cli.py" </sam_cli>
<mcp_server_scripts> SAM server: uv run --script "${CLAUDE_PLUGIN_ROOT}/scripts/run_sam_server.py" Backlog server: uv run --script "${CLAUDE_PLUGIN_ROOT}/scripts/run_backlog_server.py" --project-dir . </mcp_server_scripts>
MCP server availability: This skill uses both mcp__plugin_dh_backlog__* and mcp__plugin_dh_sam__* tools. Both servers initialize in ~1–2 seconds after a session restart. Claude Code handles connection waiting automatically. If a tool is unavailable, see the troubleshooting steps at ${CLAUDE_PLUGIN_ROOT}/docs/mcp-connection-check.md — its commands use the <sam_cli/> and <mcp_server_scripts/> values above.
Resolve Plan
Treat the value from the plan_ref key as the opaque reference returned by sam_plan create. Pass it unchanged to every SAM operation and delegation prompt.
Confirm the plan exists:
uv run "${CLAUDE_PLUGIN_ROOT}/sam_schema/cli.py" plan status --plan-address "{plan_ref}"
Record the Implementation Base SHA
Read sam_plan(plan="{plan_ref}", config={"action": "read"}).context. If it already contains a
line matching **Implementation base SHA**: <sha>, skip this step — a prior run already recorded
it, and re-running this step now would capture a later commit instead of the true starting point.
Otherwise, before the Progress Loop makes its first commit: run git rev-parse HEAD and prepend
**Implementation base SHA**: {sha}\n\n to the existing context (do not replace it —
sam_plan(action='update', context=...) overwrites the whole field), then write it back via
sam_plan(plan="{plan_ref}", config={"action": "update", "context": "{updated context}"}).
Progress Loop
- Query status:
uv run "${CLAUDE_PLUGIN_ROOT}/sam_schema/cli.py" plan status --plan-address "{plan_ref}"
After receiving the status response, extract and store the autonomy mode:
autonomy_mode = status["autonomy"]
This value governs gate behavior throughout the remainder of the Progress Loop for this plan.
Pre-existing plans that omit the autonomy field return "full_auto" (the Pydantic default).
- If tasks remain, query ready tasks once and store the result as the current batch. In a Beads workspace, use
bd ready --parent <bead-id> --jsonfor native dependency readiness; use the SAM/DH adapter only for richer structured plan rules:
If parent story identifier is known and structured SAM readiness is required (str | int — GitHub integer ID such as 42 or beads string ID such as "bd-a3f8"), use the adapter tool:
uv run "${CLAUDE_PLUGIN_ROOT}/sam_schema/cli.py" plan sam-ready-tasks --parent-issue-number N
Output shape: {"feature": "...", "ready_tasks": [...], "count": N}. The selected provider owns
availability handling and any private cache it requires.
If parent issue number is unknown, use the SAM CLI:
uv run "${CLAUDE_PLUGIN_ROOT}/sam_schema/cli.py" plan ready --plan-address "{plan_ref}"
Call
mcp__plugin_dh_sam__sam_plan(config={"action": "ready"}, plan="{plan_ref}")(orbacklog_get_ready_sam_tasks) ONCE per batch. Store the returned task list. Loop over the stored list without fetching ready tasks again — step 5 below governs when the next batch is fetched.
- Dispatch based on
autonomy_mode:
If autonomy_mode == "per_task":
Process tasks from the ready list one at a time:
- Dispatch task N via a single
Agentcall. - Complete steps 4, 4a, 4b for task N.
- Present the per-task gate (after step 4b, described below) before dispatching task N+1.
Else (autonomy_mode is "full_auto" or "checkpoint"):
When multiple tasks are simultaneously ready (non-zero count with 2+ tasks in the ready list),
dispatch one Agent() call per ready task, all in parallel. When only one task is ready, dispatch
it with a single Agent call the same way per_task mode does.
For each task being dispatched:
- Choose which agent to dispatch with the decision in
dh:dispatch-contract. Pass only the task reference (plan_ref+ task ID) — the task definition'sagentfield is read after dispatch, not by the orchestrator. - Launch the chosen agent with the task reference as its entire prompt:
{plan_ref}/{task_id}
- The dispatch carries a task reference and the receiver resolves what to load from it.
dh:task-workerreads the task record, loads the profile named in itsagentfield, and the task-execution skill it delegates to loads the task's ownskillslist; a specialist dispatched directly already carries its own behavior. Task-level skills stay additive to whatever the agent profile declares.
Agent Health Check (While Waiting)
After dispatching a batch, the orchestrator waits for completion messages. Trigger a health check
when any of these occur: no message from any dispatched agent after ~10 minutes of silence, the
user asks about agent status, or git log shows no new commits when implementation work should be
in progress. Execute the full check — crash/idle/active branches and re-spawn logic — defined in
./references/agent-health-check.md.
- After each agent returns, check its output for a
<concerns>block. If present, append each concern to the backlog item as a checklist entry:
mcp__plugin_dh_backlog__backlog_groom(
selector="{issue}", # {issue} is str | int — GitHub integer ID or beads string ID.
# See the tool's own selector parameter description for format rules.
section="Concerns",
content="- [ ] {concern text} (reported by {agent_name} on {task_id})",
append=True
)
Use the MCP tool for this call.
Concerns accumulate across all task agents. They feed into the validation stage in /complete-implementation — each verified concern becomes a new backlog item.
4a. If a parent issue number is known (str | int — GitHub integer ID or beads string ID), attempt contract verification against the architect spec:
uv run "${CLAUDE_PLUGIN_ROOT}/sam_schema/cli.py" artifact read --item-id N --artifact-type architect
If artifact_read returns content (architect spec exists), resolve the files modified by the just-completed task:
git diff --name-only HEAD~1..HEAD
Then spawn the contract-verification agent:
Agent(
subagent_type="dh:contract-verification",
prompt="""
Verify the just-completed task against the architect spec.
Task ID: {task_id}
Plan: {plan_ref}
Issue number: {issue}
Modified files:
{modified_files_list}
Fetch the architect spec yourself (per your own agent file) and read its Component Design and
Type System Design sections.
For each modified file, grep for function/class definitions and extract actual signatures.
Compare against the contracts defined in the spec.
Deliver findings per your own agent file's Delivery section — do not return them in your
response text; the dispatcher does not read it.
"""
)
If artifact_read fails or returns no content (no architect spec for this issue), skip step 4a entirely. Proportional quality gate items without an architect spec automatically skip this step.
4b. Confirm the batch is done
In per_task mode this is a no-op: the single dispatched Agent() call already returned, so the
task is terminal by construction. In full_auto/checkpoint mode, multiple agents were dispatched
concurrently — before the batch commit, confirm every task in the batch is terminal through
sam_plan(config={"action": "status"}), never by assuming a silent agent has finished.
Commit Ownership
Commit responsibility depends on which execution mode is active.
Same-worktree mode (default — no isolation flag): The orchestrator owns all commits. Commit timing depends on autonomy_mode:
-
per_taskmode: The Per-task Confirmation Gate (below) ensures only one task runs at a time. Commit after step 4b, before dispatching the next task — no concurrent agents are writing:git add -A git commit -m "<type>(task): {task_id} — {task_title}" -
full_autoandcheckpointmodes: Multiple tasks in a batch execute concurrently. Do NOT commit after each individual step 4b — other batch agents may still be writing to the worktree. Commit once after step 5 confirms all tasks in the current batch are complete:git add -A git commit -m "<type>(task-batch): {plan_ref} — {task_ids}"Confirm every task in the batch is terminal (step 4b) before this commit.
In both cases, choose <type> to match the dominant change in the committed work (feat, fix, docs, refactor, etc.). Do NOT include Fixes #N, Closes #N, or Resolves #N trailers — see start-task/SKILL.md step 6. Issue closure is handled exclusively by /complete-implementation.
Isolated-worktree mode (via /dh:work-milestone): Each agent owns its own commits. The agent commits in its isolated worktree after completing its task. The orchestrator merges each worktree back when the completion message arrives. The orchestrator does NOT issue commit calls in this mode.
Per-task Confirmation Gate (active when autonomy_mode == "per_task" only):
After task N completes (steps 4 through 4b finished), before dispatching task N+1:
-
Display a compact task result summary:
- Task ID and title
- Completion status (complete / error)
- Any concerns raised — read fresh via
backlog_view(selector="{issue}", section="Concerns", show="last")(no#prefix, per step 4 above) immediately before rendering this summary, not from step 4's in-memory<concerns>block check. Step 4a's contract-verification agent (when dispatched) delivers its findings directly to the Concerns section and is never captured by step 4's check, so a fresh read is the only way this summary sees them.
-
Present a confirmation prompt to the user. The exact wording is implementation-defined; examples include "Ready to dispatch the next task? (yes/no)" or a numbered menu of options. The prompt must make clear which task will be dispatched next (task ID and title).
-
Await explicit user confirmation before proceeding.
- If confirmed: dispatch the next task from the stored batch (or query the next batch if the batch is exhausted).
- If declined or cancelled: stop the Progress Loop. Report the current plan state via
uv run "${CLAUDE_PLUGIN_ROOT}/sam_schema/cli.py" plan status --plan-address "{plan_ref}"and exit.
Skip this gate when autonomy_mode is "full_auto" or "checkpoint".
- After all tasks in the current batch complete, call
uv run "${CLAUDE_PLUGIN_ROOT}/sam_schema/cli.py" plan status --plan-address "{plan_ref}"to check plan progress. If tasks remain, return to step 2 to fetch the next batch of ready tasks. Do not fetch another ready batch until the previous batch is fully dispatched.
5a. Wave-Completion Confirmation Gate (active when autonomy_mode == "checkpoint" only):
After all tasks in the current batch complete and the status response from step 5 confirms that tasks remain:
-
Display a compact wave-completion summary:
- Number of tasks completed in this wave
- Current plan completion percentage (from
status["completion_pct"]) - Number of tasks remaining
- Next ready tasks (from
status["ready_tasks"]list — task IDs only)
-
Present a confirmation prompt to the user. The exact wording is implementation-defined; examples include "Wave complete. Proceed with the next wave? (yes/no)".
-
Await explicit user confirmation before fetching another ready batch.
- If confirmed: proceed to step 2 to fetch the next batch.
- If declined or cancelled: stop the Progress Loop. Report the current plan state and exit. The plan remains in its current state and can be resumed later.
Skip this gate when autonomy_mode is "full_auto" or "per_task".
Note: under "per_task", per-task gates already fire for each task; no additional wave gate is needed.
Hook behavior on SubagentStop: When a sub-agent finishes,
task_status_hook.pymarks the task complete via the SAM CLI (backend-agnostic). After updating the SAM state, the hook syncs completion to the external tracker (ifparent_issue_numberis set in the active-task context). External tracker sync failure does not affect the hook exit code.parent_issue_numberacceptsstr | int— GitHub integer IDs and beads string IDs are both supported.
Bookend Task Ordering
When the plan contains acceptance-criteria-structured entries, swarm-task-planner generates T0 and TN bookend tasks. No special handling is needed in this loop — existing readiness logic dispatches them in the correct order automatically:
- T0 has
priority: 1anddependencies: [], so it is the first ready task and dispatches before any implementation task. - TN has
dependencies: [all non-bookend task IDs], so it becomes ready only after all implementation tasks complete and dispatches last.
T0 runs agent t0-baseline-capture. TN runs agent tn-verification-gate. Both agents register their results as artifacts via artifact_register (types T0-baseline and TN-verification). These artifacts are read by /complete-implementation in its pre-Phase 1 check via artifact_read.
Bookend Artifact Registration
When the parent story issue number is known (str | int — GitHub integer ID or beads string ID), include artifact_register instructions in each bookend task's delegation prompt so the bookend artifacts are registered in the issue's artifact manifest:
T0 delegation prompt addition:
Register the baseline content directly via MCP (no file write):
mcp__plugin_dh_backlog__artifact_register(item_id=N, artifact_type="T0-baseline", artifact_id="T0-baseline-{slug}", content=<baseline yaml string>, agent="t0-baseline-capture")
TN delegation prompt addition:
Register the verification content directly via MCP (no file write):
mcp__plugin_dh_backlog__artifact_register(item_id=N, artifact_type="TN-verification", artifact_id="TN-verification-{slug}", content=<verification yaml string>, agent="tn-verification-gate")
If the issue number is not known, skip registration.
Variant: Worktree Isolation
Worktree isolation variant: For milestone-scoped execution where each item gets its own worktree, use /work-milestone instead. See work-milestone SKILL.md.
Completion Gate
When all tasks show COMPLETE, load the dh:complete-implementation skill with {plan_ref} as
its argument, in this workflow's own context.