Skip to content

Commit 5dd5ce9

Browse files
u7 tool-wiring: re-land this line's ground under the trunk lock spelling
The ported chain replayed onto the trunk acquisition spelling (acquireFileLock(absoluteFilePath)) but kept the helpers, guards and test ground that were keyed on the retired resolveLockKey spelling, so the chain did not type-check: fifty five lines across six files. This commit re-lands that ground under the trunk spelling, keeps the trunk text at the contested hunks, and names what the port dropped instead of counting it as a saving. - safeWriteJson.ts: confinement, the confineTo option, the drift guard, the lock-artefact and staging-directory probes, the backup-path variable and the rollback block stay; the lock key is the path the caller gives and the guards measure against it. - applyDiffTool, guardedWrite, jsonFileRecovery, DiffViewProvider.spec: imports and double ground this line owns are restored; the duplicated Task import is removed. - safeWriteJson.test.ts: the confinement rows come back; the two rows that pinned the referent lock key are dropped with the retired spelling and named in place. - applyDiffTool.outsideWorkspace.spec.ts stays the trunk blob: the outside-workspace spec this line carried is a cost of the re-land, not a saving. Gates run in the worktree: prettier --check over the carried files exit 0; eslint --prune-suppressions --max-warnings=0 over them exit 0 with no suppression entry moved; tsc --noEmit in src exit 0 (was 55 error lines); root tsc -p tsconfig.json --noEmit exit 0; turbo run check-types exit 0 across 13 packages.
1 parent 3807c8a commit 5dd5ce9

6 files changed

Lines changed: 528 additions & 25 deletions

File tree

‎src/core/tools/ApplyDiffTool.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { TelemetryService } from "@roo-code/telemetry"
66

