Corca Workflow Framework — consolidated hooks and skill orchestration for structured development sessions

version
1.0.1
GitHub stars
75

Install

/plugin install cwf@corca-plugins

Run it inside Claude Code after adding the marketplace with /plugin marketplace add corca-ai/claude-plugins.

Contents

Discovered from source

Skills 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:

  1. If next-session.md exists in the active session directory or current workspace, read it as optional prior-session context.
  2. Always parse the user's task description (required input).
  3. Check if the combined input provides: target file paths, expected changes per file, and BDD-style success criteria.
  4. Apply this heuristic:
Input specificityClarify depthRationale
All 3 present (files + changes + criteria)AskUserQuestion only — ask 2-3 binary/choice questions for remaining ambiguities, skip Phases 2-2.5Prior session retro effectively served as clarify
1-2 present--light mode — iterative Q&A without sub-agentsPartial clarity, direct questions suffice
None present (vague requirement)Default mode — full research + expert analysisScope 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

  1. Record the original requirement verbatim
  2. 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
  3. 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).

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:

  1. Read expert_roster from cwf-state.yaml
  2. Analyze decision points for domain keywords; match against each roster entry's domain field
  3. Select 2 experts with contrasting frameworks — different analytical lenses on the same problem
  4. 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:

  1. Research context: What codebase and web research found
  2. Advisor α's position: Their argument (brief)
  3. Advisor β's position: Their argument (brief)
  4. 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):

  1. Run: bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh set . clarify_completed_at="{ISO 8601 UTC timestamp}"
  2. 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):

  1. cwf:review --mode clarify — Multi-perspective review of the clarified requirement before implementation
  2. cwf: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, as plan.md carries 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

  1. Record the requirement verbatim
  2. 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):

  1. Run: bash {CWF_PLUGIN_DIR}/scripts/cwf-live-state.sh set . clarify_completed_at="{ISO 8601 UTC timestamp}"
  2. 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

  1. Research first, ask later (default mode): Exhaust research before asking
  2. Cite evidence: Every autonomous decision must include specific evidence
  3. Respect the tiers: Do not ask about T1/T2; do not auto-decide T3
  4. Constructive tension: Conflicts between sources are signals, not problems
  5. Persistent but not annoying: Why-dig on vague answers, accept clear ones
  6. Preserve intent: Refine the requirement, don't redirect it
  7. Grounded experts: Best practice research must cite real published work
  8. Honest advisors: Advisory opinions argue in good faith, not strawman
  9. Expert evidence is supplementary: Expert analysis enriches classification but does not override direct codebase or best-practice evidence

References

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

  1. Parse args → mode (URL | --search | --local | help)
  2. No args or "help" → print usage message and stop
  3. Execute the appropriate handler (see sections below)
  4. Resolve + prepare OUTPUT_DIR before writes (URL and --local modes)
  5. Suggest follow-up: after URL gathering, suggest --search for supplementary research if helpful

Before any file write, resolve output path in this order:

  1. Explicit CLI output-dir argument
  2. Service-specific output env var
  3. CWF_GATHER_OUTPUT_DIR
  4. .cwf/projects (when writable)
  5. workspace-local gather-output fallback 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 PatternHandlerScript / Tool
