UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,659 lines • 92.2 kB
import { createHash } from "node:crypto";
import { readMember, thrownText } from "./thrown-value.js";
import { readMemberGroup } from "./member-group.js";
import { foldDriveLetter, isAbsoluteForFamily, isWinFormPath, pathFamilyOf, relativeInEveryFamily, startsWithDriveLetter } from "../tools/fs/safety.js";
import { isAbsence } from "../tools/fs/shell-read-environment.js";
import { fileHistoryBoundariesToKeep, resolveFileHistoryRetention } from "./file-history-retention.js";
import { optionKeys, receiveOptions } from "./own-property-receipt.js";
import { readUnreadableDeleteId } from "./session.js";
import { readFileHistoryScope } from "../engine/session/repo-utils.js";
const normSlash = (p) => p.replace(/\\/g, "/");
const stripTrailSep = (p) => (isWinFormPath(p) ? p.replace(/[\\/]+$/, "") : p.replace(/\/+$/, ""));
function relUnder(root, child) {
    const fold = isWinFormPath(root) ? normSlash : (p) => p;
    const r = foldDriveLetter(fold(stripTrailSep(root)));
    const c = foldDriveLetter(fold(child));
    if (c === r)
        return "";
    if (!c.startsWith(r + "/"))
        return null;
    return fold(child).slice(fold(stripTrailSep(root)).length + 1);
}
function outsideRootOf(root, abs) {
    const rel = relUnder(root, abs);
    return rel === null || (isWinFormPath(root) ? normSlash(rel) : rel).split("/").includes("..");
}
function joinUnder(root, rel) {
    const win = isWinFormPath(root);
    return stripTrailSep(root) + (win ? "\\" : "/") + (win ? rel.replace(/\//g, "\\") : rel);
}
function isUnsafeRelPathLike(relN) {
    return !relativeInEveryFamily(relN) || relN.split("/").includes("..");
}
function parentDirOf(absPath) {
    const win = isWinFormPath(absPath);
    const norm = win ? normSlash(absPath) : absPath;
    const cut = norm.replace(/\/+$/, "");
    const i = cut.lastIndexOf("/");
    const driveOnly = (p) => p.length === 2 && startsWithDriveLetter(p);
    if (i < 0 || cut === "" || driveOnly(cut))
        return undefined;
    const parent = i === 0 ? "/" : driveOnly(cut.slice(0, i)) ? `${cut.slice(0, i)}/` : cut.slice(0, i);
    return win ? parent.replace(/\//g, "\\") : parent;
}
function lastSegmentOf(absPath) {
    const cut = (isWinFormPath(absPath) ? normSlash(absPath) : absPath).replace(/\/+$/, "");
    return cut.slice(cut.lastIndexOf("/") + 1);
}
export const FILE_HISTORY_REFUSAL_CLASSES = Object.freeze(["link_safety", "base_unavailable", "key_unresolvable", "recorded_elsewhere", "place_unrecorded", "changed_since_plan"]);
export const FILE_HISTORY_LEFT_AS_IS_CLASSES = Object.freeze(["frozen_history", "recorded_outside_root"]);
export function fileHistoryEntryTravels(key) {
    return key.kind === "root-relative";
}
export function fileHistoryEntryFrozen(entry) {
    const family = entry.desc?.family ?? "posix";
    if ((entry.desc?.kind ?? (isAbsoluteForFamily(family, entry.key) ? "absolute" : "root-relative")) !== "root-relative")
        return undefined;
    const segmentsOf = (p, win) => (win ? normSlash(p) : p).split("/").filter((s) => s !== "").map(foldedSpelling);
    const dirs = segmentsOf(entry.key, family === "win").slice(0, -1);
    if (dirs.length === 0)
        return undefined;
    for (let i = entry.versions.length - 1; i >= 0; i--) {
        const place = entry.versions[i].parentIdent;
        if (place === undefined || !isPlace(place))
            continue;
        const tail = segmentsOf(place, isWinFormPath(place)).slice(-dirs.length);
        if (tail.length === dirs.length && tail.every((s, j) => s === dirs[j]))
            continue;
        return {
            class: "frozen_history",
            place,
            reason: `a version of this file was recorded through a link on its path (the directory it was recorded under is not its key's own directory), so its history is frozen: a boundary does not read it, a rewind leaves it as it is, and an export leaves it out`,
        };
    }
    return undefined;
}
export function fileHistoryTargetOf(entry, versionAtBoundary) {
    const frozen = fileHistoryEntryFrozen({ key: entry.key, desc: entry.desc, versions: entry.versions });
    if (frozen !== undefined)
        return { kind: "frozen", ...frozen };
    let version = versionAtBoundary;
    if (version === undefined) {
        if (!entry.baseAvailable)
            return { kind: "base_unavailable" };
        version = 1;
    }
    const rec = entry.versions.find((v) => v.version === version);
    if (rec === undefined)
        return { kind: "record_missing", version };
    const place = rec.parentIdent !== undefined ? { parentIdent: rec.parentIdent } : {};
    if (rec.blobHash === null)
        return { kind: "absent", version, ...place };
    return { kind: "bytes", version, hash: rec.blobHash, ...(rec.mode !== undefined ? { mode: rec.mode } : {}), ...place };
}
export function fileHistoryParentIdentTravels(parentIdent) {
    return !isPlace(parentIdent);
}
export function trackKeyFamilyOf(root) {
    return isWinFormPath(root) ? "win" : "posix";
}
export function describeTrackKey(root, absPath) {
    const key = trackKeyOf(root, absPath);
    return { key, kind: key === absPath ? "absolute" : "root-relative", family: trackKeyFamilyOf(root) };
}
export function trackKeyOf(root, absPath) {
    const rel = relUnder(root, absPath);
    if (rel === null || rel === "")
        return absPath;
    const win = isWinFormPath(root);
    const relN = win ? normSlash(rel) : rel;
    if (win ? isUnsafeRelPathLike(relN) : isAbsoluteForFamily("posix", relN) || relN.split("/").includes(".."))
        return absPath;
    return rel;
}
export function resolveTrackKey(root, key, minted) {
    const win = isWinFormPath(root);
    if (minted !== undefined && minted.family !== trackKeyFamilyOf(root)) {
        if (minted.kind === "absolute") {
            return { ok: false, reason: `foreign-family absolute key cannot be restored here (recorded under a ${minted.family} root, this root is ${trackKeyFamilyOf(root)}): ${key}`, class: "key_unresolvable" };
        }
        if (isUnsafeRelPathLike(normSlash(key)) || key.includes("\\")) {
            return { ok: false, reason: `foreign-family key is ambiguous across path families (recorded under a ${minted.family} root, this root is ${trackKeyFamilyOf(root)}): ${key}`, class: "key_unresolvable" };
        }
    }
    const keyN = win ? normSlash(key) : key;
    if (isAbsoluteForFamily(pathFamilyOf({ root }), keyN) || (win && startsWithDriveLetter(keyN)))
        return { ok: true, abs: key };
    if (win ? isUnsafeRelPathLike(keyN) : keyN.split("/").includes(".."))
        return { ok: false, reason: `unsafe recorded key escapes root: ${key}`, class: "key_unresolvable" };
    return { ok: true, abs: joinUnder(root, keyN) };
}
export const FILE_HISTORY_ERROR_CODES = Object.freeze(["track_failed", "snapshot_failed", "restore_failed", "adopt_failed", "not_found", "aborted", "unsupported_format", "conflict", "too_large"]);
export const FILE_HISTORY_LIMIT_SOURCES = Object.freeze(["store_option", "backend"]);
export function fileHistoryTooLarge(input) {
    const { what, size, limit } = input;
    return {
        code: "too_large",
        message: `${what} is ${size} bytes, over the file history's limit of ${limit.bytes} bytes for one stored copy (${limit.source === "store_option" ? "the store's maxBlobBytes" : "the storage backend's own bound"}) — the call committed nothing`,
        permanence: "terminal",
        limit: Object.freeze({ bytes: limit.bytes, source: limit.source }),
    };
}
export function readMaxBlobBytes(owner, value) {
    if (value === undefined)
        return undefined;
    if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0)
        return value;
    throw Object.assign(new TypeError(`${owner} options.maxBlobBytes must be a whole number of bytes, 0 or more (got ${value === null ? "null" : typeof value === "number" ? String(value) : typeof value})`), { code: "config.invalid_argument" });
}
export function blobOverStoreLimit(bytes, maxBlobBytes, what) {
    if (maxBlobBytes === undefined || bytes.byteLength <= maxBlobBytes)
        return undefined;
    return fileHistoryTooLarge({ what, size: bytes.byteLength, limit: { bytes: maxBlobBytes, source: "store_option" } });
}
export function overLimit(error) {
    return error === undefined ? undefined : { ok: false, error };
}
const CAUGHT_CODE_RETRY_CLASS = new Map([
    ...["EACCES", "EPERM", "EROFS", "ENAMETOOLONG", "EFBIG", "ENOTDIR", "EISDIR"].map((c) => [c, "terminal"]),
    ...["EAGAIN", "EWOULDBLOCK", "EBUSY", "EINTR", "ETIMEDOUT", "EMFILE", "ENFILE"].map((c) => [c, "transient"]),
]);
export function caughtFault(caught) {
    const code = readMember(caught, "code");
    const judged = typeof code === "string" ? CAUGHT_CODE_RETRY_CLASS.get(code) : undefined;
    return judged === undefined ? {} : { permanence: judged };
}
export const DAMAGED_RECORD = Object.freeze({ permanence: "terminal" });
export class FileHistoryStoreError extends Error {
    code;
    constructor(failure, message, thrown) {
        super(message, thrown !== undefined ? { cause: thrown.value } : undefined);
        this.name = "FileHistoryStoreError";
        this.code = failure.code;
        if (failure.permanence !== undefined)
            this.permanence = failure.permanence;
    }
}
export const UNPLACED_AT_REWIND_ROOT = "rewind_root";
export function restoreOptionsAt(options, root) {
    return options?.unplacedHistoryRecordedUnder === UNPLACED_AT_REWIND_ROOT ? { ...options, unplacedHistoryRecordedUnder: root } : options;
}
export const FILE_HISTORY_DIFF_LINE_BUDGET = 2000;
export function bytesAreBinary(bytes) {
    return bytes.includes(0);
}
export function countRestoreLineDiff(current, target) {
    if ((current !== undefined && bytesAreBinary(current)) || (target !== undefined && bytesAreBinary(target)))
        return { insertions: 0, deletions: 0 };
    const linesOf = (b) => {
        if (b === undefined)
            return [];
        const text = new TextDecoder().decode(b);
        if (text === "")
            return [];
        return text.endsWith("\n") ? text.slice(0, -1).split("\n") : text.split("\n");
    };
    const a = linesOf(current);
    const bLines = linesOf(target);
    const common = longestCommonSubsequenceLength(a, bLines);
    return { deletions: a.length - common, insertions: bLines.length - common };
}
function longestCommonSubsequenceLength(a, b) {
    const n = a.length;
    const m = b.length;
    if (n === 0 || m === 0)
        return 0;
    const max = Math.min(FILE_HISTORY_DIFF_LINE_BUDGET, n + m);
    const offset = max;
    const v = new Int32Array(2 * max + 1);
    for (let d = 0; d <= max; d++) {
        for (let k = -d; k <= d; k += 2) {
            let x;
            if (k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1]))
                x = v[offset + k + 1];
            else
                x = v[offset + k - 1] + 1;
            let y = x - k;
            while (x < n && y < m && a[x] === b[y]) {
                x++;
                y++;
            }
            v[offset + k] = x;
            if (x >= n && y >= m) {
                return (n + m - d) / 2;
            }
        }
    }
    return 0;
}
export function fileHistoryExportDigest(data) {
    const canonical = {
        formatVersion: data.formatVersion,
        tracked: [...data.tracked]
            .map((t) => ({
            relOrAbsPath: t.relOrAbsPath,
            keyKind: t.keyKind,
            keyFamily: t.keyFamily,
            baseAvailable: t.baseAvailable,
            versions: [...t.versions]
                .map((v) => ({ version: v.version, blobHash: v.blobHash, mode: v.mode ?? null, parentIdent: v.parentIdent ?? null, backupTime: v.backupTime }))
                .sort((a, b) => a.version - b.version),
        }))
            .sort((a, b) => (a.relOrAbsPath < b.relOrAbsPath ? -1 : a.relOrAbsPath > b.relOrAbsPath ? 1 : 0)),
        boundaries: [...data.boundaries]
            .map((b) => ({
            entryId: b.entryId,
            files: [...b.files].map((f) => ({ relOrAbsPath: f.relOrAbsPath, version: f.version })).sort((x, y) => (x.relOrAbsPath < y.relOrAbsPath ? -1 : x.relOrAbsPath > y.relOrAbsPath ? 1 : 0)),
        }))
            .sort((a, b) => (a.entryId < b.entryId ? -1 : a.entryId > b.entryId ? 1 : 0)),
    };
    return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
}
export function validateFileHistoryExport(data) {
    try {
        return judgeFileHistoryEnvelope(data);
    }
    catch (err) {
        return { ok: false, error: { code: "unsupported_format", message: `file-history import payload cannot be read: ${thrownText(err)}` } };
    }
}
function judgeFileHistoryEnvelope(data) {
    const bad = (message) => ({ ok: false, error: { code: "unsupported_format", message } });
    if (data === null || typeof data !== "object")
        return bad("file-history import payload is not an envelope");
    if (data.formatVersion !== "file-history/1")
        return bad(`unsupported file-history envelope format ${JSON.stringify(String(data.formatVersion))} — this engine reads "file-history/1" and refuses rather than reinterpreting a foreign epoch`);
    if (!Array.isArray(data.tracked) || !Array.isArray(data.boundaries))
        return bad("file-history envelope is missing its tracked/boundaries arrays");
    const omitted = data.absoluteEntriesOmitted;
    if (omitted !== undefined && (typeof omitted !== "number" || !Number.isSafeInteger(omitted) || omitted < 0)) {
        return bad(`file-history envelope's absoluteEntriesOmitted is ${JSON.stringify(omitted)} — a count of files left out is a non-negative integer; refused, never coerced`);
    }
    const frozenKeys = data.frozenEntryKeys;
    if (frozenKeys !== undefined && (!Array.isArray(frozenKeys) || frozenKeys.some((k) => typeof k !== "string" || k === "") || new Set(frozenKeys).size !== frozenKeys.length)) {
        return bad(`file-history envelope's frozenEntryKeys is not a list of distinct non-empty keys — refused, never coerced`);
    }
    const known = new Set();
    for (const t of data.tracked) {
        if (typeof t?.relOrAbsPath !== "string" || t.relOrAbsPath === "")
            return bad("file-history envelope carries a tracked row with no path");
        if (t.keyKind !== "root-relative" && t.keyKind !== "absolute")
            return bad(`tracked row ${t.relOrAbsPath} declares an unknown key kind ${JSON.stringify(String(t.keyKind))} — a key whose shape cannot be judged is refused, never guessed`);
        if (t.keyKind === "absolute") {
            return bad(`tracked row ${t.relOrAbsPath} is an ABSOLUTE key — an imported graph may not carry paths outside the importing root (it would grant this envelope restore authority over an arbitrary path); same-store carry across sessions is adoptScope's seat`);
        }
        if (isUnsafeRelPathLike(normSlash(t.relOrAbsPath)) || t.relOrAbsPath.includes("\\")) {
            return bad(`tracked row ${t.relOrAbsPath} is not a safe root-relative key (absolute form, drive spelling, '..' segment, or a separator that means different things across path families) — refused, never coerced`);
        }
        if (t.keyFamily !== "posix" && t.keyFamily !== "win")
            return bad(`tracked row ${t.relOrAbsPath} declares an unknown key family ${JSON.stringify(String(t.keyFamily))} — a key whose provenance cannot be judged is refused, never guessed`);
        if (typeof t.baseAvailable !== "boolean" || !Array.isArray(t.versions))
            return bad(`tracked row ${t.relOrAbsPath} is missing its base-availability state or version chain`);
        for (const v of t.versions) {
            void v?.backupTime;
            if (v?.parentIdent !== undefined && typeof v.parentIdent !== "string")
                return bad(`tracked row ${t.relOrAbsPath} carries a non-string parentIdent — refused, never coerced; leave parentIdent off the version, or send it as a relative path (no leading slash, backslash or drive letter; an imported version records no place either way)`);
            if (v?.parentIdent !== undefined && !fileHistoryParentIdentTravels(v.parentIdent)) {
                return bad(`tracked row ${t.relOrAbsPath} carries an ABSOLUTE place (parentIdent) on version ${String(v.version)} — an imported graph may not carry paths outside the importing root (a later boundary would re-read the tracked file there); a version's place is recorded where it is captured, never imported`);
            }
            if (typeof v?.version !== "number" || !Number.isInteger(v.version) || v.version < 1)
                return bad(`tracked row ${t.relOrAbsPath} carries a non-integer version number`);
            if (v.blobHash !== null && (typeof v.blobHash !== "string" || !/^[0-9a-f]{64}$/.test(v.blobHash)))
                return bad(`tracked row ${t.relOrAbsPath} carries a blob reference that is not a sha256 digest`);
            if (v.mode !== undefined) {
                if (typeof v.mode !== "number" || !Number.isInteger(v.mode) || v.mode < 0 || v.mode > 0o7777) {
                    return bad(`tracked row ${t.relOrAbsPath} carries a mode outside the permission-bit domain [0, 0o7777] — refused, never coerced`);
                }
                if ((v.mode & 0o6000) !== 0) {
                    return bad(`tracked row ${t.relOrAbsPath} carries a set-ID mode (0o${v.mode.toString(8)}) — a restore replaying setuid/setgid bits would mint a privilege-escalation primitive; refused`);
                }
            }
        }
        if (new Set(t.versions.map((v) => v.version)).size !== t.versions.length)
            return bad(`tracked row ${t.relOrAbsPath} carries the same version number twice — a chain whose versions are ambiguous cannot be published`);
        for (let i = 1; i < t.versions.length; i++) {
            if (t.versions[i].version <= t.versions[i - 1].version) {
                return bad(`tracked row ${t.relOrAbsPath} carries a chain whose versions are not strictly increasing in order (…${t.versions[i - 1].version}, ${t.versions[i].version}…) — a later local boundary would then reference an ambiguous version`);
            }
        }
        if (known.has(t.relOrAbsPath)) {
            return bad(`file-history envelope carries the tracked row ${t.relOrAbsPath} twice — duplicate keys make the published graph differ from the validated one`);
        }
        if (t.baseAvailable && t.versions.length > 0 && t.versions[0].version !== 1)
            return bad(`tracked row ${t.relOrAbsPath} claims an available base but its chain does not start at v1`);
        if (!t.baseAvailable && t.versions.some((v) => v.version === 1))
            return bad(`tracked row ${t.relOrAbsPath} carries a v1 record while declaring its base UNAVAILABLE — the DV-14 refusal state and a pristine baseline are mutually exclusive`);
        known.add(t.relOrAbsPath);
    }
    const listedTwice = (data.frozenEntryKeys ?? []).find((k) => known.has(k));
    if (listedTwice !== undefined)
        return bad(`file-history envelope lists ${listedTwice} both as a tracked row and among the frozen entries it left out`);
    const seen = new Set();
    for (const b of data.boundaries) {
        if (typeof b?.entryId !== "string" || b.entryId === "")
            return bad("file-history envelope carries a boundary with no entry id");
        if (seen.has(b.entryId))
            return bad(`file-history envelope carries the boundary ${b.entryId} twice`);
        seen.add(b.entryId);
        if (!Array.isArray(b.files))
            return bad(`boundary ${b.entryId} carries no file mapping`);
        if (new Set(b.files.map((f) => f?.relOrAbsPath)).size !== b.files.length)
            return bad(`boundary ${b.entryId} maps the same path twice — the published mapping would differ from the validated one`);
        for (const f of b.files) {
            if (typeof f?.relOrAbsPath !== "string" || typeof f.version !== "number")
                return bad(`boundary ${b.entryId} carries a malformed file mapping`);
            if (!known.has(f.relOrAbsPath))
                return bad(`boundary ${b.entryId} references ${f.relOrAbsPath}, which the envelope's tracked set does not carry`);
            const chain = data.tracked.find((t) => t.relOrAbsPath === f.relOrAbsPath);
            if (!chain.versions.some((v) => v.version === f.version))
                return bad(`boundary ${b.entryId} references ${f.relOrAbsPath}@v${f.version}, which the envelope's version chain does not carry`);
        }
    }
    return { ok: true };
}
export const FILE_HISTORY_UNREFERENCED_BLOB_GRACE_MS = 3_600_000;
export function isBlobAddress(hash) {
    return typeof hash === "string" && /^[0-9a-f]{64}$/.test(hash);
}
export function blobPutRefusal(hash, bytes) {
    if (isBlobAddress(hash) && bytes instanceof Uint8Array && createHash("sha256").update(bytes).digest("hex") === hash)
        return undefined;
    return { ok: false, error: { code: "adopt_failed", message: "the bytes handed to blobExchange.put do not hash to the address they were put under — nothing was stored", permanence: "terminal" } };
}
const BLOB_EXCHANGE_MEMBERS = Object.freeze(["put", "get", "has"]);
export function fileHistoryBlobExchangeOf(store) {
    const owner = "FileHistoryStore.blobExchange";
    let group;
    try {
        group = store.blobExchange;
    }
    catch (cause) {
        throw invalidBlobExchange(`${owner} could not be read (${thrownText(cause)}).`);
    }
    if (group === undefined)
        return undefined;
    if (typeof group !== "object" || group === null)
        throw invalidBlobExchange(`${owner} must be an object with put / get / has (got ${group === null ? "null" : typeof group}).`);
    return readMemberGroup(owner, group, BLOB_EXCHANGE_MEMBERS, true);
}
function invalidBlobExchange(message) {
    const e = new Error(message);
    e.code = "config.invalid_argument";
    return e;
}
export function boundaryPublishVerdict(attempt) {
    return attempt.aborted ? { publish: false, reason: "aborted" } : { publish: true };
}
async function placeOfParentViaEnv(env, absPath, signal) {
    const parent = parentDirOf(absPath);
    return parent === undefined ? undefined : placeOfDirViaEnv(env, parent, signal);
}
async function placeOfDirViaEnv(env, dir, signal) {
    let at = dir;
    let tail = "";
    for (;;) {
        const canon = await env.canonicalPath(at, signal);
        if (canon.ok)
            return tail === "" ? canon.value : joinUnder(canon.value, tail);
        if (canon.error.code !== "not_found")
            return undefined;
        const up = parentDirOf(at);
        if (up === undefined)
            return undefined;
        const leaf = lastSegmentOf(at);
        tail = tail === "" ? leaf : `${leaf}/${tail}`;
        at = up;
    }
}
function isPlace(parentIdent) {
    return !relativeInEveryFamily(parentIdent);
}
function trackedPlaceOf(versions) {
    for (let i = versions.length - 1; i >= 0; i--) {
        const p = versions[i].parentIdent;
        if (p !== undefined && isPlace(p))
            return p;
    }
    return undefined;
}
const foldedSpelling = (p) => p.normalize("NFC").toLowerCase();
async function placeAsItStands(env, place, signal) {
    const now = await placeOfDirViaEnv(env, place, signal);
    if (now === undefined || now === place)
        return now;
    if (foldedSpelling(now) !== foldedSpelling(place))
        return undefined;
    for (let at = place; at !== undefined; at = parentDirOf(at)) {
        const info = await env.fileInfo(at, signal);
        if (info.ok ? info.value.kind === "symlink" : info.error.code !== "not_found")
            return undefined;
    }
    return now;
}
export async function resolveTrackedFile(env, root, key, versions, minted, signal) {
    const resolved = resolveTrackKey(root, key, minted);
    if (!resolved.ok)
        return resolved;
    const frozen = fileHistoryEntryFrozen({ key, desc: minted, versions });
    if (frozen !== undefined)
        return { ok: true, held: frozen.reason };
    const place = trackedPlaceOf(versions);
    if (place !== undefined) {
        const stands = await placeAsItStands(env, place, signal);
        if (stands === undefined)
            return { ok: true, held: `the directory ${key} was recorded under (${place}) no longer resolves to itself` };
        const abs = joinUnder(stands, lastSegmentOf(resolved.abs));
        const leaf = await env.fileInfo(abs, signal);
        if (leaf.ok && leaf.value.kind === "symlink")
            return { ok: true, held: `${abs} is a symbolic link now — the recorded file is not read through it` };
        return { ok: true, abs };
    }
    const realRoot = await placeOfDirViaEnv(env, root, signal);
    const real = await env.canonicalPath(resolved.abs, signal);
    const physical = real.ok ? real.value : real.error.code === "not_found" ? await placeOfDirViaEnv(env, resolved.abs, signal) : undefined;
    const under = realRoot === undefined || physical === undefined ? null : relUnder(realRoot, physical);
    if (under === null || under === "")
        return { ok: true, held: `${resolved.abs} does not lie under the root's real path (${realRoot ?? "unreadable"}) — a file this history records no place for is read only under the root` };
    return { ok: true, abs: resolved.abs };
}
export async function trackKeyForEdit(env, root, absPath, entryOf, signal) {
    const family = trackKeyFamilyOf(root);
    if (entryOf(absPath) !== undefined)
        return { key: absPath, kind: "absolute", family };
    const here = await placeOfParentViaEnv(env, absPath, signal);
    const realRoot = here === undefined ? undefined : await placeOfDirViaEnv(env, root, signal);
    const real = here === undefined || realRoot === undefined ? undefined : { at: joinUnder(here, lastSegmentOf(absPath)), root: realRoot };
    const at = real?.at ?? absPath;
    if (at !== absPath && entryOf(at) !== undefined)
        return { key: at, kind: "absolute", family };
    const described = describeTrackKey(real?.root ?? root, at);
    if (described.kind === "absolute")
        return { key: described.key, kind: "absolute", family };
    const spelled = describeTrackKey(root, absPath);
    if (real !== undefined && spelled.kind === "root-relative" && spelled.key !== described.key && entryOf(described.key) === undefined) {
        const prior = entryOf(spelled.key);
        if (prior !== undefined && fileHistoryEntryFrozen({ key: spelled.key, desc: spelled, versions: prior.versions }) === undefined) {
            const was = trackedPlaceOf(prior.versions);
            if (was === undefined || was === here || (await placeAsItStands(env, was, signal)) === here)
                return { ...spelled, family };
        }
    }
    const existing = entryOf(described.key);
    const there = existing === undefined ? undefined : trackedPlaceOf(existing.versions);
    if (there === undefined)
        return { ...described, family };
    if (here === undefined || here === there || (await placeAsItStands(env, there, signal)) === here)
        return { ...described, family };
    return { key: at, kind: "absolute", family };
}
export function trackKeyForAnnul(root, absPath, has, proof) {
    if (proof !== undefined)
        return trackKeyForEdit(proof.env, root, absPath, proof.entryOf, proof.signal).then((k) => k.key);
    const key = trackKeyOf(root, absPath);
    return key !== absPath && has(absPath) ? absPath : key;
}
export function placeProvenDifferent(recorded, current) {
    return current !== undefined && recorded !== current;
}
export async function captureFileBackupViaEnv(env, absPath, _root, signal) {
    if (signal?.aborted)
        return { state: "aborted" };
    const parentIdent = await placeOfParentViaEnv(env, absPath, signal);
    const rb = await env.readBinaryFile(absPath, signal);
    if (!rb.ok) {
        if (signal?.aborted)
            return { state: "aborted" };
        if (isAbsence(rb.error.code))
            return { state: "absent", ...(parentIdent !== undefined ? { parentIdent } : {}) };
        return { state: "unreadable", cause: `read ${absPath}: ${rb.error.code}` };
    }
    const hash = createHash("sha256").update(rb.value).digest("hex");
    const mode = await (async () => {
        const info = await env.fileInfo(absPath, signal);
        return info.ok && typeof info.value.mode === "number" ? info.value.mode & 0o7777 : undefined;
    })();
    return { state: "file", bytes: rb.value, hash, ...(mode !== undefined ? { mode } : {}), ...(parentIdent !== undefined ? { parentIdent } : {}) };
}
export async function worldStillMatchesMint(env, absPath, root, baseAvailable, mintedBlobHash, signal) {
    if (!baseAvailable) {
        return { verdict: "kept", reason: "the first touch recorded a base-UNAVAILABLE marker, whose whole purpose is to refuse a fake pristine later — an ambiguous failure may not erase it" };
    }
    const cap = await captureFileBackupViaEnv(env, absPath, root, signal);
    if (cap.state === "absent") {
        return mintedBlobHash === null ? { verdict: "unchanged" } : { verdict: "kept", reason: "the file recorded at the first touch is gone now" };
    }
    if (cap.state === "file") {
        if (mintedBlobHash === null)
            return { verdict: "kept", reason: "the path was recorded as NOT EXISTING at the first touch but holds bytes now" };
        return cap.hash === mintedBlobHash ? { verdict: "unchanged" } : { verdict: "kept", reason: "the file's bytes differ from the ones recorded at the first touch" };
    }
    return { verdict: "unjudged", reason: `the path could not be re-read to prove it is unchanged (${cap.state === "aborted" ? "aborted" : cap.cause})`, aborted: cap.state === "aborted" };
}
export function annulProofFailure(proof, absPath) {
    if (proof.verdict === "kept") {
        return { ok: false, error: { code: "conflict", message: `first-touch record for ${absPath} is NOT retractable: ${proof.reason} — the write this retraction compensates for may have changed the file, and deleting the only baseline of a modified file is worse than keeping a stale record` } };
    }
    return { ok: false, error: { code: proof.aborted ? "aborted" : "track_failed", message: `first-touch record for ${absPath} was left in place: ${proof.reason}, so whether the write this retraction compensates for changed the file was not judged` } };
}
export function modeProvenDifferent(recorded, current) {
    return recorded !== undefined && current !== undefined && recorded !== current;
}
export async function applyFileRestoreViaEnv(env, absPath, target, opts) {
    const signal = opts.signal;
    if (signal?.aborted)
        return { outcome: "failed", reason: "aborted" };
    const guard = await restorePreflight(env, absPath, target, opts);
    if ("refused" in guard)
        return guard.refused;
    if ("left" in guard)
        return { outcome: "left", left: guard.left };
    if ("convergedAtItsPlace" in guard)
        return { outcome: "identical" };
    const verdict = await noteRealPath(env, absPath, joinUnder(guard.place, lastSegmentOf(absPath)), signal);
    if (signal?.aborted)
        return { outcome: "failed", reason: "aborted" };
    const decline = (action, v) => v.kind === "left" ? { outcome: "left", left: v.left } : { outcome: "refused", reason: v.claim(), class: "link_safety", action };
    const cur = await env.readBinaryFile(absPath, signal);
    const curAbsent = !cur.ok && isAbsence(cur.error.code);
    const curHash = cur.ok ? createHash("sha256").update(cur.value).digest("hex") : undefined;
    const unplanned = notePlannedState(env, absPath, `${curHash !== undefined ? `bytes:${curHash} mode:${guard.currentMode ?? "unread"}` : curAbsent ? "absent" : `unread:${cur.ok ? "" : cur.error.code}`} ->${"absent" in target ? "absent" : `bytes:${target.hash}`}`);
    const refuseUnplanned = (action) => ({ outcome: "refused", reason: CHANGED_SINCE_PLAN_REASON, class: "changed_since_plan", action });
    if ("absent" in target) {
        if (curAbsent)
            return { outcome: "identical" };
        if (verdict !== undefined)
            return decline("delete", verdict);
        if (unplanned)
            return refuseUnplanned("delete");
        const rm = await env.remove(absPath, { force: true, ...(signal !== undefined ? { abortSignal: signal } : {}) });
        if (!rm.ok)
            return { outcome: "failed", reason: `remove: ${rm.error.code}` };
        return { outcome: "applied" };
    }
    if (curHash !== undefined && curHash === target.hash) {
        const modeOnly = await applyRecordedMode(env, absPath, opts, guard.currentMode, verdict !== undefined || unplanned);
        if (modeOnly === "held")
            return verdict !== undefined ? decline("write", verdict) : refuseUnplanned("write");
        if (modeOnly === "unchanged")
            return { outcome: "identical" };
        if (modeOnly === "applied")
            return { outcome: "applied" };
        if (modeOnly === "applied_unpreserved")
            return { outcome: "applied", modeNotPreserved: true };
        return { outcome: "identical", modeNotPreserved: true };
    }
    if (verdict !== undefined)
        return decline("write", verdict);
    if (unplanned)
        return refuseUnplanned("write");
    const w = await writeRestoredBytes(env, absPath, target.bytes, signal);
    if (!w.ok)
        return w.refused ? { outcome: "refused", reason: `write: ${w.code} — the path stopped being what the check read just before the write (the file, or a directory above it, became a link or another object), so nothing was written; ${LINK_SAFETY_WAY_ON.changed}`, class: "link_safety", action: "write" } : { outcome: "failed", reason: `write: ${w.code}` };
    const modeAfter = await applyRecordedMode(env, absPath, opts, undefined);
    return { outcome: "applied", ...(modeAfter === "unpreserved" || modeAfter === "applied_unpreserved" ? { modeNotPreserved: true } : {}) };
}
async function restorePreflight(env, absPath, target, opts) {
    const action = "absent" in target ? "delete" : "write";
    const refuse = (cls, reason, recordedUnder) => ({
        refused: { outcome: "refused", reason, class: cls, action, ...(recordedUnder !== undefined ? { recordedUnder } : {}) },
    });
    const info = await env.fileInfo(absPath, opts.signal);
    if (info.ok && info.value.kind !== "file") {
        return refuse("link_safety", info.value.kind === "symlink"
            ? `restore target is a SYMLINK — the recorded bytes belong to the file that was edited, not to whatever the link now points at; ${LINK_SAFETY_WAY_ON.leaf}`
            : `restore target is a ${info.value.kind}, not a regular file — the recorded bytes are not this object's; ${LINK_SAFETY_WAY_ON.leaf}`);
    }
    const currentMode = info.ok ? info.value.mode : undefined;
    const recorded = await recordedPlaceOf(env, absPath, opts);
    if (recorded === undefined) {
        return refuse("place_unrecorded", "this version records no place (it was recorded before places were kept), so where it belongs cannot be told — it was not written. Where the host can vouch for the directory this session's earlier legs worked in, the rewind can restore such versions as recorded there; without that, a rewind to a turn recorded since places were kept restores this file (each boundary since records its place), and this turn's version stays out of reach");
    }
    const now = await placeOfParentViaEnv(env, absPath, opts.signal);
    if (now === recorded)
        return { currentMode, place: now };
    if (now === undefined)
        return refuse("link_safety", `where this file would land cannot be read (its directory's real path did not resolve) — it was not written; ${LINK_SAFETY_WAY_ON.unread}`);
    const stands = await placeAsItStands(env, recorded, opts.signal);
    if (stands === undefined) {
        return refuse("link_safety", `the directory this version was recorded under (${recorded}) no longer resolves to itself — it was moved or is reached through a link now — so it was not written; ${LINK_SAFETY_WAY_ON.place}`);
    }
    if (stands === now)
        return { currentMode, place: now };
    if (await placeHolds(env, stands, lastSegmentOf(absPath), target, opts.signal))
        return { convergedAtItsPlace: true };
    const rootReal = await placeOfDirViaEnv(env, opts.root, opts.signal);
    if (rootReal !== undefined && outsideRootOf(rootReal, stands)) {
        return {
            left: {
                class: "recorded_outside_root",
                place: stands,
                reason: `this version was recorded under a directory outside the one this rewind works in, so it was neither written nor deleted there or here — a rewind handed the root it was recorded under restores it`,
            },
        };
    }
    return refuse("recorded_elsewhere", `not restored: this version belongs to ${joinUnder(stands, lastSegmentOf(absPath))}, where it was recorded — a file is restored only there; rewind from ${oldRootOf(stands, relUnder(opts.root, absPath) ?? "")} to restore it`, stands);
}
const LINK_SAFETY_WAY_ON = {
    leaf: "to restore it, put a regular file back at this path in place of the link or other object (or remove it), then rewind again — or restore the file by hand",
    place: "to restore it, put that directory back where it was as a real directory (not a link to one), then rewind again — or restore the file by hand",
    unread: "to restore it, check that its directory still exists and can be reached, then rewind again — or restore the file by hand",
    changed: "to restore it, put the file and the directories above it back as they were (a regular file, no link in place of any of them), then rewind again — or restore the file by hand",
};
async function recordedPlaceOf(env, absPath, opts) {
    const ident = opts.parentIdent;
    if (ident !== undefined && isPlace(ident))
        return ident;
    const under = opts.unplacedHistoryRecordedUnder;
    if (under === undefined)
        return undefined;
    const rel = relativeParentUnder(opts.root, absPath);
    if (rel === undefined)
        return undefined;
    const base = await placeOfDirViaEnv(env, under, opts.signal);
    if (base === undefined)
        return undefined;
    return rel === "." ? base : joinUnder(base, isWinFormPath(base) ? normSlash(rel) : rel);
}
function relativeParentUnder(root, absPath) {
    const parent = parentDirOf(absPath);
    const rel = parent === undefined ? null : relUnder(root, parent);
    return rel === null ? undefined : rel === "" ? "." : rel;
}
async function placeHolds(env, place, leaf, target, signal) {
    const dir = await env.fileInfo(place, signal);
    if (!dir.ok || dir.value.kind !== "directory")
        return false;
    const there = await env.readBinaryFile(joinUnder(place, leaf), signal);
    if ("absent" in target)
        return !there.ok && isAbsence(there.error.code);
    return there.ok && createHash("sha256").update(there.value).digest("hex") === target.hash;
}
async function writeRestoredBytes(env, absPath, bytes, signal) {
    if (env.writeFileGuarded !== undefined) {
        const r = await env.writeFileGuarded(absPath, bytes, { canonicalPath: absPath, noFollow: true }, signal);
        return r.ok ? { ok: true } : { ok: false, code: r.error.code, refused: r.error.code === "precondition_failed" };
    }
    const w = await env.writeFile(absPath, bytes, signal);
    return w.ok ? { ok: true } : { ok: false, code: w.error.code, refused: false };
}
async function applyRecordedMode(env, absPath, opts, currentMode, held = false) {
    const want = opts.mode;
    if (want === undefined)
        return "unchanged";
    if (currentMode === (want & 0o7777))
        return "unchanged";
    const setMode = async (mode) => {
        try {
            return env.setFileMode !== undefined && (await env.setFileMode(absPath, mode, opts.signal)).ok;
        }
        catch {
            return false;
        }
    };
    if ((want & 0o6000) !== 0) {
        const stripped = want & 0o1777;
        if (currentMode === stripped)
            return "unpreserved";
        if (held && env.setFileMode !== undefined)
            return "held";
        return (await setMode(stripped)) ? "applied_unpreserved" : "unpreserved";
    }
    if (held && env.setFileMode !== undefined)
        return "held";
    return (await setMode(want & 0o7777)) ? "applied" : "unpreserved";
}
const IN_MEMORY_FILE_HISTORY_STORE_OPTION_KEYS = optionKeys()({ retention: 0, now: 0, maxBlobBytes: 0 });
export class InMemoryFileHistoryStore {
    scopes = new Map();
    boundaryKeep;
    blobs = new Map();
    blobAt = new Map();
    now;
    inFlightBlobs = new Map();
    writers = new Map();
    constructor(options) {
        const opts = receiveOptions(options, "InMemoryFileHistoryStore", IN_MEMORY_FILE_HISTORY_STORE_OPTION_KEYS);
        this.boundaryKeep = resolveFileHistoryRetention("InMemoryFileHistoryStore", opts.retention);
        if (opts.now !== undefined && typeof opts.now !== "function") {
            throw Object.assign(new TypeError(`InMemoryFileHistoryStore options.now must be a function answering milliseconds (got ${opts.now === null ? "null" : typeof opts.now})`), { code: "config.invalid_argument" });
        }
        this.now = opts.now ?? Date.now;
        this.maxBlobBytes = readMaxBlobBytes("InMemoryFileHistoryStore", opts.maxBlobBytes);
    }
    maxBlobBytes;
    blobExchange = {
        put: async (hash, bytes) => {
            const refused = blobPutRefusal(hash, bytes) ?? overLimit(blobOverStoreLimit(bytes, this.maxBlobBytes, `the blob put under ${hash}`));
            if (refused !== undefined)
                return refused;
            if (!this.blobs.has(hash))
                this.blobs.set(hash, Uint8Array.from(bytes));
            this.blobAt.set(hash, this.now());
            return { ok: true };
        },
        get: async (hash) => {
            const bytes = isBlobAddress(hash) ? this.blobs.get(hash) : undefined;
            return bytes === undefined ? undefined : Uint8Array.from(bytes);
        },
        has: async (hashes) => new Set(hashes.filter((h) => isBlobAddress(h) && this.blobs.has(h))),
    };
    holdBlob(hash, bytes) {
        if (this.blobs.has(hash))
            return;
        this.blobs.set(hash, bytes);
        this.blobAt.set(hash, this.now());
    }
    applyBoundaryRetention(scope, justCommitted) {
        if (this.boundaryKeep === null)
            return;
        try {
            const sc = this.scopes.get(scope);
            if (sc === undefined)
                return;
            const keepIds = fileHistoryBoundariesToKeep([...sc.boundaries.keys()], justCommitted, this.boundaryKeep);
            if (keepIds === null)
                return;
            this.reap(scope, keepIds).catch(() => { });
        }
        catch {
        }
    }
    leaseBlob(hash) {
        this.inFlightBlobs.set(hash, (this.inFlightBlobs.get(hash) ?? 0) + 1);
    }
    releaseBlob(hash) {
        const n = this.inFlightBlobs.get(hash);
        if (n === undefined)
            return;
        if (n <= 1)
            this.inFlightBlobs.delete(hash);
        else
            this.inFlightBlobs.set(hash, n - 1);
    }
    scope(scope) {
        let sc = this.scopes.get(scope);
        if (sc === undefined) {
            sc = { tracked: new Map(), boundaries: new Map(), spentAttempts: new Set(), activeAttempts: new Set(), reapedEntries: new Set() };
            this.scopes.set(scope, sc);
        }
        return sc;
    }
    persistFirstTouch(scope, key, state) {
        this.scope(scope).tracked.set(key, state);
    }
    publishBoundary(scope, entryId, staged) {
        const sc = this.scope(scope);
        for (const [key, cap] of staged) {
            if (cap.kind !== "unchanged")
                continue;
            const still = sc.tracked.get(key)?.versions.some((v) => v.version === cap.version) ?? false;
            if (!still)
                throw new Error(`staged reference ${key}@v${cap.version} no longer exists (reaped mid-capture)`);
        }
        const mapping = new Map();
        const now = new Date().toISOString();
        for (const [key, cap] of staged) {
            if (cap.kind === "unchanged") {
                mapping.set(key, cap.version);
                continue;
            }
            const t = sc.tracked.get(key);
            if (t === undefined)
                continue;
            const last = t.versions[t.versions.length - 1];
            const version = last !== undefined ? last.version + 1 : t.baseAvailable ? 1 : 2;
            t.versions.push({ version, blobHash: cap.blobHash, backupTime: now, ...(cap.mode !== undefined ? { mode: cap.mode } : {}), ...(cap.parentIdent !== undefined ? { parentIdent: cap.parentIdent } : {}) });
            mapping.set(key, version);
        }
        sc.boundaries.set(entryId, mapping);
    }
    async writing(scope, write) {
        this.writers.set(scope, (this.writers.get(scope) ?? 0) + 1);
        try {
            return await write();
        }
        finally {
            const left = (this.writers.get(scope) ?? 1) - 1;
            if (left === 0)
                this.writers.delete(scope);
            else
                this.writers.set(scope, left);
        }
    }
    trackEdit(scope, absPath, env, root, signal) {
        return this.writing(scope, () => this.trackEditCounted(scope, absPath, env, root, signal));
    }
    async trackEditCounted(scope, absPath, env, root, signal) {
        try {
            const sc = this.scope(scope);
            const { key, ...keyDesc } = await trackKeyForEdit(env, root, absPath, (k) => sc.tracked.get(k), signal);
            const already = sc.tracked.get(key);
            if (already !== undefined) {
                already.observedByLaterTouch = true;
                return { ok: true, minted: false };
            }
            const cap = await captureFileBackupViaEnv(env, absPath, root, signal);
            const raced = sc.tracked.get(key);
            if (raced !== undefined) {
                raced.observedByLaterTouch = true;
                return { ok: true, minted: false };
            }
            if (cap.state === "aborted") {
                return { ok: false, error: { code: "aborted", message: `first-touch backup of ${absPath} aborted` } };
            }
            if (cap.state === "unreadable") {
                this.persistFirstTouch(scope, key, { baseAvailable: false, keyDesc, versions: [] });
                return { ok: true, minted: true };
            }
            if (cap.state === "file") {
                const over = overLimit(blobOverStoreLimit(cap.bytes, this.maxBlobBytes, `the first-touch copy of ${absPath}`));
                if (over !== undefined)
                    return over;
                this.leaseBlob(cap.hash);
                try {
                    this.holdBlob(cap.hash, cap.bytes);
                    this.persistFirstTouch(scope, key, {
                        baseAvailable: true,
                        keyDesc,
                        versions: [{ version: 1, blobHash: cap.hash, backupTime: new Date().toISOString(), ...(cap.mode !== undefined ? { mode: cap.mode } : {}), ...(cap.parentIdent !== undefined ? { parentIdent: cap.parentIdent } : {}) }],
                    });
                }
                finally {
                    this.releaseBlob(cap.hash);
                }
                return { ok: true, minted: true };
            }
            this.persistFirstTouch(scope, key, {
                baseAvailable: true,
                keyDesc,
                versions: [{ version: 1, blobHash: null, backupTime: new Date().toISOString(), ...(cap.parentIdent !== undefined ? { parentIdent: cap.parentIdent } : {}) }],
            });
            return { ok: true, minted: true };
        }
        catch (err) {
            return { ok: false, error: { code: "track_failed", message: `first-touch record for ${absPath} could not be persisted: ${thrownText(err)}`, ...caughtFault(err) } };
        }
    }
    annulTrack(scope, absPath, root, verify) {
        return this.writing(scope, () => this.annulTrackCounted(scope, absPath, root, verify));
    }
    async annulTrackCounted(scope, absPath, root, verify) {
        try {
            const sc = this.scopes.get(scope);
            const has = (k) => sc?.tracked.has(k) === true;
            const key = verify === undefined ? trackKeyForAnnul(root, absPath, has) : await trackKeyForAnnul(root, absPath, has, { ...verify, entryOf: (k) => sc?.tracked.get(k) });
            const t = sc?.tracked.get(key);
            if (sc === undefined || t === undefined)
                return { ok: true };
            const ineligible = () => {
                const live = sc.tracked.get(key);
                if (live === undefined)
                    return undefined;
                if (live !== t)
                    return `first-touch record for ${absPath} was replaced while this retraction was being proven`;
                for (const mapping of sc.boundaries.values()) {
                    if (mapping.has(key))
                        return `first-touch record for ${absPath} is referenced by a committed boundary — it is history now, not a retractable mint`;
                }
                if (live.versions.length > 1)
                    return `first-touch record for ${absPath} has grown past its first version — only the mint itself is retractable`;
                if (live.observedByLaterTouch === true) {
                    return `first-touch record for ${absPath} has since been served to another edit of the same path — it is that edit's baseline now, not a retractable mint`;
                }
                return undefined;
            };
            const before = ineligible();
            if (before !== undefined)
                return { ok: false, error: { code: "conflict", message: before } };
            const proof = verify === undefined ? undefined : await worldStillMatchesMint(verify.env, absPath, root, t.baseAvailable, t.versions[0]?.blobHash ?? null, verify.signal);
            if (proof !== undefined && proof.verdict !== "unchanged")
                return annulProofFailure(proof, absPath);
            const after = ineligible();
            if (after !== undefined)
                return { ok: false, error: { code: "conflict", message: after } };
            sc.tracked.delete(key);
            return { ok: true };
        }
        catch (err) {
            return { ok: false, error: { code: "track_failed", message: `annulling the first-touch record for ${absPath} failed: ${thrownText(err)}`, ...caughtFault(err) } };
        }
    }
    snapshot(scope, entryId, env, root, signal) {
        return this.writing(scope, () => this.snapshotCounted(scope, entryId, env, root, signal));
    }
    async snapshotCounted(scope, entryId, env, root, signal) {
        const sc = this.scope(scope);
        if (sc.boundaries.has(entryId))
            return { ok: true };
        if (sc.reapedEntries.has(entryId)) {
            return { ok: false, error: { code: "snapshot_failed", message: `entry "${entryId}" already had a boundary and it was reaped by retention — a fresh capture now would record post-turn bytes under a pre-turn key, so this entry has no boundary and cannot get one back` } };
        }
        if (sc.spentAttempts.has(entryId)) {
            return { ok: false, error: { code: "snapshot_failed", message: `capture lease for entry "${entryId}" is closed (a prior attempt failed); no complete pre-close staging exists, so this turn has no boundary` } };
        }
        if (sc.activeAttempts.has(entryId)) {
            return { ok: false, error: { code: "snapshot_failed", message: `a capture attempt for entry "${entryId}" is already in flight — concurrent same-key capture is refused (the in-flight attempt owns the lease)` } };
        }
        const stagedBlobHashes = new Set();
        sc.activeAttempts.add(entryId);
        try {
            const staged = new Map();
            for (const [key, t] of [...sc.tracked]) {
                if (signal?.aborted) {
                    sc.spentAttempts.add(entryId);
                    return { ok: false, error: { code: "aborted", message: `boundary capture for entry "${entryId}" aborted` } };
                }
                const resolved = await resolveTrackedFile(env, root, key, t.versions, t.keyDesc, signal);
                if (!resolved.ok) {
                    sc.spentAttempts.add(entryId);
                    return { ok: false, error: { code: "snapshot_failed", message: resolved.reason } };
                }
                if ("held" in resolved) {
                    const last = t.versions[t.versions.length - 1];
                    if (last !== undefined)
                        staged.set(key, { kind: "unchanged", version: last.version });
                    continue;
                }
                const cap = await captureFileBackupViaEnv(env, resolved.abs, root, signal);
                if (cap.state === "aborted") {
                    sc.spentAttempts.add(entryId);
                    return { ok: false, error: { code: "aborted", message: `boundary capture for entry "${entryId}" aborted` } };
                }
                if (cap.state === "unreadable") {
                    sc.spentAttempts.add(entryId);
                    return { ok: false, error: { code: "snapshot_failed", message: cap.cause } };
                }
                const last = t.versions[t.versions.length - 1];
                if (cap.state === "absent") {
                    if (last !== undefined && last.blobHash === null && !placeProvenDifferent(last.parentIdent, cap.parentIdent))
                        staged.set(key, { kind: "unchanged", version: last.version });
                    else
                        staged.set(key, { kind: "changed", blobHash: null, ...(cap.parentIdent !== undefined ? { parentIdent: cap.parentIdent } : {}) });
                    continue;
                }
                if (last !== undefined && last.blobHash === cap.hash && !modeProvenDifferent(last.mode, cap.mode) && !placeProvenDifferent(last.parentIdent, cap.parentIdent)) {
                    staged.set(key, { kind: "unchanged", version: last.version });
                    continue;
                }
                const over = overLimit(blobOverStoreLimit(cap.bytes, this.maxBlobBytes, `the boundary's copy of ${resolved.abs}`));
                if (over !== undefined) {
                    sc.spentAttempts.add(entryId);
                    return over;
                }
                if (!stagedBlobHashes.has(cap.hash)) {
                    stagedBlobHashes.add(cap.hash);
                    this.leaseBlob(cap.hash);
                }
                this.holdBlob(cap.hash, cap.bytes);
                staged.set(key, { kind: "changed", blobHash: cap.hash, ...(cap.mode !== undefined ? { mode: cap.mode } : {}), ...(cap.parentIdent !== undefined ? { parentIdent: cap.parentIdent } : {}) });
            }
            const verdict = boundaryPublishVerdict({ aborted: signal?.aborted === true });
            if (!verdict.publish) {
                sc.spentAttempts.add(entryId);
                return { ok: false, error: { code: "aborted", message: `boundary capture for entry "${entryId}" aborted (fenced — never committed)` } };
            }
            try {
                this.publishBoundary(scope, entryId, staged);
            }
            catch (err) {
                sc.spentAttempts.add(entryId);
                return { ok: false, error: { code: "snapshot_failed", message: `boundary for entry "${entryId}" could not be committed: ${thrownText(err)}`, ...caughtFault(err) } };
            }
            this.applyBoundaryRetention(scope, entryId);
            return { ok: true };
        }
        catch (err) {
            sc.spentAttempts.add(entryId);
            return { ok: false, error: { code: "snapshot_failed", message: thrownText(err), ...caughtFault(err) } };
        }
        finally {
            sc.activeAttempts.delete(entryId);
            for (const h of stagedBlobHashes)
                this.releaseBlob(h);
        }
    }
    async restore(scope, entryId, env, root, signal, options) {
        const empty = { filesChanged: [], identicalSkipped: [], refused: [], failed: [] };
        try {
            const sc = this.scopes.get(scope);
            const boundary = sc?.boundaries.get(entryId);
            if (sc === undefined || boundary === undefined) {
                return { outcome: "failed", ...empty, error: { code: "not_found", message: `no history boundary for entry "${entryId}"` } };
            }
            const ledger = empty;
            let modeNotPreserved = 0;
            for (const key of [...sc.tracked.keys()].sort()) {
                const t = sc.tracked.get(key);
                const to = fileHistoryTargetOf({ key, desc: t.keyDesc, baseAvailable: t.baseAvailable, versions: t.versions }, boundary.get(key));
                if (to.kind === "frozen") {
                    const { kind: _frozen, ...left } = to;
                    (ledger.leftAsIs ??= []).push({ path: key, ...left });
                    continue;
                }
                if (signal?.aborted) {
                    ledger.failed.push({ path: key, reason: "aborted before attempt" });
                    continue;
                }
                if (to.kind === "base_unavailable") {
                    ledger.refused.push({ path: key, reason: "base_unavailable", class: "base_unavailable" });
                    continue;
                }
                if (to.kind === "record_missing") {
                    ledger.failed.push({ path: key, reason: `version ${to.version} record missing (store integrity)` });
                    continue;
                }
                const resolved = resolveTrackKey(root, key, t.keyDesc);
                if (!resolved.ok) {
                    ledger.refused.push({ path: key, reason: resolved.reason, class: resolved.class });
                    continue;
                }
                let target;
                if (to.kind === "absent")
                    target = { absent: true };
                else {
                    const bytes = this.blobs.get(to.hash);
                    if (bytes === undefined) {
                        ledger.failed.push({ path: key, reason: `blob ${to.hash} missing (store integrity)` });
                        continue;
                    }
                    target = { bytes, hash: to.hash };
                }
                let applied;
                try {
                    applied = await applyFileRestoreViaEnv(env, resolved.abs, target, {
                        root,
                        ...(to.kind === "bytes" && to.mode !== undefined ? { mode: to.mode } : {}),
                        ...(to.parentIdent !== undefined ? { parentIdent: to.parentIdent } : {}),
                        ...(signal !== undefined ? { signal } : {}),
                        ...(options?.unplacedHistoryRecordedUnder !== undefined ? { unplacedHistoryRecordedUnder: options.unplacedHistoryRecordedUnder } : {}),
                    });
                }
                catch (err) {
                    applied = { outcome: "failed", reason: thrownText(err) };
                }
                if (applied.outcome === "applied")
                    ledger.filesChanged.push(key);
                else if (applied.outcome === "identical")
                    ledger.identicalSkipped.push(key);
                else if (applied.outcome === "refused")
                    ledger.refused.push({ path: key, reason: applied.reason, class: applied.class, ...(applied.action !== undefined ? { action: applied.action } : {}), ...(applied.recordedUnder !== undefined ? { recordedUnder: applied.recordedUnder } : {}) });
                else if (applied.outcome === "left")
                    (ledger.leftAsIs ??= []).push({ path: key, ...applied.left });
                else
                    ledger.failed.push({ path: key, reason: applied.reason });
                if ((applied.outcome === "applied" || applied.outcome === "identical") && applied.modeNotPreserved === true)
                    modeNotPreserved++;
            }
            return { outcome: ledger.refused.length > 0 || ledger.failed.length > 0 ? "partial" : "complete", ...ledger, ...(modeNotPreserved > 0 ? { modeNotPreserved } : {}) };
        }
        catch (err) {
            const touched = empty.filesChanged.length > 0 || empty.identicalSkipped.length > 0 || empty.refused.length > 0 || empty.failed.length > 0;
            return { outcome: touched ? "partial" : "failed", ...empty, error: { code: "restore_failed", message: thrownText(err), ...caughtFault(err) } };
        }
    }
    async canRestore(scope, entryId) {
        return this.scopes.get(scope)?.boundaries.has(entryId) ?? false;
    }
    async readBoundaries(scope, entryIds) {
        try {
            const sc = this.scopes.get(scope);
            const boundaries = new Map();
            let keys;
            for (const entryId of entryIds) {
                if (boundaries.has(entryId))
                    continue;
                const boundary = sc?.boundaries.get(entryId);
                if (sc === undefined || boundary === undefined) {
                    boundaries.set(entryId, { ok: true, boundary: null });
                    continue;
                }
                keys ??= [...sc.tracked.keys()].sort();
                const entries = keys.map((key) => {
                    const t = sc.tracked.get(key);
                    return { key, keyDesc: { ...t.keyDesc }, target: fileHistoryTargetOf({ key, desc: t.keyDesc, baseAvailable: t.baseAvailable, versions: t.versions }, boundary.get(key)) };
                });
                boundaries.set(entryId, { ok: true, boundary: { entries } });
            }
            return { ok: true, boundaries };
        }
        catch (err) {
            return { ok: false, error: { code: "restore_failed", message: `the history boundaries of scope "${scope}" could not be read: ${thrownText(err)}`, ...caughtFault(err) } };
        }
    }
    async reap(scope, keepEntryIds) {
        const sc = this.scopes.get(scope);
        if (sc === undefined) {
            this.collectBlobs(true);
            return 0;
        }
        const keep = new Set(keepEntryIds);
        let removed = 0;
        for (const id of [...sc.boundaries.keys()]) {
            if (!keep.has(id)) {
                sc.boundaries.delete(id);
                sc.reapedEntries.add(id);
                removed++;
            }
        }
        const referenced = new Map();
        for (const mapping of sc.boundaries.values()) {
            for (const [key, v] of mapping) {
                let s = referenced.get(key);
                if (s === undefined)
                    referenced.set(key, (s = new Set()));
                s.add(v);
            }
        }
        for (const [key, t] of sc.tracked) {
            const refs = referenced.get(key);
            t.versions = t.versions.filter((v) => v.version === 1 || (refs?.has(v.version) ?? false) || fileHistoryEntryFrozen({ key, desc: t.keyDesc, versions: [v] }) !== undefined);
        }
        this.collectBlobs(true);
        return removed;
    }
    async deleteBySession(scope) {
        if (this.writers.has(scope)) {
            throw Object.assign(new Error(`file history scope "${scope}" has a write in flight in this store (a capture, a first-touch record, a retraction or an import) — a session's history is erased when no leg of it runs`), { code: "conflict" });
        }
        const sc = this.scopes.get(scope);
        let removed = 0;
        if (sc !== undefined) {
            removed = sc.boundaries.size;
            for (const t of sc.tracked.values())
                removed += t.versions.length;
            this.scopes.delete(scope);
        }
        this.collectBlobs(false);
        return removed;
    }
    async deleteUnreadableSessionHistory(sessionId) {
        const id = readUnreadableDeleteId("FileHistoryStore.deleteUnreadableSessionHistory", sessionId);
        const owned = [...new Set([...this.scopes.keys(), ...this.writers.keys()])].filter((scope) => readFileHistoryScope(scope)?.sessionId === id);
        const busy = owned.find((scope) => this.writers.has(scope));
        if (busy !== undefined)
            return this.deleteBySession(busy);
        let removed = 0;
        for (const scope of owned)
            removed += await this.deleteBySession(scope);
        if (owned.length === 0)
            this.collectBlobs(false);
        return removed;
    }
    collectBlobs(byAge) {
        const live = new Set(this.inFlightBlobs.keys());
        for (const s of this.scopes.values()) {
            for (const t of s.tracked.values())
                for (const v of t.versions)
                    if (v.blobHash !== null)
                        live.add(v.blobHash);
        }
        const now = byAge ? this.now() : 0;
        for (const h of [...this.blobs.keys()]) {
            if (live.has(h))
                continue;
            const at = this.blobAt.get(h);
            if (byAge && at !== undefined && now - at < FILE_HISTORY_UNREFERENCED_BLOB_GRACE_MS)
                continue;
            this.blobs.delete(h);
            this.blobAt.delete(h);
        }
    }
    async adoptScope(fromScope, toScope) {
        try {
            if (fromScope === toScope)
                return { ok: true };
            const from = this.scopes.get(fromScope);
            const to = this.scopes.get(toScope);
            if (to !== undefined && (to.tracked.size > 0 || to.boundaries.size > 0)) {
                return { ok: false, error: { code: "conflict", message: `adoptScope target "${toScope}" already has history of its own — adoption is legal only onto an EMPTY scope (the fork/resume boundary before the new session's first turn)` } };
            }
            if (from === undefined || (from.tracked.size === 0 && from.boundaries.size === 0)) {
                if (from !== undefined && from.reapedEntries.size > 0) {
                    const target = this.scope(toScope);
                    for (const id of from.reapedEntries)
                        target.reapedEntries.add(id);
                }
                return { ok: true };
            }
            const copy = { tracked: new Map(), boundaries: new Map(), spentAttempts: new Set(), activeAttempts: new Set(), reapedEntries: new Set([...from.reapedEntries, ...(to?.reapedEntries ?? [])]) };
            for (const [key, t] of from.tracked) {
                if (fileHistoryEntryTravels(t.keyDesc))
                    copy.tracked.set(key, { baseAvailable: t.baseAvailable, keyDesc: { ...t.keyDesc }, ...(t.observedByLaterTouch === true ? { observedByLaterTouch: true } : {}), versions: t.versions.map((v) => ({ ...v })) });
            }
            for (const [id, mapping] of from.boundaries)
                copy.boundaries.set(id, new Map([...mapping].filter(([key]) => copy.tracked.has(key))));
            this.scopes.set(toScope, copy);
            return { ok: true };
        }
        catch (err) {
            return { ok: false, error: { code: "adopt_failed", message: `adoptScope failed: ${thrownText(err)}`, ...caughtFault(err) } };
        }
    }
    async exportHistory(scope) {
        const sc = this.scopes.get(scope);
        return { ok: true, history: sc === undefined || (sc.tracked.size === 0 && sc.boundaries.size === 0) ? null : this.exportOf(sc) };
    }
    exportOf(sc) {
        const travels = [...sc.tracked.entries()].filter(([, t]) => fileHistoryEntryTravels(t.keyDesc));
        const omitted = sc.tracked.size - travels.length;
        const frozenKeys = travels.filter(([key, t]) => fileHistoryEntryFrozen({ key, desc: t.keyDesc, versions: t.versions }) !== undefined).map(([key]) => key).sort();
        const kept = new Set(travels.map(([key]) => key).filter((key) => !frozenKeys.includes(key)));
        return {
            formatVersion: "file-history/1",
            ...(omitted > 0 ? { absoluteEntriesOmitted: omitted } : {}),
            ...(frozenKeys.length > 0 ? { frozenEntryKeys: frozenKeys } : {}),
            tracked: travels
                .filter(([key]) => kept.has(key))
                .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
                .map(([key, t]) => ({
                relOrAbsPath: key,
                keyKind: t.keyDesc.kind,
                keyFamily: t.keyDesc.family,
                baseAvailable: t.baseAvailable,
                versions: t.versions.map((v) => ({ version: v.version, blobHash: v.blobHash, ...(v.mode !== undefined ? { mode: v.mode } : {}), ...(v.parentIdent !== undefined && fileHistoryParentIdentTravels(v.parentIdent) ? { parentIdent: v.parentIdent } : {}), backupTime: v.backupTime })),
            })),
            boundaries: [...sc.boundaries.entries()]
                .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
                .map(([entryId, mapping]) => ({ entryId, files: [...mapping.entries()].filter(([key]) => kept.has(key)).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([relOrAbsPath, version]) => ({ relOrAbsPath, version })) })),
        };
    }
    importHistory(scope, data, srcGetBlob) {
        return this.writing(scope, () => this.importHistoryCounted(scope, data, srcGetBlob));
    }
    async importHistoryCounted(scope, data, srcGetBlob) {
        try {
            const shaped = validateFileHistoryExport(data);
            if (!shaped.ok)
                return shaped;
            const existing = this.scopes.get(scope);
            if (existing !== undefined && (existing.tracked.size > 0 || existing.boundaries.size > 0)) {
                if (fileHistoryExportDigest(this.exportOf(existing)) === fileHistoryExportDigest(data))
                    return { ok: true };
                return { ok: false, error: { code: "conflict", message: `importHistory target "${scope}" already holds a DIFFERENT history — a first import requires an empty target and a retry is legal only for the identical envelope (atomic visibility prevents half-graphs; this law prevents publishing the wrong complete graph over locally-grown history)` } };
            }
            const needed = new Set();
            for (const t of data.tracked)
                for (const v of t.versions)
                    if (v.blobHash !== null)
                        needed.add(v.blobHash);
            for (const hash of needed)
                this.leaseBlob(hash);
            try {
                return await this.importStaged(scope, data, srcGetBlob, needed);
            }
            finally {
                for (const hash of needed)
                    this.releaseBlob(hash);
            }
        }
        catch (err) {
            return { ok: false, error: { code: "adopt_failed", message: `importHistory failed: ${thrownText(err)}`, ...caughtFault(err) } };
        }
    }
    async importStaged(scope, data, srcGetBlob, needed) {
        try {
            const staged = new Map();
            for (const hash of needed) {
                if (this.blobs.has(hash))
                    continue;
                let bytes;
                try {
                    bytes = await srcGetBlob(hash);
                }
                catch (err) {
                    return { ok: false, error: { code: "adopt_failed", message: `source blob ${hash} fetch failed: ${thrownText(err)}`, ...caughtFault(err) } };
                }
                if (bytes === undefined)
                    return { ok: false, error: { code: "adopt_failed", message: `source blob ${hash} is missing — the envelope's graph cannot be completed, so nothing is published` } };
                if (createHash("sha256").update(bytes).digest("hex") !== hash) {
                    return { ok: false, error: { code: "adopt_failed", message: `source blob ${hash} fails content-address integrity — refused, nothing published` } };
                }
                const over = overLimit(blobOverStoreLimit(bytes, this.maxBlobBytes, `source blob ${hash}`));
                if (over !== undefined)
                    return over;
                staged.set(hash, bytes);
            }
            const live = this.scopes.get(scope);
            if (live !== undefined && (live.tracked.size > 0 || live.boundaries.size > 0)) {
                const now = this.exportOf(live);
                if (fileHistoryExportDigest(now) === fileHistoryExportDigest(data))
                    return { ok: true };
                return { ok: false, error: { code: "conflict", message: `importHistory target "${scope}" gained a DIFFERENT history while this import was fetching blobs — nothing was published` } };
            }
            for (const [hash, bytes] of staged)
                this.holdBlob(hash, bytes);
            const built = { tracked: new Map(), boundaries: new Map(), spentAttempts: new Set(), activeAttempts: new Set(), reapedEntries: new Set(live?.reapedEntries ?? []) };
            for (const t of data.tracked) {
                built.tracked.set(t.relOrAbsPath, {
                    baseAvailable: t.baseAvailable,
                    keyDesc: { kind: t.keyKind, family: t.keyFamily },
                    versions: t.versions.map((v) => ({ version: v.version, blobHash: v.blobHash, ...(v.mode !== undefined ? { mode: v.mode } : {}), ...(v.parentIdent !== undefined ? { parentIdent: v.parentIdent } : {}), backupTime: v.backupTime })),
                });
            }
            for (const b of data.boundaries)
                built.boundaries.set(b.entryId, new Map(b.files.map((f) => [f.relOrAbsPath, f.version])));
            this.scopes.set(scope, built);
            return { ok: true };
        }
        catch (err) {
            return { ok: false, error: { code: "adopt_failed", message: `importHistory failed: ${thrownText(err)}`, ...caughtFault(err) } };
        }
    }
}
export function restoreMovedOf(seen) {
    return seen.asked.done > 0 ? "some" : seen.asked.issued > 0 ? "unknown" : "none";
}
function foldedFile(p) {
    return foldedSpelling(isWinFormPath(p) ? normSlash(p) : p);
}
function frozenFileOf(row, targetOf) {
    return joinUnder(row.place, lastSegmentOf(targetOf(row.path)));
}
function holdsOf(leftAsIs, targetOf) {
    const holds = new Map();
    for (const row of leftAsIs) {
        if (row.class !== "frozen_history")
            continue;
        const file = frozenFileOf(row, targetOf);
        const at = holds.get(foldedFile(file));
        if (at === undefined)
            holds.set(foldedFile(file), { file, frozenKeys: [row.path] });
        else
            at.frozenKeys.push(row.path);
    }
    return holds;
}
function heldWriteReason(file, frozenKeys) {
    return `not restored: this file (${file}) also has a history an earlier version recorded through a link (${frozenKeys.join(", ")}: frozen), and a rewind writes or deletes such a file under no key — the version this key holds may not be this turn's; neither key wrote or deleted it, so it stays as it is; restore it by hand if it must be`;
}
const FORK_OUTSIDE_ROOT_LEFT_REASON = "this session was forked from another, and a fork's rewind leaves every file outside its root as it is — neither written nor deleted — it is listed here so you can restore it by hand or from the source session";
const FORK_ROOT_UNREADABLE_REASON = "not restored: this session was forked from another, and the rewind root's real path could not be read, so whether this file lies inside the fork's root cannot be told — it was neither written nor deleted; to restore it, check that the rewind root still exists and can be reached, then rewind again — or restore the file by hand";
const REAL_PATH_SEAT = Symbol("file-history restore: the real path of a mutation");
async function noteRealPath(env, at, real, signal) {
    const seat = Reflect.get(env, REAL_PATH_SEAT);
    if (typeof seat !== "function")
        return undefined;
    const verdict = await Reflect.apply(seat, undefined, [at, real, signal]);
    return verdict !== null && typeof verdict === "object" && "kind" in verdict ? verdict : undefined;
}
const PLANNED_STATE_SEAT = Symbol("file-history restore: the state a plan read");
function notePlannedState(env, at, state) {
    const seat = Reflect.get(env, PLANNED_STATE_SEAT);
    return typeof seat === "function" && Reflect.apply(seat, undefined, [at, state]) === true;
}
const CHANGED_SINCE_PLAN_REASON = "not restored: this file is not as the rewind's plan read it a moment before (another writer changed or removed it in between, or the version to restore is another), so it was neither written nor deleted — what is there now stays; rewind again (a preview first) to restore it as it now stands";
const PLAN_READS = new Set(["absolutePath", "joinPath", "readTextFile", "readTextLines", "readBinaryFile", "fileInfo", "listDir", "canonicalPath", "readLink", "canonicalChain", "fileIdentity", "openBound", "exists"]);
const PLAN_MUTATIONS = { writeFile: "write", writeFileGuarded: "write", writeFileExclusive: "write", appendFile: "write", remove: "delete", setFileMode: "mode", createDir: "none" };
function envViewOf(env, perform, holds, planned, leaveOutsideRoot) {
    const mutations = [];
    const held = [];
    const reals = new Map();
    const asked = { issued: 0, done: 0 };
    const states = new Map();
    const occurrences = new Map();
    let rootRealPromise;
    const realRoot = (signal) => (rootRealPromise ??= placeOfDirViaEnv(env, leaveOutsideRoot, signal));
    const view = new Proxy(env, {
        get(target, prop, receiver) {
            if (prop === PLANNED_STATE_SEAT) {
                return (at, state) => {
                    const n = occurrences.get(at) ?? 0;
                    occurrences.set(at, n + 1);
                    const slot = `${at}\u0000${n}`;
                    if (!perform) {
                        states.set(slot, state);
                        return false;
                    }
                    if (planned === undefined)
                        return false;
                    const real = reals.get(at);
                    if (real !== undefined && mutations.some((m) => m.real !== undefined && foldedFile(m.real) === foldedFile(real)))
                        return false;
                    return planned.get(slot) !== state;
                };
            }
            if (prop === REAL_PATH_SEAT) {
                return async (at, real, signal) => {
                    if (leaveOutsideRoot !== undefined) {
                        if (signal?.aborted)
                            return undefined;
                        const rootReal = await realRoot(signal);
                        if (rootReal === undefined)
                            return { kind: "refuse", claim: () => FORK_ROOT_UNREADABLE_REASON };
                        const place = parentDirOf(real) ?? real;
                        if (outsideRootOf(rootReal, place)) {
                            return { kind: "left", left: { class: "recorded_outside_root", place, reason: FORK_OUTSIDE_ROOT_LEFT_REASON } };
                        }
                    }
                    const hold = holds?.get(foldedFile(real));
                    if (hold === undefined) {
                        reals.set(at, real);
                        return undefined;
                    }
                    return {
                        kind: "refuse",
                        claim: () => {
                            held.push({ at, real, file: hold.file });
                            return heldWriteReason(hold.file, hold.frozenKeys);
                        },
                    };
                };
            }
            const value = Reflect.get(target, prop, receiver);
            if (typeof value !== "function" || typeof prop !== "string")
                return value;
            const fn = value;
            const kind = Object.prototype.hasOwnProperty.call(PLAN_MUTATIONS, prop) ? PLAN_MUTATIONS[prop] : undefined;
            if (kind !== undefined) {
                return (...args) => {
                    const at = args[0];
                    const note = () => {
                        if (kind !== "none" && typeof at === "string") {
                            const real = reals.get(at);
                            mutations.push({ at, ...(real !== undefined ? { real } : {}), action: kind, ...(kind === "write" && args[1] instanceof Uint8Array ? { bytes: args[1] } : {}) });
                        }
                    };
                    if (!perform) {
                        note();
                        return Promise.resolve({ ok: true, value: undefined });
                    }
                    const hasHolds = holds !== undefined && holds.size > 0;
                    if (kind !== "none" && (leaveOutsideRoot !== undefined || hasHolds) && typeof at === "string" && !reals.has(at)) {
                        const why = hasHolds && leaveOutsideRoot !== undefined
                            ? "belongs to a forked session (leaving every file outside its root as it is) and holds files a frozen history names"
                            : hasHolds
                                ? "holds files a frozen history names"
                                : "belongs to a forked session and leaves every file outside its root as it is";
                        return Promise.resolve({ ok: false, error: { code: "precondition_failed", message: `a rewind that ${why} performs no write it cannot place, and this one (${at}) did not state where it lands` } });
                    }
                    asked.issued++;
                    return Promise.resolve(fn.apply(target, args)).then((r) => {
                        if (r !== null && typeof r === "object" && r.ok === true) {
                            asked.done++;
                            note();
                        }
                        else if (prop === "writeFileGuarded" && readMember(readMember(r, "error"), "code") === "precondition_failed") {
                            asked.issued--;
                        }
                        return r;
                    });
                };
            }
            if (PLAN_READS.has(prop))
                return fn.bind(target);
            if (perform) {
                return (...args) => {
                    asked.issued++;
                    return fn.apply(target, args);
                };
            }
            return () => Promise.resolve({ ok: false, error: { code: "unsupported", message: `a planned restore reached ${prop}, which a plan does not perform` } });
        },
    });
    return { env: view, mutations, held, told: reals, asked, states };
}
export function witnessEnvOf(env, holds, planned, leaveOutsideRoot) {
    return envViewOf(env, true, holds, planned, leaveOutsideRoot);
}
function oldRootOf(place, key) {
    const dirs = relativeInEveryFamily(key) ? key.split("/").length - 1 : 0;
    let root = place;
    for (let i = 0; i < dirs; i++)
        root = parentDirOf(root) ?? root;
    return root;
}
const REFUSED_WHEN_MOVED = {
    recorded_outside_root: {
        class: "recorded_elsewhere",
        recordedUnder: true,
        moved: (row, seen, rewound) => seen.mutations.some((m) => m.real !== undefined && !outsideRootOf(oldRootOf(row.place, row.path), m.real) && outsideRootOf(rewound.root, m.real)),
        reason: (row) => `not restored: this rewind restores another key's file under ${oldRootOf(row.place, row.path)}, where this version was recorded, so it does not leave this one behind as it is; rewind from ${oldRootOf(row.place, row.path)} to restore it`,
    },
    frozen_history: {
        class: "link_safety",
        recordedUnder: false,
        moved: (row, seen, rewound) => seen.held.some((h) => foldedFile(h.file) === foldedFile(rewound.fileOf(row))),
        reason: (row, rewound) => `not restored: its history was recorded through a link (frozen), and the same file (${rewound.fileOf(row)}) is tracked a second time under another key, whose version may not be this turn's — neither key wrote or deleted it, so it stays as it is; restore it by hand if it must be`,
    },
};
const UNPLACED_WRITE_REASON = "not restored: this restore asked a write whose real path could not be read (its store did not hand that file to the shared restore step on the env it was handed), so whether that write lands where this file lies cannot be told — this key's version was neither written nor deleted; restore it by hand if it must be";
function leftOnlyWhereUntouched(restored, seen, targetOf, root) {
    const rewound = { root, fileOf: (row) => frozenFileOf(row, targetOf) };
    const unplaced = seen.mutations.some((m) => m.real === undefined);
    const movedByClass = (row) => REFUSED_WHEN_MOVED[row.class].moved(row, seen, rewound);
    const moved = (row) => unplaced || movedByClass(row);
    const aliased = (restored.leftAsIs ?? []).filter(moved);
    if (aliased.length === 0)
        return restored;
    const { leftAsIs: all, ...rest } = restored;
    const left = (all ?? []).filter((row) => !moved(row));
    return {
        ...rest,
        outcome: rest.outcome === "complete" ? "partial" : rest.outcome,
        refused: [
            ...rest.refused,
            ...aliased.map((row) => {
                const as = REFUSED_WHEN_MOVED[row.class];
                return { path: row.path, class: as.class, ...(as.recordedUnder ? { recordedUnder: row.place } : {}), reason: movedByClass(row) ? as.reason(row, rewound) : UNPLACED_WRITE_REASON };
            }),
        ],
        ...(left.length > 0 ? { leftAsIs: left } : {}),
    };
}
export function rewindTargetOf(root) {
    return (key) => {
        const r = resolveTrackKey(root, key);
        return r.ok ? r.abs : joinUnder(root, isWinFormPath(root) ? normSlash(key) : key);
    };
}
export function mutationIndexOf(mutations) {
    const at = new Map();
    for (const m of mutations) {
        const list = at.get(m.at);
        if (list === undefined)
            at.set(m.at, [m]);
        else
            list.push(m);
    }
    return (targetPath) => at.get(targetPath) ?? [];
}
export function withRewindFiles(storeAnswer, seen, root) {
    const { mutations } = seen;
    const targetOf = rewindTargetOf(root);
    const restored = leftOnlyWhereUntouched(storeAnswer, seen, targetOf, root);
    const realAt = new Map(seen.told);
    for (const h of seen.held)
        realAt.set(h.at, h.real);
    const outside = (targetPath) => ({ outsideRoot: outsideRootOf(root, realAt.get(targetPath) ?? targetPath) });
    const mutationsAt = mutationIndexOf(mutations);
    const files = [
        ...restored.filesChanged.map((key) => {
            const targetPath = targetOf(key);
            return { path: key, targetPath, action: mutationsAt(targetPath).some((m) => m.action === "delete") ? "delete" : "write", ...outside(targetPath) };
        }),
        ...restored.refused.map((row) => {
            const targetPath = targetOf(row.path);
            return {
                path: row.path,
                targetPath,
                ...(row.action !== undefined ? { action: row.action } : {}),
                refused: { class: row.class, reason: row.reason, ...(row.recordedUnder !== undefined ? { recordedUnder: row.recordedUnder } : {}) },
                ...outside(targetPath),
            };
        }),
        ...restored.failed.flatMap((row) => {
            const targetPath = targetOf(row.path);
            const landed = mutationsAt(targetPath).find((m) => m.action !== "mode");
            return landed === undefined ? [] : [{ path: row.path, targetPath, action: landed.action === "delete" ? "delete" : "write", failed: { reason: row.reason }, ...outside(targetPath) }];
        }),
    ];
    const { leftAsIs: storeLeft, ...ledger } = restored;
    const leftAsIs = storeLeft?.map((row) => ({ ...row, outsideRoot: outsideRootOf(root, row.place) }));
    return { ...ledger, ...(leftAsIs !== undefined ? { leftAsIs } : {}), files };
}
export async function planFileHistoryRestore(store, input) {
    const options = restoreOptionsAt(input.options, input.root);
    const leaveOutsideRoot = input.forkedSession === true ? input.root : undefined;
    const pass = async (holds) => {
        const planning = envViewOf(input.env, false, holds, undefined, leaveOutsideRoot);
        const restored = await store.restore(input.scope, input.entryId, planning.env, input.root, input.signal, options);
        return { planning, stored: restored, answered: withRewindFiles(restored, planning, input.root) };
    };
    const first = await pass(undefined);
    const holds = holdsOf(first.stored.leftAsIs ?? [], rewindTargetOf(input.root));
    const hasUnplaced = first.planning.mutations.some((m) => m.real === undefined);
    const unread = holds.size > 0 && hasUnplaced;
    const unplacedForFork = leaveOutsideRoot !== undefined && hasUnplaced;
    const reaches = !unread && !unplacedForFork && first.planning.mutations.some((m) => m.real !== undefined && holds.has(foldedFile(m.real)));
    const { planning, answered } = reaches ? await pass(holds) : first;
    let insertions = 0;
    let deletions = 0;
    const changes = [];
    for (const m of planning.mutations) {
        if (m.action === "mode") {
            changes.push({ at: m.at, action: "mode" });
            continue;
        }
        const target = m.action === "write" ? m.bytes : undefined;
        const notRead = { at: m.at, action: m.action, ...(target !== undefined ? { target } : {}), current: undefined };
        let cur;
        try {
            cur = await input.env.readBinaryFile(m.at, input.signal);
        }
        catch {
            changes.push(notRead);
            continue;
        }
        if (!cur.ok && cur.error.code !== "not_found") {
            changes.push(notRead);
            continue;
        }
        const delta = countRestoreLineDiff(cur.ok ? cur.value : undefined, target);
        const current = cur.ok ? { size: cur.value.byteLength, binary: bytesAreBinary(cur.value) } : null;
        if (m.action === "delete" || target !== undefined)
            input.readCurrent?.(m.at, cur.ok ? cur.value : null, target ?? null);
        changes.push({ at: m.at, action: m.action, ...(target !== undefined ? { target } : {}), current, lines: delta });
        insertions += delta.insertions;
        deletions += delta.deletions;
    }
    return {
        restore: answered,
        diffStats: { filesChanged: answered.filesChanged, insertions, deletions, files: answered.files, refused: answered.refused, failed: answered.failed, ...(answered.leftAsIs !== undefined && answered.leftAsIs.length > 0 ? { leftAsIs: answered.leftAsIs } : {}) },
        holds,
        states: planning.states,
        ...(unread ? { unheld: [...new Set([...holds.values()].flatMap((h) => h.frozenKeys))].sort() } : {}),
        ...(unplacedForFork ? { unplacedForFork: true } : {}),
        changes,
    };
}
export async function listFrozenFileHistoryEntries(store, scope) {
    if (typeof store?.exportHistory !== "function") {
        throw Object.assign(new Error("listFrozenFileHistoryEntries: the store has no exportHistory, so its frozen entries cannot be listed"), { code: "config.invalid_argument" });
    }
    const exported = await store.exportHistory(scope);
    if (!exported.ok)
        throw new FileHistoryStoreError(exported.error, `listFrozenFileHistoryEntries: the history of scope "${scope}" cannot be read whole (${exported.error.code})`);
    return { keys: [...(exported.history?.frozenEntryKeys ?? [])].sort() };
}
export const __testables = { joinUnder, relUnder, stripTrailSep, trackKeyOf, resolveTrackKey, parentDirOf };