# Rustie Method

> AI-assisted development workflow system for feature planning, session management, and quality assurance (v2.3). WORKTREE-CENTRIC - automatically scopes to current worktree's feature (worktree name = feature name). In feature worktrees, shows only relevant feature context. In main branch, shows dashboard of all worktrees. AUTO-ACTIVATES for session start (show priorities/NBA with Explore agent), feature work (load plan context with LSP symbol grounding), new features (spike mode with parallel sub-agents), context >70% (create handoff), UI changes (run Playwright tests), completed features (suggest archive), errors or failures (trigger RCA-PCA). Works with agent-docs/ folder structure. Modes are nba, work, spike, test, validate, sync, status, handoff, archive, rca-pca, tidyup. Use when working in codebases with agent-docs/ directory.

- Skill: `majiayu000/rustie-method` (Agent Skill, multi-file: 2 files)
- Install (CLI): `npx skillmds add majiayu000/rustie-method`
- Raw SKILL.md: https://api.skillmd.com/api/skills/majiayu000/rustie-method/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: majiayu000 (https://skillmd.com/u/majiayu000)
- Updated: 2026-09-09
- Page: https://skillmd.com/skills/majiayu000/rustie-method

---


# Rustie Method Skill

AI-assisted development workflow for structured feature development, session management, and quality assurance.

## Quick Reference - All Modes

**CORE PRINCIPLE**: Worktree name = Feature name = Context scope

| Mode | Auto-Trigger | Manual Trigger | Feature Worktree | Main Branch |
|------|--------------|----------------|------------------|-------------|
| **nba** | Session start, "priorities" | "run nba mode" | THIS feature only | Dashboard: all worktrees |
| **work** | Git branch `feature/*` | "load feature X" | Auto-load (no prompt) | List & ask |
| **test** | UI files modified | "run tests" | THIS feature | Prompt for feature |
| **validate** | Before work mode | "validate feature" | THIS feature | Prompt for feature |
| **spike** | After validate (new features) | "test assumptions" | THIS feature | Prompt for feature |
| **sync** | Called by nba/work | "sync plans" | THIS worktree | "sync all" for all |
| **status** | "status", "where am I" | "show status" | THIS feature only | Overview all worktrees |
| **handoff** | Context >70%, "wrap up" | "create handoff" | Auto-detect feature | Read from context |
| **archive** | Feature 100% complete | "archive feature" | THIS feature | List completable |
| **rca-pca** | Errors, failures | "run rca" | Lesson in feature | Global lesson |
| **tidyup** | "organize", "cleanup" | "tidyup" | - | - |

---

## Worktree-Centric Workflow - CORE CONCEPT

Rustie operates on a fundamental principle: **worktree name = feature name = context scope**.

### The 1:1 Mapping

```
Worktree Folder    ←→    Feature Folder              ←→    Active Context File
─────────────────────────────────────────────────────────────────────────────────
./project-auth     ←→    agent-docs/features/auth/   ←→    features/auth/active-context.md
./project-payments ←→    agent-docs/features/payments/ ←→  features/payments/active-context.md
./project (main)   ←→    agent-docs/features/*/      ←→    (reads ALL feature contexts)
```

### Feature-Scoped Active Context (v2.1)

Each feature maintains its own `active-context.md` file inside its folder:

```
agent-docs/features/
├── auth/
│   ├── PRD.md
│   ├── plan.md
│   ├── active-context.md    ← Auth's session state
│   └── sessions/
└── payments/
    ├── PRD.md
    ├── plan.md
    ├── active-context.md    ← Payments' session state
    └── sessions/
```

**Why feature-scoped context?**
- Prevents sync conflicts between worktrees
- Each worktree reads its own feature's context
- Main branch can aggregate all contexts for dashboard view
- Context and sessions stay co-located

### Worktree Configuration (worktrees.md)

Each project should have an `agent-docs/worktrees.md` file to track port assignments and worktree-specific configuration. This enables running multiple dev servers simultaneously.

**Location**: `agent-docs/worktrees.md`

**Template**:
```markdown
# Worktree Configuration

## Port Assignments

| Worktree | Feature | Dev Port | Other Services |
|----------|---------|----------|----------------|
| project (main) | - | 3000 | - |
| project-auth | auth | 3001 | - |
| project-payments | payments | 3002 | Stripe mock: 4242 |
| project-design | design-system | 3003 | Storybook: 6006 |

## Port Convention

- **Main branch**: Default port (3000)
- **Feature worktrees**: 3001+ in creation order
- **Additional services**: Document in "Other Services" column

## Adding a New Worktree

1. Create worktree: `git worktree add ../project-feature feature-branch`
2. Assign next available port in this table
3. Configure the worktree:
   ```bash
   cd ../project-feature
   echo "PORT=30XX" >> .env.local
   ```
4. Commit the updated worktrees.md

## Environment Setup

Each worktree should have a `.env.local` (gitignored) with:
```
PORT=30XX
# Other worktree-specific env vars
```
```

**Benefits**:
- Run multiple dev servers simultaneously
- Quick reference for which port to use
- Avoid port conflicts between features
- Document additional services (Storybook, mock APIs, databases)

### Detection Logic

At session start and for every mode, Rustie determines context:

