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

1,022 lines (1,021 loc) • 49.5 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 consolidate pair pass: runs * alongside the existing promote pass inside `akmConsolidate`, over new and * changed memory-tier assets. Judges each near-duplicate/superseding pair * with complete claim comparisons and mints a reviewed `retire` proposal * for derived `duplicate` / `subsumed` / `supersedes` outcomes — never merges. * The pass itself writes no belief edges; accepting a `supersedes` retirement * writes the `supersededBy` edge before archiving. A staged retirement can be * accepted unattended by triage (`drain.ts`); an unstaged one stays pending. * * Pair-selection calibration (owner grades, 2026-09-28): `T_PAIR` stays * 0.93, not the initial 0.90, because the 0.90–0.93 band alone graded 3/4 (R1). * * Initiator eligibility and dating (post-review): "created" is the * asset's git first-add time (one `git log` per run, {@link loadGitFirstAddedMap}), * not frontmatter or mtime — mtime is only the fallback for a file git does * not know. An initiator is eligible when it has no prior `consolidate-pair` * ledger row, or its current body hash differs from the row's recorded one; * that row is written only once ALL of the initiator's own candidates were * judged this run (a run capped mid-way through its candidates leaves it * without a row, so the next run picks it back up) — see * {@link selectInitiators} and the ledger-write step in * {@link runConsolidatePairPass}. */ import fs from "node:fs"; import path from "node:path"; import consolidatePairPrompt from "../../../assets/prompts/consolidate-pair.md" with { type: "text" }; import consolidatePairCheckPrompt from "../../../assets/prompts/consolidate-pair-check.md" with { type: "text" }; import consolidatePairSameAge from "../../../assets/prompts/consolidate-pair-same-age.md" with { type: "text" }; import consolidatePairTerms from "../../../assets/prompts/consolidate-pair-terms.md" with { type: "text" }; import { parseFrontmatter } from "../../../core/asset/frontmatter.js"; import { asNonEmptyString } from "../../../core/common.js"; import { concurrentMap } from "../../../core/concurrent.js"; import { SHIPPED_ALIAS } from "../../../core/config/model-aliases.js"; import { UsageError } from "../../../core/errors.js"; import { runGit } from "../../../core/git-run.js"; import { parseEmbeddedJsonResponse } from "../../../core/parse.js"; import { DERIVED_SUFFIX } from "../../../core/recognition-util.js"; import { redactErrorBody } from "../../../core/redaction.js"; import { warnOnce } from "../../../core/warn.js"; import { sameScope, scopeFromFrontmatter } from "../../../indexer/passes/metadata.js"; import { closeDatabase, openExistingDatabase, openReadonlyExistingDatabase, } from "../../../storage/repositories/index-connection.js"; import { getAllEntries, getEntryById } from "../../../storage/repositories/index-entries-repository.js"; import { getNeighborsByEntryId, hasStoredEmbedding } from "../../../storage/repositories/index-vec-repository.js"; import { EXPIRED_GATE_REASON, isRetireProposal, PAIR_PASS_GATE, STALE_TARGET_GATE_REASON, } from "../../proposal/proposal-types.js"; import { createRetireProposal, listProposalsReadOnly, proposalContentHash, proposalTargetOf, recordGateDecision, } from "../../proposal/repository.js"; import { contentHash, stripFrontmatterBody } from "../content-hash.js"; import { resolveImproveExecution } from "../execution.js"; import { indexedAsset, indexedContent, indexedModifiedMs } from "../indexed-asset.js"; import { loadLedgerSnapshot, PAIR_PASS_LEDGER_SOURCE, recordLedgerAttempt, stripBundle } from "../ledger.js"; import { isInRetrievalScope, loadRetrievalScope } from "../retrieval-scope.js"; import { callStage } from "../stage.js"; import { checkRetirementContinuity, createContinuitySearch } from "./continuity-check.js"; export { PAIR_PASS_LEDGER_SOURCE }; /** Neighbours fetched per initiator before filtering (wide enough that self/twin/bundle/tier misses rarely starve the kept 5 below). */ export const PAIR_NEIGHBOR_FETCH_K = 20; /** Passing candidates kept per initiator, nearest-cosine-first. */ export const PAIR_NEIGHBOR_K = 5; /** Calibrated floor (R1): the 0.90–0.93 band alone graded 3/4 against the owner. */ export const T_PAIR = 0.93; /** O2: the existing backlog (an initiator with no prior pair-pass attempt) goes >= 0.95 first. */ export const BACKFILL_FLOOR = 0.95; /** * An initiator git first-added within this many days judges at `T_PAIR` even * with no prior ledger row: new material earns the same scrutiny as an edit, * not the higher bar reserved for working through the pre-existing backlog. */ export const NEW_MATERIAL_DAYS = 7; /** Pairs judged per run, highest cosine first. */ export const MAX_PAIRS_PER_RUN = 300; const MS_PER_DAY = 86_400_000; const RETIRE_LABELS = new Set(["duplicate", "subsumed", "supersedes"]); /** The labels represented by the existing retirement metadata. */ function isRetireLabel(label) { return RETIRE_LABELS.has(label); } /** Exported, with {@link buildPairUserPrompt}, so a replay can drive the exact judge call. */ export const PAIR_JUDGE_JSON_SCHEMA = { type: "object", required: ["reason", "onlyInA", "onlyInB", "confidence"], additionalProperties: false, properties: { reason: { type: "string", maxLength: 400 }, onlyInA: { type: "array", items: { type: "string", maxLength: 200 }, maxItems: 20 }, onlyInB: { type: "array", items: { type: "string", maxLength: 200 }, maxItems: 20 }, confidence: { type: "number", minimum: 0, maximum: 1 }, }, }; export const PAIR_CHECK_JSON_SCHEMA = { type: "object", required: ["missing"], additionalProperties: false, properties: { missing: { type: "array", items: { type: "string", maxLength: 200 }, maxItems: 20 } }, }; /** Validate both claim lists, then derive the outcome instead of asking the model to duplicate that decision. */ export function parsePairJudgeResponse(raw) { const parsed = parseEmbeddedJsonResponse(raw); if (!parsed) return undefined; if (typeof parsed.confidence !== "number" || !Number.isFinite(parsed.confidence)) return undefined; const confidence = Math.max(0, Math.min(1, parsed.confidence)); const reason = typeof parsed.reason === "string" ? parsed.reason : ""; const onlyInA = claimList(parsed.onlyInA); const onlyInB = claimList(parsed.onlyInB); if (!onlyInA || !onlyInB) return undefined; const relation = onlyInA.length === 0 && onlyInB.length === 0 ? "duplicate" : onlyInA.length === 0 || onlyInB.length === 0 ? "subsumed" : "overlap"; const redundant = onlyInA.length === 0 ? "A" : onlyInB.length === 0 ? "B" : null; return { onlyInA, onlyInB, relation, redundant, confidence, reason }; } function claimList(value) { if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) return undefined; return value.map((v) => v.trim()).filter(Boolean); } function isFlatName(name) { return !name.includes("/"); } /** * True only for a memory's own direct `.derived` child or parent — never a * sibling or an unrelated pair. @internal exported for unit tests. */ export function isOwnTwinOrParent(a, b) { if (a.type !== "memory" || b.type !== "memory") return false; return a.name === `${b.name}${DERIVED_SUFFIX}` || b.name === `${a.name}${DERIVED_SUFFIX}`; } /** * Every asset eligible to be a pair-pass initiator or candidate: memory (any * depth), flat knowledge, or a lesson. @internal exported for unit tests. */ export function loadPairPassPool(db, bundleId) { const assets = []; for (const e of getAllEntries(db, "memory")) { if (e.bundleId !== bundleId || !indexedAsset(e.bundleId, e.conceptId)) continue; assets.push({ ref: e.conceptId, bundleId: e.bundleId, type: "memory", name: e.entry.name, filePath: e.filePath, entryId: e.id, }); } for (const e of getAllEntries(db, "knowledge")) { if (e.bundleId !== bundleId || !isFlatName(e.entry.name) || !indexedAsset(e.bundleId, e.conceptId)) continue; assets.push({ ref: e.conceptId, bundleId: e.bundleId, type: "knowledge", name: e.entry.name, filePath: e.filePath, entryId: e.id, }); } for (const e of getAllEntries(db, "lesson")) { if (e.bundleId !== bundleId || !indexedAsset(e.bundleId, e.conceptId)) continue; assets.push({ ref: e.conceptId, bundleId: e.bundleId, type: "lesson", name: e.entry.name, filePath: e.filePath, entryId: e.id, }); } return assets; } // ── B1: created/updated dates from git, not frontmatter/mtime ────────────── /** A path relative to `stashDir`, POSIX-separated — how `git log --name-only` spells it. */ function repoRelativeKey(stashDir, filePath) { return path.relative(stashDir, filePath).replace(/\\/g, "/"); } /** 16 MiB — see the buffer-overflow comment inside {@link loadGitFirstAddedMap}. */ const GIT_LOG_MAX_BUFFER = 16 * 1024 * 1024; /** * Every tracked path's first-add time (unix ms), from one `git log` over the * whole bundle (~2.1s measured against the owner's real bundle) — never * shelled out per pair or per initiator. Follows renames (`-M * --diff-filter=AR`, oldest-first via `--reverse`): a renamed path inherits * its pre-rename first-add time, not the rename's own timestamp — the owner's * 2026-08-24 bulk rename alone re-dated 966 files under `--no-renames`, and * 11% of real candidate pairs flipped which side counted as older. A raised * `diff.renameLimit` keeps a large bulk-rename commit (exactly this * scenario) from silently falling back to detecting no renames at all. * `undefined` when `stashDir` is not itself a git root (no `.git` directly * inside it): every asset then falls back to mtime in {@link createdMsOf}, * one fallback code path instead of a second git-aware one for a bundle * nested inside a larger repo. */ export function loadGitFirstAddedMap(stashDir) { // asset-io: bundle-root git checkout probe if (!fs.existsSync(path.join(stashDir, ".git"))) return undefined; let result; try { result = runGit(["-c", "diff.renameLimit=20000", "log", "--reverse", "-M", "--diff-filter=AR", "--name-status", "--format=@%ct"], { cwd: stashDir, // spawnSync's default maxBuffer (1 MB) is too small for a bundle // with real history — the owner's real bundle alone prints // multiple MB here (migration-tool.ts's own git subprocess call // uses the same 16 MiB figure). Silently exceeding it looks // identical to "git failed" from the caller's side (status stays // non-zero) — checked explicitly below instead of folded into the // same silent fallback as "no .git", since raising the buffer // again is an actual fix and worth telling the operator about. maxBuffer: GIT_LOG_MAX_BUFFER, }); } catch { return undefined; } if (result.error) { const code = result.error.code; if (code === "ENOBUFS" || /maxBuffer/i.test(result.error.message ?? "")) { warnOnce("pair-pass-git-log-maxbuffer", `[consolidate] pair pass: git log for first-add dates in ${stashDir} exceeded its ${GIT_LOG_MAX_BUFFER / (1024 * 1024)} MiB buffer — dates fall back to mtime this run.`); } return undefined; } if (result.status !== 0 || typeof result.stdout !== "string") return undefined; // Oldest-first (--reverse): the FIRST time a path is seen, whether as a // plain add or as a rename's destination, IS its true first-add time — no // backward walk needed. A rename's destination inherits the source's // already-recorded time (or, failing that — the source itself predates // this log's window — this commit's own time). const firstAdd = new Map(); let currentMs; for (const line of result.stdout.split("\n")) { if (line.startsWith("@")) { const sec = Number(line.slice(1)); currentMs = Number.isFinite(sec) ? sec * 1000 : undefined; continue; } if (currentMs === undefined) continue; const tab = line.indexOf("\t"); if (tab < 0) continue; const status = line.slice(0, tab); if (status === "A") { const p = line.slice(tab + 1).trim(); if (p && !firstAdd.has(p)) firstAdd.set(p, currentMs); } else if (status.startsWith("R")) { const rest = line.slice(tab + 1); const tab2 = rest.indexOf("\t"); if (tab2 < 0) continue; const oldPath = rest.slice(0, tab2).trim(); const newPath = rest.slice(tab2 + 1).trim(); if (oldPath && newPath && !firstAdd.has(newPath)) { firstAdd.set(newPath, firstAdd.get(oldPath) ?? currentMs); } } } return firstAdd; } /** Created instant (ms): git first-add when known, else file mtime — the one fallback both dating and the new-material check use. */ function createdMsOf(asset, gitFirstAdded, stashDir) { const known = gitFirstAdded?.get(repoRelativeKey(stashDir, asset.filePath)); if (known !== undefined) return known; return indexedModifiedMs(asset.bundleId, asset.ref) ?? 0; } /** An unordered pair's dedup key, so a pair reachable from either side is judged once. */ function pairKey(a, b) { return [a, b].sort().join("\u0000"); } /** * A rejected retirement's dedup key (item 0): the exact ref pair plus both * content hashes at judge time, so a re-selected initiator (its own ledger * row missing because a sibling candidate was dropped or failed, not because * this pair changed) does not get this same, already-rejected pair re-judged * into a new proposal. */ function rejectedPairKey(retiredRef, successorRef, retiredHash, successorHash) { return [retiredRef, successorRef, retiredHash, successorHash].join("\u0000"); } /** * Every rejected OR reverted consolidate-pair retirement on * record, as {@link rejectedPairKey}s — read once per run, the same shape as * `pendingRetireRefs` in {@link runConsolidatePairPass}. `reverted` is * included alongside `rejected`: a person undoing an accept via `akm proposal * revert` is the same "no, not this" signal as a reject — without it, the next * run would re-mint the identical retirement, and a bulk accept could * re-apply a decision the person just undid. The keys follow each proposal's * CURRENT status, so one `akm proposal reopen` put back to `pending` (#997) is * no longer among them — and, pending, blocks its pair from a second mint. * * @internal exported for unit tests. */ export function loadRejectedPairKeys(stashDir, proposalsCtx) { const keys = new Set(); try { for (const status of ["rejected", "reverted"]) { for (const p of listProposalsReadOnly(stashDir, { status, includeArchive: true }, proposalsCtx)) { if (!isRetireProposal(p) || !p.retirement) continue; // Expiry and a stale target are procedural, not a person saying no: the pair may be judged again. const autoReason = p.gateDecision?.outcome === "auto-rejected" ? p.gateDecision.reason : undefined; if (autoReason === EXPIRED_GATE_REASON || autoReason === STALE_TARGET_GATE_REASON) continue; keys.add(rejectedPairKey(p.retirement.retiredRef, p.retirement.successorRef, p.retirement.retiredContentHash, p.retirement.successorContentHash)); } } } catch { // Best-effort de-dup only; a failed read never blocks judging. } return keys; } /** * Initiators: the pool, in the retrieval * scope, and content-eligible — no prior `consolidate-pair` ledger row, or a * row whose recorded body hash differs from the asset's current one. A row's * `next_eligible_at` is never consulted (the pair pass's own source carries * no timer at all — see `windowDays` in improve-ledger-repository.ts): * eligibility here is purely a function of content, matching the brief's "no * row, or changed" rule and the ledger-write step this run finishes with. */ export function selectInitiators(pool, opts, stashDir, gitFirstAdded) { const retrievalScope = loadRetrievalScope({ proposalsCtx: opts.proposalsCtx }, stashDir); const ledger = loadLedgerSnapshot({ proposalsCtx: opts.proposalsCtx }, stashDir, [PAIR_PASS_LEDGER_SOURCE]); const nowMs = (opts.proposalsCtx?.now ?? Date.now)(); const initiators = []; for (const asset of pool) { if (!isInRetrievalScope(retrievalScope, asset.ref, asset.filePath)) continue; const row = ledger.get(`${PAIR_PASS_LEDGER_SOURCE}\0${asset.ref}`); const raw = indexedContent(asset.bundleId, asset.ref); if (raw === undefined) continue; // unreadable: selectCandidates/judgeOne would skip it anyway const bodyHash = contentHash(raw, "body"); if (row && row.contentHash === bodyHash) continue; // unchanged since the last full attempt: not eligible const createdMs = createdMsOf(asset, gitFirstAdded, stashDir); const newMaterial = nowMs - createdMs <= NEW_MATERIAL_DAYS * MS_PER_DAY; initiators.push({ ...asset, backlog: row === undefined, newMaterial, bodyHash }); } return { initiators }; } /** * Candidates: each initiator's nearest * neighbours, filtered and thresholded — the FULL set, sorted by cosine * descending, uncapped. `runConsolidatePairPass` applies `MAX_PAIRS_PER_RUN` * (needing the uncapped per-initiator totals to tell a cap-cut initiator * apart from a fully-judged one). Fetches `PAIR_NEIGHBOR_FETCH_K` (20) * raw neighbours and keeps the first `PAIR_NEIGHBOR_K` (5) that clear every * filter, so a few self/twin/bundle/tier misses in the raw top-5 cannot * starve an initiator down to zero real candidates. An initiator with no * stored vector (embeddings off, or not embedded yet) cannot be queried at * all; its ref is added to `unvectored` so the caller does not settle it. */ export function selectCandidates(db, initiators, bundleId, unvectored) { const candidates = []; const seenPairs = new Set(); for (const initiator of initiators) { if (!hasStoredEmbedding(db, initiator.entryId)) { unvectored?.add(initiator.ref); continue; } // A changed-content or new-material initiator judges at T_PAIR; the // rest of the backlog (no row, not recently git-added) needs the higher // BACKFILL_FLOOR. const floor = initiator.backlog && !initiator.newMaterial ? BACKFILL_FLOOR : T_PAIR; const initiatorSide = loadSide(initiator, undefined, ""); if (!initiatorSide) continue; const scope = scopeFromFrontmatter(initiatorSide.frontmatter); let kept = 0; for (const hit of getNeighborsByEntryId(db, initiator.entryId, PAIR_NEIGHBOR_FETCH_K)) { if (kept >= PAIR_NEIGHBOR_K) break; if (hit.id === initiator.entryId) continue; const entry = getEntryById(db, hit.id); if (!entry || entry.bundleId !== bundleId) continue; if (entry.entry.type !== "memory" && entry.entry.type !== "knowledge" && entry.entry.type !== "lesson") continue; if (entry.entry.type === "knowledge" && !isFlatName(entry.entry.name)) continue; if (!indexedAsset(entry.bundleId, entry.conceptId)) continue; const other = { ref: entry.conceptId, bundleId: entry.bundleId, type: entry.entry.type, name: entry.entry.name, filePath: entry.filePath, entryId: hit.id, }; if (other.ref === initiator.ref || isOwnTwinOrParent(initiator, other)) continue; // distance = sqrt(2 * (1 - cosine)) (index-vec-repository.ts) — invert it back to cosine. const cosine = 1 - (hit.distance * hit.distance) / 2; if (cosine < floor) continue; const otherSide = loadSide(other, undefined, ""); if (!otherSide || !sameScope(scope, scopeFromFrontmatter(otherSide.frontmatter))) continue; const key = pairKey(initiator.ref, other.ref); if (seenPairs.has(key)) continue; seenPairs.add(key); candidates.push({ initiator, other, cosine }); kept++; } } candidates.sort((a, b) => b.cosine - a.cosine); return candidates; } function frontmatterOf(raw) { try { return parseFrontmatter(raw).data; } catch { return {}; } } function loadSide(asset, gitFirstAdded, stashDir) { const raw = indexedContent(asset.bundleId, asset.ref); if (raw === undefined) return undefined; const frontmatter = frontmatterOf(raw); // B1: created is the git first-add time (mtime only when git does not know // the file, or the bundle has none) — frontmatter createdAt/created is not // consulted; too few real assets carry it to be a reliable ordering. // Updated stays frontmatter `updated` when present, else falls back to created. const createdIso = new Date(createdMsOf(asset, gitFirstAdded, stashDir)).toISOString(); return { asset, frontmatter, raw, createdIso, updatedIso: asNonEmptyString(frontmatter.updated) ?? createdIso, }; } function sideSection(label, side) { return [ `Asset ${label}:`, `Ref: ${side.asset.ref}`, `Type: ${side.asset.type}`, `Created: ${side.createdIso}`, `Updated: ${side.updatedIso}`, `Description: ${asNonEmptyString(side.frontmatter.description) ?? "(none)"}`, "Content:", "```", stripFrontmatterBody(side.raw), "```", "", ]; } /** Lexical attention hints only: equal token sets do not prove equal claims. */ function exclusiveTerms(side, other) { const tokens = (note) => new Set(`${asNonEmptyString(note.frontmatter.description) ?? ""}\n${stripFrontmatterBody(note.raw)}` .split(/\s+/) .filter(Boolean)); const otherTerms = tokens(other); return JSON.stringify([...tokens(side)].filter((term) => !otherTerms.has(term))); } function termHints(lines) { return consolidatePairTerms.replace("{{DIFFERENCES}}", lines.join("\n")); } /** Orders two loaded sides by date (older/newer) for the "A (older)"/"B (newer)" labelling the prompt requires. */ function orderByAge(x, y) { const xMs = Date.parse(x.createdIso); const yMs = Date.parse(y.createdIso); const xIsOlder = Number.isFinite(xMs) && Number.isFinite(yMs) ? xMs <= yMs : true; return xIsOlder ? { older: x, newer: y } : { older: y, newer: x }; } /** The user message: dates decide "A (older)" / "B (newer)" (plan Appendix A), matching the calibration sample's own ordering. */ export function buildPairUserPrompt(older, newer) { // Equal dates (a batch added in one commit, notes from one file time) make neither side newer: say so, or the judge // reads "B (newer)" as proof that B replaces A (#1134). const tied = Date.parse(older.createdIso) === Date.parse(newer.createdIso); return [ ...sideSection(tied ? "A (same age as B)" : "A (older)", older), ...sideSection(tied ? "B (same age as A)" : "B (newer)", newer), termHints([ `Tokens only in A: ${exclusiveTerms(older, newer)}`, `Tokens only in B: ${exclusiveTerms(newer, older)}`, ]), ...(tied ? [consolidatePairSameAge] : []), ].join("\n"); } const NOTE_SCHEMA = { type: "object", required: ["ref", "type", "created", "updated", "content"], additionalProperties: false, properties: { ref: { type: "string" }, type: { type: "string" }, created: { type: "string" }, updated: { type: "string" }, content: { type: "string" }, }, }; function pairNoteOf(side) { return { ref: side.asset.ref, type: side.asset.type, created: side.createdIso, updated: side.updatedIso, content: side.raw, }; } function sideOfNote(note) { return { asset: { ref: note.ref, type: note.type }, frontmatter: frontmatterOf(note.content), raw: note.content, createdIso: note.created, updatedIso: note.updated, }; } export const pairJudge = { name: "consolidate.pair", description: "Consolidate's pair judge: what each of two notes states that the other does not, and so the relation between them.", schemaVersion: 1, inputSchema: { type: "object", required: ["a", "b"], additionalProperties: false, properties: { a: NOTE_SCHEMA, b: NOTE_SCHEMA }, }, outputSchema: { type: "object", required: ["onlyInA", "onlyInB", "relation", "redundant", "confidence", "reason"], additionalProperties: false, properties: { onlyInA: { type: "array", items: { type: "string" } }, onlyInB: { type: "array", items: { type: "string" } }, relation: { type: "string", enum: ["duplicate", "subsumed", "overlap"] }, redundant: { type: ["string", "null"], enum: ["A", "B", null] }, confidence: { type: "number", minimum: 0, maximum: 1 }, reason: { type: "string" }, }, }, harnessReads: "Nothing.", defaultRunner: (config, run) => resolveImproveExecution({ config, processName: "consolidate", alias: SHIPPED_ALIAS.improve, ...(run ? { run } : {}), })?.runner, async run(input, call) { const a = Date.parse(input.a.created); const b = Date.parse(input.b.created); if (Number.isFinite(a) && Number.isFinite(b) && a > b) { throw new UsageError("consolidate.pair: `a` must be the older note (its `created` is later than `b`'s)."); } const outcome = await callStage({ runner: call.runner, system: consolidatePairPrompt, prompt: buildPairUserPrompt(sideOfNote(input.a), sideOfNote(input.b)), request: { responseSchema: PAIR_JUDGE_JSON_SCHEMA, enableThinking: false, ...(call.signal ? { signal: call.signal } : {}), ...(call.chat ? { chat: call.chat } : {}), }, parse: parsePairJudgeResponse, ...(call.onNotices ? { onNotices: call.onNotices } : {}), }); if (!outcome.ok) { return { outcome: "error", reason: outcome.error, ...(outcome.reason === "aborted" ? { aborted: true } : {}) }; } const verdict = parsePairJudgeResponse(outcome.raw); if (!verdict) return { outcome: "unparseable", reason: "the reply held no verdict in the expected shape" }; return { outcome: "verdict", verdict }; }, }; /** The tombstone-vocabulary reason a judge label maps to (`supersedes` -> `superseded`; the rest unchanged). */ export function tombstoneReason(label) { return label === "supersedes" ? "superseded" : label; } /** * The calibrated outcome table (owner grades): `duplicate`/`supersedes` keep the newer copy; * `subsumed` keeps the side opposite the derived `redundant` pointer. A side is retired only when the * judge listed nothing that it alone holds. */ export function decideRetirement(label, redundant, older, newer, only) { let decision; if (label === "duplicate" || label === "supersedes") decision = { retired: older, successor: newer }; else if (label === "subsumed" && redundant === "A") decision = { retired: older, successor: newer }; else if (label === "subsumed" && redundant === "B") decision = { retired: newer, successor: older }; if (!decision) return undefined; return (decision.retired === older ? only.onlyInA : only.onlyInB).length === 0 ? decision : undefined; } function checkSection(label, side) { return [ `Note ${label}:`, `Ref: ${side.asset.ref}`, `Description: ${asNonEmptyString(side.frontmatter.description) ?? "(none)"}`, "Content:", "```", stripFrontmatterBody(side.raw), "```", "", ].join("\n"); } /** * The second look a retirement gets before it may retire unattended: one call * that asks only what the retired note holds that the kept one lacks. True * only on a clean, empty answer (it caught 2 of 4 duplicates the judge got * wrong, and held back none of 109 right ones). */ async function confirmNothingLost(ctx, retired, successor) { const outcome = await callStage({ runner: ctx.llmRunner, system: consolidatePairCheckPrompt, prompt: `${checkSection("X (to delete)", retired)}\n${checkSection("Y (kept)", successor)}\n${termHints([`Tokens only in X: ${exclusiveTerms(retired, successor)}`])}${Date.parse(retired.createdIso) === Date.parse(successor.createdIso) ? `\n${consolidatePairSameAge}` : ""}`, request: { responseSchema: PAIR_CHECK_JSON_SCHEMA, enableThinking: false, signal: ctx.opts.signal, ...(ctx.chat ? { chat: ctx.chat } : {}), }, parse: (raw) => claimList(parseEmbeddedJsonResponse(raw)?.missing), ...(ctx.opts.onNotices ? { onNotices: ctx.opts.onNotices } : {}), }); if (!outcome.ok) return false; return claimList(parseEmbeddedJsonResponse(outcome.raw)?.missing)?.length === 0; } const PAIR_FAILURES_REPORTED_MAX = 20; /** A bounded one-line reason with URLs and credentials removed; never the prompt or the reply. */ function failedPair(kind, reason) { const line = reason .replace(/https?:\/\/\S+/g, "<url>") .replace(/\s+/g, " ") .trim(); return { failure: { kind, reason: redactErrorBody(line) } }; } /** * One pair: judge it, then (for a retire class) apply the guards and mint * the proposal. Never throws — a failure is counted in `failedJudgments` or * pushed to `warnings`, never lost silently and never aborting the run. */ async function judgeOne(ctx, candidate) { const initiatorSide = loadSide(candidate.initiator, ctx.gitFirstAdded, ctx.stashDir); const otherSide = loadSide(candidate.other, ctx.gitFirstAdded, ctx.stashDir); if (!initiatorSide || !otherSide) return {}; // unreadable since selection — skip, not a judge failure const judgedScope = scopeFromFrontmatter(initiatorSide.frontmatter); if (!sameScope(judgedScope, scopeFromFrontmatter(otherSide.frontmatter))) return {}; const scopesStillFresh = () => [initiatorSide, otherSide].every((side) => { const live = loadSide(side.asset, ctx.gitFirstAdded, ctx.stashDir); return live !== undefined && sameScope(judgedScope, scopeFromFrontmatter(live.frontmatter)); }); // This exact pair (same two refs, same two content hashes, // EITHER orientation) was already judged and rejected OR reverted. Checked // HERE, before the judge call, not after — the judge (not yet run) is what // decides which side would be "retired" this time, so both orientations // are checked against the current content hashes rather than waiting for // a verdict to pick one. A settled pair therefore costs no LLM call. const initiatorHash = contentHash(initiatorSide.raw, "body"); const otherHash = contentHash(otherSide.raw, "body"); if (ctx.rejectedPairKeys.has(rejectedPairKey(initiatorSide.asset.ref, otherSide.asset.ref, initiatorHash, otherHash)) || ctx.rejectedPairKeys.has(rejectedPairKey(otherSide.asset.ref, initiatorSide.asset.ref, otherHash, initiatorHash))) { return {}; } const { older, newer } = orderByAge(initiatorSide, otherSide); const judged = await pairJudge.run({ a: pairNoteOf(older), b: pairNoteOf(newer) }, { runner: ctx.llmRunner, ...(ctx.opts.signal ? { signal: ctx.opts.signal } : {}), ...(ctx.chat ? { chat: ctx.chat } : {}), ...(ctx.opts.onNotices ? { onNotices: ctx.opts.onNotices } : {}), }); if (judged.outcome === "unparseable") return failedPair("parse", judged.reason); if (judged.outcome === "error") return failedPair(judged.aborted ? "cancelled" : "transport", judged.reason); const { verdict } = judged; ctx.labelCounts[verdict.relation]++; if (verdict.relation === "contradicts") return {}; // counted; stays human — no proposal, no belief write if (!isRetireLabel(verdict.relation)) return {}; // overlap / unrelated: judged_no_action const decision = decideRetirement(verdict.relation, verdict.redundant, older, newer, verdict); if (!decision) return {}; let { retired, successor } = decision; // Owner rule (#1092): knowledge is never replaced with a memory (a `.derived` memory is a memory). When the memory // holds nothing the note lacks, retire the memory in favour of the note instead; otherwise leave the pair alone. // The flipped pair then runs every guard below like any memory retirement. if (retired.asset.type === "knowledge" && successor.asset.type === "memory") { if ((successor === older ? verdict.onlyInA : verdict.onlyInB).length > 0) return {}; [retired, successor] = [successor, retired]; } // Guards. if (retired.asset.type === "memory" && retired.asset.name.endsWith(DERIVED_SUFFIX)) { // The parent is the ref without the `.derived` suffix, so a subfolder memory keeps its folder. const parentRef = retired.asset.ref.replace(/\.derived$/, ""); if (indexedAsset(retired.asset.bundleId, parentRef)) return {}; // never retire a .derived memory whose parent still exists } const retiredHash = contentHash(retired.raw, "body"); const successorHash = contentHash(successor.raw, "body"); // B2: an asset retired (or already spent as a successor) earlier in this // run cannot be retired or reused as a successor again — the same-run half // of the chain guard (the accept-time hash/existence check is the other, // durable half). const retiredKey = stripBundle(retired.asset.ref); const successorKey = stripBundle(successor.asset.ref); // The verdict is valid, but the conflicting proposal must resolve before // this retirement can proceed. Leave its initiator eligible for a later run. if (ctx.retiredThisRun.has(retiredKey) || ctx.retiredThisRun.has(successorKey)) { return { deferred: "same_run_retirement" }; } ctx.retiredThisRun.add(retiredKey); ctx.retiredThisRun.add(successorKey); const reason = tombstoneReason(verdict.relation); if (ctx.opts.dryRun) { ctx.retired.push(`${retired.asset.ref} -> ${successor.asset.ref}`); ctx.perInitiatorProposed.add(candidate.initiator.ref); return {}; } // Continuity check: replay the retired asset's own // past queries and flag, but do not block, a pair where the successor // would not have shown up where the retired asset did. const continuityRisk = await checkRetirementContinuity({ stashDir: ctx.stashDir, config: ctx.config, retiredRef: retired.asset.ref, successorRef: successor.asset.ref, retiredRaw: retired.raw, successorRaw: successor.raw, ledgerAccess: { proposalsCtx: ctx.opts.proposalsCtx }, search: ctx.continuitySearch, }); if (!scopesStillFresh()) return failedPair("other", "a note changed scope while the pair was being judged"); const retirement = { judgedScope, retiredRef: retired.asset.ref, successorRef: successor.asset.ref, cosine: candidate.cosine, judgeLabel: verdict.relation, judgeReason: verdict.reason, // The judge's A is the older side and B the newer (see orderByAge); record the lists by role. onlyInRetired: retired === older ? verdict.onlyInA : verdict.onlyInB, onlyInSuccessor: retired === older ? verdict.onlyInB : verdict.onlyInA, retiredContentHash: retiredHash, successorContentHash: successorHash, reason, ...(continuityRisk ? { continuityRisk } : {}), }; try { const proposal = createRetireProposal(ctx.stashDir, { ref: retired.asset.ref, // A generator of its own, kept apart from the promote pass's // "consolidate" proposals — `accept --generator consolidate` (bulk // promotion review) never sweeps a retire proposal, and the reverse. source: "consolidate-pair", sourceRun: ctx.opts.sourceRun, ...(ctx.opts.writeTarget ? { target: proposalTargetOf(ctx.opts.writeTarget) } : {}), confidence: verdict.confidence, retirement, }, ctx.opts.proposalsCtx); ctx.retired.push(proposal.id); ctx.perInitiatorProposed.add(candidate.initiator.ref); // A retirement the second look confirms loses nothing retires unattended: // the triage drain accepts it under its usual applyMode. The retired side // holds no claim of its own for any label (`decideRetirement` mints nothing // else); a duplicate must also leave the kept side with none, while a // subsumed or superseding successor holds more by definition. Replay // precision 336/360 (duplicate 0.98, subsumed 0.92, supersedes 0.875, // 2026-10-07); a duplicate alone was 109 of 111 safe on the owner's // reviewed pairs (2026-10-04). Anything else waits for a person. if ((verdict.relation !== "duplicate" || verdict.onlyInA.length + verdict.onlyInB.length === 0) && !continuityRisk && (await confirmNothingLost(ctx, retired, successor)) && scopesStillFresh()) { recordGateDecision(ctx.stashDir, proposal.id, { outcome: "staged", reason: verdict.relation, gate: PAIR_PASS_GATE, contentHash: proposalContentHash(proposal), }, ctx.opts.proposalsCtx); } return {}; } catch (error) { ctx.warnings.push(`Pair pass: could not mint a retire proposal for ${retired.asset.ref}: ${error instanceof Error ? error.message : String(error)}`); // A mint failure is transient (a lock, a disk error, a // validation hiccup) — no row is // written and the pair is retried next run instead of abandoned. return failedPair("other", error instanceof Error ? error.message : String(error)); } } const emptyLabelCounts = () => ({ duplicate: 0, subsumed: 0, supersedes: 0, contradicts: 0, overlap: 0, unrelated: 0, }); /** * The pair pass: initiators -> candidates -> one judge call per * pair -> retire proposals for the calibrated classes. Runs alongside the * promote pass, sharing its gate, its frozen LLM runner and its * connection's concurrency. `bundleId` is the target bundle's id (`undefined` skips the * pass — nothing to scope candidates to). */ export async function runConsolidatePairPass(opts, config, stashDir, bundleId, warnings, /** Test seams: a transport override for the judge call, and for the continuity check's search call. Production callers omit both. */ seams = {}) { const empty = { initiators: 0, initiatorsBacklog: 0, pairsJudged: 0, labelCounts: emptyLabelCounts(), retired: [], failedJudgments: 0, deferredJudgments: 0, }; const llmRunner = opts.llmRunner ?? undefined; if (!bundleId || !llmRunner) return empty; let initiators; let candidates; let gitFirstAdded; let db; const unvectored = new Set(); try { db = opts.dryRun ? openReadonlyExistingDatabase(undefined, { isolatedSnapshot: true }) : openExistingDatabase(); if (!db) return empty; gitFirstAdded = loadGitFirstAddedMap(stashDir); const pool = loadPairPassPool(db, bundleId); initiators = selectInitiators(pool, opts, stashDir, gitFirstAdded).initiators; candidates = selectCandidates(db, initiators, bundleId, unvectored); } catch (error) { warnings.push(`Pair pass: index unavailable — skipped (${error instanceof Error ? error.message : String(error)}).`); return empty; } finally { if (db) closeDatabase(db); } const initiatorsBacklog = initiators.filter((i) => i.backlog).length; if (unvectored.size > 0) { warnings.push(`Pair pass: ${unvectored.size} asset(s) have no stored embedding, so their neighbours cannot be found and they were not judged. The pair pass needs stored embeddings (set semanticSearchMode to "auto" in the config, then run akm index).`); } // Never judge a pair when either side already has a pending retire // proposal, as the retired ref OR its successor (B2 widens this from the // retired ref alone): an asset spoken for by one pending decision cannot // also be judged as part of another until that decision resolves. const pendingRetireRefs = new Set(); try { for (const p of listProposalsReadOnly(stashDir, { status: "pending" }, opts.proposalsCtx)) { if (!isRetireProposal(p)) continue; pendingRetireRefs.add(stripBundle(p.ref)); if (p.retirement?.successorRef) pendingRetireRefs.add(stripBundle(p.retirement.successorRef)); } } catch { // Best-effort de-dup only; a failed read never blocks judging. } const isPendingBlocked = (c) => pendingRetireRefs.has(stripBundle(c.initiator.ref)) || pendingRetireRefs.has(stripBundle(c.other.ref)); const rejectedPairKeys = loadRejectedPairKeys(stashDir, opts.proposalsCtx); // Admit WHOLE initiators under MAX_PAIRS_PER_RUN, never individual pairs: a // flat cap on pairs would let a pending-blocked pair spend a budget slot // doing nothing and leave later initiators partially judged forever (no // ledger row, so the same pairs would be re-judged every night). A group with // any pending-blocked pair is skipped before it can spend any budget at // all. New-or-changed initiators (T_PAIR floor) are admitted before ANY // backlog initiator regardless of cosine, then backlog initiators by their // own best cosine — within a tier, a later, smaller group that still fits // is admitted even after an earlier, larger one did not (first-fit), so // the budget is not left idle just because the next-best group overflows // it. const byInitiator = new Map(); for (const c of candidates) { const list = byInitiator.get(c.initiator.ref); if (list) list.push(c); else byInitiator.set(c.initiator.ref, [c]); } const isNewOrChanged = (i) => !i.backlog || i.newMaterial; const groups = [...byInitiator.values()] .filter((group) => !group.some(isPendingBlocked)) .sort((a, b) => { const tierA = isNewOrChanged(a[0].initiator) ? 0 : 1; const tierB = isNewOrChanged(b[0].initiator) ? 0 : 1; if (tierA !== tierB) return tierA - tierB; return b[0].cosine - a[0].cosine; // candidates is cosine-desc, so group[0] is this initiator's best. }); const judgeable = []; for (const group of groups) { if (judgeable.length + group.length > MAX_PAIRS_PER_RUN) continue; // first-fit: a smaller later group may still fit. judgeable.push(...group); } const ctx = { opts, config, stashDir, llmRunner, gitFirstAdded, labelCounts: emptyLabelCounts(), perInitiatorProposed: new Set(), retired: [], warnings, rejectedPairKeys, retiredThisRun: new Set(), ...(seams.chat ? { chat: seams.chat } : {}), // One instance for the whole run (not one per proposal), so its // "fell back once, go keyword-only from here" throttle actually covers // every remaining query in this run, not just one proposal's own five. continuitySearch: seams.continuitySearch ?? createContinuitySearch(stashDir, config), }; const failures = []; const deferrals = []; // Failed or deferred pairs get no ledger row: their work is still unsettled. const unsettledInitiators = new Set(); if (judgeable.length > 0) { const results = await concurrentMap(judgeable, (candidate) => judgeOne(ctx, candidate), (llmRunner.kind === "connection" ? llmRunner.concurrency : undefined) ?? 1, { signal: opts.signal }); results.forEach((r, idx) => { // `concurrentMap` leaves an entry `undefined` for a call an aborted run never sent at all: that pair did not // settle either, so it is counted as cancelled rather than as a clean "no action" verdict. const failure = r === undefined ? { kind: "cancelled", reason: "not sent: the run was cancelled" } : r.failure; const deferred = r?.deferred; if (!failure && !deferred) return; const candidate = judgeable[idx]; unsettledInitiators.add(candidate.initiator.ref); const pair = { initiator: candidate.initiator.ref, other: candidate.other.ref }; if (failure) failures.push({ ...pair, ...failure }); if (deferred) deferrals.push({ ...pair, reason: deferred }); }); } // A ledger row is written for an initiator only once ALL of its OWN // candidates were admitted (whole-initiator admission above makes this a // simple membership check: judgeable either has every one of an // initiator's candidates, or none of them) and none failed or were deferred // — including an initiator with zero candidates, which // trivially satisfies both. One left out by the cap or a pending-proposal // collision gets no row at all, so the next run reconsiders it rather // than treating it as settled. if (!opts.dryRun) { const admittedRefs = new Set(judgeable.map((c) => c.initiator.ref)); const ledgerInputs = initiators .filter((i) => { // No stored vector: the neighbour query never ran, so nothing was judged. Leave it unsettled. if (unvectored.has(i.ref)) return false; const hasCandidates = byInitiator.has(i.ref); if (!hasCandidates) return true; if (!admittedRefs.has(i.ref)) return false; return !unsettledInitiators.has(i.ref); }) .map((i) => ({ stashDir, ref: i.ref, source: PAIR_PASS_LEDGER_SOURCE, outcome: ctx.perInitiatorProposed.has(i.ref) ? "proposed" : "judged_no_action", contentHash: i.bodyHash, })); recordLedgerAttempt({ proposalsCtx: opts.proposalsCtx }, ledgerInputs); } const deferredJudgments = deferrals.length; if (deferredJudgments > 0) { warnings.push(`Pair pass: ${deferredJudgments} retire decisions deferred because a note is already reserved for retirement in this run; these pairs remain eligible for later runs.`); } const failedJudgments = failures.length; const failureKinds = {}; for (const { kind } of failures) failureKinds[kind] = (failureKinds[kind] ?? 0) + 1; if (failedJudgments > 0) { const kinds = Object.entries(failureKinds) .map(([kind, n]) => `${kind} ${n}`) .join(", "); warnings.push(`Pair pass: ${failedJudgments} of ${judgeable.length} pair judgments did not settle (${kinds}); they are retried next run.`); } return { initiators: initiators.length, initiatorsBacklog, pairsConsidered: candidates.length, // Count the judge's parsed verdicts, including decisions deferred or failing after the verdict. pairsJudged: Object.values(ctx.labelCounts).reduce((sum, count) => sum + count, 0), labelCounts: ctx.labelCounts, retired: ctx.retired, failedJudgments, deferredJudgments, ...(deferredJudgments > 0 ? { deferrals: deferrals.slice(0, PAIR_FAILURES_REPORTED_MAX) } : {}), ...(failedJudgments > 0 ? { failureKinds, failures: failures.slice(0, PAIR_FAILURES_REPORTED_MAX) } : {}), }; }