akm-cli 0.10.261124 → 0.10.261125-beta.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/cli.js +10 -0
  3. package/dist/commands/feedback-cli.js +12 -3
  4. package/dist/commands/health/semantic-search-check.js +12 -2
  5. package/dist/commands/health.js +8 -15
  6. package/dist/commands/lint/index.js +6 -6
  7. package/dist/commands/read/knowledge.js +8 -8
  8. package/dist/commands/read/related.js +3 -9
  9. package/dist/commands/read/show.js +17 -9
  10. package/dist/commands/sources/bundle-cli.js +1 -0
  11. package/dist/commands/sources/installed-stashes.js +36 -27
  12. package/dist/core/asset/resolve-ref.js +8 -0
  13. package/dist/core/common.js +21 -0
  14. package/dist/core/endpoint-url.js +4 -4
  15. package/dist/core/events.js +8 -2
  16. package/dist/core/file-lock.js +52 -1
  17. package/dist/core/state-db.js +47 -15
  18. package/dist/core/stdio-reader-gone.js +19 -0
  19. package/dist/core/write-source.js +2 -2
  20. package/dist/indexer/index-build.js +6 -3
  21. package/dist/indexer/index-readiness.js +30 -4
  22. package/dist/indexer/indexer.js +56 -8
  23. package/dist/indexer/search/db-search.js +7 -1
  24. package/dist/indexer/search/search-source.js +23 -25
  25. package/dist/indexer/usage/usage-events.js +13 -4
  26. package/dist/registry/origin-resolve.js +2 -3
  27. package/dist/scripts/akm-migrate-node.js +118 -72
  28. package/dist/scripts/akm-migrate.js +118 -72
  29. package/dist/setup/endpoint.js +1 -1
  30. package/dist/storage/repositories/index-connection.js +44 -41
  31. package/dist/storage/repositories/index-entries-repository.js +14 -7
  32. package/dist/storage/repositories/index-entry-schema.js +7 -5
  33. package/dist/storage/repositories/index-schema.js +23 -0
  34. package/dist/workspace/assets.js +24 -44
  35. package/dist/workspace/bundle-files.js +2 -2
  36. package/dist/workspace/documents.js +7 -12
  37. package/dist/workspace/graph-topics.js +249 -0
  38. package/dist/workspace/graph.js +68 -4
  39. package/docs/reference/workspace.md +21 -4
  40. package/package.json +1 -1
@@ -28760,8 +28760,27 @@ function tryAcquireLockSync(lockPath, payload) {
28760
28760
  }
28761
28761
  if (snapshot.rawContent !== payload)
28762
28762
  return;
28763
+ acquiredByThisProcess.set(lockPath, payload);
28763
28764
  return { lockPath, ...snapshot };
28764
28765
  }