docs.google.com/{document,presentation,spreadsheets}/d/*Google Exportscripts/g-export.sh
*.slack.com/archives/*/p*Slack to MDscripts/slack-api.mjs + scripts/slack-to-md.sh
*.notion.site/*, www.notion.so/*Notion to MDscripts/notion-to-md.py
github.com/*GitHubgh CLI
Any other URLGenericscripts/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:

  1. Install gh now (recommended) — run bash {SKILL_DIR}/../setup/scripts/install-tooling-deps.sh --install gh, then retry GitHub handler once.
  2. Continue with Generic handler — proceed with reduced metadata extraction.
  3. Skip this URL — do not process this GitHub URL in this run.
URL typeCommand
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 URLFall 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:

  1. Resolve paths:

    • slug: sanitized title/url token (lowercase, spaces to hyphens, remove special characters, max 50 chars)
    • output_md: {OUTPUT_DIR}/{slug}.md
    • output_meta: {OUTPUT_DIR}/{slug}.meta.yaml
  2. 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:
      1. non_http_scheme — scheme is not http or https
      2. localhost_target — host is localhost or ends with .localhost
      3. loopback_target — host/IP in 127.0.0.0/8 or ::1/128
      4. link_local_target — host/IP in 169.254.0.0/16 or fe80::/10
      5. private_ipv4_target — host/IP in RFC1918 ranges (10/8, 172.16/12, 192.168/16)
      6. private_ipv6_target — host/IP in fc00::/7
    • Default behavior for blocked URLs: do not run extraction.
    • Required interactive override path:
      1. Override once for this URL and continue (explicit user confirmation required)
      2. Skip this URL (default)
    • If override is not explicitly confirmed, stop processing this URL and write failed metadata.
  3. Try Tavily extract first:

    {SKILL_DIR}/scripts/extract.sh "<url>" > "{output_md}.tmp"
    
    • Success contract: exit code 0 and temp file has non-whitespace content.
    • On success: move temp file to {output_md} and set metadata method: tavily-extract.
    • If TAVILY_API_KEY is missing or extraction fails, continue to Step 4.
  4. 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 metadata method: webfetch-fallback.
  5. Empty-output handling:

    • Treat as failure when {output_md} is missing, whitespace-only, or the fallback response equals WEBFETCH_EMPTY.
    • On failure, do not keep partial markdown output.
  6. Metadata capture (always required):

    • Write {output_meta} with at least:
      • source_url
      • retrieved_at_utc (ISO 8601 UTC)
      • handler: generic
      • safety_precheck:
        • status (passed, blocked, or overridden)
        • blocked_reason_code (empty when passed)
        • host
        • resolved_ips
      • method (tavily-extract, webfetch-fallback, or none)
      • status (success or failed)
      • output_file (empty when failed)
      • failure_reason (when failed)
    • For safety-blocked URLs without explicit override, set:
      • status: failed
      • method: none
      • output_file: ""
      • failure_reason: url_safety_blocked

--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

CommandBackendScript
--search <query>Tavilyscripts/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>Exascripts/code-search.sh

Execution

  1. Read query-intelligence.md for routing and parameter decisions
  2. Route: code prefix or auto-detected code context → code-search.sh; otherwise → search.sh
  3. Apply query intelligence (temporal, topic, token allocation) per reference
  4. 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>"
    
  5. 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_KEY or EXA_API_KEY) in shell profile/process env, run cwf:setup --tools if runtime dependencies are also missing, then retry the same search once. Do not rely on cwf:setup --env for 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 --local argument
  • query_slug: sanitized query token (lowercase, spaces to hyphens, remove special characters, max 50 chars)
  • output_md: {OUTPUT_DIR}/local-{query_slug}.md
  • output_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:

  1. Run Task once using the prompt contract above.
  2. Validate output contract (output_md exists, has non-whitespace content, and ends with <!-- AGENT_COMPLETE -->).
  3. If invalid or Task fails, retry once with the same input and explicit correction.
  4. If retry still fails, stop local gather for this query and report failure clearly.

Provenance metadata guidance:

  • Always write output_meta with: mode: local, query_raw, query_slug, subagent_type, attempts, status, output_md (if any), generated_at_utc.
  • When failed, include failure_reason and preserve diagnostics from the last Task run.

Configuration

VariableDefaultDescription
CWF_GATHER_OUTPUT_DIR.cwf/projectsUnified 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

  1. URL auto-detect priority: Match most specific pattern first (Google > Slack > Notion > GitHub > Generic)
  2. Graceful degradation: Missing API keys print setup instructions, don't crash
  3. Output dir hierarchy: CLI argument > service-specific env var > unified env var > .cwf/projects (if writable) > gather-output fallback directory
  4. Data privacy: Do not include confidential code or sensitive information in search queries
  5. Sub-agent for --local: Always use Task tool, never inline exploration
  6. All code fences must have language specifier: Never use bare fences
  7. Missing dependency interaction: For missing required tools/keys, ask to install/configure now; do not only report unavailability.
  8. Web debug queries use shared protocol: Browser-runtime debugging requests in --local mode must follow Web Debug Loop Protocol and persist evidence paths.

References

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_stage and workflow.stages — where we are
  • sessions — full session history
  • session_defaults — expected artifacts

1.2 Identify Current Session

Determine the current session by:

  1. Check for a session directory matching today's date in .cwf/projects/
  2. Match against the most recent entry in cwf-state.yaml sessions
  3. 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 Actions section if present (unchecked items: - [ ])
  • 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

Phase 2: Determine Next Session

2.1 With master-plan.md

If master-plan.md exists (search via Glob in .cwf/projects/):

  1. Read the session roadmap section
  2. Find the current session ID in the roadmap
  3. Extract the next session's definition: title, scope, dependencies
  4. 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:

  1. Read workflow.stages for the stage progression
  2. Determine what comes next based on current stage
  3. 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 structure
  • Execution 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):

  1. Context Files to Read
  2. Task Scope
  3. Don't Touch
  4. Lessons from Prior Sessions
  5. Success Criteria
  6. Dependencies
  7. Dogfooding
  8. Execution Contract (Mention-Only Safe)
  9. 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:

  1. 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
  2. Design Decisions: Key choices made during clarify/gather with rationale. Source from clarification summaries, user decisions, and discussion outcomes
  3. Protocols: Rules and behavioral protocols discovered or established during the current phase. Source from lessons.md entries and explicit user instructions
  4. Prohibitions: Explicit "do not" constraints. Source from user instructions, clarify decisions, and scope boundaries
  5. Implementation Hints: Practical guidance for the implementer — insertion points, patterns to follow, gotchas
  6. Success Criteria: BDD-format criteria. May reference plan.md criteria 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:

  1. Find a matching session by dir (primary), then by id (fallback).
  2. If found, continue to 4.2/4.2b.
  3. If no match exists, run this explicit missing-entry branch:
    1. Draft a minimal session entry from known context: id, title, dir, branch, artifacts: [] (and stage_checkpoints: [] when used in the project).
    2. Ask user decision before insertion: "Create missing session entry now" | "Edit fields first" | "Cancel registration".
    3. If "Create missing session entry now": append the draft entry to sessions, then continue to 4.2/4.2b.
    4. If "Edit fields first", run this loop:
      • Editable fields: id, title, dir, branch.
      • Non-editable at creation: artifacts: [] (and stage_checkpoints: [] when used in the project).
      • Validate before re-confirm: id must not duplicate an existing session id, dir must not duplicate an existing session dir.
      • 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.
    5. If "Cancel registration" from the initial decision: stop registration and report that artifacts were not updated.

4.2 Update Current Session (next-session mode)

  • Add next-session.md to the artifacts list
  • Update summary if not already set
  • Set completed_at to today's date (via date +%Y-%m-%d)
  • Clear live section: set all scalar fields to "" and lists to []

4.2b Register Phase Handoff (--phase mode)

When --phase flag is used:

  • Add phase-handoff.md to the current session's artifacts list in cwf-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.sh checks 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

  1. From Deferred Actions (plan.md): Extract unchecked items (- [ ]) from the ## Deferred Actions section
  2. From Lessons (lessons.md): Identify entries with unimplemented resolution proposals (keywords: "구현은 별도 세션", "스코프 밖", "future", "deferred", "separate session", "out of scope")
  3. 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

  1. Canonical template over recent example: Read plan-protocol.md Handoff Document section for format. Do not copy-paste a recent next-session.md — derive from the protocol.
  2. master-plan.md is preferred but optional: The skill must work for projects without a master plan by falling back to user input.
  3. Lessons aggregation is selective: Only include lessons relevant to the next session's task. Do not dump all historical lessons.
  4. Dogfooding section references discovery mechanism: Point to skills/ directory, not a hardcoded skill list.
  5. Don't Touch inference is conservative: When uncertain, include the boundary. Better to over-protect than under-protect.
  6. BDD criteria are concrete: Reference actual files, features, or behaviors — not abstract qualities.
  7. cwf-state.yaml is SSOT: Read before modifying. Edit, do not overwrite.
  8. Never overwrite existing files: When a file already exists (e.g., next-session.md from a prior run), use Edit to update — not Write. Write replaces entire file contents and destroys prior work.
  9. All code fences must have language specifier: Never use bare fences.
  10. 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.
  11. 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.
  12. 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.
  13. Phase handoff is intra-session: It transfers context between phases within the same session. completed_at is not set and Phase 4b/5 are skipped.
  14. Draft-then-review: Always present the generated phase-handoff.md to the user for review before finalizing.
  15. Execution contract is required: next-session.md must include "Execution Contract (Mention-Only Safe)".
  16. Contract must include branch+commit gates: Mention-only execution must define base-branch escape and meaningful commit unit rules.
  17. Missing session entry must be resolved first: Never update artifacts, summary, or completed_at until a matching sessions entry exists (find-or-create with user confirmation).

References

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

  1. Resolve base branch:
    • explicit --base wins
    • otherwise upstream default branch
    • fallback main
  2. Resolve review scope (docs|code|all, default all).
  3. Build diff target: git diff --name-only <base>...HEAD.
  4. If --resume, load from live.hitl.state_file pointer in cwf-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.yaml live.hitl.state_file

Phase 0.5: Agreement Round (Default)

Before chunk review starts, run one agreement round in the same cwf:hitl flow (no extra mode/flag):

  1. Collect major decision points from available ship artifacts first (issue/PR body, review summaries, merge notes).
  2. Merge user-provided concerns/questions for this HITL run.
  3. Record agreements in hitl-scratchpad.md:
    • agreed wording/policy decisions
    • rationale
    • open questions
    • pending implementation items
  4. Apply high-impact agreed edits that should be reflected before chunk-by-chunk review.
  5. Immediately update hitl-scratchpad.md again after edits:
    • mark items as Applied / In progress
    • note what was changed and what remains
    • refresh the Updated timestamp
  6. 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.

  1. Trigger condition: the user reports manual edits/overwrites, or HITL detects out-of-band file changes.
  2. On trigger, update the intent-resync fields in state.yaml using the contract in hitl-state-model.md, and append the trigger to events.log.
  3. Before presenting any next chunk, check intent_resync_required.
  4. If true, run resync first:
    • re-read the changed target files
    • summarize what changed and confirm updated intent with the user
    • update hitl-scratchpad.md with the confirmed intent delta
    • clear the resync gate and set last_intent_resync_at per state model contract
  5. Only continue chunk review after the flag is cleared.

Phase 1: Build Deterministic Queue

  1. Build file queue from diff files in stable sorted order.
  2. Capture each file's blob_sha and set initial file status to pending.
  3. Build chunk queue per file:
    • Markdown: heading/fence-safe semantic chunks (typically 60-120 lines)
    • Code/text: prefer git hunk boundaries; fallback fixed windows
  4. Assign chunk IDs and initial chunk status pending.
  5. Seed deterministic context_refs per chunk and save to queue.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.
  6. Initialize state.yaml, fix-queue.yaml, and events.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:

  1. Primary Chunk ({file}:{start_line}-{end_line} and EOF 여부)
  2. Primary Excerpt
  3. Related Context (at least 1 context excerpt with path/line anchors + relation)
  4. Causal Lens (symptom, likely root cause, guardrail/invariant)
  5. Review Focus (Line-Anchored) with at least 2 concrete points
  6. Consistency Check:
    • docs: link syntax + reference integrity checks
    • code: call-path/definition-path impact checks
  7. 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)

  1. Resolve related context before presenting the chunk and persist the selected context_refs.
  2. Keep the same context refs stable across retries/resume unless file drift invalidates anchors.
  3. If semantic matches are not found, use structural fallback context (adjacent chunk/heading) and mark relation as adjacent_fallback.
  4. Never present a chunk without at least one related context reference.

Review-Fix Policy During Loop

  1. Mark the current file/chunk as in_review while presenting it.
  2. If the user asks to fix the currently open chunk, apply immediately (natural conversational flow).
  3. If a fix targets an already reviewed file/chunk, default action is to append to fix-queue.yaml first (do not silently rewrite previously closed sections).
  4. If the user explicitly requests immediate edit on a reviewed area, apply the edit and mark overlapping reviewed chunks as stale.
  5. Stale chunks are revisited via delta-review before final close.

Phase 3: Rule Capture and Propagation

When user gives an improvement rule:

  1. Normalize rule text into a durable entry in rules.yaml.
  2. Record scope (docs or code, path globs, severity/priority).
  3. Scan remaining queue for candidate matches.
  4. 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:

  1. Read state.yaml cursor.
  2. Validate queued file/chunk still exists.
  3. Compare saved blob_sha with current file blob:
    • unchanged: preserve statuses
    • changed: mark previously reviewed overlapping chunks as stale
  4. If lines drift, re-anchor by nearest previous heading/hunk.
  5. Continue with same chunk contract, prioritizing stale before untouched pending.

Close

On --close (or EOF completion):

  1. Mark session state completed (or closed_by_user).
  2. Keep rule history and event log immutable.
  3. Update cwf-state.yaml pointer updated_at.
  4. Output concise completion summary (files/chunks reviewed, rules applied, fix-queue pending/applied, stale re-reviewed count).

Rules

  1. Persist state before every user pause.
  2. Never discard accepted rules within the active session.
  3. Pointer-only policy: keep detailed HITL state in .cwf/projects/{session-dir}/hitl/; store only pointers in cwf-state.yaml.
  4. During Phase 1 migration, do not move other skills' artifact paths automatically.
  5. Maintain meaningful commit-unit boundaries when applying fixes during HITL.
  6. Default policy: in_review fixes can be immediate; reviewed fixes go to fix-queue unless the user requests immediate application.
  7. Any edit touching previously reviewed content must mark overlapping chunks stale and trigger delta-review before close.
  8. Default entry behavior: start with the agreement round (Phase 0.5), then move to chunk review.
  9. Keep artifacts separated by role: fix-queue.yaml for actionable edits, hitl-scratchpad.md for agreements/rationale.
  10. After any agreed edit is applied, update hitl-scratchpad.md before continuing.
  11. No isolated chunk reviews: every presented chunk must include Related Context.
  12. For both code and docs, use one principle: Primary Chunk + Related Context + Causal Lens.
  13. Root-Cause Discussion Prompt must focus on cause validation, not symptom restatement.
  14. For comment-driven doc HITL (for example README reflection), keep the same chunk contract and include Before, After, After Intent within the Primary Chunk section.
    • Before/After must include enough surrounding context for user judgment (for example, the full paragraph or subsection, not a single isolated sentence).
  15. 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.
  16. If user manual edits are detected/reported, trigger Phase 0.75 immediately (set intent_resync_required=true and append trigger to events.log).
  17. While intent_resync_required=true, apply the Phase 0.75 block rule (no next chunk presentation).
  18. Clear intent_resync_required only through the Phase 0.75 completion contract (hitl-scratchpad.md intent delta + last_intent_resync_at update).
  19. During active HITL doc review, document edits and scratchpad state must stay synchronized; post-run checks should flag missing scratchpad updates.
  20. 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:

  1. Scan .cwf/projects/*/plan.md using Glob.
  2. Rank candidates with this priority (highest first):
    • Session pin from live state: if plan.md exists inside live.dir from 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.md modification time.
    • Directory name order: use only as a final deterministic tiebreaker after timestamp signals.
  3. 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:

  1. Derive the directory from the plan path: dirname {plan.md path}
  2. Check if phase-handoff.md exists in that directory
  3. 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
  4. 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):

