orban avatar

intent-layer

Hierarchical AGENTS.md infrastructure for AI-navigable codebases. Create CLAUDE.md/AGENTS.md files that help AI agents navigate your codebase like senior engineers.

version
1.0.1
GitHub stars
8

Install

/plugin install intent-layer@orban

Run it inside Claude Code after adding the marketplace with /plugin marketplace add orban/intent-layer.

Contents

Discovered from source

Skills 7

Compound Learning Skill

TL;DR: Capture and triage learnings at the end of a work session. Runs conversation analysis, surfaces candidates, and integrates with proper scope routing.


When to Use

Run /intent-layer-compound after:

  • Completing a feature or bug fix
  • Finishing any significant work session
  • Discovering non-obvious behaviors or gotchas
  • When you want to capture learnings before ending the session

Three-Layer Workflow

Layer 1: AI Conversation Scan

Before prompting for manual capture, analyze the conversation for learning signals.

Scan for these patterns:

PatternExample PhrasesLearning Type
User corrections"actually...", "no, you should...", "that's wrong"pitfall
Discoveries"interesting...", "I didn't know...", "turns out..."insight
Better approaches"a better way is...", "instead, try..."pattern
Unexpected behaviors"but it returned...", "weird, it..."pitfall
Missing checks"should have verified...", "forgot to check..."check

For each candidate found:

  1. Extract the relevant conversation snippet
  2. Identify the learning type
  3. Determine affected directory (if identifiable from context)
  4. Present to user for confirmation

Example output:

Found 3 potential learnings in this conversation:

1. [pitfall] User corrected assumption about API response format
   Context: "Actually, the API returns a list when there are multiple results..."
   Affected: src/api/

2. [insight] Discovery about caching behavior
   Context: "Turns out the cache invalidates on every deploy..."
   Affected: (workflow-level)

3. [check] Missing verification identified
   Context: "Should have verified the schema before migration..."
   Affected: src/db/

Layer 2: Structured Prompts

After AI-surfaced candidates are reviewed, prompt for additional learnings:

Prompt sequence:

  1. "Were there any corrections you made to my assumptions?"
  2. "Did we discover any unexpected behaviors?"
  3. "Are there any better approaches we figured out?"
  4. "Any checks that would have helped if done earlier?"

For each "yes" response:

  • Use the scan prompt from prompts/scan.md to extract details
  • Capture via the existing capture_mistake.sh with pre-filled fields
  • Assign appropriate learning type

Layer 3: Direct Integration

After candidates are confirmed, integrate each one directly using learn.sh:

For each confirmed candidate:

${CLAUDE_PLUGIN_ROOT}/scripts/learn.sh \
  --project [PROJECT_PATH] \
  --path [AFFECTED_PATH] \
  --type [pitfall|check|pattern|insight] \
  --title "[TITLE]" \
  --detail "[DETAIL]"

learn.sh handles deduplication automatically — if the learning already exists (≥60% word overlap), it exits with code 2 and reports "duplicate skipped".

Report outcomes to the user:

  • Exit 0: "✓ Integrated into [AGENTS.md path]"
  • Exit 2: "⊘ Duplicate skipped (already documented)"
  • Exit 1: "✗ Error: [message]"

Show summary of what was integrated and where when all candidates are processed.


Resources

Scripts Used

ScriptPurpose
learn.shDirect-write learning to AGENTS.md (dedup-gated)
capture_mistake.shCreate learning report for pending queue (swarm use)

Prompts

PromptPurpose
prompts/scan.mdConversation analysis for learning signals

Quick Start

/intent-layer-compound

Or with explicit project path:

/intent-layer-compound /path/to/project

Example Session

$ /intent-layer-compound

=== Intent Layer Compound Learning ===

[Layer 1: Conversation Scan]
Analyzing conversation for potential learnings...

Found 2 potential learnings:

1. [pitfall] API response format varies
   "Actually, the API can return either a dict or a list..."
   Path: src/api/

   Is this worth documenting? [y/n/edit]: y

2. [insight] Deploy triggers cache invalidation
   "Turns out the cache clears on every deploy..."
   Path: (workflow-level)

   Is this worth documenting? [y/n/edit]: y

[Layer 2: Additional Prompts]
Any other corrections you made to my assumptions? [y/n]: n
Any unexpected behaviors discovered? [y/n]: n
Any better approaches figured out? [y/n]: n

[Layer 3: Direct Integration]
Integrating 2 confirmed learnings...

1. ✓ pitfall added to ## Pitfalls in src/api/AGENTS.md
2. ✓ insight added to ## Context in CLAUDE.md

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Summary
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  Integrated: 2
  Duplicates: 0
  Errors:     0

Compound learning complete!

Scope Routing

The compound skill routes learnings to the appropriate location:

Learning captured
       │
       └─── Is it workflow-level? (insight, cross-cutting)
                    │
          ┌────────┴────────┐
          │                 │
         Yes                No
          │                 │
          ▼                 ▼
    Root CLAUDE.md    Covering AGENTS.md
    (global scope)    (local scope)

Global Scope (Root CLAUDE.md)

Use for:

  • Workflow insights (build process, deployment, testing)
  • Cross-cutting patterns that apply everywhere
  • Project-wide conventions and decisions
  • Learnings that don't belong to any specific directory

Local Scope (Covering AGENTS.md)

Use for:

  • Code-specific pitfalls
  • API behavior quirks
  • Module-specific patterns
  • Checks for particular operations

Integration with Hooks

The compound skill works with the existing learning loop hooks:

  • PostToolUseFailure: Auto-captures failures → pending/
  • Stop hook: Prompts for learnings if configured
  • /intent-layer-compound: End-of-session synthesis

Run /intent-layer-compound to process any auto-captured learnings alongside manual capture.

Intent Layer Health Check

Quick validation of Intent Layer health before starting work. Run this at session start to catch issues early.

Quick Start

# Quick check (default, <30 seconds)
${CLAUDE_PLUGIN_ROOT}/scripts/audit_intent_layer.sh --quick

# Full check (includes consistency analysis)
${CLAUDE_PLUGIN_ROOT}/scripts/audit_intent_layer.sh

Workflow

Quick Check (Default)

Run by default, completes in <30 seconds:

${CLAUDE_PLUGIN_ROOT}/scripts/audit_intent_layer.sh --quick [path]

What it checks:

  • Validation: Root node + immediate children only
  • Staleness: Age of all discovered nodes
  • Coverage: Directories without covering AGENTS.md

What it skips:

  • Deep validation of nested nodes
  • Section consistency analysis between siblings

Full Check

Run when user requests --full or deeper analysis:

${CLAUDE_PLUGIN_ROOT}/scripts/audit_intent_layer.sh [path]

Additional checks:

  • All nodes validated (not just root + children)
  • Section consistency analysis (sibling nodes use same sections)

Interpreting Results

Status Levels

StatusExit CodeMeaning
HEALTHY0No issues - good to proceed
NEEDS_ATTENTION1Warnings only - can proceed with awareness
CRITICAL2Failures or >50% stale nodes - address before work

Validation Categories

ResultCountAction
PASSNodes with no issuesNone
WARNNodes with warningsReview, non-blocking
FAILNodes with errorsFix before proceeding

Staleness Categories

AgeCategoryAction
<30 daysFreshNone
30-90 daysAgingMonitor
>90 daysStaleSchedule maintenance

Coverage

  • 80%+: Good coverage
  • 60-80%: Consider adding nodes for uncovered areas
  • <60%: Significant gaps - run /intent-layer-maintenance

Output Format

Present results to user in this format:

## Intent Layer Health Check

**Status**: NEEDS_ATTENTION

### Summary
- Validation: 10 PASS, 2 WARN, 0 FAIL
- Staleness: 1 node stale (src/legacy/AGENTS.md - 142 days)
- Coverage: 85% (3 directories uncovered)

### Recommended Actions
1. Run `/intent-layer-maintenance` to address stale nodes
2. Consider adding AGENTS.md to: src/utils/, src/migrations/

Ready to proceed with current work? The warnings are informational.

Recommendations by Status

HEALTHY

Intent Layer is healthy. Good to proceed with current work.

NEEDS_ATTENTION

### Recommended Actions
1. [If stale nodes] Run `/intent-layer-maintenance` to update stale nodes
2. [If low coverage] Consider adding AGENTS.md to: [list uncovered directories]
3. [If validation warnings] Review warnings: [list]

These are informational - you can proceed with current work.

CRITICAL

### Immediate Actions Required
1. [If validation failures] Fix these nodes before proceeding:
   - [node path]: [issue description]
2. [If >50% stale] Most nodes are outdated - run `/intent-layer-maintenance`

Recommend addressing these issues before starting new work.

Integration Notes

Session Start

