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
260 lines (259 loc) • 13.6 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/.
/** Assets: search, one asset with its feedback and links, its history, what is related, what improve did with it. */
import path from "node:path";
import { akmRelated } from "../commands/read/related.js";
import { akmSearch, narrowSourcesToName, normalizeScopeFilters, parseBeliefFilterMode } from "../commands/read/search.js";
import { akmShowUnified } from "../commands/read/show.js";
import { parseBundleRef } from "../core/asset/asset-ref.js";
import { readFrontmatter } from "../core/asset/frontmatter-edit.js";
import { parseMarkdownToc, uniqueHeadingSlugs } from "../core/asset/markdown.js";
import { markdownLinkTargets } from "../core/asset/markdown-link-targets.js";
import { protectedTypeOf } from "../core/assets/files.js";
import { assetType } from "../core/assets/type.js";
import { loadConfig } from "../core/config/config.js";
import { defaultExcludedTypes } from "../core/config/schema/search.js";
import { resolveRefOwner } from "../core/env-secret-ref.js";
import { UsageError } from "../core/errors.js";
import { includedTypes, includesProposed } from "../core/include.js";
import { projectView, resolveProject } from "../core/projects.js";
import { inspectWriteTarget } from "../core/write-source.js";
import { readUsableIndex } from "../indexer/index-readiness.js";
import { resolveReadSources } from "../indexer/read-preflight.js";
import { countBrowseEntries } from "../indexer/search/db-search.js";
import { findSourceForPath, resolveSourceEntries } from "../indexer/search/search-source.js";
import { getEntryIdByFilePath, getItemRefById } from "../storage/repositories/index-entries-repository.js";
import { countFeedbackBySignal, listFeedbackEventRows } from "../storage/repositories/metrics-repository.js";
import { assetImprove } from "./asset-improve.js";
import { bundleFileLocation, listBundleFiles } from "./bundle-files.js";
import { bundleWriteBlockers, fileActions } from "./file-actions.js";
import { readFileRevision, readRecentCommits } from "./git-read.js";
import { capSide, clampLimit, DIFF_SIDE_MAX_CHARS, durableRefForPath, withReadonlyStateDb } from "./readers.js";
export { ruleChoices } from "../commands/read/rules.js";
export { copyEntry } from "./copy-entry.js";
export { graph } from "./graph.js";
export { searchMisses } from "./misses.js";
export { movedLinks, updateMovedLinks } from "./moved-links.js";
/** Browse keeps its contract that blank scope values are omitted (an empty filter value would mean "without the key"). */
function blanksOmitted(scope) {
if (!scope)
return undefined;
const out = Object.create(null);
for (const [key, given] of Object.entries(scope)) {
const kept = [given ?? []].flat().filter((value) => typeof value === "string" && value.trim());
if (kept.length > 0)
out[key] = kept;
}
return out;
}
export async function search(input) {
const type = input.type || undefined;
const bundle = input.bundle || undefined;
const project = input.project?.trim() ? resolveProject(loadConfig(), { project: input.project.trim() }) : undefined;
const scope = normalizeScopeFilters(blanksOmitted(input.scope));
const filters = scope && Object.keys(scope).length > 0 ? scope : project?.filters;
const from = bundle ?? project?.from;
const result = await akmSearch({
query: (input.q ?? "").trim(),
type,
limit: clampLimit(input.limit, 20),
// `--from <name>` narrows to one configured bundle; absent means every local bundle, as `akm search` does.
source: from ?? "local",
belief: parseBeliefFilterMode(input.belief || "current"),
filters,
prefer: project?.prefer,
include: input.include ?? project?.include,
readOnly: true,
});
return project
? { ...result, project: projectView({ ...project, from, filters, include: input.include ?? project.include }) }
: result;
}
/**
* What a project resolves to, and what its bundles hold: the read bundles it selects (its `from`, else every local
* bundle), the write bundle, and per bundle how many assets a browse lists (`total`) and how many of those satisfy the
* project's `filters` (`eligible`), with its `include` exclusions relaxed, counted over the whole index. `prefer` only orders results; it never changes a count.
* Counts are `null` where the bundle cannot be read or nothing is indexed.
*/
export function projectOverview(input) {
const name = (input.project ?? "").trim();
if (!name)
throw new UsageError("A project name is required.", "MISSING_REQUIRED_ARGUMENT");
const config = loadConfig();
const project = resolveProject(config, { project: name });
if (!project)
throw new UsageError(`"${name}" selects no project.`, "INVALID_FLAG_VALUE");
const local = resolveReadSources(undefined, config).sources;
const selected = project.from === undefined
? local.map((source) => ({ name: source.registryId ?? source.path ?? source.bundleId, source }))
: [project.from].flat().map((from) => ({ name: from, source: narrowSourcesToName(local, [from])[0] }));
const readable = selected.flatMap((bundle) => (bundle.source ? [bundle.source] : []));
const counts = readable.length > 0
? readUsableIndex((db) => countBrowseEntries(db, readable, project.filters, defaultExcludedTypes(config).filter((type) => !includedTypes(project.include).includes(type)), includesProposed(project.include)), undefined)
: undefined;
// Where akm would write for this project, and the sentence its write path refuses with (null when it would accept a
// write); a write bundle that does not resolve is shown by the name it was given.
const write = inspectWriteTarget(config, project.write.bundle);
const writeName = write.name ?? project.write.bundle ?? null;
return {
project: { ...projectView(project), write: project.write },
fromImplicit: project.from === undefined,
preferImplicit: config.projects?.[name]?.prefer === undefined,
writeBundle: { name: writeName, implicit: project.write.bundle === undefined, writeBlocker: write.blocker },
bundles: selected.map(({ name: bundle, source }) => {
const entry = Object.hasOwn(config.bundles ?? {}, bundle) ? config.bundles?.[bundle] : undefined;
const found = source ? counts?.[readable.indexOf(source)] : undefined;
return {
name: bundle,
configured: entry !== undefined,
enabled: entry === undefined ? false : entry.enabled !== false,
readable: source !== undefined,
writable: source?.writable ?? false,
type: source?.type ?? entry?.type ?? null,
total: found?.total ?? null,
eligible: found?.eligible ?? null,
};
}),
};
}
function feedbackFor(durableRef) {
const empty = { counts: {}, history: [] };
if (!durableRef)
return empty;
return withReadonlyStateDb((db) => {
const history = listFeedbackEventRows(db, durableRef, 50).map((row) => {
let detail = {};
try {
detail = row.metadata ? JSON.parse(row.metadata) : {};
}
catch {
// Metadata is optional.
}
return {
// `created_at` is SQLite's `YYYY-MM-DD HH:MM:SS` in UTC.
at: new Date(`${row.created_at.replace(" ", "T")}Z`).toISOString(),
signal: row.signal,
source: row.source,
...(typeof detail.reason === "string" ? { reason: detail.reason } : {}),
...(Array.isArray(detail.tags) ? { tags: detail.tags } : {}),
};
});
return { counts: countFeedbackBySignal(db, durableRef), history };
}, empty);
}
export async function show(input) {
const ref = (input.ref ?? "").trim();
if (!ref)
throw new UsageError("An asset ref is required.", "MISSING_REQUIRED_ARGUMENT");
const owner = resolveRefOwner(ref);
const type = owner ? assetType(owner) : undefined;
if (type === "env" || type === "secret") {
// Values never leave the machine's own files through the UI, whatever the renderers would show.
return { redacted: true, type, ref, note: "Env and secret values are never shown in the UI." };
}
const shown = await akmShowUnified({ ref, readOnly: true });
const durableRef = shown.path ? durableRefForPath(shown.path) : null;
const content = shown.content ?? "";
// Where the body starts in the text an asset is read from (content, a command's template, an agent's prompt).
const bodyStart = readFrontmatter(shown.content || shown.template || shown.prompt || "").bodyStart;
const headings = parseMarkdownToc(content).headings;
const slugs = uniqueHeadingSlugs(headings);
const links = {};
if (shown.path && durableRef) {
const shownDir = path.dirname(shown.path);
const owner = parseBundleRef(durableRef).bundle;
readUsableIndex((db) => {
for (const raw of markdownLinkTargets(content, false)) {
if (/^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i.test(raw))
continue;
const [file, fragment] = raw.split("#", 2);
if (!file?.toLowerCase().endsWith(".md") || file.startsWith("/"))
continue;
let decoded;
try {
decoded = decodeURIComponent(file);
}
catch {
continue;
}
const id = getEntryIdByFilePath(db, path.resolve(shownDir, decoded));
const target = id === undefined ? undefined : getItemRefById(db, id);
if (target && parseBundleRef(target).bundle === owner)
links[raw] = target + (fragment ? `#${fragment}` : "");
}
}, undefined);
}
const location = shown.path ? bundleFileLocation(shown.path) : null;
return {
redacted: false,
durableRef,
bundle: durableRef ? parseBundleRef(durableRef).bundle : null,
asset: shown,
location,
bodyStart,
// What akm accepts doing to this asset's file, and why not: the verdicts the file listing gives the same entry.
actions: location && shown.path
? fileActions({
bundle: location.bundle,
relative: location.path,
kind: "file",
absolute: shown.path,
protected: protectedTypeOf(location.path) !== undefined,
assets: durableRef ? [{ ref: durableRef, type: shown.type }] : [],
}, bundleWriteBlockers(loadConfig(), location.bundle))
: null,
feedback: feedbackFor(durableRef),
feedbackRequireReason: loadConfig().feedback?.requireReason !== false,
links,
headings: headings.map((heading, i) => ({ ...heading, slug: slugs[i] })),
};
}
export async function history(input) {
const selected = await show(input);
if (selected.redacted || !selected.asset?.path)
return { available: false, commits: [] };
const source = findSourceForPath(selected.asset.path, resolveSourceEntries(undefined, loadConfig()));
if (source?.path === undefined)
return { available: false, commits: [] };
const file = path.relative(source.path, selected.asset.path).split(path.sep).join("/");
if (file.startsWith("../") || path.isAbsolute(file))
throw new UsageError("Asset path is outside its bundle.");
const read = await readRecentCommits(source.path, clampLimit(input.limit, 30), file);
const commits = read?.commits ?? null;
const revision = input.revision;
if (revision && !commits?.some((commit) => commit.sha === revision))
throw new UsageError("Choose a revision from this asset's history.");
const diff = revision ? await readFileRevision(source.path, file, revision) : null;
const before = capSide(diff?.before ?? null);
const after = capSide(diff?.after ?? null);
return {
available: commits !== null,
commits: commits ?? [],
...(read?.error ? { error: read.error } : {}),
...(diff
? {
diff: {
before: before.text,
after: after.text,
unified: diff.unified.slice(0, DIFF_SIDE_MAX_CHARS),
truncated: before.truncated || after.truncated || diff.unified.length > DIFF_SIDE_MAX_CHARS,
},
}
: {}),
};
}
export async function related(input) {
const scope = input.scope ?? "all";
if (scope !== "all" && scope !== "bundle")
throw new UsageError("scope must be all or bundle.");
const ref = (input.ref ?? "").trim();
if (!ref)
throw new UsageError("An asset ref is required.", "MISSING_REQUIRED_ARGUMENT");
return akmRelated(ref, scope);
}
/** What improve proposed for one asset, how it was decided, and how the asset has been used since. */
export const improvement = assetImprove;
export function bundleFiles(input) {
return listBundleFiles(input.bundle ?? "", input.path ?? "", input.hidden === true);
}