@kb-labs/mind-core 2.93.0 → 2.96.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/error/mind-error.ts","../src/utils/token.ts","../src/utils/hash.ts","../src/utils/paths.ts","../src/utils/math.ts","../src/utils/file-rotation.ts","../src/utils/json.ts","../src/verification/verify-indexes.ts","../src/defaults.ts"],"names":["readFile","dotProduct","path","fsp"],"mappings":";;;;;;;;;AAKO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EACnC,WAAA,CACS,IAAA,EACP,OAAA,EACO,IAAA,EACA,IAAA,EACP;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AALN,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAEA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGP,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AAAA,EACd;AAAA,EAPS,IAAA;AAAA,EAEA,IAAA;AAAA,EACA,IAAA;AAKX;AAKO,SAAS,YAAY,GAAA,EAAwB;AAClD,EAAA,IAAI,GAAA,CAAI,SAAS,gBAAA,EAAkB;AAAC,IAAA,OAAO,CAAA;AAAA,EAAE;AAC7C,EAAA,IAAI,GAAA,CAAI,SAAS,aAAA,EAAe;AAAC,IAAA,OAAO,CAAA;AAAA,EAAE;AAC1C,EAAA,IAAI,GAAA,CAAI,SAAS,iBAAA,EAAmB;AAAC,IAAA,OAAO,CAAA;AAAA,EAAE;AAC9C,EAAA,IAAI,GAAA,CAAI,SAAS,kBAAA,EAAoB;AAAC,IAAA,OAAO,CAAA;AAAA,EAAE;AAC/C,EAAA,IAAI,GAAA,CAAI,SAAS,2BAAA,EAA6B;AAAC,IAAA,OAAO,CAAA;AAAA,EAAE;AACxD,EAAA,IAAI,GAAA,CAAI,IAAA,CAAK,U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AAAA,EACF;AACF;;;ACjIO,IAAM,cAAA,GAAgC;AAAA,EAC3C,WAAA,EAAa,GAAA;AAAA,EACb,IAAA,EAAM;AAAA,IACJ,cAAA,EAAgB,GAAA;AAAA,IAChB,gBAAA,EAAkB,GAAA;AAAA,IAClB,YAAA,EAAc,GAAA;AAAA,IACd,cAAA,EAAgB,IAAA;AAAA,IAChB,YAAA,EAAc,IAAA;AAAA,IACd,aAAA,EAAe,GAAA;AAAA,IACf,aAAA,EAAe,GAAA;AAAA,IACf,gBAAA,EAAkB;AAAA,GACpB;AAAA,EACA,UAAA,EAAY;AACd;AAKO,IAAM,cAAA,GAAgC;AAAA,EAC3C,IAAA,EAAM,UAAA;AAAA,EACN,MAAA,EAAQ;AAAA,IACN,QAAA,EAAU,CAAA;AAAA,IACV,GAAA,EAAK,GAAA;AAAA,IACL,KAAA,EAAO,CAAA;AAAA,IACP,QAAA,EAAU,GAAA;AAAA,IACV,OAAA,EAAS,GAAA;AAAA,IACT,IAAA,EAAM,GAAA;AAAA,IACN,IAAA,EAAM;AAAA;AAEV;AAKO,IAAM,sBAAA,GAAyB;AAK/B,IAAM,mBAAA,GAAsB,MAAM,IAAA,GAAO;AAKzC,IAAM,iBAAA,GAAoB;AAK1B,SAAS,YAAA,GAAuB;AACrC,EAAA,OAAO,oBAAA;AACT","file":"index.js","sourcesContent":["/**\n * @module @kb-labs/mind-core/error\n * Standardized error class for KB Labs Mind\n */\n\nexport class MindError extends Error {\n constructor(\n public code: string,\n message: string,\n public hint?: string,\n public meta?: unknown\n ) {\n super(message);\n this.name = 'MindError';\n }\n}\n\n/**\n * Maps MindError codes to CLI exit codes\n */\nexport function getExitCode(err: MindError): number {\n if (err.code === 'MIND_FORBIDDEN') {return 3;}\n if (err.code === 'MIND_NO_GIT') {return 2;}\n if (err.code === 'MIND_FS_TIMEOUT') {return 2;}\n if (err.code === 'MIND_PARSE_ERROR') {return 1;}\n if (err.code === 'MIND_PACK_BUDGET_EXCEEDED') {return 1;}\n if (err.code.startsWith('MIND_')) {return 1;}\n return 1;\n}\n\n/**\n * Error codes with their standard hints\n */\nexport const ERROR_HINTS = {\n MIND_NO_GIT: 'Initialize git repository or run from a git repository',\n MIND_FS_TIMEOUT: 'File system operation timed out - try increasing time budget',\n MIND_PARSE_ERROR: 'Failed to parse file - check syntax and try again',\n MIND_PACK_BUDGET_EXCEEDED: 'Context pack exceeds token budget - reduce content or increase budget',\n MIND_FORBIDDEN: 'Operation not permitted - check file permissions',\n MIND_TIME_BUDGET: 'Time budget exceeded - operation completed partially',\n MIND_BAD_FLAGS: 'Invalid command line flags - check values and try again',\n MIND_INVALID_FLAG: 'Invalid flag value - check format and try again',\n MIND_BUNDLE_TIMEOUT: 'Bundle operation timed out - skipped bundle information',\n MIND_FEED_ERROR: 'Mind feed operation failed - check logs for details',\n MIND_INIT_ERROR: 'Mind initialization failed - check permissions and try again',\n MIND_UPDATE_ERROR: 'Mind update operation failed - check logs for details',\n MIND_PACK_ERROR: 'Mind pack operation failed - check logs for details',\n MIND_GIT_ERROR: 'Git operation failed - check git repository status',\n MIND_INDEX_NOT_FOUND: 'Mind indexes not found - run \"kb mind init\" first',\n MIND_INVALID_PATH: 'Invalid file or directory path - check path exists and is accessible',\n MIND_DEPENDENCY_ERROR: 'Dependency resolution failed - check package configuration',\n MIND_BUILD_ERROR: 'Build operation failed - check configuration and try again',\n} as const;\n\nexport type ErrorCode = keyof typeof ERROR_HINTS;\n\n/**\n * Create a MindError with standardized code and hint\n */\nexport function createMindError(\n code: ErrorCode,\n message: string,\n meta?: unknown\n): MindError {\n return new MindError(code, message, ERROR_HINTS[code], meta);\n}\n\n/**\n * Create a MindError from a generic error\n */\nexport function wrapError(error: unknown, code: ErrorCode = 'MIND_FEED_ERROR'): MindError {\n if (error instanceof MindError) {\n return error;\n }\n \n const message = error instanceof Error ? error.message : String(error);\n return createMindError(code, message, { originalError: error });\n}\n\n/**\n * Check if an error is a MindError\n */\nexport function isMindError(error: unknown): error is MindError {\n return error instanceof MindError;\n}\n","/**\n * Token estimation utilities for KB Labs Mind\n */\n\nimport type { ITokenEstimator } from \"../types/pack\";\n\n/**\n * Default whitespace-aware token estimator\n * Algorithm: ~3.8-4.2 chars/token based on whitespace and code patterns\n */\nexport class DefaultTokenEstimator implements ITokenEstimator {\n private readonly charsPerToken: number = 4.0;\n private readonly codeBonus: number = 0.1; // 10% bonus for code-like content\n private readonly punctuationWeight: number = 0.8;\n\n estimate(text: string): number {\n if (!text || text.length === 0) {return 0;}\n\n // Count words, punctuation, and whitespace\n const words = text.match(/\\b\\w+\\b/g) || [];\n const punctuation = text.match(/[^\\w\\s]/g) || [];\n const whitespace = text.match(/\\s/g) || [];\n \n // Base estimation\n let tokens = words.length;\n \n // Add punctuation with weight\n tokens += punctuation.length * this.punctuationWeight;\n \n // Add whitespace (spaces, newlines, tabs)\n tokens += whitespace.length * 0.3;\n \n // Apply code bonus if content looks like code\n const codeIndicators = text.match(/[{}();=<>]/g) || [];\n if (codeIndicators.length > words.length * 0.1) {\n tokens *= (1 + this.codeBonus);\n }\n \n // Apply character-based adjustment\n const charBasedEstimate = text.length / this.charsPerToken;\n \n // Use the higher of word-based or char-based estimate\n return Math.ceil(Math.max(tokens, charBasedEstimate));\n }\n\n truncate(text: string, maxTokens: number, mode: \"start\"|\"middle\"|\"end\"): string {\n if (this.estimate(text) <= maxTokens) {\n return text;\n }\n\n const lines = text.split('\\n');\n const estimatedTokens = this.estimate(text);\n const ratio = maxTokens / estimatedTokens;\n const targetLines = Math.max(1, Math.floor(lines.length * ratio));\n \n if (targetLines >= lines.length) {return text;}\n\n switch (mode) {\n case 'start':\n return lines.slice(0, targetLines).join('\\n');\n case 'end':\n return lines.slice(-targetLines).join('\\n');\n case 'middle':\n default: {\n const startLines = Math.max(1, Math.floor(targetLines / 2));\n const endLines = Math.max(1, targetLines - startLines);\n const start = lines.slice(0, startLines);\n const end = lines.slice(-endLines);\n return [...start, '...', ...end].join('\\n');\n }\n }\n }\n}\n\n/**\n * Default token estimator instance\n */\nexport const defaultTokenEstimator = new DefaultTokenEstimator();\n\n/**\n * Estimate tokens using default strategy\n */\nexport function estimateTokens(text: string): number {\n return defaultTokenEstimator.estimate(text);\n}\n\n/**\n * Truncate text to token limit using default strategy\n */\nexport function truncateToTokens(\n text: string, \n maxTokens: number, \n mode: \"start\"|\"middle\"|\"end\" = \"middle\"\n): string {\n return defaultTokenEstimator.truncate(text, maxTokens, mode);\n}\n","/**\n * Hashing utilities for KB Labs Mind\n */\n\nimport { createHash } from 'node:crypto';\n\n/**\n * Compute SHA256 hash for string content\n */\nexport function sha256(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n\n/**\n * Compute SHA256 hash for Buffer content\n */\nexport function sha256Buffer(buffer: Buffer): string {\n return createHash('sha256').update(buffer).digest('hex');\n}\n\n/**\n * Compute SHA256 hash for file content (streaming for large files)\n */\nexport async function sha256File(filePath: string): Promise<string> {\n const { readFile } = await import('node:fs/promises');\n const content = await readFile(filePath);\n return sha256Buffer(content);\n}\n","/**\n * Path utilities for KB Labs Mind\n */\n\nimport path from 'node:path';\nimport { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\n\n/**\n * Convert path to POSIX format (forward slashes)\n */\nexport function toPosix(filePath: string): string {\n return filePath.replace(/\\\\/g, '/');\n}\n\n/**\n * Convert POSIX path back to platform-specific format\n */\nexport function fromPosix(posixPath: string): string {\n return posixPath.split('/').join(path.sep);\n}\n\n/**\n * Find workspace root by looking for git repository or monorepo indicators\n * Searches up the directory tree from cwd\n */\nexport async function findWorkspaceRoot(cwd: string): Promise<string> {\n let current = path.resolve(cwd);\n const root = path.parse(current).root;\n\n while (current !== root) {\n // Check for git repository\n if (existsSync(path.join(current, '.git'))) {\n return toPosix(current);\n }\n\n // Check for monorepo indicators\n const packageJsonPath = path.join(current, 'package.json');\n if (existsSync(packageJsonPath)) {\n try {\n const packageJsonContent = await readFile(packageJsonPath, 'utf8');\n const packageJson = JSON.parse(packageJsonContent);\n // Check for workspace configuration\n if (packageJson.workspaces || packageJson.pnpm?.workspace) {\n return toPosix(current);\n }\n } catch {\n // Ignore JSON parse errors\n }\n }\n\n // Check for pnpm-workspace.yaml\n if (existsSync(path.join(current, 'pnpm-workspace.yaml'))) {\n return toPosix(current);\n }\n\n // Move up one directory\n current = path.dirname(current);\n }\n\n // If no workspace found, return the original cwd as POSIX\n return toPosix(cwd);\n}\n\n/**\n * Make path relative to workspace root\n */\nexport function makeRelativeToRoot(absolutePath: string, root: string): string {\n const relative = path.relative(root, absolutePath);\n return toPosix(relative);\n}\n\n/**\n * Check if path should be ignored based on common patterns\n */\nexport function shouldIgnorePath(filePath: string): boolean {\n const posixPath = toPosix(filePath);\n \n const ignorePatterns = [\n 'node_modules/**',\n '.git/**',\n '.kb/**', // except .kb/mind/**\n 'dist/**',\n 'coverage/**',\n '.turbo/**',\n '.vite/**',\n '**/*.log',\n '**/*.tmp',\n '**/*.temp'\n ];\n \n // Simple file extension patterns\n const extensionPatterns = ['.log', '.tmp', '.temp'];\n\n // Special case: allow .kb/mind/** but ignore other .kb/**\n if (posixPath.startsWith('.kb/') && !posixPath.startsWith('.kb/mind/')) {\n return true;\n }\n \n // Allow .kb/mind/** paths\n if (posixPath.startsWith('.kb/mind/')) {\n return false;\n }\n \n // Check simple extension patterns first\n if (extensionPatterns.some(ext => posixPath.endsWith(ext))) {\n return true;\n }\n\n return ignorePatterns.some(pattern => {\n if (pattern.endsWith('/**')) {\n const prefix = pattern.slice(0, -3);\n return posixPath.startsWith(prefix + '/') || posixPath === prefix;\n }\n if (pattern.endsWith('**')) {\n const prefix = pattern.slice(0, -2);\n return posixPath.startsWith(prefix);\n }\n if (pattern.startsWith('**/')) {\n const suffix = pattern.slice(3);\n return posixPath.endsWith(suffix);\n }\n if (pattern.includes('*')) {\n // Simple glob pattern matching\n let regexPattern = pattern.replace(/\\*\\*/g, '.*').replace(/\\*/g, '[^/]*');\n // Handle **/*.ext patterns that should match files in any directory\n if (pattern.startsWith('**/')) {\n regexPattern = '.*' + regexPattern.slice(3);\n }\n const regex = new RegExp('^' + regexPattern + '$');\n return regex.test(posixPath);\n }\n return posixPath.includes(pattern);\n });\n}\n","/**\n * Mathematical utility functions for KB Labs Mind\n */\n\n/**\n * Calculate cosine similarity between two vectors\n *\n * Cosine similarity measures the cosine of the angle between two vectors,\n * producing a value between -1 and 1, where:\n * - 1 means vectors point in the same direction (identical)\n * - 0 means vectors are orthogonal (no similarity)\n * - -1 means vectors point in opposite directions\n *\n * @param a - First vector (array of numbers)\n * @param b - Second vector (array of numbers)\n * @returns Similarity score [0-1], or 0 if vectors have different lengths or zero magnitudes\n *\n * @example\n * ```typescript\n * const similarity = cosineSimilarity([1, 2, 3], [4, 5, 6]);\n * console.log(similarity); // ~0.974\n * ```\n */\nexport function cosineSimilarity(a: number[], b: number[]): number {\n // Vectors must have same dimensionality\n if (a.length !== b.length) {\n return 0;\n }\n\n let dotProduct = 0;\n let normA = 0;\n let normB = 0;\n\n // Calculate dot product and norms in single pass\n for (let i = 0; i < a.length; i++) {\n const av = a[i] ?? 0;\n const bv = b[i] ?? 0;\n dotProduct += av * bv;\n normA += av * av;\n normB += bv * bv;\n }\n\n // Handle zero magnitude vectors (division by zero)\n if (normA === 0 || normB === 0) {\n return 0;\n }\n\n // cosine(θ) = (a · b) / (||a|| * ||b||)\n return dotProduct / Math.sqrt(normA * normB);\n}\n\n/**\n * Calculate dot product of two vectors\n *\n * @param a - First vector\n * @param b - Second vector\n * @returns Dot product, or 0 if vectors have different lengths\n *\n * @example\n * ```typescript\n * const dot = dotProduct([1, 2, 3], [4, 5, 6]);\n * console.log(dot); // 32\n * ```\n */\nexport function dotProduct(a: number[], b: number[]): number {\n if (a.length !== b.length) {\n return 0;\n }\n\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result += (a[i] ?? 0) * (b[i] ?? 0);\n }\n return result;\n}\n\n/**\n * Calculate magnitude (L2 norm) of a vector\n *\n * @param vec - Input vector\n * @returns Magnitude (Euclidean length)\n *\n * @example\n * ```typescript\n * const mag = magnitude([3, 4]);\n * console.log(mag); // 5\n * ```\n */\nexport function magnitude(vec: number[]): number {\n let sum = 0;\n for (let i = 0; i < vec.length; i++) {\n const v = vec[i] ?? 0;\n sum += v * v;\n }\n return Math.sqrt(sum);\n}\n\n/**\n * Normalize a vector to unit length\n *\n * @param vec - Input vector\n * @returns Normalized vector (magnitude = 1), or original if magnitude is 0\n *\n * @example\n * ```typescript\n * const normalized = normalize([3, 4]);\n * console.log(normalized); // [0.6, 0.8]\n * ```\n */\nexport function normalize(vec: number[]): number[] {\n const mag = magnitude(vec);\n if (mag === 0) {\n return vec;\n }\n return vec.map(v => (v ?? 0) / mag);\n}\n","/**\n * Base class for file-based stores with rotation support\n *\n * Provides JSONL file rotation, segmentation by date, and automatic cleanup.\n * Used by history stores, feedback stores, and other persistent logging mechanisms.\n */\n\nimport path from 'node:path';\nimport type { IStorage } from '@kb-labs/sdk';\n\nexport interface FileRotationOptions {\n /**\n * Base directory path for storing files\n * @default '.kb/mind/store/'\n */\n basePath?: string;\n\n /**\n * Prefix for generated filenames\n * @default 'store-'\n */\n filePrefix?: string;\n\n /**\n * Maximum number of records per file before rotation\n * @default 1000\n */\n maxRecordsPerFile?: number;\n\n /**\n * Maximum number of files to keep (oldest deleted first)\n * @default 30\n */\n maxFiles?: number;\n}\n\n/**\n * Abstract base class for file-based stores with automatic rotation\n *\n * Features:\n * - JSONL format (one JSON object per line)\n * - Date-based file segmentation (YYYYMMDD-timestamp.jsonl)\n * - Automatic rotation when maxRecordsPerFile reached\n * - Automatic cleanup when maxFiles exceeded\n * - Sorted file iteration (oldest to newest)\n *\n * @example\n * ```typescript\n * class MyStore extends FileRotationStore<MyRecord> {\n * async save(record: MyRecord): Promise<void> {\n * return this.appendRecord(record);\n * }\n *\n * async find(criteria: any): Promise<MyRecord[]> {\n * return this.readRecords((rec) => rec.id === criteria.id);\n * }\n * }\n * ```\n */\nexport abstract class FileRotationStore<TRecord> {\n protected readonly basePath: string;\n protected readonly filePrefix: string;\n protected readonly maxRecordsPerFile: number;\n protected readonly maxFiles: number;\n\n constructor(\n protected readonly storage: IStorage,\n options: FileRotationOptions = {}\n ) {\n this.basePath = options.basePath ? this.ensureTrailingSlash(options.basePath) : '.kb/mind/store/';\n this.filePrefix = options.filePrefix ?? 'store-';\n this.maxRecordsPerFile = options.maxRecordsPerFile ?? 1000;\n this.maxFiles = options.maxFiles ?? 30;\n }\n\n /**\n * Append a record to the current writable file\n *\n * Automatically handles:\n * - File rotation when maxRecordsPerFile exceeded\n * - Cleanup when maxFiles exceeded\n * - JSONL formatting\n *\n * @param record - Record to append\n */\n protected async appendRecord(record: TRecord): Promise<void> {\n const target = await this.getWritableFile();\n const line = JSON.stringify({ v: 1, record }) + '\\n';\n\n const existing = await this.storage.read(target);\n const buffer = existing\n ? Buffer.concat([existing, Buffer.from(line, 'utf8')])\n : Buffer.from(line, 'utf8');\n\n await this.storage.write(target, buffer);\n await this.enforceRotation();\n }\n\n /**\n * Read records from all files, optionally filtering\n *\n * @param filter - Optional filter function\n * @param limit - Maximum number of records to return\n * @returns Array of records matching filter\n */\n protected async readRecords(\n filter?: (record: TRecord) => boolean,\n limit?: number\n ): Promise<TRecord[]> {\n const files = await this.getFilesSorted();\n const results: TRecord[] = [];\n\n for (const file of files) {\n if (limit && results.length >= limit) {break;}\n\n const buf = await this.storage.read(file);\n if (!buf) {continue;}\n\n const lines = buf.toString('utf8').split('\\n').filter(Boolean);\n for (const line of lines) {\n if (limit && results.length >= limit) {break;}\n\n try {\n const parsed = JSON.parse(line) as { v: number; record: TRecord };\n const rec = parsed.record;\n\n if (!filter || filter(rec)) {\n results.push(rec);\n }\n } catch {\n // Skip malformed lines\n continue;\n }\n }\n }\n\n return limit ? results.slice(0, limit) : results;\n }\n\n /**\n * Get the current writable file path\n *\n * Creates a new segment if:\n * - No files exist\n * - Latest file has >= maxRecordsPerFile records\n *\n * @returns Path to writable file\n */\n protected async getWritableFile(): Promise<string> {\n const files = await this.getFilesSorted();\n\n if (files.length === 0) {\n return this.segmentPath(Date.now());\n }\n\n const latest = files[files.length - 1]!;\n const buf = await this.storage.read(latest);\n\n if (!buf) {return latest;}\n\n const count = buf.toString('utf8').split('\\n').filter(Boolean).length;\n if (count >= this.maxRecordsPerFile) {\n return this.segmentPath(Date.now());\n }\n\n return latest;\n }\n\n /**\n * Get all store files sorted by timestamp (oldest to newest)\n *\n * @returns Sorted array of file paths\n */\n protected async getFilesSorted(): Promise<string[]> {\n const files = await this.storage.list(this.basePath);\n return files\n .filter((f) => f.startsWith(this.basePath + this.filePrefix) && f.endsWith('.jsonl'))\n .sort();\n }\n\n /**\n * Generate a segment file path from timestamp\n *\n * Format: {filePrefix}YYYYMMDD-{timestamp}.jsonl\n * Example: history-20251209-1733769000123.jsonl\n *\n * @param ts - Unix timestamp in milliseconds\n * @returns Full file path\n */\n protected segmentPath(ts: number): string {\n const date = new Date(ts);\n const day = String(date.getDate()).padStart(2, '0');\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const year = date.getFullYear();\n const filename = `${this.filePrefix}${year}${month}${day}-${ts}.jsonl`;\n return path.posix.join(this.basePath, filename);\n }\n\n /**\n * Enforce file rotation by deleting oldest files if maxFiles exceeded\n */\n protected async enforceRotation(): Promise<void> {\n const files = await this.getFilesSorted();\n if (files.length <= this.maxFiles) {return;}\n\n const excess = files.length - this.maxFiles;\n const toDelete = files.slice(0, excess);\n await Promise.all(toDelete.map((f: string) => this.storage.delete(f)));\n }\n\n /**\n * Ensure path ends with trailing slash\n */\n protected ensureTrailingSlash(p: string): string {\n return p.endsWith('/') ? p : `${p}/`;\n }\n}\n","/**\n * JSON file operations for KB Labs Mind\n */\n\nimport { promises as fsp } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { sha256 } from \"./hash\";\n\n/**\n * Recursively sort object keys for deterministic output\n */\nfunction sortKeysRecursively(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(sortKeysRecursively);\n }\n\n const sorted: Record<string, unknown> = {};\n const record = obj as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n\n for (const key of keys) {\n sorted[key] = sortKeysRecursively(record[key]);\n }\n\n return sorted;\n}\n\n/**\n * Read JSON file with error handling\n */\nexport async function readJson<T = unknown>(filePath: string): Promise<T | null> {\n try {\n const content = await fsp.readFile(filePath, 'utf8');\n return JSON.parse(content) as T;\n } catch (error: unknown) {\n if ((error as { code?: string }).code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n}\n\n/**\n * Write JSON file atomically with sorted keys\n */\nexport async function writeJson<T>(filePath: string, data: T): Promise<void> {\n const tmp = `${filePath}.tmp`;\n const sorted = sortKeysRecursively(data);\n const content = JSON.stringify(sorted, null, 2) + '\\n';\n\n // Ensure directory exists\n await fsp.mkdir(dirname(filePath), { recursive: true });\n\n // Write to temp file\n await fsp.writeFile(tmp, content, 'utf8');\n\n // Windows-safe atomic rename\n if (process.platform === \"win32\") {\n try {\n await fsp.unlink(filePath);\n } catch (err: unknown) {\n if ((err as { code?: string }).code !== \"ENOENT\") {throw err;}\n }\n }\n\n // Rename tmp to final location\n await fsp.rename(tmp, filePath);\n}\n\n/**\n * Compute hash of JSON content\n */\nexport function computeJsonHash(data: unknown): string {\n const content = JSON.stringify(sortKeysRecursively(data));\n return sha256(content);\n}\n","/**\n * @module @kb-labs/mind-core/verification\n * Mind index verification utilities\n *\n * Moved from mind-gateway to break circular dependency (TASK-004)\n */\n\nimport { readJson, computeJsonHash } from '../utils/json';\nimport { sha256 } from '../utils/hash';\nimport { promises as fsp } from 'node:fs';\n\nexport interface VerifyResult {\n ok: boolean;\n code: string | null;\n inconsistencies: string[];\n hint: string;\n}\n\n/**\n * Verify Mind index integrity\n *\n * Checks:\n * 1. Main index file exists (.kb/mind/index.json)\n * 2. Individual file hashes match (api-index, deps, recent-diff)\n * 3. Combined index checksum is valid\n * 4. Required files are present\n *\n * @param cwd - Workspace root directory\n * @returns Verification result with inconsistencies list\n *\n * @example\n * ```typescript\n * const result = await verifyIndexes('/path/to/workspace');\n * if (!result.ok) {\n * console.error('Inconsistencies:', result.inconsistencies);\n * console.log('Hint:', result.hint);\n * }\n * ```\n */\nexport async function verifyIndexes(cwd: string): Promise<VerifyResult> {\n const inconsistencies: string[] = [];\n\n try {\n // Load main index\n const index = await readJson<Record<string, unknown>>(`${cwd}/.kb/mind/index.json`);\n if (!index) {\n return {\n ok: false,\n code: 'MIND_NO_INDEX',\n inconsistencies: ['Main index file not found'],\n hint: 'Run \"kb mind rag-index\" to initialize indexes',\n };\n }\n\n // Load all index files\n const [apiIndex, depsGraph, recentDiff, meta, docs] = await Promise.all([\n readJson(`${cwd}/.kb/mind/api-index.json`),\n readJson(`${cwd}/.kb/mind/deps.json`),\n readJson(`${cwd}/.kb/mind/recent-diff.json`),\n readJson(`${cwd}/.kb/mind/meta.json`),\n readJson(`${cwd}/.kb/mind/docs.json`),\n ]);\n\n // Verify individual file hashes\n if (apiIndex) {\n const computedHash = computeJsonHash(apiIndex);\n if (computedHash !== index.apiIndexHash) {\n inconsistencies.push(\n `API index hash mismatch: expected ${index.apiIndexHash}, got ${computedHash}`\n );\n }\n } else if (index.apiIndexHash) {\n inconsistencies.push('API index file missing but hash is present');\n }\n\n if (depsGraph) {\n const computedHash = computeJsonHash(depsGraph);\n if (computedHash !== index.depsHash) {\n inconsistencies.push(\n `Dependencies hash mismatch: expected ${index.depsHash}, got ${computedHash}`\n );\n }\n } else if (index.depsHash) {\n inconsistencies.push('Dependencies file missing but hash is present');\n }\n\n if (recentDiff) {\n const computedHash = computeJsonHash(recentDiff);\n if (computedHash !== index.recentDiffHash) {\n inconsistencies.push(\n `Recent diff hash mismatch: expected ${index.recentDiffHash}, got ${computedHash}`\n );\n }\n } else if (index.recentDiffHash) {\n inconsistencies.push('Recent diff file missing but hash is present');\n }\n\n // Verify combined index checksum\n const combinedContent = JSON.stringify({\n apiIndex: apiIndex || {},\n deps: depsGraph || {},\n recentDiff: recentDiff || {},\n meta: meta || {},\n docs: docs || {},\n });\n const computedChecksum = sha256(combinedContent);\n\n if (computedChecksum !== index.indexChecksum) {\n inconsistencies.push(\n `Index checksum mismatch: expected ${index.indexChecksum}, got ${computedChecksum}`\n );\n }\n\n // Check for missing files that should exist\n const expectedFiles = ['api-index.json', 'deps.json', 'recent-diff.json'];\n for (const file of expectedFiles) {\n try {\n await fsp.access(`${cwd}/.kb/mind/${file}`);\n } catch {\n inconsistencies.push(`Required index file missing: ${file}`);\n }\n }\n\n const ok = inconsistencies.length === 0;\n const code = ok ? null : 'MIND_INDEX_INCONSISTENT';\n const hint = ok\n ? 'All indexes are consistent and up to date'\n : 'Run \"kb mind rag-index\" to rebuild indexes';\n\n return { ok, code, inconsistencies, hint };\n } catch (error: unknown) {\n return {\n ok: false,\n code: 'MIND_VERIFY_ERROR',\n inconsistencies: [`Verification failed: ${error instanceof Error ? error.message : String(error)}`],\n hint: 'Check file permissions and workspace structure',\n };\n }\n}\n","/**\n * Default configurations for KB Labs Mind\n */\n\nimport type { ContextBudget, ContextPreset } from \"./types/pack\";\n\n/**\n * Default context budget\n */\nexport const DEFAULT_BUDGET: ContextBudget = {\n totalTokens: 9000,\n caps: {\n intent_summary: 300,\n product_overview: 600,\n project_meta: 500,\n api_signatures: 2200,\n recent_diffs: 1200,\n docs_overview: 600,\n impl_snippets: 3000,\n configs_profiles: 700,\n },\n truncation: \"middle\",\n};\n\n/**\n * Default context preset\n */\nexport const DEFAULT_PRESET: ContextPreset = {\n name: \"balanced\",\n weight: { \n overview: 1, \n api: 1.2, \n diffs: 1, \n snippets: 1.4, \n configs: 0.6,\n meta: 0.8,\n docs: 0.9\n }\n};\n\n/**\n * Default time budget for indexing operations (ms)\n */\nexport const DEFAULT_TIME_BUDGET_MS = 800;\n\n/**\n * Maximum file size to process (bytes)\n */\nexport const MAX_FILE_SIZE_BYTES = 1.5 * 1024 * 1024; // 1.5MB\n\n/**\n * Maximum lines per snippet\n */\nexport const MAX_SNIPPET_LINES = 60;\n\n/**\n * Generator string for artifacts\n */\nexport function getGenerator(): string {\n return \"kb-labs-mind@0.1.0\";\n}\n"]}
1
+ {"version":3,"sources":["../src/types.ts","../src/ingest/discover.ts","../src/ingest/chunk.ts","../src/ingest/structural.ts","../src/ingest/embed.ts","../src/index-store.ts","../src/ingest/ingest.ts","../src/sync.ts","../src/retrieval/bm25.ts","../src/retrieval/vector.ts","../src/retrieval/fuse.ts","../src/retrieval/hyde.ts","../src/retrieval/expand.ts","../src/retrieval/retrieve.ts","../src/retrieval/rerank.ts","../src/retrieval/dedup.ts","../src/answer/verify.ts","../src/answer/field-check.ts","../src/answer/decompose.ts","../src/answer/synthesize.ts","../src/answer/answer.ts","../src/answer/explore.ts","../src/feedback/history.ts","../src/mind.ts","../src/pipeline.ts"],"names":["path","approxTokens","readFile","join","MAX_SNIPPET_CHARS","staleCount"],"mappings":";;;;;;;;;AAiDO,SAAS,OAAA,CAAQA,KAAAA,EAAc,SAAA,EAAmB,OAAA,EAAyB;AAChF,EAAA,OAAO,CAAA,EAAGA,KAAI,CAAA,CAAA,EAAI,SAAS,IAAI,OAAO,CAAA,CAAA;AACxC;AAGO,SAAS,YAAY,IAAA,EAAsB;AAChD,EAAA,IAAI,CAAA,GAAI,UAAA;AACR,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,IAAA,CAAK,QAAQ,CAAA,EAAA,EAAK;AACpC,IAAA,CAAA,IAAK,IAAA,CAAK,WAAW,CAAC,CAAA;AACtB,IAAA,CAAA,GAAI,IAAA,CAAK,IAAA,CAAK,CAAA,EAAG,QAAU,CAAA;AAAA,EAC7B;AACA,EAAA,OAAA,CAAQ,CAAA,KAAM,CAAA,EAAG,QAAA,CAAS,EAAE,CAAA;AAC9B;AAGO,SAAS,aAAaA,KAAAA,EAA+B;AAC1D,EAAA,MAAM,KAAA,GAAQA,MAAK,WAAA,EAAY;AAC/B,EAAA,IAAI,MAAM,QAAA,C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,SAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EALF,SAAuB,EAAC;AAAA,EAQzC,MAAM,GAAA,CAAU,KAAA,EAAe,KAAA,EAAU,UAAwB,EAAA,EAA6B;AAC5F,IAAA,MAAM,KAAA,GAAQ,KAAK,KAAA,EAAM;AACzB,IAAA,MAAM,MAAA,GAAS,MAAM,EAAA,CAAG,KAAA,EAAO,QAAQ,CAAA;AACvC,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK;AAAA,MACf,KAAA;AAAA,MACA,UAAA,EAAY,IAAA,CAAK,KAAA,EAAM,GAAI,KAAA;AAAA,MAC3B,aAAa,KAAA,CAAM,OAAA,CAAQ,MAAM,CAAA,GAAI,OAAO,MAAA,GAAS;AAAA,KACtD,CAAA;AACD,IAAA,OAAO,MAAA;AAAA,EACT;AAAA;AAAA,EAGA,OAAO,KAAA,EAAyB;AAC9B,IAAA,IAAA,CAAK,MAAA,CAAO,KAAK,KAAK,CAAA;AAAA,EACxB;AAAA,EAEA,MAAM,OAAA,EAAwB;AAC5B,IAAA,OAAO;AAAA,MACL,WAAW,IAAA,CAAK,SAAA;AAAA,MAChB,MAAM,IAAA,CAAK,IAAA;AAAA,MACX,OAAA;AAAA,MACA,MAAA,EAAQ,CAAC,GAAG,IAAA,CAAK,MAAM;AAAA,KACzB;AAAA,EACF;AACF","file":"index.js","sourcesContent":["/**\n * Internal engine types (not wire contracts).\n *\n * A `Chunk` is the unit of indexing/retrieval. Chunks are stored two ways:\n * - in the vector store (one `VectorRecord` per chunk, scoped by namespace=indexId)\n * for semantic search;\n * - in a per-index `chunks.json` via `IStorage` as the corpus for BM25 and\n * listing/status.\n */\n\nimport type { AgentSourceKind } from '@kb-labs/mind-contracts';\n\nexport interface Chunk {\n /** Stable id: `${path}#${startLine}-${endLine}`. */\n id: string;\n path: string;\n startLine: number;\n endLine: number;\n text: string;\n kind: AgentSourceKind;\n}\n\n/** Metadata stored alongside each vector record. */\nexport interface ChunkMeta extends Record<string, unknown> {\n path: string;\n startLine: number;\n endLine: number;\n text: string;\n kind: AgentSourceKind;\n}\n\n/** Per-file bookkeeping. `hash` enables incremental (delta) re-indexing. */\nexport interface FileEntry {\n chunks: number;\n indexedAt: string;\n /** Content hash; unchanged hash ⇒ file skipped on re-index. */\n hash: string;\n}\n\n/** Persisted per-index corpus (source of truth for BM25 + listing). */\nexport interface IndexManifest {\n indexId: string;\n /** Chunks keyed by id. */\n chunks: Chunk[];\n /** Per-path bookkeeping for incremental sync. */\n files: Record<string, FileEntry>;\n updatedAt: string | null;\n}\n\nexport function chunkId(path: string, startLine: number, endLine: number): string {\n return `${path}#${startLine}-${endLine}`;\n}\n\n/** Stable content hash for delta detection (FNV-1a, dependency-free). */\nexport function hashContent(text: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < text.length; i++) {\n h ^= text.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16);\n}\n\n/** Derive a source kind from a file path. */\nexport function kindFromPath(path: string): AgentSourceKind {\n const lower = path.toLowerCase();\n if (lower.includes('/adr/') || /adr-\\d+/.test(lower)) {\n return 'adr';\n }\n if (lower.endsWith('.md') || lower.endsWith('.mdx') || lower.endsWith('.txt')) {\n return 'doc';\n }\n if (\n lower.endsWith('.json') ||\n lower.endsWith('.yaml') ||\n lower.endsWith('.yml') ||\n lower.endsWith('.toml')\n ) {\n return 'config';\n }\n return 'code';\n}\n","/**\n * Adaptive source-file discovery via `globby` over the real filesystem.\n *\n * Reads the repo relative to `cwd` — NOT the platform `storage` adapter, which\n * is a blob store that recurses into node_modules and chokes on pnpm symlink\n * chains. Symlinks are not followed and dependency/build dirs are excluded.\n *\n * No language allowlist: we glob every file and KEEP whatever looks like source\n * text, excluding only binaries, media, archives, data blobs, lockfiles and\n * oversized/generated files. A new language (`.cs`, `.vue`, `.kt`, …) is indexed\n * automatically — discovery adapts to the repo instead of being hand-curated.\n *\n * Returns paths relative to `cwd`.\n */\n\nimport globby from 'globby';\nimport { statSync, openSync, readSync, closeSync } from 'node:fs';\nimport path from 'node:path';\n\nconst IGNORE = [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/out/**',\n '**/coverage/**',\n '**/.git/**',\n '**/.kb/**',\n '**/bin/**',\n '**/obj/**',\n '**/.next/**',\n '**/.nuxt/**',\n '**/vendor/**',\n '**/__pycache__/**',\n];\n\n/**\n * Non-source extensions — binary, media, archives, data blobs, sourcemaps,\n * minified bundles. Everything NOT here is treated as source if it is text.\n */\nconst DENY_EXT = new Set([\n 'png', 'jpg', 'jpeg', 'gif', 'svg', 'ico', 'webp', 'bmp', 'tif', 'tiff', 'avif',\n 'mp4', 'mov', 'avi', 'webm', 'mp3', 'wav', 'ogg', 'flac', 'pdf',\n 'woff', 'woff2', 'ttf', 'eot', 'otf',\n 'zip', 'gz', 'tgz', 'bz2', 'xz', 'tar', 'rar', '7z',\n 'exe', 'dll', 'so', 'dylib', 'bin', 'wasm', 'class', 'node', 'pdb',\n 'xlsx', 'xls', 'docx', 'doc', 'pptx', 'ppt', 'parquet', 'db', 'sqlite',\n 'map', 'min.js', 'min.css', 'snap',\n // Bulk data / logs / dumps — text, but no semantic value and they bloat the\n // index + embedding cost (the old extension allowlist excluded these by omission).\n 'csv', 'tsv', 'ndjson', 'jsonl', 'log', 'sql', 'dump', 'out',\n]);\n\n/** Generated/lock files that are text but carry no semantic signal. */\nconst DENY_FILE = new Set([\n 'package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'go.sum', 'Cargo.lock', 'composer.lock',\n]);\n\n/** Skip empty and oversized (usually generated/minified) files. */\nconst MAX_BYTES = 512 * 1024;\n\nfunction extOf(file: string): string {\n const name = file.slice(file.lastIndexOf('/') + 1).toLowerCase();\n if (name.endsWith('.min.js')) {\n return 'min.js';\n }\n if (name.endsWith('.min.css')) {\n return 'min.css';\n }\n const dot = name.lastIndexOf('.');\n return dot === -1 ? '' : name.slice(dot + 1);\n}\n\n/** Cheap binary sniff: a NUL byte in the first 4 KB ⇒ treat as binary. */\nfunction isBinary(abs: string): boolean {\n let fd: number | undefined;\n try {\n fd = openSync(abs, 'r');\n const buf = Buffer.alloc(4096);\n const n = readSync(fd, buf, 0, buf.length, 0);\n for (let i = 0; i < n; i++) {\n if (buf[i] === 0) {\n return true;\n }\n }\n return false;\n } catch {\n return true; // unreadable ⇒ skip\n } finally {\n if (fd !== undefined) {\n closeSync(fd);\n }\n }\n}\n\n/** Strip trailing slashes without a backtracking regex (avoids polynomial ReDoS). */\nfunction trimTrailingSlashes(s: string): string {\n let end = s.length;\n while (end > 0 && s.charCodeAt(end - 1) === 47 /* '/' */) {\n end--;\n }\n return s.slice(0, end);\n}\n\n/** Scope the engine discovers against — config-driven include/exclude globs. */\nexport interface DiscoverScope {\n /** Repo-relative roots/globs to index. Empty/undefined ⇒ whole repo. */\n include?: string[];\n /** Globs subtracted from the include set (added to the ignore list). */\n exclude?: string[];\n}\n\nexport async function discover(cwd: string, scope?: DiscoverScope): Promise<string[]> {\n const include = scope?.include && scope.include.length > 0 ? scope.include : ['.'];\n const exclude = scope?.exclude ?? [];\n\n // Each include root → a recursive glob ('.' ⇒ whole repo). exclude globs\n // join the ignore list, so they're subtracted from whatever include matched.\n const patterns = include.map((p) => {\n const base = p && p !== '.' ? trimTrailingSlashes(p) : '';\n return base ? `${base}/**/*` : '**/*';\n });\n\n const candidates = await globby(patterns, {\n cwd,\n ignore: [...IGNORE, ...exclude],\n dot: false,\n followSymbolicLinks: false,\n gitignore: false,\n onlyFiles: true,\n });\n\n return candidates.filter((rel) => {\n if (DENY_FILE.has(rel.slice(rel.lastIndexOf('/') + 1))) {\n return false;\n }\n if (DENY_EXT.has(extOf(rel))) {\n return false;\n }\n const abs = path.join(cwd, rel);\n try {\n const st = statSync(abs);\n if (st.size === 0 || st.size > MAX_BYTES) {\n return false;\n }\n } catch {\n return false;\n }\n return !isBinary(abs);\n });\n}\n","/**\n * Sliding-window chunker (Phase 2 baseline; AST chunking is layered in Phase 3).\n *\n * Splits a file into line-aligned chunks of roughly `maxTokens` tokens with\n * `overlapTokens` of overlap. Token count is approximated by whitespace words —\n * good enough for windowing; real tokenization is not needed here.\n */\n\nimport type { Chunk } from '../types';\nimport { chunkId, kindFromPath } from '../types';\n\nexport interface ChunkOptions {\n maxTokens: number;\n overlapTokens: number;\n}\n\nfunction approxTokens(line: string): number {\n const t = line.trim();\n if (t === '') {\n return 0;\n }\n return t.split(/\\s+/).length;\n}\n\nexport function slidingWindowChunks(path: string, content: string, opts: ChunkOptions): Chunk[] {\n const lines = content.split('\\n');\n const kind = kindFromPath(path);\n const chunks: Chunk[] = [];\n\n const maxTokens = Math.max(1, opts.maxTokens);\n const overlapTokens = Math.max(0, Math.min(opts.overlapTokens, maxTokens - 1));\n\n let startIdx = 0;\n while (startIdx < lines.length) {\n let tokens = 0;\n let endIdx = startIdx;\n while (endIdx < lines.length && tokens < maxTokens) {\n tokens += approxTokens(lines[endIdx] ?? '');\n endIdx++;\n }\n\n const startLine = startIdx + 1; // 1-based, inclusive\n const endLine = endIdx; // 1-based, inclusive\n const text = lines.slice(startIdx, endIdx).join('\\n');\n\n if (text.trim() !== '') {\n chunks.push({ id: chunkId(path, startLine, endLine), path, startLine, endLine, text, kind });\n }\n\n if (endIdx >= lines.length) {\n break;\n }\n\n // Step back by roughly `overlapTokens` worth of lines for overlap.\n let overlap = 0;\n let stepBack = 0;\n let i = endIdx - 1;\n while (i > startIdx && overlap < overlapTokens) {\n overlap += approxTokens(lines[i] ?? '');\n stepBack++;\n i--;\n }\n startIdx = Math.max(startIdx + 1, endIdx - stepBack);\n }\n\n return chunks;\n}\n","/**\n * Structure-aware chunking for code (AST-lite).\n *\n * Splits a source file at top-level declaration boundaries (functions, classes,\n * interfaces, etc.) so chunks align with logical units instead of arbitrary\n * windows. Oversized blocks fall back to the sliding window. This is a\n * dependency-free approximation of AST chunking; a tree-sitter backend can\n * replace it later behind the same `chunkFile` entry without touching callers.\n */\n\nimport type { Chunk } from '../types';\nimport { chunkId, kindFromPath } from '../types';\nimport { slidingWindowChunks, type ChunkOptions } from './chunk';\n\n// Declaration keywords and leading modifiers. We detect boundaries by scanning\n// the line's leading words (linear) rather than a multi-optional-group regex —\n// the latter is a polynomial-ReDoS shape on attacker-controlled file content.\nconst DECL_KEYWORDS = new Set([\n 'function', 'class', 'interface', 'type', 'enum', 'const', 'let', 'var',\n 'namespace', 'module', 'def', 'func', 'fn', 'impl', 'struct', 'trait',\n 'public', 'private',\n]);\nconst MODIFIERS = new Set([\n 'export', 'default', 'declare', 'public', 'private', 'protected',\n 'static', 'abstract', 'async',\n]);\n\n/** A top-level (unindented) line whose leading modifiers lead to a declaration. */\nfunction isBoundaryLine(line: string): boolean {\n if (line.length === 0 || line.charCodeAt(0) === 32 || line.charCodeAt(0) === 9) {\n return false; // indented → not top-level\n }\n for (const word of line.split(/\\s+/)) {\n if (DECL_KEYWORDS.has(word)) {\n return true;\n }\n if (!MODIFIERS.has(word)) {\n return false; // first non-modifier, non-keyword word → not a declaration\n }\n }\n return false;\n}\n\nfunction approxTokens(text: string): number {\n const t = text.trim();\n return t === '' ? 0 : t.split(/\\s+/).length;\n}\n\nexport function structuralChunks(path: string, content: string, opts: ChunkOptions): Chunk[] {\n const lines = content.split('\\n');\n const kind = kindFromPath(path);\n\n // Find top-level boundary line indices (indentation 0, declaration-like).\n const boundaries: number[] = [];\n lines.forEach((line, i) => {\n if (isBoundaryLine(line)) {\n boundaries.push(i);\n }\n });\n\n if (boundaries.length === 0) {\n return slidingWindowChunks(path, content, opts);\n }\n\n // Block start indices: file start + each boundary (deduped, sorted).\n const starts = [...new Set([0, ...boundaries])].sort((a, b) => a - b);\n const chunks: Chunk[] = [];\n\n for (let b = 0; b < starts.length; b++) {\n const from = starts[b]!;\n const to = b + 1 < starts.length ? starts[b + 1]! : lines.length; // exclusive\n const blockLines = lines.slice(from, to);\n const blockText = blockLines.join('\\n');\n if (blockText.trim() === '') {\n continue;\n }\n\n if (approxTokens(blockText) > opts.maxTokens) {\n // Oversized declaration: window it, offsetting line numbers to the block.\n for (const sub of slidingWindowChunks(path, blockText, opts)) {\n const startLine = from + sub.startLine; // sub is 1-based within block\n const endLine = from + sub.endLine;\n chunks.push({ id: chunkId(path, startLine, endLine), path, startLine, endLine, text: sub.text, kind });\n }\n } else {\n const startLine = from + 1;\n const endLine = to;\n chunks.push({ id: chunkId(path, startLine, endLine), path, startLine, endLine, text: blockText, kind });\n }\n }\n\n return chunks;\n}\n\n/** Dispatch: structure-aware for code when enabled, else sliding window. */\nexport function chunkFile(path: string, content: string, opts: ChunkOptions, ast: boolean): Chunk[] {\n if (ast && kindFromPath(path) === 'code') {\n return structuralChunks(path, content, opts);\n }\n return slidingWindowChunks(path, content, opts);\n}\n","/**\n * Embed chunks into vector records via the platform embeddings adapter.\n */\n\nimport type { Chunk, ChunkMeta } from '../types';\nimport type { IEmbeddings, VectorRecord } from '../services';\n\n/** Max chunks per embedding request. */\nconst MAX_BATCH_CHUNKS = 96;\n/** Max approx tokens per request — kept well under provider limits (e.g. OpenAI 300k). */\nconst MAX_BATCH_TOKENS = 200_000;\n/**\n * Hard char cap on a single input. Providers cap inputs at ~8192 tokens; dense\n * markdown/code runs ~2–3 chars/token, so 12k chars stays safely under that.\n * Only pathological chunks (e.g. a doc with one enormous line the chunker\n * couldn't split) hit this; the full text is still kept in metadata.\n */\nconst MAX_INPUT_CHARS = 12_000;\n/** Rough chars→tokens estimate for batch budgeting (avoids a tokenizer dep). */\nconst CHARS_PER_TOKEN = 4;\n\nconst approxTokens = (text: string): number => Math.ceil(text.length / CHARS_PER_TOKEN);\n\nfunction toRecord(chunk: Chunk, vector: number[], text: string): VectorRecord {\n const meta: ChunkMeta = {\n path: chunk.path,\n startLine: chunk.startLine,\n endLine: chunk.endLine,\n text,\n kind: chunk.kind,\n };\n return { id: chunk.id, vector, metadata: meta };\n}\n\n/**\n * Split chunks into request batches bounded by BOTH a chunk count and an approx\n * token budget, so a batch never exceeds the provider's per-request token limit\n * (which count-only batching blows on large files). Oversized single inputs are\n * truncated to the per-input cap.\n */\nfunction planBatches(chunks: Chunk[]): { chunk: Chunk; text: string }[][] {\n const items = chunks.map((c) => ({\n chunk: c,\n text: c.text.length > MAX_INPUT_CHARS ? c.text.slice(0, MAX_INPUT_CHARS) : c.text,\n }));\n const batches: { chunk: Chunk; text: string }[][] = [];\n let cur: { chunk: Chunk; text: string }[] = [];\n let curTokens = 0;\n for (const item of items) {\n const t = approxTokens(item.text);\n if (cur.length > 0 && (cur.length >= MAX_BATCH_CHUNKS || curTokens + t > MAX_BATCH_TOKENS)) {\n batches.push(cur);\n cur = [];\n curTokens = 0;\n }\n cur.push(item);\n curTokens += t;\n }\n if (cur.length > 0) {\n batches.push(cur);\n }\n return batches;\n}\n\n/**\n * Embed chunks into vector records. Batched by count + token budget so the\n * embedding stage reports progress and never sends an oversized request.\n */\nexport async function embedChunks(\n chunks: Chunk[],\n embeddings: IEmbeddings,\n onProgress?: (done: number, total: number) => void,\n): Promise<VectorRecord[]> {\n if (chunks.length === 0) {\n return [];\n }\n\n const records: VectorRecord[] = [];\n for (const batch of planBatches(chunks)) {\n const vectors = await embeddings.embedBatch(batch.map((b) => b.text));\n // Store the original chunk text in metadata, even if the embedded text was truncated.\n batch.forEach((b, j) => records.push(toRecord(b.chunk, vectors[j] ?? [], b.chunk.text)));\n onProgress?.(records.length, chunks.length);\n }\n return records;\n}\n","/**\n * Per-index manifest persistence via `IStorage`.\n *\n * The manifest is the source of truth for the BM25 corpus and for\n * listing/status. Vectors live in the vector store; the manifest holds chunk\n * text + per-file bookkeeping. One manifest per index id.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { IStorage } from './services';\nimport { hashContent, type IndexManifest } from './types';\n\nfunction manifestPath(indexId: string): string {\n return `mind/${indexId}/manifest.json`;\n}\n\n/**\n * Whether `file`'s on-disk content has drifted from what the manifest indexed\n * (the agent should re-read the live file). Files not in the index are treated\n * as not-stale (unknown, not misleading); unreadable/removed files are stale.\n * Bounded cost — call only for the results actually returned, not the corpus.\n */\nexport async function isStale(manifest: IndexManifest, file: string, cwd: string): Promise<boolean> {\n const entry = manifest.files[file];\n if (!entry) {\n return false;\n }\n try {\n const content = await readFile(join(cwd, file), 'utf8');\n return hashContent(content) !== entry.hash;\n } catch {\n return true; // gone from disk or unreadable\n }\n}\n\n/** Stale flag for many files at once (deduped) → `Map<file, stale>`. */\nexport async function staleMap(manifest: IndexManifest, files: string[], cwd: string): Promise<Map<string, boolean>> {\n const out = new Map<string, boolean>();\n await Promise.all(\n [...new Set(files)].map(async (f) => {\n out.set(f, await isStale(manifest, f, cwd));\n }),\n );\n return out;\n}\n\n/** Count of indexed files whose on-disk content changed — whole-index freshness (status). */\nexport async function staleCount(manifest: IndexManifest, cwd: string): Promise<number> {\n const flags = await staleMap(manifest, Object.keys(manifest.files), cwd);\n return [...flags.values()].filter(Boolean).length;\n}\n\n/**\n * Whether an index has a persisted manifest. Distinguishes \"absent\" (typo'd /\n * already-dropped id) from \"empty\", so a destructive `drop` does not report\n * success for a no-op on the wrong index.\n */\nexport async function manifestExists(storage: IStorage, indexId: string): Promise<boolean> {\n return Boolean(await storage.read(manifestPath(indexId)));\n}\n\nexport async function loadManifest(storage: IStorage, indexId: string): Promise<IndexManifest> {\n const buf = await storage.read(manifestPath(indexId));\n if (!buf) {\n return { indexId, chunks: [], files: {}, updatedAt: null };\n }\n try {\n const parsed = JSON.parse(buf.toString('utf8')) as IndexManifest;\n return { indexId, chunks: parsed.chunks ?? [], files: parsed.files ?? {}, updatedAt: parsed.updatedAt ?? null };\n } catch {\n return { indexId, chunks: [], files: {}, updatedAt: null };\n }\n}\n\nexport async function saveManifest(storage: IStorage, manifest: IndexManifest): Promise<void> {\n const buf = Buffer.from(JSON.stringify(manifest), 'utf8');\n await storage.write(manifestPath(manifest.indexId), buf);\n}\n\n/** Remove an index's manifest (used when dropping the whole index). */\nexport async function deleteManifest(storage: IStorage, indexId: string): Promise<void> {\n await storage.delete(manifestPath(indexId));\n}\n","/**\n * Ingest pipeline: discover -> (hash-delta) -> chunk -> embed ->\n * upsert(namespace=indexId), then persist the per-index manifest.\n *\n * Incremental by default: only files whose content hash changed since the last\n * index are re-chunked/re-embedded; unchanged files keep their existing chunks\n * (and vectors), removed files are pruned. `full` forces a clean rebuild.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { MindServices } from '../services';\nimport type { Chunk, FileEntry, IndexManifest } from '../types';\nimport { hashContent } from '../types';\nimport { discover, type DiscoverScope } from './discover';\nimport { type ChunkOptions } from './chunk';\nimport { chunkFile } from './structural';\nimport { embedChunks } from './embed';\nimport { loadManifest, saveManifest } from '../index-store';\n\n/** Staged progress events emitted during ingest (for CLI/REST progress UIs). */\nexport type IngestProgress =\n | { stage: 'discover'; files: number }\n | { stage: 'delta'; toIndex: number; unchanged: number; removed: number }\n | { stage: 'chunk'; chunks: number }\n | { stage: 'embed'; done: number; total: number }\n | { stage: 'upsert'; count: number }\n | { stage: 'save' };\n\nexport interface IngestInput {\n indexId: string;\n /** Workspace root that source paths are resolved against. */\n cwd: string;\n /** Config-driven include/exclude globs for discovery. */\n scope?: DiscoverScope;\n chunk: ChunkOptions;\n /** Use structure-aware chunking for code. */\n ast: boolean;\n /** Force a full rebuild instead of incremental delta. */\n full?: boolean;\n /** ISO timestamp for manifest bookkeeping (injectable for determinism). */\n now: string;\n /** Optional staged-progress sink (best-effort; never affects results). */\n onProgress?: (event: IngestProgress) => void;\n}\n\nexport interface IngestResult {\n filesIndexed: number;\n chunks: number;\n /** Files (re)embedded this run (new + changed). */\n added: number;\n updated: number;\n /** Files removed from the index (gone from disk). */\n removed: number;\n /** Files skipped because their content hash was unchanged. */\n unchanged: number;\n}\n\n/** Read + content-hash every discovered file. Unreadable files are skipped (warned). */\nasync function readAndHash(\n cwd: string,\n paths: string[],\n logger?: MindServices['logger'],\n): Promise<{ contentByPath: Map<string, string>; hashByPath: Map<string, string> }> {\n const contentByPath = new Map<string, string>();\n const hashByPath = new Map<string, string>();\n for (const path of paths) {\n let content: string;\n try {\n // Source comes from the real filesystem; storage is only for the manifest.\n content = await readFile(join(cwd, path), 'utf8');\n } catch (err) {\n logger?.warn('mind: skipped unreadable file', { path, reason: err instanceof Error ? err.message : String(err) });\n continue;\n }\n contentByPath.set(path, content);\n hashByPath.set(path, hashContent(content));\n }\n return { contentByPath, hashByPath };\n}\n\ninterface Delta {\n /** New + changed files — need re-chunk + re-embed. */\n toIndex: string[];\n /** Files whose content hash matched the previous index. */\n unchanged: string[];\n /** Files in the previous index that are gone from disk. */\n removedPaths: string[];\n added: number;\n updated: number;\n}\n\n/** Classify discovered files against the previous index by content hash. */\nfunction classify(\n contentByPath: Map<string, string>,\n hashByPath: Map<string, string>,\n prevFiles: Record<string, FileEntry>,\n): Delta {\n const toIndex: string[] = [];\n const unchanged: string[] = [];\n let added = 0;\n let updated = 0;\n for (const path of contentByPath.keys()) {\n const prevEntry = prevFiles[path];\n if (prevEntry && prevEntry.hash === hashByPath.get(path)) {\n unchanged.push(path);\n } else {\n toIndex.push(path);\n if (prevEntry) {\n updated++;\n } else {\n added++;\n }\n }\n }\n const removedPaths = Object.keys(prevFiles).filter((p) => !contentByPath.has(p));\n return { toIndex, unchanged, removedPaths, added, updated };\n}\n\nexport async function ingest(input: IngestInput, services: MindServices): Promise<IngestResult> {\n const { storage, embeddings, vectorStore } = services;\n const prev = await loadManifest(storage, input.indexId);\n const prevFiles: Record<string, FileEntry> = input.full ? {} : prev.files;\n\n const emit = input.onProgress ?? (() => {});\n\n const paths = await discover(input.cwd, input.scope);\n emit({ stage: 'discover', files: paths.length });\n const { contentByPath, hashByPath } = await readAndHash(input.cwd, paths, services.logger);\n const { toIndex, unchanged, removedPaths, added, updated } = classify(contentByPath, hashByPath, prevFiles);\n emit({ stage: 'delta', toIndex: toIndex.length, unchanged: unchanged.length, removed: removedPaths.length });\n\n // Vectors to drop: on full, everything previously indexed; otherwise only the\n // chunks of changed + removed files.\n const stalePaths = new Set(input.full ? Object.keys(prev.files) : [...toIndex, ...removedPaths]);\n const staleIds = (input.full ? prev.chunks : prev.chunks.filter((c) => stalePaths.has(c.path))).map((c) => c.id);\n if (staleIds.length > 0) {\n await vectorStore.delete(staleIds, input.indexId);\n }\n\n // Keep unchanged files' chunks + bookkeeping as-is.\n const unchangedSet = new Set(unchanged);\n const keptChunks = input.full ? [] : prev.chunks.filter((c) => unchangedSet.has(c.path));\n const files: Record<string, FileEntry> = {};\n for (const path of unchanged) {\n files[path] = prevFiles[path]!;\n }\n\n // Chunk + embed only the new/changed files.\n const newChunks: Chunk[] = [];\n for (const path of toIndex) {\n const chunks = chunkFile(path, contentByPath.get(path)!, input.chunk, input.ast);\n if (chunks.length === 0) {\n continue;\n }\n newChunks.push(...chunks);\n files[path] = { chunks: chunks.length, indexedAt: input.now, hash: hashByPath.get(path)! };\n }\n emit({ stage: 'chunk', chunks: newChunks.length });\n\n const records = await embedChunks(newChunks, embeddings, (done, total) =>\n emit({ stage: 'embed', done, total }),\n );\n if (records.length > 0) {\n emit({ stage: 'upsert', count: records.length });\n await vectorStore.upsert(records, input.indexId);\n }\n emit({ stage: 'save' });\n\n const manifest: IndexManifest = {\n indexId: input.indexId,\n chunks: [...keptChunks, ...newChunks],\n files,\n updatedAt: input.now,\n };\n await saveManifest(storage, manifest);\n\n return {\n filesIndexed: Object.keys(files).length,\n chunks: manifest.chunks.length,\n added,\n updated,\n removed: removedPaths.length,\n unchanged: unchanged.length,\n };\n}\n","/**\n * Incremental document sync — add / update / delete specific paths in an index\n * without a full rebuild. Operates on both the vector store (namespace=indexId)\n * and the persisted manifest (BM25 corpus + bookkeeping).\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { MindServices } from './services';\nimport type { Chunk, IndexManifest } from './types';\nimport { hashContent } from './types';\nimport { type ChunkOptions } from './ingest/chunk';\nimport { chunkFile } from './ingest/structural';\nimport { embedChunks } from './ingest/embed';\nimport { loadManifest, saveManifest } from './index-store';\n\nexport interface SyncOptions {\n indexId: string;\n /** Workspace root that source paths are resolved against. */\n cwd: string;\n chunk: ChunkOptions;\n ast: boolean;\n now: string;\n}\n\nexport interface SyncCounts {\n added: number;\n updated: number;\n deleted: number;\n}\n\n/** Remove all chunks for the given paths from vector store + manifest. */\nasync function removePaths(\n manifest: IndexManifest,\n paths: Set<string>,\n services: MindServices,\n indexId: string,\n): Promise<number> {\n const removedIds = manifest.chunks.filter((c) => paths.has(c.path)).map((c) => c.id);\n if (removedIds.length > 0) {\n await services.vectorStore.delete(removedIds, indexId);\n }\n manifest.chunks = manifest.chunks.filter((c) => !paths.has(c.path));\n for (const p of paths) {\n delete manifest.files[p];\n }\n return removedIds.length;\n}\n\n/** Chunk + embed + upsert the given paths into the index. */\nasync function addPaths(\n manifest: IndexManifest,\n paths: string[],\n services: MindServices,\n opts: SyncOptions,\n): Promise<number> {\n const newChunks: Chunk[] = [];\n for (const path of paths) {\n let content: string;\n try {\n content = await readFile(join(opts.cwd, path), 'utf8');\n } catch {\n continue;\n }\n const chunks = chunkFile(path, content, opts.chunk, opts.ast);\n if (chunks.length === 0) {\n continue;\n }\n newChunks.push(...chunks);\n manifest.files[path] = { chunks: chunks.length, indexedAt: opts.now, hash: hashContent(content) };\n }\n\n if (newChunks.length > 0) {\n const records = await embedChunks(newChunks, services.embeddings);\n await services.vectorStore.upsert(records, opts.indexId);\n manifest.chunks.push(...newChunks);\n }\n return newChunks.length;\n}\n\nexport async function syncAdd(paths: string[], services: MindServices, opts: SyncOptions): Promise<SyncCounts> {\n const manifest = await loadManifest(services.storage, opts.indexId);\n // Treat re-adding an existing path as an update (replace its chunks).\n const existing = new Set(paths.filter((p) => manifest.files[p]));\n await removePaths(manifest, existing, services, opts.indexId);\n await addPaths(manifest, paths, services, opts);\n manifest.updatedAt = opts.now;\n await saveManifest(services.storage, manifest);\n return { added: paths.length - existing.size, updated: existing.size, deleted: 0 };\n}\n\nexport async function syncUpdate(paths: string[], services: MindServices, opts: SyncOptions): Promise<SyncCounts> {\n const manifest = await loadManifest(services.storage, opts.indexId);\n await removePaths(manifest, new Set(paths), services, opts.indexId);\n await addPaths(manifest, paths, services, opts);\n manifest.updatedAt = opts.now;\n await saveManifest(services.storage, manifest);\n return { added: 0, updated: paths.length, deleted: 0 };\n}\n\nexport async function syncDelete(paths: string[], services: MindServices, opts: SyncOptions): Promise<SyncCounts> {\n const manifest = await loadManifest(services.storage, opts.indexId);\n const deleted = await removePaths(manifest, new Set(paths), services, opts.indexId);\n manifest.updatedAt = opts.now;\n await saveManifest(services.storage, manifest);\n return { added: 0, updated: 0, deleted };\n}\n","/**\n * BM25 keyword ranking over the in-memory chunk corpus.\n *\n * Self-contained Okapi BM25. Tokenization lowercases and splits on\n * non-alphanumerics, additionally splitting camelCase and snake_case so code\n * identifiers (`getUserId`, `user_id`) match natural-language queries.\n */\n\nimport type { Chunk } from '../types';\n\nexport interface Ranked {\n id: string;\n score: number;\n}\n\nconst K1 = 1.5;\nconst B = 0.75;\n\nexport function tokenize(text: string): string[] {\n return text\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2') // camelCase -> camel Case\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length > 1);\n}\n\nexport function bm25Search(chunks: Chunk[], query: string, limit: number): Ranked[] {\n if (chunks.length === 0) {\n return [];\n }\n\n const docs = chunks.map((c) => tokenize(c.text));\n const docLens = docs.map((d) => d.length);\n const avgDocLen = docLens.reduce((a, b) => a + b, 0) / docs.length || 1;\n\n // Document frequency per term.\n const df = new Map<string, number>();\n for (const doc of docs) {\n for (const term of new Set(doc)) {\n df.set(term, (df.get(term) ?? 0) + 1);\n }\n }\n\n const queryTerms = [...new Set(tokenize(query))];\n const N = docs.length;\n\n const scored: Ranked[] = chunks.map((chunk, i) => {\n const doc = docs[i] ?? [];\n const len = docLens[i] ?? 0;\n const tf = new Map<string, number>();\n for (const term of doc) {\n tf.set(term, (tf.get(term) ?? 0) + 1);\n }\n\n let score = 0;\n for (const term of queryTerms) {\n const termTf = tf.get(term);\n if (!termTf) {\n continue;\n }\n const docFreq = df.get(term) ?? 0;\n // BM25 idf with +1 to keep it non-negative.\n const idf = Math.log(1 + (N - docFreq + 0.5) / (docFreq + 0.5));\n const denom = termTf + K1 * (1 - B + (B * len) / avgDocLen);\n score += idf * ((termTf * (K1 + 1)) / denom);\n }\n\n return { id: chunk.id, score };\n });\n\n return scored\n .filter((r) => r.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, limit);\n}\n","/**\n * Vector retrieval via the platform vector store, scoped by namespace=indexId.\n */\n\nimport type { IVectorStore } from '../services';\nimport type { Ranked } from './bm25';\n\nexport async function vectorSearch(\n queryText: string,\n vectorStore: IVectorStore,\n embed: (text: string) => Promise<number[]>,\n indexId: string,\n limit: number,\n): Promise<Ranked[]> {\n let vector: number[];\n try {\n vector = await embed(queryText);\n } catch (err) {\n throw new Error(`mind: query embedding failed — ${err instanceof Error ? err.message : String(err)}`);\n }\n try {\n const hits = await vectorStore.search(vector, limit, undefined, indexId);\n return hits.map((h) => ({ id: h.id, score: h.score }));\n } catch (err) {\n throw new Error(\n `mind: vector search failed (indexId=\"${indexId}\", dims=${vector.length}) — ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n","/**\n * Reciprocal Rank Fusion (RRF) with intent-adaptive weights.\n *\n * Fuses ranked lists by `weight * 1/(k + rank)`. Weights shift the balance\n * between the semantic (vector) and keyword (BM25) lists based on query intent.\n */\n\nimport type { Ranked } from './bm25';\n\nexport type QueryIntent = 'lookup' | 'concept' | 'architecture';\n\n/** Which retrieval signal surfaced a result — the \"why\" + proof-of-value vs grep. */\nexport type MatchedBy = 'lexical' | 'semantic' | 'both';\n\nexport interface WeightedList {\n ranked: Ranked[];\n weight: number;\n /** Provenance label for this list (so the fused result knows where it came from). */\n label?: Exclude<MatchedBy, 'both'>;\n}\n\nexport interface FusedRanked extends Ranked {\n matchedBy: MatchedBy;\n}\n\n/** Vector/BM25 weighting per intent (vector favored for meaning, BM25 for exact terms). */\nexport function intentWeights(intent?: QueryIntent): { vector: number; bm25: number } {\n switch (intent) {\n case 'lookup':\n return { vector: 0.4, bm25: 0.6 }; // exact symbol lookups lean keyword\n case 'architecture':\n return { vector: 0.6, bm25: 0.4 };\n case 'concept':\n default:\n return { vector: 0.7, bm25: 0.3 };\n }\n}\n\nexport function rrfFuse(lists: WeightedList[], k: number): FusedRanked[] {\n const scores = new Map<string, number>();\n const labels = new Map<string, Set<Exclude<MatchedBy, 'both'>>>();\n\n for (const { ranked, weight, label } of lists) {\n ranked.forEach((item, idx) => {\n const rank = idx + 1;\n scores.set(item.id, (scores.get(item.id) ?? 0) + weight * (1 / (k + rank)));\n if (label) {\n const set = labels.get(item.id) ?? new Set();\n set.add(label);\n labels.set(item.id, set);\n }\n });\n }\n\n return [...scores.entries()]\n .map(([id, score]) => ({ id, score, matchedBy: resolveMatchedBy(labels.get(id)) }))\n .sort((a, b) => b.score - a.score);\n}\n\nfunction resolveMatchedBy(set?: Set<Exclude<MatchedBy, 'both'>>): MatchedBy {\n // Unlabelled lists (e.g. tests) → 'both' (neutral). Otherwise: in both lists → 'both'.\n if (!set || set.size === 0 || set.size === 2) {\n return 'both';\n }\n return set.has('semantic') ? 'semantic' : 'lexical';\n}\n","/**\n * HyDE — Hypothetical Document Embeddings.\n *\n * Ask the LLM to draft a short, realistic snippet that would answer the query,\n * then use THAT text (not the raw query) for the vector search. The hypothetical\n * doc lives in answer-space, so its embedding sits closer to the relevant chunks\n * than a terse question does — which helps concept queries where the query\n * wording and the code/doc wording diverge. BM25 keeps using the raw query, so\n * exact-term lookups are unaffected.\n *\n * Best-effort: on any LLM error or empty output, fall back to the raw query so\n * retrieval degrades to plain vector search rather than failing.\n */\n\nimport type { ILLM } from '../services';\n\nconst HYDE_PROMPT = (query: string) =>\n `Write a short, realistic code or documentation snippet that would directly answer ` +\n `the question below. Output only the snippet — no preamble, no explanation, no fences.\\n\\n` +\n `Question: ${query}`;\n\nexport async function hypotheticalDocument(query: string, llm: ILLM): Promise<string> {\n try {\n const { content } = await llm.complete(HYDE_PROMPT(query), { temperature: 0.0, maxTokens: 256 });\n const text = (content ?? '').trim();\n // Append the raw query so query terms still contribute to the embedding.\n return text === '' ? query : `${text}\\n\\n${query}`;\n } catch {\n return query;\n }\n}\n","/**\n * Query expansion for the lexical (BM25) side.\n *\n * Ask the LLM for code identifiers and synonyms that are likely to appear in\n * relevant source/docs, then append them to the raw query before BM25. This\n * targets vocabulary mismatch — the core failure mode on messy/undocumented\n * repos, where the asker's words and the code's words diverge. The vector side\n * keeps its own bridge (HyDE); the two levers are orthogonal.\n *\n * Best-effort: on any LLM error or empty output, fall back to the raw query so\n * retrieval degrades to plain BM25 rather than failing.\n */\n\nimport type { ILLM } from '../services';\n\nconst EXPAND_PROMPT = (query: string) =>\n `List code identifiers, function/type names, and close synonyms that would likely appear ` +\n `in source code or documentation relevant to the query below. Output a single ` +\n `space-separated line of terms only — no explanation, no punctuation, no fences.\\n\\n` +\n `Query: ${query}`;\n\nexport async function expandQuery(query: string, llm: ILLM): Promise<string> {\n try {\n const { content } = await llm.complete(EXPAND_PROMPT(query), { temperature: 0.0, maxTokens: 64 });\n const extra = (content ?? '').trim();\n // Keep the raw query first so its exact terms still dominate BM25 scoring.\n return extra === '' ? query : `${query} ${extra}`;\n } catch {\n return query;\n }\n}\n","/**\n * Retrieval pipeline: BM25 (over manifest corpus) + vector (platform store),\n * fused with intent-adaptive RRF, mapped back to chunks.\n */\n\nimport type { MindServices } from '../services';\nimport type { Chunk } from '../types';\nimport { loadManifest } from '../index-store';\nimport { bm25Search, type Ranked } from './bm25';\nimport { vectorSearch } from './vector';\nimport { rrfFuse, intentWeights, type QueryIntent, type MatchedBy } from './fuse';\nimport { hypotheticalDocument } from './hyde';\nimport { expandQuery } from './expand';\n\nexport interface RetrieveInput {\n text: string;\n indexId: string;\n limit: number;\n intent?: QueryIntent;\n rrfK: number;\n /** HyDE: embed an LLM-generated hypothetical doc for the vector search. */\n hyde?: boolean;\n /** Query expansion: append LLM-suggested related terms to the BM25 query. */\n expand?: boolean;\n}\n\nexport interface RankedChunk {\n chunk: Chunk;\n /** Fused RRF score (best first). */\n score: number;\n /** Which signal surfaced this chunk (lexical/semantic/both) — provenance. */\n matchedBy: MatchedBy;\n}\n\nexport interface RetrieveOutput {\n /** Fused, ranked chunks (best first), truncated to `limit`. */\n ranked: RankedChunk[];\n /** Raw cosine confidence proxy from the vector list (top-3 avg). */\n confidence: number;\n /** Share of returned results found semantic-only (grep would miss them). */\n semanticWinRate: number;\n}\n\nexport async function retrieve(input: RetrieveInput, services: MindServices): Promise<RetrieveOutput> {\n const manifest = await loadManifest(services.storage, input.indexId);\n const byId = new Map(manifest.chunks.map((c) => [c.id, c]));\n\n // Over-fetch each list so fusion has signal beyond the final cut.\n const candidateLimit = Math.max(input.limit * 3, 30);\n\n // Two orthogonal, optional query bridges (each one LLM call):\n // - HyDE rewrites the VECTOR text (a hypothetical answer sits near the chunks);\n // - expansion augments the BM25 (LEXICAL) text with related identifiers/synonyms.\n const vectorText = input.hyde ? await hypotheticalDocument(input.text, services.llm) : input.text;\n const lexicalText = input.expand ? await expandQuery(input.text, services.llm) : input.text;\n\n const bm25 = bm25Search(manifest.chunks, lexicalText, candidateLimit);\n const vector = await vectorSearch(\n vectorText,\n services.vectorStore,\n (t) => services.embeddings.embed(t),\n input.indexId,\n candidateLimit,\n );\n\n const weights = intentWeights(input.intent);\n const fused = rrfFuse(\n [\n { ranked: vector, weight: weights.vector, label: 'semantic' },\n { ranked: bm25, weight: weights.bm25, label: 'lexical' },\n ],\n input.rrfK,\n );\n\n const ranked: RankedChunk[] = fused\n .map((r) => {\n const chunk = byId.get(r.id);\n return chunk ? { chunk, score: r.score, matchedBy: r.matchedBy } : undefined;\n })\n .filter((r): r is RankedChunk => r !== undefined)\n .slice(0, input.limit);\n\n // Proof-of-value vs grep: how many returned hits are semantic-only (grep-miss).\n const semanticWinRate =\n ranked.length === 0 ? 0 : ranked.filter((r) => r.matchedBy === 'semantic').length / ranked.length;\n\n return { ranked, confidence: confidenceFrom(vector), semanticWinRate };\n}\n\n/** Phase 2 confidence proxy: average cosine of the top-3 vector hits. */\nfunction confidenceFrom(vector: Ranked[]): number {\n if (vector.length === 0) {\n return 0;\n }\n const top = vector.slice(0, 3);\n const avg = top.reduce((a, r) => a + r.score, 0) / top.length;\n return Math.max(0, Math.min(1, avg));\n}\n","/**\n * Heuristic reranking of fused candidates.\n *\n * Lightweight, deterministic signals layered on the fused RRF score:\n * - exact query-term coverage in the chunk text (keyword precision)\n * - identifier hit: a query token appearing verbatim (good for code lookups)\n *\n * An optional LLM reranker can be layered later; this heuristic pass is always\n * available and needs no model.\n */\n\nimport type { RankedChunk } from './retrieve';\nimport { tokenize } from './bm25';\n\nexport function rerank(ranked: RankedChunk[], query: string): RankedChunk[] {\n const qTokens = new Set(tokenize(query));\n if (qTokens.size === 0) {\n return ranked;\n }\n\n const boosted = ranked.map((item) => {\n const docTokens = tokenize(item.chunk.text);\n const docSet = new Set(docTokens);\n let covered = 0;\n for (const q of qTokens) {\n if (docSet.has(q)) {\n covered++;\n }\n }\n const coverage = covered / qTokens.size; // 0..1\n // Verbatim identifier presence (case-insensitive) — strong for symbol lookups.\n const lowerText = item.chunk.text.toLowerCase();\n const verbatim = [...qTokens].some((q) => q.length >= 3 && lowerText.includes(q)) ? 1 : 0;\n\n const boost = 1 + 0.5 * coverage + 0.25 * verbatim;\n return { ...item, score: item.score * boost };\n });\n\n return boosted.sort((a, b) => b.score - a.score);\n}\n","/**\n * Semantic-ish dedup of ranked chunks via token-set Jaccard similarity.\n *\n * Keeps the highest-ranked chunk and drops later near-duplicates (e.g. the same\n * code re-surfaced by both BM25 and vector lists, or overlapping windows).\n * Operates on the small post-fusion list, so O(n²) is fine.\n */\n\nimport type { RankedChunk } from './retrieve';\nimport { tokenize } from './bm25';\n\nfunction jaccard(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 && b.size === 0) {\n return 1;\n }\n let inter = 0;\n for (const t of a) {\n if (b.has(t)) {\n inter++;\n }\n }\n const union = a.size + b.size - inter;\n return union === 0 ? 0 : inter / union;\n}\n\nexport function dedupRanked(ranked: RankedChunk[], threshold = 0.85): RankedChunk[] {\n const kept: RankedChunk[] = [];\n const keptTokens: Set<string>[] = [];\n\n for (const item of ranked) {\n const tokens = new Set(tokenize(item.chunk.text));\n const isDup = keptTokens.some((k) => jaccard(tokens, k) >= threshold);\n if (!isDup) {\n kept.push(item);\n keptTokens.push(tokens);\n }\n }\n\n return kept;\n}\n","/**\n * Anti-hallucination verification + confidence stack.\n *\n * Each retrieved chunk is verified against the live source via `IStorage`:\n * file exists (0.7) + snippet still present (0.3). The verification rate scales\n * the retrieval confidence — a stale or fabricated source drags confidence down.\n * Mirrors the legacy mind concept (source-verifier + confidence floor).\n */\n\nimport type { AgentWarning } from '@kb-labs/mind-contracts';\nimport type { IStorage } from '../services';\nimport type { RankedChunk } from '../retrieval/retrieve';\n\nexport interface VerificationResult {\n /** 0..1 fraction of (weighted) verification across chunks. */\n rate: number;\n /** Per-chunk verification score (0..1), aligned with input order. */\n perChunk: number[];\n}\n\nconst FILE_WEIGHT = 0.7;\nconst SNIPPET_WEIGHT = 0.3;\n\nexport async function verifySources(ranked: RankedChunk[], storage: IStorage): Promise<VerificationResult> {\n if (ranked.length === 0) {\n return { rate: 1, perChunk: [] };\n }\n\n const perChunk: number[] = [];\n for (const { chunk } of ranked) {\n const exists = await storage.exists(chunk.path);\n let score = exists ? FILE_WEIGHT : 0;\n if (exists) {\n const buf = await storage.read(chunk.path);\n const content = buf?.toString('utf8') ?? '';\n // Snippet grounding: a representative line of the chunk is still present.\n const probe = chunk.text.split('\\n').find((l) => l.trim().length > 8)?.trim();\n if (probe && content.includes(probe)) {\n score += SNIPPET_WEIGHT;\n }\n }\n perChunk.push(score);\n }\n\n const rate = perChunk.reduce((a, b) => a + b, 0) / perChunk.length;\n return { rate, perChunk };\n}\n\nexport interface ConfidenceResult {\n confidence: number;\n warnings: AgentWarning[];\n}\n\n/** Combine retrieval confidence with the verification rate; warn below floor. */\nexport function computeConfidence(\n retrievalConfidence: number,\n verificationRate: number,\n floor: number,\n): ConfidenceResult {\n const confidence = Math.max(0, Math.min(1, retrievalConfidence * verificationRate));\n const warnings: AgentWarning[] = [];\n if (confidence < floor) {\n warnings.push({\n code: 'LOW_CONFIDENCE',\n message: `Confidence ${confidence.toFixed(2)} is below the floor ${floor.toFixed(2)}; the answer may be unreliable.`,\n });\n }\n return { confidence, warnings };\n}\n","/**\n * Field-checker — an anti-hallucination signal ported from the legacy engine.\n *\n * An LLM answer that cites code should only name symbols that actually appear\n * in the retrieved sources. We extract code-like symbols from the answer\n * (backtick spans, camelCase/dotted/underscored identifiers, file names) and\n * check each against the retrieved chunks (text + path). The grounded fraction\n * folds into the confidence stack, and any ungrounded terms are surfaced as a\n * warning — a cheap, deterministic guard against fabricated APIs.\n */\n\nimport type { AgentWarning } from '@kb-labs/mind-contracts';\nimport type { RankedChunk } from '../retrieval/retrieve';\n\n/** Heuristic: does this token look like a code symbol worth grounding? */\nfunction isCodeSymbol(t: string): boolean {\n if (t.length < 3 || t.length > 80) {\n return false;\n }\n if (/\\.(ts|tsx|js|jsx|json|md|go|py|rs)$/.test(t)) {\n return true; // file name\n }\n if (t.includes('.') && /[a-zA-Z]/.test(t)) {\n return true; // dotted member access (vectorStore.search, config.loader)\n }\n if (/_/.test(t) && /[a-zA-Z]/.test(t)) {\n return true; // snake_case / CONST_CASE\n }\n if (/[a-z][A-Z]/.test(t)) {\n return true; // camelCase / PascalCase transition (assemblePlatform, EventBus)\n }\n return false;\n}\n\n/** Extract code-like symbols from an answer (deduped, order-preserving). */\nexport function extractSymbols(answer: string): string[] {\n const out = new Set<string>();\n // Backtick spans are the strongest signal — the model is quoting code.\n for (const m of answer.matchAll(/`([^`\\n]{2,80})`/g)) {\n for (const tok of m[1]!.trim().split(/[\\s(),;:[\\]{}'\"]+/)) {\n if (isCodeSymbol(tok)) {\n out.add(tok);\n }\n }\n }\n // Bare identifiers in prose (camelCase/dotted/underscored/hyphenated/file names).\n for (const m of answer.matchAll(/[A-Za-z_$][A-Za-z0-9_$-]*(?:[./][A-Za-z0-9_$.-]+)*/g)) {\n if (isCodeSymbol(m[0])) {\n out.add(m[0]);\n }\n }\n return [...out];\n}\n\nexport interface FieldCheckResult {\n /** 0..1 fraction of extracted symbols grounded in the sources. */\n rate: number;\n /** Symbols not found in any retrieved chunk. */\n ungrounded: string[];\n /** Number of symbols checked (0 → nothing to verify, rate defaults to 1). */\n checked: number;\n}\n\n/** Check that symbols named in the answer appear in the retrieved sources. */\nexport function checkFields(answer: string, ranked: RankedChunk[]): FieldCheckResult {\n const symbols = extractSymbols(answer);\n if (symbols.length === 0) {\n return { rate: 1, ungrounded: [], checked: 0 };\n }\n const corpus = ranked.map((r) => `${r.chunk.path}\\n${r.chunk.text}`).join('\\n').toLowerCase();\n const grounded = (sym: string): boolean => {\n const s = sym.toLowerCase();\n if (corpus.includes(s)) {\n return true;\n }\n // Dotted member (a.b.c): accept if the head object is present in sources.\n const head = s.split('.')[0]!;\n return head.length >= 3 && corpus.includes(head);\n };\n const ungrounded = symbols.filter((s) => !grounded(s));\n return { rate: (symbols.length - ungrounded.length) / symbols.length, ungrounded, checked: symbols.length };\n}\n\n/**\n * Fold a field-check into the confidence stack: ungrounded terms scale\n * confidence down (never below 0) and surface as warnings. Returns the adjusted\n * confidence + the (possibly extended) warning list. Pure — no side effects.\n */\nexport function applyFieldCheck(\n answer: string,\n ranked: RankedChunk[],\n confidence: number,\n warnings: AgentWarning[],\n floor: number,\n): { confidence: number; warnings: AgentWarning[] } {\n const fc = checkFields(answer, ranked);\n if (fc.checked === 0 || fc.rate === 1) {\n return { confidence, warnings };\n }\n const adjusted = Math.max(0, confidence * (0.5 + 0.5 * fc.rate));\n const next = [...warnings];\n if (fc.ungrounded.length > 0) {\n next.push({\n code: 'UNGROUNDED_TERMS',\n message: `Answer mentions ${fc.ungrounded.length} term(s) not found in sources: ${fc.ungrounded.slice(0, 5).join(', ')}`,\n details: { ungrounded: fc.ungrounded, rate: Math.round(fc.rate * 1000) / 1000 },\n });\n }\n if (adjusted < floor && !next.some((w) => w.code === 'LOW_CONFIDENCE')) {\n next.push({\n code: 'LOW_CONFIDENCE',\n message: `Confidence ${adjusted.toFixed(2)} is below the floor ${floor.toFixed(2)}; the answer may be unreliable.`,\n });\n }\n return { confidence: adjusted, warnings: next };\n}\n","/**\n * Query decomposition (multi-step reasoning) for richer agent modes.\n *\n * Asks the LLM to split a complex question into focused sub-queries. Degrades\n * gracefully: if decomposition is disabled or the LLM returns nothing usable,\n * it falls back to the original query alone.\n */\n\nimport type { ILLM } from '../services';\n\nexport async function decompose(query: string, llm: ILLM, maxSubqueries: number): Promise<string[]> {\n if (maxSubqueries <= 0) {\n return [query];\n }\n\n const prompt =\n `Break the following question into at most ${maxSubqueries} focused, self-contained ` +\n `sub-questions that together cover it. Return one sub-question per line, no numbering.\\n\\n` +\n `Question: ${query}`;\n\n try {\n const { content } = await llm.complete(prompt, { temperature: 0.2, maxTokens: 256 });\n const subs = (content ?? '')\n .split('\\n')\n .map((l) => l.replace(/^[-*\\d.)\\s]+/, '').trim())\n .filter((l) => l.length > 0)\n .slice(0, maxSubqueries);\n // Always include the original query so we never lose the primary intent.\n return subs.length > 0 ? [query, ...subs] : [query];\n } catch {\n return [query];\n }\n}\n","/**\n * Shape ranked chunks into lean wire `SearchResult`s (pointers, not payloads).\n *\n * `snippet` rides only as much text as the caller asked for (`--snippet`):\n * none → nothing; line → the first meaningful line; full → truncated chunk.\n */\n\nimport type { SearchResult, SnippetMode } from '@kb-labs/mind-contracts';\nimport type { RankedChunk } from '../retrieval/retrieve';\n\nconst MAX_SNIPPET_CHARS = 600;\n\n/** Extract a snippet of the requested verbosity from chunk text. */\nexport function snippetFrom(text: string, mode: SnippetMode): string | undefined {\n if (mode === 'none') {\n return undefined;\n }\n if (mode === 'full') {\n return text.length > MAX_SNIPPET_CHARS ? `${text.slice(0, MAX_SNIPPET_CHARS)}…` : text;\n }\n // 'line' — the first non-trivial line, for an \"is this it?\" glance.\n const line = text.split('\\n').find((l) => l.trim().length > 8)?.trim() ?? text.trim().slice(0, 120);\n return line.length > 200 ? `${line.slice(0, 200)}…` : line;\n}\n\nexport interface ToResultsOptions {\n snippet: SnippetMode;\n /** file → stale (on-disk drift since indexing). */\n staleByFile: Map<string, boolean>;\n}\n\nexport function toSearchResults(ranked: RankedChunk[], opts: ToResultsOptions): SearchResult[] {\n return ranked.map(({ chunk, matchedBy }) => ({\n file: chunk.path,\n lines: [chunk.startLine, chunk.endLine] as [number, number],\n kind: chunk.kind,\n matchedBy,\n stale: opts.staleByFile.get(chunk.path) ?? false,\n snippet: snippetFrom(chunk.text, opts.snippet),\n }));\n}\n","/**\n * Answer synthesis + frozen `AgentResponse` assembly.\n *\n * Produces the `agent-response-v1` contract consumed by CLAUDE.md and the\n * task-rag skill. The response is validated against the contract zod before\n * being returned, so a drift fails loudly here rather than silently downstream.\n */\n\nimport {\n AgentResponseSchema,\n type AgentResponse,\n type AgentSource,\n type AgentWarning,\n type AgentQueryMode,\n type SnippetMode,\n} from '@kb-labs/mind-contracts';\nimport type { ILLM } from '../services';\nimport type { RankedChunk } from '../retrieval/retrieve';\nimport { snippetFrom } from './synthesize';\n\nconst MAX_SNIPPET_CHARS = 600;\n\nfunction truncate(text: string): string {\n return text.length > MAX_SNIPPET_CHARS ? `${text.slice(0, MAX_SNIPPET_CHARS)}…` : text;\n}\n\n/** Extractive fallback answer (no LLM): the most relevant snippet, attributed. */\nfunction extractiveAnswer(query: string, ranked: RankedChunk[]): string {\n if (ranked.length === 0) {\n return `No indexed content matched the query: \"${query}\".`;\n }\n const top = ranked[0]!.chunk;\n return `Most relevant source: ${top.path} (lines ${top.startLine}-${top.endLine}).\\n\\n${truncate(top.text)}`;\n}\n\nexport async function synthesizeAnswer(\n query: string,\n ranked: RankedChunk[],\n llm: ILLM,\n useLLM: boolean,\n): Promise<string> {\n if (!useLLM || ranked.length === 0) {\n return extractiveAnswer(query, ranked);\n }\n\n const context = ranked\n .map((r, i) => `[${i + 1}] ${r.chunk.path}:${r.chunk.startLine}-${r.chunk.endLine}\\n${r.chunk.text}`)\n .join('\\n\\n');\n\n const prompt =\n `Answer the question using ONLY the provided context. Be concise and cite the ` +\n `relevant files by path. If the context does not contain the answer, say so.\\n\\n` +\n `Question: ${query}\\n\\nContext:\\n${context}`;\n\n try {\n const { content } = await llm.complete(prompt, { temperature: 0.2, maxTokens: 800 });\n const trimmed = (content ?? '').trim();\n return trimmed.length > 0 ? trimmed : extractiveAnswer(query, ranked);\n } catch {\n return extractiveAnswer(query, ranked);\n }\n}\n\nexport interface ToSourcesOptions {\n snippet: SnippetMode;\n staleByFile: Map<string, boolean>;\n}\n\nexport function toSources(ranked: RankedChunk[], opts: ToSourcesOptions): AgentSource[] {\n return ranked.map(({ chunk, matchedBy }) => ({\n file: chunk.path,\n lines: [chunk.startLine, chunk.endLine] as [number, number],\n kind: chunk.kind,\n matchedBy,\n stale: opts.staleByFile.get(chunk.path) ?? false,\n snippet: snippetFrom(chunk.text, opts.snippet),\n }));\n}\n\nexport interface BuildAgentResponseInput {\n answer: string;\n ranked: RankedChunk[];\n confidence: number;\n mode: AgentQueryMode;\n requestId: string;\n timingMs: number;\n indexId: string;\n floor: number;\n snippet: SnippetMode;\n staleByFile: Map<string, boolean>;\n warnings?: AgentWarning[];\n}\n\n/** Assemble + validate the lean agent response. */\nexport function buildAgentResponse(input: BuildAgentResponseInput): AgentResponse {\n const sources = toSources(input.ranked, { snippet: input.snippet, staleByFile: input.staleByFile });\n const abstained = input.confidence < input.floor || sources.length === 0;\n\n const response: AgentResponse = {\n answer: input.answer,\n confidence: input.confidence,\n abstained,\n sources,\n warnings: input.warnings && input.warnings.length > 0 ? input.warnings : undefined,\n meta: {\n requestId: input.requestId,\n mode: input.mode,\n timingMs: input.timingMs,\n indexId: input.indexId,\n },\n };\n\n // Fail loudly if we ever drift from the contract.\n return AgentResponseSchema.parse(response);\n}\n","/**\n * Task-orientation map. No hardcoded role/name heuristics: relevance + ranking\n * come from retrieval, the orientation (\"where to start / how involved\") comes\n * from the model, and structure (`spread`) is derived from the actual paths.\n */\n\nimport type { ExploreEntry } from '@kb-labs/mind-contracts';\nimport type { ILLM } from '../services';\nimport type { RankedChunk } from '../retrieval/retrieve';\nimport { snippetFrom } from './synthesize';\n\n/** Ranked chunks → entries deduped by file (best rank kept). `why` = matched line. */\nexport function toExploreEntries(ranked: RankedChunk[], staleByFile: Map<string, boolean>): ExploreEntry[] {\n const seen = new Set<string>();\n const out: ExploreEntry[] = [];\n for (const r of ranked) {\n if (seen.has(r.chunk.path)) {\n continue;\n }\n seen.add(r.chunk.path);\n const line = snippetFrom(r.chunk.text, 'line');\n out.push({\n file: r.chunk.path,\n lines: [r.chunk.startLine, r.chunk.endLine] as [number, number],\n why: line && line.length > 0 ? line : `${r.chunk.kind} file`,\n matchedBy: r.matchedBy,\n stale: staleByFile.get(r.chunk.path) ?? false,\n });\n }\n return out;\n}\n\n/** Distinct directories the files span — a structural \"how spread out\" hint. */\nexport function spreadOf(files: string[]): number {\n return new Set(\n files.map((f) => {\n const i = f.lastIndexOf('/');\n return i < 0 ? '.' : f.slice(0, i);\n }),\n ).size;\n}\n\n/**\n * Model-synthesized orientation grounded in the retrieved files. Empty string\n * when no LLM is available (e.g. instant mode) — the file list still stands.\n */\nexport async function orientationSummary(\n task: string,\n entries: ExploreEntry[],\n llm: ILLM,\n useLLM: boolean,\n): Promise<string> {\n if (!useLLM || entries.length === 0) {\n return '';\n }\n const list = entries.map((e, i) => `[${i + 1}] ${e.file}:${e.lines[0]}-${e.lines[1]} — ${e.why}`).join('\\n');\n const prompt =\n `A developer must approach the task below in an unfamiliar codebase. Using ONLY the ` +\n `relevant files listed, briefly explain WHERE to start, the KEY files and their role, ` +\n `and HOW involved the task looks. Be concise; cite files by path.\\n\\n` +\n `Task: ${task}\\n\\nRelevant files:\\n${list}`;\n try {\n const { content } = await llm.complete(prompt, { temperature: 0.2, maxTokens: 400 });\n return (content ?? '').trim();\n } catch {\n return '';\n }\n}\n","/**\n * Query-history feedback loop via the platform cache (sorted set).\n *\n * Records queries per index (scored by timestamp) so the engine can learn from\n * usage over time. Best-effort: cache failures never break a query.\n */\n\nimport type { ICache } from '../services';\nimport { MIND_NAMESPACE_PREFIX } from '@kb-labs/mind-contracts';\n\nfunction historyKey(indexId: string): string {\n return `${MIND_NAMESPACE_PREFIX}history:${indexId}`;\n}\n\nexport async function recordQuery(\n cache: ICache,\n indexId: string,\n query: string,\n at: number,\n): Promise<void> {\n try {\n await cache.zadd(historyKey(indexId), at, query);\n } catch {\n // Feedback is best-effort; never fail the user's query because of it.\n }\n}\n\nexport async function recentQueries(\n cache: ICache,\n indexId: string,\n sinceMs = 0,\n): Promise<string[]> {\n try {\n return await cache.zrangebyscore(historyKey(indexId), sinceMs, Number.MAX_SAFE_INTEGER);\n } catch {\n return [];\n }\n}\n","/**\n * Mind facade — the single object the plugin (CLI + REST) talks to.\n *\n * `createMind(services, config)` returns verbs that both the CLI commands and\n * REST handlers call identically, so behaviour is shared by construction.\n * Phase 2 ships `index` / `search` / `status`; `ask`, `sync`, `reindex` are\n * layered in later phases.\n */\n\nimport type {\n MindConfig,\n IndexRequest,\n IndexResponse,\n SearchRequest,\n SearchResponse,\n StatusResponse,\n IndexSummary,\n HealthResponse,\n QueryRequest,\n AgentResponse,\n AgentQueryMode,\n ExploreRequest,\n ExploreResponse,\n SyncResponse,\n SyncListResponse,\n SyncStatusResponse,\n ReindexRequest,\n DropRequest,\n DropResponse,\n} from '@kb-labs/mind-contracts';\nimport { effectiveIndexConfig, resolveScope } from '@kb-labs/mind-contracts';\nimport type { MindServices } from './services';\nimport type { RankedChunk } from './retrieval/retrieve';\nimport { ingest, type IngestProgress } from './ingest/ingest';\nimport { syncAdd, syncUpdate, syncDelete, type SyncOptions } from './sync';\nimport { retrieve } from './retrieval/retrieve';\nimport { rerank } from './retrieval/rerank';\nimport { dedupRanked } from './retrieval/dedup';\nimport { verifySources, computeConfidence } from './answer/verify';\nimport { applyFieldCheck } from './answer/field-check';\nimport { decompose } from './answer/decompose';\nimport { synthesizeAnswer, buildAgentResponse } from './answer/answer';\nimport { toExploreEntries, spreadOf, orientationSummary } from './answer/explore';\nimport { recordQuery } from './feedback/history';\nimport { toSearchResults } from './answer/synthesize';\nimport { loadManifest, staleMap, staleCount, deleteManifest, manifestExists } from './index-store';\n\nexport interface Mind {\n index(req: IndexRequest, onProgress?: (event: IngestProgress) => void): Promise<IndexResponse>;\n search(req: SearchRequest): Promise<SearchResponse>;\n ask(req: QueryRequest): Promise<AgentResponse>;\n explore(req: ExploreRequest): Promise<ExploreResponse>;\n reindex(req: ReindexRequest): Promise<IndexResponse>;\n drop(req: DropRequest): Promise<DropResponse>;\n syncAdd(paths: string[], indexId?: string): Promise<SyncResponse>;\n syncUpdate(paths: string[], indexId?: string): Promise<SyncResponse>;\n syncDelete(paths: string[], indexId?: string): Promise<SyncResponse>;\n syncList(indexId?: string): Promise<SyncListResponse>;\n syncStatus(indexId?: string): Promise<SyncStatusResponse>;\n status(indexId?: string): Promise<StatusResponse>;\n health(): Promise<HealthResponse>;\n}\n\nexport interface CreateMindOptions {\n /** Workspace root that source paths are resolved against (default: process.cwd()). */\n cwd?: string;\n /** Injectable clock for deterministic tests. */\n now?: () => number;\n /** Injectable ISO timestamp source for manifest bookkeeping. */\n isoNow?: () => string;\n}\n\nexport function createMind(\n services: MindServices,\n config: MindConfig,\n options: CreateMindOptions = {},\n): Mind {\n const now = options.now ?? (() => Date.now());\n const isoNow = options.isoNow ?? (() => new Date(now()).toISOString());\n const cwd = options.cwd ?? process.cwd();\n\n function resolveIndexId(indexId?: string): string {\n return indexId && indexId.trim() !== '' ? indexId : config.defaultIndex;\n }\n\n function syncOpts(indexId: string): SyncOptions {\n const eff = effectiveIndexConfig(config, indexId);\n return {\n indexId,\n cwd,\n chunk: { maxTokens: eff.chunk.maxTokens, overlapTokens: eff.chunk.overlapTokens },\n ast: eff.chunk.ast,\n now: isoNow(),\n };\n }\n\n return {\n async index(req, onProgress): Promise<IndexResponse> {\n const indexId = resolveIndexId(req.indexId);\n const eff = effectiveIndexConfig(config, indexId);\n const start = now();\n const result = await ingest(\n {\n indexId,\n cwd,\n // CLI `--scope` overrides the include set (keeping configured excludes);\n // otherwise use the index's configured include/exclude scope.\n scope: req.scope ? { include: [req.scope], exclude: eff.scope.exclude } : eff.scope,\n full: req.full,\n chunk: { maxTokens: eff.chunk.maxTokens, overlapTokens: eff.chunk.overlapTokens },\n ast: eff.chunk.ast,\n now: isoNow(),\n onProgress,\n },\n services,\n );\n const durationMs = now() - start;\n services.logger?.info('mind: index', {\n indexId,\n filesIndexed: result.filesIndexed,\n chunks: result.chunks,\n added: result.added,\n updated: result.updated,\n removed: result.removed,\n unchanged: result.unchanged,\n durationMs,\n });\n return { indexId, filesIndexed: result.filesIndexed, chunks: result.chunks, durationMs };\n },\n\n async search(req): Promise<SearchResponse> {\n const indexId = resolveIndexId(req.indexId);\n const retrieval = effectiveIndexConfig(config, indexId).retrieval;\n const limit = req.limit ?? retrieval.limit;\n const snippet = req.snippet ?? 'line';\n const t0 = now();\n\n // Over-fetch, then refine: retrieve -> rerank -> dedup.\n const retrieved = await retrieve(\n { text: req.text, indexId, limit: limit * 3, intent: req.intent, rrfK: retrieval.rrfK, hyde: retrieval.hyde, expand: retrieval.expand },\n services,\n );\n let ranked = retrieval.rerank ? rerank(retrieved.ranked, req.text) : retrieved.ranked;\n if (retrieval.dedup) {\n ranked = dedupRanked(ranked);\n }\n ranked = ranked.slice(0, limit);\n\n // Per-result freshness for the returned files only (bounded cost).\n const manifest = await loadManifest(services.storage, indexId);\n const stales = await staleMap(manifest, ranked.map((r) => r.chunk.path), cwd);\n const results = toSearchResults(ranked, { snippet, staleByFile: stales });\n const staleCount = [...stales.values()].filter(Boolean).length;\n const timingMs = now() - t0;\n\n services.logger?.info('mind: search', {\n indexId,\n results: results.length,\n semanticWinRate: retrieved.semanticWinRate,\n staleCount,\n timingMs,\n });\n return {\n results,\n confidence: retrieved.confidence,\n indexId,\n meta: { requestId: `mind:${t0}`, timingMs, semanticWinRate: retrieved.semanticWinRate, staleCount },\n };\n },\n\n async ask(req): Promise<AgentResponse> {\n const indexId = resolveIndexId(req.indexId);\n const retrieval = effectiveIndexConfig(config, indexId).retrieval;\n const mode: AgentQueryMode = req.mode ?? 'auto';\n const budget = config.modes[mode];\n const t0 = now();\n\n // Feedback: record the query (best-effort).\n await recordQuery(services.cache, indexId, req.text, t0);\n\n // Decompose into sub-queries for richer modes; always retains the original.\n const queries = budget.useLLM\n ? await decompose(req.text, services.llm, budget.maxSubqueries)\n : [req.text];\n\n // Gather across sub-queries, merging by chunk id (keep best score).\n const merged = new Map<string, RankedChunk>();\n let retrievalConfidence = 0;\n for (const q of queries) {\n const r = await retrieve(\n { text: q, indexId, limit: budget.maxChunks, intent: undefined, rrfK: retrieval.rrfK, hyde: retrieval.hyde, expand: retrieval.expand },\n services,\n );\n retrievalConfidence = Math.max(retrievalConfidence, r.confidence);\n for (const rc of r.ranked) {\n const prev = merged.get(rc.chunk.id);\n if (!prev || rc.score > prev.score) {\n merged.set(rc.chunk.id, rc);\n }\n }\n }\n\n let ranked = retrieval.rerank\n ? rerank([...merged.values()], req.text)\n : [...merged.values()].sort((a, b) => b.score - a.score);\n if (retrieval.dedup) {\n ranked = dedupRanked(ranked);\n }\n ranked = ranked.slice(0, budget.maxChunks);\n\n const verification = await verifySources(ranked, services.storage);\n const base = computeConfidence(retrievalConfidence, verification.rate, config.confidence.floor);\n\n const answer = await synthesizeAnswer(req.text, ranked, services.llm, budget.useLLM);\n\n // Field-check (anti-hallucination): symbols the answer names must exist in\n // the retrieved sources. Ungrounded terms penalise confidence and warn.\n const { confidence, warnings } = budget.useLLM\n ? applyFieldCheck(answer, ranked, base.confidence, base.warnings, config.confidence.floor)\n : base;\n\n const manifest = await loadManifest(services.storage, indexId);\n const staleByFile = await staleMap(manifest, ranked.map((r) => r.chunk.path), cwd);\n\n const timingMs = now() - t0;\n services.logger?.info('mind: ask', {\n indexId,\n mode,\n subqueries: queries.length,\n chunks: ranked.length,\n confidence: Math.round(confidence * 1000) / 1000,\n timingMs,\n });\n return buildAgentResponse({\n answer,\n ranked,\n confidence,\n mode,\n requestId: `mind:${t0}`,\n timingMs,\n indexId,\n floor: config.confidence.floor,\n snippet: req.snippet ?? 'line',\n staleByFile,\n warnings,\n });\n },\n\n async explore(req): Promise<ExploreResponse> {\n const indexId = resolveIndexId(req.indexId);\n const retrieval = effectiveIndexConfig(config, indexId).retrieval;\n // A map is a wider view than a search; the model decides what to open.\n const budget = config.modes.auto;\n const limit = req.limit ?? retrieval.limit;\n const t0 = now();\n\n // Over-fetch with an architecture lens, then refine: retrieve -> rerank -> dedup.\n const retrieved = await retrieve(\n { text: req.task, indexId, limit: limit * 3, intent: 'architecture', rrfK: retrieval.rrfK, hyde: retrieval.hyde, expand: retrieval.expand },\n services,\n );\n let ranked = retrieval.rerank ? rerank(retrieved.ranked, req.task) : retrieved.ranked;\n if (retrieval.dedup) {\n ranked = dedupRanked(ranked);\n }\n ranked = ranked.slice(0, limit);\n\n const manifest = await loadManifest(services.storage, indexId);\n const stales = await staleMap(manifest, ranked.map((r) => r.chunk.path), cwd);\n const files = toExploreEntries(ranked, stales);\n const spread = spreadOf(files.map((f) => f.file));\n const summary = await orientationSummary(req.task, files, services.llm, budget.useLLM);\n const timingMs = now() - t0;\n\n services.logger?.info('mind: explore', {\n indexId,\n filesTouched: files.length,\n spread,\n timingMs,\n });\n return {\n task: req.task,\n indexId,\n confidence: retrieved.confidence,\n summary,\n files,\n meta: { requestId: `mind:${t0}`, timingMs, filesTouched: files.length, spread },\n };\n },\n\n async reindex(req): Promise<IndexResponse> {\n return this.index({ indexId: req.indexId, full: true });\n },\n\n async drop(req): Promise<DropResponse> {\n const indexId = resolveIndexId(req.indexId);\n if (!(await manifestExists(services.storage, indexId))) {\n throw new Error(`No such index \"${indexId}\" — nothing to drop (run \\`kb mind status\\` to list indexes).`);\n }\n const manifest = await loadManifest(services.storage, indexId);\n const ids = manifest.chunks.map((c) => c.id);\n const droppedFiles = Object.keys(manifest.files).length;\n // Remove vectors in batches (large indexes have tens of thousands of ids).\n const BATCH = 500;\n for (let i = 0; i < ids.length; i += BATCH) {\n await services.vectorStore.delete(ids.slice(i, i + BATCH), indexId);\n }\n await deleteManifest(services.storage, indexId);\n services.logger?.info('mind: drop', { indexId, droppedChunks: ids.length, droppedFiles });\n return { indexId, droppedChunks: ids.length, droppedFiles };\n },\n\n async syncAdd(paths, indexId): Promise<SyncResponse> {\n const id = resolveIndexId(indexId);\n const counts = await syncAdd(paths, services, syncOpts(id));\n return { indexId: id, ...counts };\n },\n\n async syncUpdate(paths, indexId): Promise<SyncResponse> {\n const id = resolveIndexId(indexId);\n const counts = await syncUpdate(paths, services, syncOpts(id));\n return { indexId: id, ...counts };\n },\n\n async syncDelete(paths, indexId): Promise<SyncResponse> {\n const id = resolveIndexId(indexId);\n const counts = await syncDelete(paths, services, syncOpts(id));\n return { indexId: id, ...counts };\n },\n\n async syncList(indexId): Promise<SyncListResponse> {\n const id = resolveIndexId(indexId);\n const manifest = await loadManifest(services.storage, id);\n return {\n indexId: id,\n documents: Object.entries(manifest.files).map(([path, info]) => ({\n path,\n chunks: info.chunks,\n indexedAt: info.indexedAt,\n })),\n };\n },\n\n async syncStatus(indexId): Promise<SyncStatusResponse> {\n const id = resolveIndexId(indexId);\n const manifest = await loadManifest(services.storage, id);\n return {\n indexId: id,\n documents: Object.keys(manifest.files).length,\n chunks: manifest.chunks.length,\n lastIndexedAt: manifest.updatedAt,\n stale: false,\n };\n },\n\n async status(indexId): Promise<StatusResponse> {\n // Show every CONFIGURED index (even if not yet built) plus any built ones,\n // so an agent can see which corpora/scopes the project offers.\n const ids = indexId\n ? [indexId]\n : [...new Set([...Object.keys(config.indexes), ...(await listIndexIds(services))])];\n const indexes: IndexSummary[] = [];\n for (const id of ids) {\n const manifest = await loadManifest(services.storage, id);\n const declared = config.indexes[id];\n const sc = resolveScope(declared?.scope);\n const coverage =\n sc.include.join(', ') + (sc.exclude.length ? ` · excl ${sc.exclude.join(', ')}` : '');\n indexes.push({\n indexId: id,\n label: declared?.label,\n coverage,\n documents: Object.keys(manifest.files).length,\n chunks: manifest.chunks.length,\n lastIndexedAt: manifest.updatedAt,\n staleCount: await staleCount(manifest, cwd),\n });\n }\n return { indexes, healthy: true };\n },\n\n async health(): Promise<HealthResponse> {\n return {\n ok: true,\n vectorStore: Boolean(services.vectorStore),\n embeddings: Boolean(services.embeddings),\n llm: Boolean(services.llm),\n };\n },\n };\n}\n\n/** Enumerate index ids by scanning persisted manifests under `mind/`. */\nasync function listIndexIds(services: MindServices): Promise<string[]> {\n const paths = await services.storage.list('mind/');\n const ids = new Set<string>();\n for (const p of paths) {\n const match = /^mind\\/([^/]+)\\/manifest\\.json$/.exec(p);\n if (match) {\n ids.add(match[1]!);\n }\n }\n return [...ids];\n}\n","/**\n * Pipeline primitive.\n *\n * Every stage is a pure function `(input, services) => output`. A `Tracer`\n * times each stage and collects `StageTrace` entries so the full query flow\n * (retrieve → fuse → rerank → verify → compress → synthesize) is observable.\n * Modes (instant/auto/thinking) are just configs deciding which stages run —\n * never separate code paths.\n */\n\nimport type { StageTrace, Trace } from '@kb-labs/mind-contracts';\nimport type { MindServices } from './services';\n\nexport type Stage<I, O> = (input: I, services: MindServices) => Promise<O>;\n\n/** Monotonic clock; injectable so tests stay deterministic. */\nexport type Clock = () => number;\n\nconst defaultClock: Clock = () => Date.now();\n\n/**\n * Collects per-stage traces for one request. `run` times a stage and records\n * its duration + output size.\n */\nexport class Tracer {\n private readonly stages: StageTrace[] = [];\n\n constructor(\n private readonly requestId: string,\n private readonly mode: string,\n private readonly clock: Clock = defaultClock,\n ) {}\n\n async run<I, O>(stage: string, input: I, services: MindServices, fn: Stage<I, O>): Promise<O> {\n const start = this.clock();\n const output = await fn(input, services);\n this.stages.push({\n stage,\n durationMs: this.clock() - start,\n outputCount: Array.isArray(output) ? output.length : undefined,\n });\n return output;\n }\n\n /** Record a stage trace manually (for stages not wrapped by `run`). */\n record(trace: StageTrace): void {\n this.stages.push(trace);\n }\n\n build(totalMs: number): Trace {\n return {\n requestId: this.requestId,\n mode: this.mode,\n totalMs,\n stages: [...this.stages],\n };\n }\n}\n"]}
@@ -0,0 +1,14 @@
1
+ import { PlatformServices } from '@kb-labs/sdk';
2
+
3
+ /**
4
+ * Platform services Mind consumes.
5
+ *
6
+ * No custom ports, no platform internals — just a narrow slice of
7
+ * `PlatformServices` from `@kb-labs/sdk`. The engine never knows which concrete
8
+ * adapter (Qdrant, in-memory, …) sits behind these interfaces; `entry` passes
9
+ * `ctx.platform` straight through, tests pass `createTestContext().platform`.
10
+ */
11
+
12
+ type MindServices = Pick<PlatformServices, 'vectorStore' | 'embeddings' | 'llm' | 'cache' | 'storage' | 'logger'>;
13
+
14
+ export type { MindServices as M };
@@ -0,0 +1,68 @@
1
+ import { M as MindServices } from './services-CdtgGHNc.js';
2
+ import { IEmbeddings, IStorage, IVectorStore, ILLM } from '@kb-labs/sdk';
3
+ import { VectorFilter, VectorSearchResult, VectorRecord } from '@kb-labs/sdk/adapters';
4
+
5
+ /**
6
+ * Functional in-memory test harness for the engine.
7
+ *
8
+ * `@kb-labs/sdk/testing`'s `createTestContext` returns *mock* platform services
9
+ * (empty/noop) — fine for handler wiring, useless for exercising retrieval.
10
+ * This harness provides REAL behaviour: a deterministic bag-of-words embedder
11
+ * and working in-memory vector store / storage, so ingest+retrieve and
12
+ * namespace isolation can be tested end-to-end without a daemon or network.
13
+ *
14
+ * Imports only types from `@kb-labs/sdk`; the implementations are local.
15
+ */
16
+
17
+ /** Deterministic bag-of-words embedder: shared tokens → higher cosine similarity. */
18
+ declare class DeterministicEmbedder implements IEmbeddings {
19
+ readonly dimensions = 64;
20
+ /** Number of texts embedded — lets tests assert delta re-indexing skips work. */
21
+ embedCount: number;
22
+ embed(text: string): Promise<number[]>;
23
+ embedBatch(texts: string[]): Promise<number[][]>;
24
+ getDimensions(): Promise<number>;
25
+ }
26
+ /** Minimal namespace-partitioned in-memory vector store (mirrors platform semantics). */
27
+ declare class TestVectorStore implements IVectorStore {
28
+ private ns;
29
+ private part;
30
+ search(query: number[], limit: number, _filter?: VectorFilter, namespace?: string): Promise<VectorSearchResult[]>;
31
+ upsert(vectors: VectorRecord[], namespace?: string): Promise<void>;
32
+ delete(ids: string[], namespace?: string): Promise<void>;
33
+ count(namespace?: string): Promise<number>;
34
+ query(_filter: VectorFilter, namespace?: string): Promise<VectorRecord[]>;
35
+ }
36
+ /** Minimal in-memory storage with prefix listing. */
37
+ declare class TestStorage implements IStorage {
38
+ private files;
39
+ seed(path: string, content: string): void;
40
+ read(path: string): Promise<Buffer | null>;
41
+ write(path: string, data: Buffer): Promise<void>;
42
+ delete(path: string): Promise<void>;
43
+ list(prefix: string): Promise<string[]>;
44
+ exists(path: string): Promise<boolean>;
45
+ }
46
+ /** Scripted LLM that returns a fixed completion — for testing agent synthesis. */
47
+ declare function makeScriptedLLM(content: string): ILLM;
48
+ interface TestServices extends MindServices {
49
+ storage: TestStorage;
50
+ vectorStore: TestVectorStore;
51
+ }
52
+ /** Build functional in-memory `MindServices` for engine tests. */
53
+ declare function makeTestServices(overrides?: Partial<MindServices>): TestServices;
54
+ interface TestWorkspace {
55
+ /** Workspace root (a real temp dir) — pass as `createMind(..., { cwd })`. */
56
+ cwd: string;
57
+ /** In-memory services (vector store + manifest storage). */
58
+ services: TestServices;
59
+ }
60
+ /**
61
+ * Materialize source files on disk (a temp dir) so the engine exercises its
62
+ * REAL discovery (globby + fs + ignores) instead of in-memory seeding — this is
63
+ * what catches discovery bugs (e.g. node_modules recursion). The vector store
64
+ * and manifest stay in-memory via `makeTestServices`.
65
+ */
66
+ declare function makeTestWorkspace(files: Record<string, string>, overrides?: Partial<MindServices>): TestWorkspace;
67
+
68
+ export { DeterministicEmbedder, type TestServices, TestStorage, TestVectorStore, type TestWorkspace, makeScriptedLLM, makeTestServices, makeTestWorkspace };