Skip to content

Commit 7532ed2

Browse files
fix(safe-write): compare directory identity in the safeWriteText staging guard
The windows required leg (node 22.23.4) failed at 0580426 in 20 tests, and both shapes trace to delegating the JSON commit to safeWriteText: - 8 in utils/__tests__/safeWriteJson.test.ts, raised at safeWriteText.ts:361: StagingPathError: Staging file must sit in the target's directory (C:\Users\runneradmin\AppData\Local\Temp\safeWriteJson-test-whV2CF), got C:\Users\RUNNER~1\AppData\Local\Temp\... - 12 in safeWriteJson.interruption.test.ts, all at line 187 with one payload: AssertionError: expected 'WRITE_COMPLETED' to contain 'EXIT_AT_REPLACEMENT_RENAME'. The guard's comparison has two operands produced by two different canonicalisations - the spelling the caller's staging-file derivation hands down (the short one, the message's 'got') and the spelling safeWriteText derives when it re-resolves its own argument (the long one, the message's expected directory) - and on NTFS one directory answers to more than one spelling: the 8.3 alias of any name longer than eight characters, a junction, or a link. One directory, two strings, in a single message. Measured on node 22.23.4 (.tool-versions pins 22.23.4, package.json engines repeats it, the hosted legs run it; this box's system node is v25.9.0) against a real short-name alias of a directory: path.resolve(SHORT) != path.resolve(LONG) fs.realpathSync(SHORT) != fs.realpathSync(LONG) fs.realpathSync.native(SHORT) == fs.realpathSync.native(LONG) fs.stat(SHORT).dev == fs.stat(LONG).dev, and .ino == .ino Node 22's JavaScript fs.realpath preserves whichever spelling it is handed, so comparing realpaths would not have unified the runner's pair either. Only stat identity unifies an 8.3 alias, a junction and a case difference at once. Why not just stage from the resolved directory (option a): safeWriteJson.ts already does that - :183 builds the staging name from resolvedTargetPath and :197 passes that same variable as the target - and the runner still splits the spellings, because safeWriteText re-resolves the path it is handed and that re-resolution can take a different route: an existing target canonicalises, a target that does not exist yet falls through to path.resolve. The mismatch is therefore not fixable from the call site, and it is not evidence that the guard is too strict: the guard is textual on purpose. What it protects is a property of directory identity - no cross-filesystem commit rename (EXDEV), and never publishing an unrelated file onto the target - so a textual mismatch is now settled by comparing dev+ino read as bigint, the idiom the staged-file check below it already uses, and the rejection stands whenever either directory cannot be stat'd. A staging file in a genuinely different directory is still rejected under both spellings. The interruption half: the fault hook is the child's monkey-patch of fsPromises.rename inside safeWriteJson.interruption.test.ts, not the options.trace replacement-rename line - EXIT_AT_REPLACEMENT_RENAME is printed by that hook. The delegation moved the commit rename's destination from the caller's string to safeWriteText's own resolved publish target, so the hook's textual match against INTERRUPTION_TARGET_PATH misses whenever the directory is spelled through an alias: the SIGKILL never fires, the write completes, and the parent sees WRITE_COMPLETED. That is a behavioural consequence of the delegation, not a test-only looseness, and ubuntu cannot see it because its temp directory has no alias. The harness now recognises the commit rename by canonical destination, and a new win32 case spells the target through a junction so the assertion is red without the harness fix (reproduced: 1 failed | 12 passed with the CI assertion text above; 13 passed after). Tests, all on node 22.23.4: - new services/file-safety/__tests__/safeWriteText.alias.spec.ts reproduces the guard failure for real on this box at the pre-fix guard (blob 688f2ef): same StagingPathError thrown at safeWriteText.ts:361, expected directory in the long spelling, got directory in the short one. The suite skips itself where the volume generates no 8.3 names, which is why ubuntu - and this box's own long-spelled temp path - never showed it. - negative control at 688f2ef across both specs: 2 failed | 77 passed; with the fix: 79 passed. - the misc project, which is the leg that was red, and the core project were rerun on this tree; counts are in the push report. The staging-name convention (the anchored .new_*.tmp rule in safeWriteText.ts) and its spec pin are untouched. The guard's contract and the canonicalisation choice belong to upstream, are tracked in Zoo-Code-Org#2350, and the cross-unit note is filed on Zoo-Code-Org#1405.
1 parent 793353a commit 7532ed2

