UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,607 lines • 85.1 kB
import { createHash, randomBytes } from "node:crypto";
import { closeSync, existsSync, fsyncSync, lstatSync, statSync } from "node:fs";
import { appendFileSync, openSync, readdirSync, readFileSync, renameSync, rmSync, unlinkSync, utimesSync, writeFileSync } from "./descriptor-seat.js";
import { join, relative } from "node:path";
import { callerText } from "../../core/caller-text.js";
import { thrownText } from "../../core/thrown-value.js";
import { readUnreadableDeleteId } from "../../core/session.js";
import { readFileHistoryScope } from "../../engine/session/repo-utils.js";
import { applyFileRestoreViaEnv, boundaryPublishVerdict, worldStillMatchesMint, annulProofFailure, captureFileBackupViaEnv, modeProvenDifferent, placeProvenDifferent, blobPutRefusal, blobOverStoreLimit, overLimit, readMaxBlobBytes, fileHistoryEntryFrozen, fileHistoryEntryTravels, fileHistoryParentIdentTravels, fileHistoryExportDigest, fileHistoryTargetOf, caughtFault, DAMAGED_RECORD, FILE_HISTORY_UNREFERENCED_BLOB_GRACE_MS, isBlobAddress, resolveTrackKey, resolveTrackedFile, trackKeyForAnnul, trackKeyForEdit, validateFileHistoryExport, } from "../../core/file-history-store.js";
import { fileHistoryBoundariesToKeep, resolveFileHistoryRetention } from "../../core/file-history-retention.js";
import { assertWellFormedKey, atomicWriteFile, ensureDir, sanitizePathComponent, sanitizeScope, scopeLabelOf, writeThenLink } from "./fs-atomic.js";
import { holdsUnpairedSurrogate, unpairedSurrogateRefusal } from "../../core/principal-name.js";
import { guardCorruptSink } from "./corrupt-read-sink.js";
import { isAbsoluteForFamily } from "../../tools/fs/safety.js";
import { assertAdoptionBootGate } from "./adoption/marker.js";
import { optionKeys, receiveOptions } from "../../core/own-property-receipt.js";
import { HolderLatch, closedHolderRefusal } from "../../core/holder-latch.js";
const FILE_FILE_HISTORY_STORE_OPTION_KEYS = optionKeys()({ onCorruptRead: 0, retention: 0, maxBlobBytes: 0 });
function trackedDigest(rows) {
    const canonical = [...rows]
        .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
        .map(([key, rec]) => [
        key,
        {
            baseAvailable: rec.baseAvailable,
            mintId: rec.mintId ?? null,
            keyKind: rec.keyKind ?? null,
            keyFamily: rec.keyFamily ?? null,
            observedByLaterTouch: rec.observedByLaterTouch === true,
            versions: [...rec.versions]
                .sort((x, y) => x.version - y.version)
                .map((v) => ({ version: v.version, blobHash: v.blobHash, mode: v.mode ?? null, parentIdent: v.parentIdent ?? null, backupTime: v.backupTime })),
        },
    ]);
    return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
}
function boundaryDigest(files) {
    const canonical = [...files].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
    return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
}
const EMPTY_LEDGER = () => ({
    filesChanged: [],
    identicalSkipped: [],
    refused: [],
    failed: [],
});
const WINDOWS_DEVICE_NAMES = new Set(["con", "prn", "aux", "nul", ...Array.from({ length: 10 }, (_, i) => `com${i}`), ...Array.from({ length: 10 }, (_, i) => `lpt${i}`)]);
function firstLinkIn(dir) {
    let isDir;
    try {
        const st = lstatSync(dir);
        if (st.isSymbolicLink())
            return dir;
        isDir = st.isDirectory();
    }
    catch (err) {
        if (err.code === "ENOENT")
            return undefined;
        throw err;
    }
    if (!isDir)
        return undefined;
    let names;
    try {
        names = readdirSync(dir);
    }
    catch (err) {
        if (err.code === "ENOENT")
            return undefined;
        throw err;
    }
    for (const name of names) {
        const found = firstLinkIn(join(dir, name));
        if (found !== undefined)
            return found;
    }
    return undefined;
}
function historyPathComponent(raw) {
    const safe = sanitizePathComponent(raw);
    if (safe.length > 200)
        throw new Error(`file history: path component is too long (${safe.length} > 200): ${JSON.stringify(raw.slice(0, 32))}…`);
    if (WINDOWS_DEVICE_NAMES.has(safe.split(".")[0].toLowerCase()))
        throw new Error(`file history: ${JSON.stringify(safe)} is a reserved device name — it would address a device, not a record`);
    if (!/^[A-Za-z0-9_]/.test(safe))
        throw new Error(`file history: path component must start with a letter, digit or underscore: ${JSON.stringify(safe)}`);
    return safe;
}
function descriptorOf(rec) {
    return rec.keyKind !== undefined && rec.keyFamily !== undefined ? { kind: rec.keyKind, family: rec.keyFamily } : undefined;
}
function declaredDescriptorOf(key, rec) {
    const family = rec.keyFamily ?? "posix";
    return { kind: rec.keyKind ?? (isAbsoluteForFamily(family, key) ? "absolute" : "root-relative"), family };
}
const STALE_JOURNAL_MS = 60 * 60 * 1000;
function pidIsAlive(pid) {
    if (!Number.isInteger(pid) || pid <= 0)
        return false;
    try {
        process.kill(pid, 0);
        return true;
    }
    catch (err) {
        return err.code === "EPERM";
    }
}
function parseJsonRecord(raw) {
    let parsed;
    try {
        parsed = JSON.parse(raw);
    }
    catch {
        return null;
    }
    return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
}
function leaseJournalBlob(line, live) {
    const rec = parseJsonRecord(line);
    if (rec !== null && typeof rec.blob === "string")
        live.add(rec.blob);
}
function isTrackedPair(el) {
    if (!Array.isArray(el) || el.length !== 2 || typeof el[0] !== "string")
        return false;
    const rec = el[1];
    if (typeof rec !== "object" || rec === null || Array.isArray(rec))
        return false;
    const versions = rec.versions;
    return Array.isArray(versions) && versions.every((v) => typeof v === "object" && v !== null && !Array.isArray(v));
}
function trackedRowsOf(parsed) {
    if (parsed === null || !Array.isArray(parsed.tracked))
        return null;
    const rows = [];
    for (const el of parsed.tracked) {
        if (!isTrackedPair(el))
            return null;
        rows.push(el);
    }
    return rows;
}
function nestedSetAdd(map, scope, value) {
    let inner = map.get(scope);
    if (inner === undefined)
        map.set(scope, (inner = new Set()));
    inner.add(value);
}
function nestedMapSet(map, scope, key, value) {
    let inner = map.get(scope);
    if (inner === undefined)
        map.set(scope, (inner = new Map()));
    inner.set(key, value);
}
function worstFault(faults) {
    const terminal = faults.find((f) => f.permanence === "terminal");
    if (terminal !== undefined)
        return terminal;
    return faults.length > 0 && faults.every((f) => f.permanence === "transient") ? faults[0] : {};
}
function safeRm(path) {
    try {
        let link = false;
        try {
            link = lstatSync(path).isSymbolicLink();
        }
        catch {
        }
        if (link)
            unlinkSync(path);
        else
            rmSync(path, { force: true, recursive: true });
        return true;
    }
    catch {
        return false;
    }
}
const BLOB_NAME_HOLDS_NO_FILE = new Set(["ENOENT", "EISDIR", "ELOOP"]);
export class FileFileHistoryStore {
    base;
    blobsDir;
    scopesDir;
    onCorruptRead;
    spentAttempts = new Map();
    activeCaptures = new Map();
    activeImports = new Map();
    writers = new Map();
    latch = new HolderLatch(this);
    closedArm(code, verb) {
        if (!this.latch.closed)
            return undefined;
        return { ok: false, error: { code, message: `${closedHolderRefusal(`FileFileHistoryStore.${verb}`).message} (nothing was persisted)` } };
    }
    reapedCache = new Map();
    boundaryKeep;
    maxBlobBytes;
    lastCommittedAt = 0;
    seededScopes = new Set();
    nextCommittedAt(scope) {
        if (!this.seededScopes.has(scope)) {
            this.seededScopes.add(scope);
            const dir = this.boundaryDir(scope);
            try {
                for (const f of readdirSync(dir)) {
                    if (!f.endsWith(".json"))
                        continue;
                    const order = this.boundaryOrderOf(join(dir, f));
                    if (order !== undefined && order > this.lastCommittedAt)
                        this.lastCommittedAt = order;
                }
            }
            catch {
            }
        }
        this.lastCommittedAt = Math.max(Date.now(), this.lastCommittedAt + 1);
        return this.lastCommittedAt;
    }
    constructor(root, options) {
        const opts = receiveOptions(options, "FileFileHistoryStore", FILE_FILE_HISTORY_STORE_OPTION_KEYS);
        assertAdoptionBootGate(root, "FileFileHistoryStore");
        this.boundaryKeep = resolveFileHistoryRetention("FileFileHistoryStore", opts?.retention);
        this.maxBlobBytes = readMaxBlobBytes("FileFileHistoryStore", opts?.maxBlobBytes);
        this.base = join(root, "file-history");
        this.blobsDir = join(this.base, "blobs");
        this.scopesDir = join(this.base, "scopes");
        ensureDir(this.blobsDir);
        ensureDir(this.scopesDir);
        this.onCorruptRead = guardCorruptSink(opts?.onCorruptRead);
    }
    applyBoundaryRetention(scope, justCommitted) {
        if (this.boundaryKeep === null)
            return;
        try {
            const dir = this.boundaryDir(scope);
            let names;
            try {
                names = readdirSync(dir).filter((f) => f.endsWith(".json"));
            }
            catch (err) {
                if (err.code !== "ENOENT") {
                    this.disclose(dir, `boundary directory unreadable (${err.code ?? "unknown"}) — the retention pass was skipped, so this scope is NOT bounded until it can be read`);
                }
                return;
            }
            if (names.length <= this.boundaryKeep)
                return;
            const readable = [];
            for (const f of names) {
                const path = join(dir, f);
                if (this.readBoundaryMapping(path) === null) {
                    this.disclose(join(dir, f), "a boundary in this scope cannot be judged — the retention pass is disabled for the WHOLE scope until it is repaired or removed, so this scope is NOT bounded (trimming around a record whose references cannot be read destroys the versions only it points at)");
                    return;
                }
                readable.push({ id: f.slice(0, -".json".length), order: this.boundaryOrderOf(path) ?? 0 });
            }
            const ordered = readable.sort((a, b) => a.order - b.order || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)).map((e) => e.id);
            const keepIds = fileHistoryBoundariesToKeep(ordered, justCommitted, this.boundaryKeep);
            if (keepIds === null)
                return;
            this.reap(scope, keepIds).catch(() => { });
        }
        catch {
        }
    }
    disclose(path, reason) {
        this.onCorruptRead?.({ kind: "file", path, reason });
    }
    scopeDir(scope) {
        return join(this.scopesDir, sanitizeScope(scope));
    }
    refusedScope(scope, code, what = "the scope") {
        return typeof scope === "string" && holdsUnpairedSurrogate(scope) ? { ok: false, error: { code, message: unpairedSurrogateRefusal(`file history: ${what}`), permanence: "terminal" } } : undefined;
    }
    trackedPath(scope) {
        return join(this.scopeDir(scope), "tracked.json");
    }
    boundaryDir(scope) {
        return join(this.scopeDir(scope), "boundaries");
    }
    tryBoundaryPath(scope, entryId) {
        try {
            return join(this.boundaryDir(scope), `${historyPathComponent(entryId)}.json`);
        }
        catch {
            return null;
        }
    }
    blobPath(hash) {
        return join(this.blobsDir, sanitizePathComponent(hash));
    }
    readTrackedState(scope) {
        const path = this.trackedPath(scope);
        let raw;
        try {
            raw = readFileSync(path, "utf8");
        }
        catch (err) {
            if (err.code === "ENOENT")
                return { corrupt: false, tracked: new Map() };
            this.disclose(path, `tracked set unreadable (${err.code ?? "unknown"}) — this scope's history is UNUSABLE until it is repaired`);
            return { corrupt: true, tracked: new Map(), fault: caughtFault(err) };
        }
        const parsed = parseJsonRecord(raw);
        if (parsed === null) {
            this.disclose(path, "unparseable tracked set (torn/zero-byte write?) — this scope's history is UNUSABLE until it is repaired");
            return { corrupt: true, tracked: new Map(), fault: DAMAGED_RECORD };
        }
        const rows = trackedRowsOf(parsed);
        if (rows === null) {
            this.disclose(path, "tracked set is not a pair array of [key, record] rows — this scope's history is UNUSABLE until it is repaired");
            return { corrupt: true, tracked: new Map(), fault: DAMAGED_RECORD };
        }
        if (parsed.digest !== undefined && (typeof parsed.digest !== "string" || parsed.digest !== trackedDigest(rows))) {
            this.disclose(path, "tracked set fails its own integrity digest (edited in place, or written by something that is not this store) — this scope's history is UNUSABLE until it is repaired");
            return { corrupt: true, tracked: new Map(), fault: DAMAGED_RECORD };
        }
        return { corrupt: false, tracked: new Map(rows) };
    }
    readTracked(scope) {
        return this.readTrackedState(scope).tracked;
    }
    writeTracked(scope, tracked) {
        const dir = this.scopeDir(scope);
        ensureDir(dir);
        const rows = [...tracked];
        const doc = { formatVersion: "file-history/1", scope, tracked: rows, digest: trackedDigest(rows) };
        atomicWriteFile(join(this.base, "tmp"), this.trackedPath(scope), JSON.stringify(doc));
    }
    readBoundaryMapping(path) {
        const read = this.readBoundaryState(path);
        return read instanceof Map ? read : null;
    }
    readBoundaryState(path) {
        let raw;
        try {
            raw = readFileSync(path, "utf8");
        }
        catch (err) {
            if (err.code === "ENOENT")
                return null;
            this.disclose(path, `boundary unreadable (${err.code ?? "unknown"}) — not a usable boundary`);
            return caughtFault(err);
        }
        {
            const doc = parseJsonRecord(raw);
            if (doc === null) {
                this.disclose(path, "unparseable boundary (torn/zero-byte write?) — not a usable boundary");
                return DAMAGED_RECORD;
            }
            if (doc.formatVersion !== "file-history/1" || !Array.isArray(doc.files)) {
                this.disclose(path, "boundary is not a file-history/1 pair array — not a usable boundary");
                return DAMAGED_RECORD;
            }
            const parsed = { formatVersion: doc.formatVersion, files: doc.files, digest: doc.digest };
            for (const pair of parsed.files) {
                if (!Array.isArray(pair) || pair.length !== 2 || typeof pair[0] !== "string" || !Number.isInteger(pair[1]) || pair[1] < 1) {
                    this.disclose(path, "boundary carries a malformed mapping row — not a usable boundary");
                    return DAMAGED_RECORD;
                }
            }
            if (new Set(parsed.files.map(([k]) => k)).size !== parsed.files.length) {
                this.disclose(path, "boundary maps the same path twice — not a usable boundary");
                return DAMAGED_RECORD;
            }
            if (typeof parsed.digest !== "string" || parsed.digest !== boundaryDigest(parsed.files)) {
                this.disclose(path, "boundary fails its own integrity digest (rows added or dropped?) — not a usable boundary");
                return DAMAGED_RECORD;
            }
            return new Map(parsed.files);
        }
    }
    boundaryCommittedAt(path) {
        try {
            const doc = parseJsonRecord(readFileSync(path, "utf8"));
            const at = doc?.committedAt;
            return typeof at === "number" && Number.isFinite(at) ? at : undefined;
        }
        catch {
            return undefined;
        }
    }
    carryConsumedIds(fromScope, toScope) {
        const spent = this.readReapedIds(fromScope);
        if (!(spent instanceof Set)) {
            this.disclose(this.reapedLogPath(fromScope), "source consumed-id ledger unreadable — the adoption is refused rather than published without its lineage's tombstones");
            return spent;
        }
        if (spent.size === 0)
            return true;
        return this.markReaped(toScope, [...spent]);
    }
    reapedLogPath(scope) {
        return `${this.scopeDir(scope)}.reaped.log`;
    }
    readReapedIds(scope) {
        const path = this.reapedLogPath(scope);
        let size;
        try {
            size = statSync(path).size;
        }
        catch (err) {
            if (err.code === "ENOENT")
                return new Set();
            this.disclose(path, `consumed-id ledger unreadable (${err.code ?? "unknown"})`);
            return caughtFault(err);
        }
        const cached = this.reapedCache.get(scope);
        if (cached !== undefined && cached.size === size)
            return cached.ids;
        try {
            const ids = new Set(readFileSync(path, "utf8")
                .split("\n")
                .map((l) => l.trim())
                .filter((l) => l !== ""));
            this.reapedCache.set(scope, { size, ids });
            return ids;
        }
        catch (err) {
            this.disclose(path, `consumed-id ledger unreadable (${err.code ?? "unknown"})`);
            return caughtFault(err);
        }
    }
    markReaped(scope, ids) {
        if (ids.length === 0)
            return true;
        const path = this.reapedLogPath(scope);
        try {
            ensureDir(this.scopesDir);
            const payload = ids.map((id) => `${id}\n`).join("");
            const fd = openSync(path, "a");
            try {
                writeFileSync(fd, payload);
                fsyncSync(fd);
            }
            finally {
                closeSync(fd);
            }
            const cached = this.reapedCache.get(scope);
            if (cached === undefined)
                this.reapedCache.delete(scope);
            else
                this.reapedCache.set(scope, { size: cached.size + Buffer.byteLength(payload, "utf8"), ids: new Set([...cached.ids, ...ids]) });
            return true;
        }
        catch (err) {
            this.disclose(path, `consumed-id ledger could not be appended (${err.code ?? "unknown"}) — the boundaries it names are NOT being reaped, so this scope is not bounded until it can be written`);
            return caughtFault(err);
        }
    }
    boundaryOrderOf(path) {
        const stamped = this.boundaryCommittedAt(path);
        if (stamped !== undefined)
            return stamped;
        try {
            return statSync(path).mtimeMs;
        }
        catch {
            return undefined;
        }
    }
    putBlob(hash, bytes) {
        try {
            writeThenLink(this.blobPath(hash), bytes);
        }
        catch (err) {
            if (err.code !== "EEXIST")
                throw err;
        }
    }
    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) {
        const closed = this.closedArm("track_failed", "trackEdit") ?? this.refusedScope(scope, "track_failed");
        if (closed !== undefined)
            return Promise.resolve(closed);
        return this.writing(scope, () => this.trackEditCounted(scope, absPath, env, root, signal));
    }
    async trackEditCounted(scope, absPath, env, root, signal) {
        try {
            const corrupt = (fault) => ({ ok: false, error: { code: "track_failed", message: `file history for scope "${scope}" is unreadable — refusing to mint a first-touch record over an unusable graph`, ...fault } });
            const keyed = this.readTrackedState(scope);
            if (keyed.corrupt)
                return corrupt(keyed.fault);
            const { key, kind, family } = await trackKeyForEdit(env, root, absPath, (k) => keyed.tracked.get(k), signal);
            const before = this.readTrackedState(scope);
            if (before.corrupt)
                return corrupt(before.fault);
            const existing = before.tracked.get(key);
            if (existing !== undefined) {
                if (existing.observedByLaterTouch !== true) {
                    existing.observedByLaterTouch = true;
                    this.writeTracked(scope, before.tracked);
                }
                return { ok: true, minted: false };
            }
            const cap = await captureFileBackupViaEnv(env, absPath, root, signal);
            const after = this.readTrackedState(scope);
            if (after.corrupt)
                return { ok: false, error: { code: "track_failed", message: `file history for scope "${scope}" became unreadable during the first-touch capture — nothing was recorded`, ...after.fault } };
            const tracked = after.tracked;
            const raced = tracked.get(key);
            if (raced !== undefined) {
                if (raced.observedByLaterTouch !== true) {
                    raced.observedByLaterTouch = true;
                    this.writeTracked(scope, tracked);
                }
                return { ok: true, minted: false };
            }
            if (cap.state === "aborted") {
                return { ok: false, error: { code: "aborted", message: `first-touch backup of ${absPath} aborted` } };
            }
            const now = new Date().toISOString();
            const mintId = randomBytes(8).toString("hex");
            if (cap.state === "unreadable") {
                tracked.set(key, { baseAvailable: false, mintId, keyKind: kind, keyFamily: family, versions: [] });
                this.writeTracked(scope, tracked);
                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.putBlob(cap.hash, cap.bytes);
                tracked.set(key, { baseAvailable: true, mintId, keyKind: kind, keyFamily: family, versions: [{ version: 1, blobHash: cap.hash, backupTime: now, ...(cap.mode !== undefined ? { mode: cap.mode } : {}), ...(cap.parentIdent !== undefined ? { parentIdent: cap.parentIdent } : {}) }] });
                this.writeTracked(scope, tracked);
                return { ok: true, minted: true };
            }
            tracked.set(key, { baseAvailable: true, mintId, keyKind: kind, keyFamily: family, versions: [{ version: 1, blobHash: null, backupTime: now, ...(cap.parentIdent !== undefined ? { parentIdent: cap.parentIdent } : {}) }] });
            this.writeTracked(scope, tracked);
            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) {
        const closed = this.closedArm("track_failed", "annulTrack") ?? this.refusedScope(scope, "track_failed");
        if (closed !== undefined)
            return Promise.resolve(closed);
        return this.writing(scope, () => this.annulTrackCounted(scope, absPath, root, verify));
    }
    async annulTrackCounted(scope, absPath, root, verify) {
        try {
            const state = this.readTrackedState(scope);
            const has = (k) => state.tracked.has(k);
            const key = verify === undefined ? trackKeyForAnnul(root, absPath, has) : await trackKeyForAnnul(root, absPath, has, { ...verify, entryOf: (k) => state.tracked.get(k) });
            if (state.corrupt) {
                return { ok: false, error: { code: "track_failed", message: `file history for scope "${scope}" is unreadable — the first-touch record (if any) was left in place; repair the graph before retraction can be judged`, ...state.fault } };
            }
            const tracked = state.tracked;
            const rec = tracked.get(key);
            if (rec === undefined)
                return { ok: true };
            const listed = this.listBoundaryIds(scope);
            if (!Array.isArray(listed))
                return { ok: false, error: { code: "track_failed", message: `scope "${scope}" has ${listed.what} — the first-touch record for ${absPath} was left in place, since whether a boundary references it cannot be judged`, ...listed.fault } };
            for (const entryId of listed) {
                const bp = this.tryBoundaryPath(scope, entryId);
                const mapping = bp === null ? null : this.readBoundaryMapping(bp);
                if (mapping?.has(key) === true) {
                    return { ok: false, error: { code: "conflict", message: `first-touch record for ${absPath} is referenced by a committed boundary — it is history now, not a retractable mint` } };
                }
            }
            if (rec.versions.length > 1) {
                return { ok: false, error: { code: "conflict", message: `first-touch record for ${absPath} has grown past its first version — only the mint itself is retractable` } };
            }
            if (rec.observedByLaterTouch === true) {
                return { ok: false, error: { code: "conflict", message: `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` } };
            }
            const proof = verify === undefined ? undefined : await worldStillMatchesMint(verify.env, absPath, root, rec.baseAvailable, rec.versions[0]?.blobHash ?? null, verify.signal);
            if (proof !== undefined && proof.verdict !== "unchanged")
                return annulProofFailure(proof, absPath);
            const fresh = this.readTrackedState(scope);
            if (fresh.corrupt)
                return { ok: false, error: { code: "track_failed", message: `file history for scope "${scope}" became unreadable — the record was left in place`, ...fresh.fault } };
            const still = fresh.tracked.get(key);
            if (still === undefined)
                return { ok: true };
            if (still.observedByLaterTouch === true || still.versions.length > 1) {
                return { ok: false, error: { code: "conflict", message: `first-touch record for ${absPath} stopped being a retractable mint while this retraction was being proven` } };
            }
            if (still.mintId !== rec.mintId || still.baseAvailable !== rec.baseAvailable || still.versions.length !== rec.versions.length || still.versions[0]?.blobHash !== rec.versions[0]?.blobHash || still.versions[0]?.backupTime !== rec.versions[0]?.backupTime) {
                return { ok: false, error: { code: "conflict", message: `first-touch record for ${absPath} was replaced while this retraction was being proven — the record now there belongs to a newer edit` } };
            }
            const relisted = this.listBoundaryIds(scope);
            if (!Array.isArray(relisted))
                return { ok: false, error: { code: "track_failed", message: `scope "${scope}" came to have ${relisted.what} while this retraction was being proven — the record was left in place`, ...relisted.fault } };
            for (const entryId of relisted) {
                const bp2 = this.tryBoundaryPath(scope, entryId);
                const mapping2 = bp2 === null ? null : this.readBoundaryMapping(bp2);
                if (mapping2?.has(key) === true) {
                    return { ok: false, error: { code: "conflict", message: `first-touch record for ${absPath} was frozen by a boundary committed while this retraction was being proven — it is history now` } };
                }
            }
            fresh.tracked.delete(key);
            this.writeTracked(scope, fresh.tracked);
            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) } };
        }
    }
    scopeIsEmptySync(scope) {
        const state = this.readTrackedState(scope);
        if (state.corrupt)
            return { fault: state.fault, what: "an unreadable tracked set" };
        const listed = this.listBoundaryIds(scope);
        if (!Array.isArray(listed))
            return listed;
        return state.tracked.size === 0 && listed.length === 0 ? "empty" : "not_empty";
    }
    async importTargetOf(scope, data, when) {
        const emptiness = this.scopeIsEmptySync(scope);
        if (emptiness === "empty")
            return "empty";
        if (emptiness !== "not_empty") {
            return { ok: false, error: { code: "adopt_failed", message: `importHistory target "${scope}" ${when === "before" ? "has" : "came to have"} ${emptiness.what} — a scope whose history cannot be judged is not an empty target; nothing was ${when === "before" ? "fetched or " : ""}published`, ...emptiness.fault } };
        }
        const existing = await this.exportHistory(scope);
        if (existing.ok && existing.history !== null && fileHistoryExportDigest(existing.history) === fileHistoryExportDigest(data))
            return "identical";
        const message = when === "before"
            ? `importHistory target "${scope}" was judged not empty and not this envelope — it holds a DIFFERENT history, or it changed (or could not be read) between the two reads that judge it — 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)`
            : `importHistory target "${scope}" changed while this import was fetching blobs — it gained a DIFFERENT history, or changed (or could not be read) between the two reads that judge it — nothing was published`;
        return { ok: false, error: { code: "conflict", message } };
    }
    publishStagedScopeSync(scope, staging) {
        const emptiness = this.scopeIsEmptySync(scope);
        if (emptiness !== "empty")
            return emptiness;
        safeRm(this.scopeDir(scope));
        renameSync(staging, this.scopeDir(scope));
        return "published";
    }
    listBoundaryIds(scope) {
        const dir = this.boundaryDir(scope);
        let names;
        try {
            names = readdirSync(dir).filter((f) => f.endsWith(".json"));
        }
        catch (err) {
            if (err.code === "ENOENT")
                return [];
            this.disclose(dir, `boundary directory unreadable (${err.code ?? "unknown"}) — this scope's history cannot be judged until it can be listed`);
            return { fault: caughtFault(err), what: "a boundary directory that cannot be listed" };
        }
        const ids = [];
        const unusable = [];
        const faults = [];
        for (const f of names) {
            const read = this.readBoundaryState(join(dir, f));
            (read instanceof Map ? ids : unusable).push(f.slice(0, -".json".length));
            if (!(read instanceof Map))
                faults.push(read ?? {});
        }
        if (unusable.length === 0)
            return ids;
        return { fault: worstFault(faults), what: `boundaries that cannot be used (${unusable.slice(0, 3).map((i) => JSON.stringify(i)).join(", ")}${unusable.length > 3 ? ", …" : ""})` };
    }
    snapshot(scope, entryId, env, root, signal) {
        const closed = this.closedArm("snapshot_failed", "snapshot") ?? this.refusedScope(scope, "snapshot_failed");
        if (closed !== undefined)
            return Promise.resolve(closed);
        return this.writing(scope, () => this.snapshotCounted(scope, entryId, env, root, signal));
    }
    async snapshotCounted(scope, entryId, env, root, signal) {
        const bpath = this.tryBoundaryPath(scope, entryId);
        if (bpath === null)
            return { ok: false, error: { code: "snapshot_failed", message: `unsafe boundary key ${typeof entryId === "string" ? JSON.stringify(entryId) : callerText(entryId)}` } };
        if (this.readBoundaryMapping(bpath) !== null)
            return { ok: true };
        const consumed = this.readReapedIds(scope);
        if (!(consumed instanceof Set)) {
            return { ok: false, error: { code: "snapshot_failed", message: `the consumed-entry ledger for scope "${scope}" cannot be read — refusing to mint a boundary while it is impossible to tell a fresh entry id from one retention already reaped`, ...consumed } };
        }
        if (consumed.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 (this.spentAttempts.get(scope)?.has(entryId) === true) {
            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 (this.activeCaptures.get(scope)?.has(entryId) === true) {
            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 journal = join(this.scopeDir(scope), "staging", `${Date.now().toString(36)}-${randomBytes(6).toString("hex")}.jsonl`);
        nestedMapSet(this.activeCaptures, scope, entryId, journal);
        try {
            ensureDir(join(this.scopeDir(scope), "staging"));
            appendFileSync(journal, `${JSON.stringify({ entryId, pid: process.pid, startedAt: new Date().toISOString() })}\n`);
            const state = this.readTrackedState(scope);
            if (state.corrupt) {
                nestedSetAdd(this.spentAttempts, scope, entryId);
                return { ok: false, error: { code: "snapshot_failed", message: `file history for scope "${scope}" is unreadable — a boundary minted over an unusable graph would claim to restore state that is not there`, ...state.fault } };
            }
            const tracked = state.tracked;
            const staged = new Map();
            for (const [key, rec] of tracked) {
                if (signal?.aborted) {
                    nestedSetAdd(this.spentAttempts, scope, entryId);
                    return { ok: false, error: { code: "aborted", message: `boundary capture for entry "${entryId}" aborted` } };
                }
                const resolved = await resolveTrackedFile(env, root, key, rec.versions, descriptorOf(rec), signal);
                if (!resolved.ok) {
                    nestedSetAdd(this.spentAttempts, scope, entryId);
                    return { ok: false, error: { code: "snapshot_failed", message: resolved.reason } };
                }
                if ("held" in resolved) {
                    const last = rec.versions[rec.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") {
                    nestedSetAdd(this.spentAttempts, scope, entryId);
                    return { ok: false, error: { code: "aborted", message: `boundary capture for entry "${entryId}" aborted` } };
                }
                if (cap.state === "unreadable") {
                    nestedSetAdd(this.spentAttempts, scope, entryId);
                    return { ok: false, error: { code: "snapshot_failed", message: cap.cause } };
                }
                const last = rec.versions[rec.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) {
                    nestedSetAdd(this.spentAttempts, scope, entryId);
                    return over;
                }
                appendFileSync(journal, `${JSON.stringify({ blob: cap.hash })}\n`);
                this.putBlob(cap.hash, cap.bytes);
                staged.set(key, { kind: "changed", blobHash: cap.hash, ...(cap.mode !== undefined ? { mode: cap.mode } : {}), ...(cap.parentIdent !== undefined ? { parentIdent: cap.parentIdent } : {}) });
            }
            if (!boundaryPublishVerdict({ aborted: signal?.aborted === true }).publish) {
                nestedSetAdd(this.spentAttempts, scope, entryId);
                return { ok: false, error: { code: "aborted", message: `boundary capture for entry "${entryId}" aborted (fenced — never committed)` } };
            }
            const currentState = this.readTrackedState(scope);
            if (currentState.corrupt) {
                nestedSetAdd(this.spentAttempts, scope, entryId);
                return { ok: false, error: { code: "snapshot_failed", message: `file history for scope "${scope}" became unreadable during the capture — no boundary was published`, ...currentState.fault } };
            }
            const current = currentState.tracked;
            for (const [key, cap] of staged) {
                if (cap.kind !== "unchanged")
                    continue;
                if (current.get(key)?.versions.some((v) => v.version === cap.version) !== true) {
                    nestedSetAdd(this.spentAttempts, scope, entryId);
                    return { ok: false, error: { code: "snapshot_failed", message: `staged reference ${key}@v${cap.version} no longer exists (reaped mid-capture)` } };
                }
            }
            const mapping = [];
            const now = new Date().toISOString();
            for (const [key, cap] of staged) {
                if (cap.kind === "unchanged") {
                    mapping.push([key, cap.version]);
                    continue;
                }
                const rec = current.get(key);
                if (rec === undefined)
                    continue;
                const last = rec.versions[rec.versions.length - 1];
                const version = last !== undefined ? last.version + 1 : rec.baseAvailable ? 1 : 2;
                rec.versions.push({ version, blobHash: cap.blobHash, backupTime: now, ...(cap.mode !== undefined ? { mode: cap.mode } : {}), ...(cap.parentIdent !== undefined ? { parentIdent: cap.parentIdent } : {}) });
                mapping.push([key, version]);
            }
            this.writeTracked(scope, current);
            ensureDir(this.boundaryDir(scope));
            const doc = { formatVersion: "file-history/1", files: mapping, digest: boundaryDigest(mapping), committedAt: this.nextCommittedAt(scope) };
            try {
                writeThenLink(bpath, JSON.stringify(doc));
            }
            catch (err) {
                if (err.code !== "EEXIST")
                    throw err;
                const existing = this.readBoundaryState(bpath);
                if (!(existing instanceof Map)) {
                    nestedSetAdd(this.spentAttempts, scope, entryId);
                    return { ok: false, error: { code: "snapshot_failed", message: `a boundary file for entry "${entryId}" already exists but cannot be read — this turn has no usable boundary (the unreadable file is left in place for an operator rather than silently replaced)`, ...existing } };
                }
            }
            this.applyBoundaryRetention(scope, entryId);
            return { ok: true };
        }
        catch (err) {
            nestedSetAdd(this.spentAttempts, scope, entryId);
            return { ok: false, error: { code: "snapshot_failed", message: `boundary for entry "${entryId}" could not be committed: ${thrownText(err)}`, ...caughtFault(err) } };
        }
        finally {
            this.activeCaptures.get(scope)?.delete(entryId);
            safeRm(journal);
        }
    }
    async restore(scope, entryId, env, root, signal, options) {
        const ledger = EMPTY_LEDGER();
        const closed = this.closedArm("restore_failed", "restore") ?? this.refusedScope(scope, "restore_failed");
        if (closed !== undefined)
            return { outcome: "failed", ...ledger, error: closed.error };
        let modeNotPreserved = 0;
        try {
            const bpath = this.tryBoundaryPath(scope, entryId);
            const boundary = bpath === null ? null : this.readBoundaryState(bpath);
            if (boundary === null) {
                return { outcome: "failed", ...ledger, error: { code: "not_found", message: `no history boundary for entry ${typeof entryId === "string" ? `"${entryId}"` : callerText(entryId)}` } };
            }
            if (!(boundary instanceof Map)) {
                return { outcome: "failed", ...ledger, error: { code: "restore_failed", message: `the history boundary for entry "${entryId}" is there but cannot be used — NOTHING was restored`, ...boundary } };
            }
            const state = this.readTrackedState(scope);
            if (state.corrupt) {
                return { outcome: "failed", ...ledger, error: { code: "restore_failed", message: `file history for scope "${scope}" is unreadable — the boundary exists but its version records cannot be read, so NOTHING was restored`, ...state.fault } };
            }
            const tracked = state.tracked;
            for (const key of [...tracked.keys()].sort()) {
                const rec = tracked.get(key);
                const to = fileHistoryTargetOf({ key, desc: descriptorOf(rec), baseAvailable: rec.baseAvailable, versions: rec.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, descriptorOf(rec));
                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 {
                    let bytes;
                    try {
                        bytes = readFileSync(this.blobPath(to.hash));
                    }
                    catch {
                        bytes = undefined;
                    }
                    if (bytes === undefined) {
                        ledger.failed.push({ path: key, reason: `blob ${to.hash} missing (store integrity)` });
                        continue;
                    }
                    if (createHash("sha256").update(bytes).digest("hex") !== to.hash) {
                        ledger.failed.push({ path: key, reason: `blob ${to.hash} fails content-address integrity (store corruption) — the file was left untouched` });
                        this.disclose(this.blobPath(to.hash), "blob bytes do not hash to their own name — the restore refused to apply them");
                        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 = ledger.filesChanged.length > 0 || ledger.identicalSkipped.length > 0 || ledger.refused.length > 0 || ledger.failed.length > 0;
            return { outcome: touched ? "partial" : "failed", ...ledger, error: { code: "restore_failed", message: thrownText(err), ...caughtFault(err) } };
        }
    }
    async canRestore(scope, entryId) {
        const bpath = this.tryBoundaryPath(scope, entryId);
        return bpath !== null && this.readBoundaryMapping(bpath) !== null;
    }
    async readBoundaries(scope, entryIds) {
        const refused = this.refusedScope(scope, "restore_failed");
        if (refused !== undefined)
            return refused;
        try {
            const records = new Map();
            for (const entryId of entryIds) {
                if (records.has(entryId))
                    continue;
                const bpath = this.tryBoundaryPath(scope, entryId);
                records.set(entryId, bpath === null ? null : this.readBoundaryState(bpath));
            }
            const state = [...records.values()].some((b) => b instanceof Map) ? this.readTrackedState(scope) : undefined;
            const keys = state !== undefined && !state.corrupt ? [...state.tracked.keys()].sort() : [];
            const boundaries = new Map();
            for (const [entryId, boundary] of records) {
                if (boundary === null)
                    boundaries.set(entryId, { ok: true, boundary: null });
                else if (!(boundary instanceof Map)) {
                    boundaries.set(entryId, { ok: false, error: { code: "restore_failed", message: `the history boundary for entry "${entryId}" is there but cannot be read`, ...boundary } });
                }
                else if (state !== undefined && !state.corrupt) {
                    try {
                        const entries = keys.map((key) => {
                            const rec = state.tracked.get(key);
                            return { key, keyDesc: declaredDescriptorOf(key, rec), target: fileHistoryTargetOf({ key, desc: descriptorOf(rec), baseAvailable: rec.baseAvailable, versions: rec.versions }, boundary.get(key)) };
                        });
                        boundaries.set(entryId, { ok: true, boundary: { entries } });
                    }
                    catch (err) {
                        boundaries.set(entryId, { ok: false, error: { code: "restore_failed", message: `the history boundary for entry "${entryId}" is there but a tracked record in its scope cannot be read`, ...caughtFault(err) } });
                    }
                }
                else {
                    boundaries.set(entryId, { ok: false, error: { code: "restore_failed", message: `file history for scope "${scope}" is unreadable — the boundary exists but its version records cannot be read`, ...(state?.corrupt ? state.fault : {}) } });
                }
            }
            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) } };
        }
    }
    blobExchange = {
        put: async (hash, bytes) => {
            const closed = this.closedArm("adopt_failed", "blobExchange.put");
            if (closed !== undefined)
                return closed;
            const refused = blobPutRefusal(hash, bytes) ?? overLimit(blobOverStoreLimit(bytes, this.maxBlobBytes, `the blob put under ${hash}`));
            if (refused !== undefined)
                return refused;
            try {
                const path = this.blobPath(hash);
                try {
                    writeThenLink(path, bytes);
                }
                catch (err) {
                    if (err.code !== "EEXIST")
                        throw err;
                    let held;
                    try {
                        held = readFileSync(path);
                    }
                    catch (readErr) {
                        if (!BLOB_NAME_HOLDS_NO_FILE.has(readErr.code ?? ""))
                            throw readErr;
                    }
                    if (held !== undefined && held.equals(bytes)) {
                        const now = new Date();
                        utimesSync(path, now, now);
                    }
                    else {
                        let stood = true;
                        try {
                            lstatSync(path);
                        }
                        catch {
                            stood = false;
                        }
                        safeRm(path);
                        writeThenLink(path, bytes);
                        if (stood)
                            this.disclose(path, "locally stored blob does not hash to its own name — blobExchange.put replaced it with the bytes it was handed");
                    }
                }
                return { ok: true };
            }
            catch (err) {
                return { ok: false, error: { code: "adopt_failed", message: `the blob could not be stored: ${thrownText(err)}`, ...caughtFault(err) } };
            }
        },
        get: async (hash) => {
            if (!isBlobAddress(hash))
                return undefined;
            try {
                return new Uint8Array(readFileSync(this.blobPath(hash)));
            }
            catch (err) {
                if (err.code === "ENOENT")
                    return undefined;
                throw err;
            }
        },
        has: async (hashes) => new Set(hashes.filter((h) => isBlobAddress(h) && existsSync(this.blobPath(h)))),
    };
    async reap(scope, keepEntryIds) {
        this.latch.refuse("FileFileHistoryStore.reap");
        const keep = new Set(keepEntryIds);
        let removed = 0;
        const dir = this.boundaryDir(scope);
        let entries = [];
        try {
            entries = readdirSync(dir);
        }
        catch (err) {
            if (err.code !== "ENOENT") {
                this.disclose(dir, `boundary directory unreadable (${err.code ?? "unknown"}) — the WHOLE reap is refused (0 dropped, no version or blob collection) because an unlistable directory cannot distinguish "no boundaries" from "boundaries we cannot see"`);
                return 0;
            }
        }
        const mappings = new Map();
        for (const file of entries) {
            if (!file.endsWith(".json"))
                continue;
            const mapping = this.readBoundaryMapping(join(dir, file));
            if (mapping === null) {
                this.disclose(join(dir, file), "a boundary in this scope cannot be judged — the WHOLE reap is refused (0 dropped, nothing collected) until it is repaired or removed, because trimming around a record whose references cannot be read destroys the versions only it points at");
                return 0;
            }
            mappings.set(file.slice(0, -".json".length), mapping);
        }
        const survivors = new Set(keep);
        for (const file of entries) {
            if (!file.endsWith(".json"))
                continue;
            const id = file.slice(0, -".json".length);
            if (keep.has(id))
                continue;
            if (this.markReaped(scope, [id]) !== true) {
                survivors.add(id);
                continue;
            }
            if (safeRm(join(dir, file))) {
                removed++;
            }
            else {
                survivors.add(id);
            }
        }
        const referenced = new Map();
        for (const [id, mapping] of mappings) {
            if (!survivors.has(id))
                continue;
            for (const [key, v] of mapping) {
                let s = referenced.get(key);
                if (s === undefined)
                    referenced.set(key, (s = new Set()));
                s.add(v);
            }
        }
        const tracked = this.readTracked(scope);
        if (tracked.size > 0) {
            for (const [key, rec] of tracked) {
                rec.versions = rec.versions.filter((v) => v.version === 1 || (referenced.get(key)?.has(v.version) ?? false) || fileHistoryEntryFrozen({ key, desc: descriptorOf(rec), versions: [v] }) !== undefined);
            }
            try {
                this.writeTracked(scope, tracked);
            }
            catch (err) {
                this.disclose(this.trackedPath(scope), `version-chain trim could not be committed (${thrownText(err)}) — trim skipped this pass; untrimmed versions keep their blobs live`);
            }
        }
        this.collectBlobs(true);
        return removed;
    }
    async deleteBySession(scope) {
        this.latch.refuse("FileFileHistoryStore.deleteBySession");
        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 sdir = this.scopeDir(scope);
        const ledger = this.reapedLogPath(scope);
        let removed = 0;
        const link = firstLinkIn(sdir);
        if (link !== undefined)
            throw new Error(`file history scope "${scope}" is not erased: ${link === sdir ? "its directory" : `an entry in its directory (${relative(sdir, link)})`} is a link, and an erase removes what it counted — through a link that is outside this store; nothing was removed (remove the link itself by hand, and erase again)`);
        try {
            removed += readdirSync(this.boundaryDir(scope)).filter((f) => f.endsWith(".json")).length;
        }
        catch (err) {
            if (err.code !== "ENOENT")
                throw err;
        }
        const read = this.readTrackedState(scope);
        if (read.corrupt)
            removed += 1;
        else
            for (const rec of read.tracked.values())
                removed += rec.versions.length;
        rmSync(sdir, { recursive: true, force: true });
        rmSync(ledger, { force: true });
        this.reapedCache.delete(scope);
        this.spentAttempts.delete(scope);
        this.seededScopes.delete(scope);
        this.activeCaptures.delete(scope);
        this.activeImports.delete(scope);
        const kept = this.collectBlobs(false);
        if (kept !== undefined)
            throw new Error(`file history scope "${scope}" is erased but its blobs are not: ${kept}`);
        return removed;
    }
    async deleteUnreadableSessionHistory(sessionId) {
        this.latch.refuse("FileFileHistoryStore.deleteUnreadableSessionHistory");
        const id = readUnreadableDeleteId("FileHistoryStore.deleteUnreadableSessionHistory", sessionId);
        assertWellFormedKey(id, "file history: the session id");
        const owned = new Set([...this.writers.keys()].filter((scope) => readFileHistoryScope(scope)?.sessionId === id));
        for (const scope of this.scopeNamesOnDisk())
            if (readFileHistoryScope(scope)?.sessionId === id)
                owned.add(scope);
        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.size === 0) {
            const kept = this.collectBlobs(false);
            if (kept !== undefined)
                throw new Error(`file history of session "${id}" holds no scope, but the blobs are not collected: ${kept}`);
        }
        return removed;
    }
    scopeNamesOnDisk() {
        let names;
        try {
            names = readdirSync(this.scopesDir);
        }
        catch (err) {
            if (err.code === "ENOENT")
                return [];
            throw new Error(`file history scope root ${this.scopesDir} could not be read (${err.code ?? thrownText(err)}) — no scope was erased`);
        }
        const out = [];
        for (const name of names) {
            if (name.includes("."))
                continue;
            const sdir = join(this.scopesDir, name);
            const unjudged = (why) => new Error(`file history scope directory ${sdir} names no scope this store can read (${why}) — no scope was erased`);
            try {
                if (!statSync(sdir).isDirectory())
                    continue;
            }
            catch (err) {
                if (err.code === "ENOENT")
                    continue;
                throw unjudged(err.code ?? thrownText(err));
            }
            let scope;
            try {
                scope = parseJsonRecord(readFileSync(join(sdir, "tracked.json"), "utf8"))?.scope;
            }
            catch (err) {
                if (err.code !== "ENOENT")
                    throw unjudged(err.code ?? thrownText(err));
                let committed;
                try {
                    committed = readdirSync(join(sdir, "boundaries"));
                }
                catch (cause) {
                    if (cause.code === "ENOENT")
                        continue;
                    throw unjudged(cause.code ?? thrownText(cause));
                }
                if (committed.length === 0)
                    continue;
                throw unjudged("its tracked set is missing beside a boundary");
            }
            if (typeof scope !== "string" || scopeLabelOf(scope) !== name)
                throw unjudged(`its tracked set records ${typeof scope === "string" ? "another directory's scope" : "no scope"}`);
            out.push(scope);
        }
        return out;
    }
    collectBlobs(byAge) {
        const live = new Set();
        let complete = true;
        let scopeDirs;
        try {
            scopeDirs = readdirSync(this.scopesDir);
        }
        catch (err) {
            if (err.code === "ENOENT")
                scopeDirs = [];
            else {
                this.disclose(this.scopesDir, `scope root unreadable (${err.code ?? "unknown"}) — blob GC aborted, every blob kept`);
                return "the scope root could not be read, so every blob was kept";
            }
        }
        const liveJournals = new Set([...[...this.activeCaptures.values()].flatMap((m) => [...m.values()]), ...[...this.activeImports.values()].flatMap((set) => [...set])]);
        for (const name of scopeDirs) {
            const sdir = join(this.scopesDir, name);
            try {
                if (!statSync(sdir).isDirectory())
                    continue;
            }
            catch {
                continue;
            }
            const tpath = join(sdir, "tracked.json");
            if (existsSync(tpath)) {
                let doc;
                try {
                    doc = parseJsonRecord(readFileSync(tpath, "utf8"));
                }
                catch {
                    doc = null;
                }
                const rows = trackedRowsOf(doc);
                if (rows === null) {
                    complete = false;
                    this.disclose(tpath, "tracked set unreadable during the live-set scan — blob GC aborted, every blob kept");
                    break;
                }
                if (doc?.digest !== undefined && (typeof doc.digest !== "string" || doc.digest !== trackedDigest(rows))) {
                    complete = false;
                    this.disclose(tpath, "tracked set fails its own integrity digest during the live-set scan — blob GC aborted, every blob kept (a live set built from damaged rows would delete the bytes a repair needs)");
                    break;
                }
                for (const [, rec] of rows)
                    for (const v of rec.versions)
                        if (v.blobHash !== null)
                            live.add(v.blobHash);
            }
            const stagingDir = join(sdir, "staging");
            let journals = [];
            try {
                journals = readdirSync(stagingDir);
            }
            catch (err) {
                if (err.code !== "ENOENT") {
                    complete = false;
                    this.disclose(stagingDir, `staging directory unreadable (${err.code ?? "unknown"}) — blob GC aborted, every blob kept`);
                    break;
                }
            }
            for (const j of journals) {
                const jpath = join(stagingDir, j);
                let raw;
                try {
                    raw = readFileSync(jpath, "utf8");
                }
                catch (err) {
                    if (err.code === "ENOENT")
                        continue;
                    complete = false;
                    this.disclose(jpath, "staging journal unreadable — blob GC aborted, every blob kept");
                    break;
                }
                const lines = raw.split("\n").filter((l) => l !== "");
                const header = parseJsonRecord(lines[0] ?? "");
                if (header === null || typeof header.pid !== "number" || typeof header.startedAt !== "string") {
                    this.disclose(jpath, "staging journal header is unreadable — the journal and its leased blobs are KEPT (an unknown owner is never proof of death)");
                    for (const line of lines)
                        leaseJournalBlob(line, live);
                    continue;
                }
                const ownedHere = liveJournals.has(jpath);
                const ownerAlive = !ownedHere && typeof header.pid === "number" && pidIsAlive(header.pid);
                const startedMs = Date.parse(header.startedAt ?? "");
                const young = Number.isFinite(startedMs) && Date.now() - startedMs < STALE_JOURNAL_MS;
                if (!ownedHere && !ownerAlive && !young) {
                    safeRm(jpath);
                    continue;
                }
                for (const line of lines)
                    leaseJournalBlob(line, live);
            }
            if (!complete)
                break;
        }
        if (!complete)
            return "a scope's history or staging could not be judged during the live-set scan, so every blob was kept";
        let blobs;
        try {
            blobs = readdirSync(this.blobsDir);
        }
        catch (err) {
            if (err.code === "ENOENT")
                return undefined;
            this.disclose(this.blobsDir, `blob directory unreadable (${err.code ?? "unknown"}) — blob GC skipped, every blob kept`);
            return "the blob directory could not be read, so every blob was kept";
        }
        let stuck = 0;
        const cutoff = Date.now() - FILE_HISTORY_UNREFERENCED_BLOB_GRACE_MS;
        for (const blob of blobs) {
            if (live.has(blob))
                continue;
            const path = join(this.blobsDir, blob);
            if (byAge) {
                let young = true;
                try {
                    young = statSync(path).mtimeMs > cutoff;
                }
                catch (err) {
                    if (err.code === "ENOENT")
                        continue;
                }
                if (young)
                    continue;
            }
            if (!safeRm(path))
                stuck++;
        }
        return stuck === 0 ? undefined : `${stuck} unreferenced blob(s) could not be removed`;
    }
    async adoptScope(fromScope, toScope) {
        const closed = this.closedArm("adopt_failed", "adoptScope") ?? this.refusedScope(fromScope, "adopt_failed", "the source scope (fromScope)") ?? this.refusedScope(toScope, "adopt_failed", "the target scope (toScope)");
        if (closed !== undefined)
            return closed;
        try {
            if (fromScope === toScope)
                return { ok: true };
            const target = this.scopeIsEmptySync(toScope);
            if (target === "not_empty") {
                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 (target !== "empty")
                return { ok: false, error: { code: "adopt_failed", message: `adoptScope target "${toScope}" has ${target.what} — a scope whose history cannot be judged is not an empty target; nothing was published`, ...target.fault } };
            const sourceState = this.readTrackedState(fromScope);
            if (sourceState.corrupt) {
                return { ok: false, error: { code: "adopt_failed", message: `adoptScope source "${fromScope}" has an unreadable tracked set — adopting it would publish boundaries with no version records behind them`, ...sourceState.fault } };
            }
            const source = sourceState.tracked;
            const sourceBoundaries = this.listBoundaryIds(fromScope);
            if (!Array.isArray(sourceBoundaries)) {
                return { ok: false, error: { code: "adopt_failed", message: `adoptScope source "${fromScope}" has ${sourceBoundaries.what} — adopting it would publish a graph that silently drops those turns and hands their entry ids back to the fork; nothing was published`, ...sourceBoundaries.fault } };
            }
            if (source.size === 0 && sourceBoundaries.length === 0) {
                const carried = this.carryConsumedIds(fromScope, toScope);
                if (carried !== true) {
                    return { ok: false, error: { code: "adopt_failed", message: `adoptScope could not carry the consumed-entry ledger from "${fromScope}" to "${toScope}" — refusing rather than reporting a carry that would let an already-consumed entry id be minted again in the fork`, ...carried } };
                }
                return { ok: true };
            }
            for (const [key, rec] of source) {
                for (const v of rec.versions) {
                    if (v.blobHash === null)
                        continue;
                    let fault;
                    try {
                        if (createHash("sha256").update(readFileSync(this.blobPath(v.blobHash))).digest("hex") !== v.blobHash)
                            fault = DAMAGED_RECORD;
                    }
                    catch (err) {
                        fault = err.code === "ENOENT" ? DAMAGED_RECORD : caughtFault(err);
                    }
                    if (fault !== undefined) {
                        return { ok: false, error: { code: "adopt_failed", message: `adoptScope source "${fromScope}" references blob ${v.blobHash} for ${key}@v${v.version}, which is missing or fails content-address integrity — nothing was published`, ...fault } };
                    }
                }
            }
            const staging = `${this.scopeDir(toScope)}.adopting-${process.pid}-${randomBytes(6).toString("hex")}`;
            safeRm(staging);
            try {
                ensureDir(join(staging, "boundaries"));
                const adoptedRows = [...source].filter(([key, rec]) => fileHistoryEntryTravels(declaredDescriptorOf(key, rec)));
                const adopted = new Set(adoptedRows.map(([key]) => key));
                const doc = { formatVersion: "file-history/1", scope: toScope, tracked: adoptedRows, digest: trackedDigest(adoptedRows) };
                atomicWriteFile(join(this.base, "tmp"), join(staging, "tracked.json"), JSON.stringify(doc));
                for (const id of sourceBoundaries) {
                    const bp = this.tryBoundaryPath(fromScope, id);
                    const mapping = bp === null ? null : this.readBoundaryMapping(bp);
                    if (mapping === null)
                        continue;
                    for (const [key, version] of mapping) {
                        if (source.get(key)?.versions.some((v) => v.version === version) !== true) {
                            throw new Error(`source boundary ${id} references ${key}@v${version}, which the source's version chains do not carry`);
                        }
                    }
                    const sourceCommittedAt = bp === null ? undefined : this.boundaryOrderOf(bp);
                    const files = [...mapping].filter(([key]) => adopted.has(key));
                    const bdoc = { formatVersion: "file-history/1", files, digest: boundaryDigest(files), ...(sourceCommittedAt !== undefined ? { committedAt: sourceCommittedAt } : {}) };
                    atomicWriteFile(join(this.base, "tmp"), join(staging, "boundaries", `${historyPathComponent(id)}.json`), JSON.stringify(bdoc));
                }
                const carried = this.carryConsumedIds(fromScope, toScope);
                if (carried !== true) {
                    safeRm(staging);
                    return { ok: false, error: { code: "adopt_failed", message: `adoptScope could not carry the consumed-entry ledger from "${fromScope}" to "${toScope}" — nothing was published, because a fork missing its lineage's tombstones can mint an already-consumed entry id`, ...carried } };
                }
                const published = this.publishStagedScopeSync(toScope, staging);
                if (published !== "published") {
                    safeRm(staging);
                    return published === "not_empty"
                        ? { ok: false, error: { code: "conflict", message: `adoptScope target "${toScope}" gained history of its own while this adoption was being staged — nothing was published` } }
                        : { ok: false, error: { code: "adopt_failed", message: `adoptScope target "${toScope}" came to have ${published.what} while this adoption was being staged — a scope whose history cannot be judged is not an empty target; nothing was published`, ...published.fault } };
                }
            }
            catch (err) {
                safeRm(staging);
                throw err;
            }
            return { ok: true };
        }
        catch (err) {
            return { ok: false, error: { code: "adopt_failed", message: `adoptScope failed: ${thrownText(err)}`, ...caughtFault(err) } };
        }
    }
    async exportHistory(scope) {
        const unexportable = (what, fault) => ({ ok: false, error: { code: "adopt_failed", message: `exportHistory scope "${scope}" has ${what} — its history cannot be exported whole, so nothing was exported`, ...fault } });
        const refused = this.refusedScope(scope, "adopt_failed");
        if (refused !== undefined)
            return refused;
        const state = this.readTrackedState(scope);
        if (state.corrupt)
            return unexportable("an unreadable tracked set", state.fault);
        const tracked = state.tracked;
        const boundaryIds = this.listBoundaryIds(scope);
        if (!Array.isArray(boundaryIds))
            return unexportable(boundaryIds.what, boundaryIds.fault);
        if (tracked.size === 0 && boundaryIds.length === 0)
            return { ok: true, history: null };
        const relative = [...tracked.entries()].map(([key, rec]) => ({ key, rec, desc: declaredDescriptorOf(key, rec) })).filter((t) => fileHistoryEntryTravels(t.desc));
        const frozenKeys = relative.filter((t) => fileHistoryEntryFrozen({ key: t.key, desc: descriptorOf(t.rec), versions: t.rec.versions }) !== undefined).map((t) => t.key).sort();
        const travels = relative.filter((t) => !frozenKeys.includes(t.key));
        const kept = new Set(travels.map((t) => t.key));
        const omitted = tracked.size - relative.length;
        const boundaries = [];
        for (const entryId of [...boundaryIds].sort()) {
            const bp = this.tryBoundaryPath(scope, entryId);
            const mapping = bp === null ? null : this.readBoundaryMapping(bp);
            if (mapping === null)
                return unexportable(`a boundary ("${entryId}") that stopped being usable while it was exported`, {});
            boundaries.push({ entryId, files: [...mapping.entries()].filter(([key]) => kept.has(key)).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([relOrAbsPath, version]) => ({ relOrAbsPath, version })) });
        }
        const history = {
            formatVersion: "file-history/1",
            ...(omitted > 0 ? { absoluteEntriesOmitted: omitted } : {}),
            ...(frozenKeys.length > 0 ? { frozenEntryKeys: frozenKeys } : {}),
            tracked: travels
                .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
                .map(({ key, rec, desc }) => ({
                relOrAbsPath: key,
                keyKind: desc.kind,
                keyFamily: desc.family,
                baseAvailable: rec.baseAvailable,
                versions: rec.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,
        };
        return { ok: true, history };
    }
    importHistory(scope, data, srcGetBlob) {
        const closed = this.closedArm("adopt_failed", "importHistory") ?? this.refusedScope(scope, "adopt_failed");
        if (closed !== undefined)
            return Promise.resolve(closed);
        return this.writing(scope, () => this.importHistoryCounted(scope, data, srcGetBlob));
    }
    async importHistoryCounted(scope, data, srcGetBlob) {
        try {
            const shaped = validateFileHistoryExport(data);
            if (!shaped.ok)
                return shaped;
            for (const b of data.boundaries) {
                try {
                    historyPathComponent(b.entryId);
                }
                catch (err) {
                    return { ok: false, error: { code: "unsupported_format", message: `importHistory refused a boundary entry id this backend cannot hold as a record name: ${thrownText(err)} — nothing was fetched or published` } };
                }
            }
            const target = await this.importTargetOf(scope, data, "before");
            if (typeof target === "object")
                return target;
            const identicalRepublish = target === "identical";
            const importJournal = join(this.scopeDir(scope), "staging", `import-${Date.now().toString(36)}-${randomBytes(6).toString("hex")}.jsonl`);
            ensureDir(join(this.scopeDir(scope), "staging"));
            appendFileSync(importJournal, `${JSON.stringify({ entryId: `import:${scope}`, pid: process.pid, startedAt: new Date().toISOString() })}\n`);
            nestedSetAdd(this.activeImports, scope, importJournal);
            for (const t of data.tracked) {
                for (const v of t.versions) {
                    if (v.blobHash !== null)
                        appendFileSync(importJournal, `${JSON.stringify({ blob: v.blobHash })}\n`);
                }
            }
            return await this.runImport(scope, data, srcGetBlob, importJournal, identicalRepublish);
        }
        catch (err) {
            return { ok: false, error: { code: "adopt_failed", message: `importHistory failed: ${thrownText(err)}`, ...caughtFault(err) } };
        }
    }
    async runImport(scope, data, srcGetBlob, importJournal, identicalRepublish) {
        try {
            for (const t of data.tracked) {
                for (const v of t.versions) {
                    if (v.blobHash === null)
                        continue;
                    if (existsSync(this.blobPath(v.blobHash))) {
                        let local;
                        try {
                            local = readFileSync(this.blobPath(v.blobHash));
                        }
                        catch {
                            local = undefined;
                        }
                        if (local !== undefined && createHash("sha256").update(local).digest("hex") === v.blobHash) {
                            const over = overLimit(blobOverStoreLimit(local, this.maxBlobBytes, `blob ${v.blobHash}`));
                            if (over !== undefined)
                                return over;
                            continue;
                        }
                        this.disclose(this.blobPath(v.blobHash), "locally stored blob does not hash to its own name — the import re-fetched it from the source");
                        safeRm(this.blobPath(v.blobHash));
                    }
                    let bytes;
                    try {
                        bytes = await srcGetBlob(v.blobHash);
                    }
                    catch (err) {
                        return { ok: false, error: { code: "adopt_failed", message: `source blob ${v.blobHash} fetch failed: ${thrownText(err)}`, ...caughtFault(err) } };
                    }
                    if (bytes === undefined)
                        return { ok: false, error: { code: "adopt_failed", message: `source blob ${v.blobHash} is missing — the envelope's graph cannot be completed, so nothing is published` } };
                    if (createHash("sha256").update(bytes).digest("hex") !== v.blobHash) {
                        return { ok: false, error: { code: "adopt_failed", message: `source blob ${v.blobHash} fails content-address integrity — refused, nothing published` } };
                    }
                    const over = overLimit(blobOverStoreLimit(bytes, this.maxBlobBytes, `source blob ${v.blobHash}`));
                    if (over !== undefined)
                        return over;
                    this.putBlob(v.blobHash, bytes);
                }
            }
            if (identicalRepublish)
                return { ok: true };
            const now = await this.importTargetOf(scope, data, "after");
            if (now === "identical")
                return { ok: true };
            if (now !== "empty")
                return now;
            const staging = `${this.scopeDir(scope)}.importing-${process.pid}-${randomBytes(6).toString("hex")}`;
            safeRm(staging);
            try {
                ensureDir(join(staging, "boundaries"));
                const tracked = data.tracked.map((t) => [
                    t.relOrAbsPath,
                    {
                        baseAvailable: t.baseAvailable,
                        keyKind: t.keyKind,
                        keyFamily: 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 })),
                    },
                ]);
                const doc = { formatVersion: "file-history/1", scope, tracked, digest: trackedDigest(tracked) };
                atomicWriteFile(join(this.base, "tmp"), join(staging, "tracked.json"), JSON.stringify(doc));
                for (const b of data.boundaries) {
                    const bfiles = b.files.map((f) => [f.relOrAbsPath, f.version]);
                    const bdoc = { formatVersion: "file-history/1", files: bfiles, digest: boundaryDigest(bfiles) };
                    atomicWriteFile(join(this.base, "tmp"), join(staging, "boundaries", `${historyPathComponent(b.entryId)}.json`), JSON.stringify(bdoc));
                }
                let published;
                try {
                    published = this.publishStagedScopeSync(scope, staging);
                }
                catch (err) {
                    safeRm(staging);
                    return { ok: false, error: { code: "adopt_failed", message: `importHistory could not publish the staged graph for "${scope}": ${thrownText(err)} — nothing was published (a local storage fault, not a malformed envelope)`, ...caughtFault(err) } };
                }
                if (published !== "published") {
                    safeRm(staging);
                    return published === "not_empty"
                        ? { ok: false, error: { code: "conflict", message: `importHistory target "${scope}" gained history of its own while this import was being staged — nothing was published` } }
                        : { ok: false, error: { code: "adopt_failed", message: `importHistory target "${scope}" came to have ${published.what} while this import was being staged — a scope whose history cannot be judged is not an empty target; nothing was published`, ...published.fault } };
                }
            }
            catch (err) {
                safeRm(staging);
                throw err;
            }
            return { ok: true };
        }
        catch (err) {
            return { ok: false, error: { code: "adopt_failed", message: `importHistory failed: ${thrownText(err)}`, ...caughtFault(err) } };
        }
        finally {
            safeRm(importJournal);
            this.activeImports.get(scope)?.delete(importJournal);
        }
    }
}