Skip to content

Commit a56c410

Browse files
fix(tools): use the exact Zoo-Code-Org#1399 remediation texts and create on observed-plus-absent
Pre-merge Linked Issues error on Zoo-Code-Org#1405: the S4a tracking issue requires the exact remediation texts - unobserved + present -> `file not read yet — read the file, then retry` - observed + present mismatch -> `stale version — re-read the file, then retry` guardedWrite now emits those strings verbatim (the version detail stays out of the user-facing sentence), and the spec asserts them. The observed + absent decision-table row now routes through createIfAbsent instead of a deleted-after-read error, so a read-then-deleted file is recreated safely; the entry-level and publication-time tests were updated to the new contract. Regression Evidence warning: the rollback-failure test now also asserts the staged temp unlink and the staging-directory release, and the success test pins the fsync -> close -> rename ordering. guardedWrite 39 passed, safeWriteText 44 passed.
1 parent 4133527 commit a56c410

3 files changed

Lines changed: 56 additions & 61 deletions

File tree

‎src/core/tools/__tests__/guardedWrite.spec.ts‎

Lines changed: 32 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
106106
const task = createMockTask()
107107

108108
await expect(guardedWrite(task, "existing.txt", "hello", "create")).rejects.toThrow(
109-
"File already exists at " +
110-
abs("existing.txt") +
111-
" and was not read before this write -- read the file first, then retry.",
109+
"file not read yet — read the file, then retry",
112110
)
113111
expect(mockedSafeWriteText).not.toHaveBeenCalled()
114112
})
@@ -123,21 +121,22 @@ describe("guardedWrite (S4a, epic #1375)", () => {
123121
})
124122
})
125123

126-
describe("deleted-after-read target", () => {
127-
it("normalizes an ENOENT from the version token into the re-read remediation", async () => {
124+
describe("deleted-after-read target (observed + absent)", () => {
125+
it("creates the file when it vanished after the read", async () => {
128126
const reg = new ObservationRegistry()
129127
reg.observe(abs("vanished.txt"), "v1")
130128
const task = createMockTask({ observationRegistry: reg })
131129

132-
// The file was deleted after the read: the token computation fails
133-
// with a raw ENOENT, which the guard must convert into the standard
134-
// re-read-then-retry contract.
130+
// Observed + absent is the create row of the #1399 decision table: the file the
131+
// caller read was deleted before this write, so the guard recreates it.
135132
mockedComputeVersionToken.mockRejectedValue({ code: "ENOENT" })
133+
mockedFsAccess.mockRejectedValue({ code: "ENOENT" })
136134

137-
await expect(guardedWrite(task, "vanished.txt", "next", "update")).rejects.toThrow(
138-
"File was deleted after it was read",
139-
)
140-
expect(mockedSafeWriteText).not.toHaveBeenCalled()
135+
await guardedWrite(task, "vanished.txt", "next", "update")
136+
137+
expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("vanished.txt"), "next", {
138+
verifyBeforeCommit: expect.any(Function),
139+
})
141140
})
142141

143142
it("rethrows non-ENOENT token failures verbatim from replaceIfVersion", async () => {
@@ -165,9 +164,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
165164
const task = createMockTask()
166165

167166
await expect(guardedWrite(task, "existing.txt", "hello", "update")).rejects.toThrow(
168-
"File already exists at " +
169-
abs("existing.txt") +
170-
" and was not read before this write -- read the file first, then retry.",
167+
"file not read yet — read the file, then retry",
171168
)
172169
expect(mockedSafeWriteText).not.toHaveBeenCalled()
173170
})
@@ -228,7 +225,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
228225
const task = createMockTask({ observationRegistry: reg })
229226

230227
await expect(guardedWrite(task, "kept.txt", "rewritten", "create")).rejects.toThrow(
231-
"Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.",
228+
"stale version — re-read the file, then retry",
232229
)
233230
expect(mockedSafeWriteText).not.toHaveBeenCalled()
234231
})
@@ -241,7 +238,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
241238
const task = createMockTask({ observationRegistry: reg })
242239

243240
await expect(guardedWrite(task, "locked.txt", "rewritten", "create")).rejects.toThrow(
244-
"Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.",
241+
"stale version — re-read the file, then retry",
245242
)
246243
expect(mockedSafeWriteText).not.toHaveBeenCalled()
247244
})
@@ -269,29 +266,25 @@ describe("guardedWrite (S4a, epic #1375)", () => {
269266
const task = createMockTask({ observationRegistry: reg })
270267

271268
await expect(guardedWrite(task, "doc.txt", "new content", "update")).rejects.toThrow(
272-
"Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.",
269+
"stale version — re-read the file, then retry",
273270
)
274271
expect(mockedSafeWriteText).not.toHaveBeenCalled()
275272
})
276273

277-
it("does not probe existence or recreate when an updated file vanished after the read", async () => {
274+
it("recreates when an updated file vanished after the read", async () => {
278275
const reg = new ObservationRegistry()
279276
reg.observe(abs("doc.txt"), "v1")
280277
const task = createMockTask({ observationRegistry: reg })
281-
// The file vanished: the CAS token recomputation rejects with ENOENT,
282-
// which the version guard reports as the deleted-file remediation.
278+
// Observed + absent is the create row of the #1399 decision table: the
279+
// file vanished between the read and this write, so the guard recreates it.
283280
mockedComputeVersionToken.mockRejectedValue({ code: "ENOENT" })
284281
mockedFsAccess.mockRejectedValue({ code: "ENOENT" })
285282

286-
await expect(guardedWrite(task, "doc.txt", "new content", "update")).rejects.toThrow(
287-
"File was deleted after it was read -- the version recorded at read time (v1) no longer exists; re-read the file, then retry.",
288-
)
283+
await guardedWrite(task, "doc.txt", "new content", "update")
289284

290-
// The existence probe is a "create"-only step: an "update" must not run
291-
// it (the branch condition short-circuits on kind) and must not recreate
292-
// the vanished file - only the CAS branch may decide the write.
293-
expect(mockedFsAccess).not.toHaveBeenCalled()
294-
expect(mockedSafeWriteText).not.toHaveBeenCalled()
285+
expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "new content", {
286+
verifyBeforeCommit: expect.any(Function),
287+
})
295288
})
296289
})
297290

