{"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/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  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// 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: ThreeUniverseProcessor, 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 (ThreeUniverseProcessor, 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  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  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  };\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\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    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: withProvenanceKind(options.provenance, options.childKind),\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 * 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 * 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;;;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;AAEO,IAAM,kBAA6C;AAAA,EACxD,CAAC,iBAAc,GAAG;AAAA,EAClB,CAAC,mBAAe,GAAG;AAAA,EACnB,CAAC,iBAAc,GAAG;AAAA,EAClB,CAAC,mBAAe,GAAG;AACrB;AAEO,IAAM,sBAAiD;AAAA,EAC5D,CAAC,iBAAc,GAAG;AAAA,EAClB,CAAC,mBAAe,GAAG;AAAA,EACnB,CAA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,IAC3C;AACA,WAAO;AAAA,EACT;AACF;;;AXteO,IAAM,UAAU;AAiMvB,eAAsB,UAAU,QAAgB,SAAoD;AAClG,QAAM,aAAa,IAAI,sBAAsB,SAAS,UAAU;AAChE,QAAM,YAAY,IAAI,gBAAgB,SAAS,SAAS;AACxD,QAAM,SAAS,IAAI,iBAAiB;AACpC,QAAM,UAAU,IAAI,mBAAmB,SAAS,WAAW;AAC3D,QAAM,SAAS,IAAI,oBAAoB,SAAS,WAAW;AAE3D,QAAM,sBAAsB,WAAW,UAAU,MAAM;AACvD,QAAM,eAAe,MAAM,UAAU,QAAQ,MAAM;AACnD,QAAM,QAAQ,OAAO,WAAW,aAAa,SAAS;AACtD,QAAM,QAAQ,OAAO,sBAAsB,KAAK;AAChD,QAAM,gBAAgB,QAAQ,MAAM,qBAAqB,cAAc,KAAK;AAC5E,QAAM,gBAAgB,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","uuid","uuid","raw","import_uuid","DIRECTION_LABELS","uuid"]}