4 files changed

Lines changed: 328 additions & 6 deletions

File tree

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import { execFileSync } from "child_process"
2+
import * as fs from "fs"
3+
import * as os from "os"
4+
import * as path from "path"
5+
6+
import { safeWriteText, StagingPathError } from "../safeWriteText"
7+
8+
// NTFS hands an 8.3 alias to every component whose name is longer than eight characters, so one
9+
// directory answers to two spellings. The hosted Windows runner is the case that matters: its
10+
// temp directory arrives in the short form under the profile while the writer's resolved target
11+
// arrives in the long spelling, and the staging file created beside that target carries whichever
12+
// spelling the caller's canonicalisation produced. A textual comparison of the two directories then
13+
// rejects a staging file that really is beside the target - that is the StagingPathError the
14+
// windows job reports at the staging guard.
15+
//
16+
// The alias cannot be invented on a box whose volume declines to generate 8.3 names, so this file
17+
// asks cmd for the short spelling of a directory it just created and skips the suite where the
18+
// volume does not generate one. What node 22.23.4 - the version .tool-versions and engines pin -
19+
// does with those two spellings is asserted below rather than assumed: path.resolve preserves
20+
// whichever spelling it is handed, fs.realpath preserves it too, and fs.stat reports one identity
21+
// for both. The guard compares identities for exactly that reason.
22+
23+
function shortPathOf(directory: string): string | null {
24+
const out = execFileSync("cmd.exe", ["/c", "for %A in (" + directory + ") do @echo %~sA"], {
25+
encoding: "utf8",
26+
}).trim()
27+
const marker = "~1"
28+
return out.includes(marker) ? out : null
29+
}
30+
31+
const probeBase = fs.mkdtempSync(path.join(os.tmpdir(), "safe-write-alias-probe-"))
32+
const probeDir = path.join(probeBase, "EightThreeNameProbe")
33+
fs.mkdirSync(probeDir)
34+
const EIGHT_THREE_NAMES_ARE_GENERATED = shortPathOf(probeDir) !== null
35+
fs.rmSync(probeBase, { recursive: true, force: true })
36+
37+
describe("safeWriteText staging guard against a second spelling of the target directory", () => {
38+
let tempDir: string
39+
40+
beforeEach(() => {
41+
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "safeWriteText-alias-"))
42+
})
43+
44+
afterEach(() => {
45+
fs.rmSync(tempDir, { recursive: true, force: true })
46+
})
47+
48+
function createTargetDirectory(): { longPath: string; shortPath: string | null } {
49+
const longPath = path.join(tempDir, "LONGTARGETDIRECTORYNAME")
50+
fs.mkdirSync(longPath)
51+
return { longPath, shortPath: shortPathOf(longPath) }
52+
}
53+
54+
it.runIf(EIGHT_THREE_NAMES_ARE_GENERATED)(
55+
"publishes a staging file spelled through the target directory own 8.3 alias",
56+
async () => {
57+
const { longPath, shortPath } = createTargetDirectory()
58+
if (shortPath === null) {
59+
return
60+
}
61+
const targetPath = path.join(longPath, "target.txt")
62+
fs.writeFileSync(targetPath, "committed", "utf8")
63+
// The staging file sits beside the target but is spelled through the directory's 8.3
64+
// alias, which is what a caller's own canonicalisation hands the guard.
65+
const stagingPath = path.join(shortPath, ".new_target.txt_1_x.tmp")
66+
fs.writeFileSync(stagingPath, "staged", "utf8")
67+
68+
// Preconditions, asserted rather than assumed: the two directory spellings differ as text
69+
// and this runtime's fs.realpath does not unify them...
70+
expect(path.dirname(stagingPath)).not.toBe(path.dirname(targetPath))
71+
const realViaAlias = fs.realpathSync(path.dirname(stagingPath))
72+
const realViaTarget = fs.realpathSync(path.dirname(targetPath))
73+
expect(realViaAlias).not.toBe(realViaTarget)
74+
// ...while fs.stat reports the same directory for both spellings. That identity is what
75+
// the guard compares, and it is why a rename from here onto the target cannot be EXDEV.
76+
const statViaAlias = fs.statSync(path.dirname(stagingPath), { bigint: true })
77+
const statViaTarget = fs.statSync(path.dirname(targetPath), { bigint: true })
78+
expect(statViaAlias.dev).toBe(statViaTarget.dev)
79+
expect(statViaAlias.ino).toBe(statViaTarget.ino)
80+
81+
await safeWriteText(targetPath, "", { tempPath: stagingPath, backup: false })
82+
83+
expect(fs.readFileSync(targetPath, "utf8")).toBe("staged")
84+
expect(fs.existsSync(stagingPath)).toBe(false)
85+
},
86+
)
87+
88+
it.runIf(EIGHT_THREE_NAMES_ARE_GENERATED)(
89+
"still rejects a staging file spelled through another directory 8.3 alias",
90+
async () => {
91+
const { longPath } = createTargetDirectory()
92+
const otherPath = path.join(tempDir, "OTHERTARGETDIRECTORYNAME")
93+
fs.mkdirSync(otherPath)
94+
const otherShort = shortPathOf(otherPath)
95+
if (otherShort === null) {
96+
return
97+
}
98+
const targetPath = path.join(longPath, "target.txt")
99+
fs.writeFileSync(targetPath, "committed", "utf8")
100+
const stagingPath = path.join(otherShort, ".new_target.txt_1_x.tmp")
101+
fs.writeFileSync(stagingPath, "staged", "utf8")
102+
103+
// Same alias mechanism, different directory. Accepting the target directory's alias must
104+
// not become accepting any directory, or a caller could publish an unrelated file onto the
105+
// target through a name the guard was written to refuse.
106+
await expect(safeWriteText(targetPath, "", { tempPath: stagingPath, backup: false })).rejects.toThrow(
107+
StagingPathError,
108+
)
109+
expect(fs.readFileSync(targetPath, "utf8")).toBe("committed")
110+
expect(fs.existsSync(stagingPath)).toBe(true)
111+
},
112+
)
113+
})