This skill can be run proactively at session start:

  • Quick check is non-blocking (warnings don't stop work)
  • Provides awareness of Intent Layer health before diving into tasks
  • Pairs well with SessionStart hook for automatic invocation

CI Integration

For automated checks, use JSON output:

${CLAUDE_PLUGIN_ROOT}/scripts/audit_intent_layer.sh --json --quick

Exit codes enable CI pass/fail:

  • Exit 0: HEALTHY - pipeline passes
  • Exit 1: NEEDS_ATTENTION - pipeline passes with warning
  • Exit 2: CRITICAL - pipeline fails

Related Skills

SkillUse When
/intent-layer-maintenanceStatus is NEEDS_ATTENTION or CRITICAL
/intent-layerNo Intent Layer exists (state = none/partial)
/intent-layer-queryNeed to query Intent Layer for information

Scripts

ScriptPurpose
audit_intent_layer.shMain audit script (validation, staleness, coverage, consistency)
validate_node.shSingle node validation (called by audit)
detect_staleness.shDetailed staleness analysis
detect_state.shCheck if Intent Layer exists

All paths: ${CLAUDE_PLUGIN_ROOT}/scripts/

Intent Layer Maintenance

Run the maintenance flywheel for projects with an existing Intent Layer.

Prerequisites

  • Project must have Intent Layer state = complete
  • Run intent-layer skill first if state is none or partial

Workflow

digraph maintenance {
  rankdir=TB;

  "Start" [shape=ellipse];
  "Verify state=complete" [shape=box];
  "State complete?" [shape=diamond];
  "Run intent-layer skill" [shape=box];
  "Measure token growth" [shape=box];
  "Any >20k threshold?" [shape=diamond];
  "Flag child node candidates" [shape=box];
  "Ask pain point questions" [shape=box];
  "Map findings to sections" [shape=box];
  "Present update proposal" [shape=box];
  "User approves?" [shape=diamond];
  "Apply updates" [shape=box];
  "Done" [shape=ellipse];

  "Start" -> "Verify state=complete";
  "Verify state=complete" -> "State complete?" ;
  "State complete?" -> "Run intent-layer skill" [label="no"];
  "State complete?" -> "Measure token growth" [label="yes"];
  "Run intent-layer skill" -> "Done";
  "Measure token growth" -> "Any >20k threshold?";
  "Any >20k threshold?" -> "Flag child node candidates" [label="yes"];
  "Any >20k threshold?" -> "Ask pain point questions" [label="no"];
  "Flag child node candidates" -> "Ask pain point questions";
  "Ask pain point questions" -> "Map findings to sections";
  "Map findings to sections" -> "Present update proposal";
  "Present update proposal" -> "User approves?";
  "User approves?" -> "Apply updates" [label="yes"];
  "User approves?" -> "Done" [label="no"];
  "Apply updates" -> "Done";
}

Step 1: Verify State

# From intent-layer skill
scripts/detect_state.sh /path/to/project

If state is not complete, redirect to intent-layer skill for initial setup.

Step 2: Measure Token Growth

Use the consolidated measurement script to analyze all candidates at once:

# Recommended: Auto-discover and measure all candidates
scripts/estimate_all_candidates.sh /path/to/project

# Or measure individual directories manually:
scripts/estimate_tokens.sh /path/to/project/src
scripts/estimate_tokens.sh /path/to/project/lib

Thresholds:

  • Directory >20k tokens → candidate for child AGENTS.md
  • Directory grew >50% since last audit → review coverage

Step 3: Ask Pain Point Questions

Generate a structured template to capture findings:

scripts/capture_pain_points.sh pain_points.md
# Then fill in the generated template

These questions surface tribal knowledge that should be documented:

Recent Pitfalls (distinct from Anti-patterns)

  • "What surprised you in the last 3 months?"
  • "What looked deprecated/unused but actually wasn't?"
  • "What broke silently when someone made a reasonable assumption?"
  • "What implicit assumption bit someone?"

Contract Violations

  • "Did any invariant get violated? Should we document it?"
  • "Did external consumers break because of API changes?"
  • "Are there new 'must never happen' rules?"

Architecture Changes

  • "Were any significant technical decisions made?"
  • "Should we link to new ADRs or design docs?"
  • "Did subsystem boundaries shift?"

Entry Point Changes

  • "Are there new common tasks that need routing?"
  • "Did any entry points move or get renamed?"

Step 4: Map Findings to Sections

Finding TypeTarget Section
Surprising behaviorPitfalls
"Never do X" ruleAnti-patterns
Must-be-true constraintContracts & Invariants
Technical decision rationaleArchitecture Decisions
New common taskEntry Points
New subsystemSubsystem Boundaries
Relationship to externalRelated Context
New/moved child nodeDownlinks
Changed parent/siblingNavigation

Step 5: Present Update Proposal

Show user exactly what will change:

## Proposed Updates to CLAUDE.md

### Pitfalls (adding 2)
+ `config/legacy.json` looks unused but controls feature flags for enterprise clients
+ Running `make clean` deletes cached auth tokens - must re-authenticate

### Contracts (adding 1)
+ API v2 endpoints require `X-Request-ID` header (enforced by gateway, not code)

### No changes needed
- Anti-patterns
- Architecture Decisions
- Entry Points

Step 6: Apply Updates (if approved)

Edit the CLAUDE.md file to add new items to appropriate sections.

Validation after update:

  • Node still <4k tokens
  • No duplication with ancestor nodes
  • Relative paths for internal links
  • Downlinks point to existing child nodes
  • Navigation links (parent/siblings) are accurate

Quick Reference

Audit TypeFocus
Quarterly reviewFull: tokens + all question categories
Post-incidentPitfalls + Contracts that were violated
After refactorEntry Points + Subsystem Boundaries
After new featureArchitecture Decisions + Patterns

Common Mistakes

MistakeFix
Conflating Pitfalls with Anti-patternsPitfalls = surprising truth. Anti-patterns = things to avoid.
Adding every small findingOnly add if it would confuse future agents/engineers
Not measuring before askingAlways measure first - growth data informs questions
Updating without proposalShow changes, get approval, then apply

On Merge/PR: Detect Affected Nodes

When code changes (e.g., after merge), identify which Intent Nodes need review:

scripts/detect_changes.sh main HEAD

This outputs affected nodes in leaf-first order. Check each for behavior changes.


Parallel Audit (Large Intent Layers)

For Intent Layers with 4+ nodes, use parallel subagents to speed up audits.

When to Use Parallel Audit

Node CountApproach
1-3 nodesSequential (standard workflow)
4-8 nodesParallel validation + gap detection
9+ nodesFull parallel mode

Parallel Validation

Validate all nodes simultaneously with multiple Task calls in a single message:

Task 1 (Explore): "Validate CLAUDE.md against the codebase. Check:
                   - Are Entry Points still accurate?
                   - Are Contracts still enforced?
                   - Are Pitfalls still relevant?
                   - Any new patterns not documented?
                   Return: list of stale items + missing items"

Task 2 (Explore): "Validate src/api/AGENTS.md against src/api/. Check:
                   - Are Entry Points still accurate?
                   - Are Contracts still enforced?
                   - Are Pitfalls still relevant?
                   Return: list of stale items + missing items"

Task 3 (Explore): "Validate src/core/AGENTS.md against src/core/. Check:
                   [same questions]"

Parallel Gap Detection

Find undocumented areas across the codebase:

Task 1 (Explore): "Search for error handling patterns in src/. Find:
                   - try/catch patterns that aren't documented
                   - Silent failures that should be Pitfalls
                   - Error contracts not in any AGENTS.md"

Task 2 (Explore): "Search for API contracts in src/. Find:
                   - Input validation rules not documented
                   - Response shapes not in Contracts
                   - Auth/permissions not documented"

Task 3 (Explore): "Search for integration points in src/. Find:
                   - External service calls
                   - Database access patterns
                   - Message queue usage
                   Check if documented in nearest AGENTS.md"

Parallel Post-Incident Review

After an incident, audit relevant nodes in parallel:

Task 1 (Explore): "Review [incident area] for Pitfalls. Find:
                   - What assumption was violated?
                   - What would have prevented this?
                   - What should be added to Pitfalls?"

Task 2 (Explore): "Review [incident area] for Contract gaps. Find:
                   - What invariant was broken?
                   - What constraint should be documented?
                   - What boundary was crossed?"

Synthesizing Parallel Results

After parallel agents complete:

  1. Collect all findings into a unified list
  2. Deduplicate items found by multiple agents
  3. Categorize by target section (Pitfalls, Contracts, Entry Points)
  4. Prioritize by impact (incident-related > gaps > stale items)
  5. Present proposal to user for approval

Parallel Audit Benefits

MetricSequentialParallel
5-node audit~20 min~7 min
10-node audit~40 min~10 min
Coverage consistencyVariableUniform

Agent-Driven Capture (Alternative)

For complex areas where template-based capture (capture_pain_points.sh) feels insufficient, use agent-driven capture:

  1. Agent examines code, proposes descriptions, asks questions
  2. Human corrects, answers, adds historical context
  3. Iterate until description matches mental model

See references/capture-workflow-agent.md for the full three-phase process.

Use scripts/capture_state.sh to generate a tracking template for open questions during capture.


Scripts Location

This skill uses scripts from the intent-layer skill:

ScriptPurpose
detect_state.shCheck state (none/partial/complete)
estimate_tokens.shMeasure single directory
estimate_all_candidates.shMeasure all candidates at once
capture_pain_points.shGenerate pain points template
capture_state.shTrack open questions during capture
detect_changes.shFind affected nodes on merge/PR
analyze_structure.shFind semantic boundaries
validate_node.shCheck node quality after updates

References:

  • references/templates.md - Templates (S/M/L), three-tier boundaries
  • references/compression-techniques.md - Compression techniques, LCA placement, parent node compression
  • references/capture-workflow-agent.md - Agent-driven capture workflow
  • references/agent-feedback-protocol.md - How agents surface missing context

All paths: ${CLAUDE_PLUGIN_ROOT}/

Intent Layer Onboarding

Use an existing Intent Layer to quickly orient yourself (or a new team member) in a codebase.

Prerequisites

  • Project must have Intent Layer state = complete
  • Run intent-layer skill first if state is none or partial

Quick Start

# Check Intent Layer exists
${CLAUDE_PLUGIN_ROOT}/scripts/detect_state.sh /path/to/project

# Generate orientation overview
scripts/generate_orientation.sh /path/to/project

# View hierarchy
${CLAUDE_PLUGIN_ROOT}/scripts/show_hierarchy.sh /path/to/project

The 15-Minute Orientation

Get productive in a new codebase in 15 minutes using this workflow.

Step 1: Read the Root (2 min)

Read the root CLAUDE.md or AGENTS.md completely. Focus on:

  • TL;DR - One sentence project purpose
  • Subsystem Boundaries - Major areas and owners
  • Contracts - Global rules that apply everywhere
  • Pitfalls - Surprises that bite newcomers
# Find and display root node
cat /path/to/project/CLAUDE.md || cat /path/to/project/AGENTS.md

Step 2: Map the Hierarchy (2 min)

Visualize the full Intent Layer structure:

${CLAUDE_PLUGIN_ROOT}/scripts/show_hierarchy.sh /path/to/project

Note:

  • How many child nodes exist
  • Which areas have the most documentation (complexity signals)
  • Depth of hierarchy (shallow = simple, deep = complex)

Step 3: Identify Your Entry Point (3 min)

Based on your role or first task, find where to start:

If your role is...Start with...
Frontend engineerUI/components AGENTS.md
Backend engineerAPI/services AGENTS.md
DevOps/PlatformInfrastructure AGENTS.md
Full-stackRoot node + busiest subsystem
If your first task is...Find...
Bug fix in area XAGENTS.md closest to X
New featureEntry Points in relevant subsystem
Understanding flowRoot → follow data path

Step 4: Deep-Read Your Area (5 min)

For your identified entry point:

  1. Read the specific AGENTS.md completely
  2. Note the Entry Points - these are your starting files
  3. Note the Contracts - rules you must follow
  4. Note the Pitfalls - traps to avoid

Step 5: Verify Understanding (3 min)

Test your mental model:

  1. Can you explain the project in one sentence?
  2. Do you know where your first change goes?
  3. Do you know what rules apply to that area?
  4. Do you know what NOT to do?

If any answer is "no", re-read the relevant node.


Role-Based Onboarding

For AI Agents

When an AI agent needs to understand a new codebase:

Minimum context load:

  1. Root node (always)
  2. Node for target area (if known)
  3. Ancestors of target (for inherited constraints)

Query pattern:

"I need to [task] in [area]. What should I know?"

Response pattern:

## Context for [task]

### Relevant Node
`path/to/AGENTS.md`

### Key Constraints
- [From local node]
- [Inherited from ancestors]

### Entry Point
Start at: `path/to/file.ts`

### Watch Out For
- [Pitfall 1]
- [Pitfall 2]

For New Engineers

When a human is joining the team:

Day 1 Goals:

  1. Understand project purpose (root TL;DR)
  2. Know major subsystems (root Subsystem Boundaries)
  3. Know global rules (root Contracts)
  4. Know what surprises exist (root Pitfalls)

Week 1 Goals:

  1. Deep-read your team's AGENTS.md files
  2. Understand your area's specific contracts
  3. Successfully complete one small task
  4. Know where to ask questions

Onboarding Checklist:

## Onboarding Checklist: [Name]

### Day 1
- [ ] Read root CLAUDE.md/AGENTS.md
- [ ] Run show_hierarchy.sh to see structure
- [ ] Identify which subsystem I'll work in
- [ ] Read my subsystem's AGENTS.md

### Week 1
- [ ] Complete first small task
- [ ] Verify I followed all contracts
- [ ] Note any confusion for Intent Layer feedback
- [ ] Ask about anything not documented

For Code Reviewers

When reviewing code in an unfamiliar area:

  1. Find AGENTS.md for the changed files
  2. Check Contracts section - are they followed?
  3. Check Pitfalls section - are they avoided?
  4. Check Anti-patterns section - none introduced?

Task-Based Onboarding

"I need to fix a bug in X"

Workflow:

  1. Find AGENTS.md nearest to X
  2. Read Pitfalls (often explains the bug)
  3. Read Contracts (constraints on the fix)
  4. Find Entry Point for debugging

Output:

## Bug Fix Context: [area]

**Relevant Node:** `path/to/AGENTS.md`

**Common Pitfalls (check these first):**
- [Pitfall that might explain bug]

**Fix Constraints:**
- [Rules the fix must follow]

**Start Debugging At:**
- `path/to/entry/file.ts`

"I need to add a feature to Y"

Workflow:

  1. Find AGENTS.md for Y
  2. Check if feature is in scope (vs out of scope)
  3. Read Entry Points for "add new..."
  4. Read Contracts for implementation rules
  5. Check parent nodes for inherited constraints

Output:

## Feature Context: [feature] in [area]

**In Scope:** Yes/No (from AGENTS.md)

**Entry Point:**
- Start at: `path/to/file.ts`
- Pattern to follow: [from Entry Points]

**Constraints:**
- [Local rules]
- [Inherited rules]

**Related Areas:**
- [Siblings that might be affected]

"I need to understand how Z works"

Workflow:

  1. Find AGENTS.md that owns Z
  2. Read TL;DR for high-level understanding
  3. Read Architecture Decisions for rationale
  4. Follow Entry Points to key files
  5. Read ancestors for broader context

Output:

## Understanding: [Z]

**Owner:** `path/to/AGENTS.md`

**TL;DR:**
> [From node]

**Why It's Designed This Way:**
- [From Architecture Decisions]

**Key Files to Read:**
1. `file1.ts` - [purpose]
2. `file2.ts` - [purpose]

**Broader Context:**
- [From parent nodes]

Generating Orientation Documents

For teams that want a static onboarding doc:

Quick Overview

scripts/generate_orientation.sh /path/to/project --format overview

Produces:

  • Project summary
  • Subsystem map
  • Global rules
  • Common tasks entry points

Full Onboarding Guide

scripts/generate_orientation.sh /path/to/project --format full

Produces:

  • Everything in overview
  • Per-subsystem deep dives
  • Role-based entry points
  • First-week checklist

Team-Specific

scripts/generate_orientation.sh /path/to/project --role backend

Produces:

  • Filtered view for backend engineers
  • Relevant subsystems only
  • Backend-specific entry points

Interactive Onboarding Session

For a guided, interactive orientation:

Step 1: Gather Context

Ask the newcomer:

  1. What's your role? (frontend/backend/fullstack/devops/other)
  2. What's your first task? (if known)
  3. What's your experience level? (junior/mid/senior)

Step 2: Generate Personalized Path

Based on answers, create a reading list:

Junior + No specific task:

## Your Onboarding Path

1. **Start Here:** CLAUDE.md (root) - 10 min read
2. **Then:** [area matching role]/AGENTS.md - 5 min read
3. **Exercise:** Find where [simple task] would be done
4. **Verify:** Explain the project back to me

Senior + Specific task:

## Your Onboarding Path

1. **Quick Scan:** CLAUDE.md TL;DR + Subsystems - 2 min
2. **Deep Read:** [task area]/AGENTS.md - 5 min
3. **Context:** Walk ancestors for inherited rules - 3 min
4. **Start:** [Entry point for task]

Step 3: Verify Understanding

After they complete the path, ask:

  1. "What does this project do in one sentence?"
  2. "Where would you make your first change?"
  3. "What rules must you follow there?"
  4. "What mistakes should you avoid?"

If answers are weak, point them to specific sections.

Step 4: Capture Gaps

If they found the Intent Layer confusing or incomplete:

### Intent Layer Feedback

| Type | Location | Finding |
|------|----------|---------|
| Unclear | `src/api/AGENTS.md` | Entry Points don't explain X |
| Missing | `CLAUDE.md` | No mention of Y subsystem |

Feed this back via intent-layer-maintenance skill.


Common Questions

"Where do I start?"

  1. Run show_hierarchy.sh to see structure
  2. Read root node for project overview
  3. Identify your area from Subsystem Boundaries
  4. Read that area's AGENTS.md
  5. Follow its Entry Points

"What can I safely change?"

  1. Find AGENTS.md for the area
  2. Check Contracts - these are invariants
  3. Check Anti-patterns - don't introduce these
  4. Anything not constrained is fair game

"Who owns this code?"

  1. Find nearest AGENTS.md (walk up if needed)
  2. Check TL;DR for ownership statement
  3. Check Subsystem Boundaries in parent for team info

"Why is it done this way?"

  1. Find AGENTS.md for the area
  2. Check Architecture Decisions section
  3. Follow any ADR links
  4. If not documented, flag as feedback

Parallel Onboarding (Teams & Multiple Roles)

For onboarding multiple people or generating comprehensive multi-role documentation, use parallel subagents.

When to Use Parallel Onboarding

ScenarioApproach
Single person, known roleSequential (standard 15-min workflow)
Single person, exploring rolesParallel role summaries
Multiple new team membersParallel per-person paths
Comprehensive onboarding docsParallel section generation

Parallel Role Summaries

Generate role-specific orientations simultaneously:

Task 1 (Explore): "Generate frontend engineer orientation from Intent Layer.
                   Focus on: UI components, state management, styling patterns.
                   Return: relevant nodes, key contracts, entry points, pitfalls"

Task 2 (Explore): "Generate backend engineer orientation from Intent Layer.
                   Focus on: API layer, database, services, integrations.
                   Return: relevant nodes, key contracts, entry points, pitfalls"

Task 3 (Explore): "Generate DevOps/platform orientation from Intent Layer.
                   Focus on: infrastructure, CI/CD, deployment, monitoring.
                   Return: relevant nodes, key contracts, entry points, pitfalls"

Output: Three role-specific onboarding guides generated in parallel.

Parallel Comprehensive Documentation

Generate full onboarding documentation in parallel sections:

Task 1 (Explore): "Extract project overview from Intent Layer root.
                   Return: TL;DR, architecture overview, subsystem map"

Task 2 (Explore): "Extract all global contracts and pitfalls from Intent Layer.
                   Return: merged constraints list, common mistakes to avoid"

Task 3 (Explore): "Extract all entry points across Intent Layer nodes.
                   Return: task → starting point mapping for common tasks"

Task 4 (Explore): "Identify complexity hotspots from Intent Layer.
                   Return: areas with most contracts/pitfalls (need careful reading)"

Synthesis: Combine into comprehensive onboarding document.

Parallel Task-Context Generation

When newcomer has multiple potential first tasks:

Task 1 (Explore): "Generate context for 'fix login bug' task.
                   Find: relevant node, constraints, pitfalls, entry point"

Task 2 (Explore): "Generate context for 'add new API endpoint' task.
                   Find: relevant node, constraints, pitfalls, entry point"

Task 3 (Explore): "Generate context for 'update dashboard component' task.
                   Find: relevant node, constraints, pitfalls, entry point"

Output: Three task-context summaries, let newcomer pick their starting point.

Parallel Codebase Exploration

For AI agents needing to understand unfamiliar codebase quickly:

Task 1 (Explore): "Read CLAUDE.md root node. Extract: purpose, subsystems,
                   global constraints, and identify which child nodes exist"

Task 2 (Explore): "For each child AGENTS.md, extract: ownership scope,
                   key contracts, main pitfalls. Return summary table"

Task 3 (Explore): "Map data flow through system using Intent Layer.
                   How does data move between subsystems?"

Synthesis: Complete mental model of codebase in ~5 minutes vs ~15 minutes sequential.

Example: Parallel Team Onboarding

Scenario: 3 new engineers joining (1 frontend, 1 backend, 1 fullstack)

Parallel execution:

Task 1: "Create onboarding path for frontend engineer.
         - Identify UI-related AGENTS.md nodes
         - Extract frontend-specific contracts and pitfalls
         - List frontend entry points for common tasks
         - Generate Day 1 and Week 1 checklist"

Task 2: "Create onboarding path for backend engineer.
         - Identify API/service AGENTS.md nodes
         - Extract backend-specific contracts and pitfalls
         - List backend entry points for common tasks
         - Generate Day 1 and Week 1 checklist"

Task 3: "Create onboarding path for fullstack engineer.
         - Identify cross-cutting AGENTS.md nodes
         - Extract integration contracts and pitfalls
         - List full-stack entry points
         - Generate Day 1 and Week 1 checklist"

Output: Three personalized onboarding documents in parallel.

Parallel Onboarding Benefits

ScenarioSequentialParallel
3-role documentation~30 min~10 min
5-person team onboarding~75 min~15 min
Comprehensive docs (4 sections)~40 min~12 min

Scripts Reference

ScriptPurpose
generate_orientation.shCreate onboarding documents
show_hierarchy.shVisualize Intent Layer structure
show_status.shCheck Intent Layer health
query_intent.shSearch for specific concepts
walk_ancestors.shGather context from hierarchy

Scripts from intent-layer: ${CLAUDE_PLUGIN_ROOT}/scripts/ Scripts from intent-layer-query: ${CLAUDE_PLUGIN_ROOT}/scripts/


Anti-Patterns

Don't Do ThisDo This Instead
Skip root, jump to codeAlways read root first
Read all nodes exhaustivelyRead root + your area
Ignore Pitfalls sectionPitfalls prevent 80% of mistakes
Assume contracts are optionalContracts are hard requirements
Start coding without reading Entry PointsEntry Points show the correct starting place

Success Metrics

After onboarding, the newcomer should be able to:

  1. Explain - Describe project purpose in one sentence
  2. Navigate - Find the right AGENTS.md for any task
  3. Comply - Know constraints that apply to their area
  4. Avoid - Know common pitfalls in their area
  5. Start - Know exactly which file to open first

If any of these fail, the Intent Layer may need improvement via maintenance skill.

Intent Layer Query

Query an existing Intent Layer to answer architectural and navigation questions.

Prerequisites

  • Project must have Intent Layer state = complete
  • Run intent-layer skill first if state is none or partial

Quick Start

# Check state first
${CLAUDE_PLUGIN_ROOT}/scripts/detect_state.sh /path/to/project

# View hierarchy
${CLAUDE_PLUGIN_ROOT}/scripts/show_hierarchy.sh /path/to/project

# Check health
${CLAUDE_PLUGIN_ROOT}/scripts/show_status.sh /path/to/project

Query Types

1. Ownership Queries

"What owns X?" - Find responsible component for a concept.

Process:

  1. Search all Intent Nodes for the concept
  2. Return the most specific node that claims ownership
  3. Include parent context for full picture

Example:

Q: "What owns authentication?"

Search: grep -r "authentication\|auth" in CLAUDE.md/AGENTS.md files
Result: src/auth/AGENTS.md owns authentication
Parent: CLAUDE.md references auth as critical subsystem

Output format:

## Ownership: [concept]

**Primary owner:** `path/to/AGENTS.md`
> [TL;DR from that node]

**Parent context:** `CLAUDE.md`
> [Relevant excerpt about this area]

**Contracts:**
- [Any constraints from owner or ancestors]

2. Placement Queries

"Where should I put X?" - Find correct location for new code.

Process:

  1. Identify the responsibility of X
  2. Find nodes with matching or adjacent responsibilities
  3. Check for explicit "out of scope" declarations
  4. Recommend placement with rationale

Example:

Q: "Where should I put a new payment processor?"

Analysis:
- payments/ exists → check src/payments/AGENTS.md
- If AGENTS.md says "owns all payment logic" → put there
- If AGENTS.md says "only Stripe" → may need new sibling

Output format:

## Placement: [new thing]

**Recommended:** `path/to/directory/`
**Reason:** [Why this location based on Intent Layer]

**Relevant contracts:**
- [Constraints that apply to this location]

**Alternatives considered:**
- `other/path/` - rejected because [reason from Intent Layer]

3. Constraint Queries

"What constraints apply to X?" - Gather all rules for an area.

Process:

  1. Find the most specific node for X
  2. Walk up to root, collecting constraints
  3. Merge contracts from all ancestors (child overrides parent)
  4. Return unified constraint set

Example:

Q: "What constraints apply to the API layer?"

Walk: src/api/AGENTS.md → CLAUDE.md
Collect:
- From src/api/AGENTS.md: "All endpoints must validate auth token"
- From CLAUDE.md: "Never log PII", "Use structured logging"

Output format:

## Constraints: [area]

### From `path/to/specific/AGENTS.md`
- [Local constraints]

### Inherited from `CLAUDE.md`
- [Global constraints that apply]

### Effective rules (merged)
1. [Most important constraint]
2. [Second constraint]
...

4. Entry Point Queries

"How do I [task]?" - Find starting point for common tasks.

Process:

  1. Search Entry Points sections across all nodes
  2. Match task description to documented entry points
  3. Return the most specific match with context

Example:

Q: "How do I add a new API endpoint?"

Search Entry Points for: "API", "endpoint", "route"
Match: src/api/AGENTS.md → Entry Points → "Add endpoint: start at routes/"

Output format:

## Entry Point: [task]

**Start here:** `path/to/file.ts`
**From:** `path/to/AGENTS.md`

**Steps:**
1. [Step from Entry Points section]
2. [Additional context if available]

**Watch out for:**
- [Relevant pitfalls from same node]

5. Pitfall Queries

"What can go wrong with X?" - Gather warnings for an area.

Process:

  1. Find nodes covering X
  2. Collect all Pitfalls sections
  3. Include parent pitfalls that apply
  4. Return consolidated warnings

Output format:

## Pitfalls: [area]

### Critical (from nearest node)
- [Pitfall 1]
- [Pitfall 2]

### Inherited (from ancestors)
- [Global pitfall that applies]

### Related anti-patterns
- [Things to avoid]

6. Architecture Queries

"Why is X designed this way?" - Find rationale for decisions.

Process:

  1. Search Architecture Decisions sections
  2. Look for ADR links
  3. Check Related Context for external docs

Output format:

## Architecture: [topic]

**Decision:** [What was decided]
**Rationale:** [Why, from Architecture Decisions section]
**Source:** `path/to/AGENTS.md` or linked ADR

**Related:**
- [Links to ADRs or design docs]

Interactive Query Workflow

For complex queries, use this interactive process:

Step 1: Understand the Question

Classify the query:

  • Ownership → "What owns..."
  • Placement → "Where should..."
  • Constraints → "What rules..."
  • Entry Point → "How do I..."
  • Pitfalls → "What can go wrong..."
  • Architecture → "Why is..."

Step 2: Gather Context

# View full hierarchy
${CLAUDE_PLUGIN_ROOT}/scripts/show_hierarchy.sh /path/to/project

# Search for concept in Intent Nodes
grep -r "concept" --include="CLAUDE.md" --include="AGENTS.md" /path/to/project

Step 3: Walk the Hierarchy

For the relevant node:

  1. Read the specific node
  2. Read each ancestor up to root
  3. Collect relevant sections

Step 4: Synthesize Answer

Combine findings into the appropriate output format (see Query Types above).

Step 5: Cite Sources

Always include:

  • Which nodes provided the answer
  • Line numbers for specific claims
  • Confidence level (explicit vs inferred)

Query Confidence Levels

LevelMeaning
ExplicitDirectly stated in Intent Node
InferredDerived from multiple nodes
UncertainNot documented, using code analysis

Always state confidence:

**Confidence:** Explicit (from src/auth/AGENTS.md:15)

or

**Confidence:** Inferred (no direct documentation, based on code structure)
**Recommendation:** Add to Intent Layer via maintenance skill

When Query Fails

If the Intent Layer doesn't answer the question:

1. Document the Gap

### Intent Layer Feedback

| Type | Location | Finding |
|------|----------|---------|
| Missing ownership | `CLAUDE.md` | No documented owner for [concept] |

2. Answer from Code

Fall back to code analysis, but flag uncertainty:

## Answer (from code analysis)

**Confidence:** Uncertain - not documented in Intent Layer

[Answer based on code reading]

**Recommendation:** Document this in [suggested node]

3. Trigger Maintenance

If multiple gaps found, suggest running intent-layer-maintenance skill.


Parallel Queries (Large Intent Layers)

For Intent Layers with 5+ nodes or complex multi-faceted queries, use parallel subagents.

When to Use Parallel Queries

ScenarioApproach
Single concept, small Intent LayerSequential search
Single concept, large Intent Layer (5+ nodes)Parallel node search
Multi-faceted query (ownership + constraints + pitfalls)Parallel aspect search
Cross-cutting concern investigationParallel subsystem search

Parallel Node Search

Search all nodes simultaneously for a concept:

Task 1 (Explore): "Search CLAUDE.md for references to [concept].
                   Return: any mentions, ownership claims, constraints, pitfalls"

Task 2 (Explore): "Search src/api/AGENTS.md for references to [concept].
                   Return: any mentions, ownership claims, constraints, pitfalls"

Task 3 (Explore): "Search src/core/AGENTS.md for references to [concept].
                   Return: any mentions, ownership claims, constraints, pitfalls"

Synthesis: Combine results, identify primary owner (most specific claim), collect all constraints.

Parallel Aspect Search

For complex queries needing multiple perspectives:

Q: "What do I need to know to add a new payment provider?"

Task 1 (Explore): "Search Intent Layer for ownership of payments.
                   Who owns payment logic? What's in scope/out of scope?"

Task 2 (Explore): "Search Intent Layer for payment-related contracts.
                   What invariants apply? What patterns are required?"

Task 3 (Explore): "Search Intent Layer for payment-related pitfalls.
                   What surprises exist? What has broken before?"

Task 4 (Explore): "Search Intent Layer for payment entry points.
                   How do I add new payment functionality?"

Synthesis: Combine into comprehensive answer covering ownership, constraints, warnings, and starting point.

Parallel Cross-Cutting Search

For concepts that span multiple subsystems:

Q: "How is authentication handled across the system?"

Task 1 (Explore): "Search src/api/AGENTS.md for auth mentions.
                   How does API layer handle auth?"

Task 2 (Explore): "Search src/core/AGENTS.md for auth mentions.
                   How does core layer handle auth?"

Task 3 (Explore): "Search src/db/AGENTS.md for auth mentions.
                   How does data layer handle auth?"

Synthesis: Map auth flow across subsystems, identify gaps in documentation.

Parallel Query Benefits

Query TypeSequentialParallel
Concept in 8 nodes~16 reads~3 reads (parallel)
Multi-aspect query~12 reads~4 reads (parallel)
Cross-cutting search~10 reads~3 reads (parallel)

Example: Parallel Constraint Query

Query: "What constraints apply to the checkout flow?"

Parallel execution:

Task 1: "Find all constraints in src/checkout/AGENTS.md"
Task 2: "Find all constraints in src/payments/AGENTS.md"
Task 3: "Find all global constraints in CLAUDE.md that mention checkout, payment, or transaction"

Synthesis output:

## Constraints: checkout flow

### From `src/checkout/AGENTS.md`
- Cart must be validated before payment initiation
- Inventory reserved for 15 minutes during checkout

### From `src/payments/AGENTS.md`
- All payment calls must be idempotent
- Failed payments must not leave partial state

### Inherited from `CLAUDE.md`
- All financial operations must be logged
- PII never logged in plain text

### Effective rules (merged)
1. Validate cart → reserve inventory → initiate payment (order matters)
2. Payment calls must be idempotent
3. Log all operations, redact PII
4. 15-minute timeout on reservations

Common Query Patterns

Question PatternQuery TypeKey Sections to Check
"What handles X?"OwnershipTL;DR, Subsystem Boundaries
"Where does X live?"OwnershipSubsystem Boundaries, Downlinks
"Where should I add X?"PlacementOwnership + Out of Scope
"Can I do X here?"ConstraintsContracts, Anti-patterns
"What rules apply to X?"ConstraintsContracts (all ancestors)
"How do I X?"Entry PointEntry Points section
"What's dangerous about X?"PitfallsPitfalls, Anti-patterns
"Why X instead of Y?"ArchitectureArchitecture Decisions

Scripts Reference

This skill uses scripts from intent-layer:

ScriptQuery Use
show_hierarchy.shVisualize full Intent Layer structure
show_status.shCheck health before querying
detect_state.shVerify Intent Layer exists

All paths: ${CLAUDE_PLUGIN_ROOT}/scripts/


Examples

Example 1: Ownership Query

User: "What owns user sessions?"

Process:

  1. grep -r "session" --include="*.md" in Intent Nodes
  2. Found in src/auth/AGENTS.md: "Owns: authentication, sessions, tokens"
  3. Parent CLAUDE.md confirms: "Auth subsystem handles all identity"

Answer:

## Ownership: user sessions

**Primary owner:** `src/auth/AGENTS.md`
> Owns authentication, session management, and token lifecycle.

**Contracts:**
- Sessions must expire after 24h inactivity
- Session tokens never logged

**Confidence:** Explicit (src/auth/AGENTS.md:23)

Example 2: Placement Query

User: "Where should I add rate limiting?"

Process:

  1. Search for "rate limit" - not found
  2. Search for "middleware", "request handling"
  3. Found src/api/AGENTS.md owns "request pipeline"
  4. Check if rate limiting is out of scope - no
  5. Check constraints - "middleware must be stateless"

Answer:

## Placement: rate limiting

**Recommended:** `src/api/middleware/`
**Reason:** API layer owns request pipeline, rate limiting is request-level concern

**Constraints from Intent Layer:**
- Middleware must be stateless (use Redis for counters)
- All middleware must log to structured logger

**Confidence:** Inferred (no explicit mention, derived from ownership)
**Recommendation:** Add rate limiting to src/api/AGENTS.md Entry Points

Intent Layer

TL;DR: Create CLAUDE.md/AGENTS.md files that help AI agents navigate your codebase like senior engineers. Run detect_state.sh first to see what's needed.

Hierarchical AGENTS.md infrastructure so agents navigate codebases like senior engineers.


Sub-Skills

This skill includes specialized sub-skills that are automatically invoked when appropriate:

Sub-SkillLocationAuto-Invoke When
git-historygit-history/SKILL.mdCreating nodes for existing code (extracts pitfalls from commits)
pr-review-miningpr-review-mining/SKILL.mdCreating nodes for existing code (extracts pitfalls from PR discussions)
pr-reviewpr-review/SKILL.mdReviewing PRs that touch Intent Layer nodes

git-history (Auto-Invoked During Setup)

When creating nodes for directories with git history, automatically run git-history analysis to pre-populate:

  • Pitfalls from bug fix commits
  • Anti-patterns from revert commits
  • Architecture Decisions from refactor commits
  • Contracts from breaking change commits
Trigger: Creating AGENTS.md for directory with >50 commits
Action: Run git-history analysis before writing node

pr-review-mining (Auto-Invoked During Setup)

When creating nodes for directories with merged PRs, automatically run PR mining to pre-populate:

  • Pitfalls from PR Risks sections and review warnings
  • Contracts from Breaking Changes sections
  • Architecture Decisions from Why sections and Alternatives Considered
  • Anti-patterns from rejected approaches in reviews
Trigger: Creating AGENTS.md for directory with merged PRs
Action: Run pr-review-mining alongside git-history, merge findings

pr-review (Auto-Invoked for PRs)

When reviewing PRs that modify code covered by Intent Layer:

  • Verify contracts are respected
  • Check pitfalls are avoided
  • Flag potential Intent Layer updates needed
Trigger: PR touches files under an AGENTS.md
Action: Run pr-review with --ai-generated if applicable

learning-loop (Auto-Invoked on Error Discovery)

When you discover a non-obvious gotcha during any work (not just Intent Layer setup):

  • Find the nearest AGENTS.md to where the issue occurred
  • Append to its Pitfalls section
  • Keep the Intent Layer alive with real lessons
Trigger: Fix error caused by non-obvious behavior (API format, config quirk, etc.)
Action: Append pitfall to nearest AGENTS.md
Format:
  ### Short descriptive title
  **Problem**: What assumption failed
  **Symptom**: Error message or unexpected behavior
  **Solution**: Correct approach with code reference

Example: After fixing 'list' object has no attribute 'get' because Claude CLI output format varies:

### Claude CLI JSON output format varies

**Problem**: `claude --output-format json` can return dict or list
**Symptom**: `'list' object has no attribute 'get'`
**Solution**: Check `isinstance(data, list)` before `.get()`. See `lib/claude_runner.py:parse_claude_output()`

Quick Start

Step 0: Check State

scripts/detect_state.sh /path/to/project
StateAction
noneCreate root file (continue below)
partialAdd Intent Layer section to existing root
completeUse intent-layer-maintenance skill instead

Step 1: Measure

# Auto-discover all candidate directories
scripts/estimate_all_candidates.sh /path/to/project

# Or analyze structure first
scripts/analyze_structure.sh /path/to/project

Step 2: Create Root Node

Choose CLAUDE.md (Anthropic) or AGENTS.md (cross-tool). Pick template by size:

  • Small (<50k tokens): references/templates.md → Small Project
  • Medium (50-150k): references/templates.md → Medium Project
  • Large (>150k/monorepo): references/templates.md → Large Project

Step 3: Create Child Nodes (if needed)

SignalAction
Directory >20k tokensCreate AGENTS.md
Responsibility shiftCreate AGENTS.md
Cross-cutting concernDocument at nearest common ancestor

Use child template from references/templates.md.

Step 4: Validate

scripts/validate_node.sh CLAUDE.md
scripts/validate_node.sh path/to/AGENTS.md

Checks: token count <4k, required sections, no absolute paths, no TODOs.

Step 5: Cross-Tool Compatibility

ln -s CLAUDE.md AGENTS.md  # If CLAUDE.md is primary

Interactive Wizard

Step-by-step guided setup with prompts at each decision point.

Step 1: Detect State

Run scripts/detect_state.sh, then based on result:

StateAction
noneAsk user: "Create CLAUDE.md or AGENTS.md as root?"
partialAsk user: "What's the one-line TL;DR for this project?"
completeRedirect to intent-layer-maintenance skill

Step 2: Measure & Decide

Run scripts/estimate_all_candidates.sh, then:

  • Present candidates table to user
  • Ask: "Which directories should get their own AGENTS.md?"

Step 3: Mine History (Auto-Invoked) — HIGHEST VALUE STEP

Before creating each node, automatically analyze both git history AND PR discussions using the mining scripts. Git-mined pitfalls are consistently the most valuable content in any node. Pitfalls discovered from real bugs (commit fixes, reverts, migrations) are far more useful than pitfalls guessed from reading code.

# Git commit analysis (extracts pitfalls, anti-patterns, decisions, contracts)
${CLAUDE_PLUGIN_ROOT}/scripts/mine_git_history.sh [directory]

# GitHub PR analysis (requires gh CLI)
${CLAUDE_PLUGIN_ROOT}/scripts/mine_pr_reviews.sh --limit 50

# Check for stale nodes (during maintenance)
${CLAUDE_PLUGIN_ROOT}/scripts/detect_staleness.sh --code-changes [directory]

mine_git_history.sh extracts from commits:

  1. Bug fixes → Pre-populate Pitfalls
  2. Reverts → Pre-populate Anti-patterns
  3. Refactors → Pre-populate Architecture Decisions
  4. Breaking changes → Pre-populate Contracts

mine_pr_reviews.sh extracts from PRs:

  1. Risks sections → Pre-populate Pitfalls
  2. Review warnings → Pre-populate Pitfalls
  3. Breaking Changes → Pre-populate Contracts
  4. Why/Alternatives → Pre-populate Architecture Decisions

Present merged findings to user: "History suggests these pitfalls: [list]. Include them?"

Step 4: Create Nodes

For root node:

  • Ask user about project purpose
  • Select template by size (Small/Medium/Large from references/templates.md)
  • Include git-history findings in appropriate sections

For each child node:

  • Ask user about directory's responsibility
  • Use child template from references/templates.md
  • Include git-history findings for that directory

Step 4b: Add Pre-flight Checks

For directories with history of mistakes or complex operations:

Ask: "What operations in this directory have caused problems before?"

For each risky operation identified:

  1. Ask: "What would you check before doing [operation]?"
  2. Convert answer to verifiable check format
  3. Add to Pre-flight Checks section

Mine from history:

# Find reverts and fixes that suggest missing checks
${CLAUDE_PLUGIN_ROOT}/scripts/mine_git_history.sh [directory] | grep -i "fix\|revert"

Present findings: "These commits suggest potential checks: [list]. Add any?"

Step 5: Validate

Run scripts/validate_node.sh on all created nodes:

  • Show validation results
  • Offer to fix warnings/errors

Step 6: Symlink

Ask user: "Create symlink for cross-tool compatibility? (AGENTS.md → CLAUDE.md)"

If yes: ln -s CLAUDE.md AGENTS.md


Parallel Setup (Large Codebases)

For codebases >200k tokens, use parallel subagents to dramatically speed up exploration.

When to Use Parallel Mode

Codebase SizeApproach
<100k tokensSequential (standard workflow)
100-500k tokensParallel exploration, sequential synthesis
>500k tokensFull parallel mode (explore + validate)

Step 1: Identify Subsystems

Run structure analysis first:

scripts/analyze_structure.sh /path/to/project

Identify 3-6 major subsystems from the output (e.g., src/api/, src/core/, src/db/).

Step 2: Parallel Exploration + History Mining

Spawn subagents for code exploration, git history, AND PR mining in parallel:

# Code exploration (one per subsystem)
Task 1: "Analyze src/api/ for Intent Layer setup. Find: code map (find-it-fast
         + key relationships), public API (exports used by others + core types),
         external dependencies, data flow, entry points, contracts, patterns,
         pitfalls. Return structured findings per section."

