UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3,016 lines • 103 kB
import { Et as _enum, Fn as object, Jn as string, Lt as boolean, Nt as array, Pn as number, Yt as discriminatedUnion, lr as uuid, or as union, qn as strictObject, sr as unknown, xn as literal } from "./schemas-Cy6abvsu.mjs";
import { i as runManagedCommand, n as hasUnjoinedWork } from "./managed-child-process-DkJbQpWl.mjs";
import { accessSync, chmodSync, closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, mkdtempSync, openSync, opendirSync, readSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, writeFileSync, writeSync } from "node:fs";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { createHash, randomUUID } from "node:crypto";
import { performance } from "node:perf_hooks";
import { parseArgs } from "node:util";
import { spawnSync } from "node:child_process";
import { isUtf8 } from "node:buffer";
import { DatabaseSync } from "node:sqlite";
//#region scripts/crabbox-staging-witness.mts
const objectId = /^[0-9a-f]{40}$/u;
const sourceModes = /* @__PURE__ */ new Set([
	"100644",
	"100755",
	"120000"
]);
const maxEntries$1 = 1e5;
const maxMetadataBytes = 67108864;
const maxSourceBytes = 8589934592;
const baseBudgetMs = 12e4;
const budgetPerGiBMs = 3e4;
const maxBudgetMs = 18e5;
function gitEnvironment() {
	return {
		...Object.fromEntries(Object.entries(process.env).filter(([e]) => !e.toUpperCase().startsWith("GIT_"))),
		GIT_OPTIONAL_LOCKS: "0",
		GIT_NO_LAZY_FETCH: "1",
		GIT_NO_REPLACE_OBJECTS: "1",
		GIT_CONFIG_NOSYSTEM: "1",
		GIT_CONFIG_GLOBAL: "/dev/null",
		GIT_TERMINAL_PROMPT: "0"
	};
}
const gitOptions = [
	"--no-lazy-fetch",
	"--no-replace-objects",
	"-c",
	"gc.auto=0",
	"-c",
	"maintenance.auto=false",
	"-c",
	"core.fsmonitor=false",
	"-c",
	"core.commitGraph=false",
	"-c",
	"core.multiPackIndex=false"
];
function workBudgetExceeded() {
	return /* @__PURE__ */ new Error("source witness verification exceeded its work budget; retry later, repack the witness repository, or choose another --witness-repo/--witness-ref");
}
function remainingTime(e) {
	const t = e - Date.now();
	if (t <= 0) throw workBudgetExceeded();
	return t;
}
function gitRead(e, t, n, r = {}) {
	const i = spawnSync("git", [
		...gitOptions,
		...e,
		...t
	], {
		env: gitEnvironment(),
		stdio: [
			"ignore",
			r.quiet ? "ignore" : "pipe",
			"pipe"
		],
		timeout: remainingTime(n),
		killSignal: "SIGKILL",
		maxBuffer: r.quiet ? 1048576 : maxMetadataBytes
	});
	if (!i.error && r.absent && i.status === 1) return;
	if (i.error && "code" in i.error && i.error.code === "ETIMEDOUT") throw workBudgetExceeded();
	if (i.error || i.status !== 0) {
		const e = !i.error && typeof i.status === "number" ? r.failure?.(i.status) : void 0;
		throw new Error(e ?? `source witness Git ${t[0]} could not verify local objects`);
	}
	return i.stdout ?? Buffer.alloc(0);
}
function gitText(e, t, n) {
	const r = gitRead(e, t, n);
	if (!isUtf8(r)) throw new Error("source witness Git metadata is not UTF-8");
	return r.toString("utf8").trim();
}
function retainedRef(e) {
	return e.startsWith("refs/") && e.length <= 1024 && !e.endsWith("/HEAD") && !e.includes("\\") && !e.includes("\0") && !e.split("/").some((e) => !e || e === "." || e === "..") && ![
		"refs/openclaw/source-capsule",
		"refs/bisect/",
		"refs/rewritten/",
		"refs/worktree/",
		"refs/replace/"
	].some((t) => e === t || e.startsWith(t.endsWith("/") ? t : `${t}/`));
}
function resolveRef(e, t, n) {
	if (!retainedRef(t)) throw new Error("source witness needs a named non-staging Git ref");
	gitRead(e, ["check-ref-format", t], n);
	if (gitRead(e, [
		"symbolic-ref",
		"--quiet",
		t
	], n, { absent: true })) throw new Error("source witness ref must name retained objects directly");
	const r = gitText(e, [
		"rev-parse",
		"--verify",
		"--end-of-options",
		t
	], n);
	const i = gitText(e, [
		"rev-parse",
		"--verify",
		"--end-of-options",
		`${t}^{commit}`
	], n);
	if (!objectId.test(r) || !objectId.test(i)) throw new Error("source witness requires complete SHA-1 Git identities");
	return {
		oid: r,
		commit: i
	};
}
/** Capture only an existing branch or exact ref, without searching commit history. */
function captureSourceWitness(e, t) {
	try {
		if (!objectId.test(t)) return;
		const n = Date.now() + 5e3;
		const r = ["-C", e];
		const i = realpathSync(gitText(r, [
			"rev-parse",
			"--path-format=absolute",
			"--git-common-dir"
		], n));
		const a = gitRead(r, [
			"symbolic-ref",
			"--quiet",
			"HEAD"
		], n, { absent: true });
		const o = a ? [a.toString("utf8").trim()] : gitText(r, [
			"for-each-ref",
			"--count=32",
			"--format=%(refname)",
			"--points-at",
			t,
			"refs/heads",
			"refs/remotes",
			"refs/tags"
		], n).split("\n");
		for (const e of o.filter(retainedRef)) if (resolveRef(r, e, n).commit === t) return {
			gitDir: i,
			ref: e,
			commit: t
		};
	} catch {}
}
/** Select an operator-owned retained ref without creating refs or copying source. */
function selectSourceWitness(e, t) {
	if (!retainedRef(t)) throw new Error("Choose a full retained refs/heads, refs/remotes, or refs/tags name outside staging.");
	const n = Date.now() + 5e3;
	const r = ["-C", e];
	return {
		gitDir: realpathSync(gitText(r, [
			"rev-parse",
			"--path-format=absolute",
			"--git-common-dir"
		], n)),
		ref: t,
		commit: resolveRef(r, t, n).commit
	};
}
function overlaps$2(e, t) {
	const within = (e, t) => {
		const n = relative(e, t);
		return n === "" || !isAbsolute(n) && n !== ".." && !n.startsWith(`..${sep}`);
	};
	return within(e, t) || within(t, e);
}
function sourcePath(e) {
	if (!e || e.includes("\0") || e.includes("\\") || Buffer.from(e).toString("utf8") !== e || e.split("/").some((e) => !e || e === "." || e === ".." || e.toLowerCase() === ".git")) throw new Error("source witness manifest has an invalid repository path");
	return e;
}
function validateSource(e) {
	if (e.files.length + e.deleted.length > maxEntries$1) throw new Error("source witness manifest exceeds its entry budget");
	const t = /* @__PURE__ */ new Set();
	const n = /* @__PURE__ */ new Set();
	for (const r of e.files) {
		const e = sourcePath(r.path);
		if (t.has(e) || !sourceModes.has(r.mode) || !objectId.test(r.blob)) throw new Error("source witness manifest has duplicate or invalid source entries");
		t.add(e);
		for (let t = e.lastIndexOf("/"); t >= 0; t = e.lastIndexOf("/", t - 1)) n.add(e.slice(0, t));
	}
	if ([...t].some((e) => n.has(e))) throw new Error("source witness manifest has conflicting file and directory paths");
	const r = /* @__PURE__ */ new Set();
	for (const i of e.deleted) {
		const e = sourcePath(i);
		if (r.has(e) || t.has(e) || n.has(e)) throw new Error("source witness manifest has conflicting deletions");
		r.add(e);
	}
}
/** First eligibility tier: an ordinary self-contained local object store. */
function storageIdentity(e, t, n, r) {
	const i = createHash("sha256");
	let a = 0;
	let o = 0n;
	const record = (e) => {
		remainingTime(r);
		const t = lstatSync(e, {
			bigint: true,
			throwIfNoEntry: false
		});
		if (!t) {
			i.update(`${e}\0missing\0`);
			return;
		}
		if (t.isSymbolicLink() || !t.isDirectory() && !t.isFile()) throw new Error("source witness Git storage contains a symbolic link or unsupported file kind");
		if (++a > 25e4) throw new Error("source witness object storage exceeds its inspection budget");
		i.update(`${e}\0${t.dev}:${t.ino}:${t.mode}:${t.size}:${t.mtimeNs}:${t.ctimeNs}\0`);
		return t;
	};
	if (realpathSync(e) !== e || overlaps$2(e, t) || !record(e)?.isDirectory()) throw new Error("source witness Git repository overlaps the disposable payload");
	for (const t of [
		"HEAD",
		"config",
		"config.worktree",
		"packed-refs",
		"commondir",
		"shallow",
		"info/grafts",
		n
	]) {
		const n = t.split("/");
		for (let t = 1; t < n.length; t += 1) {
			const r = record(join(e, ...n.slice(0, t)));
			if (r && !r.isDirectory()) throw new Error("source witness Git metadata has an unsupported parent path");
		}
		const r = record(join(e, t));
		if (r && !r.isFile()) throw new Error("source witness Git metadata is not a regular file");
		if (r && [
			"commondir",
			"shallow",
			"info/grafts"
		].includes(t) && r.size > 0n) throw new Error("source witness needs complete local history without redirected or truncated storage");
	}
	const walk = (e, t) => {
		if (t > 4 || !record(e)?.isDirectory()) throw new Error("source witness object storage has an unsupported directory layout");
		for (const n of readdirSync(e).toSorted()) {
			const r = join(e, n);
			const i = record(r);
			if (!i) throw new Error("source witness object storage changed during inspection");
			if (n.endsWith(".promisor")) throw new Error("source witness has promised objects; choose an independent complete store");
			if ((n === "alternates" || n === "http-alternates") && i.size > 0n) throw new Error("source witness borrows objects; choose an independent complete store");
			if (i.isDirectory()) walk(r, t + 1);
			else if (i.isFile()) o += i.size > 4096n ? i.size : 4096n;
		}
	};
	walk(join(e, "objects"), 0);
	return {
		identity: i.digest("hex"),
		objectBytes: o
	};
}
async function verifyBlobs(e, t, n, r) {
	if (t.length === 0) return;
	const i = new AbortController();
	let a;
	let o = "";
	let s = 0;
	let c = 0;
	let l = 0;
	let u;
	const consume = (e) => {
		try {
			for (let n = 0; n < e.length;) {
				if (a) return;
				if (c > 0) {
					const t = n + Math.min(c, e.length - n);
					u.update(e.subarray(n, t));
					c -= t - n;
					n = t;
				} else if (u) {
					if (e[n++] !== 10 || u.digest("hex") !== t[s]) throw new Error("source witness raw blob identity mismatch");
					u = void 0;
					s += 1;
				} else {
					const r = e[n++];
					if (r !== 10) {
						o += String.fromCharCode(r);
						if (o.length > 128) throw new Error("source witness returned invalid object framing");
						continue;
					}
					const i = /^([0-9a-f]{40}) blob (0|[1-9][0-9]*)$/u.exec(o);
					if (!i || i[1] !== t[s]) throw new Error("source witness raw blob is missing or has the wrong type");
					c = Number(i[2]);
					l += c;
					if (!Number.isSafeInteger(c) || l > maxSourceBytes) throw new Error("source witness raw blobs exceed the verification byte budget");
					u = createHash("sha1").update(`blob ${c}\0`);
					o = "";
				}
			}
		} catch (e) {
			a = e instanceof Error ? e : /* @__PURE__ */ new Error("source witness blob verification failed");
			i.abort(a);
		}
	};
	try {
		if (await runManagedCommand({
			bin: "git",
			args: [
				...gitOptions,
				...e,
				"cat-file",
				"--batch"
			],
			env: gitEnvironment(),
			stdio: [
				"pipe",
				"pipe",
				"pipe"
			],
			timeoutMs: remainingTime(n),
			signal: r ? AbortSignal.any([r, i.signal]) : i.signal,
			requireProcessTreeExit: true,
			onReady(e) {
				e.stdout.on("data", consume);
				e.stderr.resume();
				e.stdin.on("error", () => {});
				e.stdin.end(`${t.join("\n")}\n`);
			}
		}) !== 0 || a || u || o || s !== t.length) throw a ?? /* @__PURE__ */ new Error("source witness did not supply every complete raw blob");
	} catch (e) {
		if (a && a !== e) throw new AggregateError([a, e], a.message, { cause: e });
		throw e;
	}
}
function fsckFailure(e) {
	if (e < 128 && (e & 7) !== 0) return "source witness Git fsck found missing, corrupt, or unconnected objects; choose a complete --witness-repo/--witness-ref";
	if (e === 8) return "source witness Git reference database has errors; repair its refs or choose another --witness-repo/--witness-ref";
}
function supportsNoReferences(e, t) {
	const n = /^git version (\d+)\.(\d+)/u.exec(gitText(e, ["version"], t));
	return n !== null && (Number(n[1]) > 2 || Number(n[1]) === 2 && Number(n[2]) >= 50);
}
/** Read-only proof of another retained copy; the stage owner still owns disposal. */
async function verifySourceWitness(e) {
	try {
		e.signal?.throwIfAborted();
		validateSource(e.source);
		const { ref: t, commit: n } = e.witness;
		if (!objectId.test(n) || !retainedRef(t)) throw new Error("source witness needs an exact commit and named non-staging ref");
		const r = Date.now();
		const i = realpathSync(e.payloadRoot);
		const a = realpathSync(e.witness.gitDir);
		const o = [`--git-dir=${a}`];
		const s = storageIdentity(a, i, t, r + baseBudgetMs);
		const c = r + Math.min(maxBudgetMs, baseBudgetMs + Math.ceil(Number(s.objectBytes) / 1024 ** 3 * budgetPerGiBMs));
		if (gitRead(o, [
			"config",
			"--no-includes",
			"--get-regexp",
			"^(include\\.|includeif\\.|extensions\\.(partialclone|refstorage)|remote\\..*\\.promisor$|fsck\\.)"
		], c, { absent: true })) throw new Error("source witness uses configuration that prevents independent local verification");
		if (gitText(o, ["rev-parse", "--show-object-format"], c) !== "sha1") throw new Error("source witness requires a SHA-1 Git object store");
		const l = resolveRef(o, t, c);
		gitRead(o, [
			"merge-base",
			"--is-ancestor",
			n,
			l.commit
		], c);
		gitRead(o, [
			"fsck",
			"--connectivity-only",
			"--no-dangling",
			"--no-reflogs",
			"--no-progress",
			...supportsNoReferences(o, c) ? ["--no-references"] : [],
			l.oid
		], c, {
			quiet: true,
			failure: fsckFailure
		});
		const u = gitRead(o, [
			"ls-tree",
			"-r",
			"-t",
			"-z",
			"--full-tree",
			n
		], c);
		if (!isUtf8(u)) throw new Error("source witness tree paths are not UTF-8");
		const d = /* @__PURE__ */ new Map();
		for (const e of u.toString("utf8").split("\0").filter(Boolean)) {
			const t = /^(040000 tree|100644 blob|100755 blob|120000 blob|160000 commit) ([0-9a-f]{40})\t([\s\S]+)$/u.exec(e);
			if (!t || !t[1] || !t[2] || !t[3] || d.has(t[3])) throw new Error("source witness tree has unsupported or duplicate entries");
			d.set(sourcePath(t[3]), {
				mode: t[1].slice(0, 6),
				blob: t[2]
			});
		}
		for (const t of e.source.files) {
			const e = d.get(t.path);
			if (e?.mode !== t.mode || e.blob !== t.blob) throw new Error(`source witness does not preserve ${JSON.stringify(t.path)}`);
		}
		for (const t of e.source.deleted) if (d.has(t)) throw new Error(`source witness does not preserve deletion of ${JSON.stringify(t)}`);
		await verifyBlobs(o, [...new Set(e.source.files.map((e) => e.blob))], c, e.signal);
		const revalidate = () => {
			e.signal?.throwIfAborted();
			const n = Date.now() + baseBudgetMs;
			const r = storageIdentity(a, i, t, n);
			const c = resolveRef(o, t, n);
			if (r.identity !== s.identity || c.oid !== l.oid || c.commit !== l.commit) throw new Error("source witness changed while preservation was being verified");
		};
		revalidate();
		return {
			ok: true,
			witness: {
				gitDir: a,
				ref: t,
				commit: n
			},
			revalidate
		};
	} catch (e) {
		return {
			ok: false,
			reason: e instanceof Error ? e.message : "source witness could not be verified",
			error: e,
			...hasUnjoinedWork(e) ? { unjoined: true } : {}
		};
	}
}
//#endregion
//#region scripts/crabbox-staging-identity.mts
const statIdentifierSchema = string().regex(/^(?:0|[1-9]\d*)$/u);
const directoryIdentitySchema = strictObject({
	dev: statIdentifierSchema,
	ino: statIdentifierSchema,
	stable: strictObject({
		path: string().refine(isAbsolute),
		birthtimeNs: string().regex(/^[1-9]\d*$/u),
		volume: string().min(1)
	}).optional()
});
const volumes = /* @__PURE__ */ new Map();
function volumeIdentity(e, t) {
	if (process.platform !== "darwin") return "device:" + t;
	const n = volumes.get(t);
	if (n) return n;
	if (volumes.size === 0) queueMicrotask(() => volumes.clear());
	const r = {
		encoding: "utf8",
		env: {},
		timeout: 5e3,
		maxBuffer: 1048576
	};
	const i = spawnSync("/usr/bin/stat", [
		"-f",
		"%Sd",
		e
	], r);
	if (i.error || i.status !== 0 || !/^disk\d+(?:s\d+)*\s*$/u.test(i.stdout)) {
		volumes.set(t, "device:" + t);
		return "device:" + t;
	}
	const a = spawnSync("/usr/sbin/diskutil", [
		"info",
		"-plist",
		i.stdout.trim()
	], r);
	const o = /<key>VolumeUUID<\/key>\s*<string>([a-f0-9-]+)<\/string>/iu.exec(a.stdout)?.[1];
	if (a.error || a.status !== 0 || !o || !uuid().safeParse(o.toLowerCase()).success) {
		volumes.set(t, "device:" + t);
		return "device:" + t;
	}
	const s = "uuid:" + o.toLowerCase();
	volumes.set(t, s);
	return s;
}
function captureDirectoryIdentity(e, t = lstatSync(e, { bigint: true })) {
	if (!t.isDirectory() || t.isSymbolicLink()) throw new Error("staging directory was replaced: " + e);
	const n = String(t.dev);
	const r = String(t.ino);
	if (t.birthtimeNs <= 0n) return {
		dev: n,
		ino: r
	};
	const i = realpathSync(e);
	const a = volumeIdentity(i, n);
	const o = lstatSync(i, { bigint: true });
	if (o.dev !== t.dev || o.ino !== t.ino || o.birthtimeNs !== t.birthtimeNs) throw new Error("staging directory changed during volume lookup: " + e);
	return {
		dev: n,
		ino: r,
		stable: {
			path: i,
			birthtimeNs: String(t.birthtimeNs),
			volume: a
		}
	};
}
function sameDirectoryIdentity(e, t, n) {
	if (e.ino !== t.ino) return false;
	if (t.stable) return Boolean(e.stable && e.stable.path === t.stable.path && e.stable.birthtimeNs === t.stable.birthtimeNs && (e.stable.volume === t.stable.volume || t.stable.volume === "device:" + t.dev && e.dev === t.dev));
	if (e.stable && n !== void 0 && BigInt(e.stable.birthtimeNs) > n) return false;
	if (e.dev === t.dev) return true;
	return Boolean(process.platform === "darwin" && e.stable?.volume.startsWith("uuid:") && n !== void 0 && BigInt(e.stable.birthtimeNs) <= n);
}
function upgradeDirectoryIdentity(e, t, n) {
	const r = captureDirectoryIdentity(e);
	if (!sameDirectoryIdentity(r, t, n)) throw new Error("staging directory identity changed: " + e);
	return r;
}
//#endregion
//#region scripts/crabbox-staging-artifacts.mts
const outputNames = ["captures", "runs"];
const maxEntries = 1e5;
const sha256 = /^[a-f0-9]{64}$/u;
function artifactPath$1(e) {
	const t = e.split("/");
	return e.length <= 4096 && !isAbsolute(e) && !e.includes("\\") && !e.includes("\0") && outputNames.some((e) => t[0] === e) && t.every((e) => e && e !== "." && e !== "..");
}
const crabboxArtifactIdentitySchema = directoryIdentitySchema;
const entrySchema$1 = discriminatedUnion("kind", [strictObject({
	path: string().refine(artifactPath$1),
	kind: literal("directory")
}), strictObject({
	path: string().refine((e) => artifactPath$1(e) && e.includes("/")),
	kind: literal("file"),
	bytes: number().int().min(0).max(Number.MAX_SAFE_INTEGER),
	sha256: string().regex(sha256)
})]);
const evidenceFields = {
	version: literal(1),
	durable: boolean(),
	sourceIdentity: crabboxArtifactIdentitySchema,
	entries: array(entrySchema$1).max(maxEntries)
};
const crabboxArtifactEvidenceSchema = discriminatedUnion("kind", [strictObject({
	...evidenceFields,
	kind: literal("none")
}), strictObject({
	...evidenceFields,
	kind: literal("copied"),
	repository: strictObject({
		path: string(),
		identity: crabboxArtifactIdentitySchema
	}),
	parents: strictObject({
		crabbox: crabboxArtifactIdentitySchema,
		wrapperArtifacts: crabboxArtifactIdentitySchema
	}),
	destination: strictObject({
		path: string(),
		identity: crabboxArtifactIdentitySchema
	})
})]);
function directory(e, t, n) {
	const r = lstatSync(e, { bigint: true });
	if (!r.isDirectory() || t && !sameDirectoryIdentity(captureDirectoryIdentity(e, r), t, n)) throw new Error("artifact directory is missing, replaced, or not a real directory: " + e);
	return r;
}
function optionalDirectory(e) {
	const t = lstatSync(e, {
		bigint: true,
		throwIfNoEntry: false
	});
	if (t && !t.isDirectory()) throw new Error("artifact path must be a real directory: " + e);
	return t;
}
function sameFile(e, t) {
	return e.dev === t.dev && e.ino === t.ino && e.mode === t.mode && e.size === t.size && e.mtimeNs === t.mtimeNs && e.ctimeNs === t.ctimeNs;
}
function names(e) {
	const t = readdirSync(e, { encoding: "buffer" });
	if (t.length > maxEntries) throw new Error("artifact directory exceeds its entry limit");
	return t.map((e) => {
		if (!isUtf8(e)) throw new Error("artifact filename is not UTF-8");
		return e.toString("utf8");
	}).toSorted();
}
function privateDirectory(e) {
	mkdirSync(e, { mode: 448 });
	chmodSync(e, 448);
	return captureDirectoryIdentity(e, directory(e));
}
function hashFile(e, t, n, r, i) {
	const a = openSync(e, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
	let o;
	try {
		const s = fstatSync(a, { bigint: true });
		if (!s.isFile() || !sameFile(s, t) || s.size > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error("artifact file changed or is not a supported regular file: " + e);
		if (r !== void 0) {
			o = openSync(r, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
			fchmodSync(o, 384);
		}
		const c = createHash("sha256");
		let l = Number(s.size);
		while (l > 0) {
			const t = readSync(a, n, 0, Math.min(n.length, l), null);
			if (!t) throw new Error("artifact file became shorter while reading: " + e);
			c.update(n.subarray(0, t));
			if (o !== void 0) for (let e = 0; e < t;) {
				const i = writeSync(o, n, e, t - e);
				if (!i) throw new Error("artifact copy made no progress: " + r);
				e += i;
			}
			l -= t;
		}
		if (!sameFile(s, fstatSync(a, { bigint: true })) || !sameFile(s, lstatSync(e, { bigint: true }))) throw new Error("artifact file changed while reading: " + e);
		if (o !== void 0) {
			if (!flushDescriptor(o)) i?.();
		}
		return {
			bytes: Number(s.size),
			sha256: c.digest("hex")
		};
	} finally {
		try {
			if (o !== void 0) closeSync(o);
		} finally {
			closeSync(a);
		}
	}
}
function inventory$1(e, t = {}) {
	const n = [];
	const r = Buffer.alloc(65536);
	const i = optionalDirectory(e);
	if (!i) return n;
	if (t.destination && process.platform !== "win32" && (i.mode & 511n) !== 448n) throw new Error("preserved artifact destination permissions changed");
	if (t.destination && names(e).some((e) => !outputNames.some((t) => t === e))) throw new Error("preserved artifact destination gained an unexpected entry");
	const walk = (e, i, a, o = 0) => {
		if (o > 128) throw new Error("artifact directory nesting exceeds its inspection limit");
		if (!artifactPath$1(i) || n.length >= maxEntries) throw new Error("artifact inventory contains an unsupported path or exceeds its entry limit");
		const s = lstatSync(e, { bigint: true });
		if (s.isDirectory()) {
			if (t.destination && process.platform !== "win32" && (s.mode & 511n) !== 448n) throw new Error("preserved artifact directory permissions changed: " + e);
			const r = {
				path: i,
				kind: "directory"
			};
			n.push(r);
			if (a) {
				privateDirectory(join(a.root, i));
				a.copied.push(r);
			}
			for (const t of names(e)) walk(join(e, t), i + "/" + t, a, o + 1);
			if (!sameFile(s, lstatSync(e, { bigint: true }))) throw new Error("artifact directory changed while reading: " + e);
		} else if (s.isFile()) {
			if (t.destination && process.platform !== "win32" && (s.mode & 511n) !== 384n) throw new Error("preserved artifact file permissions changed: " + e);
			const o = {
				path: i,
				kind: "file",
				...hashFile(e, s, r, a && join(a.root, i), a?.nondurable)
			};
			n.push(o);
			a?.copied.push(o);
		} else throw new Error("artifact must be a regular file or real directory: " + e);
	};
	for (const n of outputNames) {
		const r = join(e, n);
		if (optionalDirectory(r)) walk(r, n, names(r).length > 0 ? t.target?.() : void 0);
	}
	if (!sameFile(i, directory(e, captureDirectoryIdentity(e, i)))) throw new Error("artifact root changed during inspection");
	return n.toSorted((e, t) => e.path < t.path ? -1 : e.path > t.path ? 1 : 0);
}
function sourceInventory(e, t, n, r) {
	const i = directory(e, t, r);
	const a = inventory$1(join(e, ".crabbox"), { target: n });
	if (!sameFile(i, directory(e, t, r))) throw new Error("artifact source checkout changed during inspection");
	return a;
}
function copiedEntries(e) {
	const t = new Set(e.filter((e) => e.path.includes("/")).map((e) => e.path.split("/")[0]));
	return e.filter((e) => t.has(e.path.split("/")[0]));
}
function sameInventory(e, t, n = false) {
	const r = new Map(t.map((e) => [e.path, e]));
	if (r.size !== t.length || e.some((e) => JSON.stringify(r.get(e.path)) !== JSON.stringify(e)) || !n && e.length !== t.length) throw new Error("artifact layout or bytes do not match the preservation evidence");
}
function overlaps$1(e, t) {
	const contains = (e, t) => {
		const n = relative(e, t);
		return n === "" || !isAbsolute(n) && n !== ".." && !n.startsWith(".." + sep);
	};
	return contains(e, t) || contains(t, e);
}
function verifyDestination(e, t, n = false, r) {
	const i = t.repository.path;
	const a = join(i, ".crabbox", "wrapper-artifacts");
	if (!isAbsolute(i) || realpathSync(i) !== i || dirname(t.destination.path) !== a || !basename(t.destination.path).startsWith("run-") || overlaps$1(e, t.destination.path)) throw new Error("artifact preservation destination is not independent of the disposable checkout");
	directory(i, t.repository.identity, r);
	directory(join(i, ".crabbox"), t.parents.crabbox, r);
	directory(a, t.parents.wrapperArtifacts, r);
	const o = directory(t.destination.path, t.destination.identity, r);
	if (process.platform !== "win32" && (o.mode & 511n) !== 448n) throw new Error("preserved artifact destination permissions changed");
	sameInventory(inventory$1(t.destination.path, { destination: true }), n ? t.entries : copiedEntries(t.entries));
	directory(i, t.repository.identity, r);
	directory(join(i, ".crabbox"), t.parents.crabbox, r);
	directory(a, t.parents.wrapperArtifacts, r);
	directory(t.destination.path, t.destination.identity, r);
}
/** Revalidate saved outputs; only missing source entries can be tolerated after partial disposal. */
function verifyPreservedCrabboxArtifacts(e, t, n = false, r) {
	const i = crabboxArtifactEvidenceSchema.parse(t);
	const a = optionalDirectory(e);
	const o = a ? realpathSync(e) : resolve(e);
	if (a && !sameDirectoryIdentity(captureDirectoryIdentity(o, a), i.sourceIdentity, r)) throw new Error("artifact source checkout was replaced");
	if (i.kind === "none") {
		if (copiedEntries(i.entries).length !== 0) throw new Error("no-output evidence contains artifacts requiring preservation");
	} else verifyDestination(o, i, false, r);
	sameInventory(a ? sourceInventory(o, i.sourceIdentity, void 0, r) : [], i.entries, n);
	if (a) directory(o, i.sourceIdentity, r);
}
function flushDescriptor(e) {
	try {
		fsyncSync(e);
		return true;
	} catch (e) {
		if ([
			"EINVAL",
			"ENOTSUP",
			"EOPNOTSUPP",
			"ENOSYS"
		].includes(e.code ?? "")) return false;
		throw e;
	}
}
function flushDirectory(e) {
	if (process.platform === "win32") return false;
	let t;
	try {
		t = openSync(e, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY);
		return flushDescriptor(t);
	} catch (e) {
		if ([
			"EINVAL",
			"ENOTSUP",
			"EOPNOTSUPP",
			"ENOSYS"
		].includes(e.code ?? "")) return false;
		throw e;
	} finally {
		if (t !== void 0) closeSync(t);
	}
}
/** Copy only native run/capture outputs into a fresh, private original-repository destination. */
function preserveCrabboxArtifacts(e, t, n, r) {
	if (e === t) return;
	const i = captureDirectoryIdentity(e, directory(e));
	const a = realpathSync(e);
	const o = {};
	const s = [];
	try {
		const e = sourceInventory(a, i, () => {
			if (!o.copied) {
				const e = captureDirectoryIdentity(t, directory(t, n, r));
				const s = realpathSync(t);
				const c = join(s, ".crabbox");
				const l = join(c, "wrapper-artifacts");
				if (overlaps$1(a, l)) throw new Error("artifact preservation destination overlaps the disposable checkout");
				for (const e of [c, l]) if (!optionalDirectory(e)) privateDirectory(e);
				const u = mkdtempSync(join(l, "run-"));
				chmodSync(u, 448);
				o.copied = {
					version: 1,
					durable: process.platform !== "win32",
					kind: "copied",
					sourceIdentity: i,
					entries: [],
					repository: {
						path: s,
						identity: e
					},
					parents: {
						crabbox: captureDirectoryIdentity(c, directory(c)),
						wrapperArtifacts: captureDirectoryIdentity(l, directory(l))
					},
					destination: {
						path: u,
						identity: captureDirectoryIdentity(u, directory(u))
					}
				};
			}
			return {
				root: o.copied.destination.path,
				copied: s,
				nondurable: () => {
					o.copied.durable = false;
				}
			};
		});
		directory(a, i);
		sameInventory(sourceInventory(a, i), e);
		const c = o.copied;
		if (!c) return {
			version: 1,
			durable: true,
			kind: "none",
			sourceIdentity: i,
			entries: e
		};
		c.entries = e;
		verifyDestination(a, c);
		for (const e of s.toReversed()) if (e.kind === "directory") c.durable = flushDirectory(join(c.destination.path, e.path)) && c.durable;
		for (const e of [
			c.destination.path,
			dirname(c.destination.path),
			join(c.repository.path, ".crabbox"),
			c.repository.path
		]) c.durable = flushDirectory(e) && c.durable;
		directory(a, i);
		console.error(`[crabbox] preserved temporary artifacts: ${join(a, ".crabbox")} -> ${relative(t, c.destination.path)}`);
		return c;
	} catch (e) {
		const t = o.copied;
		if (t) try {
			verifyDestination(a, {
				...t,
				entries: s
			}, true);
			rmSync(t.destination.path, { recursive: true });
		} catch {
			throw new Error("artifact preservation failed; partial output may remain at " + t.destination.path, { cause: e });
		}
		throw e;
	}
}
//#endregion
//#region scripts/crabbox-staging-claims.mts
const stdoutLimit$1 = 4194304;
const stderrLimit$1 = 65536;
const commandTimeoutMs = 5e3;
const inspectionBudgetMs = 1e4;
const pathSchema = string().min(1).max(8192).refine((e) => isAbsolute(e) && !e.includes("\0"));
const claimNamespaceSchema = strictObject({
	version: literal(1),
	platform: string(),
	cwd: pathSchema,
	directory: pathSchema,
	anchor: directoryIdentitySchema.extend({ path: pathSchema })
});
const inventorySchema = object({
	version: literal(1),
	source: literal("local-claims"),
	claims: array(object({
		leaseId: string().min(1).max(512),
		repoRoot: union([literal(""), pathSchema])
	})).max(1e4),
	problems: array(unknown()).max(100)
});
var ClaimInventoryHold = class extends Error {
	constructor(e, t) {
		super(e);
		this.matchingLeaseIds = t;
	}
};
function envValue(e, t) {
	if (process.platform !== "win32") return e[t] ?? "";
	const n = Object.entries(e).filter(([e]) => e.toUpperCase() === t.toUpperCase()).map(([, e]) => e ?? "");
	if (new Set(n).size > 1) throw new ClaimInventoryHold("The native claims environment has ambiguous location variables.");
	return n[0] ?? "";
}
function nativeLocation(e, t) {
	let n;
	let r = envValue(t, "XDG_STATE_HOME");
	let i;
	if (r !== "") {
		n = "XDG_STATE_HOME";
		i = ["crabbox", "claims"];
	} else if (process.platform === "win32") {
		n = "AppData";
		r = envValue(t, n);
		i = [
			"crabbox",
			"state",
			"claims"
		];
	} else if (process.platform === "darwin") {
		n = "HOME";
		r = envValue(t, n);
		i = [
			"Library",
			"Application Support",
			"crabbox",
			"state",
			"claims"
		];
	} else {
		n = "XDG_CONFIG_HOME";
		r = envValue(t, n);
		if (r !== "") {
			if (!isAbsolute(r)) throw new ClaimInventoryHold("Native claims require an absolute XDG_CONFIG_HOME.");
			i = [
				"crabbox",
				"state",
				"claims"
			];
		} else {
			n = "HOME";
			r = envValue(t, n);
			i = [
				".config",
				"crabbox",
				"state",
				"claims"
			];
		}
	}
	if (!r || r.includes("\0")) throw new ClaimInventoryHold("The native claims state location is unavailable.");
	if (process.platform === "win32" && /^[a-z]:(?:[^\\/]|$)/iu.test(r)) throw new ClaimInventoryHold("A drive-relative native claims location cannot be preserved safely.");
	const a = resolve(e, r);
	return {
		key: n,
		base: a,
		directory: join(a, ...i)
	};
}
function directoryLocation(e) {
	let t = resolve(e);
	const n = [];
	for (let e = 0; e < 128; e += 1) {
		if (lstatSync(t, {
			bigint: true,
			throwIfNoEntry: false
		})) {
			const e = realpathSync(t);
			const r = statSync(e, { bigint: true });
			if (!r.isDirectory()) throw new ClaimInventoryHold("A native claims path is not a readable directory.");
			return {
				directory: resolve(e, ...n),
				anchor: {
					path: e,
					...captureDirectoryIdentity(e, r)
				},
				generation: `${r.mode}:${r.size}:${r.mtimeNs}:${r.ctimeNs}`
			};
		}
		const e = dirname(t);
		if (e === t) break;
		n.unshift(relative(e, t));
		t = e;
	}
	throw new ClaimInventoryHold("The native claims directory cannot be established.");
}
/** Bind discovery to the original native child's location without creating state. */
function captureClaimNamespace(e, t = process.env) {
	const n = realpathSync(e);
	if (!statSync(n).isDirectory()) throw new ClaimInventoryHold("The original native working directory is unavailable.");
	const r = directoryLocation(nativeLocation(n, t).directory);
	return claimNamespaceSchema.parse({
		version: 1,
		platform: process.platform,
		cwd: n,
		directory: r.directory,
		anchor: r.anchor
	});
}
function inspectNamespace(e, t, n) {
	if (e.platform !== process.platform) throw new ClaimInventoryHold("The native claims namespace belongs to a different platform.");
	const r = lstatSync(e.anchor.path, { bigint: true });
	if (!r.isDirectory() || realpathSync(e.anchor.path) !== e.anchor.path || !sameDirectoryIdentity(captureDirectoryIdentity(e.anchor.path, r), e.anchor, n)) throw new ClaimInventoryHold("The original native claims namespace was replaced.");
	const i = nativeLocation(e.cwd, t);
	const a = directoryLocation(i.directory);
	if (a.directory !== e.directory) throw new ClaimInventoryHold("The native claims state location changed since staging was created.");
	return {
		selected: i,
		current: a
	};
}
function childEnvironment(e, t, n) {
	const r = { ...e };
	for (const e of Object.keys(r)) if (e === t || process.platform === "win32" && e.toUpperCase() === t.toUpperCase()) delete r[e];
	r[t] = n;
	return r;
}
function within(e, t) {
	const n = relative(e, t);
	return n === "" || !isAbsolute(n) && n !== ".." && !n.startsWith(".." + sep);
}
/** Read the native public inventory; absence is not a provider-liveness claim. */
async function verifyNoStagingClaims(e) {
	try {
		e.signal?.throwIfAborted();
		const t = claimNamespaceSchema.safeParse(e.namespace);
		if (!t.success) throw new ClaimInventoryHold("The recorded native claims namespace is invalid.");
		const n = t.data;
		const r = { ...e.env ?? process.env };
		const i = inspectNamespace(n, r, e.legacyBeforeNs);
		if (!isAbsolute(e.sourceRoot) || e.sourceRoot.includes("\0")) throw new ClaimInventoryHold("The staging source path must be absolute.");
		const a = directoryLocation(e.sourceRoot).directory;
		const o = Date.now() + inspectionBudgetMs;
		const s = new AbortController();
		const c = e.signal ? AbortSignal.any([e.signal, s.signal]) : s.signal;
		let l;
		const u = Buffer.alloc(stdoutLimit$1);
		let d = 0;
		let f = 0;
		const exceedLimit = () => {
			l ??= new ClaimInventoryHold("Native claim inventory exceeded its output limit.");
			s.abort(l);
		};
		let p;
		try {
			p = await runManagedCommand({
				bin: e.binary,
				args: [
					"claims",
					"list",
					"--json"
				],
				cwd: e.cwd,
				env: childEnvironment(r, i.selected.key, i.selected.base),
				stdio: [
					"ignore",
					"pipe",
					"pipe"
				],
				timeoutMs: commandTimeoutMs,
				signal: c,
				requireProcessTreeExit: process.platform !== "win32",
				onReady(e) {
					if (!e.stdout || !e.stderr) throw new ClaimInventoryHold("Native claim inventory output is unavailable.");
					e.stdout.on("data", (e) => {
						if (l) return;
						if (d + e.length > stdoutLimit$1) {
							exceedLimit();
							return;
						}
						d += e.copy(u, d);
					});
					e.stderr.on("data", (e) => {
						f += e.length;
						if (f > stderrLimit$1) exceedLimit();
					});
				}
			});
		} catch (e) {
			if (l && l !== e) throw new AggregateError([l, e], l.message, { cause: e });
			throw e;
		}
		if (l) throw l;
		if (p !== 0) throw new ClaimInventoryHold("Native claim inventory failed or returned only partial results.");
		const m = u.subarray(0, d);
		let h;
		try {
			if (!isUtf8(m)) throw new Error("invalid encoding");
			h = JSON.parse(m.toString("utf8"));
		} catch {
			throw new ClaimInventoryHold("Native claim inventory did not return valid JSON.");
		}
		const g = inventorySchema.safeParse(h);
		if (!g.success) throw new ClaimInventoryHold("Native claim inventory has an unsupported or malformed schema.");
		if (g.data.problems.length > 0) throw new ClaimInventoryHold("Native claim inventory reports unreadable or invalid local records.");
		const _ = /* @__PURE__ */ new Set();
		for (const e of g.data.claims) {
			if (Date.now() >= o) throw new ClaimInventoryHold("Native claim inventory exceeded its inspection budget.");
			if (e.repoRoot && within(a, directoryLocation(e.repoRoot).directory)) {
				_.add(e.leaseId);
				if (_.size === 16) break;
			}
		}
		if (_.size > 0) throw new ClaimInventoryHold("Local claims still name this staging source; stop or reclaim the matching leases before retrying.", [..._]);
		const v = inspectNamespace(n, r, e.legacyBeforeNs);
		if (JSON.stringify(v.current) !== JSON.stringify(i.current)) throw new ClaimInventoryHold("The native claims namespace changed during inventory.");
		e.signal?.throwIfAborted();
		return { ok: true };
	} catch (e) {
		return {
			ok: false,
			reason: e instanceof ClaimInventoryHold ? e.message : "Native claim inventory could not be verified.",
			error: e,
			...hasUnjoinedWork(e) ? { unjoined: true } : {},
			...e instanceof ClaimInventoryHold && e.matchingLeaseIds ? { matchingLeaseIds: e.matchingLeaseIds } : {}
		};
	}
}
//#endregion
//#region scripts/crabbox-staging-location.mts
const stagingPrefix = "openclaw-crabbox-sync-";
const gitRoutingKeys = /* @__PURE__ */ new Set([
	"GIT_DIR",
	"GIT_WORK_TREE",
	"GIT_CEILING_DIRECTORIES",
	"GIT_DISCOVERY_ACROSS_FILESYSTEM"
]);
function prospectiveDirectory(e) {
	let t = resolve(e);
	const n = [];
	for (let e = 0; e < 128; e += 1) try {
		const e = realpathSync(t);
		if (!statSync(e).isDirectory()) return;
		accessSync(e, constants.R_OK | constants.X_OK);
		return resolve(e, ...n);
	} catch (e) {
		if (e.code !== "ENOENT") return;
		if (lstatSync(t, { throwIfNoEntry: false })) return;
		const r = dirname(t);
		if (r === t) return;
		n.unshift(basename(t));
		t = r;
	}
}
function overlaps(e, t) {
	const n = process.platform === "darwin" || process.platform === "win32";
	const r = n ? e.toLowerCase() : e;
	const i = n ? t.toLowerCase() : t;
	const contains = (e, t) => {
		const n = relative(e, t);
		return n === "" || !isAbsolute(n) && n !== ".." && !n.startsWith(`..${sep}`);
	};
	return contains(r, i) || contains(i, r);
}
/**
* Optional recovery registration; false must never prevent ordinary staging.
* This checks the selected source/workspace only. Arbitrary extra host mounts
* are not isolated by recovery registration, and no host tree is traversed.
*/
function canRecordStaging(e, t, n = process.env) {
	try {
		const r = realpathSync(t);
		if (!statSync(r).isDirectory()) return false;
		accessSync(r, constants.R_OK | constants.X_OK);
		const i = prospectiveDirectory(e);
		if (!i || overlaps(i, r)) return false;
		for (const [e, t] of Object.entries(n)) {
			const n = e.toUpperCase();
			if (t && (n === "GIT_DIR" || n === "GIT_WORK_TREE") && !isAbsolute(t)) return false;
		}
		const a = Object.fromEntries(Object.entries(n).filter(([e]) => {
			const t = e.toUpperCase();
			return !t.startsWith("GIT_") || gitRoutingKeys.has(t);
		}));
		const o = spawnSync("git", ["rev-parse", "--show-toplevel"], {
			cwd: r,
			env: {
				...a,
				GIT_OPTIONAL_LOCKS: "0",
				GIT_TERMINAL_PROMPT: "0"
			},
			stdio: [
				"ignore",
				"pipe",
				"pipe"
			],
			timeout: 5e3,
			killSignal: "SIGKILL",
			maxBuffer: 1048576
		});
		if (o.error || o.status !== 0 || !isUtf8(o.stdout)) return false;
		const s = o.stdout.toString("utf8").replace(/\r?\n$/u, "");
		if (!isAbsolute(s)) return false;
		const c = realpathSync(s);
		if (!statSync(c).isDirectory()) return false;
		accessSync(c, constants.R_OK | constants.X_OK);
		return !overlaps(i, c);
	} catch {
		return false;
	}
}
//#endregion
//#region scripts/crabbox-staging-provenance.mts
const uuidSchema = uuid().refine((e) => e === e.toLowerCase() && e !== "00000000-0000-0000-0000-000000000000" && e !== "ffffffff-ffff-ffff-ffff-ffffffffffff");
const processProvenanceSchema = discriminatedUnion("platform", [strictObject({
	platform: literal("darwin"),
	hostId: uuidSchema,
	bootId: uuidSchema,
	pidNamespace: literal("")
}), strictObject({
	platform: literal("linux"),
	hostId: string().regex(/^(?!0{32}$)[a-f0-9]{32}$/u),
	bootId: uuidSchema,
	pidNamespace: string().regex(/^pid:\[[1-9]\d{0,19}\]$/u)
})]).readonly();
function readBounded$1(e, t) {
	const n = openSync(e, constants.O_RDONLY | constants.O_NONBLOCK);
	try {
		const e = Buffer.alloc(t + 1);
		let r = 0;
		while (r < e.length) {
			const t = readSync(n, e, r, e.length - r, null);
			if (!t) return e.subarray(0, r).toString("utf8").trim();
			r += t;
		}
		throw new Error("Process provenance exceeds its read limit.");
	} finally {
		closeSync(n);
	}
}
function systemOutput(e, t, n = 1024) {
	const r = spawnSync(e, t, {
		encoding: "utf8",
		env: {},
		timeout: 1e3,
		maxBuffer: n
	});
	if (r.error || r.status !== 0) throw new Error("Process provenance is unavailable.");
	return r.stdout.trim();
}
let cachedProvenance;
function currentProcessProvenance() {
	if (cachedProvenance !== void 0) return cachedProvenance ?? void 0;
	try {
		if (process.platform === "darwin") {
			const e = systemOutput("/usr/sbin/ioreg", [
				"-rd1",
				"-c",
				"IOPlatformExpertDevice"
			], 65536);
			const t = /"IOPlatformUUID"\s*=\s*"([a-f0-9-]+)"/iu.exec(e)?.[1];
			cachedProvenance = processProvenanceSchema.parse({
				platform: "darwin",
				hostId: t?.toLowerCase(),
				bootId: systemOutput("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"]).toLowerCase(),
				pidNamespace: ""
			});
		} else if (process.platform === "linux") cachedProvenance = processProvenanceSchema.parse({
			platform: "linux",
			hostId: readBounded$1("/etc/machine-id", 128),
			bootId: readBounded$1("/proc/sys/kernel/random/boot_id", 128).toLowerCase(),
			pidNamespace: readlinkSync("/proc/self/ns/pid")
		});
		else cachedProvenance = null;
	} catch {
		cachedProvenance = null;
	}
	return cachedProvenance ?? void 0;
}
let cachedBootTimeNs;
function currentBootTimeNs() {
	if (cachedBootTimeNs !== void 0) return cachedBootTimeNs ?? void 0;
	try {
		let e;
		let t = "0";
		if (process.platform === "darwin") {
			const n = systemOutput("/usr/sbin/sysctl", ["-n", "kern.boottime"]);
			const r = /^\{\s*sec\s*=\s*([1-9]\d*),\s*usec\s*=\s*(\d{1,6})\s*\}(?:\s+[^\r\n]*)?$/u.exec(n);
			e = r?.[1];
			t = r?.[2] ?? "0";
		} else if (process.platform === "linux") {
			const t = readBounded$1("/proc/stat", 1048576);
			e = /^btime ([1-9]\d*)$/mu.exec(t)?.[1];
		}
		if (!e) throw new Error("Boot time is unavailable.");
		cachedBootTimeNs = BigInt(e) * 1000000000n + BigInt(t) * 1000n;
	} catch {
		cachedBootTimeNs = null;
	}
	return cachedBootTimeNs ?? void 0;
}
const processDomains = /* @__PURE__ */ new WeakMap();
function processDomain(e = currentProcessProvenance()) {
	if (!e) return;
	const t = processDomains.get(e);
	if (t !== void 0) return t;
	const n = createHash("sha256").update(e.platform + ":" + e.bootId + ":" + e.pidNamespace).digest("hex");
	processDomains.set(e, n);
	return n;
}
//#endregion
//#region scripts/crabbox-staging-users.mts
const stdoutLimit = 1048576;
const stderrLimit = 65536;
function inspectUsers(e, t) {
	if (!e.endsWith("\n") || e.includes("\0")) return {
		ok: false,
		reason: "lsof returned malformed staging-user records."
	};
	const n = /* @__PURE__ */ new Set();
	let r;
	let i;
	let a = false;
	const finishFile = () => {
		if (!i) return true;
		if (i.device === void 0 || i.inode === void 0) return false;
		if (r !== process.pid || !t.has(i.device + ":" + i.inode)) n.add(r);
		a = true;
		i = void 0;
		return true;
	};
	for (const t of e.slice(0, -1).split("\n")) {
		const e = t.slice(1);
		if (t.startsWith("p") && /^[1-9]\d*$/u.test(e)) {
			if (!finishFile() || r !== void 0 && !a) return {
				ok: false,
				reason: "lsof returned incomplete staging-user records."
			};
			r = Number(e);
			a = false;
			if (!Number.isSafeInteger(r) || r > 2147483647) return {
				ok: false,
				reason: "lsof returned an invalid staging-user PID."
			};
		} else if (t.startsWith("f") && /^[a-z0-9]+$/iu.test(e) && r !== void 0) {
			if (!finishFile()) return {
				ok: false,
				reason: "lsof returned incomplete staging-user records."
			};
			i = {};
		} else if (t.startsWith("D") && /^0x[a-f0-9]{1,16}$/iu.test(e) && i && i.device === void 0) i.device = String(BigInt(e));
		else if (t.startsWith("i") && /^[1-9]\d{0,19}$/u.test(e) && i && i.inode === void 0) i.inode = e;
		else return {
			ok: false,
			reason: "lsof returned unknown staging-user records."
		};
	}
	if (!finishFile() || r === void 0 || !a) return {
		ok: false,
		reason: "lsof returned incomplete staging-user records."
	};
	if (n.size) return {
		ok: false,
		reason: `Live staging users remain (PIDs ${[...n].slice(0, 16).join(", ")}${n.size > 16 ? ", …" : ""}).`
	};
	return { ok: true };
}
async function verifyNoStagingUsers(e) {
	let t;
	try {
		e.signal?.throwIfAborted();
		const n = process.platform === "darwin" ? "/usr/sbin/lsof" : process.platform === "linux" ? "/usr/bin/lsof" : void 0;
		if (!n || e.roots.length === 0) return {
			ok: false,
			reason: "A supported lsof staging-user check is unavailable."
		};
		const r = [...new Set(e.roots)];
		const i = new Set(e.ignoredFiles ?? []);
		const a = /* @__PURE__ */ new Set();
		for (const e of r) if (!isAbsolute(e) || realpathSync(e) !== e || !lstatSync(e).isDirectory()) return {
			ok: false,
			reason: "Staging-user check requires canonical directory paths."
		};
		for (const e of i) {
			const t = lstatSync(e, { bigint: true });
			if (!isAbsolute(e) || realpathSync(e) !== e || !t.isFile() || t.nlink !== 1n) return {
				ok: false,
				reason: "Staging-user lock exemption requires a canonical regular file."
			};
			a.add(t.dev + ":" + t.ino);
		}
		const o = Date.now() + 6e4;
		for (const i of r) {
			const r = o - Date.now();
			if (r <= 0) return {
				ok: false,
				reason: "Staging-user inspection exceeded its time limit."
			};
			const s = new AbortController();
			const c = e.signal ? AbortSignal.any([e.signal, s.signal]) : s.signal;
			const l = Buffer.alloc(stdoutLimit);
			let u = 0;
			let d = 0;
			const exceedLimit = () => {
				t ??= "lsof staging-user output exceeded its limit.";
				s.abort(new Error(t));
			};
			const f = await runManagedCommand({
				bin: n,
				args: [
					"-nP",
					"-FpfDi",
					"+D",
					i
				],
				env: {
					PATH: "/usr/bin:/bin:/usr/sbin:/sbin",
					LC_ALL: "C"
				},
				stdio: [
					"ignore",
					"pipe",
					"pipe"
				],
				timeoutMs: r,
				signal: c,
				requireProcessTreeExit: true,
				onReady(e) {
					if (!e.stdout || !e.stderr) throw new Error("lsof output streams are unavailable.");
					e.stdout.on("data", (e) => {
						if (t) return;
						if (u + e.length > stdoutLimit) {
							exceedLimit();
							return;
						}
						u += e.copy(l, u);
					});
					e.stderr.on("data", (e) => {
						d += e.length;
						if (d > stderrLimit) exceedLimit();
					});
				}
			});
			e.signal?.throwIfAborted();
			if (t) return {
				ok: false,
				reason: t
			};
			if (d) return {
				ok: false,
				reason: "lsof reported an incomplete staging-user inspection."
			};
			if (f === 1 && u === 0) continue;
			if (f !== 0 && f !== 1 || u === 0) return {
				ok: false,
				reason: "lsof did not complete a valid staging-user inspection."
			};
			const p = inspectUsers(l.subarray(0, u).toString("utf8"), a);
			if (!p.ok) return p;
		}
		return { ok: true };
	} catch (e) {
		return {
			ok: false,
			reason: t ?? "lsof could not verify the absence of staging users.",
			...hasUnjoinedWork(e) ? { unjoined: true } : {}
		};
	}
}
//#endregion
//#region scripts/crabbox-staging.mts
const prefix = stagingPrefix;
const receiptName = "staging.json";
const manifestName = "manifest.json";
const headerLimit = 32768;
const manifestLimit = 67108864;
const identitySchema = crabboxArtifactIdentitySchema;
const witnessSchema = strictObject({
	gitDir: string(),
	ref: string(),
	commit: string().regex(/^[a-f0-9]{40}$/u)
});
const operatorConfirmationSchema = strictObject({
	kind: literal("same-host-prior-boot"),
	receiptSha256: string().regex(/^[a-f0-9]{64}$/u),
	receiptMtimeNs: string().regex(/^[1-9]\d*$/u),
	ownerPid: number().int().min(2),
	ownerDomain: string().regex(/^[a-f0-9]{64}$/u).optional(),
	confirmedAt: string().datetime(),
	current: processProvenanceSchema,
	syncRootIdentity: identitySchema,
	rootIdentity: identitySchema
});
const receiptSchema = strictObject({
	version: literal(2),
	id: uuid(),
	ownerPid: number().int().min(2),
	ownerDomain: string().regex(/^[a-f0-9]{64}$/u).optional(),
	ownerProvenance: processProvenanceSchema.optional(),
	operatorConfirmation: operatorConfirmationSchema.optional(),
	syncRootIdentity: identitySchema.optional(),
	repository: string(),
	repositoryIdentity: identitySchema.optional(),
	identityRecordedAtNs: string().regex(/^[1-9]\d*$/u).optional(),
	claims: claimNamespaceSchema.optional(),
	leases: array(string().min(1).max(512)).max(16).optional(),
	kind: _enum(["capsule", "worktree"]),
	rootIdentity: identitySchema,
	payloadIdentity: identitySchema,
	durable: boolean(),
	users: _enum([
		"none",
		"admitted",
		"settled"
	]),
	state: _enum([
		"preparing",
		"prepared",
		"admitted",
		"settled",
		"preserved",
		"removing"
	]),
	manifest: string().regex(/^[a-f0-9]{64}$/u).optional(),
	witness: witnessSchema.optional(),
	artifactManifest: string().regex(/^[a-f0-9]{64}$/u).optional(),
	mirror: strictObject({
		key: string().regex(/^[a-f0-9]{64}$/u),
		slotIdentity: identitySchema,
		idle: boolean(),
		disposing: literal(true).optional(),
		lastUsed: number().int().nonnegative(),
		database: string().regex(/^[a-f0-9]{64}$/u).optional()
	}).optional(),
	hold: _enum([
		"artifacts",
		"claims",
		"writers",
		"registration"
	]).optional()
});
const disposalSchema = strictObject({
	version: literal(1),
	id: uuid(),
	key: string().regex(/^[a-f0-9]{64}$/u),
	slotIdentity: identitySchema,
	receipt: receiptSchema.optional()
});
const entrySchema = strictObject({
	path: string().min(1),
	kind: _enum([
		"file",
		"symlink",
		"directory"
	]),
	mode: _enum([
		"100644",
		"100755",
		"120000"
	]).optional(),
	blob: string().regex(/^[a-f0-9]{40}$/u).optional()
});
const sourceEntrySchema = strictObject({
	path: string().min(1),
	mode: _enum([
		"100644",
		"100755",
		"120000"
	]),
	blob: string().regex(/^[a-f0-9]{40}$/u)
});
const manifestSchema = strictObject({
	source: strictObject({
		files: array(sourceEntrySchema),
		deleted: array(string())
	}),
	entries: array(entrySchema),
	artifacts: crabboxArtifactEvidenceSchema.optional()
});
const identityDeadlines = /* @__PURE__ */ new WeakMap();
function sameIdentity(e, t, n = identityDeadlines.get(t)) {
	return sameDirectoryIdentity(e, t, n);
}
function assertIdentity(e, t, n = identityDeadlines.get(t)) {
	upgradeDirectoryIdentity(e, t, n);
}
function safeRelative(e) {
	return !isAbsolute(e) && !e.includes("\\") && !e.includes("\0") && e.split("/").every((e) => e !== "" && e !== "." && e !== "..");
}
function readBounded(e, t, n) {
	const r = openSync(e, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
	try {
		const e = fstatSync(r, { bigint: true });
		if (!e.isFile() || e.size > BigInt(t)) throw new Error("staging metadata is not a bounded regular file");
		const i = Buffer.alloc(Number(e.size));
		for (let e = 0; e < i.length;) {
			const t = readSync(r, i, e, i.length - e, null);
			if (!t) throw new Error("staging metadata became shorter while reading");
			e += t;
		}
		const a = fstatSync(r, { bigint: true });
		if (e.ino !== a.ino || e.size !== a.size || e.mtimeNs !== a.mtimeNs || e.ctimeNs !== a.ctimeNs) throw new Error("staging metadata changed while reading");
		n?.(e);
		return i;
	} finally {
		closeSync(r);
	}
}
function writeAtomic(e, t, n, r = true) {
	const i = join(e, "." + t + "." + randomUUID());
	try {
		let a = false;
		const o = openSync(i, "wx", 384);
		try {
			writeFileSync(o, n);
			a = r && flushDescriptor(o);
		} finally {
			closeSync(o);
		}
		renameSync(i, join(e, t));
		return a && flushDirectory(e);
	} finally {
		rmSync(i, { force: true });
	}
}
function blob(e, t) {
	if (t) {
		const t = readlinkSync(e, { encoding: "buffer" });
		return createHash("sha1").update("blob " + t.length + "\0").update(t).digest("hex");
	}
	return regularFileDigest(e, (e) => createHash("sha1").update("blob " + e + "\0"));
}
function regularFileDigest(e, t) {
	const n = openSync(e, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
	try {
		const e = fstatSync(n, { bigint: true });
		if (!e.isFile()) throw new Error("staging contains an unsupported file");
		const r = t(e.size);
		const i = Buffer.alloc(65536);
		for (;;) {
			const e = readSync(n, i);
			if (!e) break;
			r.update(i.subarray(0, e));
		}
		const a = fstatSync(n, { bigint: true });
		if (e.size !== a.size || e.mtimeNs !== a.mtimeNs || e.ctimeNs !== a.ctimeNs) throw new Error("staging content changed while reading");
		return r.digest("hex");
	} finally {
		closeSync(n);
	}
}
function artifactPath(e) {
	return e === "source/.crabbox" || ["source/.crabbox/runs", "source/.crabbox/captures"].some((t) => e === t || e.startsWith(t + "/"));
}
function inventory(e, t = /* @__PURE__ */ new Map(), n = false, r) {
	const i = [];
	const walk = (a, o) => {
		for (const s of readdirSync(a)) {
			const a = o ? o + "/" + s : s;
			if (n && artifactPath(a) && a !== "source/.crabbox") continue;
			if (!safeRelative(a)) throw new Error("staging contains an unsupported path");
			const c = join(e, a);
			const l = lstatSync(c);
			r?.(a, l);
			if (l.isDirectory()) {
				if (!n || a !== "source/.crabbox") i.push({
					path: a,
					kind: "directory"
				});
				walk(c, a);
			} else if (l.isFile() || l.isSymbolicLink()) {
				const e = l.isSymbolicLink();
				const n = e ? "120000" : l.mode & 64 ? "100755" : "100644";
				const r = t.get(a);
				if (r && r.mode !== n) throw new Error("source mode changed before sealing: " + a);
				i.push({
					path: a,
					kind: e ? "symlink" : "file",
					mode: n,
					blob: r?.blob ?? blob(c, e)
				});
			} else throw new Error("staging contains an unsupported file kind: " + a);
		}
	};
	walk(e, "");
	return i.toSorted((e, t) => e.path.localeCompare(t.path));
}
function metadataTimestamp(e) {
	return e.birthtimeNs > 0n && e.birthtimeNs < e.mtimeNs ? e.birthtimeNs : e.mtimeNs;
}
function receiptDeadline(e) {
	return e.identityRecordedAtNs ? BigInt(e.identityRecordedAtNs) : identityDeadlines.get(e.rootIdentity);
}
function admitReceiptIdentities(e, t, n) {
	const r = receiptDeadline(t) ?? n;
	for (const e of [
		t.rootIdentity,
		t.syncRootIdentity,
		t.payloadIdentity,
		t.repositoryIdentity,
		t.mirror?.slotIdentity,
		t.claims?.anchor
	]) if (e) identityDeadlines.set(e, r);
	if (lstatSync(e, { throwIfNoEntry: false })) {
		assertIdentity(e, t.rootIdentity);
		if (t.syncRootIdentity) assertIdentity(dirname(e), t.syncRootIdentity);
	}
	return t;
}
function upgradeReceiptIdentities(e, t) {
	const n = receiptDeadline(t);
	t.identityRecordedAtNs ??= n?.toString();
	t.rootIdentity = upgradeDirectoryIdentity(e, t.rootIdentity, n);
	if (t.syncRootIdentity) t.syncRootIdentity = upgradeDirectoryIdentity(dirname(e), t.syncRootIdentity, n);
	const r = join(e, "payload");
	if (lstatSync(r, { throwIfNoEntry: false })) t.payloadIdentity = upgradeDirectoryIdentity(r, t.payloadIdentity, n);
	if (t.mirror) t.mirror.slotIdentity = upgradeDirectoryIdentity(join(dirname(e), "mirrors", t.mirror.key), t.mirror.slotIdentity, n);
}
const receiptEvidence = /* @__PURE__ */ new WeakMap();
function receiptDigest(e) {
	const t = receiptEvidence.get(e);
	if (!t) return;
	return t.sha256 ??= createHash("sha256").update(t.bytes).digest("hex");
}
function receiptSignature(e) {
	const t = receiptEvidence.get(e);
	return t ? receiptDigest(e) + ":" + t.generation : void 0;
}
function readReceipt(e) {
	captureDirectoryIdentity(e);
	let t;
	let n = 0n;
	let r = 0n;
	let i = "";
	let a;
	try {
		a = readBounded(join(e, receiptName), headerLimit, (e) => {
			n = metadataTimestamp(e);
			r = e.mtimeNs;
			i = `${e.dev}:${e.ino}:${e.birthtimeNs}:${e.mtimeNs}:${e.ctimeNs}`;
		});
		t = receiptSchema.parse(JSON.parse(a.toString("utf8")));
	} catch {
		throw new Error("staging receipt has unknown or invalid metadata");
	}
	if (basename(e) !== prefix + t.id) throw new Error("staging generation does not match its directory");
	receiptEvidence.set(t, {
		bytes: a,
		mtimeNs: r,
		generation: i
	});
	return admitReceiptIdentities(e, t, n);
}
function ownerAbsent(e) {
	try {
		process.kill(e, 0);
		return false;
	} catch (e) {
		return e.code === "ESRCH";
	}
}
function sameHost(e, t) {
	return e.platform === t.platform && e.hostId === t.hostId && e.pidNamespace === t.pidNamespace;
}
function ownerState(e, t) {
	const n = currentProcessProvenance();
	if (!n) return "unknown";
	const r = e.ownerProvenance;
	if (r) {
		if (!sameHost(r, n) || e.ownerDomain && e.ownerDomain !== processDomain(r)) return "unknown";
		return r.bootId !== n.bootId || ownerAbsent(e.ownerPid) ? "absent" : "active";
	}
	if (t && sameHost(t.current, n) && t.current.bootId === n.bootId && t.ownerPid === e.ownerPid && t.ownerDomain === e.ownerDomain) return "absent";
	return e.ownerDomain === processDomain(n) ? ownerAbsent(e.ownerPid) ? "absent" : "active" : "unknown";
}
function confirmPriorBoot(e, t, n, r) {
	const i = currentProcessProvenance();
	const a = currentBootTimeNs();
	const o = receiptEvidence.get(t);
	if (t.ownerProvenance || !i || !a || !o) throw new Error("Legacy confirmation needs a legacy receipt and verified current host/boot provenance.");
	const s = receiptDigest(t);
	if (!r && !n || n && n !== s) throw new Error("Receipt digest changed or is missing; inspect this ID and confirm its exact --receipt-sha256.");
	if (t.ownerDomain === processDomain(i) || t.claims && t.claims.platform !== i.platform) throw new Error("Legacy receipt does not establish a different boot on this platform.");
	const c = t.operatorConfirmation;
	if (c) {
		if (!sameHost(c.current, i) || c.ownerPid !== t.ownerPid || c.ownerDomain !== t.ownerDomain) throw new Error("Previous confirmation belongs to another host, namespace, or producer.");
		assertIdentity(e, c.rootIdentity);
		assertIdentity(dirname(e), c.syncRootIdentity);
	}
	const l = c && sameHost(c.current, i) && c.ownerPid === t.ownerPid && c.ownerDomain === t.ownerDomain ? BigInt(c.receiptMtimeNs) : o.mtimeNs;
	if (l <= 0n || l >= a) throw new Error("Legacy receipt mtime must predate the current boot; a different opaque domain alone is insufficient.");
	const u = captureDirectoryIdentity(dirname(e));
	const d = upgradeDirectoryIdentity(e, t.rootIdentity, receiptDeadline(t));
	if (!u.stable?.volume.startsWith("uuid:") || d.stable?.volume !== u.stable.volume) throw new Error("Legacy confirmation requires matching UUID-backed sync-root and staging volumes.");
	if (t.syncRootIdentity) assertIdentity(dirname(e), t.syncRootIdentity);
	const f = join(e, "payload");
	if (lstatSync(f, { throwIfNoEntry: false })) {
		if (upgradeDirectoryIdentity(f, t.payloadIdentity, receiptDeadline(t)).stable?.volume !== u.stable.volume) throw new Error("Legacy payload volume does not match its sync root.");
	} else if (t.state !== "removing") throw new Error("Legacy payload is missing before recorded removal.");
	return {
		kind: "same-host-prior-boot",
		receiptSha256: s,
		receiptMtimeNs: String(l),
		ownerPid: t.ownerPid,
		ownerDomain: t.ownerDomain,
		confirmedAt: (/* @__PURE__ */ new Date()).toISOString(),
		current: i,
		syncRootIdentity: u,
		rootIdentity: d
	};
}
function createStaging(e, t, n = "capsule") {
	const r = randomUUID();
	mkdirSync(e, { recursive: true });
	const i = join(realpathSync(e), prefix + r);
	mkdirSync(i, { mode: 448 });
	const a = canRecordStaging(i, t);
	const o = join(i, "payload");
	let s;
	try {
		mkdirSync(o, { mode: 448 });
		s = {
			version: 2,
			id: r,
			ownerPid: process.pid,
			ownerProvenance: a ? currentProcessProvenance() : void 0,
			syncRootIdentity: captureDirectoryIdentity(dirname(i)),
			repository: realpathSync(t),
			repositoryIdentity: captureDirectoryIdentity(realpathSync(t)),
			kind: n,
			rootIdentity: captureDirectoryIdentity(i),
			payloadIdentity: captureDirectoryIdentity(o),
			durable: a && flushDirectory(i) && flushDirectory(dirname(i)),
			users: "none",
			state: "preparing"
		};
		if (a && !writeAtomic(i, receiptName, JSON.stringify(s) + "\n", s.durable) && s.durable) {
			s.durable = false;
			writeAtomic(i, receiptName, JSON.stringify(s) + "\n", false);
		}
	} catch (e) {
		try {
			rmSync(i, {
				recursive: true,
				force: true
			});
		} catch (t) {
			throw new AggregateError([e, t], "Staging preparation failed; allocation retained at " + i, { cause: t });
		}
		throw e;
	}
	return stagingHandle(i, s, a);
}
function stagingHandle(e, t, n) {
	let r = t;
	const i = join(e, "payload");
	const update = (t) => {
		assertIdentity(e, r.rootIdentity);
		r = {
			...r,
			...t
		};
		if (!n) return;
		upgradeReceiptIdentities(e, r);
		r = receiptSchema.parse(r);
		if (!writeAtomic(e, receiptName, JSON.stringify(r) + "\n", r.durable) && r.durable) {
			r.durable = false;
			writeAtomic(e, receiptName, JSON.stringify(r) + "\n", false);
		}
	};
	let a = false;
	return {
		recorded: n,
		root: e,
		payload: i,
		prepared(t, a, o) {
			if (!n) return;
			const s = new Map(t.files.map((e) => ["source/" + e.path, {
				...e,
				path: "source/" + e.path,
				kind: e.mode === "120000" ? "symlink" : "file"
			}]));
			const c = {
				source: t,
				entries: inventory(i, s, false, o)
			};
			const l = JSON.stringify(c) + "\n";
			if (Buffer.byteLength(l) > manifestLimit) throw new Error("staging manifest exceeds the recovery metadata limit");
			const u = writeAtomic(e, manifestName, l, r.durable);
			let d;
			try {
				d = captureClaimNamespace(join(i, "source"));
			} catch {}
			update({
				durable: u,
				claims: d,
				state: "prepared",
				manifest: createHash("sha256").update(l).digest("hex"),
				witness: a
			});
		},
		admitted: (e, t) => update({
			state: "admitted",
			users: "admitted",
			claims: e,
			leases: t
		}),
		settled: (e) => update({
			state: "settled",
			users: "settled",
			leases: e ?? r.leases
		}),
		preserved(t) {
			if (!n) return;
			assertIdentity(e, r.rootIdentity);
			const i = writeArtifactRecord(e, t, r.durable);
			update({
				state: "preserved",
				durable: i.durable && r.durable && t.durable,
				artifactManifest: i.digest
			});
		},
		hold: (e) => update({ hold: r.hold === "writers" ? "writers" : e }),
		dispose() {
			if (a) return;
			update({ state: "removing" });
			assertIdentity(i, r.payloadIdentity);
			rmSync(i, {
				recursive: true,
				force: true
			});
			rmSync(e, {
				recursive: true,
				force: true
			});
			a = true;
		}
	};
}
const mirrorLimit = 32;
const mirrorDatabase = "mirror.sqlite";
function privateMirrorDirectory(e) {
	const t = lstatSync(e);
	if (!t.isDirectory() || t.isSymbolicLink() || (t.mode & 63) !== 0 || process.getuid && t.uid !== process.getuid()) throw new Error("source mirror directory is not private: " + e);
	return captureDirectoryIdentity(e);
}
function mirrorLock(e, t = false) {
	const n = dirname(e);
	const r = privateMirrorDirectory(n);
	try {
		closeSync(openSync(e, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR | constants.O_NOFOLLOW, 384));
	} catch (e) {
		if (e.code !== "EEXIST") throw e;
	}
	const i = lstatSync(e, { bigint: true });
	if (!i.isFile() || i.isSymbolicLink() || i.nlink !== 1n || i.size !== 0n || (i.mode & 63n) !== 0n || process.getuid && i.uid !== BigInt(process.getuid())) throw new Error("source mirror lock is not a private empty regular database");
	let a = false;
	const assertOwned = () => {
		assertIdentity(n, r);
		const t = lstatSync(e, { bigint: true });
		if (!t.isFile() || t.isSymbolicLink() || t.nlink !== 1n || t.dev !== i.dev || t.ino !== i.ino || t.mode !== i.mode || t.size !== 0n) throw new Error("source mirror lock ownership changed");
	};
	let o;
	try {
		o = new DatabaseSync(e, { timeout: 0 });
		try {
			o.exec("PRAGMA journal_mode=MEMORY; BEGIN EXCLUSIVE");
		} catch (e) {
			if (!t || !sqliteBusy(e)) throw e;
			console.error("[crabbox] waiting for source mirror allocation...");
			const n = performance.now() + 12e4;
			o.exec("PRAGMA busy_timeout=120000");
			o.exec("PRAGMA journal_mode=MEMORY");
			const r = Math.max(0, Math.ceil(n - performance.now()));
			o.exec(`PRAGMA busy_timeout=${r}`);
			o.exec("BEGIN EXCLUSIVE");
		}
		assertOwned();
	} catch (e) {
		o?.close();
		if (sqliteBusy(e)) return;
		throw e;
	}
	const s = o;
	const release = () => {
		if (a) return;
		s.exec("ROLLBACK");
		s.close();
		a = true;
	};
	const remove = () => {
		if (!a) throw new Error("cannot remove an active source mirror lock");
		assertOwned();
		rmSync(e);
	};
	return Object.assign(release, {
		assertOwned,
		remove
	});
}
function sqliteBusy(e) {
	return typeof e === "object" && e !== null && "errcode" in e && e.errcode === 5;
}
function mirrorSlot(e, t, n) {
	const r = join(e, "mirrors", t);
	const i = privateMirrorDirectory(r);
	if (readdirSync(r).some((e) => e !== "stage" && e !== "lock")) throw new Error("source mirror slot has unknown metadata");
	const a = lstatSync(join(r, "stage"), { throwIfNoEntry: false }) ? readBounded(join(r, "stage"), 128).toString("utf8").trim() : n;
	if (!a || !uuid().safeParse(a).success) throw new Error("source mirror slot has an invalid staging identity");
	const o = join(e, prefix + a);
	const { receipt: s, disposal: c } = readMirrorState(e, a);
	if (s && (s.mirror?.key !== t || !sameIdentity(i, s.mirror.slotIdentity))) throw new Error("source mirror staging ownership does not match its slot");
	return {
		slot: r,
		slotIdentity: i,
		root: o,
		receipt: s,
		disposal: c,
		id: a
	};
}
function idleMirror(e) {
	return Boolean(e.mirror?.idle && e.durable && e.manifest && !e.hold && (e.users === "none" && e.state === "prepared" || e.users === "settled" && e.state === "preserved"));
}
function saveMirrorReceipt(e, t) {
	upgradeReceiptIdentities(e, t);
	if (!writeAtomic(e, receiptName, JSON.stringify(t) + "\n")) {
		writeAtomic(e, receiptName, JSON.stringify({
			...t,
			durable: false,
			mirror: t.mirror ? {
				...t.mirror,
				idle: false
			} : void 0
		}) + "\n", false);
		throw new Error("source mirror ownership could not be recorded durably");
	}
}
function databaseDigest(e, t) {
	for (const t of [
		"-journal",
		"-wal",
		"-shm"
	]) if (lstatSync(join(e, mirrorDatabase + t), { throwIfNoEntry: false })) throw new Error("source mirror database has unsettled journal state");
	return regularFileDigest(join(e, mirrorDatabase), () => createHash("sha256").update(JSON.stringify(t ?? null) + "\0"));
}
function disposalPath(e, t) {
	return join(e, prefix + "disposal-" + t);
}
function readDisposal(e, t) {
	const n = disposalPath(e, t);
	const r = lstatSync(n);
	if (!r.isFile() || r.isSymbolicLink() || r.nlink !== 1 || (r.mode & 63) !== 0 || process.getuid && r.uid !== process.getuid()) throw new Error("source mirror disposal record is not private");
	let i = 0n;
	const a = disposalSchema.parse(JSON.parse(readBounded(n, headerLimit, (e) => {
		i = metadataTimestamp(e);
	}).toString("utf8")));
	const o = a.receipt;
	if (a.id !== t || o && (o.id !== t || !o.mirror?.disposing || !idleMirror(o) || o.mirror.key !== a.key || !sameIdentity(o.mirror.slotIdentity, a.slotIdentity))) throw new Error("source mirror disposal record has invalid ownership");
	const s = join(e, prefix + t);
	if (o) {
		if (lstatSync(join(s, receiptName), { throwIfNoEntry: false })) readBounded(join(s, receiptName), headerLimit, (e) => {
			i = metadataTimestamp(e);
		});
		admitReceiptIdentities(s, o, i);
	}
	identityDeadlines.set(a.slotIdentity, i);
	return a;
}
function readMirrorState(e, t) {
	const n = join(e, prefix + t);
	const r = lstatSync(disposalPath(e, t), { throwIfNoEntry: false }) ? readDisposal(e, t) : void 0;
	const i = lstatSync(n, { throwIfNoEntry: false });
	if (r && i) {
		if (!r.receipt) throw new Error("source mirror root appeared after empty-slot disposal was recorded");
		assertIdentity(n, r.receipt.rootIdentity);
	}
	if (lstatSync(join(n, receiptName), { throwIfNoEntry: false })) {
		const e = readReceipt(n);
		if (r && JSON.stringify(r.receipt) !== JSON.stringify(e)) throw new Error("source mirror disposal record does not match its receipt");
		return {
			receipt: e,
			disposal: r
		};
	}
	if (r) {
		if (i && readdirSync(n).length) throw new Error("source mirror lost its receipt before payload disposal completed");
		return {
			receipt: r.receipt,
			disposal: r
		};
	}
	return {
		receipt: i ? readReceipt(n) : void 0,
		disposal: void 0
	};
}
function saveDisposal(e, t) {
	const n = disposalSchema.parse(t);
	const r = disposalPath(e, n.id);
	if (lstatSync(r, { throwIfNoEntry: false })) {
		if (JSON.stringify(readDisposal(e, n.id)) !== JSON.stringify(n)) throw new Error("source mirror disposal record changed");
		const t = openSync(r, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
		try {
			if (!flushDescriptor(t) || !flushDirectory(e)) throw new Error("source mirror disposal record durability is unavailable");
		} finally {
			closeSync(t);
		}
	} else if (!writeAtomic(e, basename(r), JSON.stringify(n) + "\n")) throw new Error("source mirror disposal record could not be recorded durably");
	return n;
}
function removeDisposal(e, t) {
	if (JSON.stringify(readDisposal(e, t.id)) !== JSON.stringify(t)) throw new Error("source mirror disposal record changed");
	if (!flushDirectory(join(e, "mirrors")) || !flushDirectory(e)) throw new Error("source mirror namespace removal could not be recorded durably");
	rmSync(disposalPath(e, t.id));
}
/** Claim under allocation; keep the slot reserved until its recorded disposal finishes. */
function claimIdleMirror(e, t, n) {
	const r = join(e, "mirrors", t);
	privateMirrorDirectory(r);
	if (!lstatSync(join(r, "stage"), { throwIfNoEntry: false }) || !lstatSync(join(r, "lock"), { throwIfNoEntry: false })) {
		if (!n) return;
		const i = readDisposal(e, n);
		assertIdentity(r, i.slotIdentity);
		if (i.key !== t || lstatSync(join(e, prefix + n), { throwIfNoEntry: false }) || readdirSync(r).some((e) => e !== "lock")) throw new Error("source mirror terminal disposal ownership changed");
	}
	const i = mirrorLock(join(r, "lock"));
	if (!i) return;
	try {
		const a = mirrorSlot(e, t, n);
		if (n && a.id !== n || a.receipt && !idleMirror(a.receipt)) {
			i();
			return;
		}
		let o;
		return {
			release: i,
			removePayload() {
				if (lstatSync(join(a.root, "recovery.lock"), { throwIfNoEntry: false })) throw new Error("Another or interrupted recovery owns this copy; its recovery lock must remain protected.");
				if (!a.receipt) {
					if (lstatSync(a.root, { throwIfNoEntry: false })) throw new Error("source mirror root appeared before empty-slot disposal");
					o = saveDisposal(e, a.disposal ?? {
						version: 1,
						id: a.id,
						key: t,
						slotIdentity: a.slotIdentity
					});
					return;
				}
				let n = a.receipt;
				if (JSON.stringify(readMirrorState(e, a.id).receipt) !== JSON.stringify(n)) throw new Error("source mirror disposal ownership changed");
				if (!lstatSync(join(a.root, receiptName), { throwIfNoEntry: false })) {
					o = saveDisposal(e, readDisposal(e, a.id));
					return;
				}
				const r = recoveryMetadata(a.root, join(a.root, "payload", "source"));
				const s = join(a.root, "payload");
				if (!n.mirror?.disposing || lstatSync(s, { throwIfNoEntry: false })) assertIdentity(s, n.payloadIdentity);
				if (!n.mirror?.disposing || !a.disposal) {
					n = receiptSchema.parse({
						...n,
						identityRecordedAtNs: receiptDeadline(n)?.toString(),
						mirror: {
							...n.mirror,
							disposing: true
						}
					});
					saveMirrorReceipt(a.root, n);
				}
				o = saveDisposal(e, a.disposal ?? {
					version: 1,
					id: a.id,
					key: t,
					slotIdentity: a.slotIdentity,
					receipt: n
				});
				i.assertOwned();
				assertIdentity(a.root, n.rootIdentity);
				for (const e of r) rmSync(join(a.root, e));
				if (r.length && !flushDirectory(a.root)) throw new Error("source mirror metadata removal could not be recorded durably");
				rmSync(s, {
					recursive: true,
					force: true
				});
				for (const e of [
					manifestName,
					mirrorDatabase,
					`${mirrorDatabase}-journal`,
					`${mirrorDatabase}-wal`,
					`${mirrorDatabase}-shm`
				]) rmSync(join(a.root, e), { force: true });
			},
			removeSlot() {
				i.assertOwned();
				if (!o || JSON.stringify(readDisposal(e, a.id)) !== JSON.stringify(o)) throw new Error("source mirror disposal record changed before namespace removal");
				const n = mirrorSlot(e, t, a.id);
				if (n.id !== a.id || !sameIdentity(n.slotIdentity, a.slotIdentity)) throw new Error("source mirror slot changed during disposal");
				if (n.receipt) {
					if (JSON.stringify(n.receipt) !== JSON.stringify(o.receipt)) throw new Error("source mirror disposal was not recorded");
					if (lstatSync(a.root, { throwIfNoEntry: false })) {
						assertIdentity(a.root, n.receipt.rootIdentity);
						if (readdirSync(a.root).some((e) => e !== receiptName)) throw new Error("source mirror disposal has remaining metadata");
						rmSync(join(a.root, receiptName), { force: true });
						rmdirSync(a.root);
					}
				} else if (lstatSync(a.root, { throwIfNoEntry: false })) throw new Error("source mirror root appeared during empty-slot disposal");
				if (!flushDirectory(e)) throw new Error("source mirror root removal could not be recorded durably");
				assertIdentity(r, a.slotIdentity);
				rmSync(join(r, "stage"), { force: true });
				if (!flushDirectory(r)) throw new Error("source mirror slot handoff removal could not be recorded durably");
				i();
				i.remove();
				rmdirSync(r);
				removeDisposal(e, o);
			}
		};
	} catch (e) {
		i();
		throw e;
	}
}
function allocateMirrorSlot(e, t) {
	const n = join(e, "mirrors");
	const r = join(n, t);
	let i;
	const acquire = () => {
		i = mirrorLock(join(n, ".allocation.lock"), true);
		if (!i) console.error("[crabbox] source mirror allocation is busy; using a fresh capsule");
		return i;
	};
	try {
		if (!acquire()) return;
		const t = /* @__PURE__ */ new Set();
		for (;;) {
			let a = false;
			if (!lstatSync(r, { throwIfNoEntry: false })) {
				const o = readdirSync(n).filter((e) => e !== ".allocation.lock");
				if (o.length >= mirrorLimit) {
					const n = o.flatMap((n) => {
						try {
							if (!/^[a-f0-9]{64}$/u.test(n) || t.has(n)) return [];
							const r = mirrorSlot(e, n);
							return !r.receipt || idleMirror(r.receipt) ? [{
								key: n,
								lastUsed: r.receipt?.mirror?.lastUsed ?? 0
							}] : [];
						} catch {
							return [];
						}
					}).toSorted((e, t) => e.lastUsed - t.lastUsed);
					let r;
					for (const i of n) {
						t.add(i.key);
						try {
							r = claimIdleMirror(e, i.key);
							if (r) break;
						} catch {}
					}
					if (!r) {
						console.error("[crabbox] source mirror limit reached; protected copies retained, using a fresh capsule");
						return;
					}
					i();
					i = void 0;
					try {
						r.removePayload();
						if (!acquire()) return;
						r.removeSlot();
					} catch (e) {
						console.error("[crabbox] source mirror eviction could not verify a candidate; retained it and checking later idle mirrors: " + (e instanceof Error ? e.message : String(e)));
					} finally {
						r.release();
					}
					if (!i && !acquire()) return;
					continue;
				}
				mkdirSync(r, { mode: 448 });
				a = true;
			}
			const o = privateMirrorDirectory(r);
			const s = mirrorLock(join(r, "lock"));
			if (!s) {
				console.error("[crabbox] source mirror is in use or has an unresolved owner; using a fresh capsule");
				return;
			}
			return {
				slot: r,
				slotIdentity: o,
				createdSlot: a,
				release: s
			};
		}
	} finally {
		i?.();
	}
}
/** Own one immutable command view, with a bounded disposable cache between runs. */
function createMirrorStaging(e, t) {
	let n;
	try {
		if (!processDomain()) {
			console.error("[crabbox] source mirror process ownership is unavailable; using a fresh capsule");
			return;
		}
		mkdirSync(e, { recursive: true });
		const r = realpathSync(e);
		const i = realpathSync(t);
		if (!canRecordStaging(join(r, prefix + "mirror"), i)) return;
		if (!flushDirectory(r)) {
			console.error("[crabbox] durable source mirror ownership is unavailable; using a fresh capsule");
			return;
		}
		const a = join(r, "mirrors");
		mkdirSync(a, {
			recursive: true,
			mode: 448
		});
		privateMirrorDirectory(a);
		const o = createHash("sha256").update(i).digest("hex");
		const s = allocateMirrorSlot(r, o);
		if (!s) return;
		const { slot: c, slotIdentity: l, createdSlot: u } = s;
		n = s.release;
		let d;
		let f;
		if (!u && !lstatSync(join(c, "stage"), { throwIfNoEntry: false })) throw new Error("source mirror slot has no recorded staging owner");
		if (lstatSync(join(c, "stage"), { throwIfNoEntry: false })) {
			const e = mirrorSlot(r, o);
			d = e.receipt;
			f = e.root;
			if (e.disposal || d && (!idleMirror(d) || d.mirror?.disposing)) {
				console.error("[crabbox] source mirror has no completed idle handoff; using a fresh capsule");
				return;
			}
			if (d) {
				recoveryMetadata(f, join(f, "payload", "source"));
				let e = false;
				try {
					e = Boolean(d.mirror?.database) && databaseDigest(f, d.witness) === d.mirror?.database;
				} catch {}
				if (!e) {
					assertIdentity(f, d.rootIdentity);
					rmSync(f, {
						recursive: true,
						force: true
					});
					d = void 0;
					console.error("[crabbox] source mirror metadata changed or disappeared; rebuilding cold");
				}
			}
		}
		const p = Boolean(d);
		if (!d) {
			const e = createStaging(r, i);
			if (!e.recorded) {
				e.dispose();
				return;
			}
			f = e.root;
			d = readReceipt(f);
		}
		if (!f || !canRecordStaging(f, i)) return;
		assertIdentity(join(f, "payload"), d.payloadIdentity);
		const m = recoveryMetadata(f, join(f, "payload", "source"));
		const h = {
			...d,
			ownerPid: process.pid,
			ownerDomain: void 0,
			ownerProvenance: currentProcessProvenance(),
			operatorConfirmation: void 0,
			syncRootIdentity: captureDirectoryIdentity(r),
			repository: i,
			repositoryIdentity: captureDirectoryIdentity(i),
			state: "preparing",
			users: "none",
			claims: void 0,
			leases: void 0,
			witness: void 0,
			artifactManifest: void 0,
			mirror: {
				key: o,
				slotIdentity: l,
				idle: false,
				lastUsed: Date.now()
			}
		};
		saveMirrorReceipt(f, h);
		if (!writeAtomic(c, "stage", h.id + "\n")) throw new Error("source mirror slot could not be recorded durably");
		for (const e of m) rmSync(join(f, e));
		const g = stagingHandle(f, h, true);
		const _ = n;
		n = void 0;
		let v = false;
		const abandon = () => {
			if (!v) {
				_();
				v = true;
			}
		};
		const ownedReceipt = () => {
			const e = mirrorSlot(r, o);
			if (e.root !== f || e.receipt?.ownerPid !== process.pid || e.receipt.mirror?.idle || e.receipt.id !== h.id) throw new Error("source mirror ownership changed during its command");
			return e.receipt;
		};
		return {
			staging: g,
			reused: p,
			finish() {
				if (v) return;
				try {
					const e = ownedReceipt();
					const t = {
						...e,
						mirror: {
							...e.mirror,
							idle: true,
							lastUsed: Date.now()
						}
					};
					if (idleMirror(t)) {
						const n = join(g.payload, "source");
						const r = join(n, ".crabbox");
						if (lstatSync(r, { throwIfNoEntry: false })) try {
							const i = captureDirectoryIdentity(r);
							if (!e.artifactManifest) throw new Error("source mirror output preservation was not recorded");
							const a = readArtifactRecord(g.root, e.artifactManifest);
							verifyPreservedCrabboxArtifacts(n, a);
							_.assertOwned();
							assertIdentity(r, i);
							if (readdirSync(r).some((e) => e !== "runs" && e !== "captures")) {
								g.dispose();
								return;
							}
							t.mirror.database = databaseDigest(g.root, e.witness);
							for (const e of ["runs", "captures"]) rmSync(join(r, e), {
								recursive: true,
								force: true
							});
							rmdirSync(r);
						} catch (e) {
							g.hold("artifacts");
							throw e;
						}
						else t.mirror.database = databaseDigest(g.root, e.witness);
						saveMirrorReceipt(g.root, t);
					}
				} finally {
					abandon();
				}
			},
			discard() {
				if (v) return;
				try {
					const e = ownedReceipt();
					if (e.users !== "none" || e.hold || !["preparing", "prepared"].includes(e.state)) throw new Error("source mirror has admitted or unverified users; retained for recovery");
					g.dispose();
				} finally {
					abandon();
				}
			}
		};
	} catch (e) {
		console.error("[crabbox] source mirror unavailable; retained for inspection, using a fresh capsule: " + (e instanceof Error ? e.message : String(e)));
		return;
	} finally {
		n?.();
	}
}
function readManifest(e, t) {
	const n = readBounded(join(e, manifestName), manifestLimit);
	if (createHash("sha256").update(n).digest("hex") !== t.manifest) throw new Error("staging manifest does not match its receipt");
	try {
		return manifestSchema.parse(JSON.parse(n.toString("utf8")));
	} catch {
		throw new Error("staging manifest has unknown or invalid metadata");
	}
}
function writeArtifactRecord(e, t, n = true) {
	const r = JSON.stringify(t) + "\n";
	if (Buffer.byteLength(r) > manifestLimit) throw new Error("staging artifact evidence exceeds the recovery metadata limit");
	const i = createHash("sha256").update(r).digest("hex");
	return {
		digest: i,
		durable: writeAtomic(e, "artifacts-" + i + ".json", r, n)
	};
}
function readArtifactRecord(e, t) {
	const n = readBounded(join(e, "artifacts-" + t + ".json"), manifestLimit);
	if (createHash("sha256").update(n).digest("hex") !== t) throw new Error("staging artifact evidence does not match its recorded identity");
	try {
		return crabboxArtifactEvidenceSchema.parse(JSON.parse(n.toString("utf8")));
	} catch {
		throw new Error("staging artifact evidence has unknown or invalid metadata");
	}
}
function recoveryMetadata(e, t, n) {
	const r = readdirSync(e).toSorted();
	if (r.length > 68) throw new Error("staging has too many metadata generations; inspect it before recovery");
	const i = /* @__PURE__ */ new Set([
		receiptName,
		manifestName,
		"payload",
		"recovery.lock"
	]);
	const a = lstatSync(t, { throwIfNoEntry: false }) ? captureDirectoryIdentity(t) : n?.sourceIdentity;
	const o = [];
	const s = readReceipt(e);
	const c = s.mirror;
	for (const t of r) {
		if (i.has(t)) continue;
		if (c && [
			mirrorDatabase,
			`${mirrorDatabase}-journal`,
			`${mirrorDatabase}-wal`,
			`${mirrorDatabase}-shm`
		].includes(t)) {
			const n = lstatSync(join(e, t));
			if (!n.isFile() && !n.isSymbolicLink()) throw new Error("source mirror database metadata has an unsupported kind");
			continue;
		}
		const n = /^artifacts-([a-f0-9]{64})\.json$/u.exec(t);
		if (!n || !a || !sameIdentity(a, readArtifactRecord(e, n[1]).sourceIdentity, receiptDeadline(s))) throw new Error("staging has an unknown or replaced metadata sibling; preserve it before recovery");
		o.push(t);
	}
	return o;
}
function metadataStatus(e, t, n = false, r) {
	const i = {
		id: t.id,
		directory: e,
		ownerPid: t.ownerPid,
		state: t.state,
		users: t.users,
		kind: t.kind,
		hold: t.hold,
		leases: t.leases
	};
	if (lstatSync(join(e, "recovery.lock"), { throwIfNoEntry: false })) return {
		...i,
		status: "protected",
		reason: "Another or interrupted recovery owns this copy; inspect that operation before manual disposition."
	};
	const a = ownerState(t, r);
	if (idleMirror(t) && (!t.ownerProvenance || a !== "unknown")) return {
		...i,
		status: t.mirror?.disposing ? "candidate" : "protected",
		reason: t.mirror?.disposing ? "Interrupted idle source mirror disposal; its exclusive slot lock must be acquired before resuming." : "Idle source mirror retained for reuse; capacity eviction or explicit staging recover uses its exclusive mirror lock."
	};
	if (a === "unknown") return {
		...i,
		status: "protected",
		reason: "The producer belongs to an unknown host, boot, or PID namespace; inspect this ID for explicit legacy confirmation."
	};
	if (a === "active") return {
		...i,
		status: "active",
		reason: "The producer PID is live or cannot be checked; wait for its cleanup."
	};
	if (t.kind === "worktree") return {
		...i,
		status: "protected",
		reason: "Full-worktree preparation can run hooks or filters. Preserve its raw source and outputs, then verify this exact Git registration before manual disposition; recovery does not adopt it."
	};
	if (!t.durable || !t.manifest) return {
		...i,
		status: "protected",
		reason: "Preparation or durable recovery metadata is incomplete; preserve this copy for inspection."
	};
	if (t.users === "admitted" || t.state === "preparing") return {
		...i,
		status: "protected",
		reason: "Writer settlement was not recorded; PID absence does not authorize removal."
	};
	if (t.hold === "writers" || t.hold === "registration") return {
		...i,
		status: "protected",
		reason: "Writer or registration settlement is unverified; inspect and preserve this copy before manual disposition."
	};
	if (!n && (t.hold || t.users === "settled" && t.state === "settled")) return {
		...i,
		status: "protected",
		reason: "Claim or diagnostic preservation is incomplete; repair the named destination or lease, then run staging recover with this ID to retry."
	};
	if (![
		"prepared",
		"settled",
		"preserved",
		"removing"
	].includes(t.state)) return {
		...i,
		status: "protected",
		reason: "Staging state is inconsistent with recorded ownership; preserve it for inspection."
	};
	if (!t.claims) return {
		...i,
		status: "protected",
		reason: "The original native claims namespace was not recorded; absence in another namespace cannot authorize removal."
	};
	if (!t.witness) return {
		...i,
		status: "protected",
		reason: "No independent retained Git ref is recorded; preserve the snapshot in a retained repository first."
	};
	return {
		...i,
		status: "candidate",
		reason: "Source preservation and unchanged contents must still be verified before removal."
	};
}
function inspectStaging(e, t = {}) {
	const n = performance.now();
	const r = [];
	let i = false;
	let a = t.startAfter;
	let o = Boolean(t.startAfter);
	let s;
	try {
		captureDirectoryIdentity(realpathSync(e));
		currentProcessProvenance();
		s = opendirSync(e);
	} catch (e) {
		if (e.code === "ENOENT") return {
			entries: r,
			incomplete: i,
			nextCursor: void 0,
			elapsedMs: performance.now() - n
		};
		throw e;
	}
	const c = performance.now() + (t.budgetMs ?? 250);
	try {
		for (;;) {
			if (r.length >= (t.limit ?? 64) || performance.now() >= c) {
				i = true;
				break;
			}
			const n = s.readSync();
			if (!n) {
				a = void 0;
				i = o;
				break;
			}
			if (o) {
				o = n.name !== t.startAfter;
				continue;
			}
			if (!n.name.startsWith(prefix)) continue;
			a = n.name;
			const l = join(e, n.name);
			try {
				const t = n.name.startsWith(prefix + "disposal-") ? n.name.slice((prefix + "disposal-").length) : void 0;
				const i = t ? readDisposal(e, t) : void 0;
				const a = i ? i.receipt : readMirrorState(e, n.name.slice(prefix.length)).receipt;
				if (!a && !i) throw new Error("staging has no recorded owner");
				const o = i?.id ?? a.id;
				if (!r.some((e) => e.id === o)) r.push(a ? {
					...metadataStatus(join(e, prefix + o), a),
					directory: l
				} : {
					id: o,
					directory: l,
					status: "candidate",
					reason: "Recorded empty source mirror slot disposal; its allocation and slot locks must be acquired before resuming."
				});
			} catch {
				r.push({
					id: n.name,
					directory: l,
					status: "protected",
					reason: "Unmarked, unknown, replaced or unreadable staging; no automatic adoption."
				});
			}
		}
	} finally {
		s.closeSync();
	}
	return {
		entries: r,
		incomplete: i,
		nextCursor: a,
		elapsedMs: performance.now() - n
	};
}
function validatePayload(e, t, n) {
	const r = join(e, "payload");
	if (!lstatSync(r, { throwIfNoEntry: false }) && t.state === "removing") return "[]";
	assertIdentity(r, t.payloadIdentity);
	const i = n.artifacts ? n.entries.filter((e) => !artifactPath(e.path)) : n.entries;
	const a = new Map(i.map((e) => [e.path, e]));
	if (a.size !== i.length || [...a.keys()].some((e) => !safeRelative(e))) throw new Error("staging manifest contains duplicate or unsafe paths");
	const o = inventory(r, /* @__PURE__ */ new Map(), Boolean(n.artifacts));
	for (const e of o) {
		const t = a.get(e.path);
		if (!t || t.kind !== e.kind || t.mode !== e.mode || t.blob !== e.blob) throw new Error("staging contents changed or gained an entry: " + e.path);
		a.delete(e.path);
	}
	if (a.size && t.state !== "removing") throw new Error("staging contents are missing before disposal");
	return JSON.stringify(o);
}
async function recoverStaging(e, t, n) {
	if (!uuid().safeParse(t).success) return {
		id: t,
		recovered: false,
		reason: "Choose a recorded staging ID from staging inspect."
	};
	const r = join(e, prefix + t);
	const i = join(r, "payload", "source");
	let a = false;
	let o = false;
	let s;
	let c;
	let l;
	const u = JSON.stringify({
		pid: process.pid,
		generation: randomUUID()
	}) + "\n";
	const d = join(r, "recovery.lock");
	let f;
	let p;
	const checkUsers = async (t, i = false) => {
		const a = t.mirror ? join(e, "mirrors", t.mirror.key) : void 0;
		const s = await verifyNoStagingUsers({
			roots: [r, ...a ? [a] : []].filter((e) => lstatSync(e, { throwIfNoEntry: false })),
			ignoredFiles: i && a ? [join(a, "lock")] : [],
			signal: n.signal
		});
		if (!s.ok) {
			o ||= s.unjoined === true;
			throw new Error(s.reason);
		}
	};
	const assertProducerAbsent = (e) => {
		if (ownerState(e, f) !== "absent") throw new Error("The producer's absence can no longer be established.");
		if (f) {
			assertIdentity(dirname(r), f.syncRootIdentity);
			assertIdentity(r, f.rootIdentity);
		}
	};
	try {
		n.signal?.throwIfAborted();
		const { receipt: m, disposal: h } = readMirrorState(e, t);
		p = m ? receiptDigest(m) : void 0;
		const g = m ? receiptSignature(m) : void 0;
		if (n.confirmSameHostPriorBoot && (!m || h || idleMirror(m))) throw new Error("Prior-boot confirmation is per-ID and only for non-idle legacy capsules.");
		if (m && n.confirmSameHostPriorBoot) f = confirmPriorBoot(r, m, n.receiptSha256, Boolean(n.dryRun));
		if (m?.ownerProvenance && ownerState(m) === "unknown") throw new Error("The recorded producer host or PID namespace does not match this process.");
		if (h || m && idleMirror(m)) {
			if (n.dryRun) throw new Error("This inspection evaluates non-idle capsule recovery; idle/disposal records use their separate slot-locked workflow.");
			const i = h?.key ?? m.mirror.key;
			const a = h?.slotIdentity ?? m.mirror.slotIdentity;
			let s = mirrorLock(join(e, "mirrors", ".allocation.lock"), true);
			if (!s) return {
				id: t,
				recovered: false,
				reason: "Source mirror allocation is busy; retry after the active command finishes."
			};
			let c;
			try {
				const n = join(e, "mirrors", i);
				if (h && !lstatSync(r, { throwIfNoEntry: false })) {
					const r = lstatSync(n, { throwIfNoEntry: false }) ? mirrorSlot(e, i, t) : void 0;
					if (!r || r.receipt && r.id !== t) {
						removeDisposal(e, h);
						return {
							id: t,
							recovered: true,
							reason: "Completed source mirror disposal record removed."
						};
					}
					if (!sameIdentity(r.slotIdentity, a)) throw new Error("Source mirror disposal slot identity changed.");
				}
				c = claimIdleMirror(e, i, t);
				s();
				s = void 0;
				if (c) {
					if (m) await checkUsers(m, true);
					c.removePayload();
					s = mirrorLock(join(e, "mirrors", ".allocation.lock"), true);
					if (!s) throw new Error("Source mirror allocation is busy; recorded disposal retained for recovery.");
					c.removeSlot();
				}
				const o = Boolean(c);
				return {
					id: t,
					recovered: o,
					reason: o ? "Explicitly disposable idle source mirror removed." : "Source mirror is in use or its ownership changed; retained."
				};
			} finally {
				if (!o) c?.release();
				s?.();
			}
		}
		if (!m) throw new Error("Staging has no recorded owner.");
		const _ = n.witness ?? m.witness;
		const v = metadataStatus(r, {
			...m,
			witness: _
		}, true, f);
		if (v.status !== "candidate") return {
			id: t,
			recovered: false,
			eligible: false,
			receiptSha256: p,
			reason: v.reason
		};
		const y = readManifest(r, m);
		recoveryMetadata(r, i, m.artifactManifest ? readArtifactRecord(r, m.artifactManifest) : y.artifacts);
		if (m.mirror && mirrorSlot(e, m.mirror.key).root !== r) throw new Error("Source mirror staging ownership changed before recovery.");
		await checkUsers(m);
		if (receiptSignature(readReceipt(r)) !== g) throw new Error("staging receipt changed during live-user inspection");
		assertProducerAbsent(m);
		if (m.mirror && !n.dryRun) {
			const n = mirrorLock(join(e, "mirrors", ".allocation.lock"), true);
			if (!n) return {
				id: t,
				recovered: false,
				reason: "Source mirror allocation is busy; retry after the active command finishes."
			};
			try {
				const n = mirrorSlot(e, m.mirror.key);
				if (n.root !== r) throw new Error("Source mirror staging ownership changed before recovery.");
				s = mirrorLock(join(n.slot, "lock"));
				if (!s) return {
					id: t,
					recovered: false,
					reason: "Source mirror has an active lock owner; retained."
				};
			} finally {
				n();
			}
		}
		if (!n.dryRun) {
			mkdirSync(d, { mode: 448 });
			a = true;
			c = captureDirectoryIdentity(r);
			l = captureDirectoryIdentity(d);
			writeFileSync(join(d, "owner.json"), u, {
				mode: 384,
				flag: "wx"
			});
		}
		let b = readReceipt(r);
		if (receiptSignature(b) !== g) throw new Error("staging ownership changed while acquiring recovery");
		assertProducerAbsent(b);
		let x = g;
		const assertCurrentReceipt = () => {
			if (receiptSignature(readReceipt(r)) !== x) throw new Error("staging ownership changed during preservation verification");
			assertProducerAbsent(b);
			if (n.dryRun) {
				if (lstatSync(d, { throwIfNoEntry: false })) throw new Error("Another recovery acquired this copy during inspection.");
			} else {
				assertIdentity(d, l);
				if (readBounded(join(d, "owner.json"), headerLimit).toString("utf8") !== u) throw new Error("staging recovery lock ownership changed");
			}
		};
		const saveReceipt = (e) => {
			if (n.dryRun) throw new Error("Inspection cannot write recovery metadata.");
			assertCurrentReceipt();
			upgradeReceiptIdentities(r, e);
			b = receiptSchema.parse(e);
			const t = JSON.stringify(b) + "\n";
			if (!writeAtomic(r, receiptName, t)) {
				b.durable = false;
				writeAtomic(r, receiptName, JSON.stringify(b) + "\n", false);
				throw new Error("Durable recovery updates are unavailable; staging remains protected.");
			}
			b = readReceipt(r);
			x = receiptSignature(b);
		};
		if (f && !n.dryRun) saveReceipt({
			...b,
			operatorConfirmation: f,
			syncRootIdentity: f.syncRootIdentity
		});
		const checkClaims = async () => {
			const e = await verifyNoStagingClaims({
				binary: n.binary,
				cwd: n.cwd,
				namespace: b.claims,
				legacyBeforeNs: receiptDeadline(b),
				sourceRoot: r,
				signal: n.signal
			});
			if (!e.ok) {
				o ||= e.unjoined === true;
				if (!o && !n.dryRun) saveReceipt({
					...b,
					hold: "claims",
					leases: e.matchingLeaseIds ?? b.leases
				});
				throw new Error(e.reason + (e.matchingLeaseIds?.length ? " Matching leases: " + JSON.stringify(e.matchingLeaseIds) : ""), { cause: e.error });
			}
		};
		await checkClaims();
		let S = readManifest(r, b);
		if (b.artifactManifest) S = {
			...S,
			artifacts: readArtifactRecord(r, b.artifactManifest)
		};
		recoveryMetadata(r, i, S.artifacts);
		if (b.users === "settled") try {
			if (!S.artifacts) throw new Error("Diagnostic preservation was not recorded.");
			verifyPreservedCrabboxArtifacts(i, S.artifacts, b.state === "removing", receiptDeadline(b));
		} catch (e) {
			if (n.dryRun || b.state === "removing") throw e;
			if (!b.repositoryIdentity) throw new Error("Original repository identity is unavailable; preserve diagnostics manually.", { cause: e });
			assertCurrentReceipt();
			const t = preserveCrabboxArtifacts(i, b.repository, b.repositoryIdentity, receiptDeadline(b));
			if (!t?.durable) throw new Error("Durable diagnostic preservation could not be established.", { cause: e });
			S = {
				...S,
				artifacts: t
			};
			const a = writeArtifactRecord(r, t);
			if (!a.durable) throw new Error("Durable artifact evidence could not be recorded.", { cause: e });
			saveReceipt({
				...b,
				artifactManifest: a.digest,
				state: "preserved",
				hold: void 0
			});
		}
		const C = await verifySourceWitness({
			source: S.source,
			witness: _,
			payloadRoot: r,
			signal: n.signal
		});
		if (!C.ok) {
			o ||= C.unjoined === true;
			return {
				id: t,
				recovered: false,
				eligible: false,
				receiptSha256: p,
				operatorConfirmation: n.dryRun ? void 0 : f,
				reason: C.reason
			};
		}
		await checkClaims();
		await checkUsers(b, Boolean(s));
		n.signal?.throwIfAborted();
		validatePayload(r, b, S);
		if (S.artifacts) verifyPreservedCrabboxArtifacts(i, S.artifacts, b.state === "removing", receiptDeadline(b));
		const w = recoveryMetadata(r, i, S.artifacts);
		if (n.dryRun) {
			C.revalidate();
			assertCurrentReceipt();
			return {
				id: t,
				recovered: false,
				eligible: true,
				receiptSha256: p,
				confirmationRequired: Boolean(f),
				requiresExclusiveLocks: true,
				reason: "Read-only recovery checks passed; actual recovery must reacquire locks and revalidate this receipt."
			};
		}
		saveReceipt({
			...b,
			state: "removing",
			hold: void 0,
			witness: _
		});
		C.revalidate();
		assertCurrentReceipt();
		rmSync(join(r, "payload"), {
			recursive: true,
			force: true
		});
		rmSync(join(r, manifestName));
		for (const e of w) rmSync(join(r, e));
		if (b.mirror) for (const e of [
			mirrorDatabase,
			`${mirrorDatabase}-journal`,
			`${mirrorDatabase}-wal`,
			`${mirrorDatabase}-shm`
		]) rmSync(join(r, e), { force: true });
		rmSync(join(r, receiptName));
		rmSync(join(d, "owner.json"));
		rmdirSync(d);
		a = false;
		rmdirSync(r);
		return {
			id: t,
			recovered: true,
			operatorConfirmation: f,
			reason: "Independent retained source, diagnostics, and native claims verified; abandoned staging removed."
		};
	} catch (e) {
		const r = e.code === "EEXIST" ? "Another or interrupted recovery owns this copy; inspect its owner before manual disposition." : e instanceof Error ? e.message : "Staging recovery could not be verified.";
		return {
			id: t,
			recovered: false,
			eligible: false,
			receiptSha256: p,
			operatorConfirmation: n.dryRun ? void 0 : f,
			reason: r
		};
	} finally {
		if (a && !o && c && l) try {
			assertIdentity(r, c);
			assertIdentity(d, l);
			if (readBounded(join(d, "owner.json"), headerLimit).toString("utf8") === u) {
				rmSync(join(d, "owner.json"));
				rmdirSync(d);
			}
		} catch {}
		if (!o) s?.();
	}
}
async function runStagingCommand(e, t, n) {
	if (e[0] === "inspect" && (e.length === 1 || e.length === 3 && e[1] === "--after" && e[2].startsWith(prefix) && basename(e[2]) === e[2])) {
		console.log(JSON.stringify(inspectStaging(t, { startAfter: e[2] }), null, 2));
		return 0;
	}
	if (e[0] === "recover" || e[0] === "inspect" && e[1] && !e[1].startsWith("--")) try {
		const r = parseArgs({
			args: e.slice(1),
			allowPositionals: true,
			strict: true,
			tokens: true,
			options: {
				"same-host-prior-boot": { type: "boolean" },
				"confirm-same-host-prior-boot": { type: "boolean" },
				"receipt-sha256": { type: "string" },
				"witness-repo": { type: "string" },
				"witness-ref": { type: "string" }
			}
		});
		const i = r.tokens.filter((e) => e.kind === "option").map((e) => e.name);
		const a = e[0] === "inspect";
		const o = r.values;
		if (r.positionals.length !== 1 || new Set(i).size !== i.length || a && (o["confirm-same-host-prior-boot"] || o["receipt-sha256"]) || !a && o["same-host-prior-boot"]) throw new Error("Choose exactly one staging ID and use inspection or confirmation flags only with their matching command.");
		const s = a ? o["same-host-prior-boot"] : o["confirm-same-host-prior-boot"];
		const c = o["receipt-sha256"];
		if (!a && Boolean(s) !== Boolean(c) || c && !/^[a-f0-9]{64}$/u.test(c)) throw new Error("Legacy recovery requires --confirm-same-host-prior-boot and the exact --receipt-sha256 from inspection.");
		let l;
		if (o["witness-repo"] || o["witness-ref"]) {
			if (!o["witness-repo"] || !o["witness-ref"]) throw new Error("Supply both --witness-repo and --witness-ref, with one value each.");
			l = selectSourceWitness(o["witness-repo"], o["witness-ref"]);
		}
		const u = await recoverStaging(realpathSync(t), r.positionals[0], {
			...n,
			witness: l,
			dryRun: a,
			confirmSameHostPriorBoot: s,
			receiptSha256: c
		});
		console.log(JSON.stringify({
			...u,
			...a ? { inspectionOnly: true } : {}
		}, null, 2));
		return a ? 0 : u.recovered ? 0 : 1;
	} catch (t) {
		console.log(JSON.stringify({
			id: e[1],
			recovered: false,
			eligible: false,
			reason: t instanceof Error ? t.message : "Recovery options could not be verified."
		}, null, 2));
		return 1;
	}
	console.log("Usage: node scripts/crabbox-wrapper.mjs staging inspect [--after <nextCursor>]\n       node scripts/crabbox-wrapper.mjs staging inspect <id> [--same-host-prior-boot]\n       node scripts/crabbox-wrapper.mjs staging recover <id> [--confirm-same-host-prior-boot --receipt-sha256 <digest>] [--witness-repo <path> --witness-ref <full-ref>]\n\nOnly positively settled, unchanged staging with independently retained source and preserved diagnostics can be removed. Existing native claims are inspected without provider calls or claim mutation.");
	return e.length === 0 || e[0] === "--help" ? 0 : 2;
}
//#endregion
export { preserveCrabboxArtifacts as a, captureClaimNamespace as i, createStaging as n, captureSourceWitness as o, runStagingCommand as r, createMirrorStaging as t };