SectionKey Content
ContextBackground, rationale
GoalDesired outcome
StepsOrdered implementation steps (REQUIRED)
Files to Create/ModifyFile paths with actions
Success Criteria — Behavioral (BDD)Given/When/Then scenarios
Success Criteria — QualitativeNon-functional quality attributes
Don't TouchFiles explicitly out of scope
Deferred ActionsItems 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.

  1. If lessons.md does not exist, create it immediately using the structure from plan-protocol.md.
  2. Treat lesson accumulation as continuous behavior:
    • user clarifications discovered during implementation
    • plan-vs-execution gaps
    • runtime/tooling constraints discovered mid-flight
  3. 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:

  1. Place sequential-dependent steps in the same work item (preserve order)
  2. Group steps with the same domain into one work item when possible
  3. Keep parallel-safe items in separate work items
  4. 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 ItemsAgentsStrategy
1 (≤3 files)0Direct execution — Phase 3a
2-32Group related items per agent
4-63Balance 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_dir from live.dir in 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:

  1. Cross-cutting indicator: A single concept (protocol, pattern, interface) projected across 3+ files
  2. If cross-cutting: Commit boundary = change pattern. Add a Commit Group column to group files by the concept they implement, regardless of work item assignment.
  3. If modular: Commit boundary = work item (default). No Commit Group needed.

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).

  1. Execute each step in the work item sequentially

  2. Use Write, Edit, Bash, and other allowed tools directly

  3. Follow the plan's step descriptions precisely

  4. If the item is web-debug, run Web Debug Loop Protocol and persist before/after evidence under {session_dir}/debug/{timestamp}-{slug}/

  5. Respect the "Don't Touch" list — never modify those files

  6. If phase-handoff.md was loaded, apply its Implementation Hints during execution and respect its "Do NOT" constraints

  7. Append newly discovered learnings to lessons.md before commit (user language).

  8. Commit Gate: Apply the Commit Gate. Stage specific files and commit with Conventional Commit format.

  9. 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-debug items, 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:

  1. Launch all parallel-safe items in batch 1
  2. Wait for batch 1 to complete
  3. Launch dependent items in batch 2 (include batch 1 results as context)
  4. 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:

  1. Record which steps were completed
  2. Note any files created or modified
  3. Capture any issues or deviations reported by the agent
  4. Capture provenance metadata (required):
    • source (REAL_EXECUTION | CACHED | FALLBACK)
    • tool (for example claude-task, codex, gemini)
    • agent_id (or slot identifier)
    • started_at_utc, finished_at_utc, duration_ms
  5. 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):

  1. Determine which work item(s) should have addressed it
  2. Check if the relevant files were created/modified
  3. 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:

  1. List them explicitly
  2. 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

  1. Plan is the contract: Implement what the plan says. Do not add features, refactor unrelated code, or reinterpret the goal
  2. Don't Touch means don't touch: Never modify files in the Don't Touch list, even for "improvements"
  3. Parallel when safe, sequential when needed: Only parallelize items with no file overlap or output dependencies
  4. No idle agents: Size the team to the work. One agent with real work beats three agents where two wait
  5. Fail forward: If one agent fails, collect its error and continue with others. Report all failures in Phase 4
  6. Verify against criteria: Every BDD scenario must be checked, not assumed
  7. Preserve existing patterns: Follow codebase conventions visible in existing files. Do not introduce new patterns without plan justification
  8. Markdown discipline: All code fences must have a language specifier
  9. Phase handoff protocols are binding: When phase-handoff.md is present, its "Protocols to Follow" and "Do NOT" sections carry the same weight as plan constraints. They are not suggestions.
  10. Phase handoff is optional: Impl works with plan.md alone. Phase handoff enriches but is never required.
  11. Never implement on a base branch: Phase 0.5 is a hard gate. The only bypass is --skip-branch.
  12. 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.
  13. Stage specific files, never git add -A: Only stage files known to belong to the current work item. Prevent accidental inclusion of unrelated changes.
  14. Lesson-driven changes get separate commits: If a lesson triggers a code change, commit it independently. See Lesson-Driven Commits.
  15. Incremental lessons are mandatory: Update lessons.md as implementation progresses, not only at the end.
  16. 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, and decision_id. If source_recommendation is missing, stop and complete triage context first. If triage_action diverges from source_recommendation, ask the user before proceeding. For deletion actions, do not continue until runtime-caller check and pre-mortem are both recorded.
  17. Language override is mandatory: implementation/code artifacts stay in English, while lessons.md stays in the user's language.
  18. Web-debug evidence is mandatory: Work items classified as web-debug must include before/after browser evidence and a reproducible path using Web Debug Loop Protocol.

