| 1167 | } |
| 1168 | |
| 1169 | async sync(options: IndexOptions = {}): Promise<SyncResult> { |
| 1170 | const { |
| 1171 | ESM_IMPORT_LANGUAGES, |
| 1172 | aliasMayName, |
| 1173 | changedModuleConfigs, |
| 1174 | changedRoutes, |
| 1175 | createImportReader, |
| 1176 | hasSynthesisPattern, |
| 1177 | isJsxChildCandidate, |
| 1178 | moduleConfigLanguages, |
| 1179 | parseManifestStamp, |
| 1180 | parseModuleConfigSnapshot, |
| 1181 | reopenNameMatchedImports, |
| 1182 | reopenReferencesThroughAddedFiles, |
| 1183 | reopenReferencesThroughBarrels, |
| 1184 | reopenReferencesThroughChangedDefaults, |
| 1185 | reopenReferencesThroughDeclaredPackages, |
| 1186 | reopenReferencesThroughObjectMembers, |
| 1187 | reopenReferencesThroughRetargetedModules, |
| 1188 | trustedManifestList, |
| 1189 | } = engine(); |
| 1190 | return this.indexMutex.withLock(async () => { |
| 1191 | const startedAt = Date.now(); |
| 1192 | try { |
| 1193 | this.fileLock.acquire(); |
| 1194 | } catch (err) { |
| 1195 | throw new LockUnavailableError( |
| 1196 | `Sync could not acquire the file lock; retry when the index is available. ${err instanceof Error ? err.message : String(err)}` |
| 1197 | ); |
| 1198 | } |
| 1199 | // A full rebuild in another process (`codegraph index` → recreate) |
| 1200 | // unlinks the database and creates a new file at the same path. A |
| 1201 | // long-lived instance — the MCP daemon's watcher — would otherwise keep |
| 1202 | // "syncing" into the dead inode, and nothing it wrote there is visible |
| 1203 | // to anyone (#1902). Follow the path before writing (one stat), and |
| 1204 | // widen a scoped sync to a full one: whatever the old handle absorbed |
| 1205 | // since the rebuild is gone, so the new file has to be reconciled whole. |
| 1206 | // If the reopen fails (the rebuild is mid-way), report lock contention |
| 1207 | // so the watcher keeps its pending files and retries. |
| 1208 | try { |
| 1209 | this.reopenReplacedDatabase(); |
| 1210 | } catch (err) { |
| 1211 | this.fileLock.release(); |
| 1212 | throw new LockUnavailableError( |
| 1213 | `Sync could not open the rebuilt index yet; retry when the rebuild finishes. ${err instanceof Error ? err.message : String(err)}` |
| 1214 | ); |
| 1215 | } |
| 1216 | if (this.pendingFullReconcile) { |
| 1217 | // The lock above keeps sync out of a live rebuild. If the rebuild |
| 1218 | // stopped before indexAll set index_state, give the fresh empty file |
| 1219 | // a bounded grace period before reconciling it. |
| 1220 | if (this.getIndexState() === null && this.isFreshlyRecreated()) { |
| 1221 | this.fileLock.release(); |
| 1222 | throw new LockUnavailableError('A rebuild of this index is in progress; retry when it finishes.'); |
| 1223 | } |
| 1224 | // Cleared only once this run completes (below): a sync that throws |
| 1225 | // must leave the full catch-up for the next one. |
| 1226 | options = { ...options, paths: undefined }; |