28766
+ function processIdentity(pid) {
28767
+ try {
28768
+ const bootId = fs4.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
28769
+ const stat = fs4.readFileSync(`/proc/${pid}/stat`, "utf8");
28770
+ const startTime = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
28771
+ return bootId && startTime ? { bootId, startTime } : undefined;
28772
+ } catch {
28773
+ return;
28774
+ }
28775
+ }
28776
+ function holderPidReused(holderPid, recorded) {
28777
+ if (typeof recorded.bootId !== "string" || typeof recorded.startTime !== "string")
28778
+ return false;
28779
+ const current = processIdentity(holderPid);
28780
+ if (!current)
28781
+ return false;
28782
+ return current.bootId !== recorded.bootId || current.startTime !== recorded.startTime;
28783
+ }
28765
28784
  function launcherPidFromEnv() {
28766
28785
  const raw = process.env.AKM_LAUNCHER_PID;
28767
28786
  if (!raw)
@@ -28774,6 +28793,7 @@ function createLockPayload(metadata = {}) {
28774
28793
  return JSON.stringify({
28775
28794
  ...metadata,
28776
28795
  pid: process.pid,
28796
+ ...processIdentity(process.pid),
28777
28797
  ...launcherPid !== undefined ? { launcherPid } : {},
28778
28798
  lockId: randomUUID()
28779
28799
  });
@@ -28799,6 +28819,10 @@ function probeLock(lockPath) {
28799
28819
  if (!isProcessAlive(holderPid)) {
28800
28820
  return { state: "stale", reason: "pid_dead", holderPid, launcherPid, ageMs, rawContent, identity: identity3 };
28801
28821
  }
28822
+ const ownLeftover = holderPid === process.pid && acquiredByThisProcess.get(lockPath) !== rawContent;
28823
+ if (ownLeftover || holderPidReused(holderPid, parseLockJson(rawContent))) {
28824
+ return { state: "stale", reason: "pid_reused", holderPid, launcherPid, ageMs, rawContent, identity: identity3 };
28825
+ }
28802
28826
  return { state: "held", holderPid, launcherPid, ageMs, rawContent, identity: identity3 };
28803
28827
  }
28804
28828
  function reclaimStaleLock(lockPath, probe, options) {
@@ -28856,6 +28880,8 @@ function reclaimStaleLock(lockPath, probe, options) {
28856
28880
  }
28857
28881
  function releaseLock(ownership) {
28858
28882
  const { lockPath } = ownership;
28883
+ if (acquiredByThisProcess.get(lockPath) === ownership.rawContent)
28884
+ acquiredByThisProcess.delete(lockPath);
28859
28885
  let current;
28860
28886
  try {
28861
28887
  current = readLockSnapshot(lockPath);
@@ -28866,6 +28892,14 @@ function releaseLock(ownership) {
28866
28892
  releaseLockRaw(lockPath);
28867
28893
  }
28868
28894
  }
28895
+ function parseLockJson(content) {
28896
+ try {
28897
+ const parsed = JSON.parse(content);
28898
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
28899
+ } catch {
28900
+ return {};
28901
+ }
28902
+ }
28869
28903
  function extractLockIdentity(content) {
28870
28904
  const trimmed = content.trim();
28871
28905
  if (!trimmed)
@@ -28886,9 +28920,10 @@ function extractLockIdentity(content) {
28886
28920
  const pid = Number.parseInt(trimmed, 10);
28887
28921
  return { holderPid: Number.isInteger(pid) && pid > 0 ? pid : undefined };
28888
28922
  }
28889
- var UNINITIALISED_LOCK_GRACE_MS = 2000;
28923
+ var acquiredByThisProcess, UNINITIALISED_LOCK_GRACE_MS = 2000;
28890
28924
  var init_file_lock = __esm(() => {
28891
28925
  init_common();
28926
+ acquiredByThisProcess = new Map;
28892
28927
  });
28893
28928
 
28894
28929
  // src/core/config/config-io.ts
@@ -32721,7 +32756,7 @@ function sameEndpoint(a, b) {
32721
32756
  }
32722
32757
  var OPERATION_SUFFIX;
32723
32758
  var init_endpoint_url = __esm(() => {
32724
- OPERATION_SUFFIX = /\/(?:chat\/completions|embeddings)$/;
32759
+ OPERATION_SUFFIX = /\/(?:chat\/completions|completions|embeddings|models)$/i;
32725
32760
  });
32726
32761
 
32727
32762
  // src/core/config/credentials.ts
@@ -35189,16 +35224,34 @@ function migrateStateDatabase(db, dbPath) {
35189
35224
  db.exec("VACUUM");
35190
35225
  return backupPath ? { applied, backupPath } : { applied };
35191
35226
  }
35227
+ function isStateDbCorruption(error62) {
35228
+ const code = error62?.code;
35229
+ if (code === "SQLITE_NOTADB" || code === "SQLITE_CORRUPT" || code === "SQLITE_IOERR_SHORT_READ")
35230
+ return true;
35231
+ return /not a database|disk image is malformed|SQLITE_CORRUPT/i.test(error62 instanceof Error ? error62.message : String(error62));
35232
+ }
35233
+ function classifyStateDbError(error62, dbPath) {
35234
+ if (error62 instanceof ConfigError || !isStateDbCorruption(error62))
35235
+ return error62;
35236
+ return damagedStateDbError(dbPath, error62 instanceof Error ? error62.message : String(error62));
35237
+ }
35238
+ function damagedStateDbError(dbPath, detail) {
35239
+ return new ConfigError(`state.db at ${dbPath} is damaged (${detail}).`, "INVALID_CONFIG_FILE", "state.db holds non-regenerable state. Back it up, then recover it with " + '`sqlite3 -readonly state.db ".recover" | sqlite3 state.new.db`, or restore a copy; if nothing can be recovered, move it aside and the next akm command creates a new one.');
35240
+ }
35192
35241
  function openAndMigrate(dbPath) {
35193
35242
  let report = { applied: [] };
35194
- const db = openManagedDatabase({
35195
- path: dbPath,
35196
- pragmas: { dataDir: path23.dirname(dbPath) },
35197
- init: (handle) => {
35198
- report = migrateStateDatabase(handle, dbPath);
35199
- }
35200
- });
35201
- return { db, ...report };
35243
+ try {
35244
+ const db = openManagedDatabase({
35245
+ path: dbPath,
35246
+ pragmas: { dataDir: path23.dirname(dbPath) },
35247
+ init: (handle) => {
35248
+ report = migrateStateDatabase(handle, dbPath);
35249
+ }
35250
+ });
35251
+ return { db, ...report };
35252
+ } catch (error62) {
35253
+ throw classifyStateDbError(error62, dbPath);
35254
+ }
35202
35255
  }
35203
35256
  function listPendingStateMigrations(dbPath = getStateDbPath()) {
35204
35257
  if (!fs20.existsSync(dbPath))
@@ -35226,6 +35279,7 @@ var init_state_db = __esm(() => {
35226
35279
  init_sqlite_migrations();
35227
35280
  init_sqlite_pragmas();
35228
35281
  init_version2();
35282
+ init_errors();
35229
35283
  init_paths();
35230
35284
  init_migrations();
35231
35285
  init_warn();
@@ -69434,7 +69488,6 @@ var init_website_ingest = __esm(() => {
69434
69488
  });
69435
69489
 
69436
69490
  // src/indexer/search/search-source.ts
69437
- import fs47 from "fs";
69438
69491
  import path54 from "path";
69439
69492
  function implicitStashDir(config2, overrideStashDir) {
69440
69493
  if (overrideStashDir !== undefined)
@@ -69451,21 +69504,13 @@ function resolveSourceEntries(overrideStashDir, existingConfig) {
69451
69504
  if (implicitConfiguredBundle && !isBundleEnabled(config2, implicitConfiguredBundle)) {
69452
69505
  throw new ConfigError(`The requested working source is disabled as bundle ${JSON.stringify(implicitConfiguredBundle)}.`, "INVALID_CONFIG_FILE");
69453
69506
  }
69454
- const sources = implicitStash ? [{ path: implicitStash, writable: true, isDefault: true, type: "filesystem" }] : [];
69455
- const sourceIdentity = (dir) => {
69456
- const resolved = path54.resolve(dir);
69457
- try {
69458
- return fs47.realpathSync.native(resolved);
69459
- } catch {
69460
- return resolved;
69461
- }
69462
- };
69463
- const seen = new Set(implicitStash ? [sourceIdentity(implicitStash)] : []);
69507
+ const sources = implicitStash ? [{ path: safeRealpath(implicitStash), writable: true, isDefault: true, type: "filesystem" }] : [];
69508
+ const seen = new Set(implicitStash ? [safeRealpath(implicitStash)] : []);
69464
69509
  const addSource = (dir, registryId, writable, type, adapterId, unresolved = false, isDefault = false) => {
69465
69510
  const resolved = path54.resolve(dir);
69466
- const identity3 = sourceIdentity(resolved);
69511
+ const identity3 = safeRealpath(resolved);
69467
69512
  if (seen.has(identity3)) {
69468
- const existing = sources.find((source) => sourceIdentity(source.path) === identity3);
69513
+ const existing = sources.find((source) => safeRealpath(source.path) === identity3);
69469
69514
  if (existing && existing.registryId === undefined) {
69470
69515
  if (registryId)
69471
69516
  existing.registryId = registryId;
@@ -69484,7 +69529,7 @@ function resolveSourceEntries(overrideStashDir, existingConfig) {
69484
69529
  warn(`Warning: stash root "${dir}" appears to be a system directory. This may be unintentional.`);
69485
69530
  }
69486
69531
  sources.push({
69487
- path: resolved,
69532
+ path: identity3,
69488
69533
  ...registryId ? { registryId } : {},
69489
69534
  ...isDefault ? { isDefault: true } : {},
69490
69535
  writable,
@@ -69569,6 +69614,7 @@ var init_search_source = __esm(() => {
69569
69614
  // src/registry/origin-resolve.ts
69570
69615
  var init_origin_resolve = __esm(() => {
69571
69616
  init_asset_ref();
69617
+ init_common();
69572
69618
  init_installations();
69573
69619
  init_resolve();
69574
69620
  });
@@ -69640,9 +69686,9 @@ var init_env_secret_ref = __esm(() => {
69640
69686
  });
69641
69687
 
69642
69688
  // src/core/secret-value.ts
69643
- import fs48 from "fs";
69689
+ import fs47 from "fs";
69644
69690
  function readValue(secretPath) {
69645
- return fs48.readFileSync(secretPath, "utf8").trim();
69691
+ return fs47.readFileSync(secretPath, "utf8").trim();
69646
69692
  }
69647
69693
  var init_secret_value = () => {};
69648
69694
 
@@ -72843,7 +72889,7 @@ init_secret_seam();
72843
72889
 
72844
72890
  // scripts/akm-migrate/migrate/dead-residue.ts
72845
72891
  init_paths();
72846
- import fs49 from "fs";
72892
+ import fs48 from "fs";
72847
72893
  import path55 from "path";
72848
72894
  var DEAD_RESIDUE_PATHS = [
72849
72895
  { name: "proposals", reason: "superseded by the `proposals` table in $DATA/state.db (0.9.0)" },
@@ -72861,7 +72907,7 @@ function dirSizeBytes(target) {
72861
72907
  let total = 0;
72862
72908
  let entries;
72863
72909
  try {
72864
- entries = fs49.readdirSync(target, { withFileTypes: true });
72910
+ entries = fs48.readdirSync(target, { withFileTypes: true });
72865
72911
  } catch {
72866
72912
  return 0;
72867
72913
  }
@@ -72871,14 +72917,14 @@ function dirSizeBytes(target) {
72871
72917
  total += dirSizeBytes(entryPath);
72872
72918
  } else if (entry.isFile()) {
72873
72919
  try {
72874
- total += fs49.statSync(entryPath).size;
72920
+ total += fs48.statSync(entryPath).size;
72875
72921
  } catch {}
72876
72922
  }
72877
72923
  }
72878
72924
  return total;
72879
72925
  }
72880
72926
  function sizeOf(target) {
72881
- const st2 = fs49.statSync(target);
72927
+ const st2 = fs48.statSync(target);
72882
72928
  return st2.isDirectory() ? dirSizeBytes(target) : st2.size;
72883
72929
  }
72884
72930
  function hostResidue() {
@@ -72897,7 +72943,7 @@ function hostResidue() {
72897
72943
  const found = [];
72898
72944
  const claimed = new Set;
72899
72945
  for (const entry of named) {
72900
- if (claimed.has(entry.absolutePath) || !fs49.existsSync(entry.absolutePath))
72946
+ if (claimed.has(entry.absolutePath) || !fs48.existsSync(entry.absolutePath))
72901
72947
  continue;
72902
72948
  try {
72903
72949
  found.push({ ...entry, relativePath: entry.absolutePath, sizeBytes: sizeOf(entry.absolutePath) });
@@ -72921,7 +72967,7 @@ function hostResidue() {
72921
72967
  function findSidecars(root2, depth, skip) {
72922
72968
  let entries;
72923
72969
  try {
72924
- entries = fs49.readdirSync(root2, { withFileTypes: true });
72970
+ entries = fs48.readdirSync(root2, { withFileTypes: true });
72925
72971
  } catch {
72926
72972
  return [];
72927
72973
  }
@@ -72943,7 +72989,7 @@ function findDeadResidueEntries(stashDir) {
72943
72989
  const akmDir = path55.join(stashDir, ".akm");
72944
72990
  let names;
72945
72991
  try {
72946
- names = fs49.readdirSync(akmDir);
72992
+ names = fs48.readdirSync(akmDir);
72947
72993
  } catch {
72948
72994
  return host;
72949
72995
  }
@@ -72969,7 +73015,7 @@ function removeDeadResidue(stashDir) {
72969
73015
  const entries = findDeadResidueEntries(stashDir);
72970
73016
  return entries.map((entry) => {
72971
73017
  try {
72972
- fs49.rmSync(entry.absolutePath, { recursive: true, force: true });
73018
+ fs48.rmSync(entry.absolutePath, { recursive: true, force: true });
72973
73019
  return { relativePath: entry.relativePath, sizeBytes: entry.sizeBytes, removed: true };
72974
73020
  } catch (error62) {
72975
73021
  return {
@@ -72999,7 +73045,7 @@ init_errors();
72999
73045
  init_write_source();
73000
73046
  init_search_source();
73001
73047
  init_lockfile();
73002
- import fs50 from "fs";
73048
+ import fs49 from "fs";
73003
73049
  import os10 from "os";
73004
73050
  import path56 from "path";
73005
73051
  function expandTilde(value) {
@@ -73011,7 +73057,7 @@ function expandTilde(value) {
73011
73057
  }
73012
73058
  function existingDirectory(target) {
73013
73059
  try {
73014
- return fs50.statSync(target).isDirectory();
73060
+ return fs49.statSync(target).isDirectory();
73015
73061
  } catch (cause) {
73016
73062
  if (cause.code === "ENOENT")
73017
73063
  return false;
@@ -73262,14 +73308,14 @@ function planEngineKeys(inputs, resolve) {
73262
73308
 
73263
73309
  // scripts/akm-migrate/migrate/engine-key-files.ts
73264
73310
  init_walker();
73265
- import fs52 from "fs";
73311
+ import fs51 from "fs";
73266
73312
  import path59 from "path";
73267
73313
 
73268
73314
  // scripts/akm-migrate/migrate/task-files.ts
73269
73315
  init_errors();
73270
73316
  init_task_source_v4();
73271
73317
  import crypto5 from "crypto";
73272
- import fs51 from "fs";
73318
+ import fs50 from "fs";
73273
73319
  import path58 from "path";
73274
73320
 
73275
73321
  // scripts/akm-migrate/migrate/task-to-v4.ts
@@ -74327,14 +74373,14 @@ function contained(root2, candidate) {
74327
74373
  return relative === "" || !relative.startsWith("..") && !path58.isAbsolute(relative);
74328
74374
  }
74329
74375
  function realDirectory(filePath) {
74330
- const stat = fs51.lstatSync(filePath);
74376
+ const stat = fs50.lstatSync(filePath);
74331
74377
  if (stat.isSymbolicLink() || !stat.isDirectory())
74332
74378
  throw migrationError(`${filePath} must be a real directory.`);
74333
- return fs51.realpathSync(filePath);
74379
+ return fs50.realpathSync(filePath);
74334
74380
  }
74335
74381
  function isWritable(filePath) {
74336
74382
  try {
74337
- fs51.accessSync(filePath, fs51.constants.W_OK);
74383
+ fs50.accessSync(filePath, fs50.constants.W_OK);
74338
74384
  return true;
74339
74385
  } catch {
74340
74386
  return false;
@@ -74347,11 +74393,11 @@ function walkRootFiles(root2, directory, extension, onLink, visit3) {
74347
74393
  throw migrationError(`${root2.root} resolves outside bundle ${root2.bundleId}.`);
74348
74394
  }
74349
74395
  const walk = (current) => {
74350
- const physicalDirectory = fs51.realpathSync(current);
74396
+ const physicalDirectory = fs50.realpathSync(current);
74351
74397
  if (!contained(physicalRoot, physicalDirectory)) {
74352
74398
  throw migrationError(`${current} resolves outside bundle ${root2.bundleId}.`);
74353
74399
  }
74354
- for (const entry of fs51.readdirSync(current, { withFileTypes: true }).sort((a3, b) => a3.name.localeCompare(b.name))) {
74400
+ for (const entry of fs50.readdirSync(current, { withFileTypes: true }).sort((a3, b) => a3.name.localeCompare(b.name))) {
74355
74401
  const candidate = path58.join(current, entry.name);
74356
74402
  if (entry.isSymbolicLink()) {
74357
74403
  onLink(candidate);
@@ -74371,11 +74417,11 @@ function walkTasks(root2, tasksDir, out) {
74371
74417
  walkRootFiles(root2, tasksDir, ".yml", (link) => {
74372
74418
  throw migrationError(`task migration does not follow symbolic link ${link}.`);
74373
74419
  }, (candidate, directory) => {
74374
- const stat = fs51.lstatSync(candidate);
74420
+ const stat = fs50.lstatSync(candidate);
74375
74421
  const mode = stat.mode & 511;
74376
74422
  out.push({
74377
74423
  filePath: candidate,
74378
- bytes: fs51.readFileSync(candidate),
74424
+ bytes: fs50.readFileSync(candidate),
74379
74425
  mode,
74380
74426
  writable: root2.writable,
74381
74427
  onDiskWritable: isWritable(candidate) && isWritable(directory) && (mode & 146) !== 0
@@ -74387,7 +74433,7 @@ function inspectTaskFiles(roots) {
74387
74433
  for (const root2 of [...roots].sort((a3, b) => a3.bundleId.localeCompare(b.bundleId))) {
74388
74434
  const tasksDir = root2.layout === "akm-task" ? root2.root : path58.join(root2.root, "tasks");
74389
74435
  try {
74390
- const stat = fs51.lstatSync(tasksDir);
74436
+ const stat = fs50.lstatSync(tasksDir);
74391
74437
  if (stat.isSymbolicLink())
74392
74438
  throw migrationError(`task migration does not follow symbolic link ${tasksDir}.`);
74393
74439
  if (!stat.isDirectory())
@@ -74412,11 +74458,11 @@ function fsyncDirectory(directory) {
74412
74458
  if (process.platform === "win32")
74413
74459
  return;
74414
74460
  try {
74415
- const fd = fs51.openSync(directory, "r");
74461
+ const fd = fs50.openSync(directory, "r");
74416
74462
  try {
74417
- fs51.fsyncSync(fd);
74463
+ fs50.fsyncSync(fd);
74418
74464
  } finally {
74419
- fs51.closeSync(fd);
74465
+ fs50.closeSync(fd);
74420
74466
  }
74421
74467
  } catch (cause) {
74422
74468
  const code = cause.code;
@@ -74425,30 +74471,30 @@ function fsyncDirectory(directory) {
74425
74471
  }
74426
74472
  }
74427
74473
  function writeDurable(filePath, bytes, mode, exclusive = false) {
74428
- fs51.mkdirSync(path58.dirname(filePath), { recursive: true });
74429
- const fd = fs51.openSync(filePath, exclusive ? "wx" : "w", mode);
74474
+ fs50.mkdirSync(path58.dirname(filePath), { recursive: true });
74475
+ const fd = fs50.openSync(filePath, exclusive ? "wx" : "w", mode);
74430
74476
  try {
74431
- fs51.writeFileSync(fd, bytes);
74432
- fs51.fsyncSync(fd);
74477
+ fs50.writeFileSync(fd, bytes);
74478
+ fs50.fsyncSync(fd);
74433
74479
  } finally {
74434
- fs51.closeSync(fd);
74480
+ fs50.closeSync(fd);
74435
74481
  }
74436
- fs51.chmodSync(filePath, mode);
74482
+ fs50.chmodSync(filePath, mode);
74437
74483
  fsyncDirectory(path58.dirname(filePath));
74438
74484
  }
74439
74485
  function replaceAtomically(filePath, bytes, mode) {
74440
74486
  const temporary = path58.join(path58.dirname(filePath), `.${path58.basename(filePath)}.migrate-${crypto5.randomUUID()}`);
74441
74487
  try {
74442
74488
  writeDurable(temporary, bytes, mode, true);
74443
- fs51.renameSync(temporary, filePath);
74489
+ fs50.renameSync(temporary, filePath);
74444
74490
  fsyncDirectory(path58.dirname(filePath));
74445
74491
  } finally {
74446
- fs51.rmSync(temporary, { force: true });
74492
+ fs50.rmSync(temporary, { force: true });
74447
74493
  }
74448
74494
  }
74449
74495
  function holds(filePath, bytes) {
74450
74496
  try {
74451
- return fs51.readFileSync(filePath).equals(bytes);
74497
+ return fs50.readFileSync(filePath).equals(bytes);
74452
74498
  } catch {
74453
74499
  return false;
74454
74500
  }
@@ -74468,7 +74514,7 @@ function replaceFilesWithBackups(changes, backupRoot) {
74468
74514
  try {
74469
74515
  for (const change of backedUp) {
74470
74516
  if (!holds(change.filePath, change.before)) {
74471
- fs51.rmSync(taskFileBackupPath(backupRoot, change.filePath), { force: true });
74517
+ fs50.rmSync(taskFileBackupPath(backupRoot, change.filePath), { force: true });
74472
74518
  conflicts.push(change.filePath);
74473
74519
  continue;
74474
74520
  }
@@ -74479,7 +74525,7 @@ function replaceFilesWithBackups(changes, backupRoot) {
74479
74525
  const unrestored = [];
74480
74526
  for (const change of [...replaced].reverse()) {
74481
74527
  if (holds(change.filePath, change.after)) {
74482
- replaceAtomically(change.filePath, fs51.readFileSync(taskFileBackupPath(backupRoot, change.filePath)), change.mode);
74528
+ replaceAtomically(change.filePath, fs50.readFileSync(taskFileBackupPath(backupRoot, change.filePath)), change.mode);
74483
74529
  } else {
74484
74530
  unrestored.push(change.filePath);
74485
74531
  }
@@ -74525,7 +74571,7 @@ var LAYOUTS = new Map([
74525
74571
  function collect(root2, directory, role, extension, out) {
74526
74572
  let top;
74527
74573
  try {
74528
- top = fs52.lstatSync(directory);
74574
+ top = fs51.lstatSync(directory);
74529
74575
  } catch (cause) {
74530
74576
  if (cause.code === "ENOENT")
74531
74577
  return;
@@ -74538,8 +74584,8 @@ function collect(root2, directory, role, extension, out) {
74538
74584
  return;
74539
74585
  out.set(link, {
74540
74586
  filePath: link,
74541
- bytes: fs52.readFileSync(link),
74542
- mode: fs52.statSync(link).mode & 511,
74587
+ bytes: fs51.readFileSync(link),
74588
+ mode: fs51.statSync(link).mode & 511,
74543
74589
  role,
74544
74590
  writable: root2.writable,
74545
74591
  link: true
@@ -74549,8 +74595,8 @@ function collect(root2, directory, role, extension, out) {
74549
74595
  return;
74550
74596
  out.set(candidate, {
74551
74597
  filePath: candidate,
74552
- bytes: fs52.readFileSync(candidate),
74553
- mode: fs52.lstatSync(candidate).mode & 511,
74598
+ bytes: fs51.readFileSync(candidate),
74599
+ mode: fs51.lstatSync(candidate).mode & 511,
74554
74600
  role,
74555
74601
  writable: root2.writable
74556
74602
  });
@@ -74683,7 +74729,7 @@ init_paths();
74683
74729
  init_walker();
74684
74730
  import { randomUUID as randomUUID4 } from "crypto";
74685
74731
  import { spawnSync as spawnSync6 } from "child_process";
74686
- import fs53 from "fs";
74732
+ import fs52 from "fs";
74687
74733
  import path61 from "path";
74688
74734
 
74689
74735
  // scripts/akm-migrate/migrate/content-ref-planner.ts
@@ -74747,7 +74793,7 @@ function contentRefRewriter(bundles) {
74747
74793
  // scripts/akm-migrate/content-ref-migrate.ts
74748
74794
  var TEXT_EXTENSIONS = new Set([".md", ".yml", ".yaml", ".sh", ".ts", ".js", ".json", ".txt", ".py", ".mjs", ".jsonc", ".toml", ""]);
74749
74795
  function textFiles(root2) {
74750
- return walkStashFlat(root2).filter((file2) => TEXT_EXTENSIONS.has(file2.ext) && fs53.lstatSync(file2.absPath).isFile()).map((file2) => file2.absPath);
74796
+ return walkStashFlat(root2).filter((file2) => TEXT_EXTENSIONS.has(file2.ext) && fs52.lstatSync(file2.absPath).isFile()).map((file2) => file2.absPath);
74751
74797
  }
74752
74798
  function bundleDocuments(roots) {
74753
74799
  const bundles = new Map;
@@ -74783,7 +74829,7 @@ function gitReconcile(filePaths, backupPath) {
74783
74829
  const topOf = new Map;
74784
74830
  const byRoot = new Map;
74785
74831
  for (const filePath of filePaths) {
74786
- const real = fs53.realpathSync(filePath);
74832
+ const real = fs52.realpathSync(filePath);
74787
74833
  const dir = path61.dirname(real);
74788
74834
  if (!topOf.has(dir)) {
74789
74835
  const top = spawnSync6("git", ["-C", dir, "rev-parse", "--show-toplevel"], { encoding: "utf8", env });
@@ -74812,7 +74858,7 @@ function plan2() {
74812
74858
  if (seen.has(filePath) || !(documents.files.has(filePath) || isStructuralFile(root2.root, adapterId, filePath, assetDirs)))
74813
74859
  continue;
74814
74860
  seen.add(filePath);
74815
- const before = fs53.readFileSync(filePath);
74861
+ const before = fs52.readFileSync(filePath);
74816
74862
  const text2 = before.toString("utf8");
74817
74863
  if (!Buffer.from(text2, "utf8").equals(before))
74818
74864
  continue;
@@ -74820,7 +74866,7 @@ function plan2() {
74820
74866
  if (count === 0)
74821
74867
  continue;
74822
74868
  files.push({
74823
- replacement: { filePath, before, after: Buffer.from(rewritten, "utf8"), mode: fs53.statSync(filePath).mode & 511 },
74869
+ replacement: { filePath, before, after: Buffer.from(rewritten, "utf8"), mode: fs52.statSync(filePath).mode & 511 },
74824
74870
  refs: count
74825
74871
  });
74826
74872
  }
@@ -74876,7 +74922,7 @@ init_config_io();
74876
74922
  init_errors();
74877
74923
  init_paths();
74878
74924
  import { randomUUID as randomUUID5 } from "crypto";
74879
- import fs54 from "fs";
74925
+ import fs53 from "fs";
74880
74926
  import path62 from "path";
74881
74927
  function taskRoots(config2) {
74882
74928
  return bundleRoots(config2).flatMap((root2) => {
@@ -74888,7 +74934,7 @@ function taskRoot(candidate) {
74888
74934
  const { bundleId, bundleRoot, root: root2, writable } = candidate;
74889
74935
  const adapter = candidate.adapter ?? detectAdapterId(root2, "");
74890
74936
  if (!candidate.adapter && adapter === "") {
74891
- const flatTasks = fs54.readdirSync(root2, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".yml")).map((entry) => entry.name).sort();
74937
+ const flatTasks = fs53.readdirSync(root2, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".yml")).map((entry) => entry.name).sort();
74892
74938
  if (flatTasks.length > 0) {
74893
74939
  throw new ConfigError(`Task migration cannot classify top-level task file(s) ${flatTasks.join(", ")} in bundle ${bundleId}; configure adapter "akm-task" or move them under tasks/.`, "INVALID_CONFIG_FILE");
74894
74940
  }
@@ -25,7 +25,7 @@ export function normalizeEndpoint(input) {
25
25
  if (!OLLAMA_EMBED_ROUTE.test(pathname)) {
26
26
  // An operation URL (`…/chat/completions`, `…/embeddings`) names its base.
27
27
  pathname = new URL(openAiBaseUrl(url.toString())).pathname.replace(/\/+$/, "");
28
- if (!pathname.endsWith("/v1") && !pathname.includes("/openai"))
28
+ if (!/\/v1$/i.test(pathname) && !pathname.toLowerCase().includes("/openai"))
29
29
  pathname += "/v1";
30
30
  }
31
31
  url.pathname = pathname;
@@ -14,7 +14,7 @@ import fs from "node:fs";
14
14
  import { ConfigError } from "../../core/errors.js";
15
15
  import { classifyPathAccess, describeInaccessiblePath } from "../../core/path-access.js";
16
16
  import { getDbPath } from "../../core/paths.js";
17
- import { warn, warnOnce } from "../../core/warn.js";
17
+ import { warnOnce } from "../../core/warn.js";
18
18
  import { openDatabase } from "../database.js";
19
19
  import { openManagedDatabase } from "../managed-db.js";
20
20
  import { SQLITE_BUSY_TIMEOUT_MS } from "../sqlite-pragmas.js";
@@ -22,28 +22,56 @@ import { openSqliteReadSnapshot, SqliteReadSnapshotUnavailableError } from "../s
22
22
  import { CANONICAL_INDEX_DB_VERSION } from "./index-entry-schema.js";
23
23
  import { ensureSchema, newerIndexLayoutError } from "./index-schema.js";
24
24
  /**
25
- * Whether `error` is SQLite reporting on-disk corruption (`SQLITE_CORRUPT`,
26
- * "database disk image is malformed") rather than a permission, lock, or
27
- * schema problem. Matched on both `code` (bun:sqlite, better-sqlite3) and
28
- * message text, since driver error shapes are not perfectly uniform.
25
+ * Whether `error` is SQLite reporting that the file is not a usable database
26
+ * (`SQLITE_CORRUPT*` "database disk image is malformed", `SQLITE_NOTADB` "file
27
+ * is not a database") rather than a permission, lock, or schema problem.
28
+ * Matched on both `code` (bun:sqlite, better-sqlite3) and message text, since
29
+ * driver error shapes are not perfectly uniform.
29
30
  */
30
- function isCorruptionError(error) {
31
+ export function isCorruptionError(error) {
31
32
  const code = error?.code;
32
- if (code === "SQLITE_CORRUPT")
33
+ if (typeof code === "string" && (code.startsWith("SQLITE_CORRUPT") || code === "SQLITE_NOTADB"))
33
34
  return true;
34
35
  const message = error instanceof Error ? error.message : String(error);
35
- return message.includes("database disk image is malformed") || message.includes("SQLITE_CORRUPT");
36
+ return (message.includes("database disk image is malformed") ||
37
+ message.includes("file is not a database") ||
38
+ message.includes("SQLITE_CORRUPT") ||
39
+ message.includes("SQLITE_NOTADB"));
36
40
  }
37
41
  /**
38
- * Open `index.db` for writing, creating and migrating it. A corrupt file is
39
- * deleted and rebuilt only when the caller says it may (`rebuildCorrupt`): the
40
- * build, which holds the rebuild lock. Any other writable opener raises the
41
- * corruption error instead of deleting a file a build or a reader may be using.
42
+ * Whether `index.db` itself is damaged: it cannot be opened, or `PRAGMA quick_check` reports a problem.
43
+ * A corruption error from a build or a read may come from another database (state.db), so callers ask
44
+ * this before deleting or blaming the index. An absent or unreadable-by-permission file is not damaged.
42
45
  */
46
+ export function indexDbIsDamaged(dbPath = getDbPath()) {
47
+ let db;
48
+ try {
49
+ db = openDatabase(dbPath, { readonly: true, create: false });
50
+ const row = db?.prepare("PRAGMA quick_check(1)").get();
51
+ return row !== undefined && row.quick_check !== "ok";
52
+ }
53
+ catch (error) {
54
+ return isCorruptionError(error);
55
+ }
56
+ finally {
57
+ db?.close();
58
+ }
59
+ }
60
+ /** Delete `index.db` and its sidecars; the build rebuilds it from the library. Best-effort per file. */
61
+ export function deleteIndexDatabase(dbPath) {
62
+ for (const suffix of ["", "-wal", "-shm"]) {
63
+ try {
64
+ fs.rmSync(`${dbPath}${suffix}`, { force: true });
65
+ }
66
+ catch {
67
+ // Best-effort cleanup; the next open still fails loudly if the file could not actually be removed.
68
+ }
69
+ }
70
+ }
71
+ /** Open `index.db` for writing, creating and migrating it. Corruption raises; only the build, which holds the rebuild lock, deletes and rebuilds. */
43
72
  export function openIndexDatabase(dbPath, options) {
44
- const resolvedPath = dbPath ?? getDbPath();
45
- const spec = {
46
- path: resolvedPath,
73
+ return openManagedDatabase({
74
+ path: dbPath ?? getDbPath(),
47
75
  init: (db) => {
48
76
  // Source update uses this narrow lifecycle seam to ATTACH state.db and
49
77
  // open its coordinator-owned outer transaction before ensureSchema or
@@ -51,32 +79,7 @@ export function openIndexDatabase(dbPath, options) {
51
79
  options?.beforeSchema?.(db);
52
80
  ensureSchema(db);
53
81
  },
54
- };
55
- try {
56
- return openManagedDatabase(spec);
57
- }
58
- catch (error) {
59
- // index.db is a derived cache, fully regenerable from the stash on disk
60
- // (see src/core/state-db.ts's "Why a separate database from index.db"
61
- // note) — so real on-disk corruption is recovered by deleting the file
62
- // and rebuilding, not by surfacing a raw SQLITE_CORRUPT to the caller or
63
- // quietly falling through to an unreadable index (#865). This is the ONE
64
- // from-scratch rebuild: an older layout is migrated in place by
65
- // ensureSchema, never dropped.
66
- if (!options?.rebuildCorrupt || !isCorruptionError(error))
67
- throw error;
68
- warn(`Index database is corrupt at ${resolvedPath} — rebuilding.`);
69
- for (const suffix of ["", "-wal", "-shm"]) {
70
- try {
71
- fs.rmSync(`${resolvedPath}${suffix}`, { force: true });
72
- }
73
- catch {
74
- // Best-effort cleanup; the retried open below still fails loudly if
75
- // the file could not actually be removed.
76
- }
77
- }
78
- return openManagedDatabase(spec);
79
- }
82
+ });
80
83
  }
81
84
  export function openExistingDatabase(dbPath) {
82
85
  // Existing-DB callers do not mutate schema or embedding metadata on open;