```bash
# 1. Get current worktree folder name
worktree_name=$(basename "$(git rev-parse --show-toplevel)")

# 2. Get current branch
branch=$(git branch --show-current)

# 3. Determine scope
if [[ "$branch" =~ ^(main|master)$ ]]; then
  SCOPE="DASHBOARD"  # Show all worktrees/features
else
  # Extract feature name from worktree
  # Convention: {project}-{feature} where feature may contain hyphens
  # e.g., "trustie-auth" → "auth"
  # e.g., "trustie-design-system" → "design-system"

  # Method: Remove first segment (project name) only
  feature_name="${worktree_name#*-}"  # Remove up to FIRST hyphen only

  # Validate feature exists in agent-docs
  if [[ -d "agent-docs/features/$feature_name" ]]; then
    SCOPE="$feature_name"
  else
    # Fallback: try matching against existing feature folders
    for dir in agent-docs/features/*/; do
      dir_name=$(basename "$dir")
      if [[ "$worktree_name" == *"$dir_name"* ]]; then
        SCOPE="$dir_name"
        break
      fi
    done
    [[ -z "$SCOPE" ]] && SCOPE="UNKNOWN"  # Prompt user to clarify
  fi
fi
```

**Important**: The convention is `{project}-{feature}` where:
- Project name is a single segment (no hyphens): `trustie`, `myapp`, `acme`
- Feature name can contain hyphens: `auth`, `design-system`, `user-profile`

Examples:
| Worktree Name | Extracted Feature |
|---------------|-------------------|
| `trustie-auth` | `auth` |
| `trustie-design-system` | `design-system` |
| `trustie-user-profile` | `user-profile` |
| `myapp-payments` | `payments` |

### Scoping Rules by Mode

| Mode | Feature Worktree Behavior | Main/Master Behavior |
|------|---------------------------|----------------------|
| **NBA** | Next task for THIS feature only | Dashboard: all features across all worktrees |
| **Work** | Auto-load feature (no prompt) | List features, ask which one |
| **Status** | THIS feature's progress only | Overview of all worktrees |
| **Handoff** | Auto-detect feature from worktree | N/A (prompt for feature) |
| **Sync** | Sync THIS worktree | Sync all or prompt for specific |
| **Test** | Test THIS feature | Prompt for feature |
| **Archive** | Archive THIS feature | List completable features |

### Scope Indicator in Output

Every Rustie output MUST include scope context:

```
RUSTIE [auth] - Scoped to current worktree
# or
RUSTIE [DASHBOARD] - All worktrees
```

### Worktree Overview Table (Main Branch Only)

When in main/master, NBA and Status modes show:

```
WORKTREE OVERVIEW
─────────────────────────────────────────────────────────────────
Worktree              Feature             Status        Progress
─────────────────────────────────────────────────────────────────
./trustie-auth        auth                In Progress   60% (6/10)
./trustie-payments    payments            Not Started   0% (0/8)
./trustie-ui          design-system       On Hold       30% (3/10)
./trustie (main)      [DASHBOARD]         -             -
─────────────────────────────────────────────────────────────────
Active: 1 in progress, 1 not started, 1 on hold
```

### Worktree Discovery

To build the overview table:

```bash
# List all worktrees for this repo
git worktree list --porcelain | grep "^worktree" | cut -d' ' -f2

# For each worktree, extract feature name and find matching plan
for wt in $(git worktree list --porcelain | grep "^worktree" | cut -d' ' -f2); do
  wt_name=$(basename "$wt")
  feature="${wt_name#*-}"  # Remove project prefix (up to first hyphen)
  plan="$wt/agent-docs/features/$feature/plan.md"
  if [[ -f "$plan" ]]; then
    # Extract progress from plan
  fi
done
```

### Why This Matters

1. **Reduced cognitive load**: Only see what's relevant to current work
2. **Faster startup**: No scanning unrelated plans
3. **Natural isolation**: Git worktrees provide code isolation; Rustie mirrors this for docs
4. **Dashboard when needed**: Main branch = planning/coordination view

---

## Commit Discipline - CRITICAL

**Rule**: Every commit must be EITHER agent-docs OR code, NEVER both.

**Enforcement**: Install the pre-commit hook to block mixed commits automatically:
```bash
rustie-install-hooks.sh
```

### Why
- Enables cherry-picking agent-docs commits to other worktrees
- Keeps git history clean and sync-able
- Makes `git log -- agent-docs/` useful for finding updates

### Workflow
1. **Before committing**: Check `git status` (or let pre-commit hook catch it)
2. **If both agent-docs/ AND code changed**:
   - Stage and commit agent-docs first: `git add agent-docs/ && git commit -m "docs: ..."`
   - Then stage and commit code: `git add . && git commit -m "feat/fix: ..."`
3. **If only one type changed**: Commit normally

### Commit Message Examples
```
docs: update plan progress for topic-research
docs: session handoff - design-system
docs: add lesson on playwright conflicts
feat: implement forum adapter component
fix: resolve null reference in survey form
```

### Cherry-Pick Workflow
To sync agent-docs to another worktree:
```bash
# In target worktree
git fetch origin
git cherry-pick <commit-hash>  # Pick specific docs: commits
# Or cherry-pick a range
git log --oneline origin/main -- agent-docs/  # Find commits
```

