Skip to content

Commit e36a779

Browse files
committed
fix(tools,diff-view): decide adoption from the owned placeholder, and bind a relative alias to the workspace
A create session whose pre-open snapshot was a partial read lost adoption (CR thread 4474468493, minor). f95c7b4 gated the create-placeholder exception inside the null branch, so the completeness check still ran first for a session whose preOpenObservation describes a file that was already gone: the model read a slice, the file was removed, open() took the create path and replaced the registry entry with the verified empty placeholder marked complete, Auto Save wrote the accepted bytes, the guard rejected with GuardStaleVersionError (the completeness gate never ran, because the registry holds the complete placeholder observation), and adoption was refused - a failure reported for a new file that already held the accepted bytes, with no cleanup able to unlink a file that is no longer the empty placeholder. Ownership is now decided first: a session that owns its placeholder adopts iff the rejection is the moved compare-and-swap token, and the refusals apply to the sessions that do not own one. Same reason gate as before; two consequences, both fail-closed: a create session whose rejection is not the moved token now refuses even for an edit kind or with no snapshot at all, which previously fell through to adoption. - control: previous head's ordering restored -> 2 failed | 184 passed (186), the two failures being the new trigger test and its predicate pin, "expected false to be true"; ownership branch ungated -> 2 failed | 184 passed on the two not-a-moved-token pins, "expected true to be false". Both mutants reverted byte-identically. - new tests: the thread's trigger through saveChanges() (partial read -> file removed -> create -> Auto Save -> accept resolves, unlinks nothing, observation moves to the version on disk) and the predicate pin for the same combination. Containment for a relative alias that canonicalizes outside the workspace (panel Security Boundaries, third wording). A different objection from the one f95c7b4 answered: that row was the lexical fallback when realpath failed; this one is that an alias which canonicalizes OUTSIDE - the ordinary shape is a link directory inside the workspace whose referent is elsewhere - is read by the containment clause as an intentional outside-workspace write, because the clause only binds the retained target when the alias looks inside. For a path the caller named relative to task.cwd that is not an authorization: the spelling is workspace-scoped, so the alias's own containment is now checked and fails closed, naming the reconstructed canonical path the model has to re-read. An absolute caller path keeps its own authorization and still publishes to an outside referent, which is what the tool layer approved. - control: fail-closed check removed -> 1 failed | 77 passed (78), the escaping-alias test resolves instead of rejecting ("promise resolved \"'v1'\" instead of rejecting") - the bypass, reproduced; the reconstruction joined without reverse() -> 1 failed | 77 passed, the rejection named the components in the wrong order. Coverage for multi-component ancestor reconstruction (CR thread 4474468483, trivial): rejection when only the canonical workspace root resolves and a retained target sits outside it, acceptance for a retained target under the reconstructed canonicalRoot/sub/deeper/new-file.txt, and the outside-referent case above, which is what actually pins the ordered re-join. Gates (split-1833/u8, verified real node_modules): tsc --noEmit 0; eslint --prune-suppressions --max-warnings=0 clean on all four touched files with src/eslint-suppressions.json unchanged from HEAD (the prune rewrites only line order and endings - 1452 lines, identical sorted content - and HEAD's bytes were restored); prettier --check clean; DiffViewProvider.spec 186, guardedWrite.spec 78, Task dispose/observationRegistry/throttle 34. Mutation coverage still absent: the branch is over the 500 changed-executable-line cap, so these carry negative controls only.
1 parent f95c7b4 commit e36a779

4 files changed

Lines changed: 199 additions & 29 deletions

File tree

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

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1223,6 +1223,119 @@ describe("guardedWrite (S4a, epic #1375)", () => {
12231223
expect(mockedSafeWriteText).not.toHaveBeenCalled()
12241224
})
12251225

