@scramble-cloud/lurus-code-cli 2.7.0 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  // src/services/index-worker.ts
2
2
  import { parentPort, workerData } from "node:worker_threads";
3
- import { basename as basename6 } from "node:path";
4
- import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { basename as basename7 } from "node:path";
4
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
5
5
 
6
6
  // src/services/index-diagnostics.ts
7
7
  function createIndexDiagnostics() {
@@ -812,11 +812,11 @@ function isIndexFailureRetryable(failure) {
812
812
  );
813
813
  }
814
814
  function indexRetryDelay(failures, failure, baseDelayMs = 3e4) {
815
- const delay = Math.min(
815
+ const delay2 = Math.min(
816
816
  baseDelayMs * 2 ** Math.min(Math.max(failures - 1, 0), 4),
817
817
  baseDelayMs * 10
818
818
  );
819
- return Math.max(delay, failure?.retryAfterMs ?? 0);
819
+ return Math.max(delay2, failure?.retryAfterMs ?? 0);
820
820
  }
821
821
  function indexHttpFailure(status, headers, now = Date.now()) {
822
822
  if (status === 429) {
@@ -1060,27 +1060,269 @@ function isIndexingWorkspaceAllowed(workspaceRoot, options2 = {}) {
1060
1060
  }
1061
1061
 
1062
1062
  // src/services/code-index.service.ts
1063
+ import { readdir as readdir4, stat as stat3, mkdir as mkdir4, rm as rm2, unlink as unlink4 } from "node:fs/promises";
1064
+ import { existsSync as existsSync4 } from "node:fs";
1065
+
1066
+ // src/services/index-runtime-lease.ts
1067
+ import { mkdir } from "node:fs/promises";
1068
+ import { join as join4 } from "node:path";
1069
+
1070
+ // src/utils/permission-store-lock.ts
1071
+ import { randomBytes } from "node:crypto";
1063
1072
  import {
1064
- readdir as readdir3,
1065
- readFile as readFile4,
1066
- stat as stat3,
1067
- writeFile as writeFile2,
1068
- mkdir as mkdir3,
1069
- rm,
1070
- unlink as unlink3,
1073
+ link,
1071
1074
  lstat,
1072
- link
1075
+ open,
1076
+ readdir,
1077
+ realpath as realpath2,
1078
+ unlink
1073
1079
  } from "node:fs/promises";
1074
- import { existsSync as existsSync5 } from "node:fs";
1075
- import { join as join6, extname as extname2, basename as basename5, resolve as resolve4, isAbsolute as isAbsolute2 } from "node:path";
1076
- import { createHash as createHash2, randomBytes as randomBytes4 } from "node:crypto";
1080
+ import { basename as basename3, dirname as dirname3, join as join3, resolve as resolve4 } from "node:path";
1081
+ import { setTimeout as delay } from "node:timers/promises";
1082
+ var PermissionStoreLockError = class extends Error {
1083
+ constructor(code, options2) {
1084
+ super(
1085
+ code === "lock-contention" ? "Permission storage lock is occupied or its owner cannot be verified. Stop all CLI writers before inspecting or quarantining an ownerless legacy lock; preserve the data document." : "Permission storage lock could not be updated safely.",
1086
+ options2
1087
+ );
1088
+ this.code = code;
1089
+ this.name = "PermissionStoreLockError";
1090
+ }
1091
+ code;
1092
+ };
1093
+ function sameFile(left, right) {
1094
+ return left.dev === right.dev && left.ino === right.ino;
1095
+ }
1096
+ function processIsAlive(pid) {
1097
+ try {
1098
+ process.kill(pid, 0);
1099
+ return true;
1100
+ } catch (error) {
1101
+ return error.code !== "ESRCH";
1102
+ }
1103
+ }
1104
+ function parseData(raw) {
1105
+ try {
1106
+ const value = JSON.parse(raw);
1107
+ if (!value || typeof value !== "object" || Array.isArray(value))
1108
+ return null;
1109
+ const data = value;
1110
+ if (Object.keys(data).length !== 2 || typeof data.token !== "string" || !/^[a-f0-9]{48}$/.test(data.token) || !Number.isSafeInteger(data.pid) || data.pid <= 0)
1111
+ return null;
1112
+ return { token: data.token, pid: data.pid };
1113
+ } catch {
1114
+ return null;
1115
+ }
1116
+ }
1117
+ async function readData(handle) {
1118
+ const bytes = Buffer.alloc(4097);
1119
+ const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
1120
+ return bytesRead <= 4096 ? parseData(bytes.subarray(0, bytesRead).toString("utf8")) : null;
1121
+ }
1122
+ var PermissionStoreLock = class {
1123
+ constructor(path2, options2 = {}) {
1124
+ this.path = path2;
1125
+ this.options = options2;
1126
+ this.root = dirname3(path2);
1127
+ this.attempts = options2.attempts ?? 50;
1128
+ this.retryDelayMs = options2.retryDelayMs ?? 20;
1129
+ this.isAlive = options2.isProcessAlive ?? processIsAlive;
1130
+ }
1131
+ path;
1132
+ options;
1133
+ attempts;
1134
+ retryDelayMs;
1135
+ isAlive;
1136
+ root;
1137
+ async acquire() {
1138
+ await this.assertRoot();
1139
+ for (let attempt = 0; attempt < this.attempts; attempt++) {
1140
+ const token = randomBytes(24).toString("hex");
1141
+ const temp = this.alias("publish");
1142
+ let handle;
1143
+ let lease;
1144
+ let created = false;
1145
+ try {
1146
+ handle = await open(temp, "wx", 384);
1147
+ created = true;
1148
+ await handle.writeFile(JSON.stringify({ token, pid: process.pid }));
1149
+ await handle.sync();
1150
+ const stat4 = await handle.stat({ bigint: true });
1151
+ await handle.close();
1152
+ handle = void 0;
1153
+ await link(temp, this.path);
1154
+ lease = { path: this.path, token, dev: stat4.dev, ino: stat4.ino };
1155
+ await this.phase("published");
1156
+ await unlink(temp);
1157
+ created = false;
1158
+ await this.sync();
1159
+ return lease;
1160
+ } catch (error) {
1161
+ await handle?.close().catch(() => void 0);
1162
+ if (created) await unlink(temp).catch(() => void 0);
1163
+ if (lease) await this.release(lease).catch(() => void 0);
1164
+ if (error.code !== "EEXIST")
1165
+ throw new PermissionStoreLockError("persistence-failed", {
1166
+ cause: error
1167
+ });
1168
+ }
1169
+ if (await this.recover()) continue;
1170
+ await delay(this.retryDelayMs);
1171
+ }
1172
+ throw new PermissionStoreLockError("lock-contention");
1173
+ }
1174
+ async release(lease) {
1175
+ if (lease.path !== this.path)
1176
+ throw new PermissionStoreLockError("persistence-failed");
1177
+ for (let attempt = 0; attempt < this.attempts; attempt++) {
1178
+ if (await this.remove(lease, false)) return;
1179
+ const current = await this.observe();
1180
+ if (current?.token !== lease.token || !sameFile(current, lease)) return;
1181
+ await delay(this.retryDelayMs);
1182
+ }
1183
+ throw new PermissionStoreLockError("lock-contention");
1184
+ }
1185
+ async assertRoot() {
1186
+ const stat4 = await lstat(this.root);
1187
+ if (!stat4.isDirectory() || stat4.isSymbolicLink() || await realpath2(this.root) !== resolve4(this.root))
1188
+ throw new PermissionStoreLockError("persistence-failed");
1189
+ }
1190
+ alias(kind) {
1191
+ return join3(
1192
+ this.root,
1193
+ `.${basename3(this.path)}.${kind}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`
1194
+ );
1195
+ }
1196
+ phase(phase) {
1197
+ return this.options.onPhase?.(phase) ?? Promise.resolve();
1198
+ }
1199
+ sync() {
1200
+ return this.options.syncDirectory?.() ?? Promise.resolve();
1201
+ }
1202
+ async observe() {
1203
+ let handle;
1204
+ try {
1205
+ const stat4 = await lstat(this.path, { bigint: true });
1206
+ if (!stat4.isFile() || stat4.isSymbolicLink()) return null;
1207
+ handle = await open(this.path, "r");
1208
+ const pinned = await handle.stat({ bigint: true });
1209
+ if (!pinned.isFile() || !sameFile(stat4, pinned)) return null;
1210
+ const data = await readData(handle);
1211
+ return data ? { path: this.path, ...data, dev: pinned.dev, ino: pinned.ino } : null;
1212
+ } catch (error) {
1213
+ if (error.code === "ENOENT") return null;
1214
+ throw new PermissionStoreLockError("persistence-failed", {
1215
+ cause: error
1216
+ });
1217
+ } finally {
1218
+ await handle?.close();
1219
+ }
1220
+ }
1221
+ async recover() {
1222
+ const lease = await this.observe();
1223
+ if (!lease || this.isAlive(lease.pid)) return false;
1224
+ return this.remove(lease, true);
1225
+ }
1226
+ async deadAliasCount(claim, pinned, data) {
1227
+ const prefix = `.${basename3(this.path)}.`;
1228
+ let count = 0n;
1229
+ for (const name of await readdir(this.root)) {
1230
+ if (!name.startsWith(prefix)) continue;
1231
+ const path2 = join3(this.root, name);
1232
+ if (path2 === claim) continue;
1233
+ let stat4;
1234
+ try {
1235
+ stat4 = await lstat(path2, { bigint: true });
1236
+ } catch (error) {
1237
+ if (error.code === "ENOENT") continue;
1238
+ throw error;
1239
+ }
1240
+ if (!sameFile(stat4, pinned)) continue;
1241
+ const match = /^(publish|claim)\.([1-9][0-9]*)\.[a-f0-9]{16}\.tmp$/.exec(
1242
+ name.slice(prefix.length)
1243
+ );
1244
+ if (!stat4.isFile() || stat4.isSymbolicLink() || !match) return null;
1245
+ const pid = Number(match[2]);
1246
+ if (!Number.isSafeInteger(pid) || this.isAlive(pid) || match[1] === "publish" && pid !== data.pid)
1247
+ return null;
1248
+ count++;
1249
+ }
1250
+ return count;
1251
+ }
1252
+ async remove(lease, deadRequired) {
1253
+ const claim = this.alias("claim");
1254
+ let created = false;
1255
+ let handle;
1256
+ try {
1257
+ await this.assertRoot();
1258
+ const observed = await lstat(this.path, { bigint: true });
1259
+ if (!observed.isFile() || observed.isSymbolicLink() || !sameFile(observed, lease))
1260
+ return false;
1261
+ await link(this.path, claim);
1262
+ created = true;
1263
+ handle = await open(claim, "r");
1264
+ const pinned = await handle.stat({ bigint: true });
1265
+ const data = await readData(handle);
1266
+ if (!sameFile(pinned, lease) || data?.token !== lease.token || deadRequired && this.isAlive(data.pid))
1267
+ return false;
1268
+ await this.phase("claimed");
1269
+ const deadAliases = await this.deadAliasCount(claim, pinned, data);
1270
+ if (deadAliases === null) return false;
1271
+ const final = await handle.stat({ bigint: true });
1272
+ if (final.nlink !== 2n + deadAliases) return false;
1273
+ await this.phase("links-verified");
1274
+ const current = await lstat(this.path, { bigint: true });
1275
+ if (!current.isFile() || current.isSymbolicLink() || !sameFile(current, pinned) || (await readData(handle))?.token !== lease.token)
1276
+ return false;
1277
+ await this.phase("identity-verified");
1278
+ await unlink(this.path);
1279
+ await this.phase("unlinked");
1280
+ await this.sync();
1281
+ return true;
1282
+ } catch (error) {
1283
+ if (error.code === "ENOENT") return false;
1284
+ throw new PermissionStoreLockError("persistence-failed", {
1285
+ cause: error
1286
+ });
1287
+ } finally {
1288
+ await handle?.close();
1289
+ if (created) await unlink(claim).catch(() => void 0);
1290
+ }
1291
+ }
1292
+ };
1293
+
1294
+ // src/services/index-runtime-lease.ts
1295
+ function indexLock(workspaceRoot) {
1296
+ return new PermissionStoreLock(
1297
+ join4(workspaceRoot, ".lurus", "index-refresh.lock"),
1298
+ { attempts: 2, retryDelayMs: 1 }
1299
+ );
1300
+ }
1301
+ async function acquireIndexLease(workspaceRoot) {
1302
+ await mkdir(join4(workspaceRoot, ".lurus"), { recursive: true });
1303
+ try {
1304
+ const proof = await indexLock(workspaceRoot).acquire();
1305
+ return { pid: process.pid, ownerToken: proof.token, proof };
1306
+ } catch (error) {
1307
+ if (error instanceof PermissionStoreLockError && error.code === "lock-contention")
1308
+ return null;
1309
+ throw error;
1310
+ }
1311
+ }
1312
+ async function releaseIndexLease(workspaceRoot, lease) {
1313
+ await indexLock(workspaceRoot).release(lease.proof);
1314
+ }
1315
+
1316
+ // src/services/code-index.service.ts
1317
+ import { join as join8, extname as extname2, basename as basename6, resolve as resolve5, isAbsolute as isAbsolute2 } from "node:path";
1318
+ import { createHash as createHash3, randomBytes as randomBytes5 } from "node:crypto";
1077
1319
 
1078
1320
  // src/services/index-source-reader.ts
1079
- import { open, stat, rename, unlink, readdir } from "node:fs/promises";
1321
+ import { open as open2, stat, rename, unlink as unlink2, readdir as readdir2 } from "node:fs/promises";
1080
1322
  import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
1081
- import { createHash, randomBytes } from "node:crypto";
1323
+ import { createHash, randomBytes as randomBytes2 } from "node:crypto";
1082
1324
  import { isDeepStrictEqual } from "node:util";
1083
- import { join as join3, relative as relative2 } from "node:path";
1325
+ import { join as join5, relative as relative2 } from "node:path";
1084
1326
  import ignore3 from "ignore";
1085
1327
  async function scanIndexSourcePaths(workspaceRoot, policy, directoryAllowed, fileAllowed, diagnostics, onProgress) {
1086
1328
  const candidates = [];
@@ -1098,7 +1340,7 @@ async function scanIndexSourcePaths(workspaceRoot, policy, directoryAllowed, fil
1098
1340
  diagnostics.directories++;
1099
1341
  return {
1100
1342
  directory,
1101
- entries: await readdir(directory, { withFileTypes: true })
1343
+ entries: await readdir2(directory, { withFileTypes: true })
1102
1344
  };
1103
1345
  } catch (error) {
1104
1346
  if (directory === workspaceRoot) throw error;
@@ -1110,7 +1352,7 @@ async function scanIndexSourcePaths(workspaceRoot, policy, directoryAllowed, fil
1110
1352
  );
1111
1353
  const targets = listings.flatMap(
1112
1354
  ({ directory, entries }) => entries.flatMap((entry) => {
1113
- const absPath = join3(directory, entry.name);
1355
+ const absPath = join5(directory, entry.name);
1114
1356
  const relPath = indexPath(absPath);
1115
1357
  return (entry.isDirectory() ? directoryAllowed(entry.name, relPath) : entry.isFile() && fileAllowed(relPath)) ? [{ absPath, relPath, directory: entry.isDirectory() }] : [];
1116
1358
  })
@@ -1148,11 +1390,11 @@ async function scanIndexSourcePaths(workspaceRoot, policy, directoryAllowed, fil
1148
1390
  return { candidates, unavailablePaths };
1149
1391
  }
1150
1392
  async function writeIndexFile(filePath, content, cancelled, beforeCommit) {
1151
- const temporaryPath = `${filePath}.${randomBytes(4).toString("hex")}.tmp`;
1393
+ const temporaryPath = `${filePath}.${randomBytes2(4).toString("hex")}.tmp`;
1152
1394
  let handle;
1153
1395
  let owned = false;
1154
1396
  try {
1155
- handle = await open(temporaryPath, "wx");
1397
+ handle = await open2(temporaryPath, "wx");
1156
1398
  owned = true;
1157
1399
  await handle.writeFile(content);
1158
1400
  await handle.close();
@@ -1163,7 +1405,7 @@ async function writeIndexFile(filePath, content, cancelled, beforeCommit) {
1163
1405
  await rename(temporaryPath, filePath);
1164
1406
  } finally {
1165
1407
  await handle?.close().catch(() => void 0);
1166
- if (owned) await unlink(temporaryPath).catch(() => void 0);
1408
+ if (owned) await unlink2(temporaryPath).catch(() => void 0);
1167
1409
  }
1168
1410
  }
1169
1411
  async function indexManifestMatches(filePath, maxBytes, current, project) {
@@ -1174,7 +1416,7 @@ async function indexManifestMatches(filePath, maxBytes, current, project) {
1174
1416
  );
1175
1417
  }
1176
1418
  async function readStableIndexFile(filePath, maxBytes, minimumMtimeMs) {
1177
- const handle = await open(filePath, "r");
1419
+ const handle = await open2(filePath, "r");
1178
1420
  try {
1179
1421
  const before = await handle.stat();
1180
1422
  if (!before.isFile() || !Number.isSafeInteger(before.size) || before.size < 0 || before.size > maxBytes || minimumMtimeMs !== void 0 && before.mtimeMs < minimumMtimeMs) {
@@ -1205,7 +1447,7 @@ async function readStableIndexFile(filePath, maxBytes, minimumMtimeMs) {
1205
1447
  async function readIndexSourceFile(file, policy, maxBytes, isReadDenied) {
1206
1448
  const allowed = async () => await policy.validate([file.absPath]) && !isReadDenied?.(file.absPath) && !isReadDenied?.(file.relPath);
1207
1449
  if (!await allowed()) return null;
1208
- const handle = await open(file.absPath, "r");
1450
+ const handle = await open2(file.absPath, "r");
1209
1451
  try {
1210
1452
  const before = await handle.stat();
1211
1453
  if (!before.isFile() || before.size <= 0 || before.size > maxBytes)
@@ -1253,7 +1495,7 @@ function hashContent(content) {
1253
1495
  async function loadIndexIgnorePatterns(workspaceRoot, policy) {
1254
1496
  const loadMatcher = async (fileName) => {
1255
1497
  const matcher = ignore3();
1256
- const filePath = join3(workspaceRoot, fileName);
1498
+ const filePath = join5(workspaceRoot, fileName);
1257
1499
  if (!existsSync2(filePath)) return matcher;
1258
1500
  if (!await policy.isReadAllowedAsync(filePath)) {
1259
1501
  if (fileName === ".lurusignore")
@@ -1416,8 +1658,15 @@ var MAX_INDEX_EMBEDDING_RESPONSE_BYTES = 8 * 1024 * 1024;
1416
1658
 
1417
1659
  // src/utils/output.ts
1418
1660
  import pc from "picocolors";
1661
+ import { AsyncLocalStorage } from "node:async_hooks";
1662
+ var outputSinks = new AsyncLocalStorage();
1419
1663
  var useStderr = false;
1420
- function write(message) {
1664
+ function write(message, level = "log") {
1665
+ const sink = outputSinks.getStore();
1666
+ if (sink && !useStderr) {
1667
+ sink(message, level);
1668
+ return;
1669
+ }
1421
1670
  if (useStderr) {
1422
1671
  process.stderr.write(message + "\n");
1423
1672
  } else {
@@ -1426,20 +1675,40 @@ function write(message) {
1426
1675
  }
1427
1676
  var output = {
1428
1677
  log: (message) => write(message),
1429
- info: (message) => write(pc.blue(message)),
1430
- success: (message) => write(pc.green("\u2713 ") + message),
1431
- warn: (message) => console.warn(pc.yellow("\u26A0 ") + message),
1432
- error: (message) => console.error(pc.red("\u2717 ") + message),
1433
- dim: (message) => write(pc.dim(message)),
1434
- bold: (message) => write(pc.bold(message)),
1678
+ info: (message) => write(pc.blue(message), "info"),
1679
+ success: (message) => write(pc.green("\u2713 ") + message, "success"),
1680
+ warn: (message) => {
1681
+ const sink = outputSinks.getStore();
1682
+ if (sink && !useStderr) sink(message, "warn");
1683
+ else console.warn(pc.yellow("\u26A0 ") + message);
1684
+ },
1685
+ error: (message) => {
1686
+ const sink = outputSinks.getStore();
1687
+ if (sink && !useStderr) sink(message, "error");
1688
+ else console.error(pc.red("\u2717 ") + message);
1689
+ },
1690
+ dim: (message) => write(pc.dim(message), "dim"),
1691
+ bold: (message) => write(pc.bold(message), "bold"),
1435
1692
  blank: () => write("")
1436
1693
  };
1437
1694
 
1438
1695
  // src/services/index-encryption.service.ts
1439
- import { randomBytes as randomBytes2, createCipheriv, createDecipheriv } from "node:crypto";
1440
- import { readFile as readFile2, writeFile, mkdir } from "node:fs/promises";
1441
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
1442
- import { join as join4, dirname as dirname3 } from "node:path";
1696
+ import {
1697
+ randomBytes as randomBytes3,
1698
+ createCipheriv,
1699
+ createDecipheriv,
1700
+ createHash as createHash2
1701
+ } from "node:crypto";
1702
+ import {
1703
+ readFile as readFile2,
1704
+ writeFile,
1705
+ mkdir as mkdir2,
1706
+ open as open3,
1707
+ link as link2,
1708
+ rm,
1709
+ lstat as lstat2
1710
+ } from "node:fs/promises";
1711
+ import { join as join6, dirname as dirname4 } from "node:path";
1443
1712
  import { homedir as homedir4 } from "node:os";
1444
1713
  var ALGORITHM = "aes-256-gcm";
1445
1714
  var IV_LENGTH = 16;
@@ -1448,33 +1717,53 @@ var KEY_LENGTH = 32;
1448
1717
  var IndexEncryptionService = class {
1449
1718
  key = null;
1450
1719
  keyPath;
1720
+ legacyKeyPath;
1451
1721
  constructor(workspaceRoot, homeDir = homedir4()) {
1452
- const projectHash = Buffer.from(workspaceRoot).toString("base64url").slice(0, 16);
1453
- this.keyPath = join4(homeDir, ".lurus", "keys", `${projectHash}.json`);
1722
+ const projectHash = createHash2("sha256").update(workspaceRoot).digest("hex");
1723
+ const legacyHash = Buffer.from(workspaceRoot).toString("base64url").slice(0, 16);
1724
+ const root = join6(homeDir, ".lurus", "keys");
1725
+ this.keyPath = join6(root, `${projectHash}.json`);
1726
+ this.legacyKeyPath = join6(root, `${legacyHash}.json`);
1454
1727
  }
1455
1728
  async ensureKey() {
1456
1729
  if (this.key) return;
1457
- if (existsSync3(this.keyPath)) {
1730
+ const existing = await this.readKey(this.keyPath);
1731
+ if (existing) {
1732
+ this.key = existing;
1733
+ return;
1734
+ }
1735
+ const candidate = await this.readKey(this.legacyKeyPath) ?? randomBytes3(KEY_LENGTH);
1736
+ await mkdir2(dirname4(this.keyPath), { recursive: true, mode: 448 });
1737
+ const temporary = `${this.keyPath}.${randomBytes3(12).toString("hex")}.tmp`;
1738
+ const handle = await open3(temporary, "wx", 384);
1739
+ try {
1458
1740
  try {
1459
- const raw = readFileSync4(this.keyPath, "utf-8");
1460
- const keyFile2 = JSON.parse(raw);
1461
- this.key = Buffer.from(keyFile2.indexEncryptionKey, "base64");
1462
- if (this.key.length === KEY_LENGTH) return;
1463
- } catch {
1741
+ await handle.writeFile(
1742
+ JSON.stringify({ indexEncryptionKey: candidate.toString("base64") })
1743
+ );
1744
+ await handle.sync();
1745
+ } finally {
1746
+ await handle.close();
1464
1747
  }
1748
+ try {
1749
+ await link2(temporary, this.keyPath);
1750
+ this.key = candidate;
1751
+ } catch (error) {
1752
+ if (error.code !== "EEXIST") throw error;
1753
+ const published = await this.readKey(this.keyPath);
1754
+ if (!published)
1755
+ throw new Error("Index key publication failed. Retry indexing.", {
1756
+ cause: error
1757
+ });
1758
+ this.key = published;
1759
+ }
1760
+ } finally {
1761
+ await rm(temporary, { force: true }).catch(() => void 0);
1465
1762
  }
1466
- this.key = randomBytes2(KEY_LENGTH);
1467
- const keyFile = {
1468
- indexEncryptionKey: this.key.toString("base64")
1469
- };
1470
- await mkdir(dirname3(this.keyPath), { recursive: true });
1471
- await writeFile(this.keyPath, JSON.stringify(keyFile, null, 2), {
1472
- mode: 384
1473
- });
1474
1763
  }
1475
1764
  encrypt(data) {
1476
1765
  if (!this.key) throw new Error("Encryption key not initialized");
1477
- const iv = randomBytes2(IV_LENGTH);
1766
+ const iv = randomBytes3(IV_LENGTH);
1478
1767
  const cipher = createCipheriv(ALGORITHM, this.key, iv, {
1479
1768
  authTagLength: AUTH_TAG_LENGTH
1480
1769
  });
@@ -1504,7 +1793,7 @@ var IndexEncryptionService = class {
1504
1793
  }
1505
1794
  async encryptFile(plaintext, outputPath) {
1506
1795
  const encrypted = this.encrypt(plaintext);
1507
- await mkdir(dirname3(outputPath), { recursive: true });
1796
+ await mkdir2(dirname4(outputPath), { recursive: true });
1508
1797
  await writeFile(outputPath, encrypted);
1509
1798
  }
1510
1799
  async decryptFile(inputPath) {
@@ -1514,21 +1803,54 @@ var IndexEncryptionService = class {
1514
1803
  isAvailable() {
1515
1804
  return this.key !== null;
1516
1805
  }
1806
+ async readKey(path2) {
1807
+ let bytes;
1808
+ try {
1809
+ bytes = await readFile2(path2, "utf8");
1810
+ } catch (error) {
1811
+ if (error.code !== "ENOENT") throw error;
1812
+ try {
1813
+ await lstat2(path2);
1814
+ } catch (entryError) {
1815
+ if (entryError.code === "ENOENT")
1816
+ return null;
1817
+ throw entryError;
1818
+ }
1819
+ throw new Error(
1820
+ "The existing index key is unavailable. Restore access to the original key.",
1821
+ { cause: error }
1822
+ );
1823
+ }
1824
+ let value;
1825
+ try {
1826
+ value = JSON.parse(bytes);
1827
+ } catch (cause) {
1828
+ throw new Error("Invalid index key. The original key was not changed.", {
1829
+ cause
1830
+ });
1831
+ }
1832
+ if (!value || typeof value !== "object" || !("indexEncryptionKey" in value) || typeof value.indexEncryptionKey !== "string")
1833
+ throw new Error("Invalid index key. The original key was not changed.");
1834
+ const key = Buffer.from(value.indexEncryptionKey, "base64");
1835
+ if (key.length !== KEY_LENGTH || key.toString("base64") !== value.indexEncryptionKey)
1836
+ throw new Error("Invalid index key. The original key was not changed.");
1837
+ return key;
1838
+ }
1517
1839
  };
1518
1840
 
1519
1841
  // src/services/embedding-cache.service.ts
1520
- import { randomBytes as randomBytes3 } from "node:crypto";
1521
- import { existsSync as existsSync4 } from "node:fs";
1842
+ import { randomBytes as randomBytes4 } from "node:crypto";
1843
+ import { existsSync as existsSync3 } from "node:fs";
1522
1844
  import {
1523
- mkdir as mkdir2,
1845
+ mkdir as mkdir3,
1524
1846
  readFile as readFile3,
1525
- readdir as readdir2,
1847
+ readdir as readdir3,
1526
1848
  rename as rename2,
1527
- unlink as unlink2,
1528
- open as open2,
1849
+ unlink as unlink3,
1850
+ open as open4,
1529
1851
  stat as stat2
1530
1852
  } from "node:fs/promises";
1531
- import { basename as basename3, join as join5 } from "node:path";
1853
+ import { basename as basename4, join as join7 } from "node:path";
1532
1854
  var CACHE_VERSION = 1;
1533
1855
  var CACHE_MANIFEST = "manifest.json";
1534
1856
  var CACHE_FILE_PATTERN = /^(metadata|vectors)\.[a-f0-9]+\.(enc|bin)$/;
@@ -1536,7 +1858,7 @@ var EmbeddingCacheService = class {
1536
1858
  constructor(indexDir, encryption, maxVectorBytes) {
1537
1859
  this.encryption = encryption;
1538
1860
  this.maxVectorBytes = maxVectorBytes;
1539
- this.cacheDir = join5(indexDir, "cache");
1861
+ this.cacheDir = join7(indexDir, "cache");
1540
1862
  }
1541
1863
  encryption;
1542
1864
  maxVectorBytes;
@@ -1544,8 +1866,8 @@ var EmbeddingCacheService = class {
1544
1866
  writeRevision = 0;
1545
1867
  pendingCheckpoint;
1546
1868
  async load() {
1547
- const manifestPath = join5(this.cacheDir, CACHE_MANIFEST);
1548
- if (!existsSync4(manifestPath)) return null;
1869
+ const manifestPath = join7(this.cacheDir, CACHE_MANIFEST);
1870
+ if (!existsSync3(manifestPath)) return null;
1549
1871
  try {
1550
1872
  const manifest = JSON.parse(
1551
1873
  await readFile3(manifestPath, "utf-8")
@@ -1556,12 +1878,12 @@ var EmbeddingCacheService = class {
1556
1878
  const expectedBytes = manifest.entryCount * manifest.dimensions * Float32Array.BYTES_PER_ELEMENT;
1557
1879
  if (!Number.isSafeInteger(expectedBytes) || expectedBytes > this.maxVectorBytes)
1558
1880
  return null;
1559
- const vectorPath = join5(this.cacheDir, manifest.vectorsFile);
1881
+ const vectorPath = join7(this.cacheDir, manifest.vectorsFile);
1560
1882
  const before = await stat2(vectorPath);
1561
1883
  if (!before.isFile() || before.size !== expectedBytes) return null;
1562
1884
  const metadata = JSON.parse(
1563
1885
  await this.encryption.decryptFile(
1564
- join5(this.cacheDir, manifest.metadataFile)
1886
+ join7(this.cacheDir, manifest.metadataFile)
1565
1887
  )
1566
1888
  );
1567
1889
  if (!Array.isArray(metadata.keys) || metadata.keys.length !== manifest.entryCount || new Set(metadata.keys).size !== metadata.keys.length) {
@@ -1613,8 +1935,8 @@ var EmbeddingCacheService = class {
1613
1935
  try {
1614
1936
  await Promise.race([
1615
1937
  save,
1616
- new Promise((resolve5) => {
1617
- timer = setTimeout(resolve5, 500);
1938
+ new Promise((resolve6) => {
1939
+ timer = setTimeout(resolve6, 500);
1618
1940
  })
1619
1941
  ]);
1620
1942
  } finally {
@@ -1656,7 +1978,7 @@ var EmbeddingCacheService = class {
1656
1978
  ).equals(Buffer.from(old.buffer, old.byteOffset, old.byteLength));
1657
1979
  })) {
1658
1980
  const manifest2 = await readFile3(
1659
- join5(this.cacheDir, CACHE_MANIFEST),
1981
+ join7(this.cacheDir, CACHE_MANIFEST),
1660
1982
  "utf-8"
1661
1983
  ).then((text) => JSON.parse(text)).catch(() => null);
1662
1984
  if (manifest2?.generation === previous.generation && current()) return;
@@ -1667,8 +1989,8 @@ var EmbeddingCacheService = class {
1667
1989
  const vector = selectedEntries.get(key);
1668
1990
  if (vector) vectors.set(vector, index2 * dimensions);
1669
1991
  });
1670
- await mkdir2(this.cacheDir, { recursive: true });
1671
- const generation = randomBytes3(8).toString("hex");
1992
+ await mkdir3(this.cacheDir, { recursive: true });
1993
+ const generation = randomBytes4(8).toString("hex");
1672
1994
  const metadataFile = `metadata.${generation}.enc`;
1673
1995
  const vectorsFile = `vectors.${generation}.bin`;
1674
1996
  const metadataBuffer = this.encryption.encrypt(
@@ -1691,7 +2013,7 @@ var EmbeddingCacheService = class {
1691
2013
  vectorsFile
1692
2014
  };
1693
2015
  await this.atomicWrite(
1694
- join5(this.cacheDir, CACHE_MANIFEST),
2016
+ join7(this.cacheDir, CACHE_MANIFEST),
1695
2017
  JSON.stringify(manifest),
1696
2018
  current
1697
2019
  );
@@ -1703,30 +2025,30 @@ var EmbeddingCacheService = class {
1703
2025
  }
1704
2026
  async clear() {
1705
2027
  this.writeRevision++;
1706
- if (!existsSync4(this.cacheDir)) return;
1707
- const entries = await readdir2(this.cacheDir).catch(() => []);
2028
+ if (!existsSync3(this.cacheDir)) return;
2029
+ const entries = await readdir3(this.cacheDir).catch(() => []);
1708
2030
  await Promise.all(
1709
2031
  entries.map(
1710
- (entry) => unlink2(join5(this.cacheDir, entry)).catch(() => void 0)
2032
+ (entry) => unlink3(join7(this.cacheDir, entry)).catch(() => void 0)
1711
2033
  )
1712
2034
  );
1713
2035
  }
1714
2036
  isSafeArtifactName(fileName) {
1715
- return basename3(fileName) === fileName && CACHE_FILE_PATTERN.test(fileName);
2037
+ return basename4(fileName) === fileName && CACHE_FILE_PATTERN.test(fileName);
1716
2038
  }
1717
2039
  async writeArtifact(fileName, content, isCurrent) {
1718
2040
  if (!this.isSafeArtifactName(fileName)) {
1719
2041
  throw new Error("Invalid embedding cache artifact name");
1720
2042
  }
1721
- await this.atomicWrite(join5(this.cacheDir, fileName), content, isCurrent);
2043
+ await this.atomicWrite(join7(this.cacheDir, fileName), content, isCurrent);
1722
2044
  }
1723
2045
  async atomicWrite(filePath, content, isCurrent) {
1724
- const temporaryPath = `${filePath}.${randomBytes3(4).toString("hex")}.tmp`;
2046
+ const temporaryPath = `${filePath}.${randomBytes4(4).toString("hex")}.tmp`;
1725
2047
  let handle;
1726
2048
  let owned = false;
1727
2049
  try {
1728
2050
  if (!isCurrent()) return;
1729
- handle = await open2(temporaryPath, "wx");
2051
+ handle = await open4(temporaryPath, "wx");
1730
2052
  owned = true;
1731
2053
  await handle.writeFile(content);
1732
2054
  await handle.close();
@@ -1735,24 +2057,24 @@ var EmbeddingCacheService = class {
1735
2057
  await rename2(temporaryPath, filePath);
1736
2058
  } finally {
1737
2059
  await handle?.close().catch(() => void 0);
1738
- if (owned) await unlink2(temporaryPath).catch(() => void 0);
2060
+ if (owned) await unlink3(temporaryPath).catch(() => void 0);
1739
2061
  }
1740
2062
  }
1741
2063
  async removeUnreferencedArtifacts(referenced, isCurrent) {
1742
- const files = await readdir2(this.cacheDir).catch(() => []);
2064
+ const files = await readdir3(this.cacheDir).catch(() => []);
1743
2065
  if (!isCurrent()) return;
1744
2066
  await Promise.all(
1745
2067
  files.filter(
1746
2068
  (file) => CACHE_FILE_PATTERN.test(file) && !referenced.has(file)
1747
2069
  ).map(
1748
- (file) => unlink2(join5(this.cacheDir, file)).catch(() => void 0)
2070
+ (file) => unlink3(join7(this.cacheDir, file)).catch(() => void 0)
1749
2071
  )
1750
2072
  );
1751
2073
  }
1752
2074
  };
1753
2075
 
1754
2076
  // src/services/source-structure.service.ts
1755
- import { basename as basename4, extname } from "node:path";
2077
+ import { basename as basename5, extname } from "node:path";
1756
2078
  import ts from "./vendor/typescript.cjs";
1757
2079
  var LANGUAGE_MAP = {
1758
2080
  ".ts": "TypeScript",
@@ -1899,7 +2221,7 @@ var CODE_INDEX_BOUNDARY_LANGUAGES = /* @__PURE__ */ new Set([
1899
2221
  ]);
1900
2222
  function detectSourceLanguage(filePath) {
1901
2223
  const extension = extname(filePath).toLowerCase();
1902
- return LANGUAGE_LOOKUP[extension] ?? basename4(filePath);
2224
+ return LANGUAGE_LOOKUP[extension] ?? basename5(filePath);
1903
2225
  }
1904
2226
  function hasCodeIndexBoundarySupport(language) {
1905
2227
  return CODE_INDEX_BOUNDARY_LANGUAGES.has(language.split(" ")[0]);
@@ -1995,7 +2317,6 @@ var INDEX_VERSION = 3;
1995
2317
  var LEGACY_INDEX_VERSION = 2;
1996
2318
  var INDEX_DIR = ".lurus/index";
1997
2319
  var INDEX_MANIFEST_FILE = "index.json";
1998
- var INDEX_REFRESH_LEASE_FILE = "index-refresh.lock";
1999
2320
  var LEASE_POLL_INTERVAL_MS = 100;
2000
2321
  var LEASE_WAIT_TIMEOUT_MS = 3e4;
2001
2322
  var CANONICAL_EMBEDDING_MODEL = "Qwen3-Embedding-8B";
@@ -2199,7 +2520,7 @@ var CodeIndexService = class {
2199
2520
  this.httpClient = httpClient;
2200
2521
  this.now = now;
2201
2522
  this.workspaceRoot = workspaceRoot || process.cwd();
2202
- this.indexDir = join6(this.workspaceRoot, INDEX_DIR);
2523
+ this.indexDir = join8(this.workspaceRoot, INDEX_DIR);
2203
2524
  this.sourcePolicy = new IndexSourcePolicy(this.workspaceRoot);
2204
2525
  this.encryption = new IndexEncryptionService(
2205
2526
  this.workspaceRoot,
@@ -2242,6 +2563,7 @@ var CodeIndexService = class {
2242
2563
  limits;
2243
2564
  sourcePolicy;
2244
2565
  leaseListener;
2566
+ leaseBroker;
2245
2567
  getDiagnostics() {
2246
2568
  return { ...this.diagnostics };
2247
2569
  }
@@ -2251,6 +2573,9 @@ var CodeIndexService = class {
2251
2573
  onLease(listener) {
2252
2574
  this.leaseListener = listener;
2253
2575
  }
2576
+ setLeaseBroker(broker2) {
2577
+ this.leaseBroker = broker2;
2578
+ }
2254
2579
  isWorkspaceAllowed() {
2255
2580
  return isIndexingWorkspaceAllowed(this.workspaceRoot);
2256
2581
  }
@@ -2482,7 +2807,7 @@ var CodeIndexService = class {
2482
2807
  throw new Error("Timed out waiting for the workspace index lease.");
2483
2808
  }
2484
2809
  try {
2485
- await rm(this.indexDir, { recursive: true, force: true });
2810
+ await rm2(this.indexDir, { recursive: true, force: true });
2486
2811
  this.invalidationGeneration++;
2487
2812
  this.refreshAbortController?.abort();
2488
2813
  this.dirtyFiles.clear();
@@ -2498,8 +2823,8 @@ var CodeIndexService = class {
2498
2823
  async loadIndex(options2 = {}) {
2499
2824
  if (!this.isWorkspaceAllowed()) return null;
2500
2825
  this.lastLoadIndexFailure = null;
2501
- const manifestPath = join6(this.indexDir, INDEX_MANIFEST_FILE);
2502
- if (!existsSync5(manifestPath)) return null;
2826
+ const manifestPath = join8(this.indexDir, INDEX_MANIFEST_FILE);
2827
+ if (!existsSync4(manifestPath)) return null;
2503
2828
  try {
2504
2829
  await this.encryption.ensureKey();
2505
2830
  const manifestFile = await readStableIndexFile(
@@ -2515,7 +2840,22 @@ var CodeIndexService = class {
2515
2840
  }
2516
2841
  if (rawMeta["version"] === INDEX_VERSION) {
2517
2842
  const meta = this.projectIndexMeta(rawMeta, INDEX_VERSION);
2518
- const loaded = await this.loadV3Index(meta);
2843
+ let loaded;
2844
+ try {
2845
+ loaded = await this.loadV3Index(meta);
2846
+ } catch (error) {
2847
+ const latest = await readStableIndexFile(
2848
+ manifestPath,
2849
+ this.limits.maxSourceBytes
2850
+ );
2851
+ if (latest.buffer.equals(manifestFile.buffer)) throw error;
2852
+ loaded = await this.loadV3Index(
2853
+ this.projectIndexMeta(
2854
+ JSON.parse(latest.buffer.toString("utf8")),
2855
+ INDEX_VERSION
2856
+ )
2857
+ );
2858
+ }
2519
2859
  if (options2.migrateLegacy === true) {
2520
2860
  await this.removeLegacyV2Artifacts();
2521
2861
  }
@@ -2669,7 +3009,7 @@ var CodeIndexService = class {
2669
3009
  lease = acquisition.lease;
2670
3010
  let rebased = false;
2671
3011
  if (this.activeIndex?.meta.version === INDEX_VERSION && !await indexManifestMatches(
2672
- join6(this.indexDir, INDEX_MANIFEST_FILE),
3012
+ join8(this.indexDir, INDEX_MANIFEST_FILE),
2673
3013
  this.limits.maxSourceBytes,
2674
3014
  this.activeIndex.meta,
2675
3015
  (value) => this.projectIndexMeta(value, INDEX_VERSION)
@@ -2851,42 +3191,23 @@ var CodeIndexService = class {
2851
3191
  listener({ ...this.refreshState });
2852
3192
  }
2853
3193
  }
2854
- get leasePath() {
2855
- return join6(this.workspaceRoot, ".lurus", INDEX_REFRESH_LEASE_FILE);
2856
- }
2857
3194
  async acquireLease(signal, wait, timeoutMs = LEASE_WAIT_TIMEOUT_MS) {
2858
3195
  if (!this.isWorkspaceAllowed()) return { status: "cancelled" };
2859
- const leaseDirectory = join6(this.workspaceRoot, ".lurus");
2860
- await mkdir3(leaseDirectory, { recursive: true });
2861
3196
  const deadline = Date.now() + timeoutMs;
2862
3197
  while (!signal.aborted) {
2863
- const lease = {
2864
- pid: process.pid,
2865
- ownerToken: randomBytes4(16).toString("hex")
2866
- };
2867
- const temporaryPath = join6(
2868
- leaseDirectory,
2869
- `${INDEX_REFRESH_LEASE_FILE}.${lease.ownerToken}.tmp`
2870
- );
2871
- try {
2872
- await writeFile2(temporaryPath, JSON.stringify(lease), {
2873
- flag: "wx",
2874
- mode: 384
2875
- });
3198
+ const lease = await (this.leaseBroker ? this.leaseBroker.acquire() : acquireIndexLease(this.workspaceRoot));
3199
+ if (lease) {
2876
3200
  try {
2877
3201
  await this.leaseListener?.(lease.ownerToken);
2878
- await link(temporaryPath, this.leasePath);
3202
+ if (signal.aborted) {
3203
+ await this.releaseLease(lease);
3204
+ return { status: "cancelled" };
3205
+ }
2879
3206
  return { status: "acquired", lease };
2880
3207
  } catch (error) {
2881
- if (!this.isFileExistsError(error)) throw error;
3208
+ await this.releaseLease(lease);
3209
+ throw error;
2882
3210
  }
2883
- } finally {
2884
- await unlink3(temporaryPath).catch(() => void 0);
2885
- }
2886
- const inspection = await this.inspectLease();
2887
- if (inspection.status === "missing") continue;
2888
- if (inspection.status === "dead") {
2889
- if (await this.removeLeaseIfMatches(inspection.lease)) continue;
2890
3211
  }
2891
3212
  if (!wait) return { status: "contended" };
2892
3213
  if (Date.now() >= deadline) return { status: "timed_out" };
@@ -2894,51 +3215,6 @@ var CodeIndexService = class {
2894
3215
  }
2895
3216
  return { status: "cancelled" };
2896
3217
  }
2897
- async inspectLease() {
2898
- try {
2899
- const info = await lstat(this.leasePath);
2900
- if (!info.isFile() || info.isSymbolicLink()) {
2901
- return { status: "occupied" };
2902
- }
2903
- const parsed = JSON.parse(
2904
- await readFile4(this.leasePath, "utf-8")
2905
- );
2906
- const lease = this.projectLease(parsed);
2907
- if (!lease) return { status: "occupied" };
2908
- try {
2909
- process.kill(lease.pid, 0);
2910
- return { status: "active", lease };
2911
- } catch (error) {
2912
- return this.isProcessMissingError(error) ? { status: "dead", lease } : { status: "active", lease };
2913
- }
2914
- } catch (error) {
2915
- return this.isFileMissingError(error) ? { status: "missing" } : { status: "occupied" };
2916
- }
2917
- }
2918
- projectLease(value) {
2919
- if (!this.isRecord(value)) return null;
2920
- const pid = value["pid"];
2921
- const ownerToken = value["ownerToken"];
2922
- if (!Number.isSafeInteger(pid) || pid <= 0 || typeof ownerToken !== "string" || !/^[a-f0-9]{32}$/.test(ownerToken)) {
2923
- return null;
2924
- }
2925
- return { pid, ownerToken };
2926
- }
2927
- async removeLeaseIfMatches(expected) {
2928
- try {
2929
- const parsed = JSON.parse(
2930
- await readFile4(this.leasePath, "utf-8")
2931
- );
2932
- const current = this.projectLease(parsed);
2933
- if (current?.pid !== expected.pid || current?.ownerToken !== expected.ownerToken) {
2934
- return false;
2935
- }
2936
- await unlink3(this.leasePath);
2937
- return true;
2938
- } catch {
2939
- return false;
2940
- }
2941
- }
2942
3218
  async delayLeasePoll(signal, deadline = Number.POSITIVE_INFINITY) {
2943
3219
  const delayMs = Math.max(
2944
3220
  0,
@@ -2956,18 +3232,13 @@ var CodeIndexService = class {
2956
3232
  });
2957
3233
  }
2958
3234
  async releaseLease(lease) {
2959
- if (await this.removeLeaseIfMatches(lease))
2960
- await this.leaseListener?.(null);
2961
- }
2962
- isFileExistsError(error) {
2963
- return error instanceof Error && "code" in error && error.code === "EEXIST";
3235
+ if (this.leaseBroker) await this.leaseBroker.release(lease);
3236
+ else await releaseIndexLease(this.workspaceRoot, lease);
3237
+ await this.leaseListener?.(null);
2964
3238
  }
2965
3239
  isFileMissingError(error) {
2966
3240
  return error instanceof Error && "code" in error && error.code === "ENOENT";
2967
3241
  }
2968
- isProcessMissingError(error) {
2969
- return error instanceof Error && "code" in error && error.code === "ESRCH";
2970
- }
2971
3242
  async loadV3Index(meta, verifiedVectors) {
2972
3243
  if (!meta.artifacts || !this.validateArtifacts(meta.artifacts)) {
2973
3244
  throw new Error("Saved artifact manifest is invalid");
@@ -2975,15 +3246,15 @@ var CodeIndexService = class {
2975
3246
  const expectedVectorBytes = this.getExpectedVectorBytes(meta);
2976
3247
  const [vectorFile, metadataFile, keywordsFile] = await Promise.all([
2977
3248
  verifiedVectors ?? readStableIndexFile(
2978
- join6(this.indexDir, meta.artifacts.vectors),
3249
+ join8(this.indexDir, meta.artifacts.vectors),
2979
3250
  expectedVectorBytes
2980
3251
  ),
2981
3252
  readStableIndexFile(
2982
- join6(this.indexDir, meta.artifacts.metadata),
3253
+ join8(this.indexDir, meta.artifacts.metadata),
2983
3254
  this.limits.maxSourceBytes
2984
3255
  ),
2985
3256
  readStableIndexFile(
2986
- join6(this.indexDir, meta.artifacts.keywords),
3257
+ join8(this.indexDir, meta.artifacts.keywords),
2987
3258
  this.limits.maxSourceBytes
2988
3259
  )
2989
3260
  ]);
@@ -3016,7 +3287,7 @@ var CodeIndexService = class {
3016
3287
  );
3017
3288
  const [vectorFile, metadataFile, keywordsFile] = await Promise.all([
3018
3289
  readStableIndexFile(
3019
- join6(this.indexDir, "vectors.bin"),
3290
+ join8(this.indexDir, "vectors.bin"),
3020
3291
  this.limits.maxVectorBytes,
3021
3292
  manifestMtimeMs
3022
3293
  ),
@@ -3256,12 +3527,12 @@ var CodeIndexService = class {
3256
3527
  return bytes;
3257
3528
  }
3258
3529
  selectLegacyArtifact(encryptedName, plaintextName) {
3259
- const encryptedPath = join6(this.indexDir, encryptedName);
3260
- if (existsSync5(encryptedPath)) {
3530
+ const encryptedPath = join8(this.indexDir, encryptedName);
3531
+ if (existsSync4(encryptedPath)) {
3261
3532
  return { path: encryptedPath, encrypted: true };
3262
3533
  }
3263
- const plaintextPath = join6(this.indexDir, plaintextName);
3264
- if (existsSync5(plaintextPath)) {
3534
+ const plaintextPath = join8(this.indexDir, plaintextName);
3535
+ if (existsSync4(plaintextPath)) {
3265
3536
  return { path: plaintextPath, encrypted: false };
3266
3537
  }
3267
3538
  throw new Error("Legacy index artifact is missing");
@@ -3353,7 +3624,7 @@ var CodeIndexService = class {
3353
3624
  }
3354
3625
  if (scanResult.files.length === 0) {
3355
3626
  if (signal?.aborted) return { kind: "cancelled", index: null };
3356
- await rm(join6(this.indexDir, INDEX_MANIFEST_FILE), { force: true });
3627
+ await rm2(join8(this.indexDir, INDEX_MANIFEST_FILE), { force: true });
3357
3628
  const message = "No files to index";
3358
3629
  onProgress?.({ status: "complete", message });
3359
3630
  return { kind: "empty", message };
@@ -3369,7 +3640,7 @@ var CodeIndexService = class {
3369
3640
  }
3370
3641
  if (chunks.length === 0) {
3371
3642
  if (signal?.aborted) return { kind: "cancelled", index: null };
3372
- await rm(join6(this.indexDir, INDEX_MANIFEST_FILE), { force: true });
3643
+ await rm2(join8(this.indexDir, INDEX_MANIFEST_FILE), { force: true });
3373
3644
  const message = "No code chunks found";
3374
3645
  onProgress?.({ status: "complete", message });
3375
3646
  return { kind: "empty", message };
@@ -3807,8 +4078,8 @@ var CodeIndexService = class {
3807
4078
  normalizeWorkspacePath(filePath) {
3808
4079
  const trimmed = filePath.trim();
3809
4080
  if (!trimmed) return null;
3810
- const workspaceRoot = resolve4(this.workspaceRoot);
3811
- const absPath = isAbsolute2(trimmed) ? resolve4(trimmed) : resolve4(workspaceRoot, trimmed);
4081
+ const workspaceRoot = resolve5(this.workspaceRoot);
4082
+ const absPath = isAbsolute2(trimmed) ? resolve5(trimmed) : resolve5(workspaceRoot, trimmed);
3812
4083
  const relativePath = relativePathWithinRoot(workspaceRoot, absPath);
3813
4084
  if (!relativePath) return null;
3814
4085
  return { absPath, relPath: this.toIndexPath(relativePath) };
@@ -3829,7 +4100,7 @@ var CodeIndexService = class {
3829
4100
  const normalizedRelPath = this.toIndexPath(relPath);
3830
4101
  const segments = normalizedRelPath.split("/");
3831
4102
  if (segments.some((segment) => IGNORED_DIRS.has(segment))) return false;
3832
- const fileName = basename5(normalizedRelPath);
4103
+ const fileName = basename6(normalizedRelPath);
3833
4104
  const extension = extname2(normalizedRelPath).toLowerCase();
3834
4105
  if (!CODE_EXTENSIONS.has(extension) && !CODE_FILENAMES.has(fileName)) {
3835
4106
  return false;
@@ -4124,7 +4395,7 @@ var CodeIndexService = class {
4124
4395
  };
4125
4396
  }
4126
4397
  createEmbeddingCacheKey(input, model) {
4127
- return createHash2("sha256").update(
4398
+ return createHash3("sha256").update(
4128
4399
  `${EMBEDDING_INPUT_REVISION}\0${model}\0${hashContentFull(input)}`
4129
4400
  ).digest("hex");
4130
4401
  }
@@ -4142,8 +4413,8 @@ var CodeIndexService = class {
4142
4413
  this.diagnostics.cacheMs += performance.now() - startedAt;
4143
4414
  }
4144
4415
  createProjectIdentifiers() {
4145
- const name = basename5(this.workspaceRoot);
4146
- const hash = createHash2("sha256").update(this.workspaceRoot).digest("hex").slice(0, 16);
4416
+ const name = basename6(this.workspaceRoot);
4417
+ const hash = createHash3("sha256").update(this.workspaceRoot).digest("hex").slice(0, 16);
4147
4418
  return { projectHash: hash, projectName: name };
4148
4419
  }
4149
4420
  // ─── Keyword Index ──────────────────────────────────────────────────────
@@ -4201,7 +4472,7 @@ var CodeIndexService = class {
4201
4472
  try {
4202
4473
  candidate = await this.writeV3Candidate(data);
4203
4474
  const writtenVectors = await readStableIndexFile(
4204
- join6(this.indexDir, candidate.artifacts.vectors),
4475
+ join8(this.indexDir, candidate.artifacts.vectors),
4205
4476
  this.getExpectedVectorBytes(candidate.meta)
4206
4477
  );
4207
4478
  const expected = expectedVectorBuffer ?? candidate.vectorBuffer;
@@ -4228,8 +4499,8 @@ var CodeIndexService = class {
4228
4499
  }
4229
4500
  async writeV3Candidate(data) {
4230
4501
  await this.encryption.ensureKey();
4231
- await mkdir3(this.indexDir, { recursive: true });
4232
- const generation = randomBytes4(8).toString("hex");
4502
+ await mkdir4(this.indexDir, { recursive: true });
4503
+ const generation = randomBytes5(8).toString("hex");
4233
4504
  const artifacts = {
4234
4505
  vectors: `vectors.${generation}.bin`,
4235
4506
  metadata: `meta.${generation}.enc`,
@@ -4253,15 +4524,15 @@ var CodeIndexService = class {
4253
4524
  const candidate = { meta, artifacts, vectorBuffer };
4254
4525
  try {
4255
4526
  await this.atomicWrite(
4256
- join6(this.indexDir, artifacts.vectors),
4527
+ join8(this.indexDir, artifacts.vectors),
4257
4528
  vectorBuffer
4258
4529
  );
4259
4530
  await this.atomicWrite(
4260
- join6(this.indexDir, artifacts.metadata),
4531
+ join8(this.indexDir, artifacts.metadata),
4261
4532
  metadataBuffer
4262
4533
  );
4263
4534
  await this.atomicWrite(
4264
- join6(this.indexDir, artifacts.keywords),
4535
+ join8(this.indexDir, artifacts.keywords),
4265
4536
  keywordsBuffer
4266
4537
  );
4267
4538
  } catch (error) {
@@ -4274,9 +4545,9 @@ var CodeIndexService = class {
4274
4545
  async saveCommitManifest(meta, signal) {
4275
4546
  const projectedMeta = this.projectIndexMeta(meta, INDEX_VERSION);
4276
4547
  const manifest = JSON.stringify(projectedMeta, null, 2);
4277
- await mkdir3(this.indexDir, { recursive: true });
4548
+ await mkdir4(this.indexDir, { recursive: true });
4278
4549
  await this.atomicWrite(
4279
- join6(this.indexDir, INDEX_MANIFEST_FILE),
4550
+ join8(this.indexDir, INDEX_MANIFEST_FILE),
4280
4551
  manifest,
4281
4552
  signal,
4282
4553
  async () => {
@@ -4287,7 +4558,7 @@ var CodeIndexService = class {
4287
4558
  this.diagnostics.metadataBytesWritten += Buffer.byteLength(manifest);
4288
4559
  }
4289
4560
  validateArtifacts(artifacts) {
4290
- return /^vectors\.[a-f0-9]+\.bin$/.test(artifacts.vectors) && /^meta\.[a-f0-9]+\.enc$/.test(artifacts.metadata) && /^keywords\.[a-f0-9]+\.enc$/.test(artifacts.keywords) && basename5(artifacts.vectors) === artifacts.vectors && basename5(artifacts.metadata) === artifacts.metadata && basename5(artifacts.keywords) === artifacts.keywords;
4561
+ return /^vectors\.[a-f0-9]+\.bin$/.test(artifacts.vectors) && /^meta\.[a-f0-9]+\.enc$/.test(artifacts.metadata) && /^keywords\.[a-f0-9]+\.enc$/.test(artifacts.keywords) && basename6(artifacts.vectors) === artifacts.vectors && basename6(artifacts.metadata) === artifacts.metadata && basename6(artifacts.keywords) === artifacts.keywords;
4291
4562
  }
4292
4563
  async cleanupCommittedIndex(artifacts) {
4293
4564
  await Promise.allSettled([
@@ -4298,27 +4569,27 @@ var CodeIndexService = class {
4298
4569
  async removeCandidateArtifacts(artifacts) {
4299
4570
  await Promise.all(
4300
4571
  Object.values(artifacts).map(
4301
- (file) => unlink3(join6(this.indexDir, file)).catch(() => void 0)
4572
+ (file) => unlink4(join8(this.indexDir, file)).catch(() => void 0)
4302
4573
  )
4303
4574
  );
4304
4575
  }
4305
4576
  async removeUnreferencedSnapshotArtifacts(artifacts) {
4306
4577
  const referenced = new Set(Object.values(artifacts));
4307
- const files = await readdir3(this.indexDir).catch(() => []);
4578
+ const files = await readdir4(this.indexDir).catch(() => []);
4308
4579
  await Promise.all(
4309
4580
  files.filter(
4310
4581
  (file) => /^(vectors\.[a-f0-9]+\.bin|meta\.[a-f0-9]+\.enc|keywords\.[a-f0-9]+\.enc)$/.test(
4311
4582
  file
4312
4583
  ) && !referenced.has(file)
4313
4584
  ).map(
4314
- (file) => unlink3(join6(this.indexDir, file)).catch(() => void 0)
4585
+ (file) => unlink4(join8(this.indexDir, file)).catch(() => void 0)
4315
4586
  )
4316
4587
  );
4317
4588
  }
4318
4589
  async removeLegacyV2Artifacts() {
4319
4590
  await Promise.all(
4320
4591
  LEGACY_INDEX_ARTIFACTS.map(
4321
- (file) => unlink3(join6(this.indexDir, file)).catch(() => void 0)
4592
+ (file) => unlink4(join8(this.indexDir, file)).catch(() => void 0)
4322
4593
  )
4323
4594
  );
4324
4595
  }
@@ -4384,7 +4655,7 @@ var CodeIndexService = class {
4384
4655
  };
4385
4656
 
4386
4657
  // src/services/retrieval.service.ts
4387
- import { readdir as readdir4 } from "node:fs/promises";
4658
+ import { readdir as readdir5 } from "node:fs/promises";
4388
4659
  import { posix, win32 } from "node:path";
4389
4660
  var TOP_K = 10;
4390
4661
  var MAX_PER_FILE = 3;
@@ -4725,7 +4996,7 @@ var RetrievalService = class {
4725
4996
  // ─── Path Hint Extraction ──────────────────────────────────────────
4726
4997
  async extractPathHints(query) {
4727
4998
  try {
4728
- const entries = await readdir4(this.workspaceRoot, {
4999
+ const entries = await readdir5(this.workspaceRoot, {
4729
5000
  withFileTypes: true
4730
5001
  });
4731
5002
  const dirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
@@ -4989,7 +5260,7 @@ var IndexDirtyBatch = class {
4989
5260
  // src/services/index-worker.ts
4990
5261
  var port = parentPort;
4991
5262
  var options = workerData;
4992
- var searchContext = new AsyncLocalStorage();
5263
+ var searchContext = new AsyncLocalStorage2();
4993
5264
  var sequence = 0;
4994
5265
  var stopped = false;
4995
5266
  var index = null;
@@ -5027,7 +5298,7 @@ function summary() {
5027
5298
  }
5028
5299
  function broker(event, signal) {
5029
5300
  const requestId = ++sequence;
5030
- return new Promise((resolve5, reject) => {
5301
+ return new Promise((resolve6, reject) => {
5031
5302
  const timer = setTimeout(
5032
5303
  () => {
5033
5304
  pending.delete(requestId);
@@ -5046,7 +5317,7 @@ function broker(event, signal) {
5046
5317
  pending.set(requestId, {
5047
5318
  resolve: (value) => {
5048
5319
  signal?.removeEventListener("abort", abort);
5049
- resolve5(value);
5320
+ resolve6(value);
5050
5321
  },
5051
5322
  reject: (error) => {
5052
5323
  signal?.removeEventListener("abort", abort);
@@ -5092,14 +5363,15 @@ var authorize = async (paths) => !stopped && await broker({
5092
5363
  }) === true;
5093
5364
  engine.setAuthorization(authorize);
5094
5365
  retrieval.setAuthorization(authorize);
5095
- engine.onLease(async (ownerToken) => {
5096
- if (!stopped) await broker({ type: "lease", ownerToken });
5097
- else
5098
- port.postMessage({
5099
- type: "lease",
5100
- requestId: ++sequence,
5101
- ownerToken
5102
- });
5366
+ engine.setLeaseBroker({
5367
+ async acquire() {
5368
+ if (stopped) return null;
5369
+ return await broker({ type: "lease-acquire" });
5370
+ },
5371
+ async release(lease) {
5372
+ if (!stopped)
5373
+ await broker({ type: "lease-release", ownerToken: lease.ownerToken });
5374
+ }
5103
5375
  });
5104
5376
  function publishIndex(state = engine.getRefreshState()) {
5105
5377
  send({
@@ -5241,7 +5513,7 @@ function scheduleDirty(recovery = false) {
5241
5513
  if (!recovery && captured.length === 0) return;
5242
5514
  engine.replaceDirtyFiles(captured.map(({ path: path2 }) => path2));
5243
5515
  const policyChanged = captured.some(
5244
- ({ path: path2 }) => [".lurusignore", ".gitignore"].includes(basename6(path2))
5516
+ ({ path: path2 }) => [".lurusignore", ".gitignore"].includes(basename7(path2))
5245
5517
  );
5246
5518
  operation = recovery ? recoveryOperation : !index ? "startup" : policyChanged ? "refresh" : "dirty";
5247
5519
  if (!recovery) engine.resetAutomaticRefreshBlock();