---

## Mode: NBA (Next Best Action)

**Triggers**: Session start with agent-docs/ present, "priorities", "what should I work on", "what's next"

Recommend what to work on next. **Behavior depends on worktree context.**

### Worktree-Aware Behavior

| Context | Behavior |
|---------|----------|
| **Feature worktree** | Show next task for THIS feature only |
| **Main/master** | Dashboard view of ALL worktrees/features |

### Steps

0. **Script alternative**: Run `rustie-session-start.sh` for automated pre-flight checks.
   The script handles steps 1-3 and outputs a summary. Use when starting a session.

1. **Detect scope** (see Worktree-Centric Workflow section):
   ```bash
   branch=$(git branch --show-current)
   if [[ "$branch" =~ ^(main|master)$ ]]; then
     SCOPE="DASHBOARD"
   else
     worktree_name=$(basename "$(git rev-parse --show-toplevel)")
     SCOPE="${worktree_name#*-}"  # Remove project prefix (up to first hyphen)
   fi
   ```

2. **Pre-flight**: Check `agent-docs/features/` exists.

3. **Auto-sync** (silent): Fetch latest plan updates from origin.
   ```bash
   git fetch origin --quiet
   ```

4. **If SCOPE = feature name** (Feature Worktree):
   - Read ONLY `agent-docs/features/$SCOPE/plan.md`
   - Extract status, progress, next unchecked task
   - Display scoped output (see below)

5. **If SCOPE = DASHBOARD** (Main Branch):
   - Discover all worktrees: `git worktree list`
   - For each worktree, find matching feature plan
   - Also scan local `agent-docs/features/*/plan.md` for features without worktrees
   - Build worktree overview table
   - Categorize and prioritize

6. **For each plan**, extract:
   - Feature name (from directory)
   - Status (`**Status**:` line)
   - Progress (count `[x]` vs total `[ ]`)
   - Next unchecked task (first `- [ ]`)
   - Worktree path (if exists)

7. **Categorize**:
   - **In Progress**: Has unchecked tasks, not "Complete" or "On Hold"
   - **Not Started**: 0% progress
   - **On Hold**: Status contains "Hold" or "Blocked"
   - **Complete**: 100% or Status = "Complete"

8. **Display (Feature Worktree)**:
   ```
   RUSTIE [feature-name] NBA
   ─────────────────────────────────────────

   Feature: [feature-name]
   Progress: X/Y tasks (Z%)
   Status: In Progress

   NEXT TASK:
   → [first unchecked task]

   Following tasks:
   2. [task]
   3. [task]

   START: [next task or blocker to resolve]
   ```

9. **Display (Dashboard - Main Branch)**:
   ```
   RUSTIE [DASHBOARD] NBA - ALL WORKTREES
   ─────────────────────────────────────────────────────────────────────────

   WORKTREE OVERVIEW
   Worktree              Feature             Port   Status        Progress
   ─────────────────────────────────────────────────────────────────────────
   ./project-auth        auth                3001   In Progress   60% (6/10)
   ./project-payments    payments            3002   Not Started   0% (0/8)
   (no worktree)         design-system       -      On Hold       30% (3/10)
   ─────────────────────────────────────────────────────────────────────────

   RECOMMENDATION:
   Continue "auth" in ./project-auth (localhost:3001)
   Next: [task description]

   To work: cd ../project-auth && claude
   To create worktree: git worktree add ../project-payments payments
   ```

   Port information is read from `agent-docs/worktrees.md`.

10. **Optionally** ask user which feature to work on (main branch only).

---

## Mode: Work

**Triggers**: Git branch pattern `feature/*` or `claude/*`, "load feature X", "start work on X", "work on X"

Load a feature's plan and PRD, update active-context, show next tasks. **Auto-detects feature from worktree.**

### Worktree-Aware Behavior

| Context | Behavior |
|---------|----------|
| **Feature worktree** | Auto-detect feature from worktree name - NO prompt needed |
| **Main/master** | List features and ask user which one to load |

### Steps

1. **Detect scope and auto-select feature**:
   ```bash
   branch=$(git branch --show-current)
   if [[ "$branch" =~ ^(main|master)$ ]]; then
     # Main branch: list features and ask
     feature=""  # Will prompt user
   else
     # Feature worktree: auto-detect
     worktree_name=$(basename "$(git rev-parse --show-toplevel)")
     feature="${worktree_name#*-}"  # Remove project prefix (up to first hyphen)

     # Validate feature exists
     if [[ ! -d "agent-docs/features/$feature" ]]; then
       echo "Warning: No matching feature for worktree '$worktree_name'"
       feature=""  # Fall back to prompt
     fi
   fi
   ```

2. **If feature not auto-detected**: Match argument against `agent-docs/features/*/`. If no argument, list features and ask user.

3. **Auto-sync** (silent): Fetch latest from origin.

