UNPKG

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

603 lines (602 loc) • 36.7 kB
// 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/. /** * The one path every improve stage (reflect, distill, consolidate, extract, * triage, memory inference) runs through: pick the stage's runner, call the * model, judge what it produced, mint the proposal, and attribute the usage. * A stage keeps only its prompt, its parse shape and its target rule. */ import { parseFrontmatter } from "../../core/asset/frontmatter.js"; import { stateBundleId } from "../../core/bundle-at-dir.js"; import { SHIPPED_ALIAS } from "../../core/config/model-aliases.js"; import { ConfigError } from "../../core/errors.js"; import { effectiveRequestFields, thinkingSetting } from "../../core/llm-inference.js"; import { parseEmbeddedJsonResponse } from "../../core/parse.js"; import { warn } from "../../core/warn.js"; import { isRefused, structuredLoop } from "../../llm/structured.js"; import { callStructured } from "../../llm/structured-call.js"; import { currentLlmStage, withLlmStage } from "../../llm/usage-telemetry.js"; import { getImproveLedgerRow } from "../../storage/repositories/improve-ledger-repository.js"; import { getStateProposal } from "../../storage/repositories/proposals-repository.js"; import { isProceduralRejection } from "../proposal/proposal-types.js"; import { createProposal, listProposalsReadOnly, proposalContentHash, recordGateDecision, } from "../proposal/repository.js"; import { resolveImproveExecution } from "./execution.js"; import { readLedgerDb } from "./ledger.js"; /** Normalize an unknown thrown value to a message. */ export function errMessage(e) { return e instanceof Error ? e.message : String(e); } /** * A stage's runner: the one the improve plan froze for it (an own * `llmRunner` key, `null` meaning "none"), else the one the process resolves to now. */ export function stageRunner(frozen, config, processName, onNotices) { if (Object.hasOwn(frozen, "llmRunner")) return frozen.llmRunner ?? undefined; const resolved = resolveImproveExecution({ config, processName, alias: SHIPPED_ALIAS.improve }); if (resolved) onNotices?.(resolved.notices); return resolved?.runner; } /** * The stage's call under the structured loop: each dispatch is one * {@link callStageOnce}, and the correction a refused reply earns is appended * to the prompt. The loop's own result comes back, so a caller that must tell a * refused reply (and read what the parser said) from a failed call can. */ export function callStageLoop(call, parse, correct) { return structuredLoop({ dispatch: (correction) => callStageOnce(correction ? { ...call, prompt: `${call.prompt}\n\n${correction.text}` } : call), parse, ...(correct ? { correct } : {}), }); } /** * One model call. Provider trouble (transport error, timeout, abort) comes back * as `{ ok: false }`; only a configuration failure throws. A reply to a call with `request.responseSchema` that the * stage's own `parse` rejects gets one corrective retry (the structured loop); * the last reply comes back either way, and the caller parses it again. */ export async function callStage(call) { if (!call.request?.responseSchema) return callStageOnce(call); const parse = call.parse ?? parseEmbeddedJsonResponse; const loop = await callStageLoop(call, (raw) => parse(raw) === undefined ? { ok: false, errors: ["no parseable JSON"] } : { ok: true, value: raw }); return loop.ok || isRefused(loop) ? { ok: true, raw: loop.raw } : loop; } /** * One dispatch with no validation: the loop's dispatch ({@link callStageLoop}), * and a caller's own (reflect's repair turn carries a conversation). */ export async function callStageOnce(call) { const messages = [ ...(call.system ? [{ role: "system", content: call.system }] : []), ...(call.history ?? []), { role: "user", content: call.prompt }, ]; const dispatch = () => callStructured({ runner: call.runner, messages, ...(call.request ? { request: call.request } : {}), ...(call.current ? { current: call.current } : {}), ...(call.onNotices ? { onNotices: call.onNotices } : {}), }); // Usage is credited to the connection or harness that serves the call, which for a gate's own judge // (#1011) is not the one the stage planned. const stage = currentLlmStage(); return stage === undefined ? dispatch() : withLlmStage(stage, dispatch, { engine: call.runner.name }); } /** Attribute a stage's LLM calls to its process and planned connection or harness (the usage report). */ const STAGE_LABELS = { reflect: "reflect", distill: "distill", consolidate: "consolidate", extract: "session-extraction", memoryInference: "memory-inference", validation: "validation", }; export function attributeStage(plan, process, fn) { return withLlmStage(STAGE_LABELS[process], fn, { engine: plan?.processes[process].runner?.name, process }); } /** How many prior rejected proposals are shown to the model as "don't repeat this". */ export const MAX_REJECTED_PROPOSALS = 3; /** * The newest content rejections for this input. A guard can reject before * minting, and a distill proposal targets its output, not its input; the * exact input's last ledger attempt covers both. Procedural refusals do not * judge content. Read through the live connection or open one read snapshot. */ export function rejectedProposalContext(stash, ref, ctx, eventsCtx, attempt) { if (!ref) return []; const db = eventsCtx?.db ?? ctx?.db; return (readLedgerDb({ proposalsCtx: ctx, eventsCtx: db ? { ...eventsCtx, db } : eventsCtx, readOnly: true }, (db) => { const proposals = listProposalsReadOnly(stash, { ref, status: "rejected", includeArchive: true }, { ...ctx, db }); const history = []; try { const latest = attempt ? getImproveLedgerRow(db, stateBundleId(stash), attempt.ref, attempt.source) : undefined; if (latest?.outcome === "quality_rejected" && latest.detail) { history.push({ at: latest.lastAttemptAt, entry: { ref, reason: latest.detail } }); } else if (latest?.outcome === "rejected" && latest.proposalId && !proposals.some((p) => p.id === latest.proposalId)) { const linked = getStateProposal(db, latest.proposalId, stateBundleId(stash)); if (linked?.status === "rejected") proposals.push(linked); } } catch (error) { // A read-only preview may open a database that predates the ledger. warn(`[improve] ledger read failed: ${errMessage(error)}`); } for (const proposal of proposals) { if (isProceduralRejection(proposal)) continue; history.push({ at: proposal.updatedAt, entry: { ref: proposal.ref, reason: proposal.review?.reason ?? "no reason given", contentPreview: proposal.payload.content.slice(0, 500), }, }); } return history .sort((a, b) => new Date(b.at).getTime() - new Date(a.at).getTime()) .slice(0, MAX_REJECTED_PROPOSALS) .map(({ entry }) => entry); }) ?? []); } // ── Mint ───────────────────────────────────────────────────────────────────── /** * Create a stage's proposal. `judged` (the passing verdict) stamps a `staged` * gate decision with the judged content's hash and the judge's scores and reason * (the triage drain accepts it while the content still matches); `review` * leaves it `deferred` for a human (`review_needed` in the improve ledger). */ export function mintProposal(stash, proposalsCtx, input, verdict = {}) { const proposal = createProposal(stash, input, proposalsCtx); if (verdict.review) { return recordGateDecision(stash, proposal.id, { outcome: "deferred", ...verdict.review }, proposalsCtx) ?? proposal; } return verdict.judged ? stageJudgedProposal(stash, proposal, verdict.judged, proposalsCtx) : proposal; } /** * Stamp a proposal the quality judge passed. Best-effort: a failed stamp only * means the triage drain judges it again. */ export function stageJudgedProposal(stash, proposal, judged, proposalsCtx) { try { return (recordGateDecision(stash, proposal.id, { outcome: "staged", reason: "quality-judge", gate: "quality-gate", contentHash: proposalContentHash(proposal), ...(judged?.criteria ? { scores: judged.criteria } : {}), ...(judged ? { judgeReason: judged.reason } : {}), }, proposalsCtx) ?? proposal); } catch (error) { warn(`[akm] failed to record the quality-judge pass for ${proposal.id}: ${errMessage(error)}`); return proposal; } } /** Whether `improve.qualityGate` sets where the judge runs, or only how. */ function gateNamesAJudge(gate) { return ["connection", "harness", "model", "timeoutMs", "llm"].some((key) => Object.hasOwn(gate, key)); } /** * The judge of a process's quality gate (#1011). Its layers are the improve-wide * `improve.connection` / `improve.harness`, then `improve.qualityGate`'s * connection or harness, model, timeout and inference, asking for the `judge` * alias when neither names a model. What the run selected (`--connection`, * `--harness`, `--model`) is nearer than all of these. The process's own `improve.processes.<name>` * settings (its `model`, `llm`, connection) are the generation call's and do not * reach the judge, so a `reasoning` model chosen for the writer is not the one * that judges it. `undefined` when the strategy turns the gate off or no * connection or harness is configured, so the caller keeps its own. The judge * may be a connection or a harness; a harness that cannot confine the * model-work tool policy runs unrestricted, with a notice. Throws when * `improve.qualityGate` names a judge that resolves to nothing, before anything * is generated: the gate never falls back to another judge. */ export function resolveQualityGateJudge(config, profile, processName, onNotices, run) { if (profile?.processes?.[processName]?.qualityGate?.enabled === false) return undefined; const gate = config.improve?.qualityGate; const resolved = resolveImproveExecution({ config, processName: `${processName}-quality-judge`, alias: SHIPPED_ALIAS.judge, ...(gate ? { current: gate } : {}), ...(run ? { run } : {}), }); if (!resolved) { if (gate && gateNamesAJudge(gate)) { throw new ConfigError("The quality gate's judge has no connection or harness. Set improve.qualityGate.connection.", "INVALID_CONFIG_FILE"); } return undefined; } onNotices?.(resolved.notices); return resolved.runner; } /** Lesson judge prompt: what the writer was given (the source and its feedback), the assets nearest the new lesson, the lesson. */ export function buildJudgePrompt(lessonContent, sourceContent, related, feedback, extending) { const lines = [ "You are evaluating a lesson an agent wrote from a memory and the feedback about it, for an akm knowledge base.", "", "Score this lesson on each criterion from 1 (poor) to 5 (excellent):", extending !== undefined ? "1. REUSABLE: The existing lesson below is already in the library as a rule, so ask only whether the added lines leave it one. Score 4-5 when the lesson still states its rule and the added lines support it with a cause, number, limit or consequence, however specific. Score 1-2 only when an added line replaces or contradicts the rule, is about another subject, or only records who did something, when, or what shipped." : "1. REUSABLE: Does the lesson state a rule or a result an agent can use on another occasion, with the reason or the conditions it holds under? Score 1-2 when it only records what was done, shipped, decided or is pending, on a date or for one build, machine or project, the counts or outcomes of one run, or how a system is set up now, however it is phrased. Score 1-2 also when the source memory is the report of one run, build or day (its date, counts, durations, which items passed or failed) whose cause is only suspected, with no fix verified, and the lesson turns that suspicion into a cause or a rule. Score 4-5 for a rule with its reason, or for a tested or measured result about a change or method, stated with the conditions and limits it held under (what was not checked stays a limit).", extending !== undefined ? "2. NON-REDUNDANCY: The proposed lesson is the existing lesson below with lines added. Compare each added line (a line the existing lesson does not have) only with the existing lesson, never with the source memory. Redundancy means the information is already in the existing lesson. Score 1-2 when an added line only says again what the existing lesson says, in other words. Score 4-5 when every added line states a fact the existing lesson does not contain (a cause, number, version, limit or consequence), however specific or tied to one incident it is." : '2. NON-REDUNDANCY: Compare the lesson only with the assets listed under "Existing assets nearest the new lesson" (each starts with "Existing asset ref:"); never with the source memory. When that list is absent, score 5. Score 1-2 when a listed asset already states the same rule, or states most of what the lesson says in broader words. Score 4-5 when the lesson gives a rule none of the listed assets gives, or when they are on other subjects.', extending !== undefined ? "3. GROUNDING: Is every statement in the lesson stated by the source, its feedback or the existing lesson below, in any words? Check each cause, step, number, rule and limit in the lesson against them. Score 4-5 when each is stated. Score 3 when one stretches what they say. Score 1-2 when any is in none of them, when it contradicts the existing lesson or the source, or when it is about another subject than the source." : "3. GROUNDING: Is every statement in the lesson stated by the source or its feedback, in any words? Check each cause, step, number, rule and limit in the lesson against them. Score 4-5 when each is stated. Score 3 when one stretches what the source says. Score 1-2 when any is in neither, when the lesson drops a limit the source states (one place checked, not confirmed, a guess) and says more than it, or when it is about another subject than the source.", "", "Source memory:", "```", // The window distill generates from (buildDistillPrompt): grounding can reject, so the judge reads all of it. sourceContent.slice(0, 3000), "```", ]; if (feedback && feedback.length > 0) { lines.push("", "Feedback recorded about the memory (the writer saw it too):", "```", feedback.join("\n").slice(0, 1500), "```"); } if (extending !== undefined) { lines.push("", "Existing lesson that the proposed lesson extends (it is already in the library):", "```", extending.slice(0, 2000), "```"); } else if (related && related.length > 0) { lines.push("", "Existing assets nearest the new lesson (they may be on another subject):"); for (const asset of related) lines.push(`\nExisting asset ref: ${asset.ref}`, "```", asset.content.slice(0, 600), "```"); } lines.push("", "Proposed lesson:", "```", lessonContent.slice(0, 2000), "```", "", 'Return ONLY valid JSON, no prose: {"scores": {"reusable": <1-5 integer>, "nonRedundancy": <1-5 integer>, "grounding": <1-5 integer>}, "reason": "<one sentence naming the weakest criterion>"}'); return lines.join("\n"); } export function boundedDocument(content, maxChars = 6000) { if (content.length <= maxChars) return content; const half = Math.floor((maxChars - 80) / 2); return `${content.slice(0, half)}\n\n[... middle omitted for bounded judge context ...]\n\n${content.slice(-half)}`; } function buildChangedRegion(sourceContent, candidateContent) { const source = sourceContent.split("\n"); const candidate = candidateContent.split("\n"); let prefix = 0; while (prefix < source.length && prefix < candidate.length && source[prefix] === candidate[prefix]) prefix++; let suffix = 0; while (suffix < source.length - prefix && suffix < candidate.length - prefix && source[source.length - 1 - suffix] === candidate[candidate.length - 1 - suffix]) { suffix++; } const removed = source.slice(prefix, source.length - suffix).join("\n"); const added = candidate.slice(prefix, candidate.length - suffix).join("\n"); return boundedDocument(`Removed or replaced:\n${removed || "(none)"}\n\nAdded or replacement:\n${added || "(none)"}`); } /** * What the judge may do with tools when it runs on a harness: verify a * fact the revision adds or alters, and nothing else. The plain judge's prompt * is unchanged (its rubric is tuned and measured without this paragraph). */ function reflectJudgeToolRules(ref, tool) { const read = tool === "akm_show" ? "akm_show" : `\`akm show ${ref ?? "<ref>"}\``; const asset = ref ? `The asset is \`${ref}\`: read it with ${read}, ` : `Read an asset with ${read} `; return `Tools: ${asset}or an asset the changed region names, only to verify a fact the revision adds or alters; the text above already shows every change. Do not search, do not read anything else, and do not use a tool to judge structure or wording. One or two reads at most. Before scoring, check two lists: (1) every statement the revision adds: find each in the asset, or as a fact the feedback states about the subject, and score QUALITY 1-2 if any is in neither; a statement is found only when the asset or the feedback says it, in any words: a new step, cause, consequence or detail that merely seems to follow is not found; feedback says what to fix and is not content, so an added statement about how the asset was used, found or verified is unsupported; (2) every fact, caveat and field of the source: find each in the revision, and score PRESERVATION 1-3 if any is missing. A read that finds nothing wrong raises no score above what these lists support. Then reply with the JSON.`; } /** * The reflect judge's rubric, for the frontmatter-only revisions reflect makes, and the paragraph that says what * drove the revision: negative feedback (any `[negative]` line) or maintenance. Tuned on the production model * against 113 reviewed proposals (the stash's eval/judge-gate/tuning/reflect/judge-fm, rubric f07). */ const REFLECT_JUDGE_INTRO = "You are evaluating a proposed revision of an existing akm asset's frontmatter. The revision may change only the `description`, the `when_to_use` and the title (a level-1 heading added when the body has none); the body is unchanged."; const REFLECT_JUDGE_NEGATIVE = "This revision answers negative feedback. It cannot change the body, so it need not resolve the feedback: judge only the fields it changes, and never fault it for a field it leaves as it was. Most negative feedback says the asset did not help with a task it was retrieved for: a retrieval miss, not a defect. It justifies changing a field only when the field claims more than the body covers (narrow it to what the body covers), or when the feedback calls the asset stale, outdated, superseded or historical (a new `when_to_use` must then name the version or date the body records). Feedback about a task the asset never claims to cover justifies no change. Repairing a missing or broken field is always needed, whatever the feedback says."; const REFLECT_JUDGE_MAINTENANCE = "This revision is maintenance: there is no negative feedback. Only a missing or broken field needs a change; rewording a sound `description` or `when_to_use` is churn, however accurate. Adding a field the source lacks is needed, not churn; every other change in the revision is still judged on its own."; /** Judge prompt for an in-place revision. `tools` is set when the judge runs on a harness. */ export function buildReflectJudgePrompt(candidateContent, sourceContent, feedback, tools) { return [ REFLECT_JUDGE_INTRO, "", feedback.some((line) => line.startsWith("[negative]")) ? REFLECT_JUDGE_NEGATIVE : REFLECT_JUDGE_MAINTENANCE, "", "Score this revision on each criterion from 1 (poor) to 5 (excellent):", "1. NEED: Does every changed field fix a real problem? Real problems: a missing `description`, `when_to_use` or title; a broken description (a sentence split by a stray period at a line wrap, an escaped or unbalanced quote, a truncated ending, a heading fragment); and, for a revision answering negative feedback, a field that claims more than the body covers, or a stale note's `when_to_use` that does not name the version or date the body records. Replacing a stray period that splits a sentence with a comma, a word or nothing repairs a broken description, however small the change looks. Score 4-5 when every changed field fixes one. Score 1-2 when any changed field rewrites a sound field. Score NEED on the changed fields alone: leaving negative feedback about the body unresolved never lowers it.", "2. PRESERVATION: Does the new description keep every fact the old one carried: names, identifiers, numbers, versions, paths, qualifiers and status words such as 'Proposal' or 'draft'? Are all other frontmatter fields unchanged? Score 1-3 when anything is dropped or changed. A field the source lacks has no old value to keep: adding it drops nothing, so judge PRESERVATION on the fields the source already had.", "3. QUALITY: Is every new value supported by the body, without inventing, over-claiming or misdescribing? Check each new value as a claim against the body; restating the body in other words is supported. Score only values the revision adds or changes: a field it leaves as it was, however stale, is never this revision's fault. Score 1-2 when a new value says something the body does not support or the opposite of what it says, keeps a truncated or garbled fragment, or offers a dated or historical note for current work: when the feedback calls the note stale, outdated, superseded or historical, or the body records the version or date it was true for, a new `when_to_use` that does not name that version or date, or a new value that calls a dated snapshot 'current', scores 1-2.", "", "Feedback:", "```", (feedback.length > 0 ? feedback.join("\n") : "No explicit feedback supplied.").slice(0, 1000), "```", "", "Source asset content:", "```", boundedDocument(sourceContent), "```", "", "Proposed revision:", "```", boundedDocument(candidateContent), "```", "", "Changed region:", "```", buildChangedRegion(sourceContent, candidateContent), "```", "", ...(tools ? [reflectJudgeToolRules(tools.ref, tools.tool), ""] : []), 'Return ONLY valid JSON, no prose: {"scores": {"need": <1-5 integer>, "preservation": <1-5 integer>, "quality": <1-5 integer>}, "reason": "<one sentence>"}', ].join("\n"); } /** * `grounding` is scored with the other lesson criteria but left out of their * mean. A lesson criterion scored {@link LESSON_REJECT_MAX_SCORE} or less is a * rejection whatever the mean says: the mean would hide it (4 and 1 average * 2.5, a review), and a reviewer was reading every lesson that was not rejected, * 17 of 19 of them bad on 2026-10-05. The rubric reserves 1-2 for a lesson that * records what was done instead of a rule, repeats an asset the library holds, * or states what neither its source nor its feedback does. The judge is shown * the feedback the writer saw, so a statement it supports is not an invention. */ const GROUNDING_CRITERION = "grounding"; export const LESSON_REJECT_MAX_SCORE = 2; const REVIEW_MIN_SCORE = 2.5; /** * The review floor of a reflect revision: a non-pass is `reviewNeeded` (reflect queues it for a person as * `judge-uncertain`) only at a mean of this or more; a lower one is refused. Other judges flag review from * {@link REVIEW_MIN_SCORE}, but nothing reflect labels below 3.5 is worth a person's time. Labelled runs of the judge (akm-eval judge-gate, * lab 27B Q2; ~/akm/eval/judge-gate/tuning), good / bad among non-passing verdicts: * mean >= 3.5, frontmatter-only proposals Opus reviewed: 17 / 9 (shipped judge, 113 proposals), * 15 / 0, 18 / 9 and 15 / 5 (earlier rubric, three runs); * mean >= 3.5, public corpus of body rewrites: 12 / 35; * mean < 3.5, 396 labelled body rewrites: 6 / 285 (Q4 judge 5 / 177, Q2 judge 1 / 108); * public corpus 3 / 37; frontmatter-only proposals: 1 / 2 (shipped judge), 5 / 1 (earlier runs). * Mean 4.0 with one criterion at 2 was good 14 / 0; mean 3.67 was 3 / 8. A rule on the lowest * criterion did not help: a criterion at 3 or more is rare in a non-pass, and a 2 is the usual * shape of a good one. */ const REFLECT_REVIEW_MIN_SCORE = 3.5; const LESSON_JUDGE_CRITERIA = ["reusable", "nonRedundancy", GROUNDING_CRITERION]; const REFLECT_JUDGE_CRITERIA = ["need", "preservation", "quality"]; /** * Read a judge response: the per-criterion shape (averaged here, `grounding` * aside; `lowest` is the lowest score in that mean) or the older `{"score"}` * shape. Only the expected criteria are read; any missing or out-of-range * (1..5) value is a parse failure, extra keys are ignored. */ function parseJudgeResponse(raw, keys) { const parsed = parseEmbeddedJsonResponse(raw); if (!parsed || typeof parsed.reason !== "string") return undefined; const reason = parsed.reason; const inRange = (value) => typeof value === "number" && Number.isFinite(value) && value >= 1 && value <= 5; if (parsed.scores !== undefined) { if (typeof parsed.scores !== "object" || parsed.scores === null || Array.isArray(parsed.scores)) return undefined; const scores = parsed.scores; const criteria = {}; for (const key of keys) { const value = scores[key]; if (!inRange(value)) return undefined; criteria[key] = value; } const averaged = Object.entries(criteria) .filter(([key]) => key !== GROUNDING_CRITERION) .map(([, value]) => value); return { score: averaged.reduce((a, b) => a + b, 0) / averaged.length, lowest: Math.min(...averaged), reason, criteria, }; } return inRange(parsed.score) ? { score: parsed.score, lowest: parsed.score, reason } : undefined; } export function judgeResponseSchema(keys) { return { type: "object", required: ["scores", "reason"], additionalProperties: false, properties: { scores: { type: "object", required: [...keys], additionalProperties: false, properties: Object.fromEntries(keys.map((key) => [key, { type: "integer", minimum: 1, maximum: 5 }])), }, reason: { type: "string" }, }, }; } /** * The quality judge. An unparseable reply or a provider failure is an outcome of * its own, never a verdict; the pipeline's wrappers below route either to review * with score -1 (no verdict), for a person. Bands: every criterion in the mean * >= 4 passes, otherwise a mean >= {@link REVIEW_MIN_SCORE} (reflect's: {@link REFLECT_REVIEW_MIN_SCORE}) is review and a lower one reject; a * lesson criterion (`grounding` included) of {@link LESSON_REJECT_MAX_SCORE} * or less rejects whatever the mean is. * Temperature is set to 0, which reduces run-to-run variation but does not * remove it: on some servers (llama.cpp batching, for one) the same request can * score a point apart, so the routing rules are chosen with that margin in mind. */ export async function judgeQuality(prompt, keys, call, reviewMinScore = REVIEW_MIN_SCORE) { const { runner } = call; const outcome = await callStage({ runner, system: "Return only valid JSON. No prose.", prompt, request: { // Off unless the judge's own connection enables thinking (a slower, separate judge, #1011). enableThinking: runner.kind === "connection" && thinkingSetting(effectiveRequestFields(runner.request, runner.inference)) === true, temperature: 0, responseSchema: judgeResponseSchema(keys), ...(Object.hasOwn(call, "timeoutMs") ? { timeoutMs: call.timeoutMs } : {}), ...(call.signal ? { signal: call.signal } : {}), ...(call.chat ? { chat: call.chat } : {}), }, parse: (raw) => parseJudgeResponse(raw, keys), ...(call.onNotices ? { onNotices: call.onNotices } : {}), }); if (!outcome.ok) return { outcome: "error", reason: outcome.error }; const parsed = parseJudgeResponse(outcome.raw, keys); if (!parsed) return { outcome: "unparseable", reason: "the reply held no verdict in the expected shape" }; const { score, lowest, reason, criteria } = parsed; // A lesson criterion at 2 or below is a defect the mean would hide (4 and 1 average 2.5, a review): it rejects. if (criteria && criteria[GROUNDING_CRITERION] !== undefined) { const [weakest, low] = Object.entries(criteria).sort((x, y) => x[1] - y[1])[0]; if (low <= LESSON_REJECT_MAX_SCORE) return { outcome: "verdict", verdict: { pass: false, score, reason: `${weakest} ${low}/5: ${reason}`, criteria }, }; } const verdict = lowest >= 4 ? { pass: true } : score >= reviewMinScore ? { pass: false, reviewNeeded: true } : { pass: false }; return { outcome: "verdict", verdict: { ...verdict, score, reason, ...(criteria ? { criteria } : {}) } }; } export const QUALITY_VERDICT_SHAPE = { type: "object", required: ["pass", "score", "reason"], additionalProperties: false, properties: { pass: { type: "boolean" }, score: { type: "number", minimum: 1, maximum: 5 }, reason: { type: "string" }, reviewNeeded: { type: "boolean" }, criteria: { type: "object" }, }, }; const FEEDBACK_LINES = { type: "array", items: { type: "string" } }; export const reflectQualityJudge = { name: "reflect.quality", description: "Reflect's quality judge: is a revision of an asset's frontmatter needed, faithful and supported.", schemaVersion: 2, inputSchema: { type: "object", required: ["source", "candidate"], additionalProperties: false, properties: { source: { type: "string" }, candidate: { type: "string" }, feedback: FEEDBACK_LINES, ref: { type: "string" }, }, }, outputSchema: QUALITY_VERDICT_SHAPE, harnessReads: "On a harness, the asset at input.ref (akm show), to verify a fact the revision adds or alters.", defaultRunner: (config, run) => resolveQualityGateJudge(config, undefined, "reflect", undefined, run), run(input, call) { // A judge on a harness gets the tool rules, in the spelling its harness has. const { runner } = call; const tools = runner.kind !== "connection" ? { ref: input.ref, tool: runner.platform === "opencode" ? "akm_show" : "akm show" } : undefined; return judgeQuality(buildReflectJudgePrompt(input.candidate, input.source, input.feedback ?? [], tools), REFLECT_JUDGE_CRITERIA, call, REFLECT_REVIEW_MIN_SCORE); }, }; export const lessonQualityJudge = { name: "distill.lesson", description: "Distill's lesson judge: is a new lesson (or an update of one) reusable, non-redundant and grounded.", schemaVersion: 1, inputSchema: { type: "object", required: ["lesson", "source"], additionalProperties: false, properties: { lesson: { type: "string" }, source: { type: "string" }, feedback: FEEDBACK_LINES, related: { type: "array", items: { type: "object", required: ["ref", "content"], additionalProperties: false, properties: { ref: { type: "string" }, content: { type: "string" } }, }, }, extending: { type: "string" }, }, }, outputSchema: QUALITY_VERDICT_SHAPE, harnessReads: "Nothing.", // The gate's judge, else distill's own runner, as distill judges. defaultRunner: (config, run) => resolveQualityGateJudge(config, undefined, "distill", undefined, run) ?? resolveImproveExecution({ config, processName: "distill", alias: SHIPPED_ALIAS.improve, ...(run ? { run } : {}), })?.runner, run: (input, call) => judgeQuality( // The judge reads what the generator read: the memory's body, without its frontmatter (buildDistillPrompt). buildJudgePrompt(input.lesson, parseFrontmatter(input.source).content.trim(), input.related, input.feedback, input.extending), LESSON_JUDGE_CRITERIA, call), }; /** * The pipeline's way into a quality judge: the frozen runner, or the one the * feature resolves to unless the caller froze selection. No runner, a provider * failure or an unreadable reply never passes content: each comes back as review * with score -1 (no verdict), for a person. */ export async function runQualityJudge(judge, feature, config, input, chat, options) { const resolved = !options.runnerSelectionFrozen && !options.llmRunner ? resolveImproveExecution({ config, processName: `${feature}-judge`, alias: SHIPPED_ALIAS.judge }) : null; if (resolved) options.onNotices?.(resolved.notices); const runner = options.llmRunner ?? resolved?.runner; if (!runner) return { pass: false, score: -1, reason: "no connection or harness configured — cannot judge, routed to review", reviewNeeded: true, }; const result = await judge.run(input, { runner, ...(chat ? { chat } : {}), ...(Object.hasOwn(options, "timeoutMs") ? { timeoutMs: options.timeoutMs } : {}), ...(options.signal ? { signal: options.signal } : {}), ...(options.onNotices ? { onNotices: options.onNotices } : {}), }); return result.outcome === "verdict" ? result.verdict : noVerdict(result.outcome); } /** What the pipeline records for a judge that gave no verdict: review with score -1, for a person. */ export function noVerdict(outcome) { return { pass: false, score: -1, reason: outcome === "error" ? "judge timeout/error — routed to review" : "judge parse failed — routed to review", reviewNeeded: true, }; } /** Judge a proposed lesson (or knowledge promotion) against its source. */ export function runLessonQualityJudge(config, lessonContent, sourceContent, chat, options = {}) { const input = { lesson: lessonContent, source: sourceContent, ...(options.feedback ? { feedback: options.feedback } : {}), ...(options.related ? { related: options.related } : {}), ...(options.extending !== undefined ? { extending: options.extending } : {}), }; return runQualityJudge(lessonQualityJudge, "lesson_quality_gate", config, input, chat, options); } /** Judge an in-place reflect revision without new-lesson novelty criteria. */ export function runReflectQualityJudge(config, candidateContent, sourceContent, feedback, chat, options = {}) { const input = { source: sourceContent, candidate: candidateContent, feedback, ...(options.ref !== undefined ? { ref: options.ref } : {}), }; return runQualityJudge(reflectQualityJudge, "proposal_quality_gate", config, input, chat, options); }