Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
a37dd24
feat(file-safety): atomic text publish primitive + safeWriteJson refa…
easonliang28 Aug 27, 2026
7fd49bc
chore(ci): empty commit — re-trigger CI and the CodeRabbit current-he…
easonliang28 Aug 30, 2026
744f3a3
merge(upstream): take main into the atomic publish unit
Oct 6, 2026
8f9cf8b
fix(file-safety): keep the target in place and track the DACL dump on…
Oct 6, 2026
14d26dc
fix(file-safety): narrow the DACL dump path before the restore call
Oct 6, 2026
df2694b
test(utils): bring the safeWriteJson backup tests onto the copy seman…
Oct 6, 2026
db3cc26
fix(file-safety): give each write its own DACL dump and assert the sa…
Oct 6, 2026
34b37ae
fix(file-safety): keep the unique DACL dump in the target directory
Oct 6, 2026
d3aec7c
test(file-safety): put the failure-path cases inside the describe tha…
Oct 6, 2026
8b838f3
fix(file-safety): close the staging symlink hole, surface unconfirmed…
Oct 6, 2026
e7843fb
test(file-safety): assert the icacls arguments and the staged file cl…
Oct 6, 2026
8e37bc1
fix(file-safety): re-create the staging directory if a concurrent wri…
Oct 6, 2026
99fee2c
fix(utils): stage the JSON temp with the target mode instead of the p…
Oct 6, 2026
febe20d
fix(utils): keep the staged JSON file owner-writable and surface non-…
Oct 6, 2026
e367bdb
fix(utils): key the safeWriteJson lock on the canonical publish target
Oct 6, 2026
5ce4613
test(file-safety): cover the staging-directory ownership rejection
Oct 6, 2026
964ec83
chore: trigger a fresh review pass at this head
Oct 7, 2026
ed72010
fix(file-safety): never discard a committed file, and cover the retry…
Oct 8, 2026
1a0430c
test(file-safety): wrap the fsync spy so the durability case type-checks
Oct 8, 2026
7470a19
fix(file-safety): keep the write-permission contract and follow dangl…
Oct 8, 2026
157946f
fix(file-safety): apply the target mode with fchmodSync on the staged…
Oct 8, 2026
41c1de3
test+fix(file-safety): pin the symlink-cycle guard and stop abandonin…
Oct 8, 2026
f65e913
test(editor): assert the write-permission guard is handed the absolut…
Oct 8, 2026
843176e
fix(file-safety): keep the backup when the DACL restore failed, and c…
Oct 8, 2026
4b2193c
fix(file-safety): remove a partially copied backup, and cover the fai…
Oct 8, 2026
4d45c87
fix(file-safety): fail closed when a Windows target's DACL cannot be …
Oct 8, 2026
aa85a3d
fix(file-safety): propagate a failed lstat in resolvePublishTarget, a…
Oct 8, 2026
4f0a85c
fix(file-safety): judge the DACL capture by its artifact on both call…
Oct 8, 2026
fa740b0
test(file-safety): make the target-probe propagation tests load-bearing
Oct 8, 2026
823a0e7
fix(file-safety): release a staging directory this call created, and …
Oct 8, 2026
568f981
test(file-safety): cover the parent-directory create/verify failures …
Oct 8, 2026
6df83d8
fix(file-safety): remove a partial backup after a successful publish,…
Oct 8, 2026
80de8fb
test(file-safety): cover the zero-byte icacls dump in the win32 DACL …
Oct 8, 2026
de893fa
fix(file-safety): classify staging-directory release errors instead o…
Oct 9, 2026
110f944
fix(file-safety): do not strand a staging directory when the post-cre…
Oct 9, 2026
56dad4d
test(file-safety): exercise safeWriteText against a real filesystem
Oct 9, 2026
4468ee7
test(file-safety): cover the win32 DACL restore retry that succeeds o…
Oct 9, 2026
65e6dc9
test(file-safety): cover the non-regular DACL dump branch
Oct 9, 2026
1a2c41b
fix(file-safety): retry the staging temp unlink instead of swallowing…
Oct 9, 2026
9159a87
Merge org main into the atomic-publish branch
Oct 10, 2026
30cefbb
style: bring the branch's own files to the repo's prettier output
Oct 10, 2026
64923c6
fix(file-safety): stop the icacls tree walk and the restore that cann…
easonLiangWorldedtech Oct 10, 2026
73a842a
fix(file-safety): keep the target's group when publishing over it
easonLiangWorldedtech Oct 10, 2026
1476e58
test(file-safety,editor): name the retained path, catch the dump, ass…
easonLiangWorldedtech Oct 10, 2026
e25d642
test(file-safety): assert the exact icacls count in the privilege-mem…
easonLiangWorldedtech Oct 10, 2026
796e412
feat(file-safety): report a lost DACL restore as DaclRestoreError aft…
Oct 11, 2026
d10554d
test(file-safety): make the DACL backup and leftover-temp assertions …
Oct 11, 2026
b98c07b
fix(file-safety): report a publish that ran with DACL restoration dis…
Oct 11, 2026
8c78c20
fix(file-safety): name the staging directory per write
Oct 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/eslint-suppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -1686,7 +1686,7 @@
},
"utils/__tests__/safeWriteJson.test.ts": {
"@typescript-eslint/no-explicit-any": {
"count": 27
"count": 26
}
},
"utils/__tests__/shell.spec.ts": {
Expand Down Expand Up @@ -1716,7 +1716,7 @@
},
"utils/safeWriteJson.ts": {
"@typescript-eslint/no-explicit-any": {
"count": 4
"count": 3
}
},
"utils/tts.ts": {
Expand Down
17 changes: 16 additions & 1 deletion src/integrations/editor/DiffViewProvider.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as vscode from "vscode"
import * as path from "path"
import * as fs from "fs/promises"
import { constants as fsConstants } from "fs"
import * as diff from "diff"
import stripBom from "strip-bom"
import delay from "delay"
Expand All @@ -18,6 +19,7 @@ import { arePathsEqual, getReadablePath } from "../../utils/path"
import { formatResponse } from "../../core/prompts/responses"
import { diagnosticsToProblemsString, getNewDiagnostics } from "../diagnostics"
import { Task } from "../../core/task/Task"
import { safeWriteText } from "../../services/file-safety/safeWriteText"

import { DecorationController } from "./DecorationController"

Expand Down Expand Up @@ -1156,7 +1158,20 @@ export class DiffViewProvider {

// Write the content directly to the file
await createDirectoriesForFile(absolutePath)
await fs.writeFile(absolutePath, content, "utf-8")
// safeWriteText publishes with rename, which only needs write permission on the
// DIRECTORY. The previous fs.writeFile required it on the file itself, so a target
// the user marked read-only used to fail with EACCES; keep that contract instead of
// silently renaming over it. A not-yet-existing target stays creatable.
try {
await fs.access(absolutePath, fsConstants.W_OK)
} catch (error: unknown) {
const code =
typeof error === "object" && error !== null && "code" in error
? (error as { code?: string }).code
: undefined
if (code !== "ENOENT") throw error
}
await safeWriteText(absolutePath, content)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Comment thread
coderabbitai[bot] marked this conversation as resolved.

// Open the document to ensure diagnostics are loaded
// When openFile is false (PREVENT_FOCUS_DISRUPTION enabled), we only open in memory
Expand Down
114 changes: 105 additions & 9 deletions src/integrations/editor/__tests__/DiffViewProvider.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,22 @@ vi.mock("fs/promises", () => ({
readFile: vi.fn().mockResolvedValue("file content"),
writeFile: vi.fn().mockResolvedValue(undefined),
access: vi.fn().mockResolvedValue(undefined),
mkdir: vi.fn().mockResolvedValue(undefined),
rename: vi.fn().mockResolvedValue(undefined),
unlink: vi.fn().mockResolvedValue(undefined),
}))

// Mock safeWriteText (used by saveDirectly). The real module's error classes stay
// available through importOriginal, so a test can hand the caller an actual
// DaclRestoreError instead of a look-alike.
vi.mock("../../../services/file-safety/safeWriteText", async (importOriginal) => {
const actual = await importOriginal<typeof import("../../../services/file-safety/safeWriteText")>()
return {
...actual,
safeWriteText: vi.fn().mockResolvedValue(undefined),
}
})

// Mock utils
vi.mock("../../../utils/fs", () => ({
createDirectoriesForFile: vi.fn().mockResolvedValue([]),
Expand All @@ -27,6 +41,8 @@ vi.mock("../../../utils/fs", () => ({
vi.mock("path", () => ({
resolve: vi.fn((cwd, relPath) => `${cwd}/${relPath}`),
basename: vi.fn((path) => path.split("/").pop()),
dirname: vi.fn((path) => path.split("/").slice(0, -1).join("/") || "/"),
join: (...args: string[]) => args.join("/"),
}))

// Mock vscode
Expand Down Expand Up @@ -780,6 +796,86 @@ describe("DiffViewProvider", () => {
})

describe("saveDirectly method", () => {
it("rejects a save over a read-only target instead of renaming onto it", async () => {
const fs = await import("fs/promises")
const { safeWriteText } = await import("../../../services/file-safety/safeWriteText")
vi.mocked(safeWriteText).mockClear()
const eacces = Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" })
vi.mocked(fs.access).mockRejectedValueOnce(eacces)

await expect(diffViewProvider.saveDirectly("test.ts", "new content", true, true, 200)).rejects.toThrow(
"EACCES",
)

// The old fs.writeFile path failed the same way; safeWriteText must not run.
expect(safeWriteText).not.toHaveBeenCalled()
vi.mocked(fs.access).mockResolvedValue(undefined)
})

it("still writes when the target does not exist yet", async () => {
const fs = await import("fs/promises")
const { safeWriteText } = await import("../../../services/file-safety/safeWriteText")
vi.mocked(safeWriteText).mockClear()
vi.mocked(fs.access).mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" }))

const result = await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 200)

expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content")
// Call counts alone would still pass if the publish ran but the caller reported
// nothing about the content it wrote.
expect(result.finalContent).toBe("new content")
expect(result.userEdits).toBeUndefined()
vi.mocked(fs.access).mockResolvedValue(undefined)
})

it("checks write permission on the absolute target before publishing", async () => {
const fs = await import("fs/promises")
const { safeWriteText } = await import("../../../services/file-safety/safeWriteText")
vi.mocked(safeWriteText).mockClear()
vi.mocked(fs.access).mockClear()

await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 200)

// safeWriteText publishes with rename, which only needs write permission on the
// DIRECTORY. The contract this unit preserves requires it on the FILE, so the guard
// must be handed the absolute target - not the relative path the caller passed.
const calls = vi.mocked(fs.access).mock.calls
const accessIndex = calls.findIndex((call) => String(call[0]).endsWith("test.ts"))
expect(accessIndex).toBeGreaterThanOrEqual(0)
expect(calls[accessIndex][0]).toBe(`${mockCwd}/test.ts`)

// An existence-only check would not catch a read-only target: the guard has to be handed
// the write bit, otherwise the read-only contract this unit preserves is silently gone.
const { constants } = await import("fs")
expect(calls[accessIndex][1]).toBe(constants.W_OK)

// The check is only meaningful before the publish; after it, an EACCES target would
// already have been renamed over.
expect(vi.mocked(fs.access).mock.invocationCallOrder[accessIndex]).toBeLessThan(
vi.mocked(safeWriteText).mock.invocationCallOrder[0],
)
})

it("surfaces a failed DACL restore as a rejection instead of a completed save", async () => {
const { DaclRestoreError, safeWriteText } = await import("../../../services/file-safety/safeWriteText")
vi.mocked(safeWriteText).mockClear()
// The primitive reports a lost DACL after the commit rename as DaclRestoreError.
// The direct-save path must not swallow it: a caller that sees saveDirectly
// resolve would report a save whose access rights silently changed.
vi.mocked(safeWriteText).mockRejectedValueOnce(new DaclRestoreError(`${mockCwd}/test.ts`, null))

await expect(
diffViewProvider.saveDirectly("test.ts", "new content", true, true, 200),
).rejects.toBeInstanceOf(DaclRestoreError)

// The rejection is the primitive's own - the publish was attempted exactly once,
// not retried into a success the caller could observe.
const publishCalls = vi.mocked(safeWriteText).mock.calls.filter(function (call) {
return call[0] === `${mockCwd}/test.ts`
})
expect(publishCalls).toHaveLength(1)
})

beforeEach(() => {
// Mock vscode functions
vi.mocked(vscode.window.showTextDocument).mockResolvedValue({} as any)
Expand All @@ -792,9 +888,9 @@ describe("DiffViewProvider", () => {

const result = await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 2000)

// Verify file was written
const fs = await import("fs/promises")
expect(fs.writeFile).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", "utf-8")
// Verify file was written via safeWriteText
const { safeWriteText } = await import("../../../services/file-safety/safeWriteText")
expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content")

// Verify file was opened without focus
expect(vscode.window.showTextDocument).toHaveBeenCalledWith(
Expand All @@ -815,9 +911,9 @@ describe("DiffViewProvider", () => {
it("should not open file when openWithoutFocus is false", async () => {
await diffViewProvider.saveDirectly("test.ts", "new content", false, true, 1000)

// Verify file was written
const fs = await import("fs/promises")
expect(fs.writeFile).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", "utf-8")
// Verify file was written via safeWriteText
const { safeWriteText } = await import("../../../services/file-safety/safeWriteText")
expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content")

// Verify file was NOT opened
expect(vscode.window.showTextDocument).not.toHaveBeenCalled()
Expand All @@ -830,9 +926,9 @@ describe("DiffViewProvider", () => {

await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 1000)

// Verify file was written
const fs = await import("fs/promises")
expect(fs.writeFile).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", "utf-8")
// Verify file was written via safeWriteText
const { safeWriteText } = await import("../../../services/file-safety/safeWriteText")
expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content")

// Verify delay was NOT called
expect(mockDelay).not.toHaveBeenCalled()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import fsSync from "node:fs"
import os from "node:os"
import path from "node:path"

import { safeWriteText } from "../safeWriteText"

/**
* Every other suite in this directory mocks fs/promises and fs, so nothing there proves the real
* open/write/fsync/rename sequence produces a file on disk. This suite uses a real temporary
* directory and no mocks at all: it asserts the outcome (bytes on disk) and the absence of residue
* (staging directory, temp file, backup).
*/
describe("safeWriteText against a real filesystem", () => {
let dir: string

beforeEach(() => {
dir = fsSync.mkdtempSync(path.join(os.tmpdir(), "safe-write-it-"))
})

afterEach(() => {
fsSync.rmSync(dir, { recursive: true, force: true })
})

function _leftovers(): string[] {
return (
fsSync
.readdirSync(dir)
// The Windows DACL dump is written next to the target and only ever shows up on the
// windows-latest run, so a filter that misses it lets a leaked dump pass a suite
// whose claim is the absence of residue.
.filter(function (name) {
return (
name.includes(".file-safety-staging") ||
name.includes(".new_") ||
name.includes(".bak") ||
name.includes(".acl.tmp")
)
})
)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

it("creates a new file with the requested bytes and leaves no residue", async () => {
const target = path.join(dir, "brand-new.txt")

await safeWriteText(target, "first content")

expect(fsSync.readFileSync(target, "utf8")).toBe("first content")
expect(_leftovers()).toEqual([])
})

it("replaces an existing file and leaves no residue", async () => {
const target = path.join(dir, "existing.txt")
fsSync.writeFileSync(target, "old")

await safeWriteText(target, "replacement")

expect(fsSync.readFileSync(target, "utf8")).toBe("replacement")
expect(_leftovers()).toEqual([])
})
})
Loading
Loading