UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

101 lines (100 loc) • 5.17 kB
import { ConsolidationRefusedError, deriveSupersededSet } from "./consolidation.js"; import { isRunCyclePlanRequestId } from "./consolidation-driver.js"; function refused(message) { return new ConsolidationRefusedError("memory.consolidation_refused", `memory consolidation run revert refused: ${message}`); } function mintedEdges(product) { const inputs = product?.frontmatter?.distilled?.inputs; if (!Array.isArray(inputs)) return []; const rows = inputs; const out = []; for (const i of rows) { if (typeof i === "object" && i !== null && Reflect.get(i, "superseded") === true && typeof Reflect.get(i, "id") === "string") out.push(Reflect.get(i, "id")); } return out; } export async function revertConsolidationRun(engine, input) { const { scope, runId, reason, requestId } = input ?? {}; for (const [key, value] of [["scope", scope], ["runId", runId], ["reason", reason], ["requestId", requestId]]) { if (typeof value !== "string" || value.trim() === "") throw refused(`${key} must be a non-empty string`); } const run = await engine.readConsolidationDriverRun(scope); if (run === undefined || run.runId !== runId) { throw refused(`run ${JSON.stringify(runId.slice(0, 80))} is not the latest consolidation run of scope ${JSON.stringify(scope.slice(0, 80))} — the run account keeps only each scope's latest run, so only that run can be reverted`); } if (run.state !== "settled") throw refused(`run ${runId} is still pending — a resume would write more of it; revert it once it has settled`); const gate = await engine.readConsolidationGateState(scope); if (gate.state === "corrupt") throw refused(`the consolidation gate of scope ${JSON.stringify(scope.slice(0, 80))} cannot be read, so whether a plan still holds its seat is unknown: ${gate.detail}`); const seated = gate.state === "present" ? gate.row.openPlanId : undefined; if (seated !== undefined) { throw refused(`plan ${seated} holds the seat of scope ${JSON.stringify(scope.slice(0, 80))} and may still land products — converge it with reconcileConsolidation, or resolveConsolidationPlan(planId, "discard"), then revert`); } const store = engine.governance; const listed = new Set(run.planIds); const unreadablePlans = []; const unlistedPlans = []; const products = []; for (const planId of new Set([...(await store.listPlanIds()), ...run.planIds])) { const read = await store.readPlan(planId); if (read.state !== "ok") { if (listed.has(planId)) unreadablePlans.push(planId); continue; } const plan = read.plan; if (!listed.has(planId)) { if (plan.scope === scope && isRunCyclePlanRequestId(run.requestId, plan.requestId)) unlistedPlans.push(planId); continue; } for (const p of plan.products) products.push({ id: p.id, planId, applied: plan.productStates[p.id] === "applied", edges: mintedEdges(p) }); } const batch = `consolidation-run-revert:${runId}:${requestId}`; const standing = new Map((await engine.listCommittedHeaders([scope])).map((h) => [h.id, h])); const landed = []; const notWithdrawn = []; const toWithdraw = []; for (const p of products) { const h = standing.get(p.id); if (h === undefined) { if (p.applied) { landed.push(p); notWithdrawn.push({ id: p.id, planId: p.planId, why: "absent" }); } continue; } landed.push(p); if (h.distilled === undefined || h.rev !== h.distilled.carrierRev) notWithdrawn.push({ id: p.id, planId: p.planId, why: "edited_since_run" }); else toWithdraw.push({ id: p.id, planId: p.planId }); } const assigned = await engine.challengeEntries(toWithdraw.map((p) => p.id), `consolidation run ${runId} reverted by the host: ${reason}`, batch); const headers = await engine.listCommittedHeaders([scope]); const excluded = await engine.readChallengeExclusions(); const generationOf = new Map(assigned.map((a) => [a.entryId, a.generation])); const withdrawn = []; for (const p of toWithdraw) { if (excluded.has(p.id)) withdrawn.push({ ...p, generation: generationOf.get(p.id) }); else notWithdrawn.push({ ...p, why: "resolved" }); } const superseded = deriveSupersededSet(headers, { excluded: (id) => excluded.has(id) }); const present = new Set(headers.map((h) => h.id)); const inputs = [...new Set(landed.flatMap((p) => p.edges))].sort().map((id) => { if (!present.has(id)) return { id, state: "absent" }; if (excluded.has(id)) return { id, state: "withheld" }; const by = superseded.get(id); return by !== undefined ? { id, state: "superseded", by } : { id, state: "active" }; }); return { runId, scope, withdrawn, notWithdrawn, inputs, unlistedPlans: unlistedPlans.sort(), unreadablePlans: unreadablePlans.sort() }; }