@kjerneverk/riotplan-ai 1.0.0-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +731 -0
- package/dist/index.js +1963 -0
- package/dist/index.js.map +1 -0
- package/package.json +69 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/tokens.ts","../src/generator.ts","../src/tools/write-plan.ts","../src/agent-generator.ts","../src/provider-loader.ts","../src/validation.ts","../src/provenance.ts","../src/artifacts.ts"],"sourcesContent":["/**\n * Token Estimation and Budget Management\n * \n * Utilities for estimating token counts and managing prompt budgets\n */\n\nexport interface TokenBudget {\n maxTokens: number;\n evidenceFullThreshold: number; // Evidence under this size (bytes) included in full\n evidenceSummaryThreshold: number; // Evidence over this summarized\n historyFullCount: number; // Number of history events to include when under budget\n historyAbbreviatedCount: number; // Number when over budget\n}\n\nexport const DEFAULT_TOKEN_BUDGET: TokenBudget = {\n maxTokens: 40000, // Conservative default for most models\n evidenceFullThreshold: 2048, // 2KB\n evidenceSummaryThreshold: 20480, // 20KB\n historyFullCount: 15,\n historyAbbreviatedCount: 5,\n};\n\nexport interface TieringDecision {\n totalEstimatedTokens: number;\n budgetExceeded: boolean;\n evidenceTiered: {\n full: string[];\n summarized: string[];\n listOnly: string[];\n };\n historyAbbreviated: boolean;\n warnings: string[];\n}\n\n/**\n * Estimate token count from text\n * Uses character count / 4 as a reasonable approximation\n */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\n/**\n * Truncate text to a line count with ellipsis\n */\nexport function truncateToLines(text: string, lineCount: number): string {\n const lines = text.split('\\n');\n if (lines.length <= lineCount) {\n return text;\n }\n return lines.slice(0, lineCount).join('\\n') + '\\n\\n... [truncated, see full file]';\n}\n\n/**\n * Calculate tiering decisions based on artifact sizes and budget\n */\nexport function calculateTiering(\n constraints: string[],\n selectedApproach: { name: string; description: string; reasoning: string } | null,\n evidence: { name: string; content: string; size: number }[],\n historyEventCount: number,\n budget: TokenBudget = DEFAULT_TOKEN_BUDGET\n): TieringDecision {\n const decision: TieringDecision = {\n totalEstimatedTokens: 0,\n budgetExceeded: false,\n evidenceTiered: {\n full: [],\n summarized: [],\n listOnly: [],\n },\n historyAbbreviated: false,\n warnings: [],\n };\n\n // Calculate base tokens (always included)\n let baseTokens = 0;\n \n // Constraints (always full)\n for (const constraint of constraints) {\n baseTokens += estimateTokens(constraint);\n }\n \n // Selected approach (always full)\n if (selectedApproach) {\n baseTokens += estimateTokens(selectedApproach.name);\n baseTokens += estimateTokens(selectedApproach.description);\n baseTokens += estimateTokens(selectedApproach.reasoning);\n }\n \n // System prompt and structure overhead (rough estimate)\n baseTokens += 2000;\n \n decision.totalEstimatedTokens = baseTokens;\n\n // Calculate evidence tokens and tier\n let evidenceTokens = 0;\n for (const ev of evidence) {\n const fullTokens = estimateTokens(ev.content);\n \n if (ev.size < budget.evidenceFullThreshold) {\n // Tier 1: Include full\n decision.evidenceTiered.full.push(ev.name);\n evidenceTokens += fullTokens;\n } else if (ev.size < budget.evidenceSummaryThreshold) {\n // Tier 2: Summarize (first 50 lines)\n const summarized = truncateToLines(ev.content, 50);\n decision.evidenceTiered.summarized.push(ev.name);\n evidenceTokens += estimateTokens(summarized);\n } else {\n // Tier 3: List only (first 5 lines)\n const listOnly = truncateToLines(ev.content, 5);\n decision.evidenceTiered.listOnly.push(ev.name);\n evidenceTokens += estimateTokens(listOnly);\n decision.warnings.push(`Evidence file \"${ev.name}\" is very large (${Math.round(ev.size / 1024)}KB), showing first 5 lines only`);\n }\n }\n \n decision.totalEstimatedTokens += evidenceTokens;\n\n // Calculate history tokens\n const avgEventTokens = 50; // Rough estimate per event\n const historyTokens = historyEventCount * avgEventTokens;\n decision.totalEstimatedTokens += historyTokens;\n\n // Check if we exceeded budget\n if (decision.totalEstimatedTokens > budget.maxTokens) {\n decision.budgetExceeded = true;\n \n // Abbreviate history if needed\n if (historyEventCount > budget.historyAbbreviatedCount) {\n decision.historyAbbreviated = true;\n const savedTokens = (historyEventCount - budget.historyAbbreviatedCount) * avgEventTokens;\n decision.totalEstimatedTokens -= savedTokens;\n decision.warnings.push(`History abbreviated to ${budget.historyAbbreviatedCount} most recent events (was ${historyEventCount})`);\n }\n }\n\n // Add summary warnings\n if (decision.evidenceTiered.summarized.length > 0) {\n decision.warnings.push(`${decision.evidenceTiered.summarized.length} evidence file(s) summarized to manage token budget`);\n }\n\n return decision;\n}\n\n/**\n * Apply tiering decisions to evidence array\n */\nexport function applyEvidenceTiering(\n evidence: { name: string; content: string; size: number }[],\n decision: TieringDecision\n): { name: string; content: string; size: number; tiered?: 'summarized' | 'listOnly' }[] {\n return evidence.map(ev => {\n if (decision.evidenceTiered.summarized.includes(ev.name)) {\n return {\n ...ev,\n content: truncateToLines(ev.content, 50),\n tiered: 'summarized' as const,\n };\n } else if (decision.evidenceTiered.listOnly.includes(ev.name)) {\n return {\n ...ev,\n content: truncateToLines(ev.content, 5),\n tiered: 'listOnly' as const,\n };\n }\n return ev;\n });\n}\n","/**\n * AI Plan Generator\n * \n * Generates plan content using LLM providers\n */\n\nimport type { Provider, Request, ExecutionOptions } from './types.js';\nimport { \n calculateTiering, \n applyEvidenceTiering, \n DEFAULT_TOKEN_BUDGET,\n type TokenBudget,\n type TieringDecision \n} from './tokens.js';\n\nexport interface GeneratedPlan {\n summary: string;\n approach: string;\n successCriteria: string;\n steps: GeneratedStep[];\n analysis?: PlanAnalysis; // Optional for backward compatibility\n}\n\nexport interface GenerationResult {\n plan: GeneratedPlan;\n tiering?: TieringDecision;\n}\n\nexport interface PlanAnalysis {\n constraintAnalysis: ConstraintAnalysis[];\n evidenceAnalysis?: EvidenceAnalysis[];\n approachAnalysis?: ApproachAnalysis;\n risks?: string[];\n}\n\nexport interface ConstraintAnalysis {\n constraint: string;\n understanding: string;\n plannedApproach: string;\n}\n\nexport interface EvidenceAnalysis {\n evidenceFile: string;\n keyFindings: string;\n impactOnPlan: string;\n}\n\nexport interface ApproachAnalysis {\n selectedApproach: string;\n commitments: string;\n implementationStrategy: string;\n}\n\nexport interface GeneratedStep {\n number: number;\n title: string;\n objective: string;\n background: string;\n tasks: GeneratedTask[];\n acceptanceCriteria: string[];\n testing: string;\n filesChanged: string[];\n notes: string;\n provenance?: StepProvenance; // Optional for backward compatibility\n}\n\nexport interface StepProvenance {\n constraintsAddressed?: string[];\n evidenceUsed?: string[];\n rationale?: string;\n}\n\nexport interface GeneratedTask {\n id: string;\n description: string;\n}\n\nexport interface GenerationContext {\n planName: string;\n description: string;\n elaborations?: string[];\n stepCount?: number;\n // Structured artifact fields for artifact-aware generation\n constraints?: string[];\n questions?: string[];\n selectedApproach?: {\n name: string;\n description: string;\n reasoning: string;\n };\n evidence?: {\n name: string;\n content: string; // full or summarized\n size: number;\n }[];\n historyContext?: {\n recentEvents: { type: string; timestamp: string; summary: string }[];\n totalEvents: number;\n };\n ideaContent?: string;\n shapingContent?: string;\n // Token budget configuration\n tokenBudget?: {\n maxTokens?: number;\n evidenceFullThreshold?: number;\n evidenceSummaryThreshold?: number;\n historyFullCount?: number;\n historyAbbreviatedCount?: number;\n };\n // Codebase context for injection into prompts (project structure, key files)\n codebaseContext?: string;\n // Catalyst content for plan generation\n catalystContent?: {\n constraints: string;\n domainKnowledge: string;\n outputTemplates: string;\n processGuidance: string;\n questions: string;\n validationRules: string;\n appliedCatalysts: string[]; // IDs for traceability\n };\n}\n\n/**\n * Progress callback for plan generation\n */\nexport type GenerationProgressCallback = (event: {\n type: 'started' | 'streaming' | 'parsing' | 'complete';\n charsReceived?: number;\n message?: string;\n}) => void;\n\n/**\n * Extended options for plan generation\n */\nexport interface GenerationOptionsWithProgress extends ExecutionOptions {\n onProgress?: GenerationProgressCallback;\n}\n\nexport const PLAN_GENERATION_RESPONSE_SCHEMA = {\n type: 'object',\n properties: {\n analysis: {\n type: 'object',\n properties: {\n constraintAnalysis: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n constraint: { type: 'string' },\n understanding: { type: 'string' },\n plannedApproach: { type: 'string' },\n },\n required: ['constraint', 'understanding', 'plannedApproach'],\n },\n },\n evidenceAnalysis: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n evidenceFile: { type: 'string' },\n keyFindings: { type: 'string' },\n impactOnPlan: { type: 'string' },\n },\n required: ['evidenceFile', 'keyFindings', 'impactOnPlan'],\n },\n },\n approachAnalysis: {\n type: 'object',\n properties: {\n selectedApproach: { type: 'string' },\n commitments: { type: 'string' },\n implementationStrategy: { type: 'string' },\n },\n },\n risks: {\n type: 'array',\n items: { type: 'string' },\n },\n },\n required: ['constraintAnalysis'],\n },\n summary: { type: 'string' },\n approach: { type: 'string' },\n successCriteria: { type: 'string' },\n steps: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n number: { type: 'number' },\n title: { type: 'string' },\n objective: { type: 'string' },\n background: { type: 'string' },\n tasks: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n description: { type: 'string' },\n },\n required: ['id', 'description'],\n },\n },\n acceptanceCriteria: {\n type: 'array',\n items: { type: 'string' },\n },\n testing: { type: 'string' },\n filesChanged: {\n type: 'array',\n items: { type: 'string' },\n },\n notes: { type: 'string' },\n provenance: {\n type: 'object',\n properties: {\n constraintsAddressed: {\n type: 'array',\n items: { type: 'string' },\n },\n evidenceUsed: {\n type: 'array',\n items: { type: 'string' },\n },\n rationale: { type: 'string' },\n },\n },\n },\n required: ['number', 'title', 'objective', 'background', 'tasks', 'acceptanceCriteria', 'testing', 'filesChanged', 'notes'],\n },\n },\n },\n required: ['analysis', 'summary', 'approach', 'successCriteria', 'steps'],\n} as const;\n\nexport function getPlanGenerationSystemPrompt(): string {\n return SYSTEM_PROMPT;\n}\n\n/**\n * Generate a plan using AI\n */\nexport async function generatePlan(\n context: GenerationContext,\n provider: Provider,\n options: GenerationOptionsWithProgress = {}\n): Promise<GenerationResult> {\n // Apply token budget tiering if artifacts are present\n let tieringDecision: TieringDecision | undefined;\n let tieredContext = context;\n \n if (context.constraints || context.evidence || context.historyContext) {\n const budget: TokenBudget = {\n ...DEFAULT_TOKEN_BUDGET,\n ...context.tokenBudget,\n };\n \n tieringDecision = calculateTiering(\n context.constraints || [],\n context.selectedApproach || null,\n context.evidence || [],\n context.historyContext?.recentEvents.length || 0,\n budget\n );\n \n // Apply evidence tiering\n if (context.evidence && context.evidence.length > 0) {\n const tieredEvidence = applyEvidenceTiering(context.evidence, tieringDecision);\n tieredContext = {\n ...context,\n evidence: tieredEvidence,\n };\n }\n \n // Apply history abbreviation if needed\n if (tieringDecision.historyAbbreviated && context.historyContext) {\n const abbreviatedCount = budget.historyAbbreviatedCount || 5;\n tieredContext = {\n ...tieredContext,\n historyContext: {\n ...context.historyContext,\n recentEvents: context.historyContext.recentEvents.slice(0, abbreviatedCount),\n },\n };\n }\n }\n \n const prompt = buildPlanPrompt(tieredContext);\n \n const request: Request = {\n model: options.model || 'claude-sonnet-4-5',\n messages: [\n {\n role: 'system',\n content: SYSTEM_PROMPT,\n },\n {\n role: 'user',\n content: prompt,\n },\n ],\n responseFormat: {\n type: 'json_schema',\n json_schema: {\n name: 'plan_generation',\n description: 'Generate a detailed execution plan',\n schema: PLAN_GENERATION_RESPONSE_SCHEMA,\n },\n },\n addMessage: function(message) {\n this.messages.push(message);\n },\n };\n\n // Use streaming to avoid Anthropic SDK timeout errors for long requests\n // The SDK throws an error if max_tokens is high and streaming is not used\n let responseContent = '';\n const { onProgress } = options;\n \n // Notify start\n onProgress?.({ type: 'started', message: 'Generating plan...' });\n \n if (provider.executeStream) {\n // Use streaming and collect the full response\n let lastProgressUpdate = Date.now();\n for await (const chunk of provider.executeStream(request, options)) {\n if (chunk.type === 'text' && chunk.text) {\n responseContent += chunk.text;\n \n // Report progress every 500ms to avoid flooding\n const now = Date.now();\n if (now - lastProgressUpdate > 500) {\n onProgress?.({ \n type: 'streaming', \n charsReceived: responseContent.length,\n message: `Generating... (${responseContent.length} chars)`\n });\n lastProgressUpdate = now;\n }\n }\n }\n } else {\n // Fallback to non-streaming for providers that don't support it\n const response = await provider.execute(request, options);\n responseContent = response.content;\n }\n \n // Notify parsing\n onProgress?.({ type: 'parsing', message: 'Parsing generated plan...' });\n \n const plan = parsePlanResponse(responseContent, context.stepCount || 5);\n \n // Notify complete\n onProgress?.({ type: 'complete', message: 'Plan generation complete' });\n \n return {\n plan,\n tiering: tieringDecision,\n };\n}\n\n/**\n * System prompt for artifact-aware plan generation\n * \n * This prompt establishes that plan generation must be grounded in the provided artifacts,\n * not general knowledge. Constraints are non-negotiable, evidence should inform design,\n * and the selected approach defines the implementation strategy.\n */\nconst SYSTEM_PROMPT = `You are an expert project planner generating an execution plan that MUST be grounded in the provided artifacts.\n\n## Dual Audience\n\nYour plan serves two audiences: (1) a human reviewer who will read the plan and judge your design choices BEFORE implementation, and (2) an LLM that will execute each step. Both need you to SHOW your thinking with code samples, not just describe it in prose.\n\n## Core Principles\n\n1. **Constraints are non-negotiable**: Every constraint from IDEA.md MUST be addressed by at least one step. Do not ignore or work around constraints.\n\n2. **Evidence informs design**: Evidence files contain research, analysis, code snippets, and findings gathered during idea exploration. Use this evidence to inform step design - reference specific findings, not general knowledge.\n\n3. **Selected approach is the strategy**: If a selected approach is provided from SHAPING.md, your plan MUST implement that approach, not an alternative. The approach was chosen deliberately with tradeoffs considered.\n\n4. **History shows evolution**: The history context shows how thinking evolved during exploration. Respect decisions that were made and questions that were answered.\n\n5. **Be concrete, not generic**: Reference specific files, functions, code patterns from the evidence. Don't generate generic steps that could apply to any project.\n\n6. **Use portable file paths**: In \\`filesChanged\\`, always use repository/project-root-relative paths (e.g., \\`src/module/file.ts\\`), never absolute machine-specific paths.\n\n7. **Show, don't tell**: Every task that introduces an interface, schema, config, or significant function MUST include a code sketch in its description — key method signatures, table schemas, type definitions. Not the full implementation, just enough for a human to evaluate the design and say \"yes\" or \"change X.\"\n\n## Output Requirements\n\n- Generate steps that are directly traceable to the artifacts\n- Each step should cite which constraints it addresses\n- Reference evidence when it informs a step's design\n- Be specific about files, functions, and code changes\n- Include sample code in task descriptions (markdown code blocks with language tags)\n\nCRITICAL: You must output ONLY valid JSON. Do not include any text before or after the JSON object. Ensure all strings are properly escaped. Code blocks in task descriptions should use escaped backticks.`;\n\n/**\n * Build the user prompt for plan generation\n * \n * If structured artifact fields are present (constraints, evidence, selectedApproach, history),\n * constructs a rich prompt with labeled sections. Otherwise, falls back to the simple\n * description-based prompt for backward compatibility.\n */\nexport function buildPlanPrompt(context: GenerationContext): string {\n // Check if we have structured artifacts to use\n const hasStructuredArtifacts = \n (context.constraints && context.constraints.length > 0) ||\n (context.evidence && context.evidence.length > 0) ||\n context.selectedApproach ||\n (context.historyContext && context.historyContext.recentEvents.length > 0);\n \n if (hasStructuredArtifacts) {\n return buildArtifactAwarePrompt(context);\n } else {\n return buildLegacyPrompt(context);\n }\n}\n\n/**\n * Build artifact-aware prompt with labeled sections\n */\nfunction buildArtifactAwarePrompt(context: GenerationContext): string {\n const sections: string[] = [];\n \n // == PLAN NAME ==\n sections.push(`== PLAN NAME ==\n${context.planName}`);\n \n // == CORE CONCEPT ==\n // Extract just the core concept, not the full IDEA.md dump\n let coreConcept = context.description;\n // If description contains the full context dump, try to extract just the first part\n const contextMarker = coreConcept.indexOf('\\n\\n--- IDEA CONTEXT ---');\n if (contextMarker !== -1) {\n coreConcept = coreConcept.substring(0, contextMarker).trim();\n }\n sections.push(`== CORE CONCEPT ==\n${coreConcept}`);\n \n // == CONSTRAINTS (MUST HONOR ALL) ==\n if (context.constraints && context.constraints.length > 0) {\n const constraintsList = context.constraints\n .map((c, i) => `${i + 1}. ${c}`)\n .join('\\n');\n sections.push(`== CONSTRAINTS (MUST HONOR ALL) ==\nThe following constraints are NON-NEGOTIABLE. Every constraint must be addressed by at least one step in the plan.\n\n${constraintsList}`);\n }\n \n // == CATALYST CONSTRAINTS ==\n if (context.catalystContent?.constraints) {\n sections.push(`== CATALYST CONSTRAINTS ==\nThe following constraints come from applied catalysts and must also be honored:\n\n${context.catalystContent.constraints}`);\n }\n \n // == SELECTED APPROACH ==\n if (context.selectedApproach) {\n sections.push(`== SELECTED APPROACH ==\nThis approach was selected during shaping. Your plan MUST implement this approach, not an alternative.\n\n**Name**: ${context.selectedApproach.name}\n\n**Description**: ${context.selectedApproach.description}\n\n**Reasoning**: ${context.selectedApproach.reasoning}`);\n }\n \n // == EVIDENCE ==\n if (context.evidence && context.evidence.length > 0) {\n const evidenceContent = context.evidence\n .map(e => {\n const content = e.content.trim();\n const tiered = (e as any).tiered;\n \n let header = `### ${e.name}`;\n if (tiered === 'summarized') {\n header += ' (summarized for token budget)';\n } else if (tiered === 'listOnly') {\n header += ' (preview only - full content available)';\n }\n \n return `${header}\\n${content}`;\n })\n .join('\\n\\n');\n sections.push(`== EVIDENCE ==\nThe following evidence was gathered during idea exploration. Use these findings to inform step design.\n\n${evidenceContent}`);\n }\n \n // == HISTORY CONTEXT ==\n if (context.historyContext && context.historyContext.recentEvents.length > 0) {\n const historyList = context.historyContext.recentEvents\n .map(e => `- [${e.type}] ${e.summary}`)\n .join('\\n');\n sections.push(`== HISTORY CONTEXT ==\nRecent events from idea exploration (${context.historyContext.totalEvents} total events):\n\n${historyList}`);\n }\n \n // == QUESTIONS (for context) ==\n if (context.questions && context.questions.length > 0) {\n const questionsList = context.questions\n .map((q, i) => `${i + 1}. ${q}`)\n .join('\\n');\n sections.push(`== OPEN QUESTIONS ==\nThese questions were raised during exploration. Consider them when designing steps.\n\n${questionsList}`);\n }\n \n // == CATALYST DOMAIN KNOWLEDGE ==\n if (context.catalystContent?.domainKnowledge) {\n sections.push(`== CATALYST DOMAIN KNOWLEDGE ==\nThe following domain knowledge comes from applied catalysts and provides context about the domain, organization, or technology:\n\n${context.catalystContent.domainKnowledge}`);\n }\n \n // == CATALYST OUTPUT TEMPLATES ==\n if (context.catalystContent?.outputTemplates) {\n sections.push(`== CATALYST OUTPUT TEMPLATES ==\nThe following output templates define expected deliverables that the plan should produce:\n\n${context.catalystContent.outputTemplates}`);\n }\n \n // == CATALYST PROCESS GUIDANCE ==\n if (context.catalystContent?.processGuidance) {\n sections.push(`== CATALYST PROCESS GUIDANCE ==\nThe following process guidance from applied catalysts should inform how the plan is structured:\n\n${context.catalystContent.processGuidance}`);\n }\n \n // == CATALYST QUESTIONS ==\n if (context.catalystContent?.questions) {\n sections.push(`== CATALYST QUESTIONS ==\nThe following questions from applied catalysts should be considered during planning:\n\n${context.catalystContent.questions}`);\n }\n \n // == CATALYST VALIDATION RULES ==\n if (context.catalystContent?.validationRules) {\n sections.push(`== CATALYST VALIDATION RULES ==\nThe following validation rules from applied catalysts define post-creation checks:\n\n${context.catalystContent.validationRules}`);\n }\n \n // == APPLIED CATALYSTS ==\n if (context.catalystContent?.appliedCatalysts && context.catalystContent.appliedCatalysts.length > 0) {\n const catalystList = context.catalystContent.appliedCatalysts\n .map((id, i) => `${i + 1}. ${id}`)\n .join('\\n');\n sections.push(`== APPLIED CATALYSTS ==\nThis plan was generated with the following catalysts applied (in order):\n\n${catalystList}\n\nThe catalyst content above has influenced the constraints, domain knowledge, output expectations, and process guidance for this plan.`);\n }\n \n // == GENERATION INSTRUCTIONS ==\n sections.push(`== GENERATION INSTRUCTIONS ==\n\n**CRITICAL: You must complete the 'analysis' section FIRST before generating steps.**\n\nThe analysis section demonstrates your understanding of the artifacts and serves as your reasoning gate. Fill it out completely:\n\n1. **constraintAnalysis**: For EACH constraint listed above, provide:\n - constraint: The exact constraint text\n - understanding: What this constraint means and why it exists\n - plannedApproach: How you will address this constraint in the plan\n\n2. **evidenceAnalysis** (if evidence provided): For each evidence file that informs the plan:\n - evidenceFile: The evidence file name\n - keyFindings: The most important findings from this evidence\n - impactOnPlan: How these findings will shape the implementation steps\n\n3. **approachAnalysis** (if selected approach provided):\n - selectedApproach: The approach name\n - commitments: What this approach commits us to doing\n - implementationStrategy: How the steps will implement this approach\n\n4. **risks**: Any risks or challenges you foresee in implementing this plan\n\n**After completing the analysis, generate ${context.stepCount || 5} implementation steps following these requirements:**\n\n1. **Address every constraint**: Each constraint from your analysis MUST be addressed by at least one step\n2. **Implement the selected approach**: Follow the implementation strategy from your analysis\n3. **Reference evidence**: Use the key findings from your evidence analysis to inform step design\n4. **Be concrete**: Reference specific files, functions, and code patterns from the evidence\n5. **Include provenance**: For each step, fill the provenance field with:\n - constraintsAddressed: List which constraints this step addresses\n - evidenceUsed: List which evidence files informed this step\n - rationale: Explain why this step exists and how it connects to the idea\n\nFor each step, provide:\n- A clear title\n- Objective (what this step accomplishes)\n- Background (context and prerequisites, referencing evidence where relevant)\n- Specific tasks with **sample code** — every task that introduces an interface, schema, config, or significant function MUST include a code sketch in the description using markdown code blocks. Don't write the full implementation, just enough for a human to judge the design: key method signatures, table schemas, type definitions, config formats. This is a plan that a human will review before execution.\n- Acceptance criteria (measurable verification)\n- Testing approach\n- Files that will be changed\n- Notes (including which constraints are addressed)\n\nIMPORTANT: Output ONLY the JSON object, with no markdown formatting, no code blocks, no additional text.\n\nJSON structure:\n{\n \"analysis\": {\n \"constraintAnalysis\": [\n {\n \"constraint\": \"exact constraint text\",\n \"understanding\": \"what this constraint means\",\n \"plannedApproach\": \"how the plan will address this\"\n }\n ],\n \"evidenceAnalysis\": [\n {\n \"evidenceFile\": \"evidence file name\",\n \"keyFindings\": \"important findings from this evidence\",\n \"impactOnPlan\": \"how these findings shape the plan\"\n }\n ],\n \"approachAnalysis\": {\n \"selectedApproach\": \"approach name\",\n \"commitments\": \"what this approach commits to\",\n \"implementationStrategy\": \"how steps will implement this\"\n },\n \"risks\": [\"risk 1\", \"risk 2\"]\n },\n \"summary\": \"executive summary explaining what this plan accomplishes and how it addresses the constraints\",\n \"approach\": \"how the plan implements the selected approach (or your chosen approach if none selected)\",\n \"successCriteria\": \"how we'll know all constraints are satisfied and the project is complete\",\n \"steps\": [\n {\n \"number\": 1,\n \"title\": \"Step Title\",\n \"objective\": \"what this step accomplishes\",\n \"background\": \"context, prerequisites, and relevant evidence\",\n \"tasks\": [\n {\"id\": \"01.1\", \"description\": \"specific task\"},\n {\"id\": \"01.2\", \"description\": \"another task\"}\n ],\n \"acceptanceCriteria\": [\"criterion 1\", \"criterion 2\"],\n \"testing\": \"how to verify this step\",\n \"filesChanged\": [\"file1.ts\", \"file2.ts\"],\n \"notes\": \"additional notes\",\n \"provenance\": {\n \"constraintsAddressed\": [\"constraint 1\", \"constraint 2\"],\n \"evidenceUsed\": [\"evidence file 1\", \"evidence file 2\"],\n \"rationale\": \"why this step exists and how it connects to the idea\"\n }\n }\n ]\n}`);\n \n return sections.join('\\n\\n');\n}\n\n/**\n * Build legacy prompt for backward compatibility\n * Used when no structured artifacts are present\n */\nfunction buildLegacyPrompt(context: GenerationContext): string {\n let prompt = `Create a detailed execution plan for the following project:\n\n**Project Name**: ${context.planName}\n\n**Description**:\n${context.description}\n`;\n\n if (context.elaborations && context.elaborations.length > 0) {\n prompt += `\\n**Additional Context**:\\n`;\n context.elaborations.forEach((elab, i) => {\n prompt += `\\n${i + 1}. ${elab}\\n`;\n });\n }\n\n prompt += `\\n**Requirements**:\n- Generate ${context.stepCount || 5} steps\n- Each step should be focused and achievable\n- Provide specific tasks, not generic placeholders\n- Include concrete acceptance criteria\n- Consider what files or components will be affected\n\nPlease provide:\n1. Executive Summary (2-3 paragraphs explaining what this plan accomplishes)\n2. Approach (how you'll tackle this work, key decisions)\n3. Success Criteria (how we'll know the project is complete)\n4. Detailed steps with:\n - Step title\n - Objective (what this step accomplishes)\n - Background (context needed)\n - Tasks (specific actions to take)\n - Acceptance criteria (how to verify completion)\n - Testing approach\n - Files that will be changed\n - Any notes or considerations\n\nIMPORTANT: Output ONLY the JSON object below, with no markdown formatting, no code blocks, no additional text. Ensure all strings use proper JSON escaping for quotes and newlines.\n\nJSON structure:\n{\n \"summary\": \"executive summary text\",\n \"approach\": \"approach description\",\n \"successCriteria\": \"success criteria description\",\n \"steps\": [\n {\n \"number\": 1,\n \"title\": \"Step Title\",\n \"objective\": \"what this step accomplishes\",\n \"background\": \"context and prerequisites\",\n \"tasks\": [\n {\"id\": \"01.1\", \"description\": \"specific task\"},\n {\"id\": \"01.2\", \"description\": \"another task\"}\n ],\n \"acceptanceCriteria\": [\"criterion 1\", \"criterion 2\"],\n \"testing\": \"how to verify this step\",\n \"filesChanged\": [\"file1.ts\", \"file2.ts\"],\n \"notes\": \"additional notes\"\n }\n ]\n}`;\n\n return prompt;\n}\n\n/**\n * Parse the LLM response into a structured plan\n */\nfunction stripMarkdownFences(content: string): string {\n const trimmed = content.trim();\n if (!trimmed.startsWith('```')) return trimmed;\n\n const firstNewline = trimmed.indexOf('\\n');\n if (firstNewline === -1) return trimmed;\n const closingFence = trimmed.lastIndexOf('```');\n if (closingFence <= firstNewline) return trimmed;\n return trimmed.slice(firstNewline + 1, closingFence).trim();\n}\n\nfunction extractFirstJsonObject(content: string): string | null {\n let inString = false;\n let escape = false;\n let depth = 0;\n let start = -1;\n\n for (let i = 0; i < content.length; i++) {\n const ch = content[i];\n if (escape) {\n escape = false;\n continue;\n }\n if (ch === '\\\\') {\n escape = true;\n continue;\n }\n if (ch === '\"') {\n inString = !inString;\n continue;\n }\n if (inString) continue;\n if (ch === '{') {\n if (depth === 0) start = i;\n depth += 1;\n continue;\n }\n if (ch === '}') {\n if (depth === 0) continue;\n depth -= 1;\n if (depth === 0 && start !== -1) {\n return content.slice(start, i + 1);\n }\n }\n }\n return null;\n}\n\nexport function parsePlanResponse(content: string, _stepCount: number): GeneratedPlan {\n try {\n const cleanedContent = stripMarkdownFences(content);\n const jsonCandidate = extractFirstJsonObject(cleanedContent) || cleanedContent;\n const parsed = JSON.parse(jsonCandidate);\n \n // Validate structure\n if (!parsed.summary || !parsed.approach || !parsed.successCriteria || !parsed.steps) {\n throw new Error('Invalid plan structure: missing required fields');\n }\n \n // Analysis field is optional for backward compatibility\n // If present, it should have at least constraintAnalysis\n if (parsed.analysis && !parsed.analysis.constraintAnalysis) {\n throw new Error('Invalid analysis structure: missing constraintAnalysis');\n }\n \n // Ensure we have the right number of steps\n // Note: AI may generate different number of steps than requested\n \n return parsed as GeneratedPlan;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n throw new Error(\n `Failed to parse plan response: ${message}. ` +\n 'Expected a valid JSON object (markdown fences are allowed).'\n );\n }\n}\n\n/**\n * Format a generated plan into markdown content for SUMMARY.md\n */\nexport function formatSummary(plan: GeneratedPlan, planName: string): string {\n const title = planName.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');\n \n return `# ${title} - Summary\n\n## Executive Summary\n\n${plan.summary}\n\n## Approach\n\n${plan.approach}\n\n## Success Criteria\n\n${plan.successCriteria}\n`;\n}\n\n/**\n * Format step into markdown content\n */\nexport function formatStep(step: GeneratedStep): string {\n const num = String(step.number).padStart(2, '0');\n \n let content = `# Step ${num}: ${step.title}\n\n## Objective\n\n${step.objective}\n\n## Background\n\n${step.background}\n\n## Tasks\n\n`;\n\n step.tasks.forEach(task => {\n content += `### ${task.id} ${task.description}\\n\\n`;\n });\n\n content += `## Acceptance Criteria\n\n`;\n step.acceptanceCriteria.forEach(criterion => {\n content += `- [ ] ${criterion}\\n`;\n });\n\n content += `\\n## Testing\n\n${step.testing}\n\n## Files Changed\n\n`;\n step.filesChanged.forEach(file => {\n content += `- ${file}\\n`;\n });\n\n if (step.notes) {\n content += `\\n## Notes\n\n${step.notes}\n`;\n }\n\n return content;\n}\n","/**\n * write_plan tool - Agent calls this to submit a generated plan\n * \n * Uses a factory pattern: createWritePlanTool() returns both the tool\n * (for the agent to call) and a promise (for the caller to await).\n * When the agent calls write_plan, it resolves the promise with the plan.\n */\n\nimport type { Tool } from '@kjerneverk/agentic';\nimport type { GeneratedPlan } from '../generator.js';\n\n/**\n * Result of creating a write_plan tool\n */\nexport interface WritePlanToolResult {\n /** The tool to register with the agent's ToolRegistry */\n tool: Tool;\n /** Promise that resolves when the agent calls write_plan */\n planPromise: Promise<GeneratedPlan>;\n}\n\n/**\n * Create a write_plan tool with a connected promise.\n * \n * The caller awaits `planPromise` while the agent explores the codebase.\n * When the agent is ready, it calls `write_plan` with the plan JSON,\n * which resolves the promise and returns the plan to the caller.\n */\nexport function createWritePlanTool(): WritePlanToolResult {\n let resolvePlan: (plan: GeneratedPlan) => void;\n let rejectPlan: (error: Error) => void;\n \n const planPromise = new Promise<GeneratedPlan>((resolve, reject) => {\n resolvePlan = resolve;\n rejectPlan = reject;\n });\n\n const tool: Tool = {\n name: 'write_plan',\n description: `Submit the completed execution plan. Call this ONCE when you have finished exploring the codebase and are ready to submit your plan.\n\nThe plan_json parameter must be a valid JSON string with this structure:\n{\n \"analysis\": {\n \"constraintAnalysis\": [{ \"constraint\": \"...\", \"understanding\": \"...\", \"plannedApproach\": \"...\" }],\n \"evidenceAnalysis\": [{ \"evidenceFile\": \"...\", \"keyFindings\": \"...\", \"impactOnPlan\": \"...\" }],\n \"approachAnalysis\": { \"selectedApproach\": \"...\", \"commitments\": \"...\", \"implementationStrategy\": \"...\" },\n \"risks\": [\"...\"]\n },\n \"summary\": \"Executive summary of what this plan accomplishes\",\n \"approach\": \"How the plan implements the selected approach\",\n \"successCriteria\": \"How we'll know the project is complete\",\n \"steps\": [{\n \"number\": 1,\n \"title\": \"Step Title\",\n \"objective\": \"What this step accomplishes\",\n \"background\": \"Context, prerequisites, and relevant evidence\",\n \"tasks\": [{ \"id\": \"01.1\", \"description\": \"Specific task with file paths and code references\" }],\n \"acceptanceCriteria\": [\"Measurable criterion 1\"],\n \"testing\": \"How to verify this step\",\n \"filesChanged\": [\"src/actual/file.ts\"],\n \"notes\": \"Additional notes\",\n \"provenance\": {\n \"constraintsAddressed\": [\"constraint text\"],\n \"evidenceUsed\": [\"evidence file\"],\n \"rationale\": \"Why this step exists\"\n }\n }]\n}\n\nIMPORTANT: Every step MUST include real file paths in filesChanged, reference actual interfaces/classes by name, and describe concrete code changes based on your codebase exploration.`,\n parameters: {\n type: 'object',\n properties: {\n plan_json: {\n type: 'string',\n description: 'The complete plan as a JSON string matching the GeneratedPlan schema described above.',\n },\n },\n required: ['plan_json'],\n },\n category: 'planning',\n cost: 'cheap',\n execute: async (params: { plan_json: string }) => {\n try {\n const parsed = JSON.parse(params.plan_json);\n \n // Validate required top-level fields\n if (!parsed.summary || !parsed.approach || !parsed.successCriteria || !parsed.steps) {\n const missing = [];\n if (!parsed.summary) missing.push('summary');\n if (!parsed.approach) missing.push('approach');\n if (!parsed.successCriteria) missing.push('successCriteria');\n if (!parsed.steps) missing.push('steps');\n return `Error: Missing required fields: ${missing.join(', ')}. Please include all required fields and call write_plan again.`;\n }\n \n // Validate steps array\n if (!Array.isArray(parsed.steps) || parsed.steps.length === 0) {\n return 'Error: steps must be a non-empty array. Please generate at least one step and call write_plan again.';\n }\n \n // Validate each step has required fields\n for (const step of parsed.steps) {\n if (!step.number || !step.title || !step.objective) {\n return `Error: Step ${step.number || '?'} is missing required fields (number, title, objective). Please fix and call write_plan again.`;\n }\n if (!step.tasks || !Array.isArray(step.tasks) || step.tasks.length === 0) {\n return `Error: Step ${step.number} has no tasks. Each step must have at least one concrete task. Please fix and call write_plan again.`;\n }\n if (!step.filesChanged || !Array.isArray(step.filesChanged) || step.filesChanged.length === 0) {\n return `Error: Step ${step.number} has no filesChanged. Each step must list specific files that will be modified. Use your codebase exploration to identify real file paths. Please fix and call write_plan again.`;\n }\n }\n \n // Plan is valid - resolve the promise\n resolvePlan!(parsed as GeneratedPlan);\n \n return `Plan accepted with ${parsed.steps.length} steps. Plan generation complete.`;\n } catch (parseError) {\n if (parseError instanceof SyntaxError) {\n return `Error: Invalid JSON in plan_json. ${parseError.message}. Please fix the JSON and call write_plan again.`;\n }\n return `Error: ${parseError instanceof Error ? parseError.message : 'Unknown error'}. Please fix and call write_plan again.`;\n }\n },\n };\n\n // Attach reject for timeout cleanup\n (tool as any)._rejectPlan = rejectPlan!;\n\n return { tool, planPromise };\n}\n","/**\n * Agent-Powered Plan Generator\n * \n * Uses an AgentLoop with read-only codebase tools to generate plans\n * that are grounded in the actual project code. The agent explores\n * the codebase, reads files, searches for patterns, then calls\n * write_plan with a structured plan.\n * \n * This replaces the one-shot LLM call in generator.ts with a multi-turn\n * agent session that produces higher-quality, codebase-aware plans.\n */\n\nimport { AgentLoop, ToolRegistry, ConversationManager } from '@kjerneverk/agentic';\nimport type { AgentProvider, Tool } from '@kjerneverk/agentic';\nimport { createRequest } from '@kjerneverk/execution';\nimport type { Provider } from './types.js';\nimport type { GeneratedPlan, GenerationContext, GenerationResult, GenerationOptionsWithProgress } from './generator.js';\nimport { createWritePlanTool } from './tools/write-plan.js';\nimport {\n calculateTiering,\n applyEvidenceTiering,\n DEFAULT_TOKEN_BUDGET,\n type TokenBudget,\n type TieringDecision,\n} from './tokens.js';\n\n/**\n * Default max iterations for the agent loop.\n * The agent needs room to explore (read files, grep, query index)\n * but shouldn't run forever. 30 iterations is ~15 tool calls\n * which is enough to explore a medium codebase and generate a plan.\n */\nconst DEFAULT_MAX_ITERATIONS = 30;\n\n/**\n * System prompt for the agent-powered plan generator.\n * \n * This instructs the agent to explore the codebase using tools,\n * then generate a plan grounded in what it finds.\n */\nconst AGENT_SYSTEM_PROMPT = `You are an expert project planner generating a detailed execution plan. You have access to codebase tools that let you explore the actual project.\n\n## Dual Audience\n\nYour plan serves TWO audiences:\n\n1. **A human reviewer** who wants to see your design thinking, judge your approach, and give feedback BEFORE implementation begins. They need sample code, interface sketches, and schema examples — enough to form an opinion and say \"yes, that's the right approach\" or \"no, change X.\"\n\n2. **An LLM executor** who will implement each step. They need precise file paths, interface names, and concrete task descriptions.\n\nBoth audiences need you to SHOW, not just TELL. Don't say \"create a storage interface\" — show a draft of the interface with key method signatures. Don't say \"design a schema\" — show the schema. You don't have to write every line, but include enough sample code that a reader can evaluate your design choices.\n\n## Your Workflow\n\n1. **EXPLORE the codebase** — Use your tools to understand the project:\n - **START with \\`query_index\\`** — it returns the full project structure, all packages, and exported symbols in a single call (the index is pre-built and cached, so this is instant). Use queries like \"packages\", \"find file generator\", or \"export AgentLoop\".\n - Then use \\`read_file\\` to examine specific interfaces, types, and implementations\n - Use \\`grep\\` to find usage patterns and references\n - Use \\`file_outline\\` to understand a file's structure without reading every line\n - Use \\`list_files\\` only if you need directory contents not covered by the index\n\n2. **ANALYZE the artifacts** — Study the plan artifacts in the user message:\n - Constraints are NON-NEGOTIABLE — every one must be addressed\n - Evidence contains research and findings — use them to inform design\n - The selected approach defines the strategy — implement it, not an alternative\n - History shows how thinking evolved — respect past decisions\n\n3. **DESIGN concrete steps with code examples** — Each step must:\n - Reference REAL file paths you verified with tools\n - Name ACTUAL interfaces, classes, and functions from the codebase\n - Include **sample code** in task descriptions: interface drafts, schema sketches, function signatures, config examples — enough for a human to review the design\n - Include provenance linking back to constraints and evidence\n\n4. **SUBMIT the plan** — Call \\`write_plan\\` with the complete JSON\n\n## What \"Show, Don't Tell\" Means in Practice\n\n**BAD task description:**\n\"Create a StorageProvider interface with methods for reading and writing plan data\"\n\n**GOOD task description:**\n\"Create a StorageProvider interface in src/storage/types.ts:\n\n\\\\\\`\\\\\\`\\\\\\`typescript\nexport interface StorageProvider {\n readPlan(id: string): Promise<Plan>;\n writePlan(id: string, plan: Plan): Promise<void>;\n listPlans(): Promise<PlanMetadata[]>;\n readStep(planId: string, stepNumber: number): Promise<PlanStep>;\n writeStep(planId: string, step: PlanStep): Promise<void>;\n}\n\\\\\\`\\\\\\`\\\\\\`\n\nThis interface mirrors the existing file-based operations in plan/loader.ts but abstracts the storage backend. The key design choice is passing PlanStep objects rather than raw markdown — the provider handles serialization.\"\n\nThe good version lets a human reviewer evaluate the interface design, method signatures, and data flow before any code is written.\n\n## Critical Rules\n\n- EXPLORE FIRST. Do NOT generate the plan without reading relevant code.\n- Every file path in filesChanged MUST be a real file you verified exists.\n- Every interface or type name MUST be verified in the codebase.\n- Include CODE SAMPLES in task descriptions: interface sketches, schema drafts, function signatures, example configs. Use markdown code blocks.\n- Be concrete: \"Add a \\`generatePlanWithAgent()\\` function to \\`src/ai/generator.ts\\`\" not \"Add a new function to the generator\"\n- If write_plan returns an error, fix the issue and call it again.\n- You MUST call write_plan exactly once with the complete plan when done.`;\n\n/**\n * Adapt an execution Provider to an AgentProvider for use with AgentLoop.\n * \n * The execution package uses Provider/Request/ProviderResponse.\n * The agentic package uses AgentProvider/AgentRequest/AgentProviderResponse.\n * This adapter bridges the two interfaces.\n */\nfunction createAgentProvider(provider: Provider, model: string): AgentProvider {\n // We need createRequest from the execution package to build requests\n // that the provider understands\n return {\n name: provider.name,\n execute: async (request) => {\n const execRequest = createRequest(model);\n for (const msg of request.messages) {\n execRequest.addMessage(msg);\n }\n if (request.tools && request.tools.length > 0) {\n (execRequest as any).tools = request.tools;\n }\n const response = await provider.execute(execRequest);\n return {\n content: response.content,\n model: response.model,\n usage: response.usage ? {\n inputTokens: response.usage.inputTokens,\n outputTokens: response.usage.outputTokens,\n } : undefined,\n toolCalls: response.toolCalls,\n };\n },\n executeStream: async function* (request) {\n const execRequest = createRequest(model);\n for (const msg of request.messages) {\n execRequest.addMessage(msg);\n }\n if (request.tools && request.tools.length > 0) {\n (execRequest as any).tools = request.tools;\n }\n if ((provider as any).executeStream) {\n for await (const chunk of (provider as any).executeStream(execRequest)) {\n if (chunk.type === 'text') {\n yield { type: 'text' as const, text: chunk.text };\n } else if (chunk.type === 'tool_call_start') {\n yield {\n type: 'tool_call_start' as const,\n toolCall: {\n id: chunk.toolCall?.id,\n index: chunk.toolCall?.index,\n name: chunk.toolCall?.name,\n },\n };\n } else if (chunk.type === 'tool_call_delta') {\n yield {\n type: 'tool_call_delta' as const,\n toolCall: {\n id: chunk.toolCall?.id,\n index: chunk.toolCall?.index,\n argumentsDelta: chunk.toolCall?.argumentsDelta,\n },\n };\n } else if (chunk.type === 'tool_call_end') {\n yield {\n type: 'tool_call_end' as const,\n toolCall: {\n id: chunk.toolCall?.id,\n index: chunk.toolCall?.index,\n },\n };\n } else if (chunk.type === 'usage') {\n yield {\n type: 'usage' as const,\n usage: chunk.usage ? {\n inputTokens: chunk.usage.inputTokens,\n outputTokens: chunk.usage.outputTokens,\n } : undefined,\n };\n } else if (chunk.type === 'done') {\n yield { type: 'done' as const };\n }\n }\n } else {\n // Fallback to non-streaming\n const response = await provider.execute(execRequest);\n yield { type: 'text' as const, text: response.content };\n yield { type: 'done' as const };\n }\n },\n };\n}\n\n/**\n * Build the user prompt for agent-powered generation.\n * \n * Similar to buildArtifactAwarePrompt() in generator.ts but:\n * - Includes codebase context section if available\n * - Ends with \"explore and call write_plan\" instead of \"output JSON\"\n * - The agent has tools, so we tell it to use them\n */\nfunction buildAgentUserPrompt(context: GenerationContext): string {\n const sections: string[] = [];\n\n // == PLAN NAME ==\n sections.push(`== PLAN NAME ==\\n${context.planName}`);\n\n // == CORE CONCEPT ==\n let coreConcept = context.description;\n const contextMarker = coreConcept.indexOf('\\n\\n--- IDEA CONTEXT ---');\n if (contextMarker !== -1) {\n coreConcept = coreConcept.substring(0, contextMarker).trim();\n }\n sections.push(`== CORE CONCEPT ==\\n${coreConcept}`);\n\n // == CONSTRAINTS (MUST HONOR ALL) ==\n if (context.constraints && context.constraints.length > 0) {\n const constraintsList = context.constraints\n .map((c, i) => `${i + 1}. ${c}`)\n .join('\\n');\n sections.push(`== CONSTRAINTS (MUST HONOR ALL) ==\nThe following constraints are NON-NEGOTIABLE. Every constraint must be addressed by at least one step.\n\n${constraintsList}`);\n }\n\n // == CATALYST CONSTRAINTS ==\n if (context.catalystContent?.constraints) {\n sections.push(`== CATALYST CONSTRAINTS ==\n${context.catalystContent.constraints}`);\n }\n\n // == SELECTED APPROACH ==\n if (context.selectedApproach) {\n sections.push(`== SELECTED APPROACH ==\nThis approach was selected during shaping. Your plan MUST implement this approach.\n\n**Name**: ${context.selectedApproach.name}\n**Description**: ${context.selectedApproach.description}\n**Reasoning**: ${context.selectedApproach.reasoning}`);\n }\n\n // == EVIDENCE ==\n if (context.evidence && context.evidence.length > 0) {\n const evidenceContent = context.evidence\n .map(e => `### ${e.name}\\n${e.content.trim()}`)\n .join('\\n\\n');\n sections.push(`== EVIDENCE ==\nEvidence gathered during exploration. Use these findings to inform step design.\n\n${evidenceContent}`);\n }\n\n // == HISTORY CONTEXT ==\n if (context.historyContext && context.historyContext.recentEvents.length > 0) {\n const historyList = context.historyContext.recentEvents\n .map(e => `- [${e.type}] ${e.summary}`)\n .join('\\n');\n sections.push(`== HISTORY CONTEXT ==\nRecent events (${context.historyContext.totalEvents} total):\n\n${historyList}`);\n }\n\n // == QUESTIONS ==\n if (context.questions && context.questions.length > 0) {\n const questionsList = context.questions\n .map((q, i) => `${i + 1}. ${q}`)\n .join('\\n');\n sections.push(`== OPEN QUESTIONS ==\nConsider these when designing steps.\n\n${questionsList}`);\n }\n\n // == CATALYST sections ==\n if (context.catalystContent?.domainKnowledge) {\n sections.push(`== CATALYST DOMAIN KNOWLEDGE ==\\n${context.catalystContent.domainKnowledge}`);\n }\n if (context.catalystContent?.processGuidance) {\n sections.push(`== CATALYST PROCESS GUIDANCE ==\\n${context.catalystContent.processGuidance}`);\n }\n if (context.catalystContent?.outputTemplates) {\n sections.push(`== CATALYST OUTPUT TEMPLATES ==\\n${context.catalystContent.outputTemplates}`);\n }\n\n // == CODEBASE CONTEXT ==\n if (context.codebaseContext) {\n sections.push(`== CODEBASE CONTEXT ==\n${context.codebaseContext}`);\n }\n\n // == AGENT INSTRUCTIONS ==\n const stepCount = context.stepCount || 5;\n sections.push(`== YOUR TASK ==\n\nGenerate a ${stepCount}-step execution plan for this project.\n\n**Step 1: Explore the codebase.** Start by calling \\`query_index\\` with query \"packages\" to see the full project structure (this is instant — the index is pre-built). Then use \\`query_index\\` to find specific files and exports, \\`read_file\\` to examine key interfaces, and \\`grep\\` to find usage patterns.\n\n**Step 2: Call write_plan.** Once you understand the codebase well enough, call \\`write_plan\\` with the complete plan JSON. Include:\n- analysis (constraintAnalysis, evidenceAnalysis, approachAnalysis, risks)\n- summary, approach, successCriteria\n- ${stepCount} steps, each with concrete tasks referencing real files\n\n**IMPORTANT — Task descriptions must include sample code.** A human will review this plan before execution. Every task that introduces an interface, schema, config, or significant function should include a code sketch in its description using markdown code blocks. Don't write the full implementation — just enough for a person to judge the design: key method signatures, table schemas, type definitions, config formats. This is the plan's most important quality signal.\n\nEvery step's \\`filesChanged\\` must list actual files from the codebase. Every task must reference real interfaces and functions. No placeholders.`);\n\n return sections.join('\\n\\n');\n}\n\n/**\n * Generate a plan using an agent loop with codebase tools.\n * \n * The agent explores the codebase using read-only tools, then calls\n * write_plan to submit the structured plan. This produces higher-quality\n * plans than the one-shot approach because the agent can:\n * - Read actual source files\n * - Search for patterns and references\n * - Understand the project structure\n * - Reference real file paths, interfaces, and functions\n * \n * @param context - Generation context with artifacts and description\n * @param provider - Execution provider (will be adapted to AgentProvider)\n * @param codebaseTools - Read-only environment tools (read_file, grep, etc.)\n * @param options - Generation options including model and progress callback\n * @param projectRoot - Project root directory for tool working directory\n * @returns GenerationResult with the plan and tiering info\n */\nexport async function generatePlanWithAgent(\n context: GenerationContext,\n provider: Provider,\n codebaseTools: Tool[],\n options: GenerationOptionsWithProgress = {},\n projectRoot?: string,\n): Promise<GenerationResult> {\n const { onProgress } = options;\n\n // Apply token budget tiering (same as one-shot path)\n let tieringDecision: TieringDecision | undefined;\n let tieredContext = context;\n\n if (context.constraints || context.evidence || context.historyContext) {\n const budget: TokenBudget = {\n ...DEFAULT_TOKEN_BUDGET,\n ...context.tokenBudget,\n };\n\n tieringDecision = calculateTiering(\n context.constraints || [],\n context.selectedApproach || null,\n context.evidence || [],\n context.historyContext?.recentEvents.length || 0,\n budget,\n );\n\n if (context.evidence && context.evidence.length > 0) {\n const tieredEvidence = applyEvidenceTiering(context.evidence, tieringDecision);\n tieredContext = { ...context, evidence: tieredEvidence };\n }\n\n if (tieringDecision.historyAbbreviated && context.historyContext) {\n const abbreviatedCount = budget.historyAbbreviatedCount || 5;\n tieredContext = {\n ...tieredContext,\n historyContext: {\n ...context.historyContext,\n recentEvents: context.historyContext.recentEvents.slice(0, abbreviatedCount),\n },\n };\n }\n }\n\n // Notify start\n onProgress?.({ type: 'started', message: 'Starting agent-powered plan generation...' });\n\n // Create the write_plan tool with connected promise\n const { tool: writePlanTool, planPromise } = createWritePlanTool();\n\n // Create tool registry with project root as working directory\n const workingDir = projectRoot || process.cwd();\n const toolRegistry = ToolRegistry.create({\n workingDirectory: workingDir,\n });\n\n // Register codebase tools + write_plan\n for (const tool of codebaseTools) {\n toolRegistry.register(tool);\n }\n toolRegistry.register(writePlanTool);\n\n // Create conversation manager with system prompt\n const conversation = ConversationManager.create();\n conversation.addSystemMessage(AGENT_SYSTEM_PROMPT);\n\n // Create agent provider adapter\n const model = options.model || 'claude-sonnet-4-20250514';\n const agentProvider = createAgentProvider(provider, model);\n\n // Create agent loop\n const agentLoop = AgentLoop.create({\n provider: agentProvider,\n toolRegistry,\n conversation,\n model,\n maxIterations: DEFAULT_MAX_ITERATIONS,\n });\n\n // Build the user prompt with artifacts\n const userPrompt = buildAgentUserPrompt(tieredContext);\n\n // Run the agent loop\n onProgress?.({ type: 'streaming', message: 'Agent exploring codebase...', charsReceived: 0 });\n\n let textContent = '';\n let toolCallCount = 0;\n let lastProgressUpdate = Date.now();\n\n // Race between the agent loop completing and planPromise resolving.\n // The agent loop yields chunks; when write_plan is called, planPromise resolves.\n const agentDone = (async () => {\n for await (const chunk of agentLoop.runStream(userPrompt)) {\n if (chunk.type === 'text' && chunk.text) {\n textContent += chunk.text;\n }\n if (chunk.type === 'tool_start' && chunk.tool) {\n toolCallCount++;\n const now = Date.now();\n if (now - lastProgressUpdate > 300) {\n const toolName = chunk.tool.name;\n let detail = '';\n if (toolName === 'read_file' && chunk.tool.arguments?.path) {\n detail = `: ${chunk.tool.arguments.path}`;\n } else if (toolName === 'grep' && chunk.tool.arguments?.pattern) {\n detail = `: \"${chunk.tool.arguments.pattern}\"`;\n } else if (toolName === 'list_files' && chunk.tool.arguments?.path) {\n detail = `: ${chunk.tool.arguments.path}`;\n } else if (toolName === 'write_plan') {\n detail = ' (submitting plan)';\n }\n onProgress?.({\n type: 'streaming',\n message: `Agent: ${toolName}${detail} (${toolCallCount} tool calls)`,\n charsReceived: textContent.length,\n });\n lastProgressUpdate = now;\n }\n }\n if (chunk.type === 'tool_result' && chunk.tool) {\n const now = Date.now();\n if (now - lastProgressUpdate > 300) {\n onProgress?.({\n type: 'streaming',\n message: `Agent: ${chunk.tool.name} complete (${toolCallCount} tool calls)`,\n charsReceived: textContent.length,\n });\n lastProgressUpdate = now;\n }\n }\n }\n })();\n\n // Wait for either: plan submitted via write_plan, or agent loop finishes\n let plan: GeneratedPlan;\n try {\n // Use Promise.race: planPromise resolves when write_plan is called\n // agentDone resolves when the agent loop finishes all iterations\n const result = await Promise.race([\n planPromise.then(p => ({ type: 'plan' as const, plan: p })),\n agentDone.then(() => ({ type: 'done' as const, plan: null as any })),\n ]);\n\n if (result.type === 'plan') {\n plan = result.plan;\n // Agent loop may still be running (write_plan was called mid-conversation)\n // That's fine - the plan is already captured\n } else {\n // Agent finished without calling write_plan\n // Try to get the plan from the promise (it might have been resolved during the last iteration)\n try {\n plan = await Promise.race([\n planPromise,\n new Promise<never>((_, reject) => setTimeout(() => reject(new Error('timeout')), 1000)),\n ]);\n } catch {\n throw new Error(\n `Agent completed ${toolCallCount} tool calls over ${DEFAULT_MAX_ITERATIONS} iterations ` +\n `but did not call write_plan to submit the plan. ` +\n `The agent may have run out of iterations. ` +\n `Try increasing maxIterations or simplifying the plan scope.`\n );\n }\n }\n } catch (error) {\n // Clean up: reject the planPromise if it hasn't been resolved\n (writePlanTool as any)._rejectPlan?.(error instanceof Error ? error : new Error(String(error)));\n throw error;\n }\n\n // Notify parsing/completion\n onProgress?.({ type: 'parsing', message: `Plan received with ${plan.steps.length} steps from ${toolCallCount} tool calls` });\n onProgress?.({ type: 'complete', message: 'Agent-powered plan generation complete' });\n\n return {\n plan,\n tiering: tieringDecision,\n };\n}\n","/**\n * Provider Loader\n * \n * Dynamically loads LLM providers based on availability and session context.\n * Supports both MCP sampling (when available) and direct API providers.\n */\n\nimport type { Provider } from './types.js';\n\n/**\n * Minimal session context shape needed by the provider loader.\n * The full SessionContext type lives in @kjerneverk/riotplan-mcp-http.\n */\ninterface SessionContext {\n sessionId: string;\n providerMode: 'sampling' | 'direct' | 'none';\n clientInfo: { name: string; version: string } | null;\n}\n\nexport interface ProviderConfig {\n name: string;\n apiKey?: string;\n model?: string;\n session?: SessionContext;\n mcpServer?: any; // MCP server instance for sampling\n}\n\n/**\n * Load a provider based on session context and configuration\n * \n * Priority:\n * 1. If session has sampling available → use SamplingProvider\n * 2. If explicit provider name given → use that provider\n * 3. If API keys available → use default provider\n * 4. Otherwise → error with helpful message\n */\nexport async function loadProvider(config: ProviderConfig): Promise<Provider> {\n const { name, apiKey, session, mcpServer } = config;\n \n // Priority 1: Check if session supports sampling\n if (session && session.providerMode === 'sampling') {\n return await loadSamplingProvider(session, mcpServer);\n }\n \n // Priority 2: Explicit provider name\n if (name) {\n return await loadDirectProvider(name, apiKey);\n }\n \n // Priority 3: Default provider from environment\n const defaultProvider = getDefaultProvider();\n if (defaultProvider) {\n return await loadDirectProvider(defaultProvider, apiKey);\n }\n \n // Priority 4: No provider available\n const clientName = session?.clientInfo?.name ?? 'your client';\n const errorMessage = [\n '❌ No AI provider available for RiotPlan.',\n '',\n `Your client (${clientName}) does not support MCP sampling, and no API keys are configured.`,\n '',\n 'To use RiotPlan\\'s AI generation features, either:',\n '',\n '1. Use a client that supports MCP sampling:',\n ' - GitHub Copilot (supports sampling)',\n ' - FastMCP (Python framework for testing)',\n '',\n '2. Set up an API key:',\n ' - ANTHROPIC_API_KEY for Claude models (recommended)',\n ' - OPENAI_API_KEY for GPT models',\n ' - GOOGLE_API_KEY for Gemini models',\n '',\n '3. Create plan steps manually:',\n ' - Use riotplan_step with action=add to add steps without AI',\n '',\n 'For more information: https://github.com/kjerneverk/riotplan#ai-providers',\n ].join('\\n');\n \n throw new Error(errorMessage);\n}\n\n/**\n * Load a sampling provider for MCP\n */\nasync function loadSamplingProvider(session: SessionContext, mcpServer?: any): Promise<Provider> {\n try {\n const { createSamplingProvider } = await import('@kjerneverk/execution-sampling');\n \n const provider = createSamplingProvider({\n sessionId: session.sessionId,\n clientName: session.clientInfo?.name,\n supportsTools: false, // RiotPlan doesn't use tools in generation\n debug: false,\n });\n \n // Wire up MCP server for sending sampling requests\n if (mcpServer) {\n provider.setSamplingClient(mcpServer);\n }\n \n return provider;\n } catch (error) {\n if (\n error instanceof Error &&\n (error.message.includes('Cannot find package') ||\n error.message.includes('Cannot find module') ||\n error.message.includes('Could not resolve'))\n ) {\n throw new Error(\n 'Sampling provider (@kjerneverk/execution-sampling) is not installed.\\n' +\n 'This is a development error - the package should be installed as a dependency.'\n );\n }\n throw error;\n }\n}\n\n/**\n * Load a direct API provider by name\n */\nasync function loadDirectProvider(name: string, apiKey?: string): Promise<Provider> {\n try {\n switch (name.toLowerCase()) {\n case 'anthropic':\n case 'claude':\n return await loadAnthropicProvider(apiKey);\n \n case 'openai':\n case 'gpt':\n return await loadOpenAIProvider(apiKey);\n \n case 'gemini':\n case 'google':\n return await loadGeminiProvider(apiKey);\n \n default:\n throw new Error(`Unknown provider: ${name}`);\n }\n } catch (error) {\n if (\n error instanceof Error &&\n (error.message.includes('Cannot find package') ||\n error.message.includes('Cannot find module') ||\n error.message.includes('Could not resolve'))\n ) {\n const errorMessage = [\n `❌ Provider '${name}' is not installed.`,\n '',\n 'To use this provider, install it:',\n ` npm install @kjerneverk/execution-${name}`,\n '',\n 'Then set the appropriate API key:',\n ` export ${name.toUpperCase()}_API_KEY=\"your-key-here\"`,\n '',\n 'Alternative options:',\n ' 1. Use a different provider (anthropic, openai, gemini)',\n ' 2. Use RiotPlan via MCP with a sampling-enabled client',\n ' 3. Create plan steps manually with riotplan_step(action=add)',\n ].join('\\n');\n throw new Error(errorMessage);\n }\n throw error;\n }\n}\n\nasync function loadAnthropicProvider(_apiKey?: string): Promise<Provider> {\n const { createAnthropicProvider } = await import('@kjerneverk/execution-anthropic');\n return createAnthropicProvider();\n}\n\nasync function loadOpenAIProvider(_apiKey?: string): Promise<Provider> {\n const { createOpenAIProvider } = await import('@kjerneverk/execution-openai');\n return createOpenAIProvider();\n}\n\nasync function loadGeminiProvider(_apiKey?: string): Promise<Provider> {\n const { createGeminiProvider } = await import('@kjerneverk/execution-gemini');\n return createGeminiProvider();\n}\n\n/**\n * Detect available providers\n */\nexport async function detectAvailableProviders(): Promise<string[]> {\n const providers: string[] = [];\n \n const candidates = [\n { name: 'anthropic', pkg: '@kjerneverk/execution-anthropic' },\n { name: 'openai', pkg: '@kjerneverk/execution-openai' },\n { name: 'gemini', pkg: '@kjerneverk/execution-gemini' },\n ];\n \n for (const candidate of candidates) {\n try {\n await import(candidate.pkg);\n providers.push(candidate.name);\n } catch {\n // Provider not available\n }\n }\n \n return providers;\n}\n\n/**\n * Get default provider based on environment variables\n */\nexport function getDefaultProvider(): string | null {\n if (process.env.ANTHROPIC_API_KEY) return 'anthropic';\n if (process.env.OPENAI_API_KEY) return 'openai';\n if (process.env.GOOGLE_API_KEY) return 'gemini';\n return null;\n}\n\n/**\n * Get API key for a provider from environment\n */\nexport function getProviderApiKey(provider: string): string | undefined {\n switch (provider.toLowerCase()) {\n case 'anthropic':\n case 'claude':\n return process.env.ANTHROPIC_API_KEY;\n case 'openai':\n case 'gpt':\n return process.env.OPENAI_API_KEY;\n case 'gemini':\n case 'google':\n return process.env.GOOGLE_API_KEY;\n default:\n return undefined;\n }\n}\n","/**\n * Plan Validation\n * \n * Post-generation validation to ensure constraints are addressed,\n * evidence is referenced, and the selected approach is implemented\n */\n\nimport type { GeneratedPlan, GenerationContext } from './generator.js';\n\nexport interface ValidationResult {\n passed: boolean;\n warnings: string[];\n details: Record<string, any>;\n}\n\nexport interface ValidationCheck {\n name: string;\n validate(plan: GeneratedPlan, context: GenerationContext): ValidationResult;\n}\n\nexport interface ValidationReport {\n overallPassed: boolean;\n checks: {\n name: string;\n result: ValidationResult;\n }[];\n allWarnings: string[];\n}\n\n/**\n * Constraint Coverage Validation\n * Ensures each constraint from IDEA.md is addressed by at least one step\n */\nexport class ConstraintCoverageCheck implements ValidationCheck {\n name = 'constraint-coverage';\n \n validate(plan: GeneratedPlan, context: GenerationContext): ValidationResult {\n const warnings: string[] = [];\n const coverage: Record<string, string[]> = {};\n \n const constraints = context.constraints || [];\n \n if (constraints.length === 0) {\n return {\n passed: true,\n warnings: [],\n details: { coverage, message: 'No constraints to validate' },\n };\n }\n \n // Build coverage map from step provenance\n for (const step of plan.steps) {\n if (step.provenance?.constraintsAddressed) {\n for (const constraint of step.provenance.constraintsAddressed) {\n if (!coverage[constraint]) {\n coverage[constraint] = [];\n }\n coverage[constraint].push(`Step ${step.number}`);\n }\n }\n }\n \n // Check each constraint for coverage\n for (const constraint of constraints) {\n const addressed = Object.keys(coverage).some(key => \n constraint.includes(key) || key.includes(constraint.substring(0, 50))\n );\n \n if (!addressed) {\n warnings.push(`Constraint not addressed: \"${constraint.substring(0, 80)}${constraint.length > 80 ? '...' : ''}\"`);\n }\n }\n \n return {\n passed: warnings.length === 0,\n warnings,\n details: { \n coverage,\n totalConstraints: constraints.length,\n coveredConstraints: constraints.length - warnings.length,\n },\n };\n }\n}\n\n/**\n * Evidence Reference Validation\n * Checks if provided evidence files are referenced in the plan\n */\nexport class EvidenceReferenceCheck implements ValidationCheck {\n name = 'evidence-reference';\n \n validate(plan: GeneratedPlan, context: GenerationContext): ValidationResult {\n const warnings: string[] = [];\n const references: Record<string, string[]> = {};\n \n const evidence = context.evidence || [];\n \n if (evidence.length === 0) {\n return {\n passed: true,\n warnings: [],\n details: { references, message: 'No evidence to validate' },\n };\n }\n \n // Check if evidence is mentioned in analysis\n const analysisFiles = new Set<string>();\n if (plan.analysis?.evidenceAnalysis) {\n for (const ea of plan.analysis.evidenceAnalysis) {\n analysisFiles.add(ea.evidenceFile);\n }\n }\n \n // Build reference map from step provenance\n for (const step of plan.steps) {\n if (step.provenance?.evidenceUsed) {\n for (const evidenceFile of step.provenance.evidenceUsed) {\n if (!references[evidenceFile]) {\n references[evidenceFile] = [];\n }\n references[evidenceFile].push(`Step ${step.number}`);\n }\n }\n }\n \n // Check each evidence file for references\n for (const ev of evidence) {\n const inAnalysis = analysisFiles.has(ev.name);\n const inSteps = references[ev.name] && references[ev.name].length > 0;\n \n if (!inAnalysis && !inSteps) {\n warnings.push(`Evidence file not referenced: \"${ev.name}\"`);\n }\n }\n \n return {\n passed: warnings.length === 0,\n warnings,\n details: { \n references,\n analysisFiles: Array.from(analysisFiles),\n totalEvidence: evidence.length,\n referencedEvidence: evidence.length - warnings.length,\n },\n };\n }\n}\n\n/**\n * Selected Approach Validation\n * Ensures the selected approach is reflected in the analysis\n */\nexport class SelectedApproachCheck implements ValidationCheck {\n name = 'selected-approach';\n \n validate(plan: GeneratedPlan, context: GenerationContext): ValidationResult {\n const warnings: string[] = [];\n \n if (!context.selectedApproach) {\n return {\n passed: true,\n warnings: [],\n details: { message: 'No selected approach to validate' },\n };\n }\n \n const approachName = context.selectedApproach.name;\n \n // Check if approach is mentioned in analysis\n if (!plan.analysis?.approachAnalysis) {\n warnings.push(`Selected approach \"${approachName}\" not analyzed in the analysis section`);\n } else {\n const analysisText = JSON.stringify(plan.analysis.approachAnalysis).toLowerCase();\n if (!analysisText.includes(approachName.toLowerCase())) {\n warnings.push(`Selected approach \"${approachName}\" not mentioned in approach analysis`);\n }\n }\n \n // Check if approach is mentioned in plan summary or approach\n const planText = (plan.summary + ' ' + plan.approach).toLowerCase();\n if (!planText.includes(approachName.toLowerCase())) {\n warnings.push(`Selected approach \"${approachName}\" not mentioned in plan summary or approach`);\n }\n \n return {\n passed: warnings.length === 0,\n warnings,\n details: {\n approachName,\n hasApproachAnalysis: !!plan.analysis?.approachAnalysis,\n },\n };\n }\n}\n\n/**\n * Validation Pipeline\n * Runs all validation checks and aggregates results\n */\nexport class ValidationPipeline {\n private checks: ValidationCheck[] = [];\n \n constructor() {\n // Register default checks\n this.addCheck(new ConstraintCoverageCheck());\n this.addCheck(new EvidenceReferenceCheck());\n this.addCheck(new SelectedApproachCheck());\n }\n \n /**\n * Add a custom validation check\n */\n addCheck(check: ValidationCheck): void {\n this.checks.push(check);\n }\n \n /**\n * Run all validation checks\n */\n validate(plan: GeneratedPlan, context: GenerationContext): ValidationReport {\n const results: { name: string; result: ValidationResult }[] = [];\n const allWarnings: string[] = [];\n \n for (const check of this.checks) {\n const result = check.validate(plan, context);\n results.push({ name: check.name, result });\n allWarnings.push(...result.warnings);\n }\n \n return {\n overallPassed: allWarnings.length === 0,\n checks: results,\n allWarnings,\n };\n }\n}\n\n/**\n * Create and run validation pipeline\n */\nexport function validatePlan(\n plan: GeneratedPlan,\n context: GenerationContext\n): ValidationReport {\n const pipeline = new ValidationPipeline();\n return pipeline.validate(plan, context);\n}\n","/**\n * Provenance Documentation\n * \n * Generates PROVENANCE.md to document how the plan connects to idea artifacts\n */\n\nimport type { GeneratedPlan, GenerationContext } from './generator.js';\nimport type { ValidationReport } from './validation.js';\nimport type { TieringDecision } from './tokens.js';\n\nexport interface ProvenanceData {\n plan: GeneratedPlan;\n context: GenerationContext;\n validation: ValidationReport;\n tiering?: TieringDecision;\n generatedAt: Date;\n}\n\n/**\n * Generate PROVENANCE.md content\n */\nexport function generateProvenanceMarkdown(data: ProvenanceData): string {\n const { plan, context, validation, tiering, generatedAt } = data;\n \n const sections: string[] = [];\n \n // Header\n sections.push(`# Plan Provenance\n\nThis document traces how the generated plan connects to the idea artifacts.`);\n \n // Generation metadata\n sections.push(`## How This Plan Was Generated\n\n- **Generated**: ${generatedAt.toISOString()}\n- **Constraints**: ${context.constraints?.length || 0}\n- **Evidence files**: ${context.evidence?.length || 0}\n- **Selected approach**: ${context.selectedApproach?.name || 'None'}\n- **History events**: ${context.historyContext?.totalEvents || 0}`);\n \n // Artifact Analysis section\n sections.push(`## Artifact Analysis`);\n \n // Constraints\n if (plan.analysis?.constraintAnalysis && plan.analysis.constraintAnalysis.length > 0) {\n sections.push(`### Constraints\n\nThe model analyzed ${plan.analysis.constraintAnalysis.length} constraint(s):\n\n| # | Constraint | Addressed By | Model's Understanding |\n|---|-----------|-------------|----------------------|`);\n \n for (let i = 0; i < plan.analysis.constraintAnalysis.length; i++) {\n const ca = plan.analysis.constraintAnalysis[i];\n \n // Find which steps address this constraint\n const addressedBy: string[] = [];\n for (const step of plan.steps) {\n if (step.provenance?.constraintsAddressed) {\n for (const constraintRef of step.provenance.constraintsAddressed) {\n if (ca.constraint.includes(constraintRef) || constraintRef.includes(ca.constraint.substring(0, 30))) {\n addressedBy.push(`Step ${step.number}`);\n break;\n }\n }\n }\n }\n \n const constraintText = ca.constraint.length > 60 \n ? ca.constraint.substring(0, 60) + '...' \n : ca.constraint;\n const understanding = ca.understanding.length > 80 \n ? ca.understanding.substring(0, 80) + '...' \n : ca.understanding;\n const steps = addressedBy.length > 0 ? addressedBy.join(', ') : '*(none)*';\n \n sections.push(`| ${i + 1} | ${constraintText} | ${steps} | ${understanding} |`);\n }\n } else if (context.constraints && context.constraints.length > 0) {\n sections.push(`### Constraints\n\n${context.constraints.length} constraint(s) were provided but not analyzed in the response.`);\n }\n \n // Evidence\n if (plan.analysis?.evidenceAnalysis && plan.analysis.evidenceAnalysis.length > 0) {\n sections.push(`\n### Evidence Used\n\nThe model analyzed ${plan.analysis.evidenceAnalysis.length} evidence file(s):\n\n| File | Key Findings | Referenced In |\n|------|-------------|--------------|`);\n \n for (const ea of plan.analysis.evidenceAnalysis) {\n // Find which steps reference this evidence\n const referencedIn: string[] = [];\n for (const step of plan.steps) {\n if (step.provenance?.evidenceUsed?.includes(ea.evidenceFile)) {\n referencedIn.push(`Step ${step.number}`);\n }\n }\n \n const findings = ea.keyFindings.length > 100 \n ? ea.keyFindings.substring(0, 100) + '...' \n : ea.keyFindings;\n const refs = referencedIn.length > 0 ? referencedIn.join(', ') : '*(none)*';\n \n sections.push(`| ${ea.evidenceFile} | ${findings} | ${refs} |`);\n }\n } else if (context.evidence && context.evidence.length > 0) {\n sections.push(`\n### Evidence Used\n\n${context.evidence.length} evidence file(s) were provided but not analyzed in the response.`);\n }\n \n // Selected Approach\n if (plan.analysis?.approachAnalysis) {\n const aa = plan.analysis.approachAnalysis;\n sections.push(`\n### Selected Approach\n\n- **Approach**: ${aa.selectedApproach}\n- **Commitments**: ${aa.commitments}\n- **Implementation Strategy**: ${aa.implementationStrategy}`);\n } else if (context.selectedApproach) {\n sections.push(`\n### Selected Approach\n\nA selected approach (\"${context.selectedApproach.name}\") was provided but not analyzed in the response.`);\n }\n \n // Risks\n if (plan.analysis?.risks && plan.analysis.risks.length > 0) {\n sections.push(`\n### Risks Identified\n\n${plan.analysis.risks.map((r, i) => `${i + 1}. ${r}`).join('\\n')}`);\n }\n \n // Coverage Warnings\n if (validation.allWarnings.length > 0) {\n sections.push(`## Coverage Warnings\n\nThe following gaps were detected during validation:\n\n${validation.allWarnings.map(w => `- ${w}`).join('\\n')}`);\n } else {\n sections.push(`## Coverage Validation\n\n✅ All constraints addressed, all evidence referenced, selected approach implemented.`);\n }\n \n // Token Budget\n if (tiering) {\n sections.push(`## Token Budget\n\n- **Estimated tokens**: ${tiering.totalEstimatedTokens}\n- **Budget exceeded**: ${tiering.budgetExceeded ? 'Yes' : 'No'}`);\n \n if (tiering.evidenceTiered.full.length > 0) {\n sections.push(`- **Evidence (full)**: ${tiering.evidenceTiered.full.join(', ')}`);\n }\n if (tiering.evidenceTiered.summarized.length > 0) {\n sections.push(`- **Evidence (summarized)**: ${tiering.evidenceTiered.summarized.join(', ')}`);\n }\n if (tiering.evidenceTiered.listOnly.length > 0) {\n sections.push(`- **Evidence (preview only)**: ${tiering.evidenceTiered.listOnly.join(', ')}`);\n }\n if (tiering.historyAbbreviated) {\n sections.push(`- **History**: abbreviated to most recent events`);\n }\n \n if (tiering.warnings.length > 0) {\n sections.push(`\n### Tiering Warnings\n\n${tiering.warnings.map(w => `- ${w}`).join('\\n')}`);\n }\n }\n \n // Step Provenance Summary\n sections.push(`## Step Provenance\n\nHow each step connects to the idea artifacts:\n`);\n \n for (const step of plan.steps) {\n sections.push(`### Step ${step.number}: ${step.title}`);\n \n if (step.provenance) {\n if (step.provenance.rationale) {\n sections.push(`\\n**Rationale**: ${step.provenance.rationale}`);\n }\n \n if (step.provenance.constraintsAddressed && step.provenance.constraintsAddressed.length > 0) {\n sections.push(`\\n**Addresses constraints**: ${step.provenance.constraintsAddressed.join(', ')}`);\n }\n \n if (step.provenance.evidenceUsed && step.provenance.evidenceUsed.length > 0) {\n sections.push(`\\n**Uses evidence**: ${step.provenance.evidenceUsed.join(', ')}`);\n }\n } else {\n sections.push(`\\n*(No provenance data)*`);\n }\n \n sections.push(''); // Empty line between steps\n }\n \n return sections.join('\\n\\n');\n}\n","/**\n * Artifact Loading Utilities\n * \n * Shared functions for loading and extracting plan artifacts (IDEA.md, SHAPING.md, evidence, history)\n * Used by both build.ts and context.ts to ensure consistent artifact handling\n */\n\nimport { join } from 'node:path';\nimport { readFile, readdir, stat } from 'node:fs/promises';\nimport { createSqliteProvider, type PlanFileType } from '@kjerneverk/riotplan-format';\n\nexport interface ArtifactBundle {\n ideaContent: string | null;\n shapingContent: string | null;\n lifecycleContent: string | null;\n artifactDiagnostics?: {\n planId: string;\n hasIdeaArtifact: boolean;\n detectedArtifacts: Array<{\n type: string;\n filename: string;\n }>;\n };\n constraints: string[];\n questions: string[];\n selectedApproach: {\n name: string;\n description: string;\n reasoning: string;\n } | null;\n evidence: {\n name: string;\n content: string;\n size: number;\n }[];\n historyContext: {\n recentEvents: { type: string; timestamp: string; summary: string }[];\n totalEvents: number;\n };\n // Catalyst content (optional, populated when catalysts are configured)\n catalystContent?: {\n constraints: string;\n domainKnowledge: string;\n outputTemplates: string;\n processGuidance: string;\n questions: string;\n validationRules: string;\n appliedCatalysts: string[];\n };\n}\n\n/**\n * Read a file safely, returning null if it doesn't exist\n */\nasync function readFileSafe(path: string): Promise<string | null> {\n try {\n return await readFile(path, 'utf-8');\n } catch {\n return null;\n }\n}\n\nfunction getMostRecentFileByType(\n files: Array<{ type: string; content: string; updatedAt: string }>,\n fileType: PlanFileType\n): string | null {\n const matches = files\n .filter((file) => file.type === fileType)\n .sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));\n return matches[0]?.content ?? null;\n}\n\nfunction normalizeArtifactKey(value: string | undefined): string {\n return (value || '')\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '');\n}\n\nfunction isArtifactMatch(\n file: { type: string; filename: string },\n aliases: string[],\n filenameCandidates: string[]\n): boolean {\n const normalizedType = normalizeArtifactKey(file.type);\n const normalizedFilename = normalizeArtifactKey(file.filename);\n const normalizedAliases = aliases.map(normalizeArtifactKey);\n const normalizedCandidates = filenameCandidates.map(normalizeArtifactKey);\n\n return normalizedAliases.includes(normalizedType) || normalizedCandidates.includes(normalizedFilename);\n}\n\nfunction getMostRecentArtifactContent(\n files: Array<{ type: string; filename: string; content: string; updatedAt: string }>,\n aliases: string[],\n filenameCandidates: string[]\n): string | null {\n const matches = files\n .filter((file) => isArtifactMatch(file, aliases, filenameCandidates))\n .sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));\n return matches[0]?.content ?? null;\n}\n\n/**\n * Extract constraints from IDEA.md content\n */\nexport function extractConstraints(ideaContent: string): string[] {\n const constraints: string[] = [];\n const constraintsMatch = ideaContent.match(/## Constraints\\n\\n([\\s\\S]*?)(?=\\n## |$)/);\n if (constraintsMatch) {\n const lines = constraintsMatch[1].split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.startsWith('- ') && !trimmed.includes('_Add constraints')) {\n constraints.push(trimmed.substring(2));\n }\n }\n }\n return constraints;\n}\n\n/**\n * Extract questions from IDEA.md content\n */\nexport function extractQuestions(ideaContent: string): string[] {\n const questions: string[] = [];\n const questionsMatch = ideaContent.match(/## Questions\\n\\n([\\s\\S]*?)(?=\\n## |$)/);\n if (questionsMatch) {\n const lines = questionsMatch[1].split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.startsWith('- ') && !trimmed.includes('_Add questions')) {\n questions.push(trimmed.substring(2));\n }\n }\n }\n return questions;\n}\n\n/**\n * Extract selected approach from SHAPING.md content\n */\nexport function extractSelectedApproach(shapingContent: string): {\n name: string;\n description: string;\n reasoning: string;\n} | null {\n // Extract approach name\n const nameMatch = shapingContent.match(/\\*\\*Selected Approach\\*\\*: (.+)/);\n if (!nameMatch) return null;\n \n const approachName = nameMatch[1].trim();\n \n // Find the approach section\n const approachPattern = new RegExp(`### Approach: ${approachName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\s+\\\\*\\\\*Description\\\\*\\\\*: ([\\\\s\\\\S]*?)(?:\\\\*\\\\*Tradeoffs\\\\*\\\\*:|### Approach:|## |$)`);\n const approachMatch = shapingContent.match(approachPattern);\n \n // Extract reasoning\n const reasoningMatch = shapingContent.match(/\\*\\*Reasoning\\*\\*: ([^\\n]+)/);\n \n return {\n name: approachName,\n description: approachMatch ? approachMatch[1].trim() : '',\n reasoning: reasoningMatch ? reasoningMatch[1].trim() : '',\n };\n}\n\n/**\n * Read evidence files from the evidence directory\n */\nexport async function readEvidenceFiles(planPath: string, includeContent: boolean = true): Promise<{\n name: string;\n content: string;\n size: number;\n}[]> {\n const evidenceDir = join(planPath, 'evidence');\n const dotEvidenceDir = join(planPath, '.evidence');\n \n // Try both evidence/ and .evidence/ directories\n let files: string[] = [];\n let actualDir = evidenceDir;\n \n try {\n files = await readdir(evidenceDir);\n } catch {\n try {\n files = await readdir(dotEvidenceDir);\n actualDir = dotEvidenceDir;\n } catch {\n return [];\n }\n }\n \n const evidenceFiles: { name: string; content: string; size: number }[] = [];\n \n for (const file of files) {\n if (!file.endsWith('.md')) continue;\n \n const filePath = join(actualDir, file);\n try {\n const stats = await stat(filePath);\n let content = '';\n \n if (includeContent) {\n const fileContent = await readFile(filePath, 'utf-8');\n content = fileContent;\n }\n \n evidenceFiles.push({\n name: file,\n content,\n size: stats.size,\n });\n } catch {\n // Skip files we can't read\n }\n }\n \n return evidenceFiles;\n}\n\n/**\n * Read recent history events from timeline.jsonl\n */\nexport async function readRecentHistory(planPath: string, limit: number = 15): Promise<{\n recentEvents: { type: string; timestamp: string; summary: string }[];\n totalEvents: number;\n}> {\n const timelinePath = join(planPath, '.history', 'timeline.jsonl');\n \n try {\n const content = await readFile(timelinePath, 'utf-8');\n const lines = content.trim().split('\\n').filter(line => line.trim());\n const totalEvents = lines.length;\n \n // Get last N events\n const recentLines = lines.slice(-limit);\n const recentEvents: { type: string; timestamp: string; summary: string }[] = [];\n \n for (const line of recentLines) {\n try {\n const event = JSON.parse(line);\n recentEvents.push({\n type: event.type || 'unknown',\n timestamp: event.timestamp || '',\n summary: summarizeEvent(event),\n });\n } catch {\n // Skip malformed lines\n }\n }\n \n return { recentEvents, totalEvents };\n } catch {\n return { recentEvents: [], totalEvents: 0 };\n }\n}\n\n/**\n * Create a brief summary of a timeline event\n */\nfunction summarizeEvent(event: any): string {\n const type = event.type || 'unknown';\n const data = event.data || {};\n \n switch (type) {\n case 'note_added':\n return `Note: ${truncate(data.note, 60)}`;\n case 'constraint_added':\n return `Constraint: ${truncate(data.constraint, 60)}`;\n case 'question_added':\n return `Question: ${truncate(data.question, 60)}`;\n case 'evidence_added':\n return `Evidence: ${truncate(data.description, 60)}`;\n case 'narrative_chunk':\n return `Narrative: ${truncate(data.content, 60)}`;\n case 'approach_added':\n return `Approach: ${data.name || 'unnamed'}`;\n case 'approach_selected':\n return `Selected: ${data.approach || 'unknown'}`;\n case 'shaping_started':\n return 'Shaping started';\n case 'checkpoint_created':\n return `Checkpoint: ${data.name || 'unnamed'}`;\n case 'step_reflected':\n return `Step ${data.step || '?'} reflection: ${truncate(data.reflection, 60)}`;\n default:\n return type;\n }\n}\n\n/**\n * Truncate string to max length\n */\nfunction truncate(str: string, maxLength: number): string {\n if (!str) return '';\n if (str.length <= maxLength) return str;\n return str.substring(0, maxLength - 3) + '...';\n}\n\n/**\n * Attributed content item from merged catalyst\n */\ninterface AttributedContentItem {\n content: string;\n sourceId: string;\n filename?: string;\n}\n\n/**\n * Convert merged catalyst to the format needed by GenerationContext\n * \n * Takes a MergedCatalyst from @kjerneverk/riotplan-catalyst and converts it\n * to the catalystContent format used by the generator.\n * \n * The mergedCatalyst parameter uses a simplified type to avoid tight coupling\n * with the riotplan-catalyst package types.\n */\nexport function loadCatalystContent(mergedCatalyst: {\n catalystIds: string[];\n facets: {\n questions?: AttributedContentItem[];\n constraints?: AttributedContentItem[];\n outputTemplates?: AttributedContentItem[];\n domainKnowledge?: AttributedContentItem[];\n processGuidance?: AttributedContentItem[];\n validationRules?: AttributedContentItem[];\n };\n} | null): ArtifactBundle['catalystContent'] | undefined {\n if (!mergedCatalyst) {\n return undefined;\n }\n \n // Helper to render facet content with source attribution\n const renderFacet = (facetContent: AttributedContentItem[] | undefined): string => {\n if (!facetContent || facetContent.length === 0) {\n return '';\n }\n \n // Group content by source catalyst\n const bySource = new Map<string, string[]>();\n for (const item of facetContent) {\n const existing = bySource.get(item.sourceId) || [];\n existing.push(item.content);\n bySource.set(item.sourceId, existing);\n }\n \n // Render with source headers\n const parts: string[] = [];\n for (const [sourceId, contents] of bySource) {\n parts.push(`### From ${sourceId}\\n\\n${contents.join('\\n\\n')}`);\n }\n \n return parts.join('\\n\\n');\n };\n \n return {\n constraints: renderFacet(mergedCatalyst.facets.constraints),\n domainKnowledge: renderFacet(mergedCatalyst.facets.domainKnowledge),\n outputTemplates: renderFacet(mergedCatalyst.facets.outputTemplates),\n processGuidance: renderFacet(mergedCatalyst.facets.processGuidance),\n questions: renderFacet(mergedCatalyst.facets.questions),\n validationRules: renderFacet(mergedCatalyst.facets.validationRules),\n appliedCatalysts: mergedCatalyst.catalystIds,\n };\n}\n\n/**\n * Load all plan artifacts into a structured bundle\n * \n * This is the main entry point for artifact loading, used by build.ts\n */\nexport async function loadArtifacts(planPath: string): Promise<ArtifactBundle> {\n if (planPath.endsWith('.plan')) {\n const provider = createSqliteProvider(planPath);\n try {\n const [filesResult, metadataResult, evidenceResult, allEventsResult] = await Promise.all([\n provider.getFiles(),\n provider.getMetadata(),\n provider.getEvidence(),\n provider.getTimelineEvents(),\n ]);\n\n if (!filesResult.success) {\n throw new Error(filesResult.error || 'Failed to load plan files from SQLite');\n }\n if (!metadataResult.success || !metadataResult.data) {\n throw new Error(metadataResult.error || 'Failed to load plan metadata from SQLite');\n }\n if (!evidenceResult.success) {\n throw new Error(evidenceResult.error || 'Failed to load evidence from SQLite');\n }\n if (!allEventsResult.success) {\n throw new Error(allEventsResult.error || 'Failed to load timeline events from SQLite');\n }\n\n const files = filesResult.data || [];\n const ideaContent =\n getMostRecentArtifactContent(files, ['idea'], ['IDEA.md', 'idea']) ||\n getMostRecentFileByType(files, 'idea');\n const shapingContent =\n getMostRecentArtifactContent(files, ['shaping'], ['SHAPING.md', 'shaping']) ||\n getMostRecentFileByType(files, 'shaping');\n\n const lifecycleFile =\n getMostRecentArtifactContent(files, ['lifecycle'], ['LIFECYCLE.md', 'lifecycle']) ||\n getMostRecentFileByType(files, 'lifecycle');\n const lifecycleContent = lifecycleFile || `# Lifecycle\n\n## Current Stage\n\n**Stage**: \\`${metadataResult.data.stage}\\`\n**Since**: ${metadataResult.data.updatedAt}\n`;\n\n const evidence = (evidenceResult.data || []).map((entry) => {\n const body = entry.content || entry.summary || entry.description;\n return {\n name: entry.filePath || `${entry.id}.md`,\n content: body,\n size: Buffer.byteLength(body, 'utf-8'),\n };\n });\n\n const events = (allEventsResult.data || [])\n .slice()\n .sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp));\n const recentEvents = events.slice(-15).map((event) => ({\n type: event.type || 'unknown',\n timestamp: event.timestamp || '',\n summary: summarizeEvent(event),\n }));\n\n const constraints = ideaContent ? extractConstraints(ideaContent) : [];\n const questions = ideaContent ? extractQuestions(ideaContent) : [];\n const selectedApproach = shapingContent ? extractSelectedApproach(shapingContent) : null;\n\n return {\n ideaContent,\n shapingContent,\n lifecycleContent,\n artifactDiagnostics: {\n planId: planPath,\n hasIdeaArtifact: Boolean(ideaContent),\n detectedArtifacts: files.map((file) => ({\n type: file.type,\n filename: file.filename,\n })),\n },\n constraints,\n questions,\n selectedApproach,\n evidence,\n historyContext: {\n recentEvents,\n totalEvents: events.length,\n },\n };\n } finally {\n await provider.close();\n }\n }\n\n // Read all files in parallel\n const [ideaContent, shapingContent, lifecycleContent, evidence, history] = await Promise.all([\n readFileSafe(join(planPath, 'IDEA.md')),\n readFileSafe(join(planPath, 'SHAPING.md')),\n readFileSafe(join(planPath, 'LIFECYCLE.md')),\n readEvidenceFiles(planPath, true),\n readRecentHistory(planPath),\n ]);\n \n // Extract structured data\n const constraints = ideaContent ? extractConstraints(ideaContent) : [];\n const questions = ideaContent ? extractQuestions(ideaContent) : [];\n const selectedApproach = shapingContent ? extractSelectedApproach(shapingContent) : null;\n \n return {\n ideaContent,\n shapingContent,\n lifecycleContent,\n artifactDiagnostics: {\n planId: planPath,\n hasIdeaArtifact: Boolean(ideaContent),\n detectedArtifacts: [\n ...(ideaContent ? [{ type: 'idea', filename: 'IDEA.md' }] : []),\n ...(shapingContent ? [{ type: 'shaping', filename: 'SHAPING.md' }] : []),\n ...(lifecycleContent ? [{ type: 'lifecycle', filename: 'LIFECYCLE.md' }] : []),\n ],\n },\n constraints,\n questions,\n selectedApproach,\n evidence,\n historyContext: history,\n };\n}\n"],"names":["ideaContent","shapingContent","lifecycleContent","evidence","constraints","questions","selectedApproach"],"mappings":";;;;;AAcO,MAAM,uBAAoC;AAAA,EAC7C,WAAW;AAAA;AAAA,EACX,uBAAuB;AAAA;AAAA,EACvB,0BAA0B;AAAA;AAAA,EAC1B,kBAAkB;AAAA,EAClB,yBAAyB;AAC7B;AAkBO,SAAS,eAAe,MAAsB;AACjD,SAAO,KAAK,KAAK,KAAK,SAAS,CAAC;AACpC;AAKO,SAAS,gBAAgB,MAAc,WAA2B;AACrE,QAAM,QAAQ,KAAK,MAAM,IAAI;AAC7B,MAAI,MAAM,UAAU,WAA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AC3C,kBAAkB,UAAU,IAAI;AAAA,IAChC,kBAAkB,QAAQ;AAAA,EAAA,CAC7B;AAGD,QAAM,cAAc,cAAc,mBAAmB,WAAW,IAAI,CAAA;AACpE,QAAM,YAAY,cAAc,iBAAiB,WAAW,IAAI,CAAA;AAChE,QAAM,mBAAmB,iBAAiB,wBAAwB,cAAc,IAAI;AAEpF,SAAO;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA,qBAAqB;AAAA,MACjB,QAAQ;AAAA,MACR,iBAAiB,QAAQ,WAAW;AAAA,MACpC,mBAAmB;AAAA,QACf,GAAI,cAAc,CAAC,EAAE,MAAM,QAAQ,UAAU,UAAA,CAAW,IAAI,CAAA;AAAA,QAC5D,GAAI,iBAAiB,CAAC,EAAE,MAAM,WAAW,UAAU,aAAA,CAAc,IAAI,CAAA;AAAA,QACrE,GAAI,mBAAmB,CAAC,EAAE,MAAM,aAAa,UAAU,eAAA,CAAgB,IAAI,CAAA;AAAA,MAAC;AAAA,IAChF;AAAA,IAEJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,EAAA;AAExB;"}
|
package/package.json
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@kjerneverk/riotplan-ai",
|
|
3
|
+
"version": "1.0.0-dev.0",
|
|
4
|
+
"description": "AI plan generation engine for RiotPlan",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=24.0.0"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"clean": "rm -rf dist",
|
|
19
|
+
"build": "npm run lint && vite build",
|
|
20
|
+
"test": "npm run test:coverage",
|
|
21
|
+
"test:coverage": "vitest run --coverage",
|
|
22
|
+
"test:debug": "vitest --run --coverage --reporter verbose",
|
|
23
|
+
"lint": "eslint src",
|
|
24
|
+
"lint:fix": "eslint src --fix",
|
|
25
|
+
"precommit": "npm run build && npm run lint && npm run test",
|
|
26
|
+
"prepublishOnly": "npm run clean && npm run build"
|
|
27
|
+
},
|
|
28
|
+
"keywords": ["riotplan", "ai", "llm", "plan-generation", "provenance"],
|
|
29
|
+
"author": "Tim O'Brien <tobrien@discursive.com>",
|
|
30
|
+
"license": "Apache-2.0",
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "https://github.com/kjerneverk/riotplan-ai"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@kjerneverk/riotplan-format": "^1.0.1"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"@kjerneverk/agentic": "^1.0.8",
|
|
40
|
+
"@kjerneverk/execution": "^1.0.7",
|
|
41
|
+
"@kjerneverk/execution-anthropic": "^1.0.12",
|
|
42
|
+
"@kjerneverk/execution-openai": "^1.0.12",
|
|
43
|
+
"@kjerneverk/execution-sampling": "^1.0.4",
|
|
44
|
+
"@kjerneverk/riotplan-catalyst": "^1.0.6"
|
|
45
|
+
},
|
|
46
|
+
"peerDependenciesMeta": {
|
|
47
|
+
"@kjerneverk/agentic": { "optional": true },
|
|
48
|
+
"@kjerneverk/execution": { "optional": true },
|
|
49
|
+
"@kjerneverk/execution-anthropic": { "optional": true },
|
|
50
|
+
"@kjerneverk/execution-openai": { "optional": true },
|
|
51
|
+
"@kjerneverk/execution-sampling": { "optional": true },
|
|
52
|
+
"@kjerneverk/riotplan-catalyst": { "optional": true }
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@eslint/eslintrc": "^3.3.1",
|
|
56
|
+
"@eslint/js": "^9.28.0",
|
|
57
|
+
"@types/node": "^24.10.9",
|
|
58
|
+
"@typescript-eslint/eslint-plugin": "^8.34.0",
|
|
59
|
+
"@typescript-eslint/parser": "^8.34.0",
|
|
60
|
+
"@vitest/coverage-v8": "^4.0.17",
|
|
61
|
+
"eslint": "^9.28.0",
|
|
62
|
+
"eslint-plugin-import": "^2.31.0",
|
|
63
|
+
"globals": "^17.0.0",
|
|
64
|
+
"typescript": "^5.8.3",
|
|
65
|
+
"vite": "^7.0.4",
|
|
66
|
+
"vite-plugin-dts": "^4.5.4",
|
|
67
|
+
"vitest": "^4.0.17"
|
|
68
|
+
}
|
|
69
|
+
}
|