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
package/CHANGELOG.md CHANGED
@@ -6,6 +6,27 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ### Added
10
+
11
+ - AKM Desktop's library map answers four questions about the whole library, one view each: Contents (what is in it, by topic, with the searches that found nothing), Use (what is read and what is dead weight), Problems (what is outdated, disliked or duplicated) and Relations (how its topics link to each other, in 3D or flat). It replaces the point cloud of every asset, which showed none of these. The figures of each view are also in words beside it.
12
+ - `assets.graph` (`akm-cli/workspace`) answers what a library holds, what is used and what overlaps: `topics` (the embedded assets grouped by meaning, each named by its most particular words, with its nearest topics), `nodes.topic`, `duplicates` (pairs of one topic whose embeddings have a cosine of 0.96 or more), and per asset `lastShownAt`, `modifiedAt` and the feedback counts `positive` and `negative`.
13
+
14
+ ### Fixed
15
+
16
+ - An `index.db` whose `entries` table exists without its full-text table made `akm search` and `akm curate` exit 70 while `akm health` passed. Such an index now counts as unusable: reads report it and `akm index` rebuilds it, and health fails it.
17
+ - `akm feedback` accepted spellings `akm show` refuses (`tasks/x.md`, `skills/x.md`, `scripts/x.sh.md`, `env/x.md`, `secrets/x.md`), and echoed the typed spelling as `ref` (`knowledge\x`, `akm//knowledge/x.md`). It now accepts the spellings `show` accepts, and `ref` is the ref `show` returns. The `.md` toggle in an index lookup applies only to markdown files.
18
+ - A lock left by a killed process was never reclaimed once its PID was alive again, for example PID 1 in a container: `akm index` waited ten minutes and exited 75, `--skip-if-locked` runs skipped forever, and reads said the index was being built. The index rebuild lock, `akm improve`'s run lock, the asset mutation lease and the other lock files now record the holder's boot id and process start time (Linux) and treat a live PID with a different identity as stale; a lock naming this process that it did not acquire is stale too. Lock files without those fields are read as before.
19
+ - `akm bundle update --skip-if-locked` waited up to ten minutes for a running index build instead of skipping. It now returns at once with exit 0 and a skipped result.
20
+ - A damaged `index.db` (a bad header, `file is not a database`, or a bad interior page) is rebuilt by `akm index`: the build deletes the file and builds again once, wherever it finds the damage. Search and curate report "no search index; run `akm index`" and `feedback` reports no usable index, instead of exiting 70.
21
+ - `akm health` no longer passes an `index.db` that has a damaged page, and during a first build it reports the build instead of failing and advising to move `index.db` aside.
22
+ - Opening or migrating `index.db` is one transaction, so a reader or a crash can no longer meet entries without their full-text table (search and curate exited 70).
23
+ - `akm show <ref>#<fragment>` against an index laid out by 0.9.13 or earlier exited 70 (`no such table: entry_fragments`); it reports the fragment unavailable like any index that cannot supply it.
24
+ - `akm search … | head` and `akm index 2>&1 | head -1` exited 70 ("Unhandled rejection: EPIPE") once the reader closed the pipe. A closed stdout or stderr no longer fails the command: it runs to completion (an index build finishes) and exits with the code its work earned, normally 0.
25
+ - A library reached through two path spellings (a symlink and its target, macOS `/tmp` and `/private/tmp`) was a different library to the index: reads said "no search index", and every build through the other spelling re-minted every entry id. A source's path is now its real path, and the library directory is compared by real path, so an index that stored the other spelling still serves.
26
+ - `akm setup --embedding-endpoint https://host/v1/models` stored `https://host/v1/models/v1`, and `…/V1` became `…/V1/v1`. An endpoint typed with `/models`, `/completions`, `/embeddings` or `/chat/completions` (any case) now names its base, and `/V1` counts as the `/v1` root.
27
+ - The Desktop workspace API (`assets.show`, `assets.related`, `documents.readSource`, the graph) threw `no such table: entries` or `file is not a database` on a first-build, zero-filled or garbage `index.db`; they now treat an index that cannot serve as no index, so `assets.show` answers from the file with `durableRef: null`.
28
+ - A garbage, zero-filled or truncated `state.db` now raises one error, exit 78 naming the file, from every verb except `health`: `feedback` and `index` no longer exit 70, `akm health` reports it as one failing finding (exit 1) for every kind of damage, `akm log` / `akm doctor log` no longer return zero events at exit 0, and workspace readers no longer throw a raw SQLite error.
29
+
9
30
  ## [0.10.261124] - 2026-11-14
