Skip to content

Commit db5d26b

Browse files
authored
fix(utils): throw AppError from app-log-files and verified-file guards (#1853)
* fix(utils): throw AppError from app-log-files and verified-file guards The symlink, not-a-regular-file, identity-changed and identity-race guards threw plain Error, so they surfaced as UNKNOWN with a misleading hint and tests could only assert them by message. They are now COMMAND_FAILED with a recovery hint (ADR 0010); the affected tests assert through assertThrowsAppError, and the two race guards gain planted-interleaving coverage. Closes #1792 * test(utils): pin the recovery hints the AppError conversion added The tightened assertions supplied only code and message, and the helper did not look at the hint, so deleting either hint constant left every targeted test green — vacuous for the half of #1792 that ADR 0010 actually cares about. assertThrowsAppError/assertRejectsAppError now accept a hint, checked against normalizeError's view so a dropped hint surfaces as the misleading per-code default rather than passing, and each guard pins its exact text as a literal (importing the constant would compare it to itself).
1 parent 99754dc commit db5d26b

6 files changed

Lines changed: 158 additions & 59 deletions

File tree

Lines changed: 33 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,50 @@
11
import assert from 'node:assert/strict';
2-
import { AppError } from '@agent-device/kernel/errors';
2+
import { AppError, normalizeError } from '@agent-device/kernel/errors';
3+
4+
/**
5+
* What an {@link AppError} assertion may pin. `hint` is checked against the
6+
* hint a caller actually reads — `normalizeError`'s, not `details.hint` — so a
7+
* throw site that drops its hint and silently inherits `defaultHintForCode`
8+
* fails the assertion instead of passing on the default (ADR 0010: a hint is
9+
* required wherever the per-code default would mislead).
10+
*/
11+
type ExpectedAppError = { code: string; message?: RegExp; hint?: string | RegExp };
12+
13+
function assertAppError(error: unknown, expected: ExpectedAppError): true {
14+
assert.ok(
15+
error instanceof AppError,
16+
`expected AppError, got ${error?.constructor?.name ?? typeof error}: ${String(error)}`,
17+
);
18+
assert.equal(error.code, expected.code);
19+
if (expected.message) assert.match(error.message, expected.message);
20+
if (expected.hint !== undefined) {
21+
const { hint } = normalizeError(error);
22+
assert.ok(typeof hint === 'string', `expected a hint on ${error.code}, got ${String(hint)}`);
23+
if (typeof expected.hint === 'string') assert.equal(hint, expected.hint);
24+
else assert.match(hint, expected.hint);
25+
}
26+
return true;
27+
}
328

429
/**
530
* Asserts that `run` rejects with an {@link AppError} carrying `code` and,
6-
* when given, a message matching `message`. Replaces the hand-rolled
31+
* when given, a message matching `message` and the exact `hint` a caller
32+
* reads. Replaces the hand-rolled
733
* `assert.rejects(..., error instanceof AppError + code + match)` validator
834
* repeated across platform tests.
935
*/
1036
export async function assertRejectsAppError(
1137
run: () => Promise<unknown>,
12-
expected: { code: string; message?: RegExp },
38+
expected: ExpectedAppError,
1339
): Promise<void> {
14-
await assert.rejects(run, (error: unknown) => {
15-
assert.ok(
16-
error instanceof AppError,
17-
`expected AppError, got ${error?.constructor?.name ?? typeof error}: ${String(error)}`,
18-
);
19-
assert.equal(error.code, expected.code);
20-
if (expected.message) assert.match(error.message, expected.message);
21-
return true;
22-
});
40+
await assert.rejects(run, (error: unknown) => assertAppError(error, expected));
2341
}
2442

2543
/**
2644
* Synchronous sibling of {@link assertRejectsAppError}: asserts that `fn`
2745
* throws an {@link AppError} carrying `code` and, when given, a message
28-
* matching `message`.
46+
* matching `message` and the exact `hint`.
2947
*/
30-
export function assertThrowsAppError(
31-
fn: () => unknown,
32-
expected: { code: string; message?: RegExp },
33-
): void {
34-
assert.throws(fn, (error: unknown) => {
35-
assert.ok(
36-
error instanceof AppError,
37-
`expected AppError, got ${error?.constructor?.name ?? typeof error}: ${String(error)}`,
38-
);
39-
assert.equal(error.code, expected.code);
40-
if (expected.message) assert.match(error.message, expected.message);
41-
return true;
42-
});
48+
export function assertThrowsAppError(fn: () => unknown, expected: ExpectedAppError): void {
49+
assert.throws(fn, (error: unknown) => assertAppError(error, expected));
4350
}

‎src/daemon/__tests__/app-log.test.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
import fs from 'node:fs';
22
import path from 'node:path';
33
import { expect, test } from 'vitest';
4+
import { assertThrowsAppError } from '../../__tests__/test-utils/index.ts';
45
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
56
import { appendAppLogMarker, clearAppLogFiles, getAppLogPathMetadata } from '../app-log.ts';
67

8+
// Pinned as a literal on purpose — see the note in src/utils/__tests__/verified-file.test.ts.
9+
const NOT_REGULAR_FILE_HINT =
10+
'agent-device only reads and writes regular files at this path. Remove the symbolic link or special file there and retry.';
11+
712
test('marker and clear operations keep app-log file ownership in the daemon', () => {
813
const root = mkdtempForTestSync('agent-device-app-log-files-');
914
const outPath = path.join(root, 'session', 'app.log');
@@ -37,11 +42,14 @@ test.each(['metadata', 'mark', 'clear'] as const)(
3742
// whose identity check reports the path as simply not a regular file.
3843
const expectedMessage =
3944
operation === 'mark' ? /must not be a symbolic link/ : /must be a regular file/;
40-
expect(() => {
41-
if (operation === 'metadata') getAppLogPathMetadata(outPath);
42-
else if (operation === 'mark') appendAppLogMarker(outPath, 'checkpoint');
43-
else clearAppLogFiles(outPath);
44-
}).toThrow(expectedMessage);
45+
assertThrowsAppError(
46+
() => {
47+
if (operation === 'metadata') getAppLogPathMetadata(outPath);
48+
else if (operation === 'mark') appendAppLogMarker(outPath, 'checkpoint');
49+
else clearAppLogFiles(outPath);
50+
},
51+
{ code: 'COMMAND_FAILED', message: expectedMessage, hint: NOT_REGULAR_FILE_HINT },
52+
);
4553
expect(fs.readFileSync(outsidePath, 'utf8')).toBe('outside');
4654
expect(fs.lstatSync(outPath).isSymbolicLink()).toBe(true);
4755
},

‎src/utils/__tests__/app-log-files.test.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
import fs from 'node:fs';
22
import path from 'node:path';
33
import { expect, test } from 'vitest';
4+
import { assertThrowsAppError } from '../../__tests__/test-utils/index.ts';
45
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
56
import { ensureAppLogPath, rotateAppLogIfNeeded } from '../app-log-files.ts';
67

8+
// Pinned as a literal on purpose — see the note in verified-file.test.ts.
9+
const NOT_REGULAR_FILE_HINT =
10+
'agent-device only reads and writes regular files at this path. Remove the symbolic link or special file there and retry.';
11+
712
test('rotateAppLogIfNeeded rotates files and discards the oldest generation', () => {
813
const root = mkdtempForTestSync('agent-device-app-log-rotate-');
914
const outPath = path.join(root, 'app.log');
@@ -39,9 +44,11 @@ test('rotation rejects a final app.log symlink without touching its target', ()
3944
fs.writeFileSync(outsidePath, 'outside');
4045
fs.symlinkSync(outsidePath, outPath);
4146

42-
expect(() => rotateAppLogIfNeeded(outPath, { maxBytes: 1, maxRotatedFiles: 1 })).toThrow(
43-
'symbolic link',
44-
);
47+
assertThrowsAppError(() => rotateAppLogIfNeeded(outPath, { maxBytes: 1, maxRotatedFiles: 1 }), {
48+
code: 'COMMAND_FAILED',
49+
message: /must not be a symbolic link/,
50+
hint: NOT_REGULAR_FILE_HINT,
51+
});
4552
expect(fs.readFileSync(outsidePath, 'utf8')).toBe('outside');
4653
expect(fs.lstatSync(outPath).isSymbolicLink()).toBe(true);
4754
});

‎src/utils/__tests__/verified-file.test.ts‎

Lines changed: 61 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,16 @@
11
import fs from 'node:fs';
22
import os from 'node:os';
33
import path from 'node:path';
4-
import { afterEach, expect, test } from 'vitest';
4+
import { afterEach, expect, test, vi } from 'vitest';
5+
import { assertThrowsAppError } from '../../__tests__/test-utils/index.ts';
6+
7+
// The recovery hints are pinned as literals, not imported from the module under test: an
8+
// assertion that compares the constant to itself stays green when the constant is deleted or
9+
// reworded, which is the whole behaviour #1792 adds (ADR 0010 — errors say how to recover).
10+
const NOT_REGULAR_FILE_HINT =
11+
'agent-device only reads and writes regular files at this path. Remove the symbolic link or special file there and retry.';
12+
const CONCURRENT_REPLACEMENT_HINT =
13+
'Another process replaced the file at this path while it was being opened. Stop the concurrent writer, then retry.';
514
import {
615
openVerifiedFileForAppend,
716
openVerifiedFileForRead,
@@ -11,6 +20,7 @@ import {
1120
const roots: string[] = [];
1221

1322
afterEach(() => {
23+
vi.restoreAllMocks();
1424
for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
1525
});
1626

@@ -39,19 +49,60 @@ test.each(['read', 'append', 'truncate'] as const)(
3949
fs.writeFileSync(outside, 'outside');
4050
fs.symlinkSync(outside, pathname);
4151

42-
expect(() => {
43-
const descriptor =
44-
operation === 'read'
45-
? openVerifiedFileForRead(pathname)
46-
: operation === 'append'
47-
? openVerifiedFileForAppend(pathname)
48-
: openVerifiedFileForTruncate(pathname);
49-
if (descriptor !== undefined) fs.closeSync(descriptor);
50-
}).toThrow('regular file');
52+
assertThrowsAppError(
53+
() => {
54+
const descriptor =
55+
operation === 'read'
56+
? openVerifiedFileForRead(pathname)
57+
: operation === 'append'
58+
? openVerifiedFileForAppend(pathname)
59+
: openVerifiedFileForTruncate(pathname);
60+
if (descriptor !== undefined) fs.closeSync(descriptor);
61+
},
62+
{ code: 'COMMAND_FAILED', message: /must be a regular file/, hint: NOT_REGULAR_FILE_HINT },
63+
);
5164
expect(fs.readFileSync(outside, 'utf8')).toBe('outside');
5265
},
5366
);
5467

68+
// The two race guards cannot be reached from the filesystem alone, so the interleaving is
69+
// planted: the path is swapped between the open and its post-open lstat, or the create keeps
70+
// losing to a concurrent creator. Both must surface as typed failures with a recovery hint.
71+
test('reports a typed failure when the file is swapped while it is being opened', () => {
72+
const pathname = fixturePath('swapped');
73+
const other = `${pathname}.other`;
74+
fs.writeFileSync(pathname, 'first');
75+
fs.writeFileSync(other, 'second');
76+
const realLstat = fs.lstatSync;
77+
let lstatCalls = 0;
78+
vi.spyOn(fs, 'lstatSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {
79+
lstatCalls += 1;
80+
// The second lstat is the post-open identity check; answer it with the other file.
81+
const resolved = lstatCalls === 2 ? other : target;
82+
return (realLstat as (path: fs.PathLike, options?: unknown) => fs.Stats)(resolved, options);
83+
}) as typeof fs.lstatSync);
84+
85+
assertThrowsAppError(() => openVerifiedFileForRead(pathname), {
86+
code: 'COMMAND_FAILED',
87+
message: /identity changed while it was opened/,
88+
hint: CONCURRENT_REPLACEMENT_HINT,
89+
});
90+
});
91+
92+
test('reports a typed failure when a create keeps losing the identity race', () => {
93+
const pathname = fixturePath('contended');
94+
const eexist = Object.assign(new Error('EEXIST: file already exists'), { code: 'EEXIST' });
95+
vi.spyOn(fs, 'openSync').mockImplementation(() => {
96+
throw eexist;
97+
});
98+
99+
assertThrowsAppError(() => openVerifiedFileForAppend(pathname), {
100+
code: 'COMMAND_FAILED',
101+
message: /could not be opened without an identity race/,
102+
hint: CONCURRENT_REPLACEMENT_HINT,
103+
});
104+
});
105+
55106
test('returns absent for a missing read without creating the file', () => {
56107
const pathname = fixturePath('missing');
57108
expect(openVerifiedFileForRead(pathname)).toBeUndefined();

‎src/utils/app-log-files.ts‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import fs from 'node:fs';
22
import path from 'node:path';
3+
import { AppError } from '@agent-device/kernel/errors';
4+
import { lstatIfPresent, NOT_REGULAR_FILE_HINT } from './verified-file.ts';
35

46
const DEFAULT_MAX_APP_LOG_BYTES = 5 * 1024 * 1024;
57
const DEFAULT_MAX_ROTATED_FILES = 1;
@@ -37,16 +39,13 @@ function assertAppLogFileIsNotSymbolicLink(outPath: string): void {
3739
}
3840

3941
function lstatAppLogFile(outPath: string): fs.Stats | undefined {
40-
try {
41-
const stats = fs.lstatSync(outPath);
42-
if (stats.isSymbolicLink()) {
43-
throw new Error(`App-log file must not be a symbolic link: ${outPath}`);
44-
}
45-
return stats;
46-
} catch (error) {
47-
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
48-
throw error;
42+
const stats = lstatIfPresent(outPath);
43+
if (stats?.isSymbolicLink()) {
44+
throw new AppError('COMMAND_FAILED', `App-log file must not be a symbolic link: ${outPath}`, {
45+
hint: NOT_REGULAR_FILE_HINT,
46+
});
4947
}
48+
return stats;
5049
}
5150

5251
function positiveIntEnv(raw: string | undefined, fallback: number): number {

‎src/utils/verified-file.ts‎

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,14 @@
11
import fs from 'node:fs';
2+
import { AppError } from '@agent-device/kernel/errors';
3+
4+
/**
5+
* Both guards are the same failure mode seen from two sides — something other than a plain
6+
* regular file sits at the final path — so the recovery is shared (ADR 0010 §3).
7+
*/
8+
export const NOT_REGULAR_FILE_HINT =
9+
'agent-device only reads and writes regular files at this path. Remove the symbolic link or special file there and retry.';
10+
const CONCURRENT_REPLACEMENT_HINT =
11+
'Another process replaced the file at this path while it was being opened. Stop the concurrent writer, then retry.';
212

313
/** Opens a regular final-path file for verified reads, or returns absent. */
414
export function openVerifiedFileForRead(pathname: string): number | undefined {
@@ -32,7 +42,11 @@ function openVerifiedFile(
3242
if (result.status === 'retry') continue;
3343
return result.status === 'missing' ? undefined : result.descriptor;
3444
}
35-
throw new Error(`Final file could not be opened without an identity race: ${pathname}`);
45+
throw new AppError(
46+
'COMMAND_FAILED',
47+
`Final file could not be opened without an identity race: ${pathname}`,
48+
{ hint: CONCURRENT_REPLACEMENT_HINT },
49+
);
3650
}
3751

3852
type VerifiedOpenAttempt =
@@ -100,15 +114,28 @@ function assertOpenedIdentity(pathname: string, descriptor: number, before?: fs.
100114
if (before && !sameFile(before, opened)) throw identityChangedError(pathname);
101115
}
102116

103-
function identityChangedError(pathname: string): Error {
104-
return new Error(`Final file identity changed while it was opened: ${pathname}`);
117+
function identityChangedError(pathname: string): AppError {
118+
return new AppError(
119+
'COMMAND_FAILED',
120+
`Final file identity changed while it was opened: ${pathname}`,
121+
{ hint: CONCURRENT_REPLACEMENT_HINT },
122+
);
105123
}
106124

107125
function lstatRegularFile(pathname: string): fs.Stats | undefined {
126+
const stats = lstatIfPresent(pathname);
127+
if (stats && !stats.isFile()) {
128+
throw new AppError('COMMAND_FAILED', `Final path must be a regular file: ${pathname}`, {
129+
hint: NOT_REGULAR_FILE_HINT,
130+
});
131+
}
132+
return stats;
133+
}
134+
135+
/** `lstat` that treats absence as `undefined`; every other errno propagates. */
136+
export function lstatIfPresent(pathname: string): fs.Stats | undefined {
108137
try {
109-
const stats = fs.lstatSync(pathname);
110-
if (!stats.isFile()) throw new Error(`Final path must be a regular file: ${pathname}`);
111-
return stats;
138+
return fs.lstatSync(pathname);
112139
} catch (error) {
113140
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
114141
throw error;

0 commit comments

Comments
 (0)