* Rebuild the project's database from scratch and return a fresh, empty * instance — the "same result as a fresh init" semantics that `codegraph * index` documents. * * Unlike `open()` followed by `clear()`, this DISCARDS the existing * `.codegraph/codegraph.db` (and its `-wal`/`-shm`
(projectRoot: string)
| 529 | * (and running migrations against) the poisoned database entirely. |
| 530 | */ |
| 531 | static async recreate(projectRoot: string): Promise<CodeGraph> { |
| 532 | await initGrammars(); |
| 533 | const resolvedRoot = path.resolve(projectRoot); |
| 534 | |
| 535 | // Check if initialized — recreate REBUILDS an existing project; it is not a |
| 536 | // first-time `init`. |
| 537 | if (!isInitialized(resolvedRoot)) { |
| 538 | throw new Error(`CodeGraph not initialized in ${resolvedRoot}. Run init() first.`); |
| 539 | } |
| 540 | |
| 541 | const dbPath = getDatabasePath(resolvedRoot); |
| 542 | try { |
| 543 | removeDatabaseFiles(dbPath); |
| 544 | } catch (err) { |
| 545 | // POSIX unlinks an open file fine; this fires mainly on Windows when a |
| 546 | // live daemon/MCP server still holds the database. Turn the raw EBUSY into |
| 547 | // an actionable instruction instead of a generic failure. |
| 548 | const reason = err instanceof Error ? err.message : String(err); |
| 549 | throw new Error( |
| 550 | `Could not rebuild the index — the database file is in use (${reason}). ` + |
| 551 | `Stop any running CodeGraph MCP server/daemon for this project and retry, ` + |
| 552 | `or remove the ${getCodeGraphDir(resolvedRoot)} directory and run "codegraph init".` |
| 553 | ); |
| 554 | } |
| 555 | |
| 556 | // Re-create an empty, freshly-schema'd database at the same path. |
| 557 | const db = DatabaseConnection.initialize(dbPath); |
| 558 | const queries = new QueryBuilder(db.getDb()); |
| 559 | |
| 560 | return new CodeGraph(db, queries, resolvedRoot); |
| 561 | } |
| 562 | |
| 563 | /** |
| 564 | * Open synchronously (without sync). |