Skip to content

Commit 22a3f33

Browse files
committed
merge: file-write-safety trial — addendum 10 (CodeRabbit review fixes from PR #1410 + #1412: stale-card rollback rejection, unreadable-journal failure, correlated webview rollback results, change-card error a11y, openFile path labels, locale corrections; B3c/B3b, #1375)
1 parent 779cb4b commit 22a3f33

46 files changed

Lines changed: 496 additions & 99 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/core/checkpoints/__tests__/changeJournal.spec.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,16 @@ describe("changeJournal", () => {
6262
expect(await loadChanges(tmpRoot, taskId)).toEqual([])
6363
})
6464

65+
it("propagates non-ENOENT read failures instead of reporting an empty journal", async () => {
66+
// A directory at the journal path makes readFile fail with EISDIR —
67+
// a stand-in for any permission or I/O failure (EACCES etc.). Such a
68+
// failure must not be swallowed into "no changes": it would let a
69+
// rollback report a no-op success without reading the history.
70+
await fs.mkdir(journalPath(tmpRoot, taskId), { recursive: true })
71+
72+
await expect(loadChanges(tmpRoot, taskId)).rejects.toMatchObject({ code: "EISDIR" })
73+
})
74+
6575
it("parses all entries in order with a clean tail", async () => {
6676
await appendChange(tmpRoot, taskId, entry({ checkpointId: "x" }))
6777
await appendChange(tmpRoot, taskId, entry({ checkpointId: "y" }))

‎src/core/checkpoints/__tests__/rollback.spec.ts‎

Lines changed: 118 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
77
import type { Task } from "../../task/Task"
88
import type { ChangeJournalEntry } from "../changeJournal"
99
import { getCheckpointService } from "../index"
10-
import { appendChange } from "../changeJournal"
10+
import * as changeJournal from "../changeJournal"
11+
import { appendChange, journalPath } from "../changeJournal"
1112
import { restoreLatestFile, rollbackFile, rollbackStep } from "../rollback"
1213

1314
vi.mock("../index", () => ({
@@ -98,6 +99,48 @@ describe("rollbackFile (B3c: undo the step's write to the file)", () => {
9899
expect(service.restoreFile).toHaveBeenCalledWith("sha-1", "src/a.ts")
99100
})
100101

102+
it("rejects rolling back a step that is not the file's latest change", async () => {
103+
// The file was written again by a later step (sha-2): rolling back the
104+
// older step (sha-1) would overwrite the newer state, so it is
105+
// rejected instead of silently destroying it.
106+
await seedJournal([
107+
{ path: "src/a.ts", operation: "create", checkpointId: "sha-1" },
108+
{ path: "src/a.ts", operation: "update", checkpointId: "sha-2" },
109+
])
110+
const service = serviceWith("base-0")
111+
mockedGetCheckpointService.mockResolvedValue(service)
112+
113+
const outcome = await rollbackFile(makeTask(), "sha-1", "src/a.ts")
114+
115+
expect(outcome).toEqual({
116+
filePath: "src/a.ts",
117+
success: false,
118+
error: "File was modified in a later step; roll back the latest change card first",
119+
})
120+
expect(service.restoreFile).not.toHaveBeenCalled()
121+
})
122+
123+
it("fails when the journal location is unavailable (no global storage)", async () => {
124+
// No context on the provider double → the journal cannot even be
125+
// located: a clear failure, not a silent miss on the file lookup.
126+
const task = {
127+
taskId: "task-rollback",
128+
providerRef: { deref: vi.fn().mockReturnValue(undefined) },
129+
} as unknown as Task
130+
131+
const service = serviceWith("base-0")
132+
mockedGetCheckpointService.mockResolvedValue(service)
133+
134+
const outcome = await rollbackFile(task, "sha-1", "src/a.ts")
135+
136+
expect(outcome).toEqual({
137+
filePath: "src/a.ts",
138+
success: false,
139+
error: "Change journal is unavailable for this task",
140+
})
141+
expect(service.restoreFile).not.toHaveBeenCalled()
142+
})
143+
101144
it("fails cleanly when the file is not part of the given step checkpoint", async () => {
102145
await seedJournal([{ path: "src/a.ts", operation: "create", checkpointId: "sha-1" }])
103146
const service = serviceWith("base-0")
@@ -231,6 +274,28 @@ describe("rollbackStep (B3c: undo every file of the step)", () => {
231274
expect(service.restoreFile).toHaveBeenCalledTimes(1)
232275
})
233276

277+
it("rejects the stale file of a step while restoring the others", async () => {
278+
// src/a.ts was written again after this step's checkpoint, so its
279+
// sha-2 entry is no longer the file's latest: only src/b.ts (whose
280+
// latest entry IS sha-2) is restored.
281+
await seedJournal([
282+
{ path: "src/a.ts", operation: "create", checkpointId: "sha-1" },
283+
{ path: "src/a.ts", operation: "update", checkpointId: "sha-2" },
284+
{ path: "src/b.ts", operation: "create", checkpointId: "sha-2" },
285+
{ path: "src/a.ts", operation: "update", checkpointId: "sha-3" },
286+
])
287+
const service = serviceWith("base-0")
288+
mockedGetCheckpointService.mockResolvedValue(service)
289+
290+
const outcome = await rollbackStep(makeTask(), ["src/a.ts", "src/b.ts"], "sha-2")
291+
292+
expect(outcome.files[0].success).toBe(false)
293+
expect(outcome.files[0].error).toBe("File was modified in a later step; roll back the latest change card first")
294+
expect(outcome.files[1]).toEqual({ filePath: "src/b.ts", success: true })
295+
expect(service.restoreFile).toHaveBeenCalledTimes(1)
296+
expect(service.restoreFile).toHaveBeenCalledWith("base-0", "src/b.ts")
297+
})
298+
234299
it("falls back to the latest journal entry per file without a step checkpoint id", async () => {
235300
await seedJournal([
236301
{ path: "src/a.ts", operation: "create", checkpointId: "sha-1" },
@@ -258,8 +323,10 @@ describe("rollbackStep (B3c: undo every file of the step)", () => {
258323
expect(outcome.files[1].error).toBe("No change journal entry for this file")
259324
})
260325

261-
it("treats a missing global storage directory as an empty journal", async () => {
262-
// No context on the provider double → no journal location to read.
326+
it("fails per file when the journal location is unavailable (no global storage)", async () => {
327+
// No context on the provider double → the journal cannot even be
328+
// located. That is a failure, not an empty journal: reporting the
329+
// step as merely "not part of this checkpoint" would be misleading.
263330
const task = {
264331
taskId: "task-rollback",
265332
providerRef: { deref: vi.fn().mockReturnValue(undefined) },
@@ -272,7 +339,7 @@ describe("rollbackStep (B3c: undo every file of the step)", () => {
272339

273340
expect(outcome.checkpointId).toBe("sha-2")
274341
expect(outcome.files[0].success).toBe(false)
275-
expect(outcome.files[0].error).toBe("File is not part of this step's checkpoint")
342+
expect(outcome.files[0].error).toBe("Change journal is unavailable for this task")
276343
expect(service.restoreFile).not.toHaveBeenCalled()
277344
})
278345

@@ -315,6 +382,53 @@ describe("restoreLatestFile (B3c: forward direction)", () => {
315382
expect(service.restoreFile).not.toHaveBeenCalled()
316383
})
317384

385+
it("fails when the journal location is unavailable (no global storage)", async () => {
386+
// An unavailable journal is not "the task wrote nothing": a no-op
387+
// success would claim a restore that never happened.
388+
const task = {
389+
taskId: "task-rollback",
390+
providerRef: { deref: vi.fn().mockReturnValue(undefined) },
391+
} as unknown as Task
392+
393+
const service = serviceWith("base-0")
394+
mockedGetCheckpointService.mockResolvedValue(service)
395+
396+
const outcome = await restoreLatestFile(task, "src/a.ts")
397+
398+
expect(outcome).toEqual({
399+
filePath: "src/a.ts",
400+
success: false,
401+
error: "Change journal is unavailable for this task",
402+
})
403+
expect(service.restoreFile).not.toHaveBeenCalled()
404+
})
405+
406+
it("fails when the journal cannot be read (an I/O error is not an empty journal)", async () => {
407+
// A directory at the journal path makes readFile fail with EISDIR —
408+
// a stand-in for any permission or I/O failure (EACCES etc.).
409+
await fs.mkdir(journalPath(globalStorageDir, "task-rollback"), { recursive: true })
410+
const service = serviceWith("base-0")
411+
mockedGetCheckpointService.mockResolvedValue(service)
412+
413+
const outcome = await restoreLatestFile(makeTask(), "src/a.ts")
414+
415+
expect(outcome.success).toBe(false)
416+
expect(outcome.error).toContain("Change journal could not be read")
417+
expect(service.restoreFile).not.toHaveBeenCalled()
418+
})
419+
420+
it("stringifies a non-Error journal read failure into the outcome", async () => {
421+
vi.spyOn(changeJournal, "loadChanges").mockRejectedValueOnce("raw journal failure")
422+
const service = serviceWith("base-0")
423+
mockedGetCheckpointService.mockResolvedValue(service)
424+
425+
const outcome = await restoreLatestFile(makeTask(), "src/a.ts")
426+
427+
expect(outcome.success).toBe(false)
428+
expect(outcome.error).toBe("Change journal could not be read: raw journal failure")
429+
expect(service.restoreFile).not.toHaveBeenCalled()
430+
})
431+
318432
it("fails cleanly when checkpoints are not enabled", async () => {
319433
mockedGetCheckpointService.mockResolvedValue(undefined)
320434

‎src/core/checkpoints/changeJournal.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,17 +52,24 @@ export async function appendChange(globalStorageDir: string, taskId: string, ent
5252
*
5353
* Torn-tail repair: if the final line is truncated (JSON.parse fails), it is
5454
* silently discarded. The rest of the file is returned in order. An absent
55-
* or empty journal returns [].
55+
* or empty journal returns [] — but only an ABSENT file. Any other read
56+
* failure (permissions, I/O) is rethrown: a journal that cannot be read must
57+
* not be indistinguishable from one that is legitimately empty.
5658
*/
5759
export async function loadChanges(globalStorageDir: string, taskId: string): Promise<ChangeJournalEntry[]> {
5860
const filePath = journalPath(globalStorageDir, taskId)
5961

6062
let content: string
6163
try {
6264
content = await fs.readFile(filePath, "utf8")
63-
} catch {
64-
// File absent or unreadable → empty journal.
65-
return []
65+
} catch (error) {
66+
// A missing journal is a legitimate empty history; any other read
67+
// failure (permissions, I/O) must propagate. Swallowing it would let
68+
// a rollback report a no-op success without reading the history.
69+
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
70+
return []
71+
}
72+
throw error
6673
}
6774

6875
if (!content.trim()) {

‎src/core/checkpoints/rollback.ts‎

Lines changed: 76 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@
1616
* the content of its most recent recorded write (a successful no-op when
1717
* the task never wrote the file).
1818
*
19+
* A file is only rolled back from the card of its most recent step: undoing
20+
* an older step for a file that a later step wrote again would overwrite the
21+
* newer state, so such a rollback is rejected (a full checkpoint restore
22+
* still reaches any older state). A journal that cannot be located or read
23+
* fails the restore instead of masquerading as "the task wrote nothing".
24+
*
1925
* Restores reuse the existing shadow-git service (`getCheckpointService` →
2026
* `RepoPerTaskCheckpointService.restoreFile`, the same instance whose
2127
* `restoreCheckpoint` the checkpoints UI uses) — nothing is forked. Only the
@@ -45,17 +51,45 @@ const NOT_ENABLED_ERROR = "Checkpoints are not enabled for this task"
4551
const NO_TARGET_ERROR = "No checkpoint available to restore"
4652
const NOT_IN_STEP_ERROR = "File is not part of this step's checkpoint"
4753
const NO_ENTRY_ERROR = "No change journal entry for this file"
54+
const NO_JOURNAL_ERROR = "Change journal is unavailable for this task"
55+
const NOT_LATEST_ERROR = "File was modified in a later step; roll back the latest change card first"
4856

4957
type CheckpointService = NonNullable<Awaited<ReturnType<typeof getCheckpointService>>>
5058

51-
/**
52-
* Load the task's change journal. `loadChanges` never throws: an absent or
53-
* unreadable file and a torn tail resolve to the readable prefix (or `[]`).
54-
*/
55-
async function loadTaskEntries(task: Task): Promise<ChangeJournalEntry[]> {
59+
/** A readable journal (possibly legitimately empty) or the reason it could not be loaded. */
60+
type LoadedJournal = { entries: ChangeJournalEntry[] } | { error: string }
61+
62+
// `undefined` = the journal cannot be located (provider reference gone); read failures (permissions, I/O) propagate.
63+
async function loadTaskEntries(task: Task): Promise<ChangeJournalEntry[] | undefined> {
5664
const globalStorageDir = task.providerRef.deref()?.context.globalStorageUri.fsPath
5765

58-
return globalStorageDir ? loadChanges(globalStorageDir, task.taskId) : []
66+
return globalStorageDir ? loadChanges(globalStorageDir, task.taskId) : undefined
67+
}
68+
69+
// Single discriminated result for callers: a readable journal (possibly empty) or a failure.
70+
async function loadTaskJournal(task: Task): Promise<LoadedJournal> {
71+
try {
72+
const entries = await loadTaskEntries(task)
73+
74+
if (entries === undefined) {
75+
return { error: NO_JOURNAL_ERROR }
76+
}
77+
78+
return { entries }
79+
} catch (error) {
80+
const message = error instanceof Error ? error.message : String(error)
81+
return { error: `Change journal could not be read: ${message}` }
82+
}
83+
}
84+
85+
/** The most recent journal entry recorded for `filePath`, if any. */
86+
function latestEntry(entries: ChangeJournalEntry[], filePath: string): ChangeJournalEntry | undefined {
87+
for (let i = entries.length - 1; i >= 0; i--) {
88+
if (entries[i].path === filePath) {
89+
return entries[i]
90+
}
91+
}
92+
return undefined
5993
}
6094

6195
/**
@@ -74,6 +108,16 @@ function preStepRestoreTarget(
74108
if (stepIndex === -1) {
75109
return { error: NOT_IN_STEP_ERROR }
76110
}
111+
112+
// Only the file's most recent step may be rolled back: restoring an older
113+
// state would overwrite the file's newer writes. A multi-write step shares
114+
// one checkpoint id, so compare on the latest entry's checkpoint id.
115+
const latest = fileEntries[fileEntries.length - 1]
116+
117+
if (latest.checkpointId !== stepCheckpointId) {
118+
return { error: NOT_LATEST_ERROR }
119+
}
120+
77121
if (stepIndex === 0) {
78122
return { baseline: true }
79123
}
@@ -114,8 +158,13 @@ export async function rollbackFile(
114158
return { filePath, success: false, error: NOT_ENABLED_ERROR }
115159
}
116160

117-
const entries = await loadTaskEntries(task)
118-
const resolved = preStepRestoreTarget(entries, filePath, stepCheckpointId)
161+
const journal = await loadTaskJournal(task)
162+
163+
if ("error" in journal) {
164+
return { filePath, success: false, error: journal.error }
165+
}
166+
167+
const resolved = preStepRestoreTarget(journal.entries, filePath, stepCheckpointId)
119168

120169
if (resolved.error) {
121170
return { filePath, success: false, error: resolved.error }
@@ -153,9 +202,19 @@ export async function rollbackStep(
153202
}
154203
}
155204

156-
const entries = await loadTaskEntries(task)
205+
const journal = await loadTaskJournal(task)
157206
const files: RollbackFileOutcome[] = []
158207

208+
if ("error" in journal) {
209+
const journalError = journal.error
210+
return {
211+
checkpointId: stepCheckpointId,
212+
files: stepFiles.map((filePath) => ({ filePath, success: false, error: journalError })),
213+
}
214+
}
215+
216+
const entries = journal.entries
217+
159218
for (const filePath of stepFiles) {
160219
if (stepCheckpointId) {
161220
const resolved = preStepRestoreTarget(entries, filePath, stepCheckpointId)
@@ -176,7 +235,7 @@ export async function rollbackStep(
176235
continue
177236
}
178237

179-
const latest = [...entries].reverse().find((entry) => entry.path === filePath)
238+
const latest = latestEntry(entries, filePath)
180239

181240
if (!latest) {
182241
files.push({ filePath, success: false, error: NO_ENTRY_ERROR })
@@ -202,8 +261,13 @@ export async function restoreLatestFile(task: Task, filePath: string): Promise<R
202261
return { filePath, success: false, error: NOT_ENABLED_ERROR }
203262
}
204263

205-
const entries = await loadTaskEntries(task)
206-
const latest = [...entries].reverse().find((entry) => entry.path === filePath)
264+
const journal = await loadTaskJournal(task)
265+
266+
if ("error" in journal) {
267+
return { filePath, success: false, error: journal.error }
268+
}
269+
270+
const latest = latestEntry(journal.entries, filePath)
207271

208272
if (!latest) {
209273
return { filePath, success: true, noOp: true }

0 commit comments

Comments
 (0)