Files
Claude-Code-Workflow/.codex/skills/workflow-plan-execute/phases/01-session-discovery.md
catlog22 c62d26183b feat: Add interactive pre-flight checklists for ccw-loop and workflow-plan, including validation and task transformation steps
- Implemented `prep-loop.md` for ccw-loop, detailing source discovery, validation, task transformation, and auto-loop configuration.
- Created `prep-plan.md` for workflow planning, covering environment checks, task quality assessment, execution preferences, and final confirmation.
- Defined schemas and integration points for `prep-package.json` in both ccw-loop and workflow-plan skills, ensuring proper validation and task handling.
- Added error handling mechanisms for various scenarios during the preparation phases.
2026-02-09 15:02:38 +08:00

12 KiB

Phase 1: Session Discovery

Discover existing sessions or start new workflow session with intelligent session management and conflict detection.

Objective

  • Ensure project-level state exists (first-time initialization)
  • Create or discover workflow session for the planning workflow
  • Generate unique session ID (WFS-xxx format)
  • Initialize session directory structure

Step 0.0: Load Prep Package (if exists)

// Load plan-prep-package.json (generated by /prompts:prep-plan)
let prepPackage = null
const prepPath = `${projectRoot}/.workflow/.prep/plan-prep-package.json`

if (fs.existsSync(prepPath)) {
  const raw = JSON.parse(Read(prepPath))
  const checks = validatePlanPrepPackage(raw, projectRoot)

  if (checks.valid) {
    prepPackage = raw
    console.log(`✓ Prep package loaded: score=${prepPackage.task.quality_score}/10, exec=${prepPackage.execution.execution_method}`)
    console.log(`  Checks passed: ${checks.passed.join(', ')}`)
  } else {
    console.warn(`⚠ Prep package found but failed validation:`)
    checks.failures.forEach(f => console.warn(`  ✗ ${f}`))
    console.warn(`  → Falling back to default behavior (prep-package ignored)`)
    prepPackage = null
  }
}

/**
 * Validate plan-prep-package.json integrity before consumption.
 */
function validatePlanPrepPackage(prep, projectRoot) {
  const passed = []
  const failures = []

  // Check 1: prep_status
  if (prep.prep_status === 'ready') passed.push('status=ready')
  else failures.push(`prep_status is "${prep.prep_status}", expected "ready"`)

  // Check 2: target_skill
  if (prep.target_skill === 'workflow-plan-execute') passed.push('target_skill match')
  else failures.push(`target_skill is "${prep.target_skill}", expected "workflow-plan-execute"`)

  // Check 3: project_root
  if (prep.environment?.project_root === projectRoot) passed.push('project_root match')
  else failures.push(`project_root mismatch: "${prep.environment?.project_root}" vs "${projectRoot}"`)

  // Check 4: quality_score >= 6
  if ((prep.task?.quality_score || 0) >= 6) passed.push(`quality=${prep.task.quality_score}/10`)
  else failures.push(`quality_score ${prep.task?.quality_score || 0} < 6`)

  // Check 5: generated_at within 24h
  const hoursSince = (Date.now() - new Date(prep.generated_at).getTime()) / 3600000
  if (hoursSince <= 24) passed.push(`age=${Math.round(hoursSince)}h`)
  else failures.push(`prep-package is ${Math.round(hoursSince)}h old (max 24h)`)

  // Check 6: required fields
  const required = ['task.structured.goal', 'task.structured.scope', 'execution.execution_method']
  const missing = required.filter(p => !p.split('.').reduce((o, k) => o?.[k], prep))
  if (missing.length === 0) passed.push('fields complete')
  else failures.push(`missing: ${missing.join(', ')}`)

  return { valid: failures.length === 0, passed, failures }
}

// Build structured description from prep or raw input
let structuredDescription
if (prepPackage) {
  structuredDescription = {
    goal: prepPackage.task.structured.goal,
    scope: prepPackage.task.structured.scope,
    context: prepPackage.task.structured.context
  }
} else {
  structuredDescription = null  // Will be parsed from user input later
}

Step 0: Initialize Project State (First-time Only)

Executed before all modes - Ensures project-level state files exist by calling workflow:init.

Check and Initialize

# Check if project state exists (both files required)
bash(test -f ${projectRoot}/.workflow/project-tech.json && echo "TECH_EXISTS" || echo "TECH_NOT_FOUND")
bash(test -f ${projectRoot}/.workflow/project-guidelines.json && echo "GUIDELINES_EXISTS" || echo "GUIDELINES_NOT_FOUND")

If either NOT_FOUND, delegate to workflow:init:

