import { BaseLanguageModel } from '@langchain/core/language_models/base'; import { Embeddings } from '@langchain/core/embeddings'; import { RunnableLambda } from '@langchain/core/runnables'; /** * Directional Decomposer * * Decomposes a prompt through the Four Directions: * - EAST (Vision/Waabinong): What is being asked? Requirements clarity * - SOUTH (Analysis/Zhaawanong): What needs to be learned? Dependencies/research * - WEST (Validation/Epangishmok): What needs reflection? Testing/verification * - NORTH (Action/Kiiwedinong): What executes? Implementation steps * * Inspired by mcp-pde and grounded in Medicine Wheel epistemology. */ declare enum Direction { EAST = "east", SOUTH = "south", WEST = "west", NORTH = "north" } declare const ALL_DIRECTIONS: Direction[]; declare const DIRECTION_NAMES: Record; declare const DIRECTION_QUESTIONS: Record; /** Keywords that signal directional intent */ declare const DIRECTION_KEYWORDS: Record; /** A single directional observation */ interface DirectionalInsight { text: string; confidence: number; implicit: boolean; } /** Complete directional analysis of a prompt */ interface DirectionalAnalysis { id: string; timestamp: string; prompt: string; directions: Record; leadDirection: Direction; neglectedDirections: Direction[]; balance: number; } interface DecomposerOptions { neglectThreshold?: number; balanceThreshold?: number; } declare class DirectionalDecomposer { private readonly neglectThreshold; private readonly balanceThreshold; constructor(options?: DecomposerOptions); /** * Decompose a prompt into Four Directions analysis. * Uses keyword-based classification to distribute prompt segments * across directional categories. */ decompose(prompt: string): DirectionalAnalysis; /** Check if a decomposition is balanced enough to proceed */ isBalanced(analysis: DirectionalAnalysis): boolean; /** Generate guidance for neglected directions */ getGuidance(analysis: DirectionalAnalysis): string[]; private splitIntoSegments; private scoreSegment; private getTopDirection; } /** * Intent Extractor * * Extracts primary and secondary intents from a prompt, * following the PDE (Prompt Decomposition Engine) structure: * - Primary intent: single action-target-urgency-confidence tuple * - Secondary intents: multiple action items with dependency mapping, * implicit/explicit classification, and confidence scoring * * This is the EAST (Vision) function of PDE — clarifying what is being asked. */ declare enum Urgency { IMMEDIATE = "immediate", SESSION = "session", SPRINT = "sprint", ONGOING = "ongoing" } interface PrimaryIntent { action: string; target: string; urgency: Urgency; confidence: number; } interface SecondaryIntent { id: string; action: string; target: string; implicit: boolean; dependency: string | null; confidence: number; } interface IntentExtractionResult { id: string; timestamp: string; prompt: string; primary: PrimaryIntent; secondary: SecondaryIntent[]; context: ExtractionContext; } interface ExtractionContext { filesNeeded: string[]; toolsRequired: string[]; assumptions: string[]; } interface ExtractorOptions { extractImplicit?: boolean; mapDependencies?: boolean; llm?: BaseLanguageModel; } declare class IntentExtractor { private readonly extractImplicit; private readonly mapDependencies; private readonly llm?; constructor(options?: ExtractorOptions); /** * Extract intents from a prompt. * Returns a structured result with primary + secondary intents. */ extract(prompt: string): Promise; private _extractIntentsWithLLM; private splitSentences; private extractRawIntents; private findImplicitIntents; private determinePrimary; private buildSecondaryIntents; private inferDependencies; private targetsOverlap; private detectUrgency; private calculateConfidence; private extractContext; } /** * Dependency Mapper * * Maps dependencies between tasks, detects implicit requirements, * and produces a dependency-aware ordering. * * This is the SOUTH (Analysis) function of PDE — understanding * what needs to be learned and what depends on what. */ interface DependencyNode { id: string; intentId: string; action: string; target: string; direction: Direction; dependencies: string[]; dependents: string[]; depth: number; completed: boolean; } interface DependencyGraph { id: string; nodes: Map; roots: string[]; leaves: string[]; maxDepth: number; hasCycle: boolean; } interface ExecutionOrder { layers: DependencyNode[][]; totalSteps: number; criticalPath: string[]; } declare class DependencyMapper { /** * Build a dependency graph from secondary intents and their * directional classifications. */ buildGraph(intents: SecondaryIntent[], directionMap?: Map): DependencyGraph; /** * Compute execution order from a dependency graph. * Groups tasks into parallel layers where all tasks in a layer * can execute simultaneously. */ computeExecutionOrder(graph: DependencyGraph): ExecutionOrder; private inferDirection; private inferStructuralDependencies; private topicsRelated; private detectCycle; private calculateDepths; private findCriticalPath; } /** * Action Stack * * Produces a dependency-ordered, direction-tagged execution plan * from a complete PDE decomposition. This is the final output * structure that consumers (LangGraph, Flowise) use to execute tasks. * * This is the NORTH (Action) function of PDE — what actually executes. */ interface ActionItem { id: string; text: string; direction: Direction; dependency: string | null; completed: boolean; confidence: number; implicit: boolean; } /** Structured ambiguity flag (mcp-pde lineage) */ interface AmbiguityFlag { text: string; suggestion: string; } /** Expected outputs from the decomposition (mcp-pde lineage) */ interface ExpectedOutputs { artifacts: string[]; updates: string[]; communications: string[]; } interface DecompositionResult { id: string; timestamp: string; prompt: string; primary: { action: string; target: string; urgency: string; confidence: number; }; secondary: SecondaryIntent[]; context: { filesNeeded: string[]; toolsRequired: string[]; assumptions: string[]; }; outputs: ExpectedOutputs; directions: Record>; actionStack: ActionItem[]; balance: number; leadDirection: Direction; neglectedDirections: Direction[]; ambiguities: AmbiguityFlag[]; } interface ActionStackOptions { includeImplicit?: boolean; maxItems?: number; } declare class ActionStackBuilder { private readonly includeImplicit; private readonly maxItems; constructor(options?: ActionStackOptions); /** * Build the complete PDE output from directional analysis and intent extraction. * This merges all decomposition outputs into the final action stack. */ build(directionalAnalysis: DirectionalAnalysis, intentResult: IntentExtractionResult, executionOrder?: ExecutionOrder): DecompositionResult; /** * Serialize a DecompositionResult to the PDE JSON format * (compatible with /workspace/.pde/ structure) */ toJSON(result: DecompositionResult): string; /** * Render a DecompositionResult as human-readable Markdown */ toMarkdown(result: DecompositionResult): string; private fromExecutionOrder; private fromIntents; private detectAmbiguities; private extractExpectedOutputs; } /** * Medicine Wheel Bridge * * Bridges PDE's Four Directions with the MedicineWheelFilter * from ava-langchain-relational-intelligence. This maps: * EAST → SPIRITUAL (vision, purpose) * SOUTH → MENTAL (analysis, learning) * WEST → EMOTIONAL (reflection, ceremony) * NORTH → PHYSICAL (action, execution) * * When relational-intelligence is available, it enriches PDE * decompositions with wheel assessments and value gate checks. */ /** Medicine Wheel quadrants from relational-intelligence */ declare enum WheelQuadrant { PHYSICAL = "physical", EMOTIONAL = "emotional", MENTAL = "mental", SPIRITUAL = "spiritual" } /** How PDE directions map to Medicine Wheel quadrants */ declare const DIRECTION_TO_QUADRANT: Record; declare const QUADRANT_TO_DIRECTION: Record; interface WheelEnrichedAnalysis extends DirectionalAnalysis { wheelMapping: Record; quadrantPresence: Record; relationalCoverage: number; ceremonyRequired: boolean; } interface WheelBridgeOptions { ceremonyThreshold?: number; } declare class MedicineWheelBridge { private readonly ceremonyThreshold; constructor(options?: WheelBridgeOptions); /** * Enrich a directional analysis with Medicine Wheel assessment. * Maps direction coverage to quadrant presence and determines * whether ceremony is needed. */ enrich(analysis: DirectionalAnalysis): WheelEnrichedAnalysis; /** * Check if a decomposition can proceed without ceremony. * Returns false if spiritual/emotional directions are neglected. */ canProceedWithoutCeremony(analysis: DirectionalAnalysis): boolean; /** * Generate guidance for bringing a decomposition into relational balance. */ getRelationalGuidance(analysis: DirectionalAnalysis): string[]; } /** * V0 Ontology Bridge * * Maps PDE (Prompt Decomposition Engine) concepts to the * V0 Medicine Wheel Developer Suite ontology vision. * * V0.md envisions these packages: * @medicine-wheel/ontology-core → RDF + relational data model * @medicine-wheel/graph-viz → Force-directed + wheel overlays * @medicine-wheel/narrative-engine → Beat sequencing across directions * @medicine-wheel/relational-query → Context-aware traversal * @medicine-wheel/ui-components → Direction cards, timelines * * This bridge shows how PDE primitives and existing ava-langchain * packages map to each of those envisioned packages. */ /** * Maps to @medicine-wheel/ontology-core * * The PDE DirectionalDecomposer + MedicineWheelBridge provide: * - Direction/Act/Ceremony type system (Direction enum, WheelQuadrant) * - Temporal beats tracking (ActionItem with dependency ordering) * - RDF-compatible triples could be generated from DecompositionResult */ interface OntologyCoreConcept { /** Direction in Medicine Wheel */ direction: Direction; /** Corresponding quadrant */ quadrant: WheelQuadrant; /** Anishinaabe name */ indigenousName: string; /** Act in narrative structure */ act: number; /** Season symbolism */ season: string; /** Element */ element: string; } declare const ONTOLOGY_CORE_MAP: Record; /** * Maps to @medicine-wheel/narrative-engine * * PDE ActionStack items are narrative beats: * - Each action = a beat with direction, dependency, confidence * - The execution order = beat sequencing across four directions * - The DecompositionGraph = ceremonial cadence pattern * * Existing packages that feed this: * - ava-langgraph-narrative-intelligence: ThreePerspectiveProcessor, CoherenceEngine * - ava-langchain-narrative-tracing: Story beat observability */ interface NarrativeBeatMapping { /** PDE action ID */ actionId: string; /** Direction this beat belongs to */ direction: Direction; /** Act number (1-4 based on direction) */ act: number; /** The action text becomes the beat description */ description: string; /** Whether this beat was explicitly stated or inferred */ implicit: boolean; /** Confidence in this beat */ confidence: number; } /** * Convert a PDE action to a narrative beat. */ declare function actionToNarrativeBeat(action: { id: string; text: string; direction: Direction; confidence: number; implicit: boolean; }): NarrativeBeatMapping; /** * Maps to @medicine-wheel/relational-query * * PDE's DependencyMapper produces a graph of task dependencies. * This maps to relational-query's context-aware relationship traversal: * - DependencyNode = graph node with typed relationships * - Dependencies = "depends_on" relationships * - Direction = relationship context (which quadrant) * * Existing packages: * - ava-langchain-relational-intelligence: ImportanceStore, SpiralTracker * provide the accountability tracking layer */ interface RelationalQueryNode { id: string; type: "task" | "ceremony" | "vision" | "research"; direction: Direction; relationships: Array<{ targetId: string; type: "depends_on" | "validates" | "informs" | "ceremonies"; confidence: number; }>; } /** * How existing ava-* packages map to V0's envisioned @medicine-wheel/* suite. * This serves as a roadmap for convergence. */ declare const PACKAGE_MAPPING: { readonly "@medicine-wheel/ontology-core": { readonly existingPackages: readonly ["ava-langchain-prompt-decomposition (Direction, WheelQuadrant types)", "ava-langchain-relational-intelligence (MedicineWheelFilter, ImportanceUnit)"]; readonly providedBy: "Direction enum, WheelBridge, ONTOLOGY_CORE_MAP"; readonly missing: "RDF triple store, OWL vocabulary, SPARQL queries"; }; readonly "@medicine-wheel/graph-viz": { readonly existingPackages: readonly ["ava-langchain-prompt-decomposition (DependencyGraph visualization)"]; readonly providedBy: "DependencyMapper produces graph structure"; readonly missing: "D3 force-directed layout, Medicine Wheel overlay renderer"; }; readonly "@medicine-wheel/narrative-engine": { readonly existingPackages: readonly ["ava-langgraph-narrative-intelligence (ThreePerspectiveProcessor, CoherenceEngine)", "ava-langchain-narrative-tracing (NarrativeTracingHandler)", "ava-langgraph-prompt-decomposition-engine (DecompositionGraph)"]; readonly providedBy: "ActionStack → beats, DecompositionGraph → ceremonial cadence"; readonly missing: "Timeline/categorical view React components"; }; readonly "@medicine-wheel/relational-query": { readonly existingPackages: readonly ["ava-langchain-relational-intelligence (ImportanceStore, SpiralTracker, ValueGate)", "ava-langchain-prompt-decomposition (DependencyMapper)"]; readonly providedBy: "DependencyGraph + ImportanceStore"; readonly missing: "SPARQL-like query builder, OCAP-aware access control"; }; readonly "@medicine-wheel/ui-components": { readonly existingPackages: readonly ["ava-Flowise (PromptDecomposition node, MedicineWheelGate node)"]; readonly providedBy: "AgentFlow nodes for Flowise"; readonly missing: "Standalone React components, direction cards, beat timelines"; }; }; /** * Strategy Pattern Architecture for the Prompt Decomposition Engine * * This module defines a pluggable strategy system that allows the PDE * to select among multiple decomposition approaches based on prompt * complexity, available resources, and Medicine Wheel balance. * * Architecture overview: * StrategySelector → picks DecompositionStrategy → produces StrategyResult * MultiPassDecomposer → runs N strategies → ConfidenceCalibrator → merged result * * Integration with existing pipeline: * The strategy layer wraps the existing Decompose → Extract → Map → Build → Enrich * pipeline. Each strategy may use the existing components differently: * - KeywordStrategy: Uses DirectionalDecomposer + heuristic IntentExtractor (existing code) * - SemanticStrategy: Uses keyword direction analysis + LLM-enhanced intent extraction * - HybridStrategy: Runs both, merges with weighted scoring * * The StrategySelector sits *before* the pipeline, and the ConfidenceCalibrator * sits *after* it — they are pre- and post-processing layers. */ /** * Identifies which strategy produced a result. * Used for provenance tracking and confidence calibration. */ type StrategyId = "keyword" | "semantic" | "hybrid" | string; /** * Complexity classification of a prompt, used to guide strategy selection. * * - simple: Single intent, clear action verb, few clauses (< 50 words) * - moderate: 2-3 intents, some nesting, moderate ambiguity (50-150 words) * - complex: 4+ intents, nested conditionals, hedging, cross-domain references (150+ words) * - ambiguous: Cannot be reliably classified — signals that multi-pass is needed */ type PromptComplexity = "simple" | "moderate" | "complex" | "ambiguous"; /** * Signals detected during prompt analysis that inform strategy selection. * These are lightweight heuristics computed *before* full decomposition. */ interface ComplexitySignals { /** Total word count */ wordCount: number; /** Number of distinct sentences/clauses */ clauseCount: number; /** Count of conditional keywords (if, when, unless, whether) */ conditionalCount: number; /** Count of hedging language (maybe, probably, somehow, perhaps) */ hedgingCount: number; /** Count of action verbs detected */ actionVerbCount: number; /** Count of distinct directional keyword matches across all 4 directions */ directionalSpread: number; /** Whether the prompt references file paths, code symbols, or technical artifacts */ hasTechnicalReferences: boolean; /** Whether the prompt contains nested structures (lists, sub-clauses, multi-step) */ hasNestedStructure: boolean; /** Computed complexity classification */ complexity: PromptComplexity; } /** * Resources available at runtime, used by the StrategySelector to * determine which strategies are feasible. */ interface AvailableResources { /** An LLM instance for semantic classification and structured extraction */ llm?: BaseLanguageModel; /** An embeddings model for similarity-based direction classification */ embeddings?: Embeddings; /** Maximum latency budget in milliseconds (strategies that exceed this are excluded) */ maxLatencyMs?: number; /** Whether to prefer accuracy over speed (default: false = prefer speed) */ preferAccuracy?: boolean; } /** * User-specified preferences that override automatic strategy selection. */ interface StrategyPreferences { /** Force a specific strategy (bypasses auto-selection) */ forceStrategy?: StrategyId; /** Minimum confidence threshold — results below this trigger multi-pass */ minConfidence?: number; /** Enable multi-pass even for simple prompts (default: false) */ alwaysMultiPass?: boolean; /** Maximum number of passes in multi-pass mode (default: 3) */ maxPasses?: number; /** Strategies to exclude from selection */ excludeStrategies?: StrategyId[]; } /** * The output of a single strategy execution. Contains the decomposition * plus metadata about the strategy's confidence and provenance. * * This is the universal return type for all strategies, enabling * comparison, merging, and calibration across different approaches. */ interface StrategyResult { /** Which strategy produced this result */ strategyId: StrategyId; /** The directional analysis (segment → direction classification) */ directionalAnalysis: DirectionalAnalysis; /** The extracted intents (primary + secondary) */ intents: IntentExtractionResult; /** The final decomposition (action stack, outputs, ambiguities) */ decomposition: DecompositionResult; /** Medicine Wheel enrichment */ wheelEnriched: WheelEnrichedAnalysis; /** Overall confidence in this result (0-1), pre-calibration */ confidence: number; /** Per-direction confidence scores */ directionConfidence: Record; /** Execution time in milliseconds */ executionTimeMs: number; /** Any warnings or diagnostic notes from the strategy */ diagnostics: string[]; } /** * The core strategy interface. All decomposition approaches implement this. * * Design rationale: * - `id` enables provenance tracking and strategy-specific calibration curves * - `canHandle` allows strategies to self-exclude based on resource availability * - `estimateLatency` enables the selector to respect latency budgets * - `decompose` is the main entry point, returning a uniform StrategyResult * * Strategies are stateless — all configuration is passed via constructor, * and each `decompose` call is independent. */ interface DecompositionStrategy { /** Unique identifier for this strategy */ readonly id: StrategyId; /** Human-readable name for diagnostics and logging */ readonly name: string; /** * Check if this strategy can handle decomposition with the given resources. * Returns false if required resources (e.g., LLM) are unavailable. */ canHandle(resources: AvailableResources): boolean; /** * Estimate the latency of running this strategy, in milliseconds. * Used by the StrategySelector to respect latency budgets. * Returns -1 if latency cannot be estimated. */ estimateLatency(signals: ComplexitySignals): number; /** * Execute the decomposition strategy on the given prompt. * * @param prompt - The raw user prompt to decompose * @param resources - Available runtime resources (LLM, embeddings, etc.) * @returns A StrategyResult containing the full decomposition with confidence scores */ decompose(prompt: string, resources: AvailableResources): Promise; } /** * Wraps the existing keyword-based decomposition pipeline for backward * compatibility. This is the default strategy when no LLM is available. * * Characteristics: * - Zero external dependencies (no LLM, no embeddings) * - Deterministic output for the same input * - Fast (~1-5ms for typical prompts) * - Lower accuracy on nuanced or ambiguous prompts * * Uses: DirectionalDecomposer (keyword scoring) + IntentExtractor (heuristic mode) * + DependencyMapper + ActionStackBuilder + MedicineWheelBridge * * This strategy is always available and serves as the baseline for * confidence calibration. */ declare class KeywordStrategy implements DecompositionStrategy { readonly id: StrategyId; readonly name = "Keyword-Based Decomposition"; canHandle(_resources: AvailableResources): boolean; estimateLatency(signals: ComplexitySignals): number; /** * Run the existing keyword-based pipeline. * * Implementation notes: * - Instantiates DirectionalDecomposer, IntentExtractor (no LLM), * DependencyMapper, ActionStackBuilder, MedicineWheelBridge * - Runs the standard Decompose → Extract → Map → Build → Enrich flow * - Computes confidence from keyword match density and direction balance */ decompose(prompt: string, _resources: AvailableResources): Promise; /** * Overall confidence combines direction balance, primary intent confidence, * and proportion of non-implicit insights. */ private computeOverallConfidence; } /** * Provides LLM-enhanced intent extraction with keyword-based directional analysis. * * Characteristics: * - Requires an LLM (will not be selected without one) * - Non-deterministic — LLM responses vary * - Higher latency (500ms-5s depending on model) * - Significantly better on ambiguous, multi-intent, and nuanced prompts for * intent extraction; can understand context, metaphor, and implied requirements * * Architecture: * 1. Uses IntentExtractor with the LLM enabled for richer intent extraction * 2. Falls back to keyword-only extraction if LLM call fails * 3. Directional analysis still uses the keyword-based DirectionalDecomposer — * true LLM directional classification is a future enhancement * 4. Runs the rest of the pipeline (DependencyMapper, ActionStackBuilder, * MedicineWheelBridge) as normal * * The LLM call is grounded in Medicine Wheel epistemology, asking the model * to consider all four directions explicitly when extracting intents. */ declare class SemanticStrategy implements DecompositionStrategy { readonly id: StrategyId; readonly name = "LLM-Enhanced Intent Extraction with Keyword Directional Analysis"; canHandle(resources: AvailableResources): boolean; estimateLatency(signals: ComplexitySignals): number; /** * Run LLM-enhanced intent extraction with keyword-based directional analysis. * * Implementation approach: * 1. Use IntentExtractor with the LLM enabled for richer intent extraction — * the LLM identifies implicit intents, understands context and metaphor, * and provides better-calibrated confidence scores * 2. Directional analysis uses the keyword-based DirectionalDecomposer; * true LLM directional classification is a future enhancement * 3. Run the rest of the pipeline (DependencyMapper, ActionStackBuilder, * MedicineWheelBridge) as normal — those are direction-agnostic * * If the LLM call fails, falls back to heuristic intent extraction * and marks the fallback in diagnostics. */ decompose(prompt: string, resources: AvailableResources): Promise; private computeBaseConfidence; } /** * Combines keyword and semantic approaches with weighted scoring and * confidence calibration. Runs both strategies and merges the results. * * Characteristics: * - Requires an LLM (falls back to keyword-only if unavailable) * - Highest accuracy due to ensemble approach * - Highest latency (~2x semantic strategy) * - Best for complex or high-stakes prompts where accuracy matters more than speed * * Note: Both KeywordStrategy and SemanticStrategy currently use the same * keyword-based DirectionalDecomposer for directional analysis, so the ensemble * value is primarily in intent extraction (LLM-enhanced vs. heuristic). True * divergence in directional analysis will require a future LLM-based directional * classifier in SemanticStrategy. * * Merging algorithm: * 1. Run KeywordStrategy and SemanticStrategy in parallel * 2. For directional analysis: union insights from both; shared insights get * confidence = weighted average. If they disagree, flag the segment for review. * 3. For intents: union the intent sets, deduplicating by target similarity. * Shared intents get boosted confidence; strategy-unique intents are kept * but marked with lower confidence. * 4. For the final action stack: re-run DependencyMapper and ActionStackBuilder * on the merged intent set. * * Weighting: * - Default weights: keyword=0.35, semantic=0.65 * - Weights shift toward keyword for simple prompts (semantic adds little value) * - Weights shift toward semantic for complex/ambiguous prompts */ declare class HybridStrategy implements DecompositionStrategy { readonly id: StrategyId; readonly name = "Hybrid Keyword+Semantic Decomposition"; private readonly keywordWeight; private readonly semanticWeight; private readonly keywordStrategy; private readonly semanticStrategy; constructor(options?: { keywordWeight?: number; semanticWeight?: number; }); canHandle(resources: AvailableResources): boolean; estimateLatency(signals: ComplexitySignals): number; /** * Run both strategies and merge results. * * Implementation approach: * 1. Run KeywordStrategy and SemanticStrategy concurrently via Promise.all * 2. Merge directional analyses: * - For each direction, take the union of insights from both strategies * - Insights present in both get confidence = weighted average * - Insights in only one strategy get confidence penalty (×0.8) * 3. Merge intents: * - Deduplicate by action+target similarity (Jaccard on target words > 0.5) * - Shared intents: confidence = weighted average of both * - Unique intents: kept with source-strategy confidence × 0.9 * 4. Rebuild the dependency graph and action stack from merged intents * 5. Confidence = weighted combination of both strategy confidences, * with a bonus for agreement */ decompose(prompt: string, resources: AvailableResources): Promise; /** * Merge two directional analyses by taking the union of insights per direction. * Deduplicates by text similarity and averages confidence for shared insights. */ private mergeDirectionalAnalyses; /** * Merge intent extraction results from two strategies. * Uses the higher-confidence primary intent and unions secondary intents. */ private mergeIntents; /** * Jaccard similarity between two target strings (word-level). */ private targetSimilarity; /** * Compute a bonus for strategies agreeing on lead direction and primary intent. * Agreement suggests higher reliability. */ private computeAgreementBonus; /** * Merge per-direction confidence from both strategies using weights. */ private mergeDirectionConfidence; } /** * Analyzes a prompt's complexity characteristics without performing * full decomposition. This is a fast pre-processing step used by * StrategySelector to choose the right strategy. * * The analysis produces ComplexitySignals which capture: * - Structural complexity (length, clauses, nesting) * - Linguistic complexity (hedging, conditionals, ambiguity) * - Technical complexity (file references, code symbols) * - Directional spread (how many directions are touched by keywords) */ declare class ComplexityAnalyzer { /** * Analyze a prompt and return complexity signals. */ analyze(prompt: string): ComplexitySignals; } /** * Automatically selects the best decomposition strategy based on prompt * complexity, available resources, and user preferences. * * Selection algorithm (pseudocode): * * ``` * function select(prompt, resources, preferences): * // 1. Honor forced strategy if specified * if preferences.forceStrategy: * return registry[preferences.forceStrategy] * * // 2. Analyze prompt complexity * signals = ComplexityAnalyzer.analyze(prompt) * * // 3. Filter to feasible strategies * feasible = registry.filter(s => * s.canHandle(resources) && * !preferences.excludeStrategies.includes(s.id) && * (resources.maxLatencyMs == null || s.estimateLatency(signals) <= resources.maxLatencyMs) * ) * * // 4. Score each feasible strategy * for strategy in feasible: * score = 0 * if signals.complexity == "simple": * score += (strategy.id == "keyword") ? 1.0 : 0.5 * elif signals.complexity == "moderate": * score += (strategy.id == "semantic") ? 0.8 : (strategy.id == "keyword") ? 0.6 : 0.9 * elif signals.complexity in ["complex", "ambiguous"]: * score += (strategy.id == "hybrid") ? 1.0 : (strategy.id == "semantic") ? 0.7 : 0.3 * * if resources.preferAccuracy: * score += (strategy.id == "hybrid") ? 0.3 : (strategy.id == "semantic") ? 0.2 : 0 * * // 5. Return highest-scoring strategy * return feasible.maxBy(score) * ``` * * Medicine Wheel influence on selection: * - If the prompt is heavily WEST-oriented (validation/ceremony), prefer * strategies with higher accuracy (semantic/hybrid) as these are * high-stakes decisions that benefit from deeper analysis * - If the prompt is heavily NORTH-oriented (action/execution), prefer * faster strategies (keyword) as speed matters for implementation */ declare class StrategySelector { private readonly registry; private readonly complexityAnalyzer; constructor(strategies?: DecompositionStrategy[]); /** * Register a custom strategy. */ register(strategy: DecompositionStrategy): void; /** * Select the best strategy for the given prompt and context. */ select(prompt: string, resources: AvailableResources, preferences?: StrategyPreferences): { strategy: DecompositionStrategy; signals: ComplexitySignals; reason: string; }; /** * Auto-select the best strategy based on complexity signals, resources, and preferences. */ private autoSelect; /** * Get all registered strategies. */ getStrategies(): DecompositionStrategy[]; } /** * Post-processing step that calibrates confidence scores across strategies. * * Different strategies have different confidence distributions: * - KeywordStrategy tends to report moderate confidence (0.5-0.8) consistently * - SemanticStrategy may report high confidence (0.7-0.95) but with more variance * - HybridStrategy should be the most calibrated by design * * The calibrator normalizes scores so they are comparable across strategies * and applies corrections based on prompt complexity. * * Calibration approach: * 1. Strategy-specific bias correction (empirical offsets per strategy) * 2. Complexity-based adjustment (complex prompts get a confidence penalty) * 3. Balance bonus/penalty (well-balanced decompositions get a boost) * 4. Agreement bonus (if multi-pass, strategies that agree get boosted) */ declare class ConfidenceCalibrator { /** * Per-strategy bias corrections. * Positive values increase confidence; negative values decrease. * These should be tuned empirically over time. */ private readonly strategyBias; /** * Calibrate a single strategy result. */ calibrate(result: StrategyResult, signals: ComplexitySignals): StrategyResult; /** * Calibrate multiple results from a multi-pass decomposition. * Applies individual calibration plus cross-strategy agreement analysis. */ calibrateMultiple(results: StrategyResult[], signals: ComplexitySignals): StrategyResult[]; } /** * Runs multiple decomposition strategies and merges/reconciles results * for the highest quality decomposition. * * Multi-pass is particularly valuable for: * - Complex prompts where a single strategy may miss important aspects * - Ambiguous prompts where strategy disagreement reveals true ambiguity * - High-stakes decompositions where confidence calibration matters * * Pass execution modes: * 1. **Parallel mode** (default): Run all strategies concurrently, merge results * 2. **Cascading mode**: Start with fast strategy, only run slower ones if * confidence is below threshold * * Merging strategy: * - The result with the highest calibrated confidence is the "primary" * - Other results contribute supplementary intents and insights * - Agreement between strategies boosts confidence * - Disagreement is surfaced as ambiguity flags * * Integration with Medicine Wheel: * - After merging, the MultiPassDecomposer checks wheel balance * - If any direction is completely absent, it's flagged as a gap * - The ceremony requirement from MedicineWheelBridge is honored */ declare class MultiPassDecomposer { private readonly selector; private readonly calibrator; private readonly maxPasses; private readonly minConfidence; constructor(options?: { selector?: StrategySelector; calibrator?: ConfidenceCalibrator; maxPasses?: number; minConfidence?: number; }); /** * Run multi-pass decomposition in parallel mode. * * Runs all feasible strategies concurrently, calibrates results, * and returns the best result along with all individual results * for inspection. */ decomposeParallel(prompt: string, resources: AvailableResources, preferences?: StrategyPreferences): Promise; /** * Run multi-pass decomposition in cascading mode. * * Starts with the auto-selected strategy. If its confidence is below * the threshold, runs the next-best strategy, and so on up to maxPasses. * Stops as soon as a result meets the confidence threshold. */ decomposeCascading(prompt: string, resources: AvailableResources, preferences?: StrategyPreferences): Promise; /** * Detect points of disagreement between strategy results. * Disagreements are surfaced to the consumer as potential ambiguities. */ private detectDisagreements; } /** * Represents a point of disagreement between strategies. */ interface Disagreement { /** What aspect the strategies disagree on */ aspect: "lead_direction" | "primary_action" | "intent_count" | string; /** Human-readable description */ description: string; /** What each strategy reported */ strategyValues: Record; /** How severe the disagreement is */ severity: "low" | "moderate" | "high"; } /** * The result of a multi-pass decomposition. */ interface MultiPassResult { /** The best result (highest calibrated confidence) */ best: StrategyResult; /** All individual strategy results, calibrated */ allResults: StrategyResult[]; /** Any strategies that failed with error messages */ failures: Array<{ strategyId: StrategyId; error: string; }>; /** Complexity signals computed for the prompt */ signals: ComplexitySignals; /** Points of disagreement between strategies */ disagreements: Disagreement[]; /** Total wall-clock time for all passes */ totalExecutionTimeMs: number; } /** * The top-level entry point that replaces the existing `decompose()` pipeline * function with a strategy-aware version. Backward compatible: when called * without options, behaves identically to the existing keyword-based pipeline. * * Usage: * ```typescript * import { StrategicDecomposer } from "ava-langchain-prompt-decomposition"; * * // Simple — identical to existing decompose() * const decomposer = new StrategicDecomposer(); * const result = await decomposer.decompose("Build a knowledge graph..."); * * // With LLM — auto-selects semantic/hybrid strategy * const decomposer = new StrategicDecomposer({ * resources: { llm: new ChatOpenAI() }, * }); * const result = await decomposer.decompose("Build a knowledge graph..."); * * // Multi-pass for highest quality * const decomposer = new StrategicDecomposer({ * resources: { llm: new ChatOpenAI() }, * preferences: { alwaysMultiPass: true }, * }); * const result = await decomposer.decompose("Build a knowledge graph..."); * ``` */ declare class StrategicDecomposer { private readonly selector; private readonly multiPass; private readonly resources; private readonly preferences; constructor(options?: StrategicDecomposerOptions); /** * Decompose a prompt using the strategy system. * * Automatically selects the best strategy based on prompt complexity * and available resources. Optionally runs multi-pass for higher * quality on complex prompts. */ decompose(prompt: string): Promise; } /** * Runtime resources, selection preferences, and optional custom strategies * accepted by the strategy-aware decomposition API. */ interface StrategicDecomposerOptions { resources?: AvailableResources; preferences?: StrategyPreferences; strategies?: DecompositionStrategy[]; } /** * Convenience entry point for one-off strategy-aware decompositions. */ declare function strategicDecompose(prompt: string, options?: StrategicDecomposerOptions): Promise; /** * The output of StrategicDecomposer, containing the decomposition * result plus metadata about strategy selection and confidence calibration. */ interface StrategicDecompositionResult { /** The best decomposition result (calibrated) */ result: StrategyResult; /** Why this strategy was selected */ selectionReason: string; /** Complexity signals used for strategy selection */ signals: ComplexitySignals; /** Multi-pass details, if multi-pass was used */ multiPass?: MultiPassResult; } declare const STRATEGY_METADATA_SCHEMA_VERSION = 1; /** * Portable metadata extracted from a strategic decomposition result. * This is the durable contract for downstream engine consumption * (e.g. ava-langgraph-prompt-decomposition-engine, inquiry-routing-engine). * * Designed to be serializable and persistable alongside DecompositionResult * without modifying the core DecompositionResult shape. */ interface StrategyMetadata { /** Version of this portable metadata contract */ schemaVersion: typeof STRATEGY_METADATA_SCHEMA_VERSION; /** Which strategy produced this result */ strategyId: StrategyId; /** Human-readable explanation of why this strategy was selected */ selectionReason: string; /** Pre-decomposition complexity analysis */ complexity: { level: PromptComplexity; wordCount: number; clauseCount: number; conditionalCount: number; hedgingCount: number; actionVerbCount: number; directionalSpread: number; hasTechnicalReferences: boolean; hasNestedStructure: boolean; }; /** Calibrated confidence scores */ confidence: { overall: number; perDirection: Record; }; /** Diagnostic trace from strategy execution and calibration */ diagnostics: string[]; /** Execution timing in milliseconds */ executionTimeMs: number; /** Multi-pass details, if multi-pass was used */ multiPass?: { totalPasses: number; totalExecutionTimeMs: number; disagreements: Array<{ aspect: string; description: string; strategyValues: Record; severity: Disagreement["severity"]; }>; failures: Array<{ strategyId: string; error: string; }>; }; /** ISO 8601 timestamp of when this decomposition was performed */ timestamp: string; } /** * A combined result that pairs the core DecompositionResult with * strategy provenance metadata, suitable for persistence and * downstream engine consumption. */ interface DecompositionWithProvenance { /** The core decomposition result (unchanged shape) */ decomposition: DecompositionResult; /** Strategy selection and execution metadata */ metadata: StrategyMetadata; /** Optional Medicine Wheel enrichment */ wheelEnriched?: WheelEnrichedAnalysis; } /** * Extract portable strategy metadata from a StrategicDecompositionResult. * Use this to persist provenance alongside stored decomposition artifacts. * * @example * ```typescript * const strategic = await decomposer.decompose(prompt); * const metadata = extractStrategyMetadata(strategic); * await saveDecomposition(strategic.result.decomposition, outputDir); * // Save metadata alongside for downstream engines * ``` */ declare function extractStrategyMetadata(result: StrategicDecompositionResult): StrategyMetadata; /** * Convert a StrategicDecompositionResult into a DecompositionWithProvenance, * pairing the core result with durable metadata for downstream consumption. * * @example * ```typescript * const strategic = await decomposer.decompose(prompt); * const withProvenance = strategicResultToProvenance(strategic); * // withProvenance.decomposition is the standard DecompositionResult * // withProvenance.metadata has strategy selection, complexity, confidence * ``` */ declare function strategicResultToProvenance(result: StrategicDecompositionResult): DecompositionWithProvenance; /** * PDE tree metadata helpers. * * This is the portable part of miaco's folder-backed PDE lineage model: * nested .pde folders, parent/child edges, runtime provenance, add-dir * inheritance, fallback metadata, and session identifiers. It intentionally * does not execute any external engine. */ declare const PDE_DIR = ".pde"; declare const PDE_META_FILENAME = "meta.json"; declare const PDE_METADATA_SCHEMA_VERSION = 4; type ChildKind = "milestone" | "issue" | "sub-task" | "follow-up" | "refinement" | "sibling"; declare const CHILD_KINDS: readonly ChildKind[]; type PdeSessionIdSource = "engine" | "manual" | "inherited" | "unknown"; type PdeRuntimeEngine = "heuristic" | "gemini" | "claude" | "copilot" | "codex" | "pva" | "hermes" | (string & {}); interface ChildEntry { uuid: string; kind: ChildKind; created_at: string; } interface EngineFallbackAttempt { engine: PdeRuntimeEngine; model?: string; ok: boolean; error?: string; } interface PdeFallbackMetadata { reason: string; from_engine: PdeRuntimeEngine; to_engine: PdeRuntimeEngine; attempts: EngineFallbackAttempt[]; triggered_at: string; } interface PdeTreeMetadata { schema_version: number; root_pde_id: string; parent_pde_id?: string; parent_pde_dir?: string; child_kind?: ChildKind; children?: ChildEntry[]; provenance?: Record; engine: PdeRuntimeEngine; model?: string; pva_provider?: string; pva_thinking?: string; hermes_provider?: string; add_dirs?: string[]; fallback?: PdeFallbackMetadata; session_id?: string; session_id_source?: PdeSessionIdSource; created_at: string; updated_at: string; } interface PdeResolvedContext { folder: string; metadata?: PdeTreeMetadata; } declare function normalizeAddDirs(values?: readonly string[]): string[]; declare function mergeAddDirs(...sources: Array): string[] | undefined; declare function ensureDirectory(path: string): void; declare function getPdeRoot(workdir: string): string; declare function extractPdeUuidFromFolderName(folderName: string): string | null; declare function extractPdeUuidFromPath(path: string): string | null; declare function resolvePdeFolderPath(workdir: string, folderPath: string): string | null; declare function findPdeFolder(workdir: string, uuidOrFolderName: string): string | null; declare function readPdeTreeMetadata(folder: string): PdeTreeMetadata | null; declare function writePdeTreeMetadata(folder: string, meta: PdeTreeMetadata): string; declare function resolvePdeContext(workdir: string, uuid: string): PdeResolvedContext | null; declare function resolvePdeContextByPath(workdir: string, folderPath: string): PdeResolvedContext | null; declare function buildPdeTreeMetadata(input: { rootPdeId: string; parentPdeId?: string; parentPdeDir?: string; childKind?: ChildKind; provenance?: Record; engine?: PdeRuntimeEngine; model?: string; pvaProvider?: string; pvaThinking?: string; hermesProvider?: string; addDirs?: string[]; fallback?: PdeFallbackMetadata; sessionId?: string; sessionIdSource?: PdeSessionIdSource; existing?: PdeTreeMetadata | null; }): PdeTreeMetadata; declare function appendChildEntry(parentFolder: string, entry: ChildEntry): void; declare function updatePdeTreeMetadata(folder: string, patch: { engine?: PdeRuntimeEngine; model?: string; pvaProvider?: string; pvaThinking?: string; hermesProvider?: string; addDirs?: string[]; sessionId?: string; sessionIdSource?: PdeSessionIdSource; fallback?: PdeFallbackMetadata; }): PdeTreeMetadata | null; /** * PDE Storage — .pde/ dot folder persistence * * Ported from mcp-pde/src/storage.ts (IAIP lineage). * Stores decompositions as JSON files in .pde/ directory, * with Markdown exports for human-in-the-loop editing via git diff. * * Storage layout: * .pde/ * .json — StoredDecomposition (full JSON) * .md — Markdown export (human-editable, git-diffable) */ interface StoredDecomposition { id: string; timestamp: string; prompt: string; result: DecompositionResult; engine?: PdeRuntimeEngine; model?: string; parent_pde_id?: string; child_kind?: ChildKind; fallback?: PdeFallbackMetadata; provenance?: Record; folder_name?: string; pde_dir?: string; markdownPath?: string; } type PdeStorageLayout = "flat" | "tree"; interface SaveDecompositionOptions { /** Legacy flat storage is the default for backward compatibility. */ layout?: PdeStorageLayout; engine?: PdeRuntimeEngine; model?: string; sessionId?: string; sessionIdSource?: PdeSessionIdSource; parentPdeId?: string; parentPdeFolder?: string; childKind?: ChildKind; provenance?: Record; addDirs?: string[]; pvaProvider?: string; pvaThinking?: string; hermesProvider?: string; fallback?: PdeFallbackMetadata; } /** * Save a decomposition to .pde/ as JSON + Markdown. */ declare function saveDecomposition(workdir: string, result: DecompositionResult, options?: SaveDecompositionOptions): StoredDecomposition; /** * Save a decomposition using miaco-style folder-backed PDE tree storage. * * Layout: * .pde/--/pde-.json * .pde/--/pde-.md * .pde/--/meta.json * * Children are nested under their parent folder and recorded in the parent's * metadata children[] reverse edge. */ declare function saveDecompositionTree(workdir: string, result: DecompositionResult, options?: Omit): StoredDecomposition; /** * Persist a strategy-aware result while retaining the stable * DecompositionResult record shape and adding strategy provenance. */ declare function saveStrategicDecomposition(workdir: string, result: StrategicDecompositionResult, options?: SaveDecompositionOptions): StoredDecomposition; /** * Load a stored decomposition by ID. */ declare function loadDecomposition(workdir: string, id: string): StoredDecomposition | null; /** * List stored decompositions, newest first. */ declare function listDecompositions(workdir: string, limit?: number): StoredDecomposition[]; /** * Convert a DecompositionResult to git-diffable Markdown. * Includes Four Directions header and structured ambiguity flags. */ interface DecompositionMarkdownOptions { engine?: PdeRuntimeEngine; model?: string; parentPdeId?: string; } declare function decompositionToMarkdown(result: DecompositionResult, options?: DecompositionMarkdownOptions): string; interface RunnableDecomposerOptions { decomposer?: DecomposerOptions; extractor?: ExtractorOptions; actionStack?: ActionStackOptions; wheelBridge?: WheelBridgeOptions; /** Optional LLM for enhanced intent extraction */ llm?: BaseLanguageModel; /** Output format: full result object, JSON string, or markdown string */ outputFormat?: "full" | "json" | "markdown"; } interface RunnableDecomposerResult { decomposition: DecompositionResult; wheelEnriched: WheelEnrichedAnalysis; json: string; markdown: string; /** Quick-access: is ceremony required before proceeding? */ ceremonyRequired: boolean; /** Quick-access: what's the overall balance? */ balance: number; /** Quick-access: primary action */ primaryAction: string; /** Quick-access: number of actions in the stack */ actionCount: number; } /** * A LangChain Runnable that runs the full PDE pipeline. * Accepts a string prompt and returns a structured decomposition. * * Chainable with .pipe(), .batch(), .stream(), etc. */ declare class RunnableDecomposer extends RunnableLambda { static lc_name(): string; constructor(options?: RunnableDecomposerOptions); } /** * A Runnable that only runs directional analysis (EAST direction). * Lightweight — no dependency mapping or action stack building. */ declare class RunnableDirectionalAnalyzer extends RunnableLambda { static lc_name(): string; constructor(options?: DecomposerOptions); } /** * A Runnable that checks if a prompt passes the Medicine Wheel gate. * Returns enriched analysis with ceremony requirement flags. */ declare class RunnableWheelGate extends RunnableLambda { static lc_name(): string; constructor(options?: { decomposer?: DecomposerOptions; bridge?: WheelBridgeOptions; }); } /** * Standard Engine wrapper for the LangChain-based decomposition. * Provides a consistent interface for consumers like Ava-Decomposer-Studio. */ declare class ChainDecomposer { private options?; constructor(options?: RunnableDecomposerOptions & { apiKey?: string; }); /** * Run the full decomposition pipeline. * Returns a simplified result compatible with the studio's expectations. */ decompose(prompt: string): Promise; } /** * Agent Harness Adapter for the Prompt Decomposition Engine. * * Provides a standardized interface for terminal agents (ava-code, mia-code) * to decompose prompts, display results, and track execution progress. * * This adapter is framework-agnostic — it works without LangChain/LangGraph * dependencies, making it suitable for lightweight CLI agents. * * @example * ```typescript * import { AgentPDE } from "ava-langchain-prompt-decomposition/agent"; * * const pde = new AgentPDE(); * const result = await pde.decompose("Build auth with JWT and tests"); * console.log(pde.formatForTerminal(result)); * * // Track execution progress * pde.markCompleted(result, "intent-0"); * console.log(pde.getProgress(result)); * ``` */ interface AgentPDEOptions { decomposer?: DecomposerOptions; extractor?: ExtractorOptions; /** Working directory for .pde/ storage */ workdir?: string; } interface AgentDecompositionResult { id: string; decomposition: DecompositionResult; wheelEnriched: WheelEnrichedAnalysis; /** Ceremony required before execution? */ ceremonyRequired: boolean; /** Dominant direction */ leadDirection: Direction; /** Markdown output */ markdown: string; } interface ExecutionProgress { total: number; completed: number; remaining: number; percentage: number; nextActions: ActionItem[]; currentDirection: Direction; } declare class AgentPDE { private decomposer; private extractor; private mapper; private builder; private bridge; private workdir; constructor(options?: AgentPDEOptions); /** * Decompose a prompt for agent execution. */ decompose(prompt: string): Promise; /** * Format decomposition result for terminal display. * Returns a plain text string suitable for console.log(). */ formatForTerminal(result: AgentDecompositionResult): string; /** * Mark an action item as completed and return updated progress. */ markCompleted(result: AgentDecompositionResult, actionId: string): ExecutionProgress; /** * Get current execution progress. */ getProgress(result: AgentDecompositionResult): ExecutionProgress; /** * Save decomposition to .pde/ folder. */ save(result: AgentDecompositionResult): StoredDecomposition | null; } /** * Execution Planner * * Takes an ActionStack and produces an ExecutionPlan with stages, * checkpoints, fallbacks, and success criteria. This completes the * 5-layer parity with Miadi-code's PDE pipeline (Layer 5). * * Layers 1-4 (DirectionalDecomposer → IntentExtractor → DependencyMapper * → ActionStackBuilder) decompose; this layer plans execution. * * No LLM dependency — uses deterministic grouping, checkpoint generation, * and heuristic-based fallback strategies. */ /** * A stage in the execution plan — a group of actions that * share a direction and can be executed together. */ interface ExecutionStage { /** Unique stage identifier */ id: string; /** Human-readable stage title */ title: string; /** Actions belonging to this stage */ actions: ActionItem[]; /** The Medicine Wheel direction this stage serves */ direction: "east" | "south" | "west" | "north"; /** IDs of stages that must complete before this one */ dependencies: string[]; /** Estimated complexity based on action count and dependencies */ estimatedComplexity: "simple" | "moderate" | "complex"; } /** * A checkpoint inserted between stages for verification. */ interface Checkpoint { /** The stage ID after which this checkpoint occurs */ afterStageId: string; /** What should be verified at this checkpoint */ description: string; /** Specific criteria to validate */ validationCriteria: string[]; /** Whether a human must review before proceeding */ requiresHumanReview: boolean; } /** * A fallback strategy for when a stage fails or encounters ambiguity. */ interface FallbackStrategy { /** The stage this fallback applies to */ forStageId: string; /** Type of fallback strategy */ strategy: "retry" | "skip" | "alternative" | "escalate"; /** Human-readable description of what to do */ description: string; } /** * A complete execution plan — the final output of the PDE pipeline * (Layer 5) that describes how to execute a decomposition. */ interface ExecutionPlan { /** Unique plan identifier */ id: string; /** ID of the source decomposition */ decompositionId?: string; /** Ordered execution stages */ stages: ExecutionStage[]; /** Verification checkpoints */ checkpoints: Checkpoint[]; /** Fallback strategies for failure handling */ fallbacks: FallbackStrategy[]; /** Overall success criteria */ successCriteria: string[]; /** Overall estimated complexity */ estimatedComplexity: "simple" | "moderate" | "complex"; /** ISO timestamp */ createdAt: string; } /** * Configuration options for ExecutionPlanner. */ interface ExecutionPlannerOptions { /** Add checkpoints between direction changes (default true) */ autoCheckpoints?: boolean; /** Generate fallback strategies automatically (default true) */ autoFallbacks?: boolean; } /** * ExecutionPlanner takes a DecompositionResult and produces an ExecutionPlan * with stages, checkpoints, fallbacks, and success criteria. * * This is Layer 5 of the PDE pipeline — the bridge between decomposition * and actual execution. * * @example * ```typescript * const planner = new ExecutionPlanner(); * const plan = planner.plan(decompositionResult); * * for (const stage of plan.stages) { * console.log(`Stage: ${stage.title} (${stage.direction})`); * for (const action of stage.actions) { * console.log(` - ${action.text}`); * } * } * * for (const checkpoint of plan.checkpoints) { * console.log(`Checkpoint after ${checkpoint.afterStageId}:`); * console.log(` ${checkpoint.description}`); * } * ``` */ declare class ExecutionPlanner { private readonly autoCheckpoints; private readonly autoFallbacks; constructor(options?: ExecutionPlannerOptions); /** * Create an execution plan from a decomposition result. * Groups actions into stages, generates checkpoints and fallbacks, * and derives overall success criteria. */ plan(decomposition: DecompositionResult): ExecutionPlan; /** * Group actions into stages by direction and dependency. * Actions with the same direction and no cross-direction dependencies * are grouped together. */ groupIntoStages(actions: ActionItem[]): ExecutionStage[]; /** * Generate checkpoints between stages, especially at direction boundaries. */ generateCheckpoints(stages: ExecutionStage[]): Checkpoint[]; /** * Generate fallback strategies based on stage characteristics and ambiguities. */ generateFallbacks(stages: ExecutionStage[], ambiguities: AmbiguityFlag[]): FallbackStrategy[]; /** * Derive success criteria from the decomposition outputs and primary intent. */ deriveSuccessCriteria(decomposition: DecompositionResult): string[]; /** * Wire dependencies between stages based on the canonical direction order: * EAST → SOUTH → WEST → NORTH */ private wireInterStageDependencies; /** * Estimate complexity for a single stage based on action count * and presence of dependencies. */ private estimateStageComplexity; /** * Estimate overall plan complexity from stage complexities. */ private estimateOverallComplexity; /** * Chunk actions into groups of at most `maxSize`. */ private chunkActions; } /** * ava-langchain-prompt-decomposition * * Prompt Decomposition Engine (PDE) primitives for the Narrative Intelligence Stack. * Decomposes complex prompts through the Four Directions (Medicine Wheel): * * - EAST (Waabinong/Vision): What is being asked? * - SOUTH (Zhaawanong/Analysis): What needs to be learned? * - WEST (Epangishmok/Validation): What needs reflection? * - NORTH (Kiiwedinong/Action): What executes? * * Core Components: * - DirectionalDecomposer: Classifies prompt segments by direction * - IntentExtractor: Extracts primary + secondary intents with confidence * - DependencyMapper: Maps task dependencies and execution order * - ActionStackBuilder: Produces the final ordered execution plan * - MedicineWheelBridge: Maps directions to quadrants from relational-intelligence * * @example * ```typescript * import { * DirectionalDecomposer, * IntentExtractor, * DependencyMapper, * ActionStackBuilder, * MedicineWheelBridge, * } from "ava-langchain-prompt-decomposition"; * * const decomposer = new DirectionalDecomposer(); * const extractor = new IntentExtractor(); * const mapper = new DependencyMapper(); * const builder = new ActionStackBuilder(); * const bridge = new MedicineWheelBridge(); * * // Decompose a complex prompt * const directions = decomposer.decompose("Build a knowledge graph..."); * const intents = extractor.extract("Build a knowledge graph..."); * const graph = mapper.buildGraph(intents.secondary); * const order = mapper.computeExecutionOrder(graph); * const result = builder.build(directions, intents, order); * * // Check relational balance * const enriched = bridge.enrich(directions); * if (enriched.ceremonyRequired) { * console.log("Pause: ceremony needed before proceeding"); * } * * // Output as JSON or Markdown * console.log(builder.toJSON(result)); * console.log(builder.toMarkdown(result)); * ``` */ declare const VERSION = "0.1.0"; interface PipelineOptions { decomposer?: DecomposerOptions; extractor?: ExtractorOptions; actionStack?: ActionStackOptions; wheelBridge?: WheelBridgeOptions; } interface PipelineResult { decomposition: DecompositionResult; wheelEnriched: WheelEnrichedAnalysis; json: string; markdown: string; } /** * Run the full PDE pipeline on a prompt. * Decomposes → Extracts → Maps → Builds → Enriches */ declare function decompose(prompt: string, options?: PipelineOptions): Promise; export { ALL_DIRECTIONS, type ActionItem, ActionStackBuilder, type ActionStackOptions, type AgentDecompositionResult, AgentPDE, type AgentPDEOptions, type AmbiguityFlag, type AvailableResources, CHILD_KINDS, ChainDecomposer, type Checkpoint, type ChildEntry, type ChildKind, ComplexityAnalyzer, type ComplexitySignals, ConfidenceCalibrator, DIRECTION_KEYWORDS, DIRECTION_NAMES, DIRECTION_QUESTIONS, DIRECTION_TO_QUADRANT, type DecomposerOptions, type DecompositionMarkdownOptions, type DecompositionResult, type DecompositionStrategy, type DecompositionWithProvenance, type DependencyGraph, DependencyMapper, type DependencyNode, Direction, type DirectionalAnalysis, DirectionalDecomposer, type DirectionalInsight, type Disagreement, type EngineFallbackAttempt, type ExecutionOrder, type ExecutionPlan, ExecutionPlanner, type ExecutionPlannerOptions, type ExecutionProgress, type ExecutionStage, type ExpectedOutputs, type ExtractionContext, type ExtractorOptions, type FallbackStrategy, HybridStrategy, type IntentExtractionResult, IntentExtractor, KeywordStrategy, MedicineWheelBridge, MultiPassDecomposer, type MultiPassResult, type NarrativeBeatMapping, ONTOLOGY_CORE_MAP, type OntologyCoreConcept, PACKAGE_MAPPING, PDE_DIR, PDE_METADATA_SCHEMA_VERSION, PDE_META_FILENAME, type PdeFallbackMetadata, type PdeResolvedContext, type PdeRuntimeEngine, type PdeSessionIdSource, type PdeStorageLayout, type PdeTreeMetadata, type PipelineOptions, type PipelineResult, type PrimaryIntent, type PromptComplexity, QUADRANT_TO_DIRECTION, type RelationalQueryNode, RunnableDecomposer, type RunnableDecomposerOptions, type RunnableDecomposerResult, RunnableDirectionalAnalyzer, RunnableWheelGate, STRATEGY_METADATA_SCHEMA_VERSION, type SaveDecompositionOptions, type SecondaryIntent, SemanticStrategy, type StoredDecomposition, StrategicDecomposer, type StrategicDecomposerOptions, type StrategicDecompositionResult, type StrategyId, type StrategyMetadata, type StrategyPreferences, type StrategyResult, StrategySelector, Urgency, VERSION, type WheelBridgeOptions, type WheelEnrichedAnalysis, WheelQuadrant, actionToNarrativeBeat, appendChildEntry, buildPdeTreeMetadata, decompose, decompositionToMarkdown, ensureDirectory, extractPdeUuidFromFolderName, extractPdeUuidFromPath, extractStrategyMetadata, findPdeFolder, getPdeRoot, listDecompositions, loadDecomposition, mergeAddDirs, normalizeAddDirs, readPdeTreeMetadata, resolvePdeContext, resolvePdeContextByPath, resolvePdeFolderPath, saveDecomposition, saveDecompositionTree, saveStrategicDecomposition, strategicDecompose, strategicResultToProvenance, updatePdeTreeMetadata, writePdeTreeMetadata };