import { EventEmitter } from "node:events"; //#region packages/core/src/circuit-breaker.d.ts type CircuitState = 'closed' | 'open' | 'half-open'; interface CircuitBreakerOptions { /** Failures before opening. */ threshold?: number; /** How long the circuit stays open in milliseconds. */ cooldownMs?: number; /** Max probe attempts allowed while half-open. */ halfOpenMaxAttempts?: number; /** Random jitter added to the cooldown window in milliseconds. */ jitterMs?: number; /** Optional name for registry lookup (e.g. 'embedder', 'er-bridge'). */ name?: string; /** Called on state transitions. */ onStateChange?: (from: CircuitState, to: CircuitState) => void; } /** * Shared circuit breaker primitive for transient subsystem failures. */ declare class CircuitBreaker extends EventEmitter { private static readonly registry; private state; private failures; private halfOpenAttempts; private openUntil; private readonly threshold; private readonly cooldownMs; private readonly halfOpenMaxAttempts; private readonly jitterMs; private readonly name?; private readonly onStateChange?; /** Get all named circuit breakers. */ static getAll(): ReadonlyMap; /** Get a named circuit breaker. */ static get(name: string): CircuitBreaker | undefined; /** Clear the registry (for tests). */ static clearRegistry(): void; constructor(options?: CircuitBreakerOptions); /** * Execute an async operation through the circuit breaker. */ execute(fn: () => Promise): Promise; /** * Get the current breaker state. */ getState(): CircuitState; /** Get this breaker's registered name. */ getName(): string | undefined; /** * Return whether the breaker is currently blocking requests. */ isOpen(): boolean; /** * Reset the breaker to the closed state. */ reset(): void; /** Remove this breaker from the registry and clean up listeners. */ dispose(): void; /** * Force the breaker open immediately. */ forceOpen(reason?: string): void; /** * Record a successful probe or request. */ recordSuccess(): void; /** * Record a failed probe or request. */ recordFailure(): void; /** * Return remaining cooldown time in milliseconds. */ remainingCooldownMs(): number; private assertNotOpen; private refreshState; private transitionTo; private computeOpenUntil; } /** * Error thrown when a request is blocked by an open circuit. */ declare class CircuitOpenError extends Error { readonly remainingMs: number; constructor(remainingMs: number); } //#endregion //#region packages/core/src/constants.d.ts /** * Default constants for the AI Kit system. */ /** * Centralized directory paths for all AI Kit artifacts. * Single source of truth — change here to update everywhere. */ declare const AIKIT_PATHS: { /** AI Kit runtime root directory */readonly root: ".aikit"; /** AI artifacts root directory */ readonly ai: ".ai"; /** Onboard / produce_knowledge output directory */ readonly aiContext: ".ai/context"; /** Curated knowledge directory */ readonly aiCurated: ".ai/curated"; /** Restore points for destructive operations (codemod, rename, forget) */ readonly restorePoints: ".ai/restore-points"; /** Vector store + graph data */ readonly data: ".aikit/data"; /** Session state (stash, lanes, checkpoints, worksets, queues, replay, evidence-maps, snippets) */ readonly state: ".aikit/state"; /** Persistent warn/error logs for dogfooding review */ readonly logs: ".aikit/logs"; /** Brainstorming sessions */ readonly brainstorm: ".brainstorm"; /** Session handoff documents */ readonly handoffs: ".handoffs"; }; /** * Runtime directories stored inside ~/.aikit/workspaces//. * These are the default durable locations for non-flow runtime artifacts. */ declare const AIKIT_RUNTIME_PATHS: { /** Vector store + graph data directory */readonly data: "data"; /** Curated knowledge directory */ readonly curated: "curated"; /** Onboard / produce_knowledge output directory */ readonly onboard: "onboard"; /** Session state directory */ readonly state: "state"; /** Restore points for destructive operations */ readonly restorePoints: "restore-points"; /** Brainstorming sessions */ readonly brainstorm: "brainstorm"; /** Session handoff documents */ readonly handoffs: "handoffs"; /** L0 generated briefing cards (workspace memories) */ readonly l0Cards: "memories"; }; /** * Global-mode directory paths (under ~/.aikit/). * Used when AI Kit is installed at user level rather than per-workspace. */ declare const AIKIT_GLOBAL_PATHS: { /** Root directory name for global data store */readonly root: ".aikit"; /** Registry file tracking all enrolled workspaces */ readonly registry: "registry.json"; /** Workspace partitions directory */ readonly workspaces: "workspaces"; /** Shared runtime logs directory */ readonly logs: "logs"; /** Shared state migration target for legacy home-level state */ readonly state: "state"; /** Legacy global data directory name */ readonly legacyDataRoot: ".aikit-data"; /** Legacy global state directory name */ readonly legacyStateRoot: ".aikit-state"; }; /** Default chunk sizes by content type */ declare const CHUNK_SIZES: { readonly markdown: { readonly max: 1500; readonly min: 100; }; readonly code: { readonly max: 2000; readonly min: 50; }; readonly config: { readonly max: 3000; readonly min: 50; }; readonly default: { readonly max: 1500; readonly min: 100; readonly overlap: 200; }; }; /** Default embedding profile */ declare const EMBEDDING_DEFAULTS: { readonly model: "mixedbread-ai/mxbai-embed-xsmall-v1"; /** Native output dimensions before truncation */ readonly nativeDim: 384; /** Effective output dimensions (matryoshka truncation from native 384) */ readonly dimensions: 384; /** Query prefix applied by the profile. Defaults to empty string for backward compatibility. */ readonly queryPrefix: ""; }; /** Per-model capability registry for auto-resolution. * Maps model ID to known settings. OnnxEmbedder constructor uses this * to auto-fill dimensions, nativeDim, queryPrefix, and pooling when * only the model ID is specified in config. */ declare const MODEL_REGISTRY: Record; /** Default store config */ declare const STORE_DEFAULTS: { readonly backend: "sqlite-vec"; readonly path: ".aikit/data"; readonly tableName: "knowledge"; }; /** * npm install args for production dependency installation. * Single source of truth — change here to update all install sites. * Strategy: `nested` isolates native modules (better-sqlite3); * change to `hoisted` if transitive dep resolution issues arise. */ declare const INSTALL_ARGS: readonly ["install", "--production", "--install-strategy=nested", "--no-audit", "--no-fund", "--loglevel=error"]; /** File size limits */ declare const FILE_LIMITS: { readonly maxFileSizeBytes: 1000000; readonly maxCuratedFileSizeBytes: 50000; }; /** Search defaults */ declare const SEARCH_DEFAULTS: { readonly maxResults: 10; readonly minScore: 0.25; }; /** Category validation regex */ declare const CATEGORY_PATTERN: RegExp; /** Default knowledge categories */ declare const DEFAULT_CATEGORIES: readonly ["decisions", "patterns", "troubleshooting", "conventions", "architecture"]; //#endregion //#region packages/core/src/types.d.ts /** * Core types for the MCP AI Kit system. */ /** The origin of a knowledge record — how it was created */ declare const KNOWLEDGE_ORIGINS: readonly ["indexed", "curated", "produced"]; type KnowledgeOrigin = (typeof KNOWLEDGE_ORIGINS)[number]; /** Coarse source classification derived from ContentType */ declare const SOURCE_TYPES: readonly ["source", "documentation", "test", "config", "generated"]; type SourceType = (typeof SOURCE_TYPES)[number]; /** Indexing mode */ declare const INDEX_MODES: readonly ["auto", "manual", "smart"]; type IndexMode = (typeof INDEX_MODES)[number]; /** Token budget — controls default detail level for tool outputs */ declare const TOKEN_BUDGETS: readonly ["efficient", "normal", "full"]; type TokenBudget = (typeof TOKEN_BUDGETS)[number]; /** Content type classification */ declare const CONTENT_TYPES: readonly ["documentation", "code-typescript", "code-javascript", "code-python", "code-other", "config-json", "config-yaml", "config-toml", "config-env", "test-code", "cdk-stack", "markdown", "curated-knowledge", "produced-knowledge", "unknown"]; type ContentType = (typeof CONTENT_TYPES)[number]; /** A single knowledge record stored in the vector DB */ interface KnowledgeRecord { /** Unique identifier (deterministic hash of source + chunk index) */ id: string; /** The text content of this chunk */ content: string; /** Source file path relative to workspace root */ sourcePath: string; /** Content type classification */ contentType: ContentType; /** Heading path for markdown (e.g., "## Setup > ### Prerequisites") */ headingPath?: string; /** Zero-based chunk index within the source file */ chunkIndex: number; /** Total number of chunks from this source file */ totalChunks: number; /** Start line in source file (1-based) */ startLine: number; /** End line in source file (1-based) */ endLine: number; /** File hash for incremental indexing */ fileHash: string; /** SHA-256 of normalized chunk content for dedup */ contentHash?: string; /** ISO timestamp when this record was created/updated */ indexedAt: string; /** How this record was created */ origin: KnowledgeOrigin; /** User-defined tags for categorization */ tags: string[]; /** Category for curated/produced knowledge */ category?: string; /** Version number for curated knowledge updates */ version: number; /** * Confidence in this record's factual accuracy. * - 'extracted': Directly from source code/static analysis (guaranteed correct) * - 'inferred': LLM-derived relationship (best-effort) * - 'ambiguous': Uncertain relationship (needs verification) * Default: 'extracted' */ confidence?: 'extracted' | 'inferred' | 'ambiguous'; /** * Evidence string describing how this knowledge was obtained. * For extracted: file path + line range * For inferred: explanation of the inference * For ambiguous: why it's uncertain */ evidence?: string; } /** A raw chunk produced by a chunker before embedding */ interface RawChunk { /** The text content */ text: string; /** Source file path */ sourcePath: string; /** Content type */ contentType: ContentType; /** Heading path (markdown only) */ headingPath?: string; /** Chunk index */ chunkIndex: number; /** Total chunks from this file */ totalChunks: number; /** Start line (1-based) */ startLine: number; /** End line (1-based) */ endLine: number; } /** Metadata passed to a chunker */ interface ChunkMetadata { /** File path relative to workspace root */ sourcePath: string; /** Detected content type */ contentType: ContentType; } /** Search result returned by the store */ interface SearchResult { /** The matching knowledge record */ record: KnowledgeRecord; /** Similarity score (0-1, higher = more similar) */ score: number; } interface SupersessionConfig { /** Jaccard similarity threshold for flagging. Default: 0.7 */ threshold: number; /** Maximum entries to compare against. Default: 50 */ maxCompare: number; /** Auto-supersede without confirmation when above this threshold. Default: 0.95 */ autoThreshold: number; } /** Configuration loaded from aikit.config.json */ interface AikitConfig { /** MCP server name. Defaults to 'aikit'. */ serverName?: string; /** @deprecated Use `indexMode` instead. Maps true→'auto', false→'manual'. */ autoIndex?: boolean; /** * Indexing mode: * - `auto`: Full index on startup (same as autoIndex=true) * - `manual`: Only index via tool calls (same as autoIndex=false) * - `smart`: On-demand + idle indexing (default) */ indexMode?: IndexMode; /** * Prefix prepended to every MCP tool name to avoid collisions with other * MCP servers. E.g. `"aikit_"` turns `search` → `aikit_search`. * Defaults to `""` (no prefix) for backward compatibility. */ toolPrefix?: string; /** * Active tool profile name. Controls which tools are registered. * Built-in profiles: full, safe, research, minimal, discovery. * Override with AIKIT_TOOLSET env var. * Defaults to 'full'. */ toolProfile?: string; sources: Array<{ path: string; excludePatterns: string[]; }>; indexing: { chunkSize: number; chunkOverlap: number; minChunkSize: number; /** Max files processed concurrently. Defaults to half of available CPU cores. */ concurrency?: number; trickleIntervalMs?: number; trickleBatchSize?: number; }; embedding: { model: string; /** Native output dimensions before truncation. Default 1024. */ nativeDim?: number; dimensions: number; /** Query prefix for asymmetric retrieval. Default empty string. */ queryPrefix?: string; /** Pooling strategy: 'mean' averages all token embeddings, 'cls' uses the [CLS] token embedding. Default is model-specific. */ pooling?: 'mean' | 'cls'; /** Default 1. */ interOpNumThreads?: number; /** Default 4. */ intraOpNumThreads?: number; /** Default true. */ childProcess?: boolean; /** Default 60000. */ idleTimeoutMs?: number; }; store: { backend: string; path: string; }; curated: { path: string; /** Curated storage adapter. Defaults to 'filesystem'. */ adapter?: 'filesystem'; }; memory?: { retention?: { stabilityHours?: number; accessMultiplier?: number; flagThreshold?: number; maxStabilityHours?: number; }; lessons?: { confirmIncrement?: number; contradictDecrement?: number; autoArchiveDays?: number; archiveThreshold?: number; }; consolidation?: { workingToEpisodicAccesses?: number; episodicToSemanticReferences?: number; semanticToProceduralVerifications?: number; }; supersession?: Partial; }; /** Logger behavior configuration. */ logging?: { /** Include stack traces and error causes in serialized logs. Defaults to false. */errorDetails?: boolean; }; /** Resolved directory for onboard/produce_knowledge output. User-level mode redirects this outside the project. */ onboardDir?: string; /** Resolved state directory path. User-level mode redirects this to the partition. Defaults to `.aikit/state` in workspace root. */ stateDir?: string; /** * L0 generated briefing card storage directory (relative to workspace partition root). * Cards live under ~/.aikit/workspaces///. * Defaults to AIKIT_RUNTIME_PATHS.l0Cards ('memories'). */ l0CardDir?: string; /** * Layered knowledge lifecycle feature flag. * - undefined or false: legacy mode (no capability enforcement, no backtrack/claim) * - true: capability-required mutations, backtrack, claim enabled * @default undefined (disabled) */ layeredKnowledge?: boolean; /** * All workspace roots provided by the MCP client (IDE). * In multi-root workspaces this contains every folder. * `sources[0].path` remains the primary root; this field enables * tools to discover which root the user is working in. */ allRoots?: string[]; /** * Feature groups to expose. When set, only tools in these categories are * registered. Intersects with the active tool profile. * Valid categories: search, analysis, knowledge, compression, forge, * presentation, execution, manipulation, session, git, process, system, * meta, utilities, web, queue, flow. */ features?: string[]; /** Config schema version used for additive migrations. */ configVersion?: number; /** * When true, tools with `readOnlyHint: false` are excluded from * registration. The `config` tool becomes report-only. Immutable at * runtime (set once at startup). */ readOnly?: boolean; /** * Custom server instructions string. When non-empty, replaces the * auto-generated instructions passed to the MCP client. */ serverInstructions?: string; /** * Token budget controls default detail level for tool outputs. * - `'efficient'` — summary-level output (~300 tokens), good for exploration (default) * - `'normal'` — balanced output for daily development * - `'full'` — maximum detail, all data included * Explicit `detail` parameter on individual tools always overrides this. * @default 'efficient' */ tokenBudget?: TokenBudget; /** * When set, indicates the config file failed to load and the returned * config is a fallback default. Contains the error message explaining * what went wrong and what file was attempted. */ configError?: string; /** Enterprise RAG bridge configuration (optional) */ er?: { /** Whether ER integration is enabled */enabled: boolean; /** Base URL of the ER API (e.g., https://xxx.execute-api.region.amazonaws.com/prod) */ baseUrl: string; /** Request timeout in milliseconds. Defaults to 5000. */ timeoutMs?: number; /** Cache TTL in milliseconds. Defaults to 21600000 (6 hours). */ cacheTtlMs?: number; /** Maximum cache entries. Defaults to 100. */ cacheMaxEntries?: number; /** Vector similarity threshold below which ER fallback triggers. Defaults to 0.45. */ fallbackThreshold?: number; }; } /** Index statistics */ interface IndexStats { totalRecords: number; totalFiles: number; contentTypeBreakdown: Record; lastIndexedAt: string | null; storeBackend: string; embeddingModel: string; } //#endregion //#region packages/core/src/content-detector.d.ts /** * Detect the content type of a file based on its path. */ declare function detectContentType(filePath: string): ContentType; /** Derive the coarse SourceType from a ContentType. */ declare function contentTypeToSourceType(ct: ContentType): SourceType; /** Get all ContentTypes that belong to a given SourceType. */ declare function sourceTypeContentTypes(st: SourceType): ContentType[]; //#endregion //#region packages/core/src/errors.d.ts declare class AikitError extends Error { readonly code: string; readonly cause?: unknown; constructor(message: string, code: string, cause?: unknown); } declare class EmbeddingError extends AikitError { constructor(message: string, cause?: unknown); } declare class StoreError extends AikitError { constructor(message: string, cause?: unknown); } declare class IndexError extends AikitError { constructor(message: string, cause?: unknown); } declare class ConfigError extends AikitError { constructor(message: string, cause?: unknown); } /** * Transient error — safe to retry (network timeouts, 429, 5xx, circuit breaker). * Wraps the original error as `cause`. */ declare class TransientError extends AikitError { readonly retryAfterMs?: number | undefined; constructor(message: string, retryAfterMs?: number | undefined, cause?: unknown); } /** * Permanent error — do NOT retry (4xx client errors, invalid input, auth failures). */ declare class PermanentError extends AikitError { constructor(message: string, cause?: unknown); } /** Type guard: is error transient (safe to retry)? */ declare function isTransient(error: unknown): error is TransientError; /** Type guard: is error permanent (do NOT retry)? */ declare function isPermanent(error: unknown): error is PermanentError; //#endregion //#region packages/core/src/global-registry.d.ts /** * Global registry for tracking workspaces enrolled in global MCP install mode. * Registry lives at ~/.aikit/registry.json alongside per-workspace partition directories. */ /** A single workspace entry in the global registry. */ interface RegistryEntry { /** Partition key: - */ partition: string; /** Absolute path to workspace root */ workspacePath: string; /** ISO timestamp of first registration */ registeredAt: string; /** ISO timestamp of last server start */ lastAccessedAt: string; } /** Schema for ~/.aikit/registry.json */ interface GlobalRegistry { version: 1; workspaces: Record; } /** * Get the partition directory for a workspace under ~/.aikit/workspaces/. */ declare function getWorkspacePartitionDir(cwd: string): string; declare function migrateLegacyWorkspaceLayout(workspaceRoot: string): void; /** * Resolve the state directory for a workspace root. * Always routes to ~/.aikit/workspaces//state/. */ declare function resolveStateDir(cwd: string): string; /** * Get the global data directory root. * Override with `AIKIT_GLOBAL_DATA_DIR` env var for testing. */ declare function getGlobalDataDir(): string; /** * Compute a deterministic partition key from a workspace path. * Format: - * * On case-insensitive platforms (win32, darwin), lowercases the * absolute path before hashing so E:\Path and e:\path produce * the same partition key. */ /** * Normalize a resolved absolute path for stable hashing across case * variations on case-insensitive platforms (win32, darwin). * * Use this instead of inlining `createHash('sha256').update(path)` * directly — ensures all path-derived hashes in the system converge * on the same canonical string for a given workspace. */ declare function normalizePathForHash(absPath: string): string; /** * Compute a deterministic partition key from a workspace path. * Format: - * * Delegates path normalization to normalizePathForHash for * cross-platform case consistency. */ declare function computePartitionKey(cwd: string): string; /** * Produce a deterministic short hash from a file path. * Uses the same case normalization as computePartitionKey so every * path-derived identifier in the system is consistent. */ declare function hashPath(rootPath: string, length?: number): string; /** * Load the global registry. Returns empty registry if file doesn't exist. */ declare function loadRegistry(): GlobalRegistry; /** * Save the global registry atomically with file locking. * Uses O_CREAT|O_EXCL lock file + write-to-tmp + rename pattern. */ declare function saveRegistry(registry: GlobalRegistry): void; /** * Register a workspace in the global registry. Creates partition directory. * If already registered, updates lastAccessedAt. */ declare function registerWorkspace(cwd: string): RegistryEntry; /** * Look up a workspace in the registry by cwd. */ declare function lookupWorkspace(cwd: string): RegistryEntry | undefined; /** * List all registered workspaces. */ declare function listWorkspaces(): RegistryEntry[]; /** * Get the absolute path to a partition's data directory. */ declare function getPartitionDir(partition: string): string; /** * Check whether user-level mode is installed (registry.json exists in ~/.aikit/). */ declare function isUserInstalled(): boolean; /** * Resolve the shared runtime log directory. * Logs always live under the home-level ~/.aikit/logs directory. */ declare function resolveLogDir(): string; //#endregion //#region packages/core/src/health-bus.d.ts type HealthStatus = 'healthy' | 'degraded' | 'unavailable'; interface SubsystemHealth { name: string; status: HealthStatus; since: number; reason?: string; } type HealthEvent = { subsystem: string; status: HealthStatus; previousStatus: HealthStatus; reason?: string; timestamp: number; }; /** * Process-wide health event bus for subsystem status changes. */ declare class HealthBus extends EventEmitter { private static _instance; private readonly subsystems; private constructor(); /** * Get the shared HealthBus singleton. */ static instance(): HealthBus; /** * Reset the singleton instance for tests. */ static reset(): void; /** * Register a subsystem with an initial healthy status. */ register(name: string): void; /** * Mark a subsystem as degraded. */ reportDegraded(name: string, reason?: string): void; /** * Mark a subsystem as unavailable. */ reportUnavailable(name: string, reason?: string): void; /** * Mark a subsystem as recovered and healthy. */ reportRecovered(name: string): void; /** * Return whether a subsystem is degraded or unavailable. */ isDegraded(name: string): boolean; /** * Return whether a subsystem is currently healthy. */ isHealthy(name: string): boolean; /** * Return all registered subsystem health records. */ getAll(): SubsystemHealth[]; /** * Return one subsystem's health record. */ getSubsystem(name: string): SubsystemHealth | undefined; private transition; } //#endregion //#region packages/core/src/layered-knowledge-contract.d.ts /** * Layered Knowledge Delivery — Core Metadata Contract * * This module defines the versioned metadata contracts for L0-L3 knowledge layers. * It is the single authoritative source for layer types, shapes, and field requirements. * All other packages (server, flows, tools, scaffold) import from here; no competing * local schemas are permitted for the same concepts. * * L0 card storage path is configured in AIKIT_RUNTIME_PATHS.l0Cards (constants.ts) * and resolved at runtime by server config. Scaffold instructions reference the * stratum_card / compact / status tools — NOT a hardcoded path. * * @module */ type KnowledgeLayerId = 'l0' | 'l1' | 'l2' | 'l3'; /** * Shared metadata fields carried by all L0-L3 entries. */ interface LayeredKnowledgeBaseV1 { schemaVersion: 1; layer: KnowledgeLayerId; workspaceId: string; kind: string; source: { kind: 'tool' | 'document' | 'flow' | 'evidence'; ref: string; }; createdAt: string; updatedAt?: string; topicKey?: string; tags?: string[]; evidenceRefs?: string[]; freshness?: { observedAt?: string; ttlMs?: number; supersededBy?: string | null; }; quality?: { confidence?: number; impact?: 'low' | 'medium' | 'high'; actionability?: 'low' | 'medium' | 'high'; recurrence?: number; sourceDiversity?: number; }; promotionState?: 'candidate' | 'held' | 'promoted' | 'rejected' | 'superseded'; } /** * Card families for L0 generated briefing cards. */ type BriefingCardType = 'workspace-core' | 'architecture' | 'testing-release' | 'known-issues' | `workflow:${string}`; /** * L0 card metadata. Cards are generated workspace caches under * ~/.aikit/workspaces//memories/ and never become canonical. */ interface BriefingCardMetadataV1 extends LayeredKnowledgeBaseV1 { layer: 'l0'; cardType: BriefingCardType; tokenBudget: number; selectionReason: string; referenceRefs?: string[]; } type FlowContextProfileName = 'implementer' | 'documenter' | 'reviewer' | 'researcher' | 'debugger'; /** * Read-only snapshot of active flow run state for the prelude and context manifest. */ interface FlowContextSnapshotV1 { schemaVersion: 1; flowSlug: string; runId: string; stepId: string | null; stepIndex: number; stepOrder: string[]; objective: string; acceptanceCriteria: string[]; scope: string[]; exclusions: string[]; retrievedRefs: string[]; verifiedClaims: string[]; assumedClaims: string[]; unresolvedClaims: string[]; decisions: Array<{ id: string; summary: string; rationale: string; }>; artifacts: Array<{ name: string; path: string; status: 'draft' | 'final' | 'blocked'; }>; stepSummaries: Array<{ stepId: string; summary: string; outcome: 'done' | 'skipped' | 'blocked'; }>; failures: string[]; successPatterns: string[]; candidateLearnings: string[]; verifiedFinalOutcome: string | null; } /** * Atomic context update submitted by the capability holder during a step transition. */ interface FlowContextUpdateV1 { schemaVersion: 1; stepId: string; summary?: string; retrievedRefs?: string[]; verifiedClaims?: Array<{ claim: string; evidenceRefs: string[]; }>; assumedClaims?: string[]; unresolvedClaims?: string[]; decisions?: Array<{ id: string; summary: string; rationale: string; }>; artifacts?: Array<{ name: string; path: string; status: 'draft' | 'final' | 'blocked'; }>; failures?: string[]; successPatterns?: string[]; candidateLearnings?: Array<{ topicKey: string; lesson: string; impact: 'low' | 'medium' | 'high'; evidenceRefs: string[]; }>; verifiedFinalOutcome?: string; } /** * L1 flow context metadata. Attached to the active run, not to canonical storage. */ interface FlowContextMetadataV1 extends LayeredKnowledgeBaseV1 { layer: 'l1'; flowSlug: string; runId: string; stepId: string | null; stepIndex: number; objective: string; acceptanceCriteria: string[]; } /** * L2 canonical curated knowledge metadata. * Managed by CuratedKnowledgeManager; markdown is the sole canonical form. */ interface CuratedKnowledgeMetadataV1 extends LayeredKnowledgeBaseV1 { layer: 'l2'; topicKey: string; curatedMarkdownPath: string; managedBy: 'CuratedKnowledgeManager'; promotionState: 'candidate' | 'held' | 'promoted' | 'rejected' | 'superseded'; } /** * L3 evidence and auto-knowledge metadata. * Non-authoritative; supports promotion evaluation and review. */ interface EvidenceMetadataV1 extends LayeredKnowledgeBaseV1 { layer: 'l3'; evidenceRefs: string[]; quality: NonNullable; } type LayeredKnowledgeContractV1 = BriefingCardMetadataV1 | FlowContextMetadataV1 | CuratedKnowledgeMetadataV1 | EvidenceMetadataV1; /** * Declares which L0/L1/L2/L3 surfaces a built-in flow step consumes and produces. */ interface FlowStepKnowledgeContractV1 { schemaVersion: 1; contextProfile: FlowContextProfileName; consumerProfiles?: Partial>; inputs: { l0CardTypes: BriefingCardType[]; l1Fields: Array; l2Refs: 'none' | 'on-demand' | 'required'; l3Evidence: 'none' | 'on-demand' | 'required'; }; updates: Array; candidateLearnings: string[]; handoff: { artifact: string; requiredSnapshotFields: Array; }; } interface FlowLifecycleMutationV1 { schemaVersion: 1; lifecycleOwnerToken: string; currentToken: string; contextUpdate?: FlowContextUpdateV1; } interface FlowBacktrackV1 extends FlowLifecycleMutationV1 { targetStep: string; } interface FlowOwnerClaimV1 { schemaVersion: 1; currentToken: string; } interface FlowLifecycleAuditRecordV1 { schemaVersion: 1; event: 'claim' | 'backtrack' | 'reset' | 'final-consolidation'; at: string; ownerTokenVersion: number; targetStep?: string; invalidatedExecutionTokens?: string[]; reason?: string; } /** Criteria for validating a layer metadata record. */ interface LayerValidationResult { valid: boolean; missingRequired: string[]; extraFields: string[]; } /** * Validate that a metadata record satisfies the required fields for its layer. * This enforces the layer field requirements defined in LAYER_FIELD_REQUIREMENTS. */ declare function validateLayerMetadata(layer: KnowledgeLayerId, record: Record): LayerValidationResult; /** * Required and optional field sets per layer. */ declare const LAYER_FIELD_REQUIREMENTS: Record; //#endregion //#region packages/core/src/logger.d.ts type LogLevel = 'debug' | 'info' | 'warn' | 'error'; type LogListener = (entry: { level: LogLevel; component: string; message: string; data?: Record; }) => void; declare function setLogLevel(level: LogLevel): void; declare function getLogLevel(): LogLevel; declare function setFileSinkEnabled(enabled: boolean): void; /** Reset resolved log directory (for testing). */ declare function resetLogDir(): void; declare function setDetailedErrorLoggingEnabled(enabled: boolean): void; /** * Serialize an unknown error into a structured record suitable for JSON logging. * Default output stays concise; stack traces and cause chains are opt-in via * aikit.config.json logging.errorDetails for deeper startup/debug diagnostics. */ declare function serializeError(err: unknown): Record; /** * Register a listener that receives all log messages (after level filtering). * Returns a cleanup function to remove the listener. */ declare function addLogListener(listener: LogListener): () => void; declare function createLogger(component: string): { debug: (msg: string, data?: Record) => void; info: (msg: string, data?: Record) => void; warn: (msg: string, data?: Record) => void; error: (msg: string, data?: Record) => void; }; //#endregion //#region packages/core/src/retry.d.ts interface RetryOptions { /** Maximum number of attempts (including the first). Default: 3 */ maxAttempts?: number; /** Base delay in ms for exponential backoff. Default: 500 */ baseDelayMs?: number; /** Maximum delay cap in ms. Default: 30_000 */ maxDelayMs?: number; /** Jitter fraction (0-1). Default: 0.25 */ jitterFraction?: number; /** Custom predicate: should this error be retried? Default: retry TransientError */ shouldRetry?: (error: unknown, attempt: number) => boolean; /** Callback on each retry (for logging). */ onRetry?: (error: unknown, attempt: number, delayMs: number) => void; } /** * Execute an async function with exponential backoff retry. * Only retries on TransientError by default (or custom shouldRetry). * Respects `retryAfterMs` from TransientError when available. */ declare function withRetry(fn: () => Promise, options?: RetryOptions): Promise; //#endregion //#region packages/core/src/safe-cwd.d.ts /** * Safe wrapper for `process.cwd()` — returns `null` when the current working * directory has been deleted or become inaccessible (`uv_cwd` ENOENT). * * Two export variants: * - `safeCwd()` → `string | null` — for call sites that need to distinguish * between "cwd is valid" and "cwd is unavailable" * - `safeCwdOrHome()` → `string` — for call sites that always need a valid * directory; falls back to `os.homedir()` when cwd is unavailable */ /** Returns `process.cwd()` or `null` if the cwd is inaccessible. */ declare function safeCwd(): string | null; /** Returns `process.cwd()` falling back to `os.homedir()` when unavailable. */ declare function safeCwdOrHome(): string; //#endregion //#region packages/core/src/version-manager.d.ts /** * Shared version directory management for managed AI Kit installations. * * Both the CLI install command and the server's background auto-update * operate on the same `~/.aikit/versions/v{version}` layout. This module * provides a single source of truth for cleanup and sorting. */ /** * Compare two `vX.Y.Z` strings for descending sort (newest first). * Uses numeric compare instead of lexicographic to handle * varying digit counts (e.g., v0.1.9 vs v0.1.10). */ declare function compareVersionDir(a: string, b: string): number; /** * Remove old version directories from `versionsDir`, keeping the specified * version + 1 backup (the next newest). Best-effort — never throws. * * Handles Windows EPERM: skips directories that contain the running process * to avoid file-lock conflicts (rmSync fails on memory-mapped files). * * @param versionsDir Path to `~/.aikit/versions/` (or equivalent) * @param keepVersion Raw semver string (no `v` prefix) to preserve. * If omitted or `"0.0.0"`, cleanup is skipped. */ declare function cleanupOldVersions(versionsDir: string, keepVersion?: string): void; //#endregion export { AIKIT_GLOBAL_PATHS, AIKIT_PATHS, AIKIT_RUNTIME_PATHS, AikitConfig, AikitError, BriefingCardMetadataV1, BriefingCardType, CATEGORY_PATTERN, CHUNK_SIZES, CONTENT_TYPES, ChunkMetadata, CircuitBreaker, CircuitBreakerOptions, CircuitOpenError, CircuitState, ConfigError, ContentType, CuratedKnowledgeMetadataV1, DEFAULT_CATEGORIES, EMBEDDING_DEFAULTS, EmbeddingError, EvidenceMetadataV1, FILE_LIMITS, FlowBacktrackV1, FlowContextMetadataV1, FlowContextProfileName, FlowContextSnapshotV1, FlowContextUpdateV1, FlowLifecycleAuditRecordV1, FlowLifecycleMutationV1, FlowOwnerClaimV1, FlowStepKnowledgeContractV1, GlobalRegistry, HealthBus, HealthEvent, HealthStatus, INDEX_MODES, INSTALL_ARGS, IndexError, IndexMode, IndexStats, KNOWLEDGE_ORIGINS, KnowledgeLayerId, KnowledgeOrigin, KnowledgeRecord, LAYER_FIELD_REQUIREMENTS, LayerValidationResult, LayeredKnowledgeBaseV1, LayeredKnowledgeContractV1, LogLevel, LogListener, MODEL_REGISTRY, PermanentError, RawChunk, RegistryEntry, RetryOptions, SEARCH_DEFAULTS, SOURCE_TYPES, STORE_DEFAULTS, SearchResult, SourceType, StoreError, SubsystemHealth, SupersessionConfig, TOKEN_BUDGETS, TokenBudget, TransientError, addLogListener, cleanupOldVersions, compareVersionDir, computePartitionKey, contentTypeToSourceType, createLogger, detectContentType, getGlobalDataDir, getLogLevel, getPartitionDir, getWorkspacePartitionDir, hashPath, isPermanent, isTransient, isUserInstalled, listWorkspaces, loadRegistry, lookupWorkspace, migrateLegacyWorkspaceLayout, normalizePathForHash, registerWorkspace, resetLogDir, resolveLogDir, resolveStateDir, safeCwd, safeCwdOrHome, saveRegistry, serializeError, setDetailedErrorLoggingEnabled, setFileSinkEnabled, setLogLevel, sourceTypeContentTypes, validateLayerMetadata, withRetry };