References

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.

  1. Better planning input quality before drafting
    • gather + clarify collect evidence and decision points before planning starts.
    • Planning conversations can reveal constraints/preferences that must be recorded in lessons.md immediately, not after implementation.
  2. 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 optional cwf:handoff --phase, instead of shifting context-management burden to the user.
  3. 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

  1. Record the task description verbatim
  2. Identify what needs planning:
    • What is the goal?
    • What are the key decisions to make?
    • What are the known constraints?
  3. 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.

  1. Resolve the effective live-state file and read live.clarify_result_file when set.
  2. 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
  3. 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:

AgentOutput 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 typeAgent decision
Gap is mainly repository-specific (existing architecture, constraints, local patterns)Launch Codebase Analyst only
Gap is mainly external best practice / prior artLaunch Prior Art Researcher only
Gap spans both repository constraints and external practiceLaunch both agents in parallel
Gap is already answerable from baseline after re-checkNo 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.

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:

  1. plan-prior-art-research.md and plan-codebase-analysis.md are critical.
  2. If either file is still invalid after one bounded retry, hard fail the stage with explicit file-level error and stop plan drafting.
  3. Record gate path in output (PERSISTENCE_GATE=HARD_FAIL or 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:

  1. Identify steps that apply identical logic to 3+ targets (files, skills, modules)
  2. 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.
  3. 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:

  1. For each target file in "Files to Create/Modify", check its line count
  2. 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
  3. 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.md format and language policy

Keep only these skill-specific additions in the generated plan:

  1. Add a required ## Commit Strategy section:

    • Per step (default for modular changes)
    • Per change pattern (for cross-cutting changes)
    • Custom (explicit commit boundaries + rationale)
  2. Keep Success Criteria in the two-layer format:

    • Behavioral (BDD) scenarios
    • Qualitative non-functional criteria
  3. Expand ## Decision Log to include evidence/source and resolution metadata:

    #Decision PointEvidence / Source (artifact or URL + confidence)Alternatives ConsideredResolutionStatusResolved ByResolved At (UTC)
    1............open/resolved......
    • Status=open: leave Resolution, Resolved By, and Resolved At as TBD.
    • 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:

  1. If the user provided an output path, use it.
  2. Otherwise run {CWF_PLUGIN_DIR}/scripts/next-prompt-dir.sh --bootstrap <title> and use its output path.
    • --bootstrap creates the resolved directory, initializes missing plan.md/lessons.md, and pre-registers the session in cwf-state.yaml sessions when 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

  1. Evidence-first before drafting: Use gather/clarify artifacts as baseline first; run additional research only for unresolved evidence gaps
  2. Two-layer criteria: Success criteria must include both BDD and qualitative layers
  3. Cite evidence: Reference specific files, URLs, or sources for plan decisions
  4. Follow protocol: Adhere to plan-protocol.md for format and location
  5. Don't over-plan: Keep steps actionable and concrete, avoid excessive detail
  6. Preserve task intent: Refine the approach, don't redirect the goal
  7. 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
  8. Commit Strategy is required: Every plan must include a Commit Strategy section. Default is one commit per Step.
  9. Preparatory refactoring check: When a target file is 300+ lines with 3+ planned changes, add Step 0 to extract separable blocks first
  10. Conditional critical persistence hard-fail: When gap-fill research is launched, if plan-prior-art-research.md or plan-codebase-analysis.md remains invalid after bounded retry, stop with explicit error instead of drafting from partial data
  11. Language override is mandatory: plan.md is in English; lessons.md is in the user's language
  12. Plan-stage learnings must be logged immediately: Record conversation-time learnings in lessons.md during planning, not only after implementation

References

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:

InputMode
No argsQuick Scan
--tidy or --tidy <branch>Code Tidying
--codebaseCodebase Quick Scan
--codebase --deepCodebase Deep Review
--include-local-skills (no other mode flags)Quick Scan + local skills
--skill <name>Deep Review
--skill --holistic or --holisticHolistic Analysis
--docsDocs Review

Provenance Sidecars (Required)

Before using any criteria document, verify its provenance sidecar against the current live repository state (current skill/hook counts).

CriteriaProvenance sidecar
review-criteria.mdreview-criteria.provenance.yaml
holistic-criteria.mdholistic-criteria.provenance.yaml
docs-criteria.mddocs-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_count with checker current.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:

PluginSkillWordsLinesFlags
  • 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:

Task tool:
  subagent_type: general-purpose
  max_turns: 12

Each sub-agent prompt:

  1. Read {SKILL_DIR}/references/tidying-guide.md for techniques, constraints, and output format
  2. Analyze commit diff: git show {commit_hash}
  3. Check if changes still exist: git diff {commit_hash}..HEAD -- {file} (skip modified regions)
  4. Return suggestions or "No tidying opportunities"
  5. 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=fallback with non-zero exit): stop this mode and fix bootstrap/path issues before scanning

