@sema-agent/core
Version:
Stateless, task-oriented AI agent core
923 lines • 66.2 kB
JavaScript
import { createHash } from "node:crypto";
import { isAbsolute, resolve, sep } from "node:path";
import { deliverEngineNotice } from "../types.js";
import { adoptHostPromise } from "../host-promise.js";
import { admitMemoryScopes } from "../memory-admission.js";
import { adoptLegacyRepoDirs, assertRootNotSensitive, canonicalize, captureRecordsExpectingStore, deriveRepoControlPlaneDir, deriveProjectControlDir, deriveProjectMemoryDir, deriveRepoKey, deriveRepoMemoryDir, directoryPinOf, effectiveControlRootOf, isContainedIn, lookupProjectIdHint, recordProjectIdHint, resolveRunMemoryEngineRoot, transferMemoryAnnouncements } from "../memory-engine/layout.js";
import { derivePersonalControlDir, derivePersonalMemoryDir, memoryPlaneStore, mergeHarvestReports, mergeInjections, needsDualRoots, parsedProjectPlane, reachesPersonalPlane, refuseAbsentPlaneStores, scopePlanesOf } from "../memory-engine/dual-root.js";
import { memoryEngineOpens, memoryProjectScopeAbsentNotice, normalizeMemorySpec } from "../memory.js";
import { deriveSupersededSet, fileGovernanceStore, fileSessionCaptureRecordStore, governanceStoreIsFileOver } from "../memory-engine/consolidation.js";
import { shadowNamesOf } from "../memory-engine/shadowing.js";
import { mintSystemReminder } from "../reminder-mint.js";
import { MEMORY_ANNOUNCEMENT_CAPTURE_OPTOUT_CODA, MEMORY_ANNOUNCEMENT_READONLY_CODA, MEMORY_CAPTURE_OPTOUT_NOTICE, MEMORY_PREFERENCE_DISCIPLINE, MEMORY_READONLY_NOTICE, MemoryEngine, memoryCaptureOptedOutNotice, memoryConsolidationRecommendedNotice, memoryHarvestConflictNotice, memoryHarvestQuarantinedNotice, memoryHarvestRefusedNotice, memoryHoldNotices, memoryRecallDisciplineSegment, memoryRestoreWithheldNotice, memorySessionPollutedNotice, memoryUnavailableNotice, pollutionContainmentCounts, } from "../memory-engine/engine.js";
import { captureMarkUnpersistedReadingOf, memoryMountFailedNotice, memoryMountFailedReadingOf } from "../memory-engine/mount-failed-notice.js";
import { adjudicateCaptureOptOut, captureOptOutDeniedError } from "./memory-capture-optout.js";
import { isDeliberateMemoryRefusal, unpersistedOptOutRefusal } from "./memory-phase-refusals.js";
import { sessionIncarnationResolver } from "../memory-engine/session-incarnation.js";
import { createMemoryEngineTools } from "../memory-engine/tools.js";
import { assertMemoryProjectVerdict, assertScopeContractPlacement, parseScopeKey } from "../memory-engine/scope-contract.js";
import { writableRootOf } from "../memory-engine/types.js";
import { createMemoryEntry } from "../memory-engine/entry-create.js";
import { MEMORY_TAIL_MAX_CHARS } from "./conversation-segment.js";
import { indexCopyOf, keepIndexCopy } from "../memory-engine/index-copies.js";
import { asThrownError, thrownText } from "../thrown-value.js";
import { enterConfigDoor, refusalAbout } from "../config-refusal-input.js";
function heldCapturePlane(engine, backend) {
const carrier = backend.governance;
return { engine, fileCarried: carrier === undefined || governanceStoreIsFileOver(carrier, engine.controlPlaneRoot) };
}
function memoryTailKeyOf(planes) {
const parts = [];
for (const [plane, h] of planes) {
const state = h.storeState;
if (typeof state !== "object")
return undefined;
parts.push([plane, h.memoryDir, h.scopes, h.writeScope, h.indexOnDiskUntrusted === true, h.adoptionRestricted === true, state.challenged, state.erasures]);
}
return createHash("sha256").update(JSON.stringify(parts), "utf8").digest("hex").slice(0, 16);
}
function memoryTailUnfrozenSentence(planes) {
return planes.some(([, h]) => h.storeState === "rolled_back")
? "the memory store's erasure count read lower than this process read it before — its account was removed or rolled back: restart the process; until then nothing of the store is frozen in this process, the memory band is read live on every leg, and a write to the store moves the prompt prefix on the next leg"
: "the memory store's state (the entries it withholds, the erasures it ran) could not be read, or a read that began later took a higher erasure count first; the memory band is read live until a mount reads it again, so a write to the store moves the prompt prefix on the next leg";
}
async function readAncestorCaptureOptOut(ancestorDir, ancestorId, held, hostStore) {
const plane = held.find((p) => resolve(p.engine.controlPlaneRoot) === resolve(ancestorDir));
if (plane !== undefined) {
const read = await plane.engine.sessionCaptureOptOutOrFault(ancestorId);
if (read.record === undefined && read.fault)
throw new Error(`the capture opt-out record store of the plane at ${ancestorDir} is unreadable`);
return read.record;
}
if (hostStore !== undefined)
return await captureRecordsExpectingStore(hostStore({ controlDir: ancestorDir }), ancestorDir).read(ancestorId);
if (held.length > 0 && held.every((p) => p.fileCarried))
return await captureRecordsExpectingStore(fileSessionCaptureRecordStore(ancestorDir), ancestorDir).read(ancestorId);
throw new Error(`the capture opt-out record of a spawning session is kept in the control plane at ${ancestorDir}, which no carrier this run holds can read`);
}
let undeclaredCapturePostureAnnounced = false;
export async function prepareMemory(input) {
const { spec, deps, sessionId, taskRootPath, admissionCtx } = input;
let memoryWriteGate;
const memorySpec = normalizeMemorySpec(spec.memory);
let admittedOrgScopes = [];
let ownOrgVerdict;
const deploymentScopeSet = new Set(deps.deploymentMemoryScopes ?? []);
const scopeOriginsSnapshot = memorySpec?.scopeOrigins !== undefined ? { ...memorySpec.scopeOrigins } : undefined;
if (memorySpec && scopeOriginsSnapshot !== undefined)
memorySpec.scopeOrigins = scopeOriginsSnapshot;
if (memorySpec && memorySpec.enabled && deps.memoryBackend) {
const outcome = await admitMemoryScopes({
memorySpec,
principal: spec.principal,
admission: deps.memoryScopeAdmission,
deploymentScopes: deploymentScopeSet,
orgMemoryDenied: admissionCtx.orgMemoryDenied,
complianceDegraded: admissionCtx.complianceDegraded,
parentAdmittedOrgScopes: admissionCtx.parentAdmittedOrgScopes,
priorOwnVerdict: admissionCtx.priorOwnVerdict,
governedProvenance: admissionCtx.governedProvenance,
});
admittedOrgScopes = outcome.admittedOrgScopes;
ownOrgVerdict = outcome.ownVerdict;
for (const droppedScope of outcome.droppedDeploymentScopes) {
deps.onError?.(new Error(`org memory scope "${droppedScope}" (deployment-declared) was narrowed away (admission resolver or the session's frozen verdict) — the layer is not mounted this session.`), { phase: "memory", sessionId });
}
if (outcome.writeScopeNarrowed) {
deps.onError?.(new Error(`org memory writeScope "${String(memorySpec.writeScope)}" was not explicitly granted by admission — the session's memory write face is read-only (org layers default read-only).`), { phase: "memory", sessionId });
}
memorySpec.scopes = outcome.scopes;
memorySpec.writeScope = outcome.writeScope;
}
if (memorySpec?.enabled === true && memorySpec.projectKey?.absent !== undefined) {
deliverEngineNotice(deps.onNotice, memoryProjectScopeAbsentNotice({ reason: memorySpec.projectKey.absent, taskRoot: taskRootPath, sessionId, writeScope: memorySpec.writeScope }));
}
const useMemoryEngine = memoryEngineOpens(memorySpec, deps);
const capturePosture = input.memoryCapturePolicy ?? "open";
const captureEntitlement = input.captureEntitlement ?? { value: undefined, faulted: false };
const captureDeclaredRaw = memorySpec?.capture === "off";
if (captureDeclaredRaw && memorySpec !== undefined && !memorySpec.enabled) {
deps.onError?.(new Error(`memory.capture:"off" appears beside memory.enabled:false — not a contradiction (memory is off entirely, so nothing is captured either way); the opt-out declaration is covered by enabled:false this run.`), { phase: "config", sessionId });
}
const captureDeclared = captureDeclaredRaw && useMemoryEngine;
const captureFloored = input.captureFloor === true && useMemoryEngine;
if (captureDeclared && !captureFloored) {
const verdict = adjudicateCaptureOptOut({ posture: capturePosture, entitlement: captureEntitlement, subject: "declaration" });
if (!verdict.allowed)
throw captureOptOutDeniedError(verdict.detail);
if (verdict.faultDisclosure !== undefined) {
deps.onError?.(new Error(verdict.faultDisclosure), { phase: "config", sessionId });
}
if (input.captureCarrierUnsupported === true) {
const e = new Error(`memory.capture:"off" cannot be honored on this deployment shape: the execution environment's paths are not the host's (remote/per-run) ` +
`and no RunnerDeps.memoryCaptureRecordStore is supplied, so core cannot know the control plane survives to a ` +
`resume replica — a privacy promise that silently expires at the first resume is refused rather than made. A ` +
`deployment whose control plane IS durable (a single persistent host using a remote sandbox) opts back in by ` +
`supplying the store explicitly — fileSessionCaptureRecordStore(controlDir) is that one-line declaration.`);
e.code = "config.memory_capture_unsupported";
throw refusalAbout("taskConfig", e);
}
}
let captureOptedOut = false;
let captureIndeterminate = false;
let captureLineageIndeterminate = false;
let memoryEngineSession;
const openedLegs = [];
let memoryTools;
let writeChannelOpen = false;
let memoryMarkedEntriesServed = false;
let memoryTailPlanes;
let effectiveMemoryScopes;
const originOf = (scope) => scopeOriginsSnapshot !== undefined
? scopeOriginsSnapshot[scope] === "deployment"
? "deployment"
: "request"
: deploymentScopeSet.has(scope)
? "deployment"
: "request";
const materializedResidue = [];
if (useMemoryEngine && memorySpec) {
try {
const backend = deps.memoryBackend;
const lineageTokens = new Map(input.captureForkOrigin !== undefined && input.captureForkOriginIncarnation !== undefined ? [[input.captureForkOrigin, input.captureForkOriginIncarnation]] : []);
const incarnationOpt = { sessionIncarnation: sessionIncarnationResolver(sessionId, input.sessionIncarnation, lineageTokens) };
const pinned = directoryPinOf(backend);
const engineRoot = resolveRunMemoryEngineRoot(deps.memoryEngineDir, deps.onNotice);
const planes = scopePlanesOf(memorySpec.scopes, memorySpec.writeScope, memorySpec.scopeContract);
refuseAbsentPlaneStores(backend, engineRoot, planes !== undefined && reachesPersonalPlane(planes));
assertRootNotSensitive("engine_root", engineRoot);
const repoRoot = deps.rootPath ?? taskRootPath;
if (memorySpec.scopeContract === "v2")
assertMemoryProjectVerdict(input.sessionProject, memorySpec.scopes, memorySpec.writeScope);
if (repoRoot) {
adoptLegacyRepoDirs(engineRoot, repoRoot, (err) => deps.onError?.(err, { phase: "memory", sessionId }));
}
let identityKey;
if (memorySpec.scopeContract === "v2" && repoRoot) {
const marker = input.sessionProject.project?.source === "marker" ? { projectId: input.sessionProject.project.id } : undefined;
const verdictOnPartitionRoot = deriveRepoKey(input.sessionProject.root) === deriveRepoKey(repoRoot);
if (marker) {
identityKey = marker.projectId;
const firstSwitch = verdictOnPartitionRoot && lookupProjectIdHint(engineRoot, repoRoot) !== marker.projectId;
if (verdictOnPartitionRoot)
recordProjectIdHint(engineRoot, repoRoot, marker.projectId);
if (firstSwitch && backend.governance === undefined) {
try {
const oldCtl = deriveRepoControlPlaneDir(engineRoot, repoRoot);
const newCtl = deriveProjectControlDir(engineRoot, marker.projectId);
await transferMemoryAnnouncements(fileGovernanceStore(oldCtl), fileGovernanceStore(newCtl));
}
catch (err) {
deps.onError?.(asThrownError(err), { phase: "config", sessionId });
}
}
}
else if (verdictOnPartitionRoot) {
const hint = lookupProjectIdHint(engineRoot, repoRoot);
if (hint !== undefined) {
deps.onError?.(new Error(`memory project marker missing but recoverable: ${repoRoot} previously carried projectId ${hint} ` +
`(.sema/project deleted?). Restore the marker to keep the identity-keyed memory mount; this session ` +
`falls back to the path-derived key.`), { phase: "config", sessionId });
}
}
}
const memoryDir = pinned ?? (identityKey !== undefined ? deriveProjectMemoryDir(engineRoot, identityKey) : deriveRepoMemoryDir(engineRoot, repoRoot));
const projectControlDir = identityKey !== undefined ? deriveProjectControlDir(engineRoot, identityKey) : deriveRepoControlPlaneDir(engineRoot, repoRoot);
const dual = planes !== undefined && needsDualRoots(planes);
const personalOnly = planes !== undefined && !dual && planes.project.length === 0 && planes.writePlane !== "project" && reachesPersonalPlane(planes);
if (memorySpec.scopeContract === "v2" && !personalOnly) {
assertScopeContractPlacement({
parsedScopes: dual
? parsedProjectPlane(planes, memorySpec.writeScope)
: [...memorySpec.scopes, ...(memorySpec.writeScope !== null ? [memorySpec.writeScope] : [])].map(parseScopeKey),
memoryDir,
repoRoot,
});
}
const personalMemoryDir = derivePersonalMemoryDir(engineRoot);
const personalControlDir = derivePersonalControlDir(engineRoot);
const captureStoreOpt = (dir, b, configured) => deps.memoryCaptureRecordStore !== undefined ? { captureRecordStore: deps.memoryCaptureRecordStore({ controlDir: effectiveControlRootOf(dir, { pinnedBy: b, controlDir: configured }) }) } : {};
const createPersonalEngine = (personalBackend) => {
return {
engine: enterConfigDoor("deps", () => new MemoryEngine({ backend: personalBackend, memoryDir: personalMemoryDir, controlDir: personalControlDir, onIncident: onEngineIncident, provenance: input.memoryProvenance, ...captureStoreOpt(personalMemoryDir, personalBackend, personalControlDir), ...incarnationOpt, ...(input.deps.memoryConsolidation !== undefined ? { consolidation: input.deps.memoryConsolidation } : {}) })),
backend: personalBackend,
};
};
const onEngineIncident = (err) => deps.onError?.(err, { phase: "memory", sessionId });
const adoptionRestricted = input.memoryPersistenceDeclared === false;
let capturePlanes = [];
const armCaptureOptOut = async (eng) => {
const standingRead = await eng.sessionCaptureOptOutOrFault(sessionId);
if (standingRead.fault) {
captureIndeterminate = true;
deps.onError?.(new Error(`the capture opt-out record store is unreadable at prepare — this session's capture state is indeterminate, and every memory commit boundary (read-side adoption included) suppresses fail-closed until the store answers.`), { phase: "memory", sessionId });
}
if (input.captureLineageFault === true) {
const firstIndeterminate = !captureIndeterminate;
captureIndeterminate = true;
captureLineageIndeterminate = true;
if (firstIndeterminate) {
deps.onError?.(new Error(`this session's fork-lineage metadata is unreadable — whether it continues an opted-out source session cannot be established, so its capture state is indeterminate: every memory commit boundary (read-side adoption included) suppresses fail-closed; no opt-out record is minted from an unreadable state.`), { phase: "memory", sessionId });
}
}
const standing = standingRead.record;
let floored = captureFloored;
if (!floored && !captureDeclared && standing === undefined && input.captureFloorIndeterminate === true) {
const rows = new Map();
for (const row of input.captureAncestors ?? [])
rows.set(row.sessionId, row.controlDir);
if (input.parentSessionId !== undefined && !rows.has(input.parentSessionId))
rows.set(input.parentSessionId, input.parentCaptureQueryDir);
let anyFault = standingRead.fault;
let found = false;
for (const [ancestorId, ancestorDir] of rows) {
const samePlane = await eng.sessionCaptureOptOutOrFault(ancestorId);
if (samePlane.record !== undefined) {
found = true;
break;
}
if (samePlane.fault)
anyFault = true;
if (ancestorDir !== undefined && ancestorDir !== eng.controlPlaneRoot) {
try {
const crossPlane = await readAncestorCaptureOptOut(ancestorDir, ancestorId, capturePlanes, deps.memoryCaptureRecordStore);
if (crossPlane !== undefined) {
found = true;
break;
}
}
catch {
anyFault = true;
}
}
}
if (found)
floored = true;
else if (anyFault) {
if (!captureIndeterminate) {
captureIndeterminate = true;
deps.onError?.(new Error(`the spawning session's capture opt-out state was INDETERMINATE at spawn (its record store faulted) and the live re-query still cannot answer — this delegated session inherits the suppression: every memory commit boundary (read-side adoption included) suppresses fail-closed until the store answers; no opt-out record is minted from an unreadable state.`), { phase: "memory", sessionId });
}
}
}
let forkInherited = false;
if (!floored && !captureDeclared && standing === undefined && input.captureForkOrigin !== undefined) {
const src = await eng.sessionCaptureOptOutOrFault(input.captureForkOrigin);
if (src.record !== undefined)
forkInherited = true;
else if (src.fault && !captureIndeterminate) {
captureIndeterminate = true;
deps.onError?.(new Error(`this session is a FORK of session "${input.captureForkOrigin}" whose capture opt-out record store is unreadable — the fork's capture state is indeterminate (the copied transcript may be governed by a standing opt-out), so every memory commit boundary suppresses fail-closed until the store answers; no opt-out record is minted from an unreadable state.`), { phase: "memory", sessionId });
}
}
if (standing === undefined && !captureDeclared && !floored && !forkInherited)
return;
if (standing !== undefined && !captureDeclared && !floored && capturePosture !== "open") {
const verdict = adjudicateCaptureOptOut({ posture: capturePosture, entitlement: captureEntitlement, subject: "standing-record" });
if (!verdict.allowed)
throw captureOptOutDeniedError(verdict.detail);
}
if (standing === undefined) {
const outcome = await eng.markSessionCaptureOptOut(sessionId, captureDeclared ? `declared on TaskSpec.memory.capture` : forkInherited ? `inherited capture opt-out from the forked source session` : `inherited capture opt-out floor from the spawning session`);
if (outcome === "unpersisted") {
throw unpersistedOptOutRefusal(deps.onNotice, sessionId, "declaration", captureMarkUnpersistedReadingOf(eng.controlPlaneRoot));
}
if (outcome === "created")
deliverEngineNotice(deps.onNotice, memoryCaptureOptedOutNotice({ sessionId, origin: captureDeclared ? "declaration" : forkInherited ? "fork-origin" : "delegation-floor" }));
}
else if (!captureDeclared) {
deliverEngineNotice(deps.onNotice, memoryCaptureOptedOutNotice({ sessionId, origin: "standing-record" }));
}
captureOptedOut = true;
if (input.memoryCapturePolicyDeclared !== true && !undeclaredCapturePostureAnnounced) {
undeclaredCapturePostureAnnounced = true;
deps.onError?.(new Error(`a session memory-capture opt-out was honored under the DEFAULT capture posture (no RunnerDeps.memoryCapturePolicy configured) — ` +
`the switch is now in use; declare "open", "governed" or "capture-required" to make the deployment's stance explicit.`), { phase: "config", sessionId });
}
};
const retrievalBackend = (b, planeRestricted) => planeRestricted
? (b.restrictedAdoptionView?.({ audit: false }) ??
b.retrievalView?.() ??
b)
: (b.retrievalView?.() ?? b);
const planeScopes = (scopes, write) => [...new Set([...scopes, ...(write !== null ? [write] : [])])];
const mountedScopeRows = (dual
? [
...planeScopes(planes.project, planes.writePlane === "project" ? memorySpec.writeScope : null),
...planeScopes(planes.personal, planes.writePlane === "personal" ? memorySpec.writeScope : null),
]
: planeScopes(memorySpec.scopes, memorySpec.writeScope)).map((scope) => ({ scope, origin: originOf(scope) }));
const pollutedOpts = async (engine) => {
const rec = await engine.sessionPollution(sessionId);
return rec !== undefined ? { polluted: { reason: rec.reason, ...(rec.cause !== undefined ? { cause: rec.cause } : {}) } } : {};
};
let writeEngine;
let writeHandle;
let readOnlyEngine;
let readOnlyHandle;
let injectFn;
let harvestBoth;
let toolPlanes;
const admitNothingOptsNow = async () => {
if (input.memoryPersistenceDeclared === false) {
return { admitNothing: { reason: "harvest admitted nothing: memory persistence is declared unavailable for this session (memoryPersistenceCapable: false)" } };
}
if (captureLineageIndeterminate) {
return { admitNothing: { reason: `harvest admitted nothing: this session's fork-lineage metadata is unreadable — whether it continues an opted-out source cannot be established, so commits are suppressed fail-closed` } };
}
const own = captureOptedOut ? { record: { at: 0, reason: "in-run state" }, fault: false } : await writeEngine.sessionCaptureOptOutOrFault(sessionId);
if (own.record !== undefined) {
return { admitNothing: { reason: `harvest admitted nothing: this session declared memory capture opt-out (memory.capture: "off")` } };
}
if (own.fault) {
return { admitNothing: { reason: `harvest admitted nothing: the capture opt-out record store is unreadable — the opt-out state is indeterminate and commits are suppressed fail-closed` } };
}
const ancestors = new Map();
for (const row of input.captureAncestors ?? [])
ancestors.set(row.sessionId, row.controlDir);
if (input.parentSessionId !== undefined && !ancestors.has(input.parentSessionId))
ancestors.set(input.parentSessionId, input.parentCaptureQueryDir);
if (input.captureForkOrigin !== undefined && !ancestors.has(input.captureForkOrigin))
ancestors.set(input.captureForkOrigin, undefined);
for (const [ancestorId, ancestorDir] of ancestors) {
const samePlane = await writeEngine.sessionCaptureOptOutOrFault(ancestorId);
let crossPlane;
if (ancestorDir !== undefined && ancestorDir !== writeEngine.controlPlaneRoot) {
try {
crossPlane = await readAncestorCaptureOptOut(ancestorDir, ancestorId, capturePlanes, deps.memoryCaptureRecordStore);
}
catch {
return { admitNothing: { reason: `harvest admitted nothing: a spawning session's capture record store is unreadable — the floor state is indeterminate and commits are suppressed fail-closed` } };
}
}
if (samePlane.record !== undefined || crossPlane !== undefined) {
return { admitNothing: { reason: `harvest admitted nothing: a spawning session declared memory capture opt-out — the opt-out is a delegation floor no descendant loosens`, cause: "capture_optout_inherited" } };
}
if (samePlane.fault) {
return { admitNothing: { reason: `harvest admitted nothing: the capture opt-out record store is unreadable while a spawning session's floor is in question — suppressed fail-closed` } };
}
}
return {};
};
if (dual) {
const personalBackendChosen = memoryPlaneStore("personal", backend, engineRoot);
{
const projCtl = effectiveControlRootOf(memoryDir, { pinnedBy: backend, controlDir: projectControlDir });
const persCtl = effectiveControlRootOf(personalMemoryDir, { pinnedBy: personalBackendChosen, controlDir: personalControlDir });
const overlap = (a, b) => isContainedIn(a, b) || isContainedIn(b, a);
const refuse = (what, a, b) => {
const e = new Error(`memory dual-root configuration error: ${what} overlap (${canonicalize(a)} vs ${canonicalize(b)}) — the planes' data roots and control planes must all be disjoint.`);
e.code = "config.memory_dual_root_overlap";
throw refusalAbout("deps", e);
};
if (overlap(memoryDir, personalMemoryDir))
refuse("the project and personal memory roots", memoryDir, personalMemoryDir);
if (overlap(projCtl, persCtl))
refuse("the project and personal control planes", projCtl, persCtl);
for (const [ctlName, ctl] of [["project control plane", projCtl], ["personal control plane", persCtl]]) {
for (const [rootName, dataRoot] of [["project memory root", memoryDir], ["personal memory mount", personalMemoryDir]]) {
if (overlap(ctl, dataRoot))
refuse(`the ${ctlName} and the ${rootName}`, ctl, dataRoot);
}
}
}
const projectEngine = enterConfigDoor("deps", () => new MemoryEngine({
backend,
memoryDir,
controlDir: projectControlDir,
onIncident: onEngineIncident,
provenance: input.memoryProvenance,
...captureStoreOpt(memoryDir, backend, projectControlDir), ...incarnationOpt,
...(input.deps.memoryConsolidation !== undefined ? { consolidation: input.deps.memoryConsolidation } : {}),
}));
const personal = createPersonalEngine(personalBackendChosen);
const personalEngine = personal.engine;
const p = planes;
capturePlanes = [heldCapturePlane(projectEngine, backend), heldCapturePlane(personalEngine, personal.backend)];
await armCaptureOptOut(p.writePlane === "personal" ? personalEngine : projectEngine);
const writeIsPersonal = p.writePlane === "personal";
const mounts = [
{ engine: writeIsPersonal ? personalEngine : projectEngine, scopes: writeIsPersonal ? p.personal : p.project, write: p.writePlane === null ? null : memorySpec.writeScope },
{ engine: writeIsPersonal ? projectEngine : personalEngine, scopes: writeIsPersonal ? p.project : p.personal, write: null },
];
const mounted = [];
let shadowNames;
for (const m of mounts) {
const handle = await m.engine.materialize(m.scopes, m.write, {
adoptionRestricted: adoptionRestricted || captureOptedOut || captureIndeterminate,
sessionId,
...(m.write === null && shadowNames !== undefined && shadowNames.size > 0 ? { shadowNames } : {}),
});
openedLegs.push(() => m.engine.endSessionLeg(handle, sessionId));
mounted.push(handle);
materializedResidue.push(...planeScopes(m.scopes, m.write));
if (m.write !== null) {
try {
const withheld = new Set((await m.engine.readChallengeExclusions()).keys());
const committed = await m.engine.listCommittedHeaders([m.write]);
const superseded = deriveSupersededSet(committed, { excluded: (id) => withheld.has(id) });
shadowNames = shadowNamesOf(committed, m.write, { excluded: (id) => withheld.has(id) || superseded.has(id) });
}
catch {
shadowNames = undefined;
}
}
}
const projectHandle = writeIsPersonal ? mounted[1] : mounted[0];
const personalHandle = writeIsPersonal ? mounted[0] : mounted[1];
memoryMarkedEntriesServed = projectHandle.markedEntriesPresent === true || personalHandle.markedEntriesPresent === true;
writeEngine = writeIsPersonal ? personalEngine : projectEngine;
writeHandle = writeIsPersonal ? personalHandle : projectHandle;
readOnlyEngine = writeIsPersonal ? projectEngine : personalEngine;
readOnlyHandle = writeIsPersonal ? projectHandle : personalHandle;
injectFn = async (frozen) => {
const project = await projectEngine.inject(projectHandle, { writeToolMounted: writeChannelOpen, reminderMark: input.reminderMark, ...(frozen?.project !== undefined ? { frozenIndex: frozen.project } : {}) });
const personal = await personalEngine.inject(personalHandle, { writeToolMounted: writeChannelOpen, reminderMark: input.reminderMark, ...(frozen?.personal !== undefined ? { frozenIndex: frozen.personal } : {}) });
return { injection: mergeInjections(project, personal), served: { project: project.indexText ?? "", personal: personal.indexText ?? "" } };
};
memoryTailPlanes = [["project", projectHandle], ["personal", personalHandle]];
toolPlanes = [
{
backend: retrievalBackend(backend, adoptionRestricted || captureOptedOut || captureIndeterminate || p.writePlane !== "project"),
scopes: planeScopes(p.project, p.writePlane === "project" ? memorySpec.writeScope : null),
recordRetrieved: (ids) => projectEngine.recordRetrieved(ids),
challengeExclusions: () => projectEngine.readChallengeExclusions(),
enginePlaneProvenance: projectEngine.provenanceMode,
committedHeaders: () => projectEngine.listCommittedHeaders(planeScopes(p.project, p.writePlane === "project" ? memorySpec.writeScope : null)),
},
{
backend: retrievalBackend(personal.backend, adoptionRestricted || captureOptedOut || captureIndeterminate || p.writePlane !== "personal"),
scopes: planeScopes(p.personal, p.writePlane === "personal" ? memorySpec.writeScope : null),
recordRetrieved: (ids) => personalEngine.recordRetrieved(ids),
challengeExclusions: () => personalEngine.readChallengeExclusions(),
enginePlaneProvenance: personalEngine.provenanceMode,
committedHeaders: () => personalEngine.listCommittedHeaders(planeScopes(p.personal, p.writePlane === "personal" ? memorySpec.writeScope : null)),
},
];
harvestBoth = async (phase) => {
const writeFirst = writeIsPersonal ? [personalEngine, personalHandle] : [projectEngine, projectHandle];
const readOther = writeIsPersonal ? [projectEngine, projectHandle] : [personalEngine, personalHandle];
const writeReport = await writeFirst[0].harvest(writeFirst[1], { ...(await pollutedOpts(writeFirst[0])), sessionId, ...(await admitNothingOptsNow()), phase });
let readReport;
let readFailure;
try {
readReport = await readOther[0].harvest(readOther[1]);
}
catch (err) {
readFailure = thrownText(err);
}
const merged = readReport !== undefined ? mergeHarvestReports(writeReport, readReport) : writeReport;
if (readFailure !== undefined)
merged.warnings.push(`read-plane harvest failed (write-plane yield committed): ${readFailure}`);
return merged;
};
}
else if (personalOnly) {
const personal = createPersonalEngine(memoryPlaneStore("personal", backend, engineRoot));
const personalEngine = personal.engine;
capturePlanes = [heldCapturePlane(personalEngine, personal.backend)];
await armCaptureOptOut(personalEngine);
const handle = await personalEngine.materialize(memorySpec.scopes, memorySpec.writeScope, { adoptionRestricted: adoptionRestricted || captureOptedOut || captureIndeterminate, sessionId });
openedLegs.push(() => personalEngine.endSessionLeg(handle, sessionId));
materializedResidue.push(...planeScopes(memorySpec.scopes, memorySpec.writeScope));
memoryMarkedEntriesServed = handle.markedEntriesPresent === true;
writeEngine = personalEngine;
writeHandle = handle;
injectFn = async (frozen) => {
const injection = await personalEngine.inject(handle, { writeToolMounted: writeChannelOpen, reminderMark: input.reminderMark, ...(frozen?.personal !== undefined ? { frozenIndex: frozen.personal } : {}) });
return { injection, served: { personal: injection.indexText ?? "" } };
};
memoryTailPlanes = [["personal", handle]];
harvestBoth = async (phase) => personalEngine.harvest(handle, { ...(await pollutedOpts(personalEngine)), sessionId, ...(await admitNothingOptsNow()), phase });
toolPlanes = [
{
backend: retrievalBackend(personal.backend, adoptionRestricted || captureOptedOut || captureIndeterminate || memorySpec.writeScope === null),
scopes: planeScopes(memorySpec.scopes, memorySpec.writeScope),
recordRetrieved: (ids) => personalEngine.recordRetrieved(ids),
challengeExclusions: () => personalEngine.readChallengeExclusions(),
enginePlaneProvenance: personalEngine.provenanceMode,
committedHeaders: () => personalEngine.listCommittedHeaders(planeScopes(memorySpec.scopes, memorySpec.writeScope)),
},
];
}
else {
const engine = enterConfigDoor("deps", () => new MemoryEngine({
backend,
memoryDir,
controlDir: projectControlDir,
onIncident: onEngineIncident,
provenance: input.memoryProvenance,
...captureStoreOpt(memoryDir, backend, projectControlDir), ...incarnationOpt,
...(input.deps.memoryConsolidation !== undefined ? { consolidation: input.deps.memoryConsolidation } : {}),
}));
capturePlanes = [heldCapturePlane(engine, backend)];
await armCaptureOptOut(engine);
const handle = await engine.materialize(memorySpec.scopes, memorySpec.writeScope, { adoptionRestricted: adoptionRestricted || captureOptedOut || captureIndeterminate, sessionId });
openedLegs.push(() => engine.endSessionLeg(handle, sessionId));
materializedResidue.push(...planeScopes(memorySpec.scopes, memorySpec.writeScope));
memoryMarkedEntriesServed = handle.markedEntriesPresent === true;
writeEngine = engine;
writeHandle = handle;
injectFn = async (frozen) => {
const injection = await engine.inject(handle, { writeToolMounted: writeChannelOpen, reminderMark: input.reminderMark, ...(frozen?.project !== undefined ? { frozenIndex: frozen.project } : {}) });
return { injection, served: { project: injection.indexText ?? "" } };
};
memoryTailPlanes = [["project", handle]];
harvestBoth = async (phase) => engine.harvest(handle, { ...(await pollutedOpts(engine)), sessionId, ...(await admitNothingOptsNow()), phase });
toolPlanes = [
{
backend: retrievalBackend(backend, adoptionRestricted || captureOptedOut || captureIndeterminate || memorySpec.writeScope === null),
scopes: planeScopes(memorySpec.scopes, memorySpec.writeScope),
recordRetrieved: (ids) => engine.recordRetrieved(ids),
challengeExclusions: () => engine.readChallengeExclusions(),
enginePlaneProvenance: engine.provenanceMode,
committedHeaders: () => engine.listCommittedHeaders(planeScopes(memorySpec.scopes, memorySpec.writeScope)),
},
];
}
for (const [scope, count] of [...(writeHandle.shadowedByScope ?? []), ...(readOnlyHandle?.shadowedByScope ?? [])]) {
if (count <= 0 || scope === memorySpec.writeScope)
continue;
const row = mountedScopeRows.find((r) => r.scope === scope);
if (row !== undefined)
row.shadowed = (row.shadowed ?? 0) + count;
}
const foreignUnderRoot = [];
if (input.writeToolsMounted && writeHandle.writeScope !== null && input.advertisedWritableDirs !== undefined) {
const controlPlane = canonicalize(writeEngine.controlPlaneRoot);
if (isContainedIn(writableRootOf(writeHandle), controlPlane))
foreignUnderRoot.push(`the engine's control plane ${controlPlane}`);
}
if (foreignUnderRoot.length > 0) {
deps.onError?.(new Error(`memory advertised writable directory refused: the write scope's root ${writableRootOf(writeHandle)} contains what is not the model's to touch (${foreignUnderRoot.join("; ")}) — the file tools' root fence is directory-granular, so admitting it would expose those files; memory writes through the file tools stay closed this session and the write instruction is not taught.`), { phase: "config", sessionId });
}
writeChannelOpen =
input.writeToolsMounted &&
writeHandle.writeScope !== null &&
foreignUnderRoot.length === 0 &&
(input.advertisedWritableDirs === undefined || (await input.advertisedWritableDirs.admit({ path: writableRootOf(writeHandle), advertiser: "memory", expectCanonical: writableRootOf(writeHandle), ...(input.memoryPersistenceDeclared === false ? { writesRefusedByOwnGate: true } : {}) })));
memoryWriteGate = async (w) => {
if (readOnlyEngine !== undefined && readOnlyHandle !== undefined) {
const ro = readOnlyEngine.gateWrite(readOnlyHandle, w.key, w.content);
if (!ro.ok)
return ro;
}
if (input.memoryPersistenceDeclared === false) {
const root = writeHandle.writableRoot;
if (root !== null && (w.key === root || w.key.startsWith(`${root}${sep}`))) {
return {
ok: false,
code: "read_only_layering",
reason: `memory persistence is declared unavailable for this session (memoryPersistenceCapable: false) — writes into the memory store are refused. Nothing was written.`,
muted: false,
};
}
}
{
const root = writeHandle.writableRoot;
if (root !== null && (w.key === root || w.key.startsWith(`${root}${sep}`))) {
const state = captureOptedOut ? { record: { at: 0, reason: "in-run state" }, fault: false } : await writeEngine.sessionCaptureOptOutOrFault(sessionId);
if (state.record !== undefined || state.fault) {
return {
ok: false,
code: "read_only_layering",
reason: state.record !== undefined
? `memory capture is off for this session at the user's request (memory.capture: "off") — writes into the memory store are refused. Nothing was written.`
: `the capture opt-out record store is unreadable, so this session's capture state is indeterminate — writes into the memory store are refused fail-closed. Nothing was written.`,
muted: false,
};
}
}
}
return writeEngine.gateWrite(writeHandle, w.key, w.content);
};
let pollutionAnnounced = false;
let pollutionDurable = false;
const announceHarvestContainment = async (report) => {
const { count, moved, escalated } = pollutionContainmentCounts(report);
const indexOnly = input.memoryProvenance !== "off" && count === 0 && report.containment?.indexRolledBack === true;
if (count > 0 || indexOnly) {
let reason;
try {
reason = (await writeEngine.sessionPollution(sessionId))?.reason;
}
catch {
}
deliverEngineNotice(deps.onNotice, memoryHarvestQuarantinedNotice({ count, moved, escalated, ...(report.reportId !== undefined ? { reportId: report.reportId } : {}), ...(reason !== undefined ? { reason } : {}), sessionId, provenance: input.memoryProvenance, ...(indexOnly ? { indexRolledBack: true } : {}) }));
}
const refused = memoryHarvestRefusedNotice(report, sessionId);
if (refused !== undefined)
deliverEngineNotice(deps.onNotice, refused);
const conflicted = memoryHarvestConflictNotice(report, sessionId);
if (conflicted !== undefined)
deliverEngineNotice(deps.onNotice, conflicted);
if (report.restoreWithheld !== undefined && report.restoreWithheld.length > 0) {
deliverEngineNotice(deps.onNotice, memoryRestoreWithheldNotice({ paths: report.restoreWithheld, sessionId }));
}
for (const notice of memoryHoldNotices(report, sessionId))
deliverEngineNotice(deps.onNotice, notice);
const consolidationNotice = memoryConsolidationRecommendedNotice(report, sessionId);
if (consolidationNotice !== undefined)
deliverEngineNotice(deps.onNotice, consolidationNotice);
};
const harvestSafe = async (phase = "terminal") => {
try {
const report = await harvestBoth(phase);
if (!report.ok && report.incident) {
const named = report.reportId !== undefined ? `${report.incident.kind}, report ${report.reportId}` : report.incident.kind;
deps.onError?.(new Error(`memory harvest refused (${named}): ${report.incident.detail}`), { phase: "memory", sessionId });
}
await announceHarvestContainment(report);
try {
deps.onMemoryHarvestReport?.(report, { sessionId, phase });
}
catch {
}
return report;
}
catch (err) {
try {
deps.onError?.(asThrownError(err), { phase: "memory", sessionId });
}
catch {
}
return undefined;
}
};
const resolveCaptureEntitlementFresh = async () => {
if (deps.runtimeCapsResolver === undefined)
return { value: undefined, faulted: false };
try {
const caps = (await deps.runtimeCapsResolver(spec.principal)) ?? undefined;
const v = caps?.allowMemoryOptOut;
if (v !== undefined && typeof v !== "boolean")
return { value: undefined, faulted: true };
return { value: v, faulted: false };
}
catch {
return { value: undefined, faulted: true };
}
};
memoryEngineSession = {
engine: writeEngine,
handle: writeHandle,
scopeContract: memorySpec.scopeContract,
inject: injectFn,
harvest: harvestSafe, createEntry: (draft) => createMemoryEntry({ home: writeHandle.writableRoot, domain: writeHandle.memoryDir, gate: async (w) => (memoryWriteGate !== undefined ? memoryWriteGate(w) : { ok: false, code: "read_only_layering", reason: "this session's memory write gate is not installed — nothing is written" }), boundAtMount: (p) => writeHandle.baseIds.has(p), draft }),
release: async () => {
for (const end of openedLegs)
await end();
},
captureOptOut: {
optedOut: () => {
if (captureOptedOut)
return true;
const r = writeEngine.sessionCaptureOptOutOrFault(sessionId);
const rAsync = adoptHostPromise(r);
return rAsync !== undefined ? rAsync.then((s) => s.record !== undefined) : r.record !== undefined;
},
indeterminate: () => {
if (captureOptedOut)
return false;
const r = writeEngine.sessionCaptureOptOutOrFault(sessionId);
const rAsync = adoptHostPromise(r), rNow = r;
return rAsync !== undefined
? rAsync.then((s) => s.record === undefined && (captureIndeterminate || s.fault))
: rNow.record === undefined && (captureIndeterminate || rNow.fault);
},
flip: async (reason) => {
const entitlement = await resolveCaptureEntitlementFresh();
const verdict = adjudicateCaptureOptOut({ posture: capturePosture, entitlement, subject: "declaration" });
if (!verdict.allowed)
throw captureOptOutDeniedError(verdict.detail);
if (verdict.faultDisclosure !== undefined)
deps.onError?.(new Error(verdict.faultDisclosure), { phase: "config", sessionId });
if (input.captureCarrierUnsupported === true) {
const e = new Error(`memory capture opt-out cannot be honored on this deployment shape: the execution environment's paths are not the host's (remote/per-run) ` +
`and no RunnerDeps.memoryCaptureRecordStore is supplied — the record would not survive to a resume replica. Nothing was recorded.`);
e.code = "config.memory_capture_unsupported";
throw refusalAbout("taskConfig", e);
}
const trimmed = reason?.trim();
const outcome = await writeEngine.markSessionCaptureOptOut(sessionId, trimmed !== undefined && trimmed !== "" ? `host flip verb: ${trimmed.slice(0, 200)}` : "host flip verb");
if (outcome === "unpersisted") {
throw unpersistedOptOutRefusal(deps.onNotice, sessionId, "flip-verb", captureMarkUnpersistedReadingOf(writeEngine.controlPlaneRoot));
}
captureOptedOut = true;
if (outcome === "created") {
deliverEngineNotice(deps.onNotice, memoryCaptureOptedOutNotice({ sessionId, origin: "flip-verb" }));
if (input.memoryCapturePolicyDeclared !== true && !undeclaredCapturePostureAnnounced) {
undeclaredCapturePostureAnnounced = true;
deps.onError?.(new Error(`a session memory-capture opt-out was honored under the DEFAULT capture posture (no RunnerDeps.memoryCapturePolicy configured) — ` +
`the switch is now in use; declare "open", "governed" or "capture-required" to make the deployment's stance explicit.`), { phase: "config", sessionId });
}
}
const sweep = await writeEngine.sweepSessionCaptureResidue(writeHandle);
if (sweep.withheld.length > 0) {
deliverEngineNotice(deps.onNotice, memoryRestoreWithheldNotice({ paths: sweep.withheld, sessionId }));
}
if (sweep.failures.length > 0) {
const named = sweep.failures
.slice(0, 5)
.map((f) => `${f.path} (${f.detail})`)
.join("; ");
const e = new Error(`memory capture opt-out is ON (the one-way record stands) but the boundary sweep could not contain ` +
`${sweep.failures.length} path(s) on the writable memory root — the named residue stays on the authoritative ` +
`plane until a retry or host action clears it: ${named}${sweep.failures.length > 5 ? "; …" : ""}`);
e.code = "memory.capture_optout_sweep_failed";
throw e;
}
return { outcome };
},
},
pollution: {
polluted: () => writeEngine.sessionPollution(sessionId),
markPolluted: (reason, cause) => {
const outcome = writeEngine.markSessionPolluted(sessionId, reason, cause).then((o) => {
if (o !== "unpersisted")
pollutionDurable = true;
if (o === "existed" || (o === "unpersisted" && pollutionAnnounced))
return o;
pollutionAnnounced = true;
deliverEngineNotice(deps.onNotice, memorySessionPollutedNotice({ reason, sessionId, provenance: input.memoryProvenance }));
return o;
});
if (!pollutionDurable)
return outcome;
void outcome.catch(() => undefined);
return Promise.resolve("existed");
},
},
contentSafety: {
trustedTools: new Set(memorySpec.trustedTools ?? []),
execIsExternalContent: memorySpec.execIsExternalContent === true,
},
...(input.memoryProvenance !== "off"
? { settlement: { governance: writeEngine.governance, sessionId, provenance: "carry" } }
: {}),
...(input.memoryProvenance !== "off"
? {
recallTaint: {
judgeDeliveredPath: async (absPath) => {
try {
if (!isAbsolute(absPath))
return "clean";
const planes = [{ engine: writeEngine, handle: writeHandle }, ...(readOnlyEngine !== undefined && readOnlyHandle !== undefined ? [{ engine: readOnlyEngine, handle: readOnlyHandle }] : [])];
for (const plane of planes) {
if (!isContainedIn(plane.handle.memoryDir, absPath))
continue;
const id = await plane.engine.entryIdAtPlanePath(plane.handle, absPath);
if (id !== undefined)
return await plane.engine.entryExposureVerdict(id);
}
return "clean";
}
catch {
return "clean";
}
},
},
}
: {}),
};
effectiveMemoryScopes = {
state: "mounted",
contract: memorySpec.scopeContract === "v2" ? "v2" : "legacy",
scopes: mountedScopeRows,
writeScope: memorySpec.writeScope,
...(memorySpec.projectKey !== undefined ? { projectKey: memorySpec.projectKey } : {}),
};
if (input.memoryProvenance !== "off") {
const session = memoryEngineSession;
const markDerived = async (ids) => {
const shown = ids.slice(0, 3).join(", ") + (ids.length > 3 ? ", …" : "");
if ((await session.pollution.markPolluted(`this session read the content of external-origin memory entr${ids.length === 1 ? "y" : "ies"} ${shown}`, "derived")) === "unpersisted") {
throw new Error("the external-origin take-up could not be recorded durably for this session");
}
};
for (const plane of toolPlanes)
plane.onTaintedDelivery = markDerived;
}
if (input.memorySearchToolsPlanned)
memoryTools = createMemoryEngineTools({ planes: toolPlanes, sessionPollution: () => writeEngine.sessionPollution(sessionId), provenance: input.memoryProvenance, writeScope: memorySpec.writeScope });
}
catch (err) {
if (memoryEngineSession === undefined)
for (const end of openedLegs)
await end();
if (isDeliberateMemoryRefusal(err))
throw err;
if ((captureDeclared || captureFloored) && !captureOptedOut)
throw unpersistedOptOutRefusal(deps.onNotice, sessionId, "declaration", memoryMountFailedReadingOf(err), err);
deps.onError?.(asThrownError(err), { phase: "memory", sessionId });
if (effectiveMemoryScopes === undefined) {
effectiveMemoryScopes = {
state: "memoryless",
reason: "mount-failed",
contract: memorySpec.scopeContract === "v2" ? "v2" : "legacy",
scopes: [],
writeScope: null,
...(materializedResidue.length > 0 ? { materializedResidue: [...new Set(materializedResidue)] } : {}),
};
deliverEngineNotice(deps.onNotice, memoryMountFailedNotice({ sessionId, scopes: [...new Set([...memorySpec.scopes, ...(memorySpec.writeScope !== null ? [memorySpec.writeScope] : [])])], ...memoryMountFailedReadingOf(err) }));
}
}
}
if (memorySpec && memorySpec.enabled && !useMemoryEngine) {
const detail = "TaskSpec.memory is enabled but RunnerDeps.memoryBackend is not configured; memory is inactive for this task — wire a memory backend as RunnerDeps.memoryBackend (it replaces the removed RunnerDeps.memoryStore) for memory to be mounted, or leave TaskSpec.memory off.";
deps.onError?.(new Error(detail), { phase: "config", sessionId });
}
const composeInjection = async (facts) => {
let memoryBlock;
let memoryStoreAbsent = false;
let seedFiles;
let recallDisciplineSegment;
let noticesFrame;
let memoryTailOwed;
if (memoryEngineSession) {
const tailKey = memoryTailPlanes !== undefined ? memoryTailKeyOf(memoryTailPlanes) : undefined;
const anchored = tailKey !== undefined && facts.anchor?.memory?.mount === tailKey ? facts.anchor.memory : undefined;
const frozen = anchored !== undefined ? indexCopyOf(anchored.mount, anchored.digest) : undefined;
const rebuilt = memoryTailPlanes !== undefined ? Object.fromEntries(memoryTailPlanes.map(([plane, h]) => [plane, h.indexText])) : undefined;
const { injection, served } = await memoryEngineSession.inject(frozen?.planes ?? rebuilt);
const markedServed = frozen?.marked ?? memoryMarkedEntriesServed;
if (memoryTailPlanes !== undefined && tailKey === undefined)
deps.onError?.(new Error(memoryTailUnfrozenSentence(memoryTailPlanes)), { phase: "memory", sessionId });
if (frozen === undefined && facts.anchor !== undefined && tailKey !== undefined) {
const chars = Object.values(served).reduce((n, text) => n + (text?.length ?? 0), 0);
if (chars <= MEMORY_TAIL_MAX_CHARS) {
const digest = keepIndexCopy(tailKey, { planes: served, marked: markedServed }, memoryTailPlanes.map(([, h]) => h));
if (anchored?.digest !== digest)
memoryTailOwed = { mount: tailKey, digest };
}
else
deps.onError?.(new Error(`the memory index is ${chars} characters, over the ${MEMORY_TAIL_MAX_CHARS} a conversation segment freezes; it is read live on every leg, so a write to it moves the prompt prefix on the next leg`), { phase: "memory", sessionId });
}
let blockBody = injection.block;
if (captureOptedOut) {
blockBody = [MEMORY_CAPTURE_OPTOUT_NOTICE, injection.index].filter((s) => Boolean(s && s.trim())).join("\n\n");
}
else if (captureIndeterminate && facts.rosterCanPersist) {
blockBody = [memoryUnavailableNotice({ what: "capture-record-unreadable", notesReadable: true }), injection.index].filter((s) => Boolean(s && s.trim())).join("\n\n");
}
else if (!facts.rosterCanPersist && injection.instruction === "" && injection.readOnlyNotice === undefined) {
blockBody = blockBody.trim() ? `${MEMORY_READONLY_NOTICE}\n\n${blockBody}` : MEMORY_READONLY_NOTICE;
}
else if (!facts.rosterCanPersist && injection.instruction !== "") {
blockBody = [MEMORY_READONLY_NOTICE, injection.index].filter((s) => Boolean(s && s.trim())).join("\n\n");
}
else if (input.memoryPersistenceDeclared === true && injection.readOnlyNotice !== undefined) {
blockBody = [injection.index].filter((s) => Boolean(s && s.trim())).join("\n\n");
}
if ((injection.announceBlock?.trim() ?? "") !== "") {
const coda = !facts.rosterCanPersist ? MEMORY_ANNOUNCEMENT_READONLY_CODA : captureOptedOut ? MEMORY_ANNOUNCEMENT_CAPTURE_OPTOUT_CODA : undefined;
noticesFrame = coda === undefined ? injection.announceBlock : `${injection.announceBlock}\n${mintSystemReminder(coda, input.reminderMark)}`;
}
if (blockBody.trim())
memoryBlock = blockBody;
if (memoryTools !== undefined) {
recallDisciplineSegment = memoryRecallDisciplineSegment(input.memoryProvenance, { markedEntriesServed: markedServed });
memoryBlock = memoryBlock !== undefined ? `${memoryBlock}\n\n${recallDisciplineSegment}` : recallDisciplineSegment;
}
if (memoryEngineSession.handle.writeScope !== null && writeChannelOpen && facts.rosterCanPersist && !captureOptedOut && !captureIndeterminate) {
memoryBlock = memoryBlock !== undefined ? `${memoryBlock}\n\n${MEMORY_PREFERENCE_DISCIPLINE}` : MEMORY_PREFERENCE_DISCIPLINE;
}
if (memoryBlock !== undefined && injection.indexSeed !== undefined && facts.rosterCanPersist && !captureOptedOut && !captureIndeterminate)
seedFiles = [injection.indexSeed];
const accountRides = injection.index !== undefined || (injection.instruction !== "" && blockBody === injection.block);
if (memoryBlock !== undefined && injection.indexUnseeded !== undefined && accountRides && input.memoryPathsReachable)
seedFiles = [injection.indexUnseeded];
}
else if (!facts.rosterCanPersist && !facts.isSubagent) {
if (effectiveMemoryScopes?.reason === "mount-failed")
memoryBlock = memoryUnavailableNotice({ what: "mount-failed", notesReadable: false });
else
memoryStoreAbsent = true;
}
return {
memoryBlock,
...(memoryStoreAbsent ? { memoryStoreAbsent: true } : {}),
...(recallDisciplineSegment !== undefined ? { recallDisciplineSegment } : {}),
...(seedFiles !== undefined ? { seedFiles } : {}),
...(noticesFrame !== undefined ? { noticesFrame } : {}),
...(memoryTailOwed !== undefined ? { memoryTailOwed } : {}),
};
};
if (effectiveMemoryScopes === undefined) {
effectiveMemoryScopes = memorySpec
? memorySpec.enabled
? { state: "memoryless", reason: "no-backend", contract: memorySpec.scopeContract === "v2" ? "v2" : "legacy", scopes: [], writeScope: null }
: { state: "none", reason: "disabled", scopes: [], writeScope: null }
: { state: "none", reason: "no-spec", scopes: [], writeScope: null };
}
return {
memoryEngineSession,
admittedOrgScopes,
ownOrgVerdict,
effectiveMemoryScopes,
...(memoryTools !== undefined ? { memoryTools } : {}),
...(memoryWriteGate !== undefined ? { memoryWriteGate } : {}),
composeInjection,
};
}