{"version":3,"sources":["../src/index.ts","../src/directional_decomposer.ts","../src/intent_extractor.ts","../src/dependency_mapper.ts","../src/action_stack.ts","../src/wheel_bridge.ts","../src/v0_ontology_bridge.ts","../src/storage.ts","../src/strategy_spec.ts","../src/pde_metadata.ts","../src/runnable.ts","../src/agent_harness.ts","../src/execution_planner.ts"],"sourcesContent":["/**\n * ava-langchain-prompt-decomposition\n *\n * Prompt Decomposition Engine (PDE) primitives for the Narrative Intelligence Stack.\n * Decomposes complex prompts through the Four Directions (Medicine Wheel):\n *\n * - EAST (Waabinong/Vision): What is being asked?\n * - SOUTH (Zhaawanong/Analysis): What needs to be learned?\n * - WEST (Epangishmok/Validation): What needs reflection?\n * - NORTH (Kiiwedinong/Action): What executes?\n *\n * Core Components:\n * - DirectionalDecomposer: Classifies prompt segments by direction\n * - IntentExtractor: Extracts primary + secondary intents with confidence\n * - DependencyMapper: Maps task dependencies and execution order\n * - ActionStackBuilder: Produces the final ordered execution plan\n * - MedicineWheelBridge: Maps directions to quadrants from relational-intelligence\n *\n * @example\n * ```typescript\n * import {\n *   DirectionalDecomposer,\n *   IntentExtractor,\n *   DependencyMapper,\n *   ActionStackBuilder,\n *   MedicineWheelBridge,\n * } from \"ava-langchain-prompt-decomposition\";\n *\n * const decomposer = new DirectionalDecomposer();\n * const extractor = new IntentExtractor();\n * const mapper = new DependencyMapper();\n * const builder = new ActionStackBuilder();\n * const bridge = new MedicineWheelBridge();\n *\n * // Decompose a complex prompt\n * const directions = decomposer.decompose(\"Build a knowledge graph...\");\n * const intents = extractor.extract(\"Build a knowledge graph...\");\n * const graph = mapper.buildGraph(intents.secondary);\n * const order = mapper.computeExecutionOrder(graph);\n * const result = builder.build(directions, intents, order);\n *\n * // Check relational balance\n * const enriched = bridge.enrich(directions);\n * if (enriched.ceremonyRequired) {\n *   console.log(\"Pause: ceremony needed before proceeding\");\n * }\n *\n * // Output as JSON or Markdown\n * console.log(builder.toJSON(result));\n * console.log(builder.toMarkdown(result));\n * ```\n */\n\nexport const VERSION = \"0.1.0\";\n\n// =============================================================================\n// Directional Decomposer\n// =============================================================================\n\nexport {\n  Direction,\n  ALL_DIRECTIONS,\n  DIRECTION_NAMES,\n  DIRECTION_QUESTIONS,\n  DIRECTION_KEYWORDS,\n  DirectionalInsight,\n  DirectionalAnalysis,\n  DecomposerOptions,\n  DirectionalDecomposer,\n} from \"./directional_decomposer.js\";\n\n// =============================================================================\n// Intent Extractor\n// =============================================================================\n\nexport {\n  Urgency,\n  PrimaryIntent,\n  SecondaryIntent,\n  IntentExtractionResult,\n  ExtractionContext,\n  ExtractorOptions,\n  IntentExtractor,\n} from \"./intent_extractor.js\";\n\n// =============================================================================\n// Dependency Mapper\n// =============================================================================\n\nexport {\n  DependencyNode,\n  DependencyGraph,\n  ExecutionOrder,\n  DependencyMapper,\n} from \"./dependency_mapper.js\";\n\n// =============================================================================\n// Action Stack\n// =============================================================================\n\nexport {\n  ActionItem,\n  AmbiguityFlag,\n  ExpectedOutputs,\n  DecompositionResult,\n  ActionStackOptions,\n  ActionStackBuilder,\n} from \"./action_stack.js\";\n\n// =============================================================================\n// Medicine Wheel Bridge\n// =============================================================================\n\nexport {\n  WheelQuadrant,\n  DIRECTION_TO_QUADRANT,\n  QUADRANT_TO_DIRECTION,\n  WheelEnrichedAnalysis,\n  WheelBridgeOptions,\n  MedicineWheelBridge,\n} from \"./wheel_bridge.js\";\n\n// =============================================================================\n// V0 Ontology Bridge\n// =============================================================================\n\nexport {\n  OntologyCoreConcept,\n  ONTOLOGY_CORE_MAP,\n  NarrativeBeatMapping,\n  actionToNarrativeBeat,\n  RelationalQueryNode,\n  PACKAGE_MAPPING,\n} from \"./v0_ontology_bridge.js\";\n\n// =============================================================================\n// Storage (.pde/ persistence — mcp-pde lineage)\n// =============================================================================\n\nexport {\n  StoredDecomposition,\n  PdeStorageLayout,\n  SaveDecompositionOptions,\n  DecompositionMarkdownOptions,\n  saveDecomposition,\n  saveDecompositionTree,\n  saveStrategicDecomposition,\n  loadDecomposition,\n  listDecompositions,\n  decompositionToMarkdown,\n} from \"./storage.js\";\n\nexport {\n  PDE_DIR,\n  PDE_META_FILENAME,\n  PDE_METADATA_SCHEMA_VERSION,\n  CHILD_KINDS,\n  ChildKind,\n  PdeSessionIdSource,\n  PdeRuntimeEngine,\n  ChildEntry,\n  EngineFallbackAttempt,\n  PdeFallbackMetadata,\n  PdeTreeMetadata,\n  PdeResolvedContext,\n  normalizeAddDirs,\n  mergeAddDirs,\n  ensureDirectory,\n  getPdeRoot,\n  extractPdeUuidFromFolderName,\n  extractPdeUuidFromPath,\n  resolvePdeFolderPath,\n  findPdeFolder,\n  readPdeTreeMetadata,\n  writePdeTreeMetadata,\n  resolvePdeContext,\n  resolvePdeContextByPath,\n  buildPdeTreeMetadata,\n  appendChildEntry,\n  updatePdeTreeMetadata,\n} from \"./pde_metadata.js\";\n\n// =============================================================================\n// LangChain Runnable Wrappers (Chain Composability)\n// =============================================================================\n\nexport {\n  RunnableDecomposer,\n  RunnableDirectionalAnalyzer,\n  RunnableWheelGate,\n  ChainDecomposer,\n  RunnableDecomposerOptions,\n  RunnableDecomposerResult,\n} from \"./runnable.js\";\n\n// =============================================================================\n// Agent Harness Adapter (for ava-code, mia-code, etc.)\n// =============================================================================\n\nexport {\n  AgentPDE,\n  AgentPDEOptions,\n  AgentDecompositionResult,\n  ExecutionProgress,\n} from \"./agent_harness.js\";\n\n// =============================================================================\n// Execution Planner\n// =============================================================================\n\nexport {\n  ExecutionStage,\n  Checkpoint,\n  FallbackStrategy,\n  ExecutionPlan,\n  ExecutionPlannerOptions,\n  ExecutionPlanner,\n} from \"./execution_planner.js\";\n\n// =============================================================================\n// Strategy Pattern (pluggable decomposition strategies)\n// =============================================================================\n\nexport {\n  ComplexityAnalyzer,\n  KeywordStrategy,\n  SemanticStrategy,\n  HybridStrategy,\n  StrategySelector,\n  MultiPassDecomposer,\n  ConfidenceCalibrator,\n  StrategicDecomposer,\n  strategicDecompose,\n  extractStrategyMetadata,\n  strategicResultToProvenance,\n  STRATEGY_METADATA_SCHEMA_VERSION,\n} from \"./strategy_spec.js\";\n\nexport type {\n  StrategyId,\n  PromptComplexity,\n  ComplexitySignals,\n  AvailableResources,\n  StrategyPreferences,\n  StrategyResult,\n  DecompositionStrategy,\n  Disagreement,\n  MultiPassResult,\n  StrategicDecomposerOptions,\n  StrategicDecompositionResult,\n  StrategyMetadata,\n  DecompositionWithProvenance,\n} from \"./strategy_spec.js\";\n\n// =============================================================================\n// Convenience: Full Pipeline\n// =============================================================================\n\nimport { DirectionalDecomposer, type DecomposerOptions } from \"./directional_decomposer.js\";\nimport { IntentExtractor, type ExtractorOptions } from \"./intent_extractor.js\";\nimport { DependencyMapper } from \"./dependency_mapper.js\";\nimport { ActionStackBuilder, type ActionStackOptions, type DecompositionResult } from \"./action_stack.js\";\nimport { MedicineWheelBridge, type WheelBridgeOptions, type WheelEnrichedAnalysis } from \"./wheel_bridge.js\";\n\nexport interface PipelineOptions {\n  decomposer?: DecomposerOptions;\n  extractor?: ExtractorOptions;\n  actionStack?: ActionStackOptions;\n  wheelBridge?: WheelBridgeOptions;\n}\n\nexport interface PipelineResult {\n  decomposition: DecompositionResult;\n  wheelEnriched: WheelEnrichedAnalysis;\n  json: string;\n  markdown: string;\n}\n\n/**\n * Run the full PDE pipeline on a prompt.\n * Decomposes → Extracts → Maps → Builds → Enriches\n */\nexport async function decompose(prompt: string, options?: PipelineOptions): Promise<PipelineResult> {\n  const decomposer = new DirectionalDecomposer(options?.decomposer);\n  const extractor = new IntentExtractor(options?.extractor);\n  const mapper = new DependencyMapper();\n  const builder = new ActionStackBuilder(options?.actionStack);\n  const bridge = new MedicineWheelBridge(options?.wheelBridge);\n\n  const directionalAnalysis = decomposer.decompose(prompt);\n  const intentResult = await extractor.extract(prompt);\n  const graph = mapper.buildGraph(intentResult.secondary);\n  const order = mapper.computeExecutionOrder(graph);\n  const decomposition = builder.build(directionalAnalysis, intentResult, order);\n  const wheelEnriched = bridge.enrich(directionalAnalysis);\n\n  return {\n    decomposition,\n    wheelEnriched,\n    json: builder.toJSON(decomposition),\n    markdown: builder.toMarkdown(decomposition),\n  };\n}\n","/**\n * Directional Decomposer\n *\n * Decomposes a prompt through the Four Directions:\n * - EAST (Vision/Waabinong): What is being asked? Requirements clarity\n * - SOUTH (Analysis/Zhaawanong): What needs to be learned? Dependencies/research\n * - WEST (Validation/Epangishmok): What needs reflection? Testing/verification\n * - NORTH (Action/Kiiwedinong): What executes? Implementation steps\n *\n * Inspired by mcp-pde and grounded in Medicine Wheel epistemology.\n */\n\nimport { v4 as uuid } from \"uuid\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport enum Direction {\n  EAST = \"east\",\n  SOUTH = \"south\",\n  WEST = \"west\",\n  NORTH = \"north\",\n}\n\nexport const ALL_DIRECTIONS: Direction[] = [\n  Direction.EAST,\n  Direction.SOUTH,\n  Direction.WEST,\n  Direction.NORTH,\n];\n\nexport const DIRECTION_NAMES: Record<Direction, string> = {\n  [Direction.EAST]: \"Waabinong (Vision)\",\n  [Direction.SOUTH]: \"Zhaawanong (Analysis)\",\n  [Direction.WEST]: \"Epangishmok (Validation)\",\n  [Direction.NORTH]: \"Kiiwedinong (Action)\",\n};\n\nexport const DIRECTION_QUESTIONS: Record<Direction, string> = {\n  [Direction.EAST]: \"What is being asked?\",\n  [Direction.SOUTH]: \"What needs to be learned?\",\n  [Direction.WEST]: \"What needs reflection?\",\n  [Direction.NORTH]: \"What executes?\",\n};\n\n/** Keywords that signal directional intent */\nexport const DIRECTION_KEYWORDS: Record<Direction, string[]> = {\n  [Direction.EAST]: [\n    \"vision\", \"goal\", \"purpose\", \"intention\", \"want\", \"need\", \"desire\",\n    \"dream\", \"imagine\", \"envision\", \"aspire\", \"mission\", \"why\", \"objective\",\n    \"outcome\", \"result\", \"achieve\", \"create\", \"build\", \"design\",\n  ],\n  [Direction.SOUTH]: [\n    \"learn\", \"research\", \"investigate\", \"understand\", \"study\", \"analyze\",\n    \"explore\", \"discover\", \"examine\", \"review\", \"compare\", \"assess\",\n    \"dependency\", \"require\", \"prerequisite\", \"context\", \"background\",\n    \"literature\", \"existing\", \"current\", \"pattern\",\n  ],\n  [Direction.WEST]: [\n    \"test\", \"verify\", \"validate\", \"check\", \"ensure\", \"confirm\",\n    \"reflect\", \"review\", \"audit\", \"quality\", \"feedback\", \"iterate\",\n    \"ceremony\", \"accountable\", \"responsible\", \"ethical\", \"protocol\",\n    \"appropriate\", \"respectful\", \"consent\",\n  ],\n  [Direction.NORTH]: [\n    \"implement\", \"execute\", \"deploy\", \"run\", \"build\", \"code\", \"script\",\n    \"install\", \"configure\", \"setup\", \"create\", \"write\", \"develop\",\n    \"ship\", \"launch\", \"deliver\", \"produce\", \"output\", \"generate\",\n    \"commit\", \"push\", \"merge\",\n  ],\n};\n\n/** A single directional observation */\nexport interface DirectionalInsight {\n  text: string;\n  confidence: number;\n  implicit: boolean;\n}\n\n/** Complete directional analysis of a prompt */\nexport interface DirectionalAnalysis {\n  id: string;\n  timestamp: string;\n  prompt: string;\n  directions: Record<Direction, DirectionalInsight[]>;\n  leadDirection: Direction;\n  neglectedDirections: Direction[];\n  balance: number; // 0-1, how evenly distributed across directions\n}\n\n// =============================================================================\n// DirectionalDecomposer\n// =============================================================================\n\nexport interface DecomposerOptions {\n  neglectThreshold?: number; // Below this = neglected (default 0.1)\n  balanceThreshold?: number; // Above this = balanced (default 0.5)\n}\n\nexport class DirectionalDecomposer {\n  private readonly neglectThreshold: number;\n  private readonly balanceThreshold: number;\n\n  constructor(options?: DecomposerOptions) {\n    this.neglectThreshold = options?.neglectThreshold ?? 0.1;\n    this.balanceThreshold = options?.balanceThreshold ?? 0.5;\n  }\n\n  /**\n   * Decompose a prompt into Four Directions analysis.\n   * Uses keyword-based classification to distribute prompt segments\n   * across directional categories.\n   */\n  decompose(prompt: string): DirectionalAnalysis {\n    const id = uuid();\n    const sentences = this.splitIntoSegments(prompt);\n    const directions: Record<Direction, DirectionalInsight[]> = {\n      [Direction.EAST]: [],\n      [Direction.SOUTH]: [],\n      [Direction.WEST]: [],\n      [Direction.NORTH]: [],\n    };\n\n    // Classify each segment\n    for (const sentence of sentences) {\n      const scores = this.scoreSegment(sentence);\n      const topDirection = this.getTopDirection(scores);\n      const isImplicit = scores[topDirection] < 0.3;\n\n      directions[topDirection].push({\n        text: sentence.trim(),\n        confidence: Math.min(scores[topDirection] * 2, 1),\n        implicit: isImplicit,\n      });\n\n      // If a segment has strong presence in multiple directions, add as implicit\n      for (const dir of ALL_DIRECTIONS) {\n        if (dir !== topDirection && scores[dir] > 0.2) {\n          directions[dir].push({\n            text: sentence.trim(),\n            confidence: scores[dir],\n            implicit: true,\n          });\n        }\n      }\n    }\n\n    // Calculate balance\n    const counts = ALL_DIRECTIONS.map((d) => directions[d].length);\n    const total = counts.reduce((a, b) => a + b, 0) || 1;\n    const proportions = counts.map((c) => c / total);\n    const idealProportion = 0.25;\n    const deviation =\n      proportions.reduce((sum, p) => sum + Math.abs(p - idealProportion), 0) /\n      4;\n    const balance = 1 - deviation * 4; // 1 = perfectly balanced\n\n    // Find lead and neglected\n    const maxCount = Math.max(...counts);\n    const leadDirection =\n      ALL_DIRECTIONS[counts.indexOf(maxCount)] || Direction.NORTH;\n    const neglectedDirections = ALL_DIRECTIONS.filter(\n      (d) => directions[d].length / total < this.neglectThreshold\n    );\n\n    return {\n      id,\n      timestamp: new Date().toISOString(),\n      prompt,\n      directions,\n      leadDirection,\n      neglectedDirections,\n      balance: Math.max(0, Math.min(1, balance)),\n    };\n  }\n\n  /** Check if a decomposition is balanced enough to proceed */\n  isBalanced(analysis: DirectionalAnalysis): boolean {\n    return analysis.balance >= this.balanceThreshold;\n  }\n\n  /** Generate guidance for neglected directions */\n  getGuidance(analysis: DirectionalAnalysis): string[] {\n    const guidance: string[] = [];\n    for (const dir of analysis.neglectedDirections) {\n      guidance.push(\n        `${DIRECTION_NAMES[dir]}: ${DIRECTION_QUESTIONS[dir]} Consider what is missing from this perspective.`\n      );\n    }\n    if (analysis.balance < this.balanceThreshold) {\n      guidance.push(\n        `Overall balance is ${(analysis.balance * 100).toFixed(0)}% — consider addressing all four directions before proceeding.`\n      );\n    }\n    return guidance;\n  }\n\n  // ---------------------------------------------------------------------------\n  // Internal\n  // ---------------------------------------------------------------------------\n\n  private splitIntoSegments(text: string): string[] {\n    // Split on sentence boundaries, commas for lists, and newlines\n    return text\n      .split(/(?<=[.!?])\\s+|\\n+/)\n      .map((s) => s.trim())\n      .filter((s) => s.length > 3);\n  }\n\n  private scoreSegment(segment: string): Record<Direction, number> {\n    const lower = segment.toLowerCase();\n    const words = lower.split(/\\s+/);\n    const scores: Record<Direction, number> = {\n      [Direction.EAST]: 0,\n      [Direction.SOUTH]: 0,\n      [Direction.WEST]: 0,\n      [Direction.NORTH]: 0,\n    };\n\n    for (const dir of ALL_DIRECTIONS) {\n      for (const keyword of DIRECTION_KEYWORDS[dir]) {\n        for (const word of words) {\n          if (word.includes(keyword)) {\n            scores[dir] += 1;\n          }\n        }\n      }\n    }\n\n    // Normalize\n    const total =\n      Object.values(scores).reduce((a, b) => a + b, 0) || 1;\n    for (const dir of ALL_DIRECTIONS) {\n      scores[dir] /= total;\n    }\n\n    return scores;\n  }\n\n  private getTopDirection(scores: Record<Direction, number>): Direction {\n    let top = Direction.NORTH;\n    let max = -1;\n    for (const dir of ALL_DIRECTIONS) {\n      if (scores[dir] > max) {\n        max = scores[dir];\n        top = dir;\n      }\n    }\n    return top;\n  }\n}\n","/**\n * Intent Extractor\n *\n * Extracts primary and secondary intents from a prompt,\n * following the PDE (Prompt Decomposition Engine) structure:\n * - Primary intent: single action-target-urgency-confidence tuple\n * - Secondary intents: multiple action items with dependency mapping,\n *   implicit/explicit classification, and confidence scoring\n *\n * This is the EAST (Vision) function of PDE — clarifying what is being asked.\n */\n\nimport { v4 as uuid } from \"uuid\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { z } from \"zod\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport enum Urgency {\n  IMMEDIATE = \"immediate\",\n  SESSION = \"session\",\n  SPRINT = \"sprint\",\n  ONGOING = \"ongoing\",\n}\n\nexport interface PrimaryIntent {\n  action: string;\n  target: string;\n  urgency: Urgency;\n  confidence: number; // 0-1\n}\n\nexport interface SecondaryIntent {\n  id: string;\n  action: string;\n  target: string;\n  implicit: boolean;\n  dependency: string | null; // ID of another secondary intent\n  confidence: number;\n}\n\nexport interface IntentExtractionResult {\n  id: string;\n  timestamp: string;\n  prompt: string;\n  primary: PrimaryIntent;\n  secondary: SecondaryIntent[];\n  context: ExtractionContext;\n}\n\nexport interface ExtractionContext {\n  filesNeeded: string[];\n  toolsRequired: string[];\n  assumptions: string[];\n}\n\n// Action verb categories for classification\nconst ACTION_VERBS: Record<string, string[]> = {\n  create: [\"create\", \"build\", \"make\", \"generate\", \"write\", \"develop\", \"design\", \"scaffold\", \"initialize\", \"init\", \"implement\"],\n  modify: [\"modify\", \"update\", \"change\", \"edit\", \"adjust\", \"refactor\", \"rename\", \"move\", \"restructure\"],\n  investigate: [\"investigate\", \"research\", \"explore\", \"understand\", \"learn\", \"study\", \"analyze\", \"examine\", \"look\", \"check\", \"review\", \"see\"],\n  add: [\"add\", \"install\", \"include\", \"import\", \"integrate\", \"connect\", \"wire\", \"attach\", \"link\"],\n  remove: [\"remove\", \"delete\", \"clean\", \"prune\", \"drop\", \"uninstall\"],\n  test: [\"test\", \"verify\", \"validate\", \"ensure\", \"confirm\", \"check\", \"assert\"],\n  deploy: [\"deploy\", \"ship\", \"publish\", \"release\", \"push\", \"launch\"],\n  manage: [\"manage\", \"organize\", \"coordinate\", \"orchestrate\", \"maintain\", \"handle\"],\n  use: [\"use\", \"leverage\", \"utilize\", \"employ\", \"apply\", \"run\", \"execute\"],\n  draft: [\"draft\", \"outline\", \"plan\", \"sketch\", \"propose\", \"document\"],\n};\n\nconst URGENCY_KEYWORDS: Record<Urgency, string[]> = {\n  [Urgency.IMMEDIATE]: [\"now\", \"immediately\", \"urgent\", \"asap\", \"right away\", \"quickly\"],\n  [Urgency.SESSION]: [\"today\", \"this session\", \"let's\", \"get to work\", \"start\"],\n  [Urgency.SPRINT]: [\"this week\", \"sprint\", \"soon\", \"next\", \"upcoming\"],\n  [Urgency.ONGOING]: [\"eventually\", \"someday\", \"long-term\", \"future\", \"ongoing\", \"continuous\"],\n};\n\n// =============================================================================\n// IntentExtractor\n// =============================================================================\n\n// Zod schema for LLM output validation\nconst SecondaryIntentSchema = z.object({\n  action: z.string().describe(\"The primary verb or action from the prompt. Must be one of: create, modify, investigate, add, remove, test, deploy, manage, use, draft.\"),\n  target: z.string().describe(\"The object or goal of the action.\"),\n  implicit: z.boolean().describe(\"True if this intent was implied rather than explicitly stated. Defaults to false.\"),\n  dependency: z.string().nullable().describe(\"The ID of another secondary intent that this intent depends on. Set to null if no dependency is found.\"),\n  confidence: z.number().min(0).max(1).describe(\"Confidence score (0-1) that this intent is correct and actionable.\"),\n  id: z.string().optional().describe(\"Unique identifier for this intent.\"),\n});\n\nconst IntentExtractionResultSchema = z.object({\n  primary: z.object({\n    action: z.string().describe(\"The primary verb or action for the main goal. Must be one of: create, modify, investigate, add, remove, test, deploy, manage, use, draft.\"),\n    target: z.string().describe(\"The object or goal of the main action.\"),\n    urgency: z.nativeEnum(Urgency).describe(\"The detected urgency of the primary intent. One of: immediate, session, sprint, ongoing.\"),\n    confidence: z.number().min(0).max(1).describe(\"Confidence score (0-1) in the primary intent.\"),\n  }),\n  secondary: z.array(SecondaryIntentSchema).describe(\"A list of secondary, detailed intents extracted from the prompt, each with a unique ID.\"),\n  context: z.object({\n    filesNeeded: z.array(z.string()).describe(\"List of file paths or references mentioned in the prompt (e.g., /src/file.ts, @package/module).\"),\n    toolsRequired: z.array(z.string()).describe(\"List of tools or external systems mentioned as required (e.g., 'git', 'docker', 'npm').\"),\n    assumptions: z.array(z.string()).describe(\"List of assumptions made or explicit assumptions stated in the prompt.\"),\n  }),\n});\n\nexport interface ExtractorOptions {\n  extractImplicit?: boolean; // Default true\n  mapDependencies?: boolean; // Default true\n  llm?: BaseLanguageModel; // Optional LLM for enhanced extraction\n}\n\nexport class IntentExtractor {\n  private readonly extractImplicit: boolean;\n  private readonly mapDependencies: boolean;\n  private readonly llm?: BaseLanguageModel;\n\n  constructor(options?: ExtractorOptions) {\n    this.extractImplicit = options?.extractImplicit ?? true;\n    this.mapDependencies = options?.mapDependencies ?? true;\n    this.llm = options?.llm;\n  }\n\n  /**\n   * Extract intents from a prompt.\n   * Returns a structured result with primary + secondary intents.\n   */\n  async extract(prompt: string): Promise<IntentExtractionResult> {\n    const id = uuid();\n    const timestamp = new Date().toISOString();\n    const context = this.extractContext(prompt);\n\n    if (this.llm) {\n      try {\n        const llmResult = await this._extractIntentsWithLLM(prompt);\n        // Ensure IDs are generated for secondary intents if missing\n        llmResult.secondary.forEach((s) => {\n          if (!s.id) {\n            s.id = uuid();\n          }\n          // Also ensure action is one of the valid ACTION_VERBS categories\n          if (!Object.keys(ACTION_VERBS).includes(s.action)) {\n            s.action = \"investigate\"; // Fallback to a safe default\n          }\n        });\n        return {\n          id,\n          timestamp,\n          prompt,\n          primary: llmResult.primary,\n          secondary: llmResult.secondary as SecondaryIntent[],\n          context: llmResult.context ?? context,\n        };\n      } catch (e) {\n        console.warn(\"LLM intent extraction failed, falling back to heuristics:\", e);\n        // Fallback to heuristic-based extraction on LLM failure\n      }\n    }\n\n    const sentences = this.splitSentences(prompt);\n    const rawIntents = this.extractRawIntents(sentences);\n\n    // The primary intent is the one with highest confidence\n    const primary = this.determinePrimary(rawIntents, prompt);\n\n    // Remaining become secondary, with dependency mapping\n    const secondary = this.buildSecondaryIntents(rawIntents);\n\n    return {\n      id,\n      timestamp,\n      prompt,\n      primary,\n      secondary,\n      context,\n    };\n  }\n\n  // ---------------------------------------------------------------------------\n  // Internal\n  // ---------------------------------------------------------------------------\n\n  private async _extractIntentsWithLLM(prompt: string): Promise<z.infer<typeof IntentExtractionResultSchema>> {\n    if (!this.llm) {\n      throw new Error(\"LLM not provided for LLM-based extraction.\");\n    }\n\n    const schemaDescription = JSON.stringify({\n      primary: { action: \"string (one of action verbs)\", target: \"string\", urgency: \"immediate|session|sprint|ongoing\", confidence: \"number 0-1\" },\n      secondary: [{ id: \"uuid\", action: \"string\", target: \"string\", implicit: \"boolean\", dependency: \"string|null\", confidence: \"number 0-1\" }],\n      context: { filesNeeded: [\"string\"], toolsRequired: [\"string\"], assumptions: [\"string\"] },\n    }, null, 2);\n\n    const systemPrompt = `You are an expert software engineer assistant specializing in breaking down complex user prompts into structured, actionable intents.\nYour goal is to extract a primary intent, a list of secondary intents (sub-tasks), and relevant context (files, tools, assumptions).\nEach intent should have an action (one of: ${Object.keys(ACTION_VERBS).join(\", \")}), a target, a confidence score (0-1), and an optional dependency on another secondary intent by its ID.\nAlso identify if an intent is implicit (implied but not explicitly stated).\nAssign a unique ID (UUID) to each secondary intent.\nDetermine the overall urgency of the primary intent.\n\nThink step-by-step:\n1. Identify the main goal or objective (Primary Intent).\n2. Break down the main goal into smaller, discrete tasks (Secondary Intents).\n3. For each secondary intent, identify its action, target, and estimate a confidence score.\n4. Look for implicit tasks (e.g., \"ensure quality\" implies \"test\").\n5. Determine if any secondary intents depend on others.\n6. Extract any mentioned file paths, tool requirements, or explicit assumptions.\n7. Return the result in JSON matching this schema:\n\n${schemaDescription}\n\nEnsure the JSON is perfectly valid and can be directly parsed. Do not include any additional text outside the JSON object.\n`;\n\n    const response = await (this.llm as any).invoke([\n      [\"system\", systemPrompt],\n      [\"human\", prompt],\n    ]);\n\n    const content = typeof response === \"string\"\n      ? response\n      : typeof response?.content === \"string\"\n        ? response.content\n        : String(response);\n\n    let parsedResult;\n    try {\n      parsedResult = JSON.parse(content);\n    } catch (e) {\n      console.error(\"Failed to parse LLM response as JSON:\", e);\n      console.error(\"LLM response content:\", content);\n      throw new Error(\"LLM output was not valid JSON.\");\n    }\n\n    const validationResult = IntentExtractionResultSchema.safeParse(parsedResult);\n    if (!validationResult.success) {\n      console.error(\"LLM output did not match schema:\", validationResult.error);\n      throw new Error(\"LLM output did not match expected schema.\");\n    }\n\n    return validationResult.data;\n  }\n\n  private splitSentences(text: string): string[] {\n    return text\n      .split(/(?<=[.!?])\\s+|\\n+|,\\s+(?=[A-Z])|;\\s+/)\n      .map((s) => s.trim())\n      .filter((s) => s.length > 5);\n  }\n\n  private extractRawIntents(\n    sentences: string[]\n  ): Array<{ action: string; target: string; confidence: number; implicit: boolean; sentence: string }> {\n    const intents: Array<{\n      action: string;\n      target: string;\n      confidence: number;\n      implicit: boolean;\n      sentence: string;\n    }> = [];\n\n    for (const sentence of sentences) {\n      const lower = sentence.toLowerCase();\n      let bestAction = \"\";\n      let bestCategory = \"\";\n      let found = false;\n\n      for (const [category, verbs] of Object.entries(ACTION_VERBS)) {\n        for (const verb of verbs) {\n          if (lower.includes(verb)) {\n            if (!found || verb.length > bestAction.length) {\n              bestAction = verb;\n              bestCategory = category;\n              found = true;\n            }\n          }\n        }\n      }\n\n      if (found) {\n        // Extract target: everything after the action verb\n        const verbIdx = lower.indexOf(bestAction);\n        const afterVerb = sentence.substring(verbIdx + bestAction.length).trim();\n        const target = afterVerb.replace(/^(the|a|an|this|that|our|your)\\s+/i, \"\",).trim();\n\n        intents.push({\n          action: bestCategory,\n          target: target || sentence,\n          confidence: this.calculateConfidence(sentence, bestAction),\n          implicit: false,\n          sentence,\n        });\n      }\n    }\n\n    // Extract implicit intents if enabled\n    if (this.extractImplicit) {\n      const implicitIntents = this.findImplicitIntents(sentences, intents);\n      intents.push(...implicitIntents);\n    }\n\n    return intents;\n  }\n\n  private findImplicitIntents(\n    sentences: string[],\n    explicitIntents: Array<{ action: string; target: string; confidence: number; implicit: boolean; sentence: string }>\n  ): Array<{ action: string; target: string; confidence: number; implicit: boolean; sentence: string }> {\n    const implicit: Array<{\n      action: string;\n      target: string;\n      confidence: number;\n      implicit: boolean;\n      sentence: string;\n    }> = [];\n\n    // Pattern: \"which\" clauses imply investigation\n    for (const sentence of sentences) {\n      const lower = sentence.toLowerCase();\n      if (lower.includes(\"which\") && !explicitIntents.some((i) => i.sentence === sentence)) {\n        implicit.push({\n          action: \"investigate\",\n          target: sentence,\n          confidence: 0.6,\n          implicit: true,\n          sentence,\n        });\n      }\n    }\n\n    // Pattern: conditional (\"if\", \"when\") implies validation need\n    for (const sentence of sentences) {\n      const lower = sentence.toLowerCase();\n      if (\n        (lower.startsWith(\"if \") || lower.includes(\" if \") || lower.includes(\"when \")) &&\n        !explicitIntents.some((i) => i.sentence === sentence)\n      ) {\n        implicit.push({\n          action: \"test\",\n          target: sentence,\n          confidence: 0.5,\n          implicit: true,\n          sentence,\n        });\n      }\n    }\n\n    // Pattern: hedging language implies implicit intent (from mcp-pde lineage)\n    // Detects: \"I assume\", \"I expect\", \"you will need\", \"probably\", \"somehow\", \"should\"\n    for (const sentence of sentences) {\n      const lower = sentence.toLowerCase();\n      if (explicitIntents.some((i) => i.sentence === sentence)) continue;\n      if (implicit.some((i) => i.sentence === sentence)) continue;\n\n      if (/i assume|which i assume|assuming/.test(lower)) {\n        implicit.push({\n          action: \"investigate\",\n          target: sentence,\n          confidence: 0.5,\n          implicit: true,\n          sentence,\n        });\n      } else if (/i expect|expecting|you will need/.test(lower)) {\n        implicit.push({\n          action: \"investigate\",\n          target: sentence,\n          confidence: 0.55,\n          implicit: true,\n          sentence,\n        });\n      } else if (/\\bsomehow\\b/.test(lower)) {\n        implicit.push({\n          action: \"investigate\",\n          target: sentence,\n          confidence: 0.4,\n          implicit: true,\n          sentence,\n        });\n      } else if (/\\bprobably\\b|\\bshould\\b(?!\\s+not)/.test(lower) &&\n                 !explicitIntents.some((i) => i.sentence === sentence)) {\n        implicit.push({\n          action: \"investigate\",\n          target: sentence,\n          confidence: 0.45,\n          implicit: true,\n          sentence,\n        });\n      }\n    }\n\n    return implicit;\n  }\n\n  private determinePrimary(\n    rawIntents: Array<{ action: string; target: string; confidence: number }>,\n    prompt: string\n  ): PrimaryIntent {\n    if (rawIntents.length === 0) {\n      return {\n        action: \"investigate\",\n        target: prompt.substring(0, 100),\n        urgency: this.detectUrgency(prompt),\n        confidence: 0.5,\n      };\n    }\n\n    // Sort by confidence, pick highest\n    const sorted = [...rawIntents].sort((a, b) => b.confidence - a.confidence);\n    const top = sorted[0];\n\n    return {\n      action: top.action,\n      target: top.target.substring(0, 200),\n      urgency: this.detectUrgency(prompt),\n      confidence: top.confidence,\n    };\n  }\n\n  private buildSecondaryIntents(\n    rawIntents: Array<{ action: string; target: string; confidence: number; implicit: boolean }>\n  ): SecondaryIntent[] {\n    const secondaries: SecondaryIntent[] = rawIntents.map((raw) => ({\n      id: uuid(),\n      action: raw.action,\n      target: raw.target.substring(0, 300),\n      implicit: raw.implicit,\n      dependency: null,\n      confidence: raw.confidence,\n    }));\n\n    // Map dependencies if enabled\n    if (this.mapDependencies && secondaries.length > 1) {\n      this.inferDependencies(secondaries);\n    }\n\n    return secondaries;\n  }\n\n  private inferDependencies(intents: SecondaryIntent[]): void {\n    // Investigation before creation\n    const investigations = intents.filter((i) => i.action === \"investigate\");\n    const creations = intents.filter((i) =>\n      [\"create\", \"add\", \"modify\"].includes(i.action)\n    );\n\n    for (const creation of creations) {\n      for (const inv of investigations) {\n        if (this.targetsOverlap(inv.target, creation.target)) {\n          creation.dependency = inv.id;\n          break;\n        }\n      }\n    }\n\n    // Testing after creation\n    const tests = intents.filter((i) => i.action === \"test\");\n    for (const test of tests) {\n      for (const creation of creations) {\n        if (this.targetsOverlap(creation.target, test.target)) {\n          test.dependency = creation.id;\n          break;\n        }\n      }\n    }\n\n    // Deploy after test\n    const deploys = intents.filter((i) => i.action === \"deploy\");\n    for (const deploy of deploys) {\n      if (tests.length > 0) {\n        deploy.dependency = tests[tests.length - 1].id;\n      } else if (creations.length > 0) {\n        deploy.dependency = creations[creations.length - 1].id;\n      }\n    }\n  }\n\n  private targetsOverlap(a: string, b: string): boolean {\n    const wordsA = new Set(a.toLowerCase().split(/\\s+/).filter((w) => w.length > 3));\n    const wordsB = new Set(b.toLowerCase().split(/\\s+/).filter((w) => w.length > 3));\n    let overlap = 0;\n    for (const w of wordsA) {\n      if (wordsB.has(w)) overlap++;\n    }\n    return overlap >= 1;\n  }\n\n  private detectUrgency(prompt: string): Urgency {\n    const lower = prompt.toLowerCase();\n    for (const [urgency, keywords] of Object.entries(URGENCY_KEYWORDS) as Array<\n      [Urgency, string[]]\n    >) {\n      for (const kw of keywords) {\n        if (lower.includes(kw)) return urgency;\n      }\n    }\n    return Urgency.SESSION;\n  }\n\n  private calculateConfidence(sentence: string, verb: string): number {\n    const lower = sentence.toLowerCase();\n    let confidence = 0.7;\n\n    // Boost for imperative voice\n    if (lower.startsWith(verb)) confidence += 0.15;\n\n    // Boost for specific targets (paths, names)\n    if (/\\/[a-z]/.test(lower) || /@[a-z]/.test(lower)) confidence += 0.1;\n\n    // Reduce for hedging language\n    if (/maybe|perhaps|could|might|possibly/.test(lower)) confidence -= 0.2;\n\n    return Math.min(1, Math.max(0.1, confidence));\n  }\n\n  private extractContext(prompt: string): ExtractionContext {\n    const filesNeeded: string[] = [];\n    const toolsRequired: string[] = [];\n    const assumptions: string[] = [];\n\n    // Extract file paths\n    const pathMatches = prompt.match(/(?:\\/[\\w.-]+)+\\/?/g);\n    if (pathMatches) {\n      filesNeeded.push(...new Set(pathMatches));\n    }\n\n    // Extract @-references\n    const atRefs = prompt.match(/@[\\w./-]+/g);\n    if (atRefs) {\n      filesNeeded.push(...atRefs.map((r) => r.substring(1)));\n    }\n\n    // Extract tool references\n    const toolPatterns = /(?:mcp|tool|use)\\s+(\\S+)/gi;\n    let match;\n    while ((match = toolPatterns.exec(prompt)) !== null) {\n      toolsRequired.push(match[1]);\n    }\n\n    // Extract assumptions from hedging language (mcp-pde lineage)\n    const sentences = prompt.split(/(?<=[.!?])\\s+|\\n+/).filter((s) => s.length > 5);\n    for (const sentence of sentences) {\n      const lower = sentence.toLowerCase();\n      if (/i assume|i expect|i know that|which i assume|assuming that/.test(lower)) {\n        assumptions.push(sentence.trim());\n      } else if (/\\bprobably\\b|\\bsomehow\\b|\\bshould\\b/.test(lower) && lower.length < 200) {\n        assumptions.push(sentence.trim());\n      }\n    }\n\n    return { filesNeeded, toolsRequired, assumptions };\n  }\n}\n","/**\n * Dependency Mapper\n *\n * Maps dependencies between tasks, detects implicit requirements,\n * and produces a dependency-aware ordering.\n *\n * This is the SOUTH (Analysis) function of PDE — understanding\n * what needs to be learned and what depends on what.\n */\n\nimport { v4 as uuid } from \"uuid\";\nimport type { SecondaryIntent } from \"./intent_extractor.js\";\nimport type { Direction } from \"./directional_decomposer.js\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface DependencyNode {\n  id: string;\n  intentId: string;\n  action: string;\n  target: string;\n  direction: Direction;\n  dependencies: string[]; // IDs of other DependencyNodes\n  dependents: string[]; // IDs that depend on this\n  depth: number; // 0 = root (no dependencies)\n  completed: boolean;\n}\n\nexport interface DependencyGraph {\n  id: string;\n  nodes: Map<string, DependencyNode>;\n  roots: string[]; // Nodes with no dependencies\n  leaves: string[]; // Nodes with no dependents\n  maxDepth: number;\n  hasCycle: boolean;\n}\n\nexport interface ExecutionOrder {\n  layers: DependencyNode[][]; // Parallel execution layers\n  totalSteps: number;\n  criticalPath: string[]; // Longest dependency chain\n}\n\n// =============================================================================\n// DependencyMapper\n// =============================================================================\n\nexport class DependencyMapper {\n  /**\n   * Build a dependency graph from secondary intents and their\n   * directional classifications.\n   */\n  buildGraph(\n    intents: SecondaryIntent[],\n    directionMap?: Map<string, Direction>\n  ): DependencyGraph {\n    const id = uuid();\n    const nodes = new Map<string, DependencyNode>();\n\n    // Create nodes\n    for (const intent of intents) {\n      const nodeId = intent.id;\n      const direction = directionMap?.get(intent.id) ?? this.inferDirection(intent);\n\n      nodes.set(nodeId, {\n        id: nodeId,\n        intentId: intent.id,\n        action: intent.action,\n        target: intent.target,\n        direction,\n        dependencies: [],\n        dependents: [],\n        depth: 0,\n        completed: false,\n      });\n    }\n\n    // Wire dependencies from intent dependency field\n    for (const intent of intents) {\n      if (intent.dependency) {\n        const node = nodes.get(intent.id);\n        const depNode = nodes.get(intent.dependency);\n        if (node && depNode) {\n          node.dependencies.push(depNode.id);\n          depNode.dependents.push(node.id);\n        }\n      }\n    }\n\n    // Infer additional structural dependencies\n    this.inferStructuralDependencies(nodes);\n\n    // Detect cycles\n    const hasCycle = this.detectCycle(nodes);\n\n    // Calculate depths\n    if (!hasCycle) {\n      this.calculateDepths(nodes);\n    }\n\n    // Find roots and leaves\n    const roots: string[] = [];\n    const leaves: string[] = [];\n    let maxDepth = 0;\n\n    for (const [id, node] of nodes) {\n      if (node.dependencies.length === 0) roots.push(id);\n      if (node.dependents.length === 0) leaves.push(id);\n      if (node.depth > maxDepth) maxDepth = node.depth;\n    }\n\n    return { id, nodes, roots, leaves, maxDepth, hasCycle };\n  }\n\n  /**\n   * Compute execution order from a dependency graph.\n   * Groups tasks into parallel layers where all tasks in a layer\n   * can execute simultaneously.\n   */\n  computeExecutionOrder(graph: DependencyGraph): ExecutionOrder {\n    if (graph.hasCycle) {\n      // Fall back to sequential if cycles detected\n      const allNodes = Array.from(graph.nodes.values());\n      return {\n        layers: allNodes.map((n) => [n]),\n        totalSteps: allNodes.length,\n        criticalPath: allNodes.map((n) => n.id),\n      };\n    }\n\n    const layers: DependencyNode[][] = [];\n    const visited = new Set<string>();\n\n    for (let depth = 0; depth <= graph.maxDepth; depth++) {\n      const layer: DependencyNode[] = [];\n      for (const node of graph.nodes.values()) {\n        if (node.depth === depth && !visited.has(node.id)) {\n          layer.push(node);\n          visited.add(node.id);\n        }\n      }\n      if (layer.length > 0) {\n        layers.push(layer);\n      }\n    }\n\n    // Add any unvisited nodes (shouldn't happen, but safety net)\n    const remaining: DependencyNode[] = [];\n    for (const node of graph.nodes.values()) {\n      if (!visited.has(node.id)) {\n        remaining.push(node);\n        visited.add(node.id);\n      }\n    }\n    if (remaining.length > 0) {\n      layers.push(remaining);\n    }\n\n    const criticalPath = this.findCriticalPath(graph);\n\n    return {\n      layers,\n      totalSteps: layers.length,\n      criticalPath,\n    };\n  }\n\n  // ---------------------------------------------------------------------------\n  // Internal\n  // ---------------------------------------------------------------------------\n\n  private inferDirection(intent: SecondaryIntent): Direction {\n    const action = intent.action.toLowerCase();\n    if ([\"investigate\", \"research\", \"explore\", \"study\", \"analyze\"].includes(action)) {\n      return \"south\" as Direction;\n    }\n    if ([\"test\", \"verify\", \"validate\", \"review\", \"check\"].includes(action)) {\n      return \"west\" as Direction;\n    }\n    if ([\"create\", \"build\", \"implement\", \"add\", \"deploy\", \"install\", \"modify\", \"use\", \"run\"].includes(action)) {\n      return \"north\" as Direction;\n    }\n    // Vision/planning\n    if ([\"draft\", \"plan\", \"design\", \"manage\"].includes(action)) {\n      return \"east\" as Direction;\n    }\n    return \"north\" as Direction;\n  }\n\n  private inferStructuralDependencies(nodes: Map<string, DependencyNode>): void {\n    const nodeArray = Array.from(nodes.values());\n\n    // South (research) should come before North (action) on same topic\n    const southNodes = nodeArray.filter((n) => n.direction === \"south\");\n    const northNodes = nodeArray.filter((n) => n.direction === \"north\");\n\n    for (const south of southNodes) {\n      for (const north of northNodes) {\n        if (\n          this.topicsRelated(south.target, north.target) &&\n          !north.dependencies.includes(south.id) &&\n          !south.dependencies.includes(north.id) // avoid creating cycles\n        ) {\n          north.dependencies.push(south.id);\n          south.dependents.push(north.id);\n        }\n      }\n    }\n\n    // West (validation) should come after North (action) on same topic\n    const westNodes = nodeArray.filter((n) => n.direction === \"west\");\n    for (const north of northNodes) {\n      for (const west of westNodes) {\n        if (\n          this.topicsRelated(north.target, west.target) &&\n          !west.dependencies.includes(north.id) &&\n          !north.dependencies.includes(west.id)\n        ) {\n          west.dependencies.push(north.id);\n          north.dependents.push(west.id);\n        }\n      }\n    }\n  }\n\n  private topicsRelated(a: string, b: string): boolean {\n    const wordsA = new Set(\n      a.toLowerCase().split(/\\s+/).filter((w) => w.length > 3)\n    );\n    const wordsB = new Set(\n      b.toLowerCase().split(/\\s+/).filter((w) => w.length > 3)\n    );\n    let overlap = 0;\n    for (const w of wordsA) {\n      if (wordsB.has(w)) overlap++;\n    }\n    return overlap >= 2;\n  }\n\n  private detectCycle(nodes: Map<string, DependencyNode>): boolean {\n    const visited = new Set<string>();\n    const inStack = new Set<string>();\n\n    const dfs = (nodeId: string): boolean => {\n      if (inStack.has(nodeId)) return true;\n      if (visited.has(nodeId)) return false;\n\n      visited.add(nodeId);\n      inStack.add(nodeId);\n\n      const node = nodes.get(nodeId);\n      if (node) {\n        for (const dep of node.dependents) {\n          if (dfs(dep)) return true;\n        }\n      }\n\n      inStack.delete(nodeId);\n      return false;\n    };\n\n    for (const nodeId of nodes.keys()) {\n      if (dfs(nodeId)) return true;\n    }\n    return false;\n  }\n\n  private calculateDepths(nodes: Map<string, DependencyNode>): void {\n    const calculated = new Set<string>();\n\n    const calcDepth = (nodeId: string): number => {\n      if (calculated.has(nodeId)) {\n        return nodes.get(nodeId)?.depth ?? 0;\n      }\n\n      const node = nodes.get(nodeId);\n      if (!node) return 0;\n\n      if (node.dependencies.length === 0) {\n        node.depth = 0;\n        calculated.add(nodeId);\n        return 0;\n      }\n\n      let maxDepDep = 0;\n      for (const depId of node.dependencies) {\n        maxDepDep = Math.max(maxDepDep, calcDepth(depId));\n      }\n\n      node.depth = maxDepDep + 1;\n      calculated.add(nodeId);\n      return node.depth;\n    };\n\n    for (const nodeId of nodes.keys()) {\n      calcDepth(nodeId);\n    }\n  }\n\n  private findCriticalPath(graph: DependencyGraph): string[] {\n    if (graph.leaves.length === 0) return [];\n\n    let longestPath: string[] = [];\n\n    const buildPath = (nodeId: string, path: string[]): void => {\n      const node = graph.nodes.get(nodeId);\n      if (!node) return;\n\n      path.push(nodeId);\n\n      if (node.dependencies.length === 0) {\n        if (path.length > longestPath.length) {\n          longestPath = [...path];\n        }\n      } else {\n        for (const depId of node.dependencies) {\n          buildPath(depId, [...path]);\n        }\n      }\n    };\n\n    for (const leafId of graph.leaves) {\n      buildPath(leafId, []);\n    }\n\n    return longestPath.reverse();\n  }\n}\n","/**\n * Action Stack\n *\n * Produces a dependency-ordered, direction-tagged execution plan\n * from a complete PDE decomposition. This is the final output\n * structure that consumers (LangGraph, Flowise) use to execute tasks.\n *\n * This is the NORTH (Action) function of PDE — what actually executes.\n */\n\nimport { v4 as uuid } from \"uuid\";\nimport type { DirectionalAnalysis, Direction } from \"./directional_decomposer.js\";\nimport type { IntentExtractionResult, SecondaryIntent } from \"./intent_extractor.js\";\nimport type { DependencyGraph, ExecutionOrder } from \"./dependency_mapper.js\";\nimport { DependencyMapper } from \"./dependency_mapper.js\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface ActionItem {\n  id: string;\n  text: string;\n  direction: Direction;\n  dependency: string | null; // ID of prerequisite action\n  completed: boolean;\n  confidence: number;\n  implicit: boolean;\n}\n\n/** Structured ambiguity flag (mcp-pde lineage) */\nexport interface AmbiguityFlag {\n  text: string;\n  suggestion: string;\n}\n\n/** Expected outputs from the decomposition (mcp-pde lineage) */\nexport interface ExpectedOutputs {\n  artifacts: string[];\n  updates: string[];\n  communications: string[];\n}\n\nexport interface DecompositionResult {\n  id: string;\n  timestamp: string;\n  prompt: string;\n  primary: {\n    action: string;\n    target: string;\n    urgency: string;\n    confidence: number;\n  };\n  secondary: SecondaryIntent[];\n  context: {\n    filesNeeded: string[];\n    toolsRequired: string[];\n    assumptions: string[];\n  };\n  outputs: ExpectedOutputs;\n  directions: Record<Direction, Array<{ text: string; confidence: number; implicit: boolean }>>;\n  actionStack: ActionItem[];\n  balance: number;\n  leadDirection: Direction;\n  neglectedDirections: Direction[];\n  ambiguities: AmbiguityFlag[];\n}\n\nexport interface ActionStackOptions {\n  includeImplicit?: boolean; // Include implicit actions (default true)\n  maxItems?: number; // Max actions in stack (default 20)\n}\n\n// =============================================================================\n// ActionStack Builder\n// =============================================================================\n\nexport class ActionStackBuilder {\n  private readonly includeImplicit: boolean;\n  private readonly maxItems: number;\n\n  constructor(options?: ActionStackOptions) {\n    this.includeImplicit = options?.includeImplicit ?? true;\n    this.maxItems = options?.maxItems ?? 20;\n  }\n\n  /**\n   * Build the complete PDE output from directional analysis and intent extraction.\n   * This merges all decomposition outputs into the final action stack.\n   */\n  build(\n    directionalAnalysis: DirectionalAnalysis,\n    intentResult: IntentExtractionResult,\n    executionOrder?: ExecutionOrder\n  ): DecompositionResult {\n    const id = uuid();\n\n    // Build action stack from execution order or intents\n    let actionStack: ActionItem[];\n    if (executionOrder) {\n      actionStack = this.fromExecutionOrder(executionOrder, intentResult);\n    } else {\n      actionStack = this.fromIntents(intentResult, directionalAnalysis);\n    }\n\n    // Apply max items limit\n    if (actionStack.length > this.maxItems) {\n      actionStack = actionStack.slice(0, this.maxItems);\n    }\n\n    // Filter implicit if disabled\n    if (!this.includeImplicit) {\n      actionStack = actionStack.filter((a) => !a.implicit);\n    }\n\n    // Detect ambiguities\n    const ambiguities = this.detectAmbiguities(directionalAnalysis, intentResult);\n\n    return {\n      id,\n      timestamp: new Date().toISOString(),\n      prompt: intentResult.prompt,\n      primary: {\n        action: intentResult.primary.action,\n        target: intentResult.primary.target,\n        urgency: intentResult.primary.urgency,\n        confidence: intentResult.primary.confidence,\n      },\n      secondary: intentResult.secondary,\n      context: intentResult.context,\n      outputs: this.extractExpectedOutputs(intentResult),\n      directions: {\n        east: directionalAnalysis.directions.east?.map((i) => ({\n          text: i.text,\n          confidence: i.confidence,\n          implicit: i.implicit,\n        })) ?? [],\n        south: directionalAnalysis.directions.south?.map((i) => ({\n          text: i.text,\n          confidence: i.confidence,\n          implicit: i.implicit,\n        })) ?? [],\n        west: directionalAnalysis.directions.west?.map((i) => ({\n          text: i.text,\n          confidence: i.confidence,\n          implicit: i.implicit,\n        })) ?? [],\n        north: directionalAnalysis.directions.north?.map((i) => ({\n          text: i.text,\n          confidence: i.confidence,\n          implicit: i.implicit,\n        })) ?? [],\n      },\n      actionStack,\n      balance: directionalAnalysis.balance,\n      leadDirection: directionalAnalysis.leadDirection,\n      neglectedDirections: directionalAnalysis.neglectedDirections,\n      ambiguities,\n    };\n  }\n\n  /**\n   * Serialize a DecompositionResult to the PDE JSON format\n   * (compatible with /workspace/.pde/ structure)\n   */\n  toJSON(result: DecompositionResult): string {\n    return JSON.stringify(\n      {\n        id: result.id,\n        timestamp: result.timestamp,\n        prompt: result.prompt,\n        result: {\n          primary: result.primary,\n          secondary: result.secondary,\n          context: {\n            files_needed: result.context.filesNeeded,\n            tools_required: result.context.toolsRequired,\n            assumptions: result.context.assumptions,\n          },\n          outputs: result.outputs,\n          directions: result.directions,\n          actionStack: result.actionStack,\n          ambiguities: result.ambiguities,\n        },\n        options: {\n          extractImplicit: this.includeImplicit,\n          mapDependencies: true,\n        },\n      },\n      null,\n      2\n    );\n  }\n\n  /**\n   * Render a DecompositionResult as human-readable Markdown\n   */\n  toMarkdown(result: DecompositionResult): string {\n    const lines: string[] = [];\n\n    lines.push(`# Prompt Decomposition`);\n    lines.push(\"\");\n\n    // Four Directions (canonical container)\n    lines.push(`## Four Directions`);\n    lines.push(\"\");\n\n    const dirEmoji: Record<string, string> = {\n      east: \"🌅\",\n      south: \"🔥\",\n      west: \"🌊\",\n      north: \"❄️\",\n    };\n    const dirSubtitle: Record<string, string> = {\n      east: \"Vision\",\n      south: \"Analysis\",\n      west: \"Validation\",\n      north: \"Action\",\n    };\n\n    for (const dir of [\"east\", \"south\", \"west\", \"north\"] as Direction[]) {\n      const insights = result.directions[dir];\n      if (insights.length > 0) {\n        lines.push(`### ${dirEmoji[dir]} ${dir.toUpperCase()} — ${dirSubtitle[dir]}`);\n        for (const insight of insights) {\n          const tag = insight.implicit ? \" _(implicit)_\" : \"\";\n          lines.push(`- ${insight.text} [${(insight.confidence * 100).toFixed(0)}%]${tag}`);\n        }\n        lines.push(\"\");\n      }\n    }\n\n    // Primary Intent\n    lines.push(`## Primary Intent`);\n    lines.push(`**Action:** ${result.primary.action} → ${result.primary.target}`);\n    lines.push(`**Urgency:** ${result.primary.urgency} | **Confidence:** ${(result.primary.confidence * 100).toFixed(0)}%`);\n    lines.push(`**Balance:** ${(result.balance * 100).toFixed(0)}% | **Lead:** ${result.leadDirection}`);\n    lines.push(\"\");\n\n    // Secondary Intents\n    if (result.secondary.length > 0) {\n      lines.push(`## Secondary Intents`);\n      for (const s of result.secondary) {\n        const tag = s.implicit ? \" _(implicit)_\" : \"\";\n        const dep = s.dependency ? ` → depends on: ${s.dependency}` : \"\";\n        lines.push(`- ${s.action} → ${s.target} [${(s.confidence * 100).toFixed(0)}%]${tag}${dep}`);\n      }\n      lines.push(\"\");\n    }\n\n    // Context Requirements\n    if (result.context.filesNeeded.length || result.context.toolsRequired.length || result.context.assumptions.length) {\n      lines.push(`## Context Requirements`);\n      if (result.context.filesNeeded.length) {\n        lines.push(`### Files Needed`);\n        result.context.filesNeeded.forEach((f) => lines.push(`- ${f}`));\n        lines.push(\"\");\n      }\n      if (result.context.toolsRequired.length) {\n        lines.push(`### Tools Required`);\n        result.context.toolsRequired.forEach((t) => lines.push(`- ${t}`));\n        lines.push(\"\");\n      }\n      if (result.context.assumptions.length) {\n        lines.push(`### Assumptions`);\n        result.context.assumptions.forEach((a) => lines.push(`- ${a}`));\n        lines.push(\"\");\n      }\n    }\n\n    // Expected Outputs\n    if (result.outputs.artifacts.length || result.outputs.updates.length || result.outputs.communications.length) {\n      lines.push(`## Expected Outputs`);\n      if (result.outputs.artifacts.length) {\n        lines.push(`### Artifacts`);\n        result.outputs.artifacts.forEach((a) => lines.push(`- ${a}`));\n        lines.push(\"\");\n      }\n      if (result.outputs.updates.length) {\n        lines.push(`### Updates`);\n        result.outputs.updates.forEach((u) => lines.push(`- ${u}`));\n        lines.push(\"\");\n      }\n      if (result.outputs.communications.length) {\n        lines.push(`### Communications`);\n        result.outputs.communications.forEach((c) => lines.push(`- ${c}`));\n        lines.push(\"\");\n      }\n    }\n\n    // Action Stack\n    lines.push(`## Action Stack`);\n    for (const action of result.actionStack) {\n      const check = action.completed ? \"x\" : \" \";\n      const dep = action.dependency ? ` → depends on: ${action.dependency}` : \"\";\n      const tag = action.implicit ? \" _(implicit)_\" : \"\";\n      lines.push(`- [${check}] [${action.direction}] ${action.text}${tag}${dep}`);\n    }\n    lines.push(\"\");\n\n    // Ambiguity Flags\n    if (result.ambiguities.length > 0) {\n      lines.push(`## Ambiguity Flags`);\n      for (const amb of result.ambiguities) {\n        lines.push(`- **\"${amb.text}\"**`);\n        lines.push(`  - Suggestion: ${amb.suggestion}`);\n      }\n      lines.push(\"\");\n    }\n\n    return lines.join(\"\\n\");\n  }\n\n  // ---------------------------------------------------------------------------\n  // Internal\n  // ---------------------------------------------------------------------------\n\n  private fromExecutionOrder(\n    order: ExecutionOrder,\n    intentResult: IntentExtractionResult\n  ): ActionItem[] {\n    const items: ActionItem[] = [];\n    const intentMap = new Map(\n      intentResult.secondary.map((s) => [s.id, s])\n    );\n\n    for (const layer of order.layers) {\n      for (const node of layer) {\n        const intent = intentMap.get(node.intentId);\n        items.push({\n          id: node.id,\n          text: `${node.action} ${node.target}`,\n          direction: node.direction,\n          dependency: node.dependencies[0] ?? null,\n          completed: node.completed,\n          confidence: intent?.confidence ?? 0.7,\n          implicit: intent?.implicit ?? false,\n        });\n      }\n    }\n\n    return items;\n  }\n\n  private fromIntents(\n    intentResult: IntentExtractionResult,\n    directionalAnalysis: DirectionalAnalysis\n  ): ActionItem[] {\n    const mapper = new DependencyMapper();\n    const graph = mapper.buildGraph(intentResult.secondary);\n    const order = mapper.computeExecutionOrder(graph);\n    return this.fromExecutionOrder(order, intentResult);\n  }\n\n  private detectAmbiguities(\n    directionalAnalysis: DirectionalAnalysis,\n    intentResult: IntentExtractionResult\n  ): AmbiguityFlag[] {\n    const ambiguities: AmbiguityFlag[] = [];\n\n    // Low confidence primary\n    if (intentResult.primary.confidence < 0.5) {\n      ambiguities.push({\n        text: `Primary intent has low confidence (${(intentResult.primary.confidence * 100).toFixed(0)}%)`,\n        suggestion: \"Clarify the main goal with a more specific action verb and target.\",\n      });\n    }\n\n    // Neglected directions\n    for (const dir of directionalAnalysis.neglectedDirections) {\n      const desc = dir === \"east\" ? \"vision clarity\" : dir === \"south\" ? \"research context\" : dir === \"west\" ? \"validation criteria\" : \"actionable steps\";\n      ambiguities.push({\n        text: `Direction ${dir} is neglected`,\n        suggestion: `The prompt lacks ${desc}. Consider addressing what is missing from this perspective.`,\n      });\n    }\n\n    // Hedging language in prompt → ambiguity flags\n    const lower = intentResult.prompt.toLowerCase();\n    if (/\\bsomehow\\b/.test(lower)) {\n      ambiguities.push({\n        text: `\"somehow\" — method left unspecified`,\n        suggestion: \"Specify the approach or method to use.\",\n      });\n    }\n    if (/\\bprobably\\b|\\bmaybe\\b|\\bperhaps\\b/.test(lower)) {\n      ambiguities.push({\n        text: `Hedging language detected (\"probably\", \"maybe\", \"perhaps\")`,\n        suggestion: \"Confirm or deny the hedged assumptions before proceeding.\",\n      });\n    }\n\n    return ambiguities;\n  }\n\n  private extractExpectedOutputs(\n    intentResult: IntentExtractionResult\n  ): ExpectedOutputs {\n    const artifacts: string[] = [];\n    const updates: string[] = [];\n    const communications: string[] = [];\n\n    for (const intent of intentResult.secondary) {\n      if ([\"create\", \"add\"].includes(intent.action)) {\n        artifacts.push(intent.target);\n      } else if ([\"modify\", \"use\"].includes(intent.action)) {\n        updates.push(intent.target);\n      } else if ([\"deploy\", \"draft\"].includes(intent.action)) {\n        communications.push(intent.target);\n      }\n    }\n\n    // Primary also contributes\n    if ([\"create\", \"add\"].includes(intentResult.primary.action)) {\n      artifacts.push(intentResult.primary.target);\n    } else if ([\"modify\"].includes(intentResult.primary.action)) {\n      updates.push(intentResult.primary.target);\n    }\n\n    return { artifacts, updates, communications };\n  }\n}\n","/**\n * Medicine Wheel Bridge\n *\n * Bridges PDE's Four Directions with the MedicineWheelFilter\n * from ava-langchain-relational-intelligence. This maps:\n *   EAST → SPIRITUAL (vision, purpose)\n *   SOUTH → MENTAL (analysis, learning)\n *   WEST → EMOTIONAL (reflection, ceremony)\n *   NORTH → PHYSICAL (action, execution)\n *\n * When relational-intelligence is available, it enriches PDE\n * decompositions with wheel assessments and value gate checks.\n */\n\nimport { Direction, type DirectionalAnalysis } from \"./directional_decomposer.js\";\n\n// =============================================================================\n// Direction ↔ Quadrant Mapping\n// =============================================================================\n\n/** Medicine Wheel quadrants from relational-intelligence */\nexport enum WheelQuadrant {\n  PHYSICAL = \"physical\",\n  EMOTIONAL = \"emotional\",\n  MENTAL = \"mental\",\n  SPIRITUAL = \"spiritual\",\n}\n\n/** How PDE directions map to Medicine Wheel quadrants */\nexport const DIRECTION_TO_QUADRANT: Record<Direction, WheelQuadrant> = {\n  [Direction.EAST]: WheelQuadrant.SPIRITUAL,\n  [Direction.SOUTH]: WheelQuadrant.MENTAL,\n  [Direction.WEST]: WheelQuadrant.EMOTIONAL,\n  [Direction.NORTH]: WheelQuadrant.PHYSICAL,\n};\n\nexport const QUADRANT_TO_DIRECTION: Record<WheelQuadrant, Direction> = {\n  [WheelQuadrant.SPIRITUAL]: Direction.EAST,\n  [WheelQuadrant.MENTAL]: Direction.SOUTH,\n  [WheelQuadrant.EMOTIONAL]: Direction.WEST,\n  [WheelQuadrant.PHYSICAL]: Direction.NORTH,\n};\n\n// =============================================================================\n// Bridge Types\n// =============================================================================\n\nexport interface WheelEnrichedAnalysis extends DirectionalAnalysis {\n  wheelMapping: Record<Direction, WheelQuadrant>;\n  quadrantPresence: Record<WheelQuadrant, number>;\n  relationalCoverage: number;\n  ceremonyRequired: boolean;\n}\n\nexport interface WheelBridgeOptions {\n  ceremonyThreshold?: number; // Minimum spiritual+emotional coverage to not require ceremony (default 0.3)\n}\n\n// =============================================================================\n// MedicineWheelBridge\n// =============================================================================\n\nexport class MedicineWheelBridge {\n  private readonly ceremonyThreshold: number;\n\n  constructor(options?: WheelBridgeOptions) {\n    this.ceremonyThreshold = options?.ceremonyThreshold ?? 0.3;\n  }\n\n  /**\n   * Enrich a directional analysis with Medicine Wheel assessment.\n   * Maps direction coverage to quadrant presence and determines\n   * whether ceremony is needed.\n   */\n  enrich(analysis: DirectionalAnalysis): WheelEnrichedAnalysis {\n    // Calculate quadrant presence from direction coverage\n    const totalInsights = Object.values(analysis.directions)\n      .reduce((sum, insights) => sum + insights.length, 0) || 1;\n\n    const quadrantPresence: Record<WheelQuadrant, number> = {\n      [WheelQuadrant.SPIRITUAL]: analysis.directions[Direction.EAST].length / totalInsights,\n      [WheelQuadrant.MENTAL]: analysis.directions[Direction.SOUTH].length / totalInsights,\n      [WheelQuadrant.EMOTIONAL]: analysis.directions[Direction.WEST].length / totalInsights,\n      [WheelQuadrant.PHYSICAL]: analysis.directions[Direction.NORTH].length / totalInsights,\n    };\n\n    // Relational coverage: how many quadrants are represented\n    const representedQuadrants = Object.values(quadrantPresence).filter(\n      (v) => v > 0.05\n    ).length;\n    const relationalCoverage = representedQuadrants / 4;\n\n    // Ceremony required if spiritual + emotional are too low\n    const ceremonialPresence =\n      quadrantPresence[WheelQuadrant.SPIRITUAL] +\n      quadrantPresence[WheelQuadrant.EMOTIONAL];\n    const ceremonyRequired = ceremonialPresence < this.ceremonyThreshold;\n\n    return {\n      ...analysis,\n      wheelMapping: { ...DIRECTION_TO_QUADRANT },\n      quadrantPresence,\n      relationalCoverage,\n      ceremonyRequired,\n    };\n  }\n\n  /**\n   * Check if a decomposition can proceed without ceremony.\n   * Returns false if spiritual/emotional directions are neglected.\n   */\n  canProceedWithoutCeremony(analysis: DirectionalAnalysis): boolean {\n    const enriched = this.enrich(analysis);\n    return !enriched.ceremonyRequired;\n  }\n\n  /**\n   * Generate guidance for bringing a decomposition into relational balance.\n   */\n  getRelationalGuidance(analysis: DirectionalAnalysis): string[] {\n    const enriched = this.enrich(analysis);\n    const guidance: string[] = [];\n\n    if (enriched.quadrantPresence[WheelQuadrant.SPIRITUAL] < 0.1) {\n      guidance.push(\n        \"EAST/Spiritual: The vision is unclear. What is the deeper purpose? Who does this serve?\"\n      );\n    }\n\n    if (enriched.quadrantPresence[WheelQuadrant.EMOTIONAL] < 0.1) {\n      guidance.push(\n        \"WEST/Emotional: Reflection is missing. What ceremonies or protocols should be honored? Who needs to be consulted?\"\n      );\n    }\n\n    if (enriched.quadrantPresence[WheelQuadrant.MENTAL] < 0.1) {\n      guidance.push(\n        \"SOUTH/Mental: Analysis is thin. What needs to be researched or understood before proceeding?\"\n      );\n    }\n\n    if (enriched.quadrantPresence[WheelQuadrant.PHYSICAL] < 0.1) {\n      guidance.push(\n        \"NORTH/Physical: No actionable steps found. What concrete actions will manifest this work?\"\n      );\n    }\n\n    if (enriched.ceremonyRequired) {\n      guidance.push(\n        \"⚠️ Ceremony Required: Spiritual and emotional dimensions are underrepresented. Pause for relational check-in before proceeding.\"\n      );\n    }\n\n    return guidance;\n  }\n}\n","/**\n * V0 Ontology Bridge\n *\n * Maps PDE (Prompt Decomposition Engine) concepts to the\n * V0 Medicine Wheel Developer Suite ontology vision.\n *\n * V0.md envisions these packages:\n *   @medicine-wheel/ontology-core  → RDF + relational data model\n *   @medicine-wheel/graph-viz      → Force-directed + wheel overlays\n *   @medicine-wheel/narrative-engine → Beat sequencing across directions\n *   @medicine-wheel/relational-query → Context-aware traversal\n *   @medicine-wheel/ui-components  → Direction cards, timelines\n *\n * This bridge shows how PDE primitives and existing ava-langchain\n * packages map to each of those envisioned packages.\n */\n\nimport type { Direction } from \"./directional_decomposer.js\";\nimport type { WheelQuadrant } from \"./wheel_bridge.js\";\n\n// =============================================================================\n// Ontology Core Mapping\n// =============================================================================\n\n/**\n * Maps to @medicine-wheel/ontology-core\n *\n * The PDE DirectionalDecomposer + MedicineWheelBridge provide:\n * - Direction/Act/Ceremony type system (Direction enum, WheelQuadrant)\n * - Temporal beats tracking (ActionItem with dependency ordering)\n * - RDF-compatible triples could be generated from DecompositionResult\n */\nexport interface OntologyCoreConcept {\n  /** Direction in Medicine Wheel */\n  direction: Direction;\n  /** Corresponding quadrant */\n  quadrant: WheelQuadrant;\n  /** Anishinaabe name */\n  indigenousName: string;\n  /** Act in narrative structure */\n  act: number;\n  /** Season symbolism */\n  season: string;\n  /** Element */\n  element: string;\n}\n\nexport const ONTOLOGY_CORE_MAP: Record<Direction, OntologyCoreConcept> = {\n  east: {\n    direction: \"east\" as Direction,\n    quadrant: \"spiritual\" as WheelQuadrant,\n    indigenousName: \"Waabinong\",\n    act: 1,\n    season: \"spring\",\n    element: \"air\",\n  },\n  south: {\n    direction: \"south\" as Direction,\n    quadrant: \"mental\" as WheelQuadrant,\n    indigenousName: \"Zhaawanong\",\n    act: 2,\n    season: \"summer\",\n    element: \"fire\",\n  },\n  west: {\n    direction: \"west\" as Direction,\n    quadrant: \"emotional\" as WheelQuadrant,\n    indigenousName: \"Epangishmok\",\n    act: 3,\n    season: \"autumn\",\n    element: \"water\",\n  },\n  north: {\n    direction: \"north\" as Direction,\n    quadrant: \"physical\" as WheelQuadrant,\n    indigenousName: \"Kiiwedinong\",\n    act: 4,\n    season: \"winter\",\n    element: \"earth\",\n  },\n};\n\n// =============================================================================\n// Narrative Engine Mapping\n// =============================================================================\n\n/**\n * Maps to @medicine-wheel/narrative-engine\n *\n * PDE ActionStack items are narrative beats:\n * - Each action = a beat with direction, dependency, confidence\n * - The execution order = beat sequencing across four directions\n * - The DecompositionGraph = ceremonial cadence pattern\n *\n * Existing packages that feed this:\n * - ava-langgraph-narrative-intelligence: ThreePerspectiveProcessor, CoherenceEngine\n * - ava-langchain-narrative-tracing: Story beat observability\n */\nexport interface NarrativeBeatMapping {\n  /** PDE action ID */\n  actionId: string;\n  /** Direction this beat belongs to */\n  direction: Direction;\n  /** Act number (1-4 based on direction) */\n  act: number;\n  /** The action text becomes the beat description */\n  description: string;\n  /** Whether this beat was explicitly stated or inferred */\n  implicit: boolean;\n  /** Confidence in this beat */\n  confidence: number;\n}\n\n/**\n * Convert a PDE action to a narrative beat.\n */\nexport function actionToNarrativeBeat(\n  action: { id: string; text: string; direction: Direction; confidence: number; implicit: boolean }\n): NarrativeBeatMapping {\n  const concept = ONTOLOGY_CORE_MAP[action.direction];\n  return {\n    actionId: action.id,\n    direction: action.direction,\n    act: concept?.act ?? 4,\n    description: action.text,\n    implicit: action.implicit,\n    confidence: action.confidence,\n  };\n}\n\n// =============================================================================\n// Relational Query Mapping\n// =============================================================================\n\n/**\n * Maps to @medicine-wheel/relational-query\n *\n * PDE's DependencyMapper produces a graph of task dependencies.\n * This maps to relational-query's context-aware relationship traversal:\n * - DependencyNode = graph node with typed relationships\n * - Dependencies = \"depends_on\" relationships\n * - Direction = relationship context (which quadrant)\n *\n * Existing packages:\n * - ava-langchain-relational-intelligence: ImportanceStore, SpiralTracker\n *   provide the accountability tracking layer\n */\nexport interface RelationalQueryNode {\n  id: string;\n  type: \"task\" | \"ceremony\" | \"vision\" | \"research\";\n  direction: Direction;\n  relationships: Array<{\n    targetId: string;\n    type: \"depends_on\" | \"validates\" | \"informs\" | \"ceremonies\";\n    confidence: number;\n  }>;\n}\n\n// =============================================================================\n// Package Mapping Summary\n// =============================================================================\n\n/**\n * How existing ava-* packages map to V0's envisioned @medicine-wheel/* suite.\n * This serves as a roadmap for convergence.\n */\nexport const PACKAGE_MAPPING = {\n  \"@medicine-wheel/ontology-core\": {\n    existingPackages: [\n      \"ava-langchain-prompt-decomposition (Direction, WheelQuadrant types)\",\n      \"ava-langchain-relational-intelligence (MedicineWheelFilter, ImportanceUnit)\",\n    ],\n    providedBy: \"Direction enum, WheelBridge, ONTOLOGY_CORE_MAP\",\n    missing: \"RDF triple store, OWL vocabulary, SPARQL queries\",\n  },\n  \"@medicine-wheel/graph-viz\": {\n    existingPackages: [\n      \"ava-langchain-prompt-decomposition (DependencyGraph visualization)\",\n    ],\n    providedBy: \"DependencyMapper produces graph structure\",\n    missing: \"D3 force-directed layout, Medicine Wheel overlay renderer\",\n  },\n  \"@medicine-wheel/narrative-engine\": {\n    existingPackages: [\n      \"ava-langgraph-narrative-intelligence (ThreePerspectiveProcessor, CoherenceEngine)\",\n      \"ava-langchain-narrative-tracing (NarrativeTracingHandler)\",\n      \"ava-langgraph-prompt-decomposition-engine (DecompositionGraph)\",\n    ],\n    providedBy: \"ActionStack → beats, DecompositionGraph → ceremonial cadence\",\n    missing: \"Timeline/categorical view React components\",\n  },\n  \"@medicine-wheel/relational-query\": {\n    existingPackages: [\n      \"ava-langchain-relational-intelligence (ImportanceStore, SpiralTracker, ValueGate)\",\n      \"ava-langchain-prompt-decomposition (DependencyMapper)\",\n    ],\n    providedBy: \"DependencyGraph + ImportanceStore\",\n    missing: \"SPARQL-like query builder, OCAP-aware access control\",\n  },\n  \"@medicine-wheel/ui-components\": {\n    existingPackages: [\n      \"ava-Flowise (PromptDecomposition node, MedicineWheelGate node)\",\n    ],\n    providedBy: \"AgentFlow nodes for Flowise\",\n    missing: \"Standalone React components, direction cards, beat timelines\",\n  },\n} as const;\n","/**\n * PDE Storage — .pde/ dot folder persistence\n *\n * Ported from mcp-pde/src/storage.ts (IAIP lineage).\n * Stores decompositions as JSON files in .pde/ directory,\n * with Markdown exports for human-in-the-loop editing via git diff.\n *\n * Storage layout:\n *   .pde/\n *     <id>.json   — StoredDecomposition (full JSON)\n *     <id>.md     — Markdown export (human-editable, git-diffable)\n */\n\nimport {\n  existsSync,\n  mkdirSync,\n  readFileSync,\n  readdirSync,\n  statSync,\n  writeFileSync,\n} from \"fs\";\nimport { join } from \"path\";\nimport type { DecompositionResult } from \"./action_stack.js\";\nimport {\n  extractStrategyMetadata,\n  type StrategicDecompositionResult,\n} from \"./strategy_spec.js\";\nimport {\n  PDE_DIR,\n  appendChildEntry,\n  buildPdeTreeMetadata,\n  ensureDirectory,\n  extractPdeUuidFromPath,\n  findPdeFolder,\n  getPdeRoot,\n  mergeAddDirs,\n  readPdeTreeMetadata,\n  writePdeTreeMetadata,\n  type ChildKind,\n  type PdeFallbackMetadata,\n  type PdeRuntimeEngine,\n  type PdeSessionIdSource,\n} from \"./pde_metadata.js\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface StoredDecomposition {\n  id: string;\n  timestamp: string;\n  prompt: string;\n  result: DecompositionResult;\n  engine?: PdeRuntimeEngine;\n  model?: string;\n  parent_pde_id?: string;\n  child_kind?: ChildKind;\n  fallback?: PdeFallbackMetadata;\n  provenance?: Record<string, unknown>;\n  folder_name?: string;\n  pde_dir?: string;\n  markdownPath?: string;\n}\n\nexport type PdeStorageLayout = \"flat\" | \"tree\";\n\nexport interface SaveDecompositionOptions {\n  /** Legacy flat storage is the default for backward compatibility. */\n  layout?: PdeStorageLayout;\n  engine?: PdeRuntimeEngine;\n  model?: string;\n  sessionId?: string;\n  sessionIdSource?: PdeSessionIdSource;\n  parentPdeId?: string;\n  parentPdeFolder?: string;\n  childKind?: ChildKind;\n  provenance?: Record<string, unknown>;\n  addDirs?: string[];\n  pvaProvider?: string;\n  pvaThinking?: string;\n  hermesProvider?: string;\n  fallback?: PdeFallbackMetadata;\n}\n\n// =============================================================================\n// Storage Functions\n// =============================================================================\n\nfunction ensureDir(workdir: string): string {\n  const dir = getPdeRoot(workdir);\n  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n  return dir;\n}\n\nfunction generateTimestamp(): string {\n  const date = new Date();\n  const yy = String(date.getFullYear()).slice(-2);\n  const mm = String(date.getMonth() + 1).padStart(2, \"0\");\n  const dd = String(date.getDate()).padStart(2, \"0\");\n  const hh = String(date.getHours()).padStart(2, \"0\");\n  const min = String(date.getMinutes()).padStart(2, \"0\");\n  return `${yy}${mm}${dd}${hh}${min}`;\n}\n\nfunction collectStoredDecompositionFiles(root: string): string[] {\n  const results: string[] = [];\n  if (!existsSync(root)) return results;\n\n  function visit(dir: string): void {\n    let entries: string[];\n    try {\n      entries = readdirSync(dir);\n    } catch {\n      return;\n    }\n\n    for (const entry of entries) {\n      const fullPath = join(dir, entry);\n      let stat;\n      try {\n        stat = statSync(fullPath);\n      } catch {\n        continue;\n      }\n\n      if (stat.isDirectory()) {\n        visit(fullPath);\n        continue;\n      }\n\n      const isTreeRecord = entry.startsWith(\"pde-\") && entry.endsWith(\".json\");\n      const isLegacyRootRecord =\n        dir === root && entry.endsWith(\".json\") && entry !== \"meta.json\";\n      if (stat.isFile() && (isTreeRecord || isLegacyRootRecord)) {\n        results.push(fullPath);\n      }\n    }\n  }\n\n  visit(root);\n  return results;\n}\n\nfunction withProvenanceKind(\n  provenance: Record<string, unknown> | undefined,\n  childKind: ChildKind | undefined\n): Record<string, unknown> | undefined {\n  if (!childKind) return provenance;\n  if (provenance && Object.prototype.hasOwnProperty.call(provenance, \"kind\")) {\n    return provenance;\n  }\n  return { ...(provenance ?? {}), kind: childKind };\n}\n\n/**\n * Save a decomposition to .pde/ as JSON + Markdown.\n */\nexport function saveDecomposition(\n  workdir: string,\n  result: DecompositionResult,\n  options: SaveDecompositionOptions = {}\n): StoredDecomposition {\n  if (options.layout === \"tree\") {\n    return saveDecompositionTree(workdir, result, options);\n  }\n\n  const dir = ensureDir(workdir);\n  const stored: StoredDecomposition = {\n    id: result.id,\n    timestamp: result.timestamp,\n    prompt: result.prompt,\n    result,\n    provenance: options.provenance,\n  };\n\n  // Save JSON\n  const jsonPath = join(dir, `${result.id}.json`);\n  writeFileSync(jsonPath, JSON.stringify(stored, null, 2), \"utf-8\");\n\n  // Save Markdown\n  const mdPath = join(dir, `${result.id}.md`);\n  const md = decompositionToMarkdown(result);\n  writeFileSync(mdPath, md, \"utf-8\");\n  stored.markdownPath = mdPath;\n\n  return stored;\n}\n\n/**\n * Save a decomposition using miaco-style folder-backed PDE tree storage.\n *\n * Layout:\n *   .pde/<timestamp>--<uuid>/pde-<uuid>.json\n *   .pde/<timestamp>--<uuid>/pde-<uuid>.md\n *   .pde/<timestamp>--<uuid>/meta.json\n *\n * Children are nested under their parent folder and recorded in the parent's\n * metadata children[] reverse edge.\n */\nexport function saveDecompositionTree(\n  workdir: string,\n  result: DecompositionResult,\n  options: Omit<SaveDecompositionOptions, \"layout\"> = {}\n): StoredDecomposition {\n  const pdeRoot = ensureDir(workdir);\n  const folderName = `${generateTimestamp()}--${result.id}`;\n\n  let parentFolder: string | null = options.parentPdeFolder ?? null;\n  if (options.parentPdeId && !parentFolder) {\n    parentFolder = findPdeFolder(workdir, options.parentPdeId);\n  }\n  if (options.parentPdeId && !parentFolder) {\n    throw new Error(`Parent PDE not found: ${options.parentPdeId}`);\n  }\n\n  const inheritedMeta = parentFolder ? readPdeTreeMetadata(parentFolder) : null;\n  const targetDir = parentFolder ? join(parentFolder, folderName) : join(pdeRoot, folderName);\n  ensureDirectory(targetDir);\n\n  const sessionId = options.sessionId ?? inheritedMeta?.session_id;\n  const sessionIdSource: PdeSessionIdSource | undefined = options.sessionId\n    ? options.sessionIdSource ?? \"manual\"\n    : inheritedMeta?.session_id\n      ? \"inherited\"\n      : undefined;\n  const addDirs = mergeAddDirs(inheritedMeta?.add_dirs, options.addDirs);\n  const parentPdeId =\n    options.parentPdeId ?? (parentFolder ? extractPdeUuidFromPath(parentFolder) ?? undefined : undefined);\n  const provenance = withProvenanceKind(options.provenance, options.childKind);\n\n  const stored: StoredDecomposition = {\n    id: result.id,\n    timestamp: result.timestamp,\n    prompt: result.prompt,\n    result,\n    engine: options.engine ?? inheritedMeta?.engine ?? \"heuristic\",\n    model: options.model ?? inheritedMeta?.model,\n    parent_pde_id: parentPdeId,\n    child_kind: options.childKind,\n    fallback: options.fallback,\n    provenance,\n    folder_name: folderName,\n    pde_dir: targetDir,\n  };\n\n  const jsonPath = join(targetDir, `pde-${result.id}.json`);\n  writeFileSync(jsonPath, JSON.stringify(stored, null, 2), \"utf-8\");\n\n  const mdPath = join(targetDir, `pde-${result.id}.md`);\n  const md = decompositionToMarkdown(result, {\n    engine: stored.engine,\n    model: stored.model,\n    parentPdeId,\n  });\n  writeFileSync(mdPath, md, \"utf-8\");\n  stored.markdownPath = mdPath;\n\n  const metadata = buildPdeTreeMetadata({\n    rootPdeId: inheritedMeta?.root_pde_id ?? result.id,\n    parentPdeId,\n    parentPdeDir: parentFolder ?? undefined,\n    childKind: options.childKind,\n    provenance,\n    engine: stored.engine,\n    model: stored.model,\n    pvaProvider: options.pvaProvider ?? inheritedMeta?.pva_provider,\n    pvaThinking: options.pvaThinking ?? inheritedMeta?.pva_thinking,\n    hermesProvider: options.hermesProvider ?? inheritedMeta?.hermes_provider,\n    addDirs,\n    fallback: options.fallback,\n    sessionId,\n    sessionIdSource,\n  });\n  writePdeTreeMetadata(targetDir, metadata);\n\n  if (parentFolder) {\n    appendChildEntry(parentFolder, {\n      uuid: result.id,\n      kind: options.childKind ?? \"sibling\",\n      created_at: stored.timestamp,\n    });\n  }\n\n  return stored;\n}\n\n/**\n * Persist a strategy-aware result while retaining the stable\n * DecompositionResult record shape and adding strategy provenance.\n */\nexport function saveStrategicDecomposition(\n  workdir: string,\n  result: StrategicDecompositionResult,\n  options: SaveDecompositionOptions = {}\n): StoredDecomposition {\n  return saveDecomposition(workdir, result.result.decomposition, {\n    ...options,\n    provenance: {\n      ...(options.provenance ?? {}),\n      strategy: extractStrategyMetadata(result),\n    },\n  });\n}\n\n/**\n * Load a stored decomposition by ID.\n */\nexport function loadDecomposition(workdir: string, id: string): StoredDecomposition | null {\n  const folder = findPdeFolder(workdir, id);\n  if (folder) {\n    const uuid = extractPdeUuidFromPath(folder) ?? id;\n    const treePath = join(folder, `pde-${uuid}.json`);\n    if (existsSync(treePath)) {\n      const raw = readFileSync(treePath, \"utf-8\");\n      return JSON.parse(raw) as StoredDecomposition;\n    }\n  }\n\n  const legacyPath = join(workdir, PDE_DIR, `${id}.json`);\n  if (!existsSync(legacyPath)) return null;\n  const raw = readFileSync(legacyPath, \"utf-8\");\n  return JSON.parse(raw) as StoredDecomposition;\n}\n\n/**\n * List stored decompositions, newest first.\n */\nexport function listDecompositions(workdir: string, limit?: number): StoredDecomposition[] {\n  const dir = join(workdir, PDE_DIR);\n  if (!existsSync(dir)) return [];\n\n  const files = collectStoredDecompositionFiles(dir);\n  const items: StoredDecomposition[] = [];\n  for (const file of files) {\n    try {\n      const raw = readFileSync(file, \"utf-8\");\n      const parsed = JSON.parse(raw) as Partial<StoredDecomposition>;\n      if (parsed.id && parsed.result) items.push(parsed as StoredDecomposition);\n    } catch {\n      // Ignore malformed or non-storage JSON.\n    }\n  }\n\n  items.sort((a, b) => (b.timestamp || \"\").localeCompare(a.timestamp || \"\"));\n  return limit ? items.slice(0, limit) : items;\n}\n\n/**\n * Convert a DecompositionResult to git-diffable Markdown.\n * Includes Four Directions header and structured ambiguity flags.\n */\nexport interface DecompositionMarkdownOptions {\n  engine?: PdeRuntimeEngine;\n  model?: string;\n  parentPdeId?: string;\n}\n\nexport function decompositionToMarkdown(\n  result: DecompositionResult,\n  options: DecompositionMarkdownOptions = {}\n): string {\n  const lines: string[] = [];\n\n  lines.push(\"# Prompt Decomposition\");\n  if (options.engine) {\n    lines.push(\"\");\n    lines.push(`> Engine: **${options.engine}**${options.model ? ` (${options.model})` : \"\"}`);\n  }\n  if (options.parentPdeId) {\n    lines.push(\"\");\n    lines.push(`> Parent PDE: ${options.parentPdeId}`);\n  }\n  lines.push(\"\");\n\n  // Four Directions legend\n  lines.push(\"## Directions\");\n  lines.push(\"\");\n  lines.push(\"- 🌅 **EAST** — VISION: What is being asked?\");\n  lines.push(\"- 🔥 **SOUTH** — ANALYSIS: What needs to be learned?\");\n  lines.push(\"- 🌊 **WEST** — VALIDATION: What needs reflection?\");\n  lines.push(\"- ❄️ **NORTH** — ACTION: What executes the cycle?\");\n  lines.push(\"\");\n\n  // Original prompt\n  lines.push(\"## Original Prompt\");\n  lines.push(\"\");\n  lines.push(`> ${result.prompt.replace(/\\n/g, \"\\n> \")}`);\n  lines.push(\"\");\n\n  // Primary Intent\n  lines.push(\"## Primary Intent\");\n  lines.push(\"\");\n  lines.push(`**Action:** ${result.primary.action}`);\n  lines.push(`**Target:** ${result.primary.target}`);\n  lines.push(`**Urgency:** ${result.primary.urgency}`);\n  lines.push(`**Confidence:** ${Math.round(result.primary.confidence * 100)}%`);\n  lines.push(\"\");\n\n  // Secondary Intents\n  if (result.secondary.length > 0) {\n    lines.push(\"## Secondary Intents\");\n    lines.push(\"\");\n    for (let i = 0; i < result.secondary.length; i++) {\n      const s = result.secondary[i];\n      lines.push(`${i + 1}. **${s.action}** — ${s.target} _(${s.implicit ? \"implicit\" : \"explicit\"})_`);\n      if (s.dependency) lines.push(`   - depends on: ${s.dependency}`);\n    }\n    lines.push(\"\");\n  }\n\n  // Context\n  const ctx = result.context;\n  if (ctx.filesNeeded.length || ctx.toolsRequired.length || ctx.assumptions.length) {\n    lines.push(\"## Context Requirements\");\n    lines.push(\"\");\n    if (ctx.filesNeeded.length) {\n      lines.push(\"### Files Needed\");\n      ctx.filesNeeded.forEach((f) => lines.push(`- ${f}`));\n      lines.push(\"\");\n    }\n    if (ctx.toolsRequired.length) {\n      lines.push(\"### Tools Required\");\n      ctx.toolsRequired.forEach((t) => lines.push(`- ${t}`));\n      lines.push(\"\");\n    }\n    if (ctx.assumptions.length) {\n      lines.push(\"### Assumptions\");\n      ctx.assumptions.forEach((a) => lines.push(`- ${a}`));\n      lines.push(\"\");\n    }\n  }\n\n  // Four Directions detail\n  const dirEmoji: Record<string, string> = { east: \"🌅\", south: \"🔥\", west: \"🌊\", north: \"❄️\" };\n  const dirName: Record<string, string> = { east: \"VISION\", south: \"ANALYSIS\", west: \"VALIDATION\", north: \"ACTION\" };\n\n  lines.push(\"## Four Directions Analysis\");\n  lines.push(\"\");\n  for (const dir of [\"east\", \"south\", \"west\", \"north\"]) {\n    const items = result.directions[dir as keyof typeof result.directions];\n    if (!items || items.length === 0) continue;\n    lines.push(`### ${dirEmoji[dir]} ${dir.toUpperCase()} — ${dirName[dir]}`);\n    lines.push(\"\");\n    for (const item of items) {\n      const tag = item.implicit ? \" _(implicit)_\" : \"\";\n      lines.push(`- ${item.text} [${Math.round(item.confidence * 100)}%]${tag}`);\n    }\n    lines.push(\"\");\n  }\n\n  // Action Stack\n  if (result.actionStack.length > 0) {\n    lines.push(\"## Action Stack\");\n    lines.push(\"\");\n    for (const action of result.actionStack) {\n      const check = action.completed ? \"x\" : \" \";\n      const dep = action.dependency ? ` (depends on: ${action.dependency})` : \"\";\n      lines.push(`- [${check}] ${action.text}${dep}`);\n    }\n    lines.push(\"\");\n  }\n\n  // Ambiguity Flags (structured)\n  if (result.ambiguities.length > 0) {\n    lines.push(\"## Ambiguity Flags\");\n    lines.push(\"\");\n    for (const a of result.ambiguities) {\n      lines.push(`- **\"${a.text}\"**`);\n      lines.push(`  - Suggestion: ${a.suggestion}`);\n    }\n    lines.push(\"\");\n  }\n\n  // Expected Outputs\n  const out = result.outputs;\n  if (out.artifacts.length || out.updates.length || out.communications.length) {\n    lines.push(\"## Expected Outputs\");\n    lines.push(\"\");\n    if (out.artifacts.length) {\n      lines.push(\"### Artifacts\");\n      out.artifacts.forEach((a) => lines.push(`- ${a}`));\n      lines.push(\"\");\n    }\n    if (out.updates.length) {\n      lines.push(\"### Updates\");\n      out.updates.forEach((u) => lines.push(`- ${u}`));\n      lines.push(\"\");\n    }\n    if (out.communications.length) {\n      lines.push(\"### Communications\");\n      out.communications.forEach((c) => lines.push(`- ${c}`));\n      lines.push(\"\");\n    }\n  }\n\n  return lines.join(\"\\n\");\n}\n","/**\n * Strategy Pattern Architecture for the Prompt Decomposition Engine\n *\n * This module defines a pluggable strategy system that allows the PDE\n * to select among multiple decomposition approaches based on prompt\n * complexity, available resources, and Medicine Wheel balance.\n *\n * Architecture overview:\n *   StrategySelector → picks DecompositionStrategy → produces StrategyResult\n *   MultiPassDecomposer → runs N strategies → ConfidenceCalibrator → merged result\n *\n * Integration with existing pipeline:\n *   The strategy layer wraps the existing Decompose → Extract → Map → Build → Enrich\n *   pipeline. Each strategy may use the existing components differently:\n *   - KeywordStrategy: Uses DirectionalDecomposer + heuristic IntentExtractor (existing code)\n *   - SemanticStrategy: Uses keyword direction analysis + LLM-enhanced intent extraction\n *   - HybridStrategy: Runs both, merges with weighted scoring\n *\n * The StrategySelector sits *before* the pipeline, and the ConfidenceCalibrator\n * sits *after* it — they are pre- and post-processing layers.\n */\n\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { Embeddings } from \"@langchain/core/embeddings\";\n\nimport {\n  DirectionalDecomposer,\n  DIRECTION_KEYWORDS,\n  type DirectionalAnalysis,\n  type DirectionalInsight,\n  type Direction,\n} from \"./directional_decomposer.js\";\nimport {\n  IntentExtractor,\n  type IntentExtractionResult,\n  type PrimaryIntent,\n  type SecondaryIntent,\n} from \"./intent_extractor.js\";\nimport { DependencyMapper } from \"./dependency_mapper.js\";\nimport { ActionStackBuilder, type DecompositionResult } from \"./action_stack.js\";\nimport { MedicineWheelBridge, type WheelEnrichedAnalysis } from \"./wheel_bridge.js\";\n\n// =============================================================================\n// Shared Utilities\n// =============================================================================\n\n/**\n * Compute per-direction confidence from the average insight confidence\n * within each direction bucket. Shared by KeywordStrategy and SemanticStrategy.\n */\nfunction computeDirectionConfidenceFromAnalysis(\n  analysis: DirectionalAnalysis\n): Record<Direction, number> {\n  const result: Record<string, number> = {};\n  for (const dir of [\"east\", \"south\", \"west\", \"north\"] as Direction[]) {\n    const insights = analysis.directions[dir];\n    if (insights.length === 0) {\n      result[dir] = 0;\n    } else {\n      const avg =\n        insights.reduce((sum, i) => sum + i.confidence, 0) / insights.length;\n      result[dir] = avg;\n    }\n  }\n  return result as Record<Direction, number>;\n}\n\n// =============================================================================\n// Core Types\n// =============================================================================\n\n/**\n * Identifies which strategy produced a result.\n * Used for provenance tracking and confidence calibration.\n */\nexport type StrategyId = \"keyword\" | \"semantic\" | \"hybrid\" | string;\n\n/**\n * Complexity classification of a prompt, used to guide strategy selection.\n *\n * - simple: Single intent, clear action verb, few clauses (< 50 words)\n * - moderate: 2-3 intents, some nesting, moderate ambiguity (50-150 words)\n * - complex: 4+ intents, nested conditionals, hedging, cross-domain references (150+ words)\n * - ambiguous: Cannot be reliably classified — signals that multi-pass is needed\n */\nexport type PromptComplexity = \"simple\" | \"moderate\" | \"complex\" | \"ambiguous\";\n\n/**\n * Signals detected during prompt analysis that inform strategy selection.\n * These are lightweight heuristics computed *before* full decomposition.\n */\nexport interface ComplexitySignals {\n  /** Total word count */\n  wordCount: number;\n  /** Number of distinct sentences/clauses */\n  clauseCount: number;\n  /** Count of conditional keywords (if, when, unless, whether) */\n  conditionalCount: number;\n  /** Count of hedging language (maybe, probably, somehow, perhaps) */\n  hedgingCount: number;\n  /** Count of action verbs detected */\n  actionVerbCount: number;\n  /** Count of distinct directional keyword matches across all 4 directions */\n  directionalSpread: number;\n  /** Whether the prompt references file paths, code symbols, or technical artifacts */\n  hasTechnicalReferences: boolean;\n  /** Whether the prompt contains nested structures (lists, sub-clauses, multi-step) */\n  hasNestedStructure: boolean;\n  /** Computed complexity classification */\n  complexity: PromptComplexity;\n}\n\n/**\n * Resources available at runtime, used by the StrategySelector to\n * determine which strategies are feasible.\n */\nexport interface AvailableResources {\n  /** An LLM instance for semantic classification and structured extraction */\n  llm?: BaseLanguageModel;\n  /** An embeddings model for similarity-based direction classification */\n  embeddings?: Embeddings;\n  /** Maximum latency budget in milliseconds (strategies that exceed this are excluded) */\n  maxLatencyMs?: number;\n  /** Whether to prefer accuracy over speed (default: false = prefer speed) */\n  preferAccuracy?: boolean;\n}\n\n/**\n * User-specified preferences that override automatic strategy selection.\n */\nexport interface StrategyPreferences {\n  /** Force a specific strategy (bypasses auto-selection) */\n  forceStrategy?: StrategyId;\n  /** Minimum confidence threshold — results below this trigger multi-pass */\n  minConfidence?: number;\n  /** Enable multi-pass even for simple prompts (default: false) */\n  alwaysMultiPass?: boolean;\n  /** Maximum number of passes in multi-pass mode (default: 3) */\n  maxPasses?: number;\n  /** Strategies to exclude from selection */\n  excludeStrategies?: StrategyId[];\n}\n\n// =============================================================================\n// Strategy Result\n// =============================================================================\n\n/**\n * The output of a single strategy execution. Contains the decomposition\n * plus metadata about the strategy's confidence and provenance.\n *\n * This is the universal return type for all strategies, enabling\n * comparison, merging, and calibration across different approaches.\n */\nexport interface StrategyResult {\n  /** Which strategy produced this result */\n  strategyId: StrategyId;\n  /** The directional analysis (segment → direction classification) */\n  directionalAnalysis: DirectionalAnalysis;\n  /** The extracted intents (primary + secondary) */\n  intents: IntentExtractionResult;\n  /** The final decomposition (action stack, outputs, ambiguities) */\n  decomposition: DecompositionResult;\n  /** Medicine Wheel enrichment */\n  wheelEnriched: WheelEnrichedAnalysis;\n  /** Overall confidence in this result (0-1), pre-calibration */\n  confidence: number;\n  /** Per-direction confidence scores */\n  directionConfidence: Record<Direction, number>;\n  /** Execution time in milliseconds */\n  executionTimeMs: number;\n  /** Any warnings or diagnostic notes from the strategy */\n  diagnostics: string[];\n}\n\n// =============================================================================\n// DecompositionStrategy Interface\n// =============================================================================\n\n/**\n * The core strategy interface. All decomposition approaches implement this.\n *\n * Design rationale:\n * - `id` enables provenance tracking and strategy-specific calibration curves\n * - `canHandle` allows strategies to self-exclude based on resource availability\n * - `estimateLatency` enables the selector to respect latency budgets\n * - `decompose` is the main entry point, returning a uniform StrategyResult\n *\n * Strategies are stateless — all configuration is passed via constructor,\n * and each `decompose` call is independent.\n */\nexport interface DecompositionStrategy {\n  /** Unique identifier for this strategy */\n  readonly id: StrategyId;\n\n  /** Human-readable name for diagnostics and logging */\n  readonly name: string;\n\n  /**\n   * Check if this strategy can handle decomposition with the given resources.\n   * Returns false if required resources (e.g., LLM) are unavailable.\n   */\n  canHandle(resources: AvailableResources): boolean;\n\n  /**\n   * Estimate the latency of running this strategy, in milliseconds.\n   * Used by the StrategySelector to respect latency budgets.\n   * Returns -1 if latency cannot be estimated.\n   */\n  estimateLatency(signals: ComplexitySignals): number;\n\n  /**\n   * Execute the decomposition strategy on the given prompt.\n   *\n   * @param prompt - The raw user prompt to decompose\n   * @param resources - Available runtime resources (LLM, embeddings, etc.)\n   * @returns A StrategyResult containing the full decomposition with confidence scores\n   */\n  decompose(prompt: string, resources: AvailableResources): Promise<StrategyResult>;\n}\n\n// =============================================================================\n// KeywordStrategy\n// =============================================================================\n\n/**\n * Wraps the existing keyword-based decomposition pipeline for backward\n * compatibility. This is the default strategy when no LLM is available.\n *\n * Characteristics:\n * - Zero external dependencies (no LLM, no embeddings)\n * - Deterministic output for the same input\n * - Fast (~1-5ms for typical prompts)\n * - Lower accuracy on nuanced or ambiguous prompts\n *\n * Uses: DirectionalDecomposer (keyword scoring) + IntentExtractor (heuristic mode)\n *       + DependencyMapper + ActionStackBuilder + MedicineWheelBridge\n *\n * This strategy is always available and serves as the baseline for\n * confidence calibration.\n */\nexport class KeywordStrategy implements DecompositionStrategy {\n  readonly id: StrategyId = \"keyword\";\n  readonly name = \"Keyword-Based Decomposition\";\n\n  canHandle(_resources: AvailableResources): boolean {\n    // Always available — no external dependencies\n    return true;\n  }\n\n  estimateLatency(signals: ComplexitySignals): number {\n    // Keyword matching is O(words × keywords), typically < 5ms\n    return Math.max(1, signals.wordCount * 0.05);\n  }\n\n  /**\n   * Run the existing keyword-based pipeline.\n   *\n   * Implementation notes:\n   * - Instantiates DirectionalDecomposer, IntentExtractor (no LLM),\n   *   DependencyMapper, ActionStackBuilder, MedicineWheelBridge\n   * - Runs the standard Decompose → Extract → Map → Build → Enrich flow\n   * - Computes confidence from keyword match density and direction balance\n   */\n  async decompose(prompt: string, _resources: AvailableResources): Promise<StrategyResult> {\n    const startTime = Date.now();\n\n    const decomposer = new DirectionalDecomposer();\n    const extractor = new IntentExtractor(); // No LLM — pure heuristics\n    const mapper = new DependencyMapper();\n    const builder = new ActionStackBuilder();\n    const bridge = new MedicineWheelBridge();\n\n    const directionalAnalysis = decomposer.decompose(prompt);\n    const intents = await extractor.extract(prompt);\n    const graph = mapper.buildGraph(intents.secondary);\n    const order = mapper.computeExecutionOrder(graph);\n    const decomposition = builder.build(directionalAnalysis, intents, order);\n    const wheelEnriched = bridge.enrich(directionalAnalysis);\n\n    // Compute per-direction confidence from keyword density\n    const directionConfidence = computeDirectionConfidenceFromAnalysis(directionalAnalysis);\n    const confidence = this.computeOverallConfidence(directionalAnalysis, intents);\n\n    const diagnostics: string[] = [];\n    if (directionalAnalysis.balance < 0.3) {\n      diagnostics.push(\"Low directional balance — keyword coverage is sparse.\");\n    }\n    if (intents.primary.confidence < 0.5) {\n      diagnostics.push(\"Primary intent has low confidence — consider semantic strategy.\");\n    }\n\n    return {\n      strategyId: this.id,\n      directionalAnalysis,\n      intents,\n      decomposition,\n      wheelEnriched,\n      confidence,\n      directionConfidence,\n      executionTimeMs: Date.now() - startTime,\n      diagnostics,\n    };\n  }\n\n  /**\n   * Overall confidence combines direction balance, primary intent confidence,\n   * and proportion of non-implicit insights.\n   */\n  private computeOverallConfidence(\n    analysis: DirectionalAnalysis,\n    intents: IntentExtractionResult\n  ): number {\n    const balanceWeight = 0.3;\n    const intentWeight = 0.4;\n    const explicitWeight = 0.3;\n\n    const allInsights = Object.values(analysis.directions).flat();\n    const explicitRatio =\n      allInsights.length > 0\n        ? allInsights.filter((i) => !i.implicit).length / allInsights.length\n        : 0.5;\n\n    return (\n      analysis.balance * balanceWeight +\n      intents.primary.confidence * intentWeight +\n      explicitRatio * explicitWeight\n    );\n  }\n}\n\n// =============================================================================\n// SemanticStrategy\n// =============================================================================\n\n/**\n * Provides LLM-enhanced intent extraction with keyword-based directional analysis.\n *\n * Characteristics:\n * - Requires an LLM (will not be selected without one)\n * - Non-deterministic — LLM responses vary\n * - Higher latency (500ms-5s depending on model)\n * - Significantly better on ambiguous, multi-intent, and nuanced prompts for\n *   intent extraction; can understand context, metaphor, and implied requirements\n *\n * Architecture:\n * 1. Uses IntentExtractor with the LLM enabled for richer intent extraction\n * 2. Falls back to keyword-only extraction if LLM call fails\n * 3. Directional analysis still uses the keyword-based DirectionalDecomposer —\n *    true LLM directional classification is a future enhancement\n * 4. Runs the rest of the pipeline (DependencyMapper, ActionStackBuilder,\n *    MedicineWheelBridge) as normal\n *\n * The LLM call is grounded in Medicine Wheel epistemology, asking the model\n * to consider all four directions explicitly when extracting intents.\n */\nexport class SemanticStrategy implements DecompositionStrategy {\n  readonly id: StrategyId = \"semantic\";\n  readonly name = \"LLM-Enhanced Intent Extraction with Keyword Directional Analysis\";\n\n  canHandle(resources: AvailableResources): boolean {\n    // Requires an LLM\n    return resources.llm !== undefined;\n  }\n\n  estimateLatency(signals: ComplexitySignals): number {\n    // LLM calls are ~500ms minimum, scaling with prompt length\n    const baseLatency = 500;\n    const perWordLatency = 2;\n    return baseLatency + signals.wordCount * perWordLatency;\n  }\n\n  /**\n   * Run LLM-enhanced intent extraction with keyword-based directional analysis.\n   *\n   * Implementation approach:\n   * 1. Use IntentExtractor with the LLM enabled for richer intent extraction —\n   *    the LLM identifies implicit intents, understands context and metaphor,\n   *    and provides better-calibrated confidence scores\n   * 2. Directional analysis uses the keyword-based DirectionalDecomposer;\n   *    true LLM directional classification is a future enhancement\n   * 3. Run the rest of the pipeline (DependencyMapper, ActionStackBuilder,\n   *    MedicineWheelBridge) as normal — those are direction-agnostic\n   *\n   * If the LLM call fails, falls back to heuristic intent extraction\n   * and marks the fallback in diagnostics.\n   */\n  async decompose(prompt: string, resources: AvailableResources): Promise<StrategyResult> {\n    const startTime = Date.now();\n\n    if (!resources.llm) {\n      throw new Error(\"SemanticStrategy requires an LLM but none was provided.\");\n    }\n\n    const diagnostics: string[] = [];\n\n    // Use LLM-enhanced intent extraction\n    const extractor = new IntentExtractor({ llm: resources.llm });\n    let intents: IntentExtractionResult;\n    let directionalAnalysis: DirectionalAnalysis;\n\n    try {\n      intents = await extractor.extract(prompt);\n\n      // For directional analysis, we still use DirectionalDecomposer as the\n      // structural backbone, but could enhance with LLM classification in future.\n      // The IntentExtractor with LLM already provides richer intent data.\n      const decomposer = new DirectionalDecomposer();\n      directionalAnalysis = decomposer.decompose(prompt);\n\n      diagnostics.push(\"LLM-enhanced intent extraction succeeded.\");\n    } catch (error) {\n      // Fallback to keyword-only\n      diagnostics.push(\n        `LLM extraction failed (${error instanceof Error ? error.message : String(error)}), falling back to keyword strategy.`\n      );\n      const decomposer = new DirectionalDecomposer();\n      directionalAnalysis = decomposer.decompose(prompt);\n      const fallbackExtractor = new IntentExtractor();\n      intents = await fallbackExtractor.extract(prompt);\n    }\n\n    const mapper = new DependencyMapper();\n    const builder = new ActionStackBuilder();\n    const bridge = new MedicineWheelBridge();\n\n    const graph = mapper.buildGraph(intents.secondary);\n    const order = mapper.computeExecutionOrder(graph);\n    const decomposition = builder.build(directionalAnalysis, intents, order);\n    const wheelEnriched = bridge.enrich(directionalAnalysis);\n\n    const directionConfidence = computeDirectionConfidenceFromAnalysis(directionalAnalysis);\n    // Semantic strategy gets a confidence boost for using LLM\n    const baseConfidence = this.computeBaseConfidence(directionalAnalysis, intents);\n    const confidence = Math.min(1, baseConfidence + 0.1);\n\n    return {\n      strategyId: this.id,\n      directionalAnalysis,\n      intents,\n      decomposition,\n      wheelEnriched,\n      confidence,\n      directionConfidence,\n      executionTimeMs: Date.now() - startTime,\n      diagnostics,\n    };\n  }\n\n  private computeBaseConfidence(\n    analysis: DirectionalAnalysis,\n    intents: IntentExtractionResult\n  ): number {\n    return (\n      analysis.balance * 0.25 +\n      intents.primary.confidence * 0.5 +\n      (intents.secondary.length > 0 ? 0.25 : 0.1)\n    );\n  }\n}\n\n// =============================================================================\n// HybridStrategy\n// =============================================================================\n\n/**\n * Combines keyword and semantic approaches with weighted scoring and\n * confidence calibration. Runs both strategies and merges the results.\n *\n * Characteristics:\n * - Requires an LLM (falls back to keyword-only if unavailable)\n * - Highest accuracy due to ensemble approach\n * - Highest latency (~2x semantic strategy)\n * - Best for complex or high-stakes prompts where accuracy matters more than speed\n *\n * Note: Both KeywordStrategy and SemanticStrategy currently use the same\n * keyword-based DirectionalDecomposer for directional analysis, so the ensemble\n * value is primarily in intent extraction (LLM-enhanced vs. heuristic). True\n * divergence in directional analysis will require a future LLM-based directional\n * classifier in SemanticStrategy.\n *\n * Merging algorithm:\n * 1. Run KeywordStrategy and SemanticStrategy in parallel\n * 2. For directional analysis: union insights from both; shared insights get\n *    confidence = weighted average. If they disagree, flag the segment for review.\n * 3. For intents: union the intent sets, deduplicating by target similarity.\n *    Shared intents get boosted confidence; strategy-unique intents are kept\n *    but marked with lower confidence.\n * 4. For the final action stack: re-run DependencyMapper and ActionStackBuilder\n *    on the merged intent set.\n *\n * Weighting:\n * - Default weights: keyword=0.35, semantic=0.65\n * - Weights shift toward keyword for simple prompts (semantic adds little value)\n * - Weights shift toward semantic for complex/ambiguous prompts\n */\nexport class HybridStrategy implements DecompositionStrategy {\n  readonly id: StrategyId = \"hybrid\";\n  readonly name = \"Hybrid Keyword+Semantic Decomposition\";\n\n  private readonly keywordWeight: number;\n  private readonly semanticWeight: number;\n  private readonly keywordStrategy: KeywordStrategy;\n  private readonly semanticStrategy: SemanticStrategy;\n\n  constructor(options?: { keywordWeight?: number; semanticWeight?: number }) {\n    this.keywordWeight = options?.keywordWeight ?? 0.35;\n    this.semanticWeight = options?.semanticWeight ?? 0.65;\n    this.keywordStrategy = new KeywordStrategy();\n    this.semanticStrategy = new SemanticStrategy();\n  }\n\n  canHandle(resources: AvailableResources): boolean {\n    // Requires LLM for the semantic component\n    return resources.llm !== undefined;\n  }\n\n  estimateLatency(signals: ComplexitySignals): number {\n    // Both strategies run in parallel, so latency ≈ max(keyword, semantic)\n    const keywordLatency = Math.max(1, signals.wordCount * 0.05);\n    const semanticLatency = 500 + signals.wordCount * 2;\n    // Add ~50ms for merging overhead\n    return Math.max(keywordLatency, semanticLatency) + 50;\n  }\n\n  /**\n   * Run both strategies and merge results.\n   *\n   * Implementation approach:\n   * 1. Run KeywordStrategy and SemanticStrategy concurrently via Promise.all\n   * 2. Merge directional analyses:\n   *    - For each direction, take the union of insights from both strategies\n   *    - Insights present in both get confidence = weighted average\n   *    - Insights in only one strategy get confidence penalty (×0.8)\n   * 3. Merge intents:\n   *    - Deduplicate by action+target similarity (Jaccard on target words > 0.5)\n   *    - Shared intents: confidence = weighted average of both\n   *    - Unique intents: kept with source-strategy confidence × 0.9\n   * 4. Rebuild the dependency graph and action stack from merged intents\n   * 5. Confidence = weighted combination of both strategy confidences,\n   *    with a bonus for agreement\n   */\n  async decompose(prompt: string, resources: AvailableResources): Promise<StrategyResult> {\n    const startTime = Date.now();\n\n    // Run both strategies concurrently\n    const [keywordResult, semanticResult] = await Promise.all([\n      this.keywordStrategy.decompose(prompt, resources),\n      this.semanticStrategy.decompose(prompt, resources),\n    ]);\n\n    // Merge directional analyses\n    const mergedDirectionalAnalysis = this.mergeDirectionalAnalyses(\n      keywordResult.directionalAnalysis,\n      semanticResult.directionalAnalysis\n    );\n\n    // Merge intents — use the semantic result as the base (richer extraction),\n    // supplemented by any keyword-only intents\n    const mergedIntents = this.mergeIntents(\n      keywordResult.intents,\n      semanticResult.intents\n    );\n\n    // Rebuild pipeline from merged data\n    const mapper = new DependencyMapper();\n    const builder = new ActionStackBuilder();\n    const bridge = new MedicineWheelBridge();\n\n    const graph = mapper.buildGraph(mergedIntents.secondary);\n    const order = mapper.computeExecutionOrder(graph);\n    const decomposition = builder.build(mergedDirectionalAnalysis, mergedIntents, order);\n    const wheelEnriched = bridge.enrich(mergedDirectionalAnalysis);\n\n    // Compute merged confidence\n    const agreementBonus = this.computeAgreementBonus(keywordResult, semanticResult);\n    const confidence = Math.min(\n      1,\n      keywordResult.confidence * this.keywordWeight +\n        semanticResult.confidence * this.semanticWeight +\n        agreementBonus\n    );\n\n    const directionConfidence = this.mergeDirectionConfidence(\n      keywordResult.directionConfidence,\n      semanticResult.directionConfidence\n    );\n\n    const diagnostics = [\n      `Keyword confidence: ${keywordResult.confidence.toFixed(3)}`,\n      `Semantic confidence: ${semanticResult.confidence.toFixed(3)}`,\n      `Agreement bonus: ${agreementBonus.toFixed(3)}`,\n      `Keyword intents: ${keywordResult.intents.secondary.length}`,\n      `Semantic intents: ${semanticResult.intents.secondary.length}`,\n      `Merged intents: ${mergedIntents.secondary.length}`,\n      ...keywordResult.diagnostics.map((d) => `[keyword] ${d}`),\n      ...semanticResult.diagnostics.map((d) => `[semantic] ${d}`),\n    ];\n\n    return {\n      strategyId: this.id,\n      directionalAnalysis: mergedDirectionalAnalysis,\n      intents: mergedIntents,\n      decomposition,\n      wheelEnriched,\n      confidence,\n      directionConfidence,\n      executionTimeMs: Date.now() - startTime,\n      diagnostics,\n    };\n  }\n\n  /**\n   * Merge two directional analyses by taking the union of insights per direction.\n   * Deduplicates by text similarity and averages confidence for shared insights.\n   */\n  private mergeDirectionalAnalyses(\n    keyword: DirectionalAnalysis,\n    semantic: DirectionalAnalysis\n  ): DirectionalAnalysis {\n    // Use the semantic analysis as the base structure, as it carries the\n    // richer metadata. The merge enhances it with keyword-only insights.\n    const merged: DirectionalAnalysis = {\n      ...semantic,\n      directions: { east: [], south: [], west: [], north: [] } as Record<\n        Direction,\n        DirectionalInsight[]\n      >,\n    };\n\n    for (const dir of [\"east\", \"south\", \"west\", \"north\"] as Direction[]) {\n      const keyInsights = keyword.directions[dir] || [];\n      const semInsights = semantic.directions[dir] || [];\n      const seen = new Set<string>();\n\n      // Add semantic insights first (higher priority)\n      for (const insight of semInsights) {\n        const normalized = insight.text.toLowerCase().trim();\n        seen.add(normalized);\n\n        // Check if keyword strategy also found this insight\n        const keyMatch = keyInsights.find(\n          (k) => k.text.toLowerCase().trim() === normalized\n        );\n        if (keyMatch) {\n          // Both agree — boost confidence via weighted average\n          merged.directions[dir].push({\n            text: insight.text,\n            confidence: Math.min(\n              1,\n              insight.confidence * this.semanticWeight +\n                keyMatch.confidence * this.keywordWeight\n            ),\n            implicit: insight.implicit && keyMatch.implicit,\n          });\n        } else {\n          merged.directions[dir].push(insight);\n        }\n      }\n\n      // Add keyword-only insights (not found by semantic)\n      for (const insight of keyInsights) {\n        const normalized = insight.text.toLowerCase().trim();\n        if (!seen.has(normalized)) {\n          merged.directions[dir].push({\n            ...insight,\n            confidence: insight.confidence * 0.8, // Slight penalty for single-source\n          });\n        }\n      }\n    }\n\n    // Recompute balance from merged directions\n    const counts = ([\"east\", \"south\", \"west\", \"north\"] as Direction[]).map(\n      (d) => merged.directions[d].length\n    );\n    const total = counts.reduce((a, b) => a + b, 0) || 1;\n    const proportions = counts.map((c) => c / total);\n    const deviation =\n      proportions.reduce((sum, p) => sum + Math.abs(p - 0.25), 0) / 4;\n    merged.balance = Math.max(0, Math.min(1, 1 - deviation * 4));\n\n    return merged;\n  }\n\n  /**\n   * Merge intent extraction results from two strategies.\n   * Uses the higher-confidence primary intent and unions secondary intents.\n   */\n  private mergeIntents(\n    keyword: IntentExtractionResult,\n    semantic: IntentExtractionResult\n  ): IntentExtractionResult {\n    // Pick the primary intent with higher confidence\n    const primary: PrimaryIntent =\n      semantic.primary.confidence >= keyword.primary.confidence\n        ? semantic.primary\n        : keyword.primary;\n\n    // Union secondary intents, deduplicating by target similarity\n    const merged: SecondaryIntent[] = [...semantic.secondary];\n    for (const keyIntent of keyword.secondary) {\n      const isDuplicate = merged.some(\n        (m) =>\n          m.action === keyIntent.action &&\n          this.targetSimilarity(m.target, keyIntent.target) > 0.5\n      );\n      if (!isDuplicate) {\n        merged.push({\n          ...keyIntent,\n          confidence: keyIntent.confidence * 0.9, // Slight penalty for single-source\n        });\n      }\n    }\n\n    return {\n      ...semantic,\n      primary,\n      secondary: merged,\n      context: {\n        filesNeeded: Array.from(new Set([\n            ...keyword.context.filesNeeded,\n            ...semantic.context.filesNeeded,\n        ])),\n        toolsRequired: Array.from(new Set([\n            ...keyword.context.toolsRequired,\n            ...semantic.context.toolsRequired,\n        ])),\n        assumptions: Array.from(new Set([\n            ...keyword.context.assumptions,\n            ...semantic.context.assumptions,\n        ])),\n      },\n    };\n  }\n\n  /**\n   * Jaccard similarity between two target strings (word-level).\n   */\n  private targetSimilarity(a: string, b: string): number {\n    const wordsA = new Set(a.toLowerCase().split(/\\s+/).filter((w) => w.length > 2));\n    const wordsB = new Set(b.toLowerCase().split(/\\s+/).filter((w) => w.length > 2));\n    if (wordsA.size === 0 && wordsB.size === 0) return 1;\n    let intersection = 0;\n    for (const w of Array.from(wordsA)) {\n      if (wordsB.has(w)) intersection++;\n    }\n    const union = new Set([...Array.from(wordsA), ...Array.from(wordsB)]).size;\n    return union === 0 ? 0 : intersection / union;\n  }\n\n  /**\n   * Compute a bonus for strategies agreeing on lead direction and primary intent.\n   * Agreement suggests higher reliability.\n   */\n  private computeAgreementBonus(\n    keyword: StrategyResult,\n    semantic: StrategyResult\n  ): number {\n    let bonus = 0;\n\n    // Both strategies use the same keyword-based DirectionalDecomposer, so\n    // directional agreement is expected rather than a genuine signal. Use a\n    // reduced bonus (0.02) to avoid over-crediting this.\n    if (\n      keyword.directionalAnalysis.leadDirection ===\n      semantic.directionalAnalysis.leadDirection\n    ) {\n      bonus += 0.02;\n    }\n\n    // Same primary action\n    if (keyword.intents.primary.action === semantic.intents.primary.action) {\n      bonus += 0.05;\n    }\n\n    // Similar primary target\n    if (\n      this.targetSimilarity(\n        keyword.intents.primary.target,\n        semantic.intents.primary.target\n      ) > 0.5\n    ) {\n      bonus += 0.05;\n    }\n\n    return bonus;\n  }\n\n  /**\n   * Merge per-direction confidence from both strategies using weights.\n   */\n  private mergeDirectionConfidence(\n    keyword: Record<Direction, number>,\n    semantic: Record<Direction, number>\n  ): Record<Direction, number> {\n    const result: Record<string, number> = {};\n    for (const dir of [\"east\", \"south\", \"west\", \"north\"] as Direction[]) {\n      result[dir] =\n        (keyword[dir] || 0) * this.keywordWeight +\n        (semantic[dir] || 0) * this.semanticWeight;\n    }\n    return result as Record<Direction, number>;\n  }\n}\n\n// =============================================================================\n// ComplexityAnalyzer\n// =============================================================================\n\n/**\n * Analyzes a prompt's complexity characteristics without performing\n * full decomposition. This is a fast pre-processing step used by\n * StrategySelector to choose the right strategy.\n *\n * The analysis produces ComplexitySignals which capture:\n * - Structural complexity (length, clauses, nesting)\n * - Linguistic complexity (hedging, conditionals, ambiguity)\n * - Technical complexity (file references, code symbols)\n * - Directional spread (how many directions are touched by keywords)\n */\nexport class ComplexityAnalyzer {\n  /**\n   * Analyze a prompt and return complexity signals.\n   */\n  analyze(prompt: string): ComplexitySignals {\n    const lower = prompt.toLowerCase();\n    const words = prompt.split(/\\s+/).filter((w) => w.length > 0);\n    const sentences = prompt\n      .split(/(?<=[.!?])\\s+|\\n+/)\n      .filter((s) => s.trim().length > 3);\n\n    const wordCount = words.length;\n    const clauseCount = sentences.length;\n\n    const conditionalCount = (\n      lower.match(/\\b(if|when|unless|whether|provided that|assuming)\\b/g) || []\n    ).length;\n\n    const hedgingCount = (\n      lower.match(/\\b(maybe|perhaps|probably|somehow|might|could|possibly|i assume|i expect)\\b/g) || []\n    ).length;\n\n    // Count action verbs (from IntentExtractor's ACTION_VERBS)\n    const actionVerbs = [\n      \"create\", \"build\", \"make\", \"generate\", \"write\", \"develop\", \"design\",\n      \"modify\", \"update\", \"change\", \"edit\", \"refactor\",\n      \"investigate\", \"research\", \"explore\", \"analyze\", \"examine\",\n      \"add\", \"install\", \"include\", \"integrate\",\n      \"remove\", \"delete\", \"clean\",\n      \"test\", \"verify\", \"validate\",\n      \"deploy\", \"ship\", \"publish\",\n      \"manage\", \"organize\",\n      \"use\", \"run\", \"execute\",\n      \"draft\", \"plan\", \"document\",\n    ];\n    const actionVerbCount = actionVerbs.filter((v) => lower.includes(v)).length;\n\n    // Check directional spread using canonical DIRECTION_KEYWORDS\n    let directionalSpread = 0;\n    for (const keywords of Object.values(DIRECTION_KEYWORDS)) {\n      if (keywords.some((k) => lower.includes(k))) {\n        directionalSpread++;\n      }\n    }\n\n    const hasTechnicalReferences =\n      /(?:\\/[\\w.-]+){2,}/.test(prompt) || // file paths\n      /@[\\w./-]+/.test(prompt) || // package references\n      /`[^`]+`/.test(prompt) || // inline code\n      /\\b(?:function|class|interface|import|export|const|let|var)\\b/.test(lower);\n\n    const hasNestedStructure =\n      /^\\s*[-*]\\s/m.test(prompt) || // bullet lists\n      /\\d+\\.\\s/.test(prompt) || // numbered lists\n      conditionalCount >= 2 || // multiple conditionals\n      /\\b(?:first|then|next|after that|finally|also|additionally)\\b/.test(lower);\n\n    // Classify complexity\n    let complexity: PromptComplexity;\n    if (hedgingCount >= 3 || (conditionalCount >= 3 && actionVerbCount >= 4)) {\n      complexity = \"ambiguous\";\n    } else if (\n      wordCount > 150 ||\n      actionVerbCount >= 5 ||\n      (directionalSpread >= 3 && clauseCount >= 5)\n    ) {\n      complexity = \"complex\";\n    } else if (\n      wordCount > 50 ||\n      actionVerbCount >= 3 ||\n      directionalSpread >= 2\n    ) {\n      complexity = \"moderate\";\n    } else {\n      complexity = \"simple\";\n    }\n\n    return {\n      wordCount,\n      clauseCount,\n      conditionalCount,\n      hedgingCount,\n      actionVerbCount,\n      directionalSpread,\n      hasTechnicalReferences,\n      hasNestedStructure,\n      complexity,\n    };\n  }\n}\n\n// =============================================================================\n// StrategySelector\n// =============================================================================\n\n/**\n * Automatically selects the best decomposition strategy based on prompt\n * complexity, available resources, and user preferences.\n *\n * Selection algorithm (pseudocode):\n *\n * ```\n * function select(prompt, resources, preferences):\n *   // 1. Honor forced strategy if specified\n *   if preferences.forceStrategy:\n *     return registry[preferences.forceStrategy]\n *\n *   // 2. Analyze prompt complexity\n *   signals = ComplexityAnalyzer.analyze(prompt)\n *\n *   // 3. Filter to feasible strategies\n *   feasible = registry.filter(s =>\n *     s.canHandle(resources) &&\n *     !preferences.excludeStrategies.includes(s.id) &&\n *     (resources.maxLatencyMs == null || s.estimateLatency(signals) <= resources.maxLatencyMs)\n *   )\n *\n *   // 4. Score each feasible strategy\n *   for strategy in feasible:\n *     score = 0\n *     if signals.complexity == \"simple\":\n *       score += (strategy.id == \"keyword\") ? 1.0 : 0.5\n *     elif signals.complexity == \"moderate\":\n *       score += (strategy.id == \"semantic\") ? 0.8 : (strategy.id == \"keyword\") ? 0.6 : 0.9\n *     elif signals.complexity in [\"complex\", \"ambiguous\"]:\n *       score += (strategy.id == \"hybrid\") ? 1.0 : (strategy.id == \"semantic\") ? 0.7 : 0.3\n *\n *     if resources.preferAccuracy:\n *       score += (strategy.id == \"hybrid\") ? 0.3 : (strategy.id == \"semantic\") ? 0.2 : 0\n *\n *   // 5. Return highest-scoring strategy\n *   return feasible.maxBy(score)\n * ```\n *\n * Medicine Wheel influence on selection:\n * - If the prompt is heavily WEST-oriented (validation/ceremony), prefer\n *   strategies with higher accuracy (semantic/hybrid) as these are\n *   high-stakes decisions that benefit from deeper analysis\n * - If the prompt is heavily NORTH-oriented (action/execution), prefer\n *   faster strategies (keyword) as speed matters for implementation\n */\nexport class StrategySelector {\n  private readonly registry: Map<StrategyId, DecompositionStrategy>;\n  private readonly complexityAnalyzer: ComplexityAnalyzer;\n\n  constructor(strategies?: DecompositionStrategy[]) {\n    this.registry = new Map();\n    this.complexityAnalyzer = new ComplexityAnalyzer();\n\n    // Register default strategies\n    const defaults: DecompositionStrategy[] = strategies ?? [\n      new KeywordStrategy(),\n      new SemanticStrategy(),\n      new HybridStrategy(),\n    ];\n\n    for (const strategy of defaults) {\n      this.registry.set(strategy.id, strategy);\n    }\n  }\n\n  /**\n   * Register a custom strategy.\n   */\n  register(strategy: DecompositionStrategy): void {\n    this.registry.set(strategy.id, strategy);\n  }\n\n  /**\n   * Select the best strategy for the given prompt and context.\n   */\n  select(\n    prompt: string,\n    resources: AvailableResources,\n    preferences?: StrategyPreferences\n  ): { strategy: DecompositionStrategy; signals: ComplexitySignals; reason: string } {\n    // 1. Honor forced strategy\n    if (preferences?.forceStrategy) {\n      const forced = this.registry.get(preferences.forceStrategy);\n      if (forced) {\n        return {\n          strategy: forced,\n          signals: this.complexityAnalyzer.analyze(prompt),\n          reason: `Forced strategy: ${preferences.forceStrategy}`,\n        };\n      }\n      // Forced strategy not found — warn and fall through to auto-selection\n      const availableIds = Array.from(this.registry.keys()).join(\", \");\n      const warning = `Forced strategy \"${preferences.forceStrategy}\" not found in registry (available: ${availableIds}); falling back to auto-selection.`;\n      // Continue to auto-selection below; the warning is included in the reason\n      const signals = this.complexityAnalyzer.analyze(prompt);\n      const autoResult = this.autoSelect(prompt, signals, resources, preferences);\n      return {\n        ...autoResult,\n        reason: `${warning} ${autoResult.reason}`,\n      };\n    }\n\n    // 2. Analyze prompt complexity\n    const signals = this.complexityAnalyzer.analyze(prompt);\n\n    return this.autoSelect(prompt, signals, resources, preferences);\n  }\n\n  /**\n   * Auto-select the best strategy based on complexity signals, resources, and preferences.\n   */\n  private autoSelect(\n    _prompt: string,\n    signals: ComplexitySignals,\n    resources: AvailableResources,\n    preferences?: StrategyPreferences\n  ): { strategy: DecompositionStrategy; signals: ComplexitySignals; reason: string } {\n    // Filter to feasible strategies\n    const excluded = new Set(preferences?.excludeStrategies ?? []);\n    const feasible: Array<{ strategy: DecompositionStrategy; score: number }> = [];\n\n    for (const [id, strategy] of Array.from(this.registry)) {\n      if (excluded.has(id)) continue;\n      if (!strategy.canHandle(resources)) continue;\n\n      const estimatedLatency = strategy.estimateLatency(signals);\n      if (\n        resources.maxLatencyMs !== undefined &&\n        estimatedLatency > resources.maxLatencyMs\n      ) {\n        continue;\n      }\n\n      // 4. Score the strategy\n      let score = 0;\n\n      // Complexity-based scoring\n      switch (signals.complexity) {\n        case \"simple\":\n          score += id === \"keyword\" ? 1.0 : id === \"semantic\" ? 0.5 : 0.4;\n          break;\n        case \"moderate\":\n          score += id === \"hybrid\" ? 0.9 : id === \"semantic\" ? 0.8 : 0.6;\n          break;\n        case \"complex\":\n          score += id === \"hybrid\" ? 1.0 : id === \"semantic\" ? 0.7 : 0.3;\n          break;\n        case \"ambiguous\":\n          score += id === \"hybrid\" ? 1.0 : id === \"semantic\" ? 0.8 : 0.2;\n          break;\n      }\n\n      // Accuracy preference boost\n      if (resources.preferAccuracy) {\n        if (id === \"hybrid\") score += 0.3;\n        else if (id === \"semantic\") score += 0.2;\n      }\n\n      // Speed preference (inverse of latency)\n      if (!resources.preferAccuracy && estimatedLatency > 0) {\n        score += Math.max(0, 0.2 - estimatedLatency / 10000);\n      }\n\n      feasible.push({ strategy, score });\n    }\n\n    // 5. Return highest-scoring strategy (or keyword as fallback)\n    feasible.sort((a, b) => b.score - a.score);\n\n    if (feasible.length === 0) {\n      const keyword = this.registry.get(\"keyword\") ?? new KeywordStrategy();\n      return {\n        strategy: keyword,\n        signals,\n        reason: \"No feasible strategies found; defaulting to keyword.\",\n      };\n    }\n\n    const selected = feasible[0];\n    return {\n      strategy: selected.strategy,\n      signals,\n      reason: `Selected ${selected.strategy.id} (score: ${selected.score.toFixed(2)}) for ${signals.complexity} prompt (${signals.wordCount} words, ${signals.actionVerbCount} verbs, ${signals.directionalSpread}/4 directions).`,\n    };\n  }\n\n  /**\n   * Get all registered strategies.\n   */\n  getStrategies(): DecompositionStrategy[] {\n    return Array.from(this.registry.values());\n  }\n}\n\n// =============================================================================\n// ConfidenceCalibrator\n// =============================================================================\n\n/**\n * Post-processing step that calibrates confidence scores across strategies.\n *\n * Different strategies have different confidence distributions:\n * - KeywordStrategy tends to report moderate confidence (0.5-0.8) consistently\n * - SemanticStrategy may report high confidence (0.7-0.95) but with more variance\n * - HybridStrategy should be the most calibrated by design\n *\n * The calibrator normalizes scores so they are comparable across strategies\n * and applies corrections based on prompt complexity.\n *\n * Calibration approach:\n * 1. Strategy-specific bias correction (empirical offsets per strategy)\n * 2. Complexity-based adjustment (complex prompts get a confidence penalty)\n * 3. Balance bonus/penalty (well-balanced decompositions get a boost)\n * 4. Agreement bonus (if multi-pass, strategies that agree get boosted)\n */\nexport class ConfidenceCalibrator {\n  /**\n   * Per-strategy bias corrections.\n   * Positive values increase confidence; negative values decrease.\n   * These should be tuned empirically over time.\n   */\n  private readonly strategyBias: Record<string, number> = {\n    keyword: 0.0, // Baseline — no correction\n    semantic: -0.05, // LLMs tend to be slightly overconfident\n    hybrid: 0.02, // Ensemble is slightly underconfident\n  };\n\n  /**\n   * Calibrate a single strategy result.\n   */\n  calibrate(result: StrategyResult, signals: ComplexitySignals): StrategyResult {\n    const bias = this.strategyBias[result.strategyId] ?? 0;\n\n    // Complexity penalty: complex prompts are inherently harder to decompose\n    let complexityAdjustment = 0;\n    switch (signals.complexity) {\n      case \"simple\":\n        complexityAdjustment = 0.05;\n        break;\n      case \"moderate\":\n        complexityAdjustment = 0;\n        break;\n      case \"complex\":\n        complexityAdjustment = -0.05;\n        break;\n      case \"ambiguous\":\n        complexityAdjustment = -0.1;\n        break;\n    }\n\n    // Balance bonus: well-balanced decompositions are more trustworthy\n    const balanceAdjustment = (result.directionalAnalysis.balance - 0.5) * 0.1;\n\n    // Apply calibration\n    const calibratedConfidence = Math.max(\n      0,\n      Math.min(\n        1,\n        result.confidence + bias + complexityAdjustment + balanceAdjustment\n      )\n    );\n\n    // Calibrate per-direction confidence\n    const calibratedDirConfidence: Record<string, number> = {};\n    for (const dir of [\"east\", \"south\", \"west\", \"north\"] as Direction[]) {\n      calibratedDirConfidence[dir] = Math.max(\n        0,\n        Math.min(\n          1,\n          (result.directionConfidence[dir] || 0) + bias + complexityAdjustment * 0.5\n        )\n      );\n    }\n\n    return {\n      ...result,\n      confidence: calibratedConfidence,\n      directionConfidence: calibratedDirConfidence as Record<Direction, number>,\n      diagnostics: [\n        ...result.diagnostics,\n        `Calibrated: bias=${bias.toFixed(3)}, complexity=${complexityAdjustment.toFixed(3)}, balance=${balanceAdjustment.toFixed(3)}`,\n      ],\n    };\n  }\n\n  /**\n   * Calibrate multiple results from a multi-pass decomposition.\n   * Applies individual calibration plus cross-strategy agreement analysis.\n   */\n  calibrateMultiple(\n    results: StrategyResult[],\n    signals: ComplexitySignals\n  ): StrategyResult[] {\n    // First, calibrate each result individually\n    const calibrated = results.map((r) => this.calibrate(r, signals));\n\n    // Then apply agreement bonus/penalty\n    if (calibrated.length >= 2) {\n      // Check if strategies agree on lead direction\n      const leadDirections = calibrated.map(\n        (r) => r.directionalAnalysis.leadDirection\n      );\n      const allAgree = leadDirections.every((d) => d === leadDirections[0]);\n\n      // Check if strategies agree on primary action\n      const primaryActions = calibrated.map((r) => r.intents.primary.action);\n      const actionsAgree = primaryActions.every((a) => a === primaryActions[0]);\n\n      const agreementBonus = (allAgree ? 0.05 : -0.03) + (actionsAgree ? 0.03 : -0.02);\n\n      return calibrated.map((r) => ({\n        ...r,\n        confidence: Math.max(0, Math.min(1, r.confidence + agreementBonus)),\n        diagnostics: [\n          ...r.diagnostics,\n          `Cross-strategy agreement: direction=${allAgree}, action=${actionsAgree}, bonus=${agreementBonus.toFixed(3)}`,\n        ],\n      }));\n    }\n\n    return calibrated;\n  }\n}\n\n// =============================================================================\n// MultiPassDecomposer\n// =============================================================================\n\n/**\n * Runs multiple decomposition strategies and merges/reconciles results\n * for the highest quality decomposition.\n *\n * Multi-pass is particularly valuable for:\n * - Complex prompts where a single strategy may miss important aspects\n * - Ambiguous prompts where strategy disagreement reveals true ambiguity\n * - High-stakes decompositions where confidence calibration matters\n *\n * Pass execution modes:\n * 1. **Parallel mode** (default): Run all strategies concurrently, merge results\n * 2. **Cascading mode**: Start with fast strategy, only run slower ones if\n *    confidence is below threshold\n *\n * Merging strategy:\n * - The result with the highest calibrated confidence is the \"primary\"\n * - Other results contribute supplementary intents and insights\n * - Agreement between strategies boosts confidence\n * - Disagreement is surfaced as ambiguity flags\n *\n * Integration with Medicine Wheel:\n * - After merging, the MultiPassDecomposer checks wheel balance\n * - If any direction is completely absent, it's flagged as a gap\n * - The ceremony requirement from MedicineWheelBridge is honored\n */\nexport class MultiPassDecomposer {\n  private readonly selector: StrategySelector;\n  private readonly calibrator: ConfidenceCalibrator;\n  private readonly maxPasses: number;\n  private readonly minConfidence: number;\n\n  constructor(options?: {\n    selector?: StrategySelector;\n    calibrator?: ConfidenceCalibrator;\n    maxPasses?: number;\n    minConfidence?: number;\n  }) {\n    this.selector = options?.selector ?? new StrategySelector();\n    this.calibrator = options?.calibrator ?? new ConfidenceCalibrator();\n    this.maxPasses = options?.maxPasses ?? 3;\n    this.minConfidence = options?.minConfidence ?? 0.6;\n  }\n\n  /**\n   * Run multi-pass decomposition in parallel mode.\n   *\n   * Runs all feasible strategies concurrently, calibrates results,\n   * and returns the best result along with all individual results\n   * for inspection.\n   */\n  async decomposeParallel(\n    prompt: string,\n    resources: AvailableResources,\n    preferences?: StrategyPreferences\n  ): Promise<MultiPassResult> {\n    const startTime = Date.now();\n    const complexityAnalyzer = new ComplexityAnalyzer();\n    const signals = complexityAnalyzer.analyze(prompt);\n\n    // Get all feasible strategies\n    const strategies = this.selector\n      .getStrategies()\n      .filter(\n        (s) =>\n          s.canHandle(resources) &&\n          !(preferences?.excludeStrategies ?? []).includes(s.id)\n      );\n\n    // Limit to maxPasses\n    const toRun = strategies.slice(0, this.maxPasses);\n\n    // Run all in parallel\n    const results = await Promise.all(\n      toRun.map((s) =>\n        s.decompose(prompt, resources).catch((error) => ({\n          error,\n          strategyId: s.id,\n        }))\n      )\n    );\n\n    // Filter out failures\n    const successfulResults: StrategyResult[] = [];\n    const failures: Array<{ strategyId: StrategyId; error: unknown }> = [];\n\n    for (const result of results) {\n      if (\"error\" in result) {\n        failures.push(result as { strategyId: StrategyId; error: unknown });\n      } else {\n        successfulResults.push(result as StrategyResult);\n      }\n    }\n\n    // Calibrate\n    const calibratedResults = this.calibrator.calibrateMultiple(\n      successfulResults,\n      signals\n    );\n\n    // Select best result\n    const sorted = [...calibratedResults].sort(\n      (a, b) => b.confidence - a.confidence\n    );\n\n    if (sorted.length === 0) {\n      const failureDetails = failures\n        .map((f) => `${f.strategyId}: ${f.error instanceof Error ? f.error.message : String(f.error)}`)\n        .join(\"; \");\n      throw new Error(\n        `All decomposition strategies failed. No results to select from. Failures: ${failureDetails || \"none registered\"}`\n      );\n    }\n\n    const best = sorted[0];\n\n    // Detect disagreements as ambiguity signals\n    const disagreements = this.detectDisagreements(calibratedResults);\n\n    return {\n      best,\n      allResults: calibratedResults,\n      failures: failures.map((f) => ({\n        strategyId: f.strategyId,\n        error: f.error instanceof Error ? f.error.message : String(f.error),\n      })),\n      signals,\n      disagreements,\n      totalExecutionTimeMs: Date.now() - startTime,\n    };\n  }\n\n  /**\n   * Run multi-pass decomposition in cascading mode.\n   *\n   * Starts with the auto-selected strategy. If its confidence is below\n   * the threshold, runs the next-best strategy, and so on up to maxPasses.\n   * Stops as soon as a result meets the confidence threshold.\n   */\n  async decomposeCascading(\n    prompt: string,\n    resources: AvailableResources,\n    preferences?: StrategyPreferences\n  ): Promise<MultiPassResult> {\n    const startTime = Date.now();\n    const complexityAnalyzer = new ComplexityAnalyzer();\n    const signals = complexityAnalyzer.analyze(prompt);\n\n    const allResults: StrategyResult[] = [];\n    const failures: Array<{ strategyId: string; error: string }> = [];\n    const usedStrategies = new Set<StrategyId>();\n    const minConf = preferences?.minConfidence ?? this.minConfidence;\n    const maxPasses = preferences?.maxPasses ?? this.maxPasses;\n\n    for (let pass = 0; pass < maxPasses; pass++) {\n      // Select next strategy, excluding already-used ones\n      const { strategy } = this.selector.select(prompt, resources, {\n        ...preferences,\n        excludeStrategies: [\n          ...(preferences?.excludeStrategies ?? []),\n          ...Array.from(usedStrategies),\n        ],\n      });\n\n      if (usedStrategies.has(strategy.id)) {\n        break; // No more unique strategies available\n      }\n\n      usedStrategies.add(strategy.id);\n\n      try {\n        const result = await strategy.decompose(prompt, resources);\n        const [calibrated] = this.calibrator.calibrateMultiple([result], signals);\n        allResults.push(calibrated);\n\n        if (calibrated.confidence >= minConf) {\n          break; // Good enough — stop early\n        }\n      } catch (error) {\n        failures.push({\n          strategyId: strategy.id,\n          error: error instanceof Error ? error.message : String(error),\n        });\n      }\n    }\n\n    const sorted = [...allResults].sort((a, b) => b.confidence - a.confidence);\n\n    if (sorted.length === 0) {\n      const failureDetails = failures\n        .map((f) => `${f.strategyId}: ${f.error}`)\n        .join(\"; \");\n      throw new Error(\n        `All decomposition strategies failed. No results to select from. Failures: ${failureDetails || \"none registered\"}`\n      );\n    }\n\n    const best = sorted[0];\n    const disagreements = this.detectDisagreements(allResults);\n\n    return {\n      best,\n      allResults,\n      failures,\n      signals,\n      disagreements,\n      totalExecutionTimeMs: Date.now() - startTime,\n    };\n  }\n\n  /**\n   * Detect points of disagreement between strategy results.\n   * Disagreements are surfaced to the consumer as potential ambiguities.\n   */\n  private detectDisagreements(results: StrategyResult[]): Disagreement[] {\n    if (results.length < 2) return [];\n\n    const disagreements: Disagreement[] = [];\n\n    // Check lead direction agreement\n    const leadDirs = results.map((r) => r.directionalAnalysis.leadDirection);\n    const uniqueLeadDirs = new Set(leadDirs);\n    if (uniqueLeadDirs.size > 1) {\n      disagreements.push({\n        aspect: \"lead_direction\",\n        description: `Strategies disagree on lead direction: ${Array.from(uniqueLeadDirs).join(\" vs \")}`,\n        strategyValues: Object.fromEntries(\n          results.map((r) => [r.strategyId, r.directionalAnalysis.leadDirection])\n        ),\n        severity: \"moderate\",\n      });\n    }\n\n    // Check primary action agreement\n    const primaryActions = results.map((r) => r.intents.primary.action);\n    const uniqueActions = new Set(primaryActions);\n    if (uniqueActions.size > 1) {\n      disagreements.push({\n        aspect: \"primary_action\",\n        description: `Strategies disagree on primary action: ${Array.from(uniqueActions).join(\" vs \")}`,\n        strategyValues: Object.fromEntries(\n          results.map((r) => [r.strategyId, r.intents.primary.action])\n        ),\n        severity: \"high\",\n      });\n    }\n\n    // Check secondary intent count divergence\n    const intentCounts = results.map((r) => r.intents.secondary.length);\n    const maxCount = Math.max(...intentCounts);\n    const minCount = Math.min(...intentCounts);\n    if (maxCount > 0 && minCount / maxCount < 0.5) {\n      disagreements.push({\n        aspect: \"intent_count\",\n        description: `Intent count varies significantly: ${minCount}-${maxCount} across strategies`,\n        strategyValues: Object.fromEntries(\n          results.map((r) => [r.strategyId, String(r.intents.secondary.length)])\n        ),\n        severity: \"low\",\n      });\n    }\n\n    return disagreements;\n  }\n}\n\n/**\n * Represents a point of disagreement between strategies.\n */\nexport interface Disagreement {\n  /** What aspect the strategies disagree on */\n  aspect: \"lead_direction\" | \"primary_action\" | \"intent_count\" | string;\n  /** Human-readable description */\n  description: string;\n  /** What each strategy reported */\n  strategyValues: Record<StrategyId, string>;\n  /** How severe the disagreement is */\n  severity: \"low\" | \"moderate\" | \"high\";\n}\n\n/**\n * The result of a multi-pass decomposition.\n */\nexport interface MultiPassResult {\n  /** The best result (highest calibrated confidence) */\n  best: StrategyResult;\n  /** All individual strategy results, calibrated */\n  allResults: StrategyResult[];\n  /** Any strategies that failed with error messages */\n  failures: Array<{ strategyId: StrategyId; error: string }>;\n  /** Complexity signals computed for the prompt */\n  signals: ComplexitySignals;\n  /** Points of disagreement between strategies */\n  disagreements: Disagreement[];\n  /** Total wall-clock time for all passes */\n  totalExecutionTimeMs: number;\n}\n\n// =============================================================================\n// StrategicDecomposer — Top-level API\n// =============================================================================\n\n/**\n * The top-level entry point that replaces the existing `decompose()` pipeline\n * function with a strategy-aware version. Backward compatible: when called\n * without options, behaves identically to the existing keyword-based pipeline.\n *\n * Usage:\n * ```typescript\n * import { StrategicDecomposer } from \"ava-langchain-prompt-decomposition\";\n *\n * // Simple — identical to existing decompose()\n * const decomposer = new StrategicDecomposer();\n * const result = await decomposer.decompose(\"Build a knowledge graph...\");\n *\n * // With LLM — auto-selects semantic/hybrid strategy\n * const decomposer = new StrategicDecomposer({\n *   resources: { llm: new ChatOpenAI() },\n * });\n * const result = await decomposer.decompose(\"Build a knowledge graph...\");\n *\n * // Multi-pass for highest quality\n * const decomposer = new StrategicDecomposer({\n *   resources: { llm: new ChatOpenAI() },\n *   preferences: { alwaysMultiPass: true },\n * });\n * const result = await decomposer.decompose(\"Build a knowledge graph...\");\n * ```\n */\nexport class StrategicDecomposer {\n  private readonly selector: StrategySelector;\n  private readonly multiPass: MultiPassDecomposer;\n  private readonly resources: AvailableResources;\n  private readonly preferences: StrategyPreferences;\n\n  constructor(options?: StrategicDecomposerOptions) {\n    this.resources = options?.resources ?? {};\n    this.preferences = options?.preferences ?? {};\n    this.selector = new StrategySelector(options?.strategies);\n    this.multiPass = new MultiPassDecomposer({\n      selector: this.selector,\n      minConfidence: this.preferences.minConfidence,\n      maxPasses: this.preferences.maxPasses,\n    });\n  }\n\n  /**\n   * Decompose a prompt using the strategy system.\n   *\n   * Automatically selects the best strategy based on prompt complexity\n   * and available resources. Optionally runs multi-pass for higher\n   * quality on complex prompts.\n   */\n  async decompose(prompt: string): Promise<StrategicDecompositionResult> {\n    const { strategy, signals, reason } = this.selector.select(\n      prompt,\n      this.resources,\n      this.preferences\n    );\n\n    // Decide whether to use multi-pass\n    const useMultiPass =\n      this.preferences.alwaysMultiPass ||\n      (signals.complexity === \"ambiguous\" && this.resources.llm !== undefined) ||\n      (signals.complexity === \"complex\" &&\n        this.resources.preferAccuracy &&\n        this.resources.llm !== undefined);\n\n    if (useMultiPass) {\n      const multiResult = await this.multiPass.decomposeParallel(\n        prompt,\n        this.resources,\n        this.preferences\n      );\n      return {\n        result: multiResult.best,\n        selectionReason: reason,\n        signals,\n        multiPass: multiResult,\n      };\n    }\n\n    // Single-pass\n    const result = await strategy.decompose(prompt, this.resources);\n    const calibrator = new ConfidenceCalibrator();\n    const calibrated = calibrator.calibrate(result, signals);\n\n    return {\n      result: calibrated,\n      selectionReason: reason,\n      signals,\n    };\n  }\n}\n\n/**\n * Runtime resources, selection preferences, and optional custom strategies\n * accepted by the strategy-aware decomposition API.\n */\nexport interface StrategicDecomposerOptions {\n  resources?: AvailableResources;\n  preferences?: StrategyPreferences;\n  strategies?: DecompositionStrategy[];\n}\n\n/**\n * Convenience entry point for one-off strategy-aware decompositions.\n */\nexport async function strategicDecompose(\n  prompt: string,\n  options?: StrategicDecomposerOptions\n): Promise<StrategicDecompositionResult> {\n  return new StrategicDecomposer(options).decompose(prompt);\n}\n\n/**\n * The output of StrategicDecomposer, containing the decomposition\n * result plus metadata about strategy selection and confidence calibration.\n */\nexport interface StrategicDecompositionResult {\n  /** The best decomposition result (calibrated) */\n  result: StrategyResult;\n  /** Why this strategy was selected */\n  selectionReason: string;\n  /** Complexity signals used for strategy selection */\n  signals: ComplexitySignals;\n  /** Multi-pass details, if multi-pass was used */\n  multiPass?: MultiPassResult;\n}\n\n// =============================================================================\n// Strategy Metadata / Provenance Contract\n// =============================================================================\n\nexport const STRATEGY_METADATA_SCHEMA_VERSION = 1;\n\n/**\n * Portable metadata extracted from a strategic decomposition result.\n * This is the durable contract for downstream engine consumption\n * (e.g. ava-langgraph-prompt-decomposition-engine, inquiry-routing-engine).\n *\n * Designed to be serializable and persistable alongside DecompositionResult\n * without modifying the core DecompositionResult shape.\n */\nexport interface StrategyMetadata {\n  /** Version of this portable metadata contract */\n  schemaVersion: typeof STRATEGY_METADATA_SCHEMA_VERSION;\n  /** Which strategy produced this result */\n  strategyId: StrategyId;\n  /** Human-readable explanation of why this strategy was selected */\n  selectionReason: string;\n  /** Pre-decomposition complexity analysis */\n  complexity: {\n    level: PromptComplexity;\n    wordCount: number;\n    clauseCount: number;\n    conditionalCount: number;\n    hedgingCount: number;\n    actionVerbCount: number;\n    directionalSpread: number;\n    hasTechnicalReferences: boolean;\n    hasNestedStructure: boolean;\n  };\n  /** Calibrated confidence scores */\n  confidence: {\n    overall: number;\n    perDirection: Record<string, number>;\n  };\n  /** Diagnostic trace from strategy execution and calibration */\n  diagnostics: string[];\n  /** Execution timing in milliseconds */\n  executionTimeMs: number;\n  /** Multi-pass details, if multi-pass was used */\n  multiPass?: {\n    totalPasses: number;\n    totalExecutionTimeMs: number;\n    disagreements: Array<{\n      aspect: string;\n      description: string;\n      strategyValues: Record<string, string>;\n      severity: Disagreement[\"severity\"];\n    }>;\n    failures: Array<{ strategyId: string; error: string }>;\n  };\n  /** ISO 8601 timestamp of when this decomposition was performed */\n  timestamp: string;\n}\n\n/**\n * A combined result that pairs the core DecompositionResult with\n * strategy provenance metadata, suitable for persistence and\n * downstream engine consumption.\n */\nexport interface DecompositionWithProvenance {\n  /** The core decomposition result (unchanged shape) */\n  decomposition: DecompositionResult;\n  /** Strategy selection and execution metadata */\n  metadata: StrategyMetadata;\n  /** Optional Medicine Wheel enrichment */\n  wheelEnriched?: WheelEnrichedAnalysis;\n}\n\n/**\n * Extract portable strategy metadata from a StrategicDecompositionResult.\n * Use this to persist provenance alongside stored decomposition artifacts.\n *\n * @example\n * ```typescript\n * const strategic = await decomposer.decompose(prompt);\n * const metadata = extractStrategyMetadata(strategic);\n * await saveDecomposition(strategic.result.decomposition, outputDir);\n * // Save metadata alongside for downstream engines\n * ```\n */\nexport function extractStrategyMetadata(\n  result: StrategicDecompositionResult\n): StrategyMetadata {\n  return {\n    schemaVersion: STRATEGY_METADATA_SCHEMA_VERSION,\n    strategyId: result.result.strategyId,\n    selectionReason: result.selectionReason,\n    complexity: {\n      level: result.signals.complexity,\n      wordCount: result.signals.wordCount,\n      clauseCount: result.signals.clauseCount,\n      conditionalCount: result.signals.conditionalCount,\n      hedgingCount: result.signals.hedgingCount,\n      actionVerbCount: result.signals.actionVerbCount,\n      directionalSpread: result.signals.directionalSpread,\n      hasTechnicalReferences: result.signals.hasTechnicalReferences,\n      hasNestedStructure: result.signals.hasNestedStructure,\n    },\n    confidence: {\n      overall: result.result.confidence,\n      perDirection: { ...result.result.directionConfidence },\n    },\n    diagnostics: [...result.result.diagnostics],\n    executionTimeMs: result.result.executionTimeMs,\n    multiPass: result.multiPass\n      ? {\n          totalPasses: result.multiPass.allResults.length,\n          totalExecutionTimeMs: result.multiPass.totalExecutionTimeMs,\n          disagreements: result.multiPass.disagreements.map((d) => ({\n            aspect: d.aspect,\n            description: d.description,\n            strategyValues: { ...d.strategyValues },\n            severity: d.severity,\n          })),\n          failures: result.multiPass.failures.map((f) => ({\n            strategyId: f.strategyId,\n            error: f.error,\n          })),\n        }\n      : undefined,\n    timestamp: result.result.decomposition.timestamp,\n  };\n}\n\n/**\n * Convert a StrategicDecompositionResult into a DecompositionWithProvenance,\n * pairing the core result with durable metadata for downstream consumption.\n *\n * @example\n * ```typescript\n * const strategic = await decomposer.decompose(prompt);\n * const withProvenance = strategicResultToProvenance(strategic);\n * // withProvenance.decomposition is the standard DecompositionResult\n * // withProvenance.metadata has strategy selection, complexity, confidence\n * ```\n */\nexport function strategicResultToProvenance(\n  result: StrategicDecompositionResult\n): DecompositionWithProvenance {\n  return {\n    decomposition: result.result.decomposition,\n    metadata: extractStrategyMetadata(result),\n    wheelEnriched: result.result.wheelEnriched,\n  };\n}\n","/**\n * PDE tree metadata helpers.\n *\n * This is the portable part of miaco's folder-backed PDE lineage model:\n * nested .pde folders, parent/child edges, runtime provenance, add-dir\n * inheritance, fallback metadata, and session identifiers. It intentionally\n * does not execute any external engine.\n */\n\nimport {\n  existsSync,\n  mkdirSync,\n  readFileSync,\n  readdirSync,\n  statSync,\n  writeFileSync,\n} from \"fs\";\nimport { basename, dirname, isAbsolute, join, resolve } from \"path\";\n\nexport const PDE_DIR = \".pde\";\nexport const PDE_META_FILENAME = \"meta.json\";\nexport const PDE_METADATA_SCHEMA_VERSION = 4;\n\nconst UUID_PATTERN =\n  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst PDE_FOLDER_PATTERN =\n  /^(?:\\d{10}--)?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;\n\nexport type ChildKind =\n  | \"milestone\"\n  | \"issue\"\n  | \"sub-task\"\n  | \"follow-up\"\n  | \"refinement\"\n  | \"sibling\";\n\nexport const CHILD_KINDS: readonly ChildKind[] = [\n  \"milestone\",\n  \"issue\",\n  \"sub-task\",\n  \"follow-up\",\n  \"refinement\",\n  \"sibling\",\n] as const;\n\nexport type PdeSessionIdSource = \"engine\" | \"manual\" | \"inherited\" | \"unknown\";\n\nexport type PdeRuntimeEngine =\n  | \"heuristic\"\n  | \"gemini\"\n  | \"claude\"\n  | \"copilot\"\n  | \"codex\"\n  | \"pva\"\n  | \"hermes\"\n  | (string & {});\n\nexport interface ChildEntry {\n  uuid: string;\n  kind: ChildKind;\n  created_at: string;\n}\n\nexport interface EngineFallbackAttempt {\n  engine: PdeRuntimeEngine;\n  model?: string;\n  ok: boolean;\n  error?: string;\n}\n\nexport interface PdeFallbackMetadata {\n  reason: string;\n  from_engine: PdeRuntimeEngine;\n  to_engine: PdeRuntimeEngine;\n  attempts: EngineFallbackAttempt[];\n  triggered_at: string;\n}\n\nexport interface PdeTreeMetadata {\n  schema_version: number;\n  root_pde_id: string;\n  parent_pde_id?: string;\n  parent_pde_dir?: string;\n  child_kind?: ChildKind;\n  children?: ChildEntry[];\n  provenance?: Record<string, unknown>;\n  engine: PdeRuntimeEngine;\n  model?: string;\n  pva_provider?: string;\n  pva_thinking?: string;\n  hermes_provider?: string;\n  add_dirs?: string[];\n  fallback?: PdeFallbackMetadata;\n  session_id?: string;\n  session_id_source?: PdeSessionIdSource;\n  created_at: string;\n  updated_at: string;\n}\n\nexport interface PdeResolvedContext {\n  folder: string;\n  metadata?: PdeTreeMetadata;\n}\n\nexport function normalizeAddDirs(values?: readonly string[]): string[] {\n  if (!values) return [];\n  const seen = new Set<string>();\n  const normalized: string[] = [];\n\n  for (const raw of values) {\n    for (const part of raw.split(\",\")) {\n      const value = part.trim();\n      if (!value || seen.has(value)) continue;\n      seen.add(value);\n      normalized.push(value);\n    }\n  }\n\n  return normalized;\n}\n\nexport function mergeAddDirs(\n  ...sources: Array<readonly string[] | undefined>\n): string[] | undefined {\n  const merged = normalizeAddDirs(\n    sources.flatMap((source) => (source ? [...source] : []))\n  );\n  return merged.length > 0 ? merged : undefined;\n}\n\nexport function ensureDirectory(path: string): void {\n  if (!existsSync(path)) mkdirSync(path, { recursive: true });\n}\n\nexport function getPdeRoot(workdir: string): string {\n  return join(workdir, PDE_DIR);\n}\n\nexport function extractPdeUuidFromFolderName(folderName: string): string | null {\n  return folderName.match(PDE_FOLDER_PATTERN)?.[1] ?? null;\n}\n\nexport function extractPdeUuidFromPath(path: string): string | null {\n  return extractPdeUuidFromFolderName(basename(path));\n}\n\nexport function resolvePdeFolderPath(\n  workdir: string,\n  folderPath: string\n): string | null {\n  const resolved = isAbsolute(folderPath) ? folderPath : resolve(workdir, folderPath);\n  try {\n    if (!existsSync(resolved) || !statSync(resolved).isDirectory()) return null;\n  } catch {\n    return null;\n  }\n  return resolved;\n}\n\nexport function findPdeFolder(workdir: string, uuidOrFolderName: string): string | null {\n  const pdeRoot = getPdeRoot(workdir);\n  if (!existsSync(pdeRoot)) return null;\n  const uuid = extractPdeUuidFromFolderName(uuidOrFolderName) ?? uuidOrFolderName;\n  const suffix = UUID_PATTERN.test(uuid) ? `--${uuid}` : null;\n\n  function search(dir: string): string | null {\n    let entries: string[];\n    try {\n      entries = readdirSync(dir);\n    } catch {\n      return null;\n    }\n\n    for (const entry of entries) {\n      const fullPath = join(dir, entry);\n      try {\n        if (!statSync(fullPath).isDirectory()) continue;\n      } catch {\n        continue;\n      }\n      if (entry === uuidOrFolderName || (suffix && entry.endsWith(suffix))) {\n        return fullPath;\n      }\n      const found = search(fullPath);\n      if (found) return found;\n    }\n\n    return null;\n  }\n\n  return search(pdeRoot);\n}\n\nexport function readPdeTreeMetadata(folder: string): PdeTreeMetadata | null {\n  const metaPath = join(folder, PDE_META_FILENAME);\n  if (!existsSync(metaPath)) return null;\n  try {\n    return JSON.parse(readFileSync(metaPath, \"utf-8\")) as PdeTreeMetadata;\n  } catch {\n    return null;\n  }\n}\n\nexport function writePdeTreeMetadata(\n  folder: string,\n  meta: PdeTreeMetadata\n): string {\n  ensureDirectory(folder);\n  const path = join(folder, PDE_META_FILENAME);\n  writeFileSync(path, JSON.stringify(meta, null, 2), \"utf-8\");\n  return path;\n}\n\nexport function resolvePdeContext(\n  workdir: string,\n  uuid: string\n): PdeResolvedContext | null {\n  const folder = findPdeFolder(workdir, uuid);\n  if (!folder) return null;\n\n  let current = folder;\n  const pdeRoot = getPdeRoot(workdir);\n  while (current.startsWith(pdeRoot)) {\n    const metadata = readPdeTreeMetadata(current);\n    if (metadata) return { folder, metadata };\n    const parent = dirname(current);\n    if (parent === current || parent.length < pdeRoot.length) break;\n    current = parent;\n  }\n\n  return { folder };\n}\n\nexport function resolvePdeContextByPath(\n  workdir: string,\n  folderPath: string\n): PdeResolvedContext | null {\n  const folder = resolvePdeFolderPath(workdir, folderPath);\n  if (!folder) return null;\n  const metadata = readPdeTreeMetadata(folder);\n  return metadata ? { folder, metadata } : { folder };\n}\n\nexport function buildPdeTreeMetadata(input: {\n  rootPdeId: string;\n  parentPdeId?: string;\n  parentPdeDir?: string;\n  childKind?: ChildKind;\n  provenance?: Record<string, unknown>;\n  engine?: PdeRuntimeEngine;\n  model?: string;\n  pvaProvider?: string;\n  pvaThinking?: string;\n  hermesProvider?: string;\n  addDirs?: string[];\n  fallback?: PdeFallbackMetadata;\n  sessionId?: string;\n  sessionIdSource?: PdeSessionIdSource;\n  existing?: PdeTreeMetadata | null;\n}): PdeTreeMetadata {\n  const now = new Date().toISOString();\n  const addDirs =\n    input.addDirs !== undefined\n      ? mergeAddDirs(input.existing?.add_dirs, input.addDirs)\n      : input.existing?.add_dirs;\n\n  return {\n    schema_version: PDE_METADATA_SCHEMA_VERSION,\n    root_pde_id: input.rootPdeId,\n    parent_pde_id: input.parentPdeId ?? input.existing?.parent_pde_id,\n    parent_pde_dir: input.parentPdeDir ?? input.existing?.parent_pde_dir,\n    child_kind: input.childKind ?? input.existing?.child_kind,\n    children: input.existing?.children,\n    provenance: input.provenance ?? input.existing?.provenance,\n    engine: input.engine ?? input.existing?.engine ?? \"heuristic\",\n    model: input.model ?? input.existing?.model,\n    pva_provider: input.pvaProvider ?? input.existing?.pva_provider,\n    pva_thinking: input.pvaThinking ?? input.existing?.pva_thinking,\n    hermes_provider: input.hermesProvider ?? input.existing?.hermes_provider,\n    add_dirs: addDirs,\n    fallback: input.fallback ?? input.existing?.fallback,\n    session_id: input.sessionId ?? input.existing?.session_id,\n    session_id_source: input.sessionId\n      ? input.sessionIdSource ?? \"manual\"\n      : input.existing?.session_id_source,\n    created_at: input.existing?.created_at ?? now,\n    updated_at: now,\n  };\n}\n\nexport function appendChildEntry(parentFolder: string, entry: ChildEntry): void {\n  const meta = readPdeTreeMetadata(parentFolder);\n  if (!meta) return;\n  const children = meta.children ?? [];\n  if (children.some((child) => child.uuid === entry.uuid)) return;\n  meta.children = [...children, entry];\n  meta.updated_at = new Date().toISOString();\n  writePdeTreeMetadata(parentFolder, meta);\n}\n\nexport function updatePdeTreeMetadata(\n  folder: string,\n  patch: {\n    engine?: PdeRuntimeEngine;\n    model?: string;\n    pvaProvider?: string;\n    pvaThinking?: string;\n    hermesProvider?: string;\n    addDirs?: string[];\n    sessionId?: string;\n    sessionIdSource?: PdeSessionIdSource;\n    fallback?: PdeFallbackMetadata;\n  }\n): PdeTreeMetadata | null {\n  const existing = readPdeTreeMetadata(folder);\n  if (!existing) return null;\n  const next = buildPdeTreeMetadata({\n    rootPdeId: existing.root_pde_id,\n    parentPdeId: existing.parent_pde_id,\n    parentPdeDir: existing.parent_pde_dir,\n    childKind: existing.child_kind,\n    provenance: existing.provenance,\n    engine: patch.engine ?? existing.engine,\n    model: patch.model ?? existing.model,\n    pvaProvider: patch.pvaProvider ?? existing.pva_provider,\n    pvaThinking: patch.pvaThinking ?? existing.pva_thinking,\n    hermesProvider: patch.hermesProvider ?? existing.hermes_provider,\n    addDirs: patch.addDirs,\n    fallback: patch.fallback ?? existing.fallback,\n    sessionId: patch.sessionId ?? existing.session_id,\n    sessionIdSource: patch.sessionId\n      ? patch.sessionIdSource ?? existing.session_id_source\n      : existing.session_id_source,\n    existing,\n  });\n  writePdeTreeMetadata(folder, next);\n  return next;\n}\n","/**\n * LangChain Runnable wrappers for the Prompt Decomposition Engine.\n *\n * Makes PDE components composable in LangChain chains via .pipe():\n *\n * @example\n * ```typescript\n * import { RunnableDecomposer } from \"ava-langchain-prompt-decomposition\";\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * const decomposer = new RunnableDecomposer();\n *\n * // Use standalone\n * const result = await decomposer.invoke(\"Build a knowledge graph...\");\n *\n * // Chain with other runnables\n * const chain = decomposer.pipe(somePostProcessor);\n * const result = await chain.invoke(\"Build a knowledge graph...\");\n *\n * // Batch processing\n * const results = await decomposer.batch([\"prompt1\", \"prompt2\"]);\n *\n * // With LLM-enhanced extraction\n * const llmDecomposer = new RunnableDecomposer({ llm: new ChatOpenAI() });\n * ```\n */\n\nimport { RunnableLambda } from \"@langchain/core/runnables\";\nimport type { RunnableConfig } from \"@langchain/core/runnables\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { DirectionalDecomposer, type DecomposerOptions } from \"./directional_decomposer.js\";\nimport { IntentExtractor, type ExtractorOptions } from \"./intent_extractor.js\";\nimport { DependencyMapper } from \"./dependency_mapper.js\";\nimport {\n  ActionStackBuilder,\n  type ActionStackOptions,\n  type DecompositionResult,\n} from \"./action_stack.js\";\nimport {\n  MedicineWheelBridge,\n  type WheelBridgeOptions,\n  type WheelEnrichedAnalysis,\n} from \"./wheel_bridge.js\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface RunnableDecomposerOptions {\n  decomposer?: DecomposerOptions;\n  extractor?: ExtractorOptions;\n  actionStack?: ActionStackOptions;\n  wheelBridge?: WheelBridgeOptions;\n  /** Optional LLM for enhanced intent extraction */\n  llm?: BaseLanguageModel;\n  /** Output format: full result object, JSON string, or markdown string */\n  outputFormat?: \"full\" | \"json\" | \"markdown\";\n}\n\nexport interface RunnableDecomposerResult {\n  decomposition: DecompositionResult;\n  wheelEnriched: WheelEnrichedAnalysis;\n  json: string;\n  markdown: string;\n  /** Quick-access: is ceremony required before proceeding? */\n  ceremonyRequired: boolean;\n  /** Quick-access: what's the overall balance? */\n  balance: number;\n  /** Quick-access: primary action */\n  primaryAction: string;\n  /** Quick-access: number of actions in the stack */\n  actionCount: number;\n}\n\n// =============================================================================\n// RunnableDecomposer\n// =============================================================================\n\n/**\n * A LangChain Runnable that runs the full PDE pipeline.\n * Accepts a string prompt and returns a structured decomposition.\n *\n * Chainable with .pipe(), .batch(), .stream(), etc.\n */\nexport class RunnableDecomposer extends RunnableLambda<string, RunnableDecomposerResult> {\n  static lc_name() {\n    return \"RunnableDecomposer\";\n  }\n\n  constructor(options?: RunnableDecomposerOptions) {\n    const extractorOpts: ExtractorOptions = {\n      ...options?.extractor,\n      ...(options?.llm ? { llm: options.llm } : {}),\n    };\n\n    super({\n      func: async (prompt: string, _config?: RunnableConfig): Promise<RunnableDecomposerResult> => {\n        const decomposer = new DirectionalDecomposer(options?.decomposer);\n        const extractor = new IntentExtractor(extractorOpts);\n        const mapper = new DependencyMapper();\n        const builder = new ActionStackBuilder(options?.actionStack);\n        const bridge = new MedicineWheelBridge(options?.wheelBridge);\n\n        const directionalAnalysis = decomposer.decompose(prompt);\n        const intentResult = await extractor.extract(prompt);\n        const graph = mapper.buildGraph(intentResult.secondary);\n        const order = mapper.computeExecutionOrder(graph);\n        const decomposition = builder.build(directionalAnalysis, intentResult, order);\n        const wheelEnriched = bridge.enrich(directionalAnalysis);\n\n        return {\n          decomposition,\n          wheelEnriched,\n          json: builder.toJSON(decomposition),\n          markdown: builder.toMarkdown(decomposition),\n          ceremonyRequired: wheelEnriched.ceremonyRequired,\n          balance: decomposition.balance,\n          primaryAction: decomposition.primary.action,\n          actionCount: decomposition.actionStack.length,\n        };\n      },\n    });\n  }\n}\n\n/**\n * A Runnable that only runs directional analysis (EAST direction).\n * Lightweight — no dependency mapping or action stack building.\n */\nexport class RunnableDirectionalAnalyzer extends RunnableLambda<string, import(\"./directional_decomposer.js\").DirectionalAnalysis> {\n  static lc_name() {\n    return \"RunnableDirectionalAnalyzer\";\n  }\n\n  constructor(options?: DecomposerOptions) {\n    super({\n      func: async (prompt: string) => {\n        const decomposer = new DirectionalDecomposer(options);\n        return decomposer.decompose(prompt);\n      },\n    });\n  }\n}\n\n/**\n * A Runnable that checks if a prompt passes the Medicine Wheel gate.\n * Returns enriched analysis with ceremony requirement flags.\n */\nexport class RunnableWheelGate extends RunnableLambda<string, WheelEnrichedAnalysis & { guidance: string[] }> {\n  static lc_name() {\n    return \"RunnableWheelGate\";\n  }\n\n  constructor(options?: { decomposer?: DecomposerOptions; bridge?: WheelBridgeOptions }) {\n    super({\n      func: async (prompt: string) => {\n        const decomposer = new DirectionalDecomposer(options?.decomposer);\n        const bridge = new MedicineWheelBridge(options?.bridge);\n        const analysis = decomposer.decompose(prompt);\n        const enriched = bridge.enrich(analysis);\n        const guidance = bridge.getRelationalGuidance(analysis);\n        return { ...enriched, guidance };\n      },\n    });\n  }\n}\n\n// =============================================================================\n// ChainDecomposer (Consistent Engine Interface)\n// =============================================================================\n\n/**\n * Standard Engine wrapper for the LangChain-based decomposition.\n * Provides a consistent interface for consumers like Ava-Decomposer-Studio.\n */\nexport class ChainDecomposer {\n  private options?: RunnableDecomposerOptions;\n\n  constructor(options?: RunnableDecomposerOptions & { apiKey?: string }) {\n    this.options = options;\n  }\n\n  /**\n   * Run the full decomposition pipeline.\n   * Returns a simplified result compatible with the studio's expectations.\n   */\n  async decompose(prompt: string): Promise<DecompositionResult> {\n    const decomposer = new DirectionalDecomposer(this.options?.decomposer);\n    const extractor = new IntentExtractor({\n      ...this.options?.extractor,\n      ...(this.options?.llm ? { llm: this.options.llm } : {}),\n    });\n    const mapper = new DependencyMapper();\n    const builder = new ActionStackBuilder(this.options?.actionStack);\n\n    const directionalAnalysis = decomposer.decompose(prompt);\n    const intentResult = await extractor.extract(prompt);\n    const graph = mapper.buildGraph(intentResult.secondary);\n    const order = mapper.computeExecutionOrder(graph);\n    \n    return builder.build(directionalAnalysis, intentResult, order);\n  }\n}\n","/**\n * Agent Harness Adapter for the Prompt Decomposition Engine.\n *\n * Provides a standardized interface for terminal agents (ava-code, mia-code)\n * to decompose prompts, display results, and track execution progress.\n *\n * This adapter is framework-agnostic — it works without LangChain/LangGraph\n * dependencies, making it suitable for lightweight CLI agents.\n *\n * @example\n * ```typescript\n * import { AgentPDE } from \"ava-langchain-prompt-decomposition/agent\";\n *\n * const pde = new AgentPDE();\n * const result = await pde.decompose(\"Build auth with JWT and tests\");\n * console.log(pde.formatForTerminal(result));\n *\n * // Track execution progress\n * pde.markCompleted(result, \"intent-0\");\n * console.log(pde.getProgress(result));\n * ```\n */\n\nimport { DirectionalDecomposer, type DecomposerOptions } from \"./directional_decomposer.js\";\nimport { IntentExtractor, type ExtractorOptions } from \"./intent_extractor.js\";\nimport { DependencyMapper } from \"./dependency_mapper.js\";\nimport { ActionStackBuilder, type DecompositionResult, type ActionItem } from \"./action_stack.js\";\nimport { MedicineWheelBridge, type WheelEnrichedAnalysis } from \"./wheel_bridge.js\";\nimport { saveDecomposition, loadDecomposition, type StoredDecomposition } from \"./storage.js\";\nimport { Direction, ALL_DIRECTIONS } from \"./directional_decomposer.js\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface AgentPDEOptions {\n  decomposer?: DecomposerOptions;\n  extractor?: ExtractorOptions;\n  /** Working directory for .pde/ storage */\n  workdir?: string;\n}\n\nexport interface AgentDecompositionResult {\n  id: string;\n  decomposition: DecompositionResult;\n  wheelEnriched: WheelEnrichedAnalysis;\n  /** Ceremony required before execution? */\n  ceremonyRequired: boolean;\n  /** Dominant direction */\n  leadDirection: Direction;\n  /** Markdown output */\n  markdown: string;\n}\n\nexport interface ExecutionProgress {\n  total: number;\n  completed: number;\n  remaining: number;\n  percentage: number;\n  nextActions: ActionItem[];\n  currentDirection: Direction;\n}\n\n// =============================================================================\n// Direction Display Constants\n// =============================================================================\n\nconst DIRECTION_EMOJI: Record<Direction, string> = {\n  [Direction.EAST]: \"🌅\",\n  [Direction.SOUTH]: \"🔥\",\n  [Direction.WEST]: \"🌊\",\n  [Direction.NORTH]: \"❄️\",\n};\n\nconst DIRECTION_LABELS: Record<Direction, string> = {\n  [Direction.EAST]: \"Vision & Understanding\",\n  [Direction.SOUTH]: \"Growth & Analysis\",\n  [Direction.WEST]: \"Validation & Living\",\n  [Direction.NORTH]: \"Action & Wisdom\",\n};\n\nconst DIRECTION_SETTLING: Record<Direction, string> = {\n  [Direction.EAST]: \"settling into understanding what's being asked\",\n  [Direction.SOUTH]: \"breathing into research and analysis\",\n  [Direction.WEST]: \"feeling into whether this works\",\n  [Direction.NORTH]: \"honoring what emerged with action\",\n};\n\n// =============================================================================\n// Agent PDE\n// =============================================================================\n\nexport class AgentPDE {\n  private decomposer: DirectionalDecomposer;\n  private extractor: IntentExtractor;\n  private mapper: DependencyMapper;\n  private builder: ActionStackBuilder;\n  private bridge: MedicineWheelBridge;\n  private workdir: string;\n\n  constructor(options?: AgentPDEOptions) {\n    this.decomposer = new DirectionalDecomposer(options?.decomposer);\n    this.extractor = new IntentExtractor(options?.extractor);\n    this.mapper = new DependencyMapper();\n    this.builder = new ActionStackBuilder();\n    this.bridge = new MedicineWheelBridge();\n    this.workdir = options?.workdir || process.cwd();\n  }\n\n  /**\n   * Decompose a prompt for agent execution.\n   */\n  async decompose(prompt: string): Promise<AgentDecompositionResult> {\n    const directionalAnalysis = this.decomposer.decompose(prompt);\n    const intentResult = await this.extractor.extract(prompt);\n    const graph = this.mapper.buildGraph(intentResult.secondary);\n    const order = this.mapper.computeExecutionOrder(graph);\n    const decomposition = this.builder.build(directionalAnalysis, intentResult, order);\n    const wheelEnriched = this.bridge.enrich(directionalAnalysis);\n\n    const id = `agpde-${Date.now()}`;\n    const markdown = this.builder.toMarkdown(decomposition);\n\n    // Determine lead direction from action stack\n    const directionCounts: Record<Direction, number> = {\n      [Direction.EAST]: 0, [Direction.SOUTH]: 0, [Direction.WEST]: 0, [Direction.NORTH]: 0,\n    };\n    for (const item of decomposition.actionStack) {\n      directionCounts[item.direction]++;\n    }\n    const leadDirection = (Object.entries(directionCounts) as [Direction, number][])\n      .sort((a, b) => b[1] - a[1])[0]?.[0] ?? Direction.EAST;\n\n    return {\n      id,\n      decomposition,\n      wheelEnriched,\n      ceremonyRequired: wheelEnriched.ceremonyRequired ?? false,\n      leadDirection,\n      markdown,\n    };\n  }\n\n  /**\n   * Format decomposition result for terminal display.\n   * Returns a plain text string suitable for console.log().\n   */\n  formatForTerminal(result: AgentDecompositionResult): string {\n    const lines: string[] = [];\n    const { decomposition } = result;\n\n    lines.push(\"\");\n    lines.push(\"💕 Prompt Decomposition (Four Directions)\");\n    lines.push(\"─\".repeat(45));\n\n    // Group action stack by direction\n    const byDirection: Record<Direction, ActionItem[]> = {\n      [Direction.EAST]: [], [Direction.SOUTH]: [], [Direction.WEST]: [], [Direction.NORTH]: [],\n    };\n    for (const item of decomposition.actionStack) {\n      byDirection[item.direction].push(item);\n    }\n\n    let stageNum = 0;\n    for (const dir of ALL_DIRECTIONS) {\n      const items = byDirection[dir];\n      if (items.length === 0) continue;\n      stageNum++;\n\n      const emoji = DIRECTION_EMOJI[dir];\n      const label = DIRECTION_LABELS[dir];\n      const settling = DIRECTION_SETTLING[dir];\n\n      lines.push(`\\nStage ${stageNum} (${emoji} ${dir.toUpperCase()} — ${label}):`);\n      lines.push(`  💕 *${settling}*`);\n\n      for (const item of items) {\n        const dep = item.dependency ? ` [after: ${item.dependency}]` : \"\";\n        const check = item.completed ? \"●\" : \"○\";\n        lines.push(`  ${check} ${item.text}${dep}`);\n      }\n    }\n\n    // Ambiguities\n    if (decomposition.ambiguities.length > 0) {\n      lines.push(\"\\n⚠ Ambiguities:\");\n      for (const a of decomposition.ambiguities) {\n        lines.push(`  ? ${a.text}`);\n        lines.push(`    → ${a.suggestion}`);\n      }\n    }\n\n    // Ceremony check\n    if (result.ceremonyRequired) {\n      lines.push(\"\\n🙏 Ceremony recommended before proceeding.\");\n    }\n\n    // Summary\n    const intentCount = decomposition.actionStack.length;\n    const ambCount = decomposition.ambiguities.length;\n    lines.push(`\\n${intentCount} tasks · ${ambCount} ambiguities · lead: ${DIRECTION_EMOJI[result.leadDirection]} ${result.leadDirection.toUpperCase()}`);\n\n    return lines.join(\"\\n\");\n  }\n\n  /**\n   * Mark an action item as completed and return updated progress.\n   */\n  markCompleted(result: AgentDecompositionResult, actionId: string): ExecutionProgress {\n    const item = result.decomposition.actionStack.find(a => a.id === actionId);\n    if (item) item.completed = true;\n    return this.getProgress(result);\n  }\n\n  /**\n   * Get current execution progress.\n   */\n  getProgress(result: AgentDecompositionResult): ExecutionProgress {\n    const { actionStack } = result.decomposition;\n    const completed = actionStack.filter(a => a.completed).length;\n    const remaining = actionStack.length - completed;\n\n    // Find next actionable items (no uncompleted dependencies)\n    const completedIds = new Set(actionStack.filter(a => a.completed).map(a => a.id));\n    const nextActions = actionStack.filter(a =>\n      !a.completed && (!a.dependency || completedIds.has(a.dependency))\n    );\n\n    const currentDirection = nextActions[0]?.direction ?? Direction.EAST;\n\n    return {\n      total: actionStack.length,\n      completed,\n      remaining,\n      percentage: actionStack.length > 0 ? Math.round((completed / actionStack.length) * 100) : 100,\n      nextActions,\n      currentDirection,\n    };\n  }\n\n  /**\n   * Save decomposition to .pde/ folder.\n   */\n  save(result: AgentDecompositionResult): StoredDecomposition | null {\n    try {\n      return saveDecomposition(this.workdir, result.decomposition);\n    } catch {\n      return null;\n    }\n  }\n}\n","/**\n * Execution Planner\n *\n * Takes an ActionStack and produces an ExecutionPlan with stages,\n * checkpoints, fallbacks, and success criteria. This completes the\n * 5-layer parity with Miadi-code's PDE pipeline (Layer 5).\n *\n * Layers 1-4 (DirectionalDecomposer → IntentExtractor → DependencyMapper\n * → ActionStackBuilder) decompose; this layer plans execution.\n *\n * No LLM dependency — uses deterministic grouping, checkpoint generation,\n * and heuristic-based fallback strategies.\n */\n\nimport { v4 as uuid } from \"uuid\";\nimport type {\n  ActionItem,\n  DecompositionResult,\n  AmbiguityFlag,\n} from \"./action_stack.js\";\nimport type { Direction } from \"./directional_decomposer.js\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * A stage in the execution plan — a group of actions that\n * share a direction and can be executed together.\n */\nexport interface ExecutionStage {\n  /** Unique stage identifier */\n  id: string;\n  /** Human-readable stage title */\n  title: string;\n  /** Actions belonging to this stage */\n  actions: ActionItem[];\n  /** The Medicine Wheel direction this stage serves */\n  direction: \"east\" | \"south\" | \"west\" | \"north\";\n  /** IDs of stages that must complete before this one */\n  dependencies: string[];\n  /** Estimated complexity based on action count and dependencies */\n  estimatedComplexity: \"simple\" | \"moderate\" | \"complex\";\n}\n\n/**\n * A checkpoint inserted between stages for verification.\n */\nexport interface Checkpoint {\n  /** The stage ID after which this checkpoint occurs */\n  afterStageId: string;\n  /** What should be verified at this checkpoint */\n  description: string;\n  /** Specific criteria to validate */\n  validationCriteria: string[];\n  /** Whether a human must review before proceeding */\n  requiresHumanReview: boolean;\n}\n\n/**\n * A fallback strategy for when a stage fails or encounters ambiguity.\n */\nexport interface FallbackStrategy {\n  /** The stage this fallback applies to */\n  forStageId: string;\n  /** Type of fallback strategy */\n  strategy: \"retry\" | \"skip\" | \"alternative\" | \"escalate\";\n  /** Human-readable description of what to do */\n  description: string;\n}\n\n/**\n * A complete execution plan — the final output of the PDE pipeline\n * (Layer 5) that describes how to execute a decomposition.\n */\nexport interface ExecutionPlan {\n  /** Unique plan identifier */\n  id: string;\n  /** ID of the source decomposition */\n  decompositionId?: string;\n  /** Ordered execution stages */\n  stages: ExecutionStage[];\n  /** Verification checkpoints */\n  checkpoints: Checkpoint[];\n  /** Fallback strategies for failure handling */\n  fallbacks: FallbackStrategy[];\n  /** Overall success criteria */\n  successCriteria: string[];\n  /** Overall estimated complexity */\n  estimatedComplexity: \"simple\" | \"moderate\" | \"complex\";\n  /** ISO timestamp */\n  createdAt: string;\n}\n\n/**\n * Configuration options for ExecutionPlanner.\n */\nexport interface ExecutionPlannerOptions {\n  /** Add checkpoints between direction changes (default true) */\n  autoCheckpoints?: boolean;\n  /** Generate fallback strategies automatically (default true) */\n  autoFallbacks?: boolean;\n}\n\n// =============================================================================\n// Direction metadata for stage generation\n// =============================================================================\n\nconst DIRECTION_LABELS: Record<Direction, string> = {\n  east: \"Vision & Requirements\",\n  south: \"Research & Analysis\",\n  west: \"Validation & Ceremony\",\n  north: \"Implementation & Action\",\n};\n\nconst DIRECTION_CHECKPOINT_CRITERIA: Record<Direction, string[]> = {\n  east: [\n    \"Requirements are clearly defined\",\n    \"Vision alignment has been confirmed\",\n    \"Scope boundaries are established\",\n  ],\n  south: [\n    \"Research dependencies have been gathered\",\n    \"Analysis is documented\",\n    \"Context is sufficient to proceed\",\n  ],\n  west: [\n    \"Validation criteria are met\",\n    \"Ceremony or ethical review completed\",\n    \"Quality checks passed\",\n  ],\n  north: [\n    \"Implementation matches specification\",\n    \"All actions executed successfully\",\n    \"Outputs are verified\",\n  ],\n};\n\n/**\n * Directions that require human review at checkpoints.\n * WEST (ceremony/ethics) and transitions to NORTH (action) are high-stakes.\n */\nconst HUMAN_REVIEW_DIRECTIONS: Set<Direction> = new Set([\"west\" as Direction]);\n\n// =============================================================================\n// ExecutionPlanner\n// =============================================================================\n\n/**\n * ExecutionPlanner takes a DecompositionResult and produces an ExecutionPlan\n * with stages, checkpoints, fallbacks, and success criteria.\n *\n * This is Layer 5 of the PDE pipeline — the bridge between decomposition\n * and actual execution.\n *\n * @example\n * ```typescript\n * const planner = new ExecutionPlanner();\n * const plan = planner.plan(decompositionResult);\n *\n * for (const stage of plan.stages) {\n *   console.log(`Stage: ${stage.title} (${stage.direction})`);\n *   for (const action of stage.actions) {\n *     console.log(`  - ${action.text}`);\n *   }\n * }\n *\n * for (const checkpoint of plan.checkpoints) {\n *   console.log(`Checkpoint after ${checkpoint.afterStageId}:`);\n *   console.log(`  ${checkpoint.description}`);\n * }\n * ```\n */\nexport class ExecutionPlanner {\n  private readonly autoCheckpoints: boolean;\n  private readonly autoFallbacks: boolean;\n\n  constructor(options?: ExecutionPlannerOptions) {\n    this.autoCheckpoints = options?.autoCheckpoints ?? true;\n    this.autoFallbacks = options?.autoFallbacks ?? true;\n  }\n\n  /**\n   * Create an execution plan from a decomposition result.\n   * Groups actions into stages, generates checkpoints and fallbacks,\n   * and derives overall success criteria.\n   */\n  plan(decomposition: DecompositionResult): ExecutionPlan {\n    const stages = this.groupIntoStages(decomposition.actionStack);\n\n    // Wire up stage dependencies based on direction ordering\n    this.wireInterStageDependencies(stages);\n\n    const checkpoints = this.autoCheckpoints\n      ? this.generateCheckpoints(stages)\n      : [];\n\n    const fallbacks = this.autoFallbacks\n      ? this.generateFallbacks(stages, decomposition.ambiguities)\n      : [];\n\n    const successCriteria = this.deriveSuccessCriteria(decomposition);\n    const estimatedComplexity = this.estimateOverallComplexity(stages);\n\n    return {\n      id: uuid(),\n      decompositionId: decomposition.id,\n      stages,\n      checkpoints,\n      fallbacks,\n      successCriteria,\n      estimatedComplexity,\n      createdAt: new Date().toISOString(),\n    };\n  }\n\n  /**\n   * Group actions into stages by direction and dependency.\n   * Actions with the same direction and no cross-direction dependencies\n   * are grouped together.\n   */\n  groupIntoStages(actions: ActionItem[]): ExecutionStage[] {\n    if (actions.length === 0) return [];\n\n    // Group by direction, preserving order\n    const directionGroups = new Map<Direction, ActionItem[]>();\n    const directionOrder: Direction[] = [];\n\n    for (const action of actions) {\n      const dir = action.direction;\n      if (!directionGroups.has(dir)) {\n        directionGroups.set(dir, []);\n        directionOrder.push(dir);\n      }\n      directionGroups.get(dir)!.push(action);\n    }\n\n    // Create stages from groups\n    const stages: ExecutionStage[] = [];\n\n    for (const dir of directionOrder) {\n      const groupActions = directionGroups.get(dir)!;\n\n      // Split large groups into sub-stages if needed\n      const chunks = this.chunkActions(groupActions, 5);\n\n      for (let i = 0; i < chunks.length; i++) {\n        const chunk = chunks[i];\n        const suffix = chunks.length > 1 ? ` (Part ${i + 1})` : \"\";\n        const stageId = uuid();\n\n        stages.push({\n          id: stageId,\n          title: `${DIRECTION_LABELS[dir] ?? dir}${suffix}`,\n          actions: chunk,\n          direction: dir,\n          dependencies: [],\n          estimatedComplexity: this.estimateStageComplexity(chunk),\n        });\n      }\n    }\n\n    return stages;\n  }\n\n  /**\n   * Generate checkpoints between stages, especially at direction boundaries.\n   */\n  generateCheckpoints(stages: ExecutionStage[]): Checkpoint[] {\n    const checkpoints: Checkpoint[] = [];\n\n    for (let i = 0; i < stages.length - 1; i++) {\n      const currentStage = stages[i];\n      const nextStage = stages[i + 1];\n\n      // Always add checkpoint at direction changes\n      const directionChanges = currentStage.direction !== nextStage.direction;\n      const isHighStakes = HUMAN_REVIEW_DIRECTIONS.has(\n        currentStage.direction as Direction\n      );\n\n      if (directionChanges || isHighStakes) {\n        const criteria =\n          DIRECTION_CHECKPOINT_CRITERIA[\n            currentStage.direction as Direction\n          ] ?? [`Stage \"${currentStage.title}\" outputs verified`];\n\n        checkpoints.push({\n          afterStageId: currentStage.id,\n          description: directionChanges\n            ? `Direction shift: ${currentStage.direction} → ${nextStage.direction}. ` +\n              `Verify ${currentStage.title} is complete before proceeding to ${nextStage.title}.`\n            : `Checkpoint after ${currentStage.title}. Verify outputs before continuing.`,\n          validationCriteria: criteria,\n          requiresHumanReview: isHighStakes,\n        });\n      }\n    }\n\n    // Always add a final checkpoint after the last stage\n    if (stages.length > 0) {\n      const lastStage = stages[stages.length - 1];\n      checkpoints.push({\n        afterStageId: lastStage.id,\n        description: `Final checkpoint: verify all outputs from \"${lastStage.title}\" are complete and correct.`,\n        validationCriteria: [\n          \"All actions in the plan have been executed\",\n          \"No unresolved errors or ambiguities\",\n          \"Outputs match expected deliverables\",\n        ],\n        requiresHumanReview: true,\n      });\n    }\n\n    return checkpoints;\n  }\n\n  /**\n   * Generate fallback strategies based on stage characteristics and ambiguities.\n   */\n  generateFallbacks(\n    stages: ExecutionStage[],\n    ambiguities: AmbiguityFlag[]\n  ): FallbackStrategy[] {\n    const fallbacks: FallbackStrategy[] = [];\n\n    // Map ambiguity keywords to stages for targeted fallbacks\n    const ambiguityTexts = ambiguities.map((a) => a.text.toLowerCase());\n\n    for (const stage of stages) {\n      // Determine fallback strategy based on direction and complexity\n      if (stage.estimatedComplexity === \"complex\") {\n        fallbacks.push({\n          forStageId: stage.id,\n          strategy: \"escalate\",\n          description:\n            `Stage \"${stage.title}\" is complex. ` +\n            `If execution fails, escalate to human review with full context.`,\n        });\n      } else if (stage.direction === (\"west\" as Direction)) {\n        // Ceremony/validation stages should not be skipped\n        fallbacks.push({\n          forStageId: stage.id,\n          strategy: \"retry\",\n          description:\n            `Stage \"${stage.title}\" involves validation/ceremony. ` +\n            `If checks fail, retry with adjusted parameters rather than skipping.`,\n        });\n      } else if (stage.direction === (\"east\" as Direction)) {\n        // Vision stages can be iterated\n        fallbacks.push({\n          forStageId: stage.id,\n          strategy: \"alternative\",\n          description:\n            `Stage \"${stage.title}\" clarifies vision. ` +\n            `If clarity cannot be achieved, try rephrasing requirements or narrowing scope.`,\n        });\n      } else {\n        // Default: retry for simple, skip for moderate\n        const strategy =\n          stage.estimatedComplexity === \"simple\" ? \"retry\" : \"skip\";\n        fallbacks.push({\n          forStageId: stage.id,\n          strategy,\n          description:\n            strategy === \"retry\"\n              ? `Stage \"${stage.title}\" is simple enough to retry on failure.`\n              : `Stage \"${stage.title}\" can be skipped if non-critical, with degraded output.`,\n        });\n      }\n\n      // Add ambiguity-specific fallbacks\n      const stageActionTexts = stage.actions\n        .map((a) => a.text.toLowerCase())\n        .join(\" \");\n      for (const ambiguity of ambiguities) {\n        const ambLower = ambiguity.text.toLowerCase();\n        if (stageActionTexts.includes(ambLower.split(\" \")[0])) {\n          fallbacks.push({\n            forStageId: stage.id,\n            strategy: \"escalate\",\n            description:\n              `Ambiguity detected: \"${ambiguity.text}\". ` +\n              `Suggestion: ${ambiguity.suggestion}`,\n          });\n        }\n      }\n    }\n\n    return fallbacks;\n  }\n\n  /**\n   * Derive success criteria from the decomposition outputs and primary intent.\n   */\n  deriveSuccessCriteria(decomposition: DecompositionResult): string[] {\n    const criteria: string[] = [];\n\n    // Primary intent completion\n    criteria.push(\n      `Primary intent fulfilled: ${decomposition.primary.action} ${decomposition.primary.target}`\n    );\n\n    // Expected outputs as success criteria\n    if (decomposition.outputs.artifacts.length > 0) {\n      criteria.push(\n        `Artifacts produced: ${decomposition.outputs.artifacts.join(\", \")}`\n      );\n    }\n    if (decomposition.outputs.updates.length > 0) {\n      criteria.push(\n        `Updates applied: ${decomposition.outputs.updates.join(\", \")}`\n      );\n    }\n    if (decomposition.outputs.communications.length > 0) {\n      criteria.push(\n        `Communications delivered: ${decomposition.outputs.communications.join(\", \")}`\n      );\n    }\n\n    // Balance criterion\n    if (decomposition.balance < 0.5) {\n      criteria.push(\n        `Address neglected directions: ${decomposition.neglectedDirections.join(\", \")}`\n      );\n    }\n\n    // All actions completed\n    const actionCount = decomposition.actionStack.length;\n    criteria.push(\n      `All ${actionCount} actions in the action stack executed successfully`\n    );\n\n    // No unresolved ambiguities\n    if (decomposition.ambiguities.length > 0) {\n      criteria.push(\n        `All ${decomposition.ambiguities.length} ambiguities resolved or acknowledged`\n      );\n    }\n\n    return criteria;\n  }\n\n  // ---------------------------------------------------------------------------\n  // Internal\n  // ---------------------------------------------------------------------------\n\n  /**\n   * Wire dependencies between stages based on the canonical direction order:\n   * EAST → SOUTH → WEST → NORTH\n   */\n  private wireInterStageDependencies(stages: ExecutionStage[]): void {\n    const directionOrder: Direction[] = [\"east\", \"south\", \"west\", \"north\"] as Direction[];\n    const stagesByDirection = new Map<string, ExecutionStage[]>();\n\n    for (const stage of stages) {\n      const dir = stage.direction;\n      if (!stagesByDirection.has(dir)) {\n        stagesByDirection.set(dir, []);\n      }\n      stagesByDirection.get(dir)!.push(stage);\n    }\n\n    // Each direction's stages depend on the last stage of the previous direction\n    for (let i = 1; i < directionOrder.length; i++) {\n      const prevDir = directionOrder[i - 1];\n      const currDir = directionOrder[i];\n      const prevStages = stagesByDirection.get(prevDir);\n      const currStages = stagesByDirection.get(currDir);\n\n      if (prevStages && prevStages.length > 0 && currStages && currStages.length > 0) {\n        const lastPrevStage = prevStages[prevStages.length - 1];\n        currStages[0].dependencies.push(lastPrevStage.id);\n      }\n    }\n\n    // Within same direction, chain sub-stages\n    for (const dirStages of stagesByDirection.values()) {\n      for (let i = 1; i < dirStages.length; i++) {\n        dirStages[i].dependencies.push(dirStages[i - 1].id);\n      }\n    }\n  }\n\n  /**\n   * Estimate complexity for a single stage based on action count\n   * and presence of dependencies.\n   */\n  private estimateStageComplexity(\n    actions: ActionItem[]\n  ): \"simple\" | \"moderate\" | \"complex\" {\n    const hasDependencies = actions.some((a) => a.dependency !== null);\n    const hasLowConfidence = actions.some((a) => a.confidence < 0.5);\n    const count = actions.length;\n\n    if (count <= 2 && !hasDependencies && !hasLowConfidence) {\n      return \"simple\";\n    } else if (count > 4 || (hasDependencies && hasLowConfidence)) {\n      return \"complex\";\n    } else {\n      return \"moderate\";\n    }\n  }\n\n  /**\n   * Estimate overall plan complexity from stage complexities.\n   */\n  private estimateOverallComplexity(\n    stages: ExecutionStage[]\n  ): \"simple\" | \"moderate\" | \"complex\" {\n    if (stages.length === 0) return \"simple\";\n\n    const hasComplex = stages.some((s) => s.estimatedComplexity === \"complex\");\n    const hasModerate = stages.some(\n      (s) => s.estimatedComplexity === \"moderate\"\n    );\n\n    if (hasComplex || stages.length > 5) {\n      return \"complex\";\n    } else if (hasModerate || stages.length > 2) {\n      return \"moderate\";\n    } else {\n      return \"simple\";\n    }\n  }\n\n  /**\n   * Chunk actions into groups of at most `maxSize`.\n   */\n  private chunkActions(\n    actions: ActionItem[],\n    maxSize: number\n  ): ActionItem[][] {\n    const chunks: ActionItem[][] = [];\n    for (let i = 0; i < actions.length; i += maxSize) {\n      chunks.push(actions.slice(i, i + maxSize));\n    }\n    return chunks;\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACYA,kBAA2B;AAMpB,IAAK,YAAL,kBAAKA,eAAL;AACL,EAAAA,WAAA,UAAO;AACP,EAAAA,WAAA,WAAQ;AACR,EAAAA,WAAA,UAAO;AACP,EAAAA,WAAA,WAAQ;AAJE,SAAAA;AAAA,GAAA;AAOL,IAAM,iBAA8B;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA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AgB,OAAO,OAAO,mBAAmB;AAEvD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,MAAM,QAAQ,OAAO,aAAa;AAAA,IAClC,UAAU,QAAQ,WAAW,aAAa;AAAA,EAC5C;AACF;","names":["Direction","uuid","import_uuid","Urgency","uuid","import_uuid","uuid","id","import_uuid","uuid","WheelQuadrant","import_fs","import_path","signals","uuid","uuid","raw","import_uuid","DIRECTION_LABELS","uuid"]}