Capture metadata for final summary:

  • CONTRACT_STATUS: created, existing, updated, or fallback (fallback is fail-safe and must halt the stage)
  • CONTRACT_PATH
  • CONTRACT_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, optional CONTRACT_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:

  1. Resolve/bootstrap codebase contract (bootstrap-codebase-contract.sh --json)
  2. Resolve session directory with references/session-bootstrap.md (refactor-codebase-deep)
  3. Run codebase scan to {session_dir}/refactor-codebase-scan.json
  4. Select experts to {session_dir}/refactor-codebase-experts.json
  5. Launch 4 parallel experts (Fowler, Beck, Context 1, Context 2) and persist outputs with <!-- AGENT_COMPLETE -->
  6. 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:

  1. Locate the target skill, read SKILL.md + references/ + scripts/ + assets/
  2. Verify deep-review provenance (review-criteria.provenance.yaml)
  3. Resolve session directory with references/session-bootstrap.md (refactor-skill)
  4. Launch 2 parallel sub-agents (Structural 1-4, Quality+Concept 5-9) with output persistence sentinel
  5. 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:

  1. Build inventory from marketplace skills, hooks, and local skills
  2. Verify holistic criteria provenance (holistic-criteria.provenance.yaml)
  3. Resolve session directory with references/session-bootstrap.md (refactor-holistic)
  4. Launch 3 parallel sub-agents (Convention, Concept, Workflow) with output persistence sentinel
  5. Merge to holistic report and discuss prioritization with the user

Docs Review Mode (--docs)

Review documentation consistency with this fixed flow:

  1. Resolve/bootstrap docs contract (bootstrap-docs-contract.sh)
  2. Deterministic tool pass (markdownlint, local link check, doc-graph)
  3. Docs criteria provenance verification
  4. Contract-aware entry docs, project context, README, and cross-document consistency review
  5. 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

  1. Deep Review and Holistic use perspective-based parallel sub-agents (not module-based)
  2. Deep Review: 2 agents (structural 1-4 + quality/concept/portability 5-9), single batch
  3. Holistic: 3 agents (Convention Compliance, Concept Integrity, Workflow Coherence), single batch after inline inventory
  4. Code Tidying: 1 agent per commit, all in one message
  5. Codebase Quick Scan: contract-driven deterministic scan, no sub-agents
  6. Codebase Deep Review: 4 expert sub-agents (fixed 2 + context 2) after codebase scan
  7. Docs Review: inline, no sub-agents (single-context synthesis over whole-repo graph and deterministic outputs)
  8. Docs Review must run the deterministic tool pass before semantic analysis
  9. In Docs Review, do not report lint/hook-detectable issues as standalone manual findings when tool output already covers them
  10. Sub-agents analyze and report; orchestrator merges. Sub-agents do not modify files
  11. All code fences must have a language specifier

References

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:

  1. If [path] argument provided, use it
  2. Reuse .cwf/projects/ path already used in this session (plan.md/lessons.md writes)
  3. 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
  4. If user selects a new dated directory, run {CWF_PLUGIN_DIR}/scripts/next-prompt-dir.sh --bootstrap <title>, then copy plan.md and lessons.md from the previous session directory when present so retro context is preserved.
  5. If multiple candidates exist, AskUserQuestion with candidates
  6. 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_mode with 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 --light is 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 --light to 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-run present, or live task explicitly indicates cwf: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:

BatchAgentOutput file
1CDM Analysis{session_dir}/retro-cdm-analysis.md
1Learning Resources{session_dir}/retro-learning-resources.md
2Expert α{session_dir}/retro-expert-alpha.md
2Expert β{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.

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 + relevant cwf-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.md remains invalid after retry: hard fail deep retro.
  • If retro-learning-resources.md remains invalid after retry: continue with warning and render Section 6 with explicit omission note.
  • Record gate path in output (PERSISTENCE_GATE=HARD_FAIL or PERSISTENCE_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_CONTINUE or 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:

  1. .cwf/sessions/
  • Prefer suffix files: {YYMMDD}-*.claude.md, {YYMMDD}-*.codex.md
  • Also allow unsuffixed files: {YYMMDD}-*.md

Then:

  1. Filter out already-symlinked candidates.
  2. Read a sample of each candidate to verify it matches the current session.
  3. Ensure {output-dir}/session-logs/ exists.
  4. For each verified log, create a relative symlink:
    ln -s "{relative-log-path}/{filename}" "{output-dir}/session-logs/{filename}"
    
  5. 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=local
  • owner=plugin -> apply_layer=upstream

Required metadata for every persist proposal:

  • owner
  • apply_layer
  • promotion_target
  • due_release
  • evidence (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 under plugins/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.md delta-focused; do not move global contracts there.

After ownership routing, evaluate enforcement mechanisms strongest-first:

  1. Tier 1: Eval/Hook (deterministic) — Can a script/hook catch this?

    • check-session.sh / session_defaults for missing artifacts
    • PreToolUse/PostToolUse hook for tool usage patterns
    • Lint rule for style enforcement
  2. Tier 2: State (structural) — Does this change workflow state?

    • cwf-state.yaml schema (new artifacts, stage transitions)
    • session_defaults (new always/milestone artifacts)
  3. Tier 3: Doc (behavioral, last resort) — Only for judgment calls

    • project-context.md for 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.md for 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?". For owner=plugin, AskUserQuestion "Queue upstream issue/patch now?".

Expert Roster Maintenance (deep mode only, when Section 5 was produced):

  1. Extract expert names from Section 5 (Expert Lens) output
  2. Follow the Roster Maintenance procedure in {CWF_PLUGIN_DIR}/references/expert-advisor-guide.md (including the retro-specific gap analysis step)
  3. 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):

  1. Provide Retro Brief with 4-6 bullets:
    • session objective/result
    • top waste/root-cause signal
    • most important CDM lesson
    • critical tool/capability takeaway
  2. Provide Persist Proposals with 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
  3. 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 Proposals mini-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.md with 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

  1. Never duplicate content already in lessons.md.
  2. Be specific — cite session moments, not generic advice.
  3. Keep each section focused; if there is no meaningful signal, state that briefly.
  4. AGENTS.md/runtime adapter changes require explicit user approval.
  5. Use the deterministic gate checklist in retro-gates-checklist.md for deep-mode artifacts, persistence tiering, and direct-invocation reporting requirements.
  6. For Section 5 in deep mode, use {SKILL_DIR}/references/expert-lens-guide.md and include the mandatory agreement/disagreement synthesis subsection.
  7. Language override: retro.md and 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 plan before cwf:impl
  • cwf:impl → cwf:review --mode code before cwf: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

InputMode
No args or --mode codeCode review
--mode planPlan review
--mode clarifyClarify review
--humanRoute 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:

  1. parse flags (--mode, --base, --scenarios, provider overrides)
  2. detect review target by mode (code/plan/clarify) with explicit base strategy provenance
  3. extract behavioral + qualitative criteria from latest plan artifacts
  4. validate and merge holdout checks when --scenarios is provided
  5. compute turn budget + CLI timeout and apply 1200-line external CLI cutoff
  6. set web_debug_scope=true when 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.

2.0 Pre-launch setup

Before slot launch, complete deterministic pre-launch routing:

  1. resolve session_dir and apply context-recovery validation for mode-suffixed output files
  2. prepare internal/external prompts (including web_debug_scope browser block when required)
  3. detect provider preflight and route Slot 3/4 providers
  4. run agent-slot preflight (--required 6) and choose single-batch or deterministic multi-batch
  5. resolve Slot 5/6 experts from expert_roster with 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}.md and 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):

