akm-cli 0.10.261124 → 0.10.261125

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 (44) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/cli/usage.js +4 -0
  3. package/dist/cli.js +10 -0
  4. package/dist/commands/feedback-cli.js +12 -3
  5. package/dist/commands/health/semantic-search-check.js +12 -2
  6. package/dist/commands/health.js +8 -15
  7. package/dist/commands/lint/index.js +6 -6
  8. package/dist/commands/read/knowledge.js +8 -8
  9. package/dist/commands/read/related.js +3 -9
  10. package/dist/commands/read/show.js +17 -9
  11. package/dist/commands/sources/bundle-cli.js +1 -0
  12. package/dist/commands/sources/installed-stashes.js +36 -27
  13. package/dist/core/asset/resolve-ref.js +8 -0
  14. package/dist/core/common.js +21 -0
  15. package/dist/core/endpoint-url.js +4 -4
  16. package/dist/core/events.js +8 -2
  17. package/dist/core/file-lock.js +52 -1
  18. package/dist/core/state-db.js +47 -15
  19. package/dist/core/stdio-reader-gone.js +19 -0
  20. package/dist/core/write-source.js +2 -2
  21. package/dist/indexer/index-build.js +6 -3
  22. package/dist/indexer/index-readiness.js +30 -4
  23. package/dist/indexer/indexer.js +56 -8
  24. package/dist/indexer/search/db-search.js +7 -1
  25. package/dist/indexer/search/search-source.js +23 -25
  26. package/dist/indexer/usage/usage-events.js +13 -4
  27. package/dist/indexer/vector-file.js +3 -3
  28. package/dist/registry/origin-resolve.js +2 -3
  29. package/dist/scripts/akm-migrate-node.js +136 -88
  30. package/dist/scripts/akm-migrate.js +136 -88
  31. package/dist/setup/endpoint.js +1 -1
  32. package/dist/storage/database.js +29 -36
  33. package/dist/storage/repositories/index-connection.js +44 -41
  34. package/dist/storage/repositories/index-entries-repository.js +14 -7
  35. package/dist/storage/repositories/index-entry-schema.js +7 -5
  36. package/dist/storage/repositories/index-schema.js +23 -0
  37. package/dist/storage/sqlite-read-snapshot.js +2 -2
  38. package/dist/workspace/assets.js +24 -44
  39. package/dist/workspace/bundle-files.js +2 -2
  40. package/dist/workspace/documents.js +7 -12
  41. package/dist/workspace/graph-topics.js +249 -0
  42. package/dist/workspace/graph.js +68 -4
  43. package/docs/reference/workspace.md +21 -4
  44. 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
