UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

208 lines (207 loc) • 11.3 kB
import { isPersonalPlaneScope, parseScopeKey } from "./scope-contract.js"; import { CONTROL_PLANE_DIR, directoryPinOf, refuseAbsentPinnedStore, refuseAbsentStore, resolveMemoryEngineRoot } from "./layout.js"; import { ERASURE_CARRIER_CLASSES, FileMemoryEngineBackend } from "./file-backend.js"; import { thrownText } from "../thrown-value.js"; import { describeRejectedValue } from "../tool-search-setting.js"; import { normalizeMemorySpec } from "../memory.js"; import { join } from "node:path"; export function derivePersonalMemoryDir(configRoot) { return join(configRoot, "personal", "memory"); } export function derivePersonalControlDir(configRoot) { return join(configRoot, "personal", CONTROL_PLANE_DIR); } export function classifyScopePlanes(scopes, writeScope) { const project = []; const personal = []; for (const s of scopes) { (isPersonalPlaneScope(parseScopeKey(s)) ? personal : project).push(s); } const writePlane = writeScope === null ? null : isPersonalPlaneScope(parseScopeKey(writeScope)) ? "personal" : "project"; return { project, personal, writePlane }; } export function scopePlanesOf(scopes, writeScope, scopeContract) { return scopeContract === "v2" ? classifyScopePlanes(scopes, writeScope) : undefined; } export function memoryPlaneStore(plane, backend, engineRoot, onIncident) { if (plane === "project" || directoryPinOf(backend) === undefined) return backend; refuseAbsentPinnedStore(backend); return new FileMemoryEngineBackend(derivePersonalMemoryDir(engineRoot), { controlDir: derivePersonalControlDir(engineRoot), ...(onIncident !== undefined ? { onIncident } : {}) }); } export function resolveMemoryScopeStore(input) { const face = "resolveMemoryScopeStore"; judgeMemoryStoreSeat(face, input); const plane = memoryScopePlaneOf(face, input.scope, input.scopeContract); return { plane, backend: memoryPlaneStore(plane, input.backend, resolveMemoryEngineRoot(input.memoryEngineDir), input.onIncident) }; } export function judgeMemoryStoreSeat(face, input) { const { scopeContract, memoryEngineDir } = input; for (const key of ["scopeContract", "memoryEngineDir"]) { if (!Object.prototype.hasOwnProperty.call(input, key)) refuseMemoryStoreInput(face, `${key} is a required key (write undefined to state its absence)`, undefined); } judgeScopeContract(face, scopeContract); if (memoryEngineDir !== undefined && (typeof memoryEngineDir !== "string" || memoryEngineDir === "")) refuseMemoryStoreInput(face, "memoryEngineDir must be a non-empty string or undefined", memoryEngineDir); } function judgeScopeContract(face, scopeContract) { if (scopeContract !== undefined && scopeContract !== "v2") refuseMemoryStoreInput(face, `scopeContract must be "v2" or undefined`, scopeContract); } export function memoryScopePlaneOf(face, scope, scopeContract) { judgeScopeContract(face, scopeContract); let spec; try { spec = normalizeMemorySpec({ scopes: [scope], writeScope: scope, ...(scopeContract === "v2" ? { scopeContract } : {}) }); } catch (err) { refuseMemoryStoreInput(face, `the scope contract cannot read the key: ${thrownText(err)}`, scope, err); } if (spec === undefined || spec.writeScope === null) refuseMemoryStoreInput(face, "scope must be a non-empty key", scope); return scopePlanesOf(spec.scopes, spec.writeScope, spec.scopeContract)?.writePlane ?? "project"; } export function refuseMemoryStoreInput(face, what, v, cause) { const e = new Error(`${face}: ${what} (got ${describeRejectedValue(v)}) — refusing to guess which store was meant.`, cause !== undefined ? { cause } : undefined); e.code = "config.memory_scope_key"; throw e; } export function needsDualRoots(planes) { const projectActive = planes.project.length > 0 || planes.writePlane === "project"; return projectActive && reachesPersonalPlane(planes); } export function reachesPersonalPlane(planes) { return planes.personal.length > 0 || planes.writePlane === "personal"; } export function refuseAbsentPlaneStores(backend, engineRoot, personal) { refuseAbsentPinnedStore(backend); if (personal && directoryPinOf(backend) !== undefined) refuseAbsentStore(derivePersonalMemoryDir(engineRoot), derivePersonalControlDir(engineRoot)); } export function parsedProjectPlane(planes, writeScope) { const keys = [...planes.project, ...(planes.writePlane === "project" && writeScope !== null ? [writeScope] : [])]; return keys.map(parseScopeKey); } export function mergeInjections(project, personal) { if (!project) return personal ?? { instruction: "", block: "" }; if (!personal) return project; const instruction = project.instruction || personal.instruction; const readOnlyNotice = instruction === "" && project.readOnlyNotice !== undefined && personal.readOnlyNotice !== undefined ? project.readOnlyNotice : undefined; const indexParts = [project.index, personal.index].filter((s) => Boolean(s && s.trim())); const announcements = [...(project.announcements ?? []), ...(personal.announcements ?? [])]; const announceParts = [project.announceBlock, personal.announceBlock].filter((s) => Boolean(s && s.trim())); const blockParts = [instruction || readOnlyNotice, ...indexParts]; const indexSeed = project.indexSeed ?? personal.indexSeed; const indexUnseeded = project.indexUnseeded ?? personal.indexUnseeded; return { instruction, ...(readOnlyNotice !== undefined ? { readOnlyNotice } : {}), ...(indexParts.length > 0 ? { index: indexParts.join("\n\n") } : {}), ...(announcements.length > 0 ? { announcements } : {}), ...(announceParts.length > 0 ? { announceBlock: announceParts.join("\n") } : {}), ...(indexSeed !== undefined ? { indexSeed } : {}), ...(indexUnseeded !== undefined ? { indexUnseeded } : {}), block: blockParts.filter((s) => s && s.trim()).join("\n\n"), }; } export function mergeHarvestReports(a, b) { const merged = { ok: a.ok && b.ok, patches: { add: a.patches.add + b.patches.add, update: a.patches.update + b.patches.update, delete: a.patches.delete + b.patches.delete, }, conflicts: [...a.conflicts, ...b.conflicts], rejections: [...a.rejections, ...b.rejections], quarantined: [...a.quarantined, ...b.quarantined], movedToQuarantine: [...a.movedToQuarantine, ...b.movedToQuarantine], missing: [...a.missing, ...b.missing], restored: [...a.restored, ...b.restored], warnings: [...a.warnings, ...b.warnings], }; const reportId = a.reportId ?? b.reportId; if (reportId !== undefined) merged.reportId = reportId; const parts = [...new Set([a.reportId, b.reportId].filter((x) => x !== undefined))]; if (parts.length > 1) merged.mergedFrom = parts; const incident = a.incident ?? b.incident; if (incident !== undefined) merged.incident = incident; const degraded = a.degraded ?? b.degraded; if (degraded !== undefined) merged.degraded = degraded; const inbound = [...(a.inboundFindings ?? []), ...(b.inboundFindings ?? [])]; if (inbound.length > 0) merged.inboundFindings = inbound; const qf = [...(a.quarantineFailures ?? []), ...(b.quarantineFailures ?? [])]; if (qf.length > 0) merged.quarantineFailures = qf; const withheld = [...(a.restoreWithheld ?? []), ...(b.restoreWithheld ?? [])]; if (withheld.length > 0) merged.restoreWithheld = withheld; const rec = a.consolidationRecommended ?? b.consolidationRecommended; if (rec !== undefined) merged.consolidationRecommended = rec; const ac = a.containment; const bc = b.containment; if (ac !== undefined || bc !== undefined) { merged.containment = { indexRolledBack: ac?.indexRolledBack === true || bc?.indexRolledBack === true, quarantinedInstruction: [...(ac?.quarantinedInstruction ?? []), ...(bc?.quarantinedInstruction ?? [])], heldInstruction: [...(ac?.heldInstruction ?? []), ...(bc?.heldInstruction ?? [])], releasedHolds: [...(ac?.releasedHolds ?? []), ...(bc?.releasedHolds ?? [])], disposedHolds: [...(ac?.disposedHolds ?? []), ...(bc?.disposedHolds ?? [])], }; } return merged; } export function mergeErasureAttestations(a, b) { const claimed = new Set([...a.erased, ...b.erased, ...(a.erasedPreviously ?? []), ...(b.erasedPreviously ?? [])].map((row) => row.id)); const notFound = new Map(); for (const row of [...a.notFound, ...b.notFound]) { if (claimed.has(row.id)) continue; const unknown = row.historyUnknown === true || notFound.get(row.id)?.historyUnknown === true; notFound.set(row.id, unknown ? { id: row.id, historyUnknown: true } : { id: row.id }); } const answered = (x) => typeof x === "object" && x !== null && typeof x.removed === "number" && typeof x.remaining === "number"; const unreadable = (x, y) => { const [p, q] = [Reflect.get(x, "unreadable"), Reflect.get(y, "unreadable")]; return typeof p === "number" && typeof q === "number" ? { unreadable: p + q } : {}; }; const carrier = (x, y) => (answered(x) && answered(y) ? { removed: x.removed + y.removed, remaining: x.remaining + y.remaining, ...unreadable(x, y) } : { unverified: true }); const counted = (x) => typeof x === "object" && x !== null && typeof x.count === "number"; const count = (x, y) => (counted(x) && counted(y) ? { count: x.count + y.count } : { unverified: true }); const custodyRank = { complete: 0, "capability-absent": 1, damaged: 2 }; const erasedPreviously = [...(a.erasedPreviously ?? []), ...(b.erasedPreviously ?? [])]; const carriers = {}; for (const cls of ERASURE_CARRIER_CLASSES) carriers[cls] = carrier(a.residuals.carriers[cls], b.residuals.carriers[cls]); return { v: 2, requestId: a.requestId, at: Math.max(a.at, b.at), status: a.status === "complete" && b.status === "complete" ? "complete" : "partial", evidenceCapability: a.evidenceCapability === "journal" && b.evidenceCapability === "journal" ? "journal" : "none", custodyState: custodyRank[a.custodyState] >= custodyRank[b.custodyState] ? a.custodyState : b.custodyState, select: a.select, selectHash: a.selectHash, resolvedIds: [...new Set([...a.resolvedIds, ...b.resolvedIds])], erased: [...a.erased, ...b.erased], notFound: [...notFound.values()], ...(erasedPreviously.length > 0 ? { erasedPreviously } : {}), conflicts: [...a.conflicts, ...b.conflicts], residuals: { carriers, quarantineUnattributed: count(a.residuals.quarantineUnattributed, b.residuals.quarantineUnattributed), derivedEntries: count(a.residuals.derivedEntries, b.residuals.derivedEntries), replay: a.residuals.replay === "converges" && b.residuals.replay === "converges" ? "converges" : "unsupported", propagation: "local-store-only", }, }; }