Task 2: "Analyze src/core/ for Intent Layer setup. Find: code map (find-it-fast
         + key relationships), public API (exports used by others + core types),
         external dependencies, data flow, entry points, contracts, patterns,
         pitfalls. Return structured findings per section."

Task 3: "Analyze src/db/ for Intent Layer setup. Find: code map (find-it-fast
         + key relationships), public API (exports used by others + core types),
         external dependencies, data flow, entry points, contracts, patterns,
         pitfalls. Return structured findings per section."

# Git history analysis (parallel with exploration)
Task 4: "Run git-history analysis on src/api/. Find bug fixes, reverts,
         refactors, and breaking changes. Return as Intent Layer findings."

Task 5: "Run git-history analysis on src/core/. Find bug fixes, reverts,
         refactors, and breaking changes. Return as Intent Layer findings."

Task 6: "Run git-history analysis on src/db/. Find bug fixes, reverts,
         refactors, and breaking changes. Return as Intent Layer findings."

# PR review mining (parallel with above)
Task 7: "Run pr-review-mining on src/api/. Extract from PR descriptions
         and review comments: pitfalls, contracts, architecture decisions.
         Return as Intent Layer findings with PR numbers."

Task 8: "Run pr-review-mining on src/core/. Extract from PR descriptions
         and review comments: pitfalls, contracts, architecture decisions.
         Return as Intent Layer findings with PR numbers."