@@ -300,7 +293,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
300293
const task = createMockTask()
301294

302295
await expect(guardedWrite(task, "any.txt", "patched", "edit")).rejects.toThrow(
303-
"File not read yet -- read the file, then retry.",
296+
"file not read yet — read the file, then retry",
304297
)
305298
expect(mockedSafeWriteText).not.toHaveBeenCalled()
306299
expect(mockedComputeVersionToken).not.toHaveBeenCalled()
@@ -327,7 +320,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
327320
const task = createMockTask({ observationRegistry: reg })
328321

329322
await expect(guardedWrite(task, "doc.txt", "patched", "edit")).rejects.toThrow(
330-
"Stale version -- the file changed since you read it (expected v1, current v3); re-read the file, then retry.",
323+
"stale version — re-read the file, then retry",
331324
)
332325
expect(mockedSafeWriteText).not.toHaveBeenCalled()
333326
})
@@ -430,7 +423,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
430423
}
431424
expect(mockedSafeWriteText).toHaveBeenCalledTimes(1)
432425
expect(r2.reason.message).toBe(
433-
"Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.",
426+
"stale version — re-read the file, then retry",
434427
)
435428
})
436429

@@ -468,7 +461,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
468461
// content derived from the v1 read over the v2 file. An execution-time
469462
// registry lookup would rescue it with the refreshed token and lose the
470463
// first write's update.
471-
await expect(second).rejects.toThrow("Stale version")
464+
await expect(second).rejects.toThrow("stale version")
472465
expect(publishes).toBe(1)
473466
})
474467

@@ -496,8 +489,8 @@ describe("guardedWrite (S4a, epic #1375)", () => {
496489
throw new Error("expected exactly one publish, got " + r1.status + " / " + r2.status)
497490
}
498491
expect(publishes).toBe(1)
499-
expect(r2.reason.message).toContain("Stale version")
500-
expect(r2.reason.message).toContain("re-read the file, then retry.")
492+
expect(r2.reason.message).toContain("stale version")
493+
expect(r2.reason.message).toContain("re-read the file, then retry")
501494
})
502495

503496
it("the chain settles after a rejection - a later matching write still runs", async () => {
@@ -507,7 +500,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
507500
const task = createMockTask({ observationRegistry: reg })
508501

509502
const p1 = guardedWrite(task, "settle.txt", "first", "update")
510-
await expect(p1).rejects.toThrow("Stale version")
503+
await expect(p1).rejects.toThrow("stale version")
511504

512505
// No resetChain: the rejected link must not wedge the chain. The
513506
// caller re-reads the file (observation refreshed to v2) and retries.
@@ -592,9 +585,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
592585
})
593586

594587
await expect(guardedWrite(task, "raced.txt", "mine", "create")).rejects.toThrow(
595-
"File already exists at " +
596-
abs("raced.txt") +
597-
" and was not read before this write -- read the file first, then retry.",
588+
"file not read yet — read the file, then retry",
598589
)
599590
// nothing was published: the competing writer's file is preserved
600591
expect(published()).toBe(false)
@@ -613,7 +604,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
613604
})
614605

