openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
917 lines (916 loc) • 33.7 kB
JavaScript
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { o as registerOpenClawAgentDatabaseAsyncResource } from "./openclaw-agent-db-resources-Dp8HvLsg.mjs";
import { n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { l as withSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { _ as retainPreparedSessionEntryPredicate } from "./session-accessor.sqlite-entry-cache-publication-state-B4mkg2yK.mjs";
import { i as patchSessionEntryCore } from "./session-accessor.sqlite-entry-Da3xxVPX.mjs";
import { t as captureSessionEntryMetadataRead } from "./session-entry-source-authority-Bxiv7qVT.mjs";
import { o as requireGit, u as runGit } from "./git-BBx5S0aA.mjs";
import { i as timeWorktreePreparationPhase } from "./preparation-timing-YO2wGpby.mjs";
import { i as captureWorktreeRunEndContext } from "./run-end-lifecycle-CvtGWdnp.mjs";
import { a as prepareWorktreeRegistryGuard, d as readRegistryWorktree, l as readLiveRegistryWorktreeByPath, t as captureWorktreeRegistryReadGuard } from "./registry-read-DAFI5cQY.mjs";
import { s as isLocalWorkspaceBaseRefreshRef } from "./workspace-result-inventory-D0Vsi3cF.mjs";
import { n as captureWorkspaceManifestDocument, v as workspaceManifestPaths } from "./workspace-manifest-worker-CfX0osDw.mjs";
import { c as parseWorkerWorkspaceReconciliationPlan, g as buildCacheInputPaths, l as serializeWorkerWorkspaceManifest, s as parseWorkerWorkspaceManifest, u as serializeWorkerWorkspaceReconciliationPlan } from "./workspace-manifest-C118sSRH.mjs";
import { l as workspaceSizeRecoveryPaths } from "./workspace-manifest-comparison-BpzYeKoQ.mjs";
import { i as recoverWorkerWorkspaceReconciliation, n as AcceptedWorkspacePublicationIndeterminateError, t as applyStagedWorkerWorkspace } from "./workspace-reconcile-DsKvx4sc.mjs";
import { a as hasWorkerWorkspaceResultRef, d as withStagedWorkerWorkspaceResult, f as workerWorkspaceResultRef, l as readStagedWorkerWorkspaceResult, p as workerWorkspaceResultStaging, r as deleteStagedWorkerWorkspaceResult } from "./workspace-result-staging-C8wToOO8.mjs";
import { n as initializeLocalWorkspaceProjection, r as localWorkspaceProjectionPath, t as assertLocalWorkspaceDirectory } from "./local-workspace-checkout-D7yp8kUm.mjs";
import { n as withLocalWorkspaceStore } from "./local-workspace-store-DOvoTPGF.mjs";
import { t as LocalWorkspaceConflictError } from "./local-workspace-conflict-error-CvvpexHG.mjs";
import { a as readLocalWorkspaceGitExclusions, i as prepareLocalWorkspaceBuildInputs, n as captureLocalWorkspaceArchiveBaseline, o as selectLocalWorkspaceCanonicalPaths, r as parseLocalWorkspaceSourcePaths, t as admitLocalWorkspaceSourcePaths } from "./local-workspace-inventory-BbL-ilhy.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
//#region src/gateway/worker-environments/local-workspace-owner-identity.ts
function assertLocalWorkspaceProjectionOwner(e, t, n) {
if (e.worktree_id !== t.worktree.id || e.agent_id !== t.agentId || e.session_key !== t.sessionKey || e.session_id !== t.sessionId || e.lifecycle_revision !== t.lifecycleRevision || n !== void 0 && e.projection_path !== n) throw new Error("Local sandbox workspace belongs to a different session incarnation; pending edits were preserved");
}
//#endregion
//#region src/gateway/worker-environments/local-workspace-handoff.ts
/** Only a committed cut receipt plus live successor authority can change incarnation. */
async function finishLocalWorkspaceHandoff(e, t) {
e.assertCurrent();
if (t.worktreeId !== e.worktree.id || t.toSessionId !== e.sessionId || t.lifecycleRevision !== e.lifecycleRevision) throw new Error("Local workspace handoff belongs to a different session incarnation");
await withLocalWorkspaceStore({
...e,
worktreeId: e.worktree.id
}, async (n) => {
const r = n.get();
if (!r) throw new Error("Local workspace handoff lost its saved projection; recovery data was preserved");
if (r.session_id === e.sessionId) {
assertLocalWorkspaceProjectionOwner(r, e, localWorkspaceProjectionPath(e));
return;
}
assertLocalWorkspaceProjectionOwner(r, {
...e,
sessionId: t.fromSessionId
}, localWorkspaceProjectionPath(e));
if (r.revision !== t.projectionRevision || r.pending_ref || r.journal_json || r.paused_runtimes_json) throw new Error("Local workspace changed after history-cut settlement; saved edits were preserved");
await n.update(r, { session_id: e.sessionId }, e.workerAuthority);
});
}
//#endregion
//#region src/gateway/worker-environments/local-workspace-state.ts
const log = createSubsystemLogger("agents/worktrees");
function pendingDirection(e) {
return e === "canonical" || e === "projection" ? e : void 0;
}
function projectionOperations(e, t, n) {
const r = t.signal;
const i = localWorkspaceProjectionPath(e);
let a = n;
const selectCurrent = (n) => {
if (!a) throw new Error("Local workspace binding is missing");
n?.();
assertLocalWorkspaceProjectionOwner(a, e);
if (a.projection_path !== i || t.get()?.revision !== a.revision) throw new Error("Local workspace binding changed");
return a;
};
const current = () => selectCurrent(e.assertCurrent);
const assertCurrent = () => void current();
const o = {
...t.workerAuthority,
predicates: e.workerAuthority?.predicates ?? t.workerAuthority.predicates,
assertCurrent: () => {
selectCurrent(e.workerAuthority ? e.workerAuthority.assertCurrent : e.assertCurrent);
}
};
const update = async (n, r, i) => {
a = await t.update(current(), n, e.workerAuthority, r, i);
};
const repairBaseline = async () => {
const n = await t.manifest(current(), {
kind: "repair",
canonicalRoot: e.worktree.path
});
if (n.kind !== "replace") throw new Error("Local workspace baseline repair is missing");
a = await t.accept(n.update, e.workerAuthority);
};
const readManifest = async (e) => {
try {
return await t.manifest(current(), e);
} catch (n) {
if (!(n instanceof Error) || !n.message.includes("Local workspace baseline nodes are missing")) throw n;
await repairBaseline();
return await t.manifest(current(), e);
}
};
const baselineDocument = async () => {
const e = await readManifest({ kind: "materialize" });
current();
if (e.kind !== "materialize") throw new Error("Local workspace baseline materialization is missing");
return e;
};
const replaceBaseline = async (e, t, n = {}) => {
await update(n, {
rawManifest: e,
manifestRef: t,
buildCacheInputs: await buildCacheInputs()
});
};
const sourcePath = (t) => t === "canonical" ? current().projection_path : e.worktree.path;
const targetPath = (t) => t === "canonical" ? e.worktree.path : current().projection_path;
let s;
let c;
const buildCacheInputs = () => s ??= prepareLocalWorkspaceBuildInputs({
worktree: e.worktree,
projection: current(),
signal: r,
assertCurrent,
retainSourcePaths: (e) => update({ source_paths_json: e })
}).then((e) => {
c = e.paths;
return e.retained;
});
const canonicalPaths = async () => {
const t = await buildCacheInputs();
const n = current();
const i = n.baseline_ref ? await baselineDocument() : void 0;
return await selectLocalWorkspaceCanonicalPaths({
root: e.worktree.path,
admittedPaths: n.source_paths_json,
preparedPaths: c,
signal: r,
assertCurrent,
baselinePaths: i ? await workspaceManifestPaths(i, t, r) : void 0
});
};
const capture = async (t, n) => {
const i = sourcePath(t);
await assertLocalWorkspaceDirectory(i);
const a = await canonicalPaths();
const o = await captureWorkspaceManifestDocument({
root: i,
baseCommit: current().base_commit,
includePaths: t === "projection" ? a : void 0,
gitIgnore: t === "canonical" && e.worktree.removedAt === void 0 ? await readLocalWorkspaceGitExclusions(e.worktree.path, i, a) : void 0,
buildCacheInputs: new Set(await buildCacheInputs()),
preserveDirectories: n,
signal: r
});
current();
return o;
};
const scan = async (n) => {
if (e.worktree.snapshotRef) await buildCacheInputs();
await assertLocalWorkspaceDirectory(sourcePath(n));
const r = await readManifest({
kind: "scan",
target: n,
canonicalRoot: e.worktree.path
});
current();
if (r.kind !== "scan") throw new Error("Local workspace checkpoint scan is missing");
const { observation: i, ...o } = r;
if (i) a = await t.accept(i, e.workerAuthority);
s = Promise.resolve(r.buildCacheInputs);
c = void 0;
return o;
};
const recover = async () => {
const e = current();
if (!e.journal_json) return;
if (!e.journal_pack || !pendingDirection(e.pending_target)) throw new Error("Local workspace recovery metadata is incomplete");
if (!isLocalWorkspaceBaseRefreshRef(e.pending_ref)) {
const t = parseWorkerWorkspaceReconciliationPlan(e.journal_json);
await recoverWorkerWorkspaceReconciliation({
root: targetPath(pendingDirection(e.pending_target)),
journal: {
...t,
basePack: e.journal_pack
},
buildCacheInputs: await buildCacheInputs(),
assertCurrent
});
}
await update({
journal_json: null,
journal_pack: null
});
};
const cleanupAccepted = async () => {
const t = current();
if (!t.pending_ref || t.pending_target) return;
await deleteStagedWorkerWorkspaceResult({
root: e.worktree.repoRoot,
stagedResultRef: t.pending_ref,
assertCurrent
});
await update({
pending_ref: null,
checkpoint_json: null,
...t.tree_root_digest ? { baseline_json: null } : {}
});
};
const settle = async (n = false, i) => {
await recover();
const o = current();
if (o.baseline_ref && !o.tree_root_digest) {
const n = await readManifest({ kind: "convert" });
if (n.kind === "rescan") {
log.warn("Local workspace baseline conversion changed its reference; preserved source data and requesting full-scan baseline repair");
await repairBaseline();
} else if (n.kind === "replace") a = await t.accept(n.update, e.workerAuthority);
else throw new Error("Local workspace conversion preparation is missing");
}
if (!n) await cleanupAccepted();
const s = current();
if (!s.pending_ref) return;
if (!s.baseline_ref || !pendingDirection(s.pending_target)) throw new Error("Local workspace result has no accepted baseline");
const c = pendingDirection(s.pending_target);
const l = isLocalWorkspaceBaseRefreshRef(s.pending_ref);
if (!await hasWorkerWorkspaceResultRef({
root: e.worktree.path,
stagedResultRef: s.pending_ref
})) {
if (l) throw new Error("Workspace integration source is unavailable; retry github_publish prepare_pr for an imported PR, or refresh_base for the selected project. Saved work was preserved.");
let t = i;
if (!t && s.checkpoint_json) {
t = await scan(c);
await update({ checkpoint_json: JSON.stringify(t) });
}
const n = t ? void 0 : await baselineDocument();
const a = n && parseWorkerWorkspaceManifest(n.rawManifest, n.manifestRef, await buildCacheInputs());
const o = a && await capture(c, new Set(a.directories));
const u = a && e.worktree.removedAt !== void 0 && e.worktree.snapshotRef ? await captureLocalWorkspaceArchiveBaseline({
root: e.worktree.repoRoot,
snapshotCommit: await requireGit(e.worktree.repoRoot, ["rev-parse", `${e.worktree.snapshotRef}^{commit}`], {
signal: r,
beforeRun: assertCurrent
}),
manifest: a,
signal: r,
assertCurrent
}) : n;
await workerWorkspaceResultStaging.stageWorkerWorkspaceResult({
root: e.worktree.path,
stagingRoot: sourcePath(c),
stagedResultRef: s.pending_ref,
baseManifestRef: t?.baseManifestRef ?? u.manifestRef,
currentManifestRef: t?.currentManifestRef ?? o.manifestRef,
baseManifestRaw: t?.baseManifestRaw ?? u.rawManifest,
currentManifestRaw: t?.currentManifestRaw ?? o.rawManifest,
buildCacheInputs: t?.buildCacheInputs ?? await buildCacheInputs(),
assertCurrent
});
current();
}
const u = current().checkpoint_json ? JSON.parse(current().checkpoint_json) : void 0;
if (u && u.previousRoot !== s.baseline_ref) throw new Error("Local workspace checkpoint no longer matches its baseline");
const d = l ? await baselineDocument() : void 0;
let f;
await withStagedWorkerWorkspaceResult({
root: e.worktree.path,
stagedResultRef: s.pending_ref,
buildCacheInputs: u?.buildCacheInputs ?? await buildCacheInputs()
}, async (e) => {
current();
if (l && (!e.current.baseCommit || e.baseManifestRef !== d.manifestRef)) throw new Error("Local workspace result no longer matches its accepted baseline");
if (u && (e.baseManifestRef !== u.baseManifestRef || e.currentManifestRef !== u.currentManifestRef)) throw new Error("Local workspace checkpoint payload changed");
await applyStagedWorkerWorkspace({
root: targetPath(c),
stagingRoot: e.stagingRoot,
baseManifestRef: e.baseManifestRef,
currentManifestRef: e.currentManifestRef,
base: e.base,
current: e.current,
assertCurrent,
journal: {
load: async () => void 0,
begin: async (e) => {
await update({
journal_json: serializeWorkerWorkspaceReconciliationPlan(e),
journal_pack: e.basePack
}, void 0, new Uint8Array(e.basePack));
},
abort: async () => {
await update({
journal_json: null,
journal_pack: null
});
},
commit: async () => {
if (!f) throw new Error("Local workspace acceptance is missing");
try {
if (f.length) await update({
journal_json: null,
journal_pack: null
});
else if (l && c === "canonical") await update({
pending_target: "projection",
journal_json: null,
journal_pack: null
});
else {
const t = {
...l ? { base_commit: e.current.baseCommit } : {},
pending_target: null,
journal_json: null,
journal_pack: null
};
if (u) await update(t, u);
else await replaceBaseline(e.currentManifestRaw, e.currentManifestRef, t);
}
} catch (e) {
throw new AcceptedWorkspacePublicationIndeterminateError("commit", e);
}
}
},
acceptance: {
kind: "reconcile",
publish: async (e) => {
current();
f = e.conflictPaths;
}
}
});
});
if (l && c === "canonical" && current().pending_target === "projection") {
await settle(n);
return;
}
if (current().pending_target) throw new LocalWorkspaceConflictError();
if (!n) await cleanupAccepted();
};
const synchronize = async (e) => {
await settle();
const t = await scan(e);
if (t.resultingRoot !== t.previousRoot) {
await update({
pending_ref: workerWorkspaceResultRef(randomUUID()),
pending_target: e,
checkpoint_json: JSON.stringify(t)
});
await settle(false, t);
}
};
const prepare = async (n) => {
if (!a) {
const n = await requireGit(e.worktree.path, [
"rev-parse",
"--verify",
"HEAD^{commit}"
], {
signal: r,
beforeRun: e.assertCurrent
});
const o = await admitLocalWorkspaceSourcePaths({
root: e.worktree.path,
signal: r,
assertCurrent: e.assertCurrent
});
e.assertCurrent();
a = await t.create({
worktree_id: e.worktree.id,
agent_id: e.agentId,
session_key: e.sessionKey,
session_id: e.sessionId,
lifecycle_revision: e.lifecycleRevision,
projection_path: i,
base_commit: n,
source_paths_json: o,
baseline_json: null,
baseline_ref: null,
tree_root_digest: null,
source_paths_digest: null,
canonical_fingerprints: null,
projection_fingerprints: null,
checkpoint_json: null,
pending_ref: null,
pending_target: null,
journal_json: null,
journal_pack: null,
paused_runtimes_json: null,
created_at_ms: Date.now()
}, e.workerAuthority);
}
const o = current();
if (!o.baseline_ref) {
const t = await initializeLocalWorkspaceProjection({
owner: e,
projectionPath: o.projection_path,
baseCommit: o.base_commit,
signal: r,
assertCurrent,
buildCacheInputs,
dependencies: n
});
await replaceBaseline(t.rawManifest, t.manifestRef);
}
await assertLocalWorkspaceDirectory(current().projection_path);
if (o.baseline_ref) await timeWorktreePreparationPhase("synchronizeCanonical", () => synchronize("canonical"));
await timeWorktreePreparationPhase("synchronizeProjection", () => synchronize("projection"));
return current().projection_path;
};
return {
current,
workerAuthority: o,
canonicalPaths,
capture,
buildCacheInputs,
baselineDocument,
prepare,
reuse: async () => a?.baseline_ref ? await prepare() : void 0,
synchronize,
settle,
recover,
applyBaseRefresh: async (t) => {
if (!isLocalWorkspaceBaseRefreshRef(t)) throw new Error("Workspace base refresh requires its own source result");
await settle();
const n = await readStagedWorkerWorkspaceResult(e.worktree.path, t);
const r = buildCacheInputPaths(n.current.entries.map((e) => e.path));
const i = current();
const a = parseLocalWorkspaceSourcePaths(i.source_paths_json);
const o = JSON.stringify([.../* @__PURE__ */ new Set([...a, ...r])]);
await update({
pending_ref: t,
pending_target: "canonical",
...o === i.source_paths_json ? {} : { source_paths_json: o }
});
s = void 0;
c = void 0;
await settle();
},
restoreSnapshot: async () => {
await buildCacheInputs();
await recover();
const t = current();
if (!t.pending_ref) return;
if (!t.pending_target) {
const n = await readStagedWorkerWorkspaceResult(e.worktree.repoRoot, t.pending_ref, await buildCacheInputs());
current();
const r = await baselineDocument();
if (n.currentManifestRef !== r.manifestRef) throw new Error("Archive restore receipt changed");
await replaceBaseline(n.baseManifestRaw, n.baseManifestRef, {
pending_target: "canonical",
checkpoint_json: null
});
}
await settle(true);
},
finishRestore: cleanupAccepted,
prepareArchive: async (t) => {
await settle();
if ((await runGit(e.worktree.path, [
"rev-parse",
"--verify",
"--quiet",
"MERGE_HEAD"
], {
signal: r,
beforeRun: assertCurrent
})).code !== 1) throw new Error("Workspace integration is pending; finish the original github_publish prepare_pr or refresh_base action before archiving this worktree. Saved files and merge state were preserved.");
const n = await baselineDocument();
const i = parseWorkerWorkspaceManifest(n.rawManifest, n.manifestRef, await buildCacheInputs());
const a = await capture("canonical", new Set(i.directories));
if (a.manifestRef !== n.manifestRef) throw new Error("Local workspace changed before archive capture");
const o = current().projection_path;
const s = await captureLocalWorkspaceArchiveBaseline({
root: e.worktree.repoRoot,
snapshotCommit: t,
manifest: i,
signal: r,
assertCurrent
});
if (s.manifestRef === a.manifestRef) return;
const c = workerWorkspaceResultRef(randomUUID());
await update({
pending_ref: c,
pending_target: "canonical",
checkpoint_json: null
});
await workerWorkspaceResultStaging.stageWorkerWorkspaceResult({
root: e.worktree.repoRoot,
stagingRoot: o,
stagedResultRef: c,
baseManifestRaw: s.rawManifest,
baseManifestRef: s.manifestRef,
currentManifestRaw: a.rawManifest,
currentManifestRef: a.manifestRef,
buildCacheInputs: await buildCacheInputs(),
assertCurrent
});
current();
},
expire: async (n) => {
const r = current();
if (r.journal_json || r.pending_target && r.pending_target !== "canonical") throw new Error("Local sandbox has pending edits; restore its worktree before cleanup");
const i = r.baseline_ref ? await baselineDocument() : void 0;
let a = i ? {
raw: i.rawManifest,
ref: i.manifestRef
} : void 0;
if (r.pending_ref) {
if (!n || e.worktree.removedAt === void 0) throw new Error("Archive receipt still owns its restore data");
if (r.pending_target) {
const t = await readStagedWorkerWorkspaceResult(e.worktree.repoRoot, r.pending_ref, await buildCacheInputs());
current();
if (t.baseManifestRef !== i?.manifestRef && t.currentManifestRef !== i?.manifestRef) throw new Error("Archive retention receipt changed");
a = {
raw: t.currentManifestRaw,
ref: t.currentManifestRef
};
}
}
if (a) {
const e = parseWorkerWorkspaceManifest(a.raw, a.ref, await buildCacheInputs());
if ((await capture("canonical", new Set(e.directories))).rawManifest !== serializeWorkerWorkspaceManifest(e)) throw new Error("Local sandbox has unaccepted edits; restore its worktree before cleanup");
}
const { readLocalWorkspaceRuntimes: o } = await import("./local-workspace-quiescence-Be30njub.mjs");
if ((await o(r.projection_path, { env: e.env })).length) throw new Error("Local sandbox runtime still owns its workspace; cleanup deferred");
const s = path.dirname(r.projection_path);
await assertLocalWorkspaceDirectory(s);
current();
await n?.(assertCurrent);
current();
if (r.pending_ref && a) {
await replaceBaseline(a.raw, a.ref, {
pending_target: null,
checkpoint_json: null
});
await cleanupAccepted();
}
current();
await fs.rm(s, {
recursive: true,
force: true
});
await t.delete(current(), e.workerAuthority);
},
rememberPaused: (e) => update({ paused_runtimes_json: e })
};
}
//#endregion
//#region src/gateway/worker-environments/local-workspace-projection.ts
const pendingCheckpoints = /* @__PURE__ */ new Map();
async function joinLocalWorkspaceCheckpoint(e, t, n) {
const r = captureWorktreeRunEndContext(e.env ?? process.env);
e.assertCurrent?.();
e.workerAuthority?.assertCurrent?.();
const { worktree: i } = e;
const a = JSON.stringify([
r.admission.coordinationKey,
i.id,
i.path,
i.repoRoot,
i.ownerKind,
i.ownerId,
i.branch,
i.snapshotRef,
i.removedAt,
t
]);
let o = pendingCheckpoints.get(a);
if (!o) {
const forget = () => {
if (pendingCheckpoints.get(a) === o) pendingCheckpoints.delete(a);
};
o = n(forget).finally(forget);
pendingCheckpoints.set(a, o);
}
await o;
r.admission.assertCurrent();
e.assertCurrent?.();
e.workerAuthority?.assertCurrent?.();
}
/** Checkpoint callers keep their own session authority while sharing queued capture. */
function checkpointLocalWorkspace(e) {
return joinLocalWorkspaceCheckpoint(e, [
e.agentId,
e.sessionKey,
e.sessionId,
e.lifecycleRevision
], (t) => withLocalWorkspaceProjection(e, (e) => {
t();
return e.synchronize("canonical");
}));
}
/** Publication and lifecycle callers retain their own authority while joining local settlement. */
async function withSettledLocalWorkspace(e, t) {
return await settleLocalWorkspace(e, t);
}
async function settleLocalWorkspace(e, t) {
const n = captureWorktreeRunEndContext(e.env ?? process.env);
const r = {
...e.env ?? process.env,
...n.environment
};
const i = [];
if (e.retireRuntime) {
const t = await executeExistingOpenClawStateRead({
path: n.admission.databasePath,
env: r
}, {
type: "localWorkspace.get",
input: { id: e.worktree.id }
}, {
context: n,
current: true,
live: true
});
n.admission.assertCurrent();
e.assertCurrent?.();
if (t && (!t.ok || t.type !== "localWorkspace.get")) throw new Error("Unexpected local workspace retirement lookup");
if (t?.row) {
if (e.sessionOwner) {
const n = {
...e.sessionOwner,
lifecycleRevision: t.row.lifecycle_revision,
worktree: e.worktree,
env: r,
assertCurrent: e.assertCurrent ?? (() => {})
};
assertLocalWorkspaceProjectionOwner(t.row, n, localWorkspaceProjectionPath(n));
}
const { readRegistry: a } = await import("./registry-C3u7AFtC.mjs");
const { prepareSandboxPersistentExecRetirement: o } = await import("./persistent-exec-retirement-DUgh-xMT.mjs");
for (const s of (await a({
path: n.admission.databasePath,
env: r
})).entries) if (s.workspaceDir === t.row.projection_path) i.push(await o({
containerName: s.containerName,
env: r,
assertCurrent: () => {
n.admission.assertCurrent();
e.assertCurrent?.();
e.workerAuthority?.assertCurrent?.();
}
}));
}
}
return await withLocalWorkspaceStore({
...e,
env: r,
worktreeId: e.worktree.id
}, async (a) => {
a.assertCurrent();
const o = a.get();
if (!o) return await t({
worktreeId: e.worktree.id,
assertCurrent: a.assertCurrent,
workerAuthority: a.workerAuthority
});
const s = e.worktree;
const c = {
...e.workerAuthority,
assertCurrent: e.workerAuthority ? e.workerAuthority.assertCurrent : e.assertCurrent,
predicates: [...e.workerAuthority?.predicates ?? [], {
kind: "projection",
id: s.id,
ownerId: o.session_key,
path: s.path,
repoRoot: s.repoRoot
}]
};
const l = await prepareWorktreeRegistryGuard(n, c);
return await runLocalWorkspaceProjection({
worktree: s,
env: r,
agentId: e.sessionOwner?.agentId ?? o.agent_id,
sessionKey: e.sessionOwner?.sessionKey ?? o.session_key,
sessionId: e.sessionOwner?.sessionId ?? o.session_id,
lifecycleRevision: e.sessionOwner ? e.sessionOwner.lifecycleRevision : o.lifecycle_revision,
workerAuthority: c,
assertCurrent: () => {
if (e.assertCurrent !== c.assertCurrent) e.assertCurrent?.();
l();
}
}, a, async (n, r) => {
if (e.finishRestore) await n.finishRestore();
else if (e.restoreSnapshot) await n.restoreSnapshot();
else if (n.current().baseline_ref) {
await n.synchronize("canonical");
if (e.retireRuntime) await n.synchronize("projection");
}
if (e.retireRuntime) {
for (const e of i) await e.finish();
await r?.retire();
}
const o = n.current();
return await t(o.baseline_ref ? {
worktreeId: s.id,
projectionPath: o.projection_path,
projectionRevision: o.revision,
prepareArchive: n.prepareArchive,
canonicalPaths: n.canonicalPaths,
synchronizeProjection: () => n.synchronize("projection"),
assertCurrent: n.current,
workerAuthority: n.workerAuthority
} : {
worktreeId: s.id,
projectionRevision: o.revision,
assertCurrent: a.assertCurrent,
workerAuthority: a.workerAuthority
});
});
});
}
async function withSettledLocalWorkspacePath(e, t) {
const n = captureWorktreeRunEndContext(process.env);
const r = {
...process.env,
...n.environment
};
const i = await readLiveRegistryWorktreeByPath(n, e.cwd);
e.assertCurrent?.();
return i ? await withSettledLocalWorkspace({
worktree: i,
env: r,
assertCurrent: e.assertCurrent
}, t) : await t();
}
/** Every operation owns the same renewable, cross-process reconciliation lease. */
async function withLocalWorkspaceProjection(e, t, n = {}) {
return await withLocalWorkspaceStore({
...e,
worktreeId: e.worktree.id,
signal: n.signal
}, (r) => runLocalWorkspaceProjection(e, r, t, n));
}
async function runLocalWorkspaceProjection(e, t, n, r = {}) {
const assertCurrent = () => {
t.get();
e.assertCurrent();
};
assertCurrent();
let i = t.get();
if (i && i.session_id === e.sessionId && i.session_key === e.sessionKey && i.agent_id === e.agentId && i.lifecycle_revision !== e.lifecycleRevision) i = await t.update(i, { lifecycle_revision: e.lifecycleRevision }, e.workerAuthority);
const a = projectionOperations(e, t, i);
if (i) a.current();
const { quiesceLocalWorkspace: o, parseLocalWorkspacePausedRuntimes: s } = await import("./local-workspace-quiescence-Be30njub.mjs");
const c = i && !r.provision ? await timeWorktreePreparationPhase("runtimeQuiesce", () => o({
env: e.env,
workspaceDir: i.projection_path,
retained: s(i.paused_runtimes_json),
persist: (e) => a.rememberPaused(e.length ? JSON.stringify(e) : null),
assertCurrent
})) : void 0;
try {
return await n(a, c);
} catch (t) {
if (t instanceof Error && workspaceSizeRecoveryPaths(t).length > 0) {
const { describeLocalWorkspaceRecovery: n } = await import("./local-workspace-recovery-8eEIq9AO.mjs");
throw await n(t, e, a);
}
throw t;
} finally {
if (!c?.retired) t.workerAuthority.assertCurrent?.();
const e = c?.retired ? void 0 : t.get();
if (e && !e.journal_json && !(e.pending_target && isLocalWorkspaceBaseRefreshRef(e.pending_ref))) {
if (c) await timeWorktreePreparationPhase("runtimeResume", () => c.resume());
}
}
}
/** Expiry belongs to the existing worktree retention owner, never sandbox pruning. */
async function expireLocalWorkspaceProjection(e) {
const t = captureWorktreeRunEndContext(e.env);
const n = {
...e.env,
...t.environment
};
return await withLocalWorkspaceStore({
...e,
env: n,
worktreeId: e.worktree.id
}, async (r) => {
r.assertCurrent();
const i = r.get();
if (!i) {
await e.retireSnapshot?.(r.assertCurrent);
return;
}
if (e.worktree.removedAt === void 0) throw new Error("Cannot expire a live sandbox workspace");
const a = captureWorktreeRegistryReadGuard(t, "lifecycle", e.worktree);
const o = await readRegistryWorktree(t, e.worktree.id);
const s = a(o);
e.assertCurrent();
if (o?.removedAt !== e.worktree.removedAt || o?.ownerId !== i.session_key) throw new Error("Workspace retention owner changed");
await runLocalWorkspaceProjection({
worktree: e.worktree,
env: n,
agentId: i.agent_id,
sessionKey: i.session_key,
sessionId: i.session_id,
lifecycleRevision: i.lifecycle_revision,
workerAuthority: e.workerAuthority,
assertCurrent: () => {
if (e.workerAuthority?.assertCurrent !== e.assertCurrent) e.workerAuthority?.assertCurrent?.();
e.assertCurrent();
s();
}
}, r, (t) => t.expire(e.retireSnapshot));
});
}
/** Bind only a live session-owned managed checkout, never an arbitrary host path. */
async function resolveLocalWorkspaceOwner(e) {
const t = captureWorktreeRunEndContext(e.env ?? process.env);
const n = {
...e.env ?? process.env,
...t.environment
};
const r = {
agentId: e.agentId,
sessionKey: e.sessionKey,
storePath: e.storePath ?? resolveSessionStorePathCore(e.cfg.session?.store, {
agentId: e.agentId,
env: n
}),
env: n
};
const i = new DisposableStack();
let a;
let unregister = () => {};
i.defer(() => {
a?.release();
unregister();
});
const release = () => i.dispose();
const assertActive = () => {
e.assertCurrent?.();
if (i.disposed) throw new Error("Local sandbox workspace authority changed");
};
const o = captureSessionEntryMetadataRead(r, assertActive);
try {
let i;
const s = o ? o.readCurrent() : await withSessionEntryReadOnlyInWorker(r, assertActive, async (e) => {
if (!e.ok) throw e.error;
const t = e.value;
if (i && t) a = retainPreparedSessionEntryPredicate({
databaseIdentity: i,
sessionKey: r.sessionKey,
entry: t,
matches: (e, t) => t !== void 0 && e?.sessionId === t.sessionId && e?.lifecycleRevision === t.lifecycleRevision && t.archivedAt === void 0 && e?.worktree?.id === t.worktree?.id
});
return t;
}, (e, t) => {
i = t.key;
unregister = registerOpenClawAgentDatabaseAsyncResource({
agentId: e.agentId,
path: e.path,
revoke: release,
close: async () => release()
});
});
if (!s?.worktree?.id) {
release();
return;
}
const c = {
id: s.worktree.id,
ownerKind: "session"
};
const l = captureWorktreeRegistryReadGuard(t, "lifecycle", c);
const u = await readRegistryWorktree(t, s.worktree.id);
const d = l(u);
if (!u || u.removedAt !== void 0 || u.ownerKind !== "session" || u.ownerId !== e.sessionKey || u.repoRoot !== s.worktree.repoRoot || u.branch !== s.worktree.branch || e.workspaceDir && !isPathInside(u.path, e.workspaceDir)) throw new Error("Local sandbox managed workspace owner changed");
const assertSessionCurrent = () => {
if (!o) {
assertActive();
if (!a?.isCurrent()) throw new Error("Local sandbox workspace authority changed");
return;
}
const e = o.readCurrent();
if (e?.sessionId !== s.sessionId || e?.lifecycleRevision !== s.lifecycleRevision || e?.archivedAt !== void 0 || e?.worktree?.id !== u.id) throw new Error("Local sandbox workspace authority changed");
};
const assertCurrent = () => {
assertSessionCurrent();
d();
};
assertCurrent();
const f = {
agentId: e.agentId,
sessionKey: e.sessionKey,
sessionId: s.sessionId,
lifecycleRevision: s.lifecycleRevision ?? null,
worktree: u,
assertCurrent,
workerAuthority: {
assertCurrent: assertSessionCurrent,
predicates: [{
kind: "live-binding",
record: u
}]
},
env: n,
[Symbol.dispose]: release
};
if (s.localWorkspaceHandoff) {
const e = s.localWorkspaceHandoff;
await finishLocalWorkspaceHandoff(f, e);
await patchSessionEntryCore(r, (t) => {
assertCurrent();
if (t?.sessionId !== f.sessionId || t.lifecycleRevision !== s.lifecycleRevision || JSON.stringify(t.localWorkspaceHandoff) !== JSON.stringify(e)) throw new Error("Local workspace handoff changed before completion");
return { localWorkspaceHandoff: void 0 };
});
}
return f;
} catch (e) {
release();
throw e;
}
}
//#endregion
export { withSettledLocalWorkspace as a, withLocalWorkspaceProjection as i, expireLocalWorkspaceProjection as n, withSettledLocalWorkspacePath as o, resolveLocalWorkspaceOwner as r, checkpointLocalWorkspace as t };