import { ContentType, KnowledgeOrigin, TokenBudget } from "../../core/dist/index.js"; import { IEmbedder } from "../../embeddings/dist/index.js"; import { DepthGroupedResult, GraphEdge, GraphNode, GraphStats as GraphStats$1, GraphTraversalResult, GraphValidationResult, IGraphStore, IKnowledgeStore, ProcessInfo, Symbol360 } from "../../store/dist/index.js"; //#region packages/tools/src/response-envelope.d.ts interface AikitNextHint { tool: string; reason: string; suggested_args?: Record; } interface AikitToolError { code: AikitToolErrorCode; category: 'input' | 'runtime' | 'dependency' | 'timeout' | 'not_found'; retryable: boolean; message: string; suggestion?: string; } type AikitToolErrorCode = 'SYMBOL_NOT_FOUND' | 'INDEX_STALE' | 'TREE_SITTER_UNAVAILABLE' | 'PARSE_FAILED' | 'BUDGET_EXCEEDED' | 'PATH_NOT_FOUND' | 'EMBEDDING_COLD_START' | 'ANALYSIS_FAILED'; interface AikitResponseMeta { durationMs: number; tokensEstimate: number; detail: TokenBudget; cached: boolean; truncated: boolean; caveats?: string[]; } interface AikitResponse { ok: boolean; tool: string; summary: string; data?: T; meta: AikitResponseMeta; next?: AikitNextHint[]; error?: AikitToolError; } /** Create a success response. */ declare function okResponse(tool: string, summary: string, data: T, meta: Partial & { durationMs: number; }, next?: AikitNextHint[]): AikitResponse; /** Create an error response. */ declare function errorResponse(tool: string, error: AikitToolError, durationMs: number): AikitResponse; //#endregion //#region packages/tools/src/audit.d.ts type AuditCheck = 'structure' | 'dependencies' | 'patterns' | 'health' | 'dead_symbols' | 'check' | 'entry_points'; interface AuditOptions { /** Root path to audit (default: cwd) */ path?: string; /** Which checks to run (default: all) */ checks?: AuditCheck[]; /** Detail level (default: 'efficient') */ detail?: TokenBudget; } interface AuditRecommendation { priority: 'high' | 'medium' | 'low'; area: string; message: string; } interface AuditData { score: number; structure?: { files: number; packages: number; languages: Record; }; dependencies?: { external: number; internal: number; }; patterns?: Array<{ name: string; confidence: string; count: number; }>; health?: { score: number; checks: number; passed: number; warned: number; failed: number; }; deadSymbols?: { source: number; docs: number; }; entryPoints?: { total: number; types: Record; }; typecheck?: { passed: boolean; errorCount: number; topErrors: string[]; }; lint?: { passed: boolean; errorCount: number; topErrors: string[]; }; recommendations: AuditRecommendation[]; } declare function audit(store: IKnowledgeStore, embedder: IEmbedder, options?: AuditOptions): Promise>; //#endregion //#region packages/tools/src/briefing-card-compiler.d.ts /** * Briefing Card Compiler — L0 card management utility. * * This module provides runtime path resolution and card metadata for L0 * generated briefing cards. It is an INTERNAL tool (not an MCP tool) — * agents access L0 cards through enhanced existing tools (stratum_card, * compact, status). * * Card storage path is resolved from server config (AikitConfig.l0CardDir) * which defaults to AIKIT_RUNTIME_PATHS.l0Cards ('memories') under the * workspace partition root (~/.aikit/workspaces//). * * Scaffold instructions reference the TOOLS that serve L0 cards (stratum_card, * compact, status), not the raw filesystem path. * * @module */ /** * Known L0 briefing card families. Each family covers a specific workspace * knowledge domain and has an associated token budget range. */ declare const BRIEFING_CARD_FAMILIES: readonly [{ readonly type: "workspace-core"; readonly description: "Durable repo facts, tool surfaces, and session rules"; readonly minTokens: 800; readonly maxTokens: 1200; readonly loadAtSessionStart: true; }, { readonly type: "architecture"; readonly description: "Package boundaries and major data flows"; readonly minTokens: 600; readonly maxTokens: 900; readonly loadAtSessionStart: false; }, { readonly type: "testing-release"; readonly description: "Release gates and high-value verification steps"; readonly minTokens: 600; readonly maxTokens: 900; readonly loadAtSessionStart: false; }, { readonly type: "known-issues"; readonly description: "Verified failures and recurring hazards"; readonly minTokens: 400; readonly maxTokens: 700; readonly loadAtSessionStart: false; }, { readonly type: "workflow:*"; readonly description: "Active flow lineage and current task context"; readonly minTokens: 500; readonly maxTokens: 900; readonly loadAtSessionStart: false; }]; /** * Resolve the L0 card storage directory for a workspace partition. * * At runtime, the server resolves `AikitConfig.l0CardDir` via * `applyPartitionRuntimeLayout()`. This function provides the same * resolution for tool-level consumers. * * @param partitionRoot - Absolute path to the workspace partition root * @param l0CardDir - Config override, or default subdirectory name * @returns Absolute path to the L0 card storage directory */ declare function resolveL0CardDir(partitionRoot: string, l0CardDir?: string): string; /** * Describe the available card families and token budgets. * Returns a structured descriptor that the MCP layer can render into * tool responses or status prelude output. */ declare function describeBriefingCards(): { families: Array<{ type: string; description: string; minTokens: number; maxTokens: number; loadAtSessionStart: boolean; }>; sessionBudget: number; storageHint: string; }; /** * Card selection result for session start. * * Per layered knowledge protocol: * - \`workspace-core\` is ALWAYS loaded. * - If a flow is active → load \`workflow:\` as the second card (NOT a task card). * - If NO flow → optionally load one task-dependent card (architecture, testing-release, * or known-issues). The second slot is null when the caller should determine based * on the current task. * - Never load both a task card and a flow card. * - Total budget ≤ 2,100 tokens. */ interface SessionStartSelection { /** Always \`workspace-core\` */ cards: string[]; /** Human-readable rationale for the selection */ rationale: string; } /** * Get the recommended card selection for session start. * * @param activeFlowSlug - Active flow slug (if any). When set, workflow card replaces task card. * @returns Selection with primary + optional secondary card */ declare function getSessionStartCards(activeFlowSlug?: string): SessionStartSelection; /** * Estimate token budget for a session start card set. * Returns null if the set exceeds 2,100 tokens. */ /** Name of the workspace-core L0 card file. */ declare const WORKSPACE_CORE_FILENAME = "workspace-core.md"; /** Maximum characters for a generated L0 card (≈1,200 tokens × 4 chars/token). */ declare const MAX_CARD_CHARS = 4800; /** * Input data for generating a workspace-core L0 briefing card. */ interface L0CardInput { /** Workspace root path or name */ workspaceName: string; /** Structure analysis output (compact) */ structure?: string; /** Entry points analysis output */ entryPoints?: string; /** Dependencies analysis output */ dependencies?: string; /** Key symbols (comma-separated) */ symbols?: string; } /** * Generate a workspace-core L0 briefing card from analysis baselines. * Card is compact markdown ≤1,200 tokens. * * @param input - Analysis data to compress into the card * @returns Card content as markdown string */ declare function generateL0WorkspaceCoreCard(input: L0CardInput): string; declare function estimateSessionTokenBudget(cards: string[]): number | null; //#endregion //#region packages/tools/src/changelog.d.ts /** * aikit_changelog — Generate a changelog from git history. */ type ChangelogFormat = 'grouped' | 'chronological' | 'per-scope'; interface ChangelogOptions { from: string; to?: string; format?: ChangelogFormat; includeBreaking?: boolean; cwd?: string; } interface ChangelogEntry { hash: string; type: string; scope: string; subject: string; body: string; author: string; date: string; breaking: boolean; } interface ChangelogResult { entries: ChangelogEntry[]; markdown: string; stats: { total: number; breaking: number; types: Record; }; } declare function changelog(options: ChangelogOptions): ChangelogResult; /** Exported for testing */ declare function formatChangelog(entries: ChangelogEntry[], format: ChangelogFormat, includeBreaking: boolean): string; //#endregion //#region packages/tools/src/parse-output.d.ts /** * aikit_parse_output — Structured parsers for common build tool output. * * Converts noisy text output from tsc, vitest, biome, and git status * into structured JSON that LLM agents can act on directly. */ interface ParsedError { file: string; line?: number; column?: number; severity: 'error' | 'warning' | 'info'; code?: string; message: string; } interface ParsedTestResult { name: string; file?: string; status: 'pass' | 'fail' | 'skip'; duration?: number; error?: string; } interface ParsedTestSummary { tests: ParsedTestResult[]; passed: number; failed: number; skipped: number; duration?: number; suites?: number; } interface ParsedGitStatus { staged: Array<{ status: string; file: string; }>; unstaged: Array<{ status: string; file: string; }>; untracked: string[]; branch?: string; } type ParsedOutput = { tool: 'tsc'; errors: ParsedError[]; } | { tool: 'vitest'; summary: ParsedTestSummary; } | { tool: 'biome'; errors: ParsedError[]; } | { tool: 'git-status'; status: ParsedGitStatus; }; /** * Parse `tsc` output into structured errors. * * Example line: `src/foo.ts(10,5): error TS2339: Property 'x' does not exist` */ declare function parseTsc(output: string): ParsedError[]; /** * Parse vitest run output into structured test results. */ declare function parseVitest(output: string): ParsedTestSummary; /** * Parse biome check/lint output into structured errors. * * Example: `src/foo.ts:10:5 lint/suspicious/noDoubleEquals ━━━` * ` × Use === instead of ==` */ declare function parseBiome(output: string): ParsedError[]; /** * Parse `git status --porcelain=v1 -b` output into structured status. */ declare function parseGitStatus(output: string): ParsedGitStatus; /** * Auto-detect the tool from output content and parse accordingly. */ declare function parseOutput(output: string, tool?: string): ParsedOutput; //#endregion //#region packages/tools/src/check.d.ts interface CheckOptions { /** Specific files to check (if empty, checks all) */ files?: string[]; /** Working directory */ cwd?: string; /** Skip typecheck */ skipTypes?: boolean; /** Skip lint */ skipLint?: boolean; /** Detail level: efficient (default, minimal), normal (parsed errors), full (includes raw) */ detail?: TokenBudget; } interface CheckSummaryResult { passed: boolean; tsc: { passed: boolean; errorCount: number; warningCount: number; topErrors: string[]; }; biome: { passed: boolean; errorCount: number; warningCount: number; topErrors: string[]; }; } interface CheckResult { tsc: { errors: ParsedError[]; passed: boolean; raw?: string; }; biome: { errors: ParsedError[]; passed: boolean; raw?: string; }; passed: boolean; } declare function check(options?: CheckOptions): Promise; /** Produce a minimal summary for LLM consumption (~300 tokens) */ declare function summarizeCheckResult(result: CheckResult): CheckSummaryResult; //#endregion //#region packages/tools/src/checkpoint.d.ts interface Checkpoint { id: string; label: string; createdAt: string; data: Record; notes?: string; } interface CheckpointSummary { id: string; label: string; createdAt: string; notes?: string; } interface CheckpointStore { checkpointSave(id: string, label: string, data: string, notes?: string): void; checkpointLoad(id: string): { id: string; label: string; data: string; notes?: string; createdAt: string; } | undefined; checkpointList(label?: string, limit?: number): CheckpointSummary[]; checkpointLatest(label?: string): { id: string; label: string; data: string; notes?: string; createdAt: string; } | undefined; checkpointDelete(id: string): boolean; checkpointDiff(fromId: string, toId: string): { from: string; to: string; } | undefined; checkpointHistory(label?: string, limit?: number): CheckpointSummary[]; checkpointGc(keepLast?: number, maxAgeDays?: number): number; } interface LegacyCheckpointOptions { cwd?: string; stateDir?: string; } declare function checkpointSave(stateStore: CheckpointStore, label: string, data: Record, options?: { notes?: string; cwd?: string; }): Checkpoint; declare function checkpointLoad(stateStore: CheckpointStore, id: string, options?: LegacyCheckpointOptions): Checkpoint | undefined; declare function checkpointList(stateStore: CheckpointStore, options?: LegacyCheckpointOptions & { label?: string; limit?: number; }): CheckpointSummary[]; declare function checkpointLatest(stateStore: CheckpointStore, options?: LegacyCheckpointOptions & { label?: string; }): Checkpoint | undefined; declare function checkpointDiff(stateStore: CheckpointStore, fromId: string, toId: string, options?: LegacyCheckpointOptions): { fromId: string; toId: string; added: string[]; removed: string[]; modified: string[]; } | undefined; declare function checkpointHistory(stateStore: CheckpointStore, label: string, options?: { cwd?: string; limit?: number; }): CheckpointSummary[]; declare function checkpointGC(stateStore: CheckpointStore, options?: { label?: string; keepLast?: number; maxAgeDays?: number; dryRun?: boolean; cwd?: string; }): { deleted: number; kept: number; labels: string[]; deletedIds: string[]; }; //#endregion //#region packages/tools/src/codemod.d.ts interface CodemodRule { /** Description of what this rule does */ description: string; /** Regex pattern to match (string form, will be compiled) */ pattern: string; /** Replacement string (supports $1, $2 capture groups) */ replacement: string; /** Optional: only apply to files matching this glob */ fileFilter?: string; } interface CodemodOptions { /** Root directory to apply codemod in */ rootPath: string; /** Rules to apply */ rules: CodemodRule[]; /** File extensions to process */ extensions?: string[]; /** Exclude patterns */ exclude?: string[]; /** Dry run */ dryRun?: boolean; } interface CodemodChange { rule: string; path: string; line: number; before: string; after: string; } interface CodemodResult { changes: CodemodChange[]; rulesApplied: number; filesModified: number; dryRun: boolean; } declare function codemod(options: CodemodOptions): Promise; //#endregion //#region packages/tools/src/file-cache.d.ts interface FileCacheEntry { /** Full file content */ content: string; /** SHA-256 hash of content */ hash: string; /** Line count */ lines: number; /** Estimated token count (~chars/4) */ estimatedTokens: number; /** How many times this file has been requested */ hitCount: number; /** Whether content changed since last read (false on cache hit) */ changed: boolean; } interface FileCacheStats { totalReads: number; cacheHits: number; filesTracked: number; } declare class FileCache { private cache; private totalReads; private cacheHits; private static readonly MAX_ENTRIES; /** * Get file content with deduplication. * First call: reads from disk, hashes, caches. * Subsequent calls: checks mtime → if unchanged, cache hit (skip read). * If mtime changed: re-reads, re-hashes, checks if content actually changed. */ get(filePath: string): Promise; /** Remove a single file from cache. Returns true if it was cached. */ invalidate(filePath: string): boolean; /** Clear all cached files. Returns how many were cleared. */ clear(): number; /** Get cache statistics. */ stats(): FileCacheStats; } interface ExtractionCacheEntry { /** Cache schema version for compatibility checks */ schema_version: number; /** SHA256 hash of source file content */ contentHash: string; /** Extraction result as serializable data */ data: Record; /** When this entry was created */ createdAt: string; /** File size at extraction time */ fileSize: number; /** Extraction duration in ms */ durationMs: number; } declare class ExtractionCache { private cacheDir; constructor(cacheDir: string); /** * Get cached extraction result for a file. * Returns null if cache version mismatch, content changed, or no cache exists. */ get(_filePath: string, contentHash: string): Promise; /** * Save extraction result to cache. */ set(_filePath: string, contentHash: string, data: Record, fileSize: number, durationMs: number): Promise; /** Get total number of cached entries */ size(): Promise; } //#endregion //#region packages/tools/src/compact.d.ts type CompactInputOptions = { /** The text to compress. */text: string; /** The focus query — what are we trying to understand? */ query: string; path?: never; ref?: never; } | { /** File path to read server-side — avoids read_file round-trip. */path: string; /** The focus query — what are we trying to understand? */ query: string; text?: never; ref?: never; } | { /** Cached reversible ref from compact/digest/search/find/knowledge output. */ref: string; /** Optional focus query when re-compacting a cached artifact. */ query?: string; text?: never; path?: never; }; interface CompactSharedOptions { /** Target output size in characters (default: 3000) */ maxChars?: number; /** Token budget — when set, overrides maxChars (approx 4 chars per token) */ tokenBudget?: number; /** Minimum similarity score to include a segment (0-1, default: 0.3) */ minScore?: number; /** Segmentation strategy (default: 'paragraph') */ segmentation?: 'paragraph' | 'sentence' | 'line'; /** Optional file cache — use cached content instead of raw readFile */ cache?: FileCache; /** Internal: disable reversible ref storage when reusing cached artifacts. */ storeReference?: boolean; /** * Content delivery mode: * - 'full' (default): Return compressed text as normal * - 'delta': Return only changes since last read (for re-reads of same file) */ mode?: 'full' | 'delta'; } type CompactOptions = CompactInputOptions & CompactSharedOptions; interface CompactResult { /** The compressed text */ text: string; /** Reusable cache reference */ ref?: string; /** Original size in chars */ originalChars: number; /** Compressed size in chars */ compressedChars: number; /** Compression ratio (0-1, lower = more compressed) */ ratio: number; /** Number of segments kept / total */ segmentsKept: number; segmentsTotal: number; } /** * Compress text by extracting segments most relevant to a query. */ declare function compact(embedder: IEmbedder, options: CompactOptions): Promise; //#endregion //#region packages/tools/src/replay.d.ts /** * Replay — append-only audit trail of tool/CLI invocations. * * Captures tool name, arguments (redacted), duration, and result summary * to the AI Kit state directory replay log. Used by `aikit replay` CLI, `aikit_replay` MCP tool, * and the TUI log panel. */ interface ReplayEntry { /** ISO timestamp */ ts: string; /** Source: 'mcp' | 'cli' */ source: 'mcp' | 'cli'; /** Tool or command name */ tool: string; /** Redacted input summary (first 2000 chars of JSON) */ input: string; /** Duration in milliseconds */ durationMs: number; /** Result status */ status: 'ok' | 'error'; /** Short result summary (first 2000 chars) */ output: string; /** Correlation ID linking to middleware requestId */ traceId: string; /** Original output size in characters before truncation */ outputChars: number; /** Original input size in characters before truncation */ inputChars: number; } interface ReplayOptions { /** Max entries to return (default: 20) */ last?: number; /** Filter by tool name */ tool?: string; /** Filter by source */ source?: 'mcp' | 'cli'; /** Filter entries after this ISO timestamp */ since?: string; } /** * Append a replay entry to the audit log. * Creates the state directory if it doesn't exist. */ declare function replayAppend(entry: ReplayEntry): void; /** * Read replay entries with optional filters. */ declare function replayList(opts?: ReplayOptions): ReplayEntry[]; /** * Trim the replay log to MAX_ENTRIES, keeping the most recent. * Async to avoid blocking the event loop on large logs. */ declare function replayTrim(): Promise; /** * Clear the entire replay log. */ declare function replayClear(): void; /** * Helper: create a replay entry from a tool invocation. * Use as a wrapper around tool execution. */ declare function replayCapture(source: 'mcp' | 'cli', tool: string, input: unknown, fn: () => Promise, traceId?: string): Promise; //#endregion //#region packages/tools/src/compliance-scorer.d.ts interface ComplianceViolation { rule: string; ruleId: string; tool: string; timestamp: string; suggestion: string; } interface ComplianceReport { score: number; violations: ComplianceViolation[]; totalCalls: number; summary: string; } interface ComplianceRule { id: string; description: string; check: (entry: ReplayEntry) => ComplianceViolation | null; } interface ComplianceScoreOptions { lastN?: number; } declare function scoreCompliance(entries: ReplayEntry[], options?: ComplianceScoreOptions): ComplianceReport; //#endregion //#region packages/tools/src/compression/types.d.ts /** * Compression mode determines how aggressively output is compressed. */ type CompressionMode = 'structural' | 'heuristic' | 'aggressive'; /** * Context provided to compression rules for matching and processing. */ interface CompressionContext { /** Raw output text (ANSI already stripped) */ text: string; /** Detected tool/source (e.g., 'git', 'npm', 'vitest', 'docker') */ tool: string; /** Compression mode */ mode: CompressionMode; /** Maximum output characters */ maxChars: number; /** Original character count before any processing */ originalChars: number; } /** * Result from applying a compression rule. */ interface CompressionResult { /** Compressed text */ text: string; /** Original character count */ originalChars: number; /** Compressed character count */ compressedChars: number; /** Compression ratio (compressed / original) */ ratio: number; /** Which rule was applied */ rule: string; /** Detected tool */ tool: string; /** Metadata about the compression */ _meta: { truncated: boolean; mode: CompressionMode; sectionsKept?: number; sectionsTotal?: number; }; } /** * A compression rule that can match and process specific output formats. */ interface CompressionRule { /** Unique rule name */ name: string; /** Tool patterns this rule handles (regex or string) */ toolPatterns: (string | RegExp)[]; /** Priority (higher = checked first, default 0) */ priority: number; /** Test if this rule can handle the given context */ match(ctx: CompressionContext): boolean; /** Apply compression and return result text */ compress(ctx: CompressionContext): string; } //#endregion //#region packages/tools/src/compression/engine.d.ts /** * Register a compression rule. Rules are auto-sorted by priority (highest first). */ declare function registerRule(rule: CompressionRule): void; /** * Register multiple compression rules at once. */ declare function registerRules(newRules: CompressionRule[]): void; /** * Get all registered rules (for testing/inspection). */ declare function getRegisteredRules(): readonly CompressionRule[]; /** * Detect the tool that produced the output. * Uses heuristic pattern matching on the raw text. */ declare function detectOutputTool(text: string): string; /** * Core compression pipeline. * 1. Strip ANSI codes * 2. Detect tool * 3. Find matching rule (priority order) * 4. Apply rule or fall back to truncation */ declare function compressOutput(rawText: string, options?: { mode?: CompressionMode; maxChars?: number; tool?: string; }): CompressionResult; //#endregion //#region packages/tools/src/compress-output.d.ts interface CompressOutputOptions { /** Raw terminal/shell output text */ text: string; /** Override detected tool (e.g., 'git', 'npm', 'tsc') */ tool?: string; /** Compression mode: structural (default), heuristic, aggressive */ mode?: CompressionMode; /** Maximum output characters (default: 4000) */ maxChars?: number; /** Maximum output tokens (alternative to maxChars, uses 4 chars/token) */ tokenBudget?: number; } /** * Compress terminal/shell output using intelligent rule-based compression. * * Automatically detects the tool that produced the output (git, npm, tsc, * vitest, docker, kubectl, ESLint, etc.) and applies tool-specific * compression strategies that preserve critical information while reducing * token count. * * @example * ```ts * const result = compressTerminalOutput({ * text: rawGitDiff, * maxChars: 3000, * }); * // result.text contains compressed output * // result.rule tells which compression rule was applied * // result._meta.truncated tells if output was further truncated * ``` */ declare function compressTerminalOutput(options: CompressOutputOptions): CompressionResult; //#endregion //#region packages/tools/src/compression/reversible-cache.d.ts /** * Reversible compression cache. * * Stores bounded text artifacts by deterministic ref so compact/digest * outputs can be retrieved later or compacted again without re-running the * original upstream read. */ type ReversibleContextKind = 'compact' | 'digest'; interface ReversibleContextEntry { ref: string; kind: ReversibleContextKind; text: string; originalChars: number; compressedChars: number; createdAt: number; } declare function storeReversibleContext(entry: Omit): ReversibleContextEntry | undefined; //#endregion //#region packages/tools/src/compression/scoring.d.ts /** * Score a line of text by BPE token density (surprise). * Higher score = more information-dense content. * Range: 0.0 to 1.0 */ declare function bpeSurprise(line: string): number; /** * Score text lines with composite BPE surprise scoring. * Combines token density with rare token frequency. * * @param lines - Array of text lines to score * @returns Array of scores (0.0 to 1.0) in same order as input */ declare function scoreLines(lines: string[]): number[]; /** * Fallback scoring using Shannon character entropy. * Used when BPE tokenizer is unavailable. */ declare function shannonEntropy(text: string): number; /** * Score a single line with fallback to entropy if BPE fails. */ declare function scoreLine(line: string): number; //#endregion //#region packages/tools/src/data-transform.d.ts interface TransformOptions { input: unknown; expression: string; } interface TransformResult { output: unknown; outputString: string; } declare function dataTransform(options: TransformOptions): TransformResult; //#endregion //#region packages/tools/src/dead-symbols.d.ts interface DeadSymbolOptions { /** Root path to scope the search */ rootPath?: string; /** Max symbols to scan (default: 100) */ limit?: number; } interface DeadSymbol { name: string; path: string; line: number; kind: string; } interface DeadSymbolResult { /** Dead symbols in source files (.ts/.js/.tsx/.jsx) — actionable */ deadInSource: DeadSymbol[]; /** Dead symbols in documentation files (.md) — informational */ deadInDocs: DeadSymbol[]; totalExports: number; totalDeadSource: number; totalDeadDocs: number; } declare function findDeadSymbols(embedder: IEmbedder, store: IKnowledgeStore, options?: DeadSymbolOptions): Promise; //#endregion //#region packages/tools/src/delegate.d.ts interface DelegateOptions { /** The prompt / task to send to the local model. */ prompt: string; /** Model to use (default: the first available model). */ model?: string; /** Optional system prompt. */ system?: string; /** Optional context to include before the prompt. */ context?: string; /** Temperature (0-2, default: 0.3 for deterministic-ish output). */ temperature?: number; /** Timeout in milliseconds (default: 120_000). */ timeout?: number; /** Ollama base URL (default: http://localhost:11434). */ baseUrl?: string; } interface DelegateResult { model: string; response: string; durationMs: number; tokenCount?: number; error?: string; } /** * Check if Ollama is running and return available models. */ declare function delegateListModels(baseUrl?: string): Promise; /** * Delegate a task to a local Ollama model. * * Fails fast if Ollama is not running or no models are available. */ declare function delegate(options: DelegateOptions): Promise; //#endregion //#region packages/tools/src/detect-routes.d.ts /** * ENH-04: Route Detection — per-framework route parsing from file patterns. * * Detects web framework routes (Express, Fastify, Next.js) by analyzing * file naming conventions, directory structure, and route-related code patterns. * * Usage: * import { detectRoutes } from './detect-routes.js'; * const routes = await detectRoutes(rootPath); * // [{ framework: 'express', method: 'GET', path: '/api/users', file: 'src/routes/users.ts' }, ...] */ interface DetectedRoute { /** Framework that defines this route */ framework: 'express' | 'fastify' | 'nextjs'; /** HTTP method (GET, POST, PUT, DELETE, PATCH, or 'ALL' for catch-all) */ method: string; /** URL path pattern (may include params like :id or [id]) */ path: string; /** Source file defining the route */ file: string; /** Handler/controller function name (if detectable) */ handler?: string; /** Confidence: 'extracted' (found via AST/pattern) or 'inferred' (from file naming) */ confidence: 'extracted' | 'inferred'; } interface RouteDetectionResult { /** All detected routes */ routes: DetectedRoute[]; /** Routes grouped by framework */ byFramework: Record; /** Count per framework */ counts: Record; } /** * Extract routes from a file using regex patterns for a given framework. */ declare function extractRoutesFromFile(filePath: string, rootPath: string, framework: 'express' | 'fastify'): DetectedRoute[]; /** * Infer Next.js routes from file path conventions. * * App Router: * app/api/users/route.ts → GET /api/users * app/api/users/[id]/route.ts → GET /api/users/:id * app/about/page.tsx → GET /about * * Pages Router: * pages/api/users.ts → GET /api/users * pages/api/users/[id].ts → GET /api/users/:id * pages/about.tsx → GET /about */ declare function inferNextjsRoutes(routeFiles: string[]): DetectedRoute[]; /** * Detect all web framework routes in a project. * * @param rootPath — Project root to scan * @param frameworks — Frameworks to detect (default: all supported) * @returns Structured route detection result */ declare function detectRoutes(rootPath: string, frameworks?: ('express' | 'fastify' | 'nextjs')[]): Promise; //#endregion //#region packages/tools/src/diff-impact.d.ts type ChangeType = 'added' | 'modified' | 'deleted' | 'renamed'; interface FileChange { path: string; changeType: ChangeType; oldPath?: string; } interface BlastNode { /** Directly changed file */ changedFile: string; /** Files that import the changed file (transitive importers) */ affectedFiles: string[]; /** Risk: 'high' if it's a library/core file, 'medium' if many importers, 'low' otherwise */ risk: 'high' | 'medium' | 'low'; } interface DiffReport { /** Raw git status changes */ changes: FileChange[]; /** Per-file blast radius */ blastRadius: BlastNode[]; /** Aggregate summary */ summary: { totalChanged: number; added: number; modified: number; deleted: number; renamed: number; totalAffected: number; highRisk: number; mediumRisk: number; lowRisk: number; }; /** Raw git diff (text) */ rawDiff?: string; } /** Forward import graph: file → list of files it imports */ interface ImportGraph { [file: string]: string[]; } /** Reverse dependency graph: file → list of files that import it */ interface ReverseGraph { [file: string]: string[]; } /** * Build a forward import graph from a list of source files. * Uses findLocalImports to extract local imports per file, * then resolves relative import paths to absolute file paths. */ declare function buildImportGraph(rootPath: string, files: string[]): ImportGraph; /** * Build a reverse dependency graph from a forward import graph. * For each file, lists which other files import it. */ declare function buildReverseGraph(graph: ImportGraph): ReverseGraph; /** * BFS traversal of the reverse dependency graph from a set of changed files. * Returns all files transitively affected (direct and indirect importers). * * @param changedFiles — Set of changed file paths * @param reverseGraph — Reverse dependency graph (file → importers) * @param maxDepth — Maximum traversal depth (default: 10) * @returns Map of affected file → depth from nearest changed file */ declare function traverseBlastRadius(changedFiles: Set, reverseGraph: ReverseGraph, maxDepth?: number): Map; /** * Analyze the current diff (HEAD vs working tree) and produce an impact report. * * @param rootPath — Project root to analyze * @param includeRaw — Include raw diff text in the report (default: false) * @returns Structured diff impact report */ /** * Analyze git diff or explicit diff content for impact assessment. * * @param rootPath - Repository root path (used for blast-radius computation) * @param explicitDiff - Optional explicit diff text to parse (ignores git when provided) * @param includeRaw - Whether to include raw diff text in the report */ declare function analyzeDiff(rootPath: string, explicitDiff?: string, includeRaw?: boolean): Promise; //#endregion //#region packages/tools/src/diff-parse.d.ts interface DiffFile { path: string; oldPath?: string; status: 'added' | 'modified' | 'deleted' | 'renamed'; hunks: DiffHunk[]; additions: number; deletions: number; } interface DiffHunk { oldStart: number; oldLines: number; newStart: number; newLines: number; header: string; changes: DiffChange[]; } interface DiffChange { type: 'add' | 'delete' | 'context'; line: number; content: string; } interface DiffParseOptions { diff: string; } declare function diffParse(options: DiffParseOptions): DiffFile[]; //#endregion //#region packages/tools/src/digest.d.ts interface DigestSource { /** Unique identifier for this source */ id: string; /** The text to compress */ text: string; /** Priority weight (default: 1). Higher = more budget share */ weight?: number; } interface DigestOptions { /** Source texts to compress */ sources: DigestSource[]; /** Focus query — what matters for the next step? */ query: string; /** Target budget in characters (default: 4000) */ maxChars?: number; /** Key fields to always extract via keyword matching */ pinFields?: string[]; /** Segmentation strategy (default: 'paragraph') */ segmentation?: 'paragraph' | 'sentence' | 'line'; /** * Enable MMR deduplication across segments (default: true). * Prevents near-identical segments from consuming budget. */ dedup?: boolean; /** Internal: disable reversible ref storage when reusing cached artifacts. */ storeReference?: boolean; } interface DigestFieldEntry { sourceId: string; value: string; } interface DigestResult { /** Compressed narrative (all sources merged, reading order maintained) */ text: string; /** Reusable cache reference */ ref?: string; /** Extracted structured fields */ fields: Record; /** Per-source compression stats */ sourceStats: Array<{ id: string; originalChars: number; keptChars: number; segmentsKept: number; segmentsTotal: number; }>; totalOriginalChars: number; totalCompressedChars: number; ratio: number; } /** * Compress multiple text sources into a single digest. */ declare function digest(embedder: IEmbedder, options: DigestOptions): Promise; //#endregion //#region packages/tools/src/dogfood-log.d.ts /** * aikit_dogfood — Review persistent warn/error logs for dogfooding. * * Reads daily JSONL log files from ~/.aikit/logs/ and returns a * summarized or detailed view of recent issues. Useful for periodic * review cycles to identify and fix recurring problems. */ interface DogfoodLogEntry { ts: string; level: 'warn' | 'error'; component: string; msg: string; [key: string]: unknown; } interface DogfoodLogOptions { /** Number of days to look back (default: 7) */ days?: number; /** Filter by level */ level?: 'warn' | 'error'; /** Filter by component name */ component?: string; /** Maximum entries to return in detail (default: 50) */ limit?: number; } interface DogfoodLogGroupedEntry { component: string; msg: string; level: 'warn' | 'error'; count: number; firstSeen: string; lastSeen: string; } interface DogfoodLogResult { /** Total entries found matching filters */ totalEntries: number; /** Unique issue groups (by component + message) */ groups: DogfoodLogGroupedEntry[]; /** Most recent entries (up to limit) */ recent: DogfoodLogEntry[]; /** Date range covered */ dateRange: { from: string; to: string; }; } declare function dogfoodLog(options?: DogfoodLogOptions): DogfoodLogResult; //#endregion //#region packages/tools/src/domain-analyzer.d.ts /** * KB-05: Business Domain Analysis * * Rule-based file-to-domain classifier. Maps file paths to business domains * by examining top-level directory structure and file naming patterns. * No LLM required. * * Domains: payment, user, order, inventory, notification, analytics, * auth, content, communication, admin, infrastructure, unknown. * * Integration: Used as a parallel analysis step in onboard(). * Domain data is stored as a `domain` field on each knowledge-graph file node. */ type Domain = 'payment' | 'user' | 'order' | 'inventory' | 'notification' | 'analytics' | 'auth' | 'content' | 'communication' | 'admin' | 'infrastructure' | 'unknown'; interface DomainClassification { path: string; domain: Domain; confidence: 'high' | 'medium' | 'low'; reason: string; } /** * Classify a single file path into its business domain. */ declare function classifyDomain(filePath: string): DomainClassification; /** * Classify multiple file paths at once. */ declare function classifyDomains(filePaths: string[]): DomainClassification[]; /** * Group classifications by domain. */ declare function groupByDomain(classifications: DomainClassification[]): Map; /** * Format classifications as a markdown report. */ declare function formatDomainReport(classifications: DomainClassification[], rootPath: string): string; type DomainAnalysisInput = string; type DomainType = Domain; /** @deprecated Use classifyDomain() instead */ declare const analyzeDomain: typeof classifyDomain; /** @deprecated Use classifyDomains() instead */ declare const analyzeDomains: typeof classifyDomains; //#endregion //#region packages/tools/src/encode.d.ts /** * aikit_encode — Encoding, decoding, and hashing utilities. */ type EncodeOperation = 'base64_encode' | 'base64_decode' | 'url_encode' | 'url_decode' | 'sha256' | 'md5' | 'jwt_decode' | 'hex_encode' | 'hex_decode'; interface EncodeOptions { operation: EncodeOperation; input: string; } interface EncodeResult { output: string; operation: string; } declare function encode(options: EncodeOptions): EncodeResult; //#endregion //#region packages/tools/src/env-info.d.ts /** * aikit_env — System environment and runtime information. */ interface EnvInfoOptions { includeEnv?: boolean; filterEnv?: string; showSensitive?: boolean; } interface EnvInfoResult { system: { platform: string; arch: string; release: string; hostname: string; type: string; cpus: number; memoryTotalGb: number; memoryFreeGb: number; }; runtime: { node: string; v8: string; }; cwd: string; env?: Record; } declare function envInfo(options?: EnvInfoOptions): EnvInfoResult; //#endregion //#region packages/tools/src/eval.d.ts interface EvalOptions { code: string; lang?: 'js' | 'ts'; timeout?: number; } interface EvalResult { success: boolean; output: string; error?: string; durationMs: number; } declare function evaluate(options: EvalOptions): Promise; //#endregion //#region packages/tools/src/evidence-map.d.ts /** * aikit_evidence_map — FORGE Evidence Map CRUD + Gate evaluator. * * Structured storage, validation, and gate evaluation for FORGE Evidence Map entries. * Persisted in the AI Kit state directory. */ type EvidenceStatus = 'V' | 'A' | 'U'; type TimeoutAction = 'iterate' | 'retry' | 'manual' | 'terminate'; type UnknownType = 'contract' | 'convention' | 'freshness' | 'runtime' | 'data-flow' | 'impact'; type GateDecision = 'YIELD' | 'HOLD' | 'HARD_BLOCK' | 'FORCED_DELIVERY'; type ForgeTier = 'floor' | 'standard' | 'critical'; type SafetyGate = 'provenance' | 'commitment' | 'coverage'; interface GateConfig { /** Maximum retries before escalating. Default: 3 */ maxRetries?: number; /** Action to take when gate times out / max retries exceeded. Default: 'manual' */ timeoutAction?: TimeoutAction; } interface EvidenceEntry { id: number; claim: string; status: EvidenceStatus; receipt: string; criticalPath: boolean; unknownType?: UnknownType; safetyGate?: SafetyGate; } interface EvidenceMapState { taskId: string; tier: ForgeTier; entries: EvidenceEntry[]; gateConfig: Required; gateAttempts: number; createdAt: string; updatedAt: string; } interface SafetyGateResult { provenance: 'pass' | 'fail'; commitment: 'pass' | 'fail'; coverage: 'pass' | 'fail'; failures: string[]; } interface GateResult { verdict: 'YIELD' | 'HOLD' | 'HARD_BLOCK'; /** Recommended action on non-YIELD. Undefined when verdict is YIELD. */ action?: TimeoutAction; /** Retries remaining. Undefined when verdict is YIELD. */ retriesRemaining?: number; /** Summary of unresolved/assumed claims */ summary?: string; decision: GateDecision; reason: string; unresolvedCritical: EvidenceEntry[]; warnings: string[]; stats: { total: number; verified: number; assumed: number; unresolved: number; }; safetyGates?: SafetyGateResult; annotation?: string; } type EvidenceMapAction = { action: 'create'; taskId: string; tier: ForgeTier; } | { action: 'add'; taskId: string; claim: string; status: EvidenceStatus; receipt: string; criticalPath?: boolean; unknownType?: UnknownType; safetyGate?: SafetyGate; } | { action: 'update'; taskId: string; id: number; status: EvidenceStatus; receipt: string; } | { action: 'get'; taskId: string; } | { action: 'gate'; taskId: string; retryCount?: number; maxRetries?: number; timeoutAction?: TimeoutAction; } | { action: 'list'; } | { action: 'delete'; taskId: string; }; interface EvidenceMapResult { state?: EvidenceMapState; states?: EvidenceMapState[]; entry?: EvidenceEntry; gate?: GateResult; deleted?: boolean; autoCreated?: boolean; taskId?: string; summary?: string; counts?: GateResult['stats']; formattedMap?: string; } declare function evidenceMap(action: EvidenceMapAction, cwd?: string): EvidenceMapResult; declare function autoClaimTestFailures(taskId: string, failures: string[], cwd?: string): EvidenceEntry[]; //#endregion //#region packages/tools/src/file-summary.d.ts interface FileSummaryOptions { path: string; /** Pre-loaded content — skip readFile when provided (e.g., from FileCache) */ content?: string; maxTokens?: number; previewLines?: number; } interface FileSummaryResult { path: string; lines: number; language: string; imports: string[]; importCount?: number; exports: string[]; functions: Array<{ name: string; line: number; exported: boolean; signature?: string; }>; classes: Array<{ name: string; line: number; exported: boolean; signature?: string; }>; interfaces: Array<{ name: string; line: number; exported: boolean; }>; types: Array<{ name: string; line: number; exported: boolean; }>; /** Import details with external/internal classification (AST-powered) */ importDetails?: Array<{ source: string; specifiers: string[]; isExternal: boolean; }>; /** Intra-file call edges showing which functions call which (AST-powered) */ callEdges?: Array<{ caller: string; callee: string; line: number; }>; callEdgeCount?: number; estimatedTokens: number; } declare function fileSummary(options: FileSummaryOptions): Promise; //#endregion //#region packages/tools/src/file-summary-tool.d.ts interface FileSummaryToolOptions { /** File paths to summarize (card output) */ files?: string[]; /** Arbitrary text to compress (text output) */ text?: string; /** Cached ref to restore */ ref?: string; /** Output tier: T1=structure only, T2=structure+content */ tier?: 'T1' | 'T2'; /** Focus query — guides relevance scoring. Triggers T2 when present without explicit tier */ query?: string; /** T2/T2+text content budget in chars (default 800) */ maxContentChars?: number; /** How to segment content for scoring (default: paragraph) */ segmentation?: 'paragraph' | 'sentence' | 'line'; /** Minimum relevance score threshold (0-1, default: 0.3) */ minScore?: number; /** Mode: 'full' (default) or 'delta' (only changes since last read) */ mode?: 'full' | 'delta'; /** Internal: file cache for deduplicated reads */ cache?: FileCache; } interface FileSummaryToolCard { path: string; tier: 'T1' | 'T2'; card: string; unknowns: string[]; riskTier: 'low' | 'medium' | 'high'; tokenEstimate: number; originalTokenEstimate: number; } interface FileSummaryToolResult { /** Card results when files were provided */ cards?: FileSummaryToolCard[]; /** Compressed text when text was provided */ text?: string; /** Reusable cache reference */ ref?: string; /** Original size in chars (text/ref mode) */ originalChars?: number; /** Compressed size in chars (text/ref mode) */ compressedChars?: number; /** Compression ratio (text/ref mode) */ ratio?: number; /** Segments kept / total (text/ref mode) */ segmentsKept?: number; segmentsTotal?: number; /** Aggregated stats (file mode) */ totalTokenEstimate?: number; totalOriginalTokenEstimate?: number; compressionRatio?: number; } /** * Unified file_summary tool. * * Routes between three modes based on input: * - `files` → T1/T2 cards (structure + optional content) * - `text` → compressed text (compact-style) * - `ref` → cached result restoration */ declare function fileSummaryTool(embedder: IEmbedder, options: FileSummaryToolOptions): Promise; //#endregion //#region packages/tools/src/find.d.ts interface FindOptions { /** Semantic search query (optional) */ query?: string; /** File glob pattern (optional) */ glob?: string; /** Keyword/regex pattern for text search (optional) */ pattern?: string; /** Max results per strategy (default: 10) */ limit?: number; /** Filter by content type */ contentType?: ContentType; /** Working directory for glob resolution (default: cwd) */ cwd?: string; /** * Explore mode: when true, enriches find results with related context * including neighboring symbols, file summaries, and dependency info. * Requires graph store to be available for full enrichment. */ explore?: boolean; } interface FindResult { /** File path (relative to cwd) */ path: string; /** How this result was found */ source: 'vector' | 'keyword' | 'glob' | 'pattern'; /** Relevance score (0-1 for vector/keyword, 1 for glob/pattern matches) */ score: number; /** Line range if from AI Kit search */ lineRange?: { start: number; end: number; }; /** Content preview */ preview?: string; } interface FindResults { results: FindResult[]; strategies: string[]; totalFound: number; failedStrategies?: Array<{ strategy: string; reason: string; }>; } /** * Run federated search across multiple strategies. */ declare function find(embedder: IEmbedder, store: IKnowledgeStore, options: FindOptions): Promise; //#endregion //#region packages/tools/src/find-examples.d.ts interface FindExamplesOptions { /** Symbol or pattern to find examples of */ query: string; /** Max examples to return (default: 5) */ limit?: number; /** Filter by content type */ contentType?: ContentType; } interface Example { path: string; startLine: number; endLine: number; content: string; relevance: number; context: string; } interface FindExamplesResult { query: string; examples: Example[]; totalFound: number; } declare function findExamples(embedder: IEmbedder, store: IKnowledgeStore, options: FindExamplesOptions): Promise; //#endregion //#region packages/tools/src/forge-classify.d.ts interface ForgeClassifyOptions { /** Files being modified (absolute or relative paths) */ files: string[]; /** Task description for keyword detection */ task: string; /** Root path for package boundary detection */ rootPath: string; } interface ClassifyTrigger { rule: string; detail: string; source: 'blast_radius' | 'cross_package' | 'schema_contract' | 'security_auth' | 'task_hint' | 'default'; } interface TypedUnknownSeed { description: string; type: 'contract' | 'convention' | 'freshness' | 'runtime' | 'data-flow' | 'impact'; suggestedTool: string; } interface ForgeClassifyCeremony { ground: string; build: string; break: string; evidenceMap: string; gate: string; } interface ForgeClassifyResult { tier: ForgeTier; triggers: ClassifyTrigger[]; packagesCrossed: string[]; hasSchemaChange: boolean; hasSecurityPath: boolean; typedUnknownSeeds: TypedUnknownSeed[]; ceremony: ForgeClassifyCeremony; reclassifyHint?: { suggestedTier: ForgeTier; reason: string; }; } declare function forgeClassify(options: ForgeClassifyOptions): Promise; //#endregion //#region packages/tools/src/scope-map.d.ts interface ScopeMapOptions { /** Description of the task to scope */ task: string; /** Maximum number of files to include (default: 15) */ maxFiles?: number; /** Group results by directory (default: true) */ groupByDirectory?: boolean; /** Filter by content type */ contentType?: ContentType; /** Filter by origin */ origin?: KnowledgeOrigin; } interface ScopeMapEntry { /** File path */ path: string; /** Why this file is relevant (derived from matched chunks) */ reason: string; /** Estimated token count (chars / 4 approximation) */ estimatedTokens: number; /** Relevance score (0-1) */ relevance: number; /** Line ranges to focus on */ focusRanges: Array<{ start: number; end: number; heading?: string; }>; } interface ScopeMapResult { /** The task that was analyzed */ task: string; /** Prioritized file list */ files: ScopeMapEntry[]; /** Total estimated tokens across all files */ totalEstimatedTokens: number; /** Suggested reading order (file paths) */ readingOrder: string[]; /** Suggested compact/file_summary commands to reduce context */ compactCommands: string[]; } /** * Generate a task-scoped reading plan. */ declare function scopeMap(embedder: IEmbedder, store: IKnowledgeStore, options: ScopeMapOptions): Promise; //#endregion //#region packages/tools/src/forge-ground.d.ts interface ForgeGroundOptions { /** Task description */ task: string; /** Target files being modified (absolute paths) */ files: string[]; /** Root path of the codebase */ rootPath: string; /** Max constraint entries to load (default: 3) */ maxConstraints?: number; /** Force a specific tier (skip auto-classify) */ forceTier?: ForgeTier; /** Task ID for evidence map creation (default: auto-generated from task) */ taskId?: string; } interface ConstraintRef { source: string; snippet: string; relevance: number; } interface ForgeGroundResult { /** Computed or forced tier */ tier: ForgeTier; /** Classification triggers (empty if tier was forced) */ classifyTriggers: ClassifyTrigger[]; /** Scope map (relevant files with focus ranges) — null for Floor tier */ scopeMap: ScopeMapResult | null; /** Typed Unknown Queue seeds */ typedUnknownSeeds: TypedUnknownSeed[]; /** Constraint seed — relevant AI Kit entries from decisions/patterns */ constraints: ConstraintRef[]; /** File summaries for target files */ fileSummaries: Array<{ path: string; exports: string[]; functions: string[]; lines: number; error?: string; }>; /** Evidence map task ID (created if Standard or Critical) */ evidenceMapTaskId: string | null; /** Total estimated tokens for this Ground output */ estimatedTokens: number; /** Ceremony recommendations for this tier */ ceremony: { ground: string; build: string; break: string; evidenceMap: string; gate: string; }; } declare function forgeGround(embedder: IEmbedder, store: IKnowledgeStore, options: ForgeGroundOptions): Promise; //#endregion //#region packages/tools/src/git-context.d.ts interface GitContextOptions { cwd?: string; commitCount?: number; includeDiff?: boolean; } interface GitContextResult { gitRoot: string; branch: string; status: { staged: string[]; modified: string[]; untracked: string[]; }; recentCommits: Array<{ hash: string; message: string; author: string; date: string; }>; diff?: string; } declare function gitContext(options?: GitContextOptions): Promise; //#endregion //#region packages/tools/src/git-utils.d.ts /** Regex for valid git ref slug segments */ declare const GIT_REF_SLUG_PATTERN: RegExp; /** * Check if git is available in the given directory. * Results are cached per resolved root path. */ declare function gitAvailable(cwd: string): boolean; /** * Execute a git command with a 10-second timeout. * Returns trimmed stdout on success, undefined on failure. * Never throws — failures are logged and return undefined. * Pass silent=true to suppress the warning (e.g. for expected failures like rev-parse on new refs). */ declare function gitExec(args: string[], cwd: string, input?: string, silent?: boolean): string | undefined; /** * Create a slugified ref segment from a label. * Lowercase, replace non-alphanumeric with dashes, trim leading/trailing dashes, max 60 chars. */ declare function slugForRef(label: string): string; /** * Commit content to a git orphan ref. * Creates: blob -> single-entry tree -> commit (with optional parent) -> update-ref. * Returns the commit SHA on success, undefined on failure. */ declare function gitCommitToRef(ref: string, filename: string, content: string, message: string, cwd: string): string | undefined; /** Reset the git availability cache (useful for testing). */ declare function resetGitCache(): void; //#endregion //#region packages/tools/src/graph-id.d.ts /** * Graph ID Builder — canonical identity schemas for the knowledge graph. * * Every logical entity (file, symbol, call-site, module) gets one canonical * ID format shared by full onboard, incremental update, graph review, * diff impact, and consumers. * * ID Schemas: * file: "file:" — normalized workspace-relative path * symbol: "symbol:::" — fully qualified symbol within a file * call: "call:" — call-graph module reference * edge: "edge-" — sequential edge ID * * Path normalization: forward slashes, no trailing slash, no redundant segments. * Works across Windows and POSIX. */ /** * Normalize a file path to canonical form: forward slashes, * workspace-relative where possible, no trailing slash. */ declare function normalizePath(filePath: string): string; /** * Build an ID for a file node. * Uses normalized workspace-relative path as the stable identity. */ declare function fileId(filePath: string): string; /** * Build an ID for a symbol node. * Combines file identity with symbol name for uniqueness. */ declare function symbolId(filePath: string, symbolName: string): string; /** * Build an ID for a call-graph module reference. */ declare function callId(modulePath: string): string; /** * Build an edge ID (sequential). */ declare function edgeId(n: number): string; /** * Get workspace-relative path for display purposes. * Strips machine-specific absolute path when root is known. */ declare function workspacePath(filePath: string, rootPath?: string): string; //#endregion //#region packages/tools/src/graph-utils.d.ts /** Resolved community with typed metadata */ interface CommunityInfo { id: string; nodeCount: number; types: Record; samples: Array<{ id: string; name: string; type: string; }>; } /** * Build a node-Id → name lookup map. * Pure projection — zero queries. */ declare function buildNodeNameMap(nodes: GraphNode[]): Map; /** * Resolve a name from a node map with fallback. */ declare function resolveNodeName(nodeId: string, nameMap: Map): string; /** * Transform raw community detection output (Record) into * CommunityInfo[] with type histograms and sample names. * * Uses an optional node map for name resolution. Unresolved name fallback: * truncated id. */ declare function transformCommunities(communities: Record, nodeMap: Map, nodeTypes: Map): CommunityInfo[]; /** * Format empty-result message with diagnostic + suggested next command. */ declare function formatEmptyResult(entityType: string, diagnostic: string, suggestedCommand: string): string; //#endregion //#region packages/tools/src/graph-query.d.ts interface GraphQueryOptions { /** Action: query nodes, traverse from a node, get stats, or add data */ action: 'find_nodes' | 'find_edges' | 'neighbors' | 'traverse' | 'stats' | 'validate' | 'add' | 'delete' | 'clear' | 'detect_communities' | 'set_community' | 'trace_process' | 'list_processes' | 'delete_process' | 'depth_traverse' | 'cohesion' | 'symbol360'; /** Node type filter (for find_nodes) */ nodeType?: string; /** Name pattern (LIKE %pattern%) for find_nodes */ namePattern?: string; /** Source path filter */ sourcePath?: string; /** Node ID for neighbors/traverse/delete */ nodeId?: string; /** Edge type filter */ edgeType?: string; /** From node ID (for find_edges) */ fromId?: string; /** To node ID (for find_edges) */ toId?: string; /** Traversal direction */ direction?: 'outgoing' | 'incoming' | 'both'; /** Max traversal depth (default: 2) */ maxDepth?: number; /** Max results (default: 50) */ limit?: number; /** Nodes to add (for action=add) */ nodes?: Array<{ id?: string; type: string; name: string; properties?: Record; sourceRecordId?: string; sourcePath?: string; }>; /** Edges to add (for action=add) */ edges?: Array<{ id?: string; fromId: string; toId: string; type: string; weight?: number; properties?: Record; }>; /** Community label (for set_community, cohesion) */ community?: string; /** Process ID (for delete_process) */ processId?: string; /** Label for process tracing */ label?: string; } interface GraphQueryResult { action: string; nodes?: GraphNode[]; edges?: GraphEdge[]; stats?: GraphStats$1; validation?: GraphValidationResult; communities?: CommunityInfo[]; process?: ProcessInfo; processes?: ProcessInfo[]; depthGroups?: DepthGroupedResult; cohesionScore?: number; symbol360?: Symbol360; nodesAdded?: number; edgesAdded?: number; deleted?: number; summary: string; } declare function graphQuery(graphStore: IGraphStore, options: GraphQueryOptions): Promise; interface GraphAugmentOptions { /** Max graph hops from each vector hit (default: 1) */ hops?: number; /** Edge type filter for graph expansion */ edgeType?: string; /** Max graph nodes per vector hit (default: 5) */ maxPerHit?: number; } interface GraphAugmentedResult { /** Original search result record ID */ recordId: string; /** Original similarity score */ score: number; /** Source path of the matched record */ sourcePath: string; /** Graph nodes connected to this record (via sourceRecordId) */ graphContext: GraphTraversalResult; } /** * Augment vector search results with graph context. * For each search hit, finds linked graph nodes and traverses their connections. */ declare function graphAugmentSearch(graphStore: IGraphStore, hits: Array<{ recordId: string; score: number; sourcePath: string; }>, options?: GraphAugmentOptions): Promise; //#endregion //#region packages/tools/src/graph-review.d.ts /** * KB-16: Graph Review Agent * * Validates knowledge graphs for structural integrity issues: * - Dangling edges: edges that reference non-existent node IDs * - Orphan nodes: nodes with zero incoming/outgoing edges * - Duplicate IDs: nodes or edges sharing the same ID * - Missing fields: required fields that are absent * - Schema version check * * Rule-based, no LLM calls. Standalone module for reverse extraction. * * Usage: * import { reviewGraph } from './graph-review.js'; * const report = reviewGraph(graphData); * // => { findings: [...], score: 'healthy'|'fair'|'poor', summary: '...' } */ interface GraphNode$1 { id: string; label?: string; type?: string; [key: string]: unknown; } interface GraphEdge$1 { source?: string; target?: string; from?: string; to?: string; id?: string; relation?: string; [key: string]: unknown; } interface KnowledgeGraph { schema_version?: string; nodes?: GraphNode$1[]; edges?: GraphEdge$1[]; [key: string]: unknown; } type FindingSeverity = 'error' | 'warning' | 'info'; interface Finding { severity: FindingSeverity; category: 'dangling-edge' | 'orphan-node' | 'duplicate-id' | 'missing-field' | 'schema-version' | 'empty-graph' | 'self-loop'; message: string; /** IDs affected by this finding */ ids?: string[]; } interface GraphReviewReport { /** All structural findings */ findings: Finding[]; /** Overall health score */ score: 'healthy' | 'fair' | 'poor'; /** Summary string */ summary: string; /** Summary by category */ errorCount: number; warningCount: number; infoCount: number; } /** * Find edges that reference non-existent node IDs. */ declare function findDanglingEdges(edges: GraphEdge$1[], validNodeIds: Set): Finding[]; /** * Find nodes with no edges (isolated / orphan). */ declare function findOrphanNodes(nodes: GraphNode$1[], edges: GraphEdge$1[], maxWarningNodes?: number): Finding[]; /** * Find duplicate node or edge IDs. */ declare function findDuplicateIds(nodes: GraphNode$1[], _edges: GraphEdge$1[]): Finding[]; /** * Find edges where source === target (self-loops). */ declare function findSelfLoops(edges: GraphEdge$1[]): Finding[]; /** * Check schema version field. */ declare function checkSchemaVersion(graph: KnowledgeGraph): Finding[]; /** * Check for empty graph (no nodes). */ declare function checkEmptyGraph(nodes: GraphNode$1[]): Finding[]; /** * Check for missing key fields on nodes. */ declare function checkMissingFields(nodes: GraphNode$1[]): Finding[]; /** * Run all graph validation checks and produce a review report. */ declare function reviewGraph(graph: KnowledgeGraph): GraphReviewReport; //#endregion //#region packages/tools/src/guide.d.ts /** * Tool discovery — recommends MCP tools and workflows for a given goal. * * Uses keyword matching against predefined workflow templates. * No embeddings required — pure string matching for instant results. */ interface GuideRecommendation { tool: string; reason: string; order: number; suggestedArgs?: Record; /** Optional token-saving tip shown alongside the recommendation */ tokenTip?: string; } interface GuideResult { workflow: string; description: string; tools: GuideRecommendation[]; alternativeWorkflows: string[]; } /** * Match a goal description to the best workflow and return tool recommendations. */ declare function guide(goal: string, maxRecommendations?: number, indexMode?: string): GuideResult; //#endregion //#region packages/tools/src/guided-tour.d.ts /** * KB-10: Guided Tours — dependency-ordered learning paths from a knowledge graph. * * Generates structured learning paths that guide users through a codebase * in dependency order: foundational modules first, then higher-level ones. * * Usage: * import { generateGuidedTours, orderByDependency } from './guided-tour.js'; * const tours = generateGuidedTours(nodes, edges); * // [{ id: 'tour:backend', title: 'Backend Tour', steps: [...] }, ...] */ interface TourStep { /** Node id in the knowledge graph */ nodeId: string; /** Node label / display name */ label: string; /** Step number in sequence */ order: number; /** Depth from root (0 = foundational, higher = more dependent) */ depth: number; /** Node type (file, class, function, etc.) */ type: string; /** File path (if applicable) */ filePath?: string; } interface GuidedTour { /** Unique tour identifier */ id: string; /** Human-readable title */ title: string; /** Topic / domain this tour covers */ topic: string; /** Ordered steps (dependency-ordered) */ steps: TourStep[]; /** Total step count */ totalSteps: number; /** Estimated difficulty (easy/medium/hard) */ difficulty: 'easy' | 'medium' | 'hard'; } interface GuidedTourOptions { /** Maximum steps per tour (default: 20) */ maxStepsPerTour?: number; /** Minimum nodes per tour topic (default: 3) */ minNodesPerTopic?: number; /** Only include these node types (default: all) */ includeTypes?: string[]; /** Exclude these node types */ excludeTypes?: string[]; } /** * Topological sort of nodes based on dependency edges. * Foundational nodes (no dependencies) come first at depth 0; * nodes that depend on them come later at increasing depth. * * Cycles are detected and broken by excluding the minimum number of edges. * * @param nodeIds — All node IDs to order * @param edges — Dependency edges [{ source, target, ... }] * @returns Map of nodeId → { order, depth } */ declare function orderByDependency(nodeIds: string[], edges: Array<{ source: string; target: string; }>): Map; /** * Generate guided tours from a set of knowledge graph nodes and edges. * * Each tour is a dependency-ordered path through a topic area (domain, layer, or type). * Topics with fewer than `minNodesPerTopic` nodes are excluded. * * @param nodes — Knowledge graph nodes (Array<{ id, label, type, filePath?, domain?, layer? }>) * @param edges — Knowledge graph edges (Array<{ source, target, ... }>) * @param options — Optional configuration * @returns Array of guided tours */ declare function generateGuidedTours(nodes: Array>, edges: Array>, options?: GuidedTourOptions): GuidedTour[]; /** * Format a guided tour as readable markdown. */ declare function formatTour(tour: GuidedTour): string; /** * Format all tours as a markdown index with summaries. */ declare function formatToursIndex(tours: GuidedTour[]): string; /** * Find the best tour for a given query (topic or node name match). */ declare function findTour(tours: GuidedTour[], query: string): GuidedTour | undefined; //#endregion //#region packages/tools/src/health.d.ts interface HealthCheck { name: string; status: 'pass' | 'warn' | 'fail'; message: string; } interface HealthResult { path: string; checks: HealthCheck[]; score: number; summary: string; } /** Run project health checks on a directory. */ declare function health(rootPath?: string): HealthResult; //#endregion //#region packages/tools/src/http-request.d.ts /** * aikit_http — Make HTTP requests for API testing and debugging. */ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD'; interface HttpRequestOptions { url: string; method?: HttpMethod; headers?: Record; body?: string; timeout?: number; } interface HttpRequestResult { status: number; statusText: string; headers: Record; body: string; durationMs: number; contentType: string; sizeBytes: number; truncated: boolean; } declare function httpRequest(options: HttpRequestOptions): Promise; //#endregion //#region packages/tools/src/import-resolver.d.ts /** * KB-15: importMap Pre-Resolution — resolve all imports during scan phase. * * During the scan phase of the pipeline, this module extracts all import/require * specifiers from source files, resolves local imports to absolute paths, and * categorizes them (local, package, builtin). The resulting ImportMap feeds * downstream stages (dependency graph, blast radius, knowledge graph edges) * without requiring them to re-parse files. * * Usage: * import { buildImportMap, buildExportMap } from './import-resolver.js'; * const importMap = await buildImportMap(rootPath, scanResult.files); * const exportMap = await buildExportMap(rootPath, scanResult.files); */ interface ResolvedImport { /** Raw import specifier as written in source (e.g., './foo', '../bar', 'lodash', 'node:fs') */ specifier: string; /** Resolved absolute path (null for external packages and builtins) */ resolvedPath: string | null; /** Whether this is a local import (starts with . or ..) */ isLocal: boolean; /** Whether this is a bare-name import (package import like 'lodash', 'react') */ isPackage: boolean; /** Whether this is a node: builtin import */ isBuiltin: boolean; /** Resolved file extension when the path was resolved (null if unresolved) */ fileExtension: string | null; } type ImportMap = Record; type ExportMap = Record; /** * Extract all import specifiers from file content using regex. * Covers: ES import/export, dynamic import(), and require(). * Returns raw specifiers as written in source (e.g., './foo', '../bar', 'lodash'). */ declare function extractImports(content: string): string[]; /** * Resolve a local import specifier to an absolute file path. * * For local imports (starting with . or ..), resolves relative to the * importing file's directory. Tries common TS/JS extensions if the * path has no extension. * * Returns null for: * - Builtin imports (node:*) * - Package imports (bare specifiers like 'lodash') * - Imports whose resolved path doesn't exist on disk */ declare function resolveImportPath(specifier: string, filePath: string, _rootPath: string): string | null; /** * Build an ImportMap from a list of scanned files. * * For each resolvable source file, extracts all import specifiers, resolves * local paths to absolute paths, and returns a map of file path → ResolvedImport[]. * * @param rootPath — Project root for relative path resolution * @param files — List of ScannedFile entries (from scanCodebase). Required. * @returns ImportMap mapping each file's absolute path to its resolved imports */ declare function buildImportMap(rootPath: string, files: Array<{ path: string; category: string; }>): Promise; /** * Build an ExportMap from a list of scanned files. * * Extracts named exports from resolvable source files and returns a map * of export name → file path (the file where the export is defined). * * @param rootPath — Project root (used for path resolution) * @param files — List of ScannedFile entries. Required. * @returns ExportMap mapping each exported name to its defining file path */ declare function buildExportMap(_rootPath: string, files: Array<{ path: string; category: string; }>): Promise; //#endregion //#region packages/tools/src/lane.d.ts interface LaneMeta { name: string; createdAt: string; sourceFiles: string[]; rootPath: string; } interface LaneDiffEntry { file: string; status: 'modified' | 'added' | 'deleted' | 'unchanged'; diff?: string; } interface LaneDiffResult { name: string; entries: LaneDiffEntry[]; modified: number; added: number; deleted: number; } interface LaneMergeResult { name: string; filesMerged: number; files: string[]; } /** * Create an isolated lane by copying specified files into the AI Kit state directory. * Files are stored with their relative paths preserved. */ declare function laneCreate(name: string, files: string[], cwd?: string): LaneMeta; /** List all active lanes. */ declare function laneList(cwd?: string): LaneMeta[]; /** Get the status of a lane — which files are modified, added, deleted. */ declare function laneStatus(name: string, cwd?: string): LaneDiffResult; /** Generate a unified diff for modified files in a lane. */ declare function laneDiff(name: string, cwd?: string): LaneDiffResult; /** Merge lane files back to the original locations. */ declare function laneMerge(name: string, cwd?: string): LaneMergeResult; /** Discard a lane entirely. */ declare function laneDiscard(name: string, cwd?: string): boolean; //#endregion //#region packages/tools/src/layer-detector.d.ts /** * KB-04: Architectural Layer Detection * * Rule-based file-to-layer classifier. Each file path is matched against * directory-name heuristics and file extension patterns. No LLM required. * * Layers: api, service, data, ui, utility, config, test, unknown. * * Integration: Used as a parallel analysis step in onboard(). Layer data * is stored as a `layer` field on each knowledge-graph file node. */ type Layer = 'api' | 'service' | 'data' | 'ui' | 'utility' | 'config' | 'test' | 'unknown'; interface LayerClassification { path: string; layer: Layer; confidence: 'high' | 'medium' | 'low'; reason: string; } /** * Classify a single file path into its architectural layer. */ declare function classifyFile(filePath: string): LayerClassification; /** * Classify multiple file paths at once. */ declare function classifyBatch(filePaths: string[]): LayerClassification[]; type LayerDetectionInput = string; type LayerType = Layer; /** @deprecated Use classifyFile() instead */ declare const detectLayer: typeof classifyFile; /** @deprecated Use classifyBatch() instead */ declare const detectLayers: typeof classifyBatch; //#endregion //#region packages/tools/src/lease.d.ts interface Lease { id: string; agent: string; files: string[]; symbols?: string[]; intent: string; status: 'active' | 'released' | 'expired'; acquiredAt: string; expiresAt: string; releasedAt?: string; } interface LeaseConflict { leaseId: string; agent: string; overlappingFiles: string[]; overlappingSymbols?: string[]; intent: string; } interface HotspotEntry { path: string; leaseCount: number; conflictCount: number; lastContested: string; } declare function acquireLease(opts: { agent: string; files: string[]; intent: string; symbols?: string[]; ttl_minutes?: number; cwd?: string; }): { lease: Lease; conflicts: LeaseConflict[]; }; declare function releaseLease(opts: { id: string; cwd?: string; }): { released: boolean; lease?: Lease; }; declare function listActiveLeases(opts?: { agent?: string; cwd?: string; }): { leases: Lease[]; hotspots: Record; }; //#endregion //#region packages/tools/src/llm-enricher.d.ts interface EnrichSymbolEntry { name: string; kind: string; filePath: string; exported: boolean; signature?: string; } interface EnrichStructureEntry { path: string; size: number; lines: number; } interface EnrichOptions { symbols: EnrichSymbolEntry[]; structure: EnrichStructureEntry[]; /** Optional dependency data for context enrichment */ dependencies?: Record; rootPath: string; projectName: string; /** Callback to send a prompt to the session LLM. Returns the response text. */ llmCall?: (prompt: string, system?: string) => Promise; } interface ModuleInsight { filePath: string; summary: string; role: 'api' | 'service' | 'data' | 'ui' | 'utility' | 'config' | 'unknown'; tags: string[]; surfaceArea: string; confidence: number; } /** * LLM-based codebase enrichment. * Uses the session LLM (via MCP sampling callback) to produce semantic insights. * Falls back to heuristic classification when no llmCall is provided or it fails. */ declare class LLMEnricher { /** * Enrich module information with LLM-generated semantic insights. * Falls back to heuristic classification when LLM is unavailable. */ static enrich(options: EnrichOptions): Promise; private static enrichBatch; /** Produce a markdown-formatted insights report */ static formatMarkdown(insights: ModuleInsight[], projectName: string): string; /** Produce a structured JSON summary from insights */ static formatJson(insights: ModuleInsight[]): string; } //#endregion //#region packages/tools/src/maintenance.d.ts interface PruneOptions { /** If true, only report what would be deleted without actually deleting */ dryRun?: boolean; /** Max age in days for stale partitions (default: 90) */ maxAgeDays?: number; /** Max browser profiles to keep (default: 5) */ maxBrowserProfiles?: number; } interface PruneResult { forgeGroundOrphans: { count: number; bytesFreed: number; }; legacyLance: { count: number; bytesFreed: number; }; emptyEphemeral: { count: number; }; stalePartitions: { count: number; bytesFreed: number; }; browserProfiles: { count: number; bytesFreed: number; }; totalBytesFreed: number; dryRun: boolean; } declare function formatBytes(bytes: number): string; declare function prune(options?: PruneOptions): PruneResult; declare function shouldRunStartupPrune(): boolean; declare function markPruneRun(): void; declare function shouldRunWeeklyPromote(): boolean; declare function markPromoteRun(): void; //#endregion //#region packages/tools/src/measure.d.ts /** * aikit_measure — Code complexity and size metrics. */ interface MeasureOptions { path: string; extensions?: string[]; includeHidden?: boolean; } interface FileMetrics { path: string; lines: { total: number; code: number; blank: number; comment: number; }; complexity: number; /** AST-based cognitive complexity that weights nested branches higher (available when WASM is active) */ cognitiveComplexity?: number; functions: number; imports: number; exports: number; } interface MeasureResult { files: FileMetrics[]; summary: { totalFiles: number; totalLines: number; totalCodeLines: number; avgComplexity: number; maxComplexity: { file: string; value: number; }; totalFunctions: number; }; } declare function measure(options: MeasureOptions): Promise; /** Exported for unit testing */ declare function analyzeFile(path: string, content: string): FileMetrics; //#endregion //#region packages/tools/src/onboard.d.ts /** * aikit_onboard — First-time codebase onboarding in a single command. * * Runs all analysis tools in parallel and writes structured output * to ~/.aikit/workspaces// for persistent, reusable access. * Never creates files inside the project workspace. * * Analyses: structure, dependencies, entry-points, symbols, patterns, diagram. * New modes: explore, trace, diff, routes, update. */ type OnboardMode = 'memory' | 'generate'; /** Workspace-level detail level for persona-adaptive output */ type DetailLevel = 'summary' | 'standard' | 'full'; interface OnboardOptions { /** Root path to analyze */ path: string; /** Output mode */ mode?: OnboardMode; /** Output directory (default: ~/.aikit/workspaces//) */ outDir?: string; /** * Explore mode: given a topic, return entry points, related symbols, * and code snippets as a single context package. Uses indexed knowledge. */ explore?: string; /** * Trace mode: BFS traversal from a symbol. Returns callers/callees. */ trace?: string; /** Trace direction: callers, callees, or both */ direction?: 'callers' | 'callees' | 'both'; /** Trace max depth (default 2, max 10) */ maxDepth?: number; /** Edge kinds to follow in trace */ edgeKinds?: string[]; /** * Diff mode: analyze git diff for impact assessment. * true = auto-detect, string = explicit diff content. */ diff?: boolean | string; /** * Routes mode: detect web framework routes. */ routes?: boolean; /** Framework to scan (omit for all supported) */ framework?: string; /** Incremental update mode: merge into existing index */ update?: boolean; /** Detail level for persona-adaptive output */ detail?: DetailLevel; /** Language for localized output (en, zh, ja, ko, ru) */ language?: string; /** Enable LLM-based semantic enrichment (module summaries, architectural roles, tags). Uses the session LLM via MCP sampling. */ enrich?: boolean; /** Callback function for LLM text generation (provided by server layer via MCP sampling). */ llmCall?: (prompt: string, system?: string) => Promise; } /** * Resolve the workspace directory for a given project path. * All output goes here — never inside the project itself. */ declare function resolveWorkspaceDir(rootPath: string): string; interface OnboardStepResult { name: string; status: 'success' | 'failed'; output: string; durationMs: number; error?: string; } interface OnboardResult { /** Root path that was analyzed */ path: string; /** Mode used */ mode: OnboardMode; /** Results for each analysis step */ steps: OnboardStepResult[]; /** Output directory (only set in generate mode) */ outDir?: string; /** Total duration in ms */ totalDurationMs: number; /** Auto-generated AI Kit entries for curated store persistence */ autoRemember?: Array<{ title: string; content: string; category: string; tags: string[]; }>; } /** * Run all onboarding analyses in parallel and return combined results. */ declare function onboard(options: OnboardOptions): Promise; //#endregion //#region packages/tools/src/path-resolver.d.ts /** * Shared path resolver for MCP tools (E-014). * Provides consistent path resolution across all tools. */ /** * Resolve a user-supplied path to an absolute path. * - Absolute paths are returned as-is * - Relative paths are resolved against the server's cwd * - '.' and empty/undefined default to cwd */ declare function resolvePath(input?: string): string; //#endregion //#region packages/tools/src/pipeline.d.ts /** * Pipeline — multi-stage onboarding pipeline: scan → analyze → synthesize → validate. * * This module provides the structured pipeline as an alternative to the * monolithic onboard() function. Each stage is independently testable. * * Usage: * import { runPipeline } from './pipeline.js'; * const result = await runPipeline(rootPath, { mode: 'generate' }); */ interface ScannedFile { path: string; relativePath: string; ext: string; size: number; category: 'source' | 'config' | 'test' | 'documentation' | 'data' | 'build' | 'other'; /** File fingerprint (path + mtime) — not a content hash, just change detection */ fingerprint: string; /** * Resolved import specifiers (KB-15: importMap Pre-Resolution). * Populated during scan phase for source and test files. * Maps each import specifier to its resolved absolute path (or null for * external packages / builtins). */ imports?: Array<{ specifier: string; resolvedPath: string | null; isLocal: boolean; isPackage: boolean; isBuiltin: boolean; fileExtension: string | null; }>; } interface ScanResult { files: ScannedFile[]; sourceFiles: ScannedFile[]; configFiles: ScannedFile[]; testFiles: ScannedFile[]; docFiles: ScannedFile[]; dataFiles: ScannedFile[]; buildFiles: ScannedFile[]; byExtension: Record; /** * Import map: file path → resolved imports (KB-15). * Built during scan phase for all resolvable source files. */ importMap?: Record>; /** * Export map: export name → file path where it's defined (KB-15). * Built during scan phase for all resolvable source files. */ exportMap?: Record; } /** * Scan a codebase directory, categorizing files by type. * Walks the directory tree, skipping common excluded directories. * Returns categorized file lists for use by downstream analysis stages. */ declare function scanCodebase(rootPath: string): Promise; interface PipelineOptions { mode?: 'generate' | 'memory'; /** Only scan, skip deeper analysis */ scanOnly?: boolean; } interface PipelineResult { scan: ScanResult; totalFiles: number; sourceFiles: number; configFiles: number; durationMs: number; } /** * Run the full pipeline: scan → (future) analyze → synthesize → validate. * Currently implements the scan phase with hooks for future stages. */ declare function runPipeline(rootPath: string, _options?: PipelineOptions): Promise; //#endregion //#region packages/tools/src/process-manager.d.ts interface ManagedProcess { id: string; command: string; args: string[]; pid?: number; status: 'running' | 'stopped' | 'error'; startedAt: string; exitCode?: number; logs: string[]; } declare function processStart(id: string, command: string, args?: string[], options?: { cwd?: string; }): ManagedProcess; declare function processStop(id: string): ManagedProcess | undefined; declare function processStatus(id: string): ManagedProcess | undefined; declare function processList(): ManagedProcess[]; declare function processLogs(id: string, tail?: number): string[]; /** Kill all managed processes. Used during server shutdown to prevent zombies. */ declare function processStopAll(): void; //#endregion //#region packages/tools/src/queue.d.ts interface QueueItem { id: string; title: string; status: 'pending' | 'blocked' | 'in-progress' | 'done' | 'failed'; data?: unknown; dependsOn?: string[]; createdAt: string; updatedAt: string; error?: string; } interface QueueState { name: string; items: QueueItem[]; } /** Create a new named queue. */ declare function queueCreate(name: string, cwd?: string): QueueState; /** Push an item onto a queue. Creates the queue if it doesn't exist. */ declare function queuePush(name: string, title: string, data?: unknown, cwd?: string, dependsOn?: string[]): QueueItem; /** Take the next pending item from a queue and mark it in-progress. */ declare function queueNext(name: string, cwd?: string): QueueItem | null; /** Mark a queue item as done. Automatically unblocks dependents whose deps are all satisfied. */ declare function queueDone(name: string, id: string, cwd?: string): { item: QueueItem; unblocked: QueueItem[]; }; /** Mark a queue item as failed with an error message. */ declare function queueFail(name: string, id: string, error: string, cwd?: string): QueueItem; /** Get the current state of a queue. */ declare function queueGet(name: string, cwd?: string): QueueState | null; /** List all queues with their item counts. */ declare function queueList(cwd?: string): Array<{ name: string; pending: number; blocked: number; done: number; failed: number; total: number; }>; /** Clear completed and failed items from a queue. Keeps pending, blocked, and in-progress items. */ declare function queueClear(name: string, cwd?: string): number; /** View queue items organized as a DAG with topologically-sorted execution waves. */ declare function queueDag(name: string, cwd?: string): { waves: string[][]; blocked: string[]; completed: string[]; failed: string[]; }; /** Delete a queue entirely. */ declare function queueDelete(name: string, cwd?: string): boolean; //#endregion //#region packages/tools/src/regex-test.d.ts /** * aikit_regex_test — Test regex patterns against sample strings. */ interface RegexTestOptions { pattern: string; flags?: string; testStrings: string[]; mode?: 'match' | 'replace' | 'split'; replacement?: string; } interface RegexMatchInfo { full: string; groups: (string | undefined)[]; index: number; } interface RegexTestStringResult { input: string; matched: boolean; matches?: RegexMatchInfo[]; replaced?: string; split?: string[]; } interface RegexTestResult { pattern: string; flags: string; results: RegexTestStringResult[]; valid: boolean; error?: string; } declare function regexTest(options: RegexTestOptions): RegexTestResult; //#endregion //#region packages/tools/src/regex-utils.d.ts /** * Escape special regular-expression characters in a string so it can be * embedded safely inside a `new RegExp(...)` expression. */ declare function escapeRegExp(value: string): string; //#endregion //#region packages/tools/src/rename.d.ts interface RenameOptions { /** Symbol to rename */ oldName: string; /** New symbol name */ newName: string; /** Root directory to search in */ rootPath: string; /** File extensions to process (default: .ts, .tsx, .js, .jsx) */ extensions?: string[]; /** Glob patterns to exclude */ exclude?: string[]; /** Dry run — don't write changes */ dryRun?: boolean; } interface RenameChange { path: string; line: number; before: string; after: string; } interface RenameResult { oldName: string; newName: string; changes: RenameChange[]; filesModified: number; dryRun: boolean; } declare function rename(options: RenameOptions): Promise; //#endregion //#region packages/tools/src/restore-points.d.ts interface RestorePoint { id: string; timestamp: string; operation: 'codemod' | 'rename' | 'forget'; files: Array<{ path: string; content: string; }>; description: string; } /** Create a restore point before a destructive operation */ declare function createRestorePoint(operation: RestorePoint['operation'], files: Array<{ path: string; content: string; }>, description: string): string; /** List all restore points (newest first) */ declare function listRestorePoints(): RestorePoint[]; /** Restore files from a restore point, returns list of restored paths */ declare function restoreFromPoint(id: string): Promise; //#endregion //#region packages/tools/src/schema-validate.d.ts /** * aikit_schema_validate — Validate data against a JSON Schema (core subset). * * Supports: type, required, properties, additionalProperties, items, * enum, const, pattern, minimum, maximum, minLength, maxLength, * minItems, maxItems. */ interface SchemaValidateOptions { data: unknown; schema: Record; } interface ValidationError { path: string; message: string; expected?: string; received?: string; } interface SchemaValidateResult { valid: boolean; errors: ValidationError[]; } declare function schemaValidate(options: SchemaValidateOptions): SchemaValidateResult; //#endregion //#region packages/tools/src/search-response.d.ts interface SearchResponseItem { sourcePath: string; contentType: string; score: number; headingPath?: string; startLine?: number; endLine?: number; origin?: string; category?: string; tags?: string[]; } interface SearchResponseData { results: SearchResponseItem[]; totalResults: number; searchMode: string; query: string; } interface SearchSuccessResponseOptions { text: string; query: string; searchMode: string; limit: number; results: SearchResponseItem[]; durationMs: number; truncated?: boolean; caveats?: string[]; } declare function createSearchSuccessResponse(opts: SearchSuccessResponseOptions): AikitResponse; declare function createSearchErrorResponse(message: string, durationMs: number): AikitResponse; //#endregion //#region packages/tools/src/stash.d.ts interface StashEntry { key: string; value: unknown; type: string; storedAt: string; } interface StashStore { stashGet(key: string): string | undefined; stashSet(key: string, value: string): void; stashList(): Array<{ key: string; value: string; updatedAt: string; }>; stashDelete(key: string): boolean; stashClear(): void; } interface LegacyStashOptions { cwd?: string; stateDir?: string; } declare function ensureLegacyStashImported(stateStore: StashStore, options?: LegacyStashOptions): void; declare function stashSet(stateStore: StashStore, key: string, value: unknown, cwd?: string): StashEntry; declare function stashGet(stateStore: StashStore, key: string, cwd?: string): StashEntry | undefined; declare function stashList(stateStore: StashStore, cwd?: string): StashEntry[]; declare function stashDelete(stateStore: StashStore, key: string, cwd?: string): boolean; declare function stashClear(stateStore: StashStore, cwd?: string): number; //#endregion //#region packages/tools/src/session-digest.d.ts interface SessionDigestOptions { scope?: 'tools' | 'stash' | 'all'; since?: string; last?: number; focus?: string; mode?: 'deterministic' | 'sampling'; tokenBudget?: number; persist?: boolean; } interface SessionDigestResult { digest: string; stats: { replayEntries: number; stashKeys: number; checkpoints: number; errors: number; toolsUsed: string[]; }; persistedKey?: string; } interface SessionDigestDeps { replayEntries?: ReplayEntry[]; stashEntries?: StashEntry[]; checkpoints?: CheckpointSummary[]; persistEntry?: (key: string, value: unknown) => StashEntry; stateStore?: CheckpointStore & StashStore; now?: Date; } declare function sessionDigest(options?: SessionDigestOptions, deps?: SessionDigestDeps): SessionDigestResult; declare function sessionDigestSampling(options: SessionDigestOptions, samplingFn: (prompt: string, systemPrompt: string, maxTokens: number) => Promise, deps?: SessionDigestDeps): Promise; //#endregion //#region packages/tools/src/skill-matcher.d.ts interface SkillTriggerExamples { positive: string[]; negative: string[]; } interface SkillTriggerMeta { name: string; triggerKeywords: string[]; triggerPatterns: string[]; triggerExamples: SkillTriggerExamples; priority: number; } interface SkillMatch { name: string; score: number; matchedKeywords: string[]; matchedPatterns: string[]; } declare function matchSkills(query: string, skills: SkillTriggerMeta[]): SkillMatch[]; //#endregion //#region packages/tools/src/symbol-resolver.d.ts type ResolutionMethod = 'ast' | 'regex' | 'semantic' | 'llm'; interface Definition { path: string; line: number; kind: string; signature?: string; /** JSDoc/comment extracted from AST */ doc?: string; } interface Reference { path: string; line: number; /** Surrounding code context (max ~80 chars) */ context?: string; scope?: string; } interface Resolution { symbol: string; definition?: Definition; importers: Reference[]; references: Reference[]; /** Confidence 0.0-1.0. >0.8 = reliable, >0.5 = plausible, <0.5 = best guess */ confidence: number; /** Which tier produced the result */ method: ResolutionMethod; /** Human-readable explanation of how the resolution was reached */ rationale?: string; } interface ResolutionOptions { /** Symbol name to resolve */ name: string; /** Knowledge store for semantic search */ store: IKnowledgeStore; /** Embedder for vector search queries */ embedder: IEmbedder; /** Optional: enable LLM disambiguation tier (opt-in, default false) */ useLLM?: boolean; /** Max results per tier (default: 10) */ limit?: number; /** Optional: file content to search in (for Tier 1 direct AST extract) */ content?: string; /** Optional: file extension hint (e.g., '.ts', '.py') */ ext?: string; /** * Optional: LLM disambiguation callback for Tier 3. * When provided and Tier 2 returns ambiguous results, this callback is invoked * with the symbol name and candidate context to select the best match. * Should return a normalized file path, or null if it can't determine. * * The server layer can inject a function that uses mcp_aikit_delegate * or any available LLM mechanism to perform this disambiguation. */ llmDisambiguate?: (symbolName: string, candidates: Array<{ path: string; line: number; context: string; }>) => Promise; } /** * Resolve a symbol using the 3-tier hybrid approach. * * 1. Try Tier 1 (AST) if content + supported extension provided * 2. Fall back to Tier 2 (regex/semantic) via knowledge store * 3. Optionally run Tier 3 (LLM disambig) if enabled and ambiguity exists * * Returns the best resolution found, or null if symbol could not be resolved. */ declare function resolveSymbol(options: ResolutionOptions): Promise; /** * Resolve multiple symbols in batch. */ declare function resolveSymbols(symbols: string[], options: Omit): Promise>; //#endregion //#region packages/tools/src/symbol.d.ts interface SymbolGraphContext { /** Module that defines this symbol */ definingModule?: string; /** Modules that import the file containing this symbol */ importedByModules: string[]; /** Symbols defined in the same module */ siblingSymbols: string[]; } interface SymbolInfo { name: string; definedIn?: { path: string; line: number; kind: string; signature?: string; }; importedBy: Array<{ path: string; line: number; importStatement: string; }>; referencedIn: Array<{ path: string; line: number; context: string; scope?: string; }>; /** Graph-derived context (when graph store available) */ graphContext?: SymbolGraphContext; /** Transitive trace results (when direction/maxDepth provided) */ trace?: { callers: Array<{ name: string; path: string; depth: number; }>; callees: Array<{ name: string; path: string; depth: number; }>; }; /** Confidence score from hybrid resolver (0.0-1.0) */ confidence?: number; /** Which tier produced the result */ method?: ResolutionMethod; /** Human-readable rationale */ rationale?: string; } interface SymbolOptions { /** Symbol name to look up */ name: string; /** Limit results */ limit?: number; /** Optional graph store for enriching results */ graphStore?: IGraphStore; /** Optional trace direction for graph-based transitive traversal */ direction?: 'callers' | 'callees' | 'both'; /** Max traversal depth (default: 2, max: 10) */ maxDepth?: number; /** Filter edges by type (e.g., ['imports', 'calls']) */ edgeKinds?: string | string[]; /** Enable Tier 3 LLM disambiguation (opt-in, default false) */ useLLM?: boolean; /** * Custom LLM disambiguation callback. * When useLLM is true and this is omitted, a default implementation * using the local Ollama delegate is used. */ llmDisambiguate?: (symbolName: string, candidates: Array<{ path: string; line: number; context: string; }>) => Promise; } declare function symbol(embedder: IEmbedder, store: IKnowledgeStore, options: SymbolOptions): Promise; //#endregion //#region packages/tools/src/test-run.d.ts interface TestRunOptions { files?: string[]; cwd?: string; timeout?: number; grep?: string; /** Include full raw output in result (default: false to save tokens) */ includeRaw?: boolean; } interface TestRunResult { summary: ParsedTestSummary; passed: boolean; raw?: string; durationMs: number; } declare function testRun(options?: TestRunOptions): Promise; /** * Classify non-zero exit codes — some tools use exit code 1 for * non-error conditions (e.g., grep returns 1 for "no matches"). */ declare function classifyExitCode(exitCode: number, _stdout: string, command?: string): { isError: boolean; reason?: string; }; //#endregion //#region packages/tools/src/text-utils.d.ts /** * Shared text utilities used by compact, digest, stratum-card, and other tools. */ /** * Estimate token count with content-type awareness. * More accurate than the simple 4-char heuristic for code and structured data. */ declare function estimateTokens(text: string): number; /** * Segment text into chunks for scoring. */ declare function segment(text: string, strategy: 'paragraph' | 'sentence' | 'line'): string[]; /** * Cosine similarity between two vectors. */ declare function cosineSimilarity(a: Float32Array, b: Float32Array): number; /** * Reorder items using "bookend" strategy (Liu et al. 2023 "Lost in the Middle"). * Highest-scoring items placed at start and end positions for better LLM attention. * Input must already be sorted by score descending. */ declare function bookendReorder(items: T[]): T[]; //#endregion //#region packages/tools/src/time-utils.d.ts /** * aikit_time — Timezone conversion, date parsing, duration calculation. */ type TimeOperation = 'now' | 'parse' | 'convert' | 'diff' | 'add'; interface TimeOptions { operation: TimeOperation; input?: string; timezone?: string; duration?: string; } interface TimeResult { output: string; iso: string; unix: number; details?: Record; } declare function timeUtils(options: TimeOptions): TimeResult; //#endregion //#region packages/tools/src/token-benchmark.d.ts interface CorpusFile { path: string; content: string; mode: 'code' | 'prose'; } interface CorpusStats { fileCount: number; totalChars: number; totalTokens: number; codeTokens: number; proseTokens: number; byExtension: Record; } /** * Measure token count for a set of corpus files. */ declare function measureCorpus(files: CorpusFile[]): CorpusStats; interface GraphStats { nodeCount: number; edgeCount: number; estimatedTokens: number; reductionRatio: number; } /** * Estimate the token cost of a knowledge graph representation. * Each node: id (1 token) + label (2 tokens) + type (1 token) + overhead = ~5 tokens * Each edge: source (1) + target (1) + relation (1) + overhead = ~4 tokens * Plus structural overhead for schema/metadata. */ declare function estimateGraphTokens(nodes: number, edges: number): number; interface BenchmarkReport { corpus: CorpusStats; graph: GraphStats; /** Reduction ratio (graph / corpus). <1 means graph is smaller. */ ratio: number; /** Percentage reduction (1 - ratio) * 100 */ reductionPercent: number; /** Human-readable summary */ summary: string; } /** * Run a full token reduction benchmark. * * @param files - Corpus files to benchmark * @param estimateNodes - Estimated number of graph nodes (default: inferred) * @param estimateEdges - Estimated number of graph edges (default: inferred) */ declare function benchmarkTokenReduction(files: CorpusFile[], estimateNodes?: number, estimateEdges?: number): BenchmarkReport; /** * Benchmark token reduction for a list of file paths by reading their contents. */ declare function benchmarkFiles(filePaths: string[], estimateNodes?: number, estimateEdges?: number): Promise; //#endregion //#region packages/tools/src/trace.d.ts interface TraceOptions { /** Starting point — a symbol or file:line reference */ start: string; /** Direction */ direction: 'forward' | 'backward' | 'both'; /** Max depth (default: 3) */ maxDepth?: number; /** Optional graph store for enriching results */ graphStore?: IGraphStore; /** * Filter graph enrichment by edge kinds (e.g., ['imports', 'calls']). * When set, only relationships matching these edge types are included in graph context. * AST-based call detection is unaffected — this only filters graph enrichment metadata. */ edgeKinds?: string[]; } interface TraceGraphContext { /** Module that defines the traced symbol */ definingModule?: string; /** Community/cluster of the traced symbol */ community?: string; /** Modules that import the file containing this symbol */ importedByModules: string[]; /** Symbols defined in the same module */ siblingSymbols: string[]; } interface TraceNode { path: string; symbol: string; line: number; relationship: 'calls' | 'called-by' | 'imports' | 'imported-by' | 'references'; /** The enclosing function/scope where the relationship occurs (AST-powered) */ scope?: string; } interface TraceResult { start: string; direction: string; nodes: TraceNode[]; depth: number; /** Graph-derived context (when graph store available) */ graphContext?: TraceGraphContext; } declare function trace(embedder: IEmbedder, store: IKnowledgeStore, options: TraceOptions): Promise; //#endregion //#region packages/tools/src/truncation.d.ts /** * Truncate text keeping both head and tail portions. * Critical for process output where errors appear at the end. * * @param text - Full text to truncate * @param maxLen - Maximum character length * @param headRatio - Fraction for head portion (default 0.6) * @returns Truncated text with separator showing omitted line/char count */ declare function headTailTruncate(text: string, maxLen: number, headRatio?: number): string; /** * Truncate at a paragraph boundary near maxLength (head-only). * Best for web content and markdown where structure is at the top. */ declare function paragraphTruncate(text: string, maxLen: number): string; /** * Truncate text to fit within a token budget. * Uses ~4 chars/token approximation. Snaps to line boundaries. * * @param text - Full text to truncate * @param maxTokens - Maximum token count * @returns Original text if within budget, or truncated with notice */ declare function truncateToTokenBudget(text: string, maxTokens: number): string; //#endregion //#region packages/tools/src/watch.d.ts interface WatchEvent { type: 'change' | 'rename'; path: string; timestamp: string; } interface WatchOptions { /** Directory to watch */ path: string; /** Glob patterns to exclude */ exclude?: string[]; /** Max events to buffer (default: 100) */ maxEvents?: number; /** Auto-sync: track pending files for re-onboarding (default: false) */ autoSync?: boolean; /** Debounce interval in ms for auto-sync (default: 2000) */ debounceMs?: number; /** Callback invoked with pending files after debounce (when autoSync=true). May be async — errors are caught and files re-queued. */ onBatch?: (files: string[]) => void | Promise; } interface WatchHandle { id: string; path: string; events: WatchEvent[]; status: 'watching' | 'stopped'; stop: () => void; getEvents: (since?: string) => WatchEvent[]; /** Pending files (when autoSync enabled) */ pendingFiles: string[]; /** Clear pending files after processing */ clearPending: () => void; } declare function watchStart(options: WatchOptions): WatchHandle; declare function watchStop(id: string): boolean; declare function watchList(): Array<{ id: string; path: string; status: string; eventCount: number; pendingFiles: string[]; }>; //#endregion //#region packages/tools/src/web-fetch.d.ts /** * aikit_web_fetch — Fetch a web page and convert to LLM-friendly format. * * Supports multiple output modes: markdown (default), raw HTML, * extracted links, or heading outline. Strips scripts, styles, * and non-content elements for compact, token-efficient output. */ type WebFetchMode = 'markdown' | 'raw' | 'links' | 'outline'; interface WebFetchOptions { /** URL to fetch */ url: string; /** Output mode */ mode?: WebFetchMode; /** CSS selector to extract specific element (default: auto-detect main content) */ selector?: string; /** Max characters in output — smart truncation at paragraph boundaries */ maxLength?: number; /** Include page metadata header (title, description, URL) */ includeMetadata?: boolean; /** Append extracted links list at the end */ includeLinks?: boolean; /** Include image alt texts inline */ includeImages?: boolean; /** Request timeout in milliseconds */ timeout?: number; /** * Allow requests to localhost/loopback addresses. * false by default (SSRF protection). Set true for local dev servers. * When true, bypasses DNS resolution + private IP blocking for * 127.0.0.1, localhost, ::1, and 0.0.0.0. */ allowLocalhost?: boolean; } interface WebFetchResult { /** The converted content */ content: string; /** Page title */ title: string; /** Page description (from meta) */ description: string; /** Final URL after redirects */ url: string; /** Content length before truncation */ originalLength: number; /** Whether content was truncated */ truncated: boolean; } /** * Fetch a web page and convert to an LLM-friendly format. */ declare function webFetch(options: WebFetchOptions): Promise; //#endregion //#region packages/tools/src/web-search.d.ts /** * aikit_web_search — Search the web and return structured results. * * Providers: * - `multi` (default) — fan-out to keyless providers in parallel, * race against a deadline, return the * deduplicated union. Default fan-out: * DuckDuckGo + Bing (HTML) + Mojeek. * Optional providers (SearXNG, Google, * Brave, Bing API) join the fan-out * automatically when their env vars are set. * - `duckduckgo` — DuckDuckGo HTML scrape (no API key) * - `bing-html` — Bing HTML scrape (no API key) * - `mojeek` — Mojeek HTML scrape (no API key, independent crawler) * - `searxng` — Self-hosted/public SearXNG JSON API * requires SEARXNG_URL (optional SEARXNG_API_KEY) * - `google` — Google Custom Search JSON API * requires GOOGLE_API_KEY + GOOGLE_CSE_ID * - `brave` — Brave Search API * requires BRAVE_API_KEY * - `bing` — Bing Web Search v7 API * requires BING_API_KEY * * Provider resolution order: * 1. explicit `provider` argument * 2. AIKIT_SEARCH_PROVIDER env var * 3. fallback to `multi` * * For the `multi` provider, the deadline (default 10s, override via * `deadlineMs` arg or AIKIT_SEARCH_DEADLINE_MS env) bounds total wall time. * Individual sources still each have a 15s per-request timeout, but the * deadline cuts the wait short — whatever results have arrived are returned. * * For single keyed providers, missing credentials trigger graceful * fallback to DuckDuckGo with a note in `result.provider`. */ type WebSearchProvider = 'multi' | 'duckduckgo' | 'bing-html' | 'mojeek' | 'searxng' | 'google' | 'brave' | 'bing'; interface WebSearchOptions { query: string; limit?: number; site?: string; /** Provider override. Defaults to env AIKIT_SEARCH_PROVIDER, then 'multi'. */ provider?: WebSearchProvider; /** Deadline in ms for the `multi` fan-out. Default 10000. */ deadlineMs?: number; } interface WebSearchResultItem { title: string; url: string; snippet: string; /** Providers that returned this URL (only present for `multi`). */ sources?: string[]; /** Combined consensus rank (only present for `multi`; lower is better). */ rank?: number; } interface ProviderStatus { name: string; status: 'ok' | 'timeout' | 'error' | 'skipped'; count: number; elapsedMs: number; } interface WebSearchResult { results: WebSearchResultItem[]; query: string; /** Effective provider description (e.g. "duckduckgo+searxng" or "google"). */ provider: string; /** Per-provider status (only populated for `multi`). */ providers?: ProviderStatus[]; } declare function webSearch(options: WebSearchOptions): Promise; /** Parse search results from DuckDuckGo HTML. Exported for testing. */ declare function parseSearchResults(html: string, query: string, limit: number): Omit; //#endregion //#region packages/tools/src/workset.d.ts /** * aikit_workset — Named file set management. * * Persistent worksets stored in the AI Kit state directory. * Use cases: "remember this set of files I'm working on", * "load my previous context", "share file sets between sessions". */ interface Workset { name: string; files: string[]; created: string; updated: string; description?: string; } interface WorksetStore { worksets: Record; } /** * Create or update a workset. */ declare function saveWorkset(name: string, files: string[], options?: { description?: string; cwd?: string; }): Workset; /** * Get a workset by name. */ declare function getWorkset(name: string, cwd?: string): Workset | null; /** * List all worksets. */ declare function listWorksets(cwd?: string): Workset[]; /** * Delete a workset. */ declare function deleteWorkset(name: string, cwd?: string): boolean; /** * Add files to an existing workset (creates if not exists). */ declare function addToWorkset(name: string, files: string[], cwd?: string): Workset; /** * Remove files from a workset. */ declare function removeFromWorkset(name: string, files: string[], cwd?: string): Workset | null; //#endregion export { type AikitNextHint, type AikitResponse, type AikitResponseMeta, type AikitToolError, type AikitToolErrorCode, type AuditCheck, type AuditData, type AuditOptions, type AuditRecommendation, BRIEFING_CARD_FAMILIES, type BenchmarkReport, type BlastNode, type ChangelogEntry, type ChangelogFormat, type ChangelogOptions, type ChangelogResult, type CheckOptions, type CheckResult, type CheckSummaryResult, type Checkpoint, type CheckpointSummary, type ClassifyTrigger, type CodemodChange, type CodemodOptions, type CodemodResult, type CodemodRule, type CommunityInfo, type CompactOptions, type CompactResult, type ComplianceReport, type ComplianceRule, type ComplianceScoreOptions, type ComplianceViolation, type CompressOutputOptions, type CompressionContext, type CompressionMode, type CompressionResult, type CompressionRule, type ConstraintRef, type CorpusStats, type DeadSymbol, type DeadSymbolOptions, type DeadSymbolResult, type Definition, type DelegateOptions, type DelegateResult, type DetectedRoute, type DiffChange, type DiffFile, type DiffHunk, type DiffParseOptions, type DiffReport, type DigestFieldEntry, type DigestOptions, type DigestResult, type DigestSource, type DogfoodLogEntry, type DogfoodLogGroupedEntry, type DogfoodLogOptions, type DogfoodLogResult, type Domain, type DomainAnalysisInput, type DomainClassification, type DomainType, type EncodeOperation, type EncodeOptions, type EncodeResult, type EnrichOptions, type EnrichStructureEntry, type EnrichSymbolEntry, type EnvInfoOptions, type EnvInfoResult, type EvalOptions, type EvalResult, type EvidenceEntry, type EvidenceMapAction, type EvidenceMapResult, type EvidenceMapState, type EvidenceStatus, type Example, type ExportMap, ExtractionCache, type ExtractionCacheEntry, FileCache, type FileCacheEntry, type FileCacheStats, type FileChange, type FileMetrics, type FileSummaryOptions, type FileSummaryResult, type FileSummaryToolCard, type FileSummaryToolOptions, type FileSummaryToolResult, type FindExamplesOptions, type FindExamplesResult, type FindOptions, type FindResult, type FindResults, type Finding, type FindingSeverity, type ForgeClassifyCeremony, type ForgeClassifyOptions, type ForgeClassifyResult, type ForgeGroundOptions, type ForgeGroundResult, type ForgeTier, GIT_REF_SLUG_PATTERN, type GateConfig, type GateDecision, type GateResult, type GitContextOptions, type GitContextResult, type GraphAugmentOptions, type GraphAugmentedResult, type GraphQueryOptions, type GraphQueryResult, type GraphReviewReport, type GraphStats, type GuideRecommendation, type GuideResult, type GuidedTour, type GuidedTourOptions, type HealthCheck, type HealthResult, type HotspotEntry, type HttpMethod, type HttpRequestOptions, type HttpRequestResult, type ImportGraph, type ImportMap, type KnowledgeGraph, type L0CardInput, LLMEnricher, type LaneDiffEntry, type LaneDiffResult, type LaneMergeResult, type LaneMeta, type LayerDetectionInput, type LayerType, type Lease, type LeaseConflict, type LegacyStashOptions, MAX_CARD_CHARS, type ManagedProcess, type MeasureOptions, type MeasureResult, type ModuleInsight, type OnboardMode, type OnboardOptions, type OnboardResult, type OnboardStepResult, type ParsedError, type ParsedGitStatus, type ParsedOutput, type ParsedTestResult, type ParsedTestSummary, type PipelineResult, type PruneOptions, type PruneResult, type QueueItem, type QueueState, type RegexTestOptions, type RegexTestResult, type RenameChange, type RenameOptions, type RenameResult, type ReplayEntry, type ReplayOptions, type Resolution, type ResolutionMethod, type ResolutionOptions, type ResolvedImport, type RestorePoint, type ReverseGraph, type RouteDetectionResult, type SafetyGate, type SafetyGateResult, type ScanResult, type ScannedFile, type SchemaValidateOptions, type SchemaValidateResult, type ScopeMapEntry, type ScopeMapOptions, type ScopeMapResult, type SearchResponseData, type SearchResponseItem, type SearchSuccessResponseOptions, type SessionDigestOptions, type SessionDigestResult, type SessionStartSelection, type SkillMatch, type SkillTriggerExamples, type SkillTriggerMeta, type StashEntry, type StashStore, type SymbolGraphContext, type SymbolInfo, type SymbolOptions, type TestRunOptions, type TestRunResult, type TimeOptions, type TimeResult, type TimeoutAction, type TourStep, type TraceNode, type TraceOptions, type TraceResult, type TransformOptions, type TransformResult, type TypedUnknownSeed, type UnknownType, type ValidationError, WORKSPACE_CORE_FILENAME, type WatchEvent, type WatchHandle, type WatchOptions, type WebFetchMode, type WebFetchOptions, type WebFetchResult, type WebSearchOptions, type WebSearchResult, type WebSearchResultItem, type Workset, type WorksetStore, acquireLease, addToWorkset, analyzeDiff, analyzeDomain, analyzeDomains, analyzeFile, audit, autoClaimTestFailures, benchmarkFiles, benchmarkTokenReduction, bookendReorder, bpeSurprise, buildExportMap, buildImportGraph, buildImportMap, buildNodeNameMap, buildReverseGraph, callId, changelog, check, checkEmptyGraph, checkMissingFields, checkSchemaVersion, checkpointDiff, checkpointGC, checkpointHistory, checkpointLatest, checkpointList, checkpointLoad, checkpointSave, classifyDomain, classifyDomains, classifyExitCode, codemod, compact, compressOutput, compressTerminalOutput, cosineSimilarity, createRestorePoint, createSearchErrorResponse, createSearchSuccessResponse, dataTransform, delegate, delegateListModels, deleteWorkset, describeBriefingCards, detectLayer, detectLayers, detectOutputTool, detectRoutes, diffParse, digest, dogfoodLog, edgeId, encode, ensureLegacyStashImported, envInfo, errorResponse, escapeRegExp, estimateGraphTokens, estimateSessionTokenBudget, estimateTokens, evaluate, evidenceMap, extractImports, extractRoutesFromFile, fileId, fileSummary, fileSummaryTool, find, findDanglingEdges, findDeadSymbols, findDuplicateIds, findExamples, findOrphanNodes, findSelfLoops, findTour, forgeClassify, forgeGround, formatBytes, formatChangelog, formatDomainReport, formatEmptyResult, formatTour, formatToursIndex, generateGuidedTours, generateL0WorkspaceCoreCard, getRegisteredRules, getSessionStartCards, getWorkset, gitAvailable, gitCommitToRef, gitContext, gitExec, graphAugmentSearch, graphQuery, groupByDomain, guide, headTailTruncate, health, httpRequest, inferNextjsRoutes, laneCreate, laneDiff, laneDiscard, laneList, laneMerge, laneStatus, listActiveLeases, listRestorePoints, listWorksets, markPromoteRun, markPruneRun, matchSkills, measure, measureCorpus, normalizePath, okResponse, onboard, orderByDependency, paragraphTruncate, parseBiome, parseGitStatus, parseOutput, parseSearchResults, parseTsc, parseVitest, processList, processLogs, processStart, processStatus, processStop, processStopAll, prune, queueClear, queueCreate, queueDag, queueDelete, queueDone, queueFail, queueGet, queueList, queueNext, queuePush, regexTest, registerRule, registerRules, releaseLease, removeFromWorkset, rename, replayAppend, replayCapture, replayClear, replayList, replayTrim, resetGitCache, resolveImportPath, resolveL0CardDir, resolveNodeName, resolvePath, resolveSymbol, resolveSymbols, resolveWorkspaceDir, restoreFromPoint, reviewGraph, runPipeline, saveWorkset, scanCodebase, schemaValidate, scopeMap, scoreCompliance, scoreLine, scoreLines, segment, sessionDigest, sessionDigestSampling, shannonEntropy, shouldRunStartupPrune, shouldRunWeeklyPromote, slugForRef, stashClear, stashDelete, stashGet, stashList, stashSet, storeReversibleContext, summarizeCheckResult, symbol, symbolId, testRun, timeUtils, trace, transformCommunities, traverseBlastRadius, truncateToTokenBudget, watchList, watchStart, watchStop, webFetch, webSearch, workspacePath };