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
208 lines (207 loc) • 10.7 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/.
import fs from "node:fs";
import path from "node:path";
import { documentStashDirFor, refForFile, typeForStashDir } from "../../core/asset/asset-placement.js";
import { displayRefForConceptId } from "../../core/asset/resolve-ref.js";
import { lintAssetText, lintBundle, lintLooseFile } from "../../core/assets/gate.js";
import { storeFindings } from "../../core/assets/validate.js";
import { bundleSourceAt } from "../../core/bundle-at-dir.js";
import { resolveStashDir, samePath } from "../../core/common.js";
import { loadConfig, primaryBundlePath } from "../../core/config/config.js";
import { bundleAtDir } from "../../core/config/config-sources.js";
import { UsageError } from "../../core/errors.js";
import { bundleLintSkip } from "../../core/lint/bundle-skip.js";
import { diagnosticToLintIssue } from "../../core/lint/diagnostics.js";
import { readRecordedMoves } from "../../core/lint/moved-refs.js";
import { isAdvisoryLintIssue, LINT_RULES, } from "../../core/lint/types.js";
import { warn } from "../../core/warn.js";
import { resolveSourceEntries } from "../../indexer/search/search-source.js";
import { trackedSecretIssues } from "./tracked-secrets.js";
/** The bundle at `stashRoot` among the configured `sources`, under the id refs name it by (its path when none is configured there). */
function lintBundleOf(adapterId, stashRoot, sources) {
const source = sources.find((s) => s.path !== undefined && samePath(s.path, stashRoot));
return { name: source?.bundleId ?? stashRoot, path: stashRoot, adapterId };
}
/**
* What the configured keyring and vault bundles report about their stores (an entry akm cannot list, two entries of one
* name). A finding names its asset by ref, since no file holds it.
*/
async function addStoreFindings(found, sources, cfg, options) {
// Secrets are the stores' only type: a `--type` for another one leaves them out.
if (options.stores !== true || (options.typeFilter !== undefined && options.typeFilter !== "secrets"))
return;
const ctx = { config: cfg, readMoves: options.readMoves ?? readRecordedMoves };
for (const diagnostic of await storeFindings(sources, ctx)) {
const issue = { ...diagnosticToLintIssue(diagnostic), ref: diagnostic.ref };
(isAdvisoryLintIssue(issue) ? found.warnings : found.flagged).push(issue);
}
}
/** The configured bundle root (or `--dir`) that contains `file`, deepest first; undefined when `file` is outside every bundle. */
function containingBundleRoot(file, roots) {
const real = (p) => fs.realpathSync(p);
const target = real(file);
return (roots
// asset-io: bundle-root root probe
.filter((root) => fs.existsSync(root))
.filter((root) => {
const rel = path.relative(real(root), target);
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
})
.sort((a, b) => b.length - a.length)[0]);
}
/**
* `akm lint <file>`: the bundle that holds the file lints just that file (its adapter's findings narrowed to it), and a
* file outside every bundle is read as the akm document type `--type` names.
*/
async function lintFile(file, options, cfg) {
if (options.pruneDanglingEdges) {
throw new UsageError("lint: --prune-dangling-edges applies to a bundle, not a single file.", "INVALID_FLAG_VALUE");
}
// asset-io: user-input the file named
const stat = fs.statSync(file, { throwIfNoEntry: false });
if (!stat)
throw new UsageError(`lint: "${file}" does not exist.`, "INVALID_FLAG_VALUE");
if (stat.isDirectory()) {
throw new UsageError(`lint: "${file}" is a directory; use --dir to lint a bundle.`, "INVALID_FLAG_VALUE");
}
const absFile = fs.realpathSync(file);
// A machine with no bundle at all can still lint a loose file, so a missing primary bundle is not an error here.
let primary = options.dir ?? primaryBundlePath(cfg);
if (!primary) {
try {
primary = resolveStashDir();
}
catch {
primary = undefined;
}
}
const root = containingBundleRoot(absFile, [
...(options.dir ? [options.dir] : []),
...(primary ? resolveSourceEntries(primary, cfg).flatMap(({ path }) => (path === undefined ? [] : [path])) : []),
]);
if (root === undefined) {
return finishLint(lintLooseFile({ given: file, real: absFile }, cfg, options), cfg, options);
}
const sources = resolveSourceEntries(root, cfg);
const found = await lintBundle({
bundle: lintBundleOf(bundleSourceAt(root, cfg).adapterId, root, sources),
extraStashRoots: sources
.map((source) => source.path)
.filter((p) => p !== undefined)
// asset-io: bundle-root root probe
.filter((p) => !samePath(p, root) && fs.existsSync(p)),
sources,
cfg,
options,
file: { given: file, real: absFile },
});
return finishLint(found, cfg, options, root);
}
/**
* The findings for `content` as the text of the asset at `relPath` of the akm bundle at `root`, by the checks `akm lint`
* runs on that file. Nothing is read from or written to the file. `subdir` is the stash folder of the asset's type.
*/
export function lintDocumentText(input) {
const cfg = input.config ?? loadConfig();
const { root } = input;
const sinks = lintAssetText({ ...input, cfg, readMoves: input.readMoves ?? readRecordedMoves });
const { flagged, warnings } = finishLint(sinks, cfg, {}, root);
return { flagged, warnings };
}
/** The ref of an asset of the bundle at `root` by its bundle-relative `file`; undefined when `file` is not an asset path. */
function refOfFile(root, file, cfg) {
const type = typeForStashDir(file.split(/[\\/]/)[0] ?? "");
const conceptId = type ? refForFile(type, root, path.join(root, file)) : undefined;
if (conceptId === undefined)
return undefined;
const bundleId = bundleAtDir(cfg, root);
return displayRefForConceptId(conceptId, bundleId, cfg.defaultBundle);
}
/**
* Turn what a pass found into the result: drop what the bundle's `lint.skip`
* names, give each finding its asset ref, narrow to `--rule`, and count the
* flagged findings per rule.
*/
function finishLint(found, cfg, options, root) {
const skippedRules = root ? bundleLintSkip(cfg, root) : () => [];
let rule = options.rule;
if (rule !== undefined && !LINT_RULES.includes(rule)) {
warn(`Warning: lint --rule "${rule}" is not a lint rule — valid rules: ${LINT_RULES.join(", ")}. Showing every rule.`);
rule = undefined;
}
const keep = (issue) => (rule === undefined || issue.issue === rule) && !skippedRules(issue.file).includes(issue.issue);
const fixed = found.fixed.filter((issue) => rule === undefined || issue.issue === rule);
const flagged = found.flagged.filter(keep);
const warnings = found.warnings.filter(keep);
if (root) {
for (const issue of [...fixed, ...flagged, ...warnings])
issue.ref ??= refOfFile(root, issue.file, cfg);
}
const byRule = {};
const assetsByRule = new Map();
for (const issue of flagged) {
const assets = (assetsByRule.get(issue.issue) ?? new Set()).add(issue.file);
assetsByRule.set(issue.issue, assets);
byRule[issue.issue] = { findings: (byRule[issue.issue]?.findings ?? 0) + 1, assets: assets.size };
}
return {
ok: true,
fixed,
flagged,
warnings,
summary: { fixed: fixed.length, flagged: flagged.length, warnings: warnings.length },
byRule,
...(rule === undefined ? {} : { rule }),
};
}
/**
* Lint the resolved bundle at `options.dir` (default: the primary bundle) through its adapter's `lint`: one pipeline
* for every adapter. `async` because `BundleAdapter.validate()` is async by interface contract
* (`core/adapter/bundle-adapter.ts`); every existing caller already runs inside an async context
* (`commands/agent/contribute-cli.ts`, `commands/improve/preparation.ts`) or is a test that can `await` it.
*/
export async function akmLint(options = {}) {
if (options.rule !== undefined && (options.fix || options.pruneDanglingEdges || options.fixMovedRefs)) {
throw new UsageError("lint: --rule lists findings; run it without --fix or --prune-dangling-edges.", "INVALID_FLAG_VALUE");
}
// Fail closed on a mistyped invocation: a nonexistent --dir would walk
// nothing and report a clean `ok:true, flagged:0`, silently passing scripted
// --fail-on-flagged gates.
// asset-io: user-input --dir
if (options.dir !== undefined && !fs.statSync(options.dir, { throwIfNoEntry: false })?.isDirectory()) {
throw new UsageError(`lint: --dir "${options.dir}" is not a directory.`, "INVALID_FLAG_VALUE");
}
// Collect secondary stash roots from configured filesystem sources so that
// cross-stash refs (e.g. referencing assets in dimm-city/agent-stash) are
// not falsely flagged as missing-ref.
const cfg = options.config ?? loadConfig();
// `--type` names a type or its folder; the sweep and the single-file path work on the folder.
if (options.typeFilter)
options = { ...options, typeFilter: documentStashDirFor(options.typeFilter) ?? options.typeFilter };
if (options.file !== undefined)
return lintFile(options.file, options, cfg);
// The primary stash is the defaultBundle's path.
const stashRoot = options.dir ?? primaryBundlePath(cfg) ?? resolveStashDir();
const sources = resolveSourceEntries(stashRoot, cfg);
const bundle = lintBundleOf(sources.find((source) => source.path !== undefined && samePath(source.path, stashRoot))?.adapterId, stashRoot, sources);
// The adapter's checks and the sweep both ask about moved refs: the recorded moves are read once between them.
const readMoves = options.readMoves ?? readRecordedMoves;
let moves;
options = { ...options, readMoves: () => (moves ??= readMoves()) };
const found = await lintBundle({
bundle,
extraStashRoots: sources
.map((source) => source.path)
.filter((p) => p !== undefined)
// asset-io: bundle-root root probe
.filter((p) => !samePath(p, stashRoot) && fs.existsSync(p)),
sources,
cfg,
options,
});
found.flagged.push(...trackedSecretIssues(stashRoot));
await addStoreFindings(found, sources, cfg, options);
return finishLint(found, cfg, options, stashRoot);
}