77
import { getReadablePath } from "../../utils/path"
88
import { isPathOutsideWorkspace } from "../../utils/pathUtils"
9+
import { versionTokenOfStat } from "../../utils/versionToken"
910
import { Task } from "../task/Task"
1011
import { formatResponse } from "../prompts/responses"
1112
import { fileExistsAtPath } from "../../utils/fs"

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1305,7 +1305,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
13051305
// is already gone.
13061306
const task = createMockTask()
13071307
mockedWithFileLock.mockImplementation(function (filePath, operation) {
1308-
task.abort = true
1308+
;(task as { abort: boolean }).abort = true // Task.abort is a getter; the double holds a plain field
13091309
return operation(path.resolve(filePath))
13101310
})
13111311
mockedFsAccess.mockRejectedValue({ code: "ENOENT" })
@@ -1321,7 +1321,7 @@ describe("guardedWrite (S4a, epic #1375)", () => {
13211321
// The abort lands while the version token is being computed. The guard has to
13221322
// refuse on the way to the publish, not write for a task that is already gone.
13231323
mockedComputeVersionToken.mockImplementation(async () => {
1324-
task.abort = true
1324+
;(task as { abort: boolean }).abort = true // Task.abort is a getter; the double holds a plain field
13251325
return "v1"
13261326
})
13271327
const reg = new ObservationRegistry()

‎src/integrations/editor/__tests__/DiffViewProvider.spec.ts‎

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1-
import { DiffViewProvider, DIFF_VIEW_URI_SCHEME, DIFF_VIEW_LABEL_CHANGES } from "../DiffViewProvider"
1+
import {
2+
CommittedWriteBufferConflictError,
3+
DiffViewProvider,
4+
DIFF_VIEW_URI_SCHEME,
5+
DIFF_VIEW_LABEL_CHANGES,
6+
} from "../DiffViewProvider"
27
import { DecorationController } from "../DecorationController"
3-
import type { Task } from "../../../core/task/Task"
48
import type { Mock } from "vitest"
59
import * as vscode from "vscode"
610
import * as path from "path"
@@ -285,13 +289,17 @@ describe("DiffViewProvider", () => {
285289

286290
// Create a mock Task instance; the double provides providerRef.deref() ->
287291
// getState() with provider settings (see makeTaskDouble below).
288-
mockTask = makeTaskDouble({
289-
// Auto-closing edited tabs is opt-in by default; the legacy
290-
// "close/keep behavior" suite below asserts the close path, so
291-
// enable it here. The opt-in default itself is covered by the
292-
// dedicated "auto-close settings decision table" suite.
293-
autoCloseZooOpenedFiles: true,
294-
})
292+
mockTask = {
293+
...makeTaskDouble({
294+
// Auto-closing edited tabs is opt-in by default; the legacy
295+
// "close/keep behavior" suite below asserts the close path, so
296+
// enable it here. The opt-in default itself is covered by the
297+
// dedicated "auto-close settings decision table" suite.
298+
autoCloseZooOpenedFiles: true,
299+
}),
300+
cwd: mockCwd,
301+
observationRegistry: new ObservationRegistry(),
302+
} as unknown as Task // the double is partial; cast matches makeTaskDouble's own
295303

296304
diffViewProvider = new DiffViewProvider(mockCwd, mockTask)
297305
// Mock the necessary properties and methods
@@ -5182,7 +5190,19 @@ describe("DiffViewProvider", () => {
51825190
})
51835191

51845192
const setupProvider = (stateOverrides: Record<string, unknown> = {}) => {
5185-
const provider = new DiffViewProvider(mockCwd, makeTaskDouble(stateOverrides))
5193+
const task = {
5194+
...makeTaskDouble(stateOverrides),
5195+
cwd: mockCwd,
5196+
// S4b follow-up (#44): saveChanges publishes through the guarded write,
5197+
// which resolves the path against task.cwd and consults the task's
5198+
// observation registry - both must be present on this suite's mock task.
5199+
observationRegistry: new ObservationRegistry(),
5200+
} as unknown as Task // the double is partial; cast matches makeTaskDouble's own
5201+
const provider = new DiffViewProvider(mockCwd, task)
5202+
// The preview observation + matching version token let the guarded save
5203+
// proceed so these tests stay focused on the auto-close decision table.
5204+
task.observationRegistry.observe(`${mockTargetPath}`, "v1")
5205+
vi.mocked(computeVersionToken).mockResolvedValue("v1")
51865206
provider["relPath"] = "auto-close-test.ts"
51875207
provider["newContent"] = "content"
51885208
provider["activeDiffEditor"] = buildActiveDiffEditor()

‎src/utils/__tests__/jsonFileRecovery.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import * as fsSync from "fs"
66
import { acquireFileLock } from "../fileLock"
77
import { setPersistenceTraceSink } from "../../core/task-persistence/persistenceTrace"
88
import { recoverInterruptedReplacement, deleteJsonFile, recoverMissingJsonFile } from "../jsonFileRecovery"
9+
import { LockKeyWalkIncompleteError, resolveLockKey } from "../../services/file-safety/safeWriteText"
910
import { readFileWithMissingRetry } from "../../core/task-persistence/readFileWithMissingRetry"
1011

1112
vi.mock("fs/promises", async () => {

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

Lines changed: 271 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1043,4 +1043,275 @@ describe("safeWriteJson", () => {
10431043
const content = await readFileContent(currentTestFilePath)
10441044
expect(content).toEqual(newData)
10451045
})
1046+
// (dropped with the retired spelling: "acquires the lock on the resolved referent, not the caller
1047+
// alias" and "resolves the real proper-lockfile after the capture above is undone", the pair that
1048+
// pinned the lock key as the symlink referent. The chain now takes the lock on the path the caller
1049+
// gives, as trunk spells it, so those two rows describe a spelling this tree no longer carries.)
1050+
1051+
// The undo in the case above has to be visible from the other side of the file: a later
1052+
// test that imports proper-lockfile fresh must resolve the real module, not the wrapper
1053+
// that case installed for its own import graph. This is the case that reddens when the
1054+
// undo is written as vi.unmock -- Vitest hoists that call above the imports, so it is
1055+
// registered before the vi.doMock above runs, the wrapper is never removed, and it is
1056+
// what a later import resolves.
1057+
test("resolves the real proper-lockfile after the capture above is undone", async () => {
1058+
vi.resetModules()
1059+
const realLockfile = await vi.importActual<typeof import("proper-lockfile")>("proper-lockfile")
1060+
const imported = await import("proper-lockfile")
1061+
1062+
expect(imported.lock).toBe(realLockfile.lock)
1063+
expect(vi.isMockFunction(imported.lock)).toBe(false)
1064+
})
1065+
1066+
test("rejects a confined write whose target is outside the confined directory", async () => {
1067+
const scope = path.join(tempDir, "project")
1068+
await fs.mkdir(scope)
1069+
const outside = path.join(tempDir, "elsewhere.json")
1070+
1071+
// No symlink needed: the check runs on the resolved publish target, so an
1072+
// out-of-scope path is rejected on every platform, and it is rejected before the
1073+
// lock is taken and before anything is staged.
1074+
await expect(safeWriteJson(outside, { mcpServers: {} }, { confineTo: scope })).rejects.toThrow(
1075+
ConfinedPathEscapeError,
1076+
)
1077+
1078+
const left = await fs.readdir(tempDir)
1079+
expect(left).not.toContain("elsewhere.json")
1080+
expect(left.filter((entry) => entry.includes(".new_") || entry.endsWith(".lock"))).toEqual([])
1081+
})
1082+
1083+
test("treats an empty confineTo as a declared scope rather than as no scope", async () => {
1084+
const cwd = process.cwd()
1085+
// An empty string is a scope declaration: _resolveScopeRoot runs it through
1086+
// path.resolve, which yields the process working directory. The temp target has
1087+
// to sit outside that directory for this test to be about the scope rather than
1088+
// about where the temp files happen to live, so the precondition is asserted.
1089+
const outside = path.join(tempDir, "empty-scope.json")
1090+
expect(path.resolve(outside).startsWith(cwd + path.sep)).toBe(false)
1091+
expect(path.resolve(outside)).not.toBe(cwd)
1092+
1093+
await expect(safeWriteJson(outside, { mcpServers: {} }, { confineTo: "" })).rejects.toBeInstanceOf(
1094+
ConfinedPathEscapeError,
1095+
)
1096+
1097+
// Rejected the way every other confinement rejection is: nothing written.
1098+
expect(await fs.readdir(tempDir)).not.toContain("empty-scope.json")
1099+
})
1100+
1101+
test("rejects an in-scope dangling symlink to an outside referent before the advisory lock", async () => {
1102+
// The fixture needs a dangling link, and the two platforms build that shape
1103+
// differently: an unprivileged Windows cannot create a file or directory symlink
1104+
// at all (EPERM), while a junction needs no privilege, resolves through Node's
1105+
// reparse handling and reports as a symbolic link to a path that does not exist -
1106+
// the same lstat/realpath pair the POSIX file symlink produces. lstat of the
1107+
// junction here reports isSymbolicLink true and realpath reports ENOENT, which is
1108+
// the branch resolvePublishTarget and the lock-key walk take on either platform,
1109+
// so the row runs everywhere instead of only where a file link is permitted.
1110+
const projectDir = path.join(tempDir, "dangling-scope")
1111+
await fs.mkdir(projectDir)
1112+
const outsideDir = path.join(tempDir, "dangling-outside")
1113+
await fs.mkdir(outsideDir)
1114+
const link = path.join(projectDir, "link.json")
1115+
// junction on win32, file symlink elsewhere; the type is what makes the same
1116+
// dangling-link shape buildable on both lanes.
1117+
const linkType: "junction" | "file" = process.platform === "win32" ? "junction" : "file"
1118+
await fs.symlink(path.join(outsideDir, "gone.json"), link, linkType)
1119+
1120+
const realLockfile = await vi.importActual<typeof import("proper-lockfile")>("proper-lockfile")
1121+
const lockCalls: string[] = []
1122+
const lockMock = vi.fn(async (file: unknown, options?: unknown) => {
1123+
lockCalls.push(String(file))
1124+
return realLockfile.lock(file as never, options as never)
1125+
})
1126+
vi.doMock("proper-lockfile", () => ({
1127+
...realLockfile,
1128+
lock: lockMock as unknown as typeof realLockfile.lock,
1129+
}))
1130+
1131+
vi.resetModules()
1132+
const { safeWriteJson: reimported, ConfinedPathEscapeError: ReimportedError } = await import("../safeWriteJson")
1133+
1134+
try {
1135+
const outcome = await reimported(link, { mcpServers: {} }, { confineTo: projectDir }).then(
1136+
function (value: unknown) {
1137+
return { ok: true as const, value: value, error: undefined as unknown }
1138+
},
1139+
function (error: unknown) {
1140+
return { ok: false as const, value: undefined as unknown, error: error }
1141+
},
1142+
)
1143+
// A dangling link resolves to its referent for the lock key, and the referent
1144+
// is outside the declared scope, so the second confinement check rejects
1145+
// before the lock file - which proper-lockfile writes NEXT TO the key - is
1146+
// ever attempted. Asserted first, because the point of the row is the
1147+
// ordering: a rejection that arrives after a lock is a rejection that already
1148+
// wrote outside the scope.
1149+
expect(lockCalls).toEqual([])
1150+
expect(outcome.ok).toBe(false)
1151+
expect(outcome.error).toBeInstanceOf(ReimportedError)
1152+
expect(
1153+
(await fs.readdir(outsideDir)).filter(function (entry: string) {
1154+
return entry.endsWith(".lock")
1155+
}),
1156+
).toEqual([])
1157+
expect(
1158+
(await fs.readdir(projectDir)).filter(function (entry: string) {
1159+
return entry.endsWith(".lock")
1160+
}),
1161+
).toEqual([])
1162+
expect((await fs.readdir(projectDir)).sort()).toEqual(["link.json"])
1163+
} finally {
1164+
vi.doUnmock("proper-lockfile")
1165+
vi.resetModules()
1166+
}
1167+
})
1168+
1169+
test("rejects an out-of-scope target before the advisory lock is taken", async () => {
1170+
const projectDir = path.join(tempDir, "scope")
1171+
await fs.mkdir(projectDir)
1172+
const outside = path.join(tempDir, "elsewhere.json")
1173+
1174+
// Capture every lock attempt without changing how locking works. The lock file
1175+
// lives NEXT TO the key, so taking the lock on an out-of-scope referent already
1176+
// writes outside the scope the caller declared - and an unwritable directory
1177+
// there would surface a lock error instead of the confinement verdict.
1178+
const realLockfile = await vi.importActual<typeof import("proper-lockfile")>("proper-lockfile")
1179+
const lockCalls: string[] = []
1180+
const lockMock = vi.fn(async (file: unknown, options?: unknown) => {
1181+
lockCalls.push(String(file))
1182+
return realLockfile.lock(file as never, options as never)
1183+
})
1184+
vi.doMock("proper-lockfile", () => ({
1185+
...realLockfile,
1186+
lock: lockMock as unknown as typeof realLockfile.lock,
1187+
}))
1188+
1189+
// Re-import the whole graph so the SUT AND its fileLock dependency pick up the
1190+
// wrapped lock; without the reset, fileLock keeps the already-loaded real
1191+
// proper-lockfile and the capture never sees a call. The error class is taken from
1192+
// the same module instance the SUT came from.
1193+
vi.resetModules()
1194+
const { safeWriteJson: reimported, ConfinedPathEscapeError: ReimportedError } = await import("../safeWriteJson")
1195+
1196+
try {
1197+
await expect(reimported(outside, { mcpServers: {} }, { confineTo: projectDir })).rejects.toThrow(
1198+
ReimportedError,
1199+
)
1200+
1201+
// The confinement verdict came first: no lock was ever attempted.
1202+
expect(lockCalls).toEqual([])
1203+
expect(
1204+
(await fs.readdir(tempDir)).filter(function (entry: string) {
1205+
return entry.endsWith(".lock")
1206+
}),
1207+
).toEqual([])
1208+
} finally {
1209+
vi.doUnmock("proper-lockfile")
1210+
vi.resetModules()
1211+
}
1212+
})
1213+
1214+
test("rejects an out-of-scope target before creating any directory", async () => {
1215+
const projectDir = path.join(tempDir, "scope")
1216+
await fs.mkdir(projectDir)
1217+
// The target lives in a directory that does not exist. A confinement check that runs
1218+
// after the mkdir -p would create that directory OUTSIDE the declared scope first -
1219+
// the same side effect the pre-lock check exists to prevent, reached through a
1220+
// symlinked ancestor in the reported case - and an unwritable referent would surface
1221+
// the mkdir error instead of the confinement verdict.
1222+
const missingParent = path.join(tempDir, "no-such-dir")
1223+
const outside = path.join(missingParent, "elsewhere.json")
1224+
1225+
await expect(safeWriteJson(outside, { mcpServers: {} }, { confineTo: projectDir })).rejects.toThrow(
1226+
ConfinedPathEscapeError,
1227+
)
1228+
1229+
// Nothing was created outside the scope, and no lock was attempted there.
1230+
expect(fsSyncActual.existsSync(missingParent)).toBe(false)
1231+
expect(
1232+
(await fs.readdir(tempDir)).filter(function (entry: string) {
1233+
return entry.endsWith(".lock")
1234+
}),
1235+
).toEqual([])
1236+
})
1237+
1238+
test.skipIf(process.platform === "win32")(
1239+
"rejects a confined write whose symlink resolves outside the confined directory",
1240+
async () => {
1241+
const projectDir = path.join(tempDir, "project")
1242+
await fs.mkdir(projectDir)
1243+
const outside = path.join(tempDir, "outside.json")
1244+
await fsSyncActual.promises.writeFile(outside, JSON.stringify({ secret: "original" }), "utf8")
1245+
// A repository that plants its project settings file as a link to somewhere else
1246+
// must not receive the settings write at the linked path. The caller picked
1247+
// projectDir/mcp.json from the workspace, so it declares that scope.
1248+
const projectConfig = path.join(projectDir, "mcp.json")
1249+
await fs.symlink(outside, projectConfig)
1250+
1251+
await expect(safeWriteJson(projectConfig, { mcpServers: {} }, { confineTo: projectDir })).rejects.toThrow(
1252+
ConfinedPathEscapeError,
1253+
)
1254+
1255+
// The linked file is untouched and nothing was staged beside it.
1256+
expect(JSON.parse(await fsSyncActual.promises.readFile(outside, "utf8"))).toEqual({ secret: "original" })
1257+
const entries = await fs.readdir(tempDir)
1258+
expect(entries).toContain("outside.json")
1259+
expect(
1260+
entries.filter(
1261+
(entry) => entry.includes(".new_") || entry.includes("safeWriteText") || entry.endsWith(".lock"),
1262+
),
1263+
).toEqual([])
1264+
},
1265+
)
1266+
1267+
test.skipIf(process.platform === "win32")(
1268+
"publishes over a symlink referent that stays inside the confined directory",
1269+
async () => {
1270+
const projectDir = path.join(tempDir, "project-in")
1271+
await fs.mkdir(projectDir)
1272+
const referent = path.join(projectDir, "real-mcp.json")
1273+
await fsSyncActual.promises.writeFile(referent, JSON.stringify({ mcpServers: {} }), "utf8")
1274+
const alias = path.join(projectDir, "mcp.json")
1275+
await fs.symlink(referent, alias)
1276+
1277+
// Confining is about the scope, not about forbidding links: the write lands at
1278+
// the path the caller named. Main's body renames to that path and replaces the
1279+
// link node in place -- the alias becomes a regular file holding the payload and
1280+
// the old referent keeps the seed, matching the lock-referent test's contract.
1281+
await safeWriteJson(
1282+
alias,
1283+
{ mcpServers: { local: { url: "http://localhost" } } },
1284+
{ confineTo: projectDir },
1285+
)
1286+
1287+
expect(JSON.parse(await fsSyncActual.promises.readFile(alias, "utf8"))).toEqual({
1288+
mcpServers: { local: { url: "http://localhost" } },
1289+
})
1290+
expect(JSON.parse(await fsSyncActual.promises.readFile(referent, "utf8"))).toEqual({ mcpServers: {} })
1291+
expect(fsSyncActual.lstatSync(alias).isFile()).toBe(true)
1292+
},
1293+
)
1294+
1295+
test.skipIf(process.platform === "win32")(
1296+
"confines a scope path that itself runs through a symlink and does not exist yet",
1297+
async () => {
1298+
const real = path.join(tempDir, "real-project")
1299+
await fs.mkdir(real)
1300+
const alias = path.join(tempDir, "alias-project")
1301+
await fs.symlink(real, alias)
1302+
// The scope is declared through the alias, and the directory it names does not
1303+
// exist yet. Resolving it lexically would compare an unresolved scope against a
1304+
// fully resolved target and reject a write that is in fact inside the project -
1305+
// the macOS /var -> /private/var shape. The nearest existing ancestor is resolved
1306+
// and the remainder re-joined instead.
1307+
const nested = path.join(alias, "nested")
1308+
const target = path.join(nested, "mcp.json")
1309+
1310+
await safeWriteJson(target, { mcpServers: {} }, { confineTo: nested })
1311+
1312+
expect(
1313+
JSON.parse(await fsSyncActual.promises.readFile(path.join(real, "nested", "mcp.json"), "utf8")),
1314+
).toEqual({ mcpServers: {} })
1315+
},
1316+
)
10461317
})

0 commit comments

Comments
 (0)