AI Development Environment - Multi-agent orchestration for Claude Code

version
0.2.1
GitHub stars
19

Install

/plugin install aide@aide

Run it inside Claude Code after adding the marketplace with /plugin marketplace add jmylchreest/aide.

Contents

Discovered from source

Skills 26

Assess Findings

Recommended model tier: balanced (sonnet) - this skill requires reading code and making judgement calls

Triage static analysis findings by reading the actual code, assessing whether each finding is genuine or noise, and accepting (dismissing) irrelevant ones using findings_accept. Accepted findings are hidden from future output by default.

Prerequisites

  • Findings must already exist. If findings_stats returns zero counts, tell the user to run:
    ./.aide/bin/aide findings run --path .
    
  • The findings_accept tool must be available (provided by the aide MCP server).

Available Tools

Read-only (shared with patterns skill)

ToolPurpose
findings_statsCounts by analyzer and severity — start here
findings_listBrowse findings with filters (analyzer, severity, file). Pass include_accepted=true when checking a decision — accepted findings are hidden by default
findings_searchFull-text search across finding titles and details

Decisions (conformance context)

ToolPurpose
decision_listList recorded decisions — load these before triaging
decision_getFetch one decision by topic when a finding may relate to it

Write (unique to this skill)

ToolPurpose
findings_acceptMark findings as accepted/dismissed by ID or filter

Code inspection

ToolPurpose
code_outlineGet collapsed file structure to understand context
ReadRead specific line ranges to evaluate finding merit

Workflow

0. Load the Decisions

Call decision_list first — it is authoritative, where the "Project Decisions" block in session context is a session-start snapshot that can predate a decision changed since. Fall back to the block only if the tool is unavailable. Decisions are the recorded architectural commitments for this project; a finding that evidences a decision violation is not noise, whatever its analyzer or severity says.

Blank applicability adds no restriction; respect limits in the decision's wording. For explicit applicability, interpret the text, selectors and repository-relative path patterns against the finding before treating it as a violation. These are agent guidance, not automatic file filters. Specificity alone does not override another decision.

Keep the list to hand for step 3. You are not searching the codebase for violations here — that is the review skill's job. You are checking whether findings the analyzers already produced happen to be evidence of one.

1. Get the Landscape

Call findings_stats to understand the scope:

findings_stats
-> Returns: counts per analyzer (complexity, coupling, secrets, clones) and severity

If the user asked to focus on a specific analyzer or severity, note that and filter accordingly. Otherwise, work through all findings systematically.

2. Prioritise Review Order

Work through findings in this order:

  1. Secrets (critical first) — these need immediate attention; false positives are common in test fixtures
  2. Complexity (critical, then warning) — assess whether high complexity is inherent or decomposable
  3. Clones (all) — determine if duplication is extractable or structural boilerplate
  4. Coupling (all) — assess whether high fan-in/fan-out is expected for the file's role

3. Assess Each Finding

For each finding or group of related findings:

  1. Read the finding details — note the file, line range, and metric values
  2. Read the actual code — read the flagged range directly and inspect enough surrounding code to judge it. Use code_outline when unfamiliar large-file structure would help locate context; read the full file when small or mostly relevant.
  3. Check it against the decisions from step 0 — see "Decision conformance gate" below
  4. Make a judgement call using these criteria:
Decision conformance gate

Before applying any accept criterion, ask: does this finding evidence a violation of a recorded decision?

A finding is decision-linked when the code it flags contradicts a decision's stated commitment. For example:

  • a deadcode finding on a symbol written ahead of its integration, against a decision requiring all code to be reachable from real call paths
  • a secrets finding in a runtime path, against a decision on credential handling
  • a coupling finding crossing a boundary a decision declared off-limits
  • a security finding using a mechanism a decision ruled out

Reachability findings turn on intent, not on whether a caller was found. A deadcode finding is decision-linked when the symbol is genuinely unused — written ahead of its integration, or left behind after it. It is not decision-linked when the symbol is reached by a mechanism the analyzer cannot see: framework convention (file-based routing, dependency injection, reflection), a declared entry point, generated code, or a test fixture. Those are analyzer blind spots, and accepting them is the correct resolution — name the mechanism that reaches the symbol as the rationale.

no-aspirational-code bans code waiting for a caller that does not exist. It does not ban code whose caller aide cannot index. Reading every unreferenced symbol as a violation would make a framework page component permanently unacceptable, and a finding with no legal resolution is one that trains people to ignore the whole gate.

A decision-linked finding cannot be accepted as noise. There are exactly two valid resolutions:

  1. Fix the code so it conforms — the finding disappears on the next findings run.
  2. Amend the decision — if the decision is genuinely wrong or has been superseded, say so explicitly and tell the user to run /decide on that topic. Do not accept the finding on the assumption that the decision will change.

If you are unsure whether a finding is decision-linked, name the mechanism you believe resolves it — the route that reaches the symbol, the reason the string is not a credential — and keep the finding if you cannot name one. "Unsure" is not falsifiable and defaulting to linked turns the gate into a ratchet; a named mechanism can be checked and argued with. Report anything kept this way under "Decision conflicts" so a human decides.

Note the limits of this gate. It grades findings the analyzers already produced; it cannot find a decision violation that no analyzer flagged. For a code-level sweep against the decisions, use the review skill.

Accept (dismiss) when:
  • Complexity: The function is inherently complex (CLI dispatch, protocol handling, state machines) and cannot be meaningfully decomposed without harming readability
  • Clones: The duplication is structural boilerplate (e.g., CLI subcommand wiring, store method patterns) where extraction would require framework-level abstraction
  • Coupling: High fan-in/fan-out is expected for the file's architectural role (e.g., a main entry point, a facade, a registry)
  • Secrets: The flagged string is a test fixture, example config, documentation placeholder, or env var name (not an actual secret)
Keep (do NOT accept) when:
  • The finding points to a genuine problem that should be fixed
  • Complexity can be reduced by extracting helper functions
  • Duplication can be resolved by creating a shared utility
  • A coupling cycle exists that indicates poor module boundaries
  • A string looks like it could be a real secret or credential
  • The finding is decision-linked (see the conformance gate above) — this overrides every accept criterion

4. Accept Findings

Use findings_accept to dismiss noise. You can accept:

  • By IDs — for individual findings after assessment:
    findings_accept ids=["finding-id-1", "finding-id-2"]
    
  • By filter — for bulk dismissal of an entire category:
    findings_accept analyzer="clones" file="cmd/"
    

Always explain why each finding is being accepted before calling the tool.

5. Report Summary

After completing the triage, produce a summary:

## Findings Triage Summary

### Before

- Total: X findings (Y critical, Z warnings, W info)

### Accepted (Dismissed)

- N findings accepted as noise/irrelevant
  - Complexity: X (inherent complexity in [files])
  - Clones: Y (structural boilerplate in [area])
  - Coupling: Z (expected for [role])
  - Secrets: W (test fixtures / placeholders)

### Decision Conflicts (must not be accepted)

- K findings evidence a violation of a recorded decision
  - `<decision-topic>` — file:line — [what the code does vs what the decision requires]
  - (omit this section entirely when there are none)

### Remaining (Genuine)

- M findings require attention
  - [List each with file:line and brief description]

### Recommendations

1. [Prioritised action items for genuine findings]

Decision Criteria Reference

AnalyzerAccept IfKeep If
complexityCyclomatic complexity is inherent to the problem domain; function handles unavoidable branching (CLI dispatch, protocol negotiation)Function can be decomposed into smaller, testable units
clonesDuplication is cross-cutting boilerplate (CLI wiring, store CRUD patterns)A shared utility or abstraction would reduce maintenance burden
couplingFile is an intentional integration point (main, facade, registry)Circular dependencies or unexpected transitive coupling exists
secretsTest fixture, documentation example, env var name, or placeholderLooks like a real credential, API key, or connection string
anyNever — a decision-linked finding is out of scope for acceptanceThe finding evidences a recorded decision violation (overrides every row above)

Failure Handling

  1. No findings — Tell user to run ./.aide/bin/aide findings run --path . first
  2. findings_accept not available — The aide MCP server may not expose this tool; tell the user to update aide
  3. Uncertain about a finding — When in doubt, keep it. It's better to flag a false positive for human review than to dismiss a real issue
  4. Large number of findings — Work in batches by analyzer. Accept obvious noise first, then do detailed code review for borderline cases
  5. decision_list returns nothing — The project has no recorded decisions; skip the conformance gate and say so in the summary. Do not invent decisions

Verification

  • Called decision_list (or noted the fallback) before triaging
  • Called findings_stats for baseline counts
  • Reviewed each finding category (secrets, complexity, clones, coupling)
  • Read actual code for every finding before accepting
  • Checked every finding against the recorded decisions before accepting it
  • No decision-linked finding was accepted
  • Provided rationale for each acceptance
  • Produced summary with before/after counts
  • Remaining findings are genuinely actionable

Autopilot Mode

Recommended model tier: smart (opus) - this mode handles complex multi-step tasks

Full autonomous execution mode. The agent keeps working until all tasks in the todo list are verified complete. No stopping early, no partial results.

Activation

Type naturally:

autopilot build me a web app
autopilot fix all failing tests
autopilot refactor the auth module

Or explicitly set the mode:

aide state set mode autopilot

How It Works

When autopilot mode is active:

  1. The persistence hook intercepts stop signals
  2. If incomplete tasks exist in the todo list, the agent is re-prompted to continue
  3. The agent keeps working through its task list
  4. Auto-releases when ALL tasks are complete (terminal state)
  5. Safety cap: releases after 20 iterations even if tasks remain

Platform Behavior

PlatformMechanism
Claude CodeStop-blocking — prevents the AI from ending the conversation early
OpenCodeRe-prompting — session.prompt() is called on idle to keep going

Task Tracking

Autopilot relies on the todo list to determine completeness:

  • Has incomplete tasks → Block stop, continue working
  • All tasks complete → Auto-release, allow stop
  • No tasks exist → Generic reinforcement (verify your work)

When to Use

Autopilot mode is ideal for:

  • Multi-step implementations — "autopilot implement the user dashboard"
  • Fixing all test failures — "autopilot fix all failing tests"
  • Complete refactors — "autopilot refactor all error handling to use Result types"
  • Migration tasks — "autopilot migrate all components to the new API"
  • Build fixes — "autopilot make the build pass"

When NOT to Use

Avoid autopilot for:

  • Exploratory tasks — "investigate why X happens" (no clear completion criteria)
  • Design work — Use the design skill instead (needs human input)
  • Tasks requiring human judgment — Autopilot continues based on automated checks
  • Parallel work — Use swarm mode instead for decomposed parallel stories

Combining with Skills

Autopilot works well with any skill:

autopilot fix the build errors       # autopilot + build-fix behavior
autopilot make all tests pass        # autopilot + implement behavior
autopilot debug why login fails      # autopilot + debug behavior

Deactivation

To stop autopilot mode early:

aide state set mode ""

Or type "stop" — the keyword detector clears the active mode.

Instructions

When autopilot mode is activated:

  1. Create a comprehensive todo list — Break the task into specific, actionable items
  2. Work through items sequentially — Mark each as in_progress then completed
  3. Verify each step — Run tests, check builds, confirm behavior
  4. Do not stop until all items are complete — The persistence hook will block premature stops
  5. If stuck on an item after 3 attempts, record a blocker memory and move to the next item:
    ./.aide/bin/aide memory add --category=blocker --tags=project:<name>,session:<id>,source:discovered "Blocked on <task>: <reason>"
    

Binary location: The aide binary is at .aide/bin/aide. If it's on your $PATH, you can use aide directly.

Build Fix Mode

Recommended model tier: balanced (sonnet) - this skill performs straightforward operations

Rapidly fix all build, type, and lint errors with minimal changes.

Prerequisites

Before starting, ensure you have:

  • Access to the project root directory
  • Build tools installed (npm, tsc, etc.)

Workflow

Step 1: Capture All Errors

Run all checks and capture output:

# Run in sequence, capture all output
npm run build 2>&1 | head -100
npm run lint 2>&1 | head -100
npx tsc --noEmit 2>&1 | head -100

If commands fail to run:

  • Check package.json for available scripts
  • Try npm install if dependencies are missing
  • Use npm ci for clean install if lock file exists

Step 2: Categorize Errors by Priority

Process errors in this order:

  1. Type errors (highest priority) - Fix TypeScript/type issues first
  2. Build errors - Compilation failures
  3. Lint errors - ESLint, Prettier, etc.
  4. Warnings - Address only if trivial

Group similar errors:

  • Missing imports
  • Type mismatches
  • Unused variables
  • Formatting issues

Step 3: Search for Context

Use MCP tools to find definitions and patterns:

# Find type definitions
mcp__plugin_aide_aide__code_search query="InterfaceName" kind="interface"

# Find function signatures
mcp__plugin_aide_aide__code_search query="functionName" kind="function"

# Get symbols in a file
mcp__plugin_aide_aide__code_symbols file="path/to/file.ts"

# Check project conventions
mcp__plugin_aide_aide__decision_get topic="coding-style"

Step 4: Apply Fixes Systematically

Fix in batches by category:

  1. All missing imports together - Add import statements
  2. All type annotations together - Add/fix type declarations
  3. All unused variables together - Remove or prefix with _

Step 5: Verify After Each Batch

# Run full verification
npm run build && npm run lint && npx tsc --noEmit

Verification criteria:

  • Exit code 0 for all commands
  • No error output
  • Warnings are acceptable if not introduced by changes

Step 6: Final Verification

# Run tests to ensure fixes didn't break functionality
npm test

Failure Handling

FailureAction
npm run build fails to startRun npm install first
Circular dependency errorCheck import structure, may need refactoring
Type error in third-party libCheck @types package version, update if needed
Cannot resolve moduleCheck tsconfig.json paths, baseUrl settings
ESLint config errorCheck .eslintrc, ensure plugins installed
Fix introduces new errorsRevert and try alternative approach

Rules

  • Minimal changes - Fix only what's broken
  • No refactoring - Don't improve "while you're there"
  • No new features - Just fix errors
  • Match style - Follow existing patterns exactly
  • One batch at a time - Verify between batches

Common Fixes Reference

ErrorFix
Cannot find moduleAdd import statement
Type 'X' not assignableAdd type annotation or use type assertion
'X' is declared but never usedRemove or prefix with _
Missing return typeAdd explicit return type
Unexpected anyAdd proper type annotation
Property does not existCheck interface, add property or fix typo
Argument of type X not assignableCheck function signature, cast if needed

MCP Tools

  • mcp__plugin_aide_aide__code_search - Find type definitions, function signatures
  • mcp__plugin_aide_aide__code_symbols - List all symbols in a file
  • mcp__plugin_aide_aide__decision_get - Check project coding decisions

Output Format

Report all fixes made:

## Build Fix Report

### Errors Fixed

- `src/foo.ts:10` - Added missing import for `Bar`
- `src/foo.ts:25` - Fixed type: `string` -> `string | null`
- `src/bar.ts:5` - Removed unused variable `temp`

### Verification

- Build: PASS
- Lint: PASS
- Types: PASS
- Tests: PASS

### Notes
[Any observations or remaining warnings]

Code Search

Recommended model tier: balanced (sonnet) - this skill performs straightforward operations

Locate definitions and caller candidates during debugging, review, and refactoring, then inspect the current source needed for the task. Choose tools by the evidence needed; there is no mandatory navigation step before reading a small file or a known relevant range.

Available Tools

1. Search Symbols (mcp__plugin_aide_aide__code_search)

Find functions, classes, methods, interfaces, and types by name or signature.

Example usage:

Search for: "getUserById"
→ Uses code_search tool
→ Returns: function signatures, file locations, line numbers

2. Find References (mcp__plugin_aide_aide__code_references)

Find indexed candidates where a symbol is called or used, including type references. Use these to investigate callers and change impact, then verify current source.

Example usage:

Who calls "getUserById"?
→ Uses code_references tool
→ Returns: indexed candidate call sites with file:line and context

3. List File Symbols (mcp__plugin_aide_aide__code_symbols)

List parsed definitions in a specific file, with signatures and locations. Use this for the file's API surface; coverage depends on grammar support.

Example usage:

What functions are in src/auth.ts?
→ Uses code_symbols tool
→ Returns: supported function, class, and type definitions in that file

4. File Outline (mcp__plugin_aide_aide__code_outline)

Get a collapsed structural outline of a file — signatures preserved, bodies replaced with { ... }. Use an outline to navigate an unfamiliar large file when its structure will help select what to read. Read known line ranges directly; read the full file when it is small or most of its contents are needed. When several symbol names are known, code_read_symbol supports a symbols batch (up to 10). Smaller returned text does not guarantee fewer whole-task tokens: an extra navigation round has overhead.

Example usage:

Outline src/auth.ts
→ Uses code_outline tool
→ Returns: collapsed view with signatures, line ranges, bodies collapsed

5. Read Symbol Source (mcp__plugin_aide_aide__code_read_symbol)

Read current bodies for known function, method, class, or type names. Batch up to 10 names in symbols when several bodies are needed, rather than issuing a call per name. Set file to choose an exact file, including one not yet indexed. If a name occurs multiple times in that file, also set start_line to the current definition line. Ambiguous names return candidates instead of choosing one.

{ "symbols": ["authenticateUser", "validateToken"], "file": "src/auth.ts" }

Use a bounded Read for imports or surrounding context outside the selected symbols. Read directly when the file is small or most of its contents are needed.

6. Check Index Status (mcp__plugin_aide_aide__code_stats)

Inspect index counts when diagnosing missing results or unavailable indexing. This is not a required preflight before each query or source read, and counts do not establish freshness or complete coverage.

Example usage:

Is the code indexed?
→ Uses code_stats tool
→ Returns: file count, symbol count, reference count

7. Search Findings (mcp__plugin_aide_aide__findings_search)

Search static analysis findings (complexity hotspots, secrets, code clones, coupling issues).

Example usage:

Any complexity issues in src/auth?
→ Uses findings_search tool with query "auth" or file filter
→ Returns: findings with file, line, severity, description

Workflow

  1. Choose the needed evidence: code_search for definition candidates; code_references for caller/type-use candidates; code_symbols or code_outline for structure in a known file. Filter by kind, language, or file when that narrows the question. Keep Grep for literals, imports, and patterns inside function bodies.
  2. Inspect current source: follow returned code_read_symbol selectors for missing source, retaining their checkout selector. Do not repeat search or outline discovery for a location already identified. Selectors are indexed candidates; if a definition moved, retry its file/name without start_line. Reuse bodies already available in the current context; reread for changes or missing context. Batch known names with code_read_symbol, using file to disambiguate. Read known ranges or small/full-relevant files directly.
  3. Verify conclusions: indexed search/reference results are best-effort candidates, not a complete semantic graph. Same-name symbols, dynamic calls, unsupported syntax, stale files, and limits can affect results. Verify relevant definitions and callers in current source; empty results do not prove absence.
  4. Investigate indexing only when needed: if results suggest indexing is missing or stale, inspect code_stats or run ./.aide/bin/aide code index. Continue with current-source reads or Grep when the index cannot answer.

Binary location: The aide binary is at .aide/bin/aide. If it's on your $PATH, you can use aide directly.

Example Session

User: "Where is the authentication function?"

Assistant action:

  1. Use code_search with query "auth" or "authenticate"
  2. Show matching functions with file locations

User: "Who calls authenticateUser?"

Assistant action:

  1. Use code_references with symbol "authenticateUser"
  2. Inspect relevant candidate callers in current source and group the findings by file

What These Tools Cover

code_search and code_references work from the tree-sitter symbol index. Depending on grammar support and index state, their results include:

  • Function, method, class, interface, type definitions by name
  • Symbol signatures (parameter types, return types)
  • Doc comments attached to definitions
  • Call sites for a specific symbol name (via code_references)

For anything else — patterns inside function bodies, method call chains, string literals, SQL queries, imports, variable declarations — use Grep, which searches code content directly.