1226+
it("guardedWrite reconstructs several missing components below the resolving root", async () => {
1227+
// Only the workspace root resolves here: sub and deeper are part of the path this write is
1228+
// creating, so the reconstruction has to re-join them in order below the canonical root. A
1229+
// retained target outside that root still trips containment, which is the outcome the alias
1230+
// canonicalization exists to make decidable at all.
1231+
const reg = new ObservationRegistry()
1232+
const workspaceRoot = path.resolve(WORKSPACE)
1233+
const canonicalRoot = path.resolve("/private/workspace")
1234+
const rel = path.join("sub", "deeper", "new-file.txt")
1235+
reg.observe(path.resolve(workspaceRoot, rel), "v1", true)
1236+
const task = createMockTask({ observationRegistry: reg })
1237+
mockedFsAccess.mockResolvedValue(undefined)
1238+
mockedComputeVersionToken.mockResolvedValue("v1")
1239+
mockedResolvePublishTarget.mockResolvedValue(path.resolve("/outside/workspace/secret.txt"))
1240+
vi.mocked(fs.realpath).mockImplementation(async (value) => {
1241+
const key = path.resolve(String(value))
1242+
if (key === workspaceRoot) {
1243+
return canonicalRoot
1244+
}
1245+
throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
1246+
})
1247+
1248+
await expect(guardedWrite(task, rel, "hello", "update")).rejects.toThrow(/outside the workspace/)
1249+
1250+
expect(mockedSafeWriteText).not.toHaveBeenCalled()
1251+
})
1252+
1253+
it("guardedWrite publishes a retained target reached through reconstructed components", async () => {
1254+
// The other containment outcome: the retained target sits under the reconstructed canonical
1255+
// path inside the canonical root, so the write is approved and lands on that target.
1256+
const reg = new ObservationRegistry()
1257+
const workspaceRoot = path.resolve(WORKSPACE)
1258+
const canonicalRoot = path.resolve("/private/workspace")
1259+
const rel = path.join("sub", "deeper", "new-file.txt")
1260+
const retained = path.join(canonicalRoot, "sub", "deeper", "new-file.txt")
1261+
reg.observe(path.resolve(workspaceRoot, rel), "v1", true)
1262+
const task = createMockTask({ observationRegistry: reg })
1263+
mockedFsAccess.mockResolvedValue(undefined)
1264+
mockedComputeVersionToken.mockResolvedValue("v1")
1265+
mockedResolvePublishTarget.mockResolvedValue(retained)
1266+
vi.mocked(fs.realpath).mockImplementation(async (value) => {
1267+
const key = path.resolve(String(value))
1268+
if (key === workspaceRoot) {
1269+
return canonicalRoot
1270+
}
1271+
throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
1272+
})
1273+
1274+
await guardedWrite(task, rel, "hello", "update")
1275+
1276+
expect(mockedSafeWriteText).toHaveBeenCalledWith(retained, "hello", { retainedTarget: true })
1277+
})
1278+
1279+
it("guardedWrite fails closed on a relative alias that canonicalizes outside the workspace", async () => {
1280+
// The bypass this row is about: child/ is a link directory inside the workspace whose referent
1281+
// is elsewhere, and the two components below it do not exist yet. Containment alone could not
1282+
// see it - the clause only binds the retained target when the alias looks inside the canonical
1283+
// root, and here the alias itself escaped, which reads as an intentional outside-workspace
1284+
// write. The rejection names the reconstructed path in order, because that is the path the
1285+
// model has to re-read.
1286+
const reg = new ObservationRegistry()
1287+
const workspaceRoot = path.resolve(WORKSPACE)
1288+
const canonicalRoot = path.resolve("/private/workspace")
1289+
const linkDir = path.join(workspaceRoot, "child")
1290+
const referentDir = path.join("/private/external", "child")
1291+
const rel = path.join("child", "deeper", "deeper2", "new-file.txt")
1292+
reg.observe(path.resolve(workspaceRoot, rel), "v1", true)
1293+
const task = createMockTask({ observationRegistry: reg })
1294+
mockedFsAccess.mockResolvedValue(undefined)
1295+
mockedComputeVersionToken.mockResolvedValue("v1")
1296+
mockedResolvePublishTarget.mockImplementation(async (p: string) =>
1297+
path.join(referentDir, "deeper", "deeper2", path.basename(p)),
1298+
)
1299+
vi.mocked(fs.realpath).mockImplementation(async (value) => {
1300+
const key = path.resolve(String(value))
1301+
if (key === workspaceRoot) {
1302+
return canonicalRoot
1303+
}
1304+
if (key === linkDir) {
1305+
return referentDir
1306+
}
1307+
throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
1308+
})
1309+
1310+
await expect(guardedWrite(task, rel, "hello", "update")).rejects.toThrow(
1311+
path.join(referentDir, "deeper", "deeper2", "new-file.txt"),
1312+
)
1313+
1314+
expect(mockedSafeWriteText).not.toHaveBeenCalled()
1315+
})
1316+
1317+
it("guardedWrite leaves an absolute alias that canonicalizes outside the workspace to its own authorization", async () => {
1318+
// The distinction that keeps this a relative-path rule: an absolute caller path was approved as
1319+
// that path by the tool layer, so an outside referent is the caller's choice and the write
1320+
// still lands on it. Only a path the caller named relative to the workspace is bound to the
1321+
// workspace by its own spelling.
1322+
const reg = new ObservationRegistry()
1323+
const outsideAlias = path.resolve("/outside/alias.txt")
1324+
const referent = path.resolve("/private/external/referent.txt")
1325+
reg.observe(outsideAlias, "v1", true)
1326+
const task = createMockTask({ observationRegistry: reg })
1327+
mockedFsAccess.mockResolvedValue(undefined)
1328+
mockedComputeVersionToken.mockResolvedValue("v1")
1329+
mockedResolvePublishTarget.mockResolvedValue(referent)
1330+
vi.mocked(fs.realpath).mockImplementation(async (value) =>
1331+
path.resolve(String(value)) === outsideAlias ? referent : path.resolve(String(value)),
1332+
)
1333+
1334+
await guardedWrite(task, outsideAlias, "hello", "update")
1335+
1336+
expect(mockedSafeWriteText).toHaveBeenCalledWith(referent, "hello", { retainedTarget: true })
1337+
})
1338+
12261339
it.each([path.resolve("/test/workspace-evil/secret.txt"), path.resolve("./workspace", "../escape.txt")])(
12271340
"guardedWrite rejects a retained target outside the workspace: %s",
12281341
async (target) => {

‎src/core/tools/guardedWrite.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,6 +570,23 @@ export async function guardedWrite(
570570
cursor = parent
571571
}
572572
})
573+
// A relative task path is workspace-scoped by construction: the caller named it relative to
574+
// task.cwd and the tool layer approved it as an in-workspace path. Canonicalizing it can still
575+
// land outside the workspace - the ordinary shape is a link directory inside the workspace whose
576+
// referent is elsewhere - and the clause below cannot catch that, because it only binds the
577+
// retained target when the alias looks inside the canonical root. An alias that itself escapes
578+
// would read as an intentional outside-workspace write, indistinguishable here from an absolute
579+
// path the caller named outright. So the alias's own containment is checked for relative paths
580+
// only, and it fails closed: the approved bytes were approved for a path inside the workspace.
581+
// An absolute caller path keeps its own authorization and is left to the clause below.
582+
if (!path.isAbsolute(relPathOrAbsolute) && !isInsideDirectory(canonicalWorkspaceRoot, canonicalAlias)) {
583+
throw new GuardRejectedError(
584+
"The write path resolves outside the workspace (" +
585+
canonicalAlias +
586+
") -- nothing was written; re-read the file under its canonical path, then retry.",
587+
displayPath,
588+
)
589+
}
573590
const authorizeTarget = (retainedTarget: string): void => {
574591
// Containment: validateAccess enforces .rooignore only (its own tests allow
575592
// absolute and ../ paths), so a workspace symlink retargeted after the tool's

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 18 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -719,27 +719,25 @@ export class DiffViewProvider {
719719
* the save was authorized against the exact version open() stat-matched.
720720
*/
721721
private canAdoptPublishedContent(writeKind: GuardedWriteKind, rejection: GuardRejectedError): boolean {
722-
// The two authorization refusals run first, before any early-return that would
723-
// adopt the match: a never-read or partial-read preview is not a moved-token
724-
// rejection for ANY session, including one whose baseline is a create placeholder
725-
// open() itself wrote. Ordering the refusals after the placeholder branch made
726-
// adoption depend on which baseline the session happened to have.
727-
// A preview over a target the model never read: the rejection is about
728-
// authorization, not a moved token, for every write kind. Adopting the match
729-
// would record an observation for content the model never read and authorize a
730-
// later full-file replacement.
722+
// Ownership first. A create placeholder is the file open() itself wrote: open() verified the
723+
// empty content and recorded it as this session's baseline, so the session owns the bytes it is
724+
// publishing and the compare-and-swap baseline is the placeholder token. For that session nothing
725+
// in the pre-open snapshot decides the question - preOpenObservation describes the file as it was
726+
// BEFORE open() ran, and that file may already have been gone (a partial slice of it, or nothing
727+
// at all), which says nothing about the verified empty placeholder that replaced it or about the
728+
// complete registry observation that authorized this write. The exception stays gated on the
729+
// rejection the placeholder can actually explain: an "already exists and was not read" rejection
730+
// means somebody else's file is at the target, and a matching read of it is what a clobber looks
731+
// like from here. Deciding the refusals first made adoption depend on which stale snapshot the
732+
// session happened to carry, which is the same failure mode the null case had.
733+
if (this.placeholderVersion !== undefined) {
734+
return rejection instanceof GuardStaleVersionError
735+
}
736+
// A preview over a target the model never read: the rejection is about authorization, not a
737+
// moved token, for every write kind. Adopting the match would record an observation for content
738+
// the model never read and authorize a later full-file replacement.
731739
if (this.preOpenObservation === null) {
732-
// Two sessions land on a null observation and only one of them is authorized. An existing
733-
// file the model never read is the refusal: the rejection is about authorization, not a
734-
// moved token, for every write kind, and adopting the match would record an observation for
735-
// content the model never read and authorize a later full-file replacement. A file open()
736-
// itself created is the other case - there was nothing to read, and open() verified the
737-
// empty placeholder and recorded it as this session's baseline - so the session owns the
738-
// content it is publishing and an autosave of the accepted bytes stays adoptable. Gated on
739-
// the rejection the placeholder can actually explain: an "already exists and was not read"
740-
// rejection means somebody else's file is at the target, and a matching read of it is what a
741-
// clobber looks like from here.
742-
return this.placeholderVersion !== undefined && rejection instanceof GuardStaleVersionError
740+
return false
743741
}
744742
// A full-file publish rejected for a partial read is not a moved-token rejection:
745743
// the completeness gate refused before any compare-and-swap ran, so the matching
@@ -752,11 +750,6 @@ export class DiffViewProvider {
752750
if (this.preOpenObservation !== undefined && writeKind !== "edit" && !this.preOpenObservation.complete) {
753751
return false
754752
}
755-
// A create placeholder is the file open() itself wrote, so a match is
756-
// unambiguous and the CAS baseline is the placeholder token.
757-
if (this.placeholderVersion !== undefined) {
758-
return true
759-
}
760753
// open() snapshots the authorization as it stood before the preview. No
761754
// snapshot means no preview ran, so there is no pairing to verify.
762755
if (this.preOpenObservation === undefined) {

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

Lines changed: 51 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2634,13 +2634,17 @@ describe("DiffViewProvider", () => {
26342634
expect(diffViewProvider["canAdoptPublishedContent"]("update", unread)).toBe(false)
26352635
})
26362636

2637-
it("refuses to adopt a published match when a create placeholder previewed a partial read", () => {
2637+
it("adopts for an owned placeholder whose pre-open snapshot was only a partial read", () => {
26382638
diffViewProvider["placeholderVersion"] = "placeholder-token"
2639-
diffViewProvider["preOpenObservation"] = { version: "placeholder-token", complete: false }
2639+
// The snapshot describes the target as it stood before open() ran: a slice of a file that the
2640+
// create path then replaced with the verified empty placeholder. It cannot stand in for a
2641+
// refusal on behalf of the placeholder the registry now holds.
2642+
diffViewProvider["preOpenObservation"] = { version: "gone-file-partial", complete: false }
26402643

2641-
expect(diffViewProvider["canAdoptPublishedContent"]("update", stale)).toBe(false)
2642-
// A targeted edit is authorized by a partial read, so it is not this refusal.
2644+
expect(diffViewProvider["canAdoptPublishedContent"]("update", stale)).toBe(true)
26432645
expect(diffViewProvider["canAdoptPublishedContent"]("edit", stale)).toBe(true)
2646+
// The reason gate still binds: a rejection the placeholder cannot explain keeps refusing.
2647+
expect(diffViewProvider["canAdoptPublishedContent"]("update", unread)).toBe(false)
26442648
})
26452649

26462650
it("still adopts for a create placeholder when no preview snapshot exists to check", () => {
@@ -2699,6 +2703,49 @@ describe("DiffViewProvider", () => {
26992703
expect(observation?.complete).toBe(true)
27002704
})
27012705

2706+
it("adopts the bytes Auto Save published when open() recreated a partially read file", async () => {
2707+
// The thread's trigger, end to end: the model read the file partially, the file was removed,
2708+
// and open() took the create path - the registry now holds the verified empty placeholder
2709+
// marked complete and placeholderVersion is set, while preOpenObservation still describes the
2710+
// slice of a file that is gone. Auto Save wrote the accepted bytes, and the guard rejected with
2711+
// GuardStaleVersionError because the completeness gate never ran - the registry entry is
2712+
// complete. Adoption has to be decided from the placeholder the session owns, not from the
2713+
// stale snapshot: refusing here reports a failure for a new file that already holds the
2714+
// accepted bytes, and the cleanup cannot unlink it because it is no longer the empty
2715+
// placeholder open() wrote.
2716+
const cleanEditor = {
2717+
document: {
2718+
uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" },
2719+
getText: vi.fn().mockReturnValue("new content"),
2720+
lineCount: 0,
2721+
encoding: "utf8",
2722+
isDirty: false,
2723+
save: vi.fn().mockResolvedValue(undefined),
2724+
},
2725+
selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } },
2726+
edit: vi.fn().mockResolvedValue(true),
2727+
revealRange: vi.fn(),
2728+
} as unknown as vscode.TextEditor
2729+
diffViewProvider["activeDiffEditor"] = cleanEditor
2730+
diffViewProvider.editType = "create"
2731+
mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, "placeholder-token", true)
2732+
diffViewProvider["placeholderVersion"] = "placeholder-token"
2733+
diffViewProvider["placeholderIdentity"] = { dev: 1n, ino: 1n }
2734+
diffViewProvider["preOpenObservation"] = { version: "gone-file-partial", complete: false }
2735+
diffViewProvider["openToken"] = "gone-file-partial"
2736+
vi.mocked(fs.stat).mockResolvedValue(previewStats)
2737+
vi.mocked(fs.readFile).mockResolvedValue("new content")
2738+
2739+
await expect(diffViewProvider.saveChanges(false)).resolves.toMatchObject({
2740+
newProblemsMessage: "",
2741+
finalContent: "new content",
2742+
})
2743+
2744+
expect(fs.unlink).not.toHaveBeenCalled()
2745+
const observation = mockTask.observationRegistry.get(`${mockCwd}/test.ts`)
2746+
expect(observation?.version).toBe(versionTokenOfStat(previewStats))
2747+
expect(observation?.complete).toBe(true)
2748+
})
27022749
it("adopts content autosave already published instead of reporting a stale rejection", async () => {
27032750
// Autosave wrote the buffer before acceptance: the document is clean and the
27042751
// disk already holds exactly the bytes this save intended, but the version

0 commit comments

Comments
 (0)