SlotFile
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.txt for provider tool, exit code, and duration
  • {tmp_dir}/slot3-stderr.log / {tmp_dir}/slot4-stderr.log for 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:

  1. classify stderr error type first (capacity/internal/auth/tool-error)
  2. then apply exit-code fallback policy when no classifier matched
  3. extract actionable cause text for Confidence Note
  4. 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|false
  • session_log_lines: integer (0 when missing)
  • session_log_turns: integer count of ^## Turn
  • session_log_last_turn: last ## Turn header or none
  • session_log_cross_check: PASS|WARN

Policy:

  • If no session log exists, set session_log_cross_check=WARN and 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):

ConditionVerdict
Any unchecked behavioral criterionRevise
Any Concern with severity critical or securityRevise
Any Concern with severity moderateConditional Pass
Only Suggestions or no issues foundPass

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

  1. 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.
  2. Narrative only — no numerical scores, no percentages, no letter grades. Verdicts are Pass / Conditional Pass / Revise.
  3. Never inline review — always use Task sub-agents. The main agent synthesizes but does not review directly.
  4. Conservative default — stricter reviewer determines the verdict when reviewers disagree.
  5. Output to conversation + persist — review synthesis is both communication and downstream input. Always write {session_dir}/review-synthesis-{mode}.md alongside the conversation output so retro/handoff can consume it.
  6. 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.
  7. 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.
  8. Missing dependency interaction — when failures are caused by missing tools/auth, ask whether to install/configure now before final fallback-only completion.
  9. No silent holdout bypass — when --scenarios is provided, the scenario file must be validated and assessed. Never downgrade to "best effort" silently.
  10. Base strategy must be explicit in output — for code mode, always report which base path was used (explicit --base, upstream, or fallback).
  11. Critical reviewer outputs hard-fail — if any required review file remains invalid after bounded retry, stop synthesis with explicit file-level error.
  12. Commit-boundary split for mixed follow-up work — when review findings imply both tidy and behavior-policy changes, recommend separate commit units and tidy first.
  13. Preserve explicit decisions — when reviewer suggestions conflict with explicit user decisions or accepted plan constraints, include them under Considered-Not-Adopted with reason/reference.
  14. Capacity-aware launch — run agent-slot preflight before reviewer launch; if capacity is insufficient, use deterministic batches instead of oversubscribing.
  15. Code-mode session-log fields are mandatory — always include deterministic session_log_* keys in Confidence Note for --mode code.
  16. Code-mode artifact gate is mandatory — review-code is not complete unless check-run-gate-artifacts.sh --stage review-code --strict passes.
  17. Language override — synthesis output follows the user's language; reviewer prompts remain in English.
  18. 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

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:run chain is: gather → clarify → plan → review(plan) → impl → review(code) → refactor → retro → ship.
  • refactor runs 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 loose cwf substrings.
  • Do not substitute similarly named run flows from other plugins.
  • If routing is uncertain, emit WAIT_INPUT instead 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:

  1. Evaluate setup readiness first (Phase 0).
  2. If readiness is not satisfied, stop immediately before stage initialization.
  3. Print a deterministic waiting response with exact next actions.
  4. 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.

  1. Run deterministic readiness check:

    bash {CWF_PLUGIN_DIR}/scripts/check-setup-readiness.sh --base-dir . --summary
    
  2. If check fails, do not initialize live state and do not create run artifacts.

  3. 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

  1. Parse task description and flags (--from, --skip, --ambiguity-mode)

  2. 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
    
  3. 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.
  4. Resolve ambiguity mode (--ambiguity-mode or 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
    
  5. Bootstrap session directory via {CWF_PLUGIN_DIR}/scripts/next-prompt-dir.sh --bootstrap <sanitized-title>

    • This creates the directory, initializes plan.md/lessons.md if missing, and pre-registers the session in cwf-state.yaml sessions when state exists.
  6. 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"
    
  7. 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
    
  8. 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
    
  9. 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

#StageSkill InvocationGateAuto
1gathercwf:gather—false
2clarifycwf:clarifyT3 policy depends on ambiguity modefalse
3plancwf:planUser approves planfalse
4review-plancwf:review --mode planVerdict-basedtrue
5implcwf:impl --skip-clarify—true
6review-codecwf:review --mode codeVerdict-basedtrue
7refactorcwf:refactor—true
8retrocwf:retro --from-run—true
9shipcwf:ship issue → cwf:ship pr (non-base branch)User confirms PRfalse

Ambiguity Modes (Clarify T3 Policy)

Use live.ambiguity_mode (resolved in Phase 1).

ModeClarify T3 handlingMerge policy
strictStop and ask user for every T3 decisionno extra blocking by mode
defer-blockingDecide autonomously, but persist unresolved decision debtunresolved decision debt is merge-blocking at ship
defer-reversibleDecide autonomously with reversible structure (flags/adapters/switch points)track debt, non-blocking by default
explore-worktreesImplement alternatives in separate worktrees, then pick baselineblocking 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):

  1. 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."
    fi
    

    If 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 under Retro Gate Follow-ups (do not compress into a generic warning).

  2. 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.yaml stays consistent with final artifacts/summary (registration is initialized during Phase 1 bootstrap)
  3. 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

  1. 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.
  2. One auto-fix attempt: Never loop more than once on a review failure. Escalate to user after 1 retry.
  3. Skill invocation only: Use the Skill tool to invoke CWF skills. Do not inline skill logic.
  4. State tracking: Use cwf-live-state.sh set and list-set at every stage transition so session-local live state stays current while root summary remains synchronized.
  5. Preserve skill autonomy: Each invoked skill manages its own sub-agents, artifacts, and output. cwf:run orchestrates but does not micromanage.
  6. Flags compose: --from impl --skip retro is valid. Apply both filters.
  7. Graceful halt: When the user chooses "Stop", update state and report what was completed. Do not leave state in an inconsistent phase.
  8. Do not bypass impl branch gate by default: cwf:run must not pass --skip-branch to cwf:impl unless the user explicitly requests bypass.
  9. Context-deficit resilience: On resume/restart, reconstruct stage context from cwf-state.yaml, session artifacts, and handoff docs before invoking downstream skills.
  10. 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.
  11. Fail-closed run gates: While active_pipeline="cwf:run" and remaining_gates includes review-code, ship/push/commit intents must be blocked unless pipeline_override_reason is explicitly set.
  12. Artifact gate is mandatory for stage closure: review-code, refactor, retro, and ship are not complete unless check-run-gate-artifacts.sh --strict passes for that stage.
  13. Setup readiness is mandatory before run init: cwf:run must execute check-setup-readiness.sh and halt with WAIT_INPUT when prerequisites are missing.
  14. Ambiguity mode precedence: --ambiguity-mode flag overrides config. Config (CWF_RUN_AMBIGUITY_MODE) overrides built-in default (defer-blocking).
  15. Defer modes require persistence: Any non-strict T3 carry-over must be recorded in {session_dir}/run-ambiguity-decisions.md and synchronized to live.blocking_decisions_pending via sync-ambiguity-debt.sh.
  16. 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.
  17. 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.
  18. Review Fail is not Revise: Fail halts automation immediately and requires explicit user direction before any downstream stage.
  19. Run-start branch creation is mandatory: When cwf:run starts on the resolved base branch, create/switch to a dedicated feature branch before editing.
  20. 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

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:setup first; it is the default entrypoint and asks for optional integrations when relevant.
  • Use --codex / --codex-wrapper when reapplying only Codex-related integration pieces.