615606
await expect(guardedWrite(task, "raced.txt", "mine", "update")).rejects.toThrow(
616-
"Stale version -- the file changed since you read it (expected v1, current v-external); re-read the file, then retry.",
607+
"stale version — re-read the file, then retry",
617608
)
618609
expect(published()).toBe(false)
619610
})
@@ -704,7 +695,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
704695
}
705696
expect(mockedSafeWriteText).toHaveBeenCalledTimes(1)
706697
expect(r2.reason.message).toBe(
707-
"Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.",
698+
"stale version — re-read the file, then retry",
708699
)
709700
})
710701
})

‎src/core/tools/guardedWrite.ts‎

Lines changed: 12 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -125,24 +125,16 @@ async function fileIsAbsent(absolutePath: string): Promise<boolean> {
125125

126126
/** Build the read-first remediation error for an existing target. */
127127
function alreadyExistsError(absolutePath: string): GuardRejectedError {
128-
return new GuardRejectedError(
129-
"File already exists at " +
130-
absolutePath +
131-
" and was not read before this write -- read the file first, then retry.",
132-
absolutePath,
133-
)
128+
// Exact remediation text required by the S4a tracking issue (#1399).
129+
return new GuardRejectedError("file not read yet — read the file, then retry", absolutePath)
134130
}
135131

136132
/** Build the stale-version remediation error. */
137133
function staleVersionError(absolutePath: string, expectedVersion: string, currentVersion: string): GuardRejectedError {
138-
return new GuardRejectedError(
139-
"Stale version -- the file changed since you read it (expected " +
140-
expectedVersion +
141-
", current " +
142-
currentVersion +
143-
"); re-read the file, then retry.",
144-
absolutePath,
145-
)
134+
// Exact remediation text required by #1399; the version detail is diagnostic only.
135+
void expectedVersion
136+
void currentVersion
137+
return new GuardRejectedError("stale version — re-read the file, then retry", absolutePath)
146138
}
147139

148140
/** Build the deleted-after-read remediation error. */
@@ -225,11 +217,10 @@ export async function replaceIfVersion(absolutePath: string, expectedVersion: st
225217
currentVersion = await computeVersionToken(absolutePath)
226218
} catch (error: unknown) {
227219
if (errorCode(error) === "ENOENT") {
228-
// The observed file was deleted after the read: the version recorded
229-
// at read time no longer exists on disk. Normalize the raw ENOENT
230-
// into the guard's re-read-then-retry contract so the caller gets a
231-
// remediation it can act on, not a raw errno.
232-
throw deletedAfterReadError(absolutePath, expectedVersion)
220+
// Observed + absent is a create row of the #1399 decision table: the file the
221+
// caller read was deleted before this write, so creating it is the safe action.
222+
await createIfAbsent(absolutePath, content)
223+
return
233224
}
234225
// A real I/O failure (EACCES, EIO, ...) -- not a guard verdict.
235226
throw error
@@ -279,7 +270,8 @@ async function verifyVersionUnchanged(absolutePath: string, expectedVersion: str
279270
* never resolves.
280271
*/
281272
export async function unobservedEditGuard(absolutePath: string): Promise<never> {
282-
throw new GuardRejectedError("File not read yet -- read the file, then retry.", absolutePath)
273+
// Exact remediation text required by #1399.
274+
throw new GuardRejectedError("file not read yet — read the file, then retry", absolutePath)
283275
}
284276

285277
// -- Public API --------------------------------------------------------------

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,10 @@ describe("safeWriteText", () => {
111111
expect(failure?.cause?.message).toBe("rollback failed")
112112
expect(failure?.message).toContain("commit failed")
113113
expect(failure?.message).toContain("rollback failed")
114+
// The failure path still cleans up: the staged temp is unlinked and the staging
115+
// directory is released, so a double-failure does not leave write artifacts behind.
116+
expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"))
117+
expect(fsSync.rmdirSync).toHaveBeenCalledWith(expect.stringContaining(".file-safety-staging"))
114118
expect(failure?.message).toContain(failure?.backupPath)
115119
})
116120
})
@@ -149,6 +153,14 @@ describe("safeWriteText", () => {
149153
// atomic rename happened — realpath mock returns targetPath, so that's the dest
150154
expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath)
151155

156+
// Ordering contract: the content is fsynced, the descriptor closed, and only then
157+
// the temp is renamed over the target, so a crash cannot publish unflushed bytes.
158+
const fsyncOrder = vi.mocked(fsSync.fsyncSync).mock.invocationCallOrder[0]
159+
const closeOrder = vi.mocked(fsSync.closeSync).mock.invocationCallOrder[0]
160+
const renameOrder = vi.mocked(fs.rename).mock.invocationCallOrder[0]
161+
expect(fsyncOrder).toBeLessThan(closeOrder)
162+
expect(closeOrder).toBeLessThan(renameOrder)
163+
152164
// no unlink of temp (it's now the committed file; DACL skipped via platform:linux)
153165
expect(fs.unlink).not.toHaveBeenCalled()
154166
})

0 commit comments

Comments
 (0)