|
| 1 | +import { execFile } from "node:child_process"; |
| 2 | +import fs from "node:fs/promises"; |
| 3 | +import os from "node:os"; |
| 4 | +import path from "node:path"; |
| 5 | +import { promisify } from "node:util"; |
| 6 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 7 | +import * as commandExec from "../../process/exec.js"; |
| 8 | +import type { SpawnResult } from "../../process/exec.js"; |
| 9 | +import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db.js"; |
| 10 | +import { ManagedWorktreeService } from "./service.js"; |
| 11 | +import { initializeManagedWorktreeTestRepository } from "./service.test-support.js"; |
| 12 | + |
| 13 | +const execFileAsync = promisify(execFile); |
| 14 | +const realRunCommand = commandExec.runCommandWithTimeout; |
| 15 | +const emptyFailure: SpawnResult = { |
| 16 | + stdout: "", |
| 17 | + stderr: "", |
| 18 | + code: 73, |
| 19 | + signal: null, |
| 20 | + killed: false, |
| 21 | + termination: "exit", |
| 22 | +}; |
| 23 | + |
| 24 | +async function failureMessage(operation: Promise<unknown>): Promise<string> { |
| 25 | + try { |
| 26 | + await operation; |
| 27 | + } catch (error) { |
| 28 | + if (error instanceof Error) { |
| 29 | + return error.message; |
| 30 | + } |
| 31 | + throw error; |
| 32 | + } |
| 33 | + throw new Error("expected worktree operation to fail"); |
| 34 | +} |
| 35 | + |
| 36 | +async function git(cwd: string, ...args: string[]): Promise<string> { |
| 37 | + const { stdout } = await execFileAsync("git", ["-C", cwd, ...args]); |
| 38 | + return stdout.trim(); |
| 39 | +} |
| 40 | + |
| 41 | +const terminationCases: Array<{ |
| 42 | + name: string; |
| 43 | + result: Partial<SpawnResult>; |
| 44 | + expected: RegExp[]; |
| 45 | +}> = [ |
| 46 | + { |
| 47 | + name: "exit without output", |
| 48 | + result: { code: 23 }, |
| 49 | + expected: [/(?:exit|code|status)[^\n]*23/i], |
| 50 | + }, |
| 51 | + { |
| 52 | + name: "exit with output", |
| 53 | + result: { code: 23, stderr: "fatal: dependency unavailable" }, |
| 54 | + expected: [/fatal: dependency unavailable/, /(?:exit|code|status)[^\n]*23/i], |
| 55 | + }, |
| 56 | + { |
| 57 | + name: "timeout with output", |
| 58 | + result: { |
| 59 | + code: 124, |
| 60 | + termination: "timeout", |
| 61 | + signal: "SIGTERM", |
| 62 | + killed: true, |
| 63 | + stderr: "waiting for dependency", |
| 64 | + }, |
| 65 | + expected: [/waiting for dependency/, /timed?\s*out|timeout/i, /SIGTERM/], |
| 66 | + }, |
| 67 | + { |
| 68 | + name: "timeout without output", |
| 69 | + result: { |
| 70 | + code: 124, |
| 71 | + termination: "timeout", |
| 72 | + signal: "SIGKILL", |
| 73 | + killed: true, |
| 74 | + }, |
| 75 | + expected: [/timed?\s*out|timeout/i, /SIGKILL/], |
| 76 | + }, |
| 77 | + { |
| 78 | + name: "signal without output", |
| 79 | + result: { code: null, termination: "signal", signal: "SIGTERM" }, |
| 80 | + expected: [/SIGTERM/], |
| 81 | + }, |
| 82 | +]; |
| 83 | + |
| 84 | +describe("ManagedWorktreeService failure diagnostics", () => { |
| 85 | + let root: string; |
| 86 | + let repo: string; |
| 87 | + let service: ManagedWorktreeService; |
| 88 | + |
| 89 | + beforeEach(async () => { |
| 90 | + root = await fs.mkdtemp(path.join(await fs.realpath(os.tmpdir()), "openclaw-worktree-errors-")); |
| 91 | + repo = await initializeManagedWorktreeTestRepository(root); |
| 92 | + service = new ManagedWorktreeService({ |
| 93 | + env: { ...process.env, OPENCLAW_STATE_DIR: path.join(root, "state") }, |
| 94 | + }); |
| 95 | + }); |
| 96 | + |
| 97 | + afterEach(async () => { |
| 98 | + vi.restoreAllMocks(); |
| 99 | + closeOpenClawStateDatabaseForTest(); |
| 100 | + await fs.rm(root, { recursive: true, force: true }); |
| 101 | + }); |
| 102 | + |
| 103 | + async function writeFailingSetup(): Promise<string> { |
| 104 | + const script = path.join(repo, ".openclaw", "worktree-setup.sh"); |
| 105 | + await fs.mkdir(path.dirname(script)); |
| 106 | + await fs.writeFile(script, "#!/bin/sh\nprintf 'fatal: setup failed\\n' >&2\nexit 9\n", { |
| 107 | + mode: 0o755, |
| 108 | + }); |
| 109 | + return script; |
| 110 | + } |
| 111 | + |
| 112 | + it.each(terminationCases)("reports setup $name and removes its allocation", async (entry) => { |
| 113 | + const script = await writeFailingSetup(); |
| 114 | + vi.spyOn(commandExec, "runCommandWithTimeout").mockImplementation(async (argv, options) => { |
| 115 | + if (argv[0] === script) { |
| 116 | + return { ...emptyFailure, ...entry.result }; |
| 117 | + } |
| 118 | + return await realRunCommand(argv, options); |
| 119 | + }); |
| 120 | + |
| 121 | + const message = await failureMessage( |
| 122 | + service.create({ repoRoot: repo, name: "terminated-setup", baseRef: "HEAD" }), |
| 123 | + ); |
| 124 | + |
| 125 | + expect(await git(repo, "worktree", "list", "--porcelain")).not.toContain("terminated-setup"); |
| 126 | + expect(await git(repo, "branch", "--list", "openclaw/terminated-setup")).toBe(""); |
| 127 | + expect(service.listRegistryRecords()).toEqual([]); |
| 128 | + expect(message).toContain("worktree setup failed"); |
| 129 | + for (const pattern of entry.expected) { |
| 130 | + expect.soft(message).toMatch(pattern); |
| 131 | + } |
| 132 | + expect(message.length).toBeLessThanOrEqual(2_300); |
| 133 | + }); |
| 134 | + |
| 135 | + it.each([ |
| 136 | + { phase: "create", failedOperation: "remove" }, |
| 137 | + { phase: "create", failedOperation: "branch" }, |
| 138 | + { phase: "create", failedOperation: "both" }, |
| 139 | + { phase: "restore", failedOperation: "remove" }, |
| 140 | + { phase: "restore", failedOperation: "branch" }, |
| 141 | + { phase: "restore", failedOperation: "both" }, |
| 142 | + ] as const)( |
| 143 | + "reports the failed $failedOperation operation during $phase cleanup", |
| 144 | + async ({ phase, failedOperation }) => { |
| 145 | + const removeFails = failedOperation !== "branch"; |
| 146 | + const branchFails = failedOperation !== "remove"; |
| 147 | + const name = "cleanup-failure"; |
| 148 | + const branch = `openclaw/${name}`; |
| 149 | + let record; |
| 150 | + if (phase === "restore") { |
| 151 | + record = await service.create({ repoRoot: repo, name, baseRef: "HEAD" }); |
| 152 | + await service.remove({ id: record.id, reason: "test" }); |
| 153 | + } else { |
| 154 | + await writeFailingSetup(); |
| 155 | + } |
| 156 | + const registryBefore = service.listRegistryRecords(); |
| 157 | + const fatal = "fatal: branch deletion denied"; |
| 158 | + let cleanupPath: string | undefined; |
| 159 | + vi.spyOn(commandExec, "runCommandWithTimeout").mockImplementation(async (argv, options) => { |
| 160 | + const args = argv[0] === "git" ? argv.slice(3) : []; |
| 161 | + if (phase === "restore" && args[0] === "reset") { |
| 162 | + return { ...emptyFailure, code: 45, stderr: "fatal: restore index failed" }; |
| 163 | + } |
| 164 | + if (args[0] === "worktree" && args[1] === "remove") { |
| 165 | + cleanupPath = args.at(-1); |
| 166 | + const removed = await realRunCommand(argv, options); |
| 167 | + expect(removed.code).toBe(0); |
| 168 | + // A child can fail after applying its filesystem effects. Later branch |
| 169 | + // deletion output must not mask this removal failure. |
| 170 | + return removeFails ? emptyFailure : { ...removed, stdout: "worktree removal complete" }; |
| 171 | + } |
| 172 | + if (args[0] === "branch" && args[1] === "-D" && branchFails) { |
| 173 | + return { |
| 174 | + ...emptyFailure, |
| 175 | + stderr: `${"Deleting branch\r".repeat(200)}\n${"x".repeat(8_000)}${fatal}`, |
| 176 | + }; |
| 177 | + } |
| 178 | + return await realRunCommand(argv, options); |
| 179 | + }); |
| 180 | + |
| 181 | + const message = await failureMessage( |
| 182 | + record |
| 183 | + ? service.restore({ id: record.id }) |
| 184 | + : service.create({ repoRoot: repo, name, baseRef: "HEAD" }), |
| 185 | + ); |
| 186 | + |
| 187 | + expect(cleanupPath).toBeDefined(); |
| 188 | + await expect(fs.stat(cleanupPath!)).rejects.toMatchObject({ code: "ENOENT" }); |
| 189 | + expect(service.listRegistryRecords()).toEqual(registryBefore); |
| 190 | + expect(await git(repo, "branch", "--list", branch)).toBe(branchFails ? branch : ""); |
| 191 | + if (record) { |
| 192 | + expect(await git(repo, "show-ref", "--verify", registryBefore[0]!.snapshotRef!)).not.toBe( |
| 193 | + "", |
| 194 | + ); |
| 195 | + } |
| 196 | + expect(message).toContain( |
| 197 | + phase === "restore" ? "fatal: restore index failed" : "fatal: setup failed", |
| 198 | + ); |
| 199 | + const label = |
| 200 | + phase === "restore" ? "restore cleanup failed:" : "failed to clean up worktree creation:"; |
| 201 | + expect(message).toContain(label); |
| 202 | + const cleanupMessage = message.slice(message.indexOf(label) + label.length); |
| 203 | + expect.soft(cleanupMessage).toContain(removeFails ? "git worktree remove" : "git branch -D"); |
| 204 | + expect.soft(/(?:exit|code|status)[^\n]*73/i.test(cleanupMessage)).toBe(true); |
| 205 | + expect.soft(cleanupMessage).not.toContain("worktree removal complete"); |
| 206 | + expect.soft(cleanupMessage).not.toContain("Deleted branch"); |
| 207 | + if (!removeFails) { |
| 208 | + expect.soft(cleanupMessage.includes(fatal)).toBe(true); |
| 209 | + } else { |
| 210 | + expect.soft(cleanupMessage).not.toContain(fatal); |
| 211 | + } |
| 212 | + expect.soft(cleanupMessage.length).toBeLessThanOrEqual(2_300); |
| 213 | + }, |
| 214 | + ); |
| 215 | + |
| 216 | + it.each([ |
| 217 | + { name: "long evidence inside the existing window", oldEvidenceVisible: true }, |
| 218 | + { name: "evidence outside the existing newline window", oldEvidenceVisible: false }, |
| 219 | + ])("preserves retry authority for $name", async ({ oldEvidenceVisible }) => { |
| 220 | + await git(path.join(root, "remote.git"), "symbolic-ref", "HEAD", "refs/heads/main"); |
| 221 | + await git(repo, "remote", "set-head", "origin", "-a"); |
| 222 | + const name = "retry-evidence"; |
| 223 | + const branch = `openclaw/${name}`; |
| 224 | + let allocatedPath: string | undefined; |
| 225 | + let firstAdd = true; |
| 226 | + vi.spyOn(commandExec, "runCommandWithTimeout").mockImplementation(async (argv, options) => { |
| 227 | + const result = await realRunCommand(argv, options); |
| 228 | + const args = argv[0] === "git" ? argv.slice(3) : []; |
| 229 | + if (firstAdd && args[0] === "worktree" && args[1] === "add") { |
| 230 | + firstAdd = false; |
| 231 | + allocatedPath = args.at(-2); |
| 232 | + expect(result.code).toBe(0); |
| 233 | + const separator = oldEvidenceVisible ? "\r" : "\n"; |
| 234 | + return { |
| 235 | + ...result, |
| 236 | + code: 1, |
| 237 | + stderr: `Preparing worktree (new branch '${branch}')${separator}${`progress ${"x".repeat(200)}${separator}`.repeat(20)}fatal: checkout failed`, |
| 238 | + }; |
| 239 | + } |
| 240 | + return result; |
| 241 | + }); |
| 242 | + |
| 243 | + if (oldEvidenceVisible) { |
| 244 | + const created = await service.create({ repoRoot: repo, name }); |
| 245 | + expect(created.baseRef).toBe("HEAD"); |
| 246 | + expect(await git(created.path, "branch", "--show-current")).toBe(branch); |
| 247 | + expect(service.listRegistryRecords()).toEqual([created]); |
| 248 | + } else { |
| 249 | + await expect(service.create({ repoRoot: repo, name })).rejects.toThrow("checkout failed"); |
| 250 | + expect(service.listRegistryRecords()).toEqual([]); |
| 251 | + } |
| 252 | + expect(allocatedPath).toBeDefined(); |
| 253 | + expect(await git(repo, "worktree", "list", "--porcelain")).toContain(allocatedPath); |
| 254 | + expect(await git(allocatedPath!, "branch", "--show-current")).toBe(branch); |
| 255 | + }); |
| 256 | +}); |
0 commit comments