#!/usr/bin/env node
import {e}from'./chunk-JQKKVAAN.js';import*as r from'fs';import*as c from'path';import*as ce from'os';import*as N from'js-yaml';function se(e,s){let n=[];return n.push(`# ${e} - Paradigm Context`),n.push(""),n.push(`Generated for ${s} by Paradigm.`),n.push(""),n.join(`
`)}function P(e){let s=[];if(e["agent-guidelines"]?.overview&&(s.push("## Overview"),s.push(""),s.push(e["agent-guidelines"].overview),s.push("")),e["agent-guidelines"]?.["how-to-use"]?.length){s.push("## How to Use Paradigm"),s.push("");for(let n of e["agent-guidelines"]["how-to-use"])s.push(`- ${n}`);s.push("");}return s.join(`
`)}function C(e){let s=[];s.push("## Symbol System"),s.push(""),s.push("Use these prefixes to reference project elements:"),s.push(""),s.push("| Symbol | Name | Description |"),s.push("|--------|------|-------------|");let n=e["symbol-system"];if(n)for(let[a,t]of Object.entries(n))s.push(`| \`${a}\` | ${t.name} | ${t.description} |`);return s.push(""),s.push("See `.paradigm/specs/symbols.md` for complete reference."),s.push(""),s.join(`
`)}function w(e){let s=[];if(!e.logging?.enforce)return "";if(s.push("## Paradigm Logging"),s.push(""),s.push("**IMPORTANT:** Use the Paradigm logger instead of raw console.log/print."),s.push(""),s.push("```"),s.push("// Use this pattern:"),s.push("log.component('#login-handler').info('Starting login', { email });"),s.push("log.component('#database').debug('Query executed', { duration });"),s.push("log.gate('^authenticated').warn('Access denied', { userId });"),s.push("log.signal('!login-success').info('User authenticated');"),s.push("```"),s.push(""),e.logging["symbol-mapping"]){s.push("### Symbol Mapping by Directory"),s.push(""),s.push("| Directory | Symbol | Logger Method |"),s.push("|-----------|--------|---------------|");for(let[n,a]of Object.entries(e.logging["symbol-mapping"])){let t=ge(a);s.push(`| \`${n}\` | \`${a}\` | \`log.${t}()\` |`);}s.push("");}return s.push("See `.paradigm/specs/logger.md` for full specification."),s.push(""),s.join(`
`)}function ge(e){return {"#":"component","^":"gate","!":"signal",$:"flow","~":"aspect","@":"component","%":"component","&":"component"}[e]||"raw"}function ne(e){if(!e.scan?.enabled)return "";let s=[];return s.push("## Paradigm Scan"),s.push(""),s.push('When the user says "**paradigm scan**" with an image:'),s.push(""),s.push("1. Analyze the image for UI elements"),s.push("2. Cross-reference with `.paradigm/scan-index.json`"),s.push("3. Return structured mapping of visual elements to code"),s.push(""),s.push("| Mode | Use Case |"),s.push("|------|----------|"),s.push("| `paradigm scan` | Map any image to code |"),s.push("| `paradigm scan ui` | Screenshot of running app |"),s.push("| `paradigm scan design` | Mockup - gap analysis |"),s.push("| `paradigm scan error` | Error screenshot |"),s.push(""),s.push("See `.paradigm/specs/scan.md` for full protocol."),s.push(""),s.join(`
`)}function b(e){if(!e.conventions?.length)return "";let s=[];s.push("## Conventions"),s.push("");for(let n of e.conventions)s.push(`- ${n}`);return s.push(""),s.join(`
`)}function S(e){if(!e["agent-guidelines"]?.["update-rules"]?.length)return "";let s=[];s.push("## When to Update Paradigm Files"),s.push("");for(let n of e["agent-guidelines"]["update-rules"])s.push(`- ${n}`);return s.push(""),s.join(`
`)}function x(){let e=[];return e.push("## Paradigm Commands"),e.push(""),e.push("| Command | Description |"),e.push("|---------|-------------|"),e.push("| `paradigm init` | Initialize Paradigm in a project |"),e.push("| `paradigm sync` | Regenerate IDE instruction files |"),e.push("| `paradigm index` | Generate scan index |"),e.push("| `paradigm doctor` | Health check |"),e.push("| `paradigm status` | Show project status |"),e.push("| `paradigm watch` | Auto-sync on changes |"),e.push(""),e.push("See `.paradigm/docs/commands.md` for full reference."),e.push(""),e.join(`
`)}function ae(e){let s=[];return s.push("## Paradigm Navigation"),s.push(""),s.push("Before exploring this codebase:"),s.push(""),s.push("1. Read `.paradigm/navigator.yaml` for structure map"),s.push("2. Query by symbol - lookup paths directly"),s.push("3. Respect skip patterns (node_modules, dist, etc.)"),s.push(""),s.push("### Exploration Protocol"),s.push(""),s.push("**INSTEAD OF:** Broad exploration (expensive token usage)"),s.push(""),s.push("**DO THIS:**"),s.push("1. Read `.paradigm/navigator.yaml` for structure map"),s.push("2. Find relevant symbol \u2192 go to path"),s.push("3. Read only needed files"),s.push(""),s.push("### Task Recipes"),s.push(""),s.push("**Adding a feature:**"),s.push("1. Check `navigator.yaml` \u2192 `structure.features.paths`"),s.push("2. Read existing feature as template"),s.push("3. Create in same location"),s.push(""),s.push("**Modifying a component:**"),s.push("1. Look up symbol in `navigator.yaml` \u2192 `symbols`"),s.push("2. Go directly to the path"),s.push("3. Check `paradigm_ripple` for impact"),s.push(""),s.push("**Using MCP Tools:**"),s.push('- `paradigm_navigate({ intent: "find", target: "#checkout" })` - locate symbol'),s.push('- `paradigm_navigate({ intent: "explore", target: "auth" })` - browse area'),s.push('- `paradigm_navigate({ intent: "context", task: "add login" })` - task context'),s.push(""),s.push("### PM Governance (Before/After Tasks)"),s.push(""),s.push("| When | Tool | Purpose |"),s.push("|------|------|---------|"),s.push("| Starting any task | `paradigm_pm_preflight` | Get compliance plan, affected symbols, required checks |"),s.push("| Finishing any task | `paradigm_pm_postflight` | Check for violations: missing .purpose, missing gates |"),s.push(""),s.join(`
`)}function v(){let e=[];return e.push("## Commit Messages"),e.push(""),e.push("Use v2 symbols in commits for history tracking:"),e.push(""),e.push("### Format"),e.push("```"),e.push("type(#primary-symbol): short description"),e.push(""),e.push("- Detail with #component references"),e.push("- Gate changes: ^gate-name"),e.push("- Signals emitted: !signal-name"),e.push(""),e.push("Symbols: #symbol-a, #symbol-b, !signal-c"),e.push("```"),e.push(""),e.push("### Convention"),e.push("- **Subject**: `type(#symbol): description` \u2014 primary symbol in parens"),e.push("- **Body**: Reference affected symbols with prefixes (# $ ^ ! ~)"),e.push("- **Trailer**: `Symbols: #a, #b, !c` \u2014 machine-readable list of ALL affected symbols"),e.push("- The `Symbols:` trailer is parsed by the post-commit hook for automatic history capture"),e.push(""),e.push("### Examples"),e.push("```"),e.push("feat(#payment-form): add Apple Pay support"),e.push(""),e.push("- Add #apple-pay-button component"),e.push("- Update $checkout-flow with new payment step"),e.push("- Emit !payment-method-added signal"),e.push("- Gate: ^authenticated required"),e.push(""),e.push("Symbols: #payment-form, #apple-pay-button, $checkout-flow, !payment-method-added"),e.push("```"),e.push(""),e.join(`
`)}function ie(){let e=[];return e.push("## MCP Tools"),e.push(""),e.push("Paradigm provides MCP tools for token-efficient, always-fresh data. Prefer these over reading files directly."),e.push(""),e.push("| Tool | Description | When to Use |"),e.push("|------|-------------|-------------|"),e.push("| `paradigm_status` | Project overview and symbol counts | Starting a session |"),e.push("| `paradigm_search` | Find symbols by name, description, or tags | Looking for symbols |"),e.push("| `paradigm_navigate` | Find code locations, explore areas, get task context | Locating code |"),e.push("| `paradigm_ripple` | Dependency and impact analysis | Before modifying symbols |"),e.push("| `paradigm_related` | Direct relationships for a symbol | Understanding connections |"),e.push("| `paradigm_gates_for_route` | Suggest gates for an API endpoint | Adding API routes |"),e.push("| `paradigm_wisdom_context` | Team preferences and antipatterns | Before implementing |"),e.push("| `paradigm_history_fragility` | Stability warnings for symbols | Before modifying fragile areas |"),e.push("| `paradigm_flow_validate` | Validate flow definitions | Before/after implementing flows |"),e.push("| `paradigm_flows_affected` | Flows impacted by symbol changes | After modifying symbols |"),e.push("| `paradigm_test_fixtures` | Get test data for validation | Writing tests |"),e.push("| `paradigm_orchestrate_inline` | Multi-agent task planning | Complex tasks (3+ files) |"),e.push("| `paradigm_pm_preflight` | Pre-task compliance check | Starting any task |"),e.push("| `paradigm_pm_postflight` | Post-task violation detection | Finishing any task |"),e.push("| `paradigm_session_recover` | Load previous session breadcrumbs | Starting a new session |"),e.push("| `paradigm_context_check` | Check context window usage | Every 10-15 tool calls |"),e.push("| `paradigm_handoff_prepare` | Prepare session handoff summary | When context is high |"),e.push("| `paradigm_reindex` | Rebuild static index files | After modifying .purpose files |"),e.push("| `paradigm_session_checkpoint` | Save cognitive-transition checkpoint | Phase transitions |"),e.push("| `paradigm_session_stats` | Current session token usage | Checking budget |"),e.push(""),e.push("**Rule**: Use MCP tools for discovery and validation, file reads for implementation."),e.push(""),e.join(`
`)}function re(){let e=[];return e.push("## Workflow Protocol"),e.push(""),e.push("### Before Each Task"),e.push(""),e.push("1. **Preflight**: Call `paradigm_pm_preflight` with your task description"),e.push("   - Returns affected symbols, ripple analysis, required agents"),e.push("2. **Impact check**: Call `paradigm_ripple` for any symbols you'll modify"),e.push("3. **Gate check**: Call `paradigm_gates_for_route` before adding API endpoints"),e.push('4. **Complex tasks** (3+ files, security + implementation): Call `paradigm_orchestrate_inline` with mode="plan"'),e.push(""),e.push("### After Each Task"),e.push(""),e.push("1. **Postflight**: Call `paradigm_pm_postflight` with modified files and symbols"),e.push("   - Checks for missing .purpose files, unregistered routes, uncaptured wisdom"),e.push("2. **Reindex**: Call `paradigm_reindex` to rebuild static index files"),e.push("3. **Validate flows**: Call `paradigm_flow_validate` if you touched flow-related symbols"),e.push(""),e.join(`
`)}function oe(){let e=[];return e.push("## Session Recovery & Handoff"),e.push(""),e.push("### Session Start (EVERY new session)"),e.push(""),e.push("Call `paradigm_session_recover` to load previous session breadcrumbs."),e.push("Returns: symbols modified, files explored, recent actions, and suggestions."),e.push(""),e.push("### Context Monitoring"),e.push(""),e.push("Call `paradigm_context_check` every 10-15 tool calls to track context usage."),e.push(""),e.push("| Usage | Recommendation | Action |"),e.push("|-------|----------------|--------|"),e.push("| <50% | continue | Keep working |"),e.push("| 50-70% | consider-handoff | Plan handoff; prepare summary when ready |"),e.push("| 70-85% | handoff-recommended | Prepare handoff soon |"),e.push("| >85% | handoff-urgent | Handoff after current task |"),e.push(""),e.push("### Handoff Process"),e.push(""),e.push("1. Call `paradigm_handoff_prepare` with summary, next steps, and target agent"),e.push('2. User runs: `paradigm team handoff --to <agent> --summary "..."`'),e.push("3. New session accepts: `paradigm team accept <handoff-id>`"),e.push(""),e.join(`
`)}function $(){let e=[];return e.push("## Session Checkpoints"),e.push(""),e.push("**Auto-recovery**: Recovery data is automatically surfaced on your first Paradigm tool call \u2014 no action needed to receive it."),e.push(""),e.push("Save checkpoints when transitioning between workflow phases to enable crash recovery:"),e.push(""),e.push("| Phase | Trigger | What to Capture |"),e.push("|-------|---------|-----------------|"),e.push("| `planning` | After reading requirements / before coding | Plan, approach, key decisions |"),e.push("| `implementing` | After starting code changes | Modified files, symbols touched, decisions made |"),e.push("| `validating` | After implementation, before tests/review | All modified files, test plan |"),e.push("| `complete` | Task finished | Summary, final file list |"),e.push(""),e.push("### Usage"),e.push(""),e.push("```"),e.push("paradigm_session_checkpoint({"),e.push('  phase: "implementing",'),e.push('  context: "Adding JWT auth middleware to /api/projects routes",'),e.push('  modifiedFiles: ["src/middleware/auth.ts", "src/routes/projects.ts"],'),e.push('  symbolsTouched: ["^authenticated", "#project-routes"],'),e.push('  decisions: ["Using RS256 for JWT signing", "Storing refresh tokens in httpOnly cookies"]'),e.push("})"),e.push("```"),e.push(""),e.push("Keep it lightweight: `phase` + `context` are required, everything else is optional."),e.push(""),e.join(`
`)}function E(){let e=[];return e.push("## Habits Compliance"),e.push(""),e.push("Paradigm tracks behavioral habits \u2014 repeatable practices that improve code quality."),e.push(""),e.push("### When to Check Habits"),e.push(""),e.push("| Trigger | When | Tool |"),e.push("|---------|------|------|"),e.push('| `preflight` | Before starting implementation | `paradigm_habits_check({ trigger: "preflight" })` |'),e.push('| `postflight` | After completing implementation | `paradigm_habits_check({ trigger: "postflight" })` |'),e.push('| `on-stop` | Before ending a session | `paradigm_habits_check({ trigger: "on-stop" })` |'),e.push(""),e.push("### Key Habit Categories"),e.push(""),e.push("| Category | Examples |"),e.push("|----------|----------|"),e.push("| Discovery | Call `paradigm_ripple` before modifying symbols |"),e.push("| Security | Declare gates for new routes in portal.yaml |"),e.push("| Documentation | Update .purpose files for modified components |"),e.push("| Quality | Record lore for sessions modifying 3+ files |"),e.push(""),e.push("Use `paradigm_practice_context` before modifying symbols to get habit-aware warnings."),e.push(""),e.join(`
`)}function D(){let e=[];return e.push("## Lore Recording"),e.push(""),e.push("Lore captures the project timeline \u2014 sessions, decisions, milestones, and incidents."),e.push(""),e.push("### When to Record Lore"),e.push(""),e.push("| Type | When | Example |"),e.push("|------|------|---------|"),e.push('| `agent-session` | After modifying 3+ files | "Added JWT auth to /api/projects" |'),e.push('| `decision` | After making architectural choices | "Chose Redis over Memcached for caching" |'),e.push('| `milestone` | After completing a significant feature | "v2.0 migration complete" |'),e.push('| `incident` | After resolving a production issue | "Fixed OOM in payment worker" |'),e.push(""),e.push("### Recording"),e.push(""),e.push("```"),e.push("paradigm_lore_record({"),e.push('  type: "agent-session",'),e.push('  title: "Short description of work done",'),e.push('  summary: "Detailed summary of changes...",'),e.push('  symbols_touched: ["#component", "^gate"]'),e.push("})"),e.push("```"),e.push(""),e.push("Use `paradigm_lore_timeline` at session start for project history orientation."),e.push(""),e.join(`
`)}function U(){let e=[];return e.push("## llms.txt"),e.push(""),e.push("This project provides an `llms.txt` file at the repository root \u2014 a plain-text summary"),e.push("of the project optimized for LLM consumption. It includes symbols, key files, flows,"),e.push("gates, and conventions."),e.push(""),e.push("Regenerate with: `paradigm sync-llms`"),e.push(""),e.join(`
`)}function pe(){let e=[];return e.push("---"),e.push(""),e.push("## Reference Files"),e.push(""),e.push("- `.paradigm/specs/symbols.md` - Symbol system reference"),e.push("- `.paradigm/specs/logger.md` - Logging specification"),e.push("- `.paradigm/specs/scan.md` - Scan protocol"),e.push("- `.paradigm/docs/commands.md` - CLI reference"),e.push("- `.paradigm/docs/patterns.md` - Coding patterns"),e.push("- `.paradigm/docs/troubleshooting.md` - Common issues"),e.push("- `.paradigm/prompts/` - Pre-written task prompts"),e.push(""),e.push("*Generated by Paradigm. Run `paradigm sync` to regenerate.*"),e.join(`
`)}function g(e,s={}){let n=["---",`description: ${e}`];return s.globs&&n.push(`globs: ${s.globs}`),s.alwaysApply!==void 0&&n.push(`alwaysApply: ${s.alwaysApply}`),n.push("---",""),n.join(`
`)}var G=class{name="cursor";displayName="Cursor";outputPath=".cursor/rules";multiFile=true;detect(s){return !!(r.existsSync(c.join(s,".cursor"))||r.existsSync(c.join(s,".cursorrules"))||r.existsSync(c.join(s,".vscode")))}generate(s){return this.generateFiles(s).map(a=>`# ${a.path}

${a.content}`).join(`

---

`)}generateFiles(s,n){let{config:a,projectName:t}=s,i=[];i.push({path:"paradigm-core.mdc",content:this.generateCoreRules(t,a)}),i.push({path:"paradigm-workflow.mdc",content:this.generateWorkflowMdc()}),i.push({path:"paradigm-symbols.mdc",content:this.generateSymbolRules(a)}),w(a)&&i.push({path:"paradigm-logging.mdc",content:this.generateLoggingMdc(a)}),i.push({path:"paradigm-purpose.mdc",content:this.generatePurposeMdc()}),i.push({path:"paradigm-portal.mdc",content:this.generatePortalMdc()}),i.push({path:"paradigm-commands.mdc",content:this.generateCommandsMdc()}),i.push({path:"paradigm-conventions.mdc",content:this.generateConventionsMdc(a)}),i.push({path:"paradigm-agent-hints.mdc",content:this.generateAgentHintsMdc()}),i.push({path:"paradigm-navigator.mdc",content:this.generateNavigatorMdc()}),i.push({path:"paradigm-context.mdc",content:this.generateContextMdc()});let p=n?this.loadAgentsManifest(n):null;return i.push({path:"paradigm-orchestration.mdc",content:this.generateOrchestrationMdc(p)}),i.push({path:"paradigm-flows.mdc",content:this.generateFlowsMdc()}),i.push({path:"paradigm-practices.mdc",content:this.generatePracticesMdc()}),i.push({path:"paradigm-commits.mdc",content:this.generateCommitsMdc()}),i}generateCoreRules(s,n){let a=P(n);return g("Paradigm core rules - project overview and fundamentals",{alwaysApply:true})+`# Paradigm - ${s}

> **Author:** Matt Canoy ([@ascend42](https://github.com/ascend42)) | **Repo:** [github.com/ascend42/a-paradigm](https://github.com/ascend42/a-paradigm) | **npm:** [@a-company/paradigm](https://www.npmjs.com/package/@a-company/paradigm)

## CRITICAL RULES (Non-Negotiable)

1. **You MUST update the nearest \`.purpose\` file when you change behavior.** No exceptions.
2. **You MUST call \`paradigm_session_recover\` at session start and \`paradigm_pm_postflight\` when finishing.** See \`paradigm-workflow.mdc\` for the full protocol.
3. **You MUST call \`paradigm_ripple\` before modifying any documented symbol.** Check impact before changing code.

Violating these rules means your changes are non-compliant. The \`paradigm-workflow.mdc\` file contains the complete workflow \u2014 follow it.

`+a+`

`+S(n)}generateSymbolRules(s){return g("Paradigm symbol system - understand #components, $flows, ^gates, !signals, ~aspects",{alwaysApply:true})+C(s)}generateLoggingMdc(s){return g("Paradigm logger usage for TypeScript/JavaScript code",{globs:"**/*.{ts,tsx,js,jsx}",alwaysApply:false})+w(s)}generatePurposeMdc(){return g("Purpose file conventions - .purpose file format and usage",{globs:"**/.purpose",alwaysApply:false})+`# Purpose Files

Purpose files (\`.purpose\`) define the context for directories.

## Format

\`\`\`yaml
# Directory context
description: What this directory contains and why

# Components (# symbol) \u2014 all documented code units
components:
  component-name:
    description: What this component does
    tags: [feature]                # Classification via tag bank
    gates: [^gate1, ^gate2]       # Required gates
    signals: [!signal1]           # Events emitted
    used-by: [#other-component]
\`\`\`

## Symbol References (v2)

- Reference components: \`#component-name\`
- Reference flows: \`$flow-name\`
- Reference gates: \`^gate-name\`
- Reference signals: \`!signal-name\`
- Reference aspects: \`~aspect-name\`
`}generatePortalMdc(){return g("Portal (gate) configuration rules",{globs:"**/portal.yaml",alwaysApply:false})+`# Portal Configuration

Portal files (\`portal.yaml\`) define authorization topology.

## Format

\`\`\`yaml
version: "1.0"

gates:
  gate-name:
    description: What this gate protects
    locks:
      - id: lock-id
        description: Requirement description
        keys:
          - expression: "user.authenticated"
            description: User must be logged in
    prizes:
      - id: prize-id
        oneTime: true
        metadata:
          event: "gate_passed"

flows:
  flow-name:
    description: User journey
    gates: [gate1, gate2, gate3]
\`\`\`

## Portal Validation

Use the Portal Validator for authorization checks:

\`\`\`typescript
import { portal } from '@a-company/portal-sdk/validator';

const gate = portal.check('^gate-name')
  .requires('requirement description')
  .context({ userId, role });

if (!condition) {
  gate.deny('Reason for denial');
  return redirect('/unauthorized');
}

gate.allow('Access granted');
\`\`\`
`}generateCommandsMdc(){return g("Paradigm CLI commands reference",{alwaysApply:false})+x()}generateConventionsMdc(s){return g("Paradigm coding conventions",{globs:"**/*.{ts,tsx,js,jsx}",alwaysApply:false})+b(s)}generateAgentHintsMdc(){return g("Paradigm MCP tool queries for AI agents - use MCP tools instead of reading large files or running CLI commands",{alwaysApply:true})+`# Agent MCP Queries (Token-Efficient)

**Use MCP tool calls, NOT CLI commands.** MCP tools return structured data directly \u2014 no shell overhead, no parsing, no latency.

## When to Query

| Before doing this... | Call this MCP tool |
|---------------------|-------------------|
| Modifying a symbol | \`paradigm_ripple({ symbol: "#symbol" })\` |
| Debugging / searching | \`paradigm_search({ query: "ERROR_CODE" })\` |
| Starting a session | \`paradigm_session_recover()\` |
| Understanding relationships | \`paradigm_navigate({ intent: "find", target: "#symbol" })\` |
| Getting oriented | \`paradigm_status()\` |
| Checking impact on flows | \`paradigm_flows_affected({ symbol: "#symbol" })\` |
| Adding API endpoints | \`paradigm_gates_for_route({ method: "POST", path: "/api/resource" })\` |

## Query Patterns

### Before Changing Code

\`\`\`
// See what depends on what you're changing
paradigm_ripple({ symbol: "#checkout" })

// Returns: upstream deps, downstream effects, flow membership
\`\`\`

### When Debugging

\`\`\`
// Search for error context
paradigm_search({ query: "AUTH_REQUIRED" })

// Then check ripple effects of the related symbol
paradigm_ripple({ symbol: "^authenticated" })
\`\`\`

### Starting Work

\`\`\`
// Load previous session context (MUST do this at session start)
paradigm_session_recover()

// Quick project orientation
paradigm_status()
\`\`\`

### Finding Code Locations

\`\`\`
// Find a specific symbol
paradigm_navigate({ intent: "find", target: "#checkout" })

// Explore an area of code
paradigm_navigate({ intent: "explore", target: "authentication" })

// Get context for a task
paradigm_navigate({ intent: "context", task: "add Apple Pay" })
\`\`\`

## Why MCP Over CLI

- **No shell overhead**: Direct structured responses, no \`--json\` flags or \`jq\` parsing
- **Fresh data**: Always current, not stale from file generation
- **Precise**: Only get the data you need
- **Token-efficient**: ~100-300 tokens per query vs ~2000 for file reads
- **No latency**: No process spawn \u2014 MCP tools respond directly
`}generateNavigatorMdc(){return g("Paradigm Navigator - efficient codebase exploration",{alwaysApply:true})+`# Paradigm Navigator

## Exploration Protocol

Before exploring this codebase:

1. **Read \`.paradigm/navigator.yaml\`** for the structure map
2. **Query by symbol** - lookup paths directly from the symbols map
3. **Respect skip patterns** - avoid node_modules, dist, .git, etc.

## Navigation Strategy

**INSTEAD OF:** Broad exploration (expensive token usage)

**DO THIS:**
1. Read \`.paradigm/navigator.yaml\` for project structure
2. Find relevant symbol \u2192 go directly to path
3. Read only needed files

## Using MCP Navigate Tool

\`\`\`
# Find a specific symbol
paradigm_navigate({ intent: "find", target: "#checkout" })

# Explore an area
paradigm_navigate({ intent: "explore", target: "authentication" })

# Get context for a task
paradigm_navigate({ intent: "context", task: "add Apple Pay" })
\`\`\`

## Task Recipes

### Adding a Feature
1. Check \`navigator.yaml\` \u2192 \`structure.features.paths\`
2. Read an existing feature as template
3. Create in the same location

### Modifying a Component
1. Look up symbol in \`navigator.yaml\` \u2192 \`symbols\`
2. Go directly to the path
3. Use \`paradigm_ripple\` to check impact

### Understanding Dependencies
1. Use \`paradigm_navigate({ intent: "context", task: "..." })\`
2. Read suggested files in order
3. Skip patterns in the \`skip\` array

## Key Files (Quick Reference)

Always available in \`navigator.yaml\`:
- \`key_files.config\` - Configuration files
- \`key_files.entry\` - Entry points
- \`key_files.types\` - Type definitions
`}generateContextMdc(){return g("Session recovery and handoff - call paradigm_session_recover at session start, paradigm_context_check periodically during long sessions, paradigm_handoff_prepare when context is high.")+`# Context Monitoring Protocol

## Session Start (EVERY new session)

Call \`paradigm_session_recover\` to load previous session breadcrumbs.
Returns: symbols modified, files explored, recent actions, and suggestions.

## Periodic Checks

**Every 10-15 tool calls** (or when user asks about context), call:

\`\`\`
paradigm_context_check()
\`\`\`

This returns a recommendation: \`continue\`, \`consider-handoff\`, \`handoff-recommended\`, or \`handoff-urgent\`.

## When to Handoff

| Usage | Recommendation | Action |
|-------|----------------|--------|
| <50% | continue | Keep working |
| 50-70% | consider-handoff | Plan handoff; prepare summary when ready |
| 70-85% | handoff-recommended | Prepare handoff soon |
| >85% | handoff-urgent | Handoff after current task |

## When Recommendation is NOT "continue"

1. **Inform user**: "Context usage is at ~X%. Recommend handoff soon."
2. **Offer to prepare**: Ask if user wants handoff summary
3. **If urgent (>85%)**: Prioritize completing current task, then handoff

## Handoff Process

1. Call \`paradigm_handoff_prepare\` with:
   - Summary of work completed
   - List of next steps
   - Target agent role

2. User runs CLI command:
   \`\`\`bash
   paradigm team handoff --to <agent> --summary "..."
   \`\`\`

3. New session accepts:
   \`\`\`bash
   paradigm team accept <handoff-id>
   \`\`\`

## Session Stats

Get current stats anytime:
\`\`\`
paradigm_session_stats()
\`\`\`

${$()}`}generateWorkflowMdc(){return g("Paradigm workflow protocol - MUST follow for every task. Session bookends, task-size compliance, essential MCP tools.",{alwaysApply:true})+`# Paradigm Workflow Protocol

**This file defines the non-negotiable workflow for every task. Follow it.**

## Session Bookends (MUST Do)

### Session Start
\`\`\`
paradigm_session_recover()
\`\`\`
Call this FIRST in every session. Returns previous context, modified symbols, and suggestions.

### Session End
\`\`\`
paradigm_pm_postflight({ summary: "what you did" })
\`\`\`
Call this LAST before finishing. Catches missing .purpose files, missing gates, and compliance gaps.

## Task-Size Compliance Guide

Not every task needs the full ceremony. Match your effort to the scope:

### Single-file bug fix (1 file changed)
1. Session bookends (start + end)
2. That's it \u2014 fix the bug, run postflight

### Multi-file fix (2-3 files changed)
1. Session bookends
2. \`paradigm_ripple({ symbol: "#affected-symbol" })\` before changing
3. Update nearest \`.purpose\` file if behavior changed
4. Postflight

### Feature build (3+ files, new behavior)
1. Session bookends
2. \`paradigm_pm_preflight({ task: "description" })\` \u2014 get compliance plan
3. \`paradigm_ripple\` for each symbol you'll modify
4. Implement the feature
5. Create/update \`.purpose\` files for new directories
6. Update \`portal.yaml\` if adding protected routes
7. \`paradigm_pm_postflight\` \u2014 verify compliance
8. \`paradigm_lore_record\` \u2014 record what you learned

## The One Non-Negotiable Rule

**You MUST update the nearest \`.purpose\` file when you change behavior.**

- Adding a feature? Create a \`.purpose\` in the feature directory.
- Modifying a component? Update its \`.purpose\` description, gates, or signals.
- Deleting code? Remove the symbol from \`.purpose\`.
- Not sure? Run \`paradigm_pm_postflight\` \u2014 it will tell you what's missing.

## Essential MCP Tools (Use These, NOT CLI Commands)

| Tool | When | Cost |
|------|------|------|
| \`paradigm_session_recover\` | Session start | ~100 tokens |
| \`paradigm_ripple\` | Before modifying any symbol | ~300 tokens |
| \`paradigm_navigate\` | Finding code locations | ~200 tokens |
| \`paradigm_pm_preflight\` | Before starting a feature (3+ files) | ~200 tokens |
| \`paradigm_pm_postflight\` | After finishing any task | ~200 tokens |
| \`paradigm_reindex\` | After creating/modifying .purpose files | ~100 tokens |
| \`paradigm_gates_for_route\` | Before adding API endpoints | ~150 tokens |
| \`paradigm_lore_record\` | After completing a feature (record learnings) | ~100 tokens |

## Red Flags \u2014 STOP and Check

If you find yourself doing any of these, STOP:

- **Modifying 3+ files without calling \`paradigm_ripple\`** \u2192 Check impact first
- **Adding routes without checking \`paradigm_gates_for_route\`** \u2192 Get gate suggestions
- **Finishing without running \`paradigm_pm_postflight\`** \u2192 You'll miss compliance gaps
- **Creating directories without a \`.purpose\` file** \u2192 Every directory needs context
`}generatePracticesMdc(){return g("Paradigm practices - habits, lore recording, and llms.txt. Apply when finishing tasks, recording history, or checking compliance.",{alwaysApply:false})+`# Paradigm Practices

`+E()+`

`+D()+`

`+U()}loadAgentsManifest(s){let n=c.join(s,".paradigm","agents.yaml");if(!r.existsSync(n))return null;try{let a=r.readFileSync(n,"utf-8");return N.load(a)}catch{return null}}generateOrchestrationMdc(s){let n="(Run `paradigm team init` to configure agents)";if(s){let o=s.agents||s.roles;if(o&&typeof o=="object")try{n=Object.entries(o).map(([p,u])=>{let l=(u.role||u.description||"").split(`
`)[0].trim()||p,m=u.focus?.writes,j=Array.isArray(m)?m.join(", "):"any",I=u.defaultModel||"sonnet";return `- **${p}** (${I}): ${l} (writes: ${j})`}).join(`
`);}catch{}}let a=ce.platform(),i=a==="win32"?"## Terminal Syntax (Windows)\n\nThis project runs on **Windows**. Use appropriate syntax:\n\n| Operation | Windows Syntax |\n|-----------|----------------|\n| Chain commands | `cmd1 ; cmd2` or `cmd1 && cmd2` (PowerShell) |\n| Path separator | `\\` (backslash) |\n| Environment vars | `$env:VAR` (PowerShell) or `%VAR%` (CMD) |\n| Null device | `$null` (PowerShell) or `NUL` (CMD) |\n| List files | `dir` or `Get-ChildItem` |\n| Remove files | `del` or `Remove-Item` |\n\n**IMPORTANT:** Do NOT use Unix-style commands like `rm`, `cat`, `grep` directly.":`## Terminal Syntax (${a==="darwin"?"macOS":"Linux"})

This project runs on **${a==="darwin"?"macOS":"Linux"}**. Use appropriate syntax:

| Operation | Unix Syntax |
|-----------|-------------|
| Chain commands | \`cmd1 && cmd2\` (stop on error) or \`cmd1 ; cmd2\` (always continue) |
| Path separator | \`/\` (forward slash) |
| Environment vars | \`$VAR\` or \`\${VAR}\` |
| Null device | \`/dev/null\` |
| List files | \`ls\` |
| Remove files | \`rm\` |

**IMPORTANT:** Do NOT use Windows-style commands like \`dir\`, \`del\`, or \`%VAR%\`.`;return g("Multi-agent orchestration - use when task affects 3+ files, involves security AND implementation, or spans multiple features. Call paradigm_orchestrate_inline for planning.")+`# Paradigm Orchestration Protocol

${i}

## CRITICAL: When to Use Orchestration

**ALWAYS call \`paradigm_orchestrate_inline\` FIRST when:**
- Task affects 3+ files
- Task involves security/auth AND implementation
- Task mentions multiple features (#symbols)
- Building a new feature end-to-end
- User explicitly requests multi-agent workflow

## Workflow

1. **Plan first:** \`paradigm_orchestrate_inline({ task: "...", mode: "plan" })\`
   - Review suggested agents and estimated tokens
   - Check if parallel execution is possible

2. **Execute:** \`paradigm_orchestrate_inline({ task: "...", mode: "execute" })\`
   - Get full prompts and execution strategy
   - Note which stages can run in parallel

3. **Follow the plan sequentially:**
   - For each stage/agent, adopt that role's prompt and focus areas
   - Stage 0 (architect): Design and spec only \u2014 do NOT write implementation code
   - Stage 1 (builder): Implement following the architect's design
   - Stage 2 (tester/reviewer): Verify and test the implementation
   - Pass context between phases as if handing off to a teammate

4. **For true parallel execution**, suggest user runs:
   \`paradigm team orchestrate "task description"\`

5. **Record history:** \`paradigm_history_record({ type: "implement", symbols: [...], description: "..." })\`

## Available Agents

${n}

## Red Flags - STOP and Orchestrate

If you find yourself:
- Implementing 5+ files without planning \u2192 STOP, call orchestrate
- Adding auth without security review \u2192 STOP, involve security agent
- Writing code without specs \u2192 STOP, involve architect first
- Making cross-cutting changes \u2192 STOP, plan the stages

## DO NOT Skip Orchestration

Complex tasks need specialist agents. One agent trying to do everything leads to:
- Missed security gates
- Inconsistent patterns
- Poor test coverage
- Context overflow

## CLI Shortcut

You can also suggest agents via CLI:
\`\`\`bash
paradigm team agents suggest "Add user authentication with JWT"
\`\`\`
`}generateFlowsMdc(){return g("Flow-first development - apply when implementing features spanning multiple steps, requiring gates, or emitting signals. Define $flows before coding.")+`# Flow-First Development

## What are Flows?

Flows ($symbols) are composable sequences of gates, actions, and signals that represent the "happy path" for a feature.

\`\`\`yaml
# .paradigm/flows.yaml
flows:
  $task-creation:
    name: Task Creation Flow
    description: Complete flow for creating a new task
    trigger: "POST /api/tasks"
    steps:
      - type: gate
        symbol: ^authenticated
        description: User must be logged in
      - type: gate
        symbol: ^project-member
        description: User must be member of target project
      - type: action
        symbol: "#validate-task-input"
        description: Validate task data
      - type: action
        symbol: "#create-task"
        description: Create task in database
      - type: signal
        symbol: "!task-created"
        description: Emit success event
    successSignal: "!task-created"
    failureSignal: "!task-creation-failed"
\`\`\`

## When to Define Flows

**BEFORE implementing features that:**
- Span multiple steps or components
- Require authorization gates
- Emit signals/events
- Integrate with external systems

## Flow-First Protocol

1. **Define the flow first** in \`.paradigm/flows.yaml\`:
   - What gates must pass?
   - What actions occur in what order?
   - What signals are emitted?

2. **Validate before implementing:**
   \`\`\`
   paradigm_flow_validate({ flowId: "$task-creation" })
   \`\`\`
   - Ensures all gates are declared in portal.yaml
   - Checks for missing symbols

3. **Implement following the flow:**
   - Each step becomes a clear implementation target
   - Gates \u2192 middleware/authorization checks
   - Actions \u2192 business logic functions
   - Signals \u2192 event emitters/hooks

## Flow Validation

Call \`paradigm_flow_validate\` to check flows:

\`\`\`
// Validate specific flow
paradigm_flow_validate({ flowId: "$task-creation" })

// Validate all flows
paradigm_flow_validate({ checkImplementation: true })
\`\`\`

**What gets checked:**
- All ^gates are declared in portal.yaml
- All #actions reference existing components
- All !signals are documented

## Benefits

1. **Clear implementation targets** - Each flow step is a discrete unit
2. **Gate coverage** - All authorization points are explicit
3. **Testability** - Flows can be tested step-by-step
4. **Documentation** - The flow IS the documentation
5. **Parallel work** - Different team members can implement different steps

## Red Flags

**STOP and define a flow if:**
- You're implementing a "happy path" without documenting it
- You're adding gates without knowing the full sequence
- You're emitting signals without knowing what listens
- You're modifying existing flows without checking validation

## MCP Tools

| Tool | Purpose |
|------|---------|
| \`paradigm_flow_validate\` | Validate flow definitions |
| \`paradigm_flows_affected\` | Check which flows are impacted by symbol changes |

## CLI Commands

\`\`\`bash
# Validate all flows
paradigm flow validate --all

# Validate specific flow
paradigm flow validate $task-creation
\`\`\`
`}generateCommitsMdc(){return g("Paradigm commit conventions with Symbols: trailer - apply when creating git commits for history tracking.")+v()}generateMcpConfig(s){return {mcpServers:{paradigm:{command:"paradigm-mcp",args:["."],cwd:s}}}}},O=new G;function M(e,s){if(!e&&true)return "";let n=["---"];return e&&n.push(`applyTo: "${e}"`),n.push("---",""),n.join(`
`)}var H=class{name="copilot";displayName="GitHub Copilot";outputPath=".github/instructions";multiFile=true;detect(s){return !!(r.existsSync(c.join(s,".github","instructions"))||r.existsSync(c.join(s,".github","copilot-instructions.md")))}generate(s){return this.generateFiles(s).map(a=>`# ${a.path}

${a.content}`).join(`

---

`)}generateFiles(s){let{config:n,projectName:a}=s,t=[];return t.push({path:"../copilot-instructions.md",content:this.generateCoreInstructions(a,n)}),t.push({path:"paradigm-symbols.instructions.md",content:this.generateSymbolInstructions(n)}),w(n)&&t.push({path:"paradigm-logging.instructions.md",content:this.generateLoggingInstructions(n)}),t.push({path:"paradigm-purpose.instructions.md",content:this.generatePurposeInstructions()}),t.push({path:"paradigm-portal.instructions.md",content:this.generatePortalInstructions()}),t.push({path:"paradigm-conventions.instructions.md",content:this.generateConventionsInstructions(n)}),t.push({path:"paradigm-commands.instructions.md",content:this.generateCommandsInstructions()}),t.push({path:"paradigm-agent-hints.instructions.md",content:this.generateAgentHintsInstructions()}),t.push({path:"paradigm-commits.instructions.md",content:this.generateCommitsInstructions()}),t}generateCoreInstructions(s,n){let a=P(n);return `# Copilot Instructions for ${s}

This file provides context for GitHub Copilot. Generated by Paradigm.

${a}

${S(n)}

---

## Additional Context

For detailed specifications, reference these files:

- \`.paradigm/specs/symbols.md\` - Complete symbol reference
- \`.paradigm/specs/logger.md\` - Logging specification
- \`.paradigm/specs/scan.md\` - Visual discovery protocol
- \`.paradigm/docs/\` - Documentation and troubleshooting
- \`.paradigm/prompts/\` - Pre-written task prompts

*Generated by Paradigm. Run \`paradigm sync copilot\` to regenerate.*
`}generateSymbolInstructions(s){return M("**/*.ts,**/*.tsx,**/*.js,**/*.jsx")+`# Paradigm Symbol System

${C(s)}
`}generateLoggingInstructions(s){return M("**/*.ts,**/*.tsx,**/*.js,**/*.jsx")+`# Paradigm Logging

${w(s)}
`}generatePurposeInstructions(){return M("**/.purpose")+`# Purpose Files

Purpose files (\`.purpose\`) define the context for directories.

## Format

\`\`\`yaml
# Directory context
description: What this directory contains and why

# Components (# symbol) \u2014 all documented code units
components:
  component-name:
    description: What this component does
    tags: [feature]                # Classification via tag bank
    gates: [^gate1, ^gate2]       # Required gates
    signals: [!signal1]           # Events emitted
    used-by: [#other-component]
\`\`\`

## Symbol References (v2)

- Reference components: \`#component-name\`
- Reference flows: \`$flow-name\`
- Reference gates: \`^gate-name\`
- Reference signals: \`!signal-name\`
- Reference aspects: \`~aspect-name\`
`}generatePortalInstructions(){return M("**/portal.yaml")+`# Portal Configuration

Portal files (\`portal.yaml\`) define authorization topology.

## Format

\`\`\`yaml
version: "1.0"

gates:
  gate-name:
    description: What this gate protects
    locks:
      - id: lock-id
        description: Requirement description
        keys:
          - expression: "user.authenticated"
            description: User must be logged in
    prizes:
      - id: prize-id
        oneTime: true
        metadata:
          event: "gate_passed"

flows:
  flow-name:
    description: User journey
    gates: [gate1, gate2, gate3]
\`\`\`

## Portal Validation

Use the Portal Validator for authorization checks:

\`\`\`typescript
import { portal } from '@a-company/portal-sdk/validator';

const gate = portal.check('^gate-name')
  .requires('requirement description')
  .context({ userId, role });

if (!condition) {
  gate.deny('Reason for denial');
  return redirect('/unauthorized');
}

gate.allow('Access granted');
\`\`\`
`}generateConventionsInstructions(s){return M("**/*.ts,**/*.tsx,**/*.js,**/*.jsx")+`# Paradigm Conventions

${b(s)}
`}generateCommandsInstructions(){return `# Paradigm CLI Commands

${x()}
`}generateAgentHintsInstructions(){return `# Agent CLI Queries (Token-Efficient)

Instead of reading large context files, query Paradigm CLI on-demand for fresh, precise data.

## When to Query

| Before doing this... | Run this command |
|---------------------|------------------|
| Modifying a symbol | \`paradigm ripple #symbol --json\` |
| Debugging an error | \`paradigm echo ERROR_CODE --json\` |
| Starting a session | \`paradigm thread --json\` |
| Understanding relationships | \`paradigm constellation\` |
| Getting oriented | \`paradigm beacon --json\` |

## Query Patterns

### Before Changing Code

\`\`\`bash
# See what depends on what you're changing
paradigm ripple #checkout --json

# Output includes: upstream deps, downstream effects, flow membership
\`\`\`

### When Debugging

\`\`\`bash
# Look up error context
paradigm echo AUTH_REQUIRED --json

# Then check ripple effects of the related symbol
paradigm ripple ^authenticated --json
\`\`\`

### Starting Work

\`\`\`bash
# Check previous session context
paradigm thread --json

# Quick orientation
paradigm beacon --json
\`\`\`

### Querying Constellation

\`\`\`bash
# Get specific symbol
jq '.stars["#checkout"]' .paradigm/constellation.json

# Find what requires a gate
jq '[.stars | to_entries[] | select(.value.gates[]? == "^authenticated") | .key]' .paradigm/constellation.json

# List all flows
jq '.orbits | keys' .paradigm/constellation.json
\`\`\`

## Benefits

- **Fresh data**: Always current, not stale from file generation
- **Precise**: Only get the data you need
- **Token-efficient**: ~100 tokens per query vs ~2000 upfront
`}generateCommitsInstructions(){return `# Paradigm Commit Conventions

${v()}
`}},L=new H;var Q=class{name="windsurf";displayName="Windsurf";outputPath=".windsurfrules";detect(s){return !!(r.existsSync(c.join(s,".windsurfrules"))||r.existsSync(c.join(s,".windsurf")))}generate(s){let{config:n,projectName:a}=s,t=[];t.push(se(a,this.displayName)),t.push(P(n)),t.push(C(n));let i=w(n);i&&t.push(i);let o=ne(n);return o&&t.push(o),t.push(S(n)),t.push(b(n)),t.push(v()),t.push(x()),t.push(pe()),t.filter(p=>p.trim()).join(`
`)}},W=new Q;var Y=class{name="claude";displayName="Claude";outputPath="CLAUDE.md";detect(s){return !!r.existsSync(c.join(s,"CLAUDE.md"))}generate(s){let{config:n,projectName:a}=s,t=[];t.push(`# ${a} - Claude Context`),t.push(""),t.push("> **Paradigm v2.0** | For Claude Code, Claude API, and Claude-native interfaces"),t.push(">"),t.push("> **Author:** Matt Canoy ([@ascend42](https://github.com/ascend42)) | **Repo:** [github.com/ascend42/a-paradigm](https://github.com/ascend42/a-paradigm) | **npm:** [@a-company/paradigm](https://www.npmjs.com/package/@a-company/paradigm) | **Plugin:** `paradigm` via Claude Code marketplace"),t.push(""),t.push("## Project Overview"),t.push(""),n["agent-guidelines"]?.overview&&t.push(n["agent-guidelines"].overview),t.push(""),t.push("## Quick Orientation"),t.push(""),t.push("```"),t.push(".paradigm/config.yaml  \u2192 Project configuration"),t.push(".paradigm/specs/       \u2192 Detailed specifications"),t.push(".paradigm/docs/        \u2192 Commands, patterns, troubleshooting"),t.push(".cursorrules           \u2192 IDE instructions (if using Cursor)"),t.push("portal.yaml            \u2192 Security/auth definitions"),t.push(".paradigm/lore/        \u2192 Project timeline and history"),t.push("```"),t.push(""),t.push("## Symbol System"),t.push(""),t.push("Use these prefixes in documentation and commits:"),t.push(""),t.push("| Symbol | Meaning | Example |"),t.push("|--------|---------|---------|");let i=n["symbol-system"];if(i)for(let[p,u]of Object.entries(i)){let d=u.examples?.[0]||`${p}example`;t.push(`| \`${p}\` | ${u.name} | \`${d}\` |`);}t.push("");let o=b(n);if(o&&t.push(o),t.push(v()),t.push("## Agent Onboarding"),t.push(""),t.push("**First session:** Call `paradigm_status` \u2192 read `.paradigm/config.yaml` \u2192 check `portal.yaml`"),t.push(""),t.push("**Before each task:** `paradigm_ripple` for impact, `paradigm_gates_for_route` for new endpoints"),t.push(""),t.push("**Resuming:** Call `paradigm_session_recover`"),t.push(""),t.push("## Before Implementing"),t.push(""),t.push("0. Call `paradigm_protocol_search` \u2014 if a protocol matches, follow it"),t.push('1. Complex task (3+ files)? \u2192 `paradigm_orchestrate_inline` mode="plan"'),t.push("2. Affects symbols? \u2192 `paradigm_ripple`"),t.push("3. Adds endpoints? \u2192 `paradigm_gates_for_route`"),t.push(""),t.push("## Automatic Enforcement (Hooks)"),t.push(""),t.push("The stop hook **BLOCKS** if source files were modified without .purpose updates."),t.push(""),t.push("| Hook | Behavior |"),t.push("|------|----------|"),t.push("| **Stop** | Blocks on: missing .purpose, missing portal.yaml gates, aspect drift, stale purposes |"),t.push("| **Pre-commit** | Auto-rebuilds index \u2014 never blocks |"),t.push("| **Post-write** | Advisory reminder for .purpose coverage |"),t.push(""),t.push("**If blocked:** Update .purpose files \u2192 update portal.yaml if needed \u2192 `paradigm_reindex` \u2192 finish"),t.push(""),t.push("## Maintaining Paradigm Files"),t.push(""),t.push("**You MUST update Paradigm files when making code changes:**"),t.push(""),t.push("- Add feature \u2192 create `.purpose` in directory"),t.push("- Add protected route \u2192 update `portal.yaml` with gates"),t.push("- Add signal/event \u2192 add to `.purpose`"),t.push("- Add multi-step flow \u2192 document as `$flow`"),t.push("- Rename/delete symbol \u2192 update all references"),t.push("- Record lore via `paradigm_lore_record` for sessions modifying 3+ files"),t.push("- Use Paradigm logger (`log.component()`, `log.gate()`, etc.) \u2014 never raw console.log"),t.push(""),t.push("**Auth requires portal.yaml** if your code has JWT, role checks, ownership checks, or protected endpoints."),t.push(""),t.push("## On-Demand Guidance"),t.push(""),t.push("Detailed guidance is available via MCP resources \u2014 load only what you need:"),t.push(""),t.push("| Topic | Resource |"),t.push("|-------|----------|"),t.push("| Logging rules & directory mapping | `paradigm://guidance/logging` |"),t.push("| Portal protocol & gate patterns | `paradigm://guidance/portal` |"),t.push("| MCP workflow & token budgets | `paradigm://guidance/mcp-workflow` |"),t.push("| Flow-first development | `paradigm://guidance/flows` |"),t.push("| Multi-agent orchestration | `paradigm://guidance/orchestration` |"),t.push("| Workspaces (multi-project) | `paradigm://guidance/workspaces` |"),t.push("| University (knowledge base) | `paradigm://guidance/university` |"),t.push("| Confidence calibration | `paradigm://guidance/calibration` |"),t.push("| Session checkpoints | `paradigm://guidance/checkpoints` |"),t.push("| Navigation & task recipes | `paradigm://guidance/navigation` |"),t.push("| Component types & hierarchy | `paradigm://guidance/component-types` |"),t.push("| Troubleshooting | `paradigm://guidance/troubleshooting` |"),t.push(""),s.agents?.length){let p=s.agents.flatMap(u=>(u.context?.contributions||[]).filter(d=>d.priority==="high"&&d.content).map(d=>({agent:u.id,section:d.section,content:d.content})));if(p.length>0){t.push("## Agent Contributions"),t.push("");for(let u of p)t.push(`### ${u.section} (${u.agent})`),t.push(""),t.push(u.content),t.push("");}}if(n["purpose-required"]?.length){t.push("## Directory Structure"),t.push(""),t.push("`.purpose` files exist in:");for(let p of n["purpose-required"])t.push(`- \`${p.pattern}\``);t.push("");}return t.push("---"),t.push(""),t.push("*See `.paradigm/specs/` for specifications. Run `paradigm sync` to regenerate.*"),t.filter(p=>p!==void 0).join(`
`)}generateMcpConfig(s){return {mcpServers:{paradigm:{command:"paradigm-mcp",args:["."],cwd:s}}}}generateNestedContexts(s,n){let a=[],t=me(s);for(let i of t){let o=c.dirname(i),p=c.relative(s,o);if(p===""||p===".")continue;let u=r.readFileSync(i,"utf8"),d=this.generateDirectoryContext(p,u,n);a.push({path:c.join(p,"CLAUDE.md"),content:d});}return a}generateDirectoryContext(s,n,a){let t=[],i=c.basename(s);return t.push(`# ${i} - Directory Context`),t.push(""),t.push(`> Part of ${a.projectName} | See root CLAUDE.md for project overview`),t.push(""),t.push("## Purpose"),t.push(""),t.push("```yaml"),t.push(n.trim()),t.push("```"),t.push(""),t.push("## Quick Reference"),t.push(""),t.push(`- **Path**: \`${s}\``),t.push("- **Config**: See `.paradigm/config.yaml`"),t.push("- **Patterns**: See `.paradigm/docs/patterns.md`"),t.push(""),t.push("## Symbols"),t.push(""),t.push("`#` component | `$` flow | `^` gate | `!` signal | `~` aspect"),t.push(""),t.push("---"),t.push(""),t.push("*Auto-generated by `paradigm sync claude`. Edit .purpose file to update.*"),t.join(`
`)}};function me(e){let s=[];function n(a){let t=r.readdirSync(a,{withFileTypes:true});for(let i of t){let o=c.join(a,i.name);if(i.isDirectory()){if(i.name.startsWith(".")||i.name==="node_modules")continue;n(o);}else i.name===".purpose"&&s.push(o);}}return n(e),s}var J=new Y;var K=class{name="agents";displayName="AGENTS.md";outputPath="AGENTS.md";multiFile=false;detect(s){return r.existsSync(c.join(s,"AGENTS.md"))}generate(s){let{config:n,projectName:a}=s,t=[];t.push(`# ${a} - AI Agent Instructions`),t.push(""),t.push("> Generated by [Paradigm](https://github.com/anthropics/paradigm) v2.0 | Universal AI agent instruction file"),t.push(""),t.push(P(n)),t.push(C(n));let i=b(n);i&&t.push(i);let o=w(n);o&&t.push(o),t.push(ie()),t.push(ae()),t.push(re()),t.push(v()),t.push(oe()),t.push($()),t.push(E()),t.push(D()),t.push(U());let p=S(n);return p&&t.push(p),t.push(x()),t.push("---"),t.push(""),t.push("*Generated by Paradigm. Run `paradigm sync agents` to regenerate.*"),t.filter(u=>u!==void 0&&u!=="").join(`
`)}},X=new K;var Z=new Map([["cursor",O],["copilot",L],["windsurf",W],["claude",J],["agents",X]]);function ee(e){return Z.get(e.toLowerCase())}function he(){return Array.from(Z.keys())}function Ee(e){return O.detect(e)?{detected:"cursor",confidence:"high",reason:"Found .cursor directory or .cursorrules file"}:W.detect(e)?{detected:"windsurf",confidence:"high",reason:"Found .windsurf directory or .windsurfrules file"}:L.detect(e)?{detected:"copilot",confidence:"medium",reason:"Found .github/copilot-instructions.md file"}:r.existsSync(c.join(e,".vscode"))?{detected:"cursor",confidence:"low",reason:"Found .vscode directory, defaulting to Cursor format"}:{detected:null,confidence:"low",reason:"No IDE markers found"}}function De(e$1){let s=c.join(e$1,".paradigm"),n=c.join(e$1,".paradigm"),a,t,i;if(r.existsSync(s)&&r.statSync(s).isDirectory())a=c.join(s,"config.yaml"),t=c.join(s,"specs"),i=c.join(s,"docs");else if(r.existsSync(n)&&r.statSync(n).isFile())a=n,t="",i="";else return null;if(!r.existsSync(a))return null;let o;try{let f=r.readFileSync(a,"utf8");o=e(f);}catch{return null}let p={};if(t&&r.existsSync(t)){let f=["logger.md","scan.md","symbols.md"];for(let h of f){let y=c.join(t,h);if(r.existsSync(y)){let _=h.replace(".md","");p[_]=r.readFileSync(y,"utf8");}}}let u={};if(i&&r.existsSync(i)){let f=["commands.md","patterns.md","troubleshooting.md"];for(let h of f){let y=c.join(i,h);if(r.existsSync(y)){let _=h.replace(".md","");u[_]=r.readFileSync(y,"utf8");}}}let d,l=c.join(e$1,".paradigm","agents");if(r.existsSync(l))try{let f=r.readdirSync(l).filter(y=>y.endsWith(".agent")),h=[];for(let y of f)try{let _=r.readFileSync(c.join(l,y),"utf8"),F=N.load(_);F?.id&&h.push({id:F.id,role:F.role,context:F.context});}catch{}h.length>0&&(d=h);}catch{}let m,I=N.load(r.readFileSync(a,"utf8")).workspace;if(typeof I=="string"){let f=c.resolve(e$1,I);if(r.existsSync(f))try{let h=N.load(r.readFileSync(f,"utf8")),y=c.dirname(f),_=h.members?.find(F=>c.resolve(y,F.path)===e$1)?.name||c.basename(e$1);m={name:h.name,currentMember:_,members:h.members||[]};}catch{}}return {config:o,specs:p,docs:u,projectName:c.basename(e$1),workspace:m,agents:d}}function fe(e,s,n,a=false){let t=ee(s);if(!t)return {success:false,ide:s,outputPath:"",message:`Unknown IDE: ${s}. Available: ${he().join(", ")}`};let i=c.join(e,t.outputPath);try{if(t.multiFile&&t.generateFiles)return ye(e,t,n,a);!a&&r.existsSync(i);let o=c.dirname(i);r.existsSync(o)||r.mkdirSync(o,{recursive:!0});let p=t.generate(n);return r.writeFileSync(i,p,"utf8"),{success:!0,ide:s,outputPath:i,message:`Generated ${t.outputPath}`}}catch(o){return {success:false,ide:s,outputPath:i,message:`Failed to write ${t.outputPath}: ${o.message}`}}}function ye(e,s,n,a){let t=c.join(e,s.outputPath);r.existsSync(t)||r.mkdirSync(t,{recursive:true});let i=s.generateFiles(n,e),o=[];for(let l of i){let m;l.path.startsWith("../")?m=c.join(t,l.path):m=c.join(t,l.path);let j=c.dirname(m);r.existsSync(j)||r.mkdirSync(j,{recursive:true}),!a&&r.existsSync(m),r.writeFileSync(m,l.content,"utf8"),o.push(l.path);}if(s.name==="cursor"){let l=c.join(e,".cursorrules");if(r.existsSync(l)){let m=c.join(e,".cursorrules.bak");r.existsSync(m)||r.renameSync(l,m);}}let p=o.filter(l=>!l.startsWith("../")),u=o.filter(l=>l.startsWith("../")),d=`Generated ${p.length} files in ${s.outputPath}/`;return u.length>0&&(d+=` + ${u.length} additional file(s)`),{success:true,ide:s.name,outputPath:t,message:d}}function Ue(e,s,n=false){let a=[];for(let[t]of Z)a.push(fe(e,t,s,n));return a}function Oe(e,s){let n=ee(s);if(!n||!n.generateMcpConfig)return {success:false,path:"",message:`IDE ${s} does not support MCP configuration`};let a=n.generateMcpConfig(e),t;switch(s){case "cursor":t=c.join(e,".cursor","mcp.json");break;case "claude":t=c.join(e,".mcp.json");break;default:return {success:false,path:"",message:`Unknown MCP config path for ${s}`}}try{let i=c.dirname(t);r.existsSync(i)||r.mkdirSync(i,{recursive:!0});let o={};if(r.existsSync(t)){let u=r.readFileSync(t,"utf8");o=JSON.parse(u);}let p={...o,mcpServers:{...o.mcpServers||{},...a.mcpServers}};if(s==="claude"){let u=o.permissions||{},d=u.allow||[],l="Bash(paradigm *)";d.includes(l)||(p.permissions={...u,allow:[...d,l]});}return r.writeFileSync(t,JSON.stringify(p,null,2)),{success:!0,path:t,message:`MCP configuration written to ${c.relative(e,t)}`}}catch(i){return {success:false,path:t,message:`Failed to write MCP config: ${i.message}`}}}function Le(e,s,n){let a=ee(s);if(!a||!a.generateNestedContexts)return {success:false,count:0,message:`IDE ${s} does not support nested contexts`};try{let t=a.generateNestedContexts(e,n);for(let i of t){let o=c.join(e,i.path),p=c.dirname(o);r.existsSync(p)||r.mkdirSync(p,{recursive:!0}),r.writeFileSync(o,i.content,"utf8");}return {success:!0,count:t.length,message:`Generated ${t.length} nested context files`}}catch(t){return {success:false,count:0,message:`Failed to write nested contexts: ${t.message}`}}}export{ee as a,he as b,Ee as c,De as d,fe as e,Ue as f,Oe as g,Le as h};