Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions tools/teardown-worktree.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ if (process.argv.includes("--help") || process.argv.includes("-h")) {

const ORCA = process.env.ORCA_BIN || "C:\\Users\\thoma\\AppData\\Local\\Programs\\orca\\resources\\bin\\orca"
const GIT = process.env.GIT_BIN || "git"
const GH = process.env.GH_BIN || "gh"
const fail = (code, message) => {
console.error(message)
process.exit(code)
Expand Down Expand Up @@ -75,6 +76,24 @@ const git = (path, args, { allowFailure = false } = {}) => {
if (allowFailure) return null
fail(3, `git ${args.join(" ")} failed: ${(result.stderr || result.stdout || "unknown error").trim()}`)
}
const pullRequestFor = (path, branch, base) => {
let raw
try {
raw = execFileSync(GH, ["pr", "list", "--head", branch, "--base", base, "--state", "merged", "--limit", "1", "--json", "number,mergeCommit,headRefOid,mergedAt"], { cwd: path, encoding: "utf8", maxBuffer: 32 * 1024 * 1024 })
} catch (error) {
fail(3, `gh pr list for ${branch} failed: ${(error.stdout?.toString() || error.stderr?.toString() || error.message).trim()}`)
}
try {
const pullRequests = JSON.parse(raw)
if (!Array.isArray(pullRequests)) fail(3, `gh pr list for ${branch} returned an unexpected payload`)
const [pullRequest] = pullRequests
if (!pullRequest?.mergedAt || !pullRequest.number || !pullRequest.mergeCommit?.oid || !pullRequest.headRefOid) fail(1, `pull request for ${branch} is not a merged pull request with merge and head commits`)
return pullRequest
} catch (error) {
if (error instanceof SyntaxError) fail(3, `gh pr list for ${branch} returned unparseable output: ${raw.slice(0, 300)}`)
throw error
}
}
const selectorPath = (value) => value?.replace(/^path:/, "")
const normalize = (path) => (typeof path === "string" ? resolve(selectorPath(path)) : "").replaceAll("\\", "/").replace(/\/+$/, "").toLowerCase()

Expand All @@ -100,12 +119,15 @@ const state = linearIssue.state?.name ?? linearIssue.state

git(path, ["fetch", "--quiet", "origin", base], { allowFailure: true })
const baseRef = git(path, ["rev-parse", "--verify", "--quiet", `origin/${base}`], { allowFailure: true }) ? `origin/${base}` : base
const mergeBase = git(path, ["merge-base", baseRef, branch])
const branchPaths = git(path, ["diff", "--name-only", mergeBase, branch]).split("\n").filter(Boolean)
const treePresent = branchPaths.length === 0 || git(path, ["diff", "--quiet", baseRef, branch, "--", ...branchPaths], { allowFailure: true }) !== null
const pullRequest = pullRequestFor(path, branch, base)
git(path, ["fetch", "--quiet", "origin", pullRequest.mergeCommit.oid])
const mergeCommitPresent = git(path, ["merge-base", "--is-ancestor", pullRequest.mergeCommit.oid, baseRef], { allowFailure: true }) !== null
const localTip = git(path, ["rev-parse", branch])
const localTipPresent = localTip === pullRequest.headRefOid || git(path, ["merge-base", "--is-ancestor", localTip, baseRef], { allowFailure: true }) !== null
const treePresent = mergeCommitPresent && localTipPresent
const checks = [
{ name: "worktree-clean", ok: dirty.length === 0, detail: dirty.length ? `uncommitted paths: ${dirty.join(", ")}` : "no uncommitted work" },
{ name: "tree-present-in-target", ok: treePresent, detail: treePresent ? `${branch}'s content is present in ${baseRef}` : `${branch}'s content is not present in ${baseRef}` },
{ name: "tree-present-in-target", ok: treePresent, detail: treePresent ? `pull request #${pullRequest.number}'s merged content is present in ${baseRef}` : `pull request #${pullRequest.number}'s merged content is not present in ${baseRef}` },
{ name: "linear-done", ok: state === "Done", detail: `issue is ${state ?? "unknown"}, expected Done` },
{ name: "terminals-idle", ok: busy.length === 0, detail: busy.length ? `worker is still working: ${busy.map((terminal) => terminal.handle).join(", ")}` : `${terminals.length} terminal(s) idle` },
]
Expand Down
56 changes: 52 additions & 4 deletions tools/test-tools.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2414,25 +2414,47 @@ const workerWatchCases = () => {
}

/** A linked child checkout is the smallest real Git fixture that can prove teardown verification. */
const stageTeardownWorktree = (label, { dirty = false, changed = false, squashMerged = false, siblingTargetAdvance = false, branchDeleteMode } = {}) => {
const stageTeardownWorktree = (label, { dirty = false, changed = false, squashMerged = false, fastForwardMerged = false, serverMerged = false, localFollowUp = false, siblingTargetAdvance = false, branchDeleteMode } = {}) => {
const primary = join(root, "teardown", label, "primary")
const child = join(root, "teardown", label, "child")
const remote = join(root, "teardown", label, "remote.git")
mkdirSync(primary, { recursive: true })
const git = (cwd, args) => spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8" })
for (const args of [["init", "-q", "--initial-branch=main"], ["config", "user.email", "gate@orbit.test"], ["config", "user.name", "Orbit Gate"], ["commit", "-q", "--allow-empty", "-m", "base"], ["worktree", "add", "-q", "-b", "feature/orb-124-teardown", child]]) {
if (git(primary, ["init", "-q", "--bare", remote]).status !== 0) return null
for (const args of [["init", "-q", "--initial-branch=main"], ["config", "user.email", "gate@orbit.test"], ["config", "user.name", "Orbit Gate"], ["commit", "-q", "--allow-empty", "-m", "base"], ["remote", "add", "origin", remote], ["push", "-q", "-u", "origin", "main"], ["worktree", "add", "-q", "-b", "feature/orb-124-teardown", child]]) {
if (git(primary, args).status !== 0) return null
}
let mergeCommit
if (changed) {
writeFileSync(join(child, "captured.txt"), "not in main\n")
if (git(child, ["add", "captured.txt"]).status !== 0 || git(child, ["commit", "-q", "-m", "captured work"]).status !== 0) return null
if (git(child, ["push", "-q", "-u", "origin", "feature/orb-124-teardown"]).status !== 0) return null
if (squashMerged) {
writeFileSync(join(primary, "captured.txt"), "not in main\n")
if (git(primary, ["add", "captured.txt"]).status !== 0 || git(primary, ["commit", "-q", "-m", "squashed capture"]).status !== 0) return null
}
if (fastForwardMerged) {
if (git(primary, ["merge", "--ff-only", "feature/orb-124-teardown"]).status !== 0) return null
mergeCommit = git(primary, ["rev-parse", "HEAD"]).stdout.trim()
}
if (serverMerged) {
if (git(primary, ["merge", "--no-ff", "-m", "server merge", "feature/orb-124-teardown"]).status !== 0) return null
mergeCommit = git(primary, ["rev-parse", "HEAD"]).stdout.trim()
}
if (serverMerged) {
writeFileSync(join(primary, "captured.txt"), "resolved on forge\n")
if (git(primary, ["add", "captured.txt"]).status !== 0 || git(primary, ["commit", "-q", "-m", "server resolution"]).status !== 0) return null
}
if (siblingTargetAdvance) {
writeFileSync(join(primary, "sibling-ticket.txt"), "already in main\n")
if (git(primary, ["add", "sibling-ticket.txt"]).status !== 0 || git(primary, ["commit", "-q", "-m", "sibling ticket"]).status !== 0) return null
}
if ((squashMerged || fastForwardMerged || serverMerged || siblingTargetAdvance) && git(primary, ["push", "-q", "origin", "main"]).status !== 0) return null
}
const headCommit = git(child, ["rev-parse", "HEAD"]).stdout.trim()
if (localFollowUp) {
writeFileSync(join(child, "follow-up.txt"), "must not be removed\n")
if (git(child, ["add", "follow-up.txt"]).status !== 0 || git(child, ["commit", "-q", "-m", "local follow-up"]).status !== 0) return null
}
if (dirty) writeFileSync(join(child, "dirty.txt"), "uncommitted\n")
if (branchDeleteMode) {
Expand All @@ -2445,7 +2467,7 @@ const stageTeardownWorktree = (label, { dirty = false, changed = false, squashMe
writeFileSync(hook, body)
chmodSync(hook, 0o755)
}
return { primary, child, branch: "feature/orb-124-teardown" }
return { primary, child, branch: "feature/orb-124-teardown", headCommit, mergeCommit: mergeCommit ?? git(primary, ["rev-parse", "HEAD"]).stdout.trim() }
}

const stageWorkerStatusWorktree = () => {
Expand Down Expand Up @@ -2628,10 +2650,13 @@ const teardownWorktreeRecord = (fixture) => ({
baseRef: "main",
})

const teardownPlan = (fixture, { state = "Done", terminals = [], removePath, removal = JSON.stringify({ ok: true, result: {} }), removalExit = 0 } = {}) => [
const mergedPullRequest = (fixture, number = 124) => ({ number, mergedAt: "2026-07-28T12:00:00Z", mergeCommit: { oid: fixture.mergeCommit }, headRefOid: fixture.headCommit })

const teardownPlan = (fixture, { state = "Done", terminals = [], pullRequest = mergedPullRequest(fixture), pullRequestExit = 0, removePath, removal = JSON.stringify({ ok: true, result: {} }), removalExit = 0 } = {}) => [
{ match: "worktree list", stdout: JSON.stringify({ ok: true, result: { worktrees: [teardownWorktreeRecord(fixture)] } }) },
{ match: "terminal list", stdout: JSON.stringify({ ok: true, result: { terminals } }) },
{ match: "linear issue ORB-124", stdout: JSON.stringify({ ok: true, result: { issue: { identifier: "ORB-124", state: { name: state } } } }) },
{ match: "pr list", stdout: JSON.stringify(pullRequest ? [pullRequest] : []), exit: pullRequestExit },
{ match: "terminal stop", stdout: JSON.stringify({ ok: true, result: {} }) },
{ match: "worktree rm", stdout: removal, exit: removalExit, ...(removePath ? { removePath } : {}) },
]
Expand Down Expand Up @@ -2716,6 +2741,29 @@ const teardownWorktreeCases = () => {
const unmerged = stageTeardownWorktree("unmerged", { changed: true })
check("teardown-worktree.mjs", "content absent from the target branch is refused", ["--issue", "ORB-124"], { status: 1, stderr: /tree-present-in-target/ }, { env: orcaEnv(teardownPlan(unmerged, { removePath: unmerged.child })) })

const missingTarget = stageTeardownWorktree("missing-target", { changed: true })
check("teardown-worktree.mjs", "a merged pull request whose content is absent from the target keeps the refusal message", ["--issue", "ORB-124"], { status: 1, stderr: /UNMET tree-present-in-target: pull request #124's merged content is not present/ }, { env: orcaEnv(teardownPlan(missingTarget)) })

const lookupFailure = stageTeardownWorktree("lookup-failure")
check("teardown-worktree.mjs", "a nonzero merged-commit lookup refuses instead of removing", ["--issue", "ORB-124"], { status: 3, stderr: /gh pr list for feature\/orb-124-teardown failed/ }, { env: orcaEnv(teardownPlan(lookupFailure, { pullRequest: null, pullRequestExit: 1, removePath: lookupFailure.child })) })

const notMerged = stageTeardownWorktree("not-merged")
check("teardown-worktree.mjs", "an unmerged pull request is refused", ["--issue", "ORB-124"], { status: 1, stderr: /not a merged pull request with merge and head commits/ }, { env: orcaEnv(teardownPlan(notMerged, { pullRequest: null, removePath: notMerged.child })) })

const ownLocalMerged = stageTeardownWorktree("own-local-merged", { changed: true, fastForwardMerged: true })
check("teardown-worktree.mjs", "a pull request merged from the worker's own local commit tears down", ["--issue", "ORB-124"], { status: 0, stdout: /REMOVED worktree/ }, { env: orcaEnv(teardownPlan(ownLocalMerged, { removePath: ownLocalMerged.child })) })

const serverSideMerge = stageTeardownWorktree("server-side-merge", { changed: true, serverMerged: true })
check("teardown-worktree.mjs", "a server-side merged commit absent from the local branch tears down", ["--issue", "ORB-124"], { status: 0, stdout: /REMOVED worktree/ }, { env: orcaEnv(teardownPlan(serverSideMerge, { removePath: serverSideMerge.child })) })

const localFollowUp = stageTeardownWorktree("local-follow-up", { changed: true, serverMerged: true, localFollowUp: true })
check("teardown-worktree.mjs", "a local follow-up after the merged pull request is refused", ["--issue", "ORB-124"], { status: 1, stderr: /tree-present-in-target/ }, { env: orcaEnv(teardownPlan(localFollowUp)) })

for (const [issue, commit] of [["ORB-106", "f2e02ca6"], ["ORB-129", "c04e3716"]]) {
const replay = stageTeardownWorktree(`recorded-${issue.toLowerCase()}`, { changed: true, serverMerged: true })
check("teardown-worktree.mjs", `recorded ${issue} refusal at ${commit} replays as a teardown`, ["--issue", "ORB-124"], { status: 0, stdout: /REMOVED worktree/ }, { env: orcaEnv(teardownPlan(replay, { removePath: replay.child })) })
}

const notDone = stageTeardownWorktree("not-done")
check("teardown-worktree.mjs", "a closed-looking but non-Done Linear issue is refused", ["--issue", "ORB-124"], { status: 1, stderr: /linear-done[\s\S]*In Review/ }, { env: orcaEnv(teardownPlan(notDone, { state: "In Review", removePath: notDone.child })) })

Expand Down
Loading