Task 9: "Run pr-review-mining on src/db/. Extract from PR descriptions
         and review comments: pitfalls, contracts, architecture decisions.
         Return as Intent Layer findings with PR numbers."

Critical: Launch all agents in parallel (single message with multiple Task calls).

Step 3: Synthesize Results

Once all agents complete:

  1. Merge code exploration + git history + PR mining findings per subsystem
  2. Identify cross-cutting concerns (appear in multiple findings)
  3. Place cross-cutting items in root node
  4. Create child AGENTS.md for each subsystem with all sections:
    • Purpose + Design Rationale (the "why")
    • Code Map (find-it-fast + key relationships)
    • Public API (key exports + core types)
    • External Dependencies (services + failure modes)
    • Data Flow (request path)
    • Decisions (from git history + PR mining)
    • Entry Points, Contracts, Patterns
    • Pitfalls (from all sources)
    • Boundaries, Pre-flight Checks
  5. Deduplicate where multiple sources found the same insight
  6. Prefer PR-sourced rationale for Decisions (richer "why" context)

Step 4: Parallel Validation

Validate all nodes in parallel:

Task 1: "Run validate_node.sh on CLAUDE.md, report results"
Task 2: "Run validate_node.sh on src/api/AGENTS.md, report results"
Task 3: "Run validate_node.sh on src/core/AGENTS.md, report results"