// Codex: Execute workflow:init command for intelligent project analysis
codex workflow:init

// Wait for init completion
// project-tech.json and project-guidelines.json will be created

Output:

  • If BOTH_EXIST: PROJECT_STATE: initialized
  • If NOT_FOUND: Calls workflow:init → creates:
    • {projectRoot}/.workflow/project-tech.json with full technical analysis
    • {projectRoot}/.workflow/project-guidelines.json with empty scaffold

Note: workflow:init uses cli-explore-agent to build comprehensive project understanding (technology stack, architecture, key components). This step runs once per project. Subsequent executions skip initialization.

Execution

Step 1.1: Execute Session Start

// Codex: Execute session start command
codex workflow:session:start --auto "[structured-task-description]"

Task Description Structure:

GOAL: [Clear, concise objective]
SCOPE: [What's included/excluded]
CONTEXT: [Relevant background or constraints]

Example:

GOAL: Build JWT-based authentication system
SCOPE: User registration, login, token validation
CONTEXT: Existing user database schema, REST API endpoints

Step 1.2: Parse Output

  • Extract: SESSION_ID: WFS-[id] (store as sessionId)

Step 1.3: Validate

  • Session ID successfully extracted
  • Session directory {projectRoot}/.workflow/active/[sessionId]/ exists

Note: Session directory contains workflow-session.json (metadata). Do NOT look for manifest.json here - it only exists in {projectRoot}/.workflow/archives/ for archived sessions.

Step 1.4: Initialize Planning Notes

Create planning-notes.md with N+1 context support, enriched with prep data:

const planningNotesPath = `${projectRoot}/.workflow/active/${sessionId}/planning-notes.md`
const userGoal = structuredDescription?.goal || taskDescription
const userScope = structuredDescription?.scope || "Not specified"
const userConstraints = structuredDescription?.context || "None specified"

// Build source refs section from prep
const sourceRefsSection = (prepPackage?.task?.source_refs?.length > 0)
  ? prepPackage.task.source_refs
    .filter(r => r.status === 'verified' || r.status === 'linked')
    .map(r => `- **${r.type}**: ${r.path}`)
    .join('\n')
  : 'None'

// Build quality dimensions section from prep
const dimensionsSection = prepPackage?.task?.dimensions
  ? Object.entries(prepPackage.task.dimensions)
    .map(([k, v]) => `- **${k}**: ${v.value} (${v.score}/2)`)
    .join('\n')
  : ''

Write(planningNotesPath, `# Planning Notes

**Session**: ${sessionId}
**Created**: ${new Date().toISOString()}
${prepPackage ? `**Prep Package**: plan-prep-package.json (score: ${prepPackage.task.quality_score}/10)` : ''}

## User Intent (Phase 1)

- **GOAL**: ${userGoal}
- **SCOPE**: ${userScope}
- **KEY_CONSTRAINTS**: ${userConstraints}
${sourceRefsSection !== 'None' ? `
### Requirement Sources (from prep)
${sourceRefsSection}
` : ''}${dimensionsSection ? `
### Quality Dimensions (from prep)
${dimensionsSection}
` : ''}
---

## Context Findings (Phase 2)
(To be filled by context-gather)

## Conflict Decisions (Phase 2)
(To be filled if conflicts detected)

## Consolidated Constraints (Phase 3 Input)
1. ${userConstraints}

---

## Task Generation (Phase 3)
(To be filled by action-planning-agent)

## N+1 Context
### Decisions
| Decision | Rationale | Revisit? |
|----------|-----------|----------|

### Deferred
- [ ] (For N+1)
`)

Session Types

The --type parameter classifies sessions for CCW dashboard organization:

Type Description Default For
workflow Standard implementation (default) workflow:plan
review Code review sessions workflow:review-module-cycle
tdd TDD-based development workflow:tdd-plan
test Test generation/fix sessions workflow:test-fix-gen
docs Documentation sessions memory:docs

Validation: If --type is provided with invalid value, return error:

ERROR: Invalid session type. Valid types: workflow, review, tdd, test, docs

Mode 1: Discovery Mode (Default)

Usage

workflow:session:start

Step 1: List Active Sessions

bash(ls -1 ${projectRoot}/.workflow/active/ 2>/dev/null | head -5)

Step 2: Display Session Metadata

bash(cat ${projectRoot}/.workflow/active/WFS-promptmaster-platform/workflow-session.json)

Step 4: User Decision

Present session information and wait for user to select or create session.

Output: SESSION_ID: WFS-[user-selected-id]

Mode 2: Auto Mode (Intelligent)

Usage

workflow:session:start --auto "task description"

Step 1: Check Active Sessions Count

bash(find ${projectRoot}/.workflow/active/ -name "WFS-*" -type d 2>/dev/null | wc -l)

Step 2a: No Active Sessions → Create New

# Generate session slug
bash(echo "implement OAuth2 auth" | sed 's/[^a-zA-Z0-9]/-/g' | tr '[:upper:]' '[:lower:]' | cut -c1-50)

# Create directory structure
bash(mkdir -p ${projectRoot}/.workflow/active/WFS-implement-oauth2-auth/.process)
bash(mkdir -p ${projectRoot}/.workflow/active/WFS-implement-oauth2-auth/.task)
bash(mkdir -p ${projectRoot}/.workflow/active/WFS-implement-oauth2-auth/.summaries)

# Create metadata (include type field, default to "workflow" if not specified)
bash(echo '{"session_id":"WFS-implement-oauth2-auth","project":"implement OAuth2 auth","status":"planning","type":"workflow","created_at":"2024-12-04T08:00:00Z"}' > ${projectRoot}/.workflow/active/WFS-implement-oauth2-auth/workflow-session.json)

Output: SESSION_ID: WFS-implement-oauth2-auth

Step 2b: Single Active Session → Check Relevance

# Extract session ID
bash(find ${projectRoot}/.workflow/active/ -name "WFS-*" -type d 2>/dev/null | head -1 | xargs basename)

# Read project name from metadata
bash(cat ${projectRoot}/.workflow/active/WFS-promptmaster-platform/workflow-session.json | grep -o '"project":"[^"]*"' | cut -d'"' -f4)

# Check keyword match (manual comparison)
# If task contains project keywords → Reuse session
# If task unrelated → Create new session (use Step 2a)

Output (reuse): SESSION_ID: WFS-promptmaster-platform Output (new): SESSION_ID: WFS-[new-slug]

Step 2c: Multiple Active Sessions → Use First

# Get first active session
bash(find ${projectRoot}/.workflow/active/ -name "WFS-*" -type d 2>/dev/null | head -1 | xargs basename)

# Output warning and session ID
# WARNING: Multiple active sessions detected
# SESSION_ID: WFS-first-session

Mode 3: Force New Mode

Usage

workflow:session:start --new "task description"

Step 1: Generate Unique Session Slug

# Convert to slug
bash(echo "fix login bug" | sed 's/[^a-zA-Z0-9]/-/g' | tr '[:upper:]' '[:lower:]' | cut -c1-50)

# Check if exists, add counter if needed
bash(ls ${projectRoot}/.workflow/active/WFS-fix-login-bug 2>/dev/null && echo "WFS-fix-login-bug-2" || echo "WFS-fix-login-bug")

Step 2: Create Session Structure

bash(mkdir -p ${projectRoot}/.workflow/active/WFS-fix-login-bug/.process)
bash(mkdir -p ${projectRoot}/.workflow/active/WFS-fix-login-bug/.task)
bash(mkdir -p ${projectRoot}/.workflow/active/WFS-fix-login-bug/.summaries)

Step 3: Create Metadata

# Include type field from --type parameter (default: "workflow")
bash(echo '{"session_id":"WFS-fix-login-bug","project":"fix login bug","status":"planning","type":"workflow","created_at":"2024-12-04T08:00:00Z"}' > ${projectRoot}/.workflow/active/WFS-fix-login-bug/workflow-session.json)

Output: SESSION_ID: WFS-fix-login-bug

Execution Guideline

  • Non-interrupting: When called from other commands, this command completes and returns control to the caller without interrupting subsequent tasks.

Session ID Format

  • Pattern: WFS-[lowercase-slug]
  • Characters: a-z, 0-9, - only
  • Max length: 50 characters
  • Uniqueness: Add numeric suffix if collision (WFS-auth-2, WFS-auth-3)

Output Format Specification

Success

SESSION_ID: WFS-session-slug

Error

ERROR: --auto mode requires task description
ERROR: Failed to create session directory

Analysis (Auto Mode)

ANALYSIS: Task relevance = high
DECISION: Reusing existing session
SESSION_ID: WFS-promptmaster-platform

Output

  • Variable: sessionId (e.g., WFS-implement-oauth2-auth)
  • File: {projectRoot}/.workflow/active/{sessionId}/planning-notes.md
  • TodoWrite: Mark Phase 1 completed, Phase 2 in_progress

Next Phase

Return to orchestrator showing Phase 1 results, then auto-continue to Phase 2: Context Gathering.