Mode Routing

Parse input flags and run only the relevant phases:

InputPhases
cwf:setup1 → 2 → 2.8 → 2.9 → 2.10 → 2.4 (if codex available) → 2.7 (always ask) → 4 (opt-in) → 5
cwf:setup --hooks1 → 5
cwf:setup --tools2 → 2.8 → 2.9 → 2.10 → 5
cwf:setup --env2.8 → 2.10 → 5
cwf:setup --agent-teams2.9 → 5
cwf:setup --run-mode2.10 → 5
cwf:setup --codex2.5 → 5
cwf:setup --codex-wrapper2.6 → 5
cwf:setup --git-hooks <none|pre-commit|pre-push|both> [--gate-profile <fast|balanced|strict>]2.7 → 5
cwf:setup --cap-index3 → 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 loose cwf substrings.
  • Do not substitute similarly named setup flows from other plugins.
  • If routing is uncertain, emit WAIT_INPUT for 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:

  1. Resolve mode and identify the first unresolved user-choice phase before running heavy phases (full setup starts at phase 1.2).
  2. Stop immediately at that first unresolved phase when AskUserQuestion is unavailable/blocked.
  3. Print a deterministic WAIT_INPUT response with phase id, options, and a direct reply instruction.
  4. 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

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:

GroupDescription
attentionSlack notifications on idle/waiting
logAuto-log turns + auto-commit transcripts
readFile-size aware reading guard
lint_markdownMarkdown validation after Write/Edit
lint_shellShellCheck validation after Write/Edit
deletion_safetyBlocks risky file deletions and requires policy-compliant justification
workflow_gateEnforces workflow stage/branch safety rules before edits and commands
websearch_redirectRedirect WebSearch to cwf:gather
compact_recoveryInject 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}_ENABLED line 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 to user; ask user to choose target scope explicitly.
  • When selected scope is project or local and 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: run sync-skills.sh, then install-wrapper.sh --enable (add PATH only in user scope), then wrapper status.
  • Skills only: run sync-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 --status
  • type -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:

  1. Resolve hook install mode (--git-hooks or AskUserQuestion).

  2. Resolve gate profile (fast|balanced|strict) unless mode is none.

  3. Apply scripts/configure-git-hooks.sh.

  4. Bootstrap run gate contract:

    bash {SKILL_DIR}/scripts/bootstrap-gate-contract.sh --json
    
  5. If contract status is fallback, stop setup (fail-safe) and request path/permission fix.

  6. Report effective hook state + contract policy summary (auto -> portable, explicit authoring path 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:

  1. Ask whether to create templates, overwrite templates, or skip.
  2. Run scripts/bootstrap-project-config.sh (--force only for overwrite).
  3. Report effective runtime priority (.cwf-config.local.yaml > .cwf-config.yaml > process env > shell exports).
  4. If interactive prompts are unavailable, emit deterministic WAIT_INPUT and 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:

  1. Ask mode policy (enable, keep, disable).
  2. Apply via scripts/configure-agent-teams.sh with --enable, --status, or --disable.
  3. 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:

  1. Detect current effective CWF_RUN_AMBIGUITY_MODE (default fallback: defer-blocking).
  2. Ask desired default mode (defer-blocking|strict|defer-reversible|explore-worktrees).
  3. Ask target config scope (shared|local).
  4. Persist via scripts/configure-run-mode.sh, bootstrapping project templates when needed.
  5. Report selected mode/scope/path and precedence order (--ambiguity-mode flag > local config > shared config > env/shell > built-in default).
  6. If interactive prompts are unavailable, emit deterministic WAIT_INPUT and 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 --target or 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

  1. State SSOT + idempotency: Read and edit cwf-state.yaml (do not overwrite wholesale), and keep reruns safe/idempotent across all phases.
  2. 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.
  3. Index generation is explicit and deterministic: Capability index runs only via --cap-index; repository index runs via --repo-index with target resolution (agents, file, both) from CLI or repository context.
  4. Index coverage/link policy is mandatory: Generated indexes must use Markdown relative links and pass deterministic coverage checks (cap/repo profiles).
  5. File safety: Codex sync must use symlink + backup move (no direct user file deletion).
  6. Scope-aware Codex integration: Resolve active plugin scope first; non-user context must not mutate user-global Codex paths without explicit user confirmation.
  7. No fail-open scope fallback: If scope detection fails or returns none, require explicit user scope selection before any Codex mutation.
  8. Setup-contract first-run invariant: Full/tools setup must bootstrap setup-contract and explicitly report created|existing|updated|fallback status. fallback is fail-safe and must halt setup.
  9. Formatting invariant: All code fences in this skill must include language specifiers.
  10. 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

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 --merge or --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 gh is missing, run bash {SKILL_DIR}/../setup/scripts/install-tooling-deps.sh --install gh
    • if auth is missing, run gh auth login
    • then retry prerequisite checks once
  • 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):

  1. Resolve session directory from live state (live.dir).
  2. Persist a structured execution summary to {session_dir}/ship.md with these required sections:
    • ## Execution Status
    • ## Ambiguity Resolution
    • ## Next Step
  3. In ## Ambiguity Resolution, always write these scalar lines:
    • mode: strict|defer-blocking|defer-reversible|explore-worktrees
    • blocking_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 mode from live state (live.ambiguity_mode) and derive counts from {session_dir}/run-ambiguity-decisions.md if it exists.
    • For defer-blocking, merge_allowed must be no when blocking_open_count > 0.
    • When the current branch is not the resolved base branch, issue_ref and pr_ref must contain concrete GitHub URLs before ship-stage closure.
  4. Synchronize live ambiguity debt state before gate closure:
bash {CWF_PLUGIN_DIR}/scripts/sync-ambiguity-debt.sh \
  --base-dir . \
  --session-dir "{session_dir}"
  1. 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

  1. Detect session context:

    • Find the current session directory in .cwf/projects/ (most recent YYMMDD-NN-*)
    • Read plan.md if it exists for purpose, scope, success criteria
    • Read master-plan (search for master-plan.md or similar) for session number
    • Resolve {base}:
      • if --base is 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, then master; if none exists, ask the user for base branch explicitly
  2. 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 Findings when present
        • Otherwise synthesize up to 3 bullets from waste/CDM/tools sections
        • If retro artifact is missing, use _No retro summary recorded yet._
      • {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
  3. Create issue:

    gh issue create \
      --title "S{N}: {title}" \
      --body "$(cat <<'EOF'
    {composed_body}
    EOF
    )" \
      --label "cwf-v3"
    
    • If cwf-v3 label doesn't exist, create it first: gh label create cwf-v3 --color 0E8A16 --description "CWF v3 migration"
  4. Create feature branch (unless --no-branch):

    git checkout {base} && git pull origin {base}
    git checkout -b feat/{short-name}
    
  5. Report: Print issue URL and branch name.


/ship pr

Create a pull request from the current feature branch.

