UNPKG

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

683 lines (682 loc) • 34.7 kB
// 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/. /** * `akm show` — entry point. * * show(ref) → indexer.lookup(ref) → readFile(entry.filePath) * * The richer presentation logic (matchers, renderers, edit-hints, * summary-detail truncation) lives below in this file. The flow: * * 1. Ask `indexer.lookup(ref)` for the bundle's physical owner (index-free) * and the index row, when there is one. `show` never builds the index. * 2. With no row, the owning adapter's recognition of the file stands in for it; * the index only adds links, indexed fragments and usage ids. * 3. Render the file via the matcher/renderer pipeline. */ import fs from "node:fs"; import path from "node:path"; // asset-io: base a script file no adapter lists (its extension is unknown), shown as plain text as show always did; a facade read goes through an adapter (facade-fs), and none lists it import { buildFileContext } from "../../core/adapter/directory/file-context.js"; import { deriveCanonicalAssetNameFromStashRoot, stashDirFor } from "../../core/asset/asset-placement.js"; import { makeBundleRef, parseBundleRef } from "../../core/asset/asset-ref.js"; import { parseFrontmatter } from "../../core/asset/frontmatter.js"; import { extractSection, markdownFragmentSlugs, markdownToc } from "../../core/asset/markdown.js"; import { buildMarkdownLeadContext, fragmentForSelector, MARKDOWN_FRAGMENT_CONTEXT_DEFAULT_MAX_CHARS, } from "../../core/asset/markdown-fragments.js"; import { projectMarkdownFragmentContent } from "../../core/asset/markdown-projection.js"; import { displayDefaultBundle, displayRef, displayRefForConceptId } from "../../core/asset/resolve-ref.js"; import { META_DIR, parseMetaRef, readMetaFile } from "../../core/asset/stash-meta.js"; import { adapterWrites } from "../../core/assets/gate.js"; import { fileContextOf, findAsset } from "../../core/assets/read.js"; import { presentationOf } from "../../core/assets/type.js"; import { asNonEmptyString, isContainedResolvedPath, toPosix } from "../../core/common.js"; import { loadConfig } from "../../core/config/config.js"; import { ConfigError, NotFoundError, rethrowIfDataDirUnreadable, rethrowIfTestIsolationError, UsageError, } from "../../core/errors.js"; import { appendEvent } from "../../core/events.js"; import { SCRIPT_EXTENSIONS } from "../../core/recognition-util.js"; import { warn, warnOnce } from "../../core/warn.js"; import { lookupBundleRef, lookupBundleRefWithResolution, lookupBundleRefWithResolutionReadonly, } from "../../indexer/indexer.js"; import { applyCuratedFrontmatter, applyProvenanceFrontmatter } from "../../indexer/passes/metadata.js"; import { buildEditHint, findSourceForRow, isEditable, resolveSourceEntries, sourcePaths, } from "../../indexer/search/search-source.js"; import { recentShowCount, recordShowUsage } from "../../indexer/usage/show-usage.js"; import { buildRenderContext, getRenderer } from "../../output/renderer-registry.js"; import { resolveSourcesForOrigin } from "../../registry/origin-resolve.js"; import { withIndexDb } from "../../storage/repositories/index-db.js"; import { getIndexedMarkdownFragment } from "../../storage/repositories/index-fts-repository.js"; import { readEntryLinks } from "../../storage/repositories/index-links-repository.js"; import { buildWorkflowAction } from "../../workflows/renderer.js"; /** * Unified show: queries the local FTS5 index, then reads that row's file path. * A physical owner can arbitrate collisions during lookup, but show never * renders an asset without an indexed row; no provider or disk * fallback. * * When `detail` is `"brief"` or `"summary"`, the response omits * content/template/prompt and returns compact metadata. */ export async function akmShowUnified(input) { const ref = input.ref.trim(); if (input.maxTokens !== undefined) { if (!Number.isSafeInteger(input.maxTokens) || input.maxTokens <= 0 || !Number.isSafeInteger(input.maxTokens * 4)) { throw new UsageError("--max-tokens must be a positive safe integer whose character budget is safe.", "INVALID_FLAG_VALUE"); } if (input.maxContextChars !== undefined) { throw new UsageError("--max-tokens and --max-chars are mutually exclusive.", "INVALID_FLAG_VALUE"); } } const presentation = { ...input, maxContextChars: input.contextMode === "lead" && input.maxTokens !== undefined ? input.maxTokens * 4 : input.maxContextChars, }; validateFragmentContextRequest(presentation); // 0a. Stash `.meta/` convention: `[origin//]meta[:name]` direct-reads a // human-authored orientation doc from the stash's `.meta/` directory. // These files are not indexed (the walker skips dot-dirs), so they are // resolved here before the index lookup; meta docs are not asset refs. { const metaRef = parseMetaRef(ref); if (metaRef) return applyContentBudget(await showStashMeta(metaRef, input.readOnly === true), input.maxTokens); } // The bundle's files resolve the asset; the index only adds what it alone has. const result = applyContentBudget(await showLocal(presentation), input.maxTokens); // Count prior shows of this ref before logging the current one. if (!input.skipLogging && !input.readOnly) { const consumedRef = result.ref ?? makeBundleRef(undefined, parseBundleRef(ref).conceptId); const priorShowCount = recentShowCount(consumedRef); recordShowUsage(consumedRef, result.type, result.name, input.eventSource, result.path, input.project); if (priorShowCount >= 2) { // Agent has shown this same asset 3+ times — inject a loop-break hint. result.showLoopWarning = priorShowCount + 1; } } return result; } const FRONTMATTER_PREFIX = /^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/; /** * Cut `text` to at most `limit` characters without splitting a UTF-16 surrogate pair, * preferring to end at whitespace when one is close (within the last quarter, at most 32 characters). */ function cutAtBoundary(text, limit) { if (text.length <= limit) return text; let end = limit; const last = text.charCodeAt(end - 1); if (last >= 0xd800 && last <= 0xdbff) end -= 1; // The cut already falls on a word end: keep the whole word. if (/\s/.test(text[end] ?? "")) return text.slice(0, end); const window = text.slice(Math.max(0, end - Math.min(32, Math.floor(end / 4))), end); const space = window.search(/\s\S*$/); if (space > 0) end = end - window.length + space; return text.slice(0, end); } /** * Budget only rendered bodies: never reopen source files or widen sensitive renderers. * A leading frontmatter block is metadata: it is kept whole and does not count against the budget. */ function applyContentBudget(response, maxTokens) { if (maxTokens === undefined) return response; let remaining = maxTokens * 4; let chars = 0; let truncated = response.contextTruncated === true; for (const key of ["content", "template", "prompt"]) { const text = response[key]; if (text === undefined) continue; const frontmatter = FRONTMATTER_PREFIX.exec(text)?.[0] ?? ""; const body = text.slice(frontmatter.length); const bounded = cutAtBoundary(body, remaining); response[key] = frontmatter + bounded; chars += bounded.length; remaining -= bounded.length; truncated ||= bounded.length < body.length; } response.contentBudget = { maxTokens, estimatedTokens: Math.ceil(chars / 4), truncated }; if (response.contextMode === "exact" && truncated) response.contextTruncated = true; return response; } /** * Resolve a stash `.meta/` doc and return it as a lightweight ShowResponse. * * With no origin the working stash (and other configured sources, in order) * is searched and the first hit wins. With an origin the lookup is narrowed * to that stash; an uninstalled origin yields an actionable "not installed" * error. The file is read directly from disk — `.meta/` is never indexed. */ async function showStashMeta(metaRef, readOnly = false) { const allSources = resolveSourceEntries(); const sources = resolveSourcesForOrigin(metaRef.origin, allSources); if (metaRef.origin && sources.length === 0) { throw new NotFoundError(`Stash "${metaRef.origin}" is not installed, so its ${META_DIR}/ docs are unavailable. ` + `Run: akm bundle add ${metaRef.origin}`); } const config = loadConfig(); for (const source of sources) { if (source.path === undefined) continue; const metaFile = readMetaFile(source.path, metaRef.name); if (!metaFile) continue; const editable = isEditable(metaFile.path, config, allSources); if (!readOnly) { appendEvent({ eventType: "show", ref: `meta:${metaRef.name}`, metadata: { type: "meta", name: metaRef.name } }); } return { type: "meta", name: metaRef.name, path: metaFile.path, ref: `meta:${metaRef.name}`, content: metaFile.content, origin: source.registryId ?? null, editable, }; } throw new NotFoundError(`No ${META_DIR}/${metaRef.name} doc found${metaRef.origin ? ` in "${metaRef.origin}"` : ""}. ` + `Stash maintainers can create ${META_DIR}/${metaRef.name}.md to describe this stash ` + `(purpose, key assets, conventions, maintainer).`); } function validateFragmentContextRequest(input) { const flag = input.contextFlag ?? "--context lead"; const mode = input.contextMode ?? "exact"; if (mode !== "exact" && mode !== "lead") { throw new UsageError(`Invalid --context value: "${String(mode)}". Expected exact or lead.`, "INVALID_FLAG_VALUE"); } if (input.maxContextChars !== undefined && (!Number.isSafeInteger(input.maxContextChars) || input.maxContextChars <= 0)) { throw new UsageError("Fragment context budget must be a positive safe integer.", "INVALID_FLAG_VALUE"); } if (mode !== "lead" && input.maxContextChars !== undefined) { throw new UsageError("--max-chars requires --context lead.", "INVALID_FLAG_VALUE"); } if (mode !== "lead") return; if (parseMetaRef(input.ref)) { throw new UsageError(`${flag} requires an indexed Markdown asset fragment.`, "INVALID_FLAG_VALUE"); } const parsed = parseBundleRef(input.ref); if (!parsed.fragment) { throw new UsageError(`${flag} requires a fragment-qualified ref.`, "INVALID_FLAG_VALUE"); } } /** * Env/secret bodies have no safe fragment surface, and a fragment cannot widen * what the env/secret renderers expose: both always omit the body (env — key * names only; secret — never rendered), fragment or not. The entry's type * decides. `--context lead` refuses them; a plain fragment is warned about and * ignored rather than refusing the whole show. */ function enforceSensitiveFragmentPolicy(type, ref, contextMode, contextFlag = "--context lead") { if (type !== "env" && type !== "secret") return; if (contextMode === "lead") { throw new UsageError(`${contextFlag} is unavailable for sensitive ${type} assets.`, "INVALID_FLAG_VALUE"); } if (ref.fragment === undefined) return; warnOnce(`sensitive-fragment:${makeBundleRef(ref.bundle, ref.conceptId)}#${ref.fragment}`, `Fragment "#${ref.fragment}" was ignored: sensitive ${type} assets do not expose body fragments. Showing ${makeBundleRef(ref.bundle, ref.conceptId)} in full.`); } /** @internal Use akmShowUnified() for all external callers. */ export async function showLocal(input) { validateFragmentContextRequest(input); const parsed = parseBundleRef(input.ref); const config = loadConfig(); const allSources = resolveSourceEntries(input.stashDir); const searchSources = resolveSourcesForOrigin(parsed.bundle, allSources); const allSourceDirs = sourcePaths(searchSources); const resolution = input.readOnly ? await lookupBundleRefWithResolutionReadonly(parsed) : await lookupBundleRefWithResolution(parsed, true); // The index is not needed to find the asset: an absent, locked, corrupt or // still-building index just means no row. Only a refusal that names a remedy // (a newer layout, a file akm may not read) surfaces. rethrowIfTestIsolationError(resolution.indexError); if (resolution.indexError instanceof ConfigError) throw resolution.indexError; const fromFiles = !resolution.entry; const indexedEntry = resolution.entry ?? resolution.fileEntry; const assetPath = indexedEntry?.filePath; if (!indexedEntry && parsed.bundle && searchSources.length === 0) { const installCmd = `akm bundle add ${parsed.bundle}`; throw new NotFoundError(`Stash asset not found for ref: ${makeBundleRef(parsed.bundle, parsed.conceptId)}. ` + `Stash "${parsed.bundle}" is not installed. Run: ${installCmd}`); } if (!indexedEntry && !resolution.asset) { const unrecognized = findUnrecognizedScriptSource(parsed.conceptId, searchSources); if (unrecognized) { const displayExtension = unrecognized.extension || "no extension"; warn(`Script ref "${makeBundleRef(parsed.bundle, parsed.conceptId)}" has extension "${displayExtension}", which is outside the recognized set used for indexing (${[...SCRIPT_EXTENSIONS].join(", ")}); showing it as plain text.`); // asset-io: user-input the file the ref names, which no adapter lists, shown as plain text const fileCtx = buildFileContext(unrecognized.sourceRoot, unrecognized.path); const renderer = await getRenderer("script-source"); if (renderer) { const match = { type: "script", specificity: 0, renderer: "script-source" }; const renderCtx = buildRenderContext(fileCtx, match, allSourceDirs); const response = renderer.buildShowResponse(renderCtx); response.name = unrecognized.name; return response; } } } if (!indexedEntry || assetPath === undefined) { throw new NotFoundError(`Stash asset not found for ref: ${makeBundleRef(parsed.bundle, parsed.conceptId)}. ` + "Check the name with `akm search` or verify the asset exists in your stash."); } enforceSensitiveFragmentPolicy(indexedEntry.type, parsed, input.contextMode, input.contextFlag); // The entry is the one the bundle's adapter read for the ref; an index row with no entry behind it is stale. const owned = resolution.asset; if (!owned) throwIndexedPathNotFound(Object.assign(new Error("no entry"), { code: "ENOENT" }), input.ref); const source = findSourceForRow({ filePath: assetPath, bundleId: indexedEntry.bundleId }, allSources); const presentedName = indexedEntry.name; const opaqueFragmentSelector = parsed.fragment?.startsWith("akm-fragment-") === true; // Friendly heading selectors retain the source-live exact response contract. // Only resolve the indexed-safe revision when the selector itself is opaque, // or when the caller explicitly opts into indexed-safe contextual output. const indexedFragment = !fromFiles && parsed.fragment && (opaqueFragmentSelector || input.contextMode === "lead") ? readIndexedFragment(indexedEntry.itemRef, parsed.fragment, input.readOnly === true) : undefined; const indexedFragmentContent = opaqueFragmentSelector ? indexedFragment?.content : undefined; const presentation = presentationOf(owned, { type: indexedEntry.type, adapterId: indexedEntry.adapterId, ownsPresentation: indexedEntry.document?.ownsPresentation === true, }); let response; let markdown = false; try { if (assetPath === "" && indexedEntry.type === "secret") { const { secretShowResponse } = await import("../../output/renderers.js"); response = secretShowResponse(presentedName); } else if (presentation === "projection") { markdown = path.extname(assetPath).toLowerCase() === ".md"; response = buildIndexedProjectionResponse(indexedEntry, assetPath, owned.entry.content(), parsed.fragment, indexedFragmentContent); } else { const match = presentation; if (!match) { throw new UsageError(`Could not display asset "${makeBundleRef(parsed.bundle, parsed.conceptId)}" — unsupported file type or unrecognized layout`); } match.meta = { ...match.meta, name: presentedName }; const renderer = await getRenderer(match.renderer); if (!renderer) { throw new UsageError(`Renderer "${match.renderer}" not found for asset: ${makeBundleRef(parsed.bundle, parsed.conceptId)}`); } const renderBundle = indexedEntry.bundleId; const renderDefaultBundle = displayDefaultBundle(config.defaultBundle, source, renderBundle); const sourceStashDir = source?.path ?? indexedEntry.stashDir; if (!sourceStashDir) throwIndexedPathNotFound(Object.assign(new Error("no source root"), { code: "ENOENT" }), input.ref); const fileCtx = fileContextOf(owned, sourceStashDir); const renderCtx = buildRenderContext(fileCtx, match, allSourceDirs, renderBundle, renderDefaultBundle); response = renderer.buildShowResponse(renderCtx); markdown = match.renderer.endsWith("-md"); if (parsed.fragment !== undefined) { if (!markdown) { warn(`Fragment "#${parsed.fragment}" was ignored: ${makeBundleRef(parsed.bundle, parsed.conceptId)} is not a Markdown document, so heading fragments do not apply. Showing the whole asset.`); } else { applyMarkdownFragment(response, fileCtx.content(), parsed.fragment, presentedName, indexedFragmentContent); } } } // The outline is read from the bytes `#<slug>` resolves against, so every // listed slug selects its section even when the index is stale. if (markdown && parsed.fragment === undefined) { const toc = markdownToc(owned.entry.content()); if (toc.length > 0) response.toc = toc; } } catch (error) { throwIndexedPathNotFound(error, input.ref); } response.type = indexedEntry.type; response.name = indexedEntry.name; const defaultBundle = displayDefaultBundle(config.defaultBundle, source, indexedEntry.bundleId); const canonicalRef = displayRef({ conceptId: indexedEntry.conceptId, bundleId: indexedEntry.bundleId }, defaultBundle); if (parsed.fragment && indexedFragment) { const selectedFragmentId = indexedFragment.fragments[indexedFragment.ordinal].fragmentId; const selectedRef = `${canonicalRef}#${selectedFragmentId}`; const parentEstimatedTokens = typeof indexedEntry.document?.fileSize === "number" ? Math.round(indexedEntry.document.fileSize / 4) : Math.round(indexedFragment.parentChars / 4); Object.assign(response, { selectedRef, parentRef: canonicalRef, fragmentOrdinal: indexedFragment.ordinal + 1, fragmentCount: indexedFragment.count, startLine: indexedFragment.startLine, endLine: indexedFragment.endLine, ...(indexedFragment.previousFragmentId ? { previousRef: `${canonicalRef}#${indexedFragment.previousFragmentId}` } : {}), ...(indexedFragment.nextFragmentId ? { nextRef: `${canonicalRef}#${indexedFragment.nextFragmentId}` } : {}), fragmentChars: indexedFragment.fragmentChars, fragmentEstimatedTokens: Math.round(indexedFragment.fragmentChars / 4), parentChars: indexedFragment.parentChars, parentEstimatedTokens, contextMode: input.contextMode ?? "exact", contextTruncated: false, }); if (input.contextMode === "lead") { const contextMaxChars = input.maxContextChars ?? MARKDOWN_FRAGMENT_CONTEXT_DEFAULT_MAX_CHARS; const contextual = buildMarkdownLeadContext(indexedFragment.fragments, indexedFragment.ordinal, contextMaxChars); applyMarkdownResponsePayload(response, contextual.content); response.contextMaxChars = contextMaxChars; response.contextTruncated = contextual.truncated; } } else if (input.contextMode === "lead") { if (!fromFiles) throw new NotFoundError(`Indexed-safe fragment context is unavailable for ${input.ref}.`); warn(`Indexed-safe fragment context is unavailable for ${input.ref}: the search index has no row for it yet. Showing the exact section.`); } if (response.type === "workflow") response.action = buildWorkflowAction(canonicalRef); const editable = assetPath === "" ? source?.writable === true : isEditable(assetPath, config, allSources); // Evidence must describe the same revision as the rendered claim: ordinary // Markdown show is source-live, while indexed fragment show is a snapshot. let evidenceMetadata; if (["memory", "lesson", "knowledge"].includes(response.type)) { evidenceMetadata = indexedFragment ? indexedEntry.document : { name: presentedName, type: response.type }; if (!indexedFragment && evidenceMetadata) { const frontmatter = parseFrontmatter(owned.entry.content()).data; applyCuratedFrontmatter(evidenceMetadata, frontmatter); applyProvenanceFrontmatter(evidenceMetadata, frontmatter); } } const fullResponse = { ...response, ...(evidenceMetadata?.evidence ? { evidence: evidenceMetadata.evidence } : {}), ...(evidenceMetadata?.evidenceSources ? { evidenceSources: evidenceMetadata.evidenceSources } : {}), ...(evidenceMetadata?.provenance && (evidenceMetadata.evidence || evidenceMetadata.provenance.generatedAt || evidenceMetadata.provenance.sources) ? { provenance: evidenceMetadata.provenance } : {}), ref: canonicalRef, origin: source?.registryId ?? null, editable, ...(!editable ? { editHint: buildEditHint(canonicalRef) } : {}), ...(fromFiles ? {} : showLinks(indexedEntry.itemRef, defaultBundle, input.readOnly === true)), }; if (input.detail === "brief") { return buildBriefResponse(fullResponse, assetPath); } if (input.detail === "summary") { return buildSummaryResponse(fullResponse, assetPath); } return fullResponse; } /** 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. */ function readIndexedFragment(itemRef, fragment, readOnly) { try { return withIndexDb((db) => getIndexedMarkdownFragment(db, itemRef, fragment), { readOnly }); } catch (err) { rethrowIfTestIsolationError(err); rethrowIfDataDirUnreadable(err); return undefined; } } /** Refs listed per kind of declared link; `total` still counts them all (one memory is named by 1,437 others). */ const LINKS_PER_KIND = 10; /** * The declared links (#935) of an indexed asset, grouped by kind: outgoing in * authored order, incoming by ref, and unresolved tokens as authored. Empty * parts are omitted, and the field when nothing links either way. */ function showLinks(itemRef, defaultBundle, readOnly = false) { let rows; try { rows = withIndexDb((db) => readEntryLinks(db, itemRef), { readOnly }); } catch (err) { rethrowIfTestIsolationError(err); rethrowIfDataDirUnreadable(err); return {}; } const outgoing = []; const unresolved = []; for (const row of rows.outgoing) { if (row.conceptId === undefined) unresolved.push({ kind: row.kind, ref: row.raw ?? "" }); else outgoing.push({ kind: row.kind, ref: displayRefForConceptId(row.conceptId, row.bundleId, defaultBundle) }); } const incoming = rows.incoming.map((row) => ({ kind: row.kind, ref: displayRefForConceptId(row.conceptId ?? "", row.bundleId, defaultBundle), })); const links = { ...groupLinks("outgoing", outgoing), ...groupLinks("incoming", incoming), ...groupLinks("unresolved", unresolved), }; return Object.keys(links).length > 0 ? { links } : {}; } function groupLinks(part, rows) { if (rows.length === 0) return {}; const groups = {}; for (const kind of [...new Set(rows.map((row) => row.kind))].sort()) groups[kind] = { total: 0, refs: [] }; for (const { kind, ref } of rows) { const group = groups[kind]; group.total++; if (group.refs.length < LINKS_PER_KIND) group.refs.push(ref); } return { [part]: groups }; } function findUnrecognizedScriptSource(conceptId, sources) { const extension = path.extname(conceptId); if (SCRIPT_EXTENSIONS.has(extension.toLowerCase())) return undefined; for (const source of sources) { try { if (!adapterWrites(source, "script")) continue; const sourceRoot = source.path; if (sourceRoot === undefined) continue; // A script's ref is its path, so the candidate is the ref itself. const candidate = path.resolve(sourceRoot, conceptId); if (!isContainedResolvedPath(candidate, sourceRoot)) continue; // Only a file in a scripts directory is a script whose extension is the problem. const folders = toPosix(path.relative(sourceRoot, path.dirname(candidate))).split("/"); if (!folders.includes(stashDirFor("script") ?? "scripts")) continue; // asset-io: user-input the file the ref names, which no adapter lists, for the not-found hint const authoredStat = fs.lstatSync(candidate); if (!authoredStat.isFile() && !authoredStat.isSymbolicLink()) continue; const realCandidate = fs.realpathSync(candidate); // asset-io: user-input the same file if (!fs.statSync(realCandidate).isFile()) continue; const name = deriveCanonicalAssetNameFromStashRoot("script", sourceRoot, candidate) ?? conceptId; return { extension, name, path: realCandidate, sourceRoot: fs.realpathSync(sourceRoot) }; } catch { // Missing, unreadable, dangling, or otherwise unsafe paths remain normal // not-found misses; this diagnostic never widens physical ownership. } } return undefined; } /** * Minimal `show`: ref → indexer lookup → file contents. Used by callers that * just need the raw file (e.g. clone, write-source) and don't want the full * renderer graph. */ export async function showByRef(ref) { const parsed = parseBundleRef(ref); if (parsed.fragment !== undefined) { warn(`Fragment "#${parsed.fragment}" was ignored by raw show: ${ref}. Returning the whole file.`); } const entry = await lookupBundleRef(parsed); if (!entry) { throw new NotFoundError(`Asset not found for ref: ${makeBundleRef(parsed.bundle, parsed.conceptId)}`); } let body; try { const asset = findAsset(entry.itemRef); if (!asset) throw Object.assign(new Error("no entry"), { code: "ENOENT" }); body = asset.entry.content(); } catch (error) { throwIndexedPathNotFound(error, ref); } return { filePath: entry.filePath, body }; } function throwIndexedPathNotFound(error, ref) { const code = error?.code; if (code === "ENOENT" || code === "ENOTDIR" || code === "EACCES" || code === "EPERM") { throw new NotFoundError(`The indexed file for ${ref} is missing or unreadable. The search index may be stale.`, "ASSET_NOT_FOUND", "Run `akm index` to reconcile indexed paths, then retry `akm show`."); } throw error; } function buildIndexedProjectionResponse(entry, assetPath, raw, fragment, indexedFragmentContent) { const isMarkdown = path.extname(assetPath).toLowerCase() === ".md"; if (fragment !== undefined && !isMarkdown) { warn(`Fragment "#${fragment}" was ignored: ${entry.conceptId} is not a Markdown document, so heading fragments do not apply. Showing the whole asset.`); } const parsed = parseFrontmatter(raw); const content = fragment !== undefined && isMarkdown ? (indexedFragmentContent ?? requireMarkdownSection(raw, fragment, entry.name).content) : parsed.content; const description = entry.document?.description ?? asNonEmptyString(parsed.data.description); const tags = entry.document?.tags ?? (Array.isArray(parsed.data.tags) ? parsed.data.tags.filter((tag) => typeof tag === "string" && tag.trim().length > 0) : undefined); return { type: entry.type, name: entry.name, path: assetPath, action: "Read the content below.", content, ...(description ? { description } : {}), ...(tags && tags.length > 0 ? { tags } : {}), }; } function applyMarkdownFragment(response, raw, fragment, name, indexedFragmentContent) { const section = indexedFragmentContent ?? requireMarkdownSection(raw, fragment, name).content; if (response.template !== undefined) response.template = section; else if (response.prompt !== undefined) response.prompt = section; else response.content = section; } function applyMarkdownResponsePayload(response, content) { if (response.template !== undefined) response.template = content; else if (response.prompt !== undefined) response.prompt = content; else response.content = content; } const SHOW_OUTLINE_HINT = "Run `akm show <ref> --outline` for the document's outline (`toc`, no body), then `akm show <ref>#<slug>` for one section."; function requireMarkdownSection(content, fragment, name) { const section = extractSection(content, fragment); if (section) return section; const indexed = projectMarkdownFragmentContent(content); const safeFragment = indexed ? fragmentForSelector(indexed, fragment) : undefined; if (safeFragment) { return { content: safeFragment.text, startLine: safeFragment.startLine, endLine: safeFragment.endLine }; } const available = markdownFragmentSlugs(content); throw new NotFoundError(`Fragment "#${fragment}" not found in ${name}.` + (available.length > 0 ? ` Available fragments: ${available.map((slug) => `#${slug}`).join(", ")}.` : ""), "ASSET_NOT_FOUND", SHOW_OUTLINE_HINT); } /** * Build a reduced brief response from a full ShowResponse. * * Keeps routing/identification fields while omitting content/template/prompt. */ function buildBriefResponse(full, assetPath) { const summary = buildSummaryResponse(full, assetPath); return { type: summary.type, name: summary.name, path: summary.path, ...(summary.ref ? { ref: summary.ref } : {}), ...(summary.description ? { description: summary.description } : {}), ...(summary.action ? { action: summary.action } : {}), ...(full.toc ? { toc: full.toc } : {}), ...(summary.run ? { run: summary.run } : {}), ...(summary.origin !== undefined ? { origin: summary.origin } : {}), ...(full.editable !== undefined ? { editable: full.editable } : {}), ...(full.editHint ? { editHint: full.editHint } : {}), ...fragmentResponseProjection(full), }; } /** * Build a compact summary response from a full ShowResponse. * * Strips content/template/prompt and returns only metadata fields: * type, name, path, description, tags, parameters, action. * Enriches description and tags from rendered content when available. * * The resulting JSON should be under 200 tokens. */ function buildSummaryResponse(full, assetPath) { let description = full.description; const tags = full.tags; if (assetPath) { const textContent = full.content ?? full.template ?? full.prompt; if (textContent && !description) { const parsed = parseFrontmatter(textContent); description = asNonEmptyString(parsed.data.description); } } const summary = { type: full.type, name: full.name, path: full.path, ...(full.ref ? { ref: full.ref } : {}), ...(description ? { description } : {}), ...(tags && tags.length > 0 ? { tags } : {}), ...(full.parameters ? { parameters: full.parameters } : {}), ...(full.workflowTitle ? { workflowTitle: full.workflowTitle } : {}), ...(full.action ? { action: full.action } : {}), ...(full.run ? { run: full.run } : {}), ...(full.origin !== undefined ? { origin: full.origin } : {}), ...(full.editable !== undefined ? { editable: full.editable } : {}), ...(full.editHint ? { editHint: full.editHint } : {}), ...fragmentResponseProjection(full), }; return summary; } function fragmentResponseProjection(full) { if (!full.selectedRef) return {}; return { selectedRef: full.selectedRef, parentRef: full.parentRef, fragmentOrdinal: full.fragmentOrdinal, fragmentCount: full.fragmentCount, startLine: full.startLine, endLine: full.endLine, previousRef: full.previousRef, nextRef: full.nextRef, fragmentChars: full.fragmentChars, fragmentEstimatedTokens: full.fragmentEstimatedTokens, parentChars: full.parentChars, parentEstimatedTokens: full.parentEstimatedTokens, contextMode: full.contextMode, contextMaxChars: full.contextMaxChars, contextTruncated: full.contextTruncated, }; }