openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
461 lines (460 loc) • 16.5 kB
JavaScript
import { r as resolveGlobalMap } from "./global-singleton-D7yf05nR.mjs";
import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs";
import { s as redactSensitiveText } from "./redact-Mj7pppxC.mjs";
import { n as ignoreMissingPath } from "./errno-DFcoqIT9.mjs";
import { o as pathEntryExists } from "./path-existence-Co7-GyVr.mjs";
import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { l as readCommandProcessFailure, t as CommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs";
import { s as hasWorktreeUnknownOutcome } from "./errors-CJd09ymz.mjs";
import { t as runTasksWithConcurrency } from "./run-with-concurrency-B34GDKXE.mjs";
import { a as executeGitCommand, d as normalizeGitPathForFilesystem, i as enqueueGitRefMutation, m as requireGitCommandOutput, r as createGitCommandError } from "./git-exec-DHBL622T.mjs";
import { i as listGitWorktrees, o as requireGit, u as runGit } from "./git-BBx5S0aA.mjs";
import { h as estimateWorktreeGitBytes, n as startWorktreeWait } from "./allocation-DPkHxKtM.mjs";
import { i as timeWorktreePreparationPhase } from "./preparation-timing-YO2wGpby.mjs";
import { t as withWorktreeGitConfig } from "./checkout-git-config-ClOP9WBP.mjs";
import path from "node:path";
import fs from "node:fs/promises";
//#region src/agents/worktrees/base-ref.ts
const log = createSubsystemLogger("agents/worktrees");
const remoteDefaults = resolveGlobalMap(Symbol.for("openclaw.worktreeRemoteDefaults"));
const BASE_FRESHNESS_MS = 3e4;
var InvalidWorktreeBaseRefError = class extends Error {
constructor(e) {
super("Worktree base ref does not resolve to a commit. Choose a local or remote branch and retry.", e);
this.name = "InvalidWorktreeBaseRefError";
}
};
async function resolveWorktreeCreationBase(e, t) {
if (t.checkoutCommit) {
if (!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(t.checkoutCommit)) throw new Error("Worktree checkout commit is invalid");
return {
commit: t.checkoutCommit,
gitOperand: t.checkoutCommit,
recordRef: t.baseRef ?? t.checkoutCommit,
fetchSucceeded: void 0,
warning: void 0
};
}
if (!t.baseRef) t.onProgress?.("base");
return t.prepareBase && !t.baseRef ? await t.prepareBase({
signal: t.signal,
assertCurrent: t.commitGuard,
localDefault: "fast-forward",
waitBudget: t.waitBudget
}) : await resolveWorktreeBase(e, t.baseRef, t.signal, t.commitGuard, "fast-forward");
}
async function resolveWorktreeBase(e, t, n, r, i = "preserve") {
if (t) {
const i = await runGit(e, [
"-c",
"core.warnAmbiguousRefs=true",
"rev-parse",
"--verify",
"--end-of-options",
`${t === "-" ? "@{-1}" : t}^{commit}`
], {
signal: n,
beforeRun: r
});
n?.throwIfAborted();
if (i.termination === "exit" && typeof i.code === "number" && i.code !== 0) throw new InvalidWorktreeBaseRefError({ cause: createGitCommandError("git rev-parse --verify", i) });
const a = requireGitCommandOutput("git rev-parse --verify", i).trim();
if (!a || a.includes("\n") || i.stderr.trim()) throw new InvalidWorktreeBaseRefError({ cause: createGitCommandError("git rev-parse --verify", i) });
return {
commit: a,
gitOperand: t !== "-" && t.startsWith("-") ? a : t,
recordRef: t
};
}
const a = {
signal: n,
beforeRun: () => {
n?.throwIfAborted();
r?.();
},
env: {
GIT_NO_LAZY_FETCH: "1",
GIT_TERMINAL_PROMPT: "0"
}
};
const o = await fs.realpath(path.resolve(e, normalizeGitPathForFilesystem(await requireGit(e, ["rev-parse", "--git-common-dir"], a))));
return await withWorktreeBasePreparation({
repoRoot: await fs.realpath(e),
commonDir: o
}, (e) => e({
signal: n,
assertCurrent: r,
localDefault: i
}));
}
/** Capture a creation cohort before capacity waits, without fetching until a source owner consumes it. */
async function withWorktreeBasePreparation(e, t) {
const n = JSON.stringify([e.commonDir, e.repoRoot].map((e) => process.platform === "win32" ? e.toLowerCase() : e));
const r = remoteDefaults.get(n);
const i = r && (r.borrowers > 0 && r.attempt?.refreshedAt === void 0 || Date.now() - (r.attempt?.refreshedAt ?? -Infinity) < BASE_FRESHNESS_MS) ? r : { borrowers: 0 };
i.borrowers++;
remoteDefaults.set(n, i);
pruneMapToMaxSize(remoteDefaults, 32);
let a = true;
const o = [];
const resolve = async ({ signal: t, assertCurrent: n, localDefault: r = "preserve", waitBudget: o }) => {
let s;
let c;
const l = {
signal: t,
beforeRun: () => {
try {
if (!a) throw new Error("Worktree base preparation is closed");
l.signal?.throwIfAborted();
n?.();
} catch (e) {
s = { error: e };
throw e;
}
},
env: {
GIT_NO_LAZY_FETCH: "1",
GIT_TERMINAL_PROMPT: "0"
}
};
const settled = (e, t) => t.catch((t) => {
e.refreshedAt = void 0;
if (hasWorktreeUnknownOutcome(t)) throw t;
const n = readCommandProcessFailure(t);
if (n?.cleanup === "uncertain") throw new CommandProcessCleanupError({ cause: t });
if (s && s.error === t || l.signal?.aborted && (t === l.signal.reason || n?.termination === "signal" && !n.outputLimitExceeded && (n.cleanup === "normal" || n.killIssuedByAbort === true && (n.cleanup === "cooperative" || n.cleanup === "forced")))) e.retired = true;
throw t;
});
try {
for (;;) {
l.beforeRun();
let n = i.attempt;
let a = false;
if (!n) {
a = true;
const t = { pending: timeWorktreePreparationPhase("baseRefresh", () => prepareDefaultBase(e, l)).then(async (n) => {
const r = n.commit;
await timeWorktreePreparationPhase("baseHydration", () => estimateWorktreeGitBytes(e.repoRoot, n.commit, {
signal: l.signal,
assertCurrent: l.beforeRun,
preparationKey: r
}));
n.preparationKey = r;
l.beforeRun();
if (n.fetchSucceeded) t.refreshedAt = Date.now();
return n;
}) };
t.pending = settled(t, t.pending);
n = i.attempt = t;
}
if (r === "fast-forward" && !n.forwarded) {
a = true;
n.forwarded = true;
n.pending = settled(n, n.pending.then(async (t) => {
const { branch: n } = t;
const r = n ? await timeWorktreePreparationPhase("baseFastForward", () => fastForwardLocalDefault(e, n, t.commit, l)) : void 0;
return r ? {
...t,
warning: [t.warning, redactSensitiveText(r)].filter(Boolean).join("\n")
} : t;
}));
}
try {
const e = await timeWorktreePreparationPhase("baseWait", () => c && !a ? racePromiseWithAbortSignal(n.pending, l.signal, (e) => e.reason) : n.pending);
l.beforeRun();
const { branch: t, ...r } = e;
return r;
} catch (e) {
if (!n.retired || hasWorktreeUnknownOutcome(e)) throw e;
l.beforeRun();
if (!c) {
c = startWorktreeWait(o);
if (c.waitMs === 0) throw new Error("Workspace creation timed out waiting for repository preparation. Retry creating the workspace.", { cause: e });
const n = AbortSignal.timeout(c.waitMs);
l.signal = t ? AbortSignal.any([t, n]) : n;
}
if (i.attempt === n) i.attempt = void 0;
}
}
} finally {
c?.end();
}
};
try {
return await t((e) => {
const t = resolve(e);
o.push(t);
return t;
});
} finally {
a = false;
await Promise.allSettled(o);
if (--i.borrowers === 0 && !i.attempt?.refreshedAt && remoteDefaults.get(n) === i) remoteDefaults.delete(n);
}
}
async function hasOriginDestination({ repoRoot: e, commonDir: t }, n) {
const r = await runGit(e, [
"config",
"--name-only",
"--get-regexp",
"^remote\\.origin\\.(url|pushurl|vcs)$"
], n);
if (r.cleanup === "uncertain") throw new CommandProcessCleanupError();
if (r.termination !== "exit" || r.code !== 1) {
requireGitCommandOutput("git config origin destination", r);
return true;
}
const i = await runGit(e, [
"ls-remote",
"--get-url",
"origin"
], n);
if (i.cleanup === "uncertain") throw new CommandProcessCleanupError();
const a = requireGitCommandOutput("git ls-remote --get-url origin", i);
if (a !== "origin\n" && a !== "origin\r\n") return true;
for (const n of [
path.join(e, "origin"),
path.join(t, "remotes", "origin"),
path.join(t, "branches", "origin")
]) if (await pathEntryExists(n)) return true;
return false;
}
async function prepareDefaultBase(e, t) {
const { repoRoot: n } = e;
if ((await requireGit(n, ["remote"], t)).split("\n").includes("origin") && await hasOriginDestination(e, t)) return await fetchRemoteDefault(n, t);
const r = (await listGitWorktrees(n, t))[0]?.path ?? n;
const i = await requireGit(r, [
"rev-parse",
"--verify",
"HEAD^{commit}"
], t);
return {
commit: i,
gitOperand: i,
recordRef: "HEAD",
noOrigin: true
};
}
async function fetchRemoteDefault(e, t, n) {
const r = await runGit(e, [
"symbolic-ref",
"--quiet",
"refs/remotes/origin/HEAD"
], t);
if (r.cleanup === "uncertain") throw new CommandProcessCleanupError();
const runTransport = (r, i) => n ? n.run(r, i) : runGit(e, r, {
...t,
timeoutMs: i
});
const i = n ? ["--", n.url] : ["origin"];
const a = await runTransport([
"ls-remote",
"--symref",
...i,
"HEAD"
], 3e4);
if (a.cleanup === "uncertain") throw new CommandProcessCleanupError();
if (t.signal?.aborted) {
requireGitCommandOutput("git ls-remote origin HEAD", a);
t.signal.throwIfAborted();
}
const o = a.termination === "exit" && a.code === 0;
const s = o ? /^ref: refs\/heads\/(.+)\tHEAD\r?$/mu.exec(a.stdout)?.[1] : void 0;
const c = r.termination === "exit" && r.code === 0 ? /^refs\/remotes\/origin\/(.+)$/u.exec(r.stdout.trim())?.[1] : void 0;
let l = s ?? c;
const u = [];
if (!o) u.push(createGitCommandError("git ls-remote origin HEAD", a).message);
else if (!s) u.push("origin did not advertise a default branch; using its cached default.");
if (!l || l === "HEAD") throw new Error(`Remote default branch is unavailable. Repair origin or choose an explicit worktree base ref. ${redactSensitiveText(u.join("\n"))}`);
let d = `refs/remotes/origin/${l}`;
const f = await runTransport([
"fetch",
"--no-auto-maintenance",
"--no-recurse-submodules",
"--no-tags",
...i,
`+refs/heads/${l}:${d}`
], 6e4);
if (f.cleanup === "uncertain") throw new CommandProcessCleanupError();
if (t.signal?.aborted) {
requireGitCommandOutput("git fetch origin default branch", f);
t.signal.throwIfAborted();
}
const p = f.termination === "exit" && f.code === 0;
if (!p) {
u.push(createGitCommandError("git fetch origin default branch", f).message);
l = c ?? l;
d = `refs/remotes/origin/${l}`;
}
const m = [
"rev-parse",
"--verify",
`${d}^{commit}`
];
const h = n && p ? await runTransport(m, 6e4) : await runGit(e, m, t);
if (h.cleanup === "uncertain") throw new CommandProcessCleanupError();
if (t.signal?.aborted) {
requireGitCommandOutput("git rev-parse remote default", h);
t.signal.throwIfAborted();
}
if (h.termination !== "exit" || h.code !== 0) throw new Error(`Remote default ${d} is unavailable. Repair origin or choose an explicit worktree base ref. ${redactSensitiveText(u.join("\n"))}`);
const g = requireGitCommandOutput("git rev-parse remote default", h).trim();
if (n && p) await requireGit(e, [
"update-ref",
"--no-deref",
d,
g
], t);
if (p && s && c !== l) await requireGit(e, [
"symbolic-ref",
"refs/remotes/origin/HEAD",
d
], t);
t.beforeRun?.();
return {
branch: l,
commit: g,
gitOperand: d,
recordRef: `origin/${l}`,
fetchSucceeded: p,
...u.length ? { warning: redactSensitiveText(u.join("\n")) } : {}
};
}
var LocalDefaultBusyError = class extends Error {};
async function assertWorktreeGitOperationsIdle(e, t, n) {
try {
const r = path.join(e, "worktrees");
const i = await fs.readdir(r).catch((e) => ignoreMissingPath(e) ?? []);
const busy = () => new LocalDefaultBusyError("Local default retained: finish or abort the Git rebase, am, or bisect operation reserving it before advancing it.");
if ((await fs.readdir(e)).some((e) => [
"rebase-merge",
"rebase-apply",
"BISECT_LOG"
].includes(e))) throw busy();
const read = async (e, t) => await fs.readFile(path.join(e, t), "utf8").catch(ignoreMissingPath);
const a = await runTasksWithConcurrency({
limit: 16,
errorMode: "stop",
tasks: i.map((e) => async () => {
n.signal?.throwIfAborted();
n.beforeRun?.();
const i = path.join(r, e);
for (const e of [
"rebase-merge/head-name",
"rebase-apply/head-name",
"rebase-merge/update-refs"
]) if ((await read(i, e))?.trim().split("\n").includes(t)) throw busy();
const a = (await read(i, "BISECT_START"))?.trim();
if (a === t || a === t.slice(11)) {
if (await read(i, "BISECT_LOG") !== void 0) throw busy();
}
})
});
if (a.hasError) throw a.firstError;
} catch (e) {
n.signal?.throwIfAborted();
n.beforeRun?.();
if (e instanceof LocalDefaultBusyError) throw e;
throw new LocalDefaultBusyError("Local default retained: Git worktree operation state could not be checked. Inspect Git worktree metadata before retrying.", { cause: e });
}
}
async function fastForwardLocalDefault({ repoRoot: e, commonDir: t }, n, r, i) {
const a = `refs/heads/${n}`;
const o = await runGit(e, [
"rev-parse",
"--verify",
a
], i);
if (o.termination !== "exit" || o.code !== 0 || o.stdout.trim() === r) return;
const s = o.stdout.trim();
const c = await runGit(e, [
"merge-base",
"--is-ancestor",
s,
r
], i);
if (c.termination !== "exit" || c.code !== 0) return;
const l = await runGit(e, [
"symbolic-ref",
"--quiet",
"HEAD"
], i);
if (l.termination !== "exit" || l.code !== 0 || l.stdout.trim() !== a) return;
const u = await enqueueGitRefMutation(e, t, () => withWorktreeGitConfig(e, true, i, async (n) => {
try {
await assertWorktreeGitOperationsIdle(t, a, i);
const o = (await listGitWorktrees(e, i)).filter((e) => e.branch === a);
const s = o[0];
if (!s || o.length > 1 || path.resolve(s.path) !== path.resolve(e) || s.lockedReason !== void 0) throw new LocalDefaultBusyError();
const c = await runGit(e, [
"config",
"--bool",
"core.sparseCheckout"
], i);
if (c.termination !== "exit" || c.code !== 0 && c.code !== 1 || c.stdout.trim() === "true") throw new LocalDefaultBusyError();
const l = await n.run(e, [
"status",
"--porcelain",
"--untracked-files=all"
], i);
if (l.termination !== "exit" || l.code !== 0 || l.stdout.trim()) throw new LocalDefaultBusyError();
const u = await runGit(e, [
"symbolic-ref",
"--quiet",
"HEAD"
], i);
if (u.termination !== "exit" || u.code !== 0 || u.stdout.trim() !== a) throw new LocalDefaultBusyError();
return await n.withContentEnvironment((t) => executeGitCommand(e, [
"merge",
"--ff-only",
"--no-edit",
"--no-stat",
"--no-overwrite-ignore",
r
], {
...i,
env: t,
killProcessTree: true
}));
} catch (e) {
if (e instanceof LocalDefaultBusyError) return e;
throw e;
}
}), i.signal);
if (u instanceof LocalDefaultBusyError) return u.message || void 0;
if (u.termination !== "exit" || u.code !== 0) return createGitCommandError("git fast-forward local default", u).message;
}
/** Report the immutable commit captured by checkout registration, not an earlier ref value. */
async function logWorktreeBase(e, t, n, r) {
const i = Number(await requireGit(e, [
"show",
"-s",
"--no-show-signature",
"--no-notes",
"--format=%ct",
n
], {
signal: r.signal,
beforeRun: r.assertCurrent,
env: { GIT_NO_LAZY_FETCH: "1" }
}));
const a = Math.max(0, (r.now / 1e3 - i) / 86400);
const o = a > 7;
const s = t.noOrigin ? "local HEAD (no origin remote)" : t.recordRef;
const c = `; base is older than 7 days. Check ${t.noOrigin ? "local HEAD" : "origin"} before starting work.`;
const l = `worktree base ${s} at ${n} (commit age ${a.toFixed(1)} days; fetch ${t.fetchSucceeded === void 0 ? "not requested" : t.fetchSucceeded ? "succeeded" : "failed"})${t.warning ? `: ${t.warning}` : ""}${o ? c : ""}`;
const u = {
worktreePath: r.worktreePath,
ownerId: r.ownerId,
baseRef: t.recordRef,
baseCommit: n,
ageDays: a,
fetchSucceeded: t.fetchSucceeded
};
if (t.warning || o) log.warn(l, u);
else log.info(l, u);
}
//#endregion
export { resolveWorktreeCreationBase as a, resolveWorktreeBase as i, fetchRemoteDefault as n, withWorktreeBasePreparation as o, logWorktreeBase as r, InvalidWorktreeBaseRefError as t };