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
240 lines (239 loc) • 11.9 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/.
/**
* `akm rules`: the rules that apply here, in full. Read from the files of the
* bundles the selection names (never the index), recognized by the same adapter
* and filtered by the same project and scope functions search uses, so it works
* with no index and a new rule applies at once. A project that lists its `rules` gets exactly those, in order,
* from any enabled bundle. Records one `rules` usage event.
*/
import path from "node:path";
import { getStringArg, PROJECT_ARG } from "../../cli/parse-args.js";
import { defineJsonCommand, output, parseAllFlagValues } from "../../cli/shared.js";
import { stashDirFor } from "../../core/asset/asset-placement.js";
import { parseFrontmatter } from "../../core/asset/frontmatter.js";
import { displayRefForConceptId } from "../../core/asset/resolve-ref.js";
import { adapterWrites } from "../../core/assets/gate.js";
import { listAssets, lookupAsset } from "../../core/assets/read.js";
import { indexAsset } from "../../core/assets/type.js";
import { compareCodePoints } from "../../core/common.js";
import { loadConfig } from "../../core/config/config.js";
import { NotFoundError } from "../../core/errors.js";
import { resolveProject } from "../../core/projects.js";
import { withStateDbTelemetry } from "../../core/state-db.js";
import { warnOnce } from "../../core/warn.js";
import { isProposedQuality } from "../../indexer/passes/entry-normalize.js";
import { scopeMatchesFilters } from "../../indexer/passes/metadata.js";
import { resolveReadSources } from "../../indexer/read-preflight.js";
import { indexRowEntry } from "../../indexer/scan/drain-dir.js";
import { appliesUnder } from "../../indexer/search/db-search.js";
import { insertUsageEvent, resolveUsageEventSource } from "../../indexer/usage/usage-events.js";
import { registerMdRenderer } from "../../output/render-registry.js";
import { formatRulesText } from "../../output/text/rules.js";
import { TELEMETRY_BUSY_TIMEOUT_MS } from "../../storage/repositories/index-db.js";
import { assertNamedSourceExists, narrowSourcesToName, normalizeScopeFilters, parseScopeFilterFlags, parseSearchSource, } from "./search.js";
import { fromValues, projectContext, scopeFilterArg, stampedProject, withProjectDefaults } from "./search-cli.js";
/** `--from` values that select a search scope, not a bundle: they do not apply to rules. */
const SCOPE_KEYWORDS = ["local", "registry", "all"];
/** The bundle names in a `--from` value; scope keywords are ignored with one warning. `undefined`: none left. */
function bundleNames(from) {
if (from === undefined)
return undefined;
const parsed = parseSearchSource(from);
const given = Array.isArray(parsed) ? parsed : [parsed];
const names = given.filter((name) => !SCOPE_KEYWORDS.includes(name));
if (names.length < given.length) {
warnOnce("rules:from-keyword", "`akm rules` reads named bundles: --from local, registry and all are ignored.");
}
return names.length > 0 ? names : undefined;
}
const RULES_PREFIX = `${stashDirFor("rule")}/`;
/** What the asset's adapter says about it now, with nothing recorded; undefined when the adapter abstains on it. */
function describeNow(asset) {
try {
return indexAsset(asset, { persist: false });
}
catch (error) {
if (error instanceof NotFoundError)
return undefined;
throw error;
}
}
/** The adapter's description of a rule asset now; undefined when the asset is not a rule. */
function ruleEntry(asset) {
// Read as the adapter describes it now, so a rule edited since the last index applies as written.
const document = describeNow(asset);
if (document?.type !== "rule")
return undefined;
return indexRowEntry(document, path.basename(asset.conceptId));
}
function defaultBundleOf(config, sources) {
return config.defaultBundle ?? sources.find((source) => source.isDefault)?.bundleId;
}
function foundRule(asset, entry, defaultBundle) {
const named = entry.frontmatter?.project;
return {
ref: displayRefForConceptId(asset.conceptId, asset.bundle, defaultBundle),
durableRef: `${asset.bundle}//${asset.conceptId}`,
...(entry.description ? { description: entry.description } : {}),
...(named?.length ? { project: named.length === 1 ? named[0] : named } : {}),
content: parseFrontmatter(asset.entry.content()).content.trim(),
shared: !named?.length,
};
}
/** What a listed ref loads: its asset and description, or why it loads nothing. */
function checkListed(ref) {
const asset = lookupAsset(ref);
if (!asset)
return { why: "no enabled bundle holds it" };
const entry = asset.conceptId.startsWith(RULES_PREFIX) ? ruleEntry(asset) : undefined;
if (!entry)
return { why: "it is not a rule (a file in a bundle's top-level rules/ folder)" };
if (isProposedQuality(entry.quality))
return { why: "it is proposed; it loads once accepted" };
return { asset, entry };
}
/** The project's listed rules, in list order, each ref resolved as `akm show` resolves it; one naming no loadable rule warns and is skipped. */
function listedRules(project, defaultBundle) {
const found = new Map();
for (const ref of project.rules) {
const checked = checkListed(ref);
if ("why" in checked) {
warnOnce(`rules:listed:${project.name}:${ref}`, `Skipping rule "${ref}" listed by project "${project.name}": ${checked.why}.`);
continue;
}
if (!found.has(checked.asset.ref))
found.set(checked.asset.ref, foundRule(checked.asset, checked.entry, defaultBundle));
}
return [...found.values()];
}
/** The rules a call loads, before anything is recorded. */
function selectRules(input) {
const config = loadConfig();
const project = resolveProject(config, { project: input.project, cwd: input.cwd });
const { filters, view } = withProjectDefaults(project, {
source: input.from,
filters: parseScopeFilterFlags(input.filters ?? [], "--filter"),
});
const sources = resolveReadSources(undefined, config).sources;
const defaultBundle = defaultBundleOf(config, sources);
let bundles;
let found;
if (project?.rules && input.from === undefined && !input.filters?.length) {
found = listedRules({ ...project, rules: project.rules }, defaultBundle);
bundles = [...new Set(found.map((r) => r.durableRef.split("//")[0]))];
}
else {
const names = bundleNames(input.from) ?? bundleNames(project?.from);
for (const name of names ?? [])
assertNamedSourceExists(config, name);
const wanted = names
? names.flatMap((name) => narrowSourcesToName(sources, [name]))
: [
...sources.filter((source) => source.isDefault),
...(project?.write.bundle ? narrowSourcesToName(sources, [project.write.bundle]) : []),
];
const scope = normalizeScopeFilters(filters);
const context = projectContext(project, filters);
bundles = [];
found = [];
for (const source of new Set(wanted)) {
const bundleId = source.bundleId;
if (source.unresolved || !adapterWrites(bundleId, "rule"))
continue;
bundles.push(bundleId);
// Only the rules folder decides a rule (as the walk always read it), so only its assets are described.
for (const asset of listAssets({ bundle: bundleId }).filter(({ conceptId }) => conceptId.startsWith(RULES_PREFIX))) {
const entry = ruleEntry(asset);
if (!entry || isProposedQuality(entry.quality) || !appliesUnder(entry, context))
continue;
if (scope && !scopeMatchesFilters(entry, scope))
continue;
found.push(foundRule(asset, entry, defaultBundle));
}
}
found.sort((a, b) => Number(a.shared) - Number(b.shared) || compareCodePoints(a.ref, b.ref));
}
return { project, view, bundles, found };
}
export function akmRules(input) {
const { project, view, bundles, found } = selectRules(input);
const rules = found.map(({ shared: _shared, durableRef: _durableRef, ...rule }) => rule);
recordRulesUsage({
project: stampedProject(project),
bundles,
refs: found.map((rule) => rule.durableRef),
chars: found.reduce((sum, rule) => sum + rule.content.length, 0),
eventSource: input.eventSource ?? resolveUsageEventSource(),
});
return { schemaVersion: 1, ...(view ? { project: view } : {}), bundles, rules };
}
/**
* What a project's rules setting can choose from and where it stands, for a host's picker; records no usage event.
* `available`: every loadable rule of the enabled bundles, as `akm rules` prints its ref. With a `project`:
* `listed`, each ref of its `rules` as written, with the rule it resolves to or why it loads nothing, and `applies`,
* the rules `akm rules` loads for it now.
*/
export function ruleChoices(input) {
const config = loadConfig();
const defaultBundle = defaultBundleOf(config, resolveReadSources(undefined, config).sources);
const described = (asset, entry) => ({
ref: displayRefForConceptId(asset.conceptId, asset.bundle, defaultBundle),
...(entry.description ? { description: entry.description } : {}),
});
const available = listAssets().flatMap((asset) => {
const entry = asset.conceptId.startsWith(RULES_PREFIX) && adapterWrites(asset.bundle, "rule") ? ruleEntry(asset) : undefined;
return entry && !isProposedQuality(entry.quality) ? [described(asset, entry)] : [];
});
const name = input.project?.trim();
if (!name)
return { available, listed: [], applies: [] };
const project = resolveProject(config, { project: name });
const listed = (project?.rules ?? []).map((ref) => {
const checked = checkListed(ref);
if ("why" in checked)
return { ref, problem: checked.why };
const { ref: resolved, ...rest } = described(checked.asset, checked.entry);
return { ref, resolved, ...rest };
});
const applies = selectRules({ project: name }).found.map(({ ref, description }) => ({
ref,
...(description ? { description } : {}),
}));
return { available, listed, applies };
}
/** One `rules` usage event per call: what was loaded, not a search or a show. */
function recordRulesUsage(load) {
const { eventSource, ...metadata } = load;
try {
withStateDbTelemetry((stateDb) => {
insertUsageEvent(stateDb, { event_type: "rules", metadata: JSON.stringify(metadata), source: eventSource });
}, TELEMETRY_BUSY_TIMEOUT_MS);
}
catch {
/* telemetry is fire-and-forget */
}
}
export const rulesCommand = defineJsonCommand({
meta: {
name: "rules",
description: "The rules that apply here, in full: the project's and the shared ones, read from the files of the project's bundles (its `from`, else the default bundle and its write bundle)",
},
args: {
from: {
type: "string",
description: "Bundle name (repeatable); default: the project's from, else the default bundle",
},
filter: scopeFilterArg,
...PROJECT_ARG,
},
async run({ args }) {
output("rules", akmRules({
from: fromValues(args.from),
filters: parseAllFlagValues("--filter"),
project: getStringArg(args, "project"),
}));
},
});
registerMdRenderer("rules", (result) => formatRulesText(result));