Corca Workflow Framework — consolidated hooks and skill orchestration for structured development sessions
- version
- 1.0.1
- GitHub stars
- 75
Install
/plugin install cwf@corca-pluginsRun it inside Claude Code after adding the marketplace with /plugin marketplace add corca-ai/claude-plugins.
Contents
Discovered from sourceSkills 13
Clarify
Resolve ambiguity before planning so implementation starts from explicit decisions, not assumptions.
Quick Start
cwf:clarify <requirement> # Research-first (default)
cwf:clarify <requirement> --light # Direct Q&A, no sub-agents
Mode Selection
Before entering Default or --light mode, assess clarify depth based on input specificity:
- If
next-session.mdexists in the active session directory or current workspace, read it as optional prior-session context. - Always parse the user's task description (required input).
- Check if the combined input provides: target file paths, expected changes per file, and BDD-style success criteria.
- Apply this heuristic:
| Input specificity | Clarify depth | Rationale |
|---|---|---|
| All 3 present (files + changes + criteria) | AskUserQuestion only — ask 2-3 binary/choice questions for remaining ambiguities, skip Phases 2-2.5 | Prior session retro effectively served as clarify |
| 1-2 present | --light mode — iterative Q&A without sub-agents | Partial clarity, direct questions suffice |
| None present (vague requirement) | Default mode — full research + expert analysis | Scope is open, exploration needed |
This heuristic can be overridden by explicit --light flag or user instruction.
Default Mode
Phase 0: Update Live State
Use the live-state helper for scalar fields, then edit list fields in the resolved live-state file:
bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh set . \
phase="clarify" \
task="{requirement summary}"
live_state_file=$(bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh resolve)
Set live.key_files in {live_state_file} to files relevant to the requirement.
Phase 0.5: Resolve Session Directory
Resolve the effective live-state file, then read live.dir before any {session_dir} placeholder use:
live_state_file=$(bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh resolve)
session_dir=$(bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh get . dir)
session_dir: "{live.dir value from resolved live-state file}"
Phase 1: Capture & Decompose
- Record the original requirement verbatim
- Decompose into concrete decision points — specific questions that need answers before implementation can begin
- Frame as questions, not categories ("Which auth library?" not "Authentication")
- Focus on decisions that affect implementation
- Present the decision points to the user before proceeding
## Original Requirement
"{user's original request verbatim}"
## Decision Points
1. {specific question}
2. {specific question}
...
Phase 2: Research
Context recovery (before launching)
Apply the context recovery protocol to these files:
{session_dir}/clarify-codebase-research.md{session_dir}/clarify-web-research.md
Launch sub-agents simultaneously using the Task tool (only for missing or invalid results).
- Shared output persistence contract: agent-patterns.md § Sub-agent Output Persistence Contract.
Sub-agent A: Codebase Researcher
Task tool:
subagent_type: Explore
max_turns: 20
prompt: |
Read `{SKILL_DIR}/references/research-guide.md` and follow
**Section 1: Codebase Research** exactly.
Report evidence only — do not make decisions.
Decision points:
{list from Phase 1}
Write your complete findings to: {session_dir}/clarify-codebase-research.md
The file MUST exist when you finish. End your output file with the exact
line `<!-- AGENT_COMPLETE -->` as the last line.
Sub-agent B: Web Researcher
Task tool:
subagent_type: general-purpose
max_turns: 20
prompt: |
Read `{SKILL_DIR}/references/research-guide.md` and follow
**Section 2: Web / Best Practice Research** exactly.
Also follow the "Web Research Protocol" section in
`{CWF_PLUGIN_DIR}/references/agent-patterns.md` for tool order
and fallback behavior.
Report findings only — do not make decisions.
Decision points:
{list from Phase 1}
Write your complete findings to: {session_dir}/clarify-web-research.md
The file MUST exist when you finish. End your output file with the exact
line `<!-- AGENT_COMPLETE -->` as the last line.
Both sub-agents run in parallel. Wait for both to complete. Read the output files from session dir (not the in-memory Task return values).
Phase 2.5: Expert Analysis
Context recovery (before launching)
Apply the context recovery protocol to these files:
{session_dir}/clarify-expert-alpha.md{session_dir}/clarify-expert-beta.md
Launch two domain expert sub-agents simultaneously using the Task tool (only for missing or invalid results).
Expert selection:
- Read
expert_rosterfromcwf-state.yaml - Analyze decision points for domain keywords; match against each roster entry's
domainfield - Select 2 experts with contrasting frameworks — different analytical lenses on the same problem
- If roster has < 2 domain matches, fill remaining slots via independent selection (prioritize well-known figures with contrasting methodological approaches)
Expert α
Task tool:
subagent_type: general-purpose
max_turns: 12
prompt: |
Read {CWF_PLUGIN_DIR}/references/expert-advisor-guide.md.
You are Expert α, operating in **clarify mode**.
Your identity: {selected expert name}
Your framework: {expert's domain from roster or independent selection}
Decision points:
{list from Phase 1}
Research findings summary:
{summarized outputs from Phase 2 codebase + web research}
Analyze which decisions are most critical through your published framework.
Use web search to verify your expert identity and cite published work.
Output your analysis in the clarify mode format from the guide.
Write your complete findings to: {session_dir}/clarify-expert-alpha.md
The file MUST exist when you finish. End your output file with the exact
line `<!-- AGENT_COMPLETE -->` as the last line.
Expert β
Task tool:
subagent_type: general-purpose
max_turns: 12
prompt: |
Read {CWF_PLUGIN_DIR}/references/expert-advisor-guide.md.
You are Expert β, operating in **clarify mode**.
Your identity: {selected expert name — contrasting framework from Expert α}
Your framework: {expert's domain from roster or independent selection}
Decision points:
{list from Phase 1}
Research findings summary:
{summarized outputs from Phase 2 codebase + web research}
Analyze which decisions are most critical through your published framework.
Use web search to verify your expert identity and cite published work.
Output your analysis in the clarify mode format from the guide.
Write your complete findings to: {session_dir}/clarify-expert-beta.md
The file MUST exist when you finish. End your output file with the exact
line `<!-- AGENT_COMPLETE -->` as the last line.
Both expert sub-agents run in parallel. Wait for both to complete. Read the output files from session dir (not the in-memory Task return values).
--light mode: Phase 2.5 is skipped (consistent with --light skipping all sub-agents).
Phase 3: Classify & Decide
Read {SKILL_DIR}/references/aggregation-guide.md for full classification rules.
For each decision point, classify using three evidence sources: codebase research (Phase 2), web research (Phase 2), and expert analysis (Phase 2.5).
- T1 (Codebase-resolved) — codebase has clear evidence → decide autonomously, cite files
- T2 (Best-practice-resolved) — best practice consensus → decide autonomously, cite sources
- T3 (Requires human) — evidence conflicts, all silent, or subjective → queue
Constructive tension: When sources conflict, classify as T3. Expert analysis provides additional signal but does not override direct codebase or best-practice evidence.
Present the classification:
## Agent Decisions (T1 & T2)
| # | Decision Point | Tier | Decision | Evidence |
|---|---------------|------|----------|----------|
| 1 | ... | T1 | ... | file paths |
| 2 | ... | T2 | ... | sources |
## Requires Human Decision (T3)
| # | Decision Point | Reason |
|---|---------------|--------|
| 3 | ... | conflict / no evidence / subjective |
If zero T3 items: Skip Phases 3.5 and 4 entirely. Go to Phase 5.
Phase 3.5: Advisory (T3 only)
Context recovery (before launching)
Apply the context recovery protocol to these files:
{session_dir}/clarify-advisor-alpha.md{session_dir}/clarify-advisor-beta.md
Launch two advisory sub-agents simultaneously (only for missing or invalid results):
Advisor α
Task tool:
subagent_type: general-purpose
model: haiku
max_turns: 12
prompt: |
Read `{SKILL_DIR}/references/advisory-guide.md`. You are Advisor α.
Tier 3 decision points:
{list of T3 items}
Research context:
{codebase findings for these items}
{web research findings for these items}
Argue for the first perspective per the guide's side-assignment rules.
Write your complete findings to: {session_dir}/clarify-advisor-alpha.md
The file MUST exist when you finish. End your output file with the exact
line `<!-- AGENT_COMPLETE -->` as the last line.
Advisor β
Task tool:
subagent_type: general-purpose
model: haiku
max_turns: 12
prompt: |
Read `{SKILL_DIR}/references/advisory-guide.md`. You are Advisor β.
Tier 3 decision points:
{list of T3 items}
Research context:
{codebase findings for these items}
{web research findings for these items}
Argue for the opposing perspective per the guide's side-assignment rules.
Write your complete findings to: {session_dir}/clarify-advisor-beta.md
The file MUST exist when you finish. End your output file with the exact
line `<!-- AGENT_COMPLETE -->` as the last line.
Both advisors run in parallel. Wait for both to complete. Read the output files from session dir (not the in-memory Task return values).
Phase 4: Persistent Questioning (T3 only)
Read {SKILL_DIR}/references/questioning-guide.md for full methodology.
For each T3 item, use AskUserQuestion with:
- Research context: What codebase and web research found
- Advisor α's position: Their argument (brief)
- Advisor β's position: Their argument (brief)
- The question: With 2-4 concrete options from advisory perspectives
After each answer:
- Why-dig 2-3 times on surface-level answers (see questioning-guide.md)
- Detect tensions between this answer and previous answers
- Check for new ambiguities revealed by the answer → classify → repeat if T3
Phase 5: Output
## Requirement Clarification Summary
### Before (Original)
"{original request verbatim}"
### After (Clarified)
**Goal**: {precise description}
**Scope**: {what is included and excluded}
**Constraints**: {limitations and requirements}
### Expert Analysis
(Only in default mode, omitted in --light)
| Expert | Framework | Key Insight |
|--------|-----------|-------------|
| {Expert α name} | {framework} | {1-line summary of analysis} |
| {Expert β name} | {framework} | {1-line summary of analysis} |
### All Decisions
| # | Decision Point | Decision | Decided By | Evidence |
|---|---------------|----------|------------|----------|
| 1 | ... | ... | Agent (T1) | file paths |
| 2 | ... | ... | Agent (T2) | sources |
| 3 | ... | ... | Human | advisory context |
Save this clarified requirement to a project-appropriate location with a descriptive filename (required).
Completion tracking (after writing the required summary file):
- Run:
bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh set . clarify_completed_at="{ISO 8601 UTC timestamp}" - Run:
bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh set . clarify_result_file="{saved summary file path}"
This state is what cwf:impl Phase 1.0 checks as a pre-condition.
Follow-up suggestions (when CWF plugin is loaded):
cwf:review --mode clarify— Multi-perspective review of the clarified requirement before implementationcwf:handoff --phase— Generate a phase handoff document that captures HOW context (protocols, rules, must-read references, constraints) for the implementation phase. Recommended when context will be cleared before implementation, asplan.mdcarries WHAT but not HOW.
Present both suggestions. If context is getting large or the user is about to clear context, emphasize the phase handoff suggestion.
--light Mode
Fast, direct clarification without sub-agents. The original clarify behavior with added persistence.
Phase 1: Capture
- Record the requirement verbatim
- Identify ambiguities using the categories in questioning-guide.md
Phase 2: Iterative Q&A
Read {SKILL_DIR}/references/questioning-guide.md for methodology.
Loop using AskUserQuestion:
while ambiguities remain:
pick most critical ambiguity
ask with 2-4 concrete options
why-dig on surface-level answers (2-3 levels)
detect tensions with prior answers
check for new ambiguities
Phase 3: Output
## Requirement Clarification Summary
### Before (Original)
"{original request verbatim}"
### After (Clarified)
**Goal**: {precise description}
**Reason**: {the ultimate purpose or jobs-to-be-done}
**Scope**: {what is included and excluded}
**Constraints**: {limitations, requirements, preferences}
**Success Criteria**: {how to verify correctness}
### Decisions Made
| Question | Decision |
|----------|----------|
| ... | ... |
Save the summary to a project-appropriate location with a descriptive filename (required).
Completion tracking (after writing the required summary file):
- Run:
bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh set . clarify_completed_at="{ISO 8601 UTC timestamp}" - Run:
bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh set . clarify_result_file="{saved summary file path}"
This state is what cwf:impl Phase 1.0 checks as a pre-condition.
Expert Roster Update (when experts were used in Phase 2.5): Follow the Roster Maintenance procedure in {CWF_PLUGIN_DIR}/references/expert-advisor-guide.md.
Follow-up (when CWF plugin is loaded): Suggest cwf:handoff --phase if the user plans to clear context before implementation.
Rules
- Research first, ask later (default mode): Exhaust research before asking
- Cite evidence: Every autonomous decision must include specific evidence
- Respect the tiers: Do not ask about T1/T2; do not auto-decide T3
- Constructive tension: Conflicts between sources are signals, not problems
- Persistent but not annoying: Why-dig on vague answers, accept clear ones
- Preserve intent: Refine the requirement, don't redirect it
- Grounded experts: Best practice research must cite real published work
- Honest advisors: Advisory opinions argue in good faith, not strawman
- Expert evidence is supplementary: Expert analysis enriches classification but does not override direct codebase or best-practice evidence
References
- references/research-guide.md — Default sub-agent research methodology
- references/aggregation-guide.md — Tier classification rules
- references/advisory-guide.md — Advisor α/β methodology
- references/questioning-guide.md — Persistent questioning
- expert-advisor-guide.md — Expert sub-agent identity, grounding, and analysis format
Gather Context (cwf:gather)
Convert scattered sources into local, reusable artifacts so later phases reason over stable context instead of transient links.
Quick Reference
cwf:gather <url> URL auto-detect → download to OUTPUT_DIR
cwf:gather <url1> <url2> ... Multiple URLs
cwf:gather --search <query> Web search (Tavily)
cwf:gather --search --news <q> News search (Tavily)
cwf:gather --search --deep <q> Advanced depth search (Tavily)
cwf:gather --search code <query> Code/technical search (Exa)
cwf:gather --local <query> Local codebase exploration
cwf:gather Usage guide
cwf:gather help Usage guide
Why this exists:
- Normalize heterogeneous sources into local markdown artifacts that downstream skills can cite and diff reliably.
- Enforce source-access constraints explicitly (for example, Google Docs/Notion exports require public or published sharing).
Workflow
- Parse args → mode (URL |
--search|--local| help) - No args or "help" → print usage message and stop
- Execute the appropriate handler (see sections below)
- Resolve + prepare
OUTPUT_DIRbefore writes (URL and--localmodes) - Suggest follow-up: after URL gathering, suggest
--searchfor supplementary research if helpful
Before any file write, resolve output path in this order:
- Explicit CLI output-dir argument
- Service-specific output env var
CWF_GATHER_OUTPUT_DIR.cwf/projects(when writable)- workspace-local
gather-outputfallback directory
Then run:
mkdir -p "$OUTPUT_DIR"
If directory creation fails, stop that target with an explicit error and ask whether to provide a different output directory.
URL Auto-Detect
Scan input for all URLs. Classify each by pattern table (most specific first):
| URL Pattern | Handler | Script / Tool |
|---|---|---|
docs.google.com/{document,presentation,spreadsheets}/d/* | Google Export | scripts/g-export.sh |
*.slack.com/archives/*/p* | Slack to MD | scripts/slack-api.mjs + scripts/slack-to-md.sh |
*.notion.site/*, www.notion.so/* | Notion to MD | scripts/notion-to-md.py |
github.com/* | GitHub | gh CLI |
| Any other URL | Generic | scripts/extract.sh → WebFetch fallback |
Google Export
{SKILL_DIR}/scripts/g-export.sh <url> [format] [output-dir]
Prerequisites and format caveats live in references/google-export.md. TOON behavior for Sheets is defined in references/TOON.md, implemented via scripts/csv-to-toon.sh through g-export.sh.
Slack Export
URL format: https://{workspace}.slack.com/archives/{channel_id}/p{timestamp}
Parse thread_ts: p{digits} → {first10}.{rest} (e.g., p1234567890123456 → 1234567890.123456)
node {SKILL_DIR}/scripts/slack-api.mjs <channel_id> <thread_ts> --attachments-dir OUTPUT_DIR/attachments | \
{SKILL_DIR}/scripts/slack-to-md.sh <channel_id> <thread_ts> <workspace> OUTPUT_DIR/<output_file>.md [title]
After conversion, rename to a meaningful name from the first message (lowercase, hyphens, max 50 chars). Existing .md file: Extract Slack URL from > Source: line to re-fetch.
Prerequisites, token setup, and error recovery are defined in references/slack-export.md.
Notion Export
python3 {SKILL_DIR}/scripts/notion-to-md.py "$URL" "$OUTPUT_PATH"
Publication requirements and known limitations are defined in references/notion-export.md.
GitHub
For github.com URLs, use the gh CLI to extract content as markdown.
Prerequisite check: Verify command -v gh first. If gh is not available, fall through to Generic handler.
When gh is missing for a GitHub URL, do not silently downgrade only. Ask the user:
Install gh now (recommended)— runbash {SKILL_DIR}/../setup/scripts/install-tooling-deps.sh --install gh, then retry GitHub handler once.Continue with Generic handler— proceed with reduced metadata extraction.Skip this URL— do not process this GitHub URL in this run.
| URL type | Command |
|---|---|
| PR (path pattern: /pull/N) | gh pr view <url> --json title,body,state,author,comments --template '...' |
| Issue (path pattern: /issues/N) | gh issue view <url> --json title,body,state,author,comments --template '...' |
| Repository (owner/repo) | gh repo view <url> --json name,description,readme |
| Other GitHub URL | Fall through to Generic handler |
Save output to {OUTPUT_DIR}/{type}-{owner}-{repo}-{number}.md.
Template for PR/Issue (pass to --template):
# {{.title}}
State: {{.state}} | Author: {{.author.login}}
{{.body}}
{{range .comments}}---
**{{.author.login}}** ({{.createdAt}}):
{{.body}}
{{end}}
Generic URL
For URLs that don't match any known service, run this deterministic routine:
-
Resolve paths:
slug: sanitized title/url token (lowercase, spaces to hyphens, remove special characters, max 50 chars)output_md:{OUTPUT_DIR}/{slug}.mdoutput_meta:{OUTPUT_DIR}/{slug}.meta.yaml
-
Mandatory URL safety precheck (before any fetch/extract):
- Parse URL and derive:
scheme,host,resolved_ips(A/AAAA when available). - Evaluate block rules in this fixed order and store the first match as
blocked_reason_code:non_http_scheme— scheme is nothttporhttpslocalhost_target— host islocalhostor ends with.localhostloopback_target— host/IP in127.0.0.0/8or::1/128link_local_target— host/IP in169.254.0.0/16orfe80::/10private_ipv4_target— host/IP in RFC1918 ranges (10/8,172.16/12,192.168/16)private_ipv6_target— host/IP infc00::/7
- Default behavior for blocked URLs: do not run extraction.
- Required interactive override path:
Override once for this URL and continue(explicit user confirmation required)Skip this URL(default)
- If override is not explicitly confirmed, stop processing this URL and write failed metadata.
- Parse URL and derive:
-
Try Tavily extract first:
{SKILL_DIR}/scripts/extract.sh "<url>" > "{output_md}.tmp"- Success contract: exit code
0and temp file has non-whitespace content. - On success: move temp file to
{output_md}and set metadatamethod: tavily-extract. - If
TAVILY_API_KEYis missing or extraction fails, continue to Step 4.
- Success contract: exit code
-
WebFetch fallback (single fixed procedure):
- Run one Task call with this exact prompt contract:
Fetch this URL with WebFetch: <url> Return markdown only (preserve headings, lists, and links). If content cannot be retrieved, return exactly: WEBFETCH_EMPTY - If the result is not
WEBFETCH_EMPTY, save it to{output_md}and set metadatamethod: webfetch-fallback.
- Run one Task call with this exact prompt contract:
-
Empty-output handling:
- Treat as failure when
{output_md}is missing, whitespace-only, or the fallback response equalsWEBFETCH_EMPTY. - On failure, do not keep partial markdown output.
- Treat as failure when
-
Metadata capture (always required):
- Write
{output_meta}with at least:source_urlretrieved_at_utc(ISO 8601 UTC)handler: genericsafety_precheck:status(passed,blocked, oroverridden)blocked_reason_code(empty when passed)hostresolved_ips
method(tavily-extract,webfetch-fallback, ornone)status(successorfailed)output_file(empty when failed)failure_reason(when failed)
- For safety-blocked URLs without explicit override, set:
status: failedmethod: noneoutput_file: ""failure_reason: url_safety_blocked
- Write
--search Mode
Web and code search via external APIs.
Read references/query-intelligence.md before executing search — it contains the routing logic and parameter tables.
Subcommands
| Command | Backend | Script |
|---|---|---|
--search <query> | Tavily | scripts/search.sh |
--search --news <query> | Tavily (topic: news) | scripts/search.sh --topic news |
--search --deep <query> | Tavily (advanced) | scripts/search.sh --deep |
--search code <query> | Exa | scripts/code-search.sh |
Execution
- Read query-intelligence.md for routing and parameter decisions
- Route:
codeprefix or auto-detected code context →code-search.sh; otherwise →search.sh - Apply query intelligence (temporal, topic, token allocation) per reference
- Call script via Bash:
{SKILL_DIR}/scripts/search.sh [--topic news|finance] [--time-range day|week|month|year] [--deep] "<query>" {SKILL_DIR}/scripts/code-search.sh [--tokens NUM] "<query>" - Display results to user (scripts output formatted markdown)
Graceful degradation: If API key is missing, scripts print setup instructions to stderr. Do not stop at an error message only. Ask whether to configure now:
Configure now (recommended)— set the missing API key (TAVILY_API_KEYorEXA_API_KEY) in shell profile/process env, runcwf:setup --toolsif runtime dependencies are also missing, then retry the same search once. Do not rely oncwf:setup --envfor API key provisioning.Skip search for now— continue without search results.Show setup commands only— print exact export/setup commands. See references/search-api-reference.md.
Data Privacy
Queries are sent to external search services. Do not include confidential code or sensitive information in search queries.
--local Mode
Explore the local codebase for a topic and save structured results.
Task Output Contract
Input mapping:
query_raw: original--localargumentquery_slug: sanitized query token (lowercase, spaces to hyphens, remove special characters, max 50 chars)output_md:{OUTPUT_DIR}/local-{query_slug}.mdoutput_meta:{OUTPUT_DIR}/local-{query_slug}.meta.yaml
Task prompt contract:
Explore this codebase for: <query_raw>.
Use Glob, Grep, and Read to find relevant code, patterns, and architecture.
Return a structured markdown summary with:
## Overview
## Key Files
## Code Patterns
## Notable Details
Include file paths and line references where possible.
Write your complete output to: <output_md>
The file MUST exist when you finish and must end with: <!-- AGENT_COMPLETE -->
Web Debug Trigger (Autonomous)
If query_raw indicates browser-runtime debugging (for example: console error, DOM interaction failure, CDP/DevTools reproduction, viewport/mobile regression), require the Task agent to follow Web Debug Loop Protocol in addition to normal codebase exploration.
In this branch, the Task output must also include:
- reproducible browser steps used
- evidence artifact paths under
{OUTPUT_DIR}/debug/... - suspected source files and patch hypotheses (no code edits in gather)
Execution and failure handling:
- Run Task once using the prompt contract above.
- Validate output contract (
output_mdexists, has non-whitespace content, and ends with<!-- AGENT_COMPLETE -->). - If invalid or Task fails, retry once with the same input and explicit correction.
- If retry still fails, stop local gather for this query and report failure clearly.
Provenance metadata guidance:
- Always write
output_metawith:mode: local,query_raw,query_slug,subagent_type,attempts,status,output_md(if any),generated_at_utc. - When failed, include
failure_reasonand preserve diagnostics from the last Task run.
Configuration
| Variable | Default | Description |
|---|---|---|
CWF_GATHER_OUTPUT_DIR | .cwf/projects | Unified default output directory |
CWF_GATHER_GOOGLE_OUTPUT_DIR | (falls back to unified) | Google-specific override |
CWF_GATHER_NOTION_OUTPUT_DIR | (falls back to unified) | Notion-specific override |
TAVILY_API_KEY | — | Required for --search and generic URL extract |
EXA_API_KEY | — | Required for --search code |
Output dir priority: CLI argument > service-specific env var > CWF_GATHER_OUTPUT_DIR > .cwf/projects (if writable) > gather-output fallback directory
When a service-specific env var is not set, pass the unified output dir as a CLI argument to the handler script.
Supplementary Research
After gathering URL content, if best practices, reference documentation, or supplementary context would help the user, use the search scripts directly via Bash (not the WebSearch tool):
{SKILL_DIR}/scripts/search.sh "<query>"
Examples:
- Gathered a Google Doc describing a migration plan → search for best practices
- Gathered a Slack thread about an unfamiliar library → search for official docs
- Gathered a Notion page with a technical spec → search for implementation examples
Usage Message
Print when no args or "help":
Gather Context — Unified Information Acquisition
Usage:
cwf:gather <url> Gather content from URL (auto-detect service)
cwf:gather --search <query> Web search (Tavily)
cwf:gather --search --news <q> News search
cwf:gather --search --deep <q> Deep search
cwf:gather --search code <query> Code/technical search (Exa)
cwf:gather --local <query> Explore local codebase
Supported URL services:
Google Docs/Slides/Sheets, Slack threads, Notion pages, GitHub PRs/issues, generic web
Environment variables:
TAVILY_API_KEY Web search and URL extraction (https://app.tavily.com)
EXA_API_KEY Code search (https://dashboard.exa.ai)
Rules
- URL auto-detect priority: Match most specific pattern first (Google > Slack > Notion > GitHub > Generic)
- Graceful degradation: Missing API keys print setup instructions, don't crash
- Output dir hierarchy: CLI argument > service-specific env var > unified env var >
.cwf/projects(if writable) >gather-outputfallback directory - Data privacy: Do not include confidential code or sensitive information in search queries
- Sub-agent for --local: Always use Task tool, never inline exploration
- All code fences must have language specifier: Never use bare fences
- Missing dependency interaction: For missing required tools/keys, ask to install/configure now; do not only report unavailability.
- Web debug queries use shared protocol: Browser-runtime debugging requests in
--localmode must follow Web Debug Loop Protocol and persist evidence paths.
References
- references/google-export.md — Google Docs/Slides/Sheets export details
- references/slack-export.md — Slack thread export details
- references/notion-export.md — Notion page export details
- references/TOON.md — TOON format for spreadsheets
- references/search-api-reference.md — Tavily/Exa API parameters
- references/query-intelligence.md — Search routing and query enrichment
- agent-patterns.md — Shared Web Research and Web Debug protocols
Handoff
Preserve execution continuity across boundaries by generating handoff documents (next-session.md or phase-handoff.md) from project state and artifacts. Reads cwf-state.yaml for session history and master-plan.md (when available) for next-session scope.
Quick Start
cwf:handoff # Full: generate next-session.md + register
cwf:handoff --register # Register current session in cwf-state.yaml only
cwf:handoff --phase # Generate phase-handoff.md (HOW context for next phase)
Phase 1: Read Current State
1.1 Load Project State
Read cwf-state.yaml:
workflow.current_stageandworkflow.stages— where we aresessions— full session historysession_defaults— expected artifacts
1.2 Identify Current Session
Determine the current session by:
- Check for a session directory matching today's date in
.cwf/projects/ - Match against the most recent entry in
cwf-state.yamlsessions - If ambiguous, use AskUserQuestion with candidates
1.3 Read Session Artifacts
Read the current session's artifacts (if they exist):
-
plan.md— session scope and goals- Extract
## Deferred Actionssection if present (unchecked items:- [ ])
- Extract
-
lessons.md— accumulated learnings- Identify entries with unimplemented proposals (keywords: "구현은 별도 세션", "스코프 밖", "future", "deferred", "separate session", "out of scope")
-
retro.md— retrospective (if available)- Identify action items not yet addressed
-
Before consuming runtime session logs, run a best-effort Codex sync:
bash {CWF_PLUGIN_DIR}/scripts/codex/sync-session-logs.sh --cwd "$PWD" --quiet || true -
Runtime session logs (optional but recommended when available)
- Path:
.cwf/sessions/*.claude.md,.cwf/sessions/*.codex.md,.cwf/sessions/*.md - Use these as additional evidence when extracting unresolved items and collaboration signals
- Path:
Phase 2: Determine Next Session
2.1 With master-plan.md
If master-plan.md exists (search via Glob in .cwf/projects/):
- Read the session roadmap section
- Find the current session ID in the roadmap
- Extract the next session's definition: title, scope, dependencies
- Extract "Don't Touch" boundaries from master-plan context
2.2 Without master-plan.md
Fall back to cwf-state.yaml stages and user input:
- Read
workflow.stagesfor the stage progression - Determine what comes next based on current stage
- Use AskUserQuestion to get:
- Next session title
- Task scope description
- Key files to modify
master-plan.md is preferred but optional — the skill must work generically for any project using CWF.
Phase 3: Generate next-session.md
Write next-session.md in the current session artifact directory.
Use plan-protocol.md as the canonical source:
Handoff Document (milestone sessions)for required section structureExecution Contract (Mention-Only Safe)for mandatory contract clauses
Do not replicate or improvise template structure from recent examples.
3.1 Gather Inputs (by canonical section)
Prepare source material for each canonical section:
- Context Files to Read: from Phase 1/2 signals; include the repository AGENTS guide, plugin development cheatsheet, and the cwf-state session state file when present. If any is missing, note it explicitly and continue with available context. Include runtime logs when available. Include the Claude runtime adapter only when runtime behavior is relevant.
- Task Scope / Dependencies / Don't Touch: from the master plan artifact when present; otherwise from Phase 2 user answers and stage context.
- Lessons from Prior Sessions: selective aggregation from cwf-state summaries and relevant lesson artifacts only.
- Success Criteria: concrete BDD Given/When/Then tied to actual files or behaviors.
- Dogfooding: reference skill discovery mechanism (
skills/directory and trigger list), not a hardcoded skill catalog. - Execution Contract: include all minimum clauses from plan-protocol.md (mention-only execution, branch gate, commit gate, selective staging).
- Start Command: natural-language kickoff for next session execution.
3.2 Render next-session.md
Render the canonical 9 sections in protocol order (no section omission):
- Context Files to Read
- Task Scope
- Don't Touch
- Lessons from Prior Sessions
- Success Criteria
- Dependencies
- Dogfooding
- Execution Contract (Mention-Only Safe)
- Start Command
If next-session.md already exists, edit in place instead of overwriting.
3.3 Pre-Registration Validation
Before updating cwf-state.yaml, verify:
- all 9 canonical sections exist
- execution contract includes all required gates from
plan-protocol - phrasing remains behavior-executable (not advisory prose only)
Phase 3b: Generate phase-handoff.md (--phase mode)
When --phase flag is used, generate a phase-to-phase context transfer document instead of next-session.md. Phase handoff captures HOW (protocols, rules, must-reads, constraints) while plan.md captures WHAT (spec, steps, files).
Prerequisite flow: Phase 1.1 (Load Project State) and Phase 1.2 (Identify Current Session) execute normally. Phase 1.3 reads only lessons.md for protocol-relevant entries. Phase 2 is skipped entirely.
3b.1 Determine Phase Transition
Identify the source and target phases from context:
- Source phase: The current workflow phase (typically clarify, gather, or design discussion)
- Target phase: The next workflow phase (typically implementation)
If ambiguous, use AskUserQuestion:
What phase are you transitioning from and to?
Example: "clarify + design → implementation"
3b.2 Gather HOW Context
The agent executing this skill holds the clarify/gather context in its active conversation. Extract the following from conversation history and session artifacts:
- Context Files: Which files must the next phase agent read? Include the AGENTS guide and CWF state file when present. If one is missing, record the omission and continue with available context files. Add files that emerged as critical during the clarify/gather phase. Include CLAUDE.md only if runtime-specific behavior matters.
- When available, include runtime logs:
.cwf/sessions/*.claude.md,.cwf/sessions/*.codex.md,.cwf/sessions/*.md
- When available, include runtime logs:
- Design Decisions: Key choices made during clarify/gather with rationale. Source from clarification summaries, user decisions, and discussion outcomes
- Protocols: Rules and behavioral protocols discovered or established during the current phase. Source from
lessons.mdentries and explicit user instructions - Prohibitions: Explicit "do not" constraints. Source from user instructions, clarify decisions, and scope boundaries
- Implementation Hints: Practical guidance for the implementer — insertion points, patterns to follow, gotchas
- Success Criteria: BDD-format criteria. May reference
plan.mdcriteria or add phase-specific ones
3b.3 Generate phase-handoff.md
Write to .cwf/projects/{session-dir}/phase-handoff.md:
# Phase Handoff: {source phase} → {target phase}
> Source phase: {e.g., clarify + design discussion}
> Target phase: {e.g., implementation}
> Written: {date via `date +%Y-%m-%d`}
## Context Files to Read
1. `AGENTS.md` — shared project rules and protocols (cross-agent, when present)
2. `cwf-state.yaml` — current project state (when present)
3. {additional files from 3b.2}
## Design Decision Summary
{Key design choices with rationale from 3b.2}
## Protocols to Follow
{Numbered list of rules and behavioral protocols from 3b.2}
## Do NOT
{Bulleted list of explicit prohibitions from 3b.2}
## Implementation Hints
{Practical guidance from 3b.2}
## Success Criteria
```gherkin
{BDD criteria from 3b.2}
```
3b.4 User Review
Present the generated document to the user and ask for confirmation:
Phase handoff generated. Review the document above.
Use AskUserQuestion with options: "Confirm", "Edit and regenerate", "Cancel".
If "Edit and regenerate": apply user feedback, regenerate, and re-confirm.
Phase 4: Register in cwf-state.yaml
4.1 Ensure Current Session Entry Exists (Before Artifact Updates)
Resolve the current session entry in cwf-state.yaml before updating artifacts, summary, or completed_at:
- Find a matching session by
dir(primary), then byid(fallback). - If found, continue to 4.2/4.2b.
- If no match exists, run this explicit missing-entry branch:
- Draft a minimal session entry from known context:
id,title,dir,branch,artifacts: [](andstage_checkpoints: []when used in the project). - Ask user decision before insertion:
"Create missing session entry now" | "Edit fields first" | "Cancel registration". - If
"Create missing session entry now": append the draft entry tosessions, then continue to 4.2/4.2b. - If
"Edit fields first", run this loop:- Editable fields:
id,title,dir,branch. - Non-editable at creation:
artifacts: [](andstage_checkpoints: []when used in the project). - Validate before re-confirm:
idmust not duplicate an existing sessionid,dirmust not duplicate an existing sessiondir. - Re-confirm with AskUserQuestion:
"Insert this session entry with edited values?"with options:"Confirm insert" | "Edit again" | "Cancel registration". - If
"Edit again", repeat this step. - If
"Confirm insert", append the edited entry and continue to 4.2/4.2b. - If
"Cancel registration", stop registration and report that artifacts were not updated.
- Editable fields:
- If
"Cancel registration"from the initial decision: stop registration and report that artifacts were not updated.
- Draft a minimal session entry from known context:
4.2 Update Current Session (next-session mode)
- Add
next-session.mdto theartifactslist - Update
summaryif not already set - Set
completed_atto today's date (viadate +%Y-%m-%d) - Clear
livesection: set all scalar fields to""and lists to[]
4.2b Register Phase Handoff (--phase mode)
When --phase flag is used:
- Add
phase-handoff.mdto the current session'sartifactslist incwf-state.yaml - Do NOT set
completed_at— the session continues into the next phase - Do NOT update
summary— the session is not finished - Skip Phase 4b (Unresolved Items) — phase handoff is intra-session, not inter-session
- Skip Phase 5 (Checkpoint + Verify) —
check-session.shchecks session-end artifacts, not mid-session artifacts
4.3 Register-Only Mode
When --register flag is used, skip Phase 3 (generation) and only update the session entry in cwf-state.yaml.
Phase 4b: Unresolved Items
Propagate unresolved items from the current session to next-session.md to prevent context loss across session boundaries.
Sources
- From Deferred Actions (
plan.md): Extract unchecked items (- [ ]) from the## Deferred Actionssection - From Lessons (
lessons.md): Identify entries with unimplemented resolution proposals (keywords: "구현은 별도 세션", "스코프 밖", "future", "deferred", "separate session", "out of scope") - From Retro (
retro.md): Identify action items not yet addressed in this session
Output Format
Add a section to next-session.md after "Lessons from Prior Sessions":
## Unresolved Items from {current session ID}
### From Deferred Actions
- [ ] {item 1}
- [ ] {item 2}
### From Lessons
- [ ] {lesson title}: {unimplemented proposal}
### From Retro
- [ ] {action item description}
Scoping Rules
- Items relevant to the next session's scope: include directly
- Items outside the next session's scope: mark as "carry-forward" (e.g.,
- [ ] [carry-forward] {item}) - If no unresolved items exist, omit this section entirely
Phase 5: Lessons Checkpoint + Verify
5.1 Stage Checkpoints
Add handoff to cwf-state.yaml current session's stage_checkpoints list.
5.2 Run Verification
Execute the session artifact checker:
bash {CWF_PLUGIN_DIR}/scripts/check-session.sh --impl
Report results. If any artifacts are missing, list them and suggest fixes.
Rules
- Canonical template over recent example: Read
plan-protocol.mdHandoff Document section for format. Do not copy-paste a recentnext-session.md— derive from the protocol. - master-plan.md is preferred but optional: The skill must work for projects without a master plan by falling back to user input.
- Lessons aggregation is selective: Only include lessons relevant to the next session's task. Do not dump all historical lessons.
- Dogfooding section references discovery mechanism: Point to
skills/directory, not a hardcoded skill list. - Don't Touch inference is conservative: When uncertain, include the boundary. Better to over-protect than under-protect.
- BDD criteria are concrete: Reference actual files, features, or behaviors — not abstract qualities.
- cwf-state.yaml is SSOT: Read before modifying. Edit, do not overwrite.
- Never overwrite existing files: When a file already exists (e.g.,
next-session.mdfrom a prior run), use Edit to update — not Write. Write replaces entire file contents and destroys prior work. - All code fences must have language specifier: Never use bare fences.
- Unresolved items MUST be propagated: Deferred Actions, unimplemented lesson proposals, and unaddressed retro action items from the current session must appear in next-session.md. This prevents context loss across session boundaries.
- Phase handoff captures HOW, not WHAT: Do not duplicate plan.md content (steps, files to modify, goal). Focus on protocols, rules, constraints, and context files.
- Phase handoff is written by the phase that has context: The clarify/gather agent writes the phase handoff because it holds the HOW context. Do not defer to a later phase.
- Phase handoff is intra-session: It transfers context between phases within the same session.
completed_atis not set and Phase 4b/5 are skipped. - Draft-then-review: Always present the generated
phase-handoff.mdto the user for review before finalizing. - Execution contract is required:
next-session.mdmust include "Execution Contract (Mention-Only Safe)". - Contract must include branch+commit gates: Mention-only execution must define base-branch escape and meaningful commit unit rules.
- Missing session entry must be resolved first: Never update
artifacts,summary, orcompleted_atuntil a matchingsessionsentry exists (find-or-create with user confirmation).
References
- plan-protocol.md — canonical next-session structure and execution contract
- agent-patterns.md — Single pattern
HITL Review (cwf:hitl)
Insert deliberate human judgment into branch-diff review (<base>...HEAD) with resumable chunk state. Reviews file-by-file in meaningful chunks, pauses for user input each chunk, and persists state/rules so work can resume anytime.
Every chunk review must be presented as: Primary Chunk + Related Context + Causal Lens. Do not present isolated chunks.
Quick Reference
cwf:hitl [--base <branch>] [--scope docs|code|all]
cwf:hitl --resume
cwf:hitl --rule "<rule text>"
cwf:hitl --rules
cwf:hitl --state
cwf:hitl --close
State Model
Persist HITL runtime state under .cwf/projects/{session-dir}/hitl/ and keep cwf-state.yaml as pointer metadata only.
Canonical schema details (field contracts, status enums, and intent-resync state transitions) live in:
At minimum, keep these runtime artifacts:
.cwf/projects/{session-dir}/hitl/
hitl-scratchpad.md
state.yaml
rules.yaml
queue.json
fix-queue.yaml
events.log
Phase 0: Resolve Target
- Resolve base branch:
- explicit
--basewins - otherwise upstream default branch
- fallback
main
- explicit
- Resolve review scope (
docs|code|all, defaultall). - Build diff target:
git diff --name-only <base>...HEAD. - If
--resume, load fromlive.hitl.state_filepointer incwf-state.yaml.- If pointer is missing, fallback to latest
.cwf/projects/*/hitl/. - If both are missing, bootstrap HITL state interactively:
- ask whether to initialize under current
live.dir(recommended) or a new session dir - create
.cwf/projects/{session-dir}/hitl/artifacts - persist the resolved pointer back to
cwf-state.yamllive.hitl.state_file
- ask whether to initialize under current
- If pointer is missing, fallback to latest
Phase 0.5: Agreement Round (Default)
Before chunk review starts, run one agreement round in the same cwf:hitl flow (no extra mode/flag):
- Collect major decision points from available ship artifacts first (issue/PR body, review summaries, merge notes).
- Merge user-provided concerns/questions for this HITL run.
- Record agreements in
hitl-scratchpad.md:- agreed wording/policy decisions
- rationale
- open questions
- pending implementation items
- Apply high-impact agreed edits that should be reflected before chunk-by-chunk review.
- Immediately update
hitl-scratchpad.mdagain after edits:- mark items as
Applied/In progress - note what was changed and what remains
- refresh the
Updatedtimestamp
- mark items as
- Ask whether to start chunk review now.
When --resume is used, refresh the same scratchpad first (new agreements or changed priorities), then continue from cursor.
Phase 0.75: Intent Resync Gate
This gate prevents stale intent from leaking into the next chunk.
- Trigger condition: the user reports manual edits/overwrites, or HITL detects out-of-band file changes.
- On trigger, update the intent-resync fields in
state.yamlusing the contract in hitl-state-model.md, and append the trigger toevents.log. - Before presenting any next chunk, check
intent_resync_required. - If
true, run resync first:- re-read the changed target files
- summarize what changed and confirm updated intent with the user
- update
hitl-scratchpad.mdwith the confirmed intent delta - clear the resync gate and set
last_intent_resync_atper state model contract
- Only continue chunk review after the flag is cleared.
Phase 1: Build Deterministic Queue
- Build file queue from diff files in stable sorted order.
- Capture each file's
blob_shaand set initial file status topending. - Build chunk queue per file:
- Markdown: heading/fence-safe semantic chunks (typically 60-120 lines)
- Code/text: prefer git hunk boundaries; fallback fixed windows
- Assign chunk IDs and initial chunk status
pending. - Seed deterministic
context_refsper chunk and save toqueue.json.- Code chunks: prefer call sites, definitions, tests, then adjacent fallback chunk.
- Docs chunks: prefer referenced/ referring sections, governing policy docs, then adjacent heading fallback chunk.
- Initialize
state.yaml,fix-queue.yaml, andevents.log.
If high-impact edits were applied during Phase 0.5, build/rebuild queue after those edits so chunk boundaries and blob hashes are fresh.
Phase 2: Chunk Review Loop
Before every chunk presentation, enforce Phase 0.75 gate (intent_resync_required must be false).
For each chunk, output exactly:
Primary Chunk({file}:{start_line}-{end_line}and EOF 여부)Primary ExcerptRelated Context(at least 1 context excerpt with path/line anchors + relation)Causal Lens(symptom, likely root cause, guardrail/invariant)Review Focus (Line-Anchored)with at least 2 concrete pointsConsistency Check:- docs: link syntax + reference integrity checks
- code: call-path/definition-path impact checks
Root-Cause Discussion Prompt(1-2 concrete questions)
Then pause and wait for user acknowledgement.
Before each pause, persist cursor/progress.
Related Context Resolution (Required, Always-On)
- Resolve related context before presenting the chunk and persist the selected
context_refs. - Keep the same context refs stable across retries/resume unless file drift invalidates anchors.
- If semantic matches are not found, use structural fallback context (adjacent chunk/heading) and mark relation as
adjacent_fallback. - Never present a chunk without at least one related context reference.
Review-Fix Policy During Loop
- Mark the current file/chunk as
in_reviewwhile presenting it. - If the user asks to fix the currently open chunk, apply immediately (natural conversational flow).
- If a fix targets an already reviewed file/chunk, default action is to append to
fix-queue.yamlfirst (do not silently rewrite previously closed sections). - If the user explicitly requests immediate edit on a reviewed area, apply the edit and mark overlapping reviewed chunks as
stale. - Stale chunks are revisited via delta-review before final close.
Phase 3: Rule Capture and Propagation
When user gives an improvement rule:
- Normalize rule text into a durable entry in
rules.yaml. - Record scope (
docsorcode, path globs, severity/priority). - Scan remaining queue for candidate matches.
- Propose concrete follow-up targets (
file/chunk + rationale) before continuing.
All accepted rules are applied to remaining chunks in the same HITL session.
When a new rule affects already reviewed regions, add those targets to fix-queue.yaml and mark overlapping chunks stale only when an edit is actually applied.
Phase 4: Resume and Close
Resume
On --resume:
- Read
state.yamlcursor. - Validate queued file/chunk still exists.
- Compare saved
blob_shawith current file blob:- unchanged: preserve statuses
- changed: mark previously
reviewedoverlapping chunks asstale
- If lines drift, re-anchor by nearest previous heading/hunk.
- Continue with same chunk contract, prioritizing
stalebefore untouchedpending.
Close
On --close (or EOF completion):
- Mark session state
completed(orclosed_by_user). - Keep rule history and event log immutable.
- Update
cwf-state.yamlpointerupdated_at. - Output concise completion summary (
files/chunks reviewed,rules applied,fix-queue pending/applied,stale re-reviewed count).
Rules
- Persist state before every user pause.
- Never discard accepted rules within the active session.
- Pointer-only policy: keep detailed HITL state in
.cwf/projects/{session-dir}/hitl/; store only pointers incwf-state.yaml. - During Phase 1 migration, do not move other skills' artifact paths automatically.
- Maintain meaningful commit-unit boundaries when applying fixes during HITL.
- Default policy:
in_reviewfixes can be immediate;reviewedfixes go tofix-queueunless the user requests immediate application. - Any edit touching previously reviewed content must mark overlapping chunks
staleand trigger delta-review before close. - Default entry behavior: start with the agreement round (Phase 0.5), then move to chunk review.
- Keep artifacts separated by role:
fix-queue.yamlfor actionable edits,hitl-scratchpad.mdfor agreements/rationale. - After any agreed edit is applied, update
hitl-scratchpad.mdbefore continuing. - No isolated chunk reviews: every presented chunk must include
Related Context. - For both code and docs, use one principle:
Primary Chunk + Related Context + Causal Lens. Root-Cause Discussion Promptmust focus on cause validation, not symptom restatement.- For comment-driven doc HITL (for example README reflection), keep the same chunk contract and include
Before,After,After Intentwithin thePrimary Chunksection.Before/Aftermust include enough surrounding context for user judgment (for example, the full paragraph or subsection, not a single isolated sentence).
- Do not ask a separate "proceed to next item?" question. When the current item is agreed, present the next pending item immediately; if not agreed, keep discussing the same item until agreement.
- If user manual edits are detected/reported, trigger Phase 0.75 immediately (set
intent_resync_required=trueand append trigger toevents.log). - While
intent_resync_required=true, apply the Phase 0.75 block rule (no next chunk presentation). - Clear
intent_resync_requiredonly through the Phase 0.75 completion contract (hitl-scratchpad.mdintent delta +last_intent_resync_atupdate). - During active HITL doc review, document edits and scratchpad state must stay synchronized; post-run checks should flag missing scratchpad updates.
- Language override: review-facing HITL outputs follow the user's language by default unless the user explicitly requests another language.
References
- hitl-state-model.md — canonical schema and lifecycle for
state.yaml,queue.json,fix-queue.yaml, and HITL pointer metadata
Impl
Execute an approved plan predictably while preserving constraints, dependencies, and BDD validation.
Quick Start
cwf:impl # Auto-detect most recent plan.md
cwf:impl <path/to/plan.md> # Explicit plan path
cwf:impl --skip-branch # Skip Phase 0.5 branch gate (stay on current branch)
cwf:impl --skip-clarify # Skip Phase 1.0 clarify pre-condition check
Phase 0: Update Live State
Use the live-state helper for scalar fields, then initialize list fields in the resolved live-state file:
bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh set . \
phase="impl" \
task="{plan goal summary}"
live_state_file=$(bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh resolve)
In {live_state_file}, set live.key_files to the plan's key files list and initialize live.decision_journal as an empty list:
live:
phase: "impl"
task: "{plan goal summary}"
decision_journal: []
Decision Journal
Throughout Phases 2-4, append significant decisions to live.decision_journal in the resolved live-state file (bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh resolve). Record decisions when:
- A design choice is made between alternatives
- A deviation from the plan occurs
- A trade-off is resolved
Format each entry as a timestamped string:
decision_journal:
- "Phase 2: chose per-pattern commits — changes are cross-cutting"
- "Phase 3b: agent-2 deviated from plan — added error handling for edge case"
The compact recovery hook reads this field to restore decision context after auto-compaction. Keep entries concise (one line each, max ~80 chars).
Phase 0.5: Branch Gate
Apply the Branch Gate. Never proceed on a base branch.
Phase 1: Load Plan
Find and parse the plan that drives implementation.
1.0 Clarify Completion Check
Apply the Clarify Completion Gate. Hard-blocks unless --skip-clarify is provided.
1.1 Plan Discovery
If an explicit path was provided, use it. Otherwise:
- Scan
.cwf/projects/*/plan.mdusing Glob. - Rank candidates with this priority (highest first):
- Session pin from live state: if
plan.mdexists insidelive.dirfrom the resolved live-state file, prefer it. - Plan metadata timestamp: newest parseable ISO-8601 from plan metadata/frontmatter (
updated_at,created_at,generated_at,date). - Filesystem timestamp: newest
plan.mdmodification time. - Directory name order: use only as a final deterministic tiebreaker after timestamp signals.
- Session pin from live state: if
- Select the top-ranked candidate only when it is unambiguous.
Ambiguity behavior (fail-closed):
- If two or more candidates tie on all available ranking signals, stop and ask the user for an explicit path.
- If metadata timestamps are missing/invalid for all tied candidates and file mtimes are identical, stop and ask the user for an explicit path.
- Never silently pick a plan based only on lexicographic directory naming when chronology is ambiguous.
If no plan is found, report to the user and stop:
No plan.md found in .cwf/projects/. Run cwf:plan first.
1.1b Phase Handoff Discovery
Check for a phase-handoff.md in the same directory as the discovered plan.md:
- Derive the directory from the plan path:
dirname {plan.md path} - Check if
phase-handoff.mdexists in that directory - If found, read and parse all sections:
- Context Files to Read: Additional files the agent must read before implementation
- Design Decision Summary: Key choices with rationale — treat as binding context
- Protocols to Follow: Behavioral rules — treat as binding constraints alongside plan.md
- Do NOT: Prohibitions — append to plan's "Don't Touch" list as behavioral constraints
- Implementation Hints: Practical guidance — use during Phase 3 execution
- Success Criteria: Additional BDD criteria — merge with plan's criteria for Phase 4 verification
- If phase-handoff.md specifies "Context Files to Read", read each listed file before proceeding
If phase-handoff.md is not found, proceed normally with plan.md only. Phase handoff is optional.
1.2 Section Extraction
Read the plan and extract these sections (all optional except Steps):
| Section | Key Content |
|---|---|
| Context | Background, rationale |
| Goal | Desired outcome |
| Steps | Ordered implementation steps (REQUIRED) |
| Files to Create/Modify | File paths with actions |
| Success Criteria — Behavioral (BDD) | Given/When/Then scenarios |
| Success Criteria — Qualitative | Non-functional quality attributes |
| Don't Touch | Files explicitly out of scope |
| Deferred Actions | Items not for this session |
If the Steps section is missing or empty, report to the user and stop.
1.3 User Confirmation
Present a summary and confirm before proceeding:
## Plan Loaded
**Source**: {path to plan.md}
**Goal**: {goal from plan}
**Steps**: {count} steps
**Files**: {count} files to create/modify
**BDD Criteria**: {count} scenarios
**Don't Touch**: {list or "none specified"}
**Phase Handoff**: {path to phase-handoff.md, or "not found (proceeding with plan only)"}
**Phase Protocols**: {count} protocols to follow
**Phase Do NOT**: {count} prohibitions
Proceed with implementation?
Use AskUserQuestion with options: "Proceed", "Review plan first", "Cancel".
1.4 Lessons Baseline
Resolve lessons.md in the same directory as the selected plan.md.
- If
lessons.mddoes not exist, create it immediately using the structure fromplan-protocol.md. - Treat lesson accumulation as continuous behavior:
- user clarifications discovered during implementation
- plan-vs-execution gaps
- runtime/tooling constraints discovered mid-flight
- Keep lesson entries in the user's language.
Phase 2: Analyze & Decompose
Break the plan into parallelizable work items and size the agent team.
2.1 Domain Detection
Read {SKILL_DIR}/references/agent-prompts.md Section "Domain Signal Table".
For each step, identify the primary domain by matching:
- File patterns mentioned in the step
- File patterns from the "Files to Create/Modify" table
- Keywords and descriptions in the step text
2.2 Dependency Analysis
Read {SKILL_DIR}/references/agent-prompts.md Section "Dependency Detection Heuristics".
Analyze step-to-step dependencies:
- File overlap: Steps touching the same file must be sequential
- Output references: Step N uses output from Step M → sequential
- Ordering keywords: "after", "then", "once X is done" → sequential
- Independent: No shared files, no output dependencies → parallel-safe
2.3 Work Item Grouping
Group steps into work items:
- Place sequential-dependent steps in the same work item (preserve order)
- Group steps with the same domain into one work item when possible
- Keep parallel-safe items in separate work items
- Each work item gets: assigned steps, file list, relevant BDD criteria
2.4 Adaptive Team Sizing
Read {SKILL_DIR}/../../references/agent-patterns.md for general agent principles.
| Work Items | Agents | Strategy |
|---|---|---|
| 1 (≤3 files) | 0 | Direct execution — Phase 3a |
| 2-3 | 2 | Group related items per agent |
| 4-6 | 3 | Balance parallelism vs coordination |
| 7+ | 4 (hard cap) | Beyond 4, overhead exceeds gains |
2.4.1 Web Debug Classification (Conditional)
Before finalizing work items, detect browser-runtime debugging scope from step text and file signals (for example: console, DOM, CDP, DevTools, click/focus/navigation regressions, viewport or mobile regressions, HTML/CSS/SPA runtime files).
If detected:
- mark the work item as
web-debug - require Web Debug Loop Protocol execution during Phase 3 (before/after evidence)
- resolve
session_dirfromlive.dirin the resolved live-state file, then reserve{session_dir}/debug/{timestamp}-{slug}/
2.5 Cross-Cutting Assessment
Before finalizing decomposition, assess whether changes are cross-cutting:
- Cross-cutting indicator: A single concept (protocol, pattern, interface) projected across 3+ files
- If cross-cutting: Commit boundary = change pattern. Add a
Commit Groupcolumn to group files by the concept they implement, regardless of work item assignment. - If modular: Commit boundary = work item (default). No
Commit Groupneeded.
2.6 Present Decomposition
Show the decomposition before executing:
## Decomposition
### Work Items
| # | Steps | Domain | Files | Parallel | Commit Group |
|---|-------|--------|-------|----------|--------------|
| 1 | 1, 2 | {domain} | {file list} | yes | {group or "—"} |
| 2 | 3 | {domain} | {file list} | yes | {group or "—"} |
| 3 | 4, 5 | {domain} | {file list} | after #1 | {group or "—"} |
### Execution Strategy
- **Mode**: {Direct (3a) | Agent Team (3b)}
- **Agents**: {count}
- **Batches**: {count} (sequential batches of parallel items)
- **Commit Strategy**: {per work item | per change pattern}
### Don't Touch (enforced)
- {files from plan's Don't Touch section}
If Agent Team mode: use AskUserQuestion with "Execute", "Adjust grouping", "Cancel". If Direct mode: proceed without confirmation.
Phase 3a: Direct Execution
For simple plans (1 work item, ≤3 files).
-
Execute each step in the work item sequentially
-
Use Write, Edit, Bash, and other allowed tools directly
-
Follow the plan's step descriptions precisely
-
If the item is
web-debug, run Web Debug Loop Protocol and persist before/after evidence under{session_dir}/debug/{timestamp}-{slug}/ -
Respect the "Don't Touch" list — never modify those files
-
If phase-handoff.md was loaded, apply its Implementation Hints during execution and respect its "Do NOT" constraints
-
Append newly discovered learnings to
lessons.mdbefore commit (user language). -
Commit Gate: Apply the Commit Gate. Stage specific files and commit with Conventional Commit format.
-
After commit, proceed to Phase 4
Phase 3b: Agent Team Execution
For complex plans requiring parallel work.
3b.1 Prompt Construction
For each work item, build an agent prompt using the template from {SKILL_DIR}/references/agent-prompts.md Section "Implementation Agent Prompt Template". The prompt includes:
- The specific steps assigned to this agent
- The file list (create/modify) for these steps
- Relevant BDD criteria that this agent's work should satisfy
- The Don't Touch list (full list — every agent must respect it)
- Context from the plan (Goal, relevant Context sections)
- Phase handoff protocols, hints, and "Do NOT" constraints (if phase-handoff.md was loaded)
- For
web-debugitems, explicit instruction to run Web Debug Loop Protocol and persist evidence paths in the final report
3b.2 Parallel Launch
Launch agents for parallel-safe work items in a single message with multiple Task tool calls:
# All parallel items in one message
Task tool (item 1):
subagent_type: general-purpose
mode: bypassPermissions
prompt: |
{constructed prompt from 3b.1}
Task tool (item 2):
subagent_type: general-purpose
mode: bypassPermissions
prompt: |
{constructed prompt from 3b.1}
3b.3 Sequential Batches
If some work items depend on others:
- Launch all parallel-safe items in batch 1
- Wait for batch 1 to complete
- Launch dependent items in batch 2 (include batch 1 results as context)
- Repeat until all batches complete
Between batches, briefly verify that prior batch outputs exist and are valid before launching the next batch.
3b.3.5 Batch Commit
After each batch completes (before launching the next batch), apply the Commit Gate.
File-to-work-item mapping: The orchestrator maintains a map derived from Phase 2 decomposition ({work_item_id → [file_paths]}). Each agent's prompt (from 3b.1) MUST include the list of files it is expected to modify. After batch completion, use this map to attribute files to work items. If an agent modifies unexpected files, include them in that work item's commit with a note.
Commit granularity: Determined by Phase 2.6 cross-cutting assessment:
- Modular changes: One commit per work item
- Cross-cutting changes: One commit per change pattern (Commit Group)
Report after all commits in the batch:
Batch {N} committed:
- {short-hash} type(scope): summary
3b.3.6 Lesson-Driven Commits
Apply the Lesson-Driven Commits protocol. Lesson-driven changes get separate commits with "Driven by lesson:" reference.
3b.3.7 Lessons Checkpoint per Batch
After each batch (and before launching the next), update lessons.md with any new findings:
- corrected assumptions from user feedback
- design/implementation gaps discovered during execution
- constraints/tooling behavior that changed execution strategy
Keep entries concise and in the user's language.
3b.4 Result Collection
For each completed agent, append a structured result record (session artifact):
- path:
{session_dir}/impl-result-provenance.md - shape: one row per agent output (including failures)
For each row, capture:
- Record which steps were completed
- Note any files created or modified
- Capture any issues or deviations reported by the agent
- Capture provenance metadata (required):
source(REAL_EXECUTION|CACHED|FALLBACK)tool(for exampleclaude-task,codex,gemini)agent_id(or slot identifier)started_at_utc,finished_at_utc,duration_ms
- If an agent reports failure, record the failure with the same provenance fields and continue with other agents
If any provenance field is unavailable, persist — explicitly (never omit key columns).
Phase 4: Verify & Suggest Review
Check implementation against the plan's success criteria.
4.1 BDD Criteria Checklist
For each BDD scenario from the plan (and from phase-handoff.md Success Criteria, if present):
- Determine which work item(s) should have addressed it
- Check if the relevant files were created/modified
- Mark each criterion:
- Covered: Implementation addresses this scenario
- Uncovered: No implementation found for this scenario
- Partial: Some aspects addressed, others missing
4.2 Qualitative Assessment
For each qualitative criterion, briefly note how the implementation addresses it (or flag if it doesn't).
4.3 Completion Summary
Present the verification results:
## Implementation Complete
### BDD Criteria Coverage
| # | Scenario | Status | Notes |
|---|----------|--------|-------|
| 1 | {Given/When/Then summary} | Covered | {brief note} |
| 2 | {Given/When/Then summary} | Uncovered | {what's missing} |
### Qualitative Assessment
| Criterion | Assessment |
|-----------|------------|
| {criterion} | {how it's addressed} |
### Files Modified
| File | Action | Agent |
|------|--------|-------|
| {path} | Created | {agent # or "direct"} |
### Issues
- {any deviations, failures, or concerns}
4.4 Uncovered Criteria
If any BDD criteria are uncovered:
- List them explicitly
- Ask the user whether to:
- Attempt to address them now (additional implementation pass)
- Defer them (add to Deferred Actions)
- Ignore them (they may be covered by later stages)
4.5 Session Completeness Check
Run the session completeness check:
bash {CWF_PLUGIN_DIR}/scripts/check-session.sh --impl
If any FAIL items are reported, fix them before suggesting review. This ensures all required artifacts (plan.md, lessons.md, next-session.md) exist and cwf-state.yaml is properly updated.
4.6 Suggest Review
After presenting the summary:
Implementation complete. To review the code quality and verify against
the plan's success criteria, run:
cwf:review --mode code
Rules
- Plan is the contract: Implement what the plan says. Do not add features, refactor unrelated code, or reinterpret the goal
- Don't Touch means don't touch: Never modify files in the Don't Touch list, even for "improvements"
- Parallel when safe, sequential when needed: Only parallelize items with no file overlap or output dependencies
- No idle agents: Size the team to the work. One agent with real work beats three agents where two wait
- Fail forward: If one agent fails, collect its error and continue with others. Report all failures in Phase 4
- Verify against criteria: Every BDD scenario must be checked, not assumed
- Preserve existing patterns: Follow codebase conventions visible in existing files. Do not introduce new patterns without plan justification
- Markdown discipline: All code fences must have a language specifier
- Phase handoff protocols are binding: When
phase-handoff.mdis present, its "Protocols to Follow" and "Do NOT" sections carry the same weight as plan constraints. They are not suggestions. - Phase handoff is optional: Impl works with
plan.mdalone. Phase handoff enriches but is never required. - Never implement on a base branch: Phase 0.5 is a hard gate. The only bypass is
--skip-branch. - Commit boundary = change pattern: When changes are cross-cutting (Phase 2.6), commit by concept/pattern. When modular, commit per work item. See Commit Gate.
- Stage specific files, never
git add -A: Only stage files known to belong to the current work item. Prevent accidental inclusion of unrelated changes. - Lesson-driven changes get separate commits: If a lesson triggers a code change, commit it independently. See Lesson-Driven Commits.
- Incremental lessons are mandatory: Update
lessons.mdas implementation progresses, not only at the end. - Structural Triage Contract: For each triage item referencing analysis documents, enforce the triage record contract in agent-patterns.md: include
source_ref,source_recommendation,triage_action,runtime_caller_check,deletion_premortem, anddecision_id. Ifsource_recommendationis missing, stop and complete triage context first. Iftriage_actiondiverges fromsource_recommendation, ask the user before proceeding. For deletion actions, do not continue until runtime-caller check and pre-mortem are both recorded. - Language override is mandatory: implementation/code artifacts stay in English, while
lessons.mdstays in the user's language. - Web-debug evidence is mandatory: Work items classified as
web-debugmust include before/after browser evidence and a reproducible path using Web Debug Loop Protocol.
References
- references/impl-gates.md — Branch, Clarify, and Commit gate definitions
- references/agent-prompts.md — Agent prompt template, domain signals, dependency heuristics
- agent-patterns.md — Shared agent orchestration, Web Research, and Web Debug protocols
Plan
Create a reviewable execution contract (scope, files, success criteria) before code changes begin.
Quick Start
cwf:plan <task description>
Design Intent (Post-v3 Architecture)
CWF v3 moved planning from runtime-specific plan-mode hooks to a runtime-independent skill (cwf:plan) with file-based contracts.
- Better planning input quality before drafting
gather+clarifycollect evidence and decision points before planning starts.- Planning conversations can reveal constraints/preferences that must be recorded in
lessons.mdimmediately, not after implementation.
- Context continuity without user-managed reset choreography
- Some runtimes expose context-reset workflows after planning discussions.
- CWF keeps continuity by default through
plan.md,lessons.md, and optionalcwf:handoff --phase, instead of shifting context-management burden to the user.
- Stable cross-runtime contract for long autonomous work
plan.md(WHAT) +phase-handoff.md(HOW, optional) +lessons.md(learned constraints) define a persistent contract for impl/review stages.- This keeps execution safe and reliable across auto-compact and runtime boundaries (Claude/Codex).
Phase 0: Update Live State
Use the live-state helper (session-first write target):
bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh set . \
phase="plan" \
task="{task summary}"
Phase 1: Parse & Scope
- Record the task description verbatim
- Identify what needs planning:
- What is the goal?
- What are the key decisions to make?
- What are the known constraints?
- Present a brief scope summary to the user before proceeding
## Task
"{user's task description verbatim}"
## Scope Summary
- **Goal**: {what we're trying to achieve}
- **Key Decisions**: {decisions that affect the plan}
- **Known Constraints**: {limitations, boundaries}
Phase 2: Evidence Baseline & Gap-Fill Research
2.0 Resolve session directory
Resolve the effective live-state file, then read live.dir.
live_state_file=$(bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh resolve)
session_dir: "{live.dir value from resolved live-state file}"
2.1 Build baseline from existing artifacts
Use persisted artifacts as the default planning evidence before launching any new research.
- Resolve the effective live-state file and read
live.clarify_result_filewhen set. - Read gather/clarify artifacts already available for this session, prioritizing:
- clarify summary file (
live.clarify_result_file) {session_dir}/clarify-codebase-research.md{session_dir}/clarify-web-research.md{session_dir}/clarify-expert-alpha.md{session_dir}/clarify-expert-beta.md- relevant gathered markdown outputs (and matching
.meta.yaml) from the current session directory
- clarify summary file (
- Build an Evidence Gap List:
- which decision points are already answerable from existing evidence
- which decision points still need additional investigation
If no reusable artifacts are available, treat all unresolved decision points as gap candidates and continue to Phase 2.2.
2.2 Context recovery check (gap-fill outputs)
Apply the context recovery protocol to these gap-fill output files:
| Agent | Output file |
|---|---|
| Prior Art Researcher | {session_dir}/plan-prior-art-research.md |
| Codebase Analyst | {session_dir}/plan-codebase-analysis.md |
Decision:
- If Evidence Gap List is empty: skip to Phase 3 (no extra research needed).
- If Evidence Gap List is non-empty and both files are valid: reuse them and skip to Phase 3.
- Otherwise continue to Phase 2.3.
2.3 Adaptive gap triage
Assess each unresolved gap to decide which extra research lane is needed:
| Gap type | Agent decision |
|---|---|
| Gap is mainly repository-specific (existing architecture, constraints, local patterns) | Launch Codebase Analyst only |
| Gap is mainly external best practice / prior art | Launch Prior Art Researcher only |
| Gap spans both repository constraints and external practice | Launch both agents in parallel |
| Gap is already answerable from baseline after re-check | No launch for that gap |
When uncertain, prefer launching both agents.
2.4 Launch targeted sub-agents
Launch sub-agents simultaneously using the Task tool — only for lanes selected in Phase 2.3 and only when their result files are missing or invalid.
- Shared output persistence contract: agent-patterns.md § Sub-agent Output Persistence Contract.
Sub-agent A: Prior Art Researcher
Task tool:
subagent_type: general-purpose
max_turns: 20
prompt: |
Research best practices, frameworks, and prior art relevant to this task.
## Web Research Protocol
Read the "Web Research Protocol" section of
{CWF_PLUGIN_DIR}/references/agent-patterns.md and follow it exactly.
Key points: discover URLs via WebSearch first (never guess URLs),
use WebFetch then fall back to agent-browser for JS-rendered pages,
skip failed domains, budget turns for writing output.
You have Bash access for agent-browser CLI commands.
Find:
- Established methodologies or patterns for this type of work
- Common pitfalls and how others avoided them
- Relevant tools, libraries, or approaches
Cite real sources with URLs. Report findings — do not make decisions.
Task:
{task description from Phase 1}
Key decisions:
{decisions from Phase 1}
Baseline evidence summary from gather/clarify:
{summary from Phase 2.1}
Unresolved evidence gaps to investigate:
{gap list for prior-art lane from Phase 2.3}
## Output Persistence
Write your complete findings to: {session_dir}/plan-prior-art-research.md
At the very end of the file, append this sentinel marker on its own line:
<!-- AGENT_COMPLETE -->
Sub-agent B: Codebase Analyst
Task tool:
subagent_type: Explore
max_turns: 20
prompt: |
Analyze the codebase for patterns, dependencies, and constraints relevant
to this task. For each finding:
- Cite file paths and line numbers
- Assess impact on the plan (High/Medium/Low)
- Note existing patterns that should be followed
Report evidence only — do not make decisions.
Task:
{task description from Phase 1}
Key decisions:
{decisions from Phase 1}
Baseline evidence summary from gather/clarify:
{summary from Phase 2.1}
Unresolved evidence gaps to investigate:
{gap list for codebase lane from Phase 2.3}
## Output Persistence
Write your complete findings to: {session_dir}/plan-codebase-analysis.md
At the very end of the file, append this sentinel marker on its own line:
<!-- AGENT_COMPLETE -->
Wait for all launched sub-agents to complete. Re-validate each launched file using the context recovery protocol.
2.5 Read output files
After sub-agents complete, read the result files from the session directory (not in-memory return values):
{session_dir}/plan-prior-art-research.md— Prior art research findings{session_dir}/plan-codebase-analysis.md— Codebase analysis findings
Use these file contents as additional input for Phase 3 synthesis.
2.6 Persistence Gate (Critical when gap-fill research runs)
Apply the stage-tier policy from the context recovery protocol when Phase 2.4 launched any gap-fill sub-agent:
plan-prior-art-research.mdandplan-codebase-analysis.mdare critical.- If either file is still invalid after one bounded retry, hard fail the stage with explicit file-level error and stop plan drafting.
- Record gate path in output (
PERSISTENCE_GATE=HARD_FAILor equivalent).
If no gap-fill sub-agent was launched, record PERSISTENCE_GATE=SKIP_NO_GAP and proceed.
Phase 3: Plan Drafting
Synthesize baseline evidence (from gather/clarify artifacts) and any additional gap-fill research into a structured plan. Read {SKILL_DIR}/../../references/plan-protocol.md for protocol rules on location, sections, and format.
Cross-Cutting Pattern Gate
Before finalizing Steps, scan for cross-cutting patterns:
- Identify steps that apply identical logic to 3+ targets (files, skills, modules)
- If found: add a Step 0 that creates a shared reference file for the common pattern. Subsequent steps reference the shared file — never duplicate the pattern inline.
- If not found: proceed normally
Prohibited instructions in step descriptions:
- "동일 적용" / "apply the same pattern" / "same as Step N"
- Any instruction that delegates architecture to parallel implementors
Each step must either reference a shared file or contain self-contained instructions. Parallel agents cannot see each other's work, so sharing must be decided at plan level.
Preparatory Refactoring Check
Before finalizing Steps, assess whether preparatory refactoring is needed:
- For each target file in "Files to Create/Modify", check its line count
- If a file is 300+ lines AND 3+ changes are planned for it:
- Add a Step 0 that extracts separable blocks to reference files
- This reduces edit surface for subsequent steps and improves commit independence
- If no files meet the threshold: proceed normally
Plan Structure Contract
Use plan-protocol.md as the single source of truth for:
- Required plan/lesson sections
- Success criteria baseline structure
- Artifact location and creation timing
lessons.mdformat and language policy
Keep only these skill-specific additions in the generated plan:
-
Add a required
## Commit Strategysection:- Per step (default for modular changes)
- Per change pattern (for cross-cutting changes)
- Custom (explicit commit boundaries + rationale)
-
Keep Success Criteria in the two-layer format:
- Behavioral (BDD) scenarios
- Qualitative non-functional criteria
-
Expand
## Decision Logto include evidence/source and resolution metadata:# Decision Point Evidence / Source (artifact or URL + confidence) Alternatives Considered Resolution Status Resolved By Resolved At (UTC) 1 ... ... ... ... open/resolved ... ... Status=open: leaveResolution,Resolved By, andResolved AtasTBD.Status=resolved: cite concrete evidence (e.g.,plan-codebase-analysis.md,plan-prior-art-research.md, URL).
Research Integration
- Start from gather/clarify evidence as the primary baseline for plan rationale
- Incorporate gap-fill findings only for unresolved decisions
- Note where codebase patterns inform implementation steps
- Flag conflicts between best practices and existing code as decision points
Phase 4: Write Artifacts
Determine the session directory following plan-protocol.md location rules:
- If the user provided an output path, use it.
- Otherwise run
{CWF_PLUGIN_DIR}/scripts/next-prompt-dir.sh --bootstrap <title>and use its output path.--bootstrapcreates the resolved directory, initializes missingplan.md/lessons.md, and pre-registers the session incwf-state.yamlsessionswhen state exists.
Write two files:
plan.md
Write the complete plan from Phase 3, following plan-protocol.md and the skill-specific additions above (Commit Strategy, expanded Decision Log).
lessons.md
Initialize lessons.md using the shared format in plan-protocol.md (user language). If no learnings exist yet, create the file with a header and a short placeholder note.
Before finishing this skill, append plan-stage learnings captured during user ping-pong (for example: clarified constraints, corrected assumptions, revealed preferences). Do not defer these to implementation.
Phase 5: Review Offer
After writing plan artifacts, suggest review:
Plan drafted at .cwf/projects/{dir}/plan.md.
For a multi-perspective review before implementation, run:
cwf:review --mode plan
Rules
- Evidence-first before drafting: Use gather/clarify artifacts as baseline first; run additional research only for unresolved evidence gaps
- Two-layer criteria: Success criteria must include both BDD and qualitative layers
- Cite evidence: Reference specific files, URLs, or sources for plan decisions
- Follow protocol: Adhere to plan-protocol.md for format and location
- Don't over-plan: Keep steps actionable and concrete, avoid excessive detail
- Preserve task intent: Refine the approach, don't redirect the goal
- Cross-cutting → shared reference first: When identical logic applies to 3+ targets, create a shared reference file as Step 0. "동일 적용" is a plan smell — replace with an explicit shared file path
- Commit Strategy is required: Every plan must include a Commit Strategy section. Default is one commit per Step.
- Preparatory refactoring check: When a target file is 300+ lines with 3+ planned changes, add Step 0 to extract separable blocks first
- Conditional critical persistence hard-fail: When gap-fill research is launched, if
plan-prior-art-research.mdorplan-codebase-analysis.mdremains invalid after bounded retry, stop with explicit error instead of drafting from partial data - Language override is mandatory:
plan.mdis in English;lessons.mdis in the user's language - Plan-stage learnings must be logged immediately: Record conversation-time learnings in
lessons.mdduring planning, not only after implementation
References
- plan-protocol.md — Plan & Lessons Protocol
Refactor (cwf:refactor)
Control drift across code, skills, and docs as teams install and author more capabilities.
Quick Reference
cwf:refactor Quick scan all marketplace skills
cwf:refactor --include-local-skills Quick scan marketplace + local skills
cwf:refactor --tidy [branch] Commit-based tidying (parallel sub-agents)
cwf:refactor --codebase Contract-driven whole-codebase quick scan
cwf:refactor --codebase --deep Codebase deep review with 4 expert sub-agents
cwf:refactor --skill <name> Deep review of a single skill (parallel sub-agents)
cwf:refactor --skill --holistic Cross-plugin analysis (parallel sub-agents)
cwf:refactor --docs Documentation consistency review
Philosophy:
cwf:refactor(no args) is a maintenance heartbeat for ecosystem-level drift detection.cwf:refactor --skill <name>is for focused diagnosis when one authored/installed skill needs targeted correction without paying the cost of full holistic analysis.- Portability is a default review axis across deep, holistic, and docs modes (no extra flag).
Mode Routing
Parse the user's input:
| Input | Mode |
|---|---|
| No args | Quick Scan |
--tidy or --tidy <branch> | Code Tidying |
--codebase | Codebase Quick Scan |
--codebase --deep | Codebase Deep Review |
--include-local-skills (no other mode flags) | Quick Scan + local skills |
--skill <name> | Deep Review |
--skill --holistic or --holistic | Holistic Analysis |
--docs | Docs Review |
Provenance Sidecars (Required)
Before using any criteria document, verify its provenance sidecar against the current live repository state (current skill/hook counts).
| Criteria | Provenance sidecar |
|---|---|
| review-criteria.md | review-criteria.provenance.yaml |
| holistic-criteria.md | holistic-criteria.provenance.yaml |
| docs-criteria.md | docs-criteria.provenance.yaml |
Verification command:
bash {CWF_PLUGIN_DIR}/scripts/provenance-check.sh --level inform --json
Provenance verification rules:
- Confirm the mode-relevant sidecar entry exists in the checker output.
- Compare sidecar
skill_count/hook_countwith checkercurrent.skills/current.hooks. - If the sidecar is missing or stale, continue review but prepend a Provenance Warning and include the delta in the report.
Quick Scan Mode (no args)
Resolve session directory (for deterministic artifact persistence) using references/session-bootstrap.md with bootstrap key refactor-quick-scan.
Run the structural scan script and persist raw output:
bash {SKILL_DIR}/scripts/quick-scan.sh {REPO_ROOT} > {session_dir}/refactor-quick-scan.json
{REPO_ROOT} is the git repository root (5 levels up from SKILL.md in marketplace path, or use git rev-parse --show-toplevel).
Optional local-skill scope (portability hardening):
bash {SKILL_DIR}/scripts/quick-scan.sh \
{REPO_ROOT} \
--include-local-skills \
--local-skill-glob ".claude/skills/*/SKILL.md" > {session_dir}/refactor-quick-scan.json
Parse the JSON output and present a summary table. Also persist a concise summary to {session_dir}/refactor-summary.md:
| Plugin | Skill | Words | Lines | Flags |
|---|
- For each flagged skill (flag_count > 0), list the specific flags.
- Suggest: "Run
cwf:refactor --skill <name>for a deep review." - Include
Mode: cwf:refactor (Quick Scan)and the scan command in the summary file.
After writing summary artifacts, run deterministic gate:
bash {CWF_PLUGIN_DIR}/scripts/check-run-gate-artifacts.sh \
--session-dir "{session_dir}" \
--stage refactor \
--strict \
--record-lessons
Code Tidying Mode (--tidy [branch])
Analyze recent commits for safe tidying opportunities — guard clauses, dead code removal, explaining variables. Based on Kent Beck's "Tidy First?" philosophy.
1. Get Target Commits
Run the script to get recent non-tidying commits:
bash {SKILL_DIR}/scripts/tidy-target-commits.sh 5 [branch]
- If branch argument provided (e.g.,
cwf:refactor --tidy develop), pass it to the script. - If no branch specified, defaults to HEAD.
2. Parallel Analysis with Sub-agents
Resolve session directory using references/session-bootstrap.md with bootstrap key refactor-tidy.
Apply the context recovery protocol — for each commit N (1-indexed), check {session_dir}/refactor-tidy-commit-{N}.md.
For each commit hash that needs analysis, launch a parallel sub-agent using Task tool:
- Shared output persistence contract: agent-patterns.md § Sub-agent Output Persistence Contract.
Task tool:
subagent_type: general-purpose
max_turns: 12
Each sub-agent prompt:
- Read
{SKILL_DIR}/references/tidying-guide.mdfor techniques, constraints, and output format - Analyze commit diff:
git show {commit_hash} - Check if changes still exist:
git diff {commit_hash}..HEAD -- {file}(skip modified regions) - Return suggestions or "No tidying opportunities"
- Output Persistence: Write your complete analysis to:
{session_dir}/refactor-tidy-commit-{N}.md. At the very end of the file, append this sentinel marker on its own line:<!-- AGENT_COMPLETE -->
3. Aggregate Results
Read all result files from the session directory ({session_dir}/refactor-tidy-commit-{N}.md for each commit) and present:
# Tidying Analysis Results
## Commit: {hash} - {message}
- suggestion 1
- suggestion 2
## Commit: {hash} - {message}
- No tidying opportunities
Codebase Quick Scan Mode (--codebase)
Run a contract-driven quick scan across the repository codebase.
0. Resolve or Bootstrap Codebase Contract
Before scanning, resolve the repository-local codebase contract:
bash {SKILL_DIR}/scripts/bootstrap-codebase-contract.sh --json
Behavior:
- Default location:
{artifact_root}/codebase-contract.yaml - If contract is missing: create a draft contract
- If contract exists: do not overwrite unless explicit force is used
- If bootstrap fails (
status=fallbackwith non-zero exit): stop this mode and fix bootstrap/path issues before scanning
Capture metadata for final summary:
CONTRACT_STATUS:created,existing,updated, orfallback(fallbackis fail-safe and must halt the stage)CONTRACT_PATHCONTRACT_WARNING(optional)
Contract spec: references/codebase-contract.md
For shell strict-mode exceptions, use contract + file pragma dual control:
- contract allowlist:
checks.shell_strict_mode.file_overrides - file pragma:
# cwf: shell-strict-mode relax reason="..." ticket="..." expires="YYYY-MM-DD"
For implementation/regression checks of codebase-contract behavior, run:
bash {SKILL_DIR}/scripts/check-codebase-contract-runtime.sh
1. Resolve Session Directory
Use references/session-bootstrap.md with bootstrap key refactor-codebase.
2. Run Contract-Driven Scan and Persist Raw Output
bash {SKILL_DIR}/scripts/codebase-quick-scan.sh \
{REPO_ROOT} \
--contract "{CONTRACT_PATH}" > {session_dir}/refactor-codebase-scan.json
{REPO_ROOT} is the git repository root (git rev-parse --show-toplevel).
scripts/codebase-quick-scan.sh delegates contract evaluation and findings aggregation to scripts/codebase-quick-scan.py as the backend implementation.
3. Summarize Findings
Read {session_dir}/refactor-codebase-scan.json and write {session_dir}/refactor-summary.md with:
Mode: cwf:refactor --codebase- Contract metadata (
CONTRACT_STATUS,CONTRACT_PATH, optionalCONTRACT_WARNING) - Scope summary (candidate/scanned/excluded files)
- Top findings table: severity, check, file, detail
- If no findings: explicit "No significant codebase tidy risks detected"
After writing summary artifacts, run deterministic gate:
bash {CWF_PLUGIN_DIR}/scripts/check-run-gate-artifacts.sh \
--session-dir "{session_dir}" \
--stage refactor \
--strict \
--record-lessons
Codebase Deep Review Mode (--codebase --deep)
Run codebase quick scan first, then add expert-lens deep review using 4 parallel expert sub-agents.
Full procedure: references/codebase-deep-review-flow.md
Execution contract:
- Resolve/bootstrap codebase contract (
bootstrap-codebase-contract.sh --json) - Resolve session directory with references/session-bootstrap.md (
refactor-codebase-deep) - Run codebase scan to
{session_dir}/refactor-codebase-scan.json - Select experts to
{session_dir}/refactor-codebase-experts.json - Launch 4 parallel experts (Fowler, Beck, Context 1, Context 2) and persist outputs with
<!-- AGENT_COMPLETE --> - Merge scan + expert outputs into
{session_dir}/refactor-summary.md, then run gate
Deep Review Mode (--skill <name>)
Full procedure: references/deep-review-flow.md
Execution contract:
- Locate the target skill, read
SKILL.md+references/+scripts/+assets/ - Verify deep-review provenance (
review-criteria.provenance.yaml) - Resolve session directory with references/session-bootstrap.md (
refactor-skill) - Launch 2 parallel sub-agents (Structural 1-4, Quality+Concept 5-9) with output persistence sentinel
- Merge outputs into unified deep report and offer to apply changes
Holistic Mode (--skill --holistic or --holistic)
Cross-plugin analysis for global optimization. Read ALL skills and hooks, then analyze inter-plugin relationships.
Full procedure: references/holistic-review-flow.md
Execution contract:
- Build inventory from marketplace skills, hooks, and local skills
- Verify holistic criteria provenance (
holistic-criteria.provenance.yaml) - Resolve session directory with references/session-bootstrap.md (
refactor-holistic) - Launch 3 parallel sub-agents (Convention, Concept, Workflow) with output persistence sentinel
- Merge to holistic report and discuss prioritization with the user
Docs Review Mode (--docs)
Review documentation consistency with this fixed flow:
- Resolve/bootstrap docs contract (
bootstrap-docs-contract.sh) - Deterministic tool pass (
markdownlint, local link check, doc-graph) - Docs criteria provenance verification
- Contract-aware entry docs, project context, README, and cross-document consistency review
- Semantic quality and structural optimization synthesis (portability baseline always on)
Deterministic tool pass uses scripts/check-links.sh and scripts/doc-graph.mjs with markdownlint; for docs-contract runtime regression checks, run scripts/check-docs-contract-runtime.sh.
Use {SKILL_DIR}/references/docs-criteria.md for evaluation criteria, references/docs-contract.md for contract schema, and references/docs-review-flow.md for full --docs procedure (commands, sequence, and reporting scope).
Rules
- Deep Review and Holistic use perspective-based parallel sub-agents (not module-based)
- Deep Review: 2 agents (structural 1-4 + quality/concept/portability 5-9), single batch
- Holistic: 3 agents (Convention Compliance, Concept Integrity, Workflow Coherence), single batch after inline inventory
- Code Tidying: 1 agent per commit, all in one message
- Codebase Quick Scan: contract-driven deterministic scan, no sub-agents
- Codebase Deep Review: 4 expert sub-agents (fixed 2 + context 2) after codebase scan
- Docs Review: inline, no sub-agents (single-context synthesis over whole-repo graph and deterministic outputs)
- Docs Review must run the deterministic tool pass before semantic analysis
- In Docs Review, do not report lint/hook-detectable issues as standalone manual findings when tool output already covers them
- Sub-agents analyze and report; orchestrator merges. Sub-agents do not modify files
- All code fences must have a language specifier
References
- Review criteria for deep review: references/review-criteria.md
- Holistic analysis framework: references/holistic-criteria.md
- Detailed codebase deep procedure: references/codebase-deep-review-flow.md
- Detailed deep-review procedure: references/deep-review-flow.md
- Detailed holistic procedure: references/holistic-review-flow.md
- Concept synchronization map: concept-map.md
- Tidying techniques for --tidy mode: references/tidying-guide.md
- Codebase scan contract schema: references/codebase-contract.md
- Shared session bootstrap snippet: references/session-bootstrap.md
- Codebase expert selector script: scripts/select-codebase-experts.sh
- Docs review criteria: references/docs-criteria.md
- Docs review contract schema: references/docs-contract.md
- Docs review procedure flow: references/docs-review-flow.md
- Provenance sidecar (deep criteria): references/review-criteria.provenance.yaml
- Provenance sidecar (holistic criteria): references/holistic-criteria.provenance.yaml
- Provenance sidecar (docs criteria): references/docs-criteria.provenance.yaml
- Shared agent patterns: agent-patterns.md
- Skill conventions checklist: skill-conventions.md
Session Retrospective
Adaptive end-of-session review that converts outcomes into durable process/context/tool improvements. Deep by default; light mode is used with --light or for tiny routine sessions. Produces retro.md alongside plan.md and lessons.md in the session artifact directory.
Quick Start
/retro [path] # adaptive (deep by default)
/retro --deep [path] # full analysis with expert lens
/retro --from-run [path] # internal flag when invoked by cwf:run
path: optional override for output directory--deep: force full 7-section analysis (expert lens, learning resources, web search)--from-run: internal invocation context flag; enables compact report for run-chain orchestration
Workflow
0. Update Live State
Run:
bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh set . phase="retro"
1. Locate Output Directory
Resolution order:
- If
[path]argument provided, use it - Reuse
.cwf/projects/path already used in this session (plan.md/lessons.md writes) - If reused session path date prefix (
YYMMDD) differs from today's local date, AskUserQuestion:- Continue existing session directory (recommended for same logical session across midnight/day rollover)
- Start a new dated directory for today
- If user selects a new dated directory, run
{CWF_PLUGIN_DIR}/scripts/next-prompt-dir.sh --bootstrap <title>, then copyplan.mdandlessons.mdfrom the previous session directory when present so retro context is preserved. - If multiple candidates exist, AskUserQuestion with candidates
- Otherwise run
{CWF_PLUGIN_DIR}/scripts/next-prompt-dir.sh --bootstrap <title>
1.1 Non-Interactive Fallback (Required)
If AskUserQuestion is unavailable/blocked, do not wait. Resolve path in this order: explicit [path] -> live.dir -> latest .cwf/projects/ -> bootstrap via {CWF_PLUGIN_DIR}/scripts/next-prompt-dir.sh --bootstrap retro-light. Record a short note (Fast path or Post-Retro Findings) so the fallback choice is auditable.
1.2 Early Light Fast-Path Short-Circuit (Required)
If invocation includes --light, run deterministic fast path immediately after output-dir resolution (before evidence collection and large artifact reads):
bash {CWF_PLUGIN_DIR}/scripts/retro-light-fastpath.sh \
--session-dir "{output-dir}" \
--invocation "{invocation_mode}" \
--lang "{user-language}"
Then validate retro stage gate immediately:
bash {CWF_PLUGIN_DIR}/scripts/check-run-gate-artifacts.sh \
--session-dir "{output-dir}" \
--stage retro \
--strict
Rules:
- Determine
invocation_modewith the same criteria as Section 3.1 before running this command. - In non-interactive direct runs, stop after this short-circuit path succeeds.
- Do not call AskUserQuestion in this path.
2. Read Existing Artifacts
Skip this section when Section 1.2 completed and execution already ended in non-interactive light mode.
Before reading artifacts, run the evidence collector (it includes best-effort Codex session-log sync with timeout protection):
bash {CWF_PLUGIN_DIR}/scripts/retro-collect-evidence.sh --session-dir "{output-dir}"
Then read retro-evidence.md (if generated), plan.md, lessons.md, and cwf-state.yaml. Read AGENTS/adapter docs and project-context docs only when those files exist.
When running deep mode (or when user explicitly specifies a diff baseline/scope), generate coverage-contract artifacts before drafting narrative sections:
bash {CWF_PLUGIN_DIR}/scripts/retro-coverage-contract.sh \
--session-dir "{output-dir}" \
--base-ref "{retro_base_ref:-HEAD~1}"
Then cite at least:
- total changed file count (artifact name: "diff-all-excl-session-logs.txt")
- top-level breakdown (artifact name: "diff-top-level-breakdown.txt")
- historical lessons/retro primary corpus count (artifact name: "project-lessons-retro-primary.txt")
3. Select Mode
Parse the --deep flag from the invocation arguments.
If --deep is present: mode = deep (full 7 sections).
If --deep is absent: assess session weight to decide mode:
- Light (Sections 1-4 + 7): Only when
--lightis explicitly specified, OR session < 3 turns with routine/simple tasks (config changes, small fixes, doc edits) - Default bias: Deep. Invoking retro is itself a signal that the session warrants analysis. Use
--lightto explicitly request lightweight mode when cost savings is desired.
3.2 Light Fast Path (Required for --light)
Reuse the command and gate in Section 1.2. Do not rerun unless retro.md is missing/invalid. In non-interactive runs, stop after fast path + gate. Do not call AskUserQuestion when fallback policy is sufficient.
3.1 Detect Invocation Context
Determine invocation context from arguments and live task:
- Run-chain invocation:
--from-runpresent, or live task explicitly indicatescwf:run. - Direct user invocation: all other cases.
Persist this as:
invocation_mode: run_chain | direct
4. Draft Retro
Draft everything internally before writing to file.
Light Mode Path
After fast path bootstrap, enrich sections 1-4 and 7 inline only if time/context budget allows. No sub-agents.
Deep Mode Path
Draft sections 1-3 inline (these require full conversation access), then launch parallel sub-agents in two batches.
Resolve session directory: Resolve the effective live-state file, then read live.dir.
live_state_file=$(bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh resolve)
session_dir: "{live.dir value from resolved live-state file}"
Apply the context recovery protocol to these files before launching each batch:
| Batch | Agent | Output file |
|---|---|---|
| 1 | CDM Analysis | {session_dir}/retro-cdm-analysis.md |
| 1 | Learning Resources | {session_dir}/retro-learning-resources.md |
| 2 | Expert α | {session_dir}/retro-expert-alpha.md |
| 2 | Expert β | {session_dir}/retro-expert-beta.md |
Stage-tier policy for deep mode outputs:
- Critical (hard gate):
{session_dir}/retro-cdm-analysis.md - Non-critical (soft gate):
{session_dir}/retro-learning-resources.md,{session_dir}/retro-expert-alpha.md,{session_dir}/retro-expert-beta.md
For all outputs: bounded retry = 1 for missing/invalid files.
- Shared output persistence contract: agent-patterns.md § Sub-agent Output Persistence Contract.
Run slot preflight before each batch launch:
bash {CWF_PLUGIN_DIR}/scripts/agent-slot-preflight.sh --required 2 --json
- If preflight returns
launch_mode=blocked, wait/close active agents and retry once. - If it returns
launch_mode=multi_batch, run the batch sequentially agent-by-agent. - Otherwise keep the default parallel launch.
Batch 1 — launch with the preflight-selected mode (only for agents whose result files are missing or invalid):
- Agent A — CDM Analysis:
subagent_type: general-purpose,max_turns: 16. Read{SKILL_DIR}/references/cdm-guide.md, analyze Sections 1-3 summary + relevantcwf-state.yaml, write Section 4 content to{session_dir}/retro-cdm-analysis.md, append<!-- AGENT_COMPLETE -->. - Agent B — Learning Resources:
subagent_type: general-purpose,max_turns: 20. Find 2-3 external resources using the Web Research Protocol in{CWF_PLUGIN_DIR}/references/agent-patterns.md, write Section 6 content to{session_dir}/retro-learning-resources.md, append<!-- AGENT_COMPLETE -->.
Wait for Batch 1 to complete. Read output files from session directory:
{session_dir}/retro-cdm-analysis.md— CDM analysis (needed by Batch 2 experts){session_dir}/retro-learning-resources.md— Learning resources
Gate behavior after Batch 1:
- If
retro-cdm-analysis.mdremains invalid after retry: hard fail deep retro. - If
retro-learning-resources.mdremains invalid after retry: continue with warning and render Section 6 with explicit omission note. - Record gate path in output (
PERSISTENCE_GATE=HARD_FAILorPERSISTENCE_GATE=SOFT_CONTINUE, or equivalent wording).
Batch 2 — launch with the preflight-selected mode (after Batch 1, only for agents whose result files are missing or invalid):
- Agent C — Expert alpha:
subagent_type: general-purpose,max_turns: 20. Read{CWF_PLUGIN_DIR}/references/expert-advisor-guide.md+{SKILL_DIR}/references/expert-lens-guide.md, analyze Sections 1-4 summary (including CDM output), write to{session_dir}/retro-expert-alpha.md, append<!-- AGENT_COMPLETE -->. - Agent D — Expert beta:
subagent_type: general-purpose,max_turns: 20. Same contract as Expert alpha; write to{session_dir}/retro-expert-beta.md, append<!-- AGENT_COMPLETE -->.
After Batch 2: read output files from session directory ({session_dir}/retro-expert-alpha.md, {session_dir}/retro-expert-beta.md). Draft Section 5 with the required agreement/disagreement synthesis subsection, then draft Section 7 inline (capability/tool scan), then integrate all results into retro.md.
Gate behavior after Batch 2:
- If either expert file remains invalid after retry: continue with warning and render Section 5 from available expert output(s) plus explicit omission note.
- Record soft gate path in output (
PERSISTENCE_GATE=SOFT_CONTINUEor equivalent).
Rationale for 2-batch design: Expert Lens depends on CDM results. Batch 1 produces CDM + Learning in parallel, Batch 2 runs experts after CDM is available.
Section 1: Context Worth Remembering
Use section-writing guidance from section-authoring.md.
Section 2: Collaboration Preferences
Use section-writing guidance from section-authoring.md.
Section 3: Waste Reduction
Use section-writing guidance from section-authoring.md, including mandatory 5 Whys depth for major waste signals.
Section 4: Critical Decision Analysis (CDM)
Use section-writing guidance from section-authoring.md.
Section 5: Expert Lens
Use section-writing guidance from section-authoring.md. Agreement/disagreement synthesis subsection remains mandatory in deep mode.
Section 6: Learning Resources
Use section-writing guidance from section-authoring.md.
Section 7: Relevant Tools (Capabilities Included)
Use section-writing guidance from section-authoring.md, including capability inventory, gap classification, and action path.
5. Write retro.md
Write to {output-dir}/retro.md using the format below.
Immediately enforce deterministic retro artifact gate:
bash {CWF_PLUGIN_DIR}/scripts/check-run-gate-artifacts.sh \
--session-dir "{output-dir}" \
--stage retro \
--strict \
--record-lessons
If this gate fails, do not mark retro complete. Fix artifacts/mode labeling first, then re-run the gate.
6. Link Session Log
Discover runtime logs under:
.cwf/sessions/
- Prefer suffix files:
{YYMMDD}-*.claude.md,{YYMMDD}-*.codex.md - Also allow unsuffixed files:
{YYMMDD}-*.md
Then:
- Filter out already-symlinked candidates.
- Read a sample of each candidate to verify it matches the current session.
- Ensure
{output-dir}/session-logs/exists. - For each verified log, create a relative symlink:
ln -s "{relative-log-path}/{filename}" "{output-dir}/session-logs/{filename}" - If no candidates or directories do not exist, skip silently.
7. Persist Findings
retro.md is session-specific. Persist findings to project-level improvements with a required ownership check before applying the eval > state > doc hierarchy.
7.0 Ownership Gate (Required, before tiering)
For each finding, classify ownership first:
owner=repo— the fix belongs to this repository's local artifacts/policies.owner=plugin— the fix belongs to CWF plugin/runtime/shared tooling behavior.
Then set apply layer deterministically:
owner=repo->apply_layer=localowner=plugin->apply_layer=upstream
Required metadata for every persist proposal:
ownerapply_layerpromotion_targetdue_releaseevidence(command output, artifact path, or session-log line)
Routing rules:
owner=repo: continue with tiering and local target updates.owner=plugin: do not propose local AGENTS/doc edits as the primary fix. Output an upstream backlog item (issue/patch target underplugins/cwf/or related shared runtime files). Local edits are allowed only as clearly marked stopgaps.- If ownership is ambiguous: default to
owner=plugin, state uncertainty explicitly, and avoid adding repo-local policy noise. - Keep durable behavior contracts in AGENTS/runtime adapters. Keep
next-session.mddelta-focused; do not move global contracts there.
After ownership routing, evaluate enforcement mechanisms strongest-first:
-
Tier 1: Eval/Hook (deterministic) — Can a script/hook catch this?
check-session.sh/session_defaultsfor missing artifacts- PreToolUse/PostToolUse hook for tool usage patterns
- Lint rule for style enforcement
-
Tier 2: State (structural) — Does this change workflow state?
cwf-state.yamlschema (new artifacts, stage transitions)session_defaults(new always/milestone artifacts)
-
Tier 3: Doc (behavioral, last resort) — Only for judgment calls
project-context.mdfor architectural patterns- AGENTS.md or runtime adapter docs only for rules that can't be automated
Per-section persist actions:
- S1 Context →
project-context.md(Tier 3 — context is inherently behavioral). Offer to append new context. - S2 Collaboration → Classify owner first, then evaluate tier. AskUserQuestion "Apply?" for AGENTS.md/adapter changes only when
owner=repo. - S3 Waste / Root causes → For each 5 Whys structural cause, present: "Finding: X. Owner: {repo|plugin}. Apply layer: {local|upstream}. Recommended tier: {1|2|3}. Mechanism: {specific change}. Evidence: {concrete trace}." Right-placement check: AGENTS.md (or runtime adapters) for behavioral rules,
project-context.mdfor architectural patterns, protocol/skill docs for process changes. - S4 CDM → Key lessons through tiers (most → Tier 3
project-context.md). - S7 Tools → For
owner=repo, AskUserQuestion "Implement now?". Forowner=plugin, AskUserQuestion "Queue upstream issue/patch now?".
Expert Roster Maintenance (deep mode only, when Section 5 was produced):
- Extract expert names from Section 5 (Expert Lens) output
- Follow the Roster Maintenance procedure in
{CWF_PLUGIN_DIR}/references/expert-advisor-guide.md(including the retro-specific gap analysis step) - Report changes to the user in the retro output (Section 5 or post-section note) for visibility
8. Direct Invocation Report (Mandatory)
After writing retro.md, always report outcomes to the user.
If invocation_mode=direct (user-triggered /retro or cwf:retro):
- Provide
Retro Briefwith 4-6 bullets:- session objective/result
- top waste/root-cause signal
- most important CDM lesson
- critical tool/capability takeaway
- Provide
Persist Proposalswith 2-5 concrete items:- Finding
- Owner (
repo,plugin) - Apply layer (
local,upstream) - Promotion target (gate/script/doc/backlog endpoint)
- Due release (or due date)
- Recommended tier (
Eval-Hook,State,Doc) - Evidence
- Target file/script (local) or upstream backlog target (plugin)
- Apply-now recommendation
- Ask whether to apply persist proposals now:
- repo-owned items: apply locally now? (yes/no)
- plugin-owned items: queue upstream issue/patch now? (yes/no)
If invocation_mode=run_chain:
- Provide compact 2-3 bullet completion report (pipeline continuity first), and include at least one concrete takeaway (waste/root-cause signal, CDM lesson, or next action).
- Include a short
Persist Proposalsmini-list with 1-2 concrete items that each state owner/apply-layer/target (file or backlog). If no actionable item exists, state that explicitly. - Do not ask apply-now questions in run-chain mode; keep this report informative and hand off execution decisions to downstream run/ship flow.
9. Post-Retro Discussion
The user may continue the conversation after the retro. During post-retro discussion:
- Update
retro.md— append under### Post-Retro Findings - Update
lessons.mdwith new learnings - Ownership check first — for each new learning, classify
owner/apply_layer, then evaluate through eval > state > doc. - If
owner=plugin, append an upstream backlog note instead of adding repo-local policy prose. - For deep retro lessons, include metadata lines:
- **Owner**: \repo|plugin``- **Apply Layer**: \local|upstream``- **Promotion Target**: \...``- **Due Release**: \...``
- If plugin code was changed, follow normal release procedures (version bump and release note updates in README/docs as needed)
Do not prompt the user to start this discussion.
Output Format
Use canonical templates from section-authoring.md for both light/deep modes.
Rules
- Never duplicate content already in lessons.md.
- Be specific — cite session moments, not generic advice.
- Keep each section focused; if there is no meaningful signal, state that briefly.
- AGENTS.md/runtime adapter changes require explicit user approval.
- Use the deterministic gate checklist in retro-gates-checklist.md for deep-mode artifacts, persistence tiering, and direct-invocation reporting requirements.
- For Section 5 in deep mode, use
{SKILL_DIR}/references/expert-lens-guide.mdand include the mandatory agreement/disagreement synthesis subsection. - Language override:
retro.mdand deep-mode companion outputs are written in the user's language.
References
{SKILL_DIR}/references/cdm-guide.md— CDM probe methodology and output format{SKILL_DIR}/references/expert-lens-guide.md— Retro-specific expert lens constraints and output format- section-authoring.md — Section 1-7 writing guidance and canonical light/deep output templates
- retro-gates-checklist.md — Deterministic retro artifact gates and reporting checklist
- expert-advisor-guide.md — Expert identity, grounding, selection, and retro mode format
- agent-patterns.md — Shared agent orchestration patterns
Review (/review)
Apply consistent multi-perspective quality gates before implementation (plan) and after implementation (code) via 6 parallel reviewers (2 internal + 2 external slots + 2 domain experts).
Quick Reference
/review Code review (default)
/review --mode plan Plan/spec review
/review --mode clarify Requirement review
/review --mode code --base <base-branch> --scenarios .cwf/projects/holdout.md
/review --mode code --correctness-provider gemini --architecture-provider claude
Recommended linkage:
cwf:plan→cwf:review --mode planbeforecwf:implcwf:impl→cwf:review --mode codebeforecwf:ship
External CLI Setup (one-time)
For full 4-reviewer coverage, authenticate external CLIs:
codex auth login # OpenAI Codex
npx @google/gemini-cli # Google Gemini (interactive first-run setup)
Both are optional — the skill falls back to Claude Task agents when CLIs are missing or unauthenticated. But real CLI reviews provide diverse model perspectives beyond Claude.
Fallback latency: If both external CLIs fail, the skill incurs a two-round-trip penalty — first the CLI attempts run (up to {cli_timeout}s timeout each, scaled by prompt size), then fallback Task agents are launched sequentially. Error-type classification (Phase 3.2) enables fail-fast for CAPACITY errors, reducing wasted time.
Mode Routing
| Input | Mode |
|---|---|
No args or --mode code | Code review |
--mode plan | Plan review |
--mode clarify | Clarify review |
--human | Route to cwf:hitl (do not run review; invoke hitl skill directly) |
Default: --mode code.
When --human is detected (with or without --mode), stop review processing and invoke cwf:hitl instead, passing through any --base flag. This routes the F-8 alias declared in hitl's triggers.
Phase 1: Gather Review Target
Execute these deterministic sub-steps in order:
- parse flags (
--mode,--base,--scenarios, provider overrides) - detect review target by mode (
code/plan/clarify) with explicit base strategy provenance - extract behavioral + qualitative criteria from latest plan artifacts
- validate and merge holdout checks when
--scenariosis provided - compute turn budget + CLI timeout and apply 1200-line external CLI cutoff
- set
web_debug_scope=truewhen browser-runtime evidence is required
Full commands, routing matrix, and provenance fields are in references/target-and-routing.md.
Phase 2: Launch All Reviewers
Launch six reviewers in parallel: 2 internal (Task agents) + 2 external (CLI or Task fallback) + 2 domain experts (Task agents). Default is a single-message launch; when slot capacity is insufficient, split into deterministic batches after preflight.
- Shared output persistence contract: agent-patterns.md § Sub-agent Output Persistence Contract.
2.0 Pre-launch setup
Before slot launch, complete deterministic pre-launch routing:
- resolve
session_dirand apply context-recovery validation for mode-suffixed output files - prepare internal/external prompts (including
web_debug_scopebrowser block when required) - detect provider preflight and route Slot 3/4 providers
- run agent-slot preflight (
--required 6) and choose single-batch or deterministic multi-batch - resolve Slot 5/6 experts from
expert_rosterwith tie-break policy
Full command templates and routing details are in references/target-and-routing.md.
2.3 Launch reviewers (single batch or deterministic batches)
Launch slots with mode-suffixed output persistence:
- Slot 1/2: internal Task reviewers (Security, UX/DX)
- Slot 3/4: provider-routed external reviewers (Correctness, Architecture)
- Slot 5/6: expert Task reviewers with contrasting frameworks, using identities resolved in Phase 2.2.2
Required invariants:
- Every slot writes
{session_dir}/review-*-{mode}.mdand appends<!-- AGENT_COMPLETE -->. - External CLI success copies output into session file before synthesis.
- Use stdin prompt redirection for external CLI execution to avoid prompt-shell injection.
Full slot command templates and persistence snippets are in references/orchestration-and-fallbacks.md.
Phase 3: Collect All Outputs
3.1 Read all results from session directory
Read review verdicts from the session directory files (not in-memory return values):
| Slot | File |
|---|---|
| 1 | {session_dir}/review-security-{mode}.md |
| 2 | {session_dir}/review-ux-dx-{mode}.md |
| 3 | {session_dir}/review-correctness-{mode}.md |
| 4 | {session_dir}/review-architecture-{mode}.md |
| 5 | {session_dir}/review-expert-alpha-{mode}.md |
| 6 | {session_dir}/review-expert-beta-{mode}.md |
Re-validate all six files with the context recovery protocol before synthesis. If any file remains invalid after one bounded retry, apply a hard fail for the stage and stop with explicit file-level error. Report the gate path explicitly (PERSISTENCE_GATE=HARD_FAIL or equivalent).
For external slot executions, also read metadata from temp dir:
{tmp_dir}/slot3-meta.txt/{tmp_dir}/slot4-meta.txtfor provider tool, exit code, and duration{tmp_dir}/slot3-stderr.log/{tmp_dir}/slot4-stderr.logfor error details
For successful external reviews, override the provenance duration_ms with the actual value from the meta file (not any value the CLI may have generated). Use the actual command executed for the command field.
3.2 Handle external failures
Apply the deterministic failure flow:
- classify stderr error type first (capacity/internal/auth/tool-error)
- then apply exit-code fallback policy when no classifier matched
- extract actionable cause text for Confidence Note
- launch all required fallback Task agents in one message
Detailed classifier matrix, exit-code table, and fallback templates are in references/orchestration-and-fallbacks.md.
3.3 Assemble 6 review outputs
Collect all 6 outputs from session directory files (mix of REAL_EXECUTION and FALLBACK sources). Internal reviewers and expert reviewers follow the standard reviewer output format from prompts.md. Expert reviewers follow the review mode format from expert-advisor-guide.md.
3.4 Session-log cross-check (code mode)
When --mode code, perform a deterministic session-log cross-check before synthesis.
Before reading session-log artifacts, run a best-effort Codex sync:
bash {CWF_PLUGIN_DIR}/scripts/codex/sync-session-logs.sh --cwd "$PWD" --quiet || true
Inputs:
- Newest
session-logs/*.md
Required output fields (for Confidence Note):
session_log_present:true|falsesession_log_lines: integer (0when missing)session_log_turns: integer count of^## Turnsession_log_last_turn: last## Turnheader ornonesession_log_cross_check:PASS|WARN
Policy:
- If no session log exists, set
session_log_cross_check=WARNand continue. - Do not omit these fields in code mode.
Phase 4: Synthesize
1. Determine verdict
Apply these rules in order (reviewer-count-agnostic — works with 2, 3, or 4 reviewers):
| Condition | Verdict |
|---|---|
| Any unchecked behavioral criterion | Revise |
Any Concern with severity critical or security | Revise |
Any Concern with severity moderate | Conditional Pass |
| Only Suggestions or no issues found | Pass |
Conservative default: when reviewers disagree, the stricter assessment wins.
2. Render Review Synthesis
Output synthesis to the conversation and persist {session_dir}/review-synthesis-{mode}.md.
Synthesis must include:
- verdict summary
- behavioral criteria/holdout assessment (when provided)
- concerns and suggestions
- commit boundary guidance for tidy vs behavior-policy splits
- confidence note (including base strategy, fallback causes, and session-log fields in code mode)
- reviewer provenance table
Use the full markdown template from references/synthesis-and-gates.md.
The Provenance table adapts to actual results: if an external CLI succeeded, show REAL_EXECUTION with the CLI tool name and measured duration. If it fell back, show FALLBACK with claude-task-fallback.
3. Expert Roster Update
When expert reviewers (Slot 5-6) were used: Follow the Roster Maintenance procedure in {CWF_PLUGIN_DIR}/references/expert-advisor-guide.md.
4. Run-Stage Artifact Gate (code mode)
When --mode code, validate deterministic stage artifacts immediately after synthesis persistence:
bash {CWF_PLUGIN_DIR}/scripts/check-run-gate-artifacts.sh \
--session-dir "{session_dir}" \
--stage review-code \
--strict \
--record-lessons
If this gate fails, stop with file-level errors and require revision before marking review-code complete.
5. Cleanup
After rendering the synthesis, remove the temp directory:
rm -rf {tmp_dir}
This prevents sensitive review content (diffs, plans) from persisting in /tmp/.
Error Handling
Use the deterministic error-handling matrix in references/synthesis-and-gates.md, including scenario/base validation failures, external prompt cutoff behavior, fallback routing, and code-mode artifact/session-log gate outcomes.
Rules
- Always run ALL 6 reviewers — deliberate naivete. Never skip a reviewer because the change "looks simple." Each perspective catches different issues. Expert reviewers complement, not replace — the 4 core reviewers always run.
- Narrative only — no numerical scores, no percentages, no letter grades. Verdicts are Pass / Conditional Pass / Revise.
- Never inline review — always use Task sub-agents. The main agent synthesizes but does not review directly.
- Conservative default — stricter reviewer determines the verdict when reviewers disagree.
- Output to conversation + persist — review synthesis is both communication and downstream input. Always write
{session_dir}/review-synthesis-{mode}.mdalongside the conversation output so retro/handoff can consume it. - Criteria from plan — review verifies plan criteria, it does not invent its own. If no criteria exist, review on general best practices and note the absence.
- Graceful degradation — external CLI failure (missing binary, timeout, auth error) never blocks the review. Fall back to a Task sub-agent with the same perspective. Always record the fallback in the Provenance table and Confidence Note.
- Missing dependency interaction — when failures are caused by missing tools/auth, ask whether to install/configure now before final fallback-only completion.
- No silent holdout bypass — when
--scenariosis provided, the scenario file must be validated and assessed. Never downgrade to "best effort" silently. - Base strategy must be explicit in output — for code mode, always
report which base path was used (explicit
--base, upstream, or fallback). - Critical reviewer outputs hard-fail — if any required review file remains invalid after bounded retry, stop synthesis with explicit file-level error.
- Commit-boundary split for mixed follow-up work — when review findings
imply both
tidyandbehavior-policychanges, recommend separate commit units andtidyfirst. - Preserve explicit decisions — when reviewer suggestions conflict with explicit user decisions or accepted plan constraints, include them under
Considered-Not-Adoptedwith reason/reference. - Capacity-aware launch — run agent-slot preflight before reviewer launch; if capacity is insufficient, use deterministic batches instead of oversubscribing.
- Code-mode session-log fields are mandatory — always include deterministic
session_log_*keys in Confidence Note for--mode code. - Code-mode artifact gate is mandatory —
review-codeis not complete unlesscheck-run-gate-artifacts.sh --stage review-code --strictpasses. - Language override — synthesis output follows the user's language; reviewer prompts remain in English.
- Browser-runtime claims need evidence — when
web_debug_scope=true, reviewers must provide reproducible browser evidence following Web Debug Loop Protocol.
BDD Acceptance Checks
Use the canonical BDD acceptance checks from references/synthesis-and-gates.md when validating review-skill changes.
References
- Internal reviewer perspectives: references/prompts.md
- External reviewer perspectives & CLI templates: references/external-review.md
- Target detection + provider/expert routing details: references/target-and-routing.md
- Orchestration and fallback templates: references/orchestration-and-fallbacks.md
- Synthesis template, error matrix, and BDD checks: references/synthesis-and-gates.md
- Agent patterns (provenance, synthesis, execution, web-debug): agent-patterns.md
- Expert advisor guide (expert sub-agent identity, grounding, review format): expert-advisor-guide.md
Run
Delegate end-to-end workflow orchestration when users do not want to manually sequence each skill.
Quick Start
cwf:run <task description> # Full pipeline from scratch
cwf:run --from impl # Resume from impl stage
cwf:run --skip ship # Full pipeline, skip ship
cwf:run --skip review-plan,retro # Skip specific stages
cwf:run --ambiguity-mode strict # Override T3 handling policy for this run
Operational note:
- Default
cwf:runchain is: gather → clarify → plan → review(plan) → impl → review(code) → refactor → retro → ship. refactorruns before retro/ship to catch cross-skill and docs drift as part of the default delivery quality loop.- Context-deficit resilience applies: stage orchestration must recover from persisted state/artifacts/handoff files, not prior chat memory.
Namespace Routing Guard (Required)
If user input contains the token cwf:run anywhere, keep execution strictly in this CWF run skill.
- Detect by token match, not prefix-only string checks.
- Match the whole token
cwf:run(with optional flags/arguments), not loosecwfsubstrings. - Do not substitute similarly named run flows from other plugins.
- If routing is uncertain, emit
WAIT_INPUTinstead of switching skill families.
Non-Interactive Fail-Fast Policy (Required)
When interactive confirmation is unavailable, do not continue with inferred defaults for setup/readiness gates.
Mandatory behavior:
- Evaluate setup readiness first (Phase 0).
- If readiness is not satisfied, stop immediately before stage initialization.
- Print a deterministic waiting response with exact next actions.
- End the turn immediately after the waiting response.
Standard response header:
WAIT_INPUT: run requires setup readiness before pipeline initialization.
Always include:
Run `cwf:setup` first, then retry `cwf:run`.
Phase 0: Setup Readiness Preflight
Before initializing pipeline state, validate that repository setup prerequisites exist.
-
Run deterministic readiness check:
bash {CWF_PLUGIN_DIR}/scripts/check-setup-readiness.sh --base-dir . --summary -
If check fails, do not initialize live state and do not create run artifacts.
-
Return deterministic waiting output:
WAIT_INPUT: run requires setup readiness before pipeline initialization. Missing setup prerequisites were detected. Run `cwf:setup` first, then retry `cwf:run`.
Phase 1: Initialize
-
Parse task description and flags (
--from,--skip,--ambiguity-mode) -
Resolve base branch (for branch/ship policy):
resolved_base_branch="$(git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's|refs/remotes/origin/||')" if [[ -z "$resolved_base_branch" ]]; then if git show-ref --verify --quiet refs/heads/main; then resolved_base_branch="main" elif git show-ref --verify --quiet refs/heads/master; then resolved_base_branch="master" else echo "WAIT_INPUT: base branch could not be resolved (tried origin/HEAD, main, master)." exit 1 fi fi -
Enforce run-start branch policy:
current_branch="$(git branch --show-current)" if [[ "$current_branch" == "$resolved_base_branch" ]]; then session_slug="{sanitized-title}" run_branch="feat/${session_slug}" if git show-ref --verify --quiet "refs/heads/$run_branch"; then run_branch="feat/${session_slug}-$(date +%H%M%S)" fi git checkout -b "$run_branch" current_branch="$run_branch" fi- If run starts on the base branch (typically
main), create and switch to a dedicated feature branch before stage writes. - If run starts on a non-base branch, keep that branch and treat it as the active run branch.
- If run starts on the base branch (typically
-
Resolve ambiguity mode (
--ambiguity-modeor config default):source {CWF_PLUGIN_DIR}/hooks/scripts/env-loader.sh cwf_env_load_vars CWF_RUN_AMBIGUITY_MODE # precedence: CLI flag > config/env > built-in default resolved_mode="{--ambiguity-mode flag value if provided}" if [[ -z "$resolved_mode" ]]; then resolved_mode="${CWF_RUN_AMBIGUITY_MODE:-defer-blocking}" fi case "$resolved_mode" in strict|defer-blocking|defer-reversible|explore-worktrees) ;; *) echo "Invalid ambiguity mode: $resolved_mode (fallback: defer-blocking)" resolved_mode="defer-blocking" ;; esac -
Bootstrap session directory via
{CWF_PLUGIN_DIR}/scripts/next-prompt-dir.sh --bootstrap <sanitized-title>- This creates the directory, initializes
plan.md/lessons.mdif missing, and pre-registers the session incwf-state.yamlsessionswhen state exists.
- This creates the directory, initializes
-
Initialize live state (session-first write path):
bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh set . \ session_id="{next session ID}" \ dir="{session directory}" \ branch="{current branch}" \ worktree_root="{current git worktree root (absolute path)}" \ worktree_branch="{current branch}" \ phase="gather" \ task="{task description}" \ active_pipeline="cwf:run" \ user_directive="{original user directive}" \ ambiguity_mode="{resolved_mode}" \ blocking_decisions_pending="false" \ ambiguity_decisions_file="{session directory}/run-ambiguity-decisions.md" \ stage_provenance_file="{session directory}/run-stage-provenance.md" \ pipeline_override_reason="" \ state_version="1" planned_closing_gates="{comma-separated subset of review-code,refactor,retro,ship after applying --from/--skip filters}" bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh list-set . \ remaining_gates="$planned_closing_gates" -
Initialize ambiguity ledger file (all modes):
cat > "{session directory}/run-ambiguity-decisions.md" <<'EOF' # Run Ambiguity Decisions mode: {resolved_mode} open_blocking_count: 0 open_non_blocking_count: 0 updated_at: {ISO-8601 UTC} | Decision ID | Stage | Question | Chosen Option | Blocking | Reversible | Follow-up | |---|---|---|---|---|---|---| EOF -
Initialize stage provenance log file:
stage_provenance_file="{session directory}/run-stage-provenance.md" if [[ ! -f "$stage_provenance_file" ]]; then cat > "$stage_provenance_file" <<'EOF' # Run Stage Provenance | Stage | Skill | Args | Started At (UTC) | Finished At (UTC) | Duration (s) | Artifacts | Gate Outcome | |---|---|---|---|---|---|---|---| EOF elif ! grep -Fqx '| Stage | Skill | Args | Started At (UTC) | Finished At (UTC) | Duration (s) | Artifacts | Gate Outcome |' "$stage_provenance_file"; then printf '\n| Stage | Skill | Args | Started At (UTC) | Finished At (UTC) | Duration (s) | Artifacts | Gate Outcome |\n|---|---|---|---|---|---|---|---|\n' >> "$stage_provenance_file" fi -
Report initialization:
Pipeline initialized: {session_dir}
Ambiguity mode: {resolved_mode}
Stages: {list of stages to execute, with skipped ones marked}
Phase 2: Pipeline Execution
Execute stages in order. Each stage invokes the corresponding CWF skill via the Skill tool.
Stage Definition
| # | Stage | Skill Invocation | Gate | Auto |
|---|---|---|---|---|
| 1 | gather | cwf:gather | — | false |
| 2 | clarify | cwf:clarify | T3 policy depends on ambiguity mode | false |
| 3 | plan | cwf:plan | User approves plan | false |
| 4 | review-plan | cwf:review --mode plan | Verdict-based | true |
| 5 | impl | cwf:impl --skip-clarify | — | true |
| 6 | review-code | cwf:review --mode code | Verdict-based | true |
| 7 | refactor | cwf:refactor | — | true |
| 8 | retro | cwf:retro --from-run | — | true |
| 9 | ship | cwf:ship issue → cwf:ship pr (non-base branch) | User confirms PR | false |
Ambiguity Modes (Clarify T3 Policy)
Use live.ambiguity_mode (resolved in Phase 1).
| Mode | Clarify T3 handling | Merge policy |
|---|---|---|
strict | Stop and ask user for every T3 decision | no extra blocking by mode |
defer-blocking | Decide autonomously, but persist unresolved decision debt | unresolved decision debt is merge-blocking at ship |
defer-reversible | Decide autonomously with reversible structure (flags/adapters/switch points) | track debt, non-blocking by default |
explore-worktrees | Implement alternatives in separate worktrees, then pick baseline | blocking depends on final unresolved debt |
When mode is not strict, create/update {session_dir}/run-ambiguity-decisions.md whenever T3 debt exists using this minimum file contract:
# Run Ambiguity Decisions
mode: {mode}
open_blocking_count: {integer}
open_non_blocking_count: {integer}
updated_at: {ISO-8601 UTC}
| Decision ID | Stage | Question | Chosen Option | Blocking | Reversible | Follow-up |
|---|---|---|---|---|---|---|
| ... | clarify | ... | ... | yes/no | yes/no | issue/pr ref or TODO |
explore-worktrees operational flow
Use the deterministic worktree creation/validation/reconcile flow from references/stage-operations.md.
Stage Execution Loop
For each stage (respecting --from and --skip), execute deterministic loop from references/stage-operations.md, including:
- worktree consistency gate
- live-state phase + remaining gate updates
- best-effort session-log sync for
review-code|retro|ship - stage invocation timing capture
- clarify-stage ambiguity synchronization
- run-closing artifact gate (
check-run-gate-artifacts.sh --strict) - user/auto gate handling
- mandatory stage-provenance row append for all outcomes
Review Failure Handling
Use deterministic Revise/Fail handling from references/stage-operations.md. Invariant: max 1 auto-fix attempt for Revise; Fail always hard-stops and requires explicit user decision.
--from Flag
Follow deterministic precheck path in references/stage-operations.md. check-run-from-prereqs.sh output is authoritative for prerequisite pass/fail.
--skip Flag
Follow deterministic skip behavior in references/stage-operations.md.
Phase 3: Completion
After all stages complete (or the pipeline is halted):
-
Run session completeness check:
bash {CWF_PLUGIN_DIR}/scripts/check-session.sh --impl session_dir=$(bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh get . dir) stage_provenance_file=$(bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh get . stage_provenance_file) gate_args=() for closing_stage in review-code refactor retro ship; do if awk -F'|' -v stage="$closing_stage" ' BEGIN { found=0 } /^\|/ { s=$2; outcome=$9 gsub(/^[[:space:]]+|[[:space:]]+$/, "", s) gsub(/^[[:space:]]+|[[:space:]]+$/, "", outcome) if (s == stage && outcome != "Skipped") { found=1 } } END { exit(found ? 0 : 1) } ' "$stage_provenance_file"; then gate_args+=(--stage "$closing_stage") fi done if [[ "${#gate_args[@]}" -gt 0 ]]; then bash {CWF_PLUGIN_DIR}/scripts/check-run-gate-artifacts.sh \ --session-dir "$session_dir" \ "${gate_args[@]}" \ --strict \ --record-lessons else echo "No run-closing stages were executed; skip final run-closing artifact gate." fiIf any FAIL items are reported, fix them before proceeding; this is a forced function and the pipeline is not complete until all checks pass. If gate output includes
Retro soft-gate omissions (PERSISTENCE_GATE=SOFT_CONTINUE), copy those items into the final pipeline summary underRetro Gate Follow-ups(do not compress into a generic warning). -
Update state:
- Clear pending gates first:
bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh list-set . remaining_gates="" - Set final phase and clear active pipeline:
bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh set . phase="done" active_pipeline="" user_directive="" pipeline_override_reason="" blocking_decisions_pending="false" - Ensure the current session entry in
cwf-state.yamlstays consistent with final artifacts/summary (registration is initialized during Phase 1 bootstrap)
- Clear pending gates first:
-
Report pipeline summary:
## Pipeline Complete
### Stages Executed
| Stage | Status | Notes |
|-------|--------|-------|
| gather | completed | — |
| clarify | completed | — |
| plan | completed | — |
| review-plan | Pass | — |
| impl | completed | 3 commits |
| review-code | Conditional Pass | 1 concern addressed |
| refactor | completed | docs/skills drift check |
| retro | completed | — |
| ship | skipped | --skip flag |
### Artifacts
- Plan: {path to plan.md}
- Lessons: {path to lessons.md}
- Retro: {path to retro.md}
- Stage provenance: {session_dir}/run-stage-provenance.md
- Session dir: {session_dir}
### Retro Gate Follow-ups
- {none | each retro soft-gate omission from check-run-gate-artifacts output}
Rules
- Decision #19 baseline: Pre-impl stages require human gates and post-impl stages chain automatically. Ambiguity defer modes are explicit, scoped overrides for clarify-stage T3 debt only.
- One auto-fix attempt: Never loop more than once on a review failure. Escalate to user after 1 retry.
- Skill invocation only: Use the Skill tool to invoke CWF skills. Do not inline skill logic.
- State tracking: Use
cwf-live-state.sh setandlist-setat every stage transition so session-local live state stays current while root summary remains synchronized. - Preserve skill autonomy: Each invoked skill manages its own sub-agents, artifacts, and output.
cwf:runorchestrates but does not micromanage. - Flags compose:
--from impl --skip retrois valid. Apply both filters. - Graceful halt: When the user chooses "Stop", update state and report what was completed. Do not leave state in an inconsistent phase.
- Do not bypass impl branch gate by default:
cwf:runmust not pass--skip-branchtocwf:implunless the user explicitly requests bypass. - Context-deficit resilience: On resume/restart, reconstruct stage context from
cwf-state.yaml, session artifacts, and handoff docs before invoking downstream skills. - Worktree consistency gate: During an active pipeline, if current worktree root diverges from
live.worktree_root, stop immediately and request explicit user decision before any write/edit/ship action. - Fail-closed run gates: While
active_pipeline="cwf:run"andremaining_gatesincludesreview-code, ship/push/commit intents must be blocked unlesspipeline_override_reasonis explicitly set. - Artifact gate is mandatory for stage closure:
review-code,refactor,retro, andshipare not complete unlesscheck-run-gate-artifacts.sh --strictpasses for that stage. - Setup readiness is mandatory before run init:
cwf:runmust executecheck-setup-readiness.shand halt withWAIT_INPUTwhen prerequisites are missing. - Ambiguity mode precedence:
--ambiguity-modeflag overrides config. Config (CWF_RUN_AMBIGUITY_MODE) overrides built-in default (defer-blocking). - Defer modes require persistence: Any non-
strictT3 carry-over must be recorded in{session_dir}/run-ambiguity-decisions.mdand synchronized tolive.blocking_decisions_pendingviasync-ambiguity-debt.sh. - defer-blocking merge discipline: If unresolved blocking debt exists, ship must treat it as merge-blocking until linked issue/PR follow-up is recorded and blocking count reaches zero.
- Per-stage provenance is mandatory: Every stage outcome (
Proceed/Revise/Fail/Skipped/User Stop) must append a provenance row, including early-stop paths before halt/return. - Review
Failis notRevise:Failhalts automation immediately and requires explicit user direction before any downstream stage. - Run-start branch creation is mandatory: When
cwf:runstarts on the resolved base branch, create/switch to a dedicated feature branch before editing. - Non-base ship must create issue and PR: When the active branch is not the resolved base branch, ship stage must execute issue creation and PR creation (or report existing URLs) instead of stopping at status-only output.
References
- agent-patterns.md — Shared agent orchestration patterns
- plan-protocol.md — Session artifact location/protocol
- check-setup-readiness.sh — Deterministic setup preflight guard for
cwf:run - check-run-from-prereqs.sh — Deterministic
--fromprerequisite gate for stage resume safety - references/stage-operations.md — Detailed stage loop, ambiguity worktree flow, and review-failure handling
Setup
Standardize hooks, tool contracts, and project/runtime config wiring once so later workflow runs stay reproducible. Includes interactive hook toggles, external tool detection, setup-contract bootstrap for repo-adaptive suggestions, project config bootstrap, optional Agent Team mode setup, optional Codex integration, optional git hook gate installation, optional CWF capability index generation, and optional repository index generation.
Quick Start
cwf:setup # Full setup (hooks + tools + config + Agent Team + optional Codex/repo-index prompts)
cwf:setup --hooks # Hook group selection only
cwf:setup --tools # External tool detection only
cwf:setup --env # Project config bootstrap + runtime priority guidance only
cwf:setup --agent-teams # Agent Team mode setup only
cwf:setup --run-mode # Configure default cwf:run ambiguity mode only
cwf:setup --codex # Codex integration-only rerun (scope-aware skills/references sync)
cwf:setup --codex-wrapper # Codex wrapper-only rerun (scope-aware wrapper setup)
cwf:setup --git-hooks both --gate-profile balanced # Install repo git hooks and set gate depth
cwf:setup --git-hooks pre-commit --gate-profile fast # Lightweight local-only git gate
cwf:setup --git-hooks none # Remove repo-managed git hooks
cwf:setup --cap-index # Generate/refresh CWF capability index only
cwf:setup --repo-index # Generate/refresh repository index (explicit)
cwf:setup --repo-index --target agents # AGENTS.md managed block target
cwf:setup --repo-index --target file # Standalone index file target
cwf:setup --repo-index --target both # AGENTS block + standalone index file
Operational note:
- Prefer
cwf:setupfirst; it is the default entrypoint and asks for optional integrations when relevant. - Use
--codex/--codex-wrapperwhen reapplying only Codex-related integration pieces.
Mode Routing
Parse input flags and run only the relevant phases:
| Input | Phases |
|---|---|
cwf:setup | 1 → 2 → 2.8 → 2.9 → 2.10 → 2.4 (if codex available) → 2.7 (always ask) → 4 (opt-in) → 5 |
cwf:setup --hooks | 1 → 5 |
cwf:setup --tools | 2 → 2.8 → 2.9 → 2.10 → 5 |
cwf:setup --env | 2.8 → 2.10 → 5 |
cwf:setup --agent-teams | 2.9 → 5 |
cwf:setup --run-mode | 2.10 → 5 |
cwf:setup --codex | 2.5 → 5 |
cwf:setup --codex-wrapper | 2.6 → 5 |
cwf:setup --git-hooks <none|pre-commit|pre-push|both> [--gate-profile <fast|balanced|strict>] | 2.7 → 5 |
cwf:setup --cap-index | 3 → 5 |
cwf:setup --repo-index [--target <agents|file|both>] | 4 → 5 |
When mode is full setup and Codex CLI is available, do not silently skip Codex integration; always run Phase 2.4 and ask the user which integration level to apply.
When mode is full setup, do not expect users to supply optional flags manually. Always ask for git hook installation mode and gate profile in Phase 2.7.
When mode is full setup or tools-only setup, always run Phase 2.8 so project config files are bootstrapped with explicit user choice.
When mode is full setup or tools-only setup, always run Phase 2.9 so Agent Team mode is explicitly aligned with CWF's multi-agent workflow assumptions.
When mode is full setup, tools-only setup, env-only setup, or run-mode-only setup, always run Phase 2.10 so cwf:run default ambiguity policy is explicit and reproducible.
Namespace Routing Guard (Required)
If user input contains the token cwf:setup anywhere (start, middle, or end), keep execution strictly in this CWF setup skill.
- Detect by token match, not prefix-only string checks.
- Match the whole token
cwf:setup(with optional flags/arguments after it), not loosecwfsubstrings. - Do not substitute similarly named setup flows from other plugins.
- If routing is uncertain, emit
WAIT_INPUTfor the first unresolved setup phase instead of switching skill families.
Non-Interactive Fail-Fast Policy (Required)
When AskUserQuestion is unavailable or blocked, do not wait silently and do not end with empty output.
Mandatory behavior:
- Resolve mode and identify the first unresolved user-choice phase before running heavy phases (full setup starts at phase
1.2). - Stop immediately at that first unresolved phase when AskUserQuestion is unavailable/blocked.
- Print a deterministic
WAIT_INPUTresponse with phase id, options, and a direct reply instruction. - End the turn immediately after printing the waiting response.
Standard response header:
WAIT_INPUT: setup requires user selection at phase <phase-id>.
Examples:
- phase
2.8(project config bootstrap):- option 1: create missing templates (recommended)
- option 2: overwrite templates (
--force) - option 3: skip for now
- phase
2.10(run ambiguity mode):- option 1:
defer-blocking(recommended) - option 2:
strict - option 3:
defer-reversible - option 4:
explore-worktrees
- option 1:
Always include:
Please reply with your choice.
Phase 1: Hook Group Selection
Configure which hook groups are active. Default: all enabled (hooks work without running cwf:setup).
1.1 Read Current State
Read cwf-state.yaml hooks: section for current toggle state.
1.2 Present Selection
Use AskUserQuestion with multiSelect: true. Present 9 hook groups with descriptions:
| Group | Description |
|---|---|
attention | Slack notifications on idle/waiting |
log | Auto-log turns + auto-commit transcripts |
read | File-size aware reading guard |
lint_markdown | Markdown validation after Write/Edit |
lint_shell | ShellCheck validation after Write/Edit |
deletion_safety | Blocks risky file deletions and requires policy-compliant justification |
workflow_gate | Enforces workflow stage/branch safety rules before edits and commands |
websearch_redirect | Redirect WebSearch to cwf:gather |
compact_recovery | Inject live session state after auto-compact and guard session↔worktree binding on prompts |
Pre-select groups that are currently enabled in cwf-state.yaml.
1.3 Write Hook Config
Apply selected hook groups with deterministic sync script:
bash {SKILL_DIR}/scripts/sync-hook-state.sh --enable "<comma-separated selected groups>"
This command writes ~/.claude/cwf-hooks-enabled.sh with:
# Generated by cwf:setup
export HOOK_ATTENTION_ENABLED="true"
export HOOK_LOG_ENABLED="true"
export HOOK_READ_ENABLED="true"
export HOOK_LINT_MARKDOWN_ENABLED="false"
export HOOK_LINT_SHELL_ENABLED="true"
export HOOK_DELETION_SAFETY_ENABLED="true"
export HOOK_WORKFLOW_GATE_ENABLED="true"
export HOOK_WEBSEARCH_REDIRECT_ENABLED="true"
export HOOK_COMPACT_RECOVERY_ENABLED="true"
- One
export HOOK_{GROUP}_ENABLEDline per group (uppercased) - Values:
"true"or"false"(quoted strings) - Must match the variable names expected by
cwf-hook-gate.sh
1.4 Update cwf-state.yaml
The same command updates cwf-state.yaml hooks: to mirror selections:
hooks:
attention: true
log: true
read: true
lint_markdown: false
lint_shell: true
deletion_safety: true
workflow_gate: true
websearch_redirect: true
compact_recovery: true
Before moving on, verify parity:
bash {SKILL_DIR}/scripts/sync-hook-state.sh --check
Phase 2: External Tool Detection
Detect availability of external AI/search tools and local runtime dependencies used by CWF checks/skills.
2.1 Check Tools
Run external tool checks (codex, gemini, agent-browser, API keys) and local dependency checks (shellcheck, jq, gh, node, python3, lychee, markdownlint-cli2) as defined in tool-detection-and-deps.md.
2.2 Update cwf-state.yaml
Rewrite cwf-state.yaml tools: section with the detection results.
2.3 Report Results
Report detection groups:
- AI/search/browser tools + API-key presence
- local runtime dependency status
2.3.1 Missing Dependency Install Prompt (Required)
If missing dependencies exist, ask install strategy (Install missing now, Show commands only, Skip for now) and execute the matching branch from tool-detection-and-deps.md.
2.3.2 Retry Check (After Install Attempt)
After install attempts, re-run dependency check and explicitly report unresolved tools before continue/stop decision.
2.3.3 Post-Install Re-Detection + cwf-state.yaml Rewrite (Required)
When Install missing now was selected, re-run 2.1 -> 2.2 -> 2.3 in full so cwf-state.yaml stays SSOT. This is mandatory even when unresolved dependencies remain.
2.3.4 Setup Contract Bootstrap + Repo-Tool Proposal (Required for full/tools setup)
Bootstrap setup contract draft (.cwf/setup-contract.yaml by default), report contract status (created|existing|updated|fallback), and ask whether to apply repo-specific tool suggestions now. If bootstrap returns fallback, stop setup immediately and resolve bootstrap failure first.
2.3.5 agent-browser Capability Install Prompt (Optional but Recommended)
If Phase 2 reports agent-browser: unavailable, ask whether to install browser-debug capability now.
- If approved, run the install/retry branch from tool-detection-and-deps.md and re-check availability once.
- If declined, continue setup and report that browser-runtime automation paths will be limited until installed.
Detailed checks, prompts, and commands: tool-detection-and-deps.md.
Phase 2.4: Codex Integration on Full Setup (Scope-Aware)
Use this phase when:
- Mode is full setup (
cwf:setup) - Phase 2 detected
codex: available
2.4.1 Resolve Active Plugin Scope
Resolve scope using detect-plugin-scope.sh and parse key-value output without eval (safe parser examples are in codex-scope-integration.md).
Mandatory behavior:
- Always print detected values before prompting: active scope, installed scopes, active install path, active project path.
- If detection fails or returns
none, do not silently default touser; ask user to choose target scope explicitly. - When selected scope is
projectorlocaland root is empty, resolve fallback root using git top-level (or current cwd).
2.4.2 Ask Integration Scope + Level
Use AskUserQuestion prompts exactly as defined in codex-scope-integration.md:
- scope target prompt
- integration level prompt (
Skills + wrapper,Skills only,Skip)
Safety guard:
- If active scope is non-user and target is
user, require a second explicit confirmation before mutation.
2.4.3 Execute Selection
Run command matrix from codex-scope-integration.md:
Skills + wrapper: runsync-skills.sh, theninstall-wrapper.sh --enable(add PATH only in user scope), then wrapper status.Skills only: runsync-skills.sh.Skip for now: no mutation.
2.4.4 Always Print Post-Setup Verification + Rollback
When wrapper installation was selected, always report:
install-wrapper.sh --statustype -a codex- before-vs-after summary (scope, touched paths, rollback command)
Detailed rollback/report templates are in codex-scope-integration.md, including alias boundary notes for absolute-path aliases/functions.
Phase 2.5: Codex Scope-Aware Skill Sync (Optional)
Use this phase when:
- User runs
cwf:setup --codex - Full setup and user wants Codex to load CWF from local repo via symlink
2.5.1 Resolve Scope
Reuse Phase 2.4.1. Prompt/override details are in codex-scope-integration.md.
2.5.2 Run Sync Script
Run sync-skills.sh with selected scope and optional --project-root exactly as defined in codex-scope-integration.md.
2.5.3 Report Results
Report checklist and verification commands are in codex-scope-integration.md.
Phase 2.6: Codex Scope-Aware Wrapper Opt-In (Optional)
Use this phase when:
- User runs
cwf:setup --codex-wrapper - Full setup and user wants Codex session logs auto-synced into repo artifacts with post-run quality checks
2.6.1 Resolve Scope
Reuse Phase 2.4.1. Prompt/override details are in codex-scope-integration.md.
2.6.2 Ask for Opt-In
Use AskUserQuestion prompt text from codex-scope-integration.md. If user declines, skip this phase.
2.6.3 Install Wrapper (Approved Only)
Run wrapper install command matrix from codex-scope-integration.md:
- user scope uses
--add-path - project/local scope uses
--project-root
2.6.4 Report and Reversal
Status, rollback, PATH notes, and post-run tuning options are documented in codex-scope-integration.md.
Phase 2.7: Git Hook Gate Installation
Use this phase when:
- Mode is full setup (
cwf:setup) - User runs
cwf:setup --git-hooks ...
Mandatory execution order:
-
Resolve hook install mode (
--git-hooksor AskUserQuestion). -
Resolve gate profile (
fast|balanced|strict) unless mode isnone. -
Bootstrap run gate contract:
bash {SKILL_DIR}/scripts/bootstrap-gate-contract.sh --json -
If contract status is
fallback, stop setup (fail-safe) and request path/permission fix. -
Report effective hook state + contract policy summary (
auto -> portable, explicitauthoringpath only for maintainer flows).
Detailed prompts, command matrix, and reporting checklist: runtime-and-index-phases.md.
Phase 2.8: Project Config Bootstrap
Use this phase when:
- Mode is full setup (
cwf:setup) - User runs
cwf:setup --tools - User runs
cwf:setup --env
Mandatory behavior:
- Ask whether to create templates, overwrite templates, or skip.
- Run scripts/bootstrap-project-config.sh (
--forceonly for overwrite). - Report effective runtime priority (
.cwf-config.local.yaml>.cwf-config.yaml> process env > shell exports). - If interactive prompts are unavailable, emit deterministic
WAIT_INPUTand stop this run.
Detailed prompts, command templates, and reporting checklist: runtime-and-index-phases.md.
Phase 2.9: Agent Team Mode Setup
Use this phase when:
- Mode is full setup (
cwf:setup) - User runs
cwf:setup --tools - User runs
cwf:setup --agent-teams
Mandatory behavior:
- Ask mode policy (
enable,keep,disable). - Apply via scripts/configure-agent-teams.sh with
--enable,--status, or--disable. - Report effective status and remind restart/new session requirement.
Detailed prompts, command templates, and reporting checklist: runtime-and-index-phases.md.
Phase 2.10: cwf:run Ambiguity Mode Setup
Use this phase when:
- Mode is full setup (
cwf:setup) - User runs
cwf:setup --tools - User runs
cwf:setup --env - User runs
cwf:setup --run-mode
Mandatory behavior:
- Detect current effective
CWF_RUN_AMBIGUITY_MODE(default fallback:defer-blocking). - Ask desired default mode (
defer-blocking|strict|defer-reversible|explore-worktrees). - Ask target config scope (
shared|local). - Persist via scripts/configure-run-mode.sh, bootstrapping project templates when needed.
- Report selected mode/scope/path and precedence order (
--ambiguity-modeflag > local config > shared config > env/shell > built-in default). - If interactive prompts are unavailable, emit deterministic
WAIT_INPUTand stop this run.
Detailed prompts, command templates, and reporting checklist: runtime-and-index-phases.md.
Phase 3: Generate CWF Capability Index (Explicit)
This phase runs only when --cap-index is explicitly requested.
Mandatory behavior:
- build capability index from current CWF inventories
- keep deterministic ordering and link policy
- validate coverage with
check-index-coverage.sh --profile cap - if validation fails, regenerate and fix before finish
Detailed generation and validation checklist: runtime-and-index-phases.md.
Phase 4: Generate Repository Index (Optional)
Generate repository index when explicitly requested or approved in full setup.
Mandatory behavior:
- ask include/skip decision in full setup
- resolve output target via
--targetor repository-context detection (agents,file,both) - build deterministic inventories and ordering
- update selected output target(s) deterministically
- validate coverage with
check-index-coverage.sh --profile repo
Detailed generation and validation checklist: runtime-and-index-phases.md.
Phase 5: Lessons Checkpoint
5.1 Ask for Learnings
Ask for learnings and append lessons.md with the standard Expected/Actual/Takeaway format when provided.
5.2 Update Stage Checkpoints
Add setup to cwf-state.yaml current session's stage_checkpoints list.
Detailed lessons/checkpoint format: runtime-and-index-phases.md.
Rules
- State SSOT + idempotency: Read and edit
cwf-state.yaml(do not overwrite wholesale), and keep reruns safe/idempotent across all phases. - Single-entry setup UX: Full setup (
cwf:setup) must execute the integrated optional decision flow for Codex, hooks, setup-contract proposal, config bootstrap, agent-teams, and run-mode phases in one run. - Index generation is explicit and deterministic: Capability index runs only via
--cap-index; repository index runs via--repo-indexwith target resolution (agents,file,both) from CLI or repository context. - Index coverage/link policy is mandatory: Generated indexes must use Markdown relative links and pass deterministic coverage checks (cap/repo profiles).
- File safety: Codex sync must use symlink + backup move (no direct user file deletion).
- Scope-aware Codex integration: Resolve active plugin scope first; non-user context must not mutate user-global Codex paths without explicit user confirmation.
- No fail-open scope fallback: If scope detection fails or returns
none, require explicit user scope selection before any Codex mutation. - Setup-contract first-run invariant: Full/tools setup must bootstrap setup-contract and explicitly report
created|existing|updated|fallbackstatus.fallbackis fail-safe and must halt setup. - Formatting invariant: All code fences in this skill must include language specifiers.
- Run gate contract invariant: Setup must bootstrap run gate contract and report its status/path so external repos do not silently rely on implicit gate defaults.
References
- cwf-hook-gate.sh — hook gate mechanism
- hooks.json — hook definitions
- agent-patterns.md — Single pattern
- references/tool-detection-and-deps.md — detailed checks/prompts for setup Phase 2 tool detection and dependency handling
- references/setup-contract.md — setup-contract bootstrap and repo-specific tool suggestion flow
- references/codex-scope-integration.md — detailed prompt/command matrix for setup Phase 2.4/2.5/2.6
- references/runtime-and-index-phases.md — detailed prompt/command matrix for setup Phase 2.7/2.8/2.9/2.10 and Phase 3/4/5
- detect-plugin-scope.sh — active Claude plugin scope detection for cwd
- sync-skills.sh — Codex scope-aware skill sync
- install-wrapper.sh — Codex scope-aware wrapper management
- verify-skill-links.sh — Codex skill link validation
- scripts/configure-git-hooks.sh — installs and profiles repository git hook gates
- scripts/check-configure-git-hooks-runtime.sh — validates configure-git-hooks runtime behavior across profile/force paths
- scripts/bootstrap-gate-contract.sh — bootstraps repository-local run gate contract (
{artifact_root}/gate-contract.yaml) - assets/githooks/pre-commit.template.sh — pre-commit hook template rendered by
configure-git-hooks.sh - assets/githooks/pre-push.template.sh — pre-push hook template rendered by
configure-git-hooks.sh - scripts/bootstrap-project-config.sh — project config template/bootstrap and
.gitignoresync - scripts/configure-agent-teams.sh — toggles Claude Agent Team runtime mode in
~/.claude/settings.json - scripts/configure-run-mode.sh — persists default
cwf:runambiguity mode into project config - scripts/bootstrap-setup-contract.sh — bootstraps repository-local setup contract (
.cwf/setup-contract.yaml) from core baseline + repo scan - scripts/check-setup-contract-runtime.sh — validates setup-contract bootstrap status semantics (
created|existing|updated|fallback, with fail-safe fallback) - scripts/install-tooling-deps.sh — checks/installs missing local runtime dependencies for CWF workflows
- scripts/check-index-coverage.sh — deterministic index coverage validation
- .cwf-cap-index-ignore — optional intentional exclusion list for capability index coverage
- .cwf-index-ignore — optional intentional exclusion list for repository index coverage
Ship (/ship)
Convert validated CWF session artifacts into issue → PR → merge execution with explicit human merge control.
Quick Start
/ship Show usage
/ship issue [--base B] [--no-branch] Create issue + feature branch
/ship pr [--base B] [--issue N] [--draft] Create PR linked to issue
/ship merge [--squash|--merge|--rebase] Check & merge if ready
/ship status Show open issues, PRs, checks
No args or help → print the usage block above and stop.
Defaults
- Base branch: auto-detect remote default branch →
main→master(override with--base) - Merge strategy:
--squash(override with--mergeor--rebase)
Prerequisites
Before any subcommand, verify:
command -v gh >/dev/null 2>&1 || { echo "gh CLI not found"; exit 1; }
gh auth status 2>&1 | grep -q "Logged in" || { echo "Not authenticated — run: gh auth login"; exit 1; }
If either fails, do not stop with a passive failure only. Ask the user:
Install/configure now (recommended):- if
ghis missing, runbash {SKILL_DIR}/../setup/scripts/install-tooling-deps.sh --install gh - if auth is missing, run
gh auth login - then retry prerequisite checks once
- if
Show commands only:- print exact install/auth commands and stop
Skip ship for now:- stop without executing ship actions
Output Persistence (Mandatory)
For every /ship invocation (issue, pr, merge, status, and help or no-args):
- Resolve session directory from live state (
live.dir). - Persist a structured execution summary to
{session_dir}/ship.mdwith these required sections:## Execution Status## Ambiguity Resolution## Next Step
- In
## Ambiguity Resolution, always write these scalar lines:mode: strict|defer-blocking|defer-reversible|explore-worktreesblocking_open_count: <integer>blocking_issue_refs: <comma-separated refs or none>issue_ref: <issue URL or none>pr_ref: <PR URL or none>merge_allowed: yes|no- Resolve
modefrom live state (live.ambiguity_mode) and derive counts from{session_dir}/run-ambiguity-decisions.mdif it exists. - For
defer-blocking,merge_allowedmust benowhenblocking_open_count > 0. - When the current branch is not the resolved base branch,
issue_refandpr_refmust contain concrete GitHub URLs before ship-stage closure.
- Synchronize live ambiguity debt state before gate closure:
bash {CWF_PLUGIN_DIR}/scripts/sync-ambiguity-debt.sh \
--base-dir . \
--session-dir "{session_dir}"
- When running under
cwf:run, enforce the stage gate:
bash {CWF_PLUGIN_DIR}/scripts/check-run-gate-artifacts.sh \
--session-dir "{session_dir}" \
--stage ship \
--strict \
--record-lessons
/ship issue
Create a GitHub issue for the current session and optionally a feature branch.
Workflow
-
Detect session context:
- Find the current session directory in
.cwf/projects/(most recentYYMMDD-NN-*) - Read
plan.mdif it exists for purpose, scope, success criteria - Read master-plan (search for
master-plan.mdor similar) for session number - Resolve
{base}:- if
--baseis provided, use it - otherwise detect with
git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's|refs/remotes/origin/||' - if unresolved, fallback to
main, thenmaster; if none exists, ask the user for base branch explicitly
- if
- Find the current session directory in
-
Compose issue body:
- Read
{SKILL_DIR}/references/issue-template.md - Substitute variables from session context:
{BACKGROUND}— why this work is needed; extract from plan.md context/motivation section, or summarize from session history{PROBLEM}— specific problem being solved; from plan.md or ask the user{GOAL}— desired outcome; from plan.md objectives or ask the user{SCOPE}— files/areas from plan.md or summarize{BRANCH}— the feature branch name to be created{BASE}— the base branch{PLAN_LINK}— relative path to plan.md{RETRO_SUMMARY}— concise retro outcome summary from.cwf/projects/{session}/retro.md- Prefer
Post-Retro Findingswhen present - Otherwise synthesize up to 3 bullets from waste/CDM/tools sections
- If retro artifact is missing, use
_No retro summary recorded yet._
- Prefer
{RETRO_PERSIST_PROPOSALS}— actionable persistence proposals from retro/lessons- Include owner/apply-layer/target when available
- If no actionable proposal exists, use
_No persistence proposal recorded yet._
- If plan.md is missing or incomplete, ask the user for the missing fields
- Read
-
Create issue:
gh issue create \ --title "S{N}: {title}" \ --body "$(cat <<'EOF' {composed_body} EOF )" \ --label "cwf-v3"- If
cwf-v3label doesn't exist, create it first:gh label create cwf-v3 --color 0E8A16 --description "CWF v3 migration"
- If
-
Create feature branch (unless
--no-branch):git checkout {base} && git pull origin {base} git checkout -b feat/{short-name} -
Report: Print issue URL and branch name.
/ship pr
Create a pull request from the current feature branch.
Workflow
-
Pre-flight checks (stop with message if any fail):
- Resolve
{base}using the same rule as/ship issue - Not on the resolved base branch
- Has commits ahead of base:
git log {base}..HEAD --onelineis non-empty - No uncommitted changes:
git status --porcelainis empty- If dirty, ask user whether to commit first or abort
- Resolve
-
Auto-detect linked issue:
- If
--issue Nprovided, use that - Otherwise:
gh issue list --label cwf-v3 --search "S{N}" --json number,title - Match by session number from the current session artifact directory name
- If no match found, proceed without issue link (warn the user)
- If
-
Build PR body from
{SKILL_DIR}/references/pr-template.md:{ISSUE_LINK}—Closes #{N}if issue found, otherwise omit{PURPOSE}— synthesize fromgit log {base}..HEAD --onelineand plan.md; describe why this change exists, not what files changed{DECISIONS}— extract key decisions from:.cwf/projects/{session}/lessons.mdtakeaways.cwf/projects/{session}/retro.mdCDM section.cwf/projects/{session}/plan.mddecision points- Format as markdown table:
| Decision | Rationale | Alternatives |(in user's language) - If no decisions found, write a brief "no significant decisions" note (in user's language)
{VERIFICATION}— concrete, reproducible verification steps:- Include exact commands to run (e.g.,
claude --plugin-dir ... -p "...") - Describe expected output/behavior
- Cover both happy path and edge cases if relevant
- Include exact commands to run (e.g.,
{HUMAN_JUDGMENT}— agent self-assessment of items needing human review:- Architecture changes, UX decisions, security implications, breaking changes
- Read
live.ambiguity_modeand{session_dir}/run-ambiguity-decisions.mdwhen present - If mode is
defer-blockingandblocking_open_count > 0, list all open blocking decision debts here (never writeNone) - If none, write
None(this enables autonomous merge — see/ship merge)
{SYSTEM_IMPACT}— behavioral changes visible to end users or dependent systems{FUTURE_IMPACT}— impact on future development (new patterns, constraints, tech debt){GIT_DIFF_STAT}— output ofgit diff {base}...HEAD --statwrapped in a```textcode fence{LESSONS}— extract from.cwf/projects/{session}/lessons.mdif exists, otherwise write_No lessons recorded for this session._{CDM}— extract from.cwf/projects/{session}/retro.mdCDM section if exists, otherwise write_No CDM recorded yet._{RETRO_SUMMARY}— concise retro outcome summary from.cwf/projects/{session}/retro.md- Prefer
Post-Retro Findingswhen present - Otherwise synthesize up to 3 bullets from waste/CDM/tools sections
- If retro artifact is missing, use
_No retro summary recorded yet._
- Prefer
{RETRO_PERSIST_PROPOSALS}— actionable persistence proposals from retro/lessons- Include owner/apply-layer/target when available
- If no actionable proposal exists, use
_No persistence proposal recorded yet._
{CONDITIONAL_ITEMS}— add checklist items based on changed file types:*.shchanged →- [ ] Scripts are executable and pass shellcheckSKILL.mdchanged →- [ ] SKILL.md under 500 linesplugin.jsonchanged →- [ ] Version bumped appropriatelyhooks.jsonchanged →- [ ] Hook matchers are correct*.mdchanged →- [ ] Markdown lint passes
-
Push and create PR:
git push -u origin $(git branch --show-current)gh pr create \ --title "S{N}: {title}" \ --body "$(cat <<'EOF' {composed_body} EOF )" \ --base {base}- Add
--draftif the user specified it
- Add
-
Report: Print PR URL.
/ship merge
Check PR status and merge if ready.
Workflow
-
Find current PR:
gh pr view --json number,state,reviewDecision,statusCheckRollup,mergeable,headRefName- If no PR found for current branch, report and stop
-
Assess readiness:
Core checks (always required):
state=OPEN- All status checks passed (parse
statusCheckRollup) mergeable=MERGEABLE
Review requirement (conditional):
- Parse the PR body for
## Human Judgment Requiredsection - Check branch protection:
gh api repos/{owner}/{repo}/branches/{base}/protection 2>&1 - Parse
{session_dir}/run-ambiguity-decisions.mdand/orship.mdambiguity block:- if
mode: defer-blockingandblocking_open_count > 0, merge is blocked
- if
Decision matrix:
Human judgment Branch protected Review required defer-blockingwith open blocking debtAny Stop — do not merge Noneor emptyNo Skip — autonomous merge Noneor emptyYes reviewDecision=APPROVEDrequiredItems listed Any Report items, stop — do not merge If not ready, report which conditions are blocking and stop. Do not attempt to merge.
-
Merge:
gh pr merge {N} --squash --delete-branch- Use
--mergeor--rebaseif the user specified an override - Default is
--squash
- Use
-
Post-merge cleanup:
git checkout {base} && git pull origin {base} -
Report: Merge confirmation, deleted branch name.
/ship status
Read-only overview of current GitHub state.
Workflow
-
Open issues:
gh issue list --label cwf-v3 --state open --json number,title,assignees -
Open PRs:
gh pr list --json number,title,state,headRefName,reviewDecision,statusCheckRollup -
Current branch PR (if exists):
gh pr view --json number,title,state,reviewDecision,mergeable,statusCheckRollup- If no PR for current branch, note that
-
Session progress (optional):
- If
master-plan.mdexists, parse the session roadmap - Show completed vs remaining sessions
- If
-
Report: Format as a readable summary table.
Error Handling
| Situation | Action |
|---|---|
gh not installed | Ask whether to install now via setup installer script; if declined/fails, print manual commands and stop |
| Not authenticated | Report, suggest gh auth login, stop |
| No commits ahead of base | Report "nothing to PR", stop |
| Issue already exists for session | Show existing issue, ask user before creating duplicate |
| PR already exists for branch | Show existing PR URL, stop |
| Merge conflicts | Report, suggest git rebase {base} instructions, stop |
Missing lessons.md or retro.md | Use placeholder text, do not fail |
Label cwf-v3 missing | Create it automatically |
| Dirty working tree on PR | Ask user: commit or abort |
Usage Message
When invoked with no args or help, print:
Ship — GitHub workflow automation for cwf sessions
Usage:
/ship Show this message
/ship issue [--base B] [--no-branch] Create issue + feature branch
/ship pr [--base B] [--issue N] [--draft] Create PR
/ship merge [--squash|--merge|--rebase] Merge approved PR
/ship status Show issues, PRs, checks
Defaults: base=auto-detected (origin/HEAD -> main -> master), merge=squash
Rules
- Use
ghas the primary interface; do not craft raw GitHub API payloads whenghalready supports the operation. - Stop immediately on failed prerequisites (
ghmissing, unauthenticated, or invalid branch state). - Keep PR purpose and decision sections evidence-backed from session artifacts when available (
plan.md,lessons.md,retro.md). - Never auto-merge when human-judgment items are present in the PR body.
- Preserve user-created files and branches; do not perform destructive cleanup beyond explicit merge cleanup.
- All code fences must have language specifiers.
- Missing prerequisites must trigger an install/configure choice prompt, not a passive "missing tool" report only.
/shipmust always persist{session_dir}/ship.mdbefore returning.- In
defer-blockingmode, unresolved ambiguity debt is merge-blocking until tracked follow-up references are recorded andblocking_open_countis zero. - Language override: issue/PR narrative sections are written in the user's language; code blocks, file paths, commit hashes, and CLI output remain verbatim.
retrooutcomes and persistence proposals must be visible in issue/PR body sections, not only hidden in collapsed details blocks.
References
- issue-template.md — Issue body template
- pr-template.md — PR body template
- agent-patterns.md — Shared workflow pattern reference
Update
Keep installed CWF behavior aligned with the latest marketplace version and fixes, with scope-aware reconciliation for Codex integration paths.
Quick Start
cwf:update # Check + auto-update selected scope if newer version exists
cwf:update --check # Version/scope/reconcile check only (no install, no mutation)
Phase 0: Resolve Update Scope (Required)
0.1 Detect Active Plugin Scope
Resolve active scope using the safe parsing flow in scope-reconcile.md (no eval).
Mandatory behavior:
- Always print active scope, installed scopes, active install path, and active project path before prompting.
- If detection fails or returns
none, do not default touser; ask for explicit target scope. - If selected scope is
project/localand project root is missing, resolve fallback root via git top-level (or current cwd).
0.2 Confirm Target Scope (Multi-Scope Safety)
Use scope selection prompt/options from scope-reconcile.md.
Safety guard:
- If active scope is non-user and selected target is
user, require a second explicit confirmation before update/reconcile mutation. - If the chosen scope is not installed, stop and report valid installed scopes.
Phase 1: Version Check (Selected Scope)
1.1 Find Current Version + Baseline Snapshot
Resolve current installed entry from claude plugin list --json for selected scope:
plugin_list_json="$(claude plugin list --json 2>/dev/null || printf '[]')"
current_install_path="$(
printf '%s' "$plugin_list_json" \
| jq -r --arg scope "$selected_scope" \
'[.[] | select(.id | startswith("cwf@")) | select(.scope == $scope) | .installPath] | first // empty'
)"
[ -n "$current_install_path" ] || {
echo "CWF is not installed in scope: $selected_scope"
exit 1
}
current_plugin_json="$current_install_path/.claude-plugin/plugin.json"
[ -f "$current_plugin_json" ] || {
echo "plugin.json not found for selected scope: $current_plugin_json"
exit 1
}
current_plugin_root="$current_install_path"
current_version="$(jq -r '.version' "$current_plugin_json")"
baseline_root="$(mktemp -d "${TMPDIR:-/tmp}/cwf-before.XXXXXX")"
cp -a "$current_plugin_root"/. "$baseline_root"/
old_diff_root="$baseline_root"
1.2 Update Marketplace Metadata
Always refresh marketplace metadata first:
claude plugin marketplace update corca-plugins
1.3 Compare Versions (Authoritative + Fail-Closed)
Run authoritative consistency checker after marketplace refresh:
consistency_json="$(
bash {CWF_PLUGIN_DIR}/scripts/check-update-latest-consistency.sh \
--mode top-level \
--scope "$selected_scope" \
--json
)"
Parse result:
verdict="$(printf '%s' "$consistency_json" | jq -r '.verdict // "UNVERIFIED"')"
consistency_reason="$(printf '%s' "$consistency_json" | jq -r '.reason // "UNKNOWN"')"
checked_current_version="$(printf '%s' "$consistency_json" | jq -r '.current_version // empty')"
authoritative_latest_version="$(printf '%s' "$consistency_json" | jq -r '.authoritative_latest // empty')"
Fail-closed rule:
if [ "$verdict" = "UNVERIFIED" ]; then
echo "Latest-version verification is UNVERIFIED (reason: $consistency_reason)."
echo "Do not emit success-style no-update verdicts in this state."
echo "Re-run from a top-level environment where marketplace update + authoritative fetch are available."
exit 2
fi
Then set compare values and post-marketplace snapshot:
[ -n "$checked_current_version" ] || {
echo "Current version missing from consistency check output."
exit 1
}
[ -n "$authoritative_latest_version" ] || {
echo "Authoritative latest version missing from consistency check output."
exit 1
}
current_version="$checked_current_version"
latest_version="$authoritative_latest_version"
authoritative_snapshot_root="$(mktemp -d "${TMPDIR:-/tmp}/cwf-after-marketplace.XXXXXX")"
cp -a "$current_install_path"/. "$authoritative_snapshot_root"/
new_diff_root="$authoritative_snapshot_root"
Report:
Target scope: user|project|local
Current version: 0.6.0
Latest version: 0.7.0
Verdict: UP_TO_DATE|OUTDATED
Persist for later phases: old_diff_root, new_diff_root, current_version, latest_version, verdict, selected_scope, selected_project_root.
Phase 2: Apply Update (Scope-Aware)
Skip this phase if --check was used or verdict=UP_TO_DATE, and report that no update mutation was applied when the skip reason is parity. verdict=UNVERIFIED never enters this phase (fail-closed in Phase 1.3).
2.1 Apply Update to Selected Scope (No Confirmation Prompt)
Run scope-aware update:
echo "Updating CWF in scope $selected_scope from $current_version to $latest_version..."
claude plugin update "cwf@corca-plugins" --scope "$selected_scope"
If update command is unavailable in current runtime, fallback:
claude plugin install "cwf@corca-plugins" --scope "$selected_scope"
2.2 Refresh Installed Snapshot
Re-resolve selected-scope install path after update and overwrite new_diff_root:
post_list_json="$(claude plugin list --json 2>/dev/null || printf '[]')"
installed_install_path="$(
printf '%s' "$post_list_json" \
| jq -r --arg scope "$selected_scope" \
'[.[] | select(.id | startswith("cwf@")) | select(.scope == $scope) | .installPath] | first // empty'
)"
[ -n "$installed_install_path" ] || {
echo "Installed CWF metadata not found after update for scope: $selected_scope"
exit 1
}
installed_plugin_json="$installed_install_path/.claude-plugin/plugin.json"
installed_version="$(jq -r '.version' "$installed_plugin_json")"
post_install_root="$(mktemp -d "${TMPDIR:-/tmp}/cwf-after-install.XXXXXX")"
cp -a "$installed_install_path"/. "$post_install_root"/
new_diff_root="$post_install_root"
latest_version="$installed_version"
2.3 Report Success
CWF updated in scope {selected_scope} to {installed_version}. Restart Claude Code for changes to take effect.
Phase 3: Codex Integration Reconciliation (Scope-Aware)
Goal: repair stale Codex symlink/wrapper targets when plugin install paths change across versions.
3.1 Detect Existing Codex Integration for Selected Scope
Detect integration signals using the detailed flow in scope-reconcile.md.
Detection output must track:
skills_link_presentwrapper_activewrapper_link_present(wrapper link exists even whenActiveis false)
3.2 Reconcile (Mutation Rules)
- If
--check: never mutate; report detection only and print recommended reconcile commands. - If update was applied in Phase 2:
- when
skills_link_present=true, runsync-skills.shfor selected scope. - when
wrapper_link_present=trueorwrapper_active=true, runinstall-wrapper.sh --enablefor selected scope (without--add-path) to repoint stale wrapper links. - when neither is present, report "no existing Codex integration to reconcile" and skip mutation.
- when
Command templates are maintained in scope-reconcile.md.
3.3 Report Reconcile Summary (Before vs After)
Always report:
- selected scope and project root (if any)
- whether skills links were detected and reconciled
- whether wrapper link/active state was detected and reconciled
type -a codexfor command-resolution visibility- rollback commands:
bash {CWF_PLUGIN_DIR}/scripts/codex/install-wrapper.sh --scope "$selected_scope" ${selected_project_root:+--project-root "$selected_project_root"} --disable
For skill-link rollback, direct user to scope backup roots:
- user:
~/.agents/.skill-sync-backup/* - project/local:
{projectRoot}/.codex/.skill-sync-backup/*
Include alias boundary note:
- aliases that call
codexby command name inherit wrapper behavior - aliases/functions that call absolute paths bypass wrapper behavior and need manual adjustment
Phase 4: Change Summary (Opt-In)
After update/check, ask whether to summarize diff evidence.
Use AskUserQuestion:
Show change summary for differences between {current_version} and {latest_version}?
Options: Yes, summarize / No, skip
- If user selects
No, skip, do not run diff commands and continue. - If user selects
Yes, summarize, collect and summarize diff evidence with stable roots:
- Build file-change inventory:
git --no-pager diff --no-index --name-status "$old_diff_root" "$new_diff_root" || true
- Diff README for user-facing guidance changes:
git --no-pager diff --no-index \
"$old_diff_root/README.md" \
"$new_diff_root/README.md" || true
- Summary procedure:
- Summarize notable
SKILL.md/script/manifest changes from name-status diff. - Add README delta as "user-facing setup/usage guidance changes".
- If diff evidence is sparse, state that explicitly and keep the summary minimal.
- Summarize notable
Phase 5: Lessons Checkpoint
Add update to cwf-state.yaml current session's stage_checkpoints list if lessons were recorded during the update process.
Rules
- Resolve scope first: Always resolve and report active/selected scope before version check or update.
- Update marketplace first: Always run marketplace update before plugin update/install.
- Scope-aware apply: Update/install must target explicit scope via
--scope. - Auto-apply when newer version exists: In normal mode (not
--check), apply update immediately without a separate update-confirmation prompt. - Reconcile Codex links after update: For existing Codex integrations in selected scope, run reconcile in the same update flow.
- No fail-open scope fallback: If scope detection fails or returns
none, require explicit scope selection before mutation. - No mutation in check mode:
cwf:update --checkmust not install/update/reconcile; it reports status and suggested commands only. - Change summary is opt-in: Run change summary only when the user explicitly requests it in Phase 4.
- Authoritative latest only: cache is supporting evidence, not oracle; latest-version verdict must come from authoritative metadata path.
- UNVERIFIED is fail-closed: never present
No update neededwhen verdict isUNVERIFIED. - Top-level verification required: release confidence claims require top-level marketplace update + authoritative fetch success.
- Changes take effect after restart: Always remind user to restart Claude Code.
- All code fences must have language specifier: Never use bare fences.
References
- README.md — File-map entry for this skill directory (not release notes)
- agent-patterns.md — Single pattern
- references/scope-reconcile.md — detailed scope resolution and Codex reconcile matrix
- check-update-latest-consistency.sh — authoritative latest-version consistency checker (
contract,top-level) - detect-plugin-scope.sh — active Claude plugin scope detection for cwd
- sync-skills.sh — Codex scope-aware skill sync
- install-wrapper.sh — Codex scope-aware wrapper management
Sponsors
Details
- Marketplace
- corca-ai/claude-plugins
- Source
- plugins/cwf
- Category
- Community
- Keywords
- workflow, cwf, skills, hooks, clarify, plan, impl, retro, refactor, gather, review, ship, handoff, hitl
