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
841 lines (840 loc) • 41.2 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 reflect [ref]` — ask a model whether an asset's `description`,
* `when_to_use` and title need a fix, and queue the asset with that fix as a
* proposal (`source: "reflect"`). The model never writes the body: akm keeps
* it byte for byte. Reflect never writes an asset: the proposal queue is the
* only path, `akm proposal accept` the bridge.
*
* Every invocation closes with one `reflect_completed` event; `reflect_invoked`
* is emitted once the dispatch has validated its credentials (deterministic
* pre-dispatch refusals still emit both).
*/
import path from "node:path";
import { serializeFrontmatter } from "../../core/asset/asset-serialize.js";
import { parseFrontmatter } from "../../core/asset/frontmatter.js";
import { lookupAsset } from "../../core/assets/read.js";
import { assetType } from "../../core/assets/type.js";
import { addressOf } from "../../core/assets/write.js";
import { DESCRIPTION_MAX_CHARS, requiresDescription } from "../../core/authoring-rules.js";
import { bundleAt } from "../../core/bundle-at-dir.js";
import { isWithin, resolveStashDir, safeRealpath } from "../../core/common.js";
import { loadConfig } from "../../core/config/config.js";
import { SHIPPED_ALIAS } from "../../core/config/model-aliases.js";
import { generatedContentRejection } from "../../core/content-safety.js";
import { ConfigError, UsageError } from "../../core/errors.js";
import { appendEvent, readEvents } from "../../core/events.js";
import { lintLessonContent } from "../../core/lesson-lint.js";
import { resolveStandardsContext } from "../../core/standards/resolve-standards-context.js";
import { warnOnce } from "../../core/warn.js";
import { noticeSet } from "../../execution/notices.js";
import { buildReflectOutputRepairPrompt, buildReflectPrompt, REFLECT_CONTENT_CAP, } from "../../integrations/agent/prompts.js";
import { getHarness } from "../../integrations/harnesses/index.js";
import { isJsonSchemaKnownUnsupported } from "../../llm/client.js";
import { isRefused, structuredLoop } from "../../llm/structured.js";
import { enoentHintMessage, isEnoentFailure } from "../agent/agent-support.js";
import { isValidDescription } from "../proposal/validators/proposal-quality-validators.js";
import { CHARS_PER_TOKEN, DEFAULT_CONTEXT_LENGTH_TOKENS } from "./consolidate/chunking.js";
import { contentHash } from "./content-hash.js";
import { resolveImproveExecution } from "./execution.js";
import { recordLedgerAttempt, stateKey } from "./ledger.js";
import { enrichesMemory, proposeMemoryTags, withEnrichedPatch } from "./memory-enrichment.js";
import { bodyHasH1, classifyReflectChange, findReflectDefect, splitFrontmatter, } from "./reflect-noise.js";
import { parseFramedReflectOutput, parseSchemaReflectOutput, } from "./reflect-output.js";
import { callStageOnce, errMessage, mintProposal, rejectedProposalContext, resolveQualityGateJudge, runReflectQualityJudge, } from "./stage.js";
const MAX_FEEDBACK_LINES = 10;
const MAX_GLOBAL_FEEDBACK_LINES = 20;
/** Ends a feedback line whose event judged text the asset no longer has. */
const EARLIER_TEXT_MARK = " (given on an earlier version of the text)";
function readOnlyEventsContext(ctx) {
return ctx?.db ? ctx : { ...(ctx ?? {}), readOnly: true };
}
/**
* Recent `feedback` lines for `ref` (or across all assets without one). Given the
* asset's current content, a line whose event recorded the hash of a different
* body is marked. Best-effort.
*/
function readRecentFeedback(ref, eventsCtx, assetContent) {
try {
const events = readEvents({ type: "feedback", ...(ref ? { ref } : {}) }, readOnlyEventsContext(eventsCtx)).events;
const bodyHash = assetContent === undefined ? undefined : contentHash(assetContent, "body");
return events.slice(-(ref ? MAX_FEEDBACK_LINES : MAX_GLOBAL_FEEDBACK_LINES)).map((event) => {
const md = event.metadata ?? {};
const signal = typeof md.signal === "string" ? md.signal : "?";
const note = typeof md.reason === "string" ? md.reason : typeof md.note === "string" ? md.note : "";
const details = note ? `[${signal}] ${note}` : `[${signal}]`;
const line = !ref && event.ref ? `${event.ref} ${details}` : details;
return bodyHash !== undefined && typeof md.contentHash === "string" && md.contentHash !== bodyHash
? `${line}${EARLIER_TEXT_MARK}`
: line;
});
}
catch {
return [];
}
}
/**
* Types reflect may patch: its output is frontmatter + markdown, which would
* break a script or env file. Another type is allowed only when its current
* content already has that shape; secrets are never read.
*/
export const REFLECT_ALLOWED_TYPES = new Set([
"knowledge",
"memory",
"lesson",
"skill",
"agent",
"command",
"workflow",
]);
const REFLECT_REFUSED_TYPES = new Set(["secret"]);
/** Lesson lint findings for the prompt: a concrete starting point for the revision. */
function buildSchemaHints(type, content) {
if (!content || type !== "lesson")
return [];
return lintLessonContent(content, "reflect").findings.map((f) => `[${f.kind}] ${f.message}`);
}
/**
* A description derived from existing metadata (title, first heading, first
* prose sentence) that passes `isValidDescription`, or `undefined`. Never
* free-form invention.
*/
function deriveDescriptionFromAsset(title, body, targetRef) {
const candidates = [];
if (typeof title === "string" && title.trim())
candidates.push({ text: title.trim(), kind: "fragment" });
const heading = body.match(/^#{1,6}\s+(.+?)\s*$/m)?.[1];
if (heading)
candidates.push({ text: heading.trim(), kind: "fragment" });
const sentence = firstProseSentence(body);
if (sentence)
candidates.push({ text: sentence, kind: "prose" });
for (const { text, kind } of candidates) {
const normalized = text
.replace(/`/g, "")
.replace(/^[#>*\-\s]+/, "")
.replace(/\s+/g, " ")
.trim();
if (!normalized)
continue;
// A bare title/heading reads poorly as a description: prefer the sentence form.
const variants = kind === "fragment" ? [`Reference notes on ${normalized}.`, normalized] : [normalized];
for (const v of variants) {
const clamped = v.length > DESCRIPTION_MAX_CHARS ? v.slice(0, DESCRIPTION_MAX_CHARS).trimEnd() : v;
if (isValidDescription(clamped, targetRef, { skipRefTailCheck: true }).ok)
return clamped;
}
}
return undefined;
}
function firstProseSentence(body) {
for (const rawLine of body.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || /^(#{1,6}\s|```|~~~|[-*+]\s|\d+\.\s|>|\||<!--)/.test(line))
continue;
return (line.match(/^(.+?[.!?])(\s|$)/)?.[1] ?? line).trim();
}
return "";
}
/** The body with `# title` and one blank line inserted at its first non-blank line; the rest is untouched. */
function withH1(body, title) {
const eol = body.match(/\r?\n/)?.[0] ?? "\n";
const leading = body.match(/^(?:\r?\n)*/)?.[0] ?? "";
return `${leading}# ${title}${eol}${eol}${body.slice(leading.length)}`;
}
/**
* The asset with the patch applied, or `undefined` when the patch changes
* nothing (or there is no asset to patch). The body is the source's own, byte
* for byte; the one thing akm adds to it is a `# title` heading it lacks, with
* one blank line after it (#1183). A
* required description that neither the source nor the patch has is derived
* from the asset's own text (#636). Only the changed keys' frontmatter lines are
* rewritten: every other line is kept as it is, so a source whose YAML the
* parser reads only in part (a broken description beside a list) loses nothing.
*/
export function applyReflectPatch(patch, sourceContent, targetRef, refType) {
if (!sourceContent.trim())
return undefined;
const { fmText, body: sourceBody } = splitFrontmatter(sourceContent);
// A fence that is opened and never closed (`---` fused onto the last value)
// would leave the old block in the body under a new one: a person fixes it.
if (fmText === null && /^---\r?\n/.test(sourceContent))
return undefined;
const sourceFm = fmText !== null ? parseFrontmatter(sourceContent).data : {};
const { title, ...changes } = patch;
const addTitle = title !== undefined && !bodyHasH1(sourceBody);
// The heading and one blank line go in at the body's first non-blank line, in
// the body's own line ending; every other byte of the body stays where it was.
const body = addTitle ? withH1(sourceBody, title) : sourceBody;
// Only a source that already has frontmatter but no description gets one:
// injecting a whole block, or overwriting an authored one, is out of scope.
const desc = changes.description ?? sourceFm.description;
if (refType &&
requiresDescription(refType) &&
(typeof desc !== "string" || desc.trim().length === 0) &&
Object.keys(sourceFm).length > 0) {
const derived = deriveDescriptionFromAsset(sourceFm.title, body, targetRef);
if (derived)
changes.description = derived;
}
for (const key of Object.keys(changes))
if (changes[key] === sourceFm[key])
delete changes[key];
if (!addTitle && Object.keys(changes).length === 0)
return undefined;
// No frontmatter at all stays body-only unless the patch adds a field. The
// blank line after a closing fence is part of the source body, so only a
// block or heading akm adds brings its own.
if (fmText === null) {
if (Object.keys(changes).length === 0)
return { content: body };
const content = `---\n${serializeFrontmatter(changes)}\n---\n\n${body}`;
return { content, frontmatter: parseFrontmatter(content).data };
}
const content = `---\n${patchFrontmatterLines(fmText, changes)}\n---\n${body}`;
return { content, frontmatter: parseFrontmatter(content).data };
}
/** The frontmatter text with each changed key's lines (the key line and its indented continuation) replaced, or appended. */
function patchFrontmatterLines(fmText, changes) {
const lines = fmText.split(/\r?\n/);
for (const [key, value] of Object.entries(changes)) {
const replacement = serializeFrontmatter({ [key]: value }).split("\n");
const start = lines.findIndex((line) => line.startsWith(`${key}:`));
if (start === -1) {
lines.push(...replacement);
continue;
}
let end = start + 1;
while (end < lines.length && /^[ \t]/.test(lines[end] ?? ""))
end++;
lines.splice(start, end - start, ...replacement);
}
return lines.join("\n");
}
// ── Output contract ──────────────────────────────────────────────────────────
//
// A connection and a harness are asked for the same reply: the JSON object of
// REFLECT_JSON_SCHEMA, or the framed-markdown frame for a connection whose
// endpoint rejects JSON Schema. The reply is validated by the parse functions
// below and repaired once, whatever produced it.
const REFLECT_FRONTMATTER_PATCH_JSON_SCHEMA = {
type: "object",
required: ["description", "when_to_use", "title"],
additionalProperties: false,
properties: {
description: { type: ["string", "null"] },
when_to_use: { type: ["string", "null"] },
title: { type: ["string", "null"] },
},
};
const REFLECT_CONFIDENCE_SCHEMA = {
type: "number",
minimum: 0,
maximum: 1,
description: "Self-reported quality confidence in [0, 1]. Persisted on the proposal for reviewers and the triage judge to read during adjudication.",
};
export const REFLECT_JSON_SCHEMA = {
type: "object",
required: ["confidence", "frontmatterPatch"],
additionalProperties: false,
properties: {
confidence: REFLECT_CONFIDENCE_SCHEMA,
frontmatterPatch: REFLECT_FRONTMATTER_PATCH_JSON_SCHEMA,
},
};
export const REFLECT_UNSCOPED_JSON_SCHEMA = {
type: "object",
required: ["ref", "confidence", "frontmatterPatch"],
additionalProperties: false,
properties: {
ref: { type: "string", description: "Selected asset ref as a subdir-qualified conceptId." },
confidence: { type: "number", minimum: 0, maximum: 1, description: "Self-reported quality confidence in [0, 1]." },
frontmatterPatch: REFLECT_FRONTMATTER_PATCH_JSON_SCHEMA,
},
};
/**
* Frame for JSON Schema unless the connection already proved
* this process that it rejects it (the transport retries plain text on a 4xx).
*/
function wantsJsonSchemaOutput(connection) {
return !isJsonSchemaKnownUnsupported(connection);
}
/** A failure only a message describes, as a process that printed it and exited would have: what a connection reports. */
function messageFailure(error, reason, stdout = "", exitCode = 1) {
return { reason, error, exitCode, stdout, stderr: error };
}
/** How a failed dispatch is reported: an agent as it ran (exit code, streams, reason), a connection by its message. */
function dispatchFailure(outcome, runner, signal) {
const result = runner.kind === "connection" ? undefined : outcome.result;
if (result) {
const reason = result.reason ?? "non_zero_exit";
return {
reason,
error: result.error ?? `agent failure (${reason})`,
exitCode: result.exitCode,
stdout: result.stdout,
stderr: result.stderr,
};
}
return messageFailure(outcome.error, signal?.aborted || outcome.reason === "aborted"
? "aborted"
: outcome.reason === "timeout"
? "timeout"
: "non_zero_exit");
}
/**
* One reflect call on a connection or a harness (errors captured, never thrown except
* configuration). A connection and a harness are sent the same request, with the reply's
* schema as the output schema, and its reply is held to the same contract: an
* unparseable reply gets one repair turn within the original deadline, then
* fails. A failed agent dispatch is reported as it ran, with its exit code and
* stderr; an LLM call has only its message.
*/
export async function runReflectIteration(opts) {
const start = Date.now();
let repairAttempts = 0;
const configuredTimeout = Object.hasOwn(opts, "timeoutMs") ? (opts.timeoutMs ?? null) : opts.runner.timeoutMs;
const deadline = typeof configuredTimeout === "number" ? start + configuredTimeout : undefined;
const messages = [{ role: "user", content: opts.prompt ?? "" }];
const enrichMemory = opts.enrichMemory === true;
const parse = (raw) => {
try {
return {
ok: true,
value: opts.outputMode === "json_schema"
? parseSchemaReflectOutput(raw, opts.targetRef, enrichMemory)
: parseFramedReflectOutput(raw, opts.targetRef, enrichMemory),
};
}
catch (err) {
return { ok: false, errors: [errMessage(err)] };
}
};
const failed = (failure) => ({
ok: false,
durationMs: Date.now() - start,
telemetry: { outputMode: opts.outputMode, repairAttempts },
...failure,
});
// Reflect parses and repairs its own reply (the repair turn below), so one dispatch, unvalidated.
const call = (callMessages, repairTimeoutMs) => callStageOnce({
runner: opts.runner,
prompt: callMessages.at(-1)?.content ?? "",
history: callMessages.slice(0, -1),
request: {
...(repairTimeoutMs !== undefined
? { timeoutMs: repairTimeoutMs }
: Object.hasOwn(opts, "timeoutMs")
? { timeoutMs: opts.timeoutMs }
: {}),
...(opts.signal ? { signal: opts.signal } : {}),
...(opts.responseSchema !== undefined ? { responseSchema: opts.responseSchema } : {}),
...(opts.maxTokens !== undefined ? { maxTokens: opts.maxTokens } : {}),
// Visible chain-of-thought can exhaust the output before the envelope.
enableThinking: false,
...(opts.chat ? { chat: opts.chat } : {}),
},
...(opts.environment ? { current: { environment: opts.environment } } : {}),
...(opts.onNotices ? { onNotices: opts.onNotices } : {}),
});
try {
if (opts.signal?.aborted)
return failed(messageFailure("Reflect request aborted", "aborted"));
const loop = await structuredLoop({
dispatch: async (correction) => {
if (!correction)
return call(messages);
// The repair turn spends what is left of the original deadline, and does not start once the caller has aborted.
if (opts.signal?.aborted)
return { ok: false, reason: "aborted", error: "Reflect request aborted" };
const remaining = deadline === undefined ? undefined : deadline - Date.now();
if (remaining !== undefined && remaining <= 0) {
return { ok: false, reason: "timeout", error: "Reflect request timed out before output repair" };
}
repairAttempts = 1;
const repair = `${buildReflectOutputRepairPrompt(opts.outputMode, opts.targetRef !== undefined, enrichMemory)}\n\nWhat was wrong with it: ${correction.text}`;
return call([...messages, { role: "assistant", content: correction.reply }, { role: "user", content: repair }], remaining);
},
parse,
correct: (refusal) => refusal.errors.join("; "),
});
if (!loop.ok) {
// A reply that broke the contract: its message is the parser's, on a connection and a harness alike.
if (isRefused(loop))
return failed(messageFailure(loop.errors.join("; "), "parse_error", loop.raw, 0));
return failed(dispatchFailure(loop, opts.runner, opts.signal));
}
return {
ok: true,
payload: loop.value,
durationMs: Date.now() - start,
telemetry: { outputMode: opts.outputMode, repairAttempts },
};
}
catch (err) {
if (err instanceof ConfigError)
throw err;
return failed(messageFailure(errMessage(err), opts.signal?.aborted ? "aborted" : "non_zero_exit"));
}
}
/** The lazy `reflect_invoked` + failure-side `reflect_completed` emitters. */
function reflectEmitters(options) {
let invoked = false;
const emitInvoked = () => {
if (invoked)
return;
appendEvent({
eventType: "reflect_invoked",
...(options.ref ? { ref: options.itemRef ?? options.ref } : {}),
metadata: {
...(options.task ? { task: options.task } : {}),
...(options.eligibilitySource ? { eligibilitySource: options.eligibilitySource } : {}),
},
}, options.eventsCtx);
invoked = true;
};
const emitFailed = (reason, subreason, ref, extra) => {
emitInvoked();
appendEvent({
eventType: "reflect_completed",
...(ref ? { ref } : {}),
metadata: { source: "reflect", ok: false, reason, subreason, ...(extra ?? {}) },
}, options.eventsCtx);
};
return { emitInvoked, emitFailed };
}
/** The failure envelope for `failure` (with the run's notices). */
function reflectFailure(run, failure) {
return {
schemaVersion: 2,
ok: false,
reason: failure.reason,
error: failure.error,
...(run.options.ref ? { ref: run.options.ref } : {}),
engine: run.engineName,
exitCode: failure.exitCode,
...(failure.stdout ? { stdout: failure.stdout } : {}),
...(failure.stderr ? { stderr: failure.stderr } : {}),
...run.notices.fields(),
};
}
/** A failure after a dispatch that succeeded: the exit code is its, there is no output to report. */
function refusal(reason, error) {
return { reason, error, exitCode: 0 };
}
function exitCodeMeta(failure) {
return failure.exitCode !== null ? { exitCode: failure.exitCode } : {};
}
function unsupportedTypeFailure(ref, type, detail, emitFailed) {
emitFailed("unsupported_type", "unsupported_type", ref, { type });
return {
failure: {
schemaVersion: 2,
ok: false,
reason: "unsupported_type",
error: `Reflect refused: asset type "${type}" is not supported by reflect (${detail}). Use \`akm proposal new\` or edit the file directly.`,
ref,
exitCode: null,
},
};
}
/**
* A proposal writes the file that owns the ref in the proposal's bundle. When the indexed file is another one,
* accepting the proposal would leave the indexed file as it is (#1052).
*/
function fileOutsideLayoutFailure(ref, file, writes, emitFailed) {
emitFailed("unsupported_type", "file_outside_layout", ref);
return {
failure: {
schemaVersion: 2,
ok: false,
reason: "unsupported_type",
error: `Reflect refused: the file for ${ref} is ${file}, but a proposal would write ${writes}. Edit the file directly.`,
ref,
exitCode: null,
},
};
}
/** The target's parsed ref and current content, or a refusal for a type reflect cannot patch. */
async function resolveReflectSource(options, stash, emitFailed) {
if (!options.ref)
return { assetContent: undefined, parsedRef: undefined };
// A proposal writes the file that owns the ref in the proposal's own bundle; the type is that of
// the file that owns it wherever it is (a file in another bundle is `createProposal`'s to refuse, #1000).
const root = path.resolve(options.target?.root ?? stash);
const address = addressOf(bundleAt(root), options.ref);
const owned = lookupAsset(options.itemRef ?? options.ref, { bundle: bundleAt(stash) });
const parsedRef = { type: owned ? assetType(owned) : address.type, name: address.name };
// A secret's content is never read, whatever it looks like.
if (REFLECT_REFUSED_TYPES.has(parsedRef.type)) {
return unsupportedTypeFailure(options.ref, parsedRef.type, "secret material is never read or sent to an LLM", emitFailed);
}
let assetContent = options.assetContent;
let assetFile;
if (assetContent === undefined) {
try {
const held = owned ?? lookupAsset(options.itemRef ?? options.ref, { bundle: bundleAt(stash) });
if (held) {
// asset-io: display the layout guard below names the file in its refusal
assetFile = held.entry.file;
assetContent = held.entry.content();
}
}
catch {
// An index miss is not fatal: reflect then has no content to patch.
}
}
if (!REFLECT_ALLOWED_TYPES.has(parsedRef.type) &&
(assetContent === undefined || parseFrontmatter(assetContent).frontmatter === null)) {
return unsupportedTypeFailure(options.ref, parsedRef.type, "its content is not frontmatter + markdown", emitFailed);
}
// A file in another bundle is `createProposal`'s to refuse (#1000); this one is in the proposal's own bundle.
if (assetFile !== undefined && address.file !== undefined && isWithin(assetFile, root)) {
if (safeRealpath(address.file) !== safeRealpath(assetFile)) {
return fileOutsideLayoutFailure(options.ref, assetFile, address.file, emitFailed);
}
}
return { assetContent, parsedRef };
}
/**
* The single connection or harness for this invocation: the one the improve
* plan froze for reflect, else reflect's place in improve's cascade. Whatever
* its kind, reflect runs it under the model-work tool policy.
*/
function resolveReflectRunner(options) {
const config = options.config ?? loadConfig();
const activeStrategy = options.improveProfile ?? config.improve?.strategies?.[config.improve?.strategy ?? "default"];
// The plan resolved reflect's runner once, with its notices; each asset does not resolve it again.
const resolved = Object.hasOwn(options, "llmRunner")
? options.llmRunner
? { runner: options.llmRunner, notices: [] }
: null
: resolveImproveExecution({
config,
processName: "reflect",
alias: SHIPPED_ALIAS.improve,
...(options.run ? { run: options.run } : {}),
});
if (!resolved) {
throw new ConfigError("Reflect requires a connection or harness for the active improve strategy.", "LLM_NOT_CONFIGURED", "Run `akm setup`, or set improve.connection or improve.processes.reflect.connection.");
}
return {
config,
activeStrategy,
runnerSpec: resolved.runner,
engineName: resolved.runner.name,
notices: resolved.notices,
};
}
/** Whether a harness takes the prompt as an argument, which the OS limits; one that reads it from stdin does not. */
function promptInArgv(runner) {
const harness = getHarness(runner.platform);
return harness?.build({ bin: runner.bin, args: runner.args }, { prompt: "x" }).stdin === undefined;
}
/**
* The flat 12k content cap exists for CLI argv, so only a harness that takes the
* prompt there keeps it (`undefined`); one that reads stdin (claude, OpenCode)
* has none (`null`). The HTTP runner can spend half its context window (after
* the rest of the prompt) on the asset, reserving the other half for the reply.
* Never below the flat floor.
*/
function computeReflectContentBudgetChars(promptInput, runnerSpec) {
if (runnerSpec.kind === "harness")
return promptInArgv(runnerSpec) ? undefined : null;
if (!promptInput.assetContent?.trim())
return undefined;
const window = (runnerSpec.contextLength ?? DEFAULT_CONTEXT_LENGTH_TOKENS) * CHARS_PER_TOKEN;
const overhead = buildReflectPrompt({ ...promptInput, contentBudgetChars: 0 }).prompt.length;
return Math.max(REFLECT_CONTENT_CAP, Math.floor((window - overhead) / 2));
}
/** Every read-only prompt input, shared by dispatch and `--show-prompt`. */
function gatherReflectPromptSources(options, stash, parsedRef, assetContent) {
return {
feedback: readRecentFeedback(options.ref ? (options.itemRef ?? options.ref) : undefined, options.eventsCtx, assetContent),
schemaHints: buildSchemaHints(parsedRef?.type ?? "", assetContent),
rejectedProposals: rejectedProposalContext(stash, options.ref, options.ctx, options.eventsCtx, options.ref ? { source: "reflect", ref: stateKey(options.ref, options.itemRef) } : undefined),
standardsContext: resolveStandardsContext(parsedRef?.type, stash),
};
}
/** The exact prompt reflect sends, shared by dispatch and `--show-prompt`. */
function buildReflectPromptText(args) {
const { options, parsedRef, assetContent, sources, runnerSpec } = args;
const { feedback, schemaHints, rejectedProposals, standardsContext } = sources;
// A connection that rejects JSON Schema gets the framed contract; a harness gets the JSON object.
const outputMode = runnerSpec.kind === "connection" && !wantsJsonSchemaOutput(runnerSpec) ? "framed_markdown" : "json_schema";
const input = {
...(options.ref ? { ref: options.ref } : {}),
...(parsedRef?.type ? { type: parsedRef.type } : {}),
...(parsedRef?.name ? { name: parsedRef.name } : {}),
...(assetContent !== undefined ? { assetContent } : {}),
...(feedback.length > 0 ? { feedback } : {}),
...(schemaHints.length > 0 ? { schemaHints } : {}),
...(options.task ? { task: options.task } : {}),
...(standardsContext.trim() ? { standardsContext } : {}),
...(options.avoidPatterns && options.avoidPatterns.length > 0 ? { avoidPatterns: options.avoidPatterns } : {}),
...(rejectedProposals.length > 0 ? { rejectedProposals } : {}),
enrichMemory: options.enrichMemory,
outputMode,
};
const contentBudgetChars = computeReflectContentBudgetChars(input, runnerSpec);
const { prompt } = buildReflectPrompt({
...input,
...(contentBudgetChars !== undefined ? { contentBudgetChars } : {}),
});
return { prompt, outputMode };
}
/**
* Dispatch the reflect request once. Under the model-work tool policy an agent can edit only its own scratch
* directory, which is gone once it returns, so it returns the proposal as its reply, as an LLM does.
*/
async function dispatchReflect(args) {
const { run, parsedRef, assetContent, sources, agentEnv } = args;
const { options, runnerSpec } = run;
const { prompt, outputMode } = buildReflectPromptText({ options, parsedRef, assetContent, sources, runnerSpec });
const schema = options.ref ? REFLECT_JSON_SCHEMA : REFLECT_UNSCOPED_JSON_SCHEMA;
return runReflectIteration({
prompt,
runner: runnerSpec,
...(Object.hasOwn(options, "timeoutMs") ? { timeoutMs: options.timeoutMs } : {}),
...(options.signal ? { signal: options.signal } : {}),
...(outputMode === "json_schema"
? { responseSchema: options.enrichMemory ? withEnrichedPatch(schema) : schema }
: {}),
outputMode,
enrichMemory: options.enrichMemory,
...(options.ref ? { targetRef: options.ref } : {}),
...(options.chat ? { chat: options.chat } : {}),
// Only a harness (or the internal runtime) runs a child process, which has an environment.
...(runnerSpec.kind !== "connection" && Object.keys(agentEnv).length > 0 ? { environment: agentEnv } : {}),
onNotices: run.notices.add,
});
}
const NOISE_SUBREASONS = {
noop: "reflect_skipped_noop",
cosmetic: "reflect_skipped_cosmetic",
};
/**
* Apply the patch, drop a no-op/cosmetic change,
* judge the exact content that would be persisted, then mint. A revision with a
* deterministic defect is refused before the judge runs, whether or not the
* gate is on.
*/
async function finalizeReflectProposal(args) {
const { run, payload, assetContent, dispatch, judge, feedback } = args;
const { options } = run;
const { telemetry } = dispatch;
const patched = applyReflectPatch(payload.patch, assetContent, payload.ref, args.type);
// A patch that changes nothing leaves the asset as it is: an empty diff.
const content = patched?.content ?? assetContent;
const changeKind = classifyReflectChange(assetContent, content);
if (changeKind === "noop" || changeKind === "cosmetic") {
run.emitFailed("no_change", NOISE_SUBREASONS[changeKind], options.ref, { changeKind, ...telemetry });
const what = changeKind === "noop"
? "identical to the current asset (empty diff)"
: "a cosmetic-only reformat of the current asset (whitespace/fence/YAML-folding changes)";
return reflectFailure(run, refusal("no_change", `Reflect skipped: proposed content for ${payload.ref} is ${what}; no proposal created.`));
}
/** A judge refused the revision: record it for the ledger's rejection window and stop. */
const refuse = (detail, metadata, message) => {
if (options.ref) {
recordLedgerAttempt({ proposalsCtx: options.ctx, eventsCtx: options.eventsCtx }, {
stashDir: run.stash,
ref: stateKey(options.ref, options.itemRef),
source: "reflect",
outcome: "quality_rejected",
detail,
});
}
appendEvent({
eventType: "reflect_completed",
ref: payload.ref,
metadata: { source: "reflect", qualityRejected: true, ...metadata, ...telemetry },
}, options.eventsCtx);
return reflectFailure(run, refusal("quality_rejected", message));
};
// A defect no judge needs to weigh is refused before any judge call, whether or not the gate is on.
const defect = findReflectDefect(assetContent, content, options.defectFilter);
if (defect)
return refuse(defect, { reflectDefect: defect }, `Reflect proposal refused before the judge: ${defect}`);
let verdict;
let judgeFailed = false;
let judgeUncertain = false;
if (judge.enabled) {
verdict = await runReflectQualityJudge(run.config, content, assetContent, feedback, options.chat, {
runnerSelectionFrozen: true,
ref: payload.ref,
...(judge.runner ? { llmRunner: judge.runner } : {}),
...(Object.hasOwn(options, "timeoutMs") ? { timeoutMs: options.timeoutMs } : {}),
...(options.signal ? { signal: options.signal } : {}),
onNotices: run.notices.add,
});
// A judge that timed out, errored or replied unparseably gave no verdict: a person reviews the revision.
judgeFailed = verdict.reviewNeeded === true && verdict.score === -1;
// A real score the judge marks for review is uncertain, not bad: a person decides, and no window is recorded.
judgeUncertain = verdict.reviewNeeded === true && !judgeFailed;
if (!verdict.pass && !judgeFailed && !judgeUncertain) {
return refuse(verdict.reason, {
qualityScore: verdict.score,
qualityReason: verdict.reason,
...(verdict.criteria ? { qualityCriteria: verdict.criteria } : {}),
}, `Reflect proposal quality gate rejected: score=${verdict.score}, reason="${verdict.reason}"`);
}
}
const reviewReasons = [
...(judge.skippedNoJudge ? ["no-judge-configured"] : []),
...(judgeFailed ? ["judge-error"] : []),
...(judgeUncertain ? ["judge-uncertain"] : []),
];
const gateReview = judgeFailed || judgeUncertain;
const proposal = mintProposal(run.stash, options.ctx, {
ref: payload.ref,
...(options.target ? { target: options.target } : {}),
source: "reflect",
sourceRun: `reflect-${Date.now()}`,
payload: { content, ...(patched?.frontmatter ? { frontmatter: patched.frontmatter } : {}) },
confidence: payload.confidence,
...(options.eligibilitySource ? { eligibilitySource: options.eligibilitySource } : {}),
...(options.itemRef ? { itemRef: options.itemRef, attemptedRefs: [options.itemRef] } : {}),
}, reviewReasons.length > 0
? {
review: {
reason: reviewReasons.join("+"),
// The quality gate's hand-off to a person, as distill's: the triage drain leaves it alone.
gate: gateReview ? "quality-gate" : "reflect",
...(gateReview && verdict?.criteria ? { scores: verdict.criteria } : {}),
...(gateReview && verdict?.reason ? { judgeReason: verdict.reason } : {}),
},
}
: { judged: verdict });
appendEvent({
eventType: "reflect_completed",
ref: proposal.ref,
metadata: {
proposalId: proposal.id,
source: "reflect",
engine: run.engineName,
...(judge.skippedNoJudge ? { qualityGateSkippedNoJudge: true } : {}),
...(judgeFailed || judgeUncertain ? { qualityReason: verdict?.reason } : {}),
...(judgeUncertain ? { qualityScore: verdict?.score } : {}),
...telemetry,
},
}, options.eventsCtx);
return {
schemaVersion: 2,
ok: true,
proposal,
ref: proposal.ref,
engine: run.engineName,
durationMs: dispatch.durationMs,
...run.notices.fields(),
};
}
/**
* `akm improve <ref> --show-prompt`: the exact prompt reflect would send for
* one asset. Read-only: no credential, no dispatch, no event.
*/
export async function renderReflectPromptPreview(options) {
if (!options.ref) {
throw new UsageError("renderReflectPromptPreview requires options.ref.", "INVALID_FLAG_VALUE");
}
const ref = options.ref;
const stash = options.stashDir ?? resolveStashDir();
const source = await resolveReflectSource(options, stash, () => { });
if ("failure" in source) {
const { failure } = source;
throw new UsageError((!failure.ok && failure.error) || `Reflect cannot preview ref "${ref}".`, "INVALID_FLAG_VALUE");
}
const { config, runnerSpec, engineName } = resolveReflectRunner(options);
const sources = gatherReflectPromptSources(options, stash, source.parsedRef, source.assetContent);
const { prompt } = buildReflectPromptText({
options: { ...options, enrichMemory: enrichesMemory(config, source.parsedRef, source.assetContent) },
parsedRef: source.parsedRef,
assetContent: source.assetContent,
sources,
runnerSpec,
});
return { ref, prompt, engine: engineName, engineKind: runnerSpec.kind };
}
export async function akmReflect(options = {}) {
const stash = options.stashDir ?? resolveStashDir();
const { emitInvoked, emitFailed } = reflectEmitters(options);
const source = await resolveReflectSource(options, stash, emitFailed);
if ("failure" in source)
return source.failure;
const { assetContent, parsedRef } = source;
const { config, activeStrategy, runnerSpec, engineName, notices: resolutionNotices } = resolveReflectRunner(options);
const notices = noticeSet();
notices.add(resolutionNotices);
const run = {
options: { ...options, enrichMemory: enrichesMemory(config, parsedRef, assetContent) },
stash,
config,
runnerSpec,
engineName,
notices,
emitInvoked,
emitFailed,
};
// Judge selection is frozen before dispatch so a missing judge credential fails first.
const judgeWanted = activeStrategy?.processes?.reflect?.qualityGate?.enabled ?? true;
let judgeRunner;
if (judgeWanted)
judgeRunner = resolveQualityGateJudge(config, activeStrategy, "reflect", notices.add, options.run);
const skippedNoJudge = judgeWanted && !judgeRunner;
if (skippedNoJudge) {
warnOnce("reflect-quality-gate-no-judge", "Reflect proposal quality gate has no connection or harness to judge proposals (run `akm setup`). Skipping the gate for this run; the proposal is queued for human review instead.");
}
const sources = gatherReflectPromptSources(options, stash, parsedRef, assetContent);
const agentEnv = options.eventSource === "improve" ? { AKM_EVENT_SOURCE: "improve" } : {};
let iteration;
try {
iteration = await dispatchReflect({ run, parsedRef, assetContent, sources, agentEnv });
}
catch (error) {
if (!(error instanceof ConfigError))
emitInvoked();
throw error;
}
emitInvoked();
if (!iteration.ok) {
const enoent = isEnoentFailure(iteration);
emitFailed(enoent ? "spawn_failed" : iteration.reason, enoent ? "enoent" : iteration.reason === "parse_error" ? "parse_error" : "agent_crash", options.ref, { ...exitCodeMeta(iteration), ...iteration.telemetry });
return reflectFailure(run, enoent
? { ...iteration, error: enoentHintMessage(runnerSpec.kind === "connection" ? engineName : runnerSpec.bin) }
: iteration);
}
const { payload } = iteration;
const generated = Object.values(payload.patch).join("\n");
const unsafeContent = generatedContentRejection(generated);
if (unsafeContent) {
emitFailed("parse_error", "parse_error", options.ref, { exitCode: 0 });
return reflectFailure(run, refusal("parse_error", unsafeContent));
}
// An unscoped reply names its asset only now: read it as a targeted run read its own before dispatch.
const target = options.ref
? { assetContent, parsedRef }
: await resolveReflectSource({ ...options, ref: payload.ref }, stash, emitFailed);
if ("failure" in target)
return target.failure;
const { tags, ...patch } = payload.patch;
const judge = { enabled: judgeWanted && !skippedNoJudge, skippedNoJudge, runner: judgeRunner };
const memory = target.assetContent ?? "";
const revision = await finalizeReflectProposal({
run,
payload: { ...payload, patch },
assetContent: memory,
dispatch: iteration,
judge,
feedback: sources.feedback,
type: target.parsedRef?.type ?? "",
});
if (!tags)
return revision;
const { confidence, ref } = payload;
return {
...revision,
tags: await proposeMemoryTags({ run, ref, memory, tags, confidence, durationMs: iteration.durationMs, judge }),
};
}