@sema-agent/core
Version:
Stateless, task-oriented AI agent core
168 lines (167 loc) • 14.3 kB
JavaScript
import { resolveTrackKey } from "../file-history-store.js";
import { planFileHistoryRestore, restoreMovedOf, restoreOptionsAt, witnessEnvOf, withRewindFiles } from "../file-history-store.js";
import { isGovernanceRetryClass } from "../governance-codes.js";
export async function settleFileHistoryRestore(input) {
const { store, sessionId, scope, target, env, root } = input;
const plan = await planFileHistoryRestore(store, { scope, entryId: target, env, root, ...(input.signal !== undefined ? { signal: input.signal } : {}), ...(input.options !== undefined ? { options: input.options } : {}), ...(input.forkedSession === true ? { forkedSession: true } : {}) });
refuseUnheldPlan(plan, target, sessionId, input.before ? "before" : "restore");
if (input.wholeOrNothing) {
const planned = plan.restore;
refuseFailedPlan(planned, target, sessionId, input.before ? "before" : "restore");
if (planned.outcome !== "complete") {
throw restoreFailedError({ ...planned, filesChanged: [], identicalSkipped: [] }, `rewind-files: restore to entry "${target}" was refused before any file moved — the restore would be PARTIAL. Nothing was written or deleted; the plan: ${fileHistoryRestoreLedgerLine(planned, true)}. Repeating the same rewind plans the same; a rewind that restores the rest and answers this ledger is Runner.rewindFiles, and a run spec that accepts a partial restore (acceptPartialRestore) does the same where its host offers that member.`, RUN_STOPPED_RESTORE);
}
}
const witness = witnessEnvOf(env, plan.holds, plan.states, input.forkedSession === true ? root : undefined);
let answered;
try {
answered = await store.restore(scope, target, witness.env, root, input.signal, restoreOptionsAt(input.options, root));
}
finally {
if (input.outcome !== undefined)
input.outcome.moved = restoreMovedOf(witness);
}
const restored = withRewindFiles(answered, witness, root);
input.readStates?.noteRestored(sessionId, restoredAbsPathsOf(restored, root));
if (restored.outcome !== "failed")
return restored;
if (restored.error?.code === "not_found") {
throw noBoundaryFor(target, sessionId, input.before ? "before" : "restore");
}
throw restoreFailedError(restored, `rewind-files restore failed (${restored.error?.code ?? "restore_failed"}): ${restored.error?.message ?? "unknown"} — ledger: ${fileHistoryRestoreLedgerLine(restored)}`);
}
export const RUN_STOPPED_RESTORE = Object.freeze({ permanence: "terminal" });
export function restoreFailedError(restored, message, judged) {
const permanence = isGovernanceRetryClass(restored.error?.permanence) ? restored.error.permanence : judged?.permanence;
const detail = {
...(restored.error !== undefined ? { code: restored.error.code } : {}),
...(permanence !== undefined ? { permanence } : {}),
filesChangedCount: restored.filesChanged.length,
refusedCount: restored.refused.length,
failedCount: restored.failed.length,
...(restored.leftAsIs !== undefined && restored.leftAsIs.length > 0 ? { leftAsIsCount: restored.leftAsIs.length } : {}),
refused: restored.refused.map((f) => ({ path: f.path, reason: f.reason, class: f.class, ...(f.action !== undefined ? { action: f.action } : {}), ...(f.recordedUnder !== undefined ? { recordedUnder: f.recordedUnder } : {}) })),
failed: restored.failed.map((f) => ({ path: f.path, reason: f.reason })),
...(restored.files !== undefined ? { files: restored.files.map((f) => ({ ...f, ...(f.refused !== undefined ? { refused: { ...f.refused } } : {}), ...(f.failed !== undefined ? { failed: { ...f.failed } } : {}) })) } : {}),
...(restored.leftAsIs !== undefined && restored.leftAsIs.length > 0 ? { leftAsIs: restored.leftAsIs.map((f) => ({ ...f })) } : {}),
};
const e = new Error(message);
e.code = "rewind.restore_failed";
e.detail = detail;
return e;
}
export function refuseFailedPlan(planned, target, sessionId, ask) {
if (planned.outcome !== "failed")
return;
if (planned.error?.code === "not_found")
throw noBoundaryFor(target, sessionId, ask);
throw restoreFailedError({ ...planned, filesChanged: [], identicalSkipped: [] }, `rewind-files: ${ask === "preview" ? "the preview of the restore" : "the restore"} to entry "${target}" failed as a whole before any file moved (${planned.error?.code ?? "restore_failed"}: ${planned.error?.message ?? "unknown"}). Nothing was written or deleted; the plan: ${fileHistoryRestoreLedgerLine(planned, true)}.`);
}
export function refuseUnheldPlan(plan, target, sessionId, ask) {
const keys = plan.unheld;
const what = ask === "preview" ? `nothing was previewed for entry "${target}"` : `this rewind to entry "${target}" was not done at all: nothing was written or deleted`;
if (keys !== undefined) {
throw restoreFailedError({ ...plan.restore, filesChanged: [], identicalSkipped: [] }, `rewind-files: session "${sessionId}" has ${keys.length} file(s) an earlier version recorded through a link (${keys.join(", ")}), which this engine no longer writes through a link under any key; this deployment's file-history store did not hand the restore of its files to the engine's shared restore step (applyFileRestoreViaEnv, called on the env the store is handed), so which file each of its writes would land on cannot be read, and none of them can be kept off those files — ${what}. Repeating it answers the same until the store restores through that step; listFrozenFileHistoryEntries lists these files.`, RUN_STOPPED_RESTORE);
}
if (plan.unplacedForFork) {
throw restoreFailedError({ ...plan.restore, filesChanged: [], identicalSkipped: [] }, `rewind-files: session "${sessionId}" was forked from another, and a fork's rewind leaves every file outside its root as it is; this deployment's file-history store did not hand the restore of its files to the engine's shared restore step (applyFileRestoreViaEnv, called on the env the store is handed), so which file each of its writes would land on cannot be read, and none of them can be kept inside its root — ${what}. Repeating it answers the same until the store restores through that step.`, RUN_STOPPED_RESTORE);
}
}
function noBoundaryFor(target, sessionId, ask) {
return ask === "before" ? beforeWithoutBoundaryRefusal(target, sessionId) : noBoundaryRefusal(target, sessionId, ask === "preview");
}
export async function refuseTargetOutsideOwnLog(session, sessionId, target, ask) {
if (!(await entryInOwnLog(session, target)))
throw noBoundaryFor(target, sessionId, ask);
}
export async function entryInOwnLog(session, target) {
return Boolean(await session.getEntry(target));
}
export function refuseRestoreOnForkWithOwnTree(forkWithOwnTree, sessionId, target, ask) {
if (forkWithOwnTree)
throw noBoundaryFor(target, sessionId, ask);
}
export function fileHistoryRestoreLedgerLine(r, planned = false) {
const done = planned ? { write: "would write", delete: "would delete" } : { write: "written", delete: "deleted" };
const moved = r.files?.filter((f) => f.refused === undefined).map((f) => `${f.action === "delete" ? done.delete : done.write} ${f.path}`) ?? r.filesChanged.map((k) => `${planned ? "would change" : "changed"} ${k}`);
const left = r.leftAsIs ?? [];
return `${planned ? "would apply" : "applied"} ${r.filesChanged.length}, identical ${r.identicalSkipped.length}, refused ${r.refused.length}${r.refused.length > 0 ? ` (${r.refused.map((f) => `${f.path}: ${f.reason}`).join("; ")})` : ""}, failed ${r.failed.length}${r.failed.length > 0 ? ` (${r.failed.map((f) => `${f.path}: ${f.reason}`).join("; ")})` : ""}${left.length > 0 ? `, left as they are ${left.length} (${left.map((f) => `${f.path}: ${LEFT_AS_IS_WORDS[f.class].ledger}`).join("; ")})` : ""}${moved.length > 0 ? `; ${moved.join("; ")}` : ""}`;
}
const LEFT_AS_IS_WORDS = {
frozen_history: {
ledger: "history frozen",
why: "a version of it was recorded through a link on its path, so its history is frozen (no boundary reads it, no rewind writes or deletes it)",
beforehand: "listFrozenFileHistoryEntries lists a session's frozen files before a rewind",
},
recorded_outside_root: {
ledger: "recorded outside this root",
why: "this file lies in a directory outside the root this rewind works in (either its version was recorded under another root, or this session was forked from another — a forked session's rewind leaves every file outside its root untouched), so this rewind writes or deletes it neither there nor here; for an unforked session, a rewind handed the root it was recorded under restores it, and for a forked session, rewind in the source session or restore it by hand",
beforehand: "a preview (Runner.rewindFiles with dryRun) lists such files before a rewind",
},
};
function leftFileNamed(f) {
return `${f.path} (in ${f.place})`;
}
export function restoreLeftAsIsNote(restored, target) {
const left = restored.leftAsIs ?? [];
if (left.length === 0)
return undefined;
const classes = [...new Set(left.map((f) => f.class))];
const byClass = classes.map((c) => `${left.filter((f) => f.class === c).map(leftFileNamed).join(", ")} — ${LEFT_AS_IS_WORDS[c].why}; ${LEFT_AS_IS_WORDS[c].beforehand}`);
const changed = restored.filesChanged.length;
const same = restored.identicalSkipped.length;
const others = `${changed === 0 ? "restored no other file" : `restored ${changed} other file(s)`}${same > 0 ? ` (${same} more already as recorded)` : ""}`;
return {
code: "restore_left_as_is",
message: `file restore to entry "${target}" left ${left.length} file(s) as they are${restored.outcome === "complete" ? ` and ${others}` : ""}: ${byClass.join(". ")}.`,
leftAsIs: left.map((f) => ({ ...f })),
};
}
export function restoreOutsideRootNote(restored, target) {
const moved = restored.files.filter((f) => f.outsideRoot && f.refused === undefined);
if (moved.length === 0)
return undefined;
return {
code: "restore_outside_root",
message: `file restore to entry "${target}" changed or deleted ${moved.length} file(s) outside the root this run works in: ${moved.map((f) => `${f.action === "delete" ? "deleted" : "changed"} ${f.targetPath}`).join("; ")}.`,
};
}
export function fileLeftAsIsNotice(input) {
return {
code: "rewind.file_left_as_is",
message: `${leftFileNamed(input)} was not rewound and stays as it is: ${LEFT_AS_IS_WORDS[input.class].why}.`,
detail: { sessionId: input.sessionId, path: input.path, class: input.class },
};
}
export function noBoundaryRefusal(target, sessionId, preview = false) {
const e = new Error(preview
? `rewind-files: no usable file-history boundary exists for entry "${target}" on session "${sessionId}" (never made, or reaped), so there is nothing to preview. ${rewindRefusalTail()}`
: `rewind-files: no file-history boundary exists for entry "${target}" on session "${sessionId}" — the working tree was NOT rewound. ${rewindRefusalTail()}`);
e.code = "rewind_snapshot.unresolvable";
return e;
}
export function boundaryUnrecordedNotice(input) {
const why = input.cause === "aborted" ? "saving it did not finish in time" : "the file-history store could not save it";
return {
code: "rewind.boundary_unrecorded",
message: `The files' state at the start of this turn was not recorded (${why}), so this turn cannot be rewound to; the turn itself goes on. Once it has ended, a rewind can still be asked for an earlier turn whose file state was kept, or for the conversation alone, which leaves the files as they are.`,
detail: { sessionId: input.sessionId, entryId: input.entryId, cause: input.cause },
};
}
function restoredAbsPathsOf(restored, root) {
const out = [];
for (const key of [...restored.filesChanged, ...restored.failed.map((f) => f.path)]) {
const abs = resolveTrackKey(root, key);
if (abs.ok)
out.push(abs.abs);
}
return out;
}
function rewindRefusalTail() {
return `To go on: preview the files' rewind to another entry first (Runner.rewindFiles with dryRun writes no working file and reports what would be restored), or take back only the conversation (Runner.rewindConversation, or TaskSpec.resumeAt with no file-restore option), which leaves the files as they are. Boundaries are keyed by the entry of the person's input that opened a turn (an engine entry ahead of it, such as a task notification, has none) and exist only for turns that recorded history (a RunnerDeps.fileHistoryStore wired, capture on, and the run's file history not disabled); a fork holds its source's boundaries only when neither session works in a tree of its own (TaskSpec.workspace): a fork whose source has one, or whose source's checkout record cannot be read from its log, is carried none of them by the engine — the file changes before the fork are not in its history unless a host carried them in (a deletion cascade, an import), and then each file recorded under another directory is left as it is where that directory lies outside this session's root (leftAsIs, recorded_outside_root) and refused where it lies inside it (recorded_elsewhere) — and a fork that has a tree of its own records no file history and restores none in this version (its conversation is still branched by resumeAt); a file version is restored only under the directory it was recorded under, and an older version that records no directory only when a host that can vouch for the directory it was recorded under hands it to the rewind; a boundary from the retired whole-tree snapshot era is not restorable by this seat, and reaped boundaries have none.`;
}
function beforeWithoutBoundaryRefusal(target, sessionId) {
const e = new Error(`rewind-files: entry "${target}" has no file-history boundary on session "${sessionId}" — a before-restore needs the target's own boundary and never crosses into an earlier turn, so the working tree was NOT rewound. ${rewindRefusalTail()}`);
e.code = "rewind_snapshot.unresolvable";
return e;
}