4. **Check assumptions** (v2.2 - MANDATORY for new features):
   ```bash
   assumptions_file="agent-docs/features/$feature/assumptions.md"
   if [[ ! -f "$assumptions_file" ]]; then
     echo "No assumptions.md found. Running spike mode first..."
     # Trigger spike mode
   elif grep -q "❌ FAILED" "$assumptions_file"; then
     echo "Warning: Feature has unresolved failed assumptions"
     # Show failed assumptions and ask to confirm
   fi
   ```
   - If no assumptions.md → automatically run spike mode first
   - If assumptions.md has unresolved failures → warn and confirm before proceeding

5. **Read plan**: `agent-docs/features/[feature]/plan.md`
   - Extract status, progress, next 5 unchecked tasks
   - Extract current phase

6. **Read PRD** (if exists): `agent-docs/features/[feature]/PRD.md`
   - Extract overview and user stories for context

7. **LSP Symbol Grounding** (v2.3 - prevents hallucination):
   Before implementation, verify key symbols exist using LSP:

   ```
   # Identify key files from plan.md
   key_files = ["src/adapters/forum.ts", "src/types/post.ts"]

   # For each file, get real symbols via LSP
   for file in key_files:
     LSP: documentSymbol(file)
     → ForumAdapter (class), fetchPosts (method), Post (interface)

   # Include verified symbols in session context
   ```

   **Why this matters:**
   - AI may "remember" function names that don't exist
   - LSP provides ground truth from the actual codebase
   - Prevents errors like calling `getPosts()` when it's actually `fetchPosts()`

   **Integration:**
   - Run LSP documentSymbol on 2-5 key files identified in plan
   - Include real symbol names in session briefing
   - Reference verified names during implementation

8. **Update feature's active-context.md** (v2.1 - feature-scoped):

   **Script alternative**: Run `rustie-context-update.sh start` to create/update context reliably.

   Manual approach:
   ```bash
   # Path: agent-docs/features/[feature]/active-context.md
   context_file="agent-docs/features/$feature/active-context.md"
   ```
   ```markdown
   **Last Updated**: [now]
   **Feature**: [feature]
   **Worktree**: [worktree path]
   **Status**: In Progress

   ## Current Session
   Started: [timestamp]

   ## Next Steps
   1. [ ] [task from plan]
   2. [ ] [task from plan]

   ## Recent Changes
   - [will be updated as work progresses]
   ```

9. **Commit agent-docs separately**:
   ```bash
   git add agent-docs/
   git commit -m "docs: start work on [feature]"
   ```
   Note: If you also have code changes, commit them separately AFTER this.

10. **Show session briefing**:
   ```
   RUSTIE [feature-name] WORK SESSION
   ─────────────────────────────────────────

   Feature: [name]
   Worktree: [./project-feature]
   Dev Server: localhost:[port]  ← from worktrees.md
   Progress: X/Y tasks (Z%)
   Current Phase: [phase]

   ASSUMPTIONS: ✅ All verified (or ⚠️ X unresolved)

   NEXT 5 TASKS:
   - [ ] Task 1
   - [ ] Task 2
   ...

   FILES TO READ:
   - [path] - [why]

   START HERE: [first task or file to read]
   ```

   Read port from `agent-docs/worktrees.md` for this feature.

### Auto-Detection Examples

```
# In worktree ./trustie-auth (branch: auth or feature/auth)
$ claude "work mode"
→ Auto-detects feature "auth", loads plan immediately

# In main worktree (branch: main)
$ claude "work mode"
→ Lists all features, asks user which to load

# In worktree with explicit argument
$ claude "work on payments"
→ Uses explicit argument, ignores worktree detection
```

---

## Mode: Test

**Triggers**: Files in `app/`, `components/`, `pages/` modified, "test feature", "run playwright", "run tests"

Test features with Playwright, capture screenshots, optionally verify against design system.

### ⚠️ CRITICAL: Use Direct Playwright, NOT MCP

**For any project with UI, ALWAYS use project-installed Playwright via Bash**, not Playwright MCP tools.

**Why**: Playwright MCP uses a shared browser profile that causes "Browser is already in use"
errors in multi-worktree environments. Direct Playwright launches isolated browser instances.

**Setup** (one-time per project):
```bash
npm install -D @playwright/test playwright
npx playwright install chromium
```

**Create test script** at `tests/capture-screenshots.ts`:
```typescript
import { chromium } from 'playwright';

// Use PORT from .env.local or default based on worktree
// See agent-docs/worktrees.md for port assignments
const PORT = process.env.PORT || '3000';
const BASE_URL = process.env.TEST_URL || `http://localhost:${PORT}`;

async function captureScreenshots() {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({
    viewport: { width: 1280, height: 720 }
  });
  const page = await context.newPage();

  // Navigate and capture
  await page.goto(`${BASE_URL}/your-page`);
  await page.screenshot({ path: 'tests/screenshots/page.png' });

  await browser.close();
}