Workflow

  1. 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 --oneline is non-empty
    • No uncommitted changes: git status --porcelain is empty
      • If dirty, ask user whether to commit first or abort
  2. Auto-detect linked issue:

    • If --issue N provided, 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)
  3. Build PR body from {SKILL_DIR}/references/pr-template.md:

    • {ISSUE_LINK} — Closes #{N} if issue found, otherwise omit
    • {PURPOSE} — synthesize from git log {base}..HEAD --oneline and plan.md; describe why this change exists, not what files changed
    • {DECISIONS} — extract key decisions from:
      • .cwf/projects/{session}/lessons.md takeaways
      • .cwf/projects/{session}/retro.md CDM section
      • .cwf/projects/{session}/plan.md decision 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
    • {HUMAN_JUDGMENT} — agent self-assessment of items needing human review:
      • Architecture changes, UX decisions, security implications, breaking changes
      • Read live.ambiguity_mode and {session_dir}/run-ambiguity-decisions.md when present
      • If mode is defer-blocking and blocking_open_count > 0, list all open blocking decision debts here (never write None)
      • 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 of git diff {base}...HEAD --stat wrapped in a ```text code fence
    • {LESSONS} — extract from .cwf/projects/{session}/lessons.md if exists, otherwise write _No lessons recorded for this session._
    • {CDM} — extract from .cwf/projects/{session}/retro.md CDM section if exists, otherwise write _No CDM recorded yet._
    • {RETRO_SUMMARY} — concise retro outcome summary from .cwf/projects/{session}/retro.md
      • Prefer Post-Retro Findings when present
      • Otherwise synthesize up to 3 bullets from waste/CDM/tools sections
      • If retro artifact is missing, use _No retro summary recorded yet._
    • {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:
      • *.sh changed → - [ ] Scripts are executable and pass shellcheck
      • SKILL.md changed → - [ ] SKILL.md under 500 lines
      • plugin.json changed → - [ ] Version bumped appropriately
      • hooks.json changed → - [ ] Hook matchers are correct
      • *.md changed → - [ ] Markdown lint passes
  4. 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 --draft if the user specified it
  5. Report: Print PR URL.


/ship merge

Check PR status and merge if ready.

Workflow

  1. Find current PR:

    gh pr view --json number,state,reviewDecision,statusCheckRollup,mergeable,headRefName
    
    • If no PR found for current branch, report and stop
  2. 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 Required section
    • Check branch protection: gh api repos/{owner}/{repo}/branches/{base}/protection 2>&1
    • Parse {session_dir}/run-ambiguity-decisions.md and/or ship.md ambiguity block:
      • if mode: defer-blocking and blocking_open_count > 0, merge is blocked

    Decision matrix:

    Human judgmentBranch protectedReview required
    defer-blocking with open blocking debtAnyStop — do not merge
    None or emptyNoSkip — autonomous merge
    None or emptyYesreviewDecision = APPROVED required
    Items listedAnyReport items, stop — do not merge

    If not ready, report which conditions are blocking and stop. Do not attempt to merge.

  3. Merge:

    gh pr merge {N} --squash --delete-branch
    
    • Use --merge or --rebase if the user specified an override
    • Default is --squash
  4. Post-merge cleanup:

    git checkout {base} && git pull origin {base}
    
  5. Report: Merge confirmation, deleted branch name.


/ship status

Read-only overview of current GitHub state.

Workflow

  1. Open issues:

    gh issue list --label cwf-v3 --state open --json number,title,assignees
    
  2. Open PRs:

    gh pr list --json number,title,state,headRefName,reviewDecision,statusCheckRollup
    
  3. Current branch PR (if exists):

    gh pr view --json number,title,state,reviewDecision,mergeable,statusCheckRollup
    
    • If no PR for current branch, note that
  4. Session progress (optional):

    • If master-plan.md exists, parse the session roadmap
    • Show completed vs remaining sessions
  5. Report: Format as a readable summary table.


Error Handling

SituationAction
gh not installedAsk whether to install now via setup installer script; if declined/fails, print manual commands and stop
Not authenticatedReport, suggest gh auth login, stop
No commits ahead of baseReport "nothing to PR", stop
Issue already exists for sessionShow existing issue, ask user before creating duplicate
PR already exists for branchShow existing PR URL, stop
Merge conflictsReport, suggest git rebase {base} instructions, stop
Missing lessons.md or retro.mdUse placeholder text, do not fail
Label cwf-v3 missingCreate it automatically
Dirty working tree on PRAsk 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

  1. Use gh as the primary interface; do not craft raw GitHub API payloads when gh already supports the operation.
  2. Stop immediately on failed prerequisites (gh missing, unauthenticated, or invalid branch state).
  3. Keep PR purpose and decision sections evidence-backed from session artifacts when available (plan.md, lessons.md, retro.md).
  4. Never auto-merge when human-judgment items are present in the PR body.
  5. Preserve user-created files and branches; do not perform destructive cleanup beyond explicit merge cleanup.
  6. All code fences must have language specifiers.
  7. Missing prerequisites must trigger an install/configure choice prompt, not a passive "missing tool" report only.
  8. /ship must always persist {session_dir}/ship.md before returning.
  9. In defer-blocking mode, unresolved ambiguity debt is merge-blocking until tracked follow-up references are recorded and blocking_open_count is zero.
  10. Language override: issue/PR narrative sections are written in the user's language; code blocks, file paths, commit hashes, and CLI output remain verbatim.
  11. retro outcomes and persistence proposals must be visible in issue/PR body sections, not only hidden in collapsed details blocks.

References

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 to user; ask for explicit target scope.
  • If selected scope is project/local and 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_present
  • wrapper_active
  • wrapper_link_present (wrapper link exists even when Active is 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, run sync-skills.sh for selected scope.
    • when wrapper_link_present=true or wrapper_active=true, run install-wrapper.sh --enable for selected scope (without --add-path) to repoint stale wrapper links.
    • when neither is present, report "no existing Codex integration to reconcile" and skip mutation.

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 codex for 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 codex by 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:
  1. Build file-change inventory:
git --no-pager diff --no-index --name-status "$old_diff_root" "$new_diff_root" || true
  1. Diff README for user-facing guidance changes:
git --no-pager diff --no-index \
  "$old_diff_root/README.md" \
  "$new_diff_root/README.md" || true
  1. 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.

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

  1. Resolve scope first: Always resolve and report active/selected scope before version check or update.
  2. Update marketplace first: Always run marketplace update before plugin update/install.
  3. Scope-aware apply: Update/install must target explicit scope via --scope.
  4. Auto-apply when newer version exists: In normal mode (not --check), apply update immediately without a separate update-confirmation prompt.
  5. Reconcile Codex links after update: For existing Codex integrations in selected scope, run reconcile in the same update flow.
  6. No fail-open scope fallback: If scope detection fails or returns none, require explicit scope selection before mutation.
  7. No mutation in check mode: cwf:update --check must not install/update/reconcile; it reports status and suggested commands only.
  8. Change summary is opt-in: Run change summary only when the user explicitly requests it in Phase 4.
  9. Authoritative latest only: cache is supporting evidence, not oracle; latest-version verdict must come from authoritative metadata path.
  10. UNVERIFIED is fail-closed: never present No update needed when verdict is UNVERIFIED.
  11. Top-level verification required: release confidence claims require top-level marketplace update + authoritative fetch success.
  12. Changes take effect after restart: Always remind user to restart Claude Code.
  13. All code fences must have language specifier: Never use bare fences.

References

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