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
962 lines (961 loc) • 45.1 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 { assembleAsset } from "../../core/asset/asset-serialize.js";
import { conceptIdFromTypeName } from "../../core/asset/resolve-ref.js";
import { embedPendingWrites } from "../../core/assets/type.js";
import { stateBundleId } from "../../core/bundle-at-dir.js";
import { resolveStashDir, timestampForFilename } from "../../core/common.js";
import { getImproveProcessConfig, loadConfig } from "../../core/config/config.js";
import { collectCredentialValues } from "../../core/config/credentials.js";
import { SHIPPED_ALIAS } from "../../core/config/model-aliases.js";
import { ConfigError, UsageError } from "../../core/errors.js";
import { appendEvent } from "../../core/events.js";
import { releaseLock } from "../../core/file-lock.js";
import { EXTRACT_INFRASTRUCTURE_SKIP_REASONS } from "../../core/improve-types.js";
import { resolveProject } from "../../core/projects.js";
import { collectSensitiveValues, redactErrorBody } from "../../core/redaction.js";
import { resolveStashStandards } from "../../core/standards/resolve-stash-standards.js";
import { resolveTypeConventions, typeConventionRef } from "../../core/standards/resolve-type-conventions.js";
import { getStateDbPath, openStateDatabase } from "../../core/state-db.js";
import { repairTruncatedDescription } from "../../core/text-truncation.js";
import { DURATION_UNITS, parseDuration } from "../../core/time.js";
import { warn, warnVerbose } from "../../core/warn.js";
import { noticeSet } from "../../execution/notices.js";
import { fillMetadata, stampScope } from "../../indexer/passes/metadata.js";
import { collectDispatchSensitiveValues } from "../../integrations/agent/runner-dispatch.js";
import { getAvailableHarnesses } from "../../integrations/session-logs/index.js";
import { isRefused } from "../../llm/structured.js";
import { getExtractedSessionsMap, getLastExtractRunAt, upsertExtractedSession, } from "../../storage/repositories/extract-sessions-repository.js";
import { listImproveLedgerRows } from "../../storage/repositories/improve-ledger-repository.js";
import { getStateProposal } from "../../storage/repositories/proposals-repository.js";
import { openSqliteReadSnapshot } from "../../storage/sqlite-read-snapshot.js";
import { resolveProposalQueueTarget } from "../proposal/repository.js";
import { contentHash } from "./content-hash.js";
import { resolveImproveExecution } from "./execution.js";
import { buildExtractPrompt, EXTRACT_JSON_SCHEMA, parseExtractPayload, } from "./extract-prompt.js";
import { acquireExtractSessionLock, DEFAULT_TRIAGE_MIN_SCORE, extractSessionLockPath, lockedConcurrentResult, planExtractSessions, preFilterStats, runPreLlmSessionGates, sessionOutcome, } from "./extract-sessions.js";
import { cloneAndFreeze, resolveImproveStrategy, resolveProcessEnabled } from "./improve-strategies.js";
import { isLedgerBlocked, ledgerKey, readLedgerDb } from "./ledger.js";
import { buildSessionSummaryPrompt, parseSessionSummary, SESSION_SUMMARY_JSON_SCHEMA, sessionMeetsDurationGate, writeSessionAsset, } from "./session-asset.js";
import { callStage, callStageLoop, mintProposal } from "./stage.js";
/** Minimum session duration (minutes) for writing a session asset. */
const DEFAULT_MIN_SESSION_DURATION_MINUTES = 5;
/** Raw session size (chars) below which the LLM call is skipped; only truly empty sessions are safe to skip. */
const DEFAULT_MIN_CONTENT_CHARS = 10;
/** New sessions LLM-processed per run (`processes.extract.maxSessionsPerRun`, 0 disables); the rest wait for later runs. */
const DEFAULT_MAX_SESSIONS_PER_RUN = 25;
/**
* Without an explicit window, discovery looks back to the last extract run for
* the harness (a host that was off still finds sessions that ended meanwhile),
* but never less than 48h. The content-hash ledger makes the overlap free.
*/
const DEFAULT_SINCE_FLOOR_MS = 48 * 60 * 60 * 1000;
function resolveDefaultSinceMs(harnessName, now, opts) {
const floor = now - DEFAULT_SINCE_FLOOR_MS;
if (opts.skipTracking)
return floor;
let snapshot;
try {
let db = opts.stateDb;
if (!db) {
snapshot = openSqliteReadSnapshot(opts.stateDbPath ?? getStateDbPath());
db = snapshot;
}
if (!db)
return floor;
const lastRun = getLastExtractRunAt(db, harnessName);
return lastRun != null ? Math.min(lastRun, floor) : floor;
}
catch {
return floor;
}
finally {
snapshot?.close();
}
}
/** Resolve standalone extract selection once, before discovery, auto iteration or watch startup. */
export function resolveStandaloneExtractPlan(config, selection) {
const selected = resolveImproveStrategy(selection.strategy, config);
const process = cloneAndFreeze(getImproveProcessConfig("extract", selected.config) ?? {});
// The built-in strategies turn the improve-stage extract off because sessions are extracted when they end, so only
// the person's own `enabled: false` for this strategy, or the host-wide `improve.enabled: false`, stops the
// standalone run. Nothing then resolves a runner.
if (config.improve?.enabled === false ||
config.improve?.strategies?.[selected.name]?.processes?.extract?.enabled === false) {
return Object.freeze({
strategy: selected.name,
engine: "",
enabled: false,
process,
runner: null,
embeddingConfig: cloneAndFreeze(config.embedding),
});
}
const resolved = resolveImproveExecution({
config,
current: {
...(selection.connection ? { connection: selection.connection } : {}),
...(selection.harness ? { harness: selection.harness } : {}),
...(selection.engine ? { engine: selection.engine } : {}),
...(selection.model ? { model: selection.model } : {}),
...(Object.hasOwn(selection, "timeoutMs") ? { timeoutMs: selection.timeoutMs ?? null } : {}),
},
processName: "extract",
alias: SHIPPED_ALIAS.extract,
});
if (!resolved) {
throw new ConfigError("No connection or harness is configured for extract. Run `akm setup`, pass --connection or --harness, or set improve.connection or improve.processes.extract.connection.", "LLM_NOT_CONFIGURED");
}
const runner = resolved.runner;
return Object.freeze({
strategy: selected.name,
engine: runner.name,
enabled: true,
process,
runner: cloneAndFreeze(runner),
embeddingConfig: cloneAndFreeze(config.embedding),
...(resolved.notices.length > 0 ? { notices: cloneAndFreeze(resolved.notices) } : {}),
});
}
/** An extract envelope for a run that processed no sessions. */
function emptyExtractResult(args) {
return {
schemaVersion: 1,
ok: args.ok,
shape: "extract-result",
dryRun: args.dryRun,
type: args.type,
sessionsProcessed: 0,
sessionsSkipped: 0,
candidatesCreated: 0,
proposals: [],
sessions: [],
warnings: [args.warning],
durationMs: Date.now() - args.startMs,
...(args.llmRunner ? { engine: args.llmRunner.name, engineKind: args.llmRunner.kind } : {}),
};
}
/**
* A since-string as an epoch-ms cutoff: an ISO timestamp or `<n>m|h|d`
* (case-insensitive here — `5M` is five minutes). Default 24h; anything else
* is a usage error.
*/
export function parseSinceArg(value, now = Date.now()) {
if (!value || value.trim() === "")
return now - 24 * 60 * 60 * 1000;
const trimmed = value.trim();
const relMatch = trimmed.match(/^(\d+)\s*([mhd])$/i);
if (relMatch) {
const ms = parseDuration(`${relMatch[1] ?? "0"}${(relMatch[2] ?? "h").toLowerCase()}`, DURATION_UNITS);
if (ms !== null)
return now - ms;
}
const iso = Date.parse(trimmed);
if (!Number.isNaN(iso))
return iso;
throw new UsageError(`--since value "${value}" could not be parsed (expected ISO timestamp or duration like 24h / 7d / 30m)`, "INVALID_FLAG_VALUE");
}
/**
* Assemble candidate metadata once in the authoritative Markdown that acceptance
* publishes. The payload projection is for proposal readers, not another write path.
*/
function buildCandidateProposal(candidate, sourceRef, sessionAssetRef, scope = {}, projectName, metadata) {
const ref = deriveExtractCandidateRef(candidate, sourceRef, projectName);
// Complete a description the model cut mid-sentence (no-op for valid ones).
const description = repairTruncatedDescription(candidate.description, candidate.body);
const fm = {
description,
evidence: candidate.evidence,
...(sessionAssetRef ? { xrefs: [sessionAssetRef], evidenceSources: [sessionAssetRef] } : {}),
};
// With no published session asset, keep the known native session identity in
// the existing structured provenance channel, never invent an AKM asset ref.
// The identity, not the log's absolute path, so published notes carry no local paths.
if (!sessionAssetRef && sourceRef.filePath) {
fm.provenance = { sources: [{ resource: `${sourceRef.harness}:${sourceRef.sessionId}` }] };
}
if (candidate.when_to_use)
fm.when_to_use = candidate.when_to_use;
const stamped = fillMetadata(stampScope(fm, scope).data, metadata);
return { ref, content: assembleAsset(stamped, candidate.body), frontmatter: stamped };
}
function canonicalSegment(value) {
return value
.trim()
.toLowerCase()
.replace(/[^a-z0-9-]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "");
}
/** The project a session runs under: `--project`, else the one its recorded working directory is in. */
function sessionProject(run, ref) {
const { project } = run.options;
if (project !== undefined)
return resolveProject(run.config, { project });
return ref.cwd ? resolveProject(run.config, { cwd: ref.cwd }) : undefined;
}
/** The scope flags, with the project's `write` scope filling the ones not given. */
function sessionScope(project, flags = {}) {
const { user, agent, channel } = project?.write ?? {};
return { ...(user ? { user } : {}), ...(agent ? { agent } : {}), ...(channel ? { channel } : {}), ...flags };
}
/** `projectName` (a configured project) names the memory folder; without it, the platform's project hint does. */
export function deriveExtractCandidateRef(candidate, sourceRef, projectName) {
const leaf = candidate.name.split("/").map(canonicalSegment).filter(Boolean).at(-1) ?? "extracted-insight";
if (candidate.type === "memory" || candidate.type === "lesson") {
const folder = projectName ?? sourceRef.projectHint?.split(/[\\/]/).filter(Boolean).at(-1);
const scope = folder ? canonicalSegment(folder) : "";
return conceptIdFromTypeName(candidate.type, `${scope ? `${scope}/` : ""}${leaf}`);
}
return conceptIdFromTypeName("knowledge", leaf);
}
function resolveExtractStandards(stashDir) {
const sections = [];
const general = resolveStashStandards(stashDir);
if (general)
sections.push(general);
for (const type of ["memory", "lesson", "knowledge"]) {
const body = resolveTypeConventions(stashDir, type);
if (body)
sections.push(`# ${typeConventionRef(type)} (soft per-type conventions — guidance, not enforced)\n${body}`);
}
return sections.join("\n\n");
}
/** The model call's request: the response schema plus the run's abort signal and chat override, when given. */
const modelRequest = (options, responseSchema) => ({
responseSchema,
...(options.signal ? { signal: options.signal } : {}),
...(options.chat ? { chat: options.chat } : {}),
});
/**
* One session's extraction call, with one corrective retry; configuration
* errors escape before any state is written.
*/
async function extractFromSession(run, prompt) {
// This loop parses and repairs the reply itself, so each attempt is one unvalidated dispatch.
const result = await callStageLoop({
runner: run.llmRunner,
prompt,
request: modelRequest(run.options, EXTRACT_JSON_SCHEMA),
onNotices: run.notices.add,
}, (raw) => {
const payload = parseExtractPayload(raw);
return payload.parseFailure
? { ok: false, errors: [payload.parseFailure.message] }
: { ok: true, value: payload };
}, () => "## Corrective output instruction\n\nYour previous response did not contain a valid extraction payload. Respond with ONLY a JSON object matching the requested schema, with a candidates array and no prose or code fences.");
if (result.ok)
return { kind: "success", payload: result.value, attempts: result.attempts };
if (!isRefused(result))
return { kind: "unavailable" };
return {
kind: "malformed",
raw: result.raw,
attempts: result.attempts,
failure: parseExtractPayload(result.raw).parseFailure ?? {
code: "invalid_payload",
message: result.errors.join("; "),
},
};
}
/**
* Write the session's searchable asset (`sessions/<harness>/<id>.md`). Fails
* open: a failure is only a warning and never changes the extract outcome.
*/
async function maybeWriteSessionAsset(run, data) {
const { sessionIndexing } = run;
if (!sessionIndexing.enabled || run.dryRun)
return {};
if (!sessionMeetsDurationGate(data, sessionIndexing.minDurationMinutes))
return {};
try {
const result = await writeSessionAsset(data, run.stashDir, (summaryData) => sessionIndexing.generate(summaryData), sessionProject(run, data.ref)?.name);
if (!result.written)
return {};
// A standalone extract has no post-loop reindex to pick the file up.
await embedPendingWrites();
return {
...(result.ref ? { sessionAssetRef: result.ref } : {}),
...(result.logPath ? { sessionLogPath: result.logPath } : {}),
};
}
catch (err) {
if (err instanceof ConfigError)
throw err;
return { warning: `session asset write failed: ${err instanceof Error ? err.message : String(err)}` };
}
}
async function processSession(run, sessionRef, gate) {
const { harness, stashDir, sourceRun, dryRun, options } = run;
const { data, filtered, contentHash: hash } = gate;
const base = { preFilter: preFilterStats(filtered), contentHash: hash };
const project = sessionProject(run, data.ref);
const projectName = project?.name;
const extraction = await extractFromSession(run, buildExtractPrompt({
data,
events: filtered.events,
inlineRefs: data.inlineRefs,
...(run.standardsContext.trim() ? { standardsContext: run.standardsContext } : {}),
}));
const skip = (skipReason, warnings) => sessionOutcome(sessionRef.sessionId, harness.name, {
...base,
warnings,
skipped: true,
skipReason,
...run.notices.fields(),
});
if (extraction.kind === "unavailable") {
return skip("llm_unavailable", ["session_extraction feature returned empty (disabled / timeout / error)"]);
}
if (extraction.kind === "malformed") {
warnVerbose(`[extract] malformed model output for session ${sessionRef.sessionId}: ${redactErrorBody(extraction.raw)}`);
return skip("malformed_model_output", [
`malformed_model_output: ${extraction.failure.message}; attempts=${extraction.attempts}; responseLength=${extraction.raw.length}; responseSha256=${contentHash(extraction.raw)}`,
]);
}
const { payload } = extraction;
// A candidate the contract refused is reported, not silently lost (#1047).
const warnings = [...(payload.dropped ?? [])];
// Provenance xrefs are added only after the cited session asset exists.
const { warning, ...sessionAsset } = await maybeWriteSessionAsset(run, data);
if (warning)
warnings.push(warning);
const proposalIds = [];
const previewRefs = [];
let blockedCount = 0;
let failedCount = 0;
let failedRejectedCount = 0;
const failedCauses = [];
if (payload.candidates.length > 0) {
// A candidate the ledger holds a live window for (pending, or recently rejected) is not queued again.
const access = { proposalsCtx: options.ctx, eventsCtx: options.eventsCtx, ...(dryRun ? { readOnly: true } : {}) };
const ledger = new Map();
// An accepted row has no window, so a retried or re-extracted session would propose its own
// accepted insight again as an update (#1224). Hold a ref whose accepted proposal names this
// session by a mark buildCandidateProposal writes; one accepted from another session stays eligible.
// One read serves both, so a dry run takes a single snapshot.
const acceptedHere = new Set();
const marks = [
conceptIdFromTypeName("session", `${data.ref.harness}/${data.ref.sessionId}`),
`${data.ref.harness}:${data.ref.sessionId}`,
];
try {
readLedgerDb(access, (db) => {
for (const row of listImproveLedgerRows(db, stateBundleId(stashDir), ["extract"]))
ledger.set(ledgerKey(row.source, row.ref), row);
for (const candidate of payload.candidates) {
const row = ledger.get(ledgerKey("extract", deriveExtractCandidateRef(candidate, data.ref, projectName)));
if (row?.outcome !== "accepted" || !row.proposalId)
continue;
const fm = getStateProposal(db, row.proposalId, stateBundleId(stashDir))?.payload.frontmatter ?? {};
const sources = fm.provenance?.sources;
const cited = [fm.xrefs, fm.evidenceSources, Array.isArray(sources) ? sources.map((s) => s?.resource) : []];
if (cited.some((list) => Array.isArray(list) && list.some((mark) => marks.includes(mark)))) {
acceptedHere.add(row.proposalId);
}
}
});
}
catch (error) {
warn(`[improve] ledger read failed: ${error instanceof Error ? error.message : String(error)}`);
}
const nowIso = new Date().toISOString();
for (const candidate of payload.candidates) {
const built = buildCandidateProposal(candidate, data.ref, sessionAsset.sessionAssetRef, sessionScope(project, options.scope), projectName, project?.write.metadata);
const ledgerRow = ledger.get(ledgerKey("extract", built.ref));
const skipped = isLedgerBlocked(ledgerRow, nowIso)
? `${ledgerRow?.outcome} until ${ledgerRow?.nextEligibleAt}`
: ledgerRow?.proposalId && acceptedHere.has(ledgerRow.proposalId)
? `accepted from this session as proposal ${ledgerRow.proposalId}`
: undefined;
if (skipped) {
blockedCount += 1;
warnings.push(`candidate ${candidate.type}:${candidate.name} skipped: ${skipped}`);
continue;
}
if (dryRun) {
previewRefs.push(built.ref);
continue;
}
try {
const proposal = mintProposal(stashDir, options.ctx, {
ref: built.ref,
source: "extract",
sourceRun,
attemptedRefs: [built.ref],
payload: {
content: built.content,
// Model confidence stays on the proposal for reviewers; it is not published,
// where promotion scoring would read it as a signal.
frontmatter: { ...built.frontmatter, confidence: candidate.confidence },
},
});
proposalIds.push(proposal.id);
}
catch (err) {
failedCount += 1;
// The validator's refusal recurs on every retry of this content; any other failure
// (state.db busy, I/O, config) may clear, so it keeps the session retryable.
const message = err instanceof Error ? err.message : String(err);
if (err instanceof UsageError && err.code === "INVALID_PROPOSAL")
failedRejectedCount += 1;
else
failedCauses.push(message);
warnings.push(`candidate ${candidate.type}:${candidate.name} failed: ${message}`);
}
}
}
const empty = payload.candidates.length === 0;
const result = sessionOutcome(sessionRef.sessionId, harness.name, {
...base,
candidateCount: payload.candidates.length,
proposalIds,
previewRefs,
blockedCount,
failedCount,
failedRejectedCount,
...(failedCauses.length > 0 ? { failedCauses } : {}),
...(empty && payload.rationale_if_empty ? { rationaleIfEmpty: payload.rationale_if_empty } : {}),
warnings,
...sessionAsset,
...run.notices.fields(),
});
appendEvent({
eventType: "extract_invoked",
...(sessionAsset.sessionAssetRef ? { ref: sessionAsset.sessionAssetRef } : {}),
metadata: {
outcome: previewRefs.length > 0 ? "candidates_previewed" : persistedExtractOutcome(result),
dryRun,
sessionId: sessionRef.sessionId,
harness: harness.name,
sourceRun,
candidateCount: payload.candidates.length,
proposalCount: proposalIds.length,
previewCount: previewRefs.length,
blockedCount,
failedCount,
...(empty ? { rationale: payload.rationale_if_empty } : {}),
preFilterInput: filtered.stats.inputCount,
preFilterOutput: filtered.stats.outputCount,
repairAttempts: extraction.attempts - 1,
},
}, options.eventsCtx);
return result;
}
const MAX_FAILURE_CAUSES = 3;
const MAX_FAILURE_CAUSE_CHARS = 200;
/** The distinct causes, first few, each cut short: a result names why writes failed without growing with them. */
function boundedCauses(causes) {
return [...new Set(causes.map((cause) => cause.slice(0, MAX_FAILURE_CAUSE_CHARS)))].slice(0, MAX_FAILURE_CAUSES);
}
/** Queue outcomes follow effects, never merely the presence of model candidates. */
function persistedExtractOutcome(result) {
if (result.candidateCount === 0)
return "no_candidates";
if (result.proposalIds.length > 0)
return "candidates_queued";
return result.failedCount ? "proposal_write_failed" : "candidates_blocked";
}
/**
* Work the plans: claim each model session's lock, re-read and re-gate it
* under the lock (the log may have changed since planning), extract, and
* record the outcome in the seen-session table. A skipped or locked session
* refills its model slot from the deferred candidates.
*/
async function runExtractSessionLoop(run, planned, seenMap, stateDb, tracking, topLevelWarnings) {
const { options, harness, gates, dryRun } = run;
const locking = tracking && !dryRun && !options.stateDb;
const tally = {
sessions: [],
processedCount: 0,
skippedCount: 0,
triageEvaluated: 0,
triagePassed: 0,
triagedOut: 0,
allProposalIds: [],
failedCauses: [],
deferred: 0,
};
const account = ({ failedCauses, ...result }) => {
const stamped = { ...result, engine: run.llmRunner.name };
tally.failedCauses.push(...(failedCauses ?? []));
tally.sessions.push(stamped);
const preempted = ["read_failed", "too_short", "already_extracted", "locked_concurrent"].includes(result.skipReason ?? "");
if (gates.triage.enabled && !preempted) {
tally.triageEvaluated += 1;
if (result.skipReason === "triaged_out")
tally.triagedOut += 1;
else
tally.triagePassed += 1;
}
if (result.skipped)
tally.skippedCount += 1;
else
tally.processedCount += 1;
tally.allProposalIds.push(...result.proposalIds);
return stamped;
};
const accountAndRecord = (summary, result) => {
recordSessionOutcome(stateDb, tracking && !dryRun, harness.name, summary, account(result), run.sourceRun);
};
const workPlans = [...planned.plans];
let remaining = planned.deferredCandidates;
const refillModelSlot = async () => {
if (remaining.length === 0 || options.signal?.aborted)
return;
const refill = await planExtractSessions({
candidates: remaining,
options,
harness,
seenMap,
gates,
maxSessionsPerRun: 1,
locking,
});
workPlans.push(...refill.plans);
remaining = refill.deferredCandidates;
};
for (const plan of workPlans) {
if (options.signal?.aborted)
break;
const { summary } = plan;
if (plan.kind === "skip") {
accountAndRecord(summary, plan.result);
continue;
}
let lockOwnership;
if (locking) {
const lock = acquireExtractSessionLock(extractSessionLockPath(harness.name, summary.sessionId, options.stateDbPath ?? getStateDbPath()));
if (!lock.proceed) {
account(lockedConcurrentResult(harness.name, summary));
await refillModelSlot();
continue;
}
lockOwnership = lock.ownership;
}
try {
const prior = stateDb
? getExtractedSessionsMap(stateDb, harness.name, [summary.sessionId]).get(summary.sessionId)
: seenMap.get(summary.sessionId);
const gate = await runPreLlmSessionGates(harness, summary, prior, options.force === true, gates);
if ("skip" in gate) {
accountAndRecord(summary, gate.skip);
await refillModelSlot();
continue;
}
const result = await processSession(run, summary, gate);
if (result.skipReason === "malformed_model_output") {
for (const warning of result.warnings)
topLevelWarnings.push(`session ${summary.sessionId}: ${warning}`);
}
accountAndRecord(summary, result);
}
catch (err) {
if (err instanceof ConfigError)
throw err;
const msg = err instanceof Error ? err.message : String(err);
warn(`[extract] session ${summary.sessionId} threw: ${msg}`);
topLevelWarnings.push(`session ${summary.sessionId} threw: ${msg}`);
account(sessionOutcome(summary.sessionId, harness.name, {
warnings: [msg],
skipped: true,
skipReason: "exception",
...run.notices.fields(),
}));
}
finally {
if (lockOwnership)
releaseLock(lockOwnership);
}
}
tally.deferred = remaining.length;
return tally;
}
/**
* Persist a session's outcome in the seen-session table. A session skipped as
* already extracted or locked is not rewritten; one that failed for a
* transient reason, or had a proposal write fail for any reason but the
* validator's refusal, keeps a null hash so it is retried.
*/
function recordSessionOutcome(stateDb, enabled, harness, summary, result, sourceRun) {
if (!enabled || !stateDb)
return;
if (result.skipReason === "already_extracted" || result.skipReason === "locked_concurrent")
return;
const reason = result.skipReason ?? "";
try {
upsertExtractedSession(stateDb, {
harness,
sessionId: summary.sessionId,
processedAt: new Date().toISOString(),
sessionEndedAt: summary.endedAt ?? null,
outcome: result.skipped
? ["read_failed", "exception", "malformed_model_output"].includes(reason)
? "failed"
: "skipped"
: persistedExtractOutcome(result),
candidateCount: result.candidateCount,
proposalCount: result.proposalIds.length,
rationale: result.rationaleIfEmpty ?? null,
sourceRun,
// A failed proposal write keeps a null hash too, so the next run re-extracts the
// session; the ledger's `proposed` window blocks the candidates that did persist.
// A validator refusal recurs on the same content, so refusals alone record the hash.
contentHash: ["llm_unavailable", "triaged_out", "malformed_model_output"].includes(reason) ||
(result.failedCount ?? 0) > (result.failedRejectedCount ?? 0)
? null
: (result.contentHash ?? null),
metadata: {
blockedCount: result.blockedCount ?? 0,
failedCount: result.failedCount ?? 0,
failedRejectedCount: result.failedRejectedCount ?? 0,
preFilterInputCount: result.preFilter.inputCount,
preFilterOutputCount: result.preFilter.outputCount,
preFilterTruncatedCount: result.preFilter.truncatedCount,
engine: result.engine,
...(result.skipReason ? { skipReason: result.skipReason } : {}),
...(result.sessionLogPath ? { logPath: result.sessionLogPath } : {}),
...(result.sessionAssetRef ? { sessionAssetRef: result.sessionAssetRef } : {}),
},
});
}
catch (err) {
warn(`[extract] failed to record session ${summary.sessionId} in state.db: ${err instanceof Error ? err.message : String(err)}`);
}
}
/** The run's runner, budgets, gates and session-indexing settings (throws without a connection or harness). */
function resolveExtractRun(options, config, process) {
const notices = noticeSet();
let llmRunner;
if (options.resolvedPlan) {
llmRunner = options.resolvedPlan.runner;
notices.add(options.resolvedPlan.notices ?? []);
}
else if (options.llmRunner) {
llmRunner = options.llmRunner;
}
else {
const resolved = resolveImproveExecution({ config, processName: "extract", alias: SHIPPED_ALIAS.extract });
llmRunner = resolved?.runner;
if (resolved)
notices.add(resolved.notices);
}
if (!llmRunner) {
throw new ConfigError("No connection or harness is configured for extract. Run `akm setup`, or set improve.connection or improve.processes.extract.connection.", "LLM_NOT_CONFIGURED");
}
const runner = llmRunner;
const sensitiveValues = collectSensitiveValues([
...collectDispatchSensitiveValues(runner),
...collectCredentialValues(config),
]);
const triage = process?.triage;
// The default summary generator fails open: no summary, no session asset.
const generate = async (data) => {
const outcome = await callStage({
runner,
prompt: buildSessionSummaryPrompt(data, sensitiveValues),
request: modelRequest(options, SESSION_SUMMARY_JSON_SCHEMA),
parse: parseSessionSummary,
onNotices: notices.add,
});
return parseSessionSummary(outcome.ok ? outcome.raw : "");
};
return {
llmRunner: runner,
notices,
gates: {
maxTotalChars: typeof process?.maxTotalChars === "number" ? process.maxTotalChars : undefined,
minContentChars: typeof process?.minContentChars === "number" ? process.minContentChars : DEFAULT_MIN_CONTENT_CHARS,
triage: {
enabled: triage?.enabled === true,
minScore: typeof triage?.minScore === "number" ? triage.minScore : DEFAULT_TRIAGE_MIN_SCORE,
},
},
maxSessionsPerRun: options.since
? 0
: typeof process?.maxSessionsPerRun === "number"
? process.maxSessionsPerRun
: DEFAULT_MAX_SESSIONS_PER_RUN,
effectiveSince: options.since ?? process?.defaultSince,
sessionIndexing: {
enabled: process?.indexSessions ?? true,
minDurationMinutes: typeof process?.minSessionDuration === "number"
? process.minSessionDuration
: DEFAULT_MIN_SESSION_DURATION_MINUTES,
generate: options.generateSessionSummary ?? generate,
},
};
}
/** The sessions to process: the `--session-id` target (or a not-found envelope) or the discovery window. */
async function discoverExtractCandidates(options, harness, effectiveSince, startMs, dryRun, llmRunner) {
const location = options.location ? { location: options.location } : {};
if (options.sessionId) {
const target = (await harness.listSessions(location)).find((s) => s.sessionId === options.sessionId);
if (target)
return { candidates: [target] };
return {
notFound: emptyExtractResult({
ok: false,
dryRun,
type: options.type,
warning: `session ${options.sessionId} not found for harness ${options.type}`,
startMs,
llmRunner,
}),
};
}
const sinceMs = effectiveSince
? parseSinceArg(effectiveSince)
: resolveDefaultSinceMs(harness.name, startMs, {
...(options.stateDb ? { stateDb: options.stateDb } : {}),
...(options.stateDbPath ? { stateDbPath: options.stateDbPath } : {}),
...(options.skipTracking ? { skipTracking: options.skipTracking } : {}),
});
return { candidates: await harness.listSessions({ sinceMs, ...location }) };
}
function loadSeenMapReadOnly(options, harness, candidates, warnings) {
if (options.skipTracking === true || candidates.length === 0)
return new Map();
let snapshot;
try {
if (!options.stateDb)
snapshot = openSqliteReadSnapshot(options.stateDbPath ?? getStateDbPath());
const db = options.stateDb ?? snapshot;
return db
? getExtractedSessionsMap(db, harness, candidates.map((candidate) => candidate.sessionId))
: new Map();
}
catch (err) {
const msg = err instanceof Error ? err.message : String(err);
warn(`[extract] state.db snapshot unavailable, planning without skip-tracking: ${msg}`);
warnings.push(`state.db snapshot unavailable: ${msg}`);
return new Map();
}
finally {
snapshot?.close();
}
}
export async function akmExtract(options) {
const startMs = Date.now();
if (!options.type || options.type.trim() === "") {
throw new UsageError("--type is required. Pass a harness name (e.g. --type claude).", "MISSING_REQUIRED_ARGUMENT");
}
const config = options.config ?? loadConfig();
const stashDir = options.stashDir ?? resolveStashDir();
const dryRun = options.dryRun ?? false;
const sourceRun = options.sourceRun ?? `extract-${timestampForFilename()}`;
// Behavior comes from the frozen standalone plan or the active improve strategy.
const activeProfile = options.improveProfile ?? (options.resolvedPlan ? undefined : resolveImproveStrategy(undefined, config).config);
const process = options.resolvedPlan?.process ?? getImproveProcessConfig("extract", activeProfile);
// The extract toggle gates extract as an improve STAGE; an explicit `akm extract` runs unless the person's own
// config switches it off (`resolveStandaloneExtractPlan`).
const enabled = options.resolvedPlan?.enabled ??
(options.improveProfile ? resolveProcessEnabled("extract", options.improveProfile) : true);
if (!enabled) {
return emptyExtractResult({
ok: true,
dryRun,
type: options.type,
warning: "extract is disabled: improve.enabled or improve.strategies.<strategy>.processes.extract.enabled is false in your config",
startMs,
});
}
const resolved = resolveExtractRun(options, config, process);
const { llmRunner, notices } = resolved;
const harness = (options.harnesses ?? getAvailableHarnesses()).find((h) => h.name === options.type);
const unavailable = !harness
? `no available harness matches type "${options.type}" (check that the platform is installed)`
: !harness.isAvailable()
? `harness ${options.type} is registered but reports not-available (no session data on this machine)`
: undefined;
if (!harness || unavailable) {
return emptyExtractResult({
ok: false,
dryRun,
type: options.type,
warning: unavailable ?? "",
startMs,
llmRunner,
});
}
const discovery = await discoverExtractCandidates(options, harness, resolved.effectiveSince, startMs, dryRun, llmRunner);
if ("notFound" in discovery)
return discovery.notFound;
const topLevelWarnings = [];
const tracking = options.skipTracking !== true;
const seenMap = loadSeenMapReadOnly(options, harness.name, discovery.candidates, topLevelWarnings);
const planned = await planExtractSessions({
candidates: discovery.candidates,
options,
harness,
seenMap,
gates: resolved.gates,
maxSessionsPerRun: resolved.maxSessionsPerRun,
locking: tracking && !dryRun && !options.stateDb,
});
const modelPlanCount = planned.plans.filter((plan) => plan.kind === "model").length;
// A writing run needs a writable owner for its proposal queue; learn that before spending model work (#1289).
if (modelPlanCount > 0 && !dryRun)
resolveProposalQueueTarget(stashDir, config);
let stateDb;
let tally;
try {
if (tracking) {
if (options.stateDb) {
stateDb = options.stateDb;
}
else if (modelPlanCount > 0 && !dryRun) {
try {
stateDb = openStateDatabase(options.stateDbPath);
}
catch (err) {
const msg = err instanceof Error ? err.message : String(err);
warn(`[extract] state.db unavailable, processing without skip-tracking: ${msg}`);
topLevelWarnings.push(`state.db unavailable: ${msg}`);
}
}
}
const run = {
...resolved,
options,
harness,
stashDir,
config,
sourceRun,
dryRun,
standardsContext: modelPlanCount > 0 ? resolveExtractStandards(stashDir) : "",
};
tally = await runExtractSessionLoop(run, planned, seenMap, stateDb, tracking, topLevelWarnings);
}
finally {
if (stateDb && !options.stateDb) {
try {
stateDb.close();
}
catch {
// best-effort
}
}
}
if (tally.deferred > 0)
topLevelWarnings.push(`Reached maxSessionsPerRun=${resolved.maxSessionsPerRun}; ${tally.deferred} session(s) deferred to a later run.`);
// Every skip reason is counted; infrastructure failures also get a warning line.
const counts = {};
for (const { skipReason } of tally.sessions)
if (skipReason)
counts[skipReason] = (counts[skipReason] ?? 0) + 1;
for (const reason of EXTRACT_INFRASTRUCTURE_SKIP_REASONS) {
const n = counts[reason];
if (n)
topLevelWarnings.push(`${n} of ${tally.sessions.length} sessions skipped: ${reason} (engine "${llmRunner.name}")`);
}
// A write the validator refused recurs on every retry and is not a failure of the run; any other
// failure may clear, so the session stays retryable and the run is incomplete (#1290).
const failedSessions = tally.sessions.filter((session) => (session.failedCount ?? 0) > (session.failedRejectedCount ?? 0));
const writeFailures = failedSessions.length > 0
? {
candidates: failedSessions.reduce((sum, session) => sum + (session.failedCount ?? 0) - (session.failedRejectedCount ?? 0), 0),
sessions: failedSessions.length,
causes: boundedCauses(tally.failedCauses),
}
: undefined;
if (writeFailures)
topLevelWarnings.push(`${writeFailures.candidates} candidate write(s) failed in ${writeFailures.sessions} session(s): ${writeFailures.causes.join("; ")}; those sessions stay retryable.`);
if (modelPlanCount > 0 && resolved.gates.triage.enabled && tally.triageEvaluated > 0) {
appendEvent({
eventType: "extract_triaged",
metadata: {
evaluated: tally.triageEvaluated,
passed: tally.triagePassed,
triagedOut: tally.triagedOut,
sourceRun,
},
}, options.eventsCtx);
}
return {
schemaVersion: 1,
ok: true,
shape: "extract-result",
dryRun,
type: options.type,
sessionsProcessed: tally.processedCount,
sessionsSkipped: tally.skippedCount,
candidatesCreated: tally.allProposalIds.length,
proposals: tally.allProposalIds,
sessions: tally.sessions,
warnings: topLevelWarnings,
...(writeFailures ? { writeFailures } : {}),
durationMs: Date.now() - startMs,
...notices.fields(),
...(Object.keys(counts).length > 0 ? { skipReasons: counts } : {}),
engine: llmRunner.name,
engineKind: llmRunner.kind,
};
}
/**
* Count new in-window sessions across the available harnesses, with no LLM
* call, for improve's `minNewSessions` gate. It does not read session bodies,
* so a session counts as new when it has no seen row or a row without a
* content hash; the exact hash check happens at extraction.
*/
export async function countNewExtractCandidates(_config, options = {}) {
const effectiveSince = options.since ?? getImproveProcessConfig("extract", options.improveProfile)?.defaultSince;
const explicitSinceMs = effectiveSince ? parseSinceArg(effectiveSince) : undefined;
const harnesses = (options.harnesses ?? getAvailableHarnesses()).filter((h) => h.isAvailable());
let stateDb = options.stateDb;
let openedStateDb = false;
let total = 0;
try {
for (const harness of harnesses) {
const sinceMs = explicitSinceMs ??
resolveDefaultSinceMs(harness.name, Date.now(), {
...(options.stateDb ? { stateDb: options.stateDb } : {}),
...(options.stateDbPath ? { stateDbPath: options.stateDbPath } : {}),
...(options.readOnly && !options.stateDb ? { skipTracking: true } : {}),
});
const candidates = await harness.listSessions({
sinceMs,
...(options.readOnly ? { isolatedSnapshot: true } : {}),
});
if (candidates.length === 0)
continue;
// A dry planner without state.db has no seen-session ledger by definition.
if (options.readOnly && !stateDb) {
total += candidates.length;
continue;
}
let seenMap;
try {
if (!stateDb) {
stateDb = openStateDatabase(options.stateDbPath);
openedStateDb = true;
}
seenMap = getExtractedSessionsMap(stateDb, harness.name, candidates.map((c) => c.sessionId));
}
catch (err) {
// Fail open: a transient sqlite error must not skip a pass that should run.
const msg = err instanceof Error ? err.message : String(err);
warn(`[extract] state.db unavailable while counting candidates, treating all as new: ${msg}`);
total += candidates.length;
continue;
}
for (const summary of candidates) {
const prior = seenMap.get(summary.sessionId);
if (!(prior && prior.content_hash != null))
total += 1;
}
}
}
finally {
if (stateDb && openedStateDb) {
try {
stateDb.close();
}
catch {
// best-effort
}
}
}
return total;
}