import { BaseLanguageModel } from '@langchain/core/language_models/base'; 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: ThreeUniverseProcessor, 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 (ThreeUniverseProcessor, 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"; }; }; /** * 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; 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; /** * 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, CHILD_KINDS, ChainDecomposer, type Checkpoint, type ChildEntry, type ChildKind, DIRECTION_KEYWORDS, DIRECTION_NAMES, DIRECTION_QUESTIONS, DIRECTION_TO_QUADRANT, type DecomposerOptions, type DecompositionMarkdownOptions, type DecompositionResult, type DependencyGraph, DependencyMapper, type DependencyNode, Direction, type DirectionalAnalysis, DirectionalDecomposer, type DirectionalInsight, type EngineFallbackAttempt, type ExecutionOrder, type ExecutionPlan, ExecutionPlanner, type ExecutionPlannerOptions, type ExecutionProgress, type ExecutionStage, type ExpectedOutputs, type ExtractionContext, type ExtractorOptions, type FallbackStrategy, type IntentExtractionResult, IntentExtractor, MedicineWheelBridge, 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, QUADRANT_TO_DIRECTION, type RelationalQueryNode, RunnableDecomposer, type RunnableDecomposerOptions, type RunnableDecomposerResult, RunnableDirectionalAnalyzer, RunnableWheelGate, type SaveDecompositionOptions, type SecondaryIntent, type StoredDecomposition, Urgency, VERSION, type WheelBridgeOptions, type WheelEnrichedAnalysis, WheelQuadrant, actionToNarrativeBeat, appendChildEntry, buildPdeTreeMetadata, decompose, decompositionToMarkdown, ensureDirectory, extractPdeUuidFromFolderName, extractPdeUuidFromPath, findPdeFolder, getPdeRoot, listDecompositions, loadDecomposition, mergeAddDirs, normalizeAddDirs, readPdeTreeMetadata, resolvePdeContext, resolvePdeContextByPath, resolvePdeFolderPath, saveDecomposition, saveDecompositionTree, updatePdeTreeMetadata, writePdeTreeMetadata };