Example Parallel Exploration Prompt

For each subsystem, use this structured prompt:

Explore [DIRECTORY] for Intent Layer documentation. Return:

## Design Rationale
[Why does this module exist? What problem does it solve? What's the core insight?]

## Code Map
### Find It Fast
| Looking for... | Go to |
[What common searches map to which files? Focus on non-obvious locations.]

### Key Relationships
[Import direction, layer rules, what depends on what]

## Public API
### Key Exports
| Export | Used By | Change Impact |
[What do OTHER modules import from here?]

### Core Types
[The 3-5 types needed to understand this area]

## External Dependencies
| Service | Used For | Failure Mode |
[External services and what happens when down]

## Data Flow
[How requests/data move through this area - simple diagram]

## Decisions
| Decision | Why | Rejected |
[Architectural choices with rationale]

## Entry Points
| Task | Start Here |
[Common tasks and where to start]

## Contracts
[Non-type-enforced invariants]

## Patterns
[How to do common tasks - sequence and non-obvious steps]

## Pitfalls
[What looks wrong but isn't? What looks fine but breaks?]

Keep findings specific to this directory. Note cross-cutting concerns separately.

Parallel Mode Benefits

MetricSequentialParallel
500k token codebase~30 min~10 min
1M+ token codebase~60 min~15 min
Subsystem coverageVariableConsistent

Spec-First Workflow (Greenfield)

For projects WITHOUT existing code. Write Intent Nodes as specs, then scaffold.

Step 1: Define Scope

  • What's the project vision?
  • What are the major planned subsystems?
  • Who are the stakeholders?

Step 2: Create Spec Root

Use "Spec Root Template" from references/templates.md:

  • Vision statement (not TL;DR of existing code)
  • Planned Subsystems (not discovered from code)
  • Design Constraints (not extracted contracts)
  • Implementation Targets (where to build first)

Step 3: Create Component Specs

For each planned subsystem, create AGENTS.md with:

  • Responsibility Charter (what it will own)
  • Interface Contracts (how others will call it)
  • Acceptance Criteria (how we know it's done)

Step 4: AI Scaffolding

Ask Claude to scaffold against the specs:

  • "Create directory structure matching the Planned Subsystems"
  • "Generate interface stubs for the contracts defined"
  • "Set up test fixtures based on acceptance criteria"

Step 5: Implementation Loop

Build incrementally:

  1. Implement against spec
  2. Update spec as requirements clarify
  3. Spec nodes evolve into documentation nodes

Step 6: Transition to Maintenance

When implementation complete:

  • Fill in discovered Pitfalls
  • Add actual Entry Points
  • Run validate_node.sh and transition to maintenance skill

Concepts

Why Intent Layers? (click to expand)

The Problem

AI agents reading raw code lack the tribal knowledge that experienced engineers have:

  • Where to start for common tasks
  • What patterns are expected
  • What invariants must never be violated
  • What pitfalls to avoid

The Solution

Intent Nodes (CLAUDE.md/AGENTS.md files) provide compressed, high-signal context that tells agents what matters without reading thousands of lines of code.

How It Works

  • Ancestor-based loading: Reading a child node auto-loads all ancestors (T-shaped knowledge)
  • Progressive disclosure: Start minimal, agents drill down when needed
  • Compression: 200k tokens of code → 2k token node (100:1 ratio)
Core Rules (click to expand)

One Root Only

CLAUDE.md and AGENTS.md should NOT coexist at project root. Pick one and symlink the other for cross-tool compatibility.

Child Nodes Named AGENTS.md

Subdirectory nodes should be AGENTS.md (not CLAUDE.md) for cross-tool compatibility.

Token Budgets

  • Each node: <4k tokens (prefer <3k)
  • Target 100:1 compression
  • If you can't compress, scope is too broad → split

What to Document

Keep: code map (non-obvious locations), public API (what others depend on), external dependencies, data flow, decisions with rationale, contracts, patterns (non-obvious steps), pitfalls Delete: obvious mappings (routes.ts → routes), type-enforced invariants, internal exports, standard patterns, tech stack lists

Effort Estimates (click to expand)
Codebase SizeExperiencedNewcomer
<50k tokens1-2 hours3-5 hours
50-150k tokens3-5 hours6-10 hours
>150k tokens5-10 hours10-20 hours

Budget additional time for SME interviews—tribal knowledge takes conversation to extract.


Resources

Scripts

ScriptPurpose
detect_state.shCheck Intent Layer state (none/partial/complete)
analyze_structure.shFind semantic boundaries
estimate_tokens.shMeasure single directory
estimate_all_candidates.shMeasure all candidates at once
validate_node.shCheck node quality before committing
capture_pain_points.shGenerate maintenance capture template
detect_changes.shFind affected nodes on merge/PR
show_status.shHealth dashboard with metrics and recommendations
show_hierarchy.shVisual tree display of all nodes
review_pr.shReview PR against Intent Layer
capture_mistake.shGenerate mistake report for check extraction

Sub-Skills

Sub-SkillLocationPurpose
git-historygit-history/SKILL.mdExtract pitfalls/contracts from commit history
pr-review-miningpr-review-mining/SKILL.mdExtract pitfalls/contracts from PR discussions
pr-reviewpr-review/SKILL.mdReview PRs against Intent Layer contracts

References

FilePurpose
templates.mdRoot (S/M/L) and child templates, three-tier boundaries
node-examples.mdReal-world examples
capture-protocol.mdSME interview questions
compression-techniques.mdHow to achieve 100:1 compression, LCA placement
agent-feedback-protocol.mdContinuous improvement loop

Capture Questions

TL;DR: Ask these when documenting existing code. Focus on what agents can't infer from code itself.

Scope & Navigation

  1. What does this area own? What's explicitly out of scope?
  2. Where do developers commonly search? What's in non-obvious locations?
  3. What are the key relationships between modules? (import direction, layers)

Public Interface

  1. What exports do OTHER modules actually depend on?
  2. What 3-5 types must someone understand to work here?

External Dependencies

  1. What external services does this area use? What happens when they're down?

Design Rationale (the "why")

  1. What problem drove the creation of this module? What pain point does it solve?
  2. What's the core insight or philosophy? What would you lose if you removed it?
  3. What constraints shaped the design? (performance, compatibility, team size, etc.)

Understanding & Debugging

  1. How does data flow through this area? (request → response path)
  2. Why were specific technical choices made? What alternatives were rejected?

Consistency & Safety

  1. What invariants must hold that aren't enforced by types?
  2. What patterns must be followed for common tasks?
  3. What operations require verification before proceeding?

Pitfalls (highest value)

  1. What repeatedly confuses new engineers?
  2. What looks wrong but is correct? What looks correct but will break?

For full protocol: references/capture-protocol.md


When to Create Child Nodes

TL;DR: >20k tokens or responsibility shift → create. Simple utilities → don't.

SignalAction
>20k tokens in directoryCreate AGENTS.md
Responsibility shift (different owner/concern)Create AGENTS.md
Hidden contracts/invariantsDocument in nearest ancestor
Cross-cutting concernPlace at lowest common ancestor

Do NOT create for:

  • Every directory
  • Simple utilities or config-only directories
  • Test folders (unless complex test infrastructure)
  • Directories with <5 source files AND <2k tokens (too little to document meaningfully — a 54-line node for 4 markdown files is filler)

Pre-flight Checks

TL;DR: Testable verifications before risky operations. Add when mistakes reveal missing checks.

What They Are

Pre-flight checks are verifiable assertions an agent runs before modifying code. They catch "I thought I understood" mistakes.

When to Add

SignalAction
Mistake happenedWrite check that would have caught it
PR reviewer flagged missing stepConvert to check
Complex multi-step operationAdd checks for each step
Critical/irreversible operationAdd comprehension + human gate

When NOT to Add

  • Every operation (over-checking slows agents down)
  • Things covered by Boundaries section (use Always/Never instead)
  • Awareness-only items (use Pitfalls instead)

Format

See references/templates.md → Writing Pre-flight Checks for the standard format.

Mining Checks from History

# Find commits suggesting missing verifications
scripts/mine_git_history.sh --since "6 months ago" [directory] | grep -E "fix|broke|forgot"

Look for patterns like "forgot to update X" or "broke Y because didn't check Z".


Capture Order (Leaf-First)

TL;DR: Start at leaves, work up to root. Clarity compounds upward.

Always capture leaf-first, easy-to-hard:

  1. Start with deepest directories (most concrete)

    • Leaf nodes compress raw code—patterns are visible
    • Easier to identify contracts when you see the implementation
  2. Work up to parent nodes (summarize children)

    • Parent nodes compress children's Intent Nodes, not raw code
    • Wait until children are stable before writing parent
  3. Finish with root (summarize entire hierarchy)

    • Root references child nodes, provides navigation
    • Global invariants emerge from seeing all children

Why this order?

  • Clarity compounds upward—parent nodes reference stable children
  • Avoids rewriting parents when children change
  • Natural: understand details before summarizing

Anti-pattern: Starting at root and working down leads to vague descriptions that need constant revision as you discover what's actually in the code.


Feedback Flywheel

TL;DR: Agents surface missing context during work → humans review → Intent Layer improves → future agents start better.

Continuous Improvement Loop

Agent works → Finds gap → Surfaces finding → Human reviews → Node updated → Future agents benefit

During Normal Work

When you encounter gaps while working, surface them using the format in references/agent-feedback-protocol.md:

### Intent Layer Feedback
| Type | Location | Finding |
|------|----------|---------|
| Missing pitfall | `src/api/AGENTS.md` | Rate limiter fails silently when Redis down |

On Merge/PR

Run change detection to identify which nodes need review:

scripts/detect_changes.sh main HEAD

This outputs affected nodes in leaf-first order for systematic review.

Full Protocol

See references/agent-feedback-protocol.md for:

  • When to surface findings
  • Structured feedback format
  • Human review workflow (Accept/Reject/Defer)

Mistake → Check Pipeline

When agents surface mistakes, evaluate for check conversion:

Mistake surfaced → "Would a check have caught this?"
                            │
              ┌─────────────┴─────────────┐
              │                           │
             Yes                          No
              │                           │
              ▼                           ▼
    Write Pre-flight Check         Add to Pitfalls
              │                    (awareness only)
              ▼
    Add to AGENTS.md Pre-flight section

Check conversion template:

Mistake: [What happened]
Operation: [What agent was doing]
Check: Before [operation] → [verification that would have caught it]

Use scripts/capture_mistake.sh to generate structured mistake reports.


Maintenance Flywheel

TL;DR: Update nodes when behavior changes, not just when code changes.

When files change (e.g., on merge):

  1. Identify affected nodes - Run scripts/detect_changes.sh base head
  2. Check behavior change - Did contracts/invariants change, or just formatting?
  3. Update if needed - Behavior change → update affected node
  4. Consider new nodes - Patterns emerging → new node or LCA update?

For full maintenance workflow, use: intent-layer-maintenance skill


What's Next?

After completing initial setup (state = complete):

Immediate Actions

  1. Create symlink for cross-tool compatibility
  2. Test by asking an AI agent to perform a common task
  3. Share with team (note in README or onboarding docs)

Ongoing Maintenance

TriggerAction
QuarterlyRun intent-layer-maintenance skill
Post-incidentUpdate Pitfalls + Contracts
After refactorUpdate Entry Points + Subsystem Boundaries
After new featureUpdate Architecture Decisions + Patterns
PR ReviewAuto-invoke pr-review sub-skill

PR Review Integration (Auto-Invoked)

When reviewing PRs that touch files covered by Intent Layer nodes:

# Automatically run pr-review
scripts/review_pr.sh main HEAD --ai-generated

The pr-review sub-skill will:

  • Check PR against contracts in relevant AGENTS.md
  • Flag if PR approaches documented pitfalls
  • Suggest Intent Layer updates if contracts changed

Optional: CI Integration

- name: Check Intent Layer
  run: ${CLAUDE_PLUGIN_ROOT}/scripts/detect_state.sh .

- name: PR Review (if Intent Layer exists)
  if: github.event_name == 'pull_request'
  run: |
    ${CLAUDE_PLUGIN_ROOT}/scripts/review_pr.sh origin/main HEAD --exit-code

Related Skills

SkillUse When
intent-layer-maintenanceQuarterly audits, post-incident updates
intent-layer-queryAsking questions about the codebase
intent-layer-onboardingOrienting newcomers
git-history (sub-skill)Mining commit history for insights
pr-review-mining (sub-skill)Mining PR discussions for insights
pr-review (sub-skill)Reviewing PRs against Intent Layer

Review Mistakes

Interactively review pending mistake reports from the Intent Layer learning loop.

Overview

When agents make mistakes during development, skeleton reports are auto-captured in .intent-layer/mistakes/pending/. This skill helps you and the user review these reports conversationally, deciding which should become pitfalls in the Intent Layer.

Prerequisites

Check for pending reports:

ls -la ${CLAUDE_PROJECT_DIR:-.}/.intent-layer/mistakes/pending/

Workflow

Step 1: List Pending Reports

find "${CLAUDE_PROJECT_DIR:-.}/.intent-layer/mistakes/pending" \
  \( -name "MISTAKE-*.md" -o -name "SKELETON-*.md" \) \
  -type f 2>/dev/null | sort

If no reports, inform the user there's nothing to review.

Step 2: For Each Report

Read the report and present a summary:

---
**Report**: SKELETON-2026-01-23-1234.md

**Directory**: src/auth/
**Operation**: Edit on login.ts
**What happened**: Tool Edit failed - old_string not found
**Covering node**: src/auth/AGENTS.md

**Analysis**: [Your assessment - is this a real mistake or exploratory?]
---

Step 3: Ask User Decision

Present options clearly:

What would you like to do with this report?

  1. Accept - This is a real gotcha, add as pitfall to AGENTS.md
  2. Reject - Not useful (I'll ask for a reason)
  3. Discard - Exploratory failure, not a real mistake
  4. Enrich - Add more context before deciding
  5. Skip - Review later

Step 4: Execute Decision

On Accept

Run the integration script:

${CLAUDE_PLUGIN_ROOT}/lib/integrate_pitfall.sh "${CLAUDE_PROJECT_DIR:-.}/.intent-layer/mistakes/pending/<filename>"

This will:

  • Find the covering AGENTS.md
  • Extract/generate a pitfall entry
  • Append to the Pitfalls section
  • Move report to integrated/
On Reject

Ask for rejection reason, then:

# Create rejected directory if needed
mkdir -p "${CLAUDE_PROJECT_DIR:-.}/.intent-layer/mistakes/rejected"

# Add rejection reason to file
echo -e "\n### Rejection\n**Reason**: <reason>\n**Date**: $(date -u +"%Y-%m-%dT%H:%M:%SZ")" >> "<file>"

# Move to rejected
mv "<file>" "${CLAUDE_PROJECT_DIR:-.}/.intent-layer/mistakes/rejected/"
On Discard

Simply delete the skeleton:

rm "<file>"

Confirm to user: "Discarded - this was an exploratory failure, not a real mistake."

On Enrich

Open the file for editing or help the user add:

  • Better description of what went wrong
  • Root cause analysis
  • Suggested pitfall text

Then return to Step 3.

On Skip

Move to the next report. Track skipped files to mention at the end.

Step 5: Summary

After reviewing all reports (or when user wants to stop):

## Review Summary

- **Accepted**: 2 (pitfalls added to AGENTS.md)
- **Rejected**: 1
- **Discarded**: 3 (exploratory failures)
- **Skipped**: 1 (still pending)

Remaining pending: 1 report(s)

Report Types

Skeleton Reports (SKELETON-*.md)

Auto-created by PostToolUseFailure hook. Contains:

  • Tool and file context
  • Placeholder fields for root cause and suggested fix
  • Often exploratory failures - review carefully

Common skeleton dispositions:

  • Discard if: Edit failed because string wasn't found (typo, wrong file)
  • Discard if: Bash command failed during exploration
  • Accept if: Failure revealed a non-obvious gotcha about the codebase
  • Enrich then Accept if: Real mistake but needs better description

Full Reports (MISTAKE-*.md)

Created manually via capture_mistake.sh. Contains:

  • Detailed description from human/agent
  • Root cause analysis
  • Suggested fix

Common full report dispositions:

  • Accept if: Well-documented, clear pitfall
  • Reject if: One-off issue, not worth documenting
  • Enrich then Accept if: Good insight but needs clearer pitfall text

Example Conversation

Agent: "I found 3 pending mistake reports. Would you like to review them now?"

User: "yes"

Agent:


Report: SKELETON-2026-01-23-4521.md

Directory: src/api/ Operation: Edit on routes.ts What happened: Edit failed - old_string not found Covering node: src/api/AGENTS.md

Analysis: This looks like the Edit tool couldn't find the exact string to replace. This could be:

  • A typo in the old_string (exploratory)
  • The file had been modified and the string changed (possible gotcha)

What would you like to do? (1) Accept (2) Reject (3) Discard (4) Enrich (5) Skip

User: "3 - it was just a typo"

Agent: "Discarded. Moving to next report..."


Scripts Reference

ScriptPurpose
lib/integrate_pitfall.shAuto-add pitfall to covering AGENTS.md
scripts/capture_mistake.shManual capture (if needed)

All paths: ${CLAUDE_PLUGIN_ROOT}/


Tips

  • Be conservative with Accept - Only document genuine gotchas that would trip up future agents
  • Discard freely - Most skeletons from exploratory failures should be discarded
  • Enrich before Accept - A well-written pitfall is more useful than a vague one
  • Batch review - Review all pending reports periodically rather than one at a time

Agents 5

agents/

4 specialized subagents. Markdown files with YAML frontmatter (description, capabilities) that Claude auto-invokes for analysis tasks.

Purpose

Subagent definitions for Intent Layer analysis. Each is a markdown file that Claude reads when it needs specialized analysis capabilities. They aren't slash commands -- Claude picks them up contextually based on task type.

Agent map

AgentWhen invokedDoes what
explorer.mdSetting up new nodes or adding coverageAnalyzes directory structure, mines history, drafts AGENTS.md
validator.mdAfter creating/updating nodes, or PR reviewDeep semantic validation (contracts enforced? entry points exist?)
auditor.mdQuarterly maintenance, post-mergeDiscovers all nodes, checks staleness, spawns validator per node
change-tracker.mdBefore PR merge, after git pullMaps changed files to covering nodes, classifies severity

Agent pipeline

Explorer -> Validator -> (user approves) -> write AGENTS.md
Auditor -> ChangeTracker -> Validator (targeted)

Explorer creates drafts. Validator checks accuracy. Auditor orchestrates full audits. ChangeTracker narrows scope so Validator doesn't re-check everything.

Entry Points

TaskStart Here
Add a new agentCreate agents/<name>.md with description and capabilities in YAML frontmatter
Understand agent invocationAgents are contextual -- Claude reads them when tasks match their description field
Modify audit behaviorEdit auditor.md (orchestration) or validator.md (per-node checks)

Contracts

  • YAML frontmatter must include description (string) and capabilities (list). Source: CLAUDE.md root contracts.
  • Agents reference scripts via ${CLAUDE_PLUGIN_ROOT}/scripts/ and ${CLAUDE_PLUGIN_ROOT}/lib/.
  • Agents produce markdown output, not JSON. Reports use the table/heading format shown in each agent file.
  • change-tracker.md also has a triggers frontmatter field listing when it fires.

Pitfalls

Agents aren't guaranteed to run

Claude decides whether to use an agent based on context. There's no hook or trigger that forces invocation. The description field is what Claude matches against, so vague descriptions mean the agent gets skipped.

Validator does structural AND semantic checks

validate_node.sh (the script) does structural validation only (token count, required sections, paths). The Validator agent does deeper semantic checks (are contracts actually enforced in code? do entry points exist?). Don't confuse the two.

ChangeTracker severity depends on node content

Severity classification (HIGH/MEDIUM/LOW) reads the node's Entry Points section to determine if a changed file is "important". If Entry Points are stale, severity assessment is wrong too.

Intent Layer Auditor

Detects drift between Intent Layer documentation and actual codebase state.

When to Use

  • Quarterly Intent Layer maintenance
  • After major merges or releases
  • When PostToolUse hook has flagged many edits without node updates
  • User asks to "audit intent layer" or "check for stale documentation"

Audit Process

1. Discover All Nodes

Find all Intent Layer nodes in the codebase:

${CLAUDE_PLUGIN_ROOT}/scripts/show_hierarchy.sh

This produces a tree of all AGENTS.md and CLAUDE.md files.

2. Check for Staleness

Run staleness detection to find nodes that may need updates:

${CLAUDE_PLUGIN_ROOT}/scripts/detect_staleness.sh

This compares:

  • Node file modification time vs covered code modification times
  • Git history of covered directories since last node update
  • Number of commits affecting covered files

3. Validate Each Node (Parallel)

For each node identified, spawn the Validator agent to perform deep validation.

Collect results and aggregate into a single report.

4. Prioritize Findings

Rank issues by impact:

PriorityCategoryRationale
P0Contract failuresMay cause incorrect agent behavior
P1Entry point failuresAgents can't find starting points
P2Pitfall stalenessOutdated warnings, but not actively harmful
P3Pattern driftStyle/convention issues

5. Generate Audit Report

## Intent Layer Audit Report

**Date**: YYYY-MM-DD
**Nodes Audited**: N
**Overall Health**: GOOD | NEEDS_ATTENTION | CRITICAL

### Executive Summary

- X nodes require immediate attention (P0/P1 issues)
- Y nodes have minor drift (P2/P3 issues)
- Z nodes are healthy

### Critical Issues (P0/P1)

| Node | Issue | Impact | Recommended Action |
|------|-------|--------|-------------------|
| src/api/AGENTS.md | Contract violation | HIGH | Update auth contract |
| src/db/AGENTS.md | Entry point missing | MEDIUM | Add new migration entry |

### Minor Issues (P2/P3)

| Node | Issue | Last Updated | Code Changes Since |
|------|-------|--------------|-------------------|
| src/utils/AGENTS.md | 3 new commits | 2024-01-15 | 12 files changed |

### Healthy Nodes

[List of nodes that passed validation]

### Coverage Gaps

Directories with significant code but no Intent Layer coverage:
- src/legacy/ (450 files, 0 nodes)
- src/experimental/ (23 files, 0 nodes)

### Recommended Actions

1. **Immediate**: [P0/P1 fixes]
2. **This sprint**: [P2 updates]
3. **Backlog**: [P3 improvements, coverage gaps]

Automation Integration

With PostToolUse Hook

The hook tracks edits to files covered by Intent Layer. The auditor can:

  1. Read accumulated flags from hook output
  2. Focus validation on frequently-edited areas
  3. Prioritize nodes covering actively-developed code

Scheduled Runs

Recommend running auditor:

  • Weekly: Quick staleness check (detect_staleness.sh only)
  • Monthly: Full validation of flagged nodes
  • Quarterly: Complete audit of all nodes

Scripts Reference

ScriptPurposeWhen Used
show_hierarchy.shList all nodesStep 1: Discovery
detect_staleness.shFind outdated nodesStep 2: Staleness check
validate_node.shValidate single nodeStep 3: Via Validator agent
show_status.shHealth dashboardFinal summary

Output Destinations

  • Console: Summary for interactive use
  • Markdown file: Full report for team review
  • JSON: Machine-readable for CI integration (future)

Intent Layer Change Tracker

Analyzes code changes and maps them to affected Intent Layer nodes, enabling targeted validation instead of full codebase audits.

When to Use

  • Before merging a PR to understand documentation impact
  • After pulling upstream changes to identify nodes needing review
  • When Auditor needs incremental validation (skip unchanged areas)
  • User asks "what nodes are affected by these changes?"

Why This Agent Exists

The Auditor agent re-validates ALL nodes on every audit. For large codebases with many nodes, this is slow and wasteful. ChangeTracker enables:

  1. Targeted validation: Only validate nodes covering changed code
  2. Merge checklists: Generate actionable review items before merge
  3. Impact assessment: Prioritize which nodes need immediate attention

Process

1. Accept Git Reference Range

Input is a git ref range. Common patterns:

InputMeaning
main..HEADChanges on current branch vs main
HEAD~5..HEADLast 5 commits
v1.0.0..v2.0.0Between two tags
(none)Uncommitted changes

2. Detect Changed Files

Run the change detection script:

${CLAUDE_PLUGIN_ROOT}/scripts/detect_changes.sh [base_ref] [head_ref]

This outputs:

  • List of changed files
  • Which Intent Nodes cover those files
  • Files per node count

When reviewers need more than node coverage, run:

${CLAUDE_PLUGIN_ROOT}/scripts/explain_semantic_diff.sh [base_ref] [head_ref]

Use that output to understand which changes look behavioral, which appear internal-only, and which nodes need closer semantic review before updating guidance.

3. Map Files to Covering Nodes

For each changed file, find its covering node:

${CLAUDE_PLUGIN_ROOT}/lib/find_covering_node.sh <file_path>

Build a mapping: { node_path -> [list of changed files] }

Deduplicate: Multiple files often map to the same node.

4. Classify Impact Severity

For each affected node, classify based on what changed:

SeverityTriggerMeaning
HIGHContract-related files changedNode documentation likely needs update
MEDIUMImplementation files changedReview recommended, may need update
LOWMinor files changed (tests, configs, docs)Informational only

Severity classification rules:

HIGH severity if any changed file:
  - Is named in node's "Entry Points" section
  - Contains types/interfaces (contracts)
  - Is a main module file (index.*, main.*, app.*)
  - Has >100 lines changed

MEDIUM severity if any changed file:
  - Is production code (.ts, .js, .py, .go, etc.)
  - Modifies exported functions
  - Changes >20 lines

LOW severity if all changed files are:
  - Test files (*_test.*, *.spec.*, tests/*)
  - Configuration files (*.json, *.yaml, *.toml)
  - Documentation (*.md, comments only)
  - Minor changes (<20 lines)

5. Generate Impact Report

Produce a structured report with three sections:

  1. Affected Nodes Table: Summary of all impacted nodes
  2. Merge Checklist: Actionable items for PR review
  3. Validation Scope: Recommendations for Validator agent

Output Format

## Change Impact Analysis

**Range**: main..HEAD (15 commits, 23 files changed)

### Affected Intent Nodes

| Node | Files Changed | Severity | Reason |
|------|---------------|----------|--------|
| src/api/AGENTS.md | 8 files | HIGH | Contracts may need update |
| src/auth/AGENTS.md | 3 files | MEDIUM | Implementation changes |
| src/utils/AGENTS.md | 2 files | LOW | Minor utility changes |

### Merge Checklist

- [ ] Review Contracts in src/api/AGENTS.md (8 files touched core API)
- [ ] Verify Entry Points still valid in src/auth/AGENTS.md
- [ ] Check for new Pitfalls from code review comments

### Validation Scope

**Validate** (HIGH/MEDIUM impact):
- src/api/AGENTS.md
- src/auth/AGENTS.md

**Skip** (LOW impact, informational only):
- src/utils/AGENTS.md

**Estimated validation time**: ~2 nodes (vs 15 total)

Integration with Other Agents

ChangeTracker -> Auditor

Auditor can invoke ChangeTracker for incremental audits:

Traditional Auditor flow:
1. Discover all nodes (15 nodes)
2. Validate all nodes (slow)

Incremental Auditor flow:
1. ChangeTracker(main..HEAD)
2. Get affected nodes (2 nodes)
3. Validate only affected nodes (fast)

ChangeTracker -> Validator

ChangeTracker produces a focused node list for Validator:

ChangeTracker output:
  Validate: [src/api/AGENTS.md, src/auth/AGENTS.md]
  Skip: [src/utils/AGENTS.md, ...]

Validator receives:
  Task(Validator, src/api/AGENTS.md)
  Task(Validator, src/auth/AGENTS.md)
  // Skips 13 other nodes

ChangeTracker -> PR Review Skill

Before merging, PR review invokes ChangeTracker:

1. ChangeTracker(main..HEAD)
2. explain_semantic_diff.sh main HEAD
3. Generate merge checklist
4. Include checklist in PR review report
5. Optionally run targeted validation

Severity Decision Tree

For each affected node:
  changed_files = files covered by this node that changed

  has_entry_point_change = any file in node's Entry Points changed
  has_contract_file = any file contains types/interfaces
  has_major_change = any file has >100 lines changed

  IF has_entry_point_change OR has_contract_file OR has_major_change:
    severity = HIGH
  ELIF any file is production code with >20 lines changed:
    severity = MEDIUM
  ELSE:
    severity = LOW

Example Workflow

Scenario: PR Review Before Merge

User runs /review-pr or asks "what Intent Layer nodes does this PR affect?"

# Step 1: Detect changes
${CLAUDE_PLUGIN_ROOT}/scripts/detect_changes.sh main HEAD

# Output includes affected nodes with file counts

Agent then:

  1. Parses detect_changes.sh output
  2. For each node, reads the AGENTS.md to check Entry Points
  3. Classifies severity based on what changed vs what's documented
  4. Generates merge checklist
  5. Recommends validation scope

Scenario: Post-Merge Incremental Audit

After git pull brings in upstream changes:

# Step 1: Find what changed since last known state
${CLAUDE_PLUGIN_ROOT}/scripts/detect_changes.sh HEAD~10 HEAD

# Step 2: For HIGH/MEDIUM nodes, run targeted validation
${CLAUDE_PLUGIN_ROOT}/scripts/validate_node.sh src/api/AGENTS.md

Parallelization Notes

ChangeTracker itself is fast (just file mapping). The value is in enabling parallel targeted validation:

Without ChangeTracker:
  Auditor validates 15 nodes sequentially or in batches
  Time: ~15 * 30s = 7.5 minutes

With ChangeTracker:
  ChangeTracker identifies 2 affected nodes (instant)
  Validator runs on 2 nodes in parallel
  Time: ~30s

See ${CLAUDE_PLUGIN_ROOT}/references/parallel-orchestration.md for parallel validation patterns.

Error Handling

No Changes Detected

If git range has no changed files:

## Change Impact Analysis

**Range**: main..HEAD (0 commits, 0 files changed)

No code changes detected. All Intent Layer nodes are current.

No Intent Nodes Found

If repository has no Intent Layer:

## Change Impact Analysis

**Range**: main..HEAD (15 commits, 23 files changed)

No Intent Layer nodes found in repository.
Run `/intent-layer` to set up Intent Layer coverage.

Changed Files Not Covered

If changed files have no covering node:

### Uncovered Changes

The following changed files have no covering Intent Layer node:
- src/experimental/new_feature.ts (47 lines)
- src/legacy/old_module.js (12 lines)

Consider adding coverage or documenting in parent node.

Scripts Reference

ScriptPurposeWhen Used
detect_changes.shFind changed files and affected nodesStep 2: Change detection
lib/find_covering_node.shMap file to covering AGENTS.mdStep 3: Node mapping
validate_node.shValidate single nodePost-analysis targeted validation

Checklist Before Invoking

  • Git repository with history (not a fresh clone with single commit)
  • Valid git ref range (both refs exist)
  • Intent Layer nodes exist in repository
  • For PR review: compare against target branch (usually main)

Intent Layer Explorer

Analyzes directories and proposes AGENTS.md content for Intent Layer coverage.

When to Use

  • Setting up Intent Layer in a new codebase
  • Adding coverage to a directory that lacks an AGENTS.md
  • User asks to "add intent layer to X" or "create AGENTS.md for Y"

Process

1. Analyze Directory Structure

Run the structure analysis script to understand boundaries:

${CLAUDE_PLUGIN_ROOT}/scripts/analyze_structure.sh <directory>

This identifies:

  • Package/module boundaries
  • Semantic clusters (related files)
  • Recommended node placement

2. Estimate Token Budget

Check if the directory needs its own node or can be covered by a parent:

${CLAUDE_PLUGIN_ROOT}/scripts/estimate_tokens.sh <directory>

Target: <4k tokens per node, 100:1 compression ratio.

3. Mine Git History (if applicable)

For directories with significant git history (>50 commits), extract pitfalls:

${CLAUDE_PLUGIN_ROOT}/scripts/mine_git_history.sh <directory>

This reveals:

  • Bug patterns from fix commits
  • Anti-patterns from reverts
  • Architecture decisions from refactors

4. Draft AGENTS.md

Using the templates in ${CLAUDE_PLUGIN_ROOT}/references/templates.md, create a draft with:

Required sections:

  • TL;DR (one-line summary)
  • Entry Points (where to start)
  • Contracts (invariants, constraints)

Optional sections (based on analysis):

  • Pitfalls (from git history mining)
  • Patterns (if non-obvious)
  • Anti-Patterns (from reverts/fixes)

5. Validate Draft

Before presenting to user, run validation:

${CLAUDE_PLUGIN_ROOT}/scripts/validate_node.sh <draft-path>

Output Format

Present the draft with confidence scores:

## Proposed AGENTS.md for <directory>

### Confidence Scores
- Contracts: HIGH (verified in code)
- Entry Points: HIGH (found in imports)
- Pitfalls: MEDIUM (mined from 23 commits)
- Patterns: LOW (inferred, needs review)

### Draft Content
[AGENTS.md content here]

### Review Notes
- [Items needing human verification]

Integration with Other Agents

After explorer creates a draft:

  1. Validator should verify accuracy against actual code
  2. User reviews and approves
  3. Write the final AGENTS.md

Templates Reference

Load templates from: ${CLAUDE_PLUGIN_ROOT}/references/templates.md

Use compression techniques from: ${CLAUDE_PLUGIN_ROOT}/references/compression-techniques.md

Intent Layer Validator

Validates that AGENTS.md/CLAUDE.md nodes accurately reflect their covered codebase.

When to Use

  • After creating or updating an Intent Layer node
  • As part of PR review when changes touch covered areas
  • When user asks to "validate intent layer" or "check AGENTS.md accuracy"
  • Before marking a node as production-ready

Validation Process

1. Load the Node

Read the AGENTS.md file and parse its sections:

${CLAUDE_PLUGIN_ROOT}/scripts/validate_node.sh <path-to-agents-md>

The script provides structural validation. This agent does deep semantic validation.

2. Validate Each Section

Contracts Validation

For each documented contract:

  1. Search for enforcement in code (guards, assertions, type checks)
  2. Look for violations that would indicate stale documentation
  3. Check if contract scope matches reality

Validation criteria:

  • PASS: Contract enforced in code, no violations found
  • WARN: Contract mentioned but enforcement unclear
  • FAIL: Contract violated in code, or no enforcement exists
Entry Points Validation

For each documented entry point:

  1. Verify file/function exists
  2. Check if it's actually used as an entry point (imported/called)
  3. Look for undocumented entry points

Validation criteria:

  • PASS: Entry point exists and is actively used
  • WARN: Entry point exists but usage unclear
  • FAIL: Entry point doesn't exist or is deprecated
Pitfalls Validation

For each documented pitfall:

  1. Check if the pitfall condition still exists in code
  2. Look for recent fixes that might have resolved it
  3. Search for new pitfalls from recent commits

Validation criteria:

  • PASS: Pitfall is current and relevant
  • WARN: Pitfall may be outdated (related code changed)
  • FAIL: Pitfall no longer applies (condition removed)
Patterns Validation

For each documented pattern:

  1. Search for pattern usage across covered files
  2. Count adherence vs. violations
  3. Identify undocumented patterns with high usage

Validation criteria:

  • PASS: Pattern followed consistently (>80% adherence)
  • WARN: Pattern followed inconsistently (50-80%)
  • FAIL: Pattern not followed (<50%) or contradicted

3. Generate Validation Report

## Validation Report: <path-to-node>

### Summary
- **Overall Status**: PASS | WARN | FAIL
- **Sections Validated**: N
- **Issues Found**: X warnings, Y failures

### Section Results

#### Contracts [STATUS]
| Contract | Status | Evidence |
|----------|--------|----------|
| "Auth required for /api/*" | PASS | Middleware at api/auth.ts:15 |
| "Rate limit 100/min" | WARN | Config exists but no enforcement found |

#### Entry Points [STATUS]
| Entry Point | Status | Notes |
|-------------|--------|-------|
| src/api/index.ts | PASS | Main API router |
| src/utils/deprecated.ts | FAIL | File deleted in commit abc123 |

#### Pitfalls [STATUS]
...

#### Patterns [STATUS]
...

### Recommendations
1. [Specific actions to resolve failures]
2. [Suggestions for warnings]
3. [Undocumented items to consider adding]

Integration Points

  • Explorer → creates draft → Validator verifies
  • Auditor → spawns Validator for each node
  • PostToolUse hook → flags files → Validator checks affected nodes

Validation Thresholds

StatusMeaningAction Required
PASSNode accurately reflects codeNone
WARNMinor discrepancies or uncertaintyReview recommended
FAILSignificant inaccuracy detectedUpdate required

Overall status is the worst status of any section.

Sponsors

Details

Marketplace
orban/intent-layer
Category
Community