@crossdelta/pf-mcp 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/audit.ts","../src/effects/executors/deps-add.ts","../src/types/plan.ts","../src/effects/types.ts","../src/effects/utils.ts","../src/effects/executors/env-add.ts","../src/plan-hash.ts","../src/effects/executors/file-write.ts","../src/effects/executors/infra-add.ts","../src/effects/summary.ts","../src/effects/validation.ts","../src/effects/index.ts","../src/plan-cache.ts","../src/policy.ts","../src/resources/contracts.ts","../src/resources/generator-docs.ts","../src/resources/services.ts","../src/resources/templates.ts","../src/resources/workspace-summary.ts","../src/server.ts","../src/response.ts","../src/tools/apply-changes.ts","../src/tools/plan-review.ts","../src/tools/services-generate/index.ts","../src/tools/services-generate/mode-explicit.ts","../src/tools/services-generate/review.ts","../src/tools/services-generate/validation.ts","../src/tools/services-generate/mode-nl.ts","../src/tools/services-generate/npm-verifier.ts","../src/tools/workspace-scan.ts"],"sourcesContent":["/**\n * @crossdelta/pf-mcp\n *\n * Model Context Protocol (MCP) server adapter for Platform SDK\n *\n * This package provides a thin adapter layer between the MCP SDK and Platform SDK,\n * exposing plugin commands as MCP tools.\n *\n * @module\n */\n\nexport type { AuditArtifact } from './audit'\nexport { AUDIT_DIR, createAuditArtifact, generateAuditFilename, writeAuditArtifact } from './audit'\n// Effects\nexport type { DepsAddEffect } from './effects'\nexport { isDepsAddEffect } from './effects'\nexport type { CachedPlan, CachedReview } from './plan-cache'\nexport {\n cachePlan,\n cacheReview,\n clearCache,\n getCacheStats,\n getPlan,\n getReview,\n hasPlan,\n hasReview,\n listPlanHashes,\n listReviewHashes,\n} from './plan-cache'\nexport { computeContentHash, computePlanHash, stableStringify, verifyPlanHash } from './plan-hash'\nexport type { ReviewToken, ReviewTokenValidation } from './policy'\nexport {\n generateReviewToken,\n POLICY_VERSION,\n parseReviewToken,\n validateReviewToken,\n} from './policy'\nexport {\n createAllGeneratorDocResources,\n createAllTemplateResources,\n createGeneratorDocResource,\n createGeneratorDocsListResource,\n createTemplateFileResourceTemplate,\n createTemplateResource,\n createTemplatesListResource,\n readTemplateFile,\n} from './resources'\nexport type { McpServerAutoOptions, McpServerOptions } from './server'\nexport { createMcpServer, createMcpServerFromWorkspace } from './server'\nexport type {\n ApplyChangesInput,\n DependencyIntent,\n DependencyPolicy,\n EnvVarIntent,\n FilePlanEntry,\n GenerationPlanResult,\n PlanIssue,\n PlanIssueSeverity,\n PlanPreview,\n PlanPreviewCounts,\n} from './types'\nexport { DEFAULT_DEPENDENCY_POLICY, isDependencyIntent, isFilePlanEntry } from './types'\n","/**\n * Audit Module\n *\n * Writes audit artifacts for apply_changes operations.\n * Provides traceability for what was applied, when, and by whom.\n *\n * Audit artifacts are stored in: .pf/audit/<planHash>-<timestamp>.json\n *\n * Format:\n * {\n * planHash: string,\n * reviewToken?: string,\n * policyVersion: string,\n * appliedAt: string (ISO),\n * reviewedAt?: string (ISO),\n * dryRun: boolean,\n * summary: string,\n * counts: {...},\n * effects: PfEffect[],\n * results: EffectExecutionResult[]\n * }\n */\n\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { PfEffect } from '@crossdelta/platform-sdk/facade'\nimport type { ApplyResult, EffectExecutionResult } from './effects'\n\n/**\n * Audit artifact data\n */\nexport interface AuditArtifact {\n /** Plan hash (SHA-256) */\n planHash: string\n /** Review token used (if any) */\n reviewToken?: string\n /** Policy version */\n policyVersion: string\n /** ISO timestamp when apply was executed */\n appliedAt: string\n /** ISO timestamp when plan was reviewed (from review token) */\n reviewedAt?: string\n /** Whether this was a dry run */\n dryRun: boolean\n /** Summary message */\n summary: string\n /** Execution counts */\n counts: ApplyResult['counts']\n /** Effects that were applied */\n effects: readonly PfEffect[]\n /** Individual execution results */\n results: readonly EffectExecutionResult[]\n}\n\n/**\n * Audit directory name (relative to workspace root)\n */\nexport const AUDIT_DIR = '.pf/audit'\n\n/**\n * Generate audit artifact filename\n *\n * Format: <planHash>-<timestamp>.json\n * Timestamp is ISO format with colons replaced by dashes for filesystem safety\n */\nexport const generateAuditFilename = (planHash: string, appliedAt: string): string => {\n const safeTimestamp = appliedAt.replace(/:/g, '-').replace(/\\./g, '-')\n return `${planHash.slice(0, 16)}-${safeTimestamp}.json`\n}\n\n/**\n * Write audit artifact to filesystem\n *\n * @param audit - Audit artifact data\n * @param workspaceRoot - Workspace root path\n * @returns Absolute path to written audit file\n */\nexport const writeAuditArtifact = (audit: AuditArtifact, workspaceRoot: string): string => {\n const auditDir = join(workspaceRoot, AUDIT_DIR)\n const filename = generateAuditFilename(audit.planHash, audit.appliedAt)\n const filePath = join(auditDir, filename)\n\n // Ensure audit directory exists\n mkdirSync(dirname(filePath), { recursive: true })\n\n // Write audit file with pretty JSON\n writeFileSync(filePath, JSON.stringify(audit, null, 2), 'utf-8')\n\n return filePath\n}\n\n/**\n * Create audit artifact from apply result\n */\nexport const createAuditArtifact = (\n planHash: string,\n policyVersion: string,\n effects: readonly PfEffect[],\n result: ApplyResult,\n options: {\n reviewToken?: string\n reviewedAt?: string\n } = {},\n): AuditArtifact => ({\n planHash,\n reviewToken: options.reviewToken,\n policyVersion,\n appliedAt: new Date().toISOString(),\n reviewedAt: options.reviewedAt,\n dryRun: result.dryRun,\n summary: result.summary,\n counts: result.counts,\n effects,\n results: result.results,\n})\n","/**\n * Deps Add Executor\n *\n * Handles deps:add effects:\n * - Adds dependency to package.json\n * - Validates against DependencyPolicy (denyPatterns)\n * - Idempotent: skips if dependency already exists with compatible version\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { DEFAULT_DEPENDENCY_POLICY, type DependencyPolicy } from '../../types'\nimport type { ApplyOptions, EffectExecutionResult } from '../types'\nimport { ErrorCodes } from '../types'\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface DepsAddEffect {\n readonly kind: 'deps:add'\n /** Package name */\n readonly name: string\n /** Version constraint (e.g., '^1.0.0', 'latest') */\n readonly version?: string\n /** Whether this is a dev dependency */\n readonly dev?: boolean\n /** Target service directory (relative to workspace root) */\n readonly targetDir?: string\n}\n\n// ============================================================================\n// Type Guard\n// ============================================================================\n\nexport const isDepsAddEffect = (effect: unknown): effect is DepsAddEffect =>\n typeof effect === 'object' &&\n effect !== null &&\n 'kind' in effect &&\n (effect as DepsAddEffect).kind === 'deps:add' &&\n 'name' in effect &&\n typeof (effect as DepsAddEffect).name === 'string'\n\n// ============================================================================\n// Policy Validation (pure)\n// ============================================================================\n\nconst validateDependency = (\n name: string,\n version: string | undefined,\n policy: DependencyPolicy,\n): { valid: true } | { valid: false; reason: string } => {\n // Check name against deny patterns\n for (const pattern of policy.denyPatterns) {\n if (name.startsWith(pattern)) {\n return { valid: false, reason: `Package name matches denied pattern: ${pattern}` }\n }\n }\n\n // Check version against deny patterns\n if (version) {\n for (const pattern of policy.denyPatterns) {\n if (version.startsWith(pattern)) {\n return { valid: false, reason: `Version matches denied pattern: ${pattern}` }\n }\n }\n }\n\n return { valid: true }\n}\n\n// ============================================================================\n// Version Resolution (pure)\n// ============================================================================\n\nconst resolveVersion = (version: string | undefined, policy: DependencyPolicy): string => {\n if (!version || version === 'latest') {\n // For 'latest', we'll use '*' which npm/bun will resolve\n // In production, you'd call npm registry to get actual version\n return '*'\n }\n\n // Apply pinning strategy if version doesn't already have a prefix\n if (/^\\d/.test(version)) {\n switch (policy.pinningStrategy) {\n case 'exact':\n return version\n case 'tilde':\n return `~${version}`\n default:\n return `^${version}`\n }\n }\n\n return version\n}\n\n// ============================================================================\n// Result Creators (pure)\n// ============================================================================\n\nconst createSkipResult = (\n effect: DepsAddEffect,\n packageJsonPath: string,\n existingVersion: string,\n dryRun: boolean,\n): EffectExecutionResult => ({\n effect: effect as unknown as import('../types').FileWriteEffect,\n success: true,\n status: dryRun ? 'would_skip' : 'skipped',\n message: dryRun\n ? `Would skip: ${effect.name}@${existingVersion} already exists`\n : `Dependency ${effect.name}@${existingVersion} already exists`,\n path: packageJsonPath,\n target: effect.name,\n reason: 'dependency exists',\n})\n\nconst createAddResult = (\n effect: DepsAddEffect,\n packageJsonPath: string,\n version: string,\n dryRun: boolean,\n): EffectExecutionResult => ({\n effect: effect as unknown as import('../types').FileWriteEffect,\n success: true,\n status: dryRun ? 'would_create' : 'created',\n message: dryRun ? `Would add dependency: ${effect.name}@${version}` : `Added dependency: ${effect.name}@${version}`,\n path: packageJsonPath,\n target: effect.name,\n})\n\nconst createPolicyViolationResult = (effect: DepsAddEffect, reason: string): EffectExecutionResult => ({\n effect: effect as unknown as import('../types').FileWriteEffect,\n success: false,\n status: 'error',\n message: `Policy violation: ${reason}`,\n target: effect.name,\n code: ErrorCodes.POLICY_VIOLATION,\n reason,\n})\n\nconst createErrorResult = (effect: DepsAddEffect, packageJsonPath: string, error: unknown): EffectExecutionResult => ({\n effect: effect as unknown as import('../types').FileWriteEffect,\n success: false,\n status: 'error',\n message: `Failed to add dependency ${effect.name}: ${error instanceof Error ? error.message : String(error)}`,\n path: packageJsonPath,\n target: effect.name,\n code: ErrorCodes.WRITE_FAILED,\n})\n\nconst createMissingPackageJsonResult = (effect: DepsAddEffect, packageJsonPath: string): EffectExecutionResult => ({\n effect: effect as unknown as import('../types').FileWriteEffect,\n success: false,\n status: 'error',\n message: `package.json not found at ${packageJsonPath}`,\n path: packageJsonPath,\n target: effect.name,\n code: ErrorCodes.WRITE_FAILED,\n})\n\n// ============================================================================\n// Executor\n// ============================================================================\n\nexport const executeDepsAdd = (\n effect: DepsAddEffect,\n workspaceRoot: string,\n options: ApplyOptions,\n policy: DependencyPolicy = DEFAULT_DEPENDENCY_POLICY,\n): EffectExecutionResult => {\n const { name, version, dev = false, targetDir } = effect\n const { dryRun = false } = options\n\n // Determine package.json path\n const baseDir = targetDir ? join(workspaceRoot, targetDir) : workspaceRoot\n const packageJsonPath = join(baseDir, 'package.json')\n\n // Validate against policy\n const validation = validateDependency(name, version, policy)\n if (!validation.valid) {\n return createPolicyViolationResult(effect, validation.reason)\n }\n\n // Check if package.json exists\n if (!existsSync(packageJsonPath)) {\n return createMissingPackageJsonResult(effect, packageJsonPath)\n }\n\n try {\n // Read package.json\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'))\n const depsKey = dev ? 'devDependencies' : 'dependencies'\n const deps = packageJson[depsKey] ?? {}\n\n // Check if dependency already exists\n if (name in deps) {\n return createSkipResult(effect, packageJsonPath, deps[name], dryRun)\n }\n\n // Resolve version with policy\n const resolvedVersion = resolveVersion(version, policy)\n\n if (!dryRun) {\n // Add dependency\n packageJson[depsKey] = {\n ...deps,\n [name]: resolvedVersion,\n }\n\n // Sort dependencies alphabetically\n packageJson[depsKey] = Object.keys(packageJson[depsKey])\n .sort()\n .reduce(\n (acc, key) => {\n acc[key] = packageJson[depsKey][key]\n return acc\n },\n {} as Record<string, string>,\n )\n\n // Write package.json with consistent formatting\n writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\\n`, 'utf-8')\n }\n\n return createAddResult(effect, packageJsonPath, resolvedVersion, dryRun)\n } catch (error) {\n return createErrorResult(effect, packageJsonPath, error)\n }\n}\n","/**\n * Plan Types\n *\n * Types for the deterministic planning system.\n * MCP = Planner (structure), AI = Code Generator (content)\n *\n * Flow:\n * 1. AI/Copilot delivers Intent + Inputs\n * 2. pf generates Plan + Preview (deterministic)\n * 3. Optional: plan_review for validation\n * 4. User OK Gate\n * 5. apply_changes with expectedPlanHash (idempotent)\n */\n\nimport type { PfEffect } from '@crossdelta/platform-sdk/facade'\n\n// ============================================================================\n// Plan Issue (Validation)\n// ============================================================================\n\nexport type PlanIssueSeverity = 'error' | 'warning' | 'info'\n\nexport interface PlanIssue {\n /** Issue severity */\n severity: PlanIssueSeverity\n /** Error code for programmatic handling */\n code: string\n /** Human-readable message */\n message: string\n /** Affected path (if applicable) */\n path?: string\n /** Line number (if applicable) */\n line?: number\n}\n\n// ============================================================================\n// Plan Preview (Rich Artifacts)\n// ============================================================================\n\nexport interface PlanPreviewCounts {\n /** Files that would be created */\n wouldCreate: number\n /** Files that would be updated */\n wouldUpdate: number\n /** Files that would be skipped (no changes) */\n wouldSkip: number\n /** Effects with errors */\n errors: number\n}\n\nexport interface PlanPreview {\n /** Counts by action type */\n counts: PlanPreviewCounts\n /** Total bytes that would be written */\n totalNewBytes: number\n /** Total bytes that would be overwritten */\n totalOldBytes: number\n /** Files grouped by action */\n files: {\n create: string[]\n update: string[]\n skip: string[]\n }\n}\n\n// ============================================================================\n// File Plan Entry (No content - AI generates)\n// ============================================================================\n\nexport interface FilePlanEntry {\n /** Absolute path where file should be created */\n path: string\n /** Human-readable intent (what this file should do) */\n intent: string\n /** Inputs for AI code generation */\n inputs: Record<string, unknown>\n /** File layer for constraint enforcement */\n layer?: 'domain' | 'useCase' | 'adapter' | 'infra' | 'config'\n /** File kind for context */\n kind?: 'handler' | 'adapter' | 'service' | 'useCase' | 'contract' | 'config' | 'test'\n}\n\n// ============================================================================\n// Dependency Intent (for deps:add effect)\n// ============================================================================\n\nexport interface DependencyIntent {\n /** Package name (e.g., '@pusher/push-notifications-server') */\n name: string\n /** Version constraint (e.g., '^1.0.0', 'latest') */\n version?: string\n /** Whether this is a dev dependency */\n dev?: boolean\n /** Reason for adding this dependency */\n reason?: string\n}\n\n// ============================================================================\n// Environment Variable Intent\n// ============================================================================\n\nexport interface EnvVarIntent {\n /** Environment variable key */\n key: string\n /** Description for documentation */\n description: string\n /** Whether this env var is required */\n required: boolean\n /** Example value (for .env.example) */\n example?: string\n}\n\n// ============================================================================\n// Generation Plan Result\n// ============================================================================\n\nexport interface GenerationPlanResult {\n /** Whether plan generation succeeded */\n ok: boolean\n /** Service name */\n serviceName: string\n /** Service directory (relative to workspace) */\n serviceDir: string\n /** Files to generate (paths/intent only - AI fills content) */\n files: FilePlanEntry[]\n /** Effects ready to apply (scaffold files with content) */\n effects: PfEffect[]\n /** Dependencies to add */\n dependencies: DependencyIntent[]\n /** Environment variables needed */\n envVars: EnvVarIntent[]\n /** Post-generation commands */\n postCommands: string[]\n /** SHA-256 hash of the plan for integrity verification */\n planHash: string\n /** Preview of what would happen */\n preview: PlanPreview\n /** Whether plan can be applied (no blocking errors) */\n canApply: boolean\n /** Validation issues */\n issues: PlanIssue[]\n /** Metadata for debugging/logging */\n metadata: Record<string, unknown>\n}\n\n// ============================================================================\n// Apply Changes Input (enhanced)\n// ============================================================================\n\nexport interface ApplyChangesInput {\n /** Effects to apply (AI-generated content merged with plan) */\n changes: PfEffect[]\n /** Optional: Workspace root path */\n workspaceRoot?: string\n /** Optional: Expected plan hash for drift detection */\n expectedPlanHash?: string\n /** Optional: If true, requires a valid reviewToken */\n requireReview?: boolean\n /** Optional: Review token from plan_review */\n reviewToken?: string\n /** Optional: Expected policy version */\n expectedPolicyVersion?: string\n}\n\n// ============================================================================\n// Dependency Policy\n// ============================================================================\n\nexport interface DependencyPolicy {\n /** Patterns to deny (e.g., file:, git+, https://) */\n denyPatterns: string[]\n /** Pinning strategy for new dependencies */\n pinningStrategy: 'caret' | 'exact' | 'tilde'\n /** Registry URL (optional, for private registries) */\n registryUrl?: string\n}\n\nexport const DEFAULT_DEPENDENCY_POLICY: DependencyPolicy = {\n denyPatterns: ['file:', 'git+', 'git://', 'github:', 'https://', 'http://'],\n pinningStrategy: 'caret',\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nexport const isFilePlanEntry = (value: unknown): value is FilePlanEntry =>\n typeof value === 'object' &&\n value !== null &&\n 'path' in value &&\n typeof (value as FilePlanEntry).path === 'string' &&\n 'intent' in value &&\n typeof (value as FilePlanEntry).intent === 'string' &&\n 'inputs' in value &&\n typeof (value as FilePlanEntry).inputs === 'object'\n\nexport const isDependencyIntent = (value: unknown): value is DependencyIntent =>\n typeof value === 'object' && value !== null && 'name' in value && typeof (value as DependencyIntent).name === 'string'\n","/**\n * Effect Executor Types\n *\n * All type definitions for effect execution.\n * Types first, following project conventions.\n */\n\nimport type { PfEffect } from '@crossdelta/platform-sdk/facade'\n\n// ============================================================================\n// Error Codes\n// ============================================================================\n\n/**\n * Error codes for structured error reporting\n */\nexport const ErrorCodes = {\n PATH_OUTSIDE_ROOT: 'PATH_OUTSIDE_ROOT',\n REQUIRES_ELICITATION: 'REQUIRES_ELICITATION',\n UNSUPPORTED_EFFECT: 'UNSUPPORTED_EFFECT',\n WRITE_FAILED: 'WRITE_FAILED',\n ATOMIC_RENAME_FAILED: 'ATOMIC_RENAME_FAILED',\n PLAN_HASH_MISMATCH: 'PLAN_HASH_MISMATCH',\n // M10: Review gate error codes\n REVIEW_REQUIRED: 'REVIEW_REQUIRED',\n REVIEW_TOKEN_INVALID: 'REVIEW_TOKEN_INVALID',\n REVIEW_TOKEN_MISMATCH: 'REVIEW_TOKEN_MISMATCH',\n POLICY_VERSION_MISMATCH: 'POLICY_VERSION_MISMATCH',\n // Policy validation error codes\n POLICY_VIOLATION: 'POLICY_VIOLATION',\n FORBIDDEN_DIR: 'FORBIDDEN_DIR',\n CONSOLE_IN_DOMAIN: 'CONSOLE_IN_DOMAIN',\n PROCESS_ENV_IN_DOMAIN: 'PROCESS_ENV_IN_DOMAIN',\n FETCH_IN_DOMAIN: 'FETCH_IN_DOMAIN',\n} as const\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes]\n\n// ============================================================================\n// Effect Status\n// ============================================================================\n\nexport type EffectStatus = 'created' | 'updated' | 'skipped' | 'error' | 'would_create' | 'would_update' | 'would_skip'\n\n// ============================================================================\n// Preview Info\n// ============================================================================\n\nexport interface PreviewInfo {\n /** Existing file size in bytes */\n oldBytes?: number\n /** New content size in bytes */\n newBytes?: number\n /** SHA-256 hash of existing content */\n oldHash?: string\n /** SHA-256 hash of new content */\n newHash?: string\n /** Would overwrite existing file */\n wouldOverwrite?: boolean\n /** @deprecated Use oldBytes/newBytes */\n existingLength?: number\n /** @deprecated Use oldBytes/newBytes */\n newLength?: number\n}\n\n// ============================================================================\n// Execution Result\n// ============================================================================\n\nexport interface EffectExecutionResult {\n /** Effect that was executed */\n effect: PfEffect\n /** Whether execution succeeded (false for errors and dryRun) */\n success: boolean\n /** Result status */\n status: EffectStatus\n /** Human-readable message */\n message: string\n /** Path affected (if applicable) */\n path?: string\n /** Target identifier (file path, env key, etc.) */\n target?: string\n /** Error code (if error) */\n code?: ErrorCode\n /** Reason for skip/decision */\n reason?: string\n /** Preview info for dryRun (rich artifacts) */\n preview?: PreviewInfo\n}\n\n// ============================================================================\n// Summary\n// ============================================================================\n\nexport interface EffectSummary {\n /** Counts by effect kind */\n byKind: Record<string, { total: number; created: number; updated: number; skipped: number; error: number }>\n /** Total bytes that would be written */\n totalNewBytes: number\n /** Total bytes that would be overwritten */\n totalOldBytes: number\n}\n\nexport interface EffectCounts {\n created: number\n updated: number\n skipped: number\n error: number\n wouldCreate: number\n wouldUpdate: number\n wouldSkip: number\n}\n\n// ============================================================================\n// Policy Violation\n// ============================================================================\n\nexport interface PolicyViolationInfo {\n code: string\n message: string\n path: string\n line?: number\n}\n\n// ============================================================================\n// Apply Result\n// ============================================================================\n\nexport interface ApplyResult {\n /** Overall success (all effects succeeded, or dryRun completed) */\n ok: boolean\n /** Summary message */\n summary: string\n /** Individual effect results */\n results: EffectExecutionResult[]\n /** Counts by status */\n counts: EffectCounts\n /** Whether this was a dry run */\n dryRun: boolean\n /** Error code (if top-level error) */\n code?: ErrorCode\n /** Structured summary (M9: rich preview) */\n structuredSummary?: EffectSummary\n /** Policy violations (if any) */\n policyViolations?: PolicyViolationInfo[]\n}\n\n// ============================================================================\n// Apply Options\n// ============================================================================\n\nexport interface ApplyOptions {\n /** Preview mode - don't write to filesystem */\n dryRun?: boolean\n /** Framework for policy validation (e.g., 'hono', 'nestjs') */\n framework?: 'hono' | 'nestjs'\n}\n\n// ============================================================================\n// Effect Types (narrowed from PfEffect)\n// ============================================================================\n\nexport interface FileWriteEffect extends PfEffect {\n readonly kind: 'file:write'\n readonly path: string\n readonly content: string\n}\n\nexport interface EnvAddEffect extends PfEffect {\n readonly kind: 'env:add'\n readonly key: string\n readonly value: string\n}\n\nexport interface InfraAddEffect extends PfEffect {\n readonly kind: 'infra:add'\n readonly serviceName: string\n readonly port: number\n readonly framework: string\n readonly runtime: string\n}\n\n// ============================================================================\n// Executor Function Type\n// ============================================================================\n\nexport type EffectExecutor<T extends PfEffect = PfEffect> = (\n effect: T,\n workspaceRoot: string,\n options: ApplyOptions,\n) => EffectExecutionResult\n\n// ============================================================================\n// Path Resolution Result\n// ============================================================================\n\nexport type SafePathResult = { safe: true; absolutePath: string } | { safe: false; reason: string }\n","/**\n * Effect Utilities\n *\n * Pure helper functions for effect execution.\n * No side effects except where explicitly noted (atomicWriteFile).\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\n\nimport type { SafePathResult } from './types'\n\n// ============================================================================\n// Pure Functions\n// ============================================================================\n\n/**\n * Normalize line endings for consistent comparison\n * Converts \\r\\n and \\r to \\n\n */\nexport const normalizeLineEndings = (content: string): string => content.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n')\n\n/**\n * Check if a path is safely within the workspace root\n * Returns the resolved absolute path if safe, error reason if unsafe\n */\nexport const resolveSafePath = (targetPath: string, workspaceRoot: string): SafePathResult => {\n const resolvedRoot = resolve(workspaceRoot)\n const absolutePath = targetPath.startsWith('/') ? resolve(targetPath) : resolve(workspaceRoot, targetPath)\n\n const isWithinRoot = absolutePath.startsWith(`${resolvedRoot}/`) || absolutePath === resolvedRoot\n\n return isWithinRoot\n ? { safe: true, absolutePath }\n : { safe: false, reason: `Path \"${targetPath}\" resolves outside workspace root` }\n}\n\n/**\n * Read file content safely, returns undefined if file doesn't exist\n */\nexport const readFileSafe = (absolutePath: string): string | undefined =>\n existsSync(absolutePath) ? readFileSync(absolutePath, 'utf-8') : undefined\n\n/**\n * Check if file exists\n */\nexport const fileExists = (absolutePath: string): boolean => existsSync(absolutePath)\n\n// ============================================================================\n// IO Functions (side effects)\n// ============================================================================\n\n/**\n * Atomic write: Write to temp file, then rename\n * This prevents partial writes on crash/interrupt\n *\n * NOTE: This function has side effects (writes to filesystem)\n */\nexport const atomicWriteFile = (absolutePath: string, content: string): void => {\n const dir = dirname(absolutePath)\n mkdirSync(dir, { recursive: true })\n\n const tempPath = join(dir, `.tmp-${randomUUID()}`)\n\n try {\n writeFileSync(tempPath, content, 'utf-8')\n renameSync(tempPath, absolutePath)\n } catch (error) {\n cleanupTempFile(tempPath)\n throw error\n }\n}\n\n/**\n * Append content to a file, creating it if it doesn't exist\n *\n * NOTE: This function has side effects (writes to filesystem)\n */\nexport const appendToFile = (absolutePath: string, content: string): void => {\n const dir = dirname(absolutePath)\n mkdirSync(dir, { recursive: true })\n\n const existing = readFileSafe(absolutePath) ?? ''\n const newContent = existing ? `${existing}\\n${content}` : content\n\n writeFileSync(absolutePath, newContent, 'utf-8')\n}\n\n// ============================================================================\n// Internal Helpers\n// ============================================================================\n\nconst cleanupTempFile = (tempPath: string): void => {\n try {\n if (existsSync(tempPath)) {\n unlinkSync(tempPath)\n }\n } catch {\n // Ignore cleanup errors\n }\n}\n","/**\n * Env Add Executor\n *\n * Handles env:add effects:\n * - Appends to .env.local if key doesn't exist\n * - Idempotent: skips if key already exists\n */\n\nimport type { ApplyOptions, EffectExecutionResult, EnvAddEffect } from '../types'\nimport { ErrorCodes } from '../types'\nimport { atomicWriteFile, normalizeLineEndings, readFileSafe } from '../utils'\n\n// ============================================================================\n// Result Creators (pure)\n// ============================================================================\n\nconst createSkipResult = (\n effect: EnvAddEffect,\n key: string,\n envPath: string,\n dryRun: boolean,\n): EffectExecutionResult => ({\n effect,\n success: true,\n status: dryRun ? 'would_skip' : 'skipped',\n message: dryRun ? `Would skip: ${key} already exists` : `Env var ${key} already exists`,\n path: envPath,\n target: key,\n reason: 'key exists',\n})\n\nconst createAddResult = (\n effect: EnvAddEffect,\n key: string,\n envPath: string,\n dryRun: boolean,\n): EffectExecutionResult => ({\n effect,\n success: true,\n status: dryRun ? 'would_create' : 'created',\n message: dryRun ? `Would add env var: ${key}` : `Added env var: ${key}`,\n path: envPath,\n target: key,\n})\n\nconst createErrorResult = (\n effect: EnvAddEffect,\n key: string,\n envPath: string,\n error: unknown,\n): EffectExecutionResult => ({\n effect,\n success: false,\n status: 'error',\n message: `Failed to add env var ${key}: ${error instanceof Error ? error.message : String(error)}`,\n path: envPath,\n target: key,\n code: ErrorCodes.WRITE_FAILED,\n})\n\n// ============================================================================\n// Core Logic (pure decision making)\n// ============================================================================\n\nconst keyExists = (content: string, key: string): boolean => {\n const keyRegex = new RegExp(`^${key}=`, 'm')\n return keyRegex.test(content)\n}\n\nconst buildNewContent = (existingContent: string, key: string, value: string): string => {\n const normalized = normalizeLineEndings(existingContent)\n const needsNewline = normalized.length > 0 && !normalized.endsWith('\\n')\n const prefix = needsNewline ? '\\n' : ''\n return `${normalized}${prefix}${key}=${value}\\n`\n}\n\n// ============================================================================\n// Executor\n// ============================================================================\n\nexport const executeEnvAdd = (\n effect: EnvAddEffect,\n workspaceRoot: string,\n options: ApplyOptions,\n): EffectExecutionResult => {\n const { key, value } = effect\n const { dryRun = false } = options\n const envPath = `${workspaceRoot}/.env.local`\n\n try {\n const existingContent = readFileSafe(envPath) ?? ''\n\n if (keyExists(existingContent, key)) {\n return createSkipResult(effect, key, envPath, dryRun)\n }\n\n if (!dryRun) {\n const newContent = buildNewContent(existingContent, key, value)\n atomicWriteFile(envPath, newContent)\n }\n\n return createAddResult(effect, key, envPath, dryRun)\n } catch (error) {\n return createErrorResult(effect, key, envPath, error)\n }\n}\n","/**\n * Plan Hash Module\n *\n * Provides deterministic hashing for effect plans.\n * Used for integrity verification between generate→review→apply flow.\n *\n * Key Features:\n * - stableStringify: Deterministic JSON serialization (sorted keys)\n * - computePlanHash: SHA-256 hex hash of normalized plan\n * - computeContentHash: SHA-256 hex hash of file content\n */\n\nimport { createHash } from 'node:crypto'\nimport type { PfEffect } from '@crossdelta/platform-sdk/facade'\n\n/**\n * Stable JSON stringify with deterministic key ordering\n *\n * Ensures identical plans always produce identical strings,\n * regardless of object key insertion order.\n *\n * @param value - Any JSON-serializable value\n * @returns Deterministic JSON string\n */\nexport const stableStringify = (value: unknown): string => {\n if (value === null || value === undefined) {\n return JSON.stringify(value)\n }\n\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(',')}]`\n }\n\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>\n const sortedKeys = Object.keys(obj).sort()\n const pairs = sortedKeys.map((key) => `${JSON.stringify(key)}:${stableStringify(obj[key])}`)\n return `{${pairs.join(',')}}`\n }\n\n return JSON.stringify(value)\n}\n\n/**\n * Compute SHA-256 hash of a plan (effects array)\n *\n * Uses stableStringify for deterministic serialization.\n * Returns lowercase hex string.\n *\n * @param changes - Array of effects to hash\n * @returns SHA-256 hex hash (64 characters)\n */\nexport const computePlanHash = (changes: readonly PfEffect[]): string => {\n const normalized = stableStringify(changes)\n return createHash('sha256').update(normalized, 'utf-8').digest('hex')\n}\n\n/**\n * Compute SHA-256 hash of file content\n *\n * Uses UTF-8 encoding. Returns lowercase hex string.\n *\n * @param content - File content string\n * @returns SHA-256 hex hash (64 characters)\n */\nexport const computeContentHash = (content: string): string =>\n createHash('sha256').update(content, 'utf-8').digest('hex')\n\n/**\n * Verify plan hash matches expected value\n *\n * @param changes - Current effects array\n * @param expectedHash - Expected hash to verify against\n * @returns true if hashes match, false otherwise\n */\nexport const verifyPlanHash = (changes: readonly PfEffect[], expectedHash: string): boolean => {\n const actualHash = computePlanHash(changes)\n return actualHash === expectedHash\n}\n","/**\n * File Write Executor\n *\n * Handles file:write effects with:\n * - Idempotent writes (skip if content identical)\n * - Atomic writes (temp file + rename)\n * - Path safety checks\n * - Line ending normalization\n */\n\nimport { computeContentHash } from '../../plan-hash'\nimport type { ApplyOptions, EffectExecutionResult, FileWriteEffect } from '../types'\nimport { ErrorCodes } from '../types'\nimport { atomicWriteFile, normalizeLineEndings, readFileSafe, resolveSafePath } from '../utils'\n\n// ============================================================================\n// Result Creators (pure)\n// ============================================================================\n\nconst createPathSafetyError = (\n effect: FileWriteEffect,\n relativePath: string,\n reason: string,\n): EffectExecutionResult => ({\n effect,\n success: false,\n status: 'error',\n message: reason,\n target: relativePath,\n code: ErrorCodes.PATH_OUTSIDE_ROOT,\n})\n\nconst createSkipResult = (\n effect: FileWriteEffect,\n relativePath: string,\n absolutePath: string,\n dryRun: boolean,\n existingContent: string,\n newContent: string,\n): EffectExecutionResult => ({\n effect,\n success: true,\n status: dryRun ? 'would_skip' : 'skipped',\n message: dryRun ? `Would skip (unchanged): ${relativePath}` : `File unchanged: ${relativePath}`,\n path: absolutePath,\n target: relativePath,\n reason: 'content identical',\n preview: {\n oldBytes: existingContent.length,\n newBytes: newContent.length,\n oldHash: computeContentHash(existingContent),\n newHash: computeContentHash(newContent),\n wouldOverwrite: false,\n existingLength: existingContent.length,\n newLength: newContent.length,\n },\n})\n\nconst createUpdateResult = (\n effect: FileWriteEffect,\n relativePath: string,\n absolutePath: string,\n dryRun: boolean,\n existingContent: string,\n newContent: string,\n): EffectExecutionResult => ({\n effect,\n success: true,\n status: dryRun ? 'would_update' : 'updated',\n message: dryRun ? `Would update: ${relativePath}` : `Updated: ${relativePath}`,\n path: absolutePath,\n target: relativePath,\n reason: 'content differs',\n preview: {\n oldBytes: existingContent.length,\n newBytes: newContent.length,\n oldHash: computeContentHash(existingContent),\n newHash: computeContentHash(newContent),\n wouldOverwrite: true,\n existingLength: existingContent.length,\n newLength: newContent.length,\n },\n})\n\nconst createCreateResult = (\n effect: FileWriteEffect,\n relativePath: string,\n absolutePath: string,\n dryRun: boolean,\n newContent: string,\n): EffectExecutionResult => ({\n effect,\n success: true,\n status: dryRun ? 'would_create' : 'created',\n message: dryRun ? `Would create: ${relativePath}` : `Created: ${relativePath}`,\n path: absolutePath,\n target: relativePath,\n preview: {\n newBytes: newContent.length,\n newHash: computeContentHash(newContent),\n wouldOverwrite: false,\n newLength: newContent.length,\n },\n})\n\nconst createWriteError = (\n effect: FileWriteEffect,\n relativePath: string,\n absolutePath: string,\n error: unknown,\n): EffectExecutionResult => ({\n effect,\n success: false,\n status: 'error',\n message: `Failed to write ${relativePath}: ${error instanceof Error ? error.message : String(error)}`,\n path: absolutePath,\n target: relativePath,\n code: ErrorCodes.WRITE_FAILED,\n})\n\n// ============================================================================\n// Core Logic (pure decision making)\n// ============================================================================\n\ntype WriteDecisionResult =\n | { action: 'create' }\n | { action: 'skip'; existingContent: string }\n | { action: 'update'; existingContent: string }\n\nconst decideWriteAction = (absolutePath: string, normalizedContent: string): WriteDecisionResult => {\n const existing = readFileSafe(absolutePath)\n\n if (existing === undefined) {\n return { action: 'create' }\n }\n\n const normalizedExisting = normalizeLineEndings(existing)\n return normalizedExisting === normalizedContent\n ? { action: 'skip', existingContent: normalizedExisting }\n : { action: 'update', existingContent: normalizedExisting }\n}\n\n// ============================================================================\n// Executor (orchestrates decision + IO)\n// ============================================================================\n\nexport const executeFileWrite = (\n effect: FileWriteEffect,\n workspaceRoot: string,\n options: ApplyOptions,\n): EffectExecutionResult => {\n const { path: relativePath, content } = effect\n const { dryRun = false } = options\n\n // 1. Path safety check\n const pathResult = resolveSafePath(relativePath, workspaceRoot)\n if (!pathResult.safe) {\n return createPathSafetyError(effect, relativePath, pathResult.reason)\n }\n\n const { absolutePath } = pathResult\n const normalizedContent = normalizeLineEndings(content)\n\n try {\n // 2. Decide action\n const decision = decideWriteAction(absolutePath, normalizedContent)\n\n // 3. Execute based on decision\n switch (decision.action) {\n case 'skip':\n return createSkipResult(effect, relativePath, absolutePath, dryRun, decision.existingContent, normalizedContent)\n\n case 'update':\n if (!dryRun) {\n atomicWriteFile(absolutePath, normalizedContent)\n }\n return createUpdateResult(\n effect,\n relativePath,\n absolutePath,\n dryRun,\n decision.existingContent,\n normalizedContent,\n )\n\n case 'create':\n if (!dryRun) {\n atomicWriteFile(absolutePath, normalizedContent)\n }\n return createCreateResult(effect, relativePath, absolutePath, dryRun, normalizedContent)\n }\n } catch (error) {\n return createWriteError(effect, relativePath, absolutePath, error)\n }\n}\n","/**\n * Infra Add Executor\n *\n * Handles infra:add effects:\n * - Creates infra/services/{serviceName}.ts\n * - Idempotent: skips if content identical\n */\n\nimport type { ApplyOptions, EffectExecutionResult, InfraAddEffect } from '../types'\nimport { ErrorCodes } from '../types'\nimport { atomicWriteFile, normalizeLineEndings, readFileSafe, resolveSafePath } from '../utils'\n\n// ============================================================================\n// Result Creators (pure)\n// ============================================================================\n\nconst createPathSafetyError = (\n effect: InfraAddEffect,\n relativePath: string,\n reason: string,\n): EffectExecutionResult => ({\n effect,\n success: false,\n status: 'error',\n message: reason,\n target: relativePath,\n code: ErrorCodes.PATH_OUTSIDE_ROOT,\n})\n\nconst createSkipResult = (\n effect: InfraAddEffect,\n serviceName: string,\n absolutePath: string,\n relativePath: string,\n dryRun: boolean,\n): EffectExecutionResult => ({\n effect,\n success: true,\n status: dryRun ? 'would_skip' : 'skipped',\n message: dryRun ? `Would skip (unchanged): ${serviceName}` : `Infra config unchanged: ${serviceName}`,\n path: absolutePath,\n target: relativePath,\n reason: 'content identical',\n})\n\nconst createUpdateResult = (\n effect: InfraAddEffect,\n serviceName: string,\n absolutePath: string,\n relativePath: string,\n dryRun: boolean,\n): EffectExecutionResult => ({\n effect,\n success: true,\n status: dryRun ? 'would_update' : 'updated',\n message: dryRun ? `Would update infra config: ${serviceName}` : `Updated infra config: ${serviceName}`,\n path: absolutePath,\n target: relativePath,\n})\n\nconst createCreateResult = (\n effect: InfraAddEffect,\n serviceName: string,\n absolutePath: string,\n relativePath: string,\n dryRun: boolean,\n): EffectExecutionResult => ({\n effect,\n success: true,\n status: dryRun ? 'would_create' : 'created',\n message: dryRun ? `Would create infra config: ${serviceName}` : `Created infra config: ${serviceName}`,\n path: absolutePath,\n target: relativePath,\n})\n\nconst createErrorResult = (\n effect: InfraAddEffect,\n serviceName: string,\n absolutePath: string,\n relativePath: string,\n error: unknown,\n): EffectExecutionResult => ({\n effect,\n success: false,\n status: 'error',\n message: `Failed to create infra config for ${serviceName}: ${error instanceof Error ? error.message : String(error)}`,\n path: absolutePath,\n target: relativePath,\n code: ErrorCodes.WRITE_FAILED,\n})\n\n// ============================================================================\n// Content Generation (pure)\n// ============================================================================\n\nconst generateInfraContent = (serviceName: string, port: number): string =>\n `import { ports, type K8sServiceConfig } from '@crossdelta/infrastructure'\n\nconst config: K8sServiceConfig = {\n name: '${serviceName}',\n ports: ports().http(${port}).build(),\n replicas: 1,\n healthCheck: { httpPath: '/health' },\n resources: {\n requests: { cpu: '50m', memory: '64Mi' },\n limits: { cpu: '150m', memory: '128Mi' },\n },\n}\n\nexport default config\n`\n\n// ============================================================================\n// Core Logic (pure decision making)\n// ============================================================================\n\ntype InfraDecisionResult = { action: 'create' } | { action: 'skip' } | { action: 'update' }\n\nconst decideInfraAction = (absolutePath: string, normalizedContent: string): InfraDecisionResult => {\n const existing = readFileSafe(absolutePath)\n\n if (existing === undefined) {\n return { action: 'create' }\n }\n\n const normalizedExisting = normalizeLineEndings(existing)\n return normalizedExisting === normalizedContent ? { action: 'skip' } : { action: 'update' }\n}\n\n// ============================================================================\n// Executor\n// ============================================================================\n\nexport const executeInfraAdd = (\n effect: InfraAddEffect,\n workspaceRoot: string,\n options: ApplyOptions,\n): EffectExecutionResult => {\n const { serviceName, port } = effect\n const { dryRun = false } = options\n const relativePath = `infra/services/${serviceName}.ts`\n\n // 1. Path safety check\n const pathResult = resolveSafePath(relativePath, workspaceRoot)\n if (!pathResult.safe) {\n return createPathSafetyError(effect, relativePath, pathResult.reason)\n }\n\n const { absolutePath } = pathResult\n const content = generateInfraContent(serviceName, port)\n const normalizedContent = normalizeLineEndings(content)\n\n try {\n // 2. Decide action\n const decision = decideInfraAction(absolutePath, normalizedContent)\n\n // 3. Execute based on decision\n switch (decision.action) {\n case 'skip':\n return createSkipResult(effect, serviceName, absolutePath, relativePath, dryRun)\n\n case 'update':\n if (!dryRun) {\n atomicWriteFile(absolutePath, content)\n }\n return createUpdateResult(effect, serviceName, absolutePath, relativePath, dryRun)\n\n case 'create':\n if (!dryRun) {\n atomicWriteFile(absolutePath, content)\n }\n return createCreateResult(effect, serviceName, absolutePath, relativePath, dryRun)\n }\n } catch (error) {\n return createErrorResult(effect, serviceName, absolutePath, relativePath, error)\n }\n}\n","/**\n * Summary Building\n *\n * Pure functions for building effect execution summaries.\n */\n\nimport type { EffectCounts, EffectExecutionResult, EffectStatus, EffectSummary } from './types'\n\n// ============================================================================\n// Types\n// ============================================================================\n\ntype KindCounts = EffectSummary['byKind'][string]\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst statusCountMap: Record<EffectStatus, keyof EffectCounts> = {\n created: 'created',\n updated: 'updated',\n skipped: 'skipped',\n error: 'error',\n would_create: 'wouldCreate',\n would_update: 'wouldUpdate',\n would_skip: 'wouldSkip',\n}\n\nconst initialCounts: EffectCounts = {\n created: 0,\n updated: 0,\n skipped: 0,\n error: 0,\n wouldCreate: 0,\n wouldUpdate: 0,\n wouldSkip: 0,\n}\n\nconst initialKindCounts: KindCounts = { total: 0, created: 0, updated: 0, skipped: 0, error: 0 }\n\n// ============================================================================\n// Counts (pure)\n// ============================================================================\n\nexport const createInitialCounts = (): EffectCounts => ({ ...initialCounts })\n\n/**\n * Increment count for a status key (returns new object)\n */\nconst incrementCount = (counts: EffectCounts, key: keyof EffectCounts): EffectCounts => ({\n ...counts,\n [key]: counts[key] + 1,\n})\n\n/**\n * Aggregate counts from results (pure)\n */\nexport const aggregateCounts = (results: readonly EffectExecutionResult[]): EffectCounts =>\n results.reduce((acc, r) => {\n const key = statusCountMap[r.status]\n return key ? incrementCount(acc, key) : acc\n }, createInitialCounts())\n\n// ============================================================================\n// Summary String Building (pure)\n// ============================================================================\n\nconst dryRunSummaryParts = (counts: EffectCounts): string[] =>\n [\n counts.wouldCreate > 0 ? `${counts.wouldCreate} would be created` : '',\n counts.wouldUpdate > 0 ? `${counts.wouldUpdate} would be updated` : '',\n counts.wouldSkip > 0 ? `${counts.wouldSkip} would be skipped` : '',\n ].filter(Boolean)\n\nconst normalSummaryParts = (counts: EffectCounts): string[] =>\n [\n counts.created > 0 ? `${counts.created} created` : '',\n counts.updated > 0 ? `${counts.updated} updated` : '',\n counts.skipped > 0 ? `${counts.skipped} skipped` : '',\n ].filter(Boolean)\n\nexport const buildSummary = (counts: EffectCounts, dryRun: boolean): string => {\n const modeParts = dryRun ? dryRunSummaryParts(counts) : normalSummaryParts(counts)\n const errorPart = counts.error > 0 ? [`${counts.error} errors`] : []\n const parts = [...modeParts, ...errorPart]\n\n return parts.length > 0 ? parts.join(', ') : 'No effects to apply'\n}\n\n// ============================================================================\n// Structured Summary (M9 Rich Preview) - pure\n// ============================================================================\n\nconst statusToKindKey = (status: EffectStatus): keyof KindCounts | null => {\n switch (status) {\n case 'created':\n case 'would_create':\n return 'created'\n case 'updated':\n case 'would_update':\n return 'updated'\n case 'skipped':\n case 'would_skip':\n return 'skipped'\n case 'error':\n return 'error'\n default:\n return null\n }\n}\n\nconst incrementKindCounts = (counts: KindCounts, status: EffectStatus): KindCounts => {\n const key = statusToKindKey(status)\n return key ? { ...counts, total: counts.total + 1, [key]: counts[key] + 1 } : { ...counts, total: counts.total + 1 }\n}\n\nconst updateByKind = (\n byKind: EffectSummary['byKind'],\n kind: string,\n status: EffectStatus,\n): EffectSummary['byKind'] => ({\n ...byKind,\n [kind]: incrementKindCounts(byKind[kind] ?? { ...initialKindCounts }, status),\n})\n\nexport const buildStructuredSummary = (results: readonly EffectExecutionResult[]): EffectSummary =>\n results.reduce(\n (acc, r) => ({\n byKind: updateByKind(acc.byKind, r.effect.kind, r.status),\n totalNewBytes: acc.totalNewBytes + (r.preview?.newBytes ?? 0),\n totalOldBytes: acc.totalOldBytes + (r.preview?.oldBytes ?? 0),\n }),\n { byKind: {} as EffectSummary['byKind'], totalNewBytes: 0, totalOldBytes: 0 },\n )\n","/**\n * Policy Validation\n *\n * Validates effects against serviceLayoutPolicy before execution.\n * Returns violations that block apply.\n */\n\nimport type { PfEffect, PlannedFile, PolicyViolation, ServiceFramework } from '@crossdelta/platform-sdk/facade'\nimport { validateGeneratedFiles } from '@crossdelta/platform-sdk/facade'\n\nimport type { ApplyResult, ErrorCode, FileWriteEffect, InfraAddEffect } from './types'\nimport { ErrorCodes } from './types'\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type { PlannedFile, PolicyViolation, ServiceFramework }\n\n// ============================================================================\n// Pure Functions\n// ============================================================================\n\n/**\n * Extract file:write effects as PlannedFile for policy validation\n */\nexport const extractPlannedFiles = (effects: readonly PfEffect[]): PlannedFile[] =>\n effects\n .filter((e): e is FileWriteEffect => e.kind === 'file:write')\n .map((e) => ({ path: e.path, content: e.content }))\n\n/**\n * Detect framework from infra:add effect (if present)\n */\nexport const detectFramework = (effects: readonly PfEffect[]): ServiceFramework | undefined => {\n const infraEffect = effects.find((e): e is InfraAddEffect => e.kind === 'infra:add')\n if (!infraEffect) return undefined\n\n const frameworkMap: Record<string, ServiceFramework> = {\n hono: 'hono',\n nest: 'nestjs',\n nestjs: 'nestjs',\n }\n return frameworkMap[infraEffect.framework]\n}\n\n/**\n * Create ApplyResult for policy violations\n */\nexport const createPolicyViolationResult = (violations: readonly PolicyViolation[], dryRun: boolean): ApplyResult => ({\n ok: false,\n summary: `Policy violations: ${violations.length} issue(s) found`,\n results: violations.map((v) => ({\n effect: { kind: 'file:write', path: v.path, content: '' } as FileWriteEffect,\n success: false,\n status: 'error' as const,\n message: v.message,\n path: v.path,\n target: v.path,\n code: v.code as ErrorCode,\n })),\n counts: {\n created: 0,\n updated: 0,\n skipped: 0,\n error: violations.length,\n wouldCreate: 0,\n wouldUpdate: 0,\n wouldSkip: 0,\n },\n dryRun,\n code: ErrorCodes.POLICY_VIOLATION,\n policyViolations: [...violations],\n})\n\n// ============================================================================\n// Validation Pipeline\n// ============================================================================\n\nexport type ValidationResult = { valid: true } | { valid: false; result: ApplyResult }\n\n/**\n * Validate effects against policy\n *\n * @param effects - Effects to validate\n * @param framework - Explicit framework or auto-detected\n * @param dryRun - Whether this is a dry run\n * @returns Validation result with ApplyResult if invalid\n */\nexport const validateEffects = (\n effects: readonly PfEffect[],\n framework: ServiceFramework | undefined,\n dryRun: boolean,\n): ValidationResult => {\n // Skip validation if framework unknown\n if (!framework) {\n return { valid: true }\n }\n\n const plannedFiles = extractPlannedFiles(effects)\n const validationResult = validateGeneratedFiles(framework, plannedFiles)\n\n if (validationResult.valid) {\n return { valid: true }\n }\n\n return {\n valid: false,\n result: createPolicyViolationResult(validationResult.violations, dryRun),\n }\n}\n","/**\n * Effect Executor Module\n *\n * Executes effects from OperationResult.changes[].\n * Non-interactive, deterministic, idempotent.\n *\n * Features:\n * - dryRun mode: Preview changes without writing to filesystem\n * - Policy validation: Reject violations before write\n * - Atomic writes: Temp file + rename\n * - Path safety: Reject paths outside workspace root\n *\n * Structure:\n * - types.ts: All type definitions\n * - utils.ts: Pure helper functions\n * - executors/: Individual effect handlers\n * - validation.ts: Policy validation\n * - summary.ts: Summary building\n */\n\nimport type { PfEffect } from '@crossdelta/platform-sdk/facade'\n\nimport { executeDepsAdd, executeEnvAdd, executeFileWrite, executeInfraAdd } from './executors'\nimport { aggregateCounts, buildStructuredSummary, buildSummary, createInitialCounts } from './summary'\nimport type { ApplyOptions, ApplyResult, EffectExecutionResult, EffectExecutor } from './types'\nimport { ErrorCodes } from './types'\nimport { detectFramework, validateEffects } from './validation'\n\n// ============================================================================\n// Re-exports\n// ============================================================================\n\nexport { type DepsAddEffect, isDepsAddEffect } from './executors'\nexport type {\n ApplyOptions,\n ApplyResult,\n EffectCounts,\n EffectExecutionResult,\n EffectStatus,\n EffectSummary,\n EnvAddEffect,\n ErrorCode,\n FileWriteEffect,\n InfraAddEffect,\n PolicyViolationInfo,\n PreviewInfo,\n} from './types'\nexport { ErrorCodes } from './types'\n\n// ============================================================================\n// Executor Registry\n// ============================================================================\n\nconst effectExecutors: Record<string, EffectExecutor> = {\n 'file:write': executeFileWrite as EffectExecutor,\n 'env:add': executeEnvAdd as EffectExecutor,\n 'infra:add': executeInfraAdd as EffectExecutor,\n 'deps:add': executeDepsAdd as EffectExecutor,\n}\n\n// ============================================================================\n// Elicitation Guard\n// ============================================================================\n\nconst isElicitInputEffect = (effect: PfEffect): boolean => effect.kind === 'elicit:input'\n\nconst createElicitationRejection = (elicitEffects: readonly PfEffect[], dryRun: boolean): ApplyResult => ({\n ok: false,\n summary: 'Cannot apply: Plan requires user input (elicitation pending)',\n results: elicitEffects.map((effect) => ({\n effect,\n success: false,\n status: 'error' as const,\n message: 'ElicitInputEffect cannot be applied - requires host interaction',\n code: ErrorCodes.REQUIRES_ELICITATION,\n })),\n counts: {\n ...createInitialCounts(),\n error: elicitEffects.length,\n },\n dryRun,\n})\n\n// ============================================================================\n// Unsupported Effect Handler\n// ============================================================================\n\nconst createUnsupportedEffectResult = (effect: PfEffect): EffectExecutionResult => ({\n effect,\n success: false,\n status: 'error',\n message: `Unsupported effect kind: ${effect.kind}`,\n code: ErrorCodes.UNSUPPORTED_EFFECT,\n})\n\n// ============================================================================\n// Main Entry Point\n// ============================================================================\n\n/**\n * Apply all effects from an OperationResult\n *\n * Non-interactive, deterministic, idempotent.\n * Rejects if any effect is ElicitInputEffect (host-only concern).\n * Validates against serviceLayoutPolicy when framework is specified/detected.\n *\n * @param effects - Effects to apply\n * @param workspaceRoot - Workspace root path\n * @param options - Apply options (dryRun, framework, etc.)\n * @returns ApplyResult with individual results and counts\n */\nexport const applyEffects = (effects: PfEffect[], workspaceRoot: string, options: ApplyOptions = {}): ApplyResult => {\n const { dryRun = false, framework: explicitFramework } = options\n\n // 1. Guard: Check for elicitation effects\n const elicitEffects = effects.filter(isElicitInputEffect)\n if (elicitEffects.length > 0) {\n return createElicitationRejection(elicitEffects, dryRun)\n }\n\n // 2. Policy validation\n const framework = explicitFramework ?? detectFramework(effects)\n const validation = validateEffects(effects, framework, dryRun)\n if (!validation.valid) {\n return validation.result\n }\n\n // 3. Execute effects (functional: map → aggregate)\n const executeEffect = (effect: PfEffect): EffectExecutionResult => {\n const executor = effectExecutors[effect.kind]\n return executor ? executor(effect, workspaceRoot, options) : createUnsupportedEffectResult(effect)\n }\n\n const results = effects.map(executeEffect)\n const counts = aggregateCounts(results)\n\n // 4. Build result\n return {\n ok: counts.error === 0,\n summary: buildSummary(counts, dryRun),\n results,\n counts,\n dryRun,\n structuredSummary: buildStructuredSummary(results),\n }\n}\n\n// ============================================================================\n// Utility Exports\n// ============================================================================\n\n/**\n * Get list of supported effect kinds\n */\nexport const getSupportedEffectKinds = (): string[] => Object.keys(effectExecutors)\n\n/**\n * Check if an effect kind is supported\n */\nexport const isEffectSupported = (kind: string): boolean => kind in effectExecutors\n","/**\n * Plan Cache Module\n *\n * In-memory cache for plans and reviews.\n * Used by MCP resources to retrieve plan/review data by hash.\n *\n * Cache Keys:\n * - plan:<hash> → Plan data (effects array, metadata)\n * - review:<hash> → Review result (from plan_review)\n *\n * Cache is scoped to the MCP server process lifetime.\n * No persistence - restart clears cache.\n */\n\nimport type { PfEffect } from '@crossdelta/platform-sdk/facade'\n\n/**\n * Cached plan entry\n */\nexport interface CachedPlan {\n /** Plan hash (SHA-256) */\n planHash: string\n /** Effects array */\n effects: readonly PfEffect[]\n /** ISO timestamp when plan was created/cached */\n createdAt: string\n /** Source operation (generate_service, etc.) */\n source: string\n /** Optional metadata */\n metadata?: Record<string, unknown>\n}\n\n/**\n * Cached review entry\n */\nexport interface CachedReview {\n /** Plan hash this review is for */\n planHash: string\n /** Policy version at review time */\n policyVersion: string\n /** Review token (planHash.policyVersion) */\n reviewToken: string\n /** ISO timestamp when review was performed */\n reviewedAt: string\n /** Whether the plan passed review */\n valid: boolean\n /** Whether the plan can be applied */\n canApply: boolean\n /** Preview counts */\n preview: {\n wouldCreate: number\n wouldUpdate: number\n wouldSkip: number\n errors: number\n }\n /** Issues found during review */\n issues: ReadonlyArray<{\n severity: 'error' | 'warning' | 'info'\n code: string\n message: string\n target?: string\n }>\n}\n\n/**\n * Plan cache storage\n */\nconst planCache = new Map<string, CachedPlan>()\nconst reviewCache = new Map<string, CachedReview>()\n\n/**\n * Get a cached plan by hash\n */\nexport const getPlan = (planHash: string): CachedPlan | undefined => planCache.get(planHash)\n\n/**\n * Get a cached review by plan hash\n */\nexport const getReview = (planHash: string): CachedReview | undefined => reviewCache.get(planHash)\n\n/**\n * Store a plan in the cache\n */\nexport const cachePlan = (plan: CachedPlan): void => {\n planCache.set(plan.planHash, plan)\n}\n\n/**\n * Store a review in the cache\n */\nexport const cacheReview = (review: CachedReview): void => {\n reviewCache.set(review.planHash, review)\n}\n\n/**\n * Check if a plan exists in the cache\n */\nexport const hasPlan = (planHash: string): boolean => planCache.has(planHash)\n\n/**\n * Check if a review exists in the cache\n */\nexport const hasReview = (planHash: string): boolean => reviewCache.has(planHash)\n\n/**\n * Get all cached plan hashes\n */\nexport const listPlanHashes = (): string[] => Array.from(planCache.keys())\n\n/**\n * Get all cached review hashes\n */\nexport const listReviewHashes = (): string[] => Array.from(reviewCache.keys())\n\n/**\n * Clear all caches (for testing)\n */\nexport const clearCache = (): void => {\n planCache.clear()\n reviewCache.clear()\n}\n\n/**\n * Get cache statistics\n */\nexport const getCacheStats = (): { planCount: number; reviewCount: number } => ({\n planCount: planCache.size,\n reviewCount: reviewCache.size,\n})\n","/**\n * Policy Module\n *\n * Manages policy versioning and review tokens for the MCP apply flow.\n *\n * Key Concepts:\n * - POLICY_VERSION: Current version of apply policies (semantic versioning)\n * - Review Token: Binds planHash + policyVersion for tamper-evident verification\n *\n * Flow:\n * 1. generate_service → planHash\n * 2. plan_review → reviewToken (planHash + policyVersion)\n * 3. apply_changes → verify reviewToken OR skip if requireReview=false\n *\n * Upgrade Path:\n * - Current: Simple concatenation (planHash.policyVersion)\n * - Future: HMAC-based tokens for cryptographic binding (see docs)\n */\n\n/**\n * Current policy version\n *\n * Bump this when apply policies change (new validations, behavior changes).\n * Format: YYYY-MM-DD (date-based versioning)\n *\n * History:\n * - 2025-01-03: Initial policy version (M10)\n */\nexport const POLICY_VERSION = '2025-01-03'\n\n/**\n * Review token format: `${planHash}.${policyVersion}`\n *\n * Simple format for initial implementation.\n * Future: HMAC-based `${planHash}.${policyVersion}.${signature}`\n */\nexport type ReviewToken = string\n\n/**\n * Generate a review token from planHash and policyVersion\n *\n * @param planHash - SHA-256 hash of the plan (from computePlanHash)\n * @param policyVersion - Policy version (defaults to POLICY_VERSION)\n * @returns Review token in format `${planHash}.${policyVersion}`\n */\nexport const generateReviewToken = (planHash: string, policyVersion: string = POLICY_VERSION): ReviewToken =>\n `${planHash}.${policyVersion}`\n\n/**\n * Parse a review token into its components\n *\n * @param token - Review token to parse\n * @returns Parsed components or null if invalid format\n */\nexport const parseReviewToken = (token: string): { planHash: string; policyVersion: string } | null => {\n // Format: planHash (64 hex chars) + '.' + policyVersion\n const dotIndex = token.indexOf('.')\n if (dotIndex === -1) return null\n\n const planHash = token.slice(0, dotIndex)\n const policyVersion = token.slice(dotIndex + 1)\n\n // Basic validation\n if (planHash.length !== 64 || !/^[a-f0-9]+$/i.test(planHash)) return null\n if (!policyVersion || policyVersion.length === 0) return null\n\n return { planHash, policyVersion }\n}\n\n/**\n * Validation result for review tokens\n */\nexport interface ReviewTokenValidation {\n valid: boolean\n code?: 'REVIEW_TOKEN_INVALID' | 'REVIEW_TOKEN_MISMATCH' | 'POLICY_VERSION_MISMATCH'\n message?: string\n parsed?: { planHash: string; policyVersion: string }\n}\n\n/**\n * Validate a review token against expected planHash and policyVersion\n *\n * @param token - Review token to validate\n * @param expectedPlanHash - Expected plan hash\n * @param expectedPolicyVersion - Expected policy version (defaults to POLICY_VERSION)\n * @returns Validation result with code and message if invalid\n */\nexport const validateReviewToken = (\n token: string,\n expectedPlanHash: string,\n expectedPolicyVersion: string = POLICY_VERSION,\n): ReviewTokenValidation => {\n const parsed = parseReviewToken(token)\n\n if (!parsed) {\n return {\n valid: false,\n code: 'REVIEW_TOKEN_INVALID',\n message: 'Invalid review token format (expected: planHash.policyVersion)',\n }\n }\n\n if (parsed.planHash !== expectedPlanHash) {\n return {\n valid: false,\n code: 'REVIEW_TOKEN_MISMATCH',\n message: `Plan hash mismatch: token has ${parsed.planHash.slice(0, 8)}..., expected ${expectedPlanHash.slice(0, 8)}...`,\n parsed,\n }\n }\n\n if (parsed.policyVersion !== expectedPolicyVersion) {\n return {\n valid: false,\n code: 'POLICY_VERSION_MISMATCH',\n message: `Policy version mismatch: token has ${parsed.policyVersion}, expected ${expectedPolicyVersion}`,\n parsed,\n }\n }\n\n return { valid: true, parsed }\n}\n","/**\n * pf://contracts Resource\n *\n * Read-only resource returning contracts configuration.\n *\n * @module resources/contracts\n */\n\nimport { createContextFromWorkspace, type PfWorkspaceContext } from '@crossdelta/platform-sdk/facade'\nimport type { McpResourceContent, ResourceDefinition } from './types'\n\n/**\n * Resource URI\n */\nexport const CONTRACTS_URI = 'pf://contracts'\n\n/**\n * Contracts resource response shape\n */\nexport interface ContractsMeta {\n /** Contracts package path */\n path: string\n /** Contracts package name */\n packageName: string | undefined\n}\n\n/**\n * Build contracts meta from context\n */\nconst buildContractsMeta = (contracts: PfWorkspaceContext['contracts']): ContractsMeta => ({\n path: contracts.path,\n packageName: contracts.packageName,\n})\n\n/**\n * Read contracts resource\n *\n * @param workspaceRoot - Optional workspace root override\n */\nexport const readContracts = async (workspaceRoot?: string): Promise<McpResourceContent> => {\n const context = await createContextFromWorkspace(workspaceRoot)\n const meta = buildContractsMeta(context.workspace.contracts)\n\n return {\n uri: CONTRACTS_URI,\n mimeType: 'application/json',\n text: JSON.stringify(meta, null, 2),\n }\n}\n\n/**\n * Create contracts resource definition\n *\n * @param workspaceRoot - Optional workspace root override\n */\nexport const createContractsResource = (workspaceRoot?: string): ResourceDefinition => ({\n resource: {\n uri: CONTRACTS_URI,\n name: 'Contracts',\n description: 'Contracts package configuration (path and package name).',\n mimeType: 'application/json',\n },\n read: async () => readContracts(workspaceRoot),\n})\n","/**\n * Generator Documentation Resources\n *\n * Exposes generator guidelines (service.md, etc.) as MCP resources\n * for AI to read on-demand.\n *\n * @module resources/generator-docs\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { getGeneratorDocsDir, listGeneratorDocs } from '@crossdelta/platform-sdk/facade'\nimport type { McpResourceContent, ResourceDefinition } from './types'\n\n/**\n * Create a resource for a specific generator doc\n */\nexport const createGeneratorDocResource = (docName: string): ResourceDefinition => ({\n resource: {\n uri: `docs://generators/${docName}`,\n name: `${docName} Generator Guidelines`,\n description: `AI instructions for ${docName} generation`,\n mimeType: 'text/markdown',\n },\n async read(): Promise<McpResourceContent> {\n const docsDir = getGeneratorDocsDir()\n const docPath = join(docsDir, `${docName}.md`)\n\n try {\n const content = await readFile(docPath, 'utf-8')\n return {\n uri: `docs://generators/${docName}`,\n mimeType: 'text/markdown',\n text: content,\n }\n } catch (error) {\n throw new Error(\n `Failed to read generator doc '${docName}': ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n },\n})\n\n/**\n * Create a discovery resource listing all available generator docs\n */\nexport const createGeneratorDocsListResource = (): ResourceDefinition => ({\n resource: {\n uri: 'docs://generators',\n name: 'Available Generator Documentation',\n description: 'List of all available generator guidelines',\n mimeType: 'application/json',\n },\n async read(): Promise<McpResourceContent> {\n const docs = await listGeneratorDocs()\n const docsInfo = docs.map((name) => ({\n name,\n uri: `docs://generators/${name}`,\n }))\n\n return {\n uri: 'docs://generators',\n mimeType: 'application/json',\n text: JSON.stringify(docsInfo, null, 2),\n }\n },\n})\n\n/**\n * Create all generator doc resources (individual docs + list)\n */\nexport const createAllGeneratorDocResources = async (): Promise<ResourceDefinition[]> => {\n const docNames = await listGeneratorDocs()\n const docResources = docNames.map(createGeneratorDocResource)\n const listResource = createGeneratorDocsListResource()\n\n return [listResource, ...docResources]\n}\n","/**\n * pf://services Resource\n *\n * Read-only resource listing discovered services.\n *\n * @module resources/services\n */\n\nimport { createContextFromWorkspace } from '@crossdelta/platform-sdk/facade'\nimport type { McpResourceContent, ResourceDefinition } from './types'\n\n/**\n * Resource URI\n */\nexport const SERVICES_URI = 'pf://services'\n\n/**\n * Service list response shape\n */\nexport interface ServicesListMeta {\n /** List of discovered services (relative paths) */\n services: string[]\n /** Number of services */\n count: number\n}\n\n/**\n * Read services list resource\n *\n * @param workspaceRoot - Optional workspace root override\n */\nexport const readServices = async (workspaceRoot?: string): Promise<McpResourceContent> => {\n const context = await createContextFromWorkspace(workspaceRoot)\n\n const meta: ServicesListMeta = {\n services: context.workspace.availableServices,\n count: context.workspace.availableServices.length,\n }\n\n return {\n uri: SERVICES_URI,\n mimeType: 'application/json',\n text: JSON.stringify(meta, null, 2),\n }\n}\n\n/**\n * Create services list resource definition\n *\n * @param workspaceRoot - Optional workspace root override\n */\nexport const createServicesResource = (workspaceRoot?: string): ResourceDefinition => ({\n resource: {\n uri: SERVICES_URI,\n name: 'Services',\n description: 'List of discovered services in the workspace.',\n mimeType: 'application/json',\n },\n read: async () => readServices(workspaceRoot),\n})\n","/**\n * Templates Resources\n *\n * Exposes service templates (hono-microservice, nest-microservice, workspace)\n * as MCP resources for AI to discover available templates.\n *\n * @module resources/templates\n */\nimport { readdir, readFile, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { McpResourceContent, ResourceDefinition } from './types'\n\nconst getTemplatesDir = (): string => {\n const devPath = join(process.cwd(), 'packages/platform-sdk/bin/templates')\n try {\n const fs = require('node:fs')\n if (fs.existsSync(devPath)) {\n return devPath\n }\n } catch {\n // Fall through to production path\n }\n\n return join(process.cwd(), 'node_modules/@crossdelta/platform-sdk/bin/templates')\n}\n\nconst getTemplateStructure = async (templateName: string): Promise<string[]> => {\n const templateDir = join(getTemplatesDir(), templateName)\n\n const walk = async (dir: string, prefix = ''): Promise<string[]> => {\n try {\n const entries = await readdir(dir, { withFileTypes: true })\n\n const results = await Promise.all(\n entries.map(async (entry) => {\n const fullPath = join(dir, entry.name)\n const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name\n\n if (entry.isDirectory()) {\n const subFiles = await walk(fullPath, relativePath)\n return [`${relativePath}/`, ...subFiles]\n }\n\n const stats = await stat(fullPath)\n return [`${relativePath} (${stats.size} bytes)`]\n }),\n )\n\n return results.flat()\n } catch {\n return []\n }\n }\n\n return await walk(templateDir)\n}\n\nconst listTemplates = async (): Promise<string[]> => {\n const templatesDir = getTemplatesDir()\n try {\n const entries = await readdir(templatesDir, { withFileTypes: true })\n return entries.filter((e) => e.isDirectory()).map((e) => e.name)\n } catch {\n return []\n }\n}\n\nconst listTemplateFiles = async (templateName: string): Promise<string[]> => {\n const structure = await getTemplateStructure(templateName)\n return structure.filter((entry) => !entry.endsWith('/')).map((entry) => entry.replace(/ \\(\\d+ bytes\\)$/, ''))\n}\n\nconst readTemplateFile = async (templateName: string, filePath: string): Promise<string> => {\n const templateDir = join(getTemplatesDir(), templateName)\n const fullPath = join(templateDir, filePath)\n\n if (!fullPath.startsWith(templateDir)) {\n throw new Error('Invalid file path')\n }\n\n return await readFile(fullPath, 'utf-8')\n}\n\nconst readTemplateStructure = async (templateName: string): Promise<string> => {\n const structure = await getTemplateStructure(templateName)\n return JSON.stringify(\n {\n template: templateName,\n files: structure,\n totalFiles: structure.length,\n },\n null,\n 2,\n )\n}\n\nconst createTemplatesListResource = (): ResourceDefinition => ({\n resource: {\n uri: 'templates://list',\n name: 'Available Service Templates',\n description: 'List of all available service templates (hono-microservice, nest-microservice, workspace)',\n mimeType: 'application/json',\n },\n async read(): Promise<McpResourceContent> {\n const templates = await listTemplates()\n const templatesInfo = await Promise.all(\n templates.map(async (name) => ({\n name,\n uri: `templates://${name}`,\n description: `${name} template structure`,\n })),\n )\n\n return {\n uri: 'templates://list',\n mimeType: 'application/json',\n text: JSON.stringify(\n {\n templates: templatesInfo,\n count: templatesInfo.length,\n },\n null,\n 2,\n ),\n }\n },\n})\n\nconst createTemplateResource = (templateName: string): ResourceDefinition => ({\n resource: {\n uri: `templates://${templateName}`,\n name: `${templateName} Template`,\n description: `File structure of ${templateName} template`,\n mimeType: 'application/json',\n },\n async read(): Promise<McpResourceContent> {\n const structure = await getTemplateStructure(templateName)\n\n return {\n uri: `templates://${templateName}`,\n mimeType: 'application/json',\n text: JSON.stringify(\n {\n template: templateName,\n files: structure,\n totalFiles: structure.length,\n },\n null,\n 2,\n ),\n }\n },\n})\n\nconst createTemplateFileResourceTemplate = () => ({\n uriTemplate: 'templates://{template}/file/{path}',\n name: 'Template File',\n description: 'Read individual files from service templates',\n mimeType: 'text/plain',\n})\n\nconst createAllTemplateResources = async (): Promise<ResourceDefinition[]> => {\n const templates = await listTemplates()\n const templateResources = templates.map(createTemplateResource)\n const listResource = createTemplatesListResource()\n\n return [listResource, ...templateResources]\n}\n\nexport {\n createAllTemplateResources,\n createTemplateFileResourceTemplate,\n createTemplateResource,\n createTemplatesListResource,\n listTemplateFiles,\n listTemplates,\n readTemplateFile,\n readTemplateStructure,\n}\n","/**\n * pf://workspace/summary Resource\n *\n * Read-only resource returning workspace metadata as JSON.\n * Same data as workspace.scan tool.\n *\n * @module resources/workspace-summary\n */\n\nimport { createContextFromWorkspace } from '@crossdelta/platform-sdk/facade'\nimport type { WorkspaceScanMeta } from '../tools/workspace-scan'\nimport type { McpResourceContent, ResourceDefinition } from './types'\n\n/**\n * Resource URI\n */\nexport const WORKSPACE_SUMMARY_URI = 'pf://workspace/summary'\n\n/**\n * Build workspace summary from context\n */\nconst buildWorkspaceSummary = (\n context: Awaited<ReturnType<typeof createContextFromWorkspace>>,\n pluginModules: string[],\n): WorkspaceScanMeta => ({\n workspaceRoot: context.workspace.workspaceRoot,\n contracts: context.workspace.contracts,\n availableServices: context.workspace.availableServices,\n loadedPlugins: pluginModules,\n})\n\n/**\n * Read workspace summary resource\n *\n * @param pluginModules - Plugin modules to include in response\n * @param workspaceRoot - Optional workspace root override\n */\nexport const readWorkspaceSummary = async (\n pluginModules: string[] = [],\n workspaceRoot?: string,\n): Promise<McpResourceContent> => {\n const context = await createContextFromWorkspace(workspaceRoot)\n const summary = buildWorkspaceSummary(context, pluginModules)\n\n return {\n uri: WORKSPACE_SUMMARY_URI,\n mimeType: 'application/json',\n text: JSON.stringify(summary, null, 2),\n }\n}\n\n/**\n * Create workspace summary resource definition\n *\n * @param pluginModules - Plugin modules to inject\n * @param workspaceRoot - Optional workspace root override\n */\nexport const createWorkspaceSummaryResource = (\n pluginModules: string[] = [],\n workspaceRoot?: string,\n): ResourceDefinition => ({\n resource: {\n uri: WORKSPACE_SUMMARY_URI,\n name: 'Workspace Summary',\n description:\n 'Read-only workspace metadata including root path, contracts config, available services, and loaded plugins.',\n mimeType: 'application/json',\n },\n read: async () => readWorkspaceSummary(pluginModules, workspaceRoot),\n})\n","/**\n * MCP Server Implementation\n *\n * Thin adapter between MCP SDK and Platform SDK facade.\n * Uses execute() dispatch for tool calls (plan-only by default).\n *\n * Handles elicitation effects from tools:\n * - Detects elicit:input effects in tool results\n * - Returns structured error with missing fields (MCP elicitation not yet supported by VS Code)\n * - Future: Use server.elicitInput() when client declares elicitation capability\n *\n * @module server\n */\nimport type { OperationResult, PfPluginContext, PfWorkspaceContext } from '@crossdelta/platform-sdk/facade'\nimport {\n collectExecutableToolSpecs,\n createContext,\n createContextFromWorkspace,\n isElicitInputEffect,\n loadPlugins,\n} from '@crossdelta/platform-sdk/facade'\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport {\n CallToolRequestSchema,\n CompleteRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n ReadResourceRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js'\nimport {\n createAllGeneratorDocResources,\n createContractsResource,\n createServicesResource,\n createTemplateFileResourceTemplate,\n createTemplatesListResource,\n createWorkspaceSummaryResource,\n listTemplateFiles,\n listTemplates,\n type ResourceDefinition,\n readTemplateFile,\n readTemplateStructure,\n} from './resources'\nimport {\n formatElicitationAsMcpResponse,\n formatErrorAsMcpResponse,\n formatOperationResultAsMcpResponse,\n} from './response'\nimport { applyChangesTool, createWorkspaceScanTool, planReviewTool, servicesGenerateTool } from './tools'\nimport type { ExecutableToolSpec } from './tools/types'\n\n/**\n * MCP Server configuration\n */\nexport interface McpServerOptions {\n /** Server name (shown in MCP clients) */\n name: string\n /** Server version */\n version: string\n /** Workspace context */\n workspace: PfWorkspaceContext\n /** Plugin modules to load */\n plugins: string[]\n /** Optional logger */\n logger?: PfPluginContext['logger']\n}\n\n/**\n * MCP Server configuration with auto-discovery\n */\nexport interface McpServerAutoOptions {\n /** Server name (shown in MCP clients) */\n name: string\n /** Server version */\n version: string\n /** Optional workspace root (auto-discovered if omitted) */\n workspaceRoot?: string\n /** Plugin modules to load */\n plugins: string[]\n /** Optional logger */\n logger?: PfPluginContext['logger']\n}\n\n/**\n * Check if result is an OperationResult\n */\nconst isOperationResult = (result: unknown): result is OperationResult => {\n return typeof result === 'object' && result !== null && 'ok' in result && 'operation' in result && 'summary' in result\n}\n\n/**\n * Read template file resource\n */\nconst readTemplateFileResource = async (uri: string) => {\n const templateFileMatch = uri.match(/^templates:\\/\\/([^/]+)\\/file\\/(.+)$/)\n if (!templateFileMatch) return null\n\n const [, templateName, filePath] = templateFileMatch\n\n if (!templateName || !filePath) {\n throw new Error(`Invalid template file URI: ${uri}`)\n }\n\n try {\n const content = await readTemplateFile(templateName, filePath)\n return {\n contents: [\n {\n uri,\n mimeType: 'text/plain',\n text: content,\n },\n ],\n }\n } catch (error) {\n throw new Error(`Failed to read template file: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\n/**\n * Read template structure resource\n */\nconst readTemplateStructureResource = async (uri: string) => {\n const templateStructureMatch = uri.match(/^templates:\\/\\/([^/]+)$/)\n if (!templateStructureMatch) return null\n\n const [, templateName] = templateStructureMatch\n\n if (!templateName || templateName === 'list') {\n return null // Fall through to regular resource handling\n }\n\n try {\n const content = await readTemplateStructure(templateName)\n return {\n contents: [\n {\n uri,\n mimeType: 'application/json',\n text: content,\n },\n ],\n }\n } catch (error) {\n throw new Error(`Failed to read template structure: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\n/**\n * Handle template name completion\n */\nconst completeTemplateName = async () => {\n const templates = await listTemplates()\n return {\n completion: {\n values: templates,\n total: templates.length,\n hasMore: false,\n },\n }\n}\n\n/**\n * Handle template path completion\n */\nconst completeTemplatePath = async (uri: string) => {\n const templateMatch = uri.match(/templates:\\/\\/([^/]+)/)\n if (!templateMatch?.[1]) {\n return {\n completion: {\n values: [],\n total: 0,\n hasMore: false,\n },\n }\n }\n\n const templateName = templateMatch[1]\n try {\n const files = await listTemplateFiles(templateName)\n return {\n completion: {\n values: files,\n total: files.length,\n hasMore: false,\n },\n }\n } catch {\n // Template not found, return empty\n return {\n completion: {\n values: [],\n total: 0,\n hasMore: false,\n },\n }\n }\n}\n\n/**\n * Convert legacy CommandLikeResult to OperationResult\n */\nconst normalizeToOperationResult = (result: unknown, toolName: string): OperationResult => {\n if (isOperationResult(result)) {\n return result\n }\n\n // Handle legacy command result shape\n const legacyResult = result as {\n ok?: boolean\n operation?: string\n summary?: string\n effects?: unknown[]\n output?: string | string[]\n }\n\n return {\n ok: legacyResult.ok ?? true,\n operation: legacyResult.operation ?? toolName,\n summary:\n legacyResult.summary ??\n (legacyResult.output\n ? Array.isArray(legacyResult.output)\n ? legacyResult.output.join('\\n')\n : legacyResult.output\n : `Executed ${toolName}`),\n artifacts: [],\n changes: (legacyResult.effects ?? []) as OperationResult['changes'],\n diagnostics: [],\n }\n}\n\n/**\n * Build tools array from plugin tools and modules.\n */\nconst buildTools = (pluginTools: ExecutableToolSpec[], pluginModules: string[]): ExecutableToolSpec[] => {\n const workspaceScanTool = createWorkspaceScanTool(pluginModules)\n return [servicesGenerateTool, planReviewTool, applyChangesTool, workspaceScanTool, ...pluginTools]\n}\n\n/**\n * Build resources array with workspace root.\n */\nconst buildResources = async (pluginModules: string[], workspaceRoot: string): Promise<ResourceDefinition[]> => {\n const generatorDocsResources = await createAllGeneratorDocResources()\n const templatesListResource = createTemplatesListResource()\n\n return [\n createWorkspaceSummaryResource(pluginModules, workspaceRoot),\n createServicesResource(workspaceRoot),\n createContractsResource(workspaceRoot),\n ...generatorDocsResources,\n templatesListResource, // Only discovery resource, not individual templates\n ]\n}\n\n/**\n * Register all MCP handlers on the server.\n * Shared between createMcpServer and createMcpServerFromWorkspace.\n */\nconst registerHandlers = (server: Server, tools: ExecutableToolSpec[], resources: ResourceDefinition[]): void => {\n // Register tools/list handler\n server.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n })),\n }))\n\n // Register tools/call handler (execute dispatch)\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name: toolName, arguments: args } = request.params\n\n // Find tool\n const tool = tools.find((t) => t.name === toolName)\n if (!tool) {\n return formatErrorAsMcpResponse(new Error(`Unknown tool: ${toolName}`), toolName)\n }\n\n try {\n // Execute tool (plan-only by default)\n const result = await tool.execute(args ?? {})\n\n // Normalize to OperationResult\n const normalizedResult = normalizeToOperationResult(result, toolName)\n\n // Check for elicitation effect (M6: host handles elicitation)\n const elicitEffect = normalizedResult.changes.find(isElicitInputEffect)\n if (elicitEffect) {\n // TODO: Future - check server.getClientCapabilities()?.elicitation\n return formatElicitationAsMcpResponse(elicitEffect, toolName)\n }\n\n return formatOperationResultAsMcpResponse(normalizedResult)\n } catch (error) {\n return formatErrorAsMcpResponse(error instanceof Error ? error : new Error(String(error)), toolName)\n }\n })\n\n // Register resources/list handler\n server.setRequestHandler(ListResourcesRequestSchema, async () => ({\n resources: resources.map((r) => r.resource),\n }))\n\n // Register resources/templates/list handler\n server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({\n resourceTemplates: [createTemplateFileResourceTemplate()],\n }))\n\n // Register completion handler for resource template parameters\n server.setRequestHandler(CompleteRequestSchema, async (request) => {\n const { ref, argument } = request.params\n\n // Handle completion for templates://{template}/file/{path}\n if (ref.type === 'ref/resource' && ref.uri?.startsWith('templates://')) {\n // Complete {template} parameter\n if (argument.name === 'template') {\n return await completeTemplateName()\n }\n\n // Complete {path} parameter (needs template from URI)\n if (argument.name === 'path' && ref.uri) {\n return await completeTemplatePath(ref.uri)\n }\n }\n\n // No completion available\n return {\n completion: {\n values: [],\n total: 0,\n hasMore: false,\n },\n }\n })\n\n // Register resources/read handler\n server.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n const { uri } = request.params\n\n // Try template file pattern: templates://{template}/file/{path}\n const templateFileResult = await readTemplateFileResource(uri)\n if (templateFileResult) return templateFileResult\n\n // Try template structure pattern: templates://{template}\n const templateStructureResult = await readTemplateStructureResource(uri)\n if (templateStructureResult) return templateStructureResult\n\n // Regular resource\n const resource = resources.find((r) => r.resource.uri === uri)\n\n if (!resource) {\n throw new Error(`Unknown resource: ${uri}`)\n }\n\n const content = await resource.read(uri)\n return { contents: [content] }\n })\n}\n\n/**\n * Create and start an MCP server\n *\n * Uses execute() dispatch for all tool calls.\n * Built-in tools (services.generate) are always included.\n * Plugin-based tools are loaded from specified modules.\n *\n * @param options - Server configuration\n * @returns Promise that resolves when server is ready\n */\nexport const createMcpServer = async (options: McpServerOptions): Promise<void> => {\n const { name, version, workspace, plugins: pluginModules, logger } = options\n\n // Create plugin context and load plugins\n const context = createContext(workspace, logger)\n const loadedPlugins = await loadPlugins(pluginModules, context)\n const pluginTools = collectExecutableToolSpecs(loadedPlugins, context)\n\n // Build tools and resources\n const tools = buildTools(pluginTools, pluginModules)\n const resources = await buildResources(pluginModules, workspace.workspaceRoot)\n\n // Create and configure server\n const server = new Server({ name, version }, { capabilities: { tools: {}, resources: {}, completions: {} } })\n registerHandlers(server, tools, resources)\n\n // Start server\n const transport = new StdioServerTransport()\n await server.connect(transport)\n\n logger?.info(`MCP server '${name}' started with ${tools.length} tools, ${resources.length} resources`)\n}\n\n/**\n * Create and start MCP server with auto-discovered workspace\n *\n * Automatically discovers workspace configuration from package.json and filesystem.\n * This is the recommended way to start the server.\n *\n * @param options - Server options (workspace auto-discovered)\n */\nexport const createMcpServerFromWorkspace = async (options: McpServerAutoOptions): Promise<void> => {\n const { name, version, workspaceRoot, plugins: pluginModules, logger } = options\n\n // Create plugin context via facade (auto-discovery)\n const context = await createContextFromWorkspace(workspaceRoot, logger)\n const loadedPlugins = await loadPlugins(pluginModules, context)\n const pluginTools = collectExecutableToolSpecs(loadedPlugins, context)\n\n // Build tools and resources (use discovered workspace root)\n const discoveredRoot = context.workspace.workspaceRoot\n const tools = buildTools(pluginTools, pluginModules)\n const resources = await buildResources(pluginModules, discoveredRoot)\n\n // Create and configure server\n const server = new Server({ name, version }, { capabilities: { tools: {}, resources: {}, completions: {} } })\n registerHandlers(server, tools, resources)\n\n // Start server\n const transport = new StdioServerTransport()\n await server.connect(transport)\n\n logger?.info(\n `MCP server '${name}' started with ${tools.length} tools, ${resources.length} resources (auto-discovered workspace)`,\n )\n}\n","/**\n * MCP Response Formatter\n *\n * Converts OperationResult to MCP-compatible response format.\n * Uses Zod-inferred types from MCP SDK for type safety.\n *\n * Pure function, no side effects.\n */\n\nimport type { OperationResult } from '@crossdelta/platform-sdk/facade'\nimport { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js'\nimport type { z } from 'zod'\n\n/**\n * MCP CallToolResult type (inferred from SDK Zod schema)\n */\nexport type McpToolResponse = z.infer<typeof CallToolResultSchema>\n\n/**\n * Format artifacts as text summary\n */\nconst formatArtifactsSummary = (artifacts: OperationResult['artifacts']): string => {\n if (artifacts.length === 0) return ''\n\n const grouped = artifacts.reduce(\n (acc, a) => {\n const key = a.type\n if (!acc[key]) acc[key] = []\n acc[key].push(a)\n return acc\n },\n {} as Record<string, typeof artifacts>,\n )\n\n const lines: string[] = []\n for (const [type, items] of Object.entries(grouped)) {\n lines.push(`\\n${type.toUpperCase()} (${items.length}):`)\n for (const item of items) {\n lines.push(` - ${item.path}`)\n }\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Format changes as text summary\n */\nconst formatChangesSummary = (changes: OperationResult['changes']): string => {\n if (changes.length === 0) return ''\n\n const grouped = changes.reduce(\n (acc, c) => {\n const key = c.kind\n if (!acc[key]) acc[key] = []\n acc[key].push(c)\n return acc\n },\n {} as Record<string, typeof changes>,\n )\n\n const lines: string[] = []\n for (const [kind, items] of Object.entries(grouped)) {\n lines.push(`\\n${kind} (${items.length}):`)\n for (const item of items) {\n const path = 'path' in item ? (item as { path?: string }).path : ''\n lines.push(` - ${path || kind}`)\n }\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Format next actions as text\n */\nconst formatNextActionsSummary = (next?: OperationResult['next']): string => {\n if (!next || next.length === 0) return ''\n\n return `\\n\\nNEXT STEPS:\\n${next.map((n) => ` $ ${n.command}\\n ${n.description}`).join('\\n')}`\n}\n\n/**\n * Format diagnostics as text\n */\nconst formatDiagnosticsSummary = (diagnostics: OperationResult['diagnostics']): string => {\n if (diagnostics.length === 0) return ''\n\n return `\\n\\nDIAGNOSTICS:\\n${diagnostics.map((d) => ` [${d.level.toUpperCase()}] ${d.message}`).join('\\n')}`\n}\n\n/**\n * Format dependencies as text summary\n */\nconst formatDependenciesSummary = (dependencies?: Array<{ name: string; version?: string; dev?: boolean }>): string => {\n if (!dependencies || dependencies.length === 0) return ''\n\n const lines: string[] = ['\\n## Dependencies']\n for (const dep of dependencies) {\n const version = dep.version || 'latest'\n const devTag = dep.dev ? ' (dev)' : ''\n lines.push(` - ${dep.name}@${version}${devTag}`)\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Format env vars as text summary\n */\nconst formatEnvVarsSummary = (envVars?: Array<{ key: string; description: string; required: boolean }>): string => {\n if (!envVars || envVars.length === 0) return ''\n\n const lines: string[] = ['\\n## Environment Variables']\n for (const ev of envVars) {\n const reqTag = ev.required ? ' (required)' : ''\n lines.push(` - ${ev.key}${reqTag}: ${ev.description}`)\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Format files to generate as text summary\n */\nconst formatFilesToGenerateSummary = (\n files?: Array<{ path: string; intent: string; layer?: string; kind?: string }>,\n): string => {\n if (!files || files.length === 0) return ''\n\n const lines: string[] = ['\\n## Files for AI to Generate']\n for (const file of files) {\n const tags = [file.layer, file.kind].filter(Boolean).join('/')\n lines.push(` - ${file.path} [${tags}]`)\n lines.push(` Intent: ${file.intent}`)\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Extended result type for service generation (has extra fields)\n */\ninterface ExtendedResult extends OperationResult {\n files?: Array<{ path: string; intent: string; layer?: string; kind?: string }>\n dependencies?: Array<{ name: string; version?: string; dev?: boolean }>\n envVars?: Array<{ key: string; description: string; required: boolean }>\n postCommands?: string[]\n}\n\n/**\n * Format OperationResult as MCP tool response\n *\n * Returns both structured content (for programmatic use) and\n * text content (for human-readable fallback).\n */\nexport const formatOperationResultAsMcpResponse = (result: OperationResult): McpToolResponse => {\n // Cast to extended result (safe: extra fields just won't be present for non-generate results)\n const extResult = result as ExtendedResult\n\n // Build human-readable text summary\n const textParts: string[] = [`# ${result.operation}`, '', result.ok ? '✓ Success' : '✗ Failed', '', result.summary]\n\n if (result.artifacts.length > 0) {\n textParts.push('\\n## Artifacts')\n textParts.push(formatArtifactsSummary(result.artifacts))\n }\n\n if (result.changes.length > 0) {\n textParts.push('\\n## Changes (Plan)')\n textParts.push(formatChangesSummary(result.changes))\n }\n\n // Add files, dependencies, envVars if present (GenerateServiceResult)\n textParts.push(formatFilesToGenerateSummary(extResult.files))\n textParts.push(formatDependenciesSummary(extResult.dependencies))\n textParts.push(formatEnvVarsSummary(extResult.envVars))\n\n // Add post-commands if present\n if (extResult.postCommands && extResult.postCommands.length > 0) {\n textParts.push('\\n## Post Commands')\n for (const cmd of extResult.postCommands) {\n textParts.push(` $ ${cmd}`)\n }\n }\n\n textParts.push(formatDiagnosticsSummary(result.diagnostics))\n textParts.push(formatNextActionsSummary(result.next))\n\n // Add JSON fallback for full structure\n textParts.push('\\n\\n---\\n## Raw Result (JSON)')\n textParts.push('```json')\n textParts.push(JSON.stringify(result, null, 2))\n textParts.push('```')\n\n return {\n content: [\n {\n type: 'text' as const,\n text: textParts.join('\\n'),\n },\n ],\n structuredContent: result as unknown as Record<string, unknown>,\n isError: !result.ok,\n }\n}\n\n/**\n * Format error as MCP tool response\n */\nexport const formatErrorAsMcpResponse = (error: Error, operation: string): McpToolResponse => {\n return {\n content: [\n {\n type: 'text' as const,\n text: `# ${operation}\\n\\n✗ Error: ${error.message}`,\n },\n ],\n structuredContent: {\n ok: false,\n operation,\n summary: error.message,\n artifacts: [],\n changes: [],\n diagnostics: [{ level: 'error', message: error.message }],\n },\n isError: true,\n }\n}\n\n/**\n * Elicitation effect shape (matches platform-sdk ElicitInputEffect)\n */\ninterface ElicitInputEffectShape {\n kind: 'elicit:input'\n message: string\n fields: readonly {\n name: string\n prompt: string\n required?: boolean\n description?: string\n enum?: readonly string[]\n type?: string\n }[]\n}\n\n/**\n * Format elicitation effect as MCP tool response\n *\n * Returns a structured response indicating missing inputs.\n * VS Code Copilot doesn't support MCP elicitation yet, so we return\n * a helpful error message with field details.\n *\n * Future: When client supports elicitation, use server.elicitInput() instead.\n */\nexport const formatElicitationAsMcpResponse = (\n elicitEffect: ElicitInputEffectShape,\n operation: string,\n): McpToolResponse => {\n const fieldNames = elicitEffect.fields.map((f) => f.name)\n const fieldDetails = elicitEffect.fields\n .map((f) => {\n const parts = [`- **${f.name}**`]\n if (f.required) parts.push(' (required)')\n parts.push(`: ${f.prompt}`)\n if (f.enum) parts.push(` [${f.enum.join(', ')}]`)\n if (f.description) parts.push(`\\n ${f.description}`)\n return parts.join('')\n })\n .join('\\n')\n\n const textParts = [\n `# ${operation}`,\n '',\n '⏳ Missing Required Inputs',\n '',\n elicitEffect.message,\n '',\n '## Please provide:',\n fieldDetails,\n '',\n '---',\n 'Re-run the tool with these parameters.',\n ]\n\n return {\n content: [\n {\n type: 'text' as const,\n text: textParts.join('\\n'),\n },\n ],\n structuredContent: {\n ok: false,\n operation,\n summary: elicitEffect.message,\n artifacts: [],\n changes: [],\n diagnostics: [{ level: 'info', message: 'Awaiting user input' }],\n elicitation: {\n fields: elicitEffect.fields,\n missingInputs: fieldNames,\n },\n },\n isError: false, // Not an error, just needs more input\n }\n}\n","/**\n * apply_changes Tool\n *\n * Executes effects from a generate_service plan.\n * Non-interactive, deterministic, idempotent.\n *\n * IMPORTANT:\n * - Rejects plans with ElicitInputEffect (requires host interaction)\n * - Does NOT prompt for user input\n * - Idempotent: Safe to run multiple times\n * - Supports expectedPlanHash for drift detection\n * - Writes audit artifacts on successful non-dryRun execution\n */\n\nimport {\n findWorkspaceRoot,\n isElicitInputEffect,\n type OperationResult,\n type PfEffect,\n} from '@crossdelta/platform-sdk/facade'\nimport { createAuditArtifact, writeAuditArtifact } from '../audit'\nimport { type ApplyResult, applyEffects, ErrorCodes } from '../effects'\nimport { computePlanHash } from '../plan-hash'\nimport { POLICY_VERSION, validateReviewToken } from '../policy'\nimport type { ExecutableToolSpec } from './types'\n\n/**\n * Input schema for apply_changes tool\n */\nexport interface ApplyChangesInput {\n /** Effects to apply (from generate_service result) */\n changes: PfEffect[]\n /** Optional: Workspace root path */\n workspaceRoot?: string\n /** Optional: Expected plan hash from generate_service or plan_review */\n expectedPlanHash?: string\n /** Optional: If true, requires a valid reviewToken before applying */\n requireReview?: boolean\n /** Optional: Review token from plan_review (format: planHash.policyVersion) */\n reviewToken?: string\n /** Optional: Expected policy version (defaults to current POLICY_VERSION) */\n expectedPolicyVersion?: string\n}\n\n/**\n * Validate changes array\n */\nconst validateChanges = (changes: unknown): changes is PfEffect[] => {\n if (!Array.isArray(changes)) return false\n return changes.every((c) => typeof c === 'object' && c !== null && 'kind' in c && typeof c.kind === 'string')\n}\n\n/**\n * Create a failure result with consistent structure\n */\nconst createFailure = (\n summary: string,\n errorMsg: string,\n infoMsg?: string,\n code?: keyof typeof ErrorCodes,\n): OperationResult<ApplyResult> => ({\n ok: false,\n operation: 'apply_changes',\n summary,\n artifacts: [],\n changes: [],\n diagnostics: [\n { level: 'error', message: errorMsg },\n ...(infoMsg ? [{ level: 'info' as const, message: infoMsg }] : []),\n ],\n data: code\n ? {\n ok: false,\n dryRun: false,\n summary,\n results: [],\n counts: { created: 0, updated: 0, skipped: 0, error: 1, wouldCreate: 0, wouldUpdate: 0, wouldSkip: 0 },\n code: ErrorCodes[code],\n }\n : undefined,\n})\n\n/**\n * Validate review gate requirements\n * Returns failure result if validation fails, null if passes\n */\nconst checkReviewGate = (\n requireReview: unknown,\n reviewToken: unknown,\n actualHash: string,\n policyVer: string,\n): OperationResult<ApplyResult> | null => {\n if (requireReview !== true) return null\n\n if (typeof reviewToken !== 'string') {\n return createFailure(\n 'Review required but no reviewToken provided',\n 'requireReview is enabled but reviewToken was not provided',\n 'Run plan_review first to get a reviewToken, then pass it to apply_changes',\n 'REVIEW_REQUIRED',\n )\n }\n\n const validation = validateReviewToken(reviewToken, actualHash, policyVer)\n if (!validation.valid) {\n const info =\n validation.code === 'POLICY_VERSION_MISMATCH'\n ? 'Policy version has changed. Re-run plan_review to get a new reviewToken.'\n : 'Re-run plan_review to get a valid reviewToken for the current plan'\n return createFailure(\n `Review token validation failed: ${validation.message}`,\n validation.message ?? 'Review token validation failed',\n info,\n validation.code as keyof typeof ErrorCodes,\n )\n }\n\n return null\n}\n\n/**\n * Validate plan hash for drift detection\n * Returns failure result if validation fails, null if passes\n */\nconst checkPlanHash = (expectedHash: unknown, actualHash: string): OperationResult<ApplyResult> | null => {\n if (typeof expectedHash !== 'string') return null\n if (actualHash === expectedHash) return null\n\n return createFailure(\n 'Plan hash mismatch: changes have been modified since review',\n `Expected hash: ${expectedHash}, got: ${actualHash}`,\n 'Re-run plan_review to get the updated hash, or remove expectedPlanHash to skip verification',\n 'PLAN_HASH_MISMATCH',\n )\n}\n\n/**\n * Write audit artifact and return traceability info\n */\nconst writeAuditAndGetInfo = (\n planHash: string,\n policyVersion: string,\n changes: PfEffect[],\n result: ApplyResult,\n reviewToken: unknown,\n workspaceRoot: string,\n): { auditArtifactPath: string; appliedAt: string } | null => {\n if (!result.ok || result.dryRun) return null\n\n const audit = createAuditArtifact(planHash, policyVersion, changes, result, {\n reviewToken: typeof reviewToken === 'string' ? reviewToken : undefined,\n })\n const auditArtifactPath = writeAuditArtifact(audit, workspaceRoot)\n\n return { auditArtifactPath, appliedAt: audit.appliedAt }\n}\n\n/**\n * Execute apply_changes tool\n *\n * Takes effects from a plan and applies them to the filesystem.\n * Returns detailed result with created/updated/skipped/error counts.\n * If expectedPlanHash is provided, verifies plan integrity before execution.\n * If requireReview is true, requires a valid reviewToken from plan_review.\n */\nconst execute = async (args: Record<string, unknown>): Promise<OperationResult<ApplyResult>> => {\n const {\n changes,\n workspaceRoot: workspaceRootArg,\n expectedPlanHash,\n requireReview,\n reviewToken,\n expectedPolicyVersion,\n } = args\n\n // Validate changes input\n if (!changes) {\n return createFailure('Missing required input: changes', 'changes array is required')\n }\n\n if (!validateChanges(changes)) {\n return createFailure(\n 'Invalid changes format: expected array of effects with kind property',\n 'Each change must have a \"kind\" property',\n )\n }\n\n // Compute actual plan hash for all verification\n const actualPlanHash = computePlanHash(changes)\n const policyVersion = typeof expectedPolicyVersion === 'string' ? expectedPolicyVersion : POLICY_VERSION\n\n // Review gate: If requireReview is true, validate reviewToken\n const reviewGateError = checkReviewGate(requireReview, reviewToken, actualPlanHash, policyVersion)\n if (reviewGateError) return reviewGateError\n\n // Verify plan hash if provided (drift detection) - legacy support\n const hashMismatchError = checkPlanHash(expectedPlanHash, actualPlanHash)\n if (hashMismatchError) return hashMismatchError\n\n // Guard: Check for elicitation effects BEFORE applying\n const elicitEffects = changes.filter(isElicitInputEffect)\n if (elicitEffects.length > 0) {\n const fieldNames = elicitEffects\n .flatMap((e) => {\n if ('fields' in e && Array.isArray(e.fields)) {\n return (e.fields as ReadonlyArray<{ name: string }>).map((f) => f.name)\n }\n return []\n })\n .join(', ')\n\n return {\n ok: false,\n operation: 'apply_changes',\n summary: 'Cannot apply: Plan requires user input',\n artifacts: [],\n changes: elicitEffects,\n diagnostics: [\n {\n level: 'error',\n message: `Elicitation required for: ${fieldNames || 'unknown fields'}`,\n },\n {\n level: 'info',\n message: 'Use generate_service with required inputs first, then apply the resulting changes',\n },\n ],\n }\n }\n\n // Resolve workspace root\n const workspaceRoot = typeof workspaceRootArg === 'string' ? workspaceRootArg : findWorkspaceRoot()\n\n if (!workspaceRoot) {\n return {\n ok: false,\n operation: 'apply_changes',\n summary: 'Could not determine workspace root',\n artifacts: [],\n changes: [],\n diagnostics: [\n { level: 'error', message: 'Workspace root not found' },\n { level: 'info', message: 'Provide workspaceRoot parameter or run from within a workspace' },\n ],\n }\n }\n\n // Apply effects\n const result = applyEffects(changes, workspaceRoot)\n\n // Build artifacts from successful results\n const artifacts = result.results\n .filter((r) => r.success && r.path)\n .map((r) => ({\n type: 'file' as const,\n path: r.path as string,\n description: r.message,\n }))\n\n // Build diagnostics from results\n const diagnostics = result.results.map((r) => ({\n level: (r.success ? 'info' : 'error') as 'info' | 'error',\n message: r.message,\n location: r.path,\n }))\n\n // Write audit artifact for non-dryRun executions\n const auditInfo = writeAuditAndGetInfo(actualPlanHash, policyVersion, changes, result, reviewToken, workspaceRoot)\n\n if (auditInfo) {\n artifacts.push({\n type: 'file' as const,\n path: auditInfo.auditArtifactPath,\n description: 'Audit artifact',\n })\n\n diagnostics.push({\n level: 'info',\n message: `Audit artifact written to: ${auditInfo.auditArtifactPath}`,\n location: auditInfo.auditArtifactPath,\n })\n }\n\n // Extend result with traceability fields\n const extendedResult = {\n ...result,\n planHash: actualPlanHash,\n policyVersion,\n appliedAt: auditInfo?.appliedAt,\n auditArtifactPath: auditInfo?.auditArtifactPath,\n reviewTokenUsed: typeof reviewToken === 'string' ? reviewToken : undefined,\n }\n\n return {\n ok: result.ok,\n operation: 'apply_changes',\n summary: result.summary,\n artifacts,\n changes: [], // Effects already applied\n diagnostics,\n data: extendedResult,\n }\n}\n\n/**\n * apply_changes tool specification\n *\n * VS Code naming: snake_case with {verb}_{noun} pattern\n */\nexport const applyChangesTool: ExecutableToolSpec = {\n name: 'apply_changes',\n description:\n 'Apply changes (effects) from a generate_service plan. Writes files, adds env vars, and creates infra configs. Non-interactive, idempotent - safe to run multiple times. Rejects plans that require user input (elicitation). Supports requireReview gate and expectedPlanHash for drift detection.',\n inputSchema: {\n type: 'object',\n properties: {\n changes: {\n type: 'array',\n description: 'Array of effects to apply. Get this from the \"changes\" field of a generate_service result.',\n items: {\n type: 'object',\n properties: {\n kind: {\n type: 'string',\n description: 'Effect type: \"file:write\", \"env:add\", \"infra:add\"',\n },\n },\n required: ['kind'],\n },\n },\n workspaceRoot: {\n type: 'string',\n description: 'Optional workspace root path. Auto-detected if omitted.',\n },\n expectedPlanHash: {\n type: 'string',\n description:\n 'Optional: SHA-256 hash from generate_service or plan_review. If provided, apply_changes will verify the plan has not been modified before execution.',\n },\n requireReview: {\n type: 'boolean',\n description:\n 'Optional: If true, requires a valid reviewToken from plan_review before applying. Enforces review workflow.',\n },\n reviewToken: {\n type: 'string',\n description:\n 'Optional: Review token from plan_review (format: planHash.policyVersion). Required if requireReview is true.',\n },\n expectedPolicyVersion: {\n type: 'string',\n description:\n 'Optional: Expected policy version for reviewToken validation. Defaults to current POLICY_VERSION.',\n },\n },\n required: ['changes'],\n },\n execute,\n}\n","/**\n * plan_review Tool\n *\n * Validates a plan (effects array) without executing it.\n * Checks for path safety, conflicts, unsupported effects, and determinism.\n *\n * Use this before apply_changes to preview what would happen.\n * Includes planHash for integrity verification in apply_changes.\n */\n\nimport {\n findWorkspaceRoot,\n isElicitInputEffect,\n type OperationResult,\n type PfEffect,\n} from '@crossdelta/platform-sdk/facade'\nimport { applyEffects, isEffectSupported } from '../effects'\nimport { cacheReview } from '../plan-cache'\nimport { computePlanHash } from '../plan-hash'\nimport { generateReviewToken, POLICY_VERSION } from '../policy'\nimport type { ExecutableToolSpec } from './types'\n\n/**\n * Issue severity levels\n */\ntype IssueSeverity = 'error' | 'warning' | 'info'\n\n/**\n * Issue found during plan review\n */\ninterface PlanIssue {\n severity: IssueSeverity\n code: string\n message: string\n target?: string\n}\n\n/**\n * Target path extraction from effect\n */\ninterface TargetPath {\n path: string\n kind: string\n}\n\n/**\n * Plan review result\n */\ninterface PlanReviewResult {\n valid: boolean\n canApply: boolean\n issues: PlanIssue[]\n preview: {\n wouldCreate: number\n wouldUpdate: number\n wouldSkip: number\n errors: number\n }\n targets: TargetPath[]\n /** SHA-256 hash of the plan for integrity verification */\n planHash: string\n /** Current policy version */\n policyVersion: string\n /** Review token for use with apply_changes (planHash.policyVersion) */\n reviewToken: string\n /** ISO timestamp when review was performed */\n reviewedAt: string\n}\n\n/**\n * Input schema for plan_review tool\n */\nexport interface PlanReviewInput {\n /** Effects to review (from generate_service result) */\n changes: PfEffect[]\n /** Optional: Workspace root path */\n workspaceRoot?: string\n}\n\n/**\n * Validate changes array\n */\nconst validateChanges = (changes: unknown): changes is PfEffect[] => {\n if (!Array.isArray(changes)) return false\n return changes.every((c) => typeof c === 'object' && c !== null && 'kind' in c && typeof c.kind === 'string')\n}\n\n/**\n * Extract target path from effect\n */\nconst getEffectTarget = (effect: PfEffect): string | undefined => {\n if ('path' in effect && typeof effect.path === 'string') {\n return effect.path\n }\n if ('key' in effect && typeof effect.key === 'string') {\n return `.env.local:${effect.key}`\n }\n if ('serviceName' in effect && typeof effect.serviceName === 'string') {\n return `infra/services/${effect.serviceName}.ts`\n }\n return undefined\n}\n\n/**\n * Check for elicitation effects\n */\nconst checkElicitation = (effects: PfEffect[]): PlanIssue[] => {\n const elicitEffects = effects.filter(isElicitInputEffect)\n if (elicitEffects.length === 0) return []\n\n const fieldNames = elicitEffects\n .flatMap((e) => {\n if ('fields' in e && Array.isArray(e.fields)) {\n return (e.fields as ReadonlyArray<{ name: string }>).map((f) => f.name)\n }\n return []\n })\n .join(', ')\n\n return [\n {\n severity: 'error',\n code: 'REQUIRES_ELICITATION',\n message: `Plan requires user input for: ${fieldNames || 'unknown fields'}`,\n },\n ]\n}\n\n/**\n * Check for unsupported effect kinds\n */\nconst checkUnsupportedEffects = (effects: PfEffect[]): PlanIssue[] =>\n effects\n .filter((e) => !isEffectSupported(e.kind) && !isElicitInputEffect(e))\n .map((e) => ({\n severity: 'error' as const,\n code: 'UNSUPPORTED_EFFECT',\n message: `Unsupported effect kind: ${e.kind}`,\n target: getEffectTarget(e),\n }))\n\n/**\n * Check for duplicate targets (conflicts)\n */\nconst checkDuplicateTargets = (effects: PfEffect[]): PlanIssue[] => {\n const targets = effects.map(getEffectTarget).filter((t): t is string => t !== undefined)\n const seen = new Set<string>()\n const duplicates = new Set<string>()\n\n for (const target of targets) {\n if (seen.has(target)) {\n duplicates.add(target)\n }\n seen.add(target)\n }\n\n return Array.from(duplicates).map((target) => ({\n severity: 'warning' as const,\n code: 'DUPLICATE_TARGET',\n message: `Multiple effects target the same path: ${target}`,\n target,\n }))\n}\n\n/**\n * Extract all target paths\n */\nconst extractTargets = (effects: PfEffect[]): TargetPath[] =>\n effects\n .map((e) => {\n const path = getEffectTarget(e)\n return path ? { path, kind: e.kind } : null\n })\n .filter((t): t is TargetPath => t !== null)\n\n/**\n * Execute plan_review tool\n *\n * Validates and previews a plan without making changes.\n */\nconst execute = async (args: Record<string, unknown>): Promise<OperationResult<PlanReviewResult>> => {\n const { changes, workspaceRoot: workspaceRootArg } = args\n\n if (!changes) {\n return {\n ok: false,\n operation: 'plan_review',\n summary: 'Missing required input: changes',\n artifacts: [],\n changes: [],\n diagnostics: [{ level: 'error', message: 'changes array is required' }],\n }\n }\n\n if (!validateChanges(changes)) {\n return {\n ok: false,\n operation: 'plan_review',\n summary: 'Invalid changes format: expected array of effects with kind property',\n artifacts: [],\n changes: [],\n diagnostics: [{ level: 'error', message: 'Each change must have a \"kind\" property' }],\n }\n }\n\n const workspaceRoot = typeof workspaceRootArg === 'string' ? workspaceRootArg : findWorkspaceRoot()\n\n if (!workspaceRoot) {\n return {\n ok: false,\n operation: 'plan_review',\n summary: 'Could not determine workspace root',\n artifacts: [],\n changes: [],\n diagnostics: [\n { level: 'error', message: 'Workspace root not found' },\n { level: 'info', message: 'Provide workspaceRoot parameter or run from within a workspace' },\n ],\n }\n }\n\n // Collect all issues\n const issues: PlanIssue[] = [\n ...checkElicitation(changes),\n ...checkUnsupportedEffects(changes),\n ...checkDuplicateTargets(changes),\n ]\n\n // Run dry run to get preview and path safety issues\n const dryRunResult = applyEffects(changes, workspaceRoot, { dryRun: true })\n\n // Add path safety and other errors from dry run\n for (const result of dryRunResult.results) {\n if (!result.success && result.code) {\n issues.push({\n severity: 'error',\n code: result.code,\n message: result.message,\n target: result.target,\n })\n }\n }\n\n const hasErrors = issues.some((i) => i.severity === 'error')\n const targets = extractTargets(changes)\n const planHash = computePlanHash(changes)\n const reviewToken = generateReviewToken(planHash, POLICY_VERSION)\n const reviewedAt = new Date().toISOString()\n\n const reviewResult: PlanReviewResult = {\n valid: !hasErrors,\n canApply: !hasErrors && issues.every((i) => i.severity !== 'error'),\n issues,\n preview: {\n wouldCreate: dryRunResult.counts.wouldCreate,\n wouldUpdate: dryRunResult.counts.wouldUpdate,\n wouldSkip: dryRunResult.counts.wouldSkip,\n errors: dryRunResult.counts.error,\n },\n targets,\n planHash,\n policyVersion: POLICY_VERSION,\n reviewToken,\n reviewedAt,\n }\n\n // Cache the review for MCP resources\n cacheReview({\n planHash,\n policyVersion: POLICY_VERSION,\n reviewToken,\n reviewedAt,\n valid: reviewResult.valid,\n canApply: reviewResult.canApply,\n preview: reviewResult.preview,\n issues: reviewResult.issues,\n })\n\n // Build diagnostics\n const diagnostics = issues.map((issue) => ({\n level: (issue.severity === 'error' ? 'error' : issue.severity === 'warning' ? 'warning' : 'info') as\n | 'error'\n | 'warning'\n | 'info',\n message: `[${issue.code}] ${issue.message}`,\n location: issue.target,\n }))\n\n // Add preview summary\n if (reviewResult.canApply) {\n diagnostics.push({\n level: 'info',\n message: dryRunResult.summary,\n location: undefined,\n })\n }\n\n return {\n ok: reviewResult.valid,\n operation: 'plan_review',\n summary: reviewResult.valid\n ? `Plan is valid: ${dryRunResult.summary}`\n : `Plan has ${issues.filter((i) => i.severity === 'error').length} errors`,\n artifacts: [],\n changes: [], // No changes - this is review only\n diagnostics,\n data: reviewResult,\n }\n}\n\n/**\n * plan_review tool specification\n */\nexport const planReviewTool: ExecutableToolSpec = {\n name: 'plan_review',\n description:\n 'Review and validate a plan (effects array) without executing it. Checks for path safety issues, duplicate targets, unsupported effects, and elicitation requirements. Shows preview of what would be created/updated/skipped.',\n inputSchema: {\n type: 'object',\n properties: {\n changes: {\n type: 'array',\n description: 'Array of effects to review. Get this from the \"changes\" field of a generate_service result.',\n items: {\n type: 'object',\n properties: {\n kind: {\n type: 'string',\n description: 'Effect type: \"file:write\", \"env:add\", \"infra:add\"',\n },\n },\n required: ['kind'],\n },\n },\n workspaceRoot: {\n type: 'string',\n description: 'Optional workspace root path. Auto-detected if omitted.',\n },\n },\n required: ['changes'],\n },\n execute,\n}\n","/**\n * services.generate Tool\n *\n * Built-in MCP tool for planning service generation.\n * Supports two modes:\n * 1. Explicit (Mode A): template + name (calls planServiceGeneration)\n * 2. Natural Language (Mode B): prompt (calls capabilities pipeline)\n *\n * Returns ElicitInputEffect in changes[] when required inputs are missing.\n * Host (MCP/CLI) decides how to handle elicitation.\n */\n\nimport { findWorkspaceRoot } from '@crossdelta/platform-sdk/facade'\nimport type { ExecutableToolSpec } from '../types'\nimport { executeExplicitMode } from './mode-explicit'\nimport { executeNLMode } from './mode-nl'\nimport type { GenerateServiceResult } from './review'\n\n// Re-export types\nexport type { GenerateServiceResult } from './review'\nexport type { ServicesGenerateInput } from './validation'\n\n// ============================================================================\n// Main Executor\n// ============================================================================\n\n/**\n * Execute services.generate tool\n *\n * Two modes:\n * - Mode A (Explicit): template + name → planServiceGeneration()\n * - Mode B (NL): prompt → capabilities pipeline\n */\nconst execute = async (args: Record<string, unknown>): Promise<GenerateServiceResult> => {\n const { prompt, template, workspaceUri, dryRun, autoReview } = args\n\n // Resolve workspace root early (needed for both modes)\n const workspaceRoot = typeof workspaceUri === 'string' ? workspaceUri : findWorkspaceRoot()\n\n // Mode B: Natural Language prompt → capabilities pipeline\n if (typeof prompt === 'string' && prompt.trim().length > 0) {\n return executeNLMode(prompt, workspaceRoot, {\n dryRun: dryRun as boolean,\n autoReview: autoReview as boolean,\n template: template as string | undefined,\n })\n }\n\n // Mode A: Explicit template + name → template generation\n return executeExplicitMode(args, workspaceRoot, { dryRun: dryRun as boolean, autoReview: autoReview as boolean })\n}\n\n// ============================================================================\n// Tool Specification\n// ============================================================================\n\n/**\n * generate_service tool specification\n *\n * VS Code naming: snake_case with {verb}_{noun} pattern\n */\nexport const servicesGenerateTool: ExecutableToolSpec = {\n name: 'generate_service',\n description:\n 'Plan generation of a new microservice from a natural language prompt. Example: \"Erstelle notification-service, hört auf order.created, sendet Push via Pusher Beams\". Returns a structured plan with files, config, and environment variables. By default runs in plan-only mode (dryRun=true). After showing the plan, ask if user wants to apply it.\\n\\n📚 IMPORTANT: Before generating services, read the generator documentation:\\n1. First, read docs://generators to discover available documentation\\n2. Then read the relevant docs (e.g., docs://generators/service for main guidelines)\\n\\nThese resources contain up-to-date package versions, naming conventions, and best practices. Always verify package versions on npm - do not hallucinate versions!',\n inputSchema: {\n type: 'object',\n properties: {\n prompt: {\n type: 'string',\n description:\n 'Natural language prompt describing the service. Example: \"Erstelle notification-service, hört auf order.created, sendet Push via Pusher Beams\". When provided, uses capabilities pipeline for intelligent generation.',\n },\n template: {\n type: 'string',\n enum: ['hono-bun', 'nest'],\n description: 'Service template type. Required when not using prompt mode.',\n },\n name: {\n type: 'string',\n description: 'Service name in kebab-case. Required when not using prompt mode.',\n },\n workspaceUri: {\n type: 'string',\n description: 'Optional workspace root path. Auto-detected if omitted.',\n },\n port: {\n type: 'number',\n description: 'Optional explicit port number. Auto-allocated if omitted.',\n },\n events: {\n type: 'array',\n items: { type: 'string' },\n description: 'Event types to consume (e.g., [\"order.created\"]). Only for explicit mode.',\n },\n dryRun: {\n type: 'boolean',\n description: 'Plan-only mode (default: true). When true, returns plan without writing files.',\n default: true,\n },\n autoReview: {\n type: 'boolean',\n description: 'Include inline plan validation (default: false).',\n default: false,\n },\n },\n required: [],\n },\n execute,\n}\n","/**\n * Service Generation - Mode A: Explicit (Template + Name)\n *\n * Direct template-based service generation.\n */\n\nimport { planServiceGeneration } from '@crossdelta/platform-sdk/facade'\n\nimport { cachePlan } from '../../plan-cache'\nimport { computePlanHash } from '../../plan-hash'\nimport { applyPlanEffects, type GenerateServiceResult, runInlineReview } from './review'\nimport { createElicitResult, getMissingFields, isValidTemplate } from './validation'\n\n// ============================================================================\n// Mode A: Explicit Execution\n// ============================================================================\n\nexport interface ExplicitModeOptions {\n dryRun?: boolean\n autoReview?: boolean\n}\n\n/**\n * Execute Mode A: Explicit template + name → planServiceGeneration\n */\nexport const executeExplicitMode = (\n args: Record<string, unknown>,\n workspaceRoot: string,\n _options: ExplicitModeOptions,\n): GenerateServiceResult => {\n const { template, name, port, events, dryRun, autoReview } = args\n\n // Check for missing required fields → return elicitation effect\n const missingFields = getMissingFields(args)\n if (missingFields.length > 0) {\n return createElicitResult('Missing required inputs for service generation', missingFields)\n }\n\n // Validate template value\n if (!isValidTemplate(template as string)) {\n return createElicitResult(`Invalid template: ${template}. Please select a valid template.`, [\n {\n name: 'template',\n prompt: 'Which service template would you like to use?',\n required: true,\n description: 'Service template type for scaffolding',\n type: 'string',\n enum: ['hono-bun', 'nest'],\n },\n ])\n }\n\n // Parse events array\n const eventsList = Array.isArray(events) ? events.filter((e) => typeof e === 'string') : []\n\n // Execute service generation\n const result = planServiceGeneration({\n type: template as 'hono-bun' | 'nest',\n name: name as string,\n workspaceRoot,\n port: typeof port === 'number' ? port : undefined,\n events: eventsList,\n })\n\n // Add planHash for integrity verification\n if (result.ok && result.changes.length > 0) {\n const planHash = computePlanHash(result.changes)\n const extendedResult: GenerateServiceResult = {\n ...result,\n planHash,\n }\n\n // Cache the plan for MCP resources\n cachePlan({\n planHash,\n effects: result.changes,\n createdAt: new Date().toISOString(),\n source: 'generate_service',\n metadata: {\n template: template as string,\n name: name as string,\n port: typeof port === 'number' ? port : undefined,\n },\n })\n\n // Add inline review if requested\n if (autoReview === true) {\n extendedResult.review = runInlineReview(result.changes, workspaceRoot)\n }\n\n // Auto-apply if dryRun is explicitly false\n if (dryRun === false) {\n return applyPlanEffects(extendedResult, workspaceRoot)\n }\n\n return extendedResult\n }\n\n return result\n}\n","/**\n * Service Generation - Review & Apply\n *\n * Inline review and effect application helpers.\n */\n\nimport type { OperationResult, PfEffect, ServiceMeta } from '@crossdelta/platform-sdk/facade'\n\nimport { applyEffects, isEffectSupported } from '../../effects'\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface ReviewResult {\n valid: boolean\n canApply: boolean\n issues: Array<{ severity: string; code: string; message: string }>\n preview: { wouldCreate: number; wouldUpdate: number; wouldSkip: number; errors: number }\n}\n\nexport interface GenerateServiceResult extends OperationResult<ServiceMeta | undefined> {\n /** SHA-256 hash of the plan for integrity verification */\n planHash?: string\n /** Files that need AI-generated content (path + intent + inputs, NO content) */\n files?: Array<{\n path: string\n intent: string\n inputs: Record<string, unknown>\n layer?: string\n kind?: string\n }>\n /** Dependencies to add (for deps:add effects) */\n dependencies?: Array<{\n name: string\n version?: string\n dev?: boolean\n }>\n /** Environment variables needed */\n envVars?: Array<{\n key: string\n description: string\n required: boolean\n }>\n /** Post-generation commands */\n postCommands?: string[]\n /** Inline review result (when autoReview=true) */\n review?: ReviewResult\n}\n\n// ============================================================================\n// Review Functions (Pure where possible)\n// ============================================================================\n\n/**\n * Run inline plan review (simplified version of plan_review tool)\n */\nexport const runInlineReview = (changes: readonly PfEffect[], workspaceRoot: string): ReviewResult => {\n const issues: Array<{ severity: string; code: string; message: string }> = []\n\n // Check for unsupported effects\n for (const effect of changes) {\n if (!isEffectSupported(effect.kind)) {\n issues.push({\n severity: 'error',\n code: 'UNSUPPORTED_EFFECT',\n message: `Unsupported effect kind: ${effect.kind}`,\n })\n }\n }\n\n // Run dry run to get preview\n const dryRunResult = applyEffects(changes as PfEffect[], workspaceRoot, { dryRun: true })\n\n // Add errors from dry run\n for (const result of dryRunResult.results) {\n if (!result.success && result.code) {\n issues.push({\n severity: 'error',\n code: result.code,\n message: result.message,\n })\n }\n }\n\n const hasErrors = issues.some((i) => i.severity === 'error')\n\n return {\n valid: !hasErrors,\n canApply: !hasErrors,\n issues,\n preview: {\n wouldCreate: dryRunResult.counts.wouldCreate,\n wouldUpdate: dryRunResult.counts.wouldUpdate,\n wouldSkip: dryRunResult.counts.wouldSkip,\n errors: dryRunResult.counts.error,\n },\n }\n}\n\n/**\n * Apply plan effects and merge diagnostics into result\n */\nexport const applyPlanEffects = (result: GenerateServiceResult, workspaceRoot: string): GenerateServiceResult => {\n const applyResult = applyEffects(result.changes as PfEffect[], workspaceRoot, { dryRun: false })\n\n return {\n ...result,\n summary: `${result.summary} - ${applyResult.summary}`,\n diagnostics: [\n ...(result.diagnostics ?? []),\n ...applyResult.results\n .filter((r) => r.message)\n .map((r) => ({\n level: r.success ? ('info' as const) : ('error' as const),\n message: r.message,\n location: r.path,\n })),\n ],\n }\n}\n","/**\n * Service Generation - Validation & Elicitation\n *\n * Pure functions for input validation and elicitation.\n */\n\nimport type { ElicitInputEffect, ElicitInputField, OperationResult } from '@crossdelta/platform-sdk/facade'\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface ServicesGenerateInput {\n /** Natural language prompt (Mode B - uses capabilities pipeline) */\n prompt?: string\n /** Template type (Mode A - uses template generation) */\n template?: 'hono-bun' | 'nest'\n /** Service name (kebab-case, required for Mode A) */\n name?: string\n /** Optional: Workspace URI/path */\n workspaceUri?: string\n /** Optional: Explicit port for deterministic generation */\n port?: number\n /** Optional: Plan-only mode (default: true) */\n dryRun?: boolean\n /** Optional: Event types to consume (e.g., ['order.created']) */\n events?: string[]\n /** Optional: Include inline plan validation */\n autoReview?: boolean\n}\n\nexport const VALID_TEMPLATES = ['hono-bun', 'nest'] as const\nexport type ValidTemplate = (typeof VALID_TEMPLATES)[number]\n\n// ============================================================================\n// Validation Functions (Pure)\n// ============================================================================\n\n/**\n * Check which required fields are missing for Mode A (explicit)\n */\nexport const getMissingFields = (args: Record<string, unknown>): ElicitInputField[] => {\n const { template, name } = args\n const missing: ElicitInputField[] = []\n\n if (!template || typeof template !== 'string') {\n missing.push({\n name: 'template',\n prompt: 'Which service template would you like to use?',\n required: true,\n description: 'Service template type for scaffolding',\n type: 'string',\n enum: [...VALID_TEMPLATES],\n })\n }\n\n if (!name || typeof name !== 'string') {\n missing.push({\n name: 'name',\n prompt: 'What should the service be named?',\n required: true,\n description: 'Service name in kebab-case (e.g., \"order-processing\")',\n type: 'string',\n })\n }\n\n return missing\n}\n\n/**\n * Validate template value\n */\nexport const isValidTemplate = (template: string): template is ValidTemplate =>\n VALID_TEMPLATES.includes(template as ValidTemplate)\n\n// ============================================================================\n// Elicitation Helpers (Pure)\n// ============================================================================\n\n/**\n * Create an elicitation result\n *\n * Returns OperationResult with elicit:input effect in changes array.\n * Host interprets this and handles elicitation appropriately.\n */\nexport const createElicitResult = (message: string, fields: ElicitInputField[]): OperationResult<undefined> => {\n const elicitEffect: ElicitInputEffect = {\n kind: 'elicit:input',\n message,\n fields,\n }\n\n return {\n ok: false,\n operation: 'generate_service',\n summary: message,\n artifacts: [],\n changes: [elicitEffect],\n diagnostics: [{ level: 'info', message: 'Awaiting user input' }],\n }\n}\n\n/**\n * Convert parser elicit fields to MCP elicit fields\n */\nexport const toMcpElicitFields = (\n fields: Array<{ path: string; prompt: string; required: boolean; type: string; options?: string[] }>,\n): ElicitInputField[] =>\n fields.map((f) => ({\n name: f.path,\n prompt: f.prompt,\n required: f.required,\n description: f.prompt,\n type: f.type === 'enum' ? 'string' : 'string',\n enum: f.options,\n }))\n","/**\n * Service Generation - Natural Language Mode\n *\n * NL prompt → parsed spec → service scaffold → AI generates code\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport {\n loadCapabilitiesConfig,\n lowerSpecToCapabilities,\n type PfEffect,\n parseServicePrompt,\n planServiceGeneration,\n type ServiceMeta,\n} from '@crossdelta/platform-sdk/facade'\n\nimport { cachePlan } from '../../plan-cache'\nimport { computePlanHash } from '../../plan-hash'\nimport { verifyAndCorrectNpmVersions } from './npm-verifier'\nimport { applyPlanEffects, type GenerateServiceResult, runInlineReview } from './review'\nimport { createElicitResult, toMcpElicitFields } from './validation'\n\nexport interface NLModeOptions {\n dryRun?: boolean\n autoReview?: boolean\n template?: string\n}\n\ninterface Diagnostic {\n level: 'info' | 'error'\n message: string\n}\n\ninterface Artifact {\n type: 'service' | 'file' | 'config' | 'env' | 'stream'\n path: string\n description: string\n}\n\ninterface EnvVar {\n key: string\n description?: string\n required?: boolean\n}\n\n/**\n * Build diagnostic messages for service generation result\n */\nconst buildDiagnostics = (\n spec: { serviceName: string },\n serviceMeta: ServiceMeta,\n files: { path: string; intent: string }[],\n scaffoldCount: number,\n aiFilesCount: number,\n dependencies: { name: string }[],\n envVars: EnvVar[],\n templateType: string,\n): Diagnostic[] => [\n { level: 'info' as const, message: `Parsed from prompt: ${spec.serviceName}` },\n { level: 'info' as const, message: `Template: ${templateType} (port ${serviceMeta.port})` },\n { level: 'info' as const, message: `Scaffold files: ${scaffoldCount} (ready to apply)` },\n { level: 'info' as const, message: `Files for AI: ${aiFilesCount} (${files.map((f) => f.intent).join(', ')})` },\n ...(dependencies.length > 0\n ? [{ level: 'info' as const, message: `Dependencies: ${dependencies.map((d) => d.name).join(', ')}` }]\n : []),\n ...(envVars.length > 0\n ? [{ level: 'info' as const, message: `Env vars: ${envVars.map((e) => e.key).join(', ')}` }]\n : []),\n]\n\n/**\n * Normalize file metadata by ensuring all optional fields have default values\n */\nconst normalizeFiles = (\n files: {\n path: string\n intent: string\n inputs?: Record<string, unknown>\n layer?: string\n kind?: string\n }[],\n) =>\n files.map((f) => ({\n path: f.path,\n intent: f.intent,\n inputs: f.inputs ?? {},\n layer: f.layer,\n kind: f.kind,\n }))\n\n/**\n * Extract event types from service spec triggers\n */\nconst extractEventsFromSpec = (spec: { triggers: { type: string; eventType?: string }[] }): string[] =>\n spec.triggers\n .filter((t): t is { type: 'event'; eventType: string } => t.type === 'event' && !!t.eventType)\n .map((t) => t.eventType)\n\n/**\n * Convert dependencies record to array format for service generation result\n */\nconst extractDependencies = (deps: Record<string, string>) =>\n Object.entries(deps).map(([name, version]) => ({\n name,\n version,\n dev: false,\n }))\n\n/**\n * Build complete service generation result object with all metadata\n */\nconst buildServiceResult = (\n spec: { serviceName: string },\n serviceMeta: ServiceMeta,\n serviceDir: string,\n correctedChanges: PfEffect[],\n metadata: {\n files: { path: string; intent: string; inputs?: Record<string, unknown>; layer?: string; kind?: string }[]\n dependencies: Record<string, string>\n envVars: EnvVar[]\n postCommands: string[]\n },\n dependencies: { name: string; version: string; dev: boolean }[],\n verificationCorrections: { name: string; generatedVersion: string; actualVersion: string }[],\n templateType: string,\n scaffoldArtifacts: Artifact[],\n): GenerateServiceResult => ({\n ok: true,\n operation: 'generate_service',\n summary: `Planned ${spec.serviceName}: ${correctedChanges.length} scaffold files + ${metadata.files.length} files for AI to generate`,\n data: serviceMeta,\n artifacts: [\n ...scaffoldArtifacts,\n { type: 'service' as const, path: serviceDir, description: `Generated service ${spec.serviceName}` },\n ],\n changes: correctedChanges,\n files: normalizeFiles(metadata.files),\n dependencies,\n envVars: metadata.envVars.map((ev) => ({\n key: ev.key,\n description: ev.description ?? '',\n required: ev.required ?? false,\n })),\n postCommands: metadata.postCommands,\n diagnostics: [\n ...buildDiagnostics(\n spec,\n serviceMeta,\n metadata.files,\n correctedChanges.length,\n metadata.files.length,\n dependencies,\n metadata.envVars,\n templateType,\n ),\n ...verificationCorrections.map((c) => ({\n level: 'info' as const,\n message: `📦 Corrected ${c.name}: ${c.generatedVersion} → ^${c.actualVersion}`,\n })),\n ],\n})\n\n/**\n * Execute Natural Language Mode: Parse prompt → scaffold service → AI generates code\n *\n * Pipeline:\n * 1. parseServicePrompt() → ServiceSpec (with provider detection)\n * 2. lowerSpecToCapabilities() → Metadata (deps, env vars, file intents)\n * 3. planServiceGeneration() → Base service scaffold (package.json, index.ts, etc.)\n * 4. Return plan with file intents for AI to generate\n *\n * If parsing is incomplete (missing provider, etc.), returns elicitation.\n */\nexport const executeNLMode = async (\n prompt: string,\n workspaceRoot: string,\n options: NLModeOptions,\n): Promise<GenerateServiceResult> => {\n // Load workspace capabilities config (for custom providers)\n const pkgPath = join(workspaceRoot, 'package.json')\n const pkg = existsSync(pkgPath) ? JSON.parse(readFileSync(pkgPath, 'utf-8')) : null\n const workspaceConfig = loadCapabilitiesConfig(pkg)\n\n // Parse prompt → ServiceSpec\n const parseResult = await parseServicePrompt(prompt, { workspaceConfig })\n\n // Incomplete parse → elicitation\n if (!parseResult.complete) {\n const fields = toMcpElicitFields(parseResult.fields)\n return createElicitResult('Additional information needed', fields)\n }\n\n const spec = parseResult.spec\n\n // Extract events from triggers for service scaffold\n const events = extractEventsFromSpec(spec)\n\n // Service directory path\n const serviceDir = `services/${spec.serviceName}`\n\n // Lower spec to capability metadata (deps, env vars, file intents)\n const metadata = lowerSpecToCapabilities(spec, serviceDir)\n\n // Generate base service scaffold\n const templateType = options.template || 'hono-bun'\n const scaffoldResult = planServiceGeneration({\n type: templateType as 'hono-bun' | 'nest',\n name: spec.serviceName,\n workspaceRoot,\n events,\n envVars: metadata.envVars,\n })\n\n if (!scaffoldResult.ok) {\n return {\n ok: false,\n operation: 'generate_service',\n summary: scaffoldResult.summary,\n artifacts: [],\n changes: [],\n diagnostics: [{ level: 'error', message: scaffoldResult.summary }],\n }\n }\n\n if (!scaffoldResult.data) {\n return {\n ok: false,\n operation: 'generate_service',\n summary: 'Service scaffold generation failed: no data returned',\n artifacts: [],\n changes: [],\n diagnostics: [{ level: 'error', message: 'No service metadata returned from scaffold' }],\n }\n }\n\n // Extract dependencies\n const dependencies = extractDependencies(metadata.dependencies)\n\n // Verify and correct npm package versions\n const { correctedChanges, result: verificationResult } = await verifyAndCorrectNpmVersions(scaffoldResult.changes)\n\n // Build result\n const serviceMeta = scaffoldResult.data\n const result = buildServiceResult(\n spec,\n serviceMeta,\n serviceDir,\n correctedChanges as PfEffect[],\n metadata,\n dependencies,\n verificationResult.corrections,\n templateType,\n (scaffoldResult.artifacts ?? []) as Artifact[],\n )\n\n // Add planHash\n if (result.changes.length > 0) {\n result.planHash = computePlanHash(result.changes)\n cachePlan({\n planHash: result.planHash,\n effects: result.changes,\n createdAt: new Date().toISOString(),\n source: 'generate_service',\n metadata: { prompt, serviceName: spec.serviceName, filesToGenerate: metadata.files.length },\n })\n }\n\n // Add inline review if requested\n if (options.autoReview === true) {\n result.review = runInlineReview(result.changes, workspaceRoot)\n }\n\n // Auto-apply if dryRun is explicitly false\n if (options.dryRun === false) {\n return applyPlanEffects(result, workspaceRoot)\n }\n\n return result\n}\n","/**\n * NPM Package Version Verification\n *\n * Verifies and corrects npm package versions in generated package.json files.\n * Architecture: Types → Pure functions → IO adapter → Higher-order function\n */\n\nimport type { FileWriteEffect, PfEffect } from '@crossdelta/platform-sdk/facade'\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface PackageCorrection {\n name: string\n generatedVersion: string\n actualVersion: string\n corrected: boolean\n}\n\nexport interface VerificationResult {\n corrections: PackageCorrection[]\n hasCorrections: boolean\n}\n\ninterface PackageJson {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n}\n\n// ============================================================================\n// Pure Functions\n// ============================================================================\n\n/**\n * Parse package.json content from string\n */\nconst parsePackageJson = (content: string): PackageJson | null => {\n try {\n return JSON.parse(content) as PackageJson\n } catch {\n return null\n }\n}\n\n/**\n * Extract npm packages from dependencies (excluding workspace packages)\n */\nconst extractNpmPackages = (pkg: PackageJson): Array<{ name: string; version: string }> => {\n const allDeps = {\n ...(pkg.dependencies ?? {}),\n ...(pkg.devDependencies ?? {}),\n }\n\n return Object.entries(allDeps)\n .filter(([_, version]) => !version.startsWith('workspace:'))\n .map(([name, version]) => ({ name, version }))\n}\n\n/**\n * Normalize version string (remove ^ prefix)\n */\nconst normalizeVersion = (version: string): string => version.replace(/^\\^/, '')\n\n/**\n * Create correction entry\n */\nconst createCorrection = (name: string, generatedVersion: string, actualVersion: string | null): PackageCorrection => ({\n name,\n generatedVersion,\n actualVersion: actualVersion ?? generatedVersion,\n corrected: actualVersion !== null && normalizeVersion(generatedVersion) !== actualVersion,\n})\n\n/**\n * Apply corrections to package.json\n */\nconst applyCorrections = (pkg: PackageJson, corrections: PackageCorrection[]): PackageJson => {\n const corrected = { ...pkg }\n\n for (const correction of corrections.filter((c) => c.corrected)) {\n if (corrected.dependencies?.[correction.name]) {\n corrected.dependencies = {\n ...corrected.dependencies,\n [correction.name]: `^${correction.actualVersion}`,\n }\n }\n if (corrected.devDependencies?.[correction.name]) {\n corrected.devDependencies = {\n ...corrected.devDependencies,\n [correction.name]: `^${correction.actualVersion}`,\n }\n }\n }\n\n return corrected\n}\n\n// ============================================================================\n// IO Adapter\n// ============================================================================\n\n/**\n * Fetch latest version from npm registry\n * Side effect: HTTP request\n */\nconst fetchNpmVersion = async (packageName: string): Promise<string | null> => {\n try {\n const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`)\n if (!response.ok) return null\n\n const data = (await response.json()) as { version?: string }\n return data.version ?? null\n } catch {\n return null\n }\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Type guard for file:write effects\n */\nconst isFileWriteEffect = (effect: PfEffect): effect is FileWriteEffect => effect.kind === 'file:write'\n\n// ============================================================================\n// Higher-Order Function\n// ============================================================================\n\n/**\n * Verify and correct npm package versions in package.json content\n *\n * @param content - package.json content as string\n * @returns Corrected content and verification result\n */\nexport const verifyAndCorrectPackageJson = async (\n content: string,\n): Promise<{ correctedContent: string; result: VerificationResult }> => {\n // Parse package.json\n const pkg = parsePackageJson(content)\n if (!pkg) {\n return {\n correctedContent: content,\n result: { corrections: [], hasCorrections: false },\n }\n }\n\n // Extract npm packages\n const packages = extractNpmPackages(pkg)\n if (packages.length === 0) {\n return {\n correctedContent: content,\n result: { corrections: [], hasCorrections: false },\n }\n }\n\n // Fetch versions from npm registry\n const corrections = await Promise.all(\n packages.map(async ({ name, version }) => {\n const actualVersion = await fetchNpmVersion(name)\n return createCorrection(name, version, actualVersion)\n }),\n )\n\n // Apply corrections\n const hasCorrections = corrections.some((c) => c.corrected)\n const correctedPkg = hasCorrections ? applyCorrections(pkg, corrections) : pkg\n\n return {\n correctedContent: JSON.stringify(correctedPkg, null, 2),\n result: {\n corrections: corrections.filter((c) => c.corrected),\n hasCorrections,\n },\n }\n}\n\n/**\n * Verify and correct npm versions in effect changes\n *\n * @param changes - Array of effects from service generation\n * @returns Corrected changes and verification result\n */\nexport const verifyAndCorrectNpmVersions = async (\n changes: PfEffect[],\n): Promise<{ correctedChanges: PfEffect[]; result: VerificationResult }> => {\n // Find package.json in changes\n const pkgIndex = changes.findIndex((c) => isFileWriteEffect(c) && c.path.endsWith('package.json'))\n\n if (pkgIndex === -1) {\n return {\n correctedChanges: changes,\n result: { corrections: [], hasCorrections: false },\n }\n }\n\n // Verify and correct package.json (type is narrowed by findIndex predicate)\n const pkgChange = changes[pkgIndex] as FileWriteEffect\n const { correctedContent, result } = await verifyAndCorrectPackageJson(pkgChange.content)\n\n // Return corrected changes\n const correctedChanges = [...changes]\n const correctedFileEffect: FileWriteEffect = {\n kind: 'file:write',\n path: pkgChange.path,\n content: correctedContent,\n }\n correctedChanges[pkgIndex] = correctedFileEffect\n\n return { correctedChanges, result }\n}\n","/**\n * workspace.scan Tool\n *\n * Read-only MCP tool that returns a snapshot of the current workspace.\n * No file writes, no effects - pure read operation.\n *\n * @module tools/workspace-scan\n */\n\nimport {\n createContextFromWorkspace,\n type OperationResult,\n type PfWorkspaceContext,\n} from '@crossdelta/platform-sdk/facade'\nimport type { ExecutableToolSpec } from './types'\n\n/**\n * Workspace scan metadata returned by the tool\n */\nexport interface WorkspaceScanMeta {\n /** Absolute path to workspace root */\n workspaceRoot: string\n /** Contracts package info */\n contracts: PfWorkspaceContext['contracts']\n /** List of discovered services (relative paths) */\n availableServices: string[]\n /** List of loaded plugin module names */\n loadedPlugins: string[]\n}\n\n/**\n * Input for workspace.scan tool\n */\nexport interface WorkspaceScanInput {\n /** Optional workspace root override (defaults to auto-discovery) */\n workspaceRoot?: string\n}\n\n/**\n * Normalize input args\n */\nconst normalizeInput = (args: Record<string, unknown>): WorkspaceScanInput => ({\n workspaceRoot: typeof args.workspaceRoot === 'string' ? args.workspaceRoot : undefined,\n})\n\n/**\n * Build WorkspaceScanMeta from context\n */\nconst buildScanMeta = (context: { workspace: PfWorkspaceContext }, loadedPlugins: string[]): WorkspaceScanMeta => ({\n workspaceRoot: context.workspace.workspaceRoot,\n contracts: context.workspace.contracts,\n availableServices: context.workspace.availableServices,\n loadedPlugins,\n})\n\n/**\n * Create success OperationResult for workspace scan\n */\nconst createScanResult = (meta: WorkspaceScanMeta): OperationResult<WorkspaceScanMeta> => ({\n ok: true,\n operation: 'scan_workspace',\n summary: `Workspace scanned: ${meta.availableServices.length} services, contracts at ${meta.contracts.packageName}`,\n artifacts: [],\n changes: [], // Read-only: no changes\n diagnostics: [],\n data: meta,\n})\n\n/**\n * Create error OperationResult for workspace scan\n */\nconst createScanError = (error: Error): OperationResult<WorkspaceScanMeta> => ({\n ok: false,\n operation: 'scan_workspace',\n summary: `Failed to scan workspace: ${error.message}`,\n artifacts: [],\n changes: [], // Read-only: no changes\n diagnostics: [\n {\n level: 'error',\n message: error.message,\n },\n ],\n})\n\n/**\n * Execute workspace.scan tool\n *\n * Returns OperationResult<WorkspaceScanMeta> with workspace snapshot.\n * Read-only: changes[] is always empty.\n *\n * @param args - Tool arguments\n * @param pluginModules - Plugin module names (injected by server)\n */\nexport const execute = async (\n args: Record<string, unknown>,\n pluginModules: string[] = [],\n): Promise<OperationResult<WorkspaceScanMeta>> => {\n try {\n const input = normalizeInput(args)\n\n // Use facade's createContextFromWorkspace for auto-discovery\n const context = await createContextFromWorkspace(input.workspaceRoot)\n\n const meta = buildScanMeta(context, pluginModules)\n return createScanResult(meta)\n } catch (error) {\n return createScanError(error instanceof Error ? error : new Error(String(error)))\n }\n}\n\n/**\n * Tool input schema definition (reusable)\n */\nexport const workspaceScanInputSchema = {\n type: 'object' as const,\n properties: {\n workspaceRoot: {\n type: 'string',\n description: 'Optional: Absolute path to workspace root. If omitted, auto-discovers from current directory.',\n },\n },\n required: [] as string[],\n}\n\n/**\n * Create scan_workspace tool with injected plugin modules\n *\n * Factory function that creates a properly-configured tool spec\n * with plugin modules injected into execute().\n *\n * VS Code naming: snake_case with {verb}_{noun} pattern\n *\n * @param pluginModules - Array of plugin module names to report\n * @returns ExecutableToolSpec for scan_workspace\n */\nexport const createWorkspaceScanTool = (pluginModules: string[]): ExecutableToolSpec => ({\n name: 'scan_workspace',\n description:\n 'Scan the current workspace and return a read-only snapshot including workspace root, contracts configuration, discovered services, and loaded plugins. Does not write any files.',\n inputSchema: workspaceScanInputSchema,\n execute: async (args) => execute(args, pluginModules),\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACuBA,qBAAyC;AACzC,uBAA8B;AAiCvB,IAAM,YAAY;AAQlB,IAAM,wBAAwB,CAAC,UAAkB,cAA8B;AACpF,QAAM,gBAAgB,UAAU,QAAQ,MAAM,GAAG,EAAE,QAAQ,OAAO,GAAG;AACrE,SAAO,GAAG,SAAS,MAAM,GAAG,EAAE,CAAC,IAAI,aAAa;AAClD;AASO,IAAM,qBAAqB,C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AQ,SAAS;AAE9B,UAAQ,KAAK,eAAe,IAAI,kBAAkB,MAAM,MAAM,WAAW,UAAU,MAAM,YAAY;AACvG;AAUO,IAAM,+BAA+B,OAAO,YAAiD;AAClG,QAAM,EAAE,MAAM,SAAS,eAAe,SAAS,eAAe,OAAO,IAAI;AAGzE,QAAM,UAAU,UAAM,4CAA2B,eAAe,MAAM;AACtE,QAAM,gBAAgB,UAAM,6BAAY,eAAe,OAAO;AAC9D,QAAM,kBAAc,4CAA2B,eAAe,OAAO;AAGrE,QAAM,iBAAiB,QAAQ,UAAU;AACzC,QAAM,QAAQ,WAAW,aAAa,aAAa;AACnD,QAAM,YAAY,MAAM,eAAe,eAAe,cAAc;AAGpE,QAAM,SAAS,IAAI,qBAAO,EAAE,MAAM,QAAQ,GAAG,EAAE,cAAc,EAAE,OAAO,CAAC,GAAG,WAAW,CAAC,GAAG,aAAa,CAAC,EAAE,EAAE,CAAC;AAC5G,mBAAiB,QAAQ,OAAO,SAAS;AAGzC,QAAM,YAAY,IAAI,kCAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAE9B,UAAQ;AAAA,IACN,eAAe,IAAI,kBAAkB,MAAM,MAAM,WAAW,UAAU,MAAM;AAAA,EAC9E;AACF;","names":["import_node_fs","import_node_path","import_node_fs","import_node_path","createSkipResult","createAddResult","createErrorResult","import_node_crypto","createSkipResult","createPathSafetyError","createSkipResult","createUpdateResult","createCreateResult","createErrorResult","createPolicyViolationResult","import_facade","import_node_path","import_facade","import_facade","import_promises","import_node_path","import_facade","import_facade","import_types","import_types","import_facade","import_facade","validateChanges","execute","import_facade","import_facade","import_node_fs","import_node_path","import_facade","execute","import_facade","execute"]}