Skip to content

Commit b308420

Browse files
committed
fix(process): preserve safe mixed-stream diagnostics
1 parent b053fa9 commit b308420

5 files changed

Lines changed: 150 additions & 107 deletions

File tree

‎src/agents/worktrees/service.diagnostics.test.ts‎

Lines changed: 26 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -110,47 +110,32 @@ describe("ManagedWorktreeService failure diagnostics", () => {
110110
return script;
111111
}
112112

113-
it.each([
114-
{
115-
name: "mixed",
116-
stdout: "fatal: create local-fixture-input.txt and retry",
117-
stderr: "warning: optional fixture hint is unset",
118-
},
119-
{ name: "stdout-only", stdout: "fatal: create local-fixture-input.txt and retry", stderr: "" },
120-
{ name: "stderr-only", stdout: "", stderr: "fatal: create local-fixture-input.txt and retry" },
121-
])(
122-
"reports actual $name setup output without losing diagnostics or cleanup",
123-
async ({ stdout, stderr }) => {
124-
const script = await writeFailingSetup();
125-
await fs.writeFile(
126-
script,
127-
[
128-
"#!/bin/sh",
129-
'printf "%s\\n" "$OPENCLAW_WORKTREE_PATH" > "$OPENCLAW_SOURCE_TREE_PATH/setup-path.txt"',
130-
`printf '%s\\n' '${stdout}'`,
131-
`printf '%s\\n' '${stderr}' >&2`,
132-
"exit 23",
133-
"",
134-
].join("\n"),
135-
);
136-
const message = await failureMessage(
137-
service.create({ repoRoot: repo, name: "actual-failed-setup", baseRef: "HEAD" }),
138-
);
139-
const allocated = (await fs.readFile(path.join(repo, "setup-path.txt"), "utf8")).trim();
140-
await expect(fs.stat(allocated)).rejects.toMatchObject({ code: "ENOENT" });
141-
expect(await git(repo, "worktree", "list", "--porcelain")).not.toContain(
142-
"actual-failed-setup",
143-
);
144-
expect(await git(repo, "branch", "--list", "openclaw/actual-failed-setup")).toBe("");
145-
expect(service.listRegistryRecords()).toEqual([]);
146-
expect(message).toContain("worktree setup failed (exit code 23)");
147-
expect(message).toContain("create local-fixture-input.txt and retry");
148-
if (stdout && stderr) {
149-
expect(message).toContain("optional fixture hint is unset");
150-
}
151-
expect(message.length).toBeLessThanOrEqual(2_300);
152-
},
153-
);
113+
it("reports actual mixed setup output without losing diagnostics or cleanup", async () => {
114+
const script = await writeFailingSetup();
115+
await fs.writeFile(
116+
script,
117+
[
118+
"#!/bin/sh",
119+
'printf "%s\\n" "$OPENCLAW_WORKTREE_PATH" > "$OPENCLAW_SOURCE_TREE_PATH/setup-path.txt"',
120+
"printf '%s\\n' 'fatal: create local-fixture-input.txt and retry'",
121+
"printf '%s\\n' 'warning: optional fixture hint is unset' >&2",
122+
"exit 23",
123+
"",
124+
].join("\n"),
125+
);
126+
const message = await failureMessage(
127+
service.create({ repoRoot: repo, name: "actual-failed-setup", baseRef: "HEAD" }),
128+
);
129+
const allocated = (await fs.readFile(path.join(repo, "setup-path.txt"), "utf8")).trim();
130+
await expect(fs.stat(allocated)).rejects.toMatchObject({ code: "ENOENT" });
131+
expect(await git(repo, "worktree", "list", "--porcelain")).not.toContain("actual-failed-setup");
132+
expect(await git(repo, "branch", "--list", "openclaw/actual-failed-setup")).toBe("");
133+
expect(service.listRegistryRecords()).toEqual([]);
134+
expect(message).toContain("worktree setup failed (exit code 23)");
135+
expect(message).toContain("create local-fixture-input.txt and retry");
136+
expect(message).toContain("optional fixture hint is unset");
137+
expect(message.length).toBeLessThanOrEqual(2_300);
138+
});
154139

155140
it.each(terminationCases)("reports setup $name and removes its allocation", async (entry) => {
156141
const script = await writeFailingSetup();

‎src/infra/git-exec.test.ts‎

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -150,22 +150,15 @@ describe.each([
150150
});
151151

152152
describe("successful Git output", () => {
153-
it("preserves raw and trimmed text while forwarding execution options", async () => {
153+
it("keeps raw text byte-for-byte and preserves the trimmed text contract", async () => {
154154
const stdout = " \u001b[31mname\u001b[0m\rredraw\0\r\n ";
155-
const options = {
156-
env: { LC_ALL: "C" },
157-
input: "fixture stdin",
158-
timeoutMs: 300_000,
159-
signal: new AbortController().signal,
160-
};
161-
const commandSpy = vi.spyOn(processExec, "runCommandWithTimeout").mockResolvedValue({
155+
vi.spyOn(processExec, "runCommandWithTimeout").mockResolvedValue({
162156
...failure,
163157
code: 0,
164158
stdout,
165159
});
166-
await expect(requireGitCommandRaw("/repo", ["status"], options)).resolves.toBe(stdout);
167-
await expect(requireGitCommand("/repo", ["status"], options)).resolves.toBe(stdout.trim());
168-
expect(commandSpy.mock.calls.map(([, applied]) => applied)).toEqual([options, options]);
160+
await expect(requireGitCommandRaw("/repo", ["status"])).resolves.toBe(stdout);
161+
await expect(requireGitCommand("/repo", ["status"])).resolves.toBe(stdout.trim());
169162
});
170163

171164
it("keeps binary output including invalid UTF-8 and terminal control bytes", async () => {

‎src/infra/git-exec.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
import { createCommandError } from "../process/command-error.js";
22
import type { SpawnResult } from "../process/exec-result.js";
3-
import type { CommandOptions } from "../process/exec-runner.js";
43
import { runCommandBuffered, runCommandWithTimeout } from "../process/exec.js";
54

65
export const GIT_TIMEOUT_MS = 120_000;
76

87
export async function executeGitCommand(
98
cwd: string,
109
args: string[],
11-
options: Pick<CommandOptions, "env" | "input" | "timeoutMs" | "signal"> = {},
10+
options: {
11+
env?: NodeJS.ProcessEnv;
12+
input?: string | Uint8Array;
13+
timeoutMs?: number;
14+
signal?: AbortSignal;
15+
} = {},
1216
): Promise<SpawnResult & { timeoutMs: number }> {
1317
const timeoutMs = options.timeoutMs ?? GIT_TIMEOUT_MS;
1418
const result = await runCommandWithTimeout(["git", "-C", cwd, ...args], {
@@ -37,15 +41,19 @@ export function createGitCommandError(
3741
export async function requireGitCommand(
3842
cwd: string,
3943
args: string[],
40-
options: Parameters<typeof executeGitCommand>[2] = {},
44+
options: { env?: NodeJS.ProcessEnv; input?: string | Uint8Array; timeoutMs?: number } = {},
4145
): Promise<string> {
42-
return (await requireGitCommandRaw(cwd, args, options)).trim();
46+
const result = await executeGitCommand(cwd, args, options);
47+
if (result.code !== 0) {
48+
throw createGitCommandError(`git ${args.join(" ")}`, result);
49+
}
50+
return result.stdout.trim();
4351
}
4452

4553
export async function requireGitCommandRaw(
4654
cwd: string,
4755
args: string[],
48-
options: Parameters<typeof executeGitCommand>[2] = {},
56+
options: { env?: NodeJS.ProcessEnv; input?: string | Uint8Array } = {},
4957
): Promise<string> {
5058
const result = await executeGitCommand(cwd, args, options);
5159
if (result.code !== 0) {

‎src/process/command-error.test.ts‎

Lines changed: 46 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from "vitest";
2-
import { createCommandError, formatCommandResult } from "./command-error.js";
2+
import { createCommandError } from "./command-error.js";
33
import type { SpawnResult } from "./exec-result.js";
44

55
const failure: SpawnResult = {
@@ -57,9 +57,47 @@ it.each([false, true])("retains both diagnostics when outputs are buffers: %s",
5757
expect(error.message).toContain("exit code 23");
5858
expect(error.message).toContain("create local-fixture-input.txt and retry");
5959
expect(error.message).toContain("optional fixture hint is unset");
60+
expect(error.message).toContain("stderr:");
61+
expect(error.message).toContain("stdout:");
6062
expect(error.message).not.toContain("timed out");
6163
});
6264

65+
it("retains complete uneven streams when they fit within the shared budget", () => {
66+
const stdout = `recovery instruction: ${"x".repeat(1_200)}`;
67+
const error = createCommandError(
68+
"worktree setup",
69+
{
70+
...failure,
71+
code: 23,
72+
killed: false,
73+
termination: "exit",
74+
stdout,
75+
stderr: "warning",
76+
},
77+
{ timeoutMs: 120_000 },
78+
);
79+
const detail = error.message.slice(error.message.indexOf(":\n") + 2);
80+
expect(detail).toBe(`stderr: warning\nstdout: ${stdout}`);
81+
expect(detail).not.toContain("…");
82+
});
83+
84+
it("sanitizes terminal controls without flattening logical lines", () => {
85+
const error = createCommandError(
86+
"worktree setup",
87+
{
88+
...failure,
89+
code: 23,
90+
killed: false,
91+
termination: "exit",
92+
stdout: "recovery",
93+
stderr: "\u001b[31mstale\rfinal\tfield\u0007\u007f\u0085\nnext\u001b[0m",
94+
},
95+
{ timeoutMs: 120_000 },
96+
);
97+
const detail = error.message.slice(error.message.indexOf(":\n") + 2);
98+
expect(detail).toBe("stderr: final\\tfield\nnext\nstdout: recovery");
99+
});
100+
63101
it("keeps independent recent stream tails within the existing error budget", () => {
64102
const error = createCommandError(
65103
"worktree setup",
@@ -77,12 +115,13 @@ it("keeps independent recent stream tails within the existing error budget", ()
77115
expect(error.message).toContain("warning detail 🦞");
78116
expect(error.message).not.toContain("old output");
79117
expect(error.message).not.toContain("old warning");
80-
expect(error.message).toContain("…");
81118
expect(error.message).toContain(":\n");
82119
const detail = error.message.slice(error.message.indexOf(":\n") + 2);
83-
expect(detail.length).toBeLessThanOrEqual(2002);
84-
// Same observable envelope bound as maintained worktree diagnostics; this
85-
// rejects giving both streams the former full 2000-character allocation.
120+
expect(detail).toMatch(/^stderr: …\n/u);
121+
expect(detail).toContain("\nstdout: …\n");
122+
expect(detail.length).toBeLessThanOrEqual(2_000);
123+
expect(detail).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/u);
124+
expect(detail).not.toMatch(/(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u);
86125
expect(error.message.length).toBeLessThan(2300);
87126
});
88127

@@ -103,24 +142,7 @@ it.each([
103142
},
104143
{ timeoutMs: 120_000 },
105144
);
106-
expect(error.message).toContain(present);
145+
const detail = error.message.slice(error.message.indexOf(":\n") + 2);
146+
expect(detail).toBe(present);
107147
expect(error.message).toContain("exit code 23");
108148
});
109-
110-
it.each(["stdout", "stderr"] as const)(
111-
"does not widen the result %s cap for a single stream",
112-
(stream) => {
113-
const result = formatCommandResult("command", {
114-
...failure,
115-
code: 23,
116-
killed: false,
117-
termination: "exit",
118-
stdout: "",
119-
stderr: "",
120-
[stream]: "x".repeat(1600),
121-
});
122-
expect(result).toContain(`${stream}:`);
123-
expect(result).not.toContain("x".repeat(801));
124-
expect(result).toContain("…");
125-
},
126-
);

‎src/process/command-error.ts‎

Lines changed: 61 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,90 @@
11
import { sliceUtf16Safe, truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
22
import { sanitizeForLog, stripAnsi } from "../../packages/terminal-core/src/ansi.js";
3+
import { sanitizeTerminalText } from "../../packages/terminal-core/src/safe-text.js";
34
import type { SpawnResult } from "./exec-result.js";
45
import type { runCommandBuffered } from "./exec.js";
56

6-
function formatCommandOutputs(outputs: (string | Buffer)[], maxChars: number, shared = false) {
7-
// CR redraws replace the current progress frame; keep its final visible content.
8-
const normalized = outputs.map((output) =>
9-
stripAnsi(output.toString())
10-
.replace(/\r\n/g, "\n")
11-
.split("\n")
12-
.map((line) => line.replace(/\r+$/, "").split("\r").at(-1) ?? "")
13-
.join("\n")
14-
.trim(),
15-
);
16-
// Extra streams reserve their newline and omission marker inside the existing bound.
17-
const count = shared ? Math.max(1, normalized.filter(Boolean).length) : 1;
18-
const limit = shared ? Math.floor((maxChars - 3 * (count - 1)) / count) : maxChars;
19-
return normalized.map((output) => {
7+
function normalizeCommandOutput(output: string | Buffer): string {
8+
const visible = stripAnsi(output.toString())
9+
.replace(/\r\n/g, "\n")
10+
.split("\n")
11+
.map((line) => line.replace(/\r+$/, "").split("\r").at(-1) ?? "")
12+
.join("\n")
13+
.trim();
14+
return visible
15+
.split("\n")
16+
.map((line) => sanitizeTerminalText(line))
17+
.join("\n");
18+
}
19+
20+
function renderCommandOutputTail(output: string, maxChars: number, markerChars = 0): string {
21+
const tail = output.split("\n").slice(-12).join("\n");
22+
if (tail.length === output.length && tail.length <= maxChars) {
23+
return tail;
24+
}
25+
const contentLimit = Math.max(0, Math.floor(maxChars)) - markerChars;
26+
return contentLimit < 0
27+
? ""
28+
: `…\n${contentLimit > 0 ? sliceUtf16Safe(tail, -contentLimit) : ""}`;
29+
}
30+
31+
function formatCommandErrorDetail(stderr: string | Buffer, stdout: string | Buffer): string {
32+
const streams = [normalizeCommandOutput(stderr), normalizeCommandOutput(stdout)];
33+
const visible = streams.filter(Boolean);
34+
if (visible.length < 2) {
35+
return visible[0] ? renderCommandOutputTail(visible[0], 2_000) : "";
36+
}
37+
38+
const bodyBudget = 2_000 - "stderr: \nstdout: ".length;
39+
const demands = streams.map((output) => {
2040
const tail = output.split("\n").slice(-12).join("\n");
21-
const omitted = tail.length < output.length || tail.length > limit;
22-
return `${omitted ? "…\n" : ""}${sliceUtf16Safe(tail, -limit)}`;
41+
return tail.length + (tail.length < output.length ? 2 : 0);
2342
});
43+
let allocations = [...demands];
44+
if (demands[0]! + demands[1]! > bodyBudget) {
45+
allocations = demands.map((demand) => Math.min(demand, Math.floor(bodyBudget / 2)));
46+
const remaining = bodyBudget - allocations[0]! - allocations[1]!;
47+
const stderrUnmet = demands[0]! - allocations[0]!;
48+
const stdoutUnmet = demands[1]! - allocations[1]!;
49+
const index = stderrUnmet >= stdoutUnmet ? 0 : 1;
50+
allocations[index] = allocations[index]! + remaining;
51+
}
52+
return `stderr: ${renderCommandOutputTail(
53+
streams[0]!,
54+
Math.max(0, Math.floor(allocations[0]!)),
55+
2,
56+
)}\nstdout: ${renderCommandOutputTail(streams[1]!, Math.max(0, Math.floor(allocations[1]!)), 2)}`;
2457
}
2558

2659
export function formatCommandOutput(output: string | Buffer, maxChars = 800): string {
27-
return formatCommandOutputs([output], maxChars).join("");
60+
return renderCommandOutputTail(normalizeCommandOutput(output), maxChars);
2861
}
2962

30-
// Pass an operation label, never argv that may contain credentials.
63+
/** Use an operation label, never argv that may contain credentials. */
3164
export function formatCommandResult(command: string, result: SpawnResult): string {
3265
const label = truncateUtf16Safe(sanitizeForLog(command.replace(/[\r\n]+/g, " ")), 256);
3366
const termination = result.outputLimitExceeded ? "output-limit" : result.termination;
3467
const signal = result.signal ? `, signal=${result.signal}` : "";
3568
const killed = result.killed ? ", killed=true" : "";
3669
const status = result.code === 0 ? "exited" : "failed";
37-
return [
70+
const lines = [
3871
`${label} ${status} (code=${result.code}, termination=${termination}${signal}${killed})`,
39-
...formatCommandOutputs([result.stderr, result.stdout], 800).flatMap((output, index) =>
40-
output ? [`${index === 0 ? "stderr" : "stdout"}: ${output}`] : [],
41-
),
42-
].join("\n");
72+
];
73+
for (const stream of ["stderr", "stdout"] as const) {
74+
const output = formatCommandOutput(result[stream]);
75+
if (output) {
76+
lines.push(`${stream}: ${output}`);
77+
}
78+
}
79+
return lines.join("\n");
4380
}
4481

4582
export function createCommandError(
4683
command: string,
4784
result: SpawnResult | Awaited<ReturnType<typeof runCommandBuffered>>,
4885
options: { timeoutMs: number },
4986
): Error {
50-
const detail = formatCommandOutputs([result.stderr, result.stdout], 2000, true)
51-
.filter(Boolean)
52-
.join("\n");
87+
const detail = formatCommandErrorDetail(result.stderr, result.stdout);
5388
const reasons: string[] = [];
5489
if (result.termination === "timeout") {
5590
reasons.push(`timed out after ${options.timeoutMs / 1000} seconds`);

0 commit comments

Comments
 (0)