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
177 lines (176 loc) • 8.38 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/.
/**
* `indexDocumentToStashEntry` — the inverse of the `akm` adapter's
* `indexDocumentFromEntry` (`adapters/akm-adapter.ts`).
*
* The indexer drains a single `IndexDocument` stream (`drainDirDocuments` × the
* dispatched adapter's `recognize`) and persists its canonical projection in
* `entries.document_json`. Every reader (`rowToIndexedEntry` →
* `DbIndexedEntry.entry`) consumes that same projection, and parity tests pin
* the boundary.
*
* That reconstruction is lossless by construction: the akm adapter's `recognize`
* assembles a full `IndexDocument` (P1/P2 → fold → P4) and then maps it onto the
* `IndexDocument` via `indexDocumentFromEntry` — first-class search/signal fields
* onto named members, every other search-surface/provenance field onto
* `documentJson` (the `DOCUMENT_JSON_CARRIED_FIELDS` set). This function reverses
* that mapping exactly, so `indexDocumentToStashEntry(recognize(file))` deep-
* equals the current persisted document for the same file (the
* `tests/integration/shadow-scan-parity.test.ts` gate pins this boundary).
*
* Two deliberate non-round-trip fields:
* - `filename` — dropped by `indexDocumentFromEntry` (no IndexDocument home),
* recovered here as `basename(doc.path)`. `applyPostContributorFields`
* sets it to `basename(file)`, and `doc.path` IS that file, so the value is
* identical.
* - `fileSize` — never set by `recognize`; it is attached at PERSIST time (`withFileSize`). It is therefore
* intentionally absent here and added by the persist layer.
*
* Pure, type-only imports (no cycle participation).
*/
import path from "node:path";
import { getMarkdownFragmentContent, hasMarkdownFragmentContent, MARKDOWN_CONTENT_MAX_CHARS, setMarkdownFragmentContent, truncateUnicodeSafe, } from "../../core/asset/markdown-projection.js";
import { warn } from "../../core/warn.js";
/**
* Reconstruct the `IndexDocument` an `IndexDocument` was mapped from. First-class
* IndexDocument members and the `documentJson`-carried extras are both restored;
* every field is set only when present, following an
* "assign-only-when-defined" assembly so the reconstruction deep-equals the original.
*/
export function indexDocumentToStashEntry(doc) {
const dj = (doc.documentJson ?? {});
const entry = {
name: doc.name,
// `type` is a required member of IndexDocument, so no
// `?? ""` fallback is needed — `recognize` always sets it.
type: doc.type,
// Dropped by indexDocumentFromEntry — recovered from the read path (= the
// basename the indexer stores). Always present on a recognized doc.
filename: path.basename(doc.path ?? ""),
};
// ── First-class IndexDocument members ──
if (doc.description !== undefined)
entry.description = doc.description;
if (doc.tags !== undefined)
entry.tags = doc.tags;
// One content bound for every adapter's document. The `akm` adapter already
// bounds its Markdown projection, so this only cuts other adapters' bodies.
if (doc.content !== undefined) {
if (doc.content.length > MARKDOWN_CONTENT_MAX_CHARS) {
entry.content = truncateUnicodeSafe(doc.content, MARKDOWN_CONTENT_MAX_CHARS);
entry.contentTruncated = true;
warn(`${doc.path}: indexed content truncated to ${MARKDOWN_CONTENT_MAX_CHARS} chars`);
}
else {
entry.content = doc.content;
}
}
if (doc.contentTruncated !== undefined)
entry.contentTruncated = doc.contentTruncated;
if (hasMarkdownFragmentContent(doc))
setMarkdownFragmentContent(entry, getMarkdownFragmentContent(doc));
if (doc.ownsPresentation !== undefined)
entry.ownsPresentation = doc.ownsPresentation;
if (doc.locator !== undefined)
entry.locator = doc.locator;
if (doc.updated !== undefined)
entry.updated = doc.updated;
if (doc.links !== undefined)
entry.links = doc.links;
// A row carries every field `recognize` set: the trust, provenance and lifecycle family an adapter sets directly
// (the OKF v0.2 fields, okf-support.md) rides here whichever adapter set it.
if (doc.provenance !== undefined)
entry.provenance = doc.provenance;
if (doc.lifecycleStatus !== undefined)
entry.lifecycleStatus = doc.lifecycleStatus;
if (doc.staleAfter !== undefined)
entry.staleAfter = doc.staleAfter;
if (doc.okfVersion !== undefined)
entry.okfVersion = doc.okfVersion;
// An adapter's own extras are kept whole and are not read for members.
if (doc.opaqueExtras && doc.documentJson !== undefined) {
entry.documentJson = doc.documentJson;
return entry;
}
if (doc.aliases !== undefined)
entry.aliases = doc.aliases;
if (doc.searchHints !== undefined)
entry.searchHints = doc.searchHints;
if (doc.hints !== undefined)
entry.hints = doc.hints;
if (doc.quality !== undefined)
entry.quality = doc.quality;
if (doc.confidence !== undefined)
entry.confidence = doc.confidence;
if (doc.beliefState !== undefined)
entry.beliefState = doc.beliefState;
if (doc.currentBeliefRefs !== undefined)
entry.currentBeliefRefs = doc.currentBeliefRefs;
if (doc.scope !== undefined)
entry.scope = doc.scope;
if (doc.captureMode !== undefined)
entry.captureMode = doc.captureMode;
if (doc.lessonStrength !== undefined)
entry.lessonStrength = doc.lessonStrength;
if (doc.derivedFrom !== undefined)
entry.derivedFrom = doc.derivedFrom;
if (doc.pinned !== undefined)
entry.pinned = doc.pinned;
if (doc.created !== undefined)
entry.created = doc.created;
if (doc.observed !== undefined)
entry.observed = doc.observed;
if (doc.expires !== undefined)
entry.expires = doc.expires;
// ── documentJson-carried extras (DOCUMENT_JSON_CARRIED_FIELDS) ──
// The `renderer` key on documentJson is adapter-internal (WI-C presentation),
// NOT a IndexDocument field — deliberately not restored.
assignStringList(entry, "examples", dj.examples);
assignStringList(entry, "usage", dj.usage);
if (isIntent(dj.intent))
entry.intent = dj.intent;
assignStringList(entry, "xrefs", dj.xrefs);
assignString(entry, "pageKind", dj.pageKind);
assignString(entry, "whenToUse", dj.whenToUse);
if (dj.toc !== undefined)
entry.toc = dj.toc;
if (dj.parameters !== undefined)
entry.parameters = dj.parameters;
if (dj.source !== undefined)
entry.source = dj.source;
assignString(entry, "category", dj.category);
assignStringList(entry, "supersededBy", dj.supersededBy);
assignStringList(entry, "contradictedBy", dj.contradictedBy);
assignString(entry, "run", dj.run);
assignString(entry, "setup", dj.setup);
assignString(entry, "cwd", dj.cwd);
if (dj.wikiRole !== undefined)
entry.wikiRole = dj.wikiRole;
assignStringList(entry, "sources", dj.sources);
assignStringList(entry, "evidenceSources", dj.evidenceSources);
assignString(entry, "evidence", dj.evidence);
assignStringList(entry, "uses", dj.uses);
// D2 (#730): OKF v0.2 provenance promoteProposal stamps onto AKM-native
// writes, carried via DOCUMENT_JSON_CARRIED_FIELDS (akm-adapter.ts) —
// unpacked back to a first-class member here exactly like `sources`/
// `generation`/`evidenceSources` above, so it round-trips to the top level
// of the persisted entry rather than staying nested under `documentJson`.
if (dj.provenance !== undefined)
entry.provenance = dj.provenance;
if (dj.frontmatter !== undefined)
entry.frontmatter = dj.frontmatter;
return entry;
}
function assignStringList(entry, key, value) {
if (Array.isArray(value))
entry[key] = value;
}
function assignString(entry, key, value) {
if (typeof value === "string")
entry[key] = value;
}
function isIntent(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}