Skip to content

Commit 1cec40f

Browse files
thymikeeclaude
andcommitted
refactor(cli): fold the stderr writer into the CLI failure printer
writeHumanError only joined the formatter's lines and repeated the summary, behind its own options type. printHumanError in src/cli/failure-output.ts now does that directly, so a failure goes through two layers: the formatter and the CLI printer. A failed parse now takes its command from the longest argv prefix the real parser accepts, so a flag value such as `--session press` is never mistaken for the command whose synopsis Next names. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 522e171 commit 1cec40f

6 files changed

Lines changed: 66 additions & 71 deletions

File tree

‎scripts/__tests__/help-conformance-error-recovery-coverage.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ const WAIVED_GENERIC_HINT_CODES: Record<string, string> = {
3333
'Catch-all wrap of an underlying failure: the specific "what failed" lives in the message, so the generic diagnostics guidance IS its recovery step.',
3434
};
3535

36-
// Human error rendering (src/commands/output/human-error.ts writeHumanError) opens with
36+
// Human error rendering (src/cli/failure-output.ts printHumanError) opens with
3737
// `Error (CODE): message`, so any rendered error text names its own code.
3838
const RENDERED_ERROR_CODE = /(?:^|\n)Error \(([A-Z_]+)\):/g;
3939

‎scripts/__tests__/help-conformance-sample-producers.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import type { RemoteConnectionState } from '@agent-device/remote/remote-connecti
2828
import { AppError, normalizeError } from '@agent-device/kernel/errors';
2929
import type { SnapshotQualityVerdict } from '@agent-device/kernel/snapshot';
3030
import { renderSnapshotQualityWarnings } from '@agent-device/capture-kit/quality-warnings';
31-
import { writeHumanError } from '../../src/commands/output/human-error.ts';
31+
import { printHumanError } from '../../src/cli/failure-output.ts';
3232
import { captureHelpConformanceErrorRoutes } from '../../test/integration/provider-scenarios/help-conformance-error-routes.ts';
3333
import {
3434
createContractClock,
@@ -69,10 +69,10 @@ const formatPress = (result: Record<string, unknown>) => formatCommandText('pres
6969

7070
const formatFill = (result: Record<string, unknown>) => formatCommandText('fill', result);
7171

72-
/** The failure text writeHumanError writes to stderr: the summary line, any body, and the repeat. */
72+
/** The failure text the CLI writes to stderr: the summary line, any body, and the repeat. */
7373
async function renderHumanError(error: AppError): Promise<string> {
7474
const stderr = await withCapturedStderrAsync(async () => {
75-
await writeHumanError(normalizeError(error));
75+
await printHumanError(normalizeError(error));
7676
});
7777
return stderr.trimEnd();
7878
}

‎src/__tests__/cli-diagnostics.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,20 @@ test('an argument error after leading global flags still names the command synop
216216
assert.match(result.stderr, /^Error \(INVALID_ARGS\): .*Usage: agent-device press /);
217217
});
218218

219+
// The parser knows `--session` takes a value, so `press` here is the session name, not the command.
220+
test('an argument error never takes a flag value for the command', async () => {
221+
const result = await runCliCapture(
222+
['--session', 'press', 'fill', '--unknown-flag'],
223+
async () => ({
224+
ok: true,
225+
data: {},
226+
}),
227+
);
228+
assert.equal(result.code, 1);
229+
assert.match(result.stderr, /Usage: agent-device fill /);
230+
assert.equal(result.stderr.includes('Usage: agent-device press'), false);
231+
});
232+
219233
test('cli forwards save-script and no-record flags for client-backed open', async () => {
220234
const result = await runCliCapture(
221235
['open', 'settings', '--save-script', '--no-record', '--json'],
Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ import assert from 'node:assert/strict';
22
import { test } from 'vitest';
33
import { AppError } from '@agent-device/kernel/errors';
44
import { withCapturedStderrAsync } from '@agent-device/test-kit';
5-
import { writeHumanError } from './human-error.ts';
5+
import { printHumanError } from './failure-output.ts';
66

7-
test('writeHumanError writes a body-less failure as its one summary line', async () => {
7+
test('printHumanError writes a body-less failure as its one summary line', async () => {
88
const stderr = await withCapturedStderrAsync(async () => {
9-
writeHumanError(
9+
await printHumanError(
1010
new AppError('COMMAND_FAILED', 'Could not reach the app', { hint: 'Open the app first.' }),
1111
);
1212
});
@@ -18,20 +18,17 @@ test('writeHumanError writes a body-less failure as its one summary line', async
1818
});
1919

2020
// Callers merge stderr into stdout and keep `tail -1` or `head -1`; both must be the summary.
21-
test('writeHumanError closes a multi-line failure with the summary, after any trailer', async () => {
21+
test('printHumanError closes a multi-line failure with the same summary line', async () => {
2222
const stderr = await withCapturedStderrAsync(async () => {
23-
writeHumanError(
23+
await printHumanError(
2424
new AppError('COMMAND_FAILED', 'boom', { logPath: '/tmp/req.ndjson', dispatched: 'unknown' }),
25-
{ trailer: '\n[daemon log]\nlast daemon line' },
2625
);
2726
});
2827

2928
const lines = stderr.trimEnd().split('\n');
30-
assert.equal(
31-
lines[0],
29+
assert.deepEqual(lines, [
3230
'Error (COMMAND_FAILED): boom. May have reached the device. Next: Run snapshot to check the screen before you retry. Read the diagnostics log for the failing step.',
33-
);
34-
assert.equal(lines.at(-1), lines[0]);
35-
assert.ok(lines.indexOf('last daemon line') < lines.length - 1);
36-
assert.ok(lines.includes('Log: /tmp/req.ndjson'));
31+
'Log: /tmp/req.ndjson',
32+
'Error (COMMAND_FAILED): boom. May have reached the device. Next: Run snapshot to check the screen before you retry. Read the diagnostics log for the failing step.',
33+
]);
3734
});

‎src/cli/failure-output.ts‎

Lines changed: 39 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,52 @@
11
import fs from 'node:fs';
2+
import { formatHumanError } from '@agent-device/command-output';
23
import { resolveRemoteRequestDiagnosticsPath } from '@agent-device/daemon-contracts/session-artifact-paths';
3-
import type { AppError, DiagnosticsRecordRef, NormalizedError } from '@agent-device/kernel/errors';
4+
import {
5+
AppError,
6+
type DiagnosticsRecordRef,
7+
type NormalizedError,
8+
} from '@agent-device/kernel/errors';
49
import { commandSynopsis, parseRawArgs } from './parser/args.ts';
510

6-
type LogTailSource = Parameters<typeof failureLogTail>[0];
11+
/** Where the `--debug` log tail printed after a failure comes from. */
12+
export type FailureLogSource = {
13+
daemonBaseUrl: string | undefined;
14+
daemonPaths: { logPath: string; baseDir: string };
15+
record: DiagnosticsRecordRef | undefined;
16+
};
717

8-
type HumanErrorPrint = {
18+
type PrintHumanErrorOptions = {
19+
/** The `--debug`/`--verbose` tier: the raw details dump and the log tail. */
920
debugTier?: boolean;
1021
/** The command that failed; an INVALID_ARGS Next step names its synopsis. */
1122
command?: string | null;
1223
/** The raw argv of a failed parse, read for the command when `command` is unknown. */
1324
argv?: string[];
14-
/** Where the `--debug` log tail printed after the error body comes from. */
15-
logTail?: LogTailSource;
25+
logTail?: FailureLogSource;
1626
};
1727

1828
const SYNOPSIS_LIMIT = 160;
1929
const DAEMON_LOG_TAIL_MAX_BYTES = 64_000;
2030

21-
/** Writes a CLI failure to stderr through the summary-line writer. */
31+
/**
32+
* Writes a CLI failure to stderr. The summary line opens the block and, when anything follows it,
33+
* closes it too: callers that merge streams and keep only the first or the last line still read
34+
* the code, the message, the dispatch fact and the Next step.
35+
*/
2236
export async function printHumanError(
2337
err: AppError | NormalizedError,
24-
options: HumanErrorPrint = {},
38+
options: PrintHumanErrorOptions = {},
2539
): Promise<void> {
26-
const { writeHumanError } = await import('../commands/output/human-error.ts');
27-
const command = options.command ?? (options.argv ? await failedParseCommand(options.argv) : null);
40+
const command = options.command ?? (options.argv ? failedParseCommand(options.argv) : null);
2841
const synopsis =
2942
err.code === 'INVALID_ARGS' && command ? await synopsisForNextStep(command) : undefined;
43+
const { summary, body } = formatHumanError(err, { showDetails: options.debugTier, synopsis });
3044
const trailer = options.logTail ? failureLogTail(options.logTail) : undefined;
31-
writeHumanError(err, { debugTier: options.debugTier, synopsis, trailer });
45+
const lines = [summary, ...body, ...(trailer ? [trailer] : [])];
46+
if (lines.length > 1) lines.push(summary);
47+
for (const line of lines) {
48+
process.stderr.write(`${line}\n`);
49+
}
3250
}
3351

3452
async function synopsisForNextStep(command: string): Promise<string | undefined> {
@@ -38,18 +56,19 @@ async function synopsisForNextStep(command: string): Promise<string | undefined>
3856
}
3957

4058
/**
41-
* The command a failed parse was for. The parse that failed cannot say, so this takes the first
42-
* positional that names a command; a value of a leading global flag (`--platform ios`) names none.
59+
* The command a failed parse was for: the command of the longest argv prefix the real parser
60+
* accepts, so a flag value (`--session press`) is never taken for a command. `null` when no prefix
61+
* names one.
4362
*/
44-
async function failedParseCommand(argv: string[]): Promise<string | null> {
45-
try {
46-
return parseRawArgs(argv).command ?? null;
47-
} catch {
48-
for (const token of argv) {
49-
if (!token.startsWith('-') && (await commandSynopsis(token))) return token;
63+
function failedParseCommand(argv: string[]): string | null {
64+
for (let end = argv.length; end > 0; end -= 1) {
65+
try {
66+
return parseRawArgs(argv.slice(0, end)).command;
67+
} catch (error) {
68+
if (!(error instanceof AppError)) throw error;
5069
}
51-
return null;
5270
}
71+
return null;
5372
}
5473

5574
/**
@@ -61,11 +80,7 @@ async function failedParseCommand(argv: string[]): Promise<string | null> {
6180
* instead — which is what makes a CI job's transcript carry the evidence without
6281
* a second round trip (#1801).
6382
*/
64-
function failureLogTail(options: {
65-
daemonBaseUrl: string | undefined;
66-
daemonPaths: { logPath: string; baseDir: string };
67-
record: DiagnosticsRecordRef | undefined;
68-
}): string | undefined {
83+
function failureLogTail(options: FailureLogSource): string | undefined {
6984
if (!options.daemonBaseUrl) {
7085
return logFileTail('daemon log', options.daemonPaths.logPath);
7186
}

‎src/commands/output/human-error.ts‎

Lines changed: 0 additions & 31 deletions
This file was deleted.

0 commit comments

Comments
 (0)