import { ContentType, KnowledgeOrigin, TokenBudget } from "../../core/dist/index.js";
import { IEmbedder } from "../../embeddings/dist/index.js";
import { DepthGroupedResult, GraphEdge, GraphNode, GraphStats, 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<string, unknown>;
}
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<T> {
  ok: boolean;
  tool: string;
  summary: string;
  data?: T;
  meta: AikitResponseMeta;
  next?: AikitNextHint[];
  error?: AikitToolError;
}
/** Create a success response. */
declare function okResponse<T>(tool: string, summary: string, data: T, meta: Partial<AikitResponseMeta> & {
  durationMs: number;
}, next?: AikitNextHint[]): AikitResponse<T>;
/** Create an error response. */
declare function errorResponse(tool: string, error: AikitToolError, durationMs: number): AikitResponse<never>;
//#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<string, number>;
  };
  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<string, number>;
  };
  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<AikitResponse<AuditData>>;
//#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<string, number>;
  };
}
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<CheckResult>;
/** 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<string, unknown>;
  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<string, unknown>, 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<CodemodResult>;
//#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<FileCacheEntry>;
  /** 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;
}
//#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<CompactResult>;
//#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<number>;
/**
 * 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<unknown>, traceId?: string): Promise<unknown>;
//#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, 'ref' | 'createdAt'>): 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<DeadSymbolResult>;
//#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<string[]>;
/**
 * 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<DelegateResult>;
//#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<string, DigestFieldEntry[]>;
  /** 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<DigestResult>;
//#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/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<string, string>;
}
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<EvalResult>;
//#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<GateConfig>;
  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<FileSummaryResult>;
//#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;
}
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<FindResults>;
//#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<FindExamplesResult>;
//#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<ForgeClassifyResult>;
//#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<ScopeMapResult>;
//#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<ForgeGroundResult>;
//#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<GitContextResult>;
//#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-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<string, unknown>;
    sourceRecordId?: string;
    sourcePath?: string;
  }>;
  /** Edges to add (for action=add) */
  edges?: Array<{
    id?: string;
    fromId: string;
    toId: string;
    type: string;
    weight?: number;
    properties?: Record<string, unknown>;
  }>;
  /** 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;
  validation?: GraphValidationResult;
  communities?: Record<string, string[]>;
  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<GraphQueryResult>;
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<GraphAugmentedResult[]>;
//#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<string, unknown>;
  /** 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/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<string, string>;
  body?: string;
  timeout?: number;
}
interface HttpRequestResult {
  status: number;
  statusText: string;
  headers: Record<string, string>;
  body: string;
  durationMs: number;
  contentType: string;
  sizeBytes: number;
  truncated: boolean;
}
declare function httpRequest(options: HttpRequestOptions): Promise<HttpRequestResult>;
//#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/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<string, HotspotEntry>;
};
//#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<MeasureResult>;
/** 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 optionally writes structured
 * output to `.ai/context/` for human-readable reference.
 *
 * Analyses: structure, dependencies, entry-points, symbols, patterns, diagram.
 */
type OnboardMode = 'memory' | 'generate';
interface OnboardOptions {
  /** Root path to analyze */
  path: string;
  /** Output mode: 'memory' (AI Kit only) or 'generate' (write to .ai/context/) */
  mode?: OnboardMode;
  /** Output directory for generate mode (default: '<path>/.ai/context') */
  outDir?: 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<OnboardResult>;
//#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/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<RenameResult>;
//#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<string[]>;
//#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<string, unknown>;
}
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<SearchResponseData>;
declare function createSearchErrorResponse(message: string, durationMs: number): AikitResponse<never>;
//#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<string>, deps?: SessionDigestDeps): Promise<SessionDigestResult>;
//#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/stratum-card.d.ts
interface StratumCardOptions {
  files: string[];
  query: string;
  tier?: 'T1' | 'T2';
  maxContentChars?: number;
  /** Optional file cache — avoids redundant reads and eliminates double-read with fileSummary */
  cache?: FileCache;
}
interface StratumCard {
  path: string;
  tier: 'T1' | 'T2';
  card: string;
  unknowns: string[];
  riskTier: 'low' | 'medium' | 'high';
  tokenEstimate: number;
  originalTokenEstimate: number;
}
interface StratumCardResult {
  cards: StratumCard[];
  totalTokenEstimate: number;
  totalOriginalTokenEstimate: number;
  compressionRatio: number;
}
declare function stratumCard(embedder: IEmbedder, options: StratumCardOptions): Promise<StratumCardResult>;
//#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;
}
interface SymbolOptions {
  /** Symbol name to look up */
  name: string;
  /** Limit results */
  limit?: number;
  /** Optional graph store for enriching results */
  graphStore?: IGraphStore;
}
declare function symbol(embedder: IEmbedder, store: IKnowledgeStore, options: SymbolOptions): Promise<SymbolInfo>;
//#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<TestRunResult>;
/**
 * 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.
 */
