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
273 lines (272 loc) • 12.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/.
/**
* Improve profile + per-process discriminated schemas. Extracted
* verbatim from the former `config-schema.ts` monolith — no behavior change.
*/
import { z } from "zod";
import { IMPROVE_PROCESS_NAMES } from "../engine-semantics.js";
import { nonEmptyString, positiveInt } from "./primitives.js";
// ── Improve profile / process ──────────────────────────────────────────────
//
// Each of the improve processes (reflect, distill,
// consolidate, memoryInference, extract, validation, triage,
// proactiveMaintenance) has its OWN schema
// below — a shared base (`enabled`) extended
// with only the fields meaningful on that process, so a field set on a
// process it does not apply to is not silently accepted. Field→process
// assignment follows each field's runtime consumers and the built-in strategy assets
// (src/assets/improve-strategies/*.json).
//
// `ImproveProcessConfigSchema` ITSELF STAYS (unnarrowed — the union of every
// field across every process): it backs (a) the wide `ImproveProcessConfig`
// TS type that generic dynamic-process-name code needs (getImproveProcessConfig,
// ResolvedImproveProcess.config, agent/runner.ts's cast — the process name
// isn't known at the type level there, so the type must be a supertype every
// process's narrow output is assignable to), and (b) two existing tests that
// parse fields from multiple processes against it directly with no process
// context (tests/integration/extract-command.test.ts,
// tests/config-triage-process.test.ts). Real per-config validation for
// `processes.<name>` uses the NARROW per-process schemas via
// {@link ImproveProfileProcessesSchema} below — setting a field on the wrong
// process there is rejected.
// A strategy says which processes run and how; where a process runs (connection,
// harness, model, inference, timeout) is `improve.processes.<name>`, never here.
const IMPROVE_PROCESS_BASE_FIELDS = {
enabled: z.boolean().optional(),
};
/** Reflect/distill/consolidate: process-level asset-type filter (see improve-strategies.ts shouldSkipRef/DEFAULT_ALLOWED_TYPES). */
const allowedTypesField = z.array(z.string().min(1)).optional();
/**
* Consolidate process: hard cap on memories processed per pass.
* Reflect: max refs processed (same as profile-level `limit`).
*/
const processLimitField = positiveInt.optional();
/**
* The distill and reflect LLM-as-judge quality gates. Default ON; set
* `enabled: false` on the process to opt out. A judge error, timeout or
* unparsable reply never passes: distill and reflect both send the content
* to a person. Where the judge runs is `improve.qualityGate`.
*/
const qualityGateField = z
.object({
enabled: z.boolean().optional(),
})
.passthrough()
.optional();
/**
* CLS (Complementary Learning System) interleaving.
* The distill prompt includes the lessons, knowledge notes and skills the library already holds near the
* memory, so the writer answers NONE for a rule one of them states and does not overwrite a prior
* generalization. Default ON; `enabled: false` turns it off. Only meaningful on the `distill` process.
*/
const clsField = z
.object({
enabled: z.boolean().optional(),
// Number of adjacent lessons/knowledge to include in prompts (default 3).
adjacentCount: z.number().int().min(1).optional(),
})
.passthrough()
.optional();
/**
* The wording lists of reflect's pre-judge defect filter (`findReflectDefect`).
* Each list is optional: one that is set replaces that rule's default list, and
* an empty one turns the rule off. Phrases (`placeholders`, `metaCommentary`)
* match as whole words in any case; `frontmatterKeys` are exact key names.
* Reflect process only.
*/
const defectFilterField = z
.object({
placeholders: z.array(nonEmptyString).optional(),
metaCommentary: z.array(nonEmptyString).optional(),
frontmatterKeys: z.array(nonEmptyString).optional(),
})
.passthrough()
.optional();
/**
* #626 — extract process: pre-LLM heuristic triage gate. When enabled, a
* deterministic scorer decides BEFORE the extraction LLM call whether a
* session carries enough signal to be worth extracting; low-signal sessions
* are skipped at zero LLM cost. Default OFF. `minScore` is the minimum total
* heuristic score to PASS (default 2). Extract process only — NOTE: unrelated
* to the `triage` PROCESS (`processes.triage`); this is a nested object under
* `processes.extract.triage` that happens to share the name.
*/
const extractTriageGateField = z
.object({
enabled: z.boolean().optional(),
minScore: z.number().min(0).optional(),
})
.passthrough()
.optional();
// Unknown keys pass through here like every other nested surface (the loader names them once).
const triageJudgmentObjectField = z
.object({
enabled: z.boolean().optional(),
})
.passthrough();
/** Triage process: whether the LLM-as-judge runs; it runs where `improve.processes.triage` says. */
const triageJudgmentField = z
.union([z.boolean(), triageJudgmentObjectField])
.transform((value) => typeof value === "boolean" ? { enabled: value } : { ...value, enabled: value.enabled ?? true })
.optional();
const REFLECT_PROCESS_FIELDS = {
allowedTypes: allowedTypesField,
limit: processLimitField,
qualityGate: qualityGateField,
defectFilter: defectFilterField,
};
const DISTILL_PROCESS_FIELDS = {
allowedTypes: allowedTypesField,
qualityGate: qualityGateField,
// Skip distill entirely when reflect produced zero planned refs.
requirePlannedRefs: z.boolean().optional(),
cls: clsField,
};
const CONSOLIDATE_PROCESS_FIELDS = {
allowedTypes: allowedTypesField,
limit: processLimitField,
maxChunkSize: z.number().int().min(1).max(50).optional(),
};
const MEMORY_INFERENCE_PROCESS_FIELDS = {
// Minimum pending memory count to run the pass.
minPendingCount: z.number().int().min(0).optional(),
};
const EXTRACT_PROCESS_FIELDS = {
defaultSince: z.string().min(1).optional(),
maxTotalChars: positiveInt.optional(),
// Minimum raw session size (pre-filter inputCount) below which the extract
// LLM call is skipped (#595/#596). 0 disables the gate. Absent = default 10
// (skip only truly empty sessions).
minContentChars: z.number().int().min(0).optional(),
triage: extractTriageGateField,
// Minimum number of new (unseen, in-window) candidate sessions below which
// the extract pass skips entirely (emits an `improve_skipped` event with
// `reason: "below_min_new_sessions"`). 0 disables the guard. Default 0
// (disabled) so existing behaviour is preserved; only opted-in profiles set it.
minNewSessions: z.number().int().min(0).optional(),
// Cap on NEW sessions processed (LLM-called) per run; the rest roll to the
// next run (still unseen). 0 disables. Absent = default 25.
maxSessionsPerRun: z.number().int().min(0).optional(),
// #561 — index agent sessions as a searchable `session` asset. Absent =
// on-when-an-LLM-is-available (fail-open when offline). COST: when on, each
// processed session makes a SECOND LLM call (the session summary) on top of
// the extraction call — i.e. ~2 LLM calls/session. Set to false to halve
// per-session extract cost at the price of unsearchable sessions.
// (Unchanged/skip sessions still cost zero — the content-hash ledger gates
// both calls upstream.)
indexSessions: z.boolean().optional(),
// #561 — minimum session duration in minutes for session indexing. 0
// disables the gate. Absent = default 5.
minSessionDuration: z.number().min(0).optional(),
};
const TRIAGE_PROCESS_FIELDS = {
applyMode: z.enum(["queue", "promote"]).optional(),
maxAcceptsPerRun: positiveInt.optional(),
judgment: triageJudgmentField,
};
/** proactiveMaintenance process fields (Layer 2). */
const PROACTIVE_MAINTENANCE_PROCESS_FIELDS = {
// Staleness gate + rotation cooldown in days (default 30).
dueDays: z.number().int().min(0).optional(),
// Top-N bound per run (default 15).
maxPerRun: positiveInt.optional(),
};
export const ImproveProcessConfigSchema = z
.object({
...IMPROVE_PROCESS_BASE_FIELDS,
...REFLECT_PROCESS_FIELDS,
...DISTILL_PROCESS_FIELDS,
...CONSOLIDATE_PROCESS_FIELDS,
...MEMORY_INFERENCE_PROCESS_FIELDS,
...EXTRACT_PROCESS_FIELDS,
...TRIAGE_PROCESS_FIELDS,
...PROACTIVE_MAINTENANCE_PROCESS_FIELDS,
})
.passthrough();
/** `processes.reflect` — narrow per-process schema. */
export const ReflectProcessConfigSchema = z
.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...REFLECT_PROCESS_FIELDS })
.passthrough();
/** `processes.distill` — narrow per-process schema. */
export const DistillProcessConfigSchema = z
.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...DISTILL_PROCESS_FIELDS })
.passthrough();
/** `processes.consolidate` — narrow per-process schema. */
export const ConsolidateProcessConfigSchema = z
.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...CONSOLIDATE_PROCESS_FIELDS })
.passthrough();
/** `processes.memoryInference` — narrow per-process schema. */
export const MemoryInferenceProcessConfigSchema = z
.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...MEMORY_INFERENCE_PROCESS_FIELDS })
.passthrough();
/** `processes.extract` — narrow per-process schema. */
export const ExtractProcessConfigSchema = z
.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...EXTRACT_PROCESS_FIELDS })
.passthrough();
/** `processes.validation` — narrow per-process schema; no extra fields beyond the shared base. */
export const ValidationProcessConfigSchema = z.object({ ...IMPROVE_PROCESS_BASE_FIELDS }).passthrough();
/** `processes.triage` — narrow per-process schema. */
export const TriageProcessConfigSchema = z
.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...TRIAGE_PROCESS_FIELDS })
.passthrough();
/** `processes.proactiveMaintenance` — narrow per-process schema. */
export const ProactiveMaintenanceProcessConfigSchema = z
.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...PROACTIVE_MAINTENANCE_PROCESS_FIELDS })
.passthrough();
/**
* Process names that once had a dedicated schema and are now gone. Setting
* one, even with `enabled: true`, is tolerated rather than rejected by the
* "unknown enabled process" check below — an old config must keep loading.
* `graphExtraction`: the LLM
* entity-graph extraction it ran was retired.
* `feedbackDistillation`: a wrapper of `processes.distill.enabled`, removed in
* 0.8.0.
*/
const RETIRED_PROCESS_NAMES = new Set(["graphExtraction", "feedbackDistillation"]);
const ImproveProfileProcessesSchema = z
.object({
reflect: ReflectProcessConfigSchema.optional(),
distill: DistillProcessConfigSchema.optional(),
consolidate: ConsolidateProcessConfigSchema.optional(),
memoryInference: MemoryInferenceProcessConfigSchema.optional(),
extract: ExtractProcessConfigSchema.optional(),
validation: ValidationProcessConfigSchema.optional(),
triage: TriageProcessConfigSchema.optional(),
proactiveMaintenance: ProactiveMaintenanceProcessConfigSchema.optional(),
})
.passthrough()
.superRefine((val, ctx) => {
// Unknown process keys remain preserved for cross-version compatibility,
// but an enabled one is rejected below because this version cannot
// execute it.
for (const [name, process] of Object.entries(val)) {
if (!IMPROVE_PROCESS_NAMES.includes(name) &&
!RETIRED_PROCESS_NAMES.has(name) &&
process !== null &&
typeof process === "object" &&
process.enabled === true) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: [name],
message: `Unknown enabled improve process "${name}"`,
});
}
}
});
export const ImproveProfileConfigSchema = z
.object({
description: z.string().min(1).optional(),
processes: ImproveProfileProcessesSchema.optional(),
limit: positiveInt.optional(),
sync: z
.object({
enabled: z.boolean().optional(),
push: z.boolean().optional(),
message: z.string().min(1).optional(),
})
.passthrough()
.optional(),
})
.passthrough();