‎src/services/file-safety/__tests__/safeWriteText.spec.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ vi.mock("fs/promises", () => ({
2222
unlink: vi.fn(),
2323
rmdir: vi.fn(),
2424
realpath: vi.fn(),
25+
stat: vi.fn(),
2526
lstat: vi.fn(),
2627
readlink: vi.fn(),
2728
}))
@@ -105,6 +106,11 @@ function mockDefaults(): void {
105106
vi.mocked(fs.lstat).mockResolvedValue(_fileStats(false))
106107
// Post-open default: the opened file is the same single-named regular file.
107108
vi.mocked(fsSync.fstatSync).mockReturnValue(_fileStats(false))
109+
// Directory-identity default: unresolvable, so the identity check keeps the textual rejection
110+
// wherever a test does not stage an alias of the target's own directory.
111+
vi.mocked(fs.stat).mockRejectedValue(
112+
Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }),
113+
)
108114
}
109115
function _stats(mode: number): fsSync.Stats {
110116
const s = Object.create(fsSync.Stats.prototype) as fsSync.Stats
@@ -1707,6 +1713,76 @@ describe("caller-supplied staging path", () => {
17071713
expect(fs.rename).not.toHaveBeenCalled()
17081714
})
17091715

1716+
// NTFS hands an 8.3 alias to every path component longer than eight characters, and the hosted
1717+
// Windows runner's temp directory arrives in that spelling while the writer's resolved target
1718+
// arrives in the long spelling of the same directory; a junction or link does the same thing on
1719+
// any box. Two strings, one directory: the textual check above rejects a staging file that really
1720+
// is beside the target. What that check protects is the opposite - a staging file that is NOT
1721+
// beside the target, which is what makes the commit rename cross-filesystem (EXDEV) or lets a
1722+
// caller publish an unrelated file onto the target. Identity is that property, so a textual
1723+
// mismatch is resolved by comparing the two directories' dev and ino. path.resolve cannot settle
1724+
// it (it preserves whichever spelling it is given) and neither can fs.realpath: measured on node
1725+
// 22.23.4, Node's JavaScript realpath preserves an NTFS 8.3 spelling, and only
1726+
// fs.realpathSync.native expands it. These two tests drive the identity branch directly because a
1727+
// whole-file mock of fs/promises cannot present two spellings of a real directory.
1728+
it("accepts a caller-staged file whose directory is the target directory under another spelling", async () => {
1729+
const targetPath = "/tmp/test-dir/target.txt"
1730+
const aliasDir = path.resolve("/tmp/alias-dir")
1731+
const targetDir = path.dirname(path.resolve(targetPath))
1732+
// One directory under two spellings: each side hands back its own realpath, so only the pair's
1733+
// identity says they are the same directory.
1734+
// realpath here mirrors what node 22.23.4 does to an NTFS 8.3 name: it hands back the
1735+
// spelling it was given, so only the directory identity can tell an alias from another directory.
1736+
vi.mocked(fs.realpath).mockImplementation((p: unknown) => Promise.resolve(path.resolve(String(p))))
1737+
vi.mocked(fs.stat).mockImplementation((p: unknown) => {
1738+
const s = String(p)
1739+
if (s === aliasDir || s === targetDir) {
1740+
return Promise.resolve(_fileStatsWithIdentity(4242n, 7n))
1741+
}
1742+
return Promise.reject(Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }))
1743+
})
1744+
vi.mocked(fsSync.openSync).mockReturnValue(3)
1745+
1746+
const customTempPath = path.join(aliasDir, ".new_target.txt_1_x.tmp")
1747+
1748+
await safeWriteText(targetPath, "", { tempPath: customTempPath, platform: "linux" })
1749+
1750+
// The alias directory and the target directory are one directory, so the staging file is
1751+
// beside the target and the publish proceeds.
1752+
expect(fsSync.openSync).toHaveBeenCalledWith(customTempPath, "r+")
1753+
expect(fs.rename).toHaveBeenCalledWith(customTempPath, path.resolve(targetPath))
1754+
})
1755+
1756+
it("still rejects a caller-staged file whose directory has a different identity", async () => {
1757+
const targetPath = "/tmp/test-dir/target.txt"
1758+
const otherDir = path.resolve("/tmp/other-dir")
1759+
const targetDir = path.dirname(path.resolve(targetPath))
1760+
// Two directories that both resolve cleanly but are not the same directory: a staging file in
1761+
// one of them would publish an unrelated file onto the target, and across a mount the commit
1762+
// rename would fail with EXDEV.
1763+
// realpath here mirrors what node 22.23.4 does to an NTFS 8.3 name: it hands back the
1764+
// spelling it was given, so only the directory identity can tell an alias from another directory.
1765+
vi.mocked(fs.realpath).mockImplementation((p: unknown) => Promise.resolve(path.resolve(String(p))))
1766+
vi.mocked(fs.stat).mockImplementation((p: unknown) => {
1767+
const s = String(p)
1768+
if (s === otherDir) {
1769+
return Promise.resolve(_fileStatsWithIdentity(9999n, 7n))
1770+
}
1771+
if (s === targetDir) {
1772+
return Promise.resolve(_fileStatsWithIdentity(4242n, 7n))
1773+
}
1774+
return Promise.reject(Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }))
1775+
})
1776+
vi.mocked(fsSync.openSync).mockReturnValue(3)
1777+
1778+
const customTempPath = path.join(otherDir, ".new_target.txt_1_x.tmp")
1779+
1780+
await expect(safeWriteText(targetPath, "", { tempPath: customTempPath, platform: "linux" })).rejects.toThrow(
1781+
"Staging file must sit in the target's directory",
1782+
)
1783+
expect(fsSync.openSync).not.toHaveBeenCalled()
1784+
expect(fs.rename).not.toHaveBeenCalled()
1785+
})
17101786
it("rejects a caller-staged file that gained a second hard link before the open", async () => {
17111787
const targetPath = "/tmp/test-dir/target.txt"
17121788
vi.mocked(fs.realpath).mockResolvedValue(targetPath)

‎src/services/file-safety/safeWriteText.ts‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -358,10 +358,36 @@ export async function safeWriteText(
358358
// dangling symlink in resolvePublishTarget.
359359
const supplied = path.resolve(options.tempPath)
360360
if (path.dirname(supplied) !== path.resolve(dirPath)) {
361-
throw new StagingPathError(
362-
`Staging file must sit in the target's directory (${dirPath}), got ${supplied}`,
363-
supplied,
364-
)
361+
// A textual mismatch is not yet evidence that the staging file sits elsewhere, because one
362+
// directory answers to more than one spelling. NTFS hands out an 8.3 alias for every name
363+
// longer than eight characters - the hosted Windows runner's temp directory arrives as
364+
// RUNNER~1 under the profile while the writer's resolved target arrives in the long
365+
// spelling - and a junction or link does the same thing on any box. path.resolve preserves
366+
// whichever spelling it is handed, and fs.realpath (the JavaScript implementation Node 22
367+
// uses) preserves it too; only realpathSync.native expands the 8.3 form, measured on
368+
// node 22.23.4. So neither a textual nor a plain-realpath comparison can tell an alias of
369+
// the target's own directory from a different directory. The property this guard protects -
370+
// no cross-filesystem commit rename (EXDEV) and no publishing of an unrelated file onto the
371+
// target - is a property of the directory's identity, so compare identity: dev and ino, read
372+
// as bigint for the same reason as the file check below. A directory that cannot be stat'd
373+
// keeps the rejection, so this only ever accepts what the textual check would have accepted
374+
// had the spelling been canonical on both sides.
375+
const suppliedDir = path.dirname(supplied)
376+
const [suppliedDirStat, targetDirStat] = await Promise.all([
377+
fs.stat(suppliedDir, { bigint: true }).catch(() => undefined),
378+
fs.stat(dirPath, { bigint: true }).catch(() => undefined),
379+
])
380+
const sameDirectory =
381+
suppliedDirStat !== undefined &&
382+
targetDirStat !== undefined &&
383+
suppliedDirStat.dev === targetDirStat.dev &&
384+
suppliedDirStat.ino === targetDirStat.ino
385+
if (!sameDirectory) {
386+
throw new StagingPathError(
387+
`Staging file must sit in the target's directory (${dirPath}), got ${supplied}`,
388+
supplied,
389+
)
390+
}
365391
}
366392
// BigInt stats: on NTFS/ReFS the file identity can exceed Number.MAX_SAFE_INTEGER, and
367393
// a rounded number makes two different files look identical (rejecting a valid staging

‎src/utils/__tests__/safeWriteJson.interruption.test.ts‎

Lines changed: 109 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,15 +29,43 @@ const fs = require("fs")
2929
const path = require("path")
3030
3131
const targetPath = path.resolve(process.env.INTERRUPTION_TARGET_PATH)
32+
// The commit goes through safeWriteText, which renames onto the publish target it resolved
33+
// itself. One directory answers to two spellings on NTFS - every component longer than eight
34+
// characters also has an 8.3 alias, so the CI runner's temp directory arrives short-named
35+
// (RUNNER~1 under the user profile) while realpath hands back the long spelling of the same
36+
// directory - and a junction or a link does the same thing on any box. The writer's canonical
37+
// handed to this child can therefore name the same file as different text, and a textual
38+
// comparison would then let the commit land unnoticed. Canonicalise this side the same way,
39+
// and fall back to the textual form for a target that does not exist yet and cannot be
40+
// canonicalised.
41+
let canonicalTargetPath = targetPath
42+
try {
43+
canonicalTargetPath = fs.realpathSync(targetPath)
44+
} catch {
45+
// A target that is not on disk yet has no canonical spelling; the textual form is then
46+
// the only comparison available, and it is the one the writer would use anyway.
47+
}
48+
const isCommitRename = (newPath) => {
49+
const resolved = path.resolve(String(newPath))
50+
if (resolved === targetPath || resolved === canonicalTargetPath) {
51+
return true
52+
}
53+
try {
54+
return fs.realpathSync(resolved) === canonicalTargetPath
55+
} catch {
56+
// A destination that cannot be canonicalised is not the canonical target.
57+
return false
58+
}
59+
}
3260
const fsPromises = require("fs/promises")
3361
const actualRename = fsPromises.rename
3462
3563
// Fault injection: hard-kill before the replacement lands. Any rename
36-
// whose destination is the canonical path is the commit step, whatever
64+
// whose destination is the canonical path (or an alias of it) is the commit step, whatever
3765
// replacement protocol the writer uses; exit before performing it.
3866
let commitAttempts = 0
3967
fsPromises.rename = async function interruptionRename(oldPath, newPath) {
40-
if (path.resolve(String(newPath)) === targetPath) {
68+
if (isCommitRename(newPath)) {
4169
commitAttempts++
4270
if (process.env.INTERRUPTION_MODE === "fallback" && commitAttempts === 1) {
4371
return Promise.reject(Object.assign(new Error("Injected EPERM"), { code: "EPERM" }))
@@ -239,4 +267,83 @@ describe("safeWriteJson subprocess interruption fault injection", () => {
239267
},
240268
45_000,
241269
)
270+
271+
// The child intercepts the commit rename by comparing the rename's destination with
272+
// INTERRUPTION_TARGET_PATH. The commit now goes through safeWriteText, which renames onto the
273+
// publish target it resolved itself, so the destination is not necessarily the spelling the
274+
// parent passed down. On NTFS one directory answers to two spellings: every component longer
275+
// than eight characters also has an 8.3 alias, and the Windows CI runner's temp directory
276+
// arrives as C:\Users\RUNNER~1\... while realpath hands back C:\Users\runneradmin\... The
277+
// interception has to survive that. A junction gives any Windows box the same shape without
278+
// needing privileges: this case spells the target through an alias of the directory the
279+
// writer resolves to, so the parent's spelling and the writer's canonical spelling of the same
280+
// directory differ as text on a box that has no 8.3 alias on its own temp path.
281+
it.runIf(process.platform === "win32")(
282+
"intercepts the commit rename when the target path is spelled through a directory alias",
283+
async () => {
284+
const fileName = "ui_messages.json"
285+
const message = {
286+
ts: 1,
287+
type: "say",
288+
say: "text",
289+
text: "RESTART_PERSISTENCE_MARKER",
290+
role: "assistant",
291+
content: "RESTART_PERSISTENCE_MARKER",
292+
}
293+
const committed = [message]
294+
const replacement = [{ ...message, ts: 2, text: "ALIASED_WRITE", content: "ALIASED_WRITE" }]
295+
await safeWriteJson(targetPath, committed)
296+
297+
const aliasDir = path.join(tempDir, "storage-alias")
298+
try {
299+
await fs.symlink(storageDir, aliasDir, "junction")
300+
} catch (error: unknown) {
301+
const code = typeof error === "object" && error !== null ? (error as { code?: string }).code : undefined
302+
// A box that cannot create a junction cannot present a second spelling of the
303+
// directory; there is nothing to intercept differently and no alias to reject.
304+
if (code === "EPERM" || code === "ENOSYS" || code === "EEXIST") {
305+
return
306+
}
307+
throw error
308+
}
309+
const aliasTargetPath = path.join(aliasDir, fileName)
310+
expect(path.resolve(aliasTargetPath)).not.toBe(path.resolve(targetPath))
311+
312+
const child = spawn(process.execPath, [childScriptPath], {
313+
env: {
314+
...process.env,
315+
INTERRUPTION_TARGET_PATH: aliasTargetPath,
316+
INTERRUPTION_MODE: "atomic",
317+
INTERRUPTION_BOUNDARY: "before-commit",
318+
INTERRUPTION_PAYLOAD: JSON.stringify(replacement),
319+
ESBUILD_PATH: esbuildPath,
320+
SAFE_WRITE_JSON_ENTRY: safeWriteJsonEntryPath,
321+
INTERRUPTION_BUNDLE_PATH: childBundlePath,
322+
},
323+
stdio: ["ignore", "pipe", "pipe"],
324+
})
325+
const exit = await waitForChildExit(child)
326+
327+
expect(exit.stderr).not.toContain("WRITE_FAILED")
328+
expect(exit.stdout).toContain("EXIT_AT_REPLACEMENT_RENAME")
329+
expect(exit.stdout).not.toContain("WRITE_COMPLETED")
330+
expect(exit.code).toBe(1)
331+
// The canonical target is untouched by an interrupted commit, spelled through either name.
332+
expect(JSON.parse(await readFileWithMissingRetry(targetPath))).toEqual(committed)
333+
expect(JSON.parse(await readFileWithMissingRetry(aliasTargetPath))).toEqual(committed)
334+
const interruptedFiles = await fs.readdir(storageDir)
335+
expect(interruptedFiles.filter((entry) => entry.includes(".new_"))).toHaveLength(1)
336+
337+
const staleTime = new Date(Date.now() - 60_000)
338+
await fs.utimes(`${targetPath}.lock`, staleTime, staleTime)
339+
const recovered = { ui_messages: [{ ts: 3, type: "say", text: "RECOVERED_AFTER_RESTART" }] }
340+
await safeWriteJson(aliasTargetPath, recovered)
341+
expect(JSON.parse(await readFileWithMissingRetry(targetPath))).toEqual(recovered)
342+
const leftovers = (await fs.readdir(storageDir)).filter(
343+
(entry) => entry.includes(".new_") || entry.includes(".bak_"),
344+
)
345+
expect(leftovers).toEqual([])
346+
},
347+
45_000,
348+
)
242349
})

0 commit comments

Comments
 (0)