/**
 * Approximate token count from character count (~4 chars/token).
 */
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<T>(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<string, string | number>;
}
declare function timeUtils(options: TimeOptions): TimeResult;
//#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;
}
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<TraceResult>;
//#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;
}
interface WatchHandle {
  id: string;
  path: string;
  events: WatchEvent[];
  status: 'watching' | 'stopped';
  stop: () => void;
  getEvents: (since?: string) => WatchEvent[];
}
declare function watchStart(options: WatchOptions): WatchHandle;
declare function watchStop(id: string): boolean;
declare function watchList(): Array<{
  id: string;
  path: string;
  status: string;
  eventCount: number;
}>;
//#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;
}
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<WebFetchResult>;
//#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<WebSearchResult>;
/** Parse search results from DuckDuckGo HTML. Exported for testing. */
declare function parseSearchResults(html: string, query: string, limit: number): Omit<WebSearchResult, 'provider'>;
//#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;
}
/**
 * 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, 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 CompactOptions, type CompactResult, type ComplianceReport, type ComplianceRule, type ComplianceScoreOptions, type ComplianceViolation, type CompressOutputOptions, type CompressionContext, type CompressionMode, type CompressionResult, type CompressionRule, type ConstraintRef, type DeadSymbol, type DeadSymbolOptions, type DeadSymbolResult, type DelegateOptions, type DelegateResult, type DiffChange, type DiffFile, type DiffHunk, type DiffParseOptions, type DigestFieldEntry, type DigestOptions, type DigestResult, type DigestSource, type DogfoodLogEntry, type DogfoodLogGroupedEntry, type DogfoodLogOptions, type DogfoodLogResult, type EncodeOperation, type EncodeOptions, type EncodeResult, type EnvInfoOptions, type EnvInfoResult, type EvalOptions, type EvalResult, type EvidenceEntry, type EvidenceMapAction, type EvidenceMapResult, type EvidenceMapState, type EvidenceStatus, type Example, FileCache, type FileCacheEntry, type FileCacheStats, type FileMetrics, type FileSummaryOptions, type FileSummaryResult, type FindExamplesOptions, type FindExamplesResult, type FindOptions, type FindResult, type FindResults, 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 GuideRecommendation, type GuideResult, type HealthCheck, type HealthResult, type HotspotEntry, type HttpMethod, type HttpRequestOptions, type HttpRequestResult, type LaneDiffEntry, type LaneDiffResult, type LaneMergeResult, type LaneMeta, type Lease, type LeaseConflict, type LegacyStashOptions, type ManagedProcess, type MeasureOptions, type MeasureResult, type OnboardMode, type OnboardOptions, type OnboardResult, type OnboardStepResult, type ParsedError, type ParsedGitStatus, type ParsedOutput, type ParsedTestResult, type ParsedTestSummary, type PruneOptions, type PruneResult, type QueueItem, type QueueState, type RegexTestOptions, type RegexTestResult, type RenameChange, type RenameOptions, type RenameResult, type ReplayEntry, type ReplayOptions, type RestorePoint, type SafetyGate, type SafetyGateResult, type SchemaValidateOptions, type SchemaValidateResult, type ScopeMapEntry, type ScopeMapOptions, type ScopeMapResult, type SearchResponseData, type SearchResponseItem, type SearchSuccessResponseOptions, type SessionDigestOptions, type SessionDigestResult, type SkillMatch, type SkillTriggerExamples, type SkillTriggerMeta, type StashEntry, type StashStore, type StratumCard, type StratumCardOptions, type StratumCardResult, type SymbolGraphContext, type SymbolInfo, type SymbolOptions, type TestRunOptions, type TestRunResult, type TimeOptions, type TimeResult, type TimeoutAction, type TraceNode, type TraceOptions, type TraceResult, type TransformOptions, type TransformResult, type TypedUnknownSeed, type UnknownType, type ValidationError, type WatchEvent, type WatchHandle, type WatchOptions, type WebFetchMode, type WebFetchOptions, type WebFetchResult, type WebSearchOptions, type WebSearchResult, type WebSearchResultItem, type Workset, acquireLease, addToWorkset, analyzeFile, audit, autoClaimTestFailures, bookendReorder, bpeSurprise, changelog, check, checkpointDiff, checkpointGC, checkpointHistory, checkpointLatest, checkpointList, checkpointLoad, checkpointSave, classifyExitCode, codemod, compact, compressOutput, compressTerminalOutput, cosineSimilarity, createRestorePoint, createSearchErrorResponse, createSearchSuccessResponse, dataTransform, delegate, delegateListModels, deleteWorkset, detectOutputTool, diffParse, digest, dogfoodLog, encode, ensureLegacyStashImported, envInfo, errorResponse, escapeRegExp, estimateTokens, evaluate, evidenceMap, fileSummary, find, findDeadSymbols, findExamples, forgeClassify, forgeGround, formatBytes, formatChangelog, getRegisteredRules, getWorkset, gitAvailable, gitCommitToRef, gitContext, gitExec, graphAugmentSearch, graphQuery, guide, headTailTruncate, health, httpRequest, laneCreate, laneDiff, laneDiscard, laneList, laneMerge, laneStatus, listActiveLeases, listRestorePoints, listWorksets, markPromoteRun, markPruneRun, matchSkills, measure, okResponse, onboard, 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, resolvePath, restoreFromPoint, saveWorkset, schemaValidate, scopeMap, scoreCompliance, scoreLine, scoreLines, segment, sessionDigest, sessionDigestSampling, shannonEntropy, shouldRunStartupPrune, shouldRunWeeklyPromote, slugForRef, stashClear, stashDelete, stashGet, stashList, stashSet, storeReversibleContext, stratumCard, summarizeCheckResult, symbol, testRun, timeUtils, trace, truncateToTokenBudget, watchList, watchStart, watchStop, webFetch, webSearch };