/sdd:work [SPEC-XXXX | issue numbers | (empty = propose from backlog)] [--max-agents N] [--draft] [--dry-run] [--no-tests] [--module <name>] [--loop [--max-iterations N] [--max-prs N] [--max-minutes N] [--max-dollars N] [--lock={skip|wait|force}] [--resume] [--budget-file PATH]] [--no-chain]from sdd
Picks up tracker issues and implements them in parallel using git worktrees. Each issue gets its own worktree and worker agent. Supports loop mode for autonomous multi-issue execution.
Ships in sdd. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Harness portability. This skill runs on any agent harness that loads Agent Skills — Claude Code, Codex CLI, OpenCode, Crush. Tool names used below (
AskUserQuestion,Task,TeamCreate,SendMessage,TaskCreate,ToolSearch,mcp__*,${CLAUDE_PLUGIN_ROOT}) denote capabilities, not hard requirements: map each to your harness's equivalent or use the documented fallback per${CLAUDE_PLUGIN_ROOT}/references/harness-compat.md. References toCLAUDE.mdmean the project memory file (CLAUDE.md,AGENTS.md, orCRUSH.md) per harness-compat § "Project Memory File". A citation of the formshared-patterns.md § "Section"names one##heading in that file — load only that section (see its "How to Read This File" note), never the whole file. Invocation and arguments. Where your harness has no command layer (Crush, Codex CLI, OpenCode) this skill is reached from itsdescription, not a slash command: the/sdd:{name}form below is Claude Code namespacing.$ARGUMENTSmeans whatever arrived with the invocation: take the target and any--flagsfrom the request that triggered this skill, and when neither is present follow this skill's documented no-argument path instead of reporting missing arguments (harness-compat § "Invocation and Arguments").
You are picking up tracker issues and implementing them in parallel using git worktrees. Each issue gets its own worktree and worker agent.
Loop Mode (V1, opt-in). When invoked under
/loopwith the--loopflag, this skill enters autonomous-mode and uses the lockfile + budget primitives documented in${CLAUDE_PLUGIN_ROOT}/references/loop-primitives.md(acquired on entry, released on exit) and the telemetry + resume contract documented in${CLAUDE_PLUGIN_ROOT}/references/loop-telemetry.md(every iteration appends ahistory.jsonlline and emits a stdout status block;--resumereconcilestracked_prs[]andactive_worktrees[]from the last line). The full CLI surface, all 12 stop conditions, and all 6 AskUserQuestion gates are wired in story #144 (SPEC-0020). Without--loop, behavior is unchanged from the rest of this document and no.sdd/loop/artifacts are created.
Resolve artifact paths: Follow the Artifact Path Resolution pattern from ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Artifact Path Resolution" to determine the ADR and spec directories. If $ARGUMENTS contains --module <name>, resolve paths relative to that module. The resolved spec directory is {spec-dir}.
0a. Resolve the project constitution: Follow ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Constitution Resolution" once for the run. Resolved rules become {constitution}, passed to every worker in step 10 and consulted at every stop this skill would otherwise make on ambiguous scope. No constitution means every constitution step below is skipped silently, with no prompt and no mention in output.
Parse arguments: Parse $ARGUMENTS.
Target resolution:
SPEC-0003), find all open tracker issues referencing that spec.42 43 47), work on those specific issues.$ARGUMENTS is empty (ignoring flags), review the backlog (see step 4) and propose a work plan (see step 1a below) — do NOT require a spec.1a. Backlog proposal (no arguments): After discovering workable issues in step 4, analyze the backlog with a bias toward unblocking work and feature development:
--max-agents issues (default 4) as the proposed batch.Present the proposed batch to the user using AskUserQuestion:
"Here are the issues I'd like to work on. Approve or adjust before I start."
Show a table:
| # | Issue | Project/Epic | Rationale |
|---|-------|-------------|-----------|
| 1 | #42 JWT Token Generation | Auth Module | Unblocks #43 and #44 |
| 2 | #47 Setup DB Schema | Core | No dependencies, foundational |
| 3 | #51 User Registration API | Auth Module | High priority feature |
Options: "Approve this batch" / "Let me pick manually" (if chosen, present full backlog and ask for issue numbers).
Flag parsing:
--max-agents N: Maximum concurrent worker agents. Default: 4 (or CLAUDE.md Worktrees > Max Agents).--draft: Create draft PRs instead of regular PRs. Default: off (or CLAUDE.md Worktrees > PR Mode).--dry-run: Preview what would happen without creating worktrees or doing any work. Default: off.--no-tests: Skip test execution in workers. Default: off.--module <name>: Resolve artifact paths relative to the named module. Default: none.Load architecture context (when a spec is provided or issues reference a spec): Read the spec's spec.md and design.md. Validate spec pairing per ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Spec Pairing Validation". Scan for referenced ADRs (e.g., ADR-0001) and read those too. This context will be sent to every worker. If no spec is associated with the selected issues, skip this step — workers will rely on issue body and codebase context alone.
Detect tracker: Follow the "Tracker Detection" flow in the plugin's ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Tracker Detection". Fallback to tasks.md parsing if no tracker is found.
3a. Ensure lifecycle labels exist (Governing: SPEC-0015 REQ "Issue Lifecycle Labels"):
Create the lifecycle labels using the try-then-create pattern (see ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Try-Then-Create Label Pattern") — attempt to use each label, and only create it if it doesn't exist. This avoids failures on repeated runs.
| Label | Color | Meaning |
|---|---|---|
queued | #CCCCCC | Issue is in the work queue, not yet started |
in-progress | #FBCA04 | An agent is actively working on this issue |
in-review | #0E8A16 | A PR has been created and is awaiting review |
merged | #6E40C9 | The PR has been merged |
For GitHub:
gh label create "queued" --color "CCCCCC" --description "Issue is queued for work" --force
gh label create "in-progress" --color "FBCA04" --description "Agent is actively working" --force
gh label create "in-review" --color "0E8A16" --description "PR created, awaiting review" --force
gh label create "merged" --color "6E40C9" --description "PR has been merged" --force
For Gitea: Use the tea CLI per ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Gitea Access". List existing labels with tea labels ls --login {login} --repo {owner}/{repo} and create only the missing ones with tea labels create --login {login} --repo {owner}/{repo} --name queued --color CCCCCC --description "..." (and likewise for the rest).
For GitLab: Per ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "GitLab Access", list existing labels once with glab label list -R {owner}/{repo} --output json --per-page 100 and create only the missing ones with glab label create -R {owner}/{repo} --name queued --color "#CCCCCC" --description "..." (and likewise for the rest). Create them before the first transition: GitLab silently auto-creates a missing label on apply, with the default color.
For tasks.md fallback: Skip label creation (labels are not applicable to file-based tracking).
3b. Define protected paths (Governing: ADR-0017, ADR-0020, SPEC-0015 REQ "Design Document Isolation"):
The following paths are protected and MUST NOT be modified by worker agents in feature branches:
| Protected Path | Reason |
|---|---|
{spec-dir} | Spec changes require coordinated review |
{adr-dir} | ADR changes require coordinated review |
CLAUDE.md (project root) | Shared configuration — concurrent edits cause conflicts |
.claude-plugin-design.json | Plugin configuration — concurrent edits cause conflicts |
Exception: Governing comments (per ADR-0020) MUST be added in feature PRs, not deferred. These are inline code comments (e.g., // Governing: ADR-XXXX, SPEC-XXXX REQ "...") and are NOT considered design document modifications.
This list is passed to every worker in step 9.4 and enforced in worker step 7a.
3c. Tier 4 issues sync (v5.0.0+):
Before discovering workable issues (Step 4), sync the {repo}-issues qmd collection from the tracker so the lead and all workers see current issue state. This also feeds the Sibling PR Manifest (Step 8a) with fresh data. Subject to the 5-min dedup window per ${CLAUDE_PLUGIN_ROOT}/references/tracker-sync.md § "Cursor Management".
Read .sdd/issues/_meta.json. If last_sync is within the last 5 minutes, skip the sync silently.
Otherwise, invoke per-tracker fetch+normalize per ${CLAUDE_PLUGIN_ROOT}/references/tracker-sync.md. Print: "Syncing N issues from {tracker}…".
On sync failure, surface a one-line warning per tracker-sync.md § "Failure Modes and Degradation" and proceed with live tracker queries (the pre-v5 path) for this run. Do NOT block; work dispatch is the user's primary intent.
Discover workable issues: Search the tracker for open issues:
Projects if present).Filtering rules:
Skip epics: Issues labeled epic or titled "Implement ..." are grouping issues, not implementation work.
Skip issues without ### Branch sections: These lack branch naming conventions. If any are found, suggest /sdd:enrich to add them and report which issues were skipped.
Extract branch names: Parse the ### Branch section from each issue body to get the deterministic branch name (e.g., feature/42-jwt-token-generation).
Extract PR conventions: Parse the ### PR Convention section for close keywords and epic references.
Detect dependency ordering: If issue bodies reference dependencies or logical ordering, respect that order when queuing work. For Gitea, query native dependencies via GET /repos/{owner}/{repo}/issues/{index}/dependencies through tea api --login {login} to find unblocked stories. (Governing: SPEC-0011 REQ "Gitea Native Dependencies") For GitLab, read glab api --hostname {host} projects/{encoded-path}/issues/{n}/links and treat entries with link_type is_blocked_by as blockers.
Enforce dependency readiness (Governing: SPEC-0015 REQ "Issue Lifecycle Labels"): Before marking any issue as ready to work, check its dependencies:
Depends on #NNN, Blocked by #NNN, blocks: syntax, or any #NNN reference in a dependencies section.merged label, the issue is blocked and MUST NOT be started.Issue #274 is blocked by #273 (currently: in-progress)
merged state (detected during monitoring in step 11), automatically move newly-unblocked issues to the ready queue.If no workable issues are found after filtering, report why and suggest /sdd:plan (no issues at all) or /sdd:enrich (issues exist but lack branch sections).
Dry-run gate: If --dry-run is set, output a preview table and stop:
## Dry Run: /sdd:work [SPEC-0003 | issue batch]
Would create {N} worktrees with up to {max-agents} parallel agents.
| # | Issue | Branch | Status |
|---|-------|--------|--------|
| 1 | #42 JWT Token Generation | feature/42-jwt-token-generation | Ready |
| 2 | #43 Token Validation | feature/43-token-validation | Ready |
| 3 | #44 Token Refresh | feature/44-token-refresh | Blocked (depends on #42) |
| 4 | #47 Setup Auth Module | feature/47-setup-auth-module | Skipped (no ### Branch) |
### Skipped Issues
- #45 Implement Auth Service (epic — skipped)
- #47 Setup Auth Module (no ### Branch section — run `/sdd:enrich`)
No changes were made.
5a. Apply queued labels (Governing: SPEC-0015 REQ "Issue Lifecycle Labels"): For all workable issues that passed filtering, apply the queued label to indicate they are in the work queue. This provides visibility into the batch before agents start.
For GitHub:
gh issue edit {issue-number} --add-label "queued"
For Gitea: tea issues edit --login {login} --repo {owner}/{repo} --add-labels queued {number} (see shared-patterns.md § "Gitea Access").
For GitLab: glab issue update {issue-number} -R {owner}/{repo} --label queued (see shared-patterns.md § "GitLab Access").
Verify git state:
git status to check for uncommitted changes. If there are uncommitted changes, use AskUserQuestion to ask:
git fetch to ensure we have the latest remote state.Read worktree config from CLAUDE.md: Follow the "Config Resolution" pattern in the plugin's ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Config Resolution". Read the #### Worktrees subsection from the ### SDD Configuration section in CLAUDE.md. Defaults: Base Dir=.claude/worktrees/, Max Agents=3, Auto Cleanup=false, PR Mode="ready". CLI flags override config values.
7a. Resolve parallelism limit (Governing: SPEC-0015 REQ "Parallelism Limits", ADR-0017 Layer 1):
Determine the maximum number of concurrent agents using this precedence order (highest to lowest):
--max-agents N CLI flag (if provided)## SDD Configuration section, key max-parallel-agents (if present)Reading from CLAUDE.md: Scan the project's CLAUDE.md for a ## SDD Configuration section. Look for a line matching - **Max parallel agents**: N or max-parallel-agents: N. Parse the integer value. Example:
## SDD Configuration
- **Max parallel agents**: 2
- **Hotspot threshold**: 40%
Enforce the cap: The resolved limit MUST NOT be exceeded. When more stories are ready for parallel execution than the limit allows:
max-parallel-agents stories immediatelyin-review or merged), start the next queued storyReport before starting: Before spawning any agents, report the parallelism plan to the user:
Starting {N} of {M} ready stories ({Q} queued, max-parallel-agents: {limit})
Example: "Starting 4 of 8 ready stories (4 queued, max-parallel-agents: 4)"
Create team: Use TeamCreate to create a coordination team following the "Worker Coordination" protocol from ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Multi-Agent Team Protocols". The lead (you) manages the task queue and monitors progress. Spawn up to the resolved parallelism limit (from step 7a) worker agents using Task with subagent_type: "general-purpose".
If TeamCreate fails — or is not a registered tool on this harness — fall back to single-agent sequential mode: work through each issue one at a time in the main session using git worktree add for each.
Context hygiene in sequential mode (per ${CLAUDE_PLUGIN_ROOT}/references/harness-compat.md § "Single-Agent Sequential Fallback"): everything read in the lead session is resent on every later turn, and a multi-issue epic worked in one continuous session compounds fast. If subagents are available, dispatch each issue's implementation (and any post-PR diff verification) to a subagent that reports back a compact outcome — PR URL, verdict, few-line summary — never raw diffs or full file dumps. Without subagents, read diffs via --name-only + targeted excerpts, and after each issue carry forward only its outcome summary.
8a. Build sibling PR manifest (Governing: SPEC-0015 REQ "Pre-Flight PR Awareness"):
Before dispatching any workers, build a pre-flight awareness manifest so each agent knows what siblings are doing. Follow the Pre-Flight PR Awareness pattern in ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Pre-Flight PR Awareness".
Query the tracker for all open PRs in the current sprint, epic, or spec scope:
gh pr list --search "SPEC-XXXX" --json number,title,headRefName,body,url,labels --limit 50
GitLab: glab mr list -R {owner}/{repo} --search "SPEC-XXXX" --output json --per-page 100.
Include PRs from previous /sdd:work runs that haven't merged yet.
For each open PR, extract file ownership:
gh pr diff {number} --name-only
GitLab: glab api --hostname {host} projects/{encoded-path}/merge_requests/{number}/diffs --paginate --output ndjson | jq -r .new_path (glab mr diff has no file-list mode).
Scan the diff for new type/struct/interface/class/function definitions to identify shared artifacts.
For foundation PRs (labeled foundation), catalog all shared types and helpers with their file paths and merge status (merged = available on main, open = available after merge).
Assemble the Sibling PR Manifest with three sections:
This manifest is injected into each worker's context in step 9.4. Workers keep it current via live SendMessage broadcasts per the Worker Communication Protocol in ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Worker Communication Protocol".
Create worktrees and assign work: For each workable issue (respecting dependency order and max-agents concurrency):
9.1: Create the worktree.
git worktree add .claude/worktrees/{branch-name} -b {branch-name}
Use the base directory from CLAUDE.md Worktrees > Base Dir if set, otherwise .claude/worktrees/.
9.1a: Resolve a worktree collision (branch already exists). If the git worktree add above fails because {branch-name} exists — the usual mark of a prior invocation that was interrupted after starting work but before opening its PR — do NOT park the issue to backlog and do not dispatch a raw subagent outside this skill: the resume must go through this same path so it keeps the label lifecycle handling below (step 9.2) and on PR open. Decide from the branch's state:
git rev-list --count main..{branch-name}
git status --porcelain # inside the existing worktree, if one is present
main, or the worktree holds uncommitted changes: resume it. Check out the existing branch into the worktree (git worktree add .claude/worktrees/{branch-name} {branch-name}, no -b; if the worktree is already present, reuse it as-is). Dispatch the worker exactly as in a fresh run, with one addition in the message: a prior attempt on this issue was interrupted; the worktree holds its progress — inspect git log main..HEAD and the working tree, then continue the existing work to completion (tests, PR), never restarting from scratch. The issue's label lifecycle then runs unchanged: in-progress now, in-review when the worker opens the PR.main and a clean tree: reuse the branch as an empty start (check it out without -b and proceed as a fresh run).-b, as above, and proceed as a fresh run — the lead's Sibling PR Manifest (step 8a) already covers in-flight sibling PRs.9.2: Transition to in-progress (Governing: SPEC-0015 REQ "Issue Lifecycle Labels"): When assigning an issue to a worker, update its lifecycle state:
Set assignee: Assign the current user (or a worker identifier) to the issue.
gh issue edit {issue-number} --add-assignee "@me"
For Gitea, tea issues edit --login {login} --repo {owner}/{repo} --add-assignees {user} {number}. For GitLab, glab issue update {issue-number} -R {owner}/{repo} --assignee "+{username}", with {username} from glab api --hostname {host} user | jq -r .username.
Remove queued, apply in-progress: Each transition MUST remove the previous label before applying the new one.
gh issue edit {issue-number} --remove-label "queued" --add-label "in-progress"
GitLab: glab issue update {issue-number} -R {owner}/{repo} --unlabel queued --label in-progress.
9.3: Create a task using TaskCreate for each issue, with the issue details, branch name, and worktree path.
9.4: Assign to a worker using TaskUpdate with the worker's name as owner. Send the worker a message via SendMessage with all context needed to implement the issue.
Worker implementation protocol: Each worker receives and follows this protocol:
Worker receives:
### Branch section)### PR Convention section){constitution}), or nothing when the project has no constitution--no-tests flag)draft or ready)Worker steps:
1a. Worktree and stash safety. The worktree's stash stack is shared with the main checkout and every other worktree, and other sessions may push or pop it concurrently. Never use bare git stash or git stash pop in the worktree. If you need to shelve in-flight changes temporarily (for example, to take a clean-tree measurement), prefer a temporary WIP commit on the branch — git -C {worktree-path} commit -m "WIP #{issue-number}" — and fold it into your final commit in step 8 (amend or squash). If stashing is truly unavoidable, use git -C {worktree-path} stash push -u -m "sdd-{issue-number}-{short-tag}" and restore with git -C {worktree-path} stash apply <stash-sha> (never pop), dropping the stash only after the working tree is verified.
2a. Standing owner rules come before stopping.
When the acceptance criteria leave a decision open and this worker would otherwise park the issue or ask the owner, consult {constitution} before doing either:
Applies to list covers work (or which carries no such list) and whose decision answers that exact question: apply it, and record the citation line from references/constitution.md § "Citing a rule" for step 10.## Always ask the owner: stop and ask, even if another rule appears to cover it."Close enough" is not a match. A rule read and not applied is never cited, and the absence of a rule never justifies a guess. 3. Explore existing code in the worktree to understand the codebase structure.
3a. qmd-aware code pre-search before writing (v5.0.0+).
Before writing any new helper, type, struct, interface, or substantial code block, qmd-search {repo}-code for existing patterns. This complements the Sibling PR Manifest (which covers in-flight work) by surfacing patterns already on main that the worker would otherwise re-create. Mitigates the duplicate-implementation drift Foundation Story Detection (per ADR-0017) was designed to catch.
Construct a hybrid query per ${CLAUDE_PLUGIN_ROOT}/references/qmd-helpers.md § "Hybrid Retrieval":
lex: the planned helper / type / function name AND key terms from its purpose (e.g., for a parseUserID helper: "parseUserID parse user id authentication token")vec: a one-sentence framing of what the worker is about to implement (e.g., "extract a numeric user ID from an authenticated request context")intent: "/sdd:work — find existing helpers/types/patterns to import rather than recreate"collections: ["{repo}-code"]limit: 6, minScore: 0.4For each match above the threshold, the worker MUST:
TYPE_IMPORTED: #{issue} will import {TypeName} from {file-path} per the Worker Communication Protocol (already in shared-patterns.md) so the lead and siblings knowIf qmd returns zero matches above the threshold, proceed with the new implementation as planned.
On qmd unreachable / timeout per qmd-helpers.md § "Error Handling", surface the error to the lead via SendMessage and stop work on this issue. Per ADR-0024, the pre-v5 fallback ("just write new code") is gone in v5; the failure mode is "fix qmd, retry."
3b. Coordinate with sibling workers (Governing: SPEC-0015 REQ "Pre-Flight PR Awareness"). Follow the "Worker Communication Protocol" in ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Worker Communication Protocol". Before modifying any file:
CONFLICT_ALERT and wait for lead coordination instead of modifying it.SendMessage to all siblings:
FILE_CLAIM: #{issue} claiming {file-path} — before modifying any fileTYPE_CREATED: #{issue} created {TypeName} in {file-path} — after creating new shared types, structs, interfaces, or helpersAVAILABILITY: #{issue} PR merged — {artifact list} now on main — when the lead detects a sibling PR has mergedFILE_CLAIM from a sibling: add the file to the "avoid modifying" listTYPE_CREATED from a sibling: add the type to "Shared Types Available" and import it rather than recreatingAVAILABILITY from lead: move artifacts from "in-progress" to "available on main" and lift file avoidance for those filesImplement changes to satisfy the acceptance criteria.
If spec context was provided, leave governing comments in the code per ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Governing Comment Format":
// Governing: ADR-XXXX (short description), SPEC-XXXX REQ "Requirement Name"
Run tests (unless --no-tests). If tests fail, attempt to fix (max 2 fix attempts). If still failing after 2 attempts, report blocked with details.
6a. Disposable runtime resources: if satisfying the acceptance criteria requires standing one up — a simulator/emulator, a container, an ephemeral database — follow shared-patterns.md § "Disposable Runtime Resources": tag it with this issue's number, stop it rather than tear it down when your work is done, and never touch a resource that is not tagged with this issue's number.
Assess PR size before creating. Run git -C {worktree-path} diff --stat to see the scope of changes. Use judgement about whether this warrants a standalone PR:
If the implementation is too small to justify its own PR, send the lead a bundle request:
BUNDLE_REQUEST: #42 implementation is trivially small (8 lines changed, comments only). Requesting additional issues to bundle into this branch before opening a PR.
Wait for the lead to either assign additional issues or confirm proceeding with a small PR (e.g., queue is exhausted). If additional issues are assigned, return to step 2 for each, implementing them in the same worktree, then proceed with a combined commit and PR covering all bundled issues. 7a. Validate diff against protected paths (Governing: SPEC-0015 REQ "Design Document Isolation"): Before staging, check for modifications to protected paths defined in step 3b:
git -C {worktree-path} diff --name-only
For each modified file, check if it falls under a protected path ({spec-dir}, {adr-dir}, {constitution-path} when a constitution is configured, root CLAUDE.md, .claude-plugin-design.json).
If protected files are found:
git -C {worktree-path} checkout -- {protected-file}
### Deferred Design Doc Updates section in the PR body listing each deferred change:
### Deferred Design Doc Updates
- `docs/adrs/ADR-0005.md`: Update status from "proposed" to "accepted"
- `docs/openspec/specs/auth/spec.md`: Add new requirement for token rotation
Exception: Governing comments in source code files are NOT protected — they are inline code annotations, not design document modifications. Only files under the protected paths listed in step 3b are subject to this validation.
Stage and commit changes:
git -C {worktree-path} add .
git -C {worktree-path} commit -m "{descriptive message}\n\nImplements #{issue-number}\nGoverning: SPEC-XXXX"
If multiple issues were bundled, list all of them in the commit message.
Push the branch:
git -C {worktree-path} push -u origin {branch-name}
Create a PR using the code host's tools or CLI (the tracker's, when tracker and code share a host):
### Owner Rules Applied section listing one Owner rule applied: Rule N — {title} line per rule actually applied (Governing: ADR-0037). Omit the section when nothing was applied; never write it as empty.${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "PR Close Keywords" → "Split-Host"): never put a close keyword with a tracker number in the body — write Tracker: {tracker-owner}/{tracker-repo}#{issue-number} for each bundled issue instead--draft was setTransition to in-review (Governing: SPEC-0015 REQ "Issue Lifecycle Labels"): After the PR is created, update lifecycle labels:
gh issue edit {issue-number} --remove-label "in-progress" --add-label "in-review"
GitLab: glab issue update {issue-number} -R {owner}/{repo} --unlabel in-progress --label in-review.
If multiple issues were bundled into one PR, transition ALL bundled issues to in-review.
Report outcome to lead via SendMessage: success (with PR URL and list of bundled issues) or failure (with details).
Monitor, queue, and lifecycle transitions: The lead tracks worker progress (Governing: SPEC-0015 REQ "Parallelism Limits", SPEC-0015 REQ "Issue Lifecycle Labels"):
max-parallel-agents limit from step 7a. Track the count of active agents at all times.merged on PR merge: When a worker reports success and the PR is subsequently merged (either via /sdd:review or manually), transition the issue:
gh issue edit {issue-number} --remove-label "in-review" --add-label "merged"
GitLab: glab issue update {issue-number} -R {owner}/{repo} --unlabel in-review --label merged.
If the work session itself does not merge PRs, the merged transition will be handled by /sdd:review or the next /sdd:work invocation that detects merged PRs.merged, trigger a narrow re-sync of {repo}-code so the qmd index reflects the newly-merged code. Use the canonical update pattern from ${CLAUDE_PLUGIN_ROOT}/references/qmd-helpers.md § "Update Patterns". Best-effort and silent on success. On failure, append a one-line warning to the run log ("Index refresh failed for {repo}-code after merging PR #{N} — run /sdd:index update manually") but the merged-label transition still proceeds.merged, re-check the deferred queue from step 4. For each deferred issue, re-query its dependencies. If ALL dependencies now have the merged label, move the issue to the ready queue and start it if an agent slot is available.max-parallel-agents active agents.in-progress label (do NOT transition failed issues to merged).BUNDLE_REQUEST, check the issue queue for additional issues that could be bundled into the same branch. If available (and not blocked by dependencies), assign them to the same worker with instructions to implement in the same worktree before creating a PR. If the queue is exhausted or all remaining issues are blocked, tell the worker to proceed with the small PR as-is.11a. Compute topological merge order (Governing: SPEC-0015 REQ "Topological Merge Ordering"):
After all workers have completed and PRs are in in-review state, compute the optimal merge order before merging begins. Follow the Topological Merge Ordering pattern in ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Topological Merge Ordering".
Collect file lists for each PR:
gh pr diff {number} --name-only
GitLab: the merge_requests/{number}/diffs call from step 8 above.
Build file overlap graph. For each pair of PRs, compute the intersection of modified files. PRs that share files have an ordering dependency.
Classify PRs into tiers:
foundation with dependents — merge after Tier 0Detect circular dependencies. If the overlap graph contains a cycle, report it to the user and request manual resolution:
Circular file dependency detected between PRs #X and #Y (both modify {files}).
Please specify which should merge first.
Do NOT proceed with merging the cycle until the user resolves it.
Offer PR stacking when a direct dependency exists (PR B depends on PR A via issue body AND they share files):
PR #143 depends on PR #141. Stack #143 on top of #141's branch to avoid rebase conflicts? (Y/n)
Report the merge order to the user before merging:
### Merge Order
| Order | PR | Issue | Overlapping Files | Action |
|-------|----|-------|-------------------|--------|
| 1 | #142 | #42 Isolated feature | (none) | Merge |
| 1 | #145 | #45 Another isolated | (none) | Merge |
| 2 | #141 | #41 Foundation types | main.go, sync.go | Merge, then rebase remaining |
| 3 | #143 | #43 Depends on #141 | sync.go | Rebase, then merge |
| 4 | #144 | #44 Touches everything | main.go, sync.go, config.go | Rebase, then merge |
Proceed with this merge order? (Y/n)
Execute the merge sequence (after user approval):
git fetch origin main
git -C {worktree-path} rebase origin/main
git -C {worktree-path} push --force-with-lease
merged label per step 11's lifecycle rulesCleanup and report: After all issues are processed:
12.1: Shut down team. Send shutdown_request to all workers via SendMessage.
12.2: Offer worktree cleanup. If CLAUDE.md Worktrees > Auto Cleanup is true, clean up worktrees for successfully-PRed issues automatically. Otherwise, use AskUserQuestion:
${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Worktree Cleanup" — git worktree remove alone leaves the branch ref behind permanently, so the branch delete step is not optional. Note that at this point the issue's PR is open and unmerged; the branch is deletable only because git push -u in step 11 put every commit on the remote, and the pattern's step 3 is what keeps a branch with unpushed work from being lost.12.3: Batch deferred design doc updates (Governing: SPEC-0015 REQ "Design Document Isolation"):
After all sprint PRs are merged, collect deferred design document updates from all PR bodies:
### Deferred Design Doc Updates section.docs/sprint-{N}-design-updates (or docs/design-updates-{date} if no sprint number is available)documentationThis ensures design documents are updated in a single, reviewable PR rather than risking merge conflicts from parallel modifications.
12.4: Final report.
## Work Complete: [SPEC-0003 | issue batch]
Implemented {N} of {M} issues using {agent-count} parallel agents.
### Results
| Issue | Branch | PR | Status |
|-------|--------|----|--------|
| #42 JWT Token Generation | feature/42-jwt-token-generation | #101 | in-review |
| #43 Token Validation | feature/43-token-validation | #102 | in-review |
| #44 Token Refresh | feature/44-token-refresh | — | Failed (in-progress) |
| #45 Session Revocation | — | — | Blocked by #44 |
### Failed Issues
- **#44 Token Refresh**: Tests failing after 2 fix attempts. Worktree preserved at `.claude/worktrees/feature/44-token-refresh` for manual pickup. Error: `TokenRefreshService.refresh() returns expired token in test_refresh_expired`.
### Blocked Issues
- **#45 Session Revocation**: Blocked by #44 (currently: in-progress). Will be unblocked when #44 reaches `merged`.
### Worktrees
- Cleaned up: 2
- Preserved (failed): 1
### Next Steps
- Run `/sdd:review` for automated spec-aware PR review and merge
- Fix failing issue #44 manually or re-run `/sdd:work 44`
- Run `/sdd:check` to verify implementation alignment
- Run `/sdd:audit` for comprehensive drift analysis
git worktree add Instead of EnterWorktreeEnterWorktree creates random branch names; we need deterministic names matching ### Branch conventions from issue bodies.EnterWorktree switches the session's working directory; the lead agent must stay in the main tree to coordinate.git worktree add gives full control over branch name and worktree location.| Condition | Behavior |
|---|---|
| Worker can't complete implementation | Reports failure to lead, worktree preserved for manual pickup |
| Tests fail after 2 retries | Worker reports blocked with error details, moves to next issue |
TeamCreate fails or is not a registered tool | Falls back to single-agent sequential mode with the context-hygiene rules from step 8 (subagent dispatch or --name-only + targeted excerpts; never full diffs inline) |
| No workable issues found | Suggest /sdd:plan (no issues at all) or /sdd:enrich (issues exist but lack ### Branch) |
| Uncommitted changes in main tree | Ask user whether to continue or commit first |
git worktree add fails (branch exists) | Resolve per step 9.1a: remote branch → check out without -b; local branch with real progress (commits ahead of main or uncommitted changes) → resume it through this skill's own dispatch so the label lifecycle applies; no progress → reuse as a fresh start. Never park the issue to backlog over a collision alone |
| Push fails (remote rejection) | Worker reports the error to lead; worktree preserved |
| PR creation fails | Worker reports the error to lead; branch is still pushed, user can create PR manually |
| Tracker not available | Suggest /sdd:plan to create issues first |
| Issue has no acceptance criteria | Worker uses the issue title and body as guidance, warns in PR description |
| Label creation fails (permissions) | Warn the user that lifecycle labels could not be created, continue without label management |
| Label transition fails | Log the failure but do NOT block work — label management is best-effort, implementation is primary |
| Dependency issue not found in tracker | Treat as unblocked (dependency may have been deleted or moved) with a warning |
| All issues are blocked by dependencies | Report the dependency graph and suggest resolving blocking issues first |
| Circular dependency detected | Report the cycle and refuse to start any issue in the cycle; suggest the user break the cycle manually |
| Sibling PR manifest query fails | Proceed without manifest — workers operate independently with live broadcasting only |
gh pr diff fails for a sibling PR | Omit that PR from the manifest with a warning; continue with available data |
| Rebase fails during merge ordering | Preserve the worktree, report conflicting files, skip that PR, and continue with remaining PRs |
| Circular file dependency in merge order | Report the cycle to the user and request manual merge order specification |
| All PRs have file overlaps (no Tier 0) | Start with foundation PRs, then proceed by overlap count (fewest overlaps first) |
| Worker modifies protected path (design docs) | Revert the protected file, record change in ### Deferred Design Doc Updates PR body section, continue with implementation |
| No deferred design doc updates after sprint | Skip batch PR creation — nothing to consolidate |
| Batch design doc PR conflicts | Report conflict to user for manual resolution |
/sdd:work can operate from the backlog aloneToolSearch); where it cannot, assume no tracker MCP tool is present and take the tracker CLI path (gh / glab / tea) — never assume specific tools are available (harness-compat § Capability Map)${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Config Resolution" to read configuration from CLAUDE.mdshared-patterns.md § "Constitution Resolution", pass it to every worker, and consult it at every ambiguous stop before parking or asking (worker step 2a, loop gate above). A project with no constitution sees no change in behavior and no mention of one (Governing: ADR-0037)## Always ask the owner, and MUST NOT apply a rule whose Applies to list excludes work (Governing: ADR-0037)Owner rule applied: Rule N — {title} in the PR body's ### Owner Rules Applied section, and MUST NOT cite a rule that did not change the outcome (Governing: ADR-0037)epic or titled "Implement ...") — only work on implementation issues### Branch sections and suggest /sdd:enrich--draft${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Governing Comment Format" in implemented code when spec context is available; omit when there is no specgit stash or git stash pop in a worktree — the stash stack is shared with the main checkout and all other worktrees; prefer a temporary WIP commit, or a tagged git stash push -u -m restored via git stash apply <sha> (worker step 1a)BUNDLE_REQUEST to the lead insteadBUNDLE_REQUEST by checking the queue for additional bundleable issues before telling the worker to proceed--dry-run MUST NOT create any worktrees, branches, or PRsTeamCreate fails or is absent, MUST fall back to single-agent sequential mode — never error out--name-only + targeted excerpts (per harness-compat § "Single-Agent Sequential Fallback"; friction report #201)is_blocked_by links the same waymax-parallel-agents concurrent agents (default: 4); resolve from CLI flag → CLAUDE.md → default (Governing: SPEC-0015 REQ "Parallelism Limits", ADR-0017 Layer 1)## SDD Configuration from CLAUDE.md for max-parallel-agents setting before falling back to defaultFILE_CLAIM before modifying any file — via SendMessage where the harness has team messaging, otherwise by recording the claim in the shared manifest the lead maintains (harness-compat § Capability Map)TYPE_CREATED after creating new types, structs, interfaces, or shared helpers — via SendMessage where the harness has team messaging, otherwise in that same shared manifestTYPE_CREATED MUST import the type rather than creating a duplicateFILE_CLAIM for a file they also need MUST send CONFLICT_ALERT and wait for lead coordinationqueued, in-progress, in-review, merged) exist before assigning work — using the try-then-create pattern (see ${CLAUDE_PLUGIN_ROOT}/references/shared-patterns.md § "Try-Then-Create Label Pattern") (Governing: SPEC-0015 REQ "Issue Lifecycle Labels")queued label to all workable issues upon discoveryqueued -> in-progress when an agent picks up an issue, removing the previous label firstin-progress -> in-review when a PR is created, removing the previous label firstin-review -> merged when a PR is merged, removing the previous label firstgh issue edit --add-assignee "@me", glab issue update --assignee "+{username}", or equivalent)Depends on #NNN, Blocked by #NNN, and blocks: syntaxmerged statemergedSendMessage where the harness has team messaging; otherwise the lead refreshes the manifest between steps and each worker re-reads it before touching filesAVAILABILITY when foundation or sibling PRs merge so workers can lift file avoidance directives — via SendMessage where the harness has team messaging, otherwise by refreshing the manifest each worker re-readsin-review state (Governing: SPEC-0015 REQ "Topological Merge Ordering"){spec-dir}, {adr-dir}, root CLAUDE.md, .claude-plugin-design.json) in feature branches (Governing: SPEC-0015 REQ "Design Document Isolation")git diff --name-only before staging and revert any protected files that were modified### Deferred Design Doc Updates section in the PR body{repo}-code for matches; if found above threshold (minScore 0.4), MUST import the existing implementation and broadcast TYPE_IMPORTED rather than recreate (Governing: ADR-0024, SPEC-0019 REQ "qmd-Smart Sprint Skills"){repo}-code after detecting a PR merge per Step 11 — best-effort, silent on success, one-line warning on failure (Governing: ADR-0026, SPEC-0019 REQ "Tier 1 Mutation-Aware Updates")When /sdd:work is invoked under /loop with the --loop flag (e.g. /loop /sdd:work --loop), the skill enters autonomous-mode and follows the contract below on every tick. Without --loop, the skill behaves exactly as the rest of this document specifies and creates no .sdd/loop/ artifacts (per SPEC-0020 REQ "Loop Mode Opt-In").
The runtime /loop skill is unchanged. --loop is a skill-side opt-in. /loop schedules ticks; everything inside a tick is the wrapped skill's concern.
When --loop is set, /sdd:work accepts the following additional flags. All are optional with the documented conservative defaults (per SPEC-0020 REQ "CLI Surface for Loop Controls"). Budgets are inclusive across the entire loop run, not per-iteration.
| Flag | Default | Purpose |
|---|---|---|
--loop | off | Opt into autonomous-mode |
--max-iterations N | 5 | Iteration ceiling across the run |
--max-prs N | 20 | Distinct-PR ceiling across the run |
--max-minutes N | 60 | Wall-clock ceiling across the run |
--max-dollars N | 25 | Dollar-cost ceiling; 0 disables condition #12 (estimate still tracked) |
--lock={skip|wait|force} | skip | Concurrency mode on lockfile contention |
--resume | off | Recover state from the most recent history.jsonl line |
--budget-file PATH | .sdd/loop/work.budget.json | Override the budget-file location |
--no-chain | off | Skip the post-PR chain (/sdd:review + /autofix-pr); restores legacy "open PR, stop" behavior. See "Post-PR Chain" below. |
The first write of budget.json records the active ceilings (per ${CLAUDE_PLUGIN_ROOT}/references/loop-primitives.md § First-write rule) so a later --resume cannot silently widen them.
Each tick follows this canonical flow (control flow diagram in docs/openspec/specs/loop-autonomous-mode/design.md):
.sdd/loop/work.lock per ${CLAUDE_PLUGIN_ROOT}/references/loop-primitives.md § Acquisition flow (skip / wait / force per --lock)..sdd/loop/work.budget.json; on first write, initialize ceilings, started_at, and rate_table_source (per ${CLAUDE_PLUGIN_ROOT}/references/loop-primitives.md § First-write rule).stop halts the loop.in-progress per "Concurrency invariants"), dispatch workers, open PRs.--no-chain or --dry-run).iterations_used, union prs_touched, accumulate tokens_in/tokens_out/agents_dispatched, recompute dollars_estimate, evaluate exit-time stop conditions 3 / 4 / 5 / 12..sdd/loop/work.history.jsonl (per ${CLAUDE_PLUGIN_ROOT}/references/loop-telemetry.md) and emit the stdout status block./loop schedule the next tick.The loop halts on any matching condition. The cause is recorded in stop_conditions_fired[] of the final history line.
| # | Condition | Behavior |
|---|---|---|
| 1 | Backlog empty (no unblocked, unworked, in-scope issues on entry) | Final report names empty queue; release lock; do NOT signal another tick (SPEC-0020 REQ "Backlog-Empty Stop") |
| 3 | iterations_used >= max_iterations (entry-time check) | stop_conditions_fired: ["iteration_budget"] (SPEC-0020 REQ "Iteration Budget Stop") |
| 4 | len(prs_touched) >= max_prs (deduplicated set; entry-time + after each PR open) | stop_conditions_fired: ["prs_touched_budget"] (SPEC-0020 REQ "PR-Touch Budget Stop") |
| 5 | minutes_elapsed >= max_minutes (clock anchored at started_at, persists across --resume) | stop_conditions_fired: ["wall_clock_budget"] (SPEC-0020 REQ "Wall-Clock Budget Stop") |
| 6 | Same issue/PR failed twice consecutively with the same root cause | Fire the Repeated-Failure gate (does NOT silently halt) (SPEC-0020 REQ "Repeated-Failure Stop") |
| 7 | Issue-dependency analysis (per SPEC-0015 Layer 2) detects a cycle | Halt and surface the cycle's edges; do NOT attempt automatic break (SPEC-0020 REQ "Dependency-Cycle Stop") |
| 8 | User interrupt (Ctrl-C / session close / explicit /loop stop) | Drain in-flight workers (no new dispatch), release lock, emit final report, no half-states (SPEC-0020 REQ "User Interrupt Stop") |
| 9 | Lockfile holds a live PID under --lock=skip | Emit one-line skip note; do NOT increment counters (SPEC-0020 REQ "Lockfile Contention Skip"). --lock=wait blocks bounded by max_minutes; --lock=force fires the Force-Unlock gate. |
| 10 | Any prior gates[] entry recorded answer == "stop" | "Loop already stopped at gate {name} in iteration {N}"; release lock; do NOT increment counters (SPEC-0020 REQ "Prior-Gate-Stop Honor") |
| 11 | qmd unreachable for 2 consecutive iterations | Halt with the ADR-0024 remediation message; the wrapped skill signals via stderr token qmd-unreachable OR exit code EX_QMD_UNREACHABLE=78; any successful iteration resets qmd_failures_consecutive to 0 (SPEC-0020 REQ "qmd-Unreachable Stop") |
| 12 | dollars_estimate >= max_dollars (and max_dollars > 0) | "Cost budget reached: $X / $Y"; --max-dollars 0 disables the stop but dollars_estimate is still tracked (SPEC-0020 REQ "Cost Budget Stop") |
Condition #2 (terminal PR state) does NOT apply to /sdd:work — it is a /sdd:review --loop --pr <N> condition.
The wrapped skill signals qmd-unreachable using either of these signals (per SPEC-0020 REQ "qmd-Unreachable Stop"):
qmd-unreachable (per ${CLAUDE_PLUGIN_ROOT}/references/qmd-helpers.md § "Error Handling")EX_QMD_UNREACHABLE = 78 (matches BSD sysexits.h EX_CONFIG)The loop reads exit status first; on non-zero, scans stderr for the sentinel as a fallback. Either signal is sufficient. On detection, increment qmd_failures_consecutive. On any successful iteration, reset to 0. On increment to 2, condition #11 trips.
All gates are re-evaluated on every tick (per SPEC-0020 REQ "Gates Are Not Debounced Across Iterations") — the skill MUST NOT cache or reuse a prior iteration's answer to suppress a current iteration's gate. Each invocation is captured verbatim in the iteration's gates[] array per ${CLAUDE_PLUGIN_ROOT}/references/loop-telemetry.md.
| Gate | Trigger | Prompt template | Options |
|---|---|---|---|
| Backlog Drift | Unblocked-issue snapshot differs from the prior iteration's recorded snapshot | "Backlog changed since last iteration. Re-propose the next batch?" | re-propose, continue, stop |
| Ambiguous Criteria | Issue lacks ### Acceptance Criteria OR section contains TBD/TODO markers | "Issue #{N} has ambiguous criteria. Skip, escalate, or proceed with my best interpretation?" | skip, escalate, proceed, stop |
| Budget Escalation (80%) | One or more active budgets cross 80% on this tick | "Approaching {budget(s)} ({used}/{total} each). Continue, raise ceiling(s), or stop?" — combined into a single prompt across all simultaneously-tripped budgets | continue, raise, stop |
| Force-Unlock | --lock=force AND lockfile is present | "Force-unlock previous iteration's lock? This may corrupt in-flight work." | yes, no, stop |
| Repeated Failure | Same issue/PR failed in two consecutive iterations with the same root cause | "Issue/PR #{N} failed twice with: {root-cause}. Skip, retry once more, or stop the loop?" | skip, retry, stop |
| Resume-Divergence (resume only) | A tracked_prs[] entry's head_sha_at_iteration_end does not match the live remote HEAD | "PR #{N} has diverged since the prior iteration crashed — re-attach, skip, or stop the loop?" | re-attach, skip, stop |
Note: the Post-Feedback Merge gate is a /sdd:review --loop gate; it does NOT fire on the work side. Backlog-Drift is a work-side-only gate.
The Ambiguous Criteria gate fires on a question the owner may already have answered. Before firing it, consult {constitution} (resolved in step 0a, and re-resolved on a tick that follows a --resume, since the file may have changed between runs):
work: the gate does not fire. The worker implements under that rule and cites it in the PR body per worker step 2a and step 10. No gates[] entry is recorded, because the gate never fired — the citation, not a gate record, is the audit trail.## Always ask the owner: the gate fires as documented, whatever else the rules say.Rules resolve ambiguity. They never resolve a budget, lockfile, dependency-cycle, qmd-unreachable, or interrupt condition: every other gate and stop condition in this section is unaffected by a constitution.
When two or more budgets cross 80% in the same tick, the gate fires once with a combined message listing every tripped budget (per SPEC-0020 REQ "Budget-Escalation Gate"). When any budget reaches 100% in the same tick that another crosses 80%, the 100%-stop wins (conditions 3 / 4 / 5 / 12 take precedence) and the gate is suppressed. Pseudocode in docs/openspec/specs/loop-autonomous-mode/design.md § Multi-budget 80% gate batching.
/sdd:work --loop MUST NOT pick up an issue already labeled in-progress by a sibling iteration's worktree (per SPEC-0020 REQ "Concurrency Invariants for /sdd:work"). The check happens during workable-issue discovery in each iteration, before dispatch. The iteration MUST NOT clear or contest the label — it skips the issue and picks the next one.
This invariant is independent of the lockfile (which scopes "is another iteration running?"). The label invariant scopes "is this issue already being implemented somewhere?".
When the loop halts for any reason, the wrapped skill MUST emit a final report before lockfile release (per SPEC-0020 REQ "Final Report on Stop"). The report covers:
.sdd/loop/work.budget.json and .sdd/loop/work.history.jsonl for further inspectionThe lockfile is released after the report is emitted so a stale-lock reaper on a subsequent tick sees a complete telemetry trail.
After each PR opened in an iteration, /sdd:work invokes the post-PR chain — a bounded architectural review pass (/sdd:review, exactly one round per ADR-0010) followed by an open-ended CI / conflict / comment maintenance pass (/autofix-pr, the Claude Code built-in). The chain is unconditional within an iteration unless --no-chain or --dry-run is set (per SPEC-0020 REQ "Post-PR Chain Invocation"). It also runs on single-shot /sdd:work invocations — not just under --loop — so single-PR sessions get the same autonomy benefit (per ADR-0030 sub-decision 1).
This contract applies to both --loop and non-loop invocations of /sdd:work. In non-loop mode, the worker that opens a PR follows the same chain — and the per-PR history.jsonl line still records the chain outcome fields (per SPEC-0020 REQ "Chain Outcome Telemetry"; the file is single-line in non-loop mode rather than appended).
For each PR a worker opens in an iteration:
Check --no-chain. If set: log "Chain skipped for PR #{N} (--no-chain)"; record chain_invoked: false in the iteration's history.jsonl line; omit review_outcome, autofix_pr_invoked, and autofix_pr_invocation_status (per SPEC-0020 REQ "Chain Outcome Telemetry"); proceed to next PR (or exit iteration body).
Check --dry-run. If set: log "Would invoke /sdd:review on PR #{N}, then /autofix-pr"; record chain_invoked: false; omit the per-stage fields; proceed.
Invoke /sdd:review on PR #{N}, scoped to exactly one architectural round (ADR-0010 invariant):
"approve", "changes-requested" (resolved in round), "needs-human", or "errored" (qmd / infrastructure failure)Branch on review outcome:
| Outcome | Behavior |
|---|---|
"approve" | Proceed to step 5 (/autofix-pr invocation) |
"changes-requested" (resolved in round) | Proceed to step 5 |
"needs-human" | Apply the needs-human-follow-up label to PR #{N}; proceed to step 5 (the maintenance loop may still resolve CI flakes / conflicts independently of the architectural concern) |
"errored" | Apply the chain-failed-pre-autofix label to PR #{N}; skip step 5; record autofix_pr_invoked: false; omit autofix_pr_invocation_status (per SPEC-0020 REQ "Post-PR Chain Invocation"); proceed to next PR. The user can rerun /sdd:review after fixing the infrastructure issue (e.g., qmd unreachable per ADR-0024). |
Check /autofix-pr availability. The command is a Claude Code built-in (not a plugin-provided skill), so it only exists at all when running under Claude Code. Probe by attempting to introspect the runtime's available commands.
/autofix-pr is a Claude Code built-in and is not available on this harness — skipping the autofix stage"); record autofix_pr_invoked: false and autofix_pr_invocation_status: "unavailable"; proceed to next PR. Do NOT open a tracker issue — the absence is expected, not a version problem./autofix-pr is not available in this Claude Code build — install or upgrade Claude Code to enable post-PR autofix chain"); open a tracker issue tagged claude-code-version-required (deduped per /sdd:work invocation — open at most one such issue per session); record autofix_pr_invoked: false and autofix_pr_invocation_status: "unavailable"; proceed to next PR. PR creation is NOT blocked.Invoke /autofix-pr on PR #{N} fire-and-forget: /sdd:work does NOT wait for /autofix-pr to terminate; the built-in runs in its own background lifecycle managed by Claude Code, watching CI failures, review comments, and merge conflicts, and pushing corrective commits until the PR merges or is closed. /sdd:work returns once the invocation is accepted (the command was parsed and the lifecycle started).
autofix_pr_invoked: true, autofix_pr_invocation_status: "accepted".autofix_pr_invoked: true, autofix_pr_invocation_status: "errored"; emit a one-line warning. The PR is NOT blocked.Telemetry. The iteration's history.jsonl line records the four chain fields per the canonical schema in ${CLAUDE_PLUGIN_ROOT}/references/loop-telemetry.md:
{
"chain_invoked": true,
"review_outcome": "approve",
"autofix_pr_invoked": true,
"autofix_pr_invocation_status": "accepted"
}
In non-loop mode, the same fields are still emitted (a non-loop /sdd:work writes a single-line history.jsonl for that invocation; this is the trade documented in ADR-0030 sub-decision 6 to keep telemetry shape uniform).
| Failure | Behavior |
|---|---|
User passed --no-chain | Skip both invocations; record chain_invoked: false and omit per-stage fields. Legacy "open PR, stop" behavior. |
User passed --dry-run | Log "would invoke" for both; skip both invocations; record chain_invoked: false. |
/sdd:review returns "approve", "changes-requested" (resolved in round), or "needs-human" | Proceed to /autofix-pr |
/sdd:review returns "errored" (qmd unreachable per ADR-0024 sub-decision 2, or other infrastructure failure) | Apply chain-failed-pre-autofix label; skip /autofix-pr; record autofix_pr_invoked: false; omit autofix_pr_invocation_status |
/autofix-pr unavailable in current Claude Code build | Log warning; open one tracker issue with claude-code-version-required label per /sdd:work session (deduped); exit cleanly. PR is NOT blocked. |
/autofix-pr absent because the harness is not Claude Code | Log a one-line note and skip the stage; NO tracker issue (expected absence, not a version problem). PR is NOT blocked. |
/autofix-pr invocation parse error | Record autofix_pr_invocation_status: "errored"; one-line warning; PR NOT blocked. |
--loopEach loop iteration's per-PR chain is a self-contained unit (per ADR-0030 sub-decision 5). When a worker opens N PRs in parallel within a single iteration, the chain runs once per PR, in parallel across workers (one chain per PR). The chain invocations are NOT serialized across the workers in a single iteration.
ADR-0028's gates (backlog drift, ambiguous criteria, budget escalation, force-unlock, repeated failure) fire before the chain — they decide whether to start the iteration. Once an iteration runs and a PR is opened, the chain is unconditional within that iteration unless --no-chain is set. There is no per-PR gate that interposes between PR creation and /sdd:review; the architectural review is the bounded round (ADR-0010), and the post-feedback-merge gate (/sdd:review --loop only) is the only human-mediated checkpoint that can pause the chain's eventual merge path.
Each chain invocation is metered by its own tool's cost surface (per ADR-0030 sub-decision 6). /sdd:work does not double-count /sdd:review's tokens or /autofix-pr's tokens against its own budget; those costs accrue under the invoked command's accounting. What /sdd:work records in history.jsonl is the event of invocation (chain_invoked, review_outcome, autofix_pr_invoked) so users correlating cost spikes after the fact can map them back to the iteration that opened the PR. The chain is therefore visible in telemetry as an event but not as a token line item.
/sdd:review is invoked exactly once by /sdd:work per PR (per chain invocation). The chain does NOT loop /sdd:review. A second architectural round on the same PR is forbidden by ADR-0010 and forbidden here. If the user wants another round, they invoke /sdd:review directly (or, under --loop, the next iteration's /sdd:review --loop invocation does its own one round on that PR).
This contract IS the implementation of the chain; before story #148 lands, /sdd:work opens a PR and stops (legacy behavior). Once #148 merges, the chain is the new default unless --no-chain is set.
--resume recovers state from the most recent history.jsonl line per ${CLAUDE_PLUGIN_ROOT}/references/loop-telemetry.md § Resume Contract. Counters are restored; gate evaluations are recomputed; the lockfile is treated as stale per the PID-liveness rule; tracked_prs[] and active_worktrees[] are reconciled by SHA equality with no external probing substituted.
Every iteration appends a line to .sdd/loop/work.history.jsonl and emits the stdout status block. Skipped ticks (lockfile contention) MUST also append a line with outcome: "skipped_lock" and MUST NOT increment iterations_used. Schema details in ${CLAUDE_PLUGIN_ROOT}/references/loop-telemetry.md.
/loop skill — re-invocation cadence is /loop's concern; the wrapped skill enforces only intra-iteration semantics${CLAUDE_PLUGIN_ROOT}/references/loop-primitives.md § Acquisition flow--resume cannot silently widen themprs_touched (a PR re-touched across iterations counts once)history.jsonl line on every iteration including skipped ticksiterations_used for a skipped tickgates[] entry recorded answer == "stop" (condition #10)in-progress by a sibling iteration's worktree (concurrency invariant)qmd-unreachable OR exit code EX_QMD_UNREACHABLE=78 (the wrapped skill emits; the loop layer detects)--no-chain or --dry-run is set/sdd:work invocations (single-shot mode); the chain is not gated by --loop (per ADR-0030 sub-decision 1)/sdd:review exactly once per PR per chain invocation (preserves ADR-0010's bounded one-round invariant)/sdd:review exits with review_outcome: "errored" THEN MUST apply the chain-failed-pre-autofix label, MUST NOT invoke /autofix-pr, and MUST omit autofix_pr_invocation_status from the per-iteration telemetry/sdd:review exits with "needs-human" THEN MUST apply the needs-human-follow-up label AND proceed to /autofix-pr (the maintenance loop may resolve CI / conflicts independently)/autofix-pr is unavailable on Claude Code THEN MUST log a warning AND open a tracker issue with the claude-code-version-required label (deduped at one issue per session) AND exit cleanly (PR creation MUST NOT be blocked); WHEN the harness is not Claude Code THEN MUST skip the stage with a one-line note and MUST NOT open a tracker issue/autofix-pr invocation MUST be fire-and-forget — /sdd:work MUST NOT wait for /autofix-pr to terminate/sdd:work's budget — costs of /sdd:review and /autofix-pr accrue under their own tool accounting; /sdd:work records only the invocation events in history.jsonlWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub joestump/claude-plugin-sdd --plugin sdd22 skills in this plugin
/adrCreate a new Architecture Decision Record (ADR) using MADR format. Use when the user wants to document an architectural decision, says "create an ADR", "we need an ADR for", or discusses a decision that should be recorded./auditComprehensive audit of design artifact alignment across the project. Use when the user says "audit the architecture", "full drift report", or wants a thorough review of spec compliance and ADR adherence./checkQuick-check code against ADRs and specs for drift. Use when the user says "check for drift", "does this match the spec", or wants a fast alignment check on a specific file or directory./discoverDiscover implicit architectural decisions and spec-worthy subsystems in an existing codebase. Use when the user says "discover architecture", "what decisions exist in this code", "bootstrap ADRs", or wants to reverse-engineer design artifacts from code./docsGenerate a documentation site from your ADRs and specs. Use when the user says "generate docs", "create a docs site", or wants to publish their architecture decisions./enrichRetroactively add branch naming and PR convention sections to existing issue bodies. Use when the user says "add branch names to issues", "enrich issues", or wants to add developer workflow conventions to existing issues.Other plugins' skills for the same job