akm-cli
Version:
akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur
723 lines (722 loc) • 36.3 kB
JavaScript
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
/**
* Database-backed (SQLite FTS5 + vector) search.
*
* Ranking is two candidate channels fused by reciprocal rank (`ranking.ts`):
* BM25 over whole documents matching any query word, and the nearest document
* vectors to the query embedding. The fused score is then scaled by the
* asset's recorded user feedback and, among dated assets, ordered by recency. Filters narrow
* the list; nothing else reorders it.
*/
import path from "node:path";
import { displayRef } from "../../core/asset/resolve-ref.js";
import { compareCodePoints } from "../../core/common.js";
import { defaultExcludedTypes } from "../../core/config/schema/search.js";
import { withStateDbTelemetry } from "../../core/state-db.js";
import { systemErrorCode } from "../../core/system-error.js";
import { isoDay } from "../../core/time.js";
import { presentationFor } from "../../core/type-presentation.js";
import { embed } from "../../llm/embedder.js";
import { effectiveEmbedding } from "../../llm/embedders/connection.js";
import { applyEmbeddingTemplate, resolveEmbeddingProfile } from "../../llm/embedders/profile.js";
import { normalizeEmbeddingEndpoint } from "../../llm/embedders/remote.js";
import { closeDatabase, indexDbIsDamaged, isCorruptionError } from "../../storage/repositories/index-connection.js";
import { getAllEntries, getBaseBeliefStatesForDerivedTwins, getEntriesByIds, getEntryById, getEntryRefsAndTypes, } from "../../storage/repositories/index-entries-repository.js";
import { searchFts } from "../../storage/repositories/index-fts-repository.js";
import { getMeta } from "../../storage/repositories/index-meta-repository.js";
import { getEmbeddingCount, searchVec } from "../../storage/repositories/index-vec-repository.js";
import { incompleteIndexWarning, noIndexWarning, openUsableIndex } from "../index-readiness.js";
import { isProposedQuality } from "../passes/entry-normalize.js";
import { appliesToProject, scopeMatchesFilters } from "../passes/metadata.js";
import { countFeedbackSignalsByRef, countShownByRef } from "../usage/usage-events.js";
import { ftsQueryTokens, parseRefPrefixQuery } from "./fts-query.js";
import { applyFeedback, applyPrefer, applyRecency, reciprocalRankFusion, } from "./ranking.js";
import { attachSearchHitAttribution } from "./search-attribution.js";
import { enrichSearchHit, searchHitLibrary } from "./search-hit-enrichers.js";
import { buildEditHint, findSourceForRow, isEditable } from "./search-source.js";
/**
* Age past which search surfaces a "run akm index" hint. Reads serve the
* existing index as-is (freshness is the writers' job — `indexWrittenAssets`
* plus full runs), so on installs with no improve cron a hand-edited or
* git-pulled file stays invisible until someone reindexes. The hint makes that
* actionable without re-introducing read-triggered reindexing.
*/
const STALE_INDEX_HINT_MS = 7 * 24 * 60 * 60 * 1000;
/** Candidates each channel contributes to fusion. */
const CHANNEL_DEPTH = 100;
/** How long search waits for the query embedding unless `embedding.queryTimeoutMs` says otherwise. */
export const DEFAULT_QUERY_EMBED_TIMEOUT_MS = 3000;
function hasIndexedProvenance(entry) {
return Boolean(entry.itemRef && entry.bundleId && entry.conceptId);
}
function buildStaleIndexHint(db) {
try {
const builtAt = getMeta(db, "builtAt");
if (!builtAt)
return undefined;
const ageMs = Date.now() - new Date(builtAt).getTime();
if (!Number.isFinite(ageMs) || ageMs < STALE_INDEX_HINT_MS)
return undefined;
const days = Math.floor(ageMs / (24 * 60 * 60 * 1000));
return `Search index was last built ${days} day(s) ago. Files added or edited outside akm since then are not searchable — run 'akm index' to refresh.`;
}
catch {
return undefined;
}
}
export function buildLocalAction(type, ref) {
return presentationFor(type).action?.(ref) ?? `akm show ${ref}`;
}
function resolveSearchHitRef(provenance, defaultBundleId) {
return displayRef({ conceptId: provenance.conceptId, bundleId: provenance.bundleId }, defaultBundleId);
}
// ── Main search entrypoint ───────────────────────────────────────────────────
/**
* Whether `auto` has a usable embedding provider.
*
* `auto` with no (or no remote) embedding settings falls back to the built-in
* local model (`DEFAULT_LOCAL_MODEL`, or `embedding.localModel`), so semantic
* search works without any configuration. The only config that can never
* succeed is a remote `endpoint` without a `model` — `RemoteEmbedder` throws on
* construction. Treating "no endpoint+model pair" as unconfigured warned every
* default install that semantic search had no provider while it worked.
*/
function hasConfiguredEmbeddingProvider(config) {
const embedding = config.embedding;
if (!embedding?.endpoint)
return true;
return Boolean(embedding.model);
}
export async function searchLocal(input) {
const { stashDir, config } = input;
const warnings = [];
// Semantic search is attempted fresh on every query (see `startVectorChannel`);
// there is no cached readiness verdict to consult here. The only thing
// worth flagging ahead of the attempt is a config that can never succeed.
if (config.semanticSearchMode === "auto" && !hasConfiguredEmbeddingProvider(config)) {
warnings.push("Semantic search is enabled (semanticSearchMode='auto') but embedding.endpoint is set without embedding.model. " +
"Either: (a) set embedding.model, or (b) remove embedding.endpoint to use the built-in local model, or " +
"(c) `akm config set semanticSearchMode off` to use keyword-only search.");
}
// Reads never build and never wait: they serve what is persisted for this
// library and say so when that is nothing, or not yet everything. Content
// freshness is the writers' job (indexWrittenAssets + explicit runs).
const usable = openUsableIndex(stashDir, { readOnly: input.readOnly });
if (!usable) {
return { hits: [], warnings: [...warnings, noIndexWarning()], mode: "keyword" };
}
const { db, complete } = usable;
try {
if (!complete)
warnings.push(incompleteIndexWarning());
const staleHint = buildStaleIndexHint(db);
if (staleHint)
warnings.push(staleHint);
const { hits, embedMs, rankMs, mode, semanticWarning, feedbackWarning } = await searchDatabase(db, input);
if (semanticWarning)
warnings.push(semanticWarning);
if (feedbackWarning)
warnings.push(feedbackWarning);
return {
hits,
tip: hits.length === 0 ? EMPTY_RESULT_TIP : undefined,
warnings: warnings.length > 0 ? warnings : undefined,
embedMs,
rankMs,
// Report the mode the search ACTUALLY used, carried explicitly from the
// vector channel — not inferred from elapsed embedding milliseconds.
mode,
};
}
catch (error) {
// A damaged page is an index that cannot serve; `akm index` rebuilds it.
if (!isCorruptionError(error) || !indexDbIsDamaged())
throw error;
return { hits: [], warnings: [...warnings, noIndexWarning()], mode: "keyword" };
}
finally {
closeDatabase(db);
}
}
// ── Database search ─────────────────────────────────────────────────────────
async function searchDatabase(db, input) {
const { query, searchType, limit, stashDir, sources, config, filters, prefer } = input;
const filterOptions = {
db,
sources,
restrictToSources: input.restrictToSources === true,
filters,
since: input.since,
until: input.until,
includeProposed: input.includeProposed === true,
beliefFilter: input.beliefFilter ?? "all",
project: input.project,
};
// #627 — resolve the default type-exclusion policy. It applies ONLY on the
// untyped ('any') path and only when the caller did not opt back in via
// `includeExcludedTypes`. When the config key is ABSENT a built-in default of
// ['session'] is applied; an explicit empty list disables exclusion.
const defaultExcludes = searchType === "any" && !input.includeExcludedTypes
? defaultExcludedTypes(config).filter((type) => !input.includeTypes?.includes(type))
: [];
// D4 — conceptId-prefix queries (`memories/projecta/`, `bundle//`,
// `bundle//skills/`) translate to a deterministic enumeration narrowed by
// conceptId instead of a keyword search over their path words. The branch
// fires only on the untyped path: an explicit `--type` flag expresses
// stronger intent and wins. The PREFIX is itself explicit intent, so
// `defaultExcludeTypes` does not apply — `sessions/` enumerates sessions
// exactly like `--type session` does, and `bundle//` means the whole bundle.
const refPrefix = searchType === "any" ? parseRefPrefixQuery(query) : null;
if (refPrefix) {
return {
hits: await enumerateEntries({
...filterOptions,
limit,
prefer,
stashDir,
config,
excludeTypes: [],
conceptIdPrefix: refPrefix.conceptIdPrefix,
...(refPrefix.bundle !== undefined ? { bundle: refPrefix.bundle } : {}),
}),
mode: "keyword",
};
}
// Empty queries — including ones with no searchable token such as "." —
// enumerate matching entries instead of returning nothing.
if (ftsQueryTokens(query).length === 0) {
return {
hits: await enumerateEntries({
...filterOptions,
limit,
prefer,
stashDir,
config,
typeFilter: searchType === "any" ? undefined : searchType,
// Rules are standing context, listed on their own; they are not "used" assets.
excludeTypes: input.byUsage ? [...defaultExcludes, "rule"] : defaultExcludes,
...(input.byUsage ? { usage: input.project ?? {} } : {}),
}),
mode: "keyword",
};
}
const typeFilter = searchType === "any" ? undefined : searchType;
const startedAt = Date.now();
// The query embedding request goes out first, so FTS runs while it is in flight.
const filterCandidates = (ids) => {
const entries = getEntriesByIds(db, ids)
.filter(hasIndexedProvenance)
.filter((row) => (typeFilter ? row.entry.type === typeFilter : !defaultExcludes.includes(row.entry.type)));
return new Set(applyEntryFilters(entries, filterOptions).map((row) => row.id));
};
const vectorChannel = startVectorChannel(db, query, config, filterCandidates);
const lexical = searchFts(db, query, CHANNEL_DEPTH, typeFilter, defaultExcludes, filterCandidates);
const vector = await vectorChannel;
const embedMs = Date.now() - startedAt;
const tRank0 = Date.now();
const vectorCandidates = vector.neighbors ? keepAllowedTypes(db, vector.neighbors, typeFilter, defaultExcludes) : [];
const rrf = reciprocalRankFusion([lexical, vectorCandidates]);
const feedback = readFeedback(rrf);
const feedbackRanked = applyFeedback(rrf, feedback.counts);
const fused = applyRecency(prefer ? applyPrefer(feedbackRanked, readPreferred(db, feedbackRanked, prefer)) : feedbackRanked, readEntryDays(db, rrf));
const selected = selectFusedEntries(db, fused, limit, filterOptions);
const rankMs = Date.now() - tRank0;
const hits = await Promise.all(selected.map(({ candidate, row }) => buildDbHit({
entry: row.entry,
path: row.filePath,
itemRef: row.itemRef,
bundleId: row.bundleId,
conceptId: row.conceptId,
score: Math.round(candidate.score * 1e6) / 1e6,
whyMatched: describeRanks(candidate),
defaultStashDir: stashDir,
sources,
config,
db,
eligible: (row) => applyEntryFilters([row], filterOptions).length > 0,
})));
const mode = vector.warning ? "fts-fallback" : vector.neighbors ? "semantic" : "keyword";
return { embedMs, rankMs, hits, mode, semanticWarning: vector.warning, feedbackWarning: feedback.warning };
}
/**
* User feedback counts of the fused candidates, from state.db in one query.
* A search never creates state.db, and one that cannot read it ranks without
* feedback and says so.
*/
function readFeedback(fused) {
let counts = new Map();
try {
withStateDbTelemetry((stateDb) => {
counts = countFeedbackSignalsByRef(stateDb, fused.map((candidate) => candidate.itemRef));
});
}
catch (error) {
return {
counts: new Map(),
warning: `Feedback was not applied to the ranking: ${error instanceof Error ? error.message : String(error)}`,
};
}
return { counts };
}
/** The `itemRef`s of the fused candidates whose scope matches the preference. */
function readPreferred(db, fused, prefer) {
const preferred = new Set();
for (const { itemRef, entry } of getEntriesByIds(db, fused.map((candidate) => candidate.id))) {
if (scopeMatchesFilters(entry, prefer))
preferred.add(itemRef);
}
return preferred;
}
/** The date of each fused candidate that has one, by entry id. */
function readEntryDays(db, fused) {
const days = new Map();
for (const { id, entry } of getEntriesByIds(db, fused.map((candidate) => candidate.id))) {
const day = entryDay(entry);
if (day)
days.set(id, day);
}
return days;
}
/**
* Walk the fused list in order, loading entries a batch at a time, and keep
* the first `limit` that survive path deduplication and the filters. An entry
* whose indexed content is identical to a kept one's (the same body saved
* under another name or in another bundle) is a duplicate and is skipped.
*
* A memory and the `.derived` twin memory-inference wrote beside it are one
* family and take one slot: the twin is skipped when its parent is kept, and
* a parent that arrives after its twin takes the place of the first twin and drops the others. Twins of one parent do not collapse into each other. A twin whose
* parent is not a hit stays. Only a current-belief search collapses; `--belief all` and `historical` ask for every record. The parent's `expandTo` still points at the twin.
*/
function selectFusedEntries(db, fused, limit, filterOptions) {
const selected = [];
const seenPaths = new Set();
const seenContent = new Set();
const families = new Map();
const batchSize = Math.max(limit * 2, 20);
for (let offset = 0; offset < fused.length && selected.length < limit; offset += batchSize) {
const batch = [];
for (const candidate of fused.slice(offset, offset + batchSize)) {
const row = getEntryById(db, candidate.id);
if (!row || !hasIndexedProvenance(row) || seenPaths.has(row.filePath || row.itemRef))
continue;
seenPaths.add(row.filePath || row.itemRef);
batch.push({ ...row, id: candidate.id, candidate });
}
for (const kept of applyEntryFilters(batch, filterOptions)) {
const { candidate, ...row } = kept;
const content = row.entry.content?.replace(/\s+/g, " ").trim();
if (content) {
if (seenContent.has(content))
continue;
seenContent.add(content);
}
if (row.entry.type === "memory" && filterOptions.beliefFilter === "current") {
const twin = Boolean(row.entry.derivedFrom);
const key = `${row.bundleId}\0${row.entry.derivedFrom ?? row.conceptId}`;
const family = families.get(key) ?? { parent: false, twins: [] };
families.set(key, family);
if (twin && family.parent)
continue;
if (!twin) {
family.parent = true;
const [first, ...rest] = family.twins;
if (first) {
selected[selected.indexOf(first)] = { candidate, row };
for (const other of rest)
selected.splice(selected.indexOf(other), 1);
family.twins = [];
continue;
}
}
else {
const entry = { candidate, row };
family.twins.push(entry);
selected.push(entry);
continue;
}
}
selected.push({ candidate, row });
}
}
return selected.slice(0, limit);
}
/** Vector candidates of the requested type, nearest first; equal distances are ordered by ref. */
function keepAllowedTypes(db, neighbors, typeFilter, excludeTypes) {
const rows = getEntryRefsAndTypes(db, neighbors.map((neighbor) => neighbor.id));
const excluded = new Set(excludeTypes);
return neighbors
.flatMap(({ id, distance }) => {
const row = rows.get(id);
if (!row)
return [];
if (typeFilter ? row.type !== typeFilter : excluded.has(row.type))
return [];
return [{ id, itemRef: row.itemRef, distance }];
})
.sort((a, b) => a.distance - b.distance || compareCodePoints(a.itemRef, b.itemRef))
.map(({ id, itemRef }) => ({ id, itemRef }));
}
/** `whyMatched` for a fused hit: its rank in each channel that returned it. */
function describeRanks(candidate) {
const [lexicalRank, vectorRank] = candidate.ranks;
return [
...(lexicalRank !== undefined ? [`lexical rank ${lexicalRank}`] : []),
...(vectorRank !== undefined ? [`vector rank ${vectorRank}`] : []),
];
}
const EMPTY_RESULT_TIP = "No matching stash assets were found. Try a different query or run 'akm index' to rebuild.";
// ── Enumeration (browse) path ────────────────────────────────────────────────
/**
* Enumerate index entries without FTS scoring — the browse path shared by
* empty/unsearchable queries and D4 conceptId-prefix queries (`memories/`,
* `bundle//`, `bundle//skills/`). Applies the same filters as the scored
* path (source narrowing, scope, proposed-quality, belief) before the limit
* slice. Hits carry the fixed browse score 1 in type-then-name order — this is
* a deterministic listing, not a relevance ranking. A preference moves its
* matches to the front of that order, before the limit slice.
*/
async function enumerateEntries(opts) {
const { db, sources, config } = opts;
const allEntries = getAllEntries(db, opts.typeFilter, opts.excludeTypes).filter(hasIndexedProvenance);
// Explicit listing order: type, then name, then filePath. The underlying
// SELECT carries no ORDER BY, so its row order tracks the query plan and the
// index-insertion (file-walk) order — both machine-dependent. A browse
// listing must not change order across hosts or SQLite versions.
allEntries.sort((a, b) => a.entry.type.localeCompare(b.entry.type) ||
a.entry.name.localeCompare(b.entry.name) ||
(a.filePath || a.itemRef).localeCompare(b.filePath || b.itemRef));
// D4: narrow to the requested bundle and subtree. Matching is against the
// conceptId — the spelling every emitted `ref` carries — so a ref copied out
// of search output round-trips back in. `startsWith` on the full
// slash-retaining prefix is exact: "memories/projecta/" cannot match a
// sibling "memories/projectalpha/…" scope.
const bundle = opts.bundle?.toLowerCase();
const bundleFiltered = bundle === undefined ? allEntries : allEntries.filter((ie) => ie.bundleId.toLowerCase() === bundle);
const conceptIdPrefix = opts.conceptIdPrefix?.toLowerCase() ?? "";
const prefixFiltered = conceptIdPrefix.length > 0
? bundleFiltered.filter((ie) => ie.conceptId.toLowerCase().startsWith(conceptIdPrefix))
: bundleFiltered;
// Deduplicate by file path — multiple entries can share the same file.
// Filtering happens BEFORE the limit slice so a restrictive filter still
// returns up to `limit` results.
const eligible = applyEntryFilters(deduplicateByPath(prefixFiltered), opts);
const { prefer } = opts;
const ordered = opts.usage
? rankByUsage(eligible, opts.usage)
: prefer
? [
...eligible.filter((ie) => scopeMatchesFilters(ie.entry, prefer)),
...eligible.filter((ie) => !scopeMatchesFilters(ie.entry, prefer)),
]
: eligible;
const selected = ordered.slice(0, opts.limit);
return Promise.all(selected.map((ie) => buildDbHit({
entry: ie.entry,
path: ie.filePath,
itemRef: ie.itemRef,
bundleId: ie.bundleId,
conceptId: ie.conceptId,
score: 1,
defaultStashDir: opts.stashDir,
sources,
config,
db,
eligible: (row) => applyEntryFilters([row], opts).length > 0,
})));
}
/**
* The items shown in `project` (anywhere, when absent), most shown first, ties by ref. With a project, an
* asset naming another project is left out. A missing state.db is no history. Never a relevance ranking.
*/
function rankByUsage(items, project) {
let shown = new Map();
withStateDbTelemetry((stateDb) => {
shown = countShownByRef(stateDb, project.name);
});
return items
.filter((item) => item.entry.type !== "rule" &&
shown.has(item.itemRef) &&
(project.name === undefined || appliesUnder(item.entry, project)))
.sort((a, b) => (shown.get(b.itemRef) ?? 0) - (shown.get(a.itemRef) ?? 0) || a.itemRef.localeCompare(b.itemRef));
}
/** Whether an asset applies under the project: it names it or no project, unless the selection's filter decided. */
export function appliesUnder(entry, project) {
return project.byFilter === true || appliesToProject(entry, project.name);
}
/** The day an entry is dated by: when it was observed, else when it was last updated. */
function entryDay(entry) {
const date = entry.observed ?? entry.updated;
return date === undefined ? undefined : isoDay(date);
}
/**
* Filter chain shared by the scored and browse paths, in this order:
* source-narrowing → scope → date range → proposed-quality → derived-twin
* belief inheritance → belief filter.
*/
export function applyEntryFilters(items, opts) {
const { filters } = opts;
// Source filter: when the caller narrowed `sources` via `--from <name>`,
// drop entries whose filePath does not live under any requested source. The
// index spans every configured source, so without this filter a narrowed
// --from request would still leak results from other sources.
const sourceFiltered = opts.restrictToSources
? items.filter((item) => findSourceForRow(item, opts.sources) !== undefined)
: items;
// Scope filter: drop entries whose stored scope does not satisfy every
// supplied key.
const scopeFiltered = filters
? sourceFiltered.filter((item) => scopeMatchesFilters(item.entry, filters))
: sourceFiltered;
// Rule filter: a project's rules apply to that project only; shared rules to every one.
const { project } = opts;
const ruleFiltered = project
? scopeFiltered.filter((item) => item.entry.type !== "rule" || appliesUnder(item.entry, project))
: scopeFiltered;
// Date filter: keep entries dated within the inclusive range; undated
// entries cannot satisfy a bound.
const { since, until } = opts;
const dateFiltered = since === undefined && until === undefined
? ruleFiltered
: ruleFiltered.filter((item) => {
const day = entryDay(item.entry);
return day !== undefined && (since === undefined || day >= since) && (until === undefined || day <= until);
});
// Proposed-quality filter: exclude `quality: "proposed"`
// entries unless the caller opts in.
const qualityFiltered = opts.includeProposed
? dateFiltered
: dateFiltered.filter((item) => !isProposedQuality(item.entry.quality));
// 03-R3: derived twins inherit their base's demoting belief state BEFORE the
// belief filter, so the filter (and the reported hit state) stays consistent
// across both paths.
inheritDerivedTwinBeliefStates(opts.db, qualityFiltered);
return qualityFiltered.filter((item) => matchBeliefFilter(item.entry.beliefState, opts.beliefFilter));
}
/**
* 03-R3: let each `.derived` twin inherit its base memory's demoting belief
* state, so `--belief` treats a stale flag-free twin like its corrected base.
* The base carries the flag; its near-duplicate `.derived` twin carries none.
* Done in-memory at search time — NOT by writing the twin's frontmatter —
* because the SCC belief resolver refreshes any non-frozen state written to a
* derived memory back to `active` on the next improve run, erasing it. Only
* twins with no state of their own inherit; an explicit twin state always wins.
*/
function inheritDerivedTwinBeliefStates(db, items) {
const DEMOTING = new Set(["contradicted", "superseded", "deprecated", "archived"]);
const twins = items.filter((it) => it.entry.type === "memory" &&
it.entry.beliefState === undefined &&
it.entry.name.toLowerCase().endsWith(".derived"));
if (twins.length === 0)
return;
const baseBeliefByTwinId = getBaseBeliefStatesForDerivedTwins(db, twins.map((t) => t.id));
for (const t of twins) {
const baseBelief = baseBeliefByTwinId.get(t.id);
// Only inherit DEMOTIONS — never let a base's active/asserted state lift a twin.
if (baseBelief && DEMOTING.has(baseBelief)) {
t.entry.beliefState = baseBelief;
}
}
}
export function matchBeliefFilter(beliefState, filter) {
if (filter === "all")
return true;
// 03: the belief filter applies to ANY flagged entry, not just memories, so
// `current`/`historical` filters catch contradicted/superseded KNOWLEDGE too.
// Unflagged entries (beliefState === undefined) still pass the `current` filter.
if (filter === "current") {
// Phase 1A: `asserted` is a "current" state (stronger authority than `active`);
// `deprecated` is excluded from current results.
return beliefState === undefined || beliefState === "active" || beliefState === "asserted";
}
// historical
return (beliefState === "contradicted" ||
beliefState === "superseded" ||
beliefState === "deprecated" ||
beliefState === "archived");
}
// ── Vector channel ──────────────────────────────────────────────────────────
/**
* Embed the query and return its nearest document ids, best first. The
* embedding request is dispatched before this returns, so the caller's FTS
* query overlaps it. A slow or failing embedder degrades the search to keyword
* ranking with a warning after `embedding.queryTimeoutMs`.
*/
function startVectorChannel(db, query, config, filterCandidates) {
if (config.semanticSearchMode === "off")
return Promise.resolve({ neighbors: null });
// A real-time completeness fact, not a cached verdict: skip the round trip
// only when the index has never embedded anything. A PARTIAL failure still
// attempts — and if the endpoint is genuinely down, the failure surfaces as
// a live warning instead of silently skipping with no signal.
if (getEmbeddingCount(db) === 0)
return Promise.resolve({ neighbors: null });
const embedding = effectiveEmbedding(config);
const timeoutMs = embedding?.queryTimeoutMs ?? DEFAULT_QUERY_EMBED_TIMEOUT_MS;
const controller = new AbortController();
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => {
controller.abort();
reject(new Error(`Query embedding timed out after ${timeoutMs}ms`));
}, timeoutMs);
});
const queryText = applyEmbeddingTemplate(resolveEmbeddingProfile(embedding).queryTemplate, query);
return Promise.race([embed(queryText, embedding, controller.signal), timeout])
.then((vector) => ({ neighbors: searchVec(db, vector, CHANNEL_DEPTH, undefined, filterCandidates) }))
.catch((error) => ({ neighbors: null, warning: buildVectorFallbackWarning(config, error) }))
.finally(() => clearTimeout(timer));
}
function buildVectorFallbackWarning(config, error) {
const endpoint = safeEmbeddingEndpoint(config);
const reason = classifyVectorFailure(error);
const target = endpoint
? `embedding endpoint ${endpoint}`
: effectiveEmbedding(config)?.endpoint
? "configured embedding endpoint"
: "local embedding model";
const unavailable = reason === "connection failed" ? `cannot reach ${target}` : `${target} is unavailable`;
return `Vector search unavailable: ${unavailable} (${reason}) — falling back to keyword search.`;
}
/**
* Name the useful endpoint without ever carrying URL userinfo, query secrets,
* or fragments into a warning. Invalid authored values fail closed.
*/
function safeEmbeddingEndpoint(config) {
const endpoint = effectiveEmbedding(config)?.endpoint;
if (!endpoint)
return undefined;
try {
const parsed = new URL(normalizeEmbeddingEndpoint(endpoint));
parsed.username = "";
parsed.password = "";
parsed.search = "";
parsed.hash = "";
return parsed.toString();
}
catch {
return undefined;
}
}
/** Map untrusted runtime failures onto a small, non-secret diagnostic set. */
function classifyVectorFailure(error) {
const code = systemErrorCode(error);
const message = error instanceof Error ? error.message : "";
if (code === "ECONNREFUSED" ||
code === "ECONNRESET" ||
code === "ENETUNREACH" ||
code === "EHOSTUNREACH" ||
code === "ENOTFOUND" ||
code === "EAI_AGAIN" ||
/typo in the url or port|connection (?:refused|failed|reset)|fetch failed/i.test(message)) {
return "connection failed";
}
if (code === "ETIMEDOUT" || /timed? out|timeout/i.test(message))
return "request timed out";
const httpStatus = message.match(/Embedding (?:batch )?request failed \((\d{3})\)/i)?.[1];
if (httpStatus)
return `HTTP ${httpStatus}`;
if (/unexpected embedding response|missing data\[0\]\.embedding/i.test(message))
return "invalid embedding response";
return "request failed";
}
// ── Hit building ────────────────────────────────────────────────────────────
export async function buildDbHit(input) {
// An entry no file holds has no path: none is printed.
const absolutePath = input.path === "" ? "" : path.resolve(input.path);
const source = findSourceForRow({ filePath: absolutePath, bundleId: input.bundleId }, input.sources);
const { entryStashDir, defaultBundleId } = searchHitLibrary(input.defaultStashDir, source, absolutePath, input.bundleId, input.config?.defaultBundle);
const ref = resolveSearchHitRef(input, defaultBundleId);
const editable = absolutePath === "" ? source?.writable === true : isEditable(absolutePath, input.config, input.sources);
const estimatedTokens = typeof input.entry.fileSize === "number" ? Math.round(input.entry.fileSize / 4) : undefined;
const hit = {
type: input.entry.type,
name: input.entry.name,
...(absolutePath === "" ? {} : { path: absolutePath }),
ref,
itemRef: input.itemRef,
origin: source?.registryId ?? null,
editable,
...(!editable ? { editHint: buildEditHint(ref) } : {}),
description: input.entry.description,
tags: input.entry.tags,
size: deriveSize(input.entry.fileSize),
action: buildLocalAction(input.entry.type, ref),
score: input.score,
...(input.whyMatched ? { whyMatched: input.whyMatched } : {}),
...(estimatedTokens !== undefined ? { estimatedTokens } : {}),
// Surface optional quality. Omitted when entry has
// no `quality` field so payloads stay compact for the common case.
...(input.entry.quality ? { quality: input.entry.quality } : {}),
...(input.entry.beliefState ? { beliefState: input.entry.beliefState } : {}),
...(input.entry.currentBeliefRefs ? { currentBeliefRefs: input.entry.currentBeliefRefs } : {}),
...(input.entry.observed ? { observed: input.entry.observed } : {}),
...(input.entry.created ? { created: input.entry.created } : {}),
...(input.entry.updated ? { updated: input.entry.updated } : {}),
...(input.entry.expires ? { expires: input.entry.expires } : {}),
};
if (input.entry.derivedFrom) {
attachSearchHitAttribution(hit, {
memoryInference: { exposure: "direct" },
});
}
await enrichSearchHit(hit, {
type: input.entry.type,
stashDir: entryStashDir,
bundleId: input.bundleId,
conceptId: input.conceptId,
defaultBundleId,
descriptionSource: input.entry.source,
db: input.db,
eligible: input.eligible,
});
return hit;
}
// ── Utilities ────────────────────────────────────────────────────────────────
export function deriveSize(bytes) {
if (bytes === undefined)
return undefined;
if (bytes < 1024)
return "small";
if (bytes < 10240)
return "medium";
return "large";
}
/**
* For each source, how many assets a browse lists in it (`total`: the browse defaults, so no proposed or historical
* entry and none of `excludeTypes`) and how many of those satisfy `filters` (`eligible`). Counts the whole index,
* not a result page, through the same source narrowing, belief and scope matching the browse path applies.
*/
export function countBrowseEntries(db, sources, filters, excludeTypes, includeProposed = false) {
const all = deduplicateByPath(getAllEntries(db, undefined, [...excludeTypes]).filter(hasIndexedProvenance));
const tally = (items) => {
const byType = {};
for (const { entry } of items)
byType[entry.type] = (byType[entry.type] ?? 0) + 1;
return { count: items.length, byType };
};
return sources.map((source) => {
const total = applyEntryFilters(all, {
db,
sources: [source],
restrictToSources: true,
includeProposed,
beliefFilter: "current",
});
const eligible = filters ? total.filter((item) => scopeMatchesFilters(item.entry, filters)) : total;
return { total: tally(total), eligible: tally(eligible) };
});
}
/** Keep the first entry per file path; the caller owns the order. */
function deduplicateByPath(items) {
const seen = new Set();
return items.filter((item) => {
const key = item.filePath || item.itemRef;
if (seen.has(key))
return false;
seen.add(key);
return true;
});
}