@@ -30713,26 +30748,28 @@ var init_agent_builder = __esm(() => {
30713
30748
  // src/storage/database.ts
30714
30749
  import { createRequire as createRequire2 } from "module";
30715
30750
  function openDatabase(path13, opts) {
30716
- return isBun2 ? openBunDatabase(path13, opts) : openNodeDatabase(path13, opts);
30717
- }
30718
- function openDatabaseFinalizing(path13, opts) {
30719
- const db = openDatabase(path13, opts);
30720
- const tracked = new Set;
30721
- const origPrepare = db.prepare.bind(db);
30722
- const origClose = db.close.bind(db);
30723
- db.prepare = (sql, ...rest) => {
30724
- const stmt = origPrepare(sql, ...rest);
30725
- tracked.add(stmt);
30751
+ return isBun2 ? finalizeOnClose(openBunDatabase(path13, opts)) : openNodeDatabase(path13, opts);
30752
+ }
30753
+ function finalizeOnClose(db) {
30754
+ const live = new Set;
30755
+ const forget = new FinalizationRegistry((ref) => live.delete(ref));
30756
+ const prepare = db.prepare.bind(db);
30757
+ const close = db.close.bind(db);
30758
+ db.prepare = (sql) => {
30759
+ const stmt = prepare(sql);
30760
+ const ref = new WeakRef(stmt);
30761
+ live.add(ref);
30762
+ forget.register(stmt, ref);
30726
30763
  return stmt;
30727
30764
  };
30728
- db.close = (...args) => {
30729
- for (const stmt of tracked) {
30765
+ db.close = () => {
30766
+ for (const ref of live) {
30730
30767
  try {
30731
- stmt.finalize?.();
30768
+ ref.deref()?.finalize?.();
30732
30769
  } catch {}
30733
30770
  }
30734
- tracked.clear();
30735
- return origClose(...args);
30771
+ live.clear();
30772
+ close();
30736
30773
  };
30737
30774
  return db;
30738
30775
  }
@@ -30901,7 +30938,7 @@ function openSqliteReadSnapshot(dbPath) {
30901
30938
  let db;
30902
30939
  try {
30903
30940
  copySqliteSnapshot(dbPath, snapshotPath);
30904
- db = openDatabaseFinalizing(snapshotPath, { readonly: true, create: false });
30941
+ db = openDatabase(snapshotPath, { readonly: true, create: false });
30905
30942
  const closeSnapshot = db.close.bind(db);
30906
30943
  let closed = false;
30907
30944
  const cleanup = (bestEffort) => {
@@ -32721,7 +32758,7 @@ function sameEndpoint(a, b) {
32721
32758
  }
32722
32759
  var OPERATION_SUFFIX;
32723
32760
  var init_endpoint_url = __esm(() => {
32724
- OPERATION_SUFFIX = /\/(?:chat\/completions|embeddings)$/;
32761
+ OPERATION_SUFFIX = /\/(?:chat\/completions|completions|embeddings|models)$/i;
32725
32762
  });
32726
32763
 
32727
32764
  // src/core/config/credentials.ts
@@ -35189,16 +35226,34 @@ function migrateStateDatabase(db, dbPath) {
35189
35226
  db.exec("VACUUM");
35190
35227
  return backupPath ? { applied, backupPath } : { applied };
35191
35228
  }
35229
+ function isStateDbCorruption(error62) {
35230
+ const code = error62?.code;
35231
+ if (code === "SQLITE_NOTADB" || code === "SQLITE_CORRUPT" || code === "SQLITE_IOERR_SHORT_READ")
35232
+ return true;
35233
+ return /not a database|disk image is malformed|SQLITE_CORRUPT/i.test(error62 instanceof Error ? error62.message : String(error62));
35234
+ }
35235
+ function classifyStateDbError(error62, dbPath) {
35236
+ if (error62 instanceof ConfigError || !isStateDbCorruption(error62))
35237
+ return error62;
35238
+ return damagedStateDbError(dbPath, error62 instanceof Error ? error62.message : String(error62));
35239
+ }
35240
+ function damagedStateDbError(dbPath, detail) {
35241
+ 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.');
35242
+ }
35192
35243
  function openAndMigrate(dbPath) {
35193
35244
  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 };
35245
+ try {
35246
+ const db = openManagedDatabase({
35247
+ path: dbPath,
35248
+ pragmas: { dataDir: path23.dirname(dbPath) },
35249
+ init: (handle) => {
35250
+ report = migrateStateDatabase(handle, dbPath);
35251
+ }
35252
+ });
35253
+ return { db, ...report };
35254
+ } catch (error62) {
35255
+ throw classifyStateDbError(error62, dbPath);
35256
+ }
35202
35257
  }
35203
35258
  function listPendingStateMigrations(dbPath = getStateDbPath()) {
35204
35259
  if (!fs20.existsSync(dbPath))
@@ -35226,6 +35281,7 @@ var init_state_db = __esm(() => {
35226
35281
  init_sqlite_migrations();
35227
35282
  init_sqlite_pragmas();
35228
35283
  init_version2();
35284
+ init_errors();
35229
35285
  init_paths();
35230
35286
  init_migrations();
35231
35287
  init_warn();
@@ -69434,7 +69490,6 @@ var init_website_ingest = __esm(() => {
69434
69490
  });
69435
69491
 
69436
69492
  // src/indexer/search/search-source.ts
69437
- import fs47 from "fs";
69438
69493
  import path54 from "path";
69439
69494
  function implicitStashDir(config2, overrideStashDir) {
69440
69495
  if (overrideStashDir !== undefined)
@@ -69451,21 +69506,13 @@ function resolveSourceEntries(overrideStashDir, existingConfig) {
69451
69506
  if (implicitConfiguredBundle && !isBundleEnabled(config2, implicitConfiguredBundle)) {
69452
69507
  throw new ConfigError(`The requested working source is disabled as bundle ${JSON.stringify(implicitConfiguredBundle)}.`, "INVALID_CONFIG_FILE");
69453
69508
  }
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)] : []);
69509
+ const sources = implicitStash ? [{ path: safeRealpath(implicitStash), writable: true, isDefault: true, type: "filesystem" }] : [];
69510
+ const seen = new Set(implicitStash ? [safeRealpath(implicitStash)] : []);
69464
69511
  const addSource = (dir, registryId, writable, type, adapterId, unresolved = false, isDefault = false) => {
69465
69512
  const resolved = path54.resolve(dir);
69466
- const identity3 = sourceIdentity(resolved);
69513
+ const identity3 = safeRealpath(resolved);
69467
69514
  if (seen.has(identity3)) {
69468
- const existing = sources.find((source) => sourceIdentity(source.path) === identity3);
69515
+ const existing = sources.find((source) => safeRealpath(source.path) === identity3);
69469
69516
  if (existing && existing.registryId === undefined) {
69470
69517
  if (registryId)
69471
69518
  existing.registryId = registryId;
@@ -69484,7 +69531,7 @@ function resolveSourceEntries(overrideStashDir, existingConfig) {
69484
69531
  warn(`Warning: stash root "${dir}" appears to be a system directory. This may be unintentional.`);
69485
69532
  }
69486
69533
  sources.push({
69487
- path: resolved,
69534
+ path: identity3,
69488
69535
  ...registryId ? { registryId } : {},
69489
69536
  ...isDefault ? { isDefault: true } : {},
69490
69537
  writable,
@@ -69569,6 +69616,7 @@ var init_search_source = __esm(() => {
69569
69616
  // src/registry/origin-resolve.ts
69570
69617
  var init_origin_resolve = __esm(() => {
69571
69618
  init_asset_ref();
69619
+ init_common();
69572
69620
  init_installations();
69573
69621
  init_resolve();
69574
69622
  });
@@ -69640,9 +69688,9 @@ var init_env_secret_ref = __esm(() => {
69640
69688
  });
69641
69689
 
69642
69690
  // src/core/secret-value.ts
69643
- import fs48 from "fs";
69691
+ import fs47 from "fs";
69644
69692
  function readValue(secretPath) {
69645
- return fs48.readFileSync(secretPath, "utf8").trim();
69693
+ return fs47.readFileSync(secretPath, "utf8").trim();
69646
69694
  }
69647
69695
  var init_secret_value = () => {};
69648
69696
 
@@ -72843,7 +72891,7 @@ init_secret_seam();
72843
72891
 
72844
72892
  // scripts/akm-migrate/migrate/dead-residue.ts
72845
72893
  init_paths();
72846
- import fs49 from "fs";
72894
+ import fs48 from "fs";
72847
72895
  import path55 from "path";
72848
72896
  var DEAD_RESIDUE_PATHS = [
72849
72897
  { name: "proposals", reason: "superseded by the `proposals` table in $DATA/state.db (0.9.0)" },
@@ -72861,7 +72909,7 @@ function dirSizeBytes(target) {
72861
72909
  let total = 0;
72862
72910
  let entries;
72863
72911
  try {
72864
- entries = fs49.readdirSync(target, { withFileTypes: true });
72912
+ entries = fs48.readdirSync(target, { withFileTypes: true });
72865
72913
  } catch {
72866
72914
  return 0;
72867
72915
  }
@@ -72871,14 +72919,14 @@ function dirSizeBytes(target) {
72871
72919
  total += dirSizeBytes(entryPath);
72872
72920
  } else if (entry.isFile()) {
72873
72921
  try {
72874
- total += fs49.statSync(entryPath).size;
72922
+ total += fs48.statSync(entryPath).size;
72875
72923
  } catch {}
72876
72924
  }
72877
72925
  }
72878
72926
  return total;
72879
72927
  }
72880
72928
  function sizeOf(target) {
72881
- const st2 = fs49.statSync(target);
72929
+ const st2 = fs48.statSync(target);
72882
72930
  return st2.isDirectory() ? dirSizeBytes(target) : st2.size;
72883
72931
  }
72884
72932
  function hostResidue() {
@@ -72897,7 +72945,7 @@ function hostResidue() {
72897
72945
  const found = [];
72898
72946
  const claimed = new Set;
72899
72947
  for (const entry of named) {
72900
- if (claimed.has(entry.absolutePath) || !fs49.existsSync(entry.absolutePath))
72948
+ if (claimed.has(entry.absolutePath) || !fs48.existsSync(entry.absolutePath))
72901
72949
  continue;
72902
72950
  try {
72903
72951
  found.push({ ...entry, relativePath: entry.absolutePath, sizeBytes: sizeOf(entry.absolutePath) });
@@ -72921,7 +72969,7 @@ function hostResidue() {
72921
72969
  function findSidecars(root2, depth, skip) {
72922
72970
  let entries;
72923
72971
  try {
72924
- entries = fs49.readdirSync(root2, { withFileTypes: true });
72972
+ entries = fs48.readdirSync(root2, { withFileTypes: true });
72925
72973
  } catch {
72926
72974
  return [];
72927
72975
  }
@@ -72943,7 +72991,7 @@ function findDeadResidueEntries(stashDir) {
72943
72991
  const akmDir = path55.join(stashDir, ".akm");
72944
72992
  let names;
72945
72993
  try {
72946
- names = fs49.readdirSync(akmDir);
72994
+ names = fs48.readdirSync(akmDir);
72947
72995
  } catch {
72948
72996
  return host;
72949
72997
  }
@@ -72969,7 +73017,7 @@ function removeDeadResidue(stashDir) {
72969
73017
  const entries = findDeadResidueEntries(stashDir);
72970
73018
  return entries.map((entry) => {
72971
73019
  try {
72972
- fs49.rmSync(entry.absolutePath, { recursive: true, force: true });
73020
+ fs48.rmSync(entry.absolutePath, { recursive: true, force: true });
72973
73021
  return { relativePath: entry.relativePath, sizeBytes: entry.sizeBytes, removed: true };
72974
73022
  } catch (error62) {
72975
73023
  return {
@@ -72999,7 +73047,7 @@ init_errors();
72999
73047
  init_write_source();
73000
73048
  init_search_source();
73001
73049
  init_lockfile();
73002
- import fs50 from "fs";
73050
+ import fs49 from "fs";
73003
73051
  import os10 from "os";
73004
73052
  import path56 from "path";
73005
73053
  function expandTilde(value) {
@@ -73011,7 +73059,7 @@ function expandTilde(value) {
73011
73059
  }
73012
73060
  function existingDirectory(target) {
73013
73061
  try {
73014
- return fs50.statSync(target).isDirectory();
73062
+ return fs49.statSync(target).isDirectory();
73015
73063
  } catch (cause) {
73016
73064
  if (cause.code === "ENOENT")
73017
73065
  return false;
@@ -73262,14 +73310,14 @@ function planEngineKeys(inputs, resolve) {
73262
73310
 
73263
73311
  // scripts/akm-migrate/migrate/engine-key-files.ts
73264
73312
  init_walker();
73265
- import fs52 from "fs";
73313
+ import fs51 from "fs";
73266
73314
  import path59 from "path";
73267
73315
 
73268
73316
  // scripts/akm-migrate/migrate/task-files.ts
73269
73317
  init_errors();
73270
73318
  init_task_source_v4();
73271
73319
  import crypto5 from "crypto";
73272
- import fs51 from "fs";
73320
+ import fs50 from "fs";
73273
73321
  import path58 from "path";
73274
73322
 
73275
73323
  // scripts/akm-migrate/migrate/task-to-v4.ts
@@ -74327,14 +74375,14 @@ function contained(root2, candidate) {
74327
74375
  return relative === "" || !relative.startsWith("..") && !path58.isAbsolute(relative);
74328
74376
  }
74329
74377
  function realDirectory(filePath) {
74330
- const stat = fs51.lstatSync(filePath);
74378
+ const stat = fs50.lstatSync(filePath);
74331
74379
  if (stat.isSymbolicLink() || !stat.isDirectory())
74332
74380
  throw migrationError(`${filePath} must be a real directory.`);
74333
- return fs51.realpathSync(filePath);
74381
+ return fs50.realpathSync(filePath);
74334
74382
  }
74335
74383
  function isWritable(filePath) {
74336
74384
  try {
74337
- fs51.accessSync(filePath, fs51.constants.W_OK);
74385
+ fs50.accessSync(filePath, fs50.constants.W_OK);
74338
74386
  return true;
74339
74387
  } catch {
74340
74388
  return false;
@@ -74347,11 +74395,11 @@ function walkRootFiles(root2, directory, extension, onLink, visit3) {
74347
74395
  throw migrationError(`${root2.root} resolves outside bundle ${root2.bundleId}.`);
74348
74396
  }
74349
74397
  const walk = (current) => {
74350
- const physicalDirectory = fs51.realpathSync(current);
74398
+ const physicalDirectory = fs50.realpathSync(current);
74351
74399
  if (!contained(physicalRoot, physicalDirectory)) {
74352
74400
  throw migrationError(`${current} resolves outside bundle ${root2.bundleId}.`);
74353
74401
  }
74354
- for (const entry of fs51.readdirSync(current, { withFileTypes: true }).sort((a3, b) => a3.name.localeCompare(b.name))) {
74402
+ for (const entry of fs50.readdirSync(current, { withFileTypes: true }).sort((a3, b) => a3.name.localeCompare(b.name))) {
74355
74403
  const candidate = path58.join(current, entry.name);
74356
74404
  if (entry.isSymbolicLink()) {
74357
74405
  onLink(candidate);
@@ -74371,11 +74419,11 @@ function walkTasks(root2, tasksDir, out) {
74371
74419
  walkRootFiles(root2, tasksDir, ".yml", (link) => {
74372
74420
  throw migrationError(`task migration does not follow symbolic link ${link}.`);
74373
74421
  }, (candidate, directory) => {
74374
- const stat = fs51.lstatSync(candidate);
74422
+ const stat = fs50.lstatSync(candidate);
74375
74423
  const mode = stat.mode & 511;
74376
74424
  out.push({
74377
74425
  filePath: candidate,
74378
- bytes: fs51.readFileSync(candidate),
74426
+ bytes: fs50.readFileSync(candidate),
74379
74427
  mode,
74380
74428
  writable: root2.writable,
74381
74429
  onDiskWritable: isWritable(candidate) && isWritable(directory) && (mode & 146) !== 0
@@ -74387,7 +74435,7 @@ function inspectTaskFiles(roots) {
74387
74435
  for (const root2 of [...roots].sort((a3, b) => a3.bundleId.localeCompare(b.bundleId))) {
74388
74436
  const tasksDir = root2.layout === "akm-task" ? root2.root : path58.join(root2.root, "tasks");
74389
74437
  try {
74390
- const stat = fs51.lstatSync(tasksDir);
74438
+ const stat = fs50.lstatSync(tasksDir);
74391
74439
  if (stat.isSymbolicLink())
74392
74440
  throw migrationError(`task migration does not follow symbolic link ${tasksDir}.`);
74393
74441
  if (!stat.isDirectory())
@@ -74412,11 +74460,11 @@ function fsyncDirectory(directory) {
74412
74460
  if (process.platform === "win32")
74413
74461
  return;
74414
74462
  try {
74415
- const fd = fs51.openSync(directory, "r");
74463
+ const fd = fs50.openSync(directory, "r");
74416
74464
  try {
74417
- fs51.fsyncSync(fd);
74465
+ fs50.fsyncSync(fd);
74418
74466
  } finally {
74419
- fs51.closeSync(fd);
74467
+ fs50.closeSync(fd);
74420
74468
  }
74421
74469
  } catch (cause) {
74422
74470
  const code = cause.code;
@@ -74425,30 +74473,30 @@ function fsyncDirectory(directory) {
74425
74473
  }
74426
74474
  }
74427
74475
  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);
74476
+ fs50.mkdirSync(path58.dirname(filePath), { recursive: true });
74477
+ const fd = fs50.openSync(filePath, exclusive ? "wx" : "w", mode);
74430
74478
  try {
74431
- fs51.writeFileSync(fd, bytes);
74432
- fs51.fsyncSync(fd);
74479
+ fs50.writeFileSync(fd, bytes);
74480
+ fs50.fsyncSync(fd);
74433
74481
  } finally {
74434
- fs51.closeSync(fd);
74482
+ fs50.closeSync(fd);
74435
74483
  }
74436
- fs51.chmodSync(filePath, mode);
74484
+ fs50.chmodSync(filePath, mode);
74437
74485
  fsyncDirectory(path58.dirname(filePath));
74438
74486
  }
74439
74487
  function replaceAtomically(filePath, bytes, mode) {
74440
74488
  const temporary = path58.join(path58.dirname(filePath), `.${path58.basename(filePath)}.migrate-${crypto5.randomUUID()}`);
74441
74489
  try {
74442
74490
  writeDurable(temporary, bytes, mode, true);
74443
- fs51.renameSync(temporary, filePath);
74491
+ fs50.renameSync(temporary, filePath);
74444
74492
  fsyncDirectory(path58.dirname(filePath));
74445
74493
  } finally {
74446
- fs51.rmSync(temporary, { force: true });
74494
+ fs50.rmSync(temporary, { force: true });
74447
74495
  }
74448
74496
  }
74449
74497
  function holds(filePath, bytes) {
74450
74498
  try {
74451
- return fs51.readFileSync(filePath).equals(bytes);
74499
+ return fs50.readFileSync(filePath).equals(bytes);
74452
74500
  } catch {
74453
74501
  return false;
74454
74502
  }
@@ -74468,7 +74516,7 @@ function replaceFilesWithBackups(changes, backupRoot) {
74468
74516
  try {
74469
74517
  for (const change of backedUp) {
74470
74518
  if (!holds(change.filePath, change.before)) {
74471
- fs51.rmSync(taskFileBackupPath(backupRoot, change.filePath), { force: true });
74519
+ fs50.rmSync(taskFileBackupPath(backupRoot, change.filePath), { force: true });
74472
74520
  conflicts.push(change.filePath);
74473
74521
  continue;
74474
74522
  }
@@ -74479,7 +74527,7 @@ function replaceFilesWithBackups(changes, backupRoot) {
74479
74527
  const unrestored = [];
74480
74528
  for (const change of [...replaced].reverse()) {
74481
74529
  if (holds(change.filePath, change.after)) {
74482
- replaceAtomically(change.filePath, fs51.readFileSync(taskFileBackupPath(backupRoot, change.filePath)), change.mode);
74530
+ replaceAtomically(change.filePath, fs50.readFileSync(taskFileBackupPath(backupRoot, change.filePath)), change.mode);
74483
74531
  } else {
74484
74532
  unrestored.push(change.filePath);
74485
74533
  }
@@ -74525,7 +74573,7 @@ var LAYOUTS = new Map([
74525
74573
  function collect(root2, directory, role, extension, out) {
74526
74574
  let top;
74527
74575
  try {
74528
- top = fs52.lstatSync(directory);
74576
+ top = fs51.lstatSync(directory);
74529
74577
  } catch (cause) {
74530
74578
  if (cause.code === "ENOENT")
74531
74579
  return;
@@ -74538,8 +74586,8 @@ function collect(root2, directory, role, extension, out) {
74538
74586
  return;
74539
74587
  out.set(link, {
74540
74588
  filePath: link,
74541
- bytes: fs52.readFileSync(link),
74542
- mode: fs52.statSync(link).mode & 511,
74589
+ bytes: fs51.readFileSync(link),
74590
+ mode: fs51.statSync(link).mode & 511,
74543
74591
  role,
74544
74592
  writable: root2.writable,
74545
74593
  link: true
@@ -74549,8 +74597,8 @@ function collect(root2, directory, role, extension, out) {
74549
74597
  return;
74550
74598
  out.set(candidate, {
74551
74599
  filePath: candidate,
74552
- bytes: fs52.readFileSync(candidate),
74553
- mode: fs52.lstatSync(candidate).mode & 511,
74600
+ bytes: fs51.readFileSync(candidate),
74601
+ mode: fs51.lstatSync(candidate).mode & 511,
74554
74602
  role,
74555
74603
  writable: root2.writable
74556
74604
  });
@@ -74683,7 +74731,7 @@ init_paths();
74683
74731
  init_walker();
74684
74732
  import { randomUUID as randomUUID4 } from "crypto";
74685
74733
  import { spawnSync as spawnSync6 } from "child_process";
74686
- import fs53 from "fs";
74734
+ import fs52 from "fs";
74687
74735
  import path61 from "path";
74688
74736
 
74689
74737
  // scripts/akm-migrate/migrate/content-ref-planner.ts
@@ -74747,7 +74795,7 @@ function contentRefRewriter(bundles) {
74747
74795
  // scripts/akm-migrate/content-ref-migrate.ts
74748
74796
  var TEXT_EXTENSIONS = new Set([".md", ".yml", ".yaml", ".sh", ".ts", ".js", ".json", ".txt", ".py", ".mjs", ".jsonc", ".toml", ""]);
74749
74797
  function textFiles(root2) {
74750
- return walkStashFlat(root2).filter((file2) => TEXT_EXTENSIONS.has(file2.ext) && fs53.lstatSync(file2.absPath).isFile()).map((file2) => file2.absPath);
74798
+ return walkStashFlat(root2).filter((file2) => TEXT_EXTENSIONS.has(file2.ext) && fs52.lstatSync(file2.absPath).isFile()).map((file2) => file2.absPath);
74751
74799
  }
74752
74800
  function bundleDocuments(roots) {
74753
74801
  const bundles = new Map;
@@ -74783,7 +74831,7 @@ function gitReconcile(filePaths, backupPath) {
74783
74831
  const topOf = new Map;
74784
74832
  const byRoot = new Map;
74785
74833
  for (const filePath of filePaths) {
74786
- const real = fs53.realpathSync(filePath);
74834
+ const real = fs52.realpathSync(filePath);
74787
74835
  const dir = path61.dirname(real);
74788
74836
  if (!topOf.has(dir)) {
74789
74837
  const top = spawnSync6("git", ["-C", dir, "rev-parse", "--show-toplevel"], { encoding: "utf8", env });
@@ -74812,7 +74860,7 @@ function plan2() {
74812
74860
  if (seen.has(filePath) || !(documents.files.has(filePath) || isStructuralFile(root2.root, adapterId, filePath, assetDirs)))
74813
74861
  continue;
74814
74862
  seen.add(filePath);
74815
- const before = fs53.readFileSync(filePath);
74863
+ const before = fs52.readFileSync(filePath);
74816
74864
  const text2 = before.toString("utf8");
74817
74865
  if (!Buffer.from(text2, "utf8").equals(before))
74818
74866
  continue;
@@ -74820,7 +74868,7 @@ function plan2() {
74820
74868
  if (count === 0)
74821
74869
  continue;
74822
74870
  files.push({
74823
- replacement: { filePath, before, after: Buffer.from(rewritten, "utf8"), mode: fs53.statSync(filePath).mode & 511 },
74871
+ replacement: { filePath, before, after: Buffer.from(rewritten, "utf8"), mode: fs52.statSync(filePath).mode & 511 },
74824
74872
  refs: count
74825
74873
  });
74826
74874
  }
@@ -74876,7 +74924,7 @@ init_config_io();
74876
74924
  init_errors();
74877
74925
  init_paths();
74878
74926
  import { randomUUID as randomUUID5 } from "crypto";
74879
- import fs54 from "fs";
74927
+ import fs53 from "fs";
74880
74928
  import path62 from "path";
74881
74929
  function taskRoots(config2) {
74882
74930
  return bundleRoots(config2).flatMap((root2) => {
@@ -74888,7 +74936,7 @@ function taskRoot(candidate) {
74888
74936
  const { bundleId, bundleRoot, root: root2, writable } = candidate;
74889
74937
  const adapter = candidate.adapter ?? detectAdapterId(root2, "");
74890
74938
  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();
74939
+ const flatTasks = fs53.readdirSync(root2, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".yml")).map((entry) => entry.name).sort();
74892
74940
  if (flatTasks.length > 0) {
74893
74941
  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
74942
  }
@@ -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;
@@ -40,52 +40,45 @@ const nodeRequire = createRequire(import.meta.url);
40
40
  * Open a SQLite database handle at `path` on the current runtime's driver
41
41
  * (`bun:sqlite` on Bun, `better-sqlite3` on Node). Returns a handle conforming
42
42
  * to the structural {@link Database} type.
43
+ *
44
+ * On Bun, `close()` means CLOSED. bun:sqlite's own `close()` is a
45
+ * `sqlite3_close_v2`: while any `prepare()` statement is unfinalized the
46
+ * connection survives as a zombie, holding the file, its WAL and its
47
+ * shared memory, until GC finalizes the statements. When GC finally closes it,
48
+ * the last-connection checkpoint writes that WAL into whatever file now sits at
49
+ * the path, a restored or replaced copy included. It also kept a later
50
+ * connection from leaving WAL mode (issue #720). So the handle finalizes every
51
+ * statement it prepared that is still alive before the real close. Statements
52
+ * are held weakly, so a per-row `prepare()` is not kept alive until close.
53
+ * better-sqlite3's `close()` already closes the connection outright.
43
54
  */
44
55
  export function openDatabase(path, opts) {
45
- return isBun ? openBunDatabase(path, opts) : openNodeDatabase(path, opts);
56
+ return isBun ? finalizeOnClose(openBunDatabase(path, opts)) : openNodeDatabase(path, opts);
46
57
  }
47
- /**
48
- * {@link openDatabase} with a finalize-on-close guard (issue #720).
49
- *
50
- * bun:sqlite's `Database.close()` is a `sqlite3_close_v2`: with any UNFINALIZED
51
- * `prepare()` statement outstanding, the underlying connection — and its WAL
52
- * shared-memory mapping — survives as a zombie until GC finalizes the
53
- * statements. A later connection in the same process then cannot leave WAL
54
- * mode (`PRAGMA journal_mode = DELETE` → "database is locked"), which is
55
- * exactly what silently defeated the migrate-apply single-file conversion.
56
- * (`db.query()` statements are Database-cached and immune; `prepare()` is the
57
- * dominant idiom in the migration helpers.)
58
- *
59
- * This variant tracks `prepare()` results and finalizes them (idempotently)
60
- * before the real `close()`, so close always means CLOSED. It is deliberately
61
- * OPT-IN for the migrate-apply flow's short-lived helper connections and the
62
- * migration test fixtures — NOT the global default: long-lived/hot paths cache
63
- * prepared statements per connection (e.g. the entries upsert WeakMap) and
64
- * worker flows may still be stepping a statement when a sibling close lands;
65
- * force-finalizing under them changes behavior they were built on.
66
- */
67
- export function openDatabaseFinalizing(path, opts) {
68
- const db = openDatabase(path, opts);
69
- const tracked = new Set();
70
- const origPrepare = db.prepare.bind(db);
71
- const origClose = db.close.bind(db);
72
- db.prepare = ((sql, ...rest) => {
73
- const stmt = origPrepare(sql, ...rest);
74
- tracked.add(stmt);
58
+ function finalizeOnClose(db) {
59
+ const live = new Set();
60
+ const forget = new FinalizationRegistry((ref) => live.delete(ref));
61
+ const prepare = db.prepare.bind(db);
62
+ const close = db.close.bind(db);
63
+ db.prepare = ((sql) => {
64
+ const stmt = prepare(sql);
65
+ const ref = new WeakRef(stmt);
66
+ live.add(ref);
67
+ forget.register(stmt, ref);
75
68
  return stmt;
76
69
  });
77
- db.close = ((...args) => {
78
- for (const stmt of tracked) {
70
+ db.close = () => {
71
+ for (const ref of live) {
79
72
  try {
80
- stmt.finalize?.();
73
+ ref.deref()?.finalize?.();
81
74
  }
82
75
  catch {
83
- // Already finalized (double-finalize is the idempotent no-op case).
76
+ // Already finalized by its owner.
84
77
  }
85
78
  }
86
- tracked.clear();
87
- return origClose(...args);
88
- });
79
+ live.clear();
80
+ close();
81
+ };
89
82
  return db;
90
83
  }
91
84
  function openBunDatabase(path, opts) {