10
31
 
11
32
  ### Fixed
package/dist/cli.js CHANGED
@@ -32,7 +32,14 @@
32
32
  // and lazy `import()` failures are the typical sources. Registered before
33
33
  // any other top-level work so the startup IIFE banner and the stale-DB
34
34
  // cleanup are also covered.
35
+ // A reader that closed early (`akm search … | head`) is not a failure of the work: the command keeps
36
+ // running, its remaining output goes nowhere, and the process ends with the code the work earned.
37
+ // Only our own stdio is forgiven: an EPIPE from a socket (an embedding or LLM call) is still a failure.
38
+ const stdioStreams = [process.stdout, process.stderr];
39
+ const stdioReaderGone = trackStdioReaderGone(stdioStreams);
35
40
  process.on("unhandledRejection", (reason) => {
41
+ if (stdioReaderGone.explains(reason))
42
+ return;
36
43
  const err = reason instanceof Error ? reason : new Error(String(reason));
37
44
  console.error(JSON.stringify({
38
45
  ok: false,
@@ -45,6 +52,8 @@ process.on("unhandledRejection", (reason) => {
45
52
  process.exit(EXIT_CODES.INTERNAL);
46
53
  });
47
54
  process.on("uncaughtException", (err) => {
55
+ if (stdioReaderGone.explains(err))
56
+ return;
48
57
  console.error(JSON.stringify({
49
58
  ok: false,
50
59
  error: `Uncaught exception: ${err.message}`,
@@ -74,6 +83,7 @@ import { akmHealth } from "./commands/health.js";
74
83
  import { doctorMetricsCommand } from "./commands/metrics/usage-cli.js";
75
84
  import { akmTasksDoctor } from "./commands/tasks/tasks.js";
76
85
  import { closestMatch } from "./core/closest-match.js";
86
+ import { trackStdioReaderGone } from "./core/stdio-reader-gone.js";
77
87
  import "./commands/health/renderers.js";
78
88
  import "./commands/metrics/md-report.js";
79
89
  import { parseWindowSpec } from "./commands/health/windows.js";
@@ -9,6 +9,7 @@ import { defineJsonCommand, output, parseAllFlagValues } from "../cli/shared.js"
9
9
  import { makeBundleRef, parseBundleRef } from "../core/asset/asset-ref.js";
10
10
  import { assembleAsset, serializeFrontmatter } from "../core/asset/asset-serialize.js";
11
11
  import { parseFrontmatter, parseFrontmatterBlock, spliceFrontmatterLine } from "../core/asset/frontmatter.js";
12
+ import { displayDefaultBundle, displayRef } from "../core/asset/resolve-ref.js";
12
13
  import { isWithin, resolveStashDir, safeRealpath, writeFileAtomic } from "../core/common.js";
13
14
  import { loadConfig } from "../core/config/config.js";
14
15
  import { ConfigError, NotFoundError, TransientError, UsageError } from "../core/errors.js";
@@ -21,10 +22,10 @@ import { NO_INDEX_MESSAGE, openUsableIndex } from "../indexer/index-readiness.js
21
22
  import { heldRebuildLock } from "../indexer/index-rebuild-lock.js";
22
23
  import { recomputeUtilityScores } from "../indexer/indexer.js";
23
24
  import { currentConceptId, resolveWriteAddress } from "../indexer/lookup/adapter-concept-owner.js";
24
- import { resolveSourceEntries } from "../indexer/search/search-source.js";
25
+ import { findSourceForPath, resolveSourceEntries } from "../indexer/search/search-source.js";
25
26
  import { insertUsageEventStrict, resolveUsageEventSource } from "../indexer/usage/usage-events.js";
26
27
  import { resolveSourcesForOrigin } from "../registry/origin-resolve.js";
27
- import { closeDatabase, openExistingDatabase } from "../storage/repositories/index-connection.js";
28
+ import { closeDatabase, indexDbIsDamaged, isCorruptionError, openExistingDatabase, } from "../storage/repositories/index-connection.js";
28
29
  import { findEntryIdByRef, getEntryById, getEntryFilePathById, getItemRefById, } from "../storage/repositories/index-entries-repository.js";
29
30
  import { getUtilityScore } from "../storage/repositories/index-utility-repository.js";
30
31
  import { contentHash } from "./improve/content-hash.js";
@@ -563,6 +564,7 @@ export const feedbackCommand = defineJsonCommand({
563
564
  let countsTowardRanking = false;
564
565
  let rankingSkippedReason;
565
566
  let durableRef = ref;
567
+ let shownRef = ref;
566
568
  let fix;
567
569
  const config = loadConfig();
568
570
  const sources = resolveSourceEntries(undefined, config);
@@ -604,6 +606,8 @@ export const feedbackCommand = defineJsonCommand({
604
606
  throw new UsageError(`Indexed ref "${ref}" has no durable item ref.`, "INVALID_PROPOSAL");
605
607
  durableRef = itemRef;
606
608
  const filePath = getEntryFilePathById(db, entryId);
609
+ const { bundle, conceptId } = parseBundleRef(itemRef);
610
+ shownRef = displayRef({ conceptId, bundleId: bundle }, displayDefaultBundle(config.defaultBundle, filePath ? findSourceForPath(filePath, sources) : undefined, bundle));
607
611
  const entryType = getEntryById(db, entryId)?.entry.type;
608
612
  const textHash = judgedTextHash(entryType, filePath);
609
613
  if (textHash)
@@ -657,6 +661,11 @@ export const feedbackCommand = defineJsonCommand({
657
661
  countsTowardRanking = recordResult.countsTowardRanking;
658
662
  rankingSkippedReason = recordResult.rankingSkippedReason;
659
663
  }
664
+ catch (error) {
665
+ if (isCorruptionError(error) && indexDbIsDamaged())
666
+ throw new UsageError(NO_INDEX_MESSAGE, "MISSING_REQUIRED_ARGUMENT", "akm index");
667
+ throw error;
668
+ }
660
669
  finally {
661
670
  closeDatabase(db);
662
671
  }
@@ -748,7 +757,7 @@ export const feedbackCommand = defineJsonCommand({
748
757
  }
749
758
  output("feedback", {
750
759
  ok: true,
751
- ref,
760
+ ref: shownRef,
752
761
  signal,
753
762
  reason: reason?.trim() ?? null,
754
763
  tags: validatedTags,
@@ -9,19 +9,25 @@
9
9
  * search used to obey); it reports what the index says.
10
10
  */
11
11
  import { getDbPath } from "../../core/paths.js";
12
+ import { heldRebuildLock } from "../../indexer/index-rebuild-lock.js";
12
13
  import { SEMANTIC_SEARCH_META_KEY } from "../../indexer/walk/index-context.js";
13
14
  import { LOCAL_EMBEDDING_RUNTIME } from "../../llm/embedders/local.js";
14
- import { closeDatabase, openReadonlyExistingDatabase } from "../../storage/repositories/index-connection.js";
15
+ import { closeDatabase, indexDbIsDamaged, openReadonlyExistingDatabase, } from "../../storage/repositories/index-connection.js";
15
16
  import { getEmbeddableEntryCount } from "../../storage/repositories/index-entries-repository.js";
17
+ import { hasCurrentEntriesTable } from "../../storage/repositories/index-entry-schema.js";
16
18
  import { getMeta } from "../../storage/repositories/index-meta-repository.js";
17
19
  import { getEmbeddingCount } from "../../storage/repositories/index-vec-repository.js";
18
20
  /** Read the last index run's record and the index's counts, read-only. */
19
21
  export function readSemanticSearchState(mode) {
20
22
  try {
23
+ if (indexDbIsDamaged())
24
+ throw new Error("index.db is damaged");
21
25
  const db = openReadonlyExistingDatabase(getDbPath());
22
26
  if (!db)
23
27
  return { mode };
24
28
  try {
29
+ if (!hasCurrentEntriesTable(db))
30
+ throw new Error("index.db has no searchable entries table");
25
31
  const raw = getMeta(db, SEMANTIC_SEARCH_META_KEY);
26
32
  return {
27
33
  mode,
@@ -38,6 +44,8 @@ export function readSemanticSearchState(mode) {
38
44
  }
39
45
  }
40
46
  catch (error) {
47
+ if (heldRebuildLock())
48
+ return { mode, building: true };
41
49
  return { mode, error: error instanceof Error ? error.message : String(error) };
42
50
  }
43
51
  }
@@ -52,7 +60,9 @@ export function semanticSearchCheck(state) {
52
60
  });
53
61
  // Keyword search needs a readable index too, even when embeddings are off.
54
62
  if (state.error)
55
- return result("fail", `Could not read the index: ${state.error}. Repair or move aside index.db, then run \`akm index\`.`);
63
+ return result("fail", `Could not read the index: ${state.error}. Run \`akm index\`; it rebuilds a damaged index.db.`);
64
+ if (state.building)
65
+ return result("unknown", "The search index is being built; check again when the build finishes.");
56
66
  if (state.mode === "off")
57
67
  return result("pass", "Semantic search is off (semanticSearchMode: off).", { mode: "off" });
58
68
  const index = state.index;
@@ -8,7 +8,7 @@ import { loadConfig } from "../core/config/config.js";
8
8
  import { ConfigError, rethrowIfTestIsolationError, UsageError } from "../core/errors.js";
9
9
  import { classifyPathAccess, describeInaccessiblePath } from "../core/path-access.js";
10
10
  import { getConfigPath, getDataDir, getDbPath, getStateDbPathInDataDir } from "../core/paths.js";
11
- import { listExistingTableNames, listPendingStateMigrations, openStateDatabaseWithReport, withStateDb, } from "../core/state-db.js";
11
+ import { classifyStateDbError, isStateDbCorruption, listExistingTableNames, listPendingStateMigrations, openStateDatabaseWithReport, withStateDb, } from "../core/state-db.js";
12
12
  import { DURATION_UNITS, parseDuration, parseSinceToIso } from "../core/time.js";
13
13
  import { resolveSourceEntries } from "../indexer/search/search-source.js";
14
14
  import { probeLlmEndpoint } from "../llm/client.js";
@@ -556,22 +556,16 @@ function degradedStateDbReport(hardCheck, options) {
556
556
  improve: emptyImproveMetrics(),
557
557
  };
558
558
  }
559
- /** SQLite refused the file: garbage, a truncated copy, or a non-database file left where state.db belongs. */
560
- function isNotADatabase(error) {
561
- return (error?.code === "SQLITE_NOTADB" ||
562
- /not a database/i.test(error instanceof Error ? error.message : String(error)));
563
- }
564
- function corruptStateDbCheck(stateDbPath, detail) {
559
+ /** The one failing finding for a damaged state.db, worded by the same classified error every other verb raises. */
560
+ function corruptStateDbCheck(stateDbPath, error) {
561
+ const damaged = classifyStateDbError(error, stateDbPath);
565
562
  return {
566
563
  name: "state-db-readable",
567
564
  kind: "deterministic",
568
565
  status: "fail",
569
566
  confidence: "high",
570
- message: `state.db at ${stateDbPath} is not a SQLite database (${detail}). Every other health check is skipped because ` +
571
- 'none of them can read it. Repair: back up state.db, run `sqlite3 -readonly state.db ".recover" | sqlite3 state.new.db`, ' +
572
- "stop every akm process, delete state.db-wal and state.db-shm, then swap state.new.db in as state.db; if nothing " +
573
- "can be recovered, move state.db aside and the next akm command creates a new one.",
574
- evidence: { path: stateDbPath, detail },
567
+ message: `${damaged.message} ${damaged.hint()} Every other health check is skipped because none of them can read it.`,
568
+ evidence: { path: stateDbPath, detail: damaged.message },
575
569
  };
576
570
  }
577
571
  function unreadableStateDbCheck(detail) {
@@ -639,9 +633,8 @@ export async function akmHealth(options = {}) {
639
633
  if (access === "inaccessible") {
640
634
  return degradedStateDbReport(unreadableStateDbCheck(describeInaccessiblePath(stateDbPath, code)), options);
641
635
  }
642
- if (isNotADatabase(error)) {
643
- return degradedStateDbReport(corruptStateDbCheck(stateDbPath, error instanceof Error ? error.message : String(error)), options);
644
- }
636
+ if (isStateDbCorruption(error))
637
+ return degradedStateDbReport(corruptStateDbCheck(stateDbPath, error), options);
645
638
  // A migration that failed to apply rolled back and is still pending:
646
639
  // name it from a read-only listing (which never applies anything) rather
647
640
  // than pattern-matching the error text. A ledger too broken to enumerate
@@ -11,7 +11,7 @@ import { stashDirFor } from "../../core/asset/asset-placement.js";
11
11
  import { parseFrontmatter } from "../../core/asset/frontmatter.js";
12
12
  import { conceptIdForStashFile, displayRefForConceptId } from "../../core/asset/resolve-ref.js";
13
13
  import { deriveBundleIds } from "../../core/bundle-id.js";
14
- import { compareCodePoints, isAkmRegistryCachePath, resolveStashDir } from "../../core/common.js";
14
+ import { compareCodePoints, isAkmRegistryCachePath, resolveStashDir, safeRealpath, samePath } from "../../core/common.js";
15
15
  import { loadConfig, primaryBundlePath } from "../../core/config/config.js";
16
16
  import { UsageError } from "../../core/errors.js";
17
17
  import { warn } from "../../core/warn.js";
@@ -268,7 +268,7 @@ async function lintViaAdapter(adapterId, stashRoot, extraStashRoots, sources, cf
268
268
  op: "update",
269
269
  }));
270
270
  const ids = deriveBundleIds(sources);
271
- const sourceIndex = sources.findIndex((s) => path.resolve(s.path) === path.resolve(stashRoot));
271
+ const sourceIndex = sources.findIndex((s) => samePath(s.path, stashRoot));
272
272
  const componentId = sourceIndex >= 0 ? ids[sourceIndex] : stashRoot;
273
273
  const ctx = createValidateContext({ root: stashRoot, extraRoots: extraStashRoots });
274
274
  const diagnostics = await adapter.validate({ id: componentId, adapter: adapterId, root: stashRoot, writable: true }, changes, ctx);
@@ -340,9 +340,9 @@ function collectEnvFiles(dir) {
340
340
  function runEnvDangerousKeyPass(stashRoot, extraStashRoots, sources, cfg) {
341
341
  const flagged = [];
342
342
  const envRoots = [stashRoot, ...extraStashRoots];
343
- const bundleIdByRoot = new Map(sources.map((source) => [path.resolve(source.path), source.registryId]));
343
+ const bundleIdByRoot = new Map(sources.map((source) => [safeRealpath(source.path), source.registryId]));
344
344
  for (const root of envRoots) {
345
- const bundleId = bundleIdByRoot.get(path.resolve(root));
345
+ const bundleId = bundleIdByRoot.get(safeRealpath(root));
346
346
  // `env` assets live under `env/`, whole-file `secret` assets under
347
347
  // `secrets/`. `displayRefForConceptId` owns the short-default /
348
348
  // qualified-secondary `Ref:` spelling `akm show` emits — the old
@@ -379,7 +379,7 @@ function runEnvDangerousKeyPass(stashRoot, extraStashRoots, sources, cfg) {
379
379
  * policy and stays fixable, exactly as today.
380
380
  */
381
381
  function assertFixTargetWritable(stashRoot, sources) {
382
- const target = sources.find((source) => path.resolve(source.path) === path.resolve(stashRoot));
382
+ const target = sources.find((source) => samePath(source.path, stashRoot));
383
383
  if (target?.writable !== false)
384
384
  return;
385
385
  // Same error kind and code `write-source.ts#ensureWritable` raises for the
@@ -848,7 +848,7 @@ export async function akmLint(options = {}) {
848
848
  // The primary stash is the defaultBundle's path.
849
849
  const stashRoot = options.dir ?? primaryBundlePath(cfg) ?? resolveStashDir();
850
850
  const sources = resolveSourceEntries(stashRoot, cfg);
851
- const configuredAdapter = sources.find((source) => path.resolve(source.path) === path.resolve(stashRoot))?.adapterId;
851
+ const configuredAdapter = sources.find((source) => samePath(source.path, stashRoot))?.adapterId;
852
852
  const adapterId = configuredAdapter ?? detectAdapterId(stashRoot);
853
853
  const extraStashRoots = sources.map((s) => s.path).filter((p) => p !== stashRoot && fs.existsSync(p));
854
854
  if (adapterId !== "akm")
@@ -19,7 +19,7 @@ import { assetPathForName, stashDirFor } from "../../core/asset/asset-placement.
19
19
  import { assembleAsset } from "../../core/asset/asset-serialize.js";
20
20
  import { parseFrontmatter } from "../../core/asset/frontmatter.js";
21
21
  import { conceptIdFromTypeName, parsePlacementRef } from "../../core/asset/resolve-ref.js";
22
- import { isHttpUrl, isWithin, resolveStashDir, tryReadStdinText } from "../../core/common.js";
22
+ import { isHttpUrl, isWithin, resolveStashDir, safeRealpath, samePath, tryReadStdinText } from "../../core/common.js";
23
23
  import { loadConfig } from "../../core/config/config.js";
24
24
  import { UsageError } from "../../core/errors.js";
25
25
  import { resolveBundleWriteTarget, resolveMutationTarget } from "../../core/mutation-target.js";
@@ -196,7 +196,7 @@ function resolveWriteRefRoots(target, targetFlag) {
196
196
  // No working stash configured — the write target alone.
197
197
  }
198
198
  const mutableRoots = [stashRoot];
199
- if (workingStash && path.resolve(workingStash) !== path.resolve(stashRoot))
199
+ if (workingStash && !samePath(workingStash, stashRoot))
200
200
  mutableRoots.push(workingStash);
201
201
  const namedSources = resolveSourceEntries(undefined, cfg);
202
202
  const installations = deriveInstallations(namedSources);
@@ -204,19 +204,19 @@ function resolveWriteRefRoots(target, targetFlag) {
204
204
  const bundleId = installations[index]?.id;
205
205
  return bundleId ? [[path.resolve(source.path), bundleId]] : [];
206
206
  }));
207
- const otherSources = namedSources.filter((s) => !mutableRoots.some((m) => path.resolve(m) === path.resolve(s.path)) && fs.existsSync(s.path));
207
+ const otherSources = namedSources.filter((s) => !mutableRoots.some((m) => samePath(m, s.path)) && fs.existsSync(s.path));
208
208
  const roots = [
209
209
  ...mutableRoots
210
210
  .filter((p) => fs.existsSync(p))
211
211
  .map((p) => {
212
- const source = namedSources.find((candidate) => path.resolve(candidate.path) === path.resolve(p));
213
- const mutable = path.resolve(p) === path.resolve(stashRoot)
212
+ const source = namedSources.find((candidate) => samePath(candidate.path, p));
213
+ const mutable = samePath(p, stashRoot)
214
214
  ? writeTarget.source.adapterId === "akm"
215
215
  : source?.writable === true && (source.adapterId ?? detectAdapterId(p)) === "akm";
216
216
  return {
217
217
  path: p,
218
218
  source,
219
- bundleId: bundleByPath.get(path.resolve(p)) ?? slugForPath(p),
219
+ bundleId: bundleByPath.get(safeRealpath(p)) ?? slugForPath(p),
220
220
  mutable,
221
221
  };
222
222
  }),
@@ -616,7 +616,7 @@ export async function writeMarkdownAsset(options) {
616
616
  // on a git target, uncommitted (and a re-run hits RESOURCE_ALREADY_EXISTS).
617
617
  // Degrade to the same applied:false report the non-writable path uses.
618
618
  try {
619
- const sameSource = path.resolve(item.stashRoot) === path.resolve(source.path);
619
+ const sameSource = samePath(item.stashRoot, source.path);
620
620
  writeSupersededEdge(item.filePath, durableRef);
621
621
  if (sameSource) {
622
622
  recordWriteTargetPath(source, item.filePath);
@@ -655,7 +655,7 @@ export async function writeMarkdownAsset(options) {
655
655
  const sourceEntries = resolveSourceEntries(undefined, cfg);
656
656
  const sourceInstallations = deriveInstallations(sourceEntries);
657
657
  for (const [root, files] of demotedByRoot) {
658
- const sourceIndex = sourceEntries.findIndex((entry) => path.resolve(entry.path) === path.resolve(root));
658
+ const sourceIndex = sourceEntries.findIndex((entry) => samePath(entry.path, root));
659
659
  await indexWrittenAssets(root, files, { bundleId: sourceInstallations[sourceIndex]?.id });
660
660
  }
661
661
  // Placement hint (stash-organization conventions): CLI writers never receive
@@ -4,9 +4,9 @@
4
4
  import fs from "node:fs";
5
5
  import { parseBundleRef } from "../../core/asset/asset-ref.js";
6
6
  import { loadConfig } from "../../core/config/config.js";
7
+ import { readUsableIndex } from "../../indexer/index-readiness.js";
7
8
  import { applyEntryFilters } from "../../indexer/search/db-search.js";
8
9
  import { resolveSourceEntries } from "../../indexer/search/search-source.js";
9
- import { closeDatabase, openReadonlyExistingDatabase } from "../../storage/repositories/index-connection.js";
10
10
  import { getEntriesByIds, getEntryIdByFilePath, getItemRefById, } from "../../storage/repositories/index-entries-repository.js";
11
11
  import { getMeta } from "../../storage/repositories/index-meta-repository.js";
12
12
  import { getAllEntriesForEmbedding, getNeighborsByEntryId, hasStoredEmbedding, } from "../../storage/repositories/index-vec-repository.js";
@@ -23,10 +23,7 @@ export async function akmRelated(ref, scope = "all") {
23
23
  if (shown.type === "env" || shown.type === "secret")
24
24
  return unavailable("This asset has no comparable indexed content.");
25
25
  const file = shown.path;
26
- const db = openReadonlyExistingDatabase();
27
- if (!db)
28
- return unavailable("No index is available. Build the AKM index to compare stored embeddings.");
29
- try {
26
+ return readUsableIndex((db) => {
30
27
  const id = file ? getEntryIdByFilePath(db, file) : undefined;
31
28
  const bundle = id === undefined ? undefined : parseBundleRef(getItemRefById(db, id) ?? "").bundle;
32
29
  if (id === undefined || !bundle || !hasStoredEmbedding(db, id))
@@ -68,8 +65,5 @@ export async function akmRelated(ref, scope = "all") {
68
65
  matches,
69
66
  note: `Up to ${RELATED_LIMIT} nearest stored embeddings. Scores describe indexed content; refresh the index after external edits.`,
70
67
  };
71
- }
72
- finally {
73
- closeDatabase(db);
74
- }
68
+ }, unavailable("No index is available. Build the AKM index to compare stored embeddings."));
75
69
  }
@@ -24,7 +24,7 @@ import { makeBundleRef, parseBundleRef } from "../../core/asset/asset-ref.js";
24
24
  import { parseFrontmatter } from "../../core/asset/frontmatter.js";
25
25
  import { extractSection, markdownFragmentSlugs, markdownToc } from "../../core/asset/markdown.js";
26
26
  import { buildMarkdownLeadContext, fragmentForSelector, MARKDOWN_FRAGMENT_CONTEXT_DEFAULT_MAX_CHARS, } from "../../core/asset/markdown-fragments.js";
27
- import { displayRef, displayRefForConceptId } from "../../core/asset/resolve-ref.js";
27
+ import { displayDefaultBundle, displayRef, displayRefForConceptId } from "../../core/asset/resolve-ref.js";
28
28
  import { META_DIR, parseMetaRef, readMetaFile } from "../../core/asset/stash-meta.js";
29
29
  import { asNonEmptyString, isContainedResolvedPath } from "../../core/common.js";
30
30
  import { loadConfig } from "../../core/config/config.js";
@@ -281,9 +281,7 @@ export async function showLocal(input) {
281
281
  // Only resolve the indexed-safe revision when the selector itself is opaque,
282
282
  // or when the caller explicitly opts into indexed-safe contextual output.
283
283
  const indexedFragment = !fromFiles && parsed.fragment && (opaqueFragmentSelector || input.contextMode === "lead")
284
- ? withIndexDb((db) => getIndexedMarkdownFragment(db, indexedEntry.itemRef, parsed.fragment), {
285
- readOnly: input.readOnly === true,
286
- })
284
+ ? readIndexedFragment(indexedEntry.itemRef, parsed.fragment, input.readOnly === true)
287
285
  : undefined;
288
286
  const indexedFragmentContent = opaqueFragmentSelector ? indexedFragment?.content : undefined;
289
287
  const indexedRenderer = rendererForIndexedEntry(indexedEntry, fileCtx);
@@ -305,7 +303,7 @@ export async function showLocal(input) {
305
303
  throw new UsageError(`Renderer "${match.renderer}" not found for asset: ${makeBundleRef(parsed.bundle, parsed.conceptId)}`);
306
304
  }
307
305
  const renderBundle = indexedEntry.bundleId;
308
- const renderDefaultBundle = config.defaultBundle ?? (source?.isDefault === true ? renderBundle : undefined);
306
+ const renderDefaultBundle = displayDefaultBundle(config.defaultBundle, source, renderBundle);
309
307
  const renderCtx = buildRenderContext(fileCtx, match, allSourceDirs, renderBundle, renderDefaultBundle);
310
308
  response = renderer.buildShowResponse(renderCtx);
311
309
  markdown = match.renderer.endsWith("-md");
@@ -331,9 +329,8 @@ export async function showLocal(input) {
331
329
  }
332
330
  response.type = indexedEntry.type;
333
331
  response.name = indexedEntry.name;
334
- const isPrimaryStash = source?.isDefault === true;
335
- const displayDefaultBundle = config.defaultBundle ?? (isPrimaryStash ? indexedEntry.bundleId : undefined);
336
- const canonicalRef = displayRef({ conceptId: indexedEntry.conceptId, bundleId: indexedEntry.bundleId }, displayDefaultBundle);
332
+ const defaultBundle = displayDefaultBundle(config.defaultBundle, source, indexedEntry.bundleId);
333
+ const canonicalRef = displayRef({ conceptId: indexedEntry.conceptId, bundleId: indexedEntry.bundleId }, defaultBundle);
337
334
  if (parsed.fragment && indexedFragment) {
338
335
  const selectedFragmentId = indexedFragment.fragments[indexedFragment.ordinal].fragmentId;
339
336
  const selectedRef = `${canonicalRef}#${selectedFragmentId}`;
@@ -397,7 +394,7 @@ export async function showLocal(input) {
397
394
  origin: source?.registryId ?? null,
398
395
  editable,
399
396
  ...(!editable ? { editHint: buildEditHint(canonicalRef) } : {}),
400
- ...(fromFiles ? {} : showLinks(indexedEntry.itemRef, displayDefaultBundle, input.readOnly === true)),
397
+ ...(fromFiles ? {} : showLinks(indexedEntry.itemRef, defaultBundle, input.readOnly === true)),
401
398
  };
402
399
  if (input.detail === "brief") {
403
400
  return buildBriefResponse(fullResponse, assetPath);
@@ -407,6 +404,17 @@ export async function showLocal(input) {
407
404
  }
408
405
  return fullResponse;
409
406
  }
407
+ /** The indexed-safe fragment, or undefined when the index cannot supply it (an older layout without `entry_fragments`). The caller then refuses with "fragment context unavailable; run `akm index`" (exit 1) for a `--lead` or opaque fragment selector. */
408
+ function readIndexedFragment(itemRef, fragment, readOnly) {
409
+ try {
410
+ return withIndexDb((db) => getIndexedMarkdownFragment(db, itemRef, fragment), { readOnly });
411
+ }
412
+ catch (err) {
413
+ rethrowIfTestIsolationError(err);
414
+ rethrowIfDataDirUnreadable(err);
415
+ return undefined;
416
+ }
417
+ }
410
418
  /** Refs listed per kind of declared link; `total` still counts them all (one memory is named by 1,437 others). */
411
419
  const LINKS_PER_KIND = 10;
412
420
  /**
@@ -157,6 +157,7 @@ const updateCommand = defineJsonCommand({
157
157
  target: args.target,
158
158
  all: args.all,
159
159
  force: args.force,
160
+ skipIfLocked: args["skip-if-locked"],
160
161
  });
161
162
  }
162
163
  catch (error) {