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
255 lines (254 loc) • 14 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 consolidate from "../../assets/improve-strategies/consolidate.json" with { type: "json" };
import defaultStrategy from "../../assets/improve-strategies/default.json" with { type: "json" };
import { ambiguousDefaultAdvice, } from "../../core/config/config.js";
import { ImproveProfileConfigSchema } from "../../core/config/config-schema.js";
import { deepMergeConfig } from "../../core/config/deep-merge.js";
import { BUILTIN_IMPROVE_STRATEGY_NAMES, IMPROVE_ENGINE_PROCESSES, IMPROVE_PROCESS_NAMES, REMOVED_IMPROVE_STRATEGY_NAMES, } from "../../core/config/engine-semantics.js";
import { SHIPPED_ALIAS } from "../../core/config/model-aliases.js";
import { ConfigError } from "../../core/errors.js";
import { applyAutonomyGate } from "./autonomy-gate.js";
import { resolveImproveExecution } from "./execution.js";
export const DEFAULT_ALLOWED_TYPES = {
reflect: ["agent", "command", "knowledge", "lesson", "memory", "skill", "workflow"],
distill: ["memory"],
consolidate: ["memory"],
};
/** Resolve process enablement from the selected strategy, the sole improve authority. */
export function resolveProcessEnabled(processName, strategy) {
const processes = strategy.processes;
return processes?.[processName]?.enabled === true;
}
export function shouldSkipRef({ type }, processName, strategy) {
const process = strategy.processes?.[processName];
if (process?.enabled === false)
return { skip: true, reason: "process-disabled" };
const allowed = process?.allowedTypes ?? DEFAULT_ALLOWED_TYPES[processName];
if (!allowed.includes(type))
return { skip: true, reason: "type-filter" };
return { skip: false, reason: "" };
}
const REF_SCOPED_PROCESSES = new Set(["reflect", "distill", "consolidate"]);
/** How many refs a ref-scoped process would act on (`undefined` for any other process). */
export function eligibleRefCount(refs, process, strategy) {
if (!REF_SCOPED_PROCESSES.has(process))
return undefined;
const name = process;
return refs.filter((entry) => !shouldSkipRef(entry, name, strategy).skip).length;
}
export function isStrategyFilteredForAllPasses(asset, strategy) {
return shouldSkipRef(asset, "reflect", strategy).skip && shouldSkipRef(asset, "distill", strategy).skip;
}
const BUILTIN_STRATEGIES = {
default: defaultStrategy,
consolidate,
};
if (BUILTIN_IMPROVE_STRATEGY_NAMES.some((name) => !(name in BUILTIN_STRATEGIES))) {
throw new Error("Built-in improve strategy names are out of sync with their assets");
}
export function resolveImproveStrategy(name, config) {
const selectedName = name ?? config.improve?.strategy ?? "default";
const userStrategies = config.improve?.strategies ?? {};
// graph-refresh named a specific, common retirement — refuse it
// unconditionally, even when `improve.strategies["graph-refresh"]` still
// has an override block from when it customized the (now-deleted) built-in
// strategy of the same name. That override is a partial patch (e.g. just
// `processes.graphExtraction.mode`), not a full strategy definition —
// falling through to the generic "resolve as a user strategy" path below
// would silently merge it onto `default` and run a full, unplanned improve
// pass instead of refusing. `akm migrate apply` drops the leftover block
// (src/core/config/config.ts, normalizeConfigFile) since it can never
// apply again.
if (selectedName === "graph-refresh") {
const hasLeftoverOverride = Boolean(userStrategies["graph-refresh"]);
throw new ConfigError(`Improve strategy "graph-refresh" was retired in 0.9.17-alpha.9 along with the LLM entity-graph extraction it ran.` +
(hasLeftoverOverride
? ' Your config still has a leftover `improve.strategies["graph-refresh"]` override for it — `akm migrate apply` removes it.'
: ""), "UNKNOWN_IMPROVE_STRATEGY",
// Override CONFIG_HINTS.UNKNOWN_IMPROVE_STRATEGY (src/core/errors.ts):
// its "listed strategy names" phrase does not apply here (this message
// names no strategies), and its "define it under improve.strategies"
// suggestion is actively wrong — that is exactly the leftover-override
// shape this refusal exists to reject, not a way around it.
"Choose a different strategy. `graph-refresh` cannot be redefined under `improve.strategies` — it always refuses.");
}
if (!(selectedName in BUILTIN_STRATEGIES) &&
!userStrategies[selectedName] &&
REMOVED_IMPROVE_STRATEGY_NAMES.includes(selectedName)) {
throw new ConfigError(`Improve strategy "${selectedName}" was removed in 0.10. Use "default" (or "consolidate"), or define "${selectedName}" under improve.strategies to keep your own version.`, "UNKNOWN_IMPROVE_STRATEGY", `Run \`akm improve --strategy default\`, or add \`improve.strategies.${selectedName}\` to your config; a block of that name is a user-defined strategy that inherits \`default\`.`);
}
if (!(selectedName in BUILTIN_STRATEGIES) && !userStrategies[selectedName]) {
const valid = [...new Set([...Object.keys(BUILTIN_STRATEGIES), ...Object.keys(userStrategies)])].sort();
throw new ConfigError(`Improve strategy "${selectedName}" not found. Valid strategies: ${valid.join(", ")}.`, "UNKNOWN_IMPROVE_STRATEGY");
}
const selectedStrategy = BUILTIN_STRATEGIES[selectedName] ?? {};
const baseStrategy = deepMergeConfig(BUILTIN_STRATEGIES.default ?? {}, selectedStrategy);
const resolved = deepMergeConfig(baseStrategy, (userStrategies[selectedName] ?? {}));
return { name: selectedName, config: ImproveProfileConfigSchema.parse(resolved) };
}
/**
* The processes that make their own model calls, so the plan resolves a runner
* for each: every process that makes a model call but triage, whose connection or harness is its judgment's.
*/
export const MODEL_CALLING_PROCESSES = new Set(IMPROVE_ENGINE_PROCESSES.filter((name) => name !== "triage"));
/**
* Project a resolved improve plan into one routing row per
* {@link IMPROVE_PROCESS_NAMES} name, plus a `"triage.judgment"`
* pseudo-row when the strategy configures a judgment connection or harness. Pure — no I/O,
* no re-resolution. Shared by `improve --dry-run`'s `plan.processes` (#947)
* and `akm health`'s post-run reporting (#944).
*/
export function projectResolvedProcessRouting(plan) {
const unavailableByProcess = new Map(plan.engineUnavailable.map((item) => [item.process, item]));
const rows = [];
for (const processName of IMPROVE_PROCESS_NAMES) {
const process = plan.processes[processName];
const unavailable = unavailableByProcess.get(processName);
rows.push({
process: processName,
enabled: process.enabled,
...(process.runner
? {
engine: process.runner.name,
...(process.runner.model !== undefined ? { model: process.runner.model } : {}),
engineKind: process.runner.kind,
}
: {}),
notices: process.notices ?? [],
...(unavailable ? { unavailable: { configKey: unavailable.configKey, reason: unavailable.reason } } : {}),
});
}
if (plan.strategy.config.processes?.triage?.judgment?.enabled === true) {
const judgmentUnavailable = unavailableByProcess.get("triage.judgment");
rows.push({
process: "triage.judgment",
enabled: plan.triageJudgment !== null,
...(plan.triageJudgment
? {
engine: plan.triageJudgment.name,
engineKind: plan.triageJudgment.kind,
...(plan.triageJudgment.model !== undefined ? { model: plan.triageJudgment.model } : {}),
}
: {}),
notices: plan.triageJudgmentNotices ?? [],
...(judgmentUnavailable
? { unavailable: { configKey: judgmentUnavailable.configKey, reason: judgmentUnavailable.reason } }
: {}),
});
}
return rows;
}
export function cloneAndFreeze(value) {
const clone = structuredClone(value);
const freeze = (item) => {
if (typeof item !== "object" || item === null || Object.isFrozen(item))
return;
for (const child of Object.values(item))
freeze(child);
Object.freeze(item);
};
freeze(clone);
return clone;
}
/** Resolve every enabled process structurally before improve emits signals or performs I/O. */
export function resolveImprovePlan(name, config, options = {}) {
const selected = resolveImproveStrategy(name, config);
// D8 — gate autonomy BEFORE the plan is built, so every downstream consumer
// (process enablement, LLM preflight, triage judgment) sees one already-safe
// strategy rather than each having to re-ask whether autonomy is allowed.
const { config: gatedStrategyConfig, gated } = applyAutonomyGate(selected.config, config);
const strategy = { name: selected.name, config: gatedStrategyConfig };
return { ...buildImprovePlan(strategy, config, options), autonomyGated: gated };
}
function buildImprovePlan(strategy, config, options) {
const processes = {};
const engineUnavailable = [];
for (const processName of IMPROVE_PROCESS_NAMES) {
const sourceProcessConfig = strategy.config.processes?.[processName] ?? {};
const enabled = sourceProcessConfig.enabled === true;
let runner = null;
let notices = [];
if (!MODEL_CALLING_PROCESSES.has(processName) || !enabled) {
processes[processName] = Object.freeze({ enabled, config: cloneAndFreeze(sourceProcessConfig), runner });
continue;
}
// Validation itself is structural and always runs. Only its optional repair
// step needs a model, so disabling repair must not create an LLM preflight.
const skipsRepairEngine = processName === "validation" && options.repairValidationFailures === false;
if (!skipsRepairEngine) {
const resolved = resolveImproveExecution({
config,
processName,
alias: SHIPPED_ALIAS.improve,
...(options.run ? { run: options.run } : {}),
});
runner = resolved?.runner ?? null;
notices = resolved?.notices ?? [];
}
if (!runner && !skipsRepairEngine) {
const configKey = `improve.processes.${processName}.connection`;
engineUnavailable.push({
process: processName,
configKey,
reason: `requires a connection or harness that is not configured. Run \`akm setup\`, or set ${configKey}`,
});
processes[processName] = Object.freeze({
enabled: false,
config: cloneAndFreeze({ ...sourceProcessConfig, enabled: false }),
runner: null,
});
continue;
}
if (runner)
runner = cloneAndFreeze(runner);
processes[processName] = Object.freeze({
enabled,
config: cloneAndFreeze(sourceProcessConfig),
runner,
...(notices.length > 0 ? { notices: cloneAndFreeze(notices) } : {}),
});
}
if (engineUnavailable.length > 0 &&
// Triage without its judgment and proactiveMaintenance make no model call: they alone do not keep a run alive.
![...MODEL_CALLING_PROCESSES].some((name) => processes[name].enabled)) {
const names = engineUnavailable.map((item) => `"${item.process}"`).join(", ");
const ambiguous = ambiguousDefaultAdvice(config);
throw new ConfigError(`No improve process can run: ${names} ${engineUnavailable.length === 1 ? "requires" : "require"} a connection or harness that ${ambiguous ? "has no default to run on" : "is not configured"}. ${ambiguous ? `${ambiguous}.` : "Run `akm setup`, or set improve.connection or improve.harness."}`, "LLM_NOT_CONFIGURED");
}
const triage = strategy.config.processes?.triage;
const judgmentEnabled = triage?.judgment?.enabled === true;
const triageJudgmentResolution = processes.triage.enabled && judgmentEnabled
? resolveImproveExecution({
config,
process: "triage",
processName: "triage-judgment",
alias: SHIPPED_ALIAS.judge,
...(options.run ? { run: options.run } : {}),
})
: null;
const triageJudgment = triageJudgmentResolution?.runner ?? null;
if (processes.triage.enabled && judgmentEnabled && !triageJudgment) {
throw new ConfigError(`Enabled improve triage judgment requires a connection or harness. Run \`akm setup\`, or set improve.connection or improve.processes.triage.connection.`, "LLM_NOT_CONFIGURED");
}
const frozenProcesses = Object.freeze(processes);
const frozenStrategy = Object.freeze({
name: strategy.name,
config: cloneAndFreeze({
...strategy.config,
processes: Object.fromEntries(Object.entries(frozenProcesses).map(([name, process]) => [name, process.config])),
}),
});
return Object.freeze({
config: cloneAndFreeze(config),
strategy: frozenStrategy,
processes: frozenProcesses,
triageJudgment: triageJudgment ? cloneAndFreeze(triageJudgment) : null,
...(options.run ? { run: cloneAndFreeze(options.run) } : {}),
...(triageJudgmentResolution?.notices.length
? { triageJudgmentNotices: cloneAndFreeze(triageJudgmentResolution.notices) }
: {}),
engineUnavailable: Object.freeze(engineUnavailable),
});
}