Notes

  • Indexed searches need an index; exact-file code_read_symbol and on-demand file structure tools can inspect source without one
  • Indexing is incremental - only changed files are re-parsed
  • Supports: TypeScript, JavaScript, Go, Python, Rust, and more
  • File watching is on by default; disable with AIDE_CODE_WATCH=0 or code.watch: false in .aide/config/aide.json

Context Usage Analysis

Recommended model tier: balanced (sonnet) - straightforward SQL queries

Analyze the current session's context window consumption, tool usage breakdown, and token costs by querying the OpenCode SQLite database directly.

Prerequisites

  • This skill only works on OpenCode. Verify by checking the environment:
    • $OPENCODE=1 — set by the OpenCode runtime
    • $AIDE_PLATFORM=opencode — set by aide when running under OpenCode
    • $AIDE_SESSION_ID — the current session ID (injected by aide)
  • The OpenCode database is at ~/.local/share/opencode/opencode.db.
  • sqlite3 must be available on the system.

If $OPENCODE is not 1 or $AIDE_PLATFORM is not opencode, abort immediately and inform the user that this skill is only supported on OpenCode. Do not attempt to query other databases (e.g. Claude Code's storage) — the schema is OpenCode-specific.

If $AIDE_SESSION_ID is not set, abort with a message explaining that the session ID could not be determined.

Workflow

Run the following queries sequentially in a single Bash call (chain with &&). Present results to the user in a formatted summary after all queries complete.

Step 1: Validate environment

test "$OPENCODE" = "1" && echo "Platform: OpenCode" || echo "ERROR: Not running on OpenCode (OPENCODE=$OPENCODE)"
test "$AIDE_PLATFORM" = "opencode" && echo "AIDE Platform: opencode" || echo "WARNING: AIDE_PLATFORM=$AIDE_PLATFORM"
test -n "$AIDE_SESSION_ID" && echo "Session: $AIDE_SESSION_ID" || echo "ERROR: AIDE_SESSION_ID not set"

If OPENCODE is not 1, stop immediately — this skill cannot work outside OpenCode. If AIDE_SESSION_ID is not set, stop and inform the user.

Step 2: Session overview

sqlite3 ~/.local/share/opencode/opencode.db "
SELECT
  s.title,
  s.slug,
  ROUND((julianday('now') - julianday(datetime(s.time_created/1000, 'unixepoch'))) * 24, 1) as hours_old,
  (SELECT COUNT(*) FROM message m WHERE m.session_id = s.id) as messages,
  CASE WHEN s.time_compacting IS NOT NULL THEN 'yes' ELSE 'no' END as compacted
FROM session s
WHERE s.id = '$AIDE_SESSION_ID';
"

Step 3: Token totals

Sum tokens from step-finish parts (each represents one LLM turn):

sqlite3 ~/.local/share/opencode/opencode.db "
SELECT
  SUM(json_extract(data, '$.tokens.input')) as input_tokens,
  SUM(json_extract(data, '$.tokens.output')) as output_tokens,
  SUM(json_extract(data, '$.tokens.cache.read')) as cache_read_tokens,
  SUM(json_extract(data, '$.tokens.cache.write')) as cache_write_tokens,
  SUM(json_extract(data, '$.tokens.total')) as total_tokens,
  COUNT(*) as llm_turns
FROM part
WHERE session_id = '$AIDE_SESSION_ID'
  AND json_extract(data, '$.type') = 'step-finish';
"

Step 4: Tool output breakdown

Show tool usage ranked by total output size:

sqlite3 ~/.local/share/opencode/opencode.db "
SELECT
  json_extract(data, '$.tool') as tool,
  COUNT(*) as calls,
  SUM(length(json_extract(data, '$.state.output'))) as total_output_bytes,
  ROUND(AVG(length(json_extract(data, '$.state.output')))) as avg_bytes,
  MAX(length(json_extract(data, '$.state.output'))) as max_bytes
FROM part
WHERE session_id = '$AIDE_SESSION_ID'
  AND json_extract(data, '$.type') = 'tool'
GROUP BY tool
ORDER BY total_output_bytes DESC;
"

Step 5: Total session size

sqlite3 ~/.local/share/opencode/opencode.db "
SELECT
  SUM(length(json_extract(data, '$.state.output'))) as tool_output_bytes,
  SUM(length(json_extract(data, '$.state.input'))) as tool_input_bytes,
  SUM(length(data)) as total_part_bytes
FROM part
WHERE session_id = '$AIDE_SESSION_ID'
  AND json_extract(data, '$.type') = 'tool';
"

Output Format

Present the results as a structured summary:

## Session Context Usage

**Session:** <title> (<slug>)
**Age:** <hours> hours | **Messages:** <count> | **Compacted:** yes/no

### Token Usage
| Metric | Count |
|--------|-------|
| Input tokens | <n> |
| Output tokens | <n> |
| Cache read | <n> |
| Cache write | <n> |
| **Total tokens** | **<n>** |
| LLM turns | <n> |

### Tool Output Breakdown (by total bytes)
| Tool | Calls | Total Output | Avg/call | Max |
|------|-------|-------------|----------|-----|
| ... | ... | ... | ... | ... |

### Session Size
- Tool outputs: <n> KB
- Tool inputs: <n> KB
- Total part storage: <n> KB (includes JSON metadata overhead)

Format byte values as KB (divide by 1024, round to 1 decimal). Highlight the top 3 tools by total output as the biggest context consumers. If any single tool call exceeds 20KB, flag it as a potential optimization target.

Debug Mode

Recommended model tier: smart (opus) - this skill requires complex reasoning

Systematic approach to identifying and fixing bugs.

Prerequisites

Before starting:

  • Get the exact error message or unexpected behavior description
  • Identify the entry point or trigger for the bug
  • Note any relevant environment details (Node version, OS, etc.)

Workflow

Step 1: Reproduce the Issue

Goal: Confirm the bug exists and understand its behavior.

# Run the failing code/test
npm test -- --grep "failing test"
# OR
node path/to/script.js

Document:

  • Exact error message
  • Steps to trigger
  • Expected vs actual behavior
  • Is it consistent or intermittent?

If cannot reproduce:

  • Check environment differences
  • Look for race conditions
  • Check for cached state

Step 2: Locate the Relevant Code

Use tools to find code related to the error:

# Search for function mentioned in stack trace
mcp__plugin_aide_aide__code_search query="functionName" kind="function"

# Navigate an unfamiliar large suspect file when its structure is needed
mcp__plugin_aide_aide__code_outline file="path/to/file.ts"

# Get symbols in suspect file
mcp__plugin_aide_aide__code_symbols file="path/to/file.ts"

# Search for error message text in code
Grep for "error message text"

Step 3: Trace the Execution Path

Follow the code flow from entry to error:

  1. Read the failing function or known stack-trace ranges directly
  2. Use code_references to find callers of the failing function
  3. Read the relevant execution path; use code_outline when unfamiliar large-file structure would help locate the next section, or batch known symbols with code_read_symbol
  4. Check type definitions with code_search kind="interface"

Read the full file when it is small or most contents are needed. Extra navigation rounds can outweigh smaller responses; use outlines when they resolve missing context.

Step 4: Form Hypotheses

Based on the error type, consider these causes:

SymptomLikely Causes
"undefined is not a function"Variable is null/undefined, wrong import
"Cannot read property of undefined"Missing null check, async timing issue
"Type error"Type mismatch, wrong function signature
"Maximum call stack"Infinite recursion, circular reference
"Network error"Bad URL, CORS, timeout, server down
"State not updating"Mutation instead of new object, missing dependency

Step 5: Validate Hypotheses

Test each hypothesis systematically:

# Add temporary logging
console.log('DEBUG: variable =', JSON.stringify(variable));

# Check with debugger
node --inspect-brk script.js

# Run specific test
npm test -- --grep "test name"

Validation checklist:

  • Check variable values at key points
  • Verify assumptions about input data
  • Test edge cases (null, empty, boundary values)
  • Check async ordering

Step 6: Apply the Fix

Rules:

  • Change only what's necessary to fix the bug
  • Don't refactor unrelated code
  • Match existing code patterns

Common fixes:

  • Add null/undefined check
  • Fix type annotation
  • Correct async/await usage
  • Fix variable scope
  • Add missing initialization

Step 7: Verify the Fix

# Run the originally failing test/scenario
npm test -- --grep "failing test"

# Run related tests
npm test -- --grep "related feature"

# Run full test suite to check for regressions
npm test

Verification criteria:

  • Original issue no longer occurs
  • Related tests still pass
  • No new errors introduced

Failure Handling

SituationAction
Cannot reproduceCheck environment, add logging to narrow down
Multiple bugs intertwinedFix one at a time, verify after each
Fix causes new failuresRevert, analyze dependencies, try different approach
Root cause is in dependencyCheck for updates, file issue, implement workaround
Bug is in async codeAdd proper await, check Promise chains

When abandoning an approach: If you try a fix direction and abandon it (e.g., revert because it causes regressions), record it as an abandoned approach so future sessions don't repeat it:

./.aide/bin/aide memory add --category=abandoned \
  --tags=reason:<why>,approach:<what>,project:<name>,session:<id>,source:discovered \
  "ABANDONED: <what was tried>. REASON: <why>. ALTERNATIVE: <new direction>. CONTEXT: <details>"

MCP Tools

  • mcp__plugin_aide_aide__code_outline - Navigate unfamiliar large files when their structure is needed
  • mcp__plugin_aide_aide__code_search - Find functions, classes, types involved in the bug
  • mcp__plugin_aide_aide__code_symbols - List all symbols in a file
  • mcp__plugin_aide_aide__code_references - Find all callers of a function
  • mcp__plugin_aide_aide__memory_search - Check for related past issues

Output Format

## Debug Report: [Issue Title]

### Problem

[What was happening vs what should happen]

### Reproduction

[Steps to reproduce the issue]

### Root Cause

[Identified cause with file:line reference]
[Why the bug occurred]

### Fix Applied

[What was changed and why]

### Verification

- Original issue: FIXED
- Related tests: PASS
- Full suite: PASS

### Prevention

[Optional: How to prevent similar bugs]

Tips

  • Always get the full error message and stack trace first
  • Don't guess - trace the code path methodically
  • One fix at a time - don't bundle unrelated changes
  • Remove temporary logging before committing
  • Consider if the bug could occur elsewhere

Memory Hygiene

When storing memories from this skill (abandoned approaches, blockers), always:

  1. Include source: tag — Use source:discovered for things you found, source:inferred for deductions
  2. Include scope tags — Add project:<name>,session:<id> (get project name from git remote or directory; session ID from $AIDE_SESSION_ID or $CLAUDE_SESSION_ID)
  3. Verify codebase claims before storing — If a memory references a file, function, or path, confirm it exists first. See the memorise skill for the full verification workflow.
  4. Never use scope:global unless storing a user preference

Decision Mode

Recommended model tier: smart (opus) - this skill requires complex reasoning

Formal decision-making workflow for architectural and technical choices.

Purpose

When facing a significant technical decision, this workflow guides you through structured analysis to make an informed choice that will be recorded and respected by all future sessions and agents.

Workflow

Phase 1: IDENTIFY

Ask the user to clarify:

  • What decision needs to be made?
  • What is the context? (new system, migration, constraint?)
  • What are the requirements? (scale, team, timeline?)
  • Are there any hard constraints?

Example questions:

  • "What technical decision do you need to make?"
  • "What problem are you trying to solve?"
  • "Are there any constraints I should know about?"

Phase 2: EXPLORE

Research and propose options:

  • List 3-5 viable alternatives
  • Include the obvious choices AND less common ones
  • For each option, note what it's best suited for

Output format:

## Options

1. **[Option A]** - Brief description
   - Best for: [use case]

2. **[Option B]** - Brief description
   - Best for: [use case]

3. **[Option C]** - Brief description
   - Best for: [use case]

Phase 3: ANALYZE

For each option, evaluate:

  • Pros: What are the benefits?
  • Cons: What are the drawbacks?
  • Fit: How well does it match the requirements?

Output format:

## Analysis

| Option   | Pros         | Cons           | Fit                   |
| -------- | ------------ | -------------- | --------------------- |
| Option A | Fast, simple | Limited scale  | Good for MVP          |
| Option B | Scalable     | Complex setup  | Good for growth       |
| Option C | Flexible     | Learning curve | Good if team knows it |

Consider:

  • Complexity (implementation, maintenance)
  • Team familiarity
  • Scalability
  • Security implications
  • Cost (time, money, resources)
  • Reversibility (how hard to change later?)

Phase 4: RECOMMEND

Provide a clear recommendation with rationale:

## Recommendation

I recommend **[Option]** because:

1. [Primary reason tied to requirements]
2. [Secondary benefit]
3. [Risk mitigation]

This choice [addresses constraint X] while [enabling future Y].

Ask for confirmation:

  • "Does this recommendation align with your goals?"
  • "Would you like to proceed with this decision?"
  • "Any concerns before we record this?"

Phase 5: CONFIRM

Wait for explicit user approval before recording:

  • User says "yes", "go ahead", "let's do it" → proceed to record
  • User has concerns → address them, refine recommendation
  • User wants different option → adjust and confirm

Phase 6: RECORD

Store the decision using the ./.aide/bin/aide decision set CLI command via Bash:

./.aide/bin/aide decision set "<topic-slug>" "<decision summary>" \
  --rationale="<why this was chosen>" --by="<git-username>"

Applicability is optional. Leave it blank by default for user-created decisions. Blank adds no restriction and needs no label or classification question. Respect any boundaries in the decision's wording. When the agreed decision explicitly applies to only part of the work, record that boundary as freeform text or structured selectors:

./.aide/bin/aide decision set customer-web-rendering "Use server-side rendering." \
  --context='{"applicability":"Only the customer-facing web app; exclude the admin app."}'
./.aide/bin/aide decision set billing-errors "Wrap errors with operation context." \
  --context='{"applicability":{"kind":"context","any_of":[{"language":"go","paths":["services/billing/**"]}]}}'

All decisions remain visible. Text, labels and repository-relative path patterns are guidance for the agent, not automatic file filters. Each any_of entry is an alternative; fields within an entry apply together, every listed tool is required, and paths within an entry are alternatives. Use forward slashes for paths on every platform.

On edits, omit --context to preserve existing applicability and supersession. If changing it, inspect the current decision first: --context replaces both fields, and --context='{}' clears both. Specificity alone does not override another topic; record an agreed exception with explicit, nonblank applicability and a supersedes list naming the overridden topics. Updating the same topic still appends a new revision.

Attribution (--by): use the git username — the GitHub handle, as in the remote URL — not a display name. Never guess a person's identifier: if you do not know it, omit --by rather than inventing one. The store is append-only, so a wrong byline cannot be edited, only superseded by a new version whose sole change is the name.

Binary location: The aide binary is at .aide/bin/aide. If it's on your $PATH, you can use aide directly.

Topic naming:

  • Use kebab-case: auth-strategy, database-choice, api-design
  • Be specific: user-auth-method not just auth
  • Include scope if relevant: payments-queue-strategy

Verify the decision was stored:

./.aide/bin/aide decision get "<topic-slug>"

Example Session

User: help me decide how to handle background jobs

Claude: [IDENTIFY]
What kind of background jobs do you need to handle?
- Scheduled tasks (cron-like)?
- Async processing (triggered by events)?
- Long-running workers?

What's your current stack and scale expectations?

User: Async processing for email sending and webhook deliveries.
Stack is Node.js/TypeScript, expecting 10K jobs/day initially.

Claude: [EXPLORE]
## Options

1. **BullMQ (Redis)** - Production-ready Node.js queue
   - Best for: Node.js apps needing reliability + Redis features

2. **AWS SQS + Lambda** - Serverless queue
   - Best for: AWS-native apps, variable load

3. **Database-backed queue** - Simple polling
   - Best for: Low volume, no new infrastructure

4. **RabbitMQ** - Enterprise message broker
   - Best for: Complex routing, multi-language

[ANALYZE]
| Option | Pros | Cons | Fit |
|--------|------|------|-----|
| BullMQ | Native TS, retries, dashboard | Needs Redis | Excellent |
| SQS+Lambda | Serverless, scales | Cold starts, AWS lock-in | Good |
| DB queue | Simple, no new infra | Polling overhead, scale limits | MVP only |
| RabbitMQ | Powerful routing | Overkill, operational burden | Over-engineered |

[RECOMMEND]
I recommend **BullMQ with Redis** because:
1. Native TypeScript support matches your stack
2. Built-in retries, delays, and rate limiting for email/webhooks
3. Bull Board provides visibility without custom tooling
4. 10K/day is well within comfortable range, scales to millions

Redis adds infrastructure but enables other features (caching, sessions).

Do you want to proceed with this decision?

User: yes, let's go with BullMQ

Claude: [RECORD]
[Calls ./.aide/bin/aide decision set via Bash]

```bash
./.aide/bin/aide decision set "background-jobs-queue" "Use BullMQ with Redis for background job processing (emails, webhooks)" --rationale="Native TypeScript support, built-in retries/delays/rate-limiting, Bull Board for visibility, 10K/day well within capacity. Rejected: SQS+Lambda (AWS lock-in, cold starts), DB queue (limited scale), RabbitMQ (over-engineered)"

Decision recorded. Future sessions will follow this architectural choice.


## Integration

Decisions stored via `./.aide/bin/aide decision set` are:
1. Persisted in the aide memory database
2. Injected into future session contexts at startup
3. Visible to swarm agents (they won't contradict decisions)
4. Queryable via `./.aide/bin/aide decision get`, `./.aide/bin/aide decision list`, or the MCP tools `decision_get`/`decision_list`

## When to Use This Skill

**Good candidates for formal decisions:**
- Authentication/authorization strategy
- Database technology choice
- API design patterns
- State management approach
- Testing strategy
- Deployment architecture
- Third-party service selection

**NOT needed for:**
- Minor implementation details
- Obvious choices with no trade-offs
- Temporary/experimental code
- Personal preferences (use memories instead)

## Changing Decisions

Decisions can be superseded:
1. Run `/aide:decide` again for the same topic
2. New decision replaces old (history preserved)
3. Use `mcp__plugin_aide_aide__decision_history` to see evolution

Design Mode

Recommended model tier: smart (opus) - this skill requires complex reasoning

Output a technical design specification that downstream SDLC stages can consume.

Purpose

Create a structured design document that defines:

  1. What to build (interfaces, types, components)
  2. How it fits together (data flow, interactions)
  3. Why key decisions were made (rationale)
  4. Success criteria (acceptance criteria for TEST stage)

Workflow

Step 1: Understand the Request

Read the request and identify:

  • Core functionality required
  • Constraints (tech stack, patterns, performance)
  • Integration points with existing code

Step 2: Explore the Codebase

Use search tools to understand existing patterns:

  • Use Grep for similar patterns, interfaces, types
  • Use Glob for relevant files
  • Use mcp__plugin_aide_aide__decision_list to review all decisions
  • Use mcp__plugin_aide_aide__decision_get with the relevant topic to check specific decisions

Step 3: Define Interfaces

Define the public API/interfaces first:

// Example TypeScript interface
interface UserService {
  createUser(data: CreateUserInput): Promise<User>;
  getUser(id: string): Promise<User | null>;
  updateUser(id: string, data: UpdateUserInput): Promise<User>;
}

interface CreateUserInput {
  email: string;
  name: string;
}
// Example Go interface
type UserService interface {
    CreateUser(ctx context.Context, input CreateUserInput) (*User, error)
    GetUser(ctx context.Context, id string) (*User, error)
    UpdateUser(ctx context.Context, id string, input UpdateUserInput) (*User, error)
}

Step 4: Document Data Flow

Describe how components interact:

Request → Controller → Service → Repository → Database
                ↓
           Validator
                ↓
          Error Handler → Response

Step 5: Record Key Decisions

Store architectural decisions for future reference:

./.aide/bin/aide decision set "<feature>-storage" "PostgreSQL with JSONB for metadata" \
  --rationale="Need flexible schema for user preferences" --by="<git-username>"

./.aide/bin/aide decision set "<feature>-auth" "JWT with refresh tokens" \
  --rationale="Stateless auth, mobile client support" --by="<git-username>"

Attribution (--by): use the git username — the GitHub handle, as in the remote URL — not a display name. Never guess a person's identifier: if you do not know it, omit --by rather than inventing one. The store is append-only, so a wrong byline cannot be edited, only superseded by a new version whose sole change is the name.

Binary location: The aide binary is at .aide/bin/aide. If it's on your $PATH, you can use aide directly.

Step 6: Define Acceptance Criteria

List specific, testable criteria for the TEST stage:

## Acceptance Criteria

- [ ] User can be created with email and name
- [ ] Duplicate emails are rejected with 409 status
- [ ] Created user has UUID identifier
- [ ] User can be retrieved by ID
- [ ] Non-existent user returns null (not error)
- [ ] User email can be updated
- [ ] User name can be updated

Required Output Format

# Design: [Feature Name]

## Overview

[1-2 sentence summary of what this feature does]

## Interfaces

### [Interface/Type Name]

\`\`\`typescript
// Interface definition with comments
\`\`\`

## Data Flow

[Diagram or description of component interactions]

## Key Decisions

| Decision | Choice     | Rationale |
| -------- | ---------- | --------- |
| Storage  | PostgreSQL | [why]     |
| Auth     | JWT        | [why]     |

## Acceptance Criteria

- [ ] Criterion 1
- [ ] Criterion 2
- [ ] Criterion 3

## Files to Create/Modify

- `path/to/file.ts` - [purpose]
- `path/to/test.ts` - [test scope]

## Dependencies

- [External packages needed]
- [Internal modules to import]

## Out of Scope

- [Explicitly excluded items]

Failure Handling

Unclear Requirements

  1. List specific ambiguities
  2. State assumptions you're making
  3. Record assumptions: ./.aide/bin/aide memory add --category=decision --tags=project:<name>,session:${AIDE_SESSION_ID},source:inferred "Assumed X because Y"
  4. Proceed with reasonable defaults

Conflicting Patterns Found

  1. Document the conflicting patterns
  2. Choose one and record the decision:
    ./.aide/bin/aide decision set "<topic>" "<choice>" --rationale="<why this over alternatives>"
    

Too Large / Too Vague

  1. Break into smaller, focused designs
  2. Design the core/MVP first
  3. Note future phases in "Out of Scope"

Verification Checklist

Before completing design:

  • Interfaces are defined with types
  • Data flow is documented
  • Key decisions are recorded in aide
  • Acceptance criteria are testable
  • Files to modify are listed
  • Dependencies are identified

Memory Hygiene

When storing memories from this skill (assumptions, decisions, discoveries), always:

  1. Include source: tag — Use source:inferred for assumptions, source:discovered for findings during exploration
  2. Include scope tags — Add project:<name>,session:<id> (get project name from git remote or directory; session ID from $AIDE_SESSION_ID or $CLAUDE_SESSION_ID)
  3. Verify codebase claims before storing — If a memory references a file, function, or path, confirm it exists first. See the memorise skill for the full verification workflow.
  4. Never use scope:global unless storing a user preference

Completion

When design is complete:

  1. Output the full design document
  2. Confirm: "Design complete. Ready for TEST stage."

The design document feeds directly into the TEST stage, where acceptance criteria become test cases.

Documentation Mode

Recommended model tier: balanced (sonnet) - this skill performs straightforward operations

Update documentation to accurately reflect the implemented code.

Purpose

This is the DOCS stage of the SDLC pipeline. Implementation is complete and verified. Your job is to ensure documentation matches reality.

What to Document

1. README Updates

If the feature affects how users interact with the project:

  • Installation steps changed?
  • New commands or options?
  • New configuration?
  • New dependencies?

2. API Documentation

If public APIs were added or changed:

  • Function/method signatures
  • Parameters and return types
  • Usage examples
  • Error conditions

3. Inline Documentation

If code needs explanation:

  • Complex algorithms
  • Non-obvious design decisions
  • Integration points
  • Edge cases

4. Architecture Docs

If structure changed:

  • New components
  • Changed data flow
  • New dependencies between modules

Workflow

Step 1: Identify Changed Files

# See what was changed
git diff --name-only HEAD~5  # or appropriate range

# Find related docs
Glob for **/*.md
Glob for **/docs/**/*

Step 2: Check Existing Documentation

Read current docs that might be affected:

Read README.md
Read docs/api.md  # if exists
Read CHANGELOG.md  # if exists

Step 3: Read the Implementation

Understand what was built:

  • Read the new code files
  • Use mcp__plugin_aide_aide__decision_get with the feature topic to check design decisions
  • Use mcp__plugin_aide_aide__decision_list to see all decisions

Step 4: Update Documentation

README.md Updates

Add/update sections as needed:

## New Feature

Description of what it does.

### Usage

\`\`\`bash
command --new-flag
\`\`\`

### Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| newOption | string | "default" | What it does |
API Documentation

Document public interfaces:

### functionName(param1, param2)

Brief description.

**Parameters:**
- `param1` (string): What it is
- `param2` (number, optional): What it does. Default: 10

**Returns:** `Promise<Result>`

**Example:**
\`\`\`typescript
const result = await functionName("input", 20);
\`\`\`

**Throws:**
- `ValidationError`: When param1 is empty
Inline Comments

Add comments for non-obvious code:

// Use exponential backoff to handle rate limiting
// Starts at 100ms, doubles each retry, max 5 retries
async function fetchWithRetry(url: string): Promise<Response> {
  // ...
}

Step 5: Verify Documentation

# If docs have a build step
npm run docs:build

# Check for broken links (if tool available)
npm run docs:check

# Manual review - read what you wrote

Step 6: Commit Documentation

git add -A
git commit -m "docs: document <feature>"

Documentation Standards

Be Accurate

  • Documentation must match code exactly
  • If code changes, docs must change
  • Never document aspirational features

Be Concise

  • One sentence per concept
  • Use examples over explanations
  • Bullet points over paragraphs

Be Complete

  • Cover happy path AND error cases
  • Include all public API
  • Document breaking changes

Be Findable

  • Use clear headings
  • Add to table of contents
  • Cross-reference related sections

What NOT to Document

  • Internal implementation details (unless complex)
  • Obvious code (self-documenting)
  • Temporary workarounds (use TODO instead)
  • Aspirational features (only document what exists)

Output Format

## Documentation Updates

### Files Modified
- `README.md` - Added new feature section
- `docs/api.md` - Documented new endpoints
- `src/service.ts` - Added inline comments for complex logic

### Summary of Changes
1. Added usage instructions for `--new-flag`
2. Documented `createUser` API with examples
3. Updated configuration table with new options

### Verification
- [ ] Docs build successfully
- [ ] Examples are copy-pasteable and work
- [ ] No broken internal links

Failure Handling

No Documentation Exists

If this is a new project without docs structure:

  1. Create minimal README.md
  2. Document the feature inline
  3. Note: "Recommend creating docs/ structure in future"

Documentation Tool Broken

If docs build fails:

  1. Fix the build issue if simple
  2. Document what was attempted
  3. Note: "Docs build issue - needs separate fix"

Unclear What to Document

  1. Focus on public API only
  2. Document what a new user would need
  3. Skip internal details
  4. When in doubt, add an example

Verification Checklist

Before completing:

  • All new public APIs are documented
  • README is updated if user-facing changes
  • Examples are tested and work
  • Docs build (if applicable)
  • Changes are committed

Completion

When documentation is complete:

Documentation complete.
- Updated: [list of files]
- Added: [new sections/files]

SDLC pipeline complete for this story.

Integration with SDLC Pipeline

[DESIGN] → [TEST] → [DEV] → [VERIFY] → [DOCS]
                                          ↑
                                     YOU ARE HERE
  • Input: Verified, working implementation
  • Output: Updated documentation
  • Next: Story complete, ready for merge

Forget

Recommended model tier: balanced (sonnet) - this skill performs straightforward operations

Manage outdated, incorrect, or obsolete memories by soft-deleting (tagging with forget) or hard-deleting them.

Key Concepts

Soft Delete (Preferred)

Memories tagged with forget are excluded by default from search, list, and context injection. They remain in the database and can be recovered.

./.aide/bin/aide memory tag <MEMORY_ID> --add=forget

Hard Delete (Permanent)

Permanently removes a memory from the database. Use when the memory is clearly wrong or contains sensitive data.

./.aide/bin/aide memory delete <MEMORY_ID>

Unforget (Recover)

Remove the forget tag to restore a soft-deleted memory.

./.aide/bin/aide memory tag <MEMORY_ID> --remove=forget

Workflow

When the user wants to forget, correct, or supersede a memory:

Step 1: Find the Memory

Search for the memory to identify its ID:

# Search by content keywords
./.aide/bin/aide memory search "<keywords>" --full --limit=10

# If the memory might already be forgotten, include all
./.aide/bin/aide memory list --all

Step 2: Confirm with User

Before deleting or forgetting, show the user what was found and confirm which memories to act on. Display the memory ID, content, and tags.

Step 3: Apply the Appropriate Action

Choose based on the situation:

SituationActionCommand
Memory is outdated but was once trueSoft delete (forget)aide memory tag <ID> --add=forget
Memory is factually wrongHard deleteaide memory delete <ID>
Memory is resolved (issue fixed)Soft delete + optionally add resolutionSee "Superseding" below
Memory contains sensitive dataHard deleteaide memory delete <ID>
Memory was accidentally forgottenUnforgetaide memory tag <ID> --remove=forget

Step 4: Optionally Add a Replacement

If the memory is being superseded (not just deleted), add a new corrected memory without the forget tag:

# 1. Forget the old memory
./.aide/bin/aide memory tag <OLD_ID> --add=forget

# 2. Add the corrected memory (NO forget tag) — include scope + provenance tags
./.aide/bin/aide memory add --category=<category> --tags=<relevant,tags>,project:<name>,session:${AIDE_SESSION_ID},source:discovered "<corrected content>"

Step 5: Verify

Confirm the memory is no longer visible in normal searches:

# Should NOT appear in normal search
./.aide/bin/aide memory search "<keywords>"

# Should appear with --all flag
./.aide/bin/aide memory list --all

Anti-Patterns (AVOID)

DO NOT add a new memory with the forget tag to "supersede" an old one

This is the most common mistake. Adding a new memory tagged forget does nothing useful:

  • The new "superseding" memory is immediately hidden (because it has the forget tag)
  • The original incorrect memory remains visible and active

Wrong:

# BAD - creates a hidden memory, leaves the original untouched
aide memory add --tags="forget,some-topic" "RESOLVED: the old issue is fixed"

Correct:

# GOOD - forget the original, add a visible replacement
aide memory tag <ORIGINAL_ID> --add=forget
aide memory add --tags="some-topic" "RESOLVED: the old issue is fixed"

DO NOT guess memory IDs

Always search first to find the exact memory ID. Memory IDs are ULIDs (e.g., 01KJ3X7GMQET613WMPT7JT8GYD).

DO NOT forget memories without user confirmation

Always show the user what will be affected and get confirmation before acting, especially for hard deletes.

Batch Operations

To forget multiple related memories:

# Search for all related memories
./.aide/bin/aide memory search "<topic>" --full --limit=50

# Forget each one (after user confirmation)
./.aide/bin/aide memory tag <ID1> --add=forget
./.aide/bin/aide memory tag <ID2> --add=forget

To clear ALL memories (destructive, requires explicit user request):

./.aide/bin/aide memory clear

Examples

User says "that thing about ESM imports is wrong"

# 1. Find the memory
./.aide/bin/aide memory search "ESM imports" --full

# 2. Show user and confirm
# "Found memory 01KJ... about ESM imports requiring .js extensions. Delete this?"

# 3. Soft delete
./.aide/bin/aide memory tag 01KJ3XVFXBFTKKH1M500N6R5 --add=forget

User says "we changed from JWT to sessions, update the memory"

# 1. Find the old memory
./.aide/bin/aide memory search "JWT auth" --full

# 2. Forget the old one
./.aide/bin/aide memory tag <OLD_ID> --add=forget

# 3. Add the corrected one
./.aide/bin/aide memory add --category=decision --tags=auth,sessions,project:myapp,session:${AIDE_SESSION_ID},source:discovered "Auth strategy changed from JWT to server-side sessions with Redis store"

User says "recover that forgotten memory about testing"

# 1. Find forgotten memories
./.aide/bin/aide memory list --all

# 2. Unforget it
./.aide/bin/aide memory tag <ID> --remove=forget

Failure Handling

If aide memory tag fails:

  1. "memory not found" - The ID may be wrong. Re-search with --all flag to include forgotten memories.
  2. Panic/crash - If the tag command panics, fall back to delete + re-add:
    # Workaround: get memory content, delete, re-add with forget tag
    ./.aide/bin/aide memory list --all  # Find the memory content
    ./.aide/bin/aide memory delete <ID>
    ./.aide/bin/aide memory add --category=<cat> --tags=<existing-tags>,forget "<content>"
    
  3. Database locked - Another process may hold the lock. Wait and retry, or ensure the aide daemon is running (CLI routes through gRPC when daemon is active).

Memory Hygiene

When adding replacement memories (Step 4 above), always:

  1. Include source: tag — Use source:discovered for corrected facts, source:user if the user provided the correction
  2. Include scope tags — Add project:<name>,session:<id> (get project name from git remote or directory; session ID from $AIDE_SESSION_ID or $CLAUDE_SESSION_ID)
  3. Verify codebase claims before storing — If a replacement memory references a file, function, or path, confirm it exists first. See the memorise skill for the full verification workflow.
  4. Never use scope:global unless storing a user preference

Verification

After forgetting a memory, verify:

# Memory should NOT appear here
./.aide/bin/aide memory search "<term>"

# Memory SHOULD appear here (with forget tag)
./.aide/bin/aide memory list --all

Git Mode

Recommended model tier: balanced (sonnet) - this skill performs straightforward operations

Expert git operations including worktree management for parallel work.

Commit Guidelines

Message Format

<type>: <short description>

[optional body]

Types: feat, fix, refactor, docs, test, chore

Commit Process

  1. Check status: git status
  2. Review diff: git diff
  3. Stage specific files (not git add .)
  4. Write descriptive message
  5. Never skip hooks unless explicitly asked

Worktree Management

Create Worktree

# For feature work
git worktree add ../feature-branch -b feature/name

# For parallel tasks
git worktree add ../aide-worktrees/task-1 -b aide/task-1

List Worktrees

git worktree list

Remove Worktree

git worktree remove ../feature-branch
git branch -d feature/name  # if merged

Common Operations

Feature Branch Workflow

git checkout -b feature/name
# ... work ...
git add <specific-files>
git commit -m "feat: add feature"
git push -u origin feature/name

Rebase onto Main

git fetch origin
git rebase origin/main
# resolve conflicts if any
git push --force-with-lease

Cherry-Pick

git cherry-pick <commit-hash>

Stash

git stash push -m "description"
git stash list
git stash pop

Safety Rules

Never run without explicit user request:

  • git push --force (use --force-with-lease if needed)
  • git reset --hard
  • git clean -f
  • git checkout . or git restore .

Safe operations:

  • git status, git diff, git log
  • git add <specific-files>
  • git commit
  • git push (without force)
  • git worktree operations

Failure Handling

Commit failures:

  1. Pre-commit hook failure - Read the error, fix the issue, create NEW commit (never amend after hook failure)
  2. Merge conflict - Report conflicts, do not auto-resolve without explicit request
  3. Push rejected - Fetch and rebase, report if conflicts arise

Worktree failures:

  1. Branch already exists - Use different name or checkout existing
  2. Dirty working tree - Stash or commit before worktree operations
  3. Locked worktree - Check git worktree list for stale entries, use git worktree prune

Recovery commands:

# Recover from bad merge (before commit)
git merge --abort

# Recover from bad rebase (before complete)
git rebase --abort

# Prune stale worktrees
git worktree prune

Verification Criteria

After commit:

# Verify commit was created
git log -1 --oneline

# Verify expected files changed
git show --stat HEAD

After push:

# Verify remote updated
git log origin/<branch> -1 --oneline

After worktree creation:

# Verify worktree exists
git worktree list | grep <worktree-path>

# Verify branch created
git branch -a | grep <branch-name>

Change Context with Findings

When reviewing diffs or preparing commits, use findings tools to understand the quality context of changed code:

  • mcp__plugin_aide_aide__findings_search — Search for known issues (complexity, secrets, clones) in changed files
  • mcp__plugin_aide_aide__findings_list — List all findings for a specific file to understand its health
  • mcp__plugin_aide_aide__findings_stats — Quick overview of finding counts across the project

This helps surface pre-existing issues in files you're touching, and can inform whether a commit should also address nearby problems.

Parallel Work Pattern

For swarm mode or parallel features:

# Setup
git worktree add ../work-1 -b feature/part-1
git worktree add ../work-2 -b feature/part-2

# Work in parallel (different terminals/agents)
cd ../work-1 && # ... implement part 1
cd ../work-2 && # ... implement part 2

# Merge
git checkout main
git merge feature/part-1
git merge feature/part-2

# Cleanup
git worktree remove ../work-1
git worktree remove ../work-2
git branch -d feature/part-1 feature/part-2

Implement Mode

Recommended model tier: smart (opus) - this skill requires complex reasoning

Focused TDD implementation: make failing tests pass with minimal code.

Purpose

This is the DEV stage of the SDLC pipeline. Tests already exist from the TEST stage. Your job is to write the minimal implementation that makes them pass.

Prerequisites

Before starting:

  • Tests exist and are failing (from TEST stage)
  • Design/spec is available (from DESIGN stage)
  • You know which files to create/modify

Workflow

Step 1: Verify Tests Exist and Fail

# Run the tests - they MUST fail initially
npm test -- path/to/feature.test.ts
# or
go test ./pkg/feature/...

If tests pass: The work is already done. Mark complete and move on.

If tests don't exist: This is wrong - go back to TEST stage.

Step 2: Read the Tests

Understand what the tests expect:

  • What functions/methods need to exist?
  • What are the expected inputs and outputs?
  • What edge cases are covered?
# If a large test file is unfamiliar, an outline can help locate relevant tests
mcp__plugin_aide_aide__code_outline file="path/to/feature.test.ts"

# Read relevant test sections directly when their ranges are known
Read path/to/feature.test.ts offset=<start> limit=<count>

# Read the full file when it is small or most tests are relevant
Read path/to/feature.test.ts

For related source, read known ranges or symbols directly. Use code_outline when unfamiliar large-file structure would help select relevant code; read the full file when most contents are needed. Batch known symbols with code_read_symbol (symbols, up to 10) when useful. Extra retrieval rounds can outweigh smaller responses, so an outline is not a prerequisite to reading or editing.

Step 3: Check Design Decisions

Use mcp__plugin_aide_aide__decision_get with the feature topic to review decisions from DESIGN stage. Use mcp__plugin_aide_aide__decision_list to see all project decisions.

Step 4: Implement Incrementally

Write code to make tests pass one at a time:

  1. Pick the simplest failing test
  2. Write minimal code to pass it
  3. Run tests
  4. If passing, move to next test
  5. If failing, fix before proceeding
# Run specific test
npm test -- --grep "should create user"
# or
go test -run TestCreateUser ./pkg/...

Step 5: Backpressure Checkpoint (REQUIRED)

You CANNOT proceed until ALL tests pass.

# Full test run
npm test -- path/to/feature.test.ts
# or
go test -v ./pkg/feature/...

BLOCKING RULE: If any test fails:

  1. Analyze the failure
  2. Fix the issue
  3. Re-run tests
  4. Repeat until ALL pass

DO NOT skip failing tests. DO NOT proceed with red tests.

Step 6: Verify Build

# Ensure it compiles
npm run build
# or
go build ./...

Step 7: Commit

git add -A
git commit -m "feat: implement <feature> - tests passing"

Rules

  1. Tests First: Never write code without a failing test
  2. Minimal Code: Only write what's needed to pass tests
  3. No Gold Plating: Don't add features not covered by tests
  4. Red → Green: Tests must fail before they pass
  5. Atomic Commits: One logical change per commit
  6. No Skipping: Every test must pass

Common Patterns

TypeScript/JavaScript

// Read test expectations
describe("UserService", () => {
  it("should create user with email and name", async () => {
    const user = await service.createUser({
      email: "test@example.com",
      name: "Test",
    });
    expect(user.id).toBeDefined();
    expect(user.email).toBe("test@example.com");
  });
});

// Implement to match
export class UserService {
  async createUser(input: CreateUserInput): Promise<User> {
    return {
      id: crypto.randomUUID(),
      email: input.email,
      name: input.name,
      createdAt: new Date(),
    };
  }
}

Go

// Read test expectations
func TestCreateUser(t *testing.T) {
    svc := NewUserService()
    user, err := svc.CreateUser(context.Background(), CreateUserInput{
        Email: "test@example.com",
        Name:  "Test",
    })
    require.NoError(t, err)
    assert.NotEmpty(t, user.ID)
    assert.Equal(t, "test@example.com", user.Email)
}

// Implement to match
func (s *UserService) CreateUser(ctx context.Context, input CreateUserInput) (*User, error) {
    return &User{
        ID:        uuid.New().String(),
        Email:     input.Email,
        Name:      input.Name,
        CreatedAt: time.Now(),
    }, nil
}

Failure Handling

Test Won't Pass After Multiple Attempts

  1. Re-read the test - is the expectation correct?
  2. Check if test has a bug (it happens)
  3. Check design decisions - is implementation matching spec?
  4. Record blocker:
    ./.aide/bin/aide memory add --category=blocker --tags=project:<name>,session:<id>,source:discovered "Cannot pass test X: <reason>"
    
  5. If you abandon the approach, record it so future sessions don't repeat it:
    ./.aide/bin/aide memory add --category=abandoned \
      --tags=reason:<why>,approach:<what>,project:<name>,session:<id>,source:discovered \
      "ABANDONED: <what was tried>. REASON: <why>. ALTERNATIVE: <new direction>. CONTEXT: <details>"
    
  6. If stuck after 3 attempts, ask for help

Build Fails

  1. Read error message carefully
  2. Check for missing imports
  3. Check for type mismatches
  4. Fix and re-run build
  5. Then re-run tests

Test Passes But Implementation Feels Wrong

  1. If tests pass, the contract is met
  2. Don't refactor during implement stage
  3. Note concerns for future:
    ./.aide/bin/aide memory add --category=issue --tags=project:<name>,session:<id>,source:discovered "Implementation of X could be improved: <how>"
    
  4. Proceed - refactoring is a separate concern

Binary location: The aide binary is at .aide/bin/aide. If it's on your $PATH, you can use aide directly.

Verification Checklist

Before completing:

  • All tests pass (not just some)
  • Build succeeds
  • Changes are committed
  • No debug code left (console.log, fmt.Println for debugging)

Completion

When all tests pass:

# Final verification
npm test -- path/to/feature.test.ts && npm run build

# Or Go
go test -v ./pkg/feature/... && go build ./...

Output: "Implementation complete. All tests passing. Ready for VERIFY stage."

Memory Hygiene

When storing memories from this skill (blockers, issues, abandoned approaches), always:

  1. Include source: tag — Use source:discovered for things you found, source:inferred for deductions
  2. Include scope tags — Add project:<name>,session:<id> (get project name from git remote or directory; session ID from $AIDE_SESSION_ID or $CLAUDE_SESSION_ID)
  3. Verify codebase claims before storing — If a memory references a file, function, or path, confirm it exists first. See the memorise skill for the full verification workflow.
  4. Never use scope:global unless storing a user preference

Integration with SDLC Pipeline

This skill is designed for the DEV stage:

[DESIGN] → [TEST] → [DEV/IMPLEMENT] → [VERIFY] → [DOCS]
                         ↑
                    YOU ARE HERE
  • Input: Failing tests from TEST stage
  • Output: Passing tests, working implementation
  • Next: VERIFY stage runs full validation

Memorise

Recommended model tier: balanced (sonnet) - this skill performs straightforward operations

Capture important information for future sessions by storing it in the aide memory database.

How to Store

Use the ./.aide/bin/aide memory add CLI command via Bash:

./.aide/bin/aide memory add --category=<category> --tags=<comma,separated,tags> "<content>"

Binary location: The aide binary is at .aide/bin/aide. If it's on your $PATH, you can use aide directly.

Categories

  • learning - Something discovered about the codebase or tools
  • decision - An architectural or design choice made
  • session - Summary of a work session
  • pattern - A reusable approach or pattern identified
  • gotcha - A pitfall or issue to avoid in future
  • abandoned - An approach that was tried and abandoned (see Abandoned Approaches below)

When to Use

  • End of a significant task or session
  • After discovering something important about the codebase
  • When a decision is made that should persist
  • After solving a tricky problem (capture the solution)
  • When user shares a preference or important information

Examples

Simple preference (global - injected at session start)

./.aide/bin/aide memory add --category=learning --tags=preferences,colour,scope:global,source:user "User's favourite colour is blue"

Technical learning (project-specific, verified)

./.aide/bin/aide memory add --category=learning --tags=testing,vitest,project:myapp,session:abc12345,source:discovered,verified:true "Vitest requires .js extensions for ESM imports even for .ts files. Configure moduleResolution: NodeNext in tsconfig."

Session summary

./.aide/bin/aide memory add --category=session --tags=auth,api,project:myapp,session:abc12345,source:discovered "Implemented JWT auth with 15min access tokens, 7day refresh tokens in httpOnly cookies. Files: src/auth/jwt.ts, src/middleware/auth.ts, src/routes/auth.ts"

Gotcha (global - applies everywhere)

./.aide/bin/aide memory add --category=gotcha --tags=hooks,claude-code,scope:global,source:discovered,verified:true "Hooks must not write to stderr - Claude Code interprets any stderr as error. Debug logging must go to files only."

Unverified external claim

./.aide/bin/aide memory add --category=learning --tags=api,stripe,project:myapp,source:user,verified:false "Stripe webhook signatures use HMAC-SHA256 with the whsec_ prefix."

Instructions

When the user invokes /aide:memorise <something>:

  1. Parse what they want to remember
  2. Verify factual claims before storing (see Verification Before Storage below)
  3. Determine the scope:
    • User preference (colour, style, etc.) → add scope:global
    • Project-specific learning → add project:<project-name>,session:${AIDE_SESSION_ID}
    • Session summary → add project:<project-name>,session:${AIDE_SESSION_ID}
  4. Choose appropriate category and descriptive tags
  5. Add provenance tags (see Provenance Tags below)
  6. Format the content concisely but completely
  7. Call ./.aide/bin/aide memory add via Bash to store it
  8. Verify success - check exit code is 0 and output contains the memory ID
  9. Confirm what was stored, including verification outcome

Keep content concise - aim for 1-3 sentences unless it's a complex session summary.

Verification Before Storage (Anti-Poison)

Memories persist across sessions and influence future behaviour. Storing incorrect information is worse than storing nothing — it creates compounding errors. Before storing any memory, verify its claims.

What to Verify

Claim TypeVerification MethodExample
File existsUse Glob or Read to confirm"Config is in src/config.ts"
Function/class existsUse Grep or code search"Use parseToken() from auth.ts"
Function signatureRead the file, check the actual signature"parseToken takes a string and returns Claims"
API behaviourCheck the implementation or tests"The /users endpoint requires auth"
Dependency/versionCheck package.json, go.mod, etc."Project uses Vitest v2"
Build/test commandConfirm the script exists in package.json or Makefile"Run npm run test:e2e for integration tests"

What Does NOT Need Verification

  • User preferences — The user is the authority ("I prefer tabs over spaces")
  • Session summaries — Recap of what just happened in the current session
  • Opinions/decisions — Architectural choices made by the user ("We chose Postgres")
  • External facts — Things not checkable against the codebase ("React 19 uses...")

Verification Workflow

Is it a codebase claim (file, function, path, command, behaviour)?
├── No → Store directly with source:user or source:stated
└── Yes → Can you verify it right now?
          ├── Yes → Verify it
          │         ├── Correct → Store with verified:true
          │         └── Wrong → Inform user, do NOT store. Offer corrected version.
          └── No (e.g., external service, runtime behaviour)
                    → Store with verified:false, note unverified

Verification Rules

  1. NEVER store a codebase claim without checking — If the user says "the auth middleware is in src/middleware/auth.ts", confirm the file exists before memorising.
  2. If verification fails, do NOT store — Tell the user what you found instead and offer to store the corrected version.
  3. If you cannot verify (e.g., claim about runtime behaviour, external API), store it but tag with verified:false.
  4. Err on the side of not storing — A missing memory is recoverable; a wrong memory causes future errors.

Example: Verified vs Rejected

User says: "Remember that the database schema is defined in db/schema.sql"

Verification steps:

  1. Check: does db/schema.sql exist? → Use Glob to search
  2. If yes → Store with verified:true
  3. If no → "I checked and db/schema.sql doesn't exist. I found database/migrations/ instead. Would you like me to store that instead?"

Provenance Tags

Always include provenance tags to track the origin and verification status of memories:

TagMeaningWhen to Use
source:userUser explicitly stated thisUser preferences, direct instructions
source:discoveredAgent discovered this by examining codeFile paths, function signatures, patterns found
source:inferredAgent inferred this from contextBehaviour deduced from code, not directly stated
verified:trueCodebase claim was checked and confirmedAfter successful verification
verified:falseClaim could not be verified against codeExternal facts, runtime behaviour

Provenance Rules

  • Every memory MUST have exactly one source: tag
  • Codebase claims MUST have a verified: tag
  • User preferences and opinions do NOT need verified: tags (user is authoritative)

Failure Handling

If ./.aide/bin/aide memory add fails:

  1. Check error message - common issues:

    • Database not accessible: ensure aide MCP server is running
    • Invalid category: use one of learning, decision, session, pattern, gotcha
    • Empty content: content must be non-empty
  2. Retry with fixes if the issue is correctable

  3. Report failure if unable to store:

    Failed to store memory: <error details>
    Please check aide MCP server status.
    

Verification

A successful memory add returns:

Added memory: <ULID>

You can verify by searching for the memory:

./.aide/bin/aide memory search "<key term from content>" --limit=1

Scope Tags

Use scope tags to control when memories are injected:

TagWhen to UseInjection
scope:globalUser preferences, universal learningsEvery session
project:<name>Project-specific learningsSessions in that project
session:<id>Context for this work sessionRecent session injection

Tagging Rules

  • User preferences (favourite colour, coding style): Always add scope:global
  • Project learnings (API patterns, testing approach): Add project:<name>,session:<id>
  • Session summaries: Add project:<name>,session:<id> with category=session

Get the project name from the git remote or directory name. Session ID is available as $AIDE_SESSION_ID (set by aide hooks) or $CLAUDE_SESSION_ID (Claude Code native).

Abandoned Approaches

When an approach is tried and abandoned during implementation, debugging, or design, record it as an abandoned memory. This prevents future sessions from repeating the same failed approach.

When to Record

  • You try an implementation approach and it fails or is rejected
  • You explore a design direction and discover it won't work
  • The user explicitly abandons a direction (e.g., "let's not do it that way")
  • A dependency or library is evaluated and rejected

Content Template

Use this structured format:

ABANDONED: <what was tried>
REASON: <why it was abandoned>
ALTERNATIVE: <what was done instead, or "none yet">
CONTEXT: <any useful context for future reference>

Required Tags

TagPurposeExample
reason:<why>Machine-searchable abandon reasonreason:performance
approach:<what>What was triedapproach:sqlite-fts
project:<name>Project scopeproject:aide
source:discoveredProvenance (always discovered)source:discovered
session:<id>Session contextsession:abc12345

Example

./.aide/bin/aide memory add --category=abandoned \
  --tags=reason:performance,approach:sqlite-fts,project:aide,session:abc12345,source:discovered \
  "ABANDONED: Using SQLite FTS5 for memory search. REASON: go-sqlite3 requires CGO which breaks cross-compilation. ALTERNATIVE: Bleve full-text search (pure Go). CONTEXT: FTS5 was faster in benchmarks but CGO dependency was a non-starter for the release pipeline."

Decision Interaction

If an abandoned approach contradicts or supersedes an existing Decision (check with mcp__plugin_aide_aide__decision_list), also update the decision to reflect the change. For example, if a decision said "use SQLite FTS" and you abandoned that approach, update the decision with the new direction.

When updating a formal decision, omit --context to retain its existing applicability and supersession. New user decisions need no applicability metadata by default. Add freeform or structured applicability only for an explicit boundary; consult the decide skill for syntax. This metadata belongs to formal decisions, not memory add categories.

For Swarm/Multi-Agent

Add agent context to tags:

./.aide/bin/aide memory add --category=session --tags=swarm,agent:main "Overall task outcome..."

Pattern Analysis

Recommended model tier: balanced (sonnet) - this skill combines search with structured analysis

Analyze codebase patterns using static analysis findings. Surface complexity hotspots, code duplication, coupling issues, and potential secrets. Use this skill to understand code health and identify areas that need attention.

Prerequisites

Findings must be generated first by running analyzers via the CLI:

# Run all analyzers
./.aide/bin/aide findings run --path .

# Run specific analyzers
./.aide/bin/aide findings run --path . --analyzer complexity
./.aide/bin/aide findings run --path . --analyzer coupling
./.aide/bin/aide findings run --path . --analyzer secrets
./.aide/bin/aide findings run --path . --analyzer clones

Binary location: The aide binary is at .aide/bin/aide. If it's on your $PATH, you can use aide directly.

Available Tools

1. Search Findings (mcp__plugin_aide_aide__findings_search)

Full-text search across all findings. Supports Bleve query syntax for advanced searches.

Parameters:

  • query (required) — Search term or Bleve query
  • analyzer (optional) — Filter to one analyzer: complexity, coupling, secrets, clones
  • severity (optional) — Filter by severity: info, warning, critical
  • file (optional) — Filter by file path substring
  • limit (optional) — Max results (default 20)

Example usage:

Search for: "high complexity"
-> findings_search query="complexity" severity="warning"
-> Returns: functions with high cyclomatic complexity, with file:line

2. List Findings (mcp__plugin_aide_aide__findings_list)

List findings with filters. Use when you want to browse rather than search.

Parameters:

  • analyzer (optional) — Filter to one analyzer
  • severity (optional) — Filter by severity
  • file (optional) — Filter by file path substring
  • limit (optional) — Max results (default 20)
  • offset (optional) — Pagination offset

Example usage:

List all critical findings
-> findings_list severity="critical"
-> Returns: all critical-severity findings across all analyzers

3. Findings Statistics (mcp__plugin_aide_aide__findings_stats)

Get aggregate counts by analyzer and severity. Use as a starting point to understand overall code health before drilling into specifics.

Example usage:

How healthy is the codebase?
-> findings_stats
-> Returns: counts per analyzer, counts per severity, total findings

Workflow

Quick Health Check

  1. Get overview — Use findings_stats to see counts by analyzer and severity
  2. Triage critical — Use findings_list severity="critical" to review highest-priority items
  3. Drill into areas — Use findings_search with file or query filters for specific concerns

Complexity Analysis

  1. Run findings_search analyzer="complexity" severity="critical" to find the most complex functions
  2. Read the flagged functions directly using the finding locations
  3. Examine surrounding code as needed; use code_outline when unfamiliar large-file structure would help, or read the full file when small or mostly relevant
  4. Recommend decomposition strategies

Duplication Analysis

  1. Run findings_list analyzer="clones" to see detected code clones
  2. Each finding includes the clone pair — both file locations and line ranges
  3. Use Read to compare the duplicated sections
  4. Recommend extraction into shared functions or modules

Coupling Analysis

  1. Run findings_search analyzer="coupling" to see import fan-out/fan-in issues
  2. High fan-out means a file imports too many things (potential god module)
  3. High fan-in means many files depend on one (fragile dependency)
  4. Cycle findings indicate circular dependency chains

Secret Detection

  1. Run findings_list analyzer="secrets" severity="critical" for confirmed secrets
  2. Run findings_list analyzer="secrets" for all potential secrets (including unverified)
  3. Each finding includes the secret category (e.g., AWS, GitHub, generic API key)
  4. Snippets are redacted for safety — use Read to examine context around the finding

Anti-Pattern Identification

Beyond the automated analyzers, look for these patterns using findings as starting points:

FindingLikely Anti-PatternAction
Complexity > 20God functionDecompose into smaller functions
Fan-out > 15Kitchen sink moduleSplit responsibilities
Fan-in > 20Fragile dependencyConsider interface/abstraction
Multiple clonesCopy-paste programmingExtract shared utility
Import cycleCircular dependencyRestructure module boundaries

Output Format

## Code Health Report

### Overview

- Total findings: X (Y critical, Z warnings)
- Top concern: [area/file with most issues]

### Hotspots

1. **`file:line`** - [description] (severity)
   - Impact: [why this matters]
   - Recommendation: [what to do]

### Patterns Detected

- [List of anti-patterns found with evidence]

### Recommendations

1. [Prioritized action items]

Failure Handling

  1. No findings data — Tell user to run analyzers first: ./.aide/bin/aide findings run --path .
  2. Stale findings — Findings reflect the state at last analyzer run; recommend re-running if code changed significantly
  3. False positives — Secret detection may flag test fixtures or example configs; note when findings appear to be in test/example code

Verification Criteria

  • Checked findings_stats for overall picture
  • Reviewed critical findings
  • Cross-referenced findings with the relevant source code
  • Provided actionable recommendations with file:line references
  • Noted any false positives or findings that need manual verification

Performance Mode

Recommended model tier: smart (opus) - this skill requires complex reasoning

Systematic approach to identifying and fixing performance issues.

Prerequisites

Before starting:

  • Identify the specific operation or endpoint that is slow
  • Understand what "fast enough" means (target latency, throughput)
  • Ensure you can measure performance reproducibly

Workflow

Step 1: Establish Baseline Measurement

Never optimize without data. Measure current performance:

# Node.js - simple timing
time node script.js

# Node.js - CPU profiling
node --cpu-prof script.js
# Creates CPU.*.cpuprofile - analyze in Chrome DevTools

# Go - benchmarks
go test -bench=. -benchmem ./...

# API endpoint (ENDPOINT_URL is the URL under test)
curl -w "@curl-format.txt" -o /dev/null -s "$ENDPOINT_URL"

Record baseline metrics:

  • Execution time (p50, p95, p99 if available)
  • Memory usage
  • Number of operations per second
  • Number of I/O operations

Step 2: Identify Hotspots

Find where time is being spent:

# Node.js profiling
node --cpu-prof app.js
# Then load .cpuprofile in Chrome DevTools > Performance

# Go profiling
go test -cpuprofile=cpu.prof -bench=.
go tool pprof -http=:8080 cpu.prof
# Navigate unfamiliar large suspect files when their structure is needed
mcp__plugin_aide_aide__code_outline file="path/to/hotspot.ts"

# Find functions/classes in suspect area by name
mcp__plugin_aide_aide__code_search query="processData" kind="function"

# Find all callers of a hot function
mcp__plugin_aide_aide__code_references symbol="processData"

# Search for expensive patterns in code bodies (Grep is better here)
Grep for ".forEach(", ".map(", ".filter("    # Loop/iteration patterns
Grep for "SELECT", "find(", "query("         # Database queries
Grep for "fetch(", "axios", "http.Get"       # Network calls
Grep for "setTimeout", "setInterval"         # Timers
Grep for "JSON.parse", "JSON.stringify"      # Serialization

Note: code_search finds function/class/type definitions by name. For patterns inside function bodies (loops, queries, call chains), use Grep.

Read hotspot functions directly from known profiling/search locations, or batch known symbols with code_read_symbol. Use code_outline when unfamiliar large-file structure would help locate relevant code. Read full files when small or mostly relevant; extra navigation rounds can outweigh smaller responses.

Step 3: Analyze Performance Patterns

Look for these common issues:

IssuePatternSolution
N+1 queriesLoop containing DB callBatch/eager load
Repeated computationSame calculation in loopMemoize/cache
Large allocationsCreating objects in loopReuse/pool objects
Blocking I/OSync file/network opsMake async/concurrent
Missing indexesSlow DB queriesAdd database indexes
Unnecessary workProcessing unused dataFilter/skip early
Serial executionSequential independent opsParallelize

Step 4: Apply Optimizations

Priority order (highest impact first):

  1. Algorithmic improvements - O(n^2) -> O(n log n)
  2. Reduce I/O - Batch requests, add caching
  3. Parallelize - Concurrent operations
  4. Reduce allocations - Reuse objects, pre-allocate
  5. Micro-optimizations - Only as last resort

Make one optimization at a time and measure after each.

Step 5: Measure After Each Change

# Same measurement as baseline
time node script.js
go test -bench=. -benchmem ./...

Compare:

  • Did the metric improve?
  • By how much (percentage)?
  • Any negative side effects?

If no improvement: Revert and try different approach.

Step 6: Verify No Regressions

# Run all tests
npm test
go test ./...

# Check for correctness
# Ensure output is still correct after optimization

Failure Handling

SituationAction
Cannot measure reliablyIncrease sample size, reduce variance sources
Optimization made it slowerRevert, analyze why, profile more carefully
Optimization broke testsFix tests or revert if behavior changed
Bottleneck is externalDocument, consider caching, async processing
Memory improved but CPU worseEvaluate trade-off for use case

Common Optimizations

JavaScript/TypeScript

// BAD: N+1 queries
for (const user of users) {
  const posts = await db.getPosts(user.id);
}

// GOOD: Batch query
const userIds = users.map((u) => u.id);
const posts = await db.getPostsForUsers(userIds);

// BAD: Repeated work
const typeA = items.filter((x) => x.type === "a").map((x) => x.value);
const typeB = items.filter((x) => x.type === "b").map((x) => x.value);

// GOOD: Single pass
const grouped = { a: [], b: [] };
for (const x of items) {
  if (x.type in grouped) grouped[x.type].push(x.value);
}

// BAD: Serial async
const result1 = await fetch(url1);
const result2 = await fetch(url2);

// GOOD: Parallel async
const [result1, result2] = await Promise.all([fetch(url1), fetch(url2)]);

Go

// BAD: Allocation in loop
var result []T
for _, item := range items {
    result = append(result, process(item))
}

// GOOD: Pre-allocate
result := make([]T, 0, len(items))
for _, item := range items {
    result = append(result, process(item))
}

// BAD: String concatenation
s := ""
for _, item := range items {
    s += item
}

// GOOD: Builder
var b strings.Builder
for _, item := range items {
    b.WriteString(item)
}

SQL

-- BAD: Missing index on frequently queried column
SELECT * FROM users WHERE email = 'x@y.com';

-- GOOD: Add index
CREATE INDEX idx_users_email ON users(email);

-- BAD: SELECT *
SELECT * FROM users;

-- GOOD: Select only needed columns
SELECT id, name, email FROM users;

-- BAD: Query in loop
-- for each user: SELECT * FROM posts WHERE user_id = ?

-- GOOD: Single batch query
SELECT * FROM posts WHERE user_id IN (?, ?, ?);

MCP Tools

  • mcp__plugin_aide_aide__code_outline - Navigate unfamiliar large files when their structure is needed
  • mcp__plugin_aide_aide__code_search - Find function/class/type definitions by name
  • mcp__plugin_aide_aide__code_symbols - List all symbol definitions in a file
  • mcp__plugin_aide_aide__code_references - Find all callers of a hot function (exact name match)
  • mcp__plugin_aide_aide__memory_search - Check past performance decisions
  • Grep - Find code patterns in bodies: loops, queries, call chains, string literals

Profiling Commands Reference

Node.js

# CPU profiling
node --cpu-prof app.js
# Produces .cpuprofile file

# Memory profiling
node --heap-prof app.js
# Produces .heapprofile file

# Clinic.js for analysis
npx clinic doctor -- node app.js
npx clinic flame -- node app.js

Go

# CPU profiling
go test -cpuprofile=cpu.prof -bench=.
go tool pprof -http=:8080 cpu.prof

# Memory profiling
go test -memprofile=mem.prof -bench=.
go tool pprof -http=:8080 mem.prof

# Execution trace
go test -trace=trace.out -bench=.
go tool trace trace.out

Browser

  • DevTools -> Performance -> Record
  • DevTools -> Memory -> Heap snapshot
  • Lighthouse for overall page performance

Verification Criteria

Before completing:

  • Baseline measurement recorded
  • Improvement quantified (percentage)
  • All tests still pass
  • No correctness regressions
  • Memory usage acceptable

Output Format

## Performance Analysis: [Operation/Endpoint Name]

### Baseline

- Execution time: 450ms (p50), 680ms (p95)
- Memory: 125MB peak
- Database queries: 150

### Hotspots Identified

1. `db.getUsers()` - 300ms (67% of total)
2. `processData()` - 100ms (22% of total)
3. `formatOutput()` - 50ms (11% of total)

### Optimizations Applied

1. Batched user queries - 300ms -> 50ms
2. Memoized processData for repeated calls - 100ms -> 5ms

### Results

- Execution time: 450ms -> 105ms (77% faster)
- Memory: 125MB -> 80MB (36% reduction)
- Database queries: 150 -> 3 (98% reduction)

### Verification

- All tests: PASS
- Output correctness: VERIFIED

Plan Swarm

Recommended model tier: smart (opus) - this skill requires careful reasoning

Structured planning interview to decompose work into independent stories before running a swarm.

Quick Reference

plan swarm                → Full interview workflow (recommended)
plan swarm --fast         → Skip interview, state assumptions, decompose directly

Workflow

Phase 1: Understand

Explore the codebase and existing context before asking questions.

  1. Read existing decisions via mcp__plugin_aide_aide__decision_list and mcp__plugin_aide_aide__decision_get
  2. Search memories via mcp__plugin_aide_aide__memory_search for relevant past context
  3. Explore the codebase — read key files, understand architecture, identify boundaries
  4. Identify the scope — what is the user asking for? What are the natural boundaries?

Do NOT ask questions yet. Build understanding first.

Phase 2: Interview

Conduct 2-3 rounds of focused questions. Each round has 2-4 questions. Max 3 rounds total.

Round 1: Scope & Boundaries

  • What is in scope vs out of scope?
  • What are the success criteria?
  • Are there any constraints (time, tech, compatibility)?

Round 2: Dependencies & Risks

  • What shared state or files will multiple stories touch?
  • What could go wrong? What are the risky parts?
  • Are there external dependencies (APIs, services, data)?

Round 3: Acceptance Criteria (if needed)

  • How will we know each story is done?
  • What tests should exist?
  • What does "good enough" look like?

Use the AskUserQuestion tool for each round. Summarize what you've learned before asking the next round.

Fast mode (plan swarm --fast): Skip this phase. State your assumptions explicitly, then proceed directly to Phase 3.

Phase 3: Decompose

Output a structured story list. Each story must be:

  • Independent — can be developed in parallel without conflicting file edits
  • Complete — has clear boundaries and acceptance criteria
  • Testable — has concrete verification steps

Story format:

## Stories

### 1. [Story Name]

- **Description**: What this story implements
- **Files**: List of files this story will create or modify
- **Acceptance Criteria**:
  - [ ] Criterion 1
  - [ ] Criterion 2
- **Risk**: low | medium | high
- **Notes**: Any special considerations

### 2. [Story Name]

...

Independence check: Verify that no two stories modify the same file. If they do, either:

  1. Merge the stories
  2. Restructure so each story owns its files
  3. Sequence them (one blocks the other)

Phase 4: Validate & Store

  1. Present the plan to the user for review

  2. Store as decision once approved:

    ./.aide/bin/aide decision set "swarm-plan" "<N> stories: <story-1>, <story-2>, ..." \
      --details='<JSON object>' \
      --rationale="<brief description of scope and approach>" \
      --by="<git-username>"
    
  3. Record shared decisions discovered during planning:

    ./.aide/bin/aide decision set "<topic>" "<decision>" --by="<git-username>"
    

    --by is the git username — the GitHub handle, as in the remote URL, not a display name. Never guess it: omit the flag rather than inventing an identifier, since the store is append-only and a wrong byline can only be superseded, not edited.

Binary location: The aide binary is at .aide/bin/aide. If it's on your $PATH, you can use aide directly.

  1. Instruct the user: Run /aide:swarm to execute the plan

Note on task materialization: The plan is stored as a decision, not as tasks. The /aide:swarm skill reads the plan and materializes tasks at execution time:

  • Claude Code: Each story agent creates native tasks (TaskCreate) with blockedBy dependency chaining for SDLC stages.
  • OpenCode: The orchestrator creates aide tasks (task_create MCP tool) for all SDLC stages upfront, and story agents claim them.

Output Format

The stored swarm-plan decision should be a JSON object:

{
  "stories": [
    {
      "name": "story-name",
      "description": "What it does",
      "files": ["src/foo.ts", "src/bar.ts"],
      "acceptance": ["criterion 1", "criterion 2"],
      "risk": "low",
      "notes": ""
    }
  ],
  "shared_decisions": ["auth-strategy", "db-schema"],
  "assumptions": ["Node 20+", "existing test framework"],
  "created": "ISO timestamp"
}

Tips

  • Fewer stories is usually better. 2-4 stories is ideal for most tasks.
  • Each story should take roughly similar effort.
  • If a story is too large, split it. If it's too small, merge it.
  • Stories that share database migrations or config files should be sequenced, not parallelized.
  • The plan is a starting point. The swarm skill will adapt if needed.

Recall

Recommended model tier: balanced (sonnet) - this skill performs straightforward operations

Search stored memories and decisions to answer questions about past learnings, architectural choices, patterns, and project context.

MCP Tools

Search Memories

ToolPurpose
mcp__plugin_aide_aide__memory_searchFull-text search (fuzzy, prefix, substring matching)
mcp__plugin_aide_aide__memory_listList memories, optionally filtered by category

Get Decisions

ToolPurpose
mcp__plugin_aide_aide__decision_getGet specific decision by topic
mcp__plugin_aide_aide__decision_listList all decisions
mcp__plugin_aide_aide__decision_historyGet all versions of a decision

Workflow

  1. Parse the question - Extract key terms
  2. Search both sources:
    • Use mcp__plugin_aide_aide__memory_search with relevant keywords
    • Use mcp__plugin_aide_aide__decision_get with the topic, or mcp__plugin_aide_aide__decision_list
  3. Analyze timestamps - Prefer most recent (ULIDs are time-ordered)
  4. Answer - Combine relevant context from both sources

Instructions

When the user asks about previous context:

  1. For architectural/design questions (testing, auth, database, etc.):

    • Use mcp__plugin_aide_aide__decision_get with topic (e.g., "testing")
    • If unsure of topic name, use mcp__plugin_aide_aide__decision_list
  2. For learnings/patterns/gotchas:

    • Use mcp__plugin_aide_aide__memory_search with query (e.g., "ESM imports")
  3. When answering:

    • Cite the source (memory or decision)
    • Include the date for context
    • Note if something was updated/changed

Examples

User: "What testing framework did we decide on?" → Use mcp__plugin_aide_aide__decision_get with topic="testing" → Answer with the decision and rationale

User: "What was the issue with ESM imports?" → Use mcp__plugin_aide_aide__memory_search with query="ESM imports" → Answer with the learning

User: "What approach did we take for auth?" → Use both mcp__plugin_aide_aide__decision_get (topic="auth") and mcp__plugin_aide_aide__memory_search (query="auth") → Combine both sources in answer

Failure Handling

If no results found:

  1. Try alternative terms - search with synonyms or related keywords
  2. Broaden the search - use mcp__plugin_aide_aide__memory_list to browse all memories
  3. Report clearly: "No memories or decisions found for ''. This may not have been recorded previously."

Notes

  • This skill is READ-ONLY - searches but doesn't modify
  • Decisions are structured (topic → decision + rationale)
  • Memories are freeform learnings, gotchas, patterns
  • Always prefer the most recent when there are conflicts

Reflect

Extract candidate instincts — patterns repeatedly observed in this session that might be worth promoting to durable memories.

Your role as the agent running this skill

You propose, the user approves. Nothing this skill does writes a memory or marks anything superseded without an explicit yes from the user.

Detectors emit proposals into a holding bucket (they're never auto-promoted to memories). When this skill runs, your job is to make those proposals reviewable — to add the judgement that mechanical matching can't:

  1. Classify intent of user prompts in convergence windows — was the user actually correcting the previous edit, or just commenting?
  2. Rewrite the content into a useful memory — see below. This is the most important step; the detector's content is a [DRAFT — rewrite…] placeholder, never the finished memory.
  3. Judge semantic conflicts — which existing memories (if any) does this proposal supersede?
  4. Recommend an action — accept (with rewritten content + supersedes), reject (why), or leave open for the user to think about.

Then stop and ask. Surface each proposal to the user with your recommendation. Wait for explicit approval before running aide reflect accept|reject. The CLI is the write surface; your role is to make the user's approval decision as well-informed as possible, not to make it for them.

Concretely: do not chain "list proposals → accept proposals" in the same turn. List, summarise, recommend, wait, then act on user instruction.

Why rewriting is the default, not the exception

The detector emits an observation ("cat was run 5 times in 1 minute"). That's a structural signal, not a useful memory. A useful memory captures:

  • Why the repetition / convergence happened (the underlying need or mistake the agent kept circling around).
  • What the canonical alternative is (a specific file path, command, pattern, or piece of project knowledge).
  • Scope (this codebase / this kind of task / this directory).

The agent reviewing the proposal does this synthesis by reading the evidence snapshot. The detector can't — it only knows the count.

Bad memory (the raw template): "In this project, cat is run repeatedly. Cache its output."

Good memory (after agent synthesis): "When investigating the aide README for plugin/config questions, the file is stable per commit and the config table sits around lines 11-25 — inject the slice via Read with offset/limit instead of re-cat-ing the whole file."

The proposal's content field literally starts with [DRAFT — rewrite with concrete context before accepting] to make this obvious. If you accept without rewriting, you've stored noise.

How this skill differs from the automatic Stop hook

  • The Stop hook (AIDE_REFLECT=1 env or reflect.enabled=true in .aide/config/aide.json) runs aide reflect run automatically at session end. Deterministic-only: marker matching for convergence, pure counting for repetition. No supersession beyond structural instinct_key:* matches.
  • This skill adds a second pass: it lists user-prompt candidates that fall in convergence-relevant windows, you judge intent in-context, you search for semantically conflicting memories, then you feed everything back. Higher-quality output, no extra API cost — uses tokens you'd be spending anyway.

Session resolution

All commands below default to the current session — aide finds it by checking, in order: an explicit --session=<id> flag, the AIDE_SESSION_ID env var (set by OpenCode automatically; not by Claude Code), then the session of the most recent observe event. Pass --session=<id> to target a specific session, or run ./.aide/bin/aide reflect current-session to see what would be resolved.

Steps

1. Get candidate prompts

./.aide/bin/aide reflect candidates

Returns JSON like:

{
  "session_id": "abc123",
  "guidance": "For each prompt, judge whether it was correcting...",
  "asks": ["intent"],
  "prompts": [
    {
      "id": "01JF...A",
      "timestamp": "...",
      "text": "no don't add async — it should stay sync",
      "preceding_edit": "Edit src/api/users.ts",
      "following_edit": "Edit src/api/users.ts",
      "file_path": "src/api/users.ts"
    }
  ]
}

If prompts is empty, skip to step 4 (deterministic run only).

2. Classify each prompt

For each prompt, judge its intent using the surrounding edit context:

  • corrective — the user was redirecting the assistant's last action
  • positive — the user was affirming the assistant's last action ("perfect", "ship it", "lgtm")
  • neutral — neither corrective nor affirming (e.g. a new task, a question)

Build a JSON array:

[
  {"id": "01JF...A", "intent": "corrective", "confidence": 0.95},
  {"id": "01JF...B", "intent": "neutral"}
]

3. Run with classifications

./.aide/bin/aide reflect run --llm \
  --classifications-json='[{"id":"01JF...A","intent":"corrective"}]'

Returns a JSON summary: {"proposals_written": N, "shapes": {...}}.

The --llm flag puts the runner in LLM mode, which runs the RequiresLLM detectors (convergence, friction) in addition to repetition. The Stop hook never passes it, so those detectors only ever surface in this reviewed pass.

4. Run in LLM mode without classifications

If step 1 returned no candidates, still run with --llm (not bare) so friction and the marker-based convergence pass fire — only the LLM-graded convergence intent is skipped:

./.aide/bin/aide reflect run --llm

5. List proposals and summarise for the user

mcp__plugin_aide_aide__instinct_proposals_list { "status": "open" }

Summarise each new proposal's summary field for the user. Don't act on anything yet — let them decide.

6. You decide what gets superseded

This is where your judgement matters most. The structural auto-supersession (same instinct_key:* tag) only catches instinct-on-instinct dedup. The interesting case is when a new instinct contradicts a manually-set memory the user wrote earlier — e.g. a "documentation standard: always run rustdoc" memory being superseded by a new "rustdoc runs repeatedly, cache it" instinct.

Mechanical matching can't catch that. You can. Process:

  1. Extract the key subject from the proposal (e.g. "rustdoc", a file path, a command name).
  2. mcp__plugin_aide_aide__memory_search { "query": "<subject>" }
  3. Read each result. Judge — you are the judge:
    • Does the new instinct's guidance contradict this memory's guidance?
    • Does it replace it with a better recommendation?
    • Or does it just touch the same topic without conflicting?
  4. Only collect IDs that genuinely conflict. False positives create silent memory loss; bias toward "leave it" when uncertain.
  5. Surface your reasoning to the user before acting: "I think proposal X supersedes memory Y because Z — accept with --supersedes=Y?"

7. Rewrite the content, then present recommendations — do not auto-act

For each proposal:

  1. Read the evidence snapshot via mcp__plugin_aide_aide__instinct_inspect.
  2. Synthesise the underlying lesson. What was the agent (you, or a past you) actually trying to achieve? Why did the pattern repeat / converge? What's the canonical alternative for this codebase?
  3. Draft the rewritten memory content. Skip the [DRAFT — …] template text from the proposal; write a useful instinct from scratch.
  4. Present to the user with the rewrite inline:

Proposal 01JF… (repetition, rustdoc × 7 in 5 min). Reading the evidence: 6 of the 7 calls were rustdoc --no-deps checking the same public crate while iterating on a doctest. I'd accept with this rewritten content and supersede memory 01JD… ("always run rustdoc") because the new guidance refines, not contradicts, that one:

"When iterating on a single doctest, cargo test --doc <module> re-runs only that doctest in ~1s; reserve rustdoc --no-deps for final pre-commit verification across all crates."

Command: aide reflect accept 01JF… --supersedes=01JD… \ --content="When iterating on a single doctest…"

Then wait. The user might say:

  • "yes" → run the command verbatim
  • "yes but tweak the wording to …" → adjust --content= and re-present
  • "accept but don't supersede" → drop --supersedes
  • "reject — that's not actually a pattern, I asked you to repeat for testing" → run reject with that reason
  • "leave them open, I'll review later" → do nothing, you're done

If the evidence doesn't support a meaningful rewrite — e.g. the events are a test trigger, a one-off, a data artifact — recommend reject. A proposal with no useful synthesis is noise; promoting it pollutes the memory store.

8. Execute the user's decision via the CLI

Only after the user has chosen — writes are CLI-only per aide convention:

# Accept with rewritten content (the default — see step 7):
./.aide/bin/aide reflect accept <proposal-id> --content="<your synthesised memory>"

# Accept with rewritten content AND supersession:
./.aide/bin/aide reflect accept <proposal-id> \
  --content="<your synthesis>" \
  --supersedes=<mem-id1>,<mem-id2>

# Accept verbatim (the [DRAFT…] template lands as the memory — almost
# never what you want, included only for completeness):
./.aide/bin/aide reflect accept <proposal-id>

# Reject (with reason for the audit trail):
./.aide/bin/aide reflect reject <proposal-id> --reason="not useful"

Supersession unions two sources:

  1. Structural (auto) — instinct memories sharing the same instinct_key:* tag (cheap dedup; same Bash command for repetition, same file path for convergence).
  2. Semantic (via --supersedes) — IDs from step 6. Works for any memory including manually-set ones with no instinct tags.

Each superseded record gets superseded + superseded_by:<new-id> tags; the new memory gets supersedes:<csv> pointing back. Superseded records stay in the bucket for audit but are filtered out of default queries.

Inspecting evidence

mcp__plugin_aide_aide__instinct_inspect { "id": "<ulid>" }

The evidence.snapshot array contains the observe events that triggered the pattern.

Opt-in toggle for the Stop hook

export AIDE_REFLECT=1      # also: true, on, yes — any truthy value

When unset or set to a falsy value (0, false, off, no), the Stop hook is a no-op. This skill still works regardless — it's manually invoked, not gated by the env var.

Shape catalogue

  • repetition — Bash commands run > N times in a session, suggesting the agent forgot it already had the answer. Pure counting, no LLM input needed.
  • convergence — Edit A → user corrective marker → Edit B on the same file → optional positive signal. Marker-based by default, upgrades to LLM-classified when intent labels are provided via step 3.
  • friction — the same tool failing repeatedly on the same target (a Bash command that keeps erroring, an Edit that won't apply to a file). Gathered from the observe Error field; the lesson worth keeping is usually the fix, which you supply by reading the evidence. RequiresLLM — never auto-fires in the Stop hook.

Detectors declare a RequiresLLM capability — two tiers:

  • Deterministic tier (RequiresLLM=false: repetition) runs automatically in the Stop hook. Must be high-precision; nothing reviews it before it lands as a proposal.
  • LLM tier (RequiresLLM=true: convergence, friction) runs only in this reviewed pass, when the skill passes --llm (step 3/4). Higher recall is fine — you judge each proposal before anything is promoted.

Code Review Mode

Recommended model tier: smart (opus) - this skill requires complex reasoning

Comprehensive code review covering quality, security, and maintainability.

Review Checklist

Decision Conformance

Recorded decisions are this project's binding architectural commitments. Check them first — a conformance violation outranks any style or quality issue below.

  • Called decision_list (or noted the fallback) before reading any code
  • Every changed file checked against every decision that could apply to it
  • Every ✅ backed by a cited check, not by inspection alone
  • Every decision on its own line, including the ones that do not apply — no bulk dismissals
  • "Decisions loaded: N" counted, not estimated, and matching the number of lines
  • No decision violated by the change under review
  • Change does not extend a pre-existing violation
  • Where a decision seems wrong rather than the code, that is stated explicitly

Code Quality

  • Clear naming (variables, functions, classes)
  • Single responsibility (functions do one thing)
  • DRY (no unnecessary duplication)
  • Appropriate abstraction level
  • Error handling coverage
  • Edge cases considered

Security (OWASP Top 10)

  • Input validation (no injection vulnerabilities)
  • Authentication checks (routes protected)
  • Authorization (proper access control)
  • Sensitive data handling (no secrets in code)
  • SQL/NoSQL injection prevention
  • XSS prevention (output encoding)
  • CSRF protection
  • Secure dependencies (no known vulnerabilities)

Maintainability

  • Code is readable without comments
  • Comments explain "why" not "what"
  • Consistent with codebase patterns
  • Tests cover critical paths
  • No dead code

Performance

  • No N+1 queries
  • Appropriate caching
  • No memory leaks
  • Efficient algorithms

Context-Efficient Reading

Choose retrieval from the review evidence already available. Inspect the diff and known ranges directly; read full files when they are small or most contents are relevant. Use navigation tools when they resolve missing context, since extra rounds can outweigh smaller responses:

  • code_outline -- Collapsed skeleton with signatures and line ranges. Useful for navigating unfamiliar large files.
  • code_symbols -- Quick symbol list when you only need names and kinds.
  • code_search / code_references -- Find symbol definitions or callers across the codebase.
  • Read with offset/limit -- Read known ranges from the diff, search results, or an outline.
  • code_read_symbol -- Read known symbols; batch several names with symbols (up to 10).
  • Grep -- Find patterns in code content (loops, queries, string literals) that the index doesn't cover.

For reviews spanning many files, consider using Task sub-agents (explore type) which run in their own context and return summaries.

Review Process

  1. Load the decisions - Call decision_list. It is authoritative: live, and complete with Details and References. The "Project Decisions" block in session context is a convenience copy — a snapshot taken at session start that omits Details and References and goes stale the moment a decision changes, so it is a fallback when the tool is unavailable, never the source you check against. Use decision_get for one decision's full text when the list entry is not enough to judge conformance. Blank applicability adds no restriction; respect limits in the decision's wording. Interpret explicit text, selectors and repository-relative path patterns against the changed code before reporting a violation. They are agent guidance, not automatic file filters. A narrower decision only overrides another topic when explicitly stated. See "Decision Conformance Pass" below for how to check them.
  2. Inspect changed files - Read the diff and identify areas needing surrounding context. Use code_outline when unfamiliar large-file structure would help locate that context.
  3. Read relevant code - Read the functions/sections needed for detailed review, using known ranges or symbol reads. Read a full file when its size or the review scope warrants it.
  4. Search for context - Use code_search, code_references, and Grep:
    • code_search — Find related function/class/type definitions by name
    • code_references — Find all callers/usages of a modified symbol (exact name match)
    • Grep — Find code patterns in bodies (error handling, SQL queries, security-sensitive calls)
  5. Check integration - How does it fit the larger system?
  6. Run static analysis - Use lsp_diagnostics, ast_grep if available
  7. Document findings - Use severity levels

Decision Conformance Pass

This is the part of the review that no static analyzer can do for you. assess-findings grades findings the analyzers already produced; this pass reads the code and looks for violations nothing flagged.

Scope. Default to the changed code — the diff, or the files the user named. Say which scope you used. Only sweep the whole repo when the user asks for it; a full sweep is slow and mostly re-reports known debt.

Method. For each decision, work out what would falsify it, then go looking for that:

Decision shapeHow to check it
Bans a mechanism ("no bash in runtime paths")Grep for the mechanism across the reviewed scope
Requires a boundary ("plugin code must not import daemon internals")code_references on the target symbols, or Grep the import lines
Requires a property of all code ("must be reachable from real call paths")findings_list analyzer=deadcode include_accepted=true for the scope, then confirm by reading. Accepted findings are hidden by default, and an acceptance predating the decision is exactly what you are looking for
Mandates a library or approach ("use go-git, not shelling out to git")Grep for the banned alternative and for the required one
Constrains a platform or runtimeRead the changed code for platform-specific assumptions

A decision whose text gives you nothing falsifiable is not checkable here. Say so plainly rather than inventing a check — and mention it to the user, because a decision that cannot be checked is a decision that cannot be enforced.

Evidence is required, including for a pass. Every ✅ must cite what produced it — the Grep pattern you ran, the code_references call, the findings_list filter, or the specific lines you read. "Looks fine" is not a check, and a conformance block full of uncited ticks is worse than no block at all: it reports assurance you did not earn.

Every decision gets its own line. Report all of them, individually, with a reason — including the ones that do not apply. Never collapse several into a category dismissal ("the remaining N are out of scope"): a bulk ➖ is the same evasion as an uncited ✅, and it is how a decision that did apply gets swept up with the ones that did not. A ➖ still needs its own evidence — the path check or grep that shows the diff does not touch what the decision governs. Grouping several decisions under one shared piece of evidence is fine when the evidence genuinely covers them all (one path check disposing of every survey-* decision, say), as long as each still has its own line naming it.

State the count and make it match. "Decisions loaded: N" must equal the number of lines below it. Count them; do not estimate.

A hidden finding is not an absent one. Any findings_* call made to discharge a decision must pass include_accepted=true; the default hides accepted findings, so a single earlier acceptance turns every later review into a cited, confident, wrong ✅ — the exact failure the evidence rule above exists to prevent. When an accepted finding is decision-linked, report the acceptance rather than passing over it: it may predate the decision, and nothing re-examines it otherwise.

Reporting. A confirmed violation is 🔴 Critical regardless of how small the code change is, and must name the decision topic. If the code looks right and the decision looks wrong or stale, say that instead of forcing a violation — recommend /decide on that topic.

MCP Tools

Use these tools during review:

  • mcp__plugin_aide_aide__code_outline - Navigate unfamiliar large files with signatures and line ranges when needed
  • mcp__plugin_aide_aide__code_search - Find symbols related to changes (e.g., code_search query="getUserById")
  • mcp__plugin_aide_aide__code_symbols - List all symbols in a file being reviewed
  • mcp__plugin_aide_aide__code_references - Find all callers/usages of a modified symbol
  • mcp__plugin_aide_aide__decision_list - Load first. The authoritative list of recorded decisions — current, and including Details and References
  • mcp__plugin_aide_aide__decision_get - Full text of one decision by topic, including rationale
  • mcp__plugin_aide_aide__memory_search - Check for related past learnings, gotchas, or issues
  • mcp__plugin_aide_aide__findings_search - Search static analysis findings (complexity, secrets, clones) related to changed code
  • mcp__plugin_aide_aide__findings_list - List findings filtered by file, severity, or analyzer
  • mcp__plugin_aide_aide__findings_stats - Overview of finding counts by analyzer and severity

Output Format

## Code Review: [Feature/PR Name]

### Summary

[1-2 sentence overview]

### Decision Conformance

Scope checked: [diff / named files / whole repo]
Decisions loaded: N

- ✅ `<topic>` — conforms — checked by: [grep pattern / tool call / lines read]
- ❌ `<topic>` — violated at `file:line`: [what the code does vs what the decision requires]
- ➖ `<topic>` — n/a: [the path check or grep showing the diff does not touch what it governs]
- ➖ `<topic>` — not checkable: [nothing falsifiable in the decision text as written]

One line per decision, no exceptions — the list length must equal "Decisions loaded".
Decisions sharing one piece of evidence still get one line each.

(State "no decisions recorded" if `decision_list` returns none.)

### Findings

#### 🔴 Critical (must fix)

- **[Issue]** `file:line`
  - Problem: [description]
  - Fix: [recommendation]

#### 🟡 Warning (should fix)

- **[Issue]** `file:line`
  - Problem: [description]
  - Fix: [recommendation]

#### 🔵 Suggestion (consider)

- **[Issue]** `file:line`
  - Suggestion: [recommendation]

### Security Notes

- [Any security-specific observations]

### Verdict

[ ] ✅ Approve
[ ] ⚠️ Approve with comments
[ ] ❌ Request changes

Severity Guide

LevelCriteria
CriticalSecurity vulnerability, data loss risk, crash, recorded decision violated
WarningBug potential, maintainability issue, performance
SuggestionStyle, minor improvement, optional

Failure Handling

If unable to complete review:

  1. Missing files - Report which files could not be read
  2. Ambiguous scope - Ask user to clarify what code to review
  3. Large changeset - Break into smaller chunks, review systematically
  4. No decisions recorded - decision_list returns none; skip the conformance pass, say so in the report, and continue with the rest of the review. Never invent decisions
  5. decision_list unavailable - Fall back to the injected "Project Decisions" block and say in the report that you used it, since it omits Details and References and may predate a decision changed this session. If neither is available, report the conformance pass as not run rather than passing it

Reporting blockers:

## Review Status: Incomplete

### Blockers

- Could not access: `path/to/file.ts` (permission denied)
- Missing context: Need to understand `AuthService` implementation

### Partial Findings

[Include any findings from files that were reviewed]

Verification Criteria

A complete code review must:

  1. Inspect all changed files - Examine every file in the diff/scope
  2. Read critical sections - Read flagged areas and enough surrounding code to evaluate their behavior
  3. Check for related code - Use code_search and code_references to find callers/callees
  4. Verify test coverage - Check if tests exist for critical paths
  5. Document all findings - Even if no issues found, state that explicitly

Checklist before submitting review:

  • All files in diff/scope have been examined
  • Critical functions/sections and necessary context read in detail
  • Related symbols searched (callers, implementations)
  • Security checklist evaluated
  • Findings documented with file:line references
  • Verdict provided with clear reasoning

Semgrep Security Analysis

Run Semgrep to detect security vulnerabilities and code quality issues in the codebase.

Workflow

1. Run Semgrep scan

# Auto-detect rules for the project's languages
semgrep scan --config auto --json --quiet 2>/dev/null | head -c 50000

If JSON output is too large, use text output:

semgrep scan --config auto --quiet 2>/dev/null

2. For specific rule sets

# Security-focused rules only
semgrep scan --config "p/security-audit" --json --quiet

# OWASP Top 10
semgrep scan --config "p/owasp-top-ten" --json --quiet

# Language-specific
semgrep scan --config "p/golang" --json --quiet
semgrep scan --config "p/python" --json --quiet
semgrep scan --config "p/typescript" --json --quiet

3. Triage results

For each finding:

  1. Read the file and surrounding context
  2. Assess whether the finding is a true positive or false positive
  3. For true positives, fix the issue following the suggestion in the finding
  4. For false positives, consider adding a # nosemgrep inline comment with justification

4. Scan specific files

# Scan only changed files
semgrep scan --config auto --json --quiet -- path/to/file.py

Common Issues

  • Too many findings: Use --severity ERROR to focus on critical issues first
  • Slow scan: Use --config auto instead of multiple rule packs to avoid re-scanning
  • Missing rules: Install additional rules with semgrep registry
  • False positives: Add # nosemgrep: rule-id with a comment explaining why

Codebase Survey

Recommended model tier: balanced (sonnet) - this skill performs structured queries

Understand the structure, technology, entry points, and change hotspots of a codebase. Survey describes WHAT the codebase IS — not code problems (use findings for that).

Available Tools

1. Survey Stats (mcp__plugin_aide_aide__survey_stats)

Start here. Get an overview of what has been surveyed: total entries, breakdown by analyzer and kind, and per-analyzer freshness (the git commit each analyzer last ran at, and how many commits behind HEAD it is).

Is the codebase surveyed?
→ Uses survey_stats
→ Returns: counts by analyzer (topology, entrypoints, churn, modules) and kind, plus freshness vs git HEAD

If freshness shows an analyzer is commits behind HEAD, re-run survey_run before trusting its data.

2. Survey Run (mcp__plugin_aide_aide__survey_run)

Run analyzers to populate survey data. Three analyzers available:

  • topology — Packages, workspaces, build systems, tech stack detection (filesystem view)
  • entrypoints — main() functions, HTTP handlers, gRPC services, CLI roots (cobra/urfave). Uses code index when available; falls back to file scanning
  • churn — Git history hotspots (files/dirs that change most often)
  • modules — Structural modules discovered by clustering the import/reference graph: what files actually belong together, which directory layout can hide. Requires the code index (aide code index)
Survey this codebase
→ Uses survey_run (no analyzer param = run all)
→ Returns: entry counts per analyzer, an added/removed diff vs the previous run, and the git commit the run is tagged with

3. Survey List (mcp__plugin_aide_aide__survey_list)

Browse entries filtered by analyzer, kind, or file path. No search query needed.

Kinds: module, entrypoint, dependency, tech_stack, churn, submodule, subproject, workspace, arch_pattern

What other projects live inside this repo?
→ Uses survey_list with kind=subproject
→ Returns: child project scopes (submodules, nested repos) with identity and whether each has its own .aide store — their files belong to THEIR stores, not this project's
What modules are in this codebase?
→ Uses survey_list with kind=module
→ Returns: all module entries

What technologies does this use?
→ Uses survey_list with kind=tech_stack
→ Returns: detected frameworks, languages, build systems

What files change most?
→ Uses survey_list with kind=churn
→ Returns: high-churn files ranked by commit count

4. Survey Search (mcp__plugin_aide_aide__survey_search)

Full-text search across entry names, titles, and details. Use when looking for specific modules or technologies.

Find anything related to "auth"
→ Uses survey_search with query="auth"
→ Returns: modules, entrypoints, churn entries matching "auth"

5. Call Graph (mcp__plugin_aide_aide__survey_graph)

Build a call graph for a symbol showing callers, callees, or both. BFS traversal over the code index.

Who calls BuildCallGraph?
→ Uses survey_graph with symbol="BuildCallGraph" direction="callers"
→ Returns: graph of calling symbols with file:line locations

What does handleSurveyRun call?
→ Uses survey_graph with symbol="handleSurveyRun" direction="callees"
→ Returns: graph of called symbols

Show call neighborhood of RunTopology
→ Uses survey_graph with symbol="RunTopology" direction="both"
→ Returns: both callers and callees

Parameters:

  • symbol (required): Function/method name
  • direction: "both" (default), "callers", "callees"
  • max_depth: BFS hops (default 2)
  • max_nodes: Max nodes (default 50)

Requires: Code index must be populated (aide code index).

Workflow

Orienting in an unfamiliar codebase

  1. Check survey status:

    • Use survey_stats to see if data exists
    • If empty, run survey_run to populate
  2. Understand the structure:

    • survey_list kind=module — What are the major modules?
    • survey_list kind=tech_stack — What technologies are used?
    • survey_list kind=workspace — Is this a monorepo?
  3. Find entry points:

    • survey_list kind=entrypoint — Where does execution start?
    • Identifies main() functions, HTTP handlers, CLI roots
  4. Identify hotspots:

    • survey_list kind=churn — What files change most? (complexity/bug magnets)
  5. Trace call relationships:

    • survey_graph symbol="handleRequest" — Map the call neighborhood
    • Use direction=callers to find who invokes a function
    • Use direction=callees to understand what a function depends on

Answering specific questions

QuestionToolParameters
"What is this codebase?"survey_listkind=module
"What tech stack?"survey_listkind=tech_stack
"Where are the entry points?"survey_listkind=entrypoint
"What changes most?"survey_listkind=churn
"Is there an auth module?"survey_searchquery="auth"
"Who calls this function?"survey_graphsymbol=X, direction=callers
"What does this call?"survey_graphsymbol=X, direction=callees

Survey vs Findings vs Code Search

ToolPurposeExample
SurveyWHAT the codebase ISModules, tech stack, entry points, churn
FindingsCode PROBLEMSComplexity, security issues, duplication
Code SearchSymbol DEFINITIONSFind function signatures, call sites

Survey gives you the big picture. Code search gives you specific symbols. Findings gives you problems to fix.

Prerequisites

  • Survey data: Run aide survey run or use survey_run tool
  • Code index (for entrypoints + graph): Run aide code index
  • Git history (for churn): Must be a git repository (uses go-git, no git binary needed)

Binary location: The aide binary is at .aide/bin/aide. If it's on your $PATH, you can use aide directly.

Notes

  • Survey results are cached in BoltDB — re-run analyzers to refresh after significant changes
  • Topology analyzer inspects the filesystem (build files, directory structure)
  • Entrypoints analyzer uses the code index when available; falls back to file scanning
  • Churn analyzer uses go-git to read git history directly (no git binary required)
  • Call graph is computed on demand from the code index (not stored)

Swarm Status

Quick orchestrator-side inspection of a live swarm. Run this when you want to see what your spawned subagents are doing right now without halting them or opening the aide-web dashboard.

Steps

1. Resolve current session (your own)

./.aide/bin/aide reflect current-session

Use that ID as <parent> below — it's the orchestrator session that owns the swarm.

2. List agents in this swarm

./.aide/bin/aide agent list --parent=<parent> --json

Returns one record per registered subagent with parent_session, namespace, status, halt, paused, deadline.

3. Active tasks for this swarm

./.aide/bin/aide task list --parent-session=<parent> --json

Filters the project-wide task bucket to ones tagged with this swarm's parent. Look for tasks stuck in claimed without progress.

4. Recent messages

./.aide/bin/aide message list --parent-session=<parent>

Cross-agent comms within this swarm. High-priority messages from the orchestrator are surfaced to subagents on their next tool call by the signals hook.

5. Summarise for the user

Group by agent. For each, report:

  • Status (running / paused / halted)
  • Current tool (read agent:<id>:currentTool via aide state get currentTool --agent=<id> if you want this)
  • Any flags (halt with reason, pause)
  • Open tasks they hold
  • Deadline if set

Example output:

Swarm <parent-id-short> — 3 agents

agent-auth (running):
  current: Edit src/auth/handler.ts
  tasks: 2 in_progress
  no flags

agent-payments (paused):
  reason: scope drift — investigating
  tasks: 1 claimed (#42)
  paused 3m ago

agent-docs (halted):
  reason: repeated rustdoc — see new instinct
  halted 12m ago

When to use halts vs. messages

  • Halt if the agent is clearly off-track or burning budget with no progress. The halt blocks tool calls; the model will respond once with the halt reason then stop.
  • High-priority message if you want to redirect without stopping — arrives as additionalContext on the next tool call so the model can read it and adjust.

Both are sent via aide CLI:

./.aide/bin/aide agent halt <agent-id> --reason="..."
./.aide/bin/aide message send --from=orchestrator --to=<agent-id> \
  --priority=high "redirect: focus on auth.ts only"

Not for

This skill is read-only orchestration. Use the swarm skill itself to launch new agents or resolve worktrees at the end.

Swarm Mode

Recommended model tier: smart (opus) - this skill requires complex reasoning

Launch parallel agents, each working on a story through SDLC stages.

NON-NEGOTIABLE REQUIREMENTS

  1. SDLC Pipeline is MANDATORY - Every story MUST go through all 5 stages: DESIGN → TEST → DEV → VERIFY → DOCS
  2. Git Worktrees are MANDATORY - Each story agent MUST work in an isolated worktree
  3. VERIFY failures trigger BUILD-FIX loop - If VERIFY fails, invoke /aide:build-fix and re-verify until passing
  4. Swarm MUST conclude with /aide:worktree-resolve - All story branches must be merged before completion

Activation

swarm 3                              → 3 story agents (SDLC mode)
swarm stories "Auth" "Payments"      → Named stories
swarm 2 --flat                       → Flat task mode (legacy)

Architecture

┌─────────────────────────────────────────────────────────────────────────┐
│  ORCHESTRATOR (you)                                                      │
│  1. Decompose work into stories                                          │
│  2. Create worktree per story                                           │
│  3. Spawn story agent per worktree (subagent_type: general-purpose)     │
│  4. Monitor progress via TaskList (DO NOT create tasks yourself!)       │
│  5. Call /aide:worktree-resolve when all stories complete               │
└─────────────────────────────────────────────────────────────────────────┘
                              │
       ┌──────────────────────┼──────────────────────┐
       ▼                      ▼                      ▼
┌─────────────────┐   ┌─────────────────┐   ┌─────────────────┐
│ Story A Agent   │   │ Story B Agent   │   │ Story C Agent   │
│ (worktree-a)    │   │ (worktree-b)    │   │ (worktree-c)    │
├─────────────────┤   ├─────────────────┤   ├─────────────────┤
│ SDLC Pipeline:  │   │ SDLC Pipeline:  │   │ SDLC Pipeline:  │
│ [DESIGN]        │   │ [DESIGN]        │   │ [DESIGN]        │
│ [TEST]          │   │ [TEST]          │   │ [TEST]          │
│ [DEV]           │   │ [DEV]           │   │ [DEV]           │
│ [VERIFY]        │   │ [VERIFY]        │   │ [VERIFY]        │
│ [DOCS]          │   │ [DOCS]          │   │ [DOCS]          │
└─────────────────┘   └─────────────────┘   └─────────────────┘
        │                     │                     │
        └─────────────────────┼─────────────────────┘
                              ▼
┌─────────────────────────────────────────────────────────────────────────┐
│  SHARED NATIVE TASKS (Claude Code TaskList)                             │
│  All agents can see, create, and update tasks                           │
│  Dependencies via blockedBy auto-manage stage ordering                  │
└─────────────────────────────────────────────────────────────────────────┘

Workflow

1. Story Decomposition

First, check for an existing plan from /aide:plan-swarm:

mcp__plugin_aide_aide__decision_get with topic="swarm-plan"

If a plan exists, use its stories directly — skip ad-hoc decomposition. The plan has already been validated for independence and acceptance criteria.

If no plan exists, break the work into independent stories/features:

## Stories

1. **Auth Module** - User authentication with JWT
2. **Payment Processing** - Stripe integration for subscriptions
3. **User Dashboard** - Profile management UI

Each story should be:

  • Independent (can be developed in parallel)
  • Complete (has clear boundaries)
  • Testable (has acceptance criteria)

2. Create Git Worktrees

Each story agent gets an isolated workspace. Create worktrees using git commands:

git worktree add .aide/worktrees/story-auth -b feat/story-auth
git worktree add .aide/worktrees/story-payments -b feat/story-payments
git worktree add .aide/worktrees/story-dashboard -b feat/story-dashboard

Automatic Integration:

  • Worktrees in .aide/worktrees/ are auto-discovered by AIDE hooks
  • When agents spawn, their worktree path is auto-injected into context
  • When agents complete, worktrees are marked as "agent-complete" (ready for merge)
  • Worktree state is tracked in .aide/state/worktrees.json

Naming Convention:

  • Use story-<name> as worktree directory name
  • Use matching agent-<name> as agent_id when spawning
  • Example: story-auth worktree → spawn with agent_id containing "auth"

If worktree creation fails:

  1. Check if branch exists: git branch -a | grep feat/story-auth
  2. Remove stale worktree: git worktree remove .aide/worktrees/story-auth --force
  3. Prune refs: git worktree prune
  4. Retry creation

3. Spawn Story Agents

Launch agents using the Task tool with subagent_type: "general-purpose" (required for Edit/Write access).

IMPORTANT: Task Ownership

  • The ORCHESTRATOR does NOT create SDLC tasks
  • Each SUBAGENT creates and manages its OWN tasks
  • Orchestrator only monitors via TaskList

Each agent manages its own SDLC pipeline.

Task({
  subagent_type: "general-purpose",
  prompt: `You are a story agent working on: Auth Module

Worktree: /path/to/.aide/worktrees/story-auth
Story ID: story-auth
Agent ID: agent-auth

## Your Mission
Implement the Auth Module through the full SDLC pipeline.

## SDLC Pipeline
You will create and execute these stages IN ORDER:

### Stage 1: DESIGN
Use the /aide:design skill (or follow its workflow).
Output: Technical design with interfaces, decisions, acceptance criteria.

### Stage 2: TEST
Use the /aide:test skill.
Write failing tests based on acceptance criteria from DESIGN.

### Stage 3: DEV
Use the /aide:implement skill.
Make all tests pass with minimal implementation.

### Stage 4: VERIFY
Use the /aide:verify skill.
Run full test suite, lint, type check. Must all pass.

**IF VERIFY FAILS:**
1. Invoke /aide:build-fix to address failures
2. Re-run /aide:verify
3. Repeat until VERIFY passes
4. Only then proceed to DOCS

### Stage 5: DOCS
Use the /aide:docs skill.
Update documentation to match implementation.

## Task Management
Use native Claude Code task tools to track your progress:

1. Create all stage tasks upfront:
   TaskCreate: "[story-auth][DESIGN] Design auth module"
   TaskCreate: "[story-auth][TEST] Write auth tests" (blockedBy: DESIGN task)
   TaskCreate: "[story-auth][DEV] Implement auth" (blockedBy: TEST task)
   TaskCreate: "[story-auth][VERIFY] Verify auth" (blockedBy: DEV task)
   TaskCreate: "[story-auth][DOCS] Document auth" (blockedBy: VERIFY task)

2. As you start each stage:
   TaskUpdate: taskId=X, status=in_progress, owner=agent-auth

3. As you complete each stage:
   TaskUpdate: taskId=X, status=completed

## Coordination

**Messaging (MCP tools):**
- Send status: \`message_send\` with from=agent-auth, type="status", content="[DESIGN] complete"
- Send blocker: \`message_send\` with from=agent-auth, type="blocker", content="Need API schema"
- Check inbox: \`message_list\` with agent_id=agent-auth
- Acknowledge: \`message_ack\` with message_id=N, agent_id=agent-auth

**At each stage transition:**
1. Check messages via \`message_list\`
2. Acknowledge and act on any requests
3. Send \`status\` message with new stage

**Shared state (MCP + CLI):**
- Check decisions: \`mcp__plugin_aide_aide__decision_get\` (MCP read)
- Record decisions: \`./.aide/bin/aide decision set <topic> "<decision>"\` (CLI write)
- Share discoveries: \`./.aide/bin/aide memory add --category=discovery --tags=project:<name>,session:\${AIDE_SESSION_ID},source:discovered "<finding>"\` (CLI write)

**Binary location:** The aide binary is at \`.aide/bin/aide\`. If it's on your \`$PATH\`, you can use \`aide\` directly.

## Completion
When all 5 stages are complete:
1. Verify all tasks show completed
2. Ensure all changes are committed
3. Send completion message: \`message_send\` with from=agent-auth, type="completion"
4. Report: "Story complete: Auth Module"
\`
});

Mid-flight control

Once stories are launched, you can intervene without killing/restarting agents. All control writes go through aide agent and reach the subagent on its next tool call (worst case ≈ duration of an in-flight Bash/Edit). The signal hook (src/hooks/agent-signals.ts) gates on a subagent's parent_session being set — orchestrator/solo sessions see zero overhead.

  • Inspect: ./.aide/bin/aide agent list --parent=$(./.aide/bin/aide reflect current-session) --json
  • Halt cleanly: ./.aide/bin/aide agent halt <agent-id> --reason="repeated rustdoc — see new instinct" Next tool call is blocked with the reason surfaced to the model.
  • Pause / resume: ./.aide/bin/aide agent pause <agent-id> then ./.aide/bin/aide agent resume <agent-id>. Paused agents can only call message_send/message_list/message_ack/state_get.
  • Mid-flight instruction: ./.aide/bin/aide message send --from=orchestrator --to=<agent-id> --priority=high "scope drifted — focus on auth.ts only". Surfaced as additionalContext on the subagent's next tool call.
  • Soft deadline: ./.aide/bin/aide agent deadline <agent-id> 30m — warns at < 5min remaining; halts at 0.

When to intervene vs. let it run: prefer letting agents finish a stage and review at the next checkpoint. Use mid-flight halt only for clearly-wrong directions (infinite loops, scope drift, depleted budget with no progress).

Monitor Progress

Use TaskList to see all story progress:

TaskList

Example output:

#10 [completed] [story-auth][DESIGN] Design auth module (agent-auth)
#11 [completed] [story-auth][TEST] Write auth tests (agent-auth)
#12 [in_progress] [story-auth][DEV] Implement auth (agent-auth)
#13 [pending] [story-auth][VERIFY] Verify auth [blocked by #12]
#14 [pending] [story-auth][DOCS] Document auth [blocked by #13]
#20 [in_progress] [story-payments][DESIGN] Design payment module (agent-payments)

5. Merge Results

When all stories complete, use /aide:worktree-resolve:

# Verify all tasks complete
TaskList  # Should show all [completed]

# Check for blockers (use MCP tool)
mcp__plugin_aide_aide__memory_list with category=blocker

# Merge worktrees
/aide:worktree-resolve

SDLC Stage Reference

StageSkillCreatesDepends On
DESIGN/aide:designInterfaces, decisions, acceptance criteria-
TEST/aide:testFailing testsDESIGN
DEV/aide:implementPassing implementationTEST
VERIFY/aide:verifyQuality validationDEV
DOCS/aide:docsUpdated documentationVERIFY

VERIFY → BUILD-FIX Loop

                    ┌──────────────┐
                    │    VERIFY    │
                    └──────┬───────┘
                           │
              ┌────────────┴────────────┐
              │                         │
           PASS                       FAIL
              │                         │
              ▼                         ▼
         ┌────────┐              ┌──────────────┐
         │  DOCS  │              │  BUILD-FIX   │
         └────────┘              └──────┬───────┘
                                        │
                                        └──────► back to VERIFY

If VERIFY fails:

  1. /aide:build-fix to fix issues
  2. Re-run /aide:verify
  3. Repeat until passing
  4. Then proceed to DOCS

Story Agent Instructions Template

When spawning story agents, include:

You are story agent [AGENT-ID] working in worktree [PATH].

## Story

[Story name and description]

## SDLC Pipeline

Execute these stages in order. For each stage:

1. Create task with TaskCreate (set blockedBy for dependencies)
2. Claim task with TaskUpdate (owner=your-id, status=in_progress)
3. Execute stage using appropriate skill
4. Mark complete with TaskUpdate (status=completed)

### Stage Tasks to Create

TaskCreate({
subject: "[STORY-ID][DESIGN] Design [feature]",
description: "Technical design with interfaces and acceptance criteria",
activeForm: "Designing [feature]"
})

TaskCreate({
subject: "[STORY-ID][TEST] Write tests for [feature]",
description: "Failing tests based on acceptance criteria",
activeForm: "Writing tests"
})
// ... set blockedBy to DESIGN task ID

TaskCreate({
subject: "[STORY-ID][DEV] Implement [feature]",
description: "Make tests pass with minimal code",
activeForm: "Implementing [feature]"
})
// ... set blockedBy to TEST task ID

TaskCreate({
subject: "[STORY-ID][VERIFY] Verify [feature]",
description: "Full test suite, lint, type check",
activeForm: "Verifying [feature]"
})
// ... set blockedBy to DEV task ID

TaskCreate({
subject: "[STORY-ID][DOCS] Document [feature]",
description: "Update documentation",
activeForm: "Documenting [feature]"
})
// ... set blockedBy to VERIFY task ID

## Coordination

**Messaging (MCP tools):**

- Send status: `message_send` with from=[AGENT-ID], type="status", content="[STAGE] complete"
- Send blocker: `message_send` with from=[AGENT-ID], type="blocker", content="description"
- Check inbox: `message_list` with agent_id=[AGENT-ID]
- Acknowledge: `message_ack` with message_id=N, agent_id=[AGENT-ID]

**At each stage transition:**

1. Check messages via `message_list`
2. Acknowledge and act on any requests
3. Send `status` message with new stage name

**Shared state:**

- Check existing decisions: `mcp__plugin_aide_aide__decision_get` (MCP read)
- Record new decisions: `./.aide/bin/aide decision set <topic> "<decision>"` (CLI write)
- Share discoveries: `./.aide/bin/aide memory add --category=discovery --tags=project:<name>,session:${AIDE_SESSION_ID},source:discovered "<finding>"` (CLI write)

## VERIFY Failure Handling

If VERIFY stage fails:

1. DO NOT proceed to DOCS
2. Invoke /aide:build-fix to address failures
3. Re-run /aide:verify
4. Repeat until VERIFY passes
5. Only then proceed to DOCS

## Completion

All stages must complete. When done:

1. All 5 tasks show [completed]
2. VERIFY must have passed (not skipped)
3. All changes committed to your worktree branch
4. Send completion: `message_send` with from=[AGENT-ID], type="completion", content="Story [STORY-ID] complete"
5. Report: "Story [STORY-ID] complete - ready for merge"

Flat Mode (Legacy)

For non-code tasks or simple work, use --flat:

swarm 3 --flat

This uses the original task-grabbing model without SDLC stages.

Coordination via aide

Messages (MCP tools — primary coordination mechanism):

# Send status update (broadcast)
message_send: from="agent-auth", type="status", content="[DESIGN] complete, starting TEST"

# Send direct message
message_send: from="agent-auth", to="agent-payments", type="request", content="Need payment API schema"

# Check inbox
message_list: agent_id="agent-auth"

# Acknowledge after reading
message_ack: message_id=42, agent_id="agent-auth"

Decisions (shared across agents):

# Write (CLI)
./.aide/bin/aide decision set "auth-strategy" "JWT with refresh tokens"

# Read (MCP) - use mcp__plugin_aide_aide__decision_get with topic="auth-strategy"

Memory (shared discoveries):

./.aide/bin/aide memory add --category=discovery --tags=project:<name>,session:${AIDE_SESSION_ID},source:discovered "User model needs email validation"

Memory Hygiene

When any agent stores memories (discoveries, blockers, session summaries), always:

  1. Include source: tag — Use source:discovered for findings, source:inferred for deductions
  2. Include scope tags — Add project:<name>,session:<id> (get project name from git remote or directory; session ID from $AIDE_SESSION_ID or $CLAUDE_SESSION_ID)
  3. Verify codebase claims before storing — If a memory references a file, function, or path, confirm it exists first. See the memorise skill for the full verification workflow.
  4. Never use scope:global unless storing a user preference

This applies to all memory add commands in agent prompts, coordination examples, and the orchestrator memory section above.

OpenCode Mode

OpenCode has native todowrite/todoread for per-agent progress tracking, and a task tool for spawning subagents. However, OpenCode's todos are session-private — they are NOT shared across agents. For multi-agent coordination, use aide tasks (MCP tools) as the shared task system.

Task System Roles (OpenCode)

SystemRoleScope
aide tasks (MCP: task_create, task_list, task_claim, task_complete)Shared coordination — all agents see the same boardCross-session, persistent
todowrite (native)Personal progress tracking within each agentSession-private, per-agent
aide messages (MCP: message_send, message_list)Real-time coordination, status broadcasts, blockersCross-session

Setup

  1. Create worktrees as normal (one per story)
  2. Launch separate OpenCode terminal sessions, one per story
  3. Each session works in its assigned worktree directory

Orchestrator Workflow

The orchestrator (human or primary session):

  1. Decompose stories (use /aide:plan-swarm first)
  2. Create worktrees
  3. Create aide tasks for all SDLC stages upfront:
    task_create: title="[story-auth][DESIGN] Design auth module"
    task_create: title="[story-auth][TEST] Write auth tests"
    task_create: title="[story-auth][DEV] Implement auth"
    task_create: title="[story-auth][VERIFY] Verify auth"
    task_create: title="[story-auth][DOCS] Document auth"
    
  4. Launch terminal sessions with instructions (include agent ID and story assignment)
  5. Monitor progress via task_list (MCP tool) or ./.aide/bin/aide task list (CLI)
  6. When all tasks show done, run /aide:worktree-resolve

Story Agent Workflow (OpenCode)

Each story agent follows the same SDLC pipeline. Use aide tasks for shared tracking and native todowrite for personal step-by-step progress:

## Per SDLC Stage:

1. Claim the stage task:
   task_claim: task_id=<id>, agent_id=agent-auth

2. Use todowrite for personal tracking:
   todowrite: [{"content": "Design interfaces for auth", "status": "in_progress", "priority": "high"}]

3. Execute the stage (use appropriate /aide: skill)

4. Complete the aide task:
   task_complete: task_id=<id>, result="Designed JWT auth with refresh tokens"

5. Send status message:
   message_send: from="agent-auth", type="status", content="[DESIGN] complete"

6. Check for messages from other agents:
   message_list: agent_id="agent-auth"

Note: aide tasks do not have blockedBy dependency chaining like Claude Code native tasks. Stage ordering is enforced by the SDLC pipeline instructions — each agent processes stages sequentially (DESIGN → TEST → DEV → VERIFY → DOCS).

Coordination (OpenCode)

# Shared task board — all agents see the same tasks
task_list                                          # View all tasks
task_list: status="pending"                        # View unclaimed work

# Messages — real-time coordination
message_send: from="agent-auth", type="status", content="[DESIGN] complete, starting TEST"
message_send: from="agent-auth", to="agent-payments", type="request", content="Need payment API schema"
message_list: agent_id="agent-auth"
message_ack: message_id=42, agent_id="agent-auth"

# State — supplementary progress tracking
./.aide/bin/aide state set "agent-auth:stage" "TEST"

# Decisions and discoveries — shared knowledge
mcp__plugin_aide_aide__decision_get with topic="auth-strategy"
./.aide/bin/aide decision set "auth-strategy" "JWT with refresh tokens"
./.aide/bin/aide memory add --category=discovery --tags=project:<name>,session:${AIDE_SESSION_ID},source:discovered "User model needs email validation"

Completion (MANDATORY STEPS)

Swarm completion checklist - ALL REQUIRED:

Step 1: Verify All Stories Complete

# Claude Code:
TaskList  # All story tasks must show [completed]

# OpenCode:
task_list  # All aide tasks must show [done]
  • Every story must have completed all 5 SDLC stages
  • No tasks should be [pending] or [in_progress]

Step 2: Check for Blockers

Use mcp__plugin_aide_aide__memory_list with category=blocker

  • If blockers exist, resolve them before proceeding
  • Use /aide:build-fix for any remaining build/test issues

Step 3: Final Verification

Run verification on each worktree:

cd .aide/worktrees/story-X && npm test && npm run build
  • If any fail, invoke /aide:build-fix and re-verify

Step 4: Merge Worktrees (MANDATORY)

YOU MUST invoke /aide:worktree-resolve - this is not optional.

/aide:worktree-resolve

This skill will:

  • Merge each story branch into main
  • Handle any merge conflicts
  • Clean up worktrees

Step 5: Record Session

Only after successful merge, record the swarm session (see Orchestrator Memory below).

Orchestrator Memory

After swarm completes, record the session using the CLI:

./.aide/bin/aide memory add --category=session --tags=swarm,sdlc,project:<name>,session:${AIDE_SESSION_ID},source:discovered "## Swarm: [Brief Description]

### Stories Completed
- Story A: [outcome]
- Story B: [outcome]
- Story C: [outcome]

### Key Decisions Made
- [decision]: [rationale]

### Files Changed
- [summary of changes per story]

### Merge Status
- [branches merged successfully / any conflicts]"

Test Mode

Recommended model tier: balanced (sonnet) - this skill performs straightforward operations

Write comprehensive tests and run test suites.

Prerequisites

Before starting:

  • Identify the code to be tested (function, module, feature)
  • Understand the testing framework used in the project

Workflow

Step 1: Check Project Testing Decisions

Use the mcp__plugin_aide_aide__decision_get tool with topic testing to check for testing framework decisions.

Common frameworks by language:

  • TypeScript/JavaScript: Vitest, Jest, Mocha
  • Go: built-in go test
  • Python: pytest, unittest

Step 2: Discover Existing Test Patterns

Use Glob to find test files:

  • Pattern: **/*.test.ts, **/*.spec.ts (TypeScript)
  • Pattern: **/*_test.go (Go)
  • Pattern: **/test_*.py, **/*_test.py (Python)

Use Grep to find test patterns in existing test files:

  • Grep pattern="describe\(" include="*.test.*" — find test suites
  • Grep pattern="it\(|test\(" include="*.test.*" — find test cases

Read an existing test file to understand:

  • Import patterns
  • Setup/teardown patterns
  • Mocking approach
  • Assertion style

Step 3: Analyze Target Code

Use mcp__plugin_aide_aide__code_symbols with the target file path to get function signatures. Use mcp__plugin_aide_aide__code_search to find related types.

Identify:

  • Input parameters and types
  • Return type
  • Side effects
  • Dependencies to mock
  • Edge cases

Step 4: Write Tests

Follow the project's testing conventions. Cover these scenarios:

Test Categories:

  1. Happy path - Normal, expected inputs
  2. Edge cases - Empty, null, boundary values
  3. Error cases - Invalid inputs, expected failures
  4. Async behavior - If applicable

Naming convention:

  • Descriptive names that explain what is being tested
  • Format: "should [expected behavior] when [condition]"

Step 5: Run Tests

# TypeScript/JavaScript
npm test                    # Run all tests
npm test -- --grep "name"   # Run specific test
npm run test:coverage       # Run with coverage

# Go
go test ./...               # Run all tests
go test -v ./pkg/...        # Verbose output
go test -cover ./...        # With coverage

# Python
pytest                      # Run all tests
pytest -v                   # Verbose
pytest --cov                # With coverage

Step 6: Verify Coverage

# Check coverage report
npm run test:coverage

# Go
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

Coverage targets:

  • New code: aim for >80%
  • Critical paths: aim for >90%
  • Focus on meaningful tests, not just coverage numbers

Failure Handling

FailureAction
Test imports failCheck path aliases, ensure test config matches main
Mock not workingVerify mock setup, check dependency injection
Async test timeoutAdd proper await, increase timeout if needed
Flaky testCheck for shared state, timing issues, or external deps
Coverage too lowAdd edge case tests, error path tests

Test Structure Templates

TypeScript/JavaScript (Vitest/Jest)

import { describe, it, expect, beforeEach, vi } from "vitest";
import { functionToTest } from "./module";

describe("functionToTest", () => {
  beforeEach(() => {
    // Reset state before each test
    vi.clearAllMocks();
  });

  it("should return expected result for valid input", () => {
    const result = functionToTest("valid input");
    expect(result).toBe("expected output");
  });

  it("should handle empty input", () => {
    const result = functionToTest("");
    expect(result).toBe("");
  });

  it("should throw error for null input", () => {
    expect(() => functionToTest(null)).toThrow("Input required");
  });

  it("should handle async operation", async () => {
    const result = await functionToTest("async input");
    expect(result).resolves.toBe("async output");
  });
});

Go

func TestFunctionName(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    string
        wantErr bool
    }{
        {"valid input", "input", "expected", false},
        {"empty input", "", "", false},
        {"invalid input", "bad", "", true},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := FunctionName(tt.input)
            if (err != nil) != tt.wantErr {
                t.Errorf("error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if got != tt.want {
                t.Errorf("got = %v, want %v", got, tt.want)
            }
        })
    }
}

Python

import pytest
from module import function_to_test

class TestFunctionToTest:
    def test_valid_input(self):
        assert function_to_test("input") == "expected"

    def test_empty_input(self):
        assert function_to_test("") == ""

    def test_invalid_input_raises(self):
        with pytest.raises(ValueError):
            function_to_test(None)

    @pytest.fixture
    def mock_dependency(self, mocker):
        return mocker.patch("module.dependency")

MCP Tools

  • mcp__plugin_aide_aide__code_search - Find existing tests, patterns, types
  • mcp__plugin_aide_aide__code_symbols - Understand function signatures to test
  • mcp__plugin_aide_aide__decision_get - Check testing framework decisions

Verification Criteria

Before completing:

  • All new tests pass
  • Existing tests still pass
  • Coverage meets project standards
  • Tests are deterministic (not flaky)
  • Tests follow project conventions

Output Format

## Tests Added

### Files

- `path/to/file.test.ts` - 5 tests for UserService

### Test Cases

1. should create user with valid data
2. should reject duplicate email
3. should hash password before saving
4. should handle empty name
5. should validate email format

### Coverage

- New code: 92%
- Total project: 84%

### Verification

- All tests: PASS
- No flaky tests observed

Verify Mode

Recommended model tier: smart (opus) - this skill requires complex reasoning

Active QA verification: run all quality checks and report pass/fail status.

Purpose

This is the VERIFY stage of the SDLC pipeline. Implementation is complete. Your job is to run comprehensive validation and report results.

This is different from review: Review is read-only analysis. Verify is active execution of quality checks.

Verification Checklist

Run ALL of the following. Each must pass.

1. Full Test Suite

# TypeScript/JavaScript
npm test

# Go
go test ./...

# Python
pytest

Expected: All tests pass, no failures, no skipped tests.

2. Type Checking

# TypeScript
npx tsc --noEmit

# Go (implicit in build)
go build ./...

# Python (if using mypy)
mypy .

Expected: No type errors.

3. Linting

# TypeScript/JavaScript
npm run lint

# Go
go vet ./...
golangci-lint run

# Python
ruff check .

Expected: No lint errors. Warnings acceptable if pre-existing.

4. Build

# TypeScript/JavaScript
npm run build

# Go
go build ./...

# Python
python -m py_compile *.py

Expected: Build succeeds without errors.

5. Debug Artifact Check

Search for common debug artifacts that shouldn't be committed:

# Console logs (JS/TS)
Grep for "console.log" in changed files

# Debug prints (Go)
Grep for "fmt.Println" or "log.Print" that look like debug

# Python debug
Grep for "print(" or "pdb" or "breakpoint()"

# TODO/FIXME comments
Grep for "TODO" or "FIXME" in changed files

# Debugger statements
Grep for "debugger" in JS/TS files

Expected: No debug artifacts in new code. Pre-existing ones noted but not blocking.

6. Uncommitted Changes Check

git status

Expected: Working directory clean, or only expected files modified.

Workflow

Step 1: Run All Checks

Execute each check in sequence, capturing output:

# Run all checks, capture results
npm test 2>&1 | head -50
npm run lint 2>&1 | head -50
npx tsc --noEmit 2>&1 | head -50
npm run build 2>&1 | head -50

Step 2: Check for Debug Artifacts

# Search for debug code in recently changed files
git diff --name-only HEAD~1 | xargs grep -l "console.log\|debugger" 2>/dev/null || true

Step 3: Compile Results

Create a verification report.

Output Format

All Checks Pass

## Verification Report: PASS

### Tests
- Status: PASS
- Total: 42
- Passed: 42
- Failed: 0

### Type Check
- Status: PASS
- Errors: 0

### Lint
- Status: PASS
- Errors: 0
- Warnings: 3 (pre-existing)

### Build
- Status: PASS

### Debug Artifacts
- Status: CLEAN
- No debug code found in new files

### Verdict: READY FOR DOCS STAGE

Some Checks Fail

## Verification Report: FAIL

### Tests
- Status: FAIL
- Total: 42
- Passed: 40
- Failed: 2
- Failures:
  - `UserService.test.ts:45` - expected 200, got 401
  - `AuthMiddleware.test.ts:23` - timeout after 5000ms

### Type Check
- Status: PASS

### Lint
- Status: FAIL
- Errors:
  - `src/user.ts:12` - 'unused' is defined but never used

### Build
- Status: PASS

### Debug Artifacts
- Status: WARNING
- Found:
  - `src/user.ts:34` - console.log("debug user:", user)

### Verdict: NEEDS BUILD-FIX

Issues to resolve:
1. Fix 2 failing tests
2. Remove console.log on line 34
3. Fix lint error (remove unused variable)

Failure Handling

Tests Fail

  1. Document which tests fail and why
  2. Do NOT fix them yourself (that's BUILD-FIX stage (via /aide:build-fix))
  3. Report failures clearly
  4. Verdict: FAIL, needs BUILD-FIX stage (via /aide:build-fix)

Lint Errors

  1. Document all lint errors
  2. Distinguish new errors from pre-existing
  3. New errors = FAIL
  4. Pre-existing warnings = PASS with notes

Type Errors

  1. Document all type errors with file:line
  2. Always FAIL on type errors
  3. Type errors must be fixed before proceeding

Build Fails

  1. Document build error
  2. Always FAIL on build errors
  3. Critical blocker for release

Decision Tree

All tests pass?
├── No → FAIL (needs BUILD-FIX)
└── Yes → Type check pass?
          ├── No → FAIL (needs BUILD-FIX)
          └── Yes → Lint pass?
                    ├── No (new errors) → FAIL (needs BUILD-FIX)
                    └── Yes/Warnings only → Build pass?
                                           ├── No → FAIL (needs BUILD-FIX)
                                           └── Yes → Debug artifacts?
                                                     ├── Found → FAIL (needs cleanup)
                                                     └── Clean → PASS

Completion

On PASS

Verification complete: ALL CHECKS PASS
Ready for DOCS stage.

On FAIL

Verification complete: CHECKS FAILED
Returning to BUILD-FIX stage (via `/aide:build-fix`).

Issues:
1. [list of issues]

When FAIL, the BUILD-FIX stage (via /aide:build-fix) addresses issues, then VERIFY runs again.

Integration with SDLC Pipeline

[DESIGN] → [TEST] → [DEV] → [VERIFY] → [DOCS]
                               ↑
                          YOU ARE HERE
                               │
                    ┌──────────┴──────────┐
                    │                     │
                  PASS                  FAIL
                    │                     │
                    ▼                     ▼
                 [DOCS]               [BUILD-FIX] → [VERIFY]
  • Input: Completed implementation from DEV stage
  • Output: Pass/Fail report with specifics
  • On Pass: Proceed to DOCS stage
  • On Fail: Return to BUILD-FIX stage (via /aide:build-fix), then re-verify

Worktree Resolution

Recommended model tier: balanced (sonnet) - this skill performs straightforward operations

Merge all swarm worktrees back into the main branch after testing.

Workflow

1. List Active Worktrees

git worktree list

Check the AIDE worktree state file for metadata and status:

cat .aide/state/worktrees.json

Worktree Status Values:

  • active - Agent is still working on this worktree
  • agent-complete - Agent finished, ready for merge review
  • merged - Successfully merged to main

Only merge worktrees with status agent-complete.

Example state file:

{
  "active": [
    {
      "name": "story-auth",
      "path": ".aide/worktrees/story-auth",
      "branch": "feat/story-auth",
      "taskId": "story-auth",
      "agentId": "agent-auth",
      "status": "agent-complete",
      "createdAt": "2026-02-07T...",
      "completedAt": "2026-02-07T..."
    }
  ],
  "baseBranch": "main"
}

2. For Each Worktree Branch

Run these steps for every feat/* branch from swarm:

a) Test the Branch
# Checkout the worktree
cd .aide/worktrees/<name>

# Run tests
npm test  # or appropriate test command

# Run linting
npm run lint  # or appropriate lint command

# Check build
npm run build  # if applicable
b) Review Changes
# Back in main repo
git log main..feat/<name> --oneline
git diff main...feat/<name> --stat
c) Check Merge Compatibility
# Dry-run merge check
git merge-tree $(git merge-base main feat/<name>) main feat/<name>

If conflicts shown, note them for manual resolution.

3. Merge Clean Branches

For branches that pass tests and have no conflicts:

git checkout main
git merge feat/<branch-name> --no-edit

4. Handle Conflicts (Intelligent Resolution)

When merge conflicts occur, do not use -X theirs or -X ours - these blindly discard changes.

Instead, resolve conflicts intelligently:

Step 1: Attempt merge and identify conflicts
git merge feat/<name> --no-edit
# If conflicts occur, git will list the conflicted files
Step 2: For each conflicted file, read and analyze
# Read the file with conflict markers
cat <conflicted-file>

The conflict markers show:

<<<<<<< HEAD
[changes from main branch]
=======
[changes from feature branch]
>>>>>>> feat/<name>
Step 3: Resolve as a code review expert

Act as an expert code reviewer. For each conflict:

  1. Analyze both code paths - What was each change trying to achieve?
  2. Understand the intent - Are they complementary, overlapping, or contradictory?
  3. Modify the feature branch locally to incorporate main's changes while preserving the feature's logic
  4. Edit the file to remove conflict markers and combine both sets of functionality correctly

The resolution must:

  • Remove all conflict markers (<<<<<<<, =======, >>>>>>>)
  • Preserve the functional intent of BOTH changes
  • Be syntactically and semantically correct
  • Maintain code style consistency
Step 4: Verify and complete
# Stage the resolved files
git add <resolved-file>

# Run tests to verify the resolution works
npm test  # or appropriate test command

# If tests pass, complete the merge
git commit --no-edit
Step 5: Handle failure

If you cannot resolve the conflict (logic is contradictory, tests fail after resolution, or changes are too complex):

  1. Abort the merge to restore clean state:

    git merge --abort
    
  2. Record the failure using aide messaging:

    ./.aide/bin/aide message send --from=resolver --to=orchestrator "CONFLICT: Cannot merge feat/<name> - <brief reason>"
    

Binary location: The aide binary is at .aide/bin/aide. If it's on your $PATH, you can use aide directly.

  1. Skip this branch and continue with remaining branches

  2. Report at completion - list unmerged branches in the final summary for manual review

Do NOT:

  • Force through a broken resolution
  • Use -X theirs or -X ours to blindly pick one side
  • Get stuck - always abort and report if resolution fails
Example Resolution

Conflict:

<<<<<<< HEAD
function getUser(id: string): User {
  return db.users.find(u => u.id === id);
}
=======
function getUser(id: string): User | null {
  const user = db.users.find(u => u.id === id);
  return user ?? null;
}
>>>>>>> feat/null-safety

Analysis:

  • HEAD: Basic lookup returning User
  • Feature: Added null-safety with explicit null return

Resolution:

function getUser(id: string): User | null {
  const user = db.users.find((u) => u.id === id);
  return user ?? null;
}

Feature branch improved null safety - this is additive, keep it.

5. Cleanup

After all branches merged:

# Remove each worktree
git worktree remove .aide/worktrees/<name>

# Delete merged branches
git branch -d feat/<name>

# Prune any orphaned worktrees
git worktree prune

# Clear state file
rm .aide/state/worktrees.json

6. Final Verification

# Ensure all tests pass on main
git checkout main
npm test
npm run lint
npm run build

# Check no worktrees remain
git worktree list  # Should only show main

Summary Report

After resolution, report:

## Worktree Resolution Complete

### Merged Branches
- feat/task1-agent1: ✓ (3 files, +150/-20)
- feat/task2-agent2: ✓ (5 files, +280/-45)

### Skipped (conflicts/failures)
- feat/task3-agent3: Test failures in auth.test.ts

### Final Status
- All tests passing: ✓
- Lint clean: ✓
- Build successful: ✓

Quick Commands

# List all feat branches from swarm
git branch --list 'feat/*'

# Merge all clean branches at once (risky - prefer one at a time)
for branch in $(git branch --list 'feat/*' | tr -d ' '); do
  git merge $branch --no-edit || echo "Conflict in $branch"
done

# Bulk cleanup worktrees
git worktree list | grep '.aide/worktrees' | awk '{print $1}' | xargs -I {} git worktree remove {}

# Bulk delete feat branches (only if merged)
git branch --list 'feat/*' | xargs git branch -d

Failure Handling

If merge fails:

  1. Abort immediately: git merge --abort
  2. Record the failure:
    ./.aide/bin/aide message send --from=resolver --to=orchestrator "Merge failed: feat/<name> - <reason>"
    
  3. Continue with remaining branches - do not block on one failure
  4. Include in final report - list all failed branches with reasons

If tests fail after merge:

  1. Revert the merge: git revert -m 1 HEAD
  2. Record the failure with aide messaging
  3. Continue with other branches

If worktree removal fails:

# Force remove if necessary
git worktree remove --force .aide/worktrees/<name>

# Prune any orphaned entries
git worktree prune

Verification Criteria

After each merge:

# Verify merge commit exists
git log -1 --oneline

# Verify no uncommitted changes
git status --porcelain  # Should be empty

# Verify tests pass
npm test  # or appropriate test command

After full resolution:

# Verify all worktrees removed
git worktree list  # Should only show main worktree

# Verify all feature branches deleted (or list unmerged)
git branch --list 'feat/*'  # Should be empty for merged branches

# Verify main is clean
git status

# Verify final tests pass
npm test && npm run lint && npm run build

Safety Notes

  • Always test each branch before merging
  • Merge one at a time to isolate issues
  • Keep backups - create a tag before bulk operations: git tag pre-swarm-merge
  • Don't force delete - use -d not -D to prevent deleting unmerged work
  • Report all failures - never silently skip branches

MCP servers 1

Sponsors

Details

Marketplace
jmylchreest/aide
Category
Productivity