import type { Command, DescribeEntry } from "./cli"; import { BundledDatabase } from "./bundled_database"; import { renderCommands, renderDocumented, renderMatches, renderMetadataBlock, renderSeedExport, renderSeedImport, } from "./contract"; import { scanCurrentPath } from "./command_index"; import { EmbedderManager, refreshEmbeddings, syncPreparedEmbedder, searchByEmbedding, } from "./embedder/index"; import { exportSeedFiles, importSeedFiles } from "./seed_files"; import { assessSearch } from "./search"; import { withDatabaseLock, withFileLock } from "./store/lock"; import { IndexStore } from "./store/store"; import { cacheHome } from "./xdg"; export class App { static fromEnvironment(): App { return new App( `${cacheHome()}/tool-query/index.sqlite3`, EmbedderManager.fromEnvironment(), BundledDatabase.fromPackage(), ); } constructor( private readonly databasePath: string, private readonly embedder: EmbedderManager, private readonly bundledDatabase: BundledDatabase, ) {} async run(command: Command): Promise { switch (command.kind) { case "search": return await this.runSearch(command.input.query); case "describe": return await this.runDescribe(command.input.entries); case "seed-export": return await this.runSeedExport(command.input.directory, command.input.batch_size ?? 20); case "seed-import": return await this.runSeedImport(command.input.directory); case "list": return await this.runList(); case "scan": return this.runScan(); case "help": return ""; } } private async runSearch(query: string): Promise { if (!query.trim()) { throw new AppError("invalid_search_payload", "query must be a non-empty string"); } const index = scanCurrentPath(); await this.ensureLocalDatabase(); const preparedEmbedder = await this.embedder.prepare(); const initialAssessment = this.withReadonlyStore((store) => ({ bundledSeedSyncNeeded: this.bundledDatabase.needsSync(store), ...assessSearch(store, index, preparedEmbedder.fingerprint), })); if ( !initialAssessment.bundledSeedSyncNeeded && !initialAssessment.needsCommandSync && !initialAssessment.needsSeedHydration && !initialAssessment.needsEmbeddingRefresh ) { if (initialAssessment.undocumented.length > 0) { return renderMetadataBlock(initialAssessment.undocumented); } return await this.withReadonlyStoreAsync(async (store) => renderMatches(await searchByEmbedding(store, preparedEmbedder, query)), ); } const blocked = await this.withLockedStore(async (store) => { if (this.bundledDatabase.needsSync(store)) { this.bundledDatabase.syncInto(store); } const assessment = assessSearch(store, index, preparedEmbedder.fingerprint); if (assessment.needsCommandSync) { store.syncCommands(index); } if (assessment.needsSeedHydration) { store.hydrateSeedMetadata(); } const undocumented = store.undocumentedCommandNames(); if (undocumented.length > 0) { return renderMetadataBlock(undocumented); } syncPreparedEmbedder(store, preparedEmbedder); await refreshEmbeddings(store, preparedEmbedder); return null; }); if (blocked) { return blocked; } return await this.withReadonlyStoreAsync(async (store) => renderMatches(await searchByEmbedding(store, preparedEmbedder, query)), ); } private async runDescribe(entries: DescribeEntry[]): Promise { return await this.withLockedStore(async (store) => { if (this.bundledDatabase.needsSync(store)) { this.bundledDatabase.syncInto(store); } store.documentCommands(entries, "manual"); return renderDocumented(entries.map((entry) => entry.name)); }); } private async runSeedExport(directory: string, batchSize: number): Promise { const index = scanCurrentPath(); return await this.withLockedStore(async (store) => { if (this.bundledDatabase.needsSync(store)) { this.bundledDatabase.syncInto(store); } store.syncCommands(index); store.hydrateSeedMetadata(); const undocumented = store.undocumentedCommandNames(); const files = exportSeedFiles(directory, undocumented, batchSize); return renderSeedExport(files, undocumented.length, batchSize); }); } private async runSeedImport(directory: string): Promise { const index = scanCurrentPath(); return await this.withLockedStore(async (store) => { if (this.bundledDatabase.needsSync(store)) { this.bundledDatabase.syncInto(store); } store.syncCommands(index); const entries = importSeedFiles(directory); store.importSeedEntries(entries, "seed-import"); const hydrated = store.hydrateSeedMetadata(); return renderSeedImport(entries.length, hydrated.length); }); } private async runList(): Promise { await this.ensureLocalDatabase(); return await this.withReadonlyStoreAsync( async (store) => renderCommands(store.listCommandNames()), ); } private runScan(): string { const index = scanCurrentPath(); return renderCommands(index.names); } private openStore(): IndexStore { return IndexStore.open(this.databasePath); } private openReadonlyStore(): IndexStore { return IndexStore.openReadonlyExisting(this.databasePath); } private async withLockedStore(run: (store: IndexStore) => Promise): Promise { await this.ensureLocalDatabase(); return await withDatabaseLock(this.lockPath(), async () => { const store = this.openStore(); try { return await run(store); } finally { store.close(); } }); } private withReadonlyStore(run: (store: IndexStore) => T): T { const store = this.openReadonlyStore(); try { return run(store); } finally { store.close(); } } private async withReadonlyStoreAsync(run: (store: IndexStore) => Promise): Promise { const store = this.openReadonlyStore(); try { return await run(store); } finally { store.close(); } } private async ensureLocalDatabase(): Promise { await withFileLock(this.bootstrapLockPath(), async () => { this.bundledDatabase.ensureBootstrapped(this.databasePath); }); } private bootstrapLockPath(): string { return `${this.databasePath}.bootstrap.lock`; } private lockPath(): string { return `${this.databasePath}.lock`; } } export class AppError extends Error { constructor( readonly code: string, message: string, ) { super(message); this.name = "AppError"; } }