captureScreenshots().catch(console.error);
```

### Usage Variants
- Basic test: "test [feature]"
- Full journey: "test [feature] user-journey"
- With design review: "test [feature] verify"

### Steps

1. **Ensure Playwright is installed**:
   ```bash
   grep "@playwright" package.json || npm install -D @playwright/test playwright
   ```

2. **Find feature plan**: `agent-docs/features/[feature]/plan.md`

3. **Read PRD** for user stories and expected behavior.

4. **Start dev server** if not running:
   ```bash
   npm run dev &
   # Wait for localhost:3000 (verify with: curl -s localhost:3000)
   ```

5. **If user-journey**:
   - Design journey from PRD user stories (CRUD flow)
   - Generate test data with LLM
   - **Run tests via Bash** (NOT MCP):
     ```bash
     npx tsx tests/capture-screenshots.ts
     # OR for full test suite:
     npx playwright test
     ```
   - Take screenshot after each step

6. **If verify**:
   - Send each screenshot to LLM for design review
   - Compare against design system (if exists)
   - Flag issues

7. **Create test report**:
   ```bash
   mkdir -p agent-docs/features/[feature]/tests/screenshots
   # Save report: test-report-[timestamp].md
   ```

8. **Summary**:
   ```
   RUSTIE TEST COMPLETE

   Steps: X/Y passed
   Screenshots: Z captured
   Design Issues: N found

   Report: agent-docs/features/[feature]/tests/test-report-*.md
   ```

### When to Use MCP vs Direct Playwright

| Scenario | Use MCP | Use Direct Playwright |
|----------|---------|----------------------|
| Single worktree only | ✅ OK | ✅ OK |
| Multi-worktree environment | ❌ Conflicts | ✅ Required |
| Interactive exploration | ✅ Good | ⚠️ Requires script |
| Screenshot capture | ⚠️ Lock issues | ✅ Required |
| Visual regression testing | ❌ Unreliable | ✅ Required |
| CI/CD pipelines | ❌ N/A | ✅ Required |

**Reference**: See `agent-docs/lessons/playwright-mcp-worktree-conflicts.md` for full RCA-PCA.

---

## Mode: Validate

**Triggers**: Before work mode, "validate feature", "check structure"

Check that a feature directory has all required files and valid structure.

### Steps

1. **Find feature** (or validate current if no argument)

2. **Check required files**:
   - PRD.md - REQUIRED
   - plan.md - REQUIRED
   - sessions/ - OPTIONAL
   - tests/ - OPTIONAL

3. **Validate plan structure**:
   - Has `**Status**:` field
   - Has checkboxes (`- [ ]` or `- [x]`)
   - Has phases (## Phase headers)

4. **Validate PRD structure**:
   - Has Problem Statement
   - Has User Stories
   - Has Success Criteria

5. **Report results**:
   ```
   VALIDATION: [feature-name]

   Required Files:
   PRD.md: FOUND / MISSING
   plan.md: FOUND / MISSING

   Plan Structure:
   Status field: FOUND / MISSING
   Checkboxes: X found
   Phases: Y found

   Result: VALID / NEEDS FIXES
   ```

6. **If invalid**, suggest fixes.

7. **If valid AND new feature** (no assumptions.md exists):
   - Automatically trigger Spike mode
   - "Structure valid. Running assumption validation..."

---

## Mode: Spike (v2.4)

**Triggers**:
- Automatically after validate passes for new features (no assumptions.md)
- "test assumptions", "spike", "validate assumptions"
- "check assumptions for [feature]"

**Purpose**: Identify and test key technical assumptions BEFORE implementation starts. This prevents wasted effort when plans are based on false assumptions.

**v2.4 Enhancements**:
- **LSP Grounding**: Verify code reality before planning
- **ADR Integration**: Record significant decisions during spike
- **Pattern Compliance**: Surface lessons and codebase patterns
- **PRD Hash Tracking**: Detect assumption drift

### Why Spike Mode Exists

**Problem**: Plans often contain implicit technical assumptions that aren't validated until implementation fails.

**Example**: A web scraping project assumed server-side rendering, but the site was client-side rendered. The entire approach was invalidated after work started.

**Solution**: Test assumptions with minimal "spike" code before committing to implementation.

### Assumption Categories (Explicit)

| Category | Examples | Test Methods |
|----------|----------|--------------|
| **Rendering** | SSR vs CSR, static vs dynamic | `curl` + check content, view page source |
| **API** | REST vs GraphQL, auth method, rate limits | API probe requests |
| **Data Format** | JSON structure, encoding, pagination | Sample request + parse |
| **Dependencies** | Package availability, version compatibility | Package lookup, install test |
| **Performance** | Response times, throughput limits | Timed requests |
| **Access** | Authentication requirements, CORS, robots.txt | Direct access tests |

### Implicit Assumption Discovery (v2.2)

The categories above catch "known unknowns" - assumptions we know to look for. But plans often contain "unknown unknowns" - assumptions so implicit they're invisible until they fail.

**Two-Phase Approach**:
- **Phase 1**: Check explicit categories (table above)
- **Phase 2**: Discover implicit assumptions through structured prompting

**Discovery Prompts** (run after Phase 1):

1. **Senior Engineer Review**:
   ```
   As a senior engineer with 20 years of experience, ultrathink about this plan and PRD.
   What implicit assumptions are being made that aren't explicitly stated? Consider:
   - Environmental (OS, memory, network reliability, disk space)
   - Timing/ordering (events arrive in order, responses before timeout)
   - State/consistency (database state, cache validity)
   - Scale (concurrent users, data volume growth)
   - Integration (third-party API stability, backward compatibility)
   - Security (input sanitized upstream, auth handled elsewhere)
   - User behavior (users won't do X, all users have Y)
   - Cultural/locale (language, timezone, currency, date format)
   ```

2. **Failure Mode Analysis**:
   ```
   What could go wrong that we haven't explicitly considered?
   What edge cases would break this design?
   What happens if [network fails / API is slow / data is malformed / load spikes]?
   ```

3. **Pessimist Review**:
   ```
   As a pessimistic code reviewer who has seen many projects fail:
   What holes would you poke in this plan?
   What would you insist we verify before proceeding?
   What's the most likely way this project fails?
   ```

**Domain-Specific Discovery Questions**:

| Domain | Questions to Ask |
|--------|------------------|
| **Web Scraping** | What if site structure changes? Rate limiting? Geo-blocking? |
| **API Integration** | What about retries? Idempotency? Version changes? |
| **Data Processing** | Character encoding? Malformed input? Memory limits? |
| **Mobile/Cross-platform** | Device fragmentation? Offline mode? Battery impact? |
| **Auth/Security** | Token expiry? Session handling? Permission edge cases? |

**Discovered Assumption Handling**:
- **Testable**: Add to test queue with appropriate priority
- **Non-testable but critical**: Document as "⚠️ NOTED - manual consideration required"
- **Architectural**: May require plan revision before testing

### Pre-Spike LSP Grounding (v2.4)

Before testing assumptions, ground the plan in code reality using LSP tools. This prevents plans that reference non-existent code or ignore established patterns.

**LSP Grounding Steps**:

1. **Identify key files from PRD.md**:
   - Dependencies mentioned (APIs, libraries, components)
   - Integration points (files that will be modified)
   - Related existing features

2. **Run LSP documentSymbol** on key files:
   ```
   For each key file:
   → LSP documentSymbol to get functions, classes, interfaces
   → Build verified symbol table
   ```

3. **Run LSP findReferences** for key functions:
   ```
   For heavily-used patterns:
   → LSP findReferences to see how they're used
   → Extract existing conventions
   ```

4. **Build Code Reality Summary**:
   ```markdown
   ## Code Reality Check (LSP-Grounded)

   ### Verified Symbols (can be called/used)
   | File | Symbol | Type | References |
   |------|--------|------|------------|
   | src/auth/jwt.ts | verifyToken | function | 12 |
   | src/api/client.ts | fetchWithRetry | function | 8 |

   ### Existing Patterns Detected
   - Error handling: ErrorBoundary component (23 usages)
   - API calls: All use fetchWithRetry wrapper
   - State management: React Context (no Redux)

   ### Grounding Violations
   ⚠️ Plan references `AuthService.validate()` - symbol not found
   ⚠️ Plan assumes REST, but `graphql/` directory detected
   ```

**Benefits**:
- Plans cannot reference non-existent functions
- Existing patterns are surfaced before decisions
- Architectural assumptions caught before implementation

### ADR Integration (v2.4)

When significant design decisions are made during spike, record them as Architecture Decision Records (ADRs) in the existing `decisions/adrs/` structure.

**When to Create ADR**:
- Choosing between alternative approaches (e.g., REST vs GraphQL)
- Selecting technology/library for a capability
- Deciding on architectural patterns
- Resolving contradictions between requirements

**ADR Creation During Spike**:

1. **Detect decision point**: When spike reveals a choice must be made
2. **Prompt for ADR**:
   ```
   Significant decision detected: [choice description]

   Create ADR? This will document:
   - The decision and rationale
   - Alternatives considered
   - Lessons that informed this choice

   [Create ADR] [Skip - not significant]
   ```

3. **Create ADR file** in appropriate location:
   - Feature-specific: `agent-docs/features/{feature}/decisions/ADR-{n}-{slug}.md`
   - Global/cross-cutting: `agent-docs/decisions/adrs/ADR-{n}-{slug}.md`

4. **ADR Template**:
   ```markdown
   # ADR-{number}: {title}

   **Status**: Proposed | Accepted | Deprecated | Superseded
   **Date**: {date}
   **Feature**: {feature-name} or "Global"

   ## Context
   What is the issue that motivated this decision?

   ## Decision
   What is the change or approach we're adopting?

   ## Rationale
   Why this approach over alternatives?

   ## Alternatives Considered
   | Alternative | Pros | Cons |
   |-------------|------|------|
   | {alt 1} | {pros} | {cons} |
   | {alt 2} | {pros} | {cons} |

   ## Consequences
   What becomes easier or harder because of this?

   ## Related
   - PRD: {link if applicable}
   - Lessons: {relevant lesson refs}
   - Prior ADRs: {supersedes/relates-to}
   ```

5. **Link from assumptions.md**: Add ADR reference to Related ADRs section

### Pattern Surfacing (v2.4)

At spike start, systematically gather patterns from three sources:

**Tier 1: Lesson Patterns** (from RCA-PCA system)
- Query lessons catalog for `trigger_technologies` matching PRD tech stack
- Query for `trigger_contexts` matching feature type
- Extract PCAs as patterns to follow/consider

**Tier 2: Code Patterns** (from codebase via Explore agent + LSP)
- **Use Explore agent** for broad pattern detection (v2.4):
  ```
  Task(subagent_type="Explore", prompt="""
  Find existing implementations related to [feature domain]:
  1. Similar features (authentication, API endpoints, etc.)
  2. Established patterns (error handling, state management, etc.)
  3. Utility functions that should be reused
  4. Architectural patterns (folder structure, naming conventions)

  Return: file paths, pattern descriptions, usage counts
  """)
  ```
- Use LSP findReferences on common utilities for precise counts
- Identify established conventions (error handling, API calls, etc.)
- Surface as "existing patterns"

**Tier 3: ADR Patterns** (from prior decisions)
- **Use rustie-prior-decisions.sh** for automated ADR cross-referencing (v2.4):
  ```bash
  # Query prior ADRs for relevant precedents
  ./scripts/rustie-prior-decisions.sh --keywords "auth,jwt,session" --feature "user-login"

  # Output: matching ADRs with status, decisions, and conflict flags
  ```
- Search `decisions/adrs/` for related prior decisions
- Flag potential conflicts with new decisions
- Surface as "precedent decisions"

**Pattern Compliance Table** (added to assumptions.md):
```markdown
## Pattern Compliance

| Pattern | Source | Status | Notes |
|---------|--------|--------|-------|
| "Always use fetchWithRetry" | codebase:src/api/client.ts | Will Follow | |
| "JWT via interceptor" | ADR-042 | Will Follow | |
| "Validate inputs at boundary" | lesson:api-security | Will Follow | |
| "Use GraphQL for complex queries" | ADR-015 | Conflict | PRD suggests REST |
```

**Status Values**:
- `Will Follow`: Will implement this pattern
- `Conflict`: Pattern conflicts with current approach - needs ADR
- `Not Applicable`: Pattern doesn't apply to this feature
- `Override`: Consciously choosing different approach (document why)

### Steps

1. **Read PRD.md and plan.md** for the feature

2. **Compute PRD Hash** (for drift detection):
   ```bash
   # Store hash to detect future PRD changes
   PRD_HASH=$(sha256sum agent-docs/features/{feature}/PRD.md | cut -d' ' -f1)
   ```

3. **Run Pre-Spike LSP Grounding** (v2.4):
   - Identify key files mentioned in PRD
   - Run LSP documentSymbol on each
   - Build Code Reality Summary
   - Flag any grounding violations

4. **Surface Patterns** (v2.4):
   - Query lessons catalog for matching patterns
   - Use LSP to detect codebase patterns
   - Check prior ADRs for precedent decisions
   - Build Pattern Compliance table

5. **Phase 1 - Extract explicit assumptions** (predefined categories):
   - Scan for technology choices mentioned or implied
   - Identify external dependencies
   - Note data format expectations
   - Flag performance requirements
   - List access/auth assumptions

6. **Phase 2 - Discover implicit assumptions** (structured prompting):
   - Run Senior Engineer Review prompt
   - Run Failure Mode Analysis
   - Run Pessimist Review
   - Apply domain-specific questions if applicable
   - Merge discovered assumptions with explicit list

7. **Categorize ALL assumptions by risk**:
   - **Critical**: If wrong, invalidates entire approach
   - **High**: Requires significant plan changes
   - **Medium**: Requires task-level adjustments
   - **Low**: Minor impact

8. **Create verification tests** for Critical/High assumptions:
   ```bash
   # Example: Test if site is SSR
   curl -s "https://example.com" | grep -q "expected-content"

   # Example: Test API endpoint exists
   curl -s -o /dev/null -w "%{http_code}" "https://api.example.com/endpoint"

   # Example: Check rate limiting
   for i in {1..10}; do curl -s -o /dev/null -w "%{http_code}\n" "https://api.example.com"; done
   ```

9. **Run tests** and collect results

10. **Create/update assumptions.md** (v2.4 enhanced template):
   ```markdown
   # Technical Assumptions: [feature]

   ## Context (v2.4)
   **Last Validated**: [timestamp]
   **Feature**: [feature-name]
   **PRD Hash**: sha256:[hash] (for drift detection)
   **Related ADRs**: [links to ADRs created during this spike]

   ## Code Reality Check (LSP-Grounded)

   ### Verified Symbols
   | File | Symbol | Type | References |
   |------|--------|------|------------|
   | src/auth/jwt.ts | verifyToken | function | 12 |
   | src/api/client.ts | fetchWithRetry | function | 8 |

   ### Grounding Violations
   ⚠️ None detected (or list violations)

   ## Pattern Compliance

   | Pattern | Source | Status | Notes |
   |---------|--------|--------|-------|
   | "Use fetchWithRetry" | codebase:src/api/client.ts | Will Follow | |
   | "JWT via interceptor" | ADR-042 | Will Follow | |
   | "Validate inputs" | lesson:api-security | Will Follow | |

   ## Critical Assumptions (Explicit)

   | Assumption | Test | Result | Impact |
   |------------|------|--------|--------|
   | Site is SSR | curl + grep content | ❌ FAILED | Need browser automation |
   | API is REST | GET /api endpoint | ✅ PASSED | - |

   ## High-Risk Assumptions (Explicit)

   | Assumption | Test | Result | Impact |
   |------------|------|--------|--------|
   | No auth required | curl without headers | ✅ PASSED | - |

   ## Discovered Assumptions (Implicit)

   These were surfaced through structured review, not predefined categories.

   | Source | Assumption | Risk | Test | Result |
   |--------|------------|------|------|--------|
   | Senior Review | Network is reliable | Medium | N/A | ⚠️ NOTED |
   | Failure Analysis | API may change structure | High | Check API versioning | ✅ PASSED |
   | Pessimist Review | Rate limits under burst | High | Burst test (10 req/s) | ✅ PASSED |
   | Domain-Specific | Site structure may change | Medium | N/A | ⚠️ NOTED |

   ## Pending (not yet tested)

   - [ ] Rate limit > 60/min
   - [ ] Pagination supported

   ## Plan Impact

   ### Failed Assumptions
   - **Site is SSR**: Original plan used simple HTTP requests
     - **Revised**: Use Playwright for browser automation
     - **Tasks affected**: All scraping tasks

   ### Noted Assumptions (require manual consideration)
   - **Network reliability**: Add retry logic with exponential backoff
   - **Site structure changes**: Design for graceful degradation, add monitoring

   ### Recommendations
   1. Update plan.md with Playwright approach
   2. Add browser setup task
   3. Add retry logic for network resilience
   4. Increase time estimates by 50%
   ```

11. **If critical assumptions fail**:
   - Display clear warning
   - Show impact on plan
   - Offer options:
     1. Update plan automatically
     2. Discuss alternatives with user
     3. Proceed anyway (not recommended)

12. **Output summary**:
   ```
   RUSTIE [feature] SPIKE COMPLETE
   ─────────────────────────────────────────

   EXPLICIT ASSUMPTIONS (predefined categories):
   ✅ Passed: 3  ❌ Failed: 1 (CRITICAL)  ⏳ Pending: 1

   DISCOVERED ASSUMPTIONS (implicit):
   ✅ Tested: 2  ⚠️ Noted: 2 (require consideration)

   CRITICAL FAILURE:
   → "Site is SSR" - Content loaded via JavaScript

   NOTED (manual consideration required):
   → Network reliability - Add retry logic
   → Site structure changes - Add monitoring

   IMPACT: Plan requires browser automation (Playwright)

   Options:
   1. Update plan with Playwright approach
   2. Discuss alternatives
   3. Proceed with original plan (not recommended)

   assumptions.md saved to: agent-docs/features/[feature]/
   ```

### Integration with Work Mode

Work mode checks for assumptions.md:
- If exists with no critical failures → proceed
- If exists with unresolved failures → warn and ask to confirm
- If missing for feature with plan.md → trigger spike first

**PRD Drift Detection (v2.4)**:
Work mode also checks PRD hash when assumptions.md exists:
```bash
# Compare current PRD hash against stored hash
CURRENT_HASH=$(sha256sum agent-docs/features/{feature}/PRD.md | cut -d' ' -f1)
STORED_HASH=$(grep "PRD Hash" assumptions.md | cut -d':' -f2 | tr -d ' ')

if [ "$CURRENT_HASH" != "$STORED_HASH" ]; then
    echo "⚠️ PRD has changed since last spike!"
    echo "Assumptions may no longer be valid."
    echo "Options: [Re-spike] [Proceed anyway] [View diff]"
fi
```

**Continuous LSP Grounding (v2.4)**:
During work mode, run a background agent to verify code references in real-time:

```
Task(subagent_type="Explore", run_in_background=true, prompt="""
CONTINUOUS GROUNDING VERIFICATION

Monitor the current implementation for hallucination detection:

1. **File Path Verification**:
   - Extract file paths from plan.md and current task
   - Verify each path exists using Glob
   - Alert if referencing non-existent files

2. **Symbol Reference Verification**:
   - For each function/class mentioned in plan
   - Use LSP documentSymbol to verify it exists
   - Check signature matches expected usage

3. **Pattern Drift Detection**:
   - Compare implementation against Pattern Compliance table
   - Flag if deviating from stated patterns without ADR

Report Format:
```json
{
  "status": "grounded|drift_detected|hallucination",
  "verified_paths": [...],
  "missing_paths": [...],
  "verified_symbols": [...],
  "missing_symbols": [...],
  "pattern_violations": [...]
}
```

Alert immediately if:
- File path in plan doesn't exist
- Symbol referenced but not found via LSP
- Implementation contradicts Pattern Compliance table
""")
```

**When to Trigger Background Verification**:
- At work mode start (initial grounding check)
- After completing each plan step (incremental verification)
- Before major implementation decisions (pre-decision check)
- When context usage exceeds 50% (drift prevention)

**Handling Verification Alerts**:
```markdown
## Grounding Alert Response

| Alert Type | Severity | Action |
|------------|----------|--------|
| Missing file path | ERROR | Stop, correct plan or create file |
| Missing symbol | ERROR | Stop, verify with LSP, update approach |
| Pattern violation | WARN | Document deviation, create ADR if needed |
| Signature mismatch | WARN | Verify correct usage, update if wrong |
```

### Spike Best Practices

1. **Keep tests minimal** - Just enough to validate, not full implementation
2. **Test critical first** - Don't waste time on low-risk assumptions if critical fails
3. **Document everything** - Future sessions need to know what was validated
4. **

…(truncated)
