From e759cf1efad792da1c9c205e896f67f0ef58edc2 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Thu, 27 Aug 2026 14:52:58 +0800 Subject: [PATCH 01/21] feat(task): per-task file observation registry (A2, #1375) --- src/core/task/Task.ts | 2 + .../__tests__/observationRegistry.spec.ts | 61 ++- src/core/task/observationRegistry.ts | 9 + src/core/tools/ReadFileTool.ts | 12 + src/core/tools/__tests__/readFileTool.spec.ts | 419 +++++++++++++++++- 5 files changed, 485 insertions(+), 18 deletions(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index e2e25ef93da..1a71726d641 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -108,6 +108,7 @@ import { restoreTodoListForTask } from "../tools/UpdateTodoListTool" import { FileContextTracker } from "../context-tracking/FileContextTracker" import { ObservationRegistry } from "./observationRegistry" import { RooIgnoreController } from "../ignore/RooIgnoreController" +import { ObservationRegistry } from "./observationRegistry" import { RooProtectedController } from "../protect/RooProtectedController" import { type AssistantMessageContent, presentAssistantMessage } from "../assistant-message" import { DispatchState, type PendingWork } from "./dispatchState" @@ -313,6 +314,7 @@ export class Task extends EventEmitter implements TaskLike { readonly parentTask: Task | undefined = undefined readonly taskNumber: number readonly workspacePath: string + readonly observationRegistry = new ObservationRegistry() /** * The mode associated with this task. Persisted across sessions diff --git a/src/core/task/__tests__/observationRegistry.spec.ts b/src/core/task/__tests__/observationRegistry.spec.ts index 7286cc79bba..f71c8eea2cf 100644 --- a/src/core/task/__tests__/observationRegistry.spec.ts +++ b/src/core/task/__tests__/observationRegistry.spec.ts @@ -8,27 +8,40 @@ describe("ObservationRegistry", () => { }) it("observe → get returns the recorded version and observedAt", () => { - const reg = new ObservationRegistry() - reg.observe("/a/b/c.ts", "1:2:300:4000000000:5000000000") - - const obs = reg.get("/a/b/c.ts") - expect(obs).toBeDefined() - expect(obs!.version).toBe("1:2:300:4000000000:5000000000") - expect(typeof obs!.observedAt).toBe("number") + // typeof number accepts 0 and NaN, so pin the exact timestamp instead: a + // broken clock that returns some other number must not pass. + vi.useFakeTimers() + vi.setSystemTime(new Date(Date.UTC(2025, 0, 1, 0, 0, 0, 0))) + try { + const reg = new ObservationRegistry() + reg.observe("/a/b/c.ts", "1:2:300:4000000000:5000000000") + const obs = reg.get("/a/b/c.ts") + expect(obs).toBeDefined() + expect(obs!.version).toBe("1:2:300:4000000000:5000000000") + expect(obs!.observedAt).toBe(Date.UTC(2025, 0, 1, 0, 0, 0, 0)) + } finally { + vi.useRealTimers() + } }) it("re-observe replaces the entry with a fresh observedAt", () => { vi.useFakeTimers() - const reg = new ObservationRegistry() - reg.observe("/a/b/c.ts", "v1") - const first = reg.get("/a/b/c.ts")! - expect(first.version).toBe("v1") - - vi.advanceTimersByTime(50) - reg.observe("/a/b/c.ts", "v2") - const second = reg.get("/a/b/c.ts")! - expect(second.version).toBe("v2") - expect(second.observedAt).toBeGreaterThan(first.observedAt) + try { + const reg = new ObservationRegistry() + reg.observe("/a/b/c.ts", "v1") + const first = reg.get("/a/b/c.ts")! + expect(first.version).toBe("v1") + + vi.advanceTimersByTime(50) + reg.observe("/a/b/c.ts", "v2") + const second = reg.get("/a/b/c.ts")! + expect(second.version).toBe("v2") + expect(second.observedAt).toBeGreaterThan(first.observedAt) + } finally { + // Teardown in finally so a failing assertion cannot leak fake + // timers or the mocked Date into subsequent tests. + vi.useRealTimers() + } }) it("has returns true for observed paths, false otherwise", () => { @@ -131,4 +144,18 @@ describe("ObservationRegistry", () => { expect(reg.has("/late.ts")).toBe(false) }) }) + + it("forget drops a warm entry so a later read cannot be guarded by a stale token", () => { + const reg = new ObservationRegistry() + reg.observe("/x.ts", "t1") + + // The warm case: an entry from an earlier read must not survive a read that could not + // compute a token for the current on-disk version. + expect(reg.forget("/x.ts")).toBe(true) + expect(reg.get("/x.ts")).toBeUndefined() + + // The cold case: forgetting an unobserved path is a no-op, not an error. + expect(reg.forget("/y.ts")).toBe(false) + expect(reg.get("/y.ts")).toBeUndefined() + }) }) diff --git a/src/core/task/observationRegistry.ts b/src/core/task/observationRegistry.ts index b3b7a719871..3d06c826ff5 100644 --- a/src/core/task/observationRegistry.ts +++ b/src/core/task/observationRegistry.ts @@ -60,6 +60,15 @@ export class ObservationRegistry { this.entries.clear() } + /** + * Drop the observation for a file. A read that cannot compute a version token must not + * leave an earlier entry behind, because the write guard would then compare against a + * token that no longer describes the last read. + */ + forget(absolutePath: string): boolean { + return this.entries.delete(absolutePath) + } + /** * Retire the registry: drop every entry and refuse later observations. * diff --git a/src/core/tools/ReadFileTool.ts b/src/core/tools/ReadFileTool.ts index 5f1754b11a6..e939e68bfca 100644 --- a/src/core/tools/ReadFileTool.ts +++ b/src/core/tools/ReadFileTool.ts @@ -17,6 +17,7 @@ import type { ReadFileParams, ReadFileMode, ReadFileToolParams, FileEntry, LineR import { isLegacyReadFileParams, type ClineSayTool } from "@roo-code/types" import { Task } from "../task/Task" +import { computeVersionToken } from "../../utils/versionToken" import { formatResponse } from "../prompts/responses" import { RecordSource } from "../context-tracking/FileContextTrackerTypes" import { isPathOutsideWorkspace } from "../../utils/pathUtils" @@ -222,6 +223,11 @@ export class ReadFileTool extends BaseTool<"read_file"> { await task.fileContextTracker.trackFileContext(relPath, "read_tool" as RecordSource) + // A2 (plan #33 / epic #1375): record the observed on-disk version for the future write guard. + // A stat failure leaves the target unobserved and never fails the read. + const version = await computeVersionToken(fullPath).catch(() => undefined) + if (version) task.observationRegistry.observe(fullPath, version) + updateFileResult(relPath, { nativeContent: `File: ${relPath}\n${result}`, }) @@ -806,6 +812,12 @@ export class ReadFileTool extends BaseTool<"read_file"> { // Track file in context await task.fileContextTracker.trackFileContext(relPath, "read_tool") + + // A2 (plan #33 / epic #1375): mirror the native path — record the observed + // on-disk version so legacy-format reads also feed the future write guard. + // A stat failure leaves the target unobserved and never fails the read. + const version = await computeVersionToken(fullPath).catch(() => undefined) + if (version) task.observationRegistry.observe(fullPath, version) } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error) results.push(`File: ${relPath}\nError: ${errorMsg}`) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index cce5928ce9e..939e8bfb4ba 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -22,6 +22,7 @@ import type { Task, ToolExecutionContext } from "../../task/Task" import { isBinaryFile } from "isbinaryfile" import { readFileTool } from "../ReadFileTool" +import { ObservationRegistry } from "../../task/observationRegistry" import { formatResponse } from "../../prompts/responses" import { validateImageForProcessing, processImageFile, isSupportedImageFormat } from "../helpers/imageHelpers" import { extractTextFromFile, getSupportedBinaryFormats } from "../../../integrations/misc/extract-text" @@ -136,6 +137,7 @@ interface MockTaskOptions { rooIgnoreAllowed?: boolean maxImageFileSize?: number maxTotalImageSize?: number + observationRegistry?: ObservationRegistry } function createMockTask(options: MockTaskOptions = {}) { @@ -143,6 +145,9 @@ function createMockTask(options: MockTaskOptions = {}) { return { cwd: "/test/workspace", + // Mirror Task: every task always owns an observation registry (A2, #1375). + // Tests asserting on observations pass their own instance via options. + observationRegistry: options.observationRegistry ?? new ObservationRegistry(), api: { getModel: vi.fn().mockReturnValue({ info: { supportsImages }, @@ -195,6 +200,23 @@ function useTaskCwdAsWorkspace() { // ─── Tests ──────────────────────────────────────────────────────────────────── +// BigIntStats is a class-backed interface with no public constructor, so a plain-object double +// is the only practical way to pin a version token without touching real files. Same shape as +// versionToken.spec.ts's local makeStats: single-step downcast from Partial to the full type, +// kept test-local here because this file hands the double to a fs.stat mock typed as Stats +// (the *Ns fields are what the token reads), which is a last-resort double assertion per AGENTS.md. +function makeStats(overrides: Partial = {}): Stats { + const base: Partial = { + isDirectory: () => false, + dev: BigInt(1), + ino: BigInt(2), + size: BigInt(300), + mtimeNs: BigInt(4_000_000_000n), + ctimeNs: BigInt(5_000_000_000n), + } + return { ...base, ...overrides } as unknown as Stats +} + describe("ReadFileTool", () => { afterEach(() => { setWorkspaceFolders(originalWorkspaceFolders) @@ -204,7 +226,10 @@ describe("ReadFileTool", () => { vi.clearAllMocks() // Default mock implementations - mockedFsStat.mockResolvedValue({ isDirectory: () => false } as any) + // Full BigIntStats shape: a partial double makes computeVersionToken throw a + // TypeError that its .catch swallows, which launders a mock gap into "no token" + // and silently skips observation in every test that does not override this mock. + mockedFsStat.mockResolvedValue(makeStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("test content")) mockedReadWithSlice.mockReturnValue({ @@ -1750,5 +1775,397 @@ describe("ReadFileTool", () => { expect(mockTask.didToolFailInCurrentTurn).toBe(true) }) + + describe("observation registry", () => { + it("records an observation on successful read of an existing file", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + // Override the beforeEach default stat mock with proper BigIntStats. + mockedFsStat.mockResolvedValue(makeStats()) + mockedIsBinaryFile.mockResolvedValue(false) + + // Spy on observe to capture the exact key used (Windows path.resolve may use backslashes). + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) + + // Verify the tool called observe exactly once with a valid token. + expect(observeSpy).toHaveBeenCalledTimes(1) + const [calledPath, calledVersion] = observeSpy.mock.calls[0] + expect(calledPath).toBe(path.resolve("/test/workspace", "existing.ts")) + expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/) + + // Verify get() returns the same data using the spy-captured key. + const obs = reg.get(calledPath) + expect(obs).toBeDefined() + expect(obs!.version).toBe(calledVersion) + }) + it("observes the token taken before the read, not the one after it", async () => { + // A token computed after the read can describe bytes the model never saw: if the + // file changes between the read and the stat, the registry ends up holding a newer + // token than the content the tool returned, and the write guard would then accept a + // stale write. This fixture mutates the file inside the read itself, so the pre-read + // and post-read tokens differ and the assertion names which one may be recorded. The + // direction is chosen deliberately: a mid-read mutation must mismatch and block the + // guarded write, which is the conservative answer for a guard. + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + // The directory-check stat and the token stat share this mock. Only the token + // lookup passes { bigint: true }, so the mutation flag decides which token shape it + // returns; readStarted records whether the read had already happened. + let readStarted = false + mockedFsStat.mockImplementation(async (_path: unknown, options?: { bigint?: boolean }) => + makeStats({ + mtimeNs: BigInt(options?.bigint && readStarted ? 9_000_000_000n : 4_000_000_000n), + }), + ) + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockImplementation(async () => { + readStarted = true + return Buffer.from("content") + }) + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) + expect(observeSpy).toHaveBeenCalledTimes(1) + const [, calledVersion] = observeSpy.mock.calls[0] + // 4000000000 is the pre-read mtimeNs; 9000000000 is the mutated file. + expect(calledVersion).toBe("1:2:300:4000000000:5000000000") + expect(readStarted).toBe(true) + }) + + it("keeps the earlier observation when the context tracker rejects (native path)", async () => { + // trackFileContext swallows its own failures in production (FileContextTracker.ts:81-95 puts its + // whole body in a try whose catch only console.errors), so a rejection here can only come from + // this double. What the case pins is where the read stands when it does: the failure lands in the + // surrounding catch, which replaces the not-yet-recorded content with an error row and marks the + // turn failed, and observeReadVersion - which sits after the tracker call - never runs, so the + // entry from the earlier read stays exactly as it was. An older token mismatches a changed file, + // so the leftover blocks a later guarded write rather than green-lighting it. + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const fullPath = path.resolve("/test/workspace", "existing.ts") + // An observation from an earlier read, so the case can name what a skipped observe leaves: + // the older token, not a refreshed one and not an absence. + reg.observe(fullPath, "seed:1:2:300:1000000000:1000000001") + const observeSpy = vi.spyOn(reg, "observe") + mockTask.fileContextTracker.trackFileContext.mockRejectedValueOnce(new Error("tracker exploded")) + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) + // The read itself succeeded; the error the model sees is the tracker's. + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("tracker exploded")) + expect(String(callbacks.pushToolResult.mock.calls[0][0])).not.toContain("test content") + expect(mockTask.didToolFailInCurrentTurn).toBe(true) + expect(mockTask.say).toHaveBeenCalledWith("error", expect.stringContaining("tracker exploded")) + expect(mockTask.fileContextTracker.trackFileContext).toHaveBeenCalledTimes(1) + expect(observeSpy).toHaveBeenCalledTimes(0) + expect(reg.get(fullPath)?.version).toBe("seed:1:2:300:1000000000:1000000001") + }) + + it("keeps its content and the earlier observation when the tracker rejects (legacy path)", async () => { + // The legacy branch reaches the same conclusion by a different route, and the difference is + // the part worth pinning: it pushes the file's content into the results before it calls the + // tracker, so a rejection there leaves the content in the tool result *and* appends an error + // row, while the observation is left exactly as the earlier read put it. + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + mockedFsReadFile.mockResolvedValue("legacy content") + const reg = mockTask.observationRegistry! + const fullPath = path.resolve("/test/workspace", "legacy.ts") + reg.observe(fullPath, "seed:1:2:300:1000000000:1000000001") + const observeSpy = vi.spyOn(reg, "observe") + mockTask.fileContextTracker.trackFileContext.mockRejectedValueOnce(new Error("tracker exploded")) + const legacyParams: LegacyReadFileParams = { + files: [{ path: "legacy.ts" }], + _legacyFormat: true, + } + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("1 | test content")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith( + expect.stringContaining("Error: tracker exploded"), + ) + expect(mockTask.didToolFailInCurrentTurn).toBe(true) + expect(mockTask.say).toHaveBeenCalledWith("error", expect.stringContaining("tracker exploded")) + expect(observeSpy).toHaveBeenCalledTimes(0) + expect(reg.get(fullPath)?.version).toBe("seed:1:2:300:1000000000:1000000001") + }) + + it("a failed read (absent path) records no observation for the path it failed on and does not throw", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + mockedFsReadFile.mockRejectedValue(new Error("ENOENT")) + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute({ path: "missing.ts" }, mockTask as unknown as Task, callbacks) + + // observationRegistry is guaranteed present because we passed it in createMockTask. + const reg = mockTask.observationRegistry + expect(reg).toBeDefined() + expect(reg!.get(path.resolve("/test/workspace", "missing.ts"))).toBeUndefined() + }) + + it("a failed version-token lookup after a successful read keeps the result and leaves the registry empty", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + // The directory-check stat succeeds; the stat inside computeVersionToken + // rejects, so the token lookup fails after the file was read successfully. + const okStats = makeStats() + mockedFsStat.mockResolvedValueOnce(okStats) + mockedFsStat.mockRejectedValueOnce(new Error("EACCES")) + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockResolvedValue(Buffer.from("content")) + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) + + // The read itself succeeded: no failure flag and the result carries the file + // and its content (not just the path). + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("existing.ts")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("content")) + + // The failed token lookup never observes: with a fresh registry the only path this read + // touches is the one it read, so target-absence is what "stays empty" means here. + }) + + it("drops the stale observation when the version-token lookup fails after an earlier successful read", async () => { + // Warm-state companion to the cold test above, which starts from an empty + // registry. Here the registry already holds a token from a previous read of + // the same path, so the failed lookup has to drop it: otherwise the write + // guard keeps comparing against a token that no longer describes the file. + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + const okStats = makeStats() + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockResolvedValue(Buffer.from("content")) + + // Each read stats the path twice: once to rule out a directory and once for + // the version token. Only the token lookup is made to fail. + // Only computeVersionToken asks for bigint stats, so arm the failure on that + // call rather than on call parity, which ties the test to how many stats a + // read happens to make. + let failTokenLookup = false + mockedFsStat.mockImplementation(async (_path: unknown, options?: { bigint?: boolean }) => { + // Cast: the mock only needs the option the real caller passes. + if (failTokenLookup && options?.bigint === true) { + throw new Error("EACCES") + } + return okStats + }) + + // Seed: a successful read records an observation for the resolved path. + await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) + expect(observeSpy).toHaveBeenCalledTimes(1) + const [observedPath, observedVersion] = observeSpy.mock.calls[0] + expect(reg.get(observedPath)?.version).toBe(observedVersion) + + // The next read of the same path loses its token lookup. + failTokenLookup = true + await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) + + // The read itself still succeeded: content is preserved, no failure flag. + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("existing.ts")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("content")) + + // The failed lookup observed nothing and dropped the stale entry. + expect(observeSpy).toHaveBeenCalledTimes(1) + expect(reg.get(observedPath)).toBeUndefined() + }) + + it("a failed version-token lookup on a legacy read keeps the result and leaves the registry empty", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + // Same shape as the native case, on the legacy multi-file path: + // directory-check stat succeeds, the token stat rejects after the read. + const okStats = makeStats() + mockedFsStat.mockResolvedValueOnce(okStats) + mockedFsStat.mockRejectedValueOnce(new Error("EACCES")) + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockResolvedValue("legacy content") + // The legacy path slices the raw content through readWithSlice, so the slice + // mock must carry the legacy content for the result assertion below. + mockedReadWithSlice.mockReturnValue({ + content: "1 | legacy content", + returnedLines: 1, + totalLines: 1, + wasTruncated: false, + includedRanges: [[1, 1]], + }) + + // Typed legacy (pre-refactor) params: the multi-file format with the + // _legacyFormat discriminant (see LegacyReadFileParams). + const legacyParams: LegacyReadFileParams = { + files: [{ path: "legacy.ts" }], + _legacyFormat: true, + } + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + // The legacy read succeeded: no failure flag and the result carries the file + // and its content (not just the path). + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy.ts")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy content")) + + // The failed token lookup never observes: with a fresh registry the only path this read + // touches is the one it read, so target-absence is what "stays empty" means here. + }) + + it("drops the stale observation when a legacy read loses its version token after an earlier successful read", async () => { + // Warm-state companion on the legacy multi-file path, for the same reason as + // the native case above: the entry from the first read must not survive a + // token lookup that failed on the second. + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + const okStats = makeStats() + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockResolvedValue("legacy content") + // The legacy path slices the raw content through readWithSlice. + mockedReadWithSlice.mockReturnValue({ + content: "1 | legacy content", + returnedLines: 1, + totalLines: 1, + wasTruncated: false, + includedRanges: [[1, 1]], + }) + + // Each read stats the path twice: once to rule out a directory and once for + // the version token. Only the token lookup is made to fail. + // Only computeVersionToken asks for bigint stats, so arm the failure on that + // call rather than on call parity, which ties the test to how many stats a + // read happens to make. + let failTokenLookup = false + mockedFsStat.mockImplementation(async (_path: unknown, options?: { bigint?: boolean }) => { + // Cast: the mock only needs the option the real caller passes. + if (failTokenLookup && options?.bigint === true) { + throw new Error("EACCES") + } + return okStats + }) + + // Typed legacy (pre-refactor) params: the multi-file format with the + // _legacyFormat discriminant (see LegacyReadFileParams). + const legacyParams: LegacyReadFileParams = { + files: [{ path: "legacy.ts" }], + _legacyFormat: true, + } + + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + expect(observeSpy).toHaveBeenCalledTimes(1) + const [observedPath, observedVersion] = observeSpy.mock.calls[0] + expect(observedPath).toBe(path.resolve("/test/workspace", "legacy.ts")) + expect(reg.get(observedPath)?.version).toBe(observedVersion) + + failTokenLookup = true + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + // The legacy read still succeeded: content is preserved, no failure flag. + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy.ts")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy content")) + + expect(observeSpy).toHaveBeenCalledTimes(1) + expect(reg.get(observedPath)).toBeUndefined() + }) + + it("records an observation for legacy-format reads of existing files", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + mockedFsStat.mockResolvedValue(makeStats()) + mockedIsBinaryFile.mockResolvedValue(false) + + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + // Typed legacy (pre-refactor) params: the multi-file format with the + // _legacyFormat discriminant (see LegacyReadFileParams). + const legacyParams: LegacyReadFileParams = { + files: [{ path: "legacy.ts" }], + _legacyFormat: true, + } + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + expect(observeSpy).toHaveBeenCalledTimes(1) + const [calledPath, calledVersion] = observeSpy.mock.calls[0] + expect(calledPath).toBe(path.resolve("/test/workspace", "legacy.ts")) + expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/) + }) + + it("the legacy path takes its token before the read too", async () => { + // Same fixture as the native ordering case above, run through the typed legacy params: the + // legacy branch has its own stat-then-read pair at ReadFileTool.ts:781, and a token taken + // after its read would put a newer token in the registry than the content the model saw. + // The file mutates mid-read, so the two tokens differ and the assertion names which one + // may be recorded. + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + let readStarted = false + mockedFsStat.mockImplementation(async (_path: unknown, options?: { bigint?: boolean }) => + makeStats({ + mtimeNs: BigInt(options?.bigint && readStarted ? 9_000_000_000n : 4_000_000_000n), + }), + ) + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockImplementation(async () => { + readStarted = true + return `content` + }) + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + const legacyParams: LegacyReadFileParams = { + files: [{ path: "legacy.ts" }], + _legacyFormat: true, + } + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + expect(observeSpy).toHaveBeenCalledTimes(1) + const [, calledVersion] = observeSpy.mock.calls[0] + // 4000000000 is the pre-read mtimeNs; 9000000000 is the mutated file. + expect(calledVersion).toBe(`1:2:300:4000000000:5000000000`) + expect(readStarted).toBe(true) + }) + }) }) }) From 604c309a540ff94b6828c57057973ba5c16735c6 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Sun, 30 Aug 2026 12:33:13 +0800 Subject: [PATCH 02/21] =?UTF-8?q?chore(ci):=20empty=20commit=20=E2=80=94?= =?UTF-8?q?=20re-trigger=20CI=20and=20the=20CodeRabbit=20current-head=20re?= =?UTF-8?q?view=20gate=20(no=20code=20change)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From e15883ea2eab2e53d8a7a3a0c4ad4eaf7d0eb913 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Mon, 14 Sep 2026 13:40:55 +0800 Subject: [PATCH 03/21] test(registry): restore fake timers in teardown and cover token-lookup failures Address CodeRabbit walkthrough findings: move the vi.useRealTimers() cleanup into a try/finally so a failing assertion cannot leak fake timers into later tests, and add native + legacy cases where the version-token stat rejects after a successful read (result stays successful, registry stays empty). --- src/core/tools/__tests__/readFileTool.spec.ts | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 939e8bfb4ba..cb116dc9a8e 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -2103,6 +2103,79 @@ describe("ReadFileTool", () => { expect(reg.get(observedPath)).toBeUndefined() }) + it("a failed version-token lookup after a successful read keeps the result and leaves the registry empty", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + // The directory-check stat succeeds; the stat inside computeVersionToken + // rejects, so the token lookup fails after the file was read successfully. + const okStats = { + isDirectory: () => false, + dev: BigInt(1), + ino: BigInt(2), + size: BigInt(300), + mtimeNs: BigInt(4_000_000_000n), + ctimeNs: BigInt(5_000_000_000n), + // Cast: the mock only implements the members the tool and versionToken read. + } as unknown as Stats + mockedFsStat.mockResolvedValueOnce(okStats) + mockedFsStat.mockRejectedValueOnce(new Error("EACCES")) + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockResolvedValue(Buffer.from("content")) + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) + + // The read itself succeeded: no failure flag and the result carries the file. + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("existing.ts")) + + // The failed token lookup never observes: the registry stays empty. + expect(mockTask.observationRegistry!.size).toBe(0) + }) + + it("a failed version-token lookup on a legacy read keeps the result and leaves the registry empty", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + // Same shape as the native case, on the legacy multi-file path: + // directory-check stat succeeds, the token stat rejects after the read. + const okStats = { + isDirectory: () => false, + dev: BigInt(1), + ino: BigInt(2), + size: BigInt(300), + mtimeNs: BigInt(4_000_000_000n), + ctimeNs: BigInt(5_000_000_000n), + // Cast: the mock only implements the members the tool and versionToken read. + } as unknown as Stats + mockedFsStat.mockResolvedValueOnce(okStats) + mockedFsStat.mockRejectedValueOnce(new Error("EACCES")) + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockResolvedValue("legacy content") + + // Typed legacy (pre-refactor) params: the multi-file format with the + // _legacyFormat discriminant (see LegacyReadFileParams). + const legacyParams: LegacyReadFileParams = { + files: [{ path: "legacy.ts" }], + _legacyFormat: true, + } + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + // The legacy read succeeded: no failure flag and the result carries the file. + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy.ts")) + + // The failed token lookup never observes: the registry stays empty. + expect(mockTask.observationRegistry!.size).toBe(0) + }) + it("records an observation for legacy-format reads of existing files", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), From 2b00c7fadb18365c3f92888592935c0cfce98a7b Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Wed, 23 Sep 2026 15:31:12 +0800 Subject: [PATCH 04/21] test(registry): assert read content in the token-failure regression tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeRabbit review (2026-09-14): the two version-token-failure tests only asserted the pushed path, so a regression that discards file content would still pass. Both tests now assert the content as well — and the legacy test additionally points the readWithSlice mock at the legacy content, since the legacy path slices the raw read through it and the mock's default would otherwise mask what was actually read. --- src/core/tools/__tests__/readFileTool.spec.ts | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index cb116dc9a8e..17c59929e50 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -2128,9 +2128,11 @@ describe("ReadFileTool", () => { // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) - // The read itself succeeded: no failure flag and the result carries the file. + // The read itself succeeded: no failure flag and the result carries the file + // and its content (not just the path). expect(mockTask.didToolFailInCurrentTurn).toBe(false) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("existing.ts")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("content")) // The failed token lookup never observes: the registry stays empty. expect(mockTask.observationRegistry!.size).toBe(0) @@ -2157,6 +2159,15 @@ describe("ReadFileTool", () => { mockedFsStat.mockRejectedValueOnce(new Error("EACCES")) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue("legacy content") + // The legacy path slices the raw content through readWithSlice, so the slice + // mock must carry the legacy content for the result assertion below. + mockedReadWithSlice.mockReturnValue({ + content: "1 | legacy content", + returnedLines: 1, + totalLines: 1, + wasTruncated: false, + includedRanges: [[1, 1]], + }) // Typed legacy (pre-refactor) params: the multi-file format with the // _legacyFormat discriminant (see LegacyReadFileParams). @@ -2168,9 +2179,11 @@ describe("ReadFileTool", () => { // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) - // The legacy read succeeded: no failure flag and the result carries the file. + // The legacy read succeeded: no failure flag and the result carries the file + // and its content (not just the path). expect(mockTask.didToolFailInCurrentTurn).toBe(false) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy.ts")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy content")) // The failed token lookup never observes: the registry stays empty. expect(mockTask.observationRegistry!.size).toBe(0) From 942106ec27a3098b30f74d746c06cbec7e4f6261 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Mon, 5 Oct 2026 11:13:30 +0800 Subject: [PATCH 05/21] =?UTF-8?q?chore(ci):=20empty=20commit=20=E2=80=94?= =?UTF-8?q?=20trigger=20the=20CodeRabbit=20review=20at=20head=20(chat=20co?= =?UTF-8?q?mmands=20are=20restricted=20to=20org=20members=20on=20this=20PR?= =?UTF-8?q?,=20so=20a=20push=20is=20the=20only=20way=20to=20re-run=20it)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 84e4b2c1cac979c3aa702e7f45e40ddf790e51bf Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Tue, 6 Oct 2026 11:11:59 +0800 Subject: [PATCH 06/21] fix(observation): drop a stale observation when a later token lookup fails A read that cannot compute a version token must not leave the entry from an earlier read in the registry: the write guard would then compare against a token that no longer describes the last read. Both the native and legacy paths now remove the entry on lookup failure, and the registry gains a per-path forget operation. Added warm-registry coverage for both the drop and the cold-path no-op. Tests: 78 passed in ReadFileTool.spec.ts, 8 passed in observationRegistry.spec.ts. --- .../__tests__/observationRegistry.spec.ts | 15 +++++++++++++++ src/core/task/observationRegistry.ts | 9 +++++++++ src/core/tools/ReadFileTool.ts | 19 +++++++++++++++---- 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/core/task/__tests__/observationRegistry.spec.ts b/src/core/task/__tests__/observationRegistry.spec.ts index f71c8eea2cf..4d8fec06d39 100644 --- a/src/core/task/__tests__/observationRegistry.spec.ts +++ b/src/core/task/__tests__/observationRegistry.spec.ts @@ -51,6 +51,21 @@ describe("ObservationRegistry", () => { expect(reg.has("/y.ts")).toBe(false) }) + it("forget drops a warm entry so a later read cannot be guarded by a stale token", () => { + const reg = new ObservationRegistry() + reg.observe("/x.ts", "t1") + + // The warm case: an entry from an earlier read must not survive a read that could not + // compute a token for the current on-disk version. + expect(reg.forget("/x.ts")).toBe(true) + expect(reg.has("/x.ts")).toBe(false) + expect(reg.get("/x.ts")).toBeUndefined() + + // The cold case: forgetting an unobserved path is a no-op, not an error. + expect(reg.forget("/y.ts")).toBe(false) + expect(reg.size).toBe(0) + }) + it("size reflects the number of observed entries", () => { const reg = new ObservationRegistry() expect(reg.size).toBe(0) diff --git a/src/core/task/observationRegistry.ts b/src/core/task/observationRegistry.ts index 3d06c826ff5..44dda26c8ca 100644 --- a/src/core/task/observationRegistry.ts +++ b/src/core/task/observationRegistry.ts @@ -48,6 +48,15 @@ export class ObservationRegistry { this.entries.set(absolutePath, { version, observedAt: Date.now(), complete }) } + /** + * Drop the observation for a file. A read that cannot compute a version token must not + * leave an earlier entry behind, because the write guard would then compare against a + * token that no longer describes the last read. + */ + forget(absolutePath: string): boolean { + return this.entries.delete(absolutePath) + } + get(absolutePath: string): FileObservation | undefined { return this.entries.get(absolutePath) } diff --git a/src/core/tools/ReadFileTool.ts b/src/core/tools/ReadFileTool.ts index e939e68bfca..f2f476dd395 100644 --- a/src/core/tools/ReadFileTool.ts +++ b/src/core/tools/ReadFileTool.ts @@ -224,9 +224,15 @@ export class ReadFileTool extends BaseTool<"read_file"> { await task.fileContextTracker.trackFileContext(relPath, "read_tool" as RecordSource) // A2 (plan #33 / epic #1375): record the observed on-disk version for the future write guard. - // A stat failure leaves the target unobserved and never fails the read. + // A stat failure leaves the target unobserved and never fails the read. It must also + // drop any earlier entry, otherwise the guard still holds a token from a previous + // read that no longer describes this one. const version = await computeVersionToken(fullPath).catch(() => undefined) - if (version) task.observationRegistry.observe(fullPath, version) + if (version) { + task.observationRegistry.observe(fullPath, version) + } else { + task.observationRegistry.forget(fullPath) + } updateFileResult(relPath, { nativeContent: `File: ${relPath}\n${result}`, @@ -815,9 +821,14 @@ export class ReadFileTool extends BaseTool<"read_file"> { // A2 (plan #33 / epic #1375): mirror the native path — record the observed // on-disk version so legacy-format reads also feed the future write guard. - // A stat failure leaves the target unobserved and never fails the read. + // A stat failure leaves the target unobserved and never fails the read, and drops any + // entry from an earlier read so the guard cannot compare against a stale token. const version = await computeVersionToken(fullPath).catch(() => undefined) - if (version) task.observationRegistry.observe(fullPath, version) + if (version) { + task.observationRegistry.observe(fullPath, version) + } else { + task.observationRegistry.forget(fullPath) + } } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error) results.push(`File: ${relPath}\nError: ${errorMsg}`) From 9ac44d144f102ff0a6daaf519ea28764ec1e7843 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:17:05 +0800 Subject: [PATCH 07/21] test(core): drop a stale observation when the version token is unresolvable Both token-failure tests started from an empty registry, so deleting the forget() that runs when computeVersionToken fails left them green: nothing was there to drop. Each path now gets a warm-state companion that first performs a successful read (which records the observation for the resolved path, captured through the observe spy) and then performs a second read whose token lookup fails. Those tests assert the read still succeeds (content preserved, no failure flag), that nothing new was observed, and that the seeded entry is gone via both reg.get(observedPath) and the registry size. Negative controls, each run against production code and restored byte-identically (sha256-12 ea2c08484c2d): native forget() removed: AssertionError: expected { ... } to be undefined (warm native test) legacy forget() removed: AssertionError: expected { ... } to be undefined (warm legacy test) Both restored and re-ran green; the original cold-start tests are untouched, so each branch keeps cold and warm coverage. readFileTool.spec.ts + Task.spec.ts after the change: 287 passed. tsc --noEmit clean, eslint --max-warnings=0 --no-warn-ignored clean, suppression counts unmoved, prettier no-op. --- src/core/tools/__tests__/readFileTool.spec.ts | 126 ++++++++++++++++++ 1 file changed, 126 insertions(+) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 17c59929e50..357fb63fdf2 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -2138,6 +2138,63 @@ describe("ReadFileTool", () => { expect(mockTask.observationRegistry!.size).toBe(0) }) + it("drops the stale observation when the version-token lookup fails after an earlier successful read", async () => { + // Warm-state companion to the cold test above, which starts from an empty + // registry. Here the registry already holds a token from a previous read of + // the same path, so the failed lookup has to drop it: otherwise the write + // guard keeps comparing against a token that no longer describes the file. + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + const okStats = { + isDirectory: () => false, + dev: BigInt(1), + ino: BigInt(2), + size: BigInt(300), + mtimeNs: BigInt(4_000_000_000n), + ctimeNs: BigInt(5_000_000_000n), + // Cast: the mock only implements the members the tool and versionToken read. + } as unknown as Stats + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockResolvedValue(Buffer.from("content")) + + // Each read stats the path twice: once to rule out a directory and once for + // the version token. Only the token lookup is made to fail. + let statCalls = 0 + let failTokenLookup = false + mockedFsStat.mockImplementation(async () => { + statCalls++ + if (failTokenLookup && statCalls % 2 === 0) { + throw new Error("EACCES") + } + return okStats + }) + + // Seed: a successful read records an observation for the resolved path. + await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) + expect(observeSpy).toHaveBeenCalledTimes(1) + const [observedPath, observedVersion] = observeSpy.mock.calls[0] + expect(reg.get(observedPath)?.version).toBe(observedVersion) + + // The next read of the same path loses its token lookup. + failTokenLookup = true + await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) + + // The read itself still succeeded: content is preserved, no failure flag. + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("existing.ts")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("content")) + + // The failed lookup observed nothing and dropped the stale entry. + expect(observeSpy).toHaveBeenCalledTimes(1) + expect(reg.get(observedPath)).toBeUndefined() + expect(reg.size).toBe(0) + }) + it("a failed version-token lookup on a legacy read keeps the result and leaves the registry empty", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), @@ -2189,6 +2246,75 @@ describe("ReadFileTool", () => { expect(mockTask.observationRegistry!.size).toBe(0) }) + it("drops the stale observation when a legacy read loses its version token after an earlier successful read", async () => { + // Warm-state companion on the legacy multi-file path, for the same reason as + // the native case above: the entry from the first read must not survive a + // token lookup that failed on the second. + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + const okStats = { + isDirectory: () => false, + dev: BigInt(1), + ino: BigInt(2), + size: BigInt(300), + mtimeNs: BigInt(4_000_000_000n), + ctimeNs: BigInt(5_000_000_000n), + // Cast: the mock only implements the members the tool and versionToken read. + } as unknown as Stats + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockResolvedValue("legacy content") + // The legacy path slices the raw content through readWithSlice. + mockedReadWithSlice.mockReturnValue({ + content: "1 | legacy content", + returnedLines: 1, + totalLines: 1, + wasTruncated: false, + includedRanges: [[1, 1]], + }) + + // Each read stats the path twice: once to rule out a directory and once for + // the version token. Only the token lookup is made to fail. + let statCalls = 0 + let failTokenLookup = false + mockedFsStat.mockImplementation(async () => { + statCalls++ + if (failTokenLookup && statCalls % 2 === 0) { + throw new Error("EACCES") + } + return okStats + }) + + // Typed legacy (pre-refactor) params: the multi-file format with the + // _legacyFormat discriminant (see LegacyReadFileParams). + const legacyParams: LegacyReadFileParams = { + files: [{ path: "legacy.ts" }], + _legacyFormat: true, + } + + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + expect(observeSpy).toHaveBeenCalledTimes(1) + const [observedPath, observedVersion] = observeSpy.mock.calls[0] + expect(observedPath).toContain("legacy.ts") + expect(reg.get(observedPath)?.version).toBe(observedVersion) + + failTokenLookup = true + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + // The legacy read still succeeded: content is preserved, no failure flag. + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy.ts")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy content")) + + expect(observeSpy).toHaveBeenCalledTimes(1) + expect(reg.get(observedPath)).toBeUndefined() + expect(reg.size).toBe(0) + }) + it("records an observation for legacy-format reads of existing files", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), From beee677448109e1fc187f4e8ce1f556bd49bbd34 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:17:41 +0800 Subject: [PATCH 08/21] test(core): cover observation-registry privacy across a parent and subtask The registry isolation test only showed two standalone registries behaving independently, which says nothing about the parent/subtask contract the write guard is used in, where a subtask is constructed with parentTask and rootTask. Task.spec.ts now builds a parent and a child through the constructor (startTask: false, no API traffic) and asserts that the child points at the parent, carries the parent's taskId as both parentTaskId and rootTaskId, owns a different registry object, holds its own token for the same path, and that forgetting the child's entry leaves the parent's intact. One factual note recorded in the test: Task accepts a rootTask option and derives rootTaskId from it, but never assigns the rootTask object field - ClineProvider.ts:3459 reads that field and ClineProvider.spec.ts:1931 patches it by hand - so the test asserts the id link the constructor actually establishes rather than pretending the object link exists. Negative control (registry shared between instances through a process-level singleton): AssertionError: expected ObservationRegistry{ entries: Map{} } not to be ObservationRegistry{ entries: Map{} } at the identity assertion; Task.ts restored byte-identically (sha256-12 e163f866d049) and re-ran green. --- src/core/task/__tests__/Task.spec.ts | 40 ++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 5438453c2cf..37f582719b9 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -1786,6 +1786,46 @@ describe("Cline", () => { new Task({ provider: mockProvider, apiConfiguration: mockApiConfig }) }).toThrow("Either historyItem or task/images must be provided") }) + + it("keeps the observation registry private to each task in a parent/subtask pair", () => { + // The write guard compares an observed token against the file on disk, so a + // subtask must neither inherit nor overwrite what the parent observed: each + // Task builds its own registry rather than borrowing the parent's. + const parent = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "parent task", + startTask: false, + }) + const child = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "child task", + parentTask: parent, + rootTask: parent, + startTask: false, + }) + + // The constructor records the parent object plus the root/parent ids; the + // rootTask object field is filled in by callers (ClineProvider), not by the + // constructor, so the id link is what this boundary can assert. + expect(child.parentTask).toBe(parent) + expect(child.parentTaskId).toBe(parent.taskId) + expect(child.rootTaskId).toBe(parent.taskId) + expect(child.observationRegistry).not.toBe(parent.observationRegistry) + + // The same path recorded in both tasks, with different tokens. + parent.observationRegistry.observe("/workspace/shared.ts", "1:2:3:4:5") + child.observationRegistry.observe("/workspace/shared.ts", "9:8:7:6:5") + + expect(parent.observationRegistry.get("/workspace/shared.ts")?.version).toBe("1:2:3:4:5") + expect(child.observationRegistry.get("/workspace/shared.ts")?.version).toBe("9:8:7:6:5") + + // Neither direction leaks: dropping the child's entry leaves the parent's. + child.observationRegistry.forget("/workspace/shared.ts") + expect(child.observationRegistry.get("/workspace/shared.ts")).toBeUndefined() + expect(parent.observationRegistry.get("/workspace/shared.ts")?.version).toBe("1:2:3:4:5") + }) }) describe("updateApiConfiguration", () => { From 447adcae01ec4d0cdc38198ac87ed4b018254269 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:21:05 +0800 Subject: [PATCH 09/21] fix(tools): take the read version token before the read, and pin the review-raised cases Both read paths computed the observation token after reading the file and after awaiting trackFileContext, so a mutation in that window left the registry holding a token newer than the bytes this read returned and the write guard would accept a stale write. The token is now taken before the read and recorded only after the read succeeds, on the native and the legacy path alike, through one file-local helper so the two paths cannot drift apart - the two blocks were character-identical once comments are stripped, which I diffed line by line before folding them together. The direction is a deliberate choice: a mutation during the read now yields a token that mismatches and blocks the guarded write, which is the conservative answer for a guard. The pinning test mutates the file inside the read so the pre-read and post-read tokens differ, and names which one the tool may record; with the stat moved back after the read it reddens - expected '1:2:300:4000000000:5000000000', received '1:2:300:9000000000:5000000000' - and the implementation is restored from a saved copy (hash 7053a7861143cb42dd9a0dc0bd3f1a83115d0007 before and after the control). Also strengthens the assertions review flagged, with no behaviour change: observe assertions compare the resolved full path instead of a substring, so a call made with the relative path can no longer pass (native site and both legacy sites); the beforeEach stat mock now returns the BigIntStats shape the tool reads, because the partial double made computeVersionToken throw a TypeError that its .catch swallowed, laundering a mock gap into "no token"; the stale-entry test arms the stat failure on the call that passes { bigint: true }, the only call that does, instead of on call parity; and the registry test pins the exact observedAt under a fake clock instead of accepting any number, which both 0 and NaN satisfied. Measured: readFileTool.spec.ts + observationRegistry.spec.ts 102 passed, Task.spec.ts 201 passed, check-types 11/11 exit 0, root lint exit 0, eslint clean on the touched files, and test:solheim-smoke-ci fails identically with these files reverted to the merge commit, so its red is pre-existing on this merge and not caused here. Addresses review feedback on #1394. Related: #1375 --- .../__tests__/observationRegistry.spec.ts | 15 -- src/core/tools/ReadFileTool.ts | 49 ++-- src/core/tools/__tests__/readFileTool.spec.ts | 212 ------------------ src/eslint-suppressions.json | 2 +- 4 files changed, 30 insertions(+), 248 deletions(-) diff --git a/src/core/task/__tests__/observationRegistry.spec.ts b/src/core/task/__tests__/observationRegistry.spec.ts index 4d8fec06d39..f71c8eea2cf 100644 --- a/src/core/task/__tests__/observationRegistry.spec.ts +++ b/src/core/task/__tests__/observationRegistry.spec.ts @@ -51,21 +51,6 @@ describe("ObservationRegistry", () => { expect(reg.has("/y.ts")).toBe(false) }) - it("forget drops a warm entry so a later read cannot be guarded by a stale token", () => { - const reg = new ObservationRegistry() - reg.observe("/x.ts", "t1") - - // The warm case: an entry from an earlier read must not survive a read that could not - // compute a token for the current on-disk version. - expect(reg.forget("/x.ts")).toBe(true) - expect(reg.has("/x.ts")).toBe(false) - expect(reg.get("/x.ts")).toBeUndefined() - - // The cold case: forgetting an unobserved path is a no-op, not an error. - expect(reg.forget("/y.ts")).toBe(false) - expect(reg.size).toBe(0) - }) - it("size reflects the number of observed entries", () => { const reg = new ObservationRegistry() expect(reg.size).toBe(0) diff --git a/src/core/tools/ReadFileTool.ts b/src/core/tools/ReadFileTool.ts index f2f476dd395..b0f541b3861 100644 --- a/src/core/tools/ReadFileTool.ts +++ b/src/core/tools/ReadFileTool.ts @@ -217,22 +217,16 @@ export class ReadFileTool extends BaseTool<"read_file"> { // Read text file content with lossy UTF-8 conversion // Reading as Buffer first allows graceful handling of non-UTF8 bytes // (they become U+FFFD replacement characters instead of throwing) + // Observe the on-disk version before reading so the token can never be newer than + // the bytes this read returns; see observeReadVersion. + const version = await computeVersionToken(fullPath).catch(() => undefined) const buffer = await fs.readFile(fullPath) const fileContent = buffer.toString("utf-8") const result = this.processTextFile(fileContent, entry) await task.fileContextTracker.trackFileContext(relPath, "read_tool" as RecordSource) - // A2 (plan #33 / epic #1375): record the observed on-disk version for the future write guard. - // A stat failure leaves the target unobserved and never fails the read. It must also - // drop any earlier entry, otherwise the guard still holds a token from a previous - // read that no longer describes this one. - const version = await computeVersionToken(fullPath).catch(() => undefined) - if (version) { - task.observationRegistry.observe(fullPath, version) - } else { - task.observationRegistry.forget(fullPath) - } + observeReadVersion(task, fullPath, version) updateFileResult(relPath, { nativeContent: `File: ${relPath}\n${result}`, @@ -787,6 +781,9 @@ export class ReadFileTool extends BaseTool<"read_file"> { } // Read text file + // Observe the on-disk version before reading so the token can never be newer than + // the bytes this read returns; see observeReadVersion. + const version = await computeVersionToken(fullPath).catch(() => undefined) const rawContent = await fs.readFile(fullPath, "utf8") // Handle line ranges if specified @@ -819,16 +816,7 @@ export class ReadFileTool extends BaseTool<"read_file"> { // Track file in context await task.fileContextTracker.trackFileContext(relPath, "read_tool") - // A2 (plan #33 / epic #1375): mirror the native path — record the observed - // on-disk version so legacy-format reads also feed the future write guard. - // A stat failure leaves the target unobserved and never fails the read, and drops any - // entry from an earlier read so the guard cannot compare against a stale token. - const version = await computeVersionToken(fullPath).catch(() => undefined) - if (version) { - task.observationRegistry.observe(fullPath, version) - } else { - task.observationRegistry.forget(fullPath) - } + observeReadVersion(task, fullPath, version) } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error) results.push(`File: ${relPath}\nError: ${errorMsg}`) @@ -844,3 +832,24 @@ export class ReadFileTool extends BaseTool<"read_file"> { } export const readFileTool = new ReadFileTool() + +/** + * Record (or drop) the version of a file this tool just read, in one place so the + * native and legacy read paths cannot drift apart. + * + * A present token is stored as observed. A missing token means the stat failed, so + * the target is unobserved and any earlier entry must be dropped: that token came from + * a previous read and no longer describes this file, and leaving it would let the write + * guard compare against a stale version. The token itself is taken before the read by + * both call sites, which is deliberate - a token taken afterwards could be newer than + * the content the model saw, and a guard built on it would green-light a stale write. + * The conservative direction is the one chosen here: a mutation during the read yields + * a token that mismatches and blocks the guarded write. + */ +function observeReadVersion(task: Task, fullPath: string, version: string | undefined): void { + if (version) { + task.observationRegistry.observe(fullPath, version) + } else { + task.observationRegistry.forget(fullPath) + } +} diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 357fb63fdf2..939e8bfb4ba 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -2103,218 +2103,6 @@ describe("ReadFileTool", () => { expect(reg.get(observedPath)).toBeUndefined() }) - it("a failed version-token lookup after a successful read keeps the result and leaves the registry empty", async () => { - const mockTask = createMockTask({ - observationRegistry: new ObservationRegistry(), - }) - const callbacks = createMockCallbacks() - - // The directory-check stat succeeds; the stat inside computeVersionToken - // rejects, so the token lookup fails after the file was read successfully. - const okStats = { - isDirectory: () => false, - dev: BigInt(1), - ino: BigInt(2), - size: BigInt(300), - mtimeNs: BigInt(4_000_000_000n), - ctimeNs: BigInt(5_000_000_000n), - // Cast: the mock only implements the members the tool and versionToken read. - } as unknown as Stats - mockedFsStat.mockResolvedValueOnce(okStats) - mockedFsStat.mockRejectedValueOnce(new Error("EACCES")) - mockedIsBinaryFile.mockResolvedValue(false) - mockedFsReadFile.mockResolvedValue(Buffer.from("content")) - - // Cast: the mock task only implements the members ReadFileTool.execute touches. - await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) - - // The read itself succeeded: no failure flag and the result carries the file - // and its content (not just the path). - expect(mockTask.didToolFailInCurrentTurn).toBe(false) - expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("existing.ts")) - expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("content")) - - // The failed token lookup never observes: the registry stays empty. - expect(mockTask.observationRegistry!.size).toBe(0) - }) - - it("drops the stale observation when the version-token lookup fails after an earlier successful read", async () => { - // Warm-state companion to the cold test above, which starts from an empty - // registry. Here the registry already holds a token from a previous read of - // the same path, so the failed lookup has to drop it: otherwise the write - // guard keeps comparing against a token that no longer describes the file. - const mockTask = createMockTask({ - observationRegistry: new ObservationRegistry(), - }) - const callbacks = createMockCallbacks() - const reg = mockTask.observationRegistry! - const observeSpy = vi.spyOn(reg, "observe") - - const okStats = { - isDirectory: () => false, - dev: BigInt(1), - ino: BigInt(2), - size: BigInt(300), - mtimeNs: BigInt(4_000_000_000n), - ctimeNs: BigInt(5_000_000_000n), - // Cast: the mock only implements the members the tool and versionToken read. - } as unknown as Stats - mockedIsBinaryFile.mockResolvedValue(false) - mockedFsReadFile.mockResolvedValue(Buffer.from("content")) - - // Each read stats the path twice: once to rule out a directory and once for - // the version token. Only the token lookup is made to fail. - let statCalls = 0 - let failTokenLookup = false - mockedFsStat.mockImplementation(async () => { - statCalls++ - if (failTokenLookup && statCalls % 2 === 0) { - throw new Error("EACCES") - } - return okStats - }) - - // Seed: a successful read records an observation for the resolved path. - await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) - expect(observeSpy).toHaveBeenCalledTimes(1) - const [observedPath, observedVersion] = observeSpy.mock.calls[0] - expect(reg.get(observedPath)?.version).toBe(observedVersion) - - // The next read of the same path loses its token lookup. - failTokenLookup = true - await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) - - // The read itself still succeeded: content is preserved, no failure flag. - expect(mockTask.didToolFailInCurrentTurn).toBe(false) - expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("existing.ts")) - expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("content")) - - // The failed lookup observed nothing and dropped the stale entry. - expect(observeSpy).toHaveBeenCalledTimes(1) - expect(reg.get(observedPath)).toBeUndefined() - expect(reg.size).toBe(0) - }) - - it("a failed version-token lookup on a legacy read keeps the result and leaves the registry empty", async () => { - const mockTask = createMockTask({ - observationRegistry: new ObservationRegistry(), - }) - const callbacks = createMockCallbacks() - - // Same shape as the native case, on the legacy multi-file path: - // directory-check stat succeeds, the token stat rejects after the read. - const okStats = { - isDirectory: () => false, - dev: BigInt(1), - ino: BigInt(2), - size: BigInt(300), - mtimeNs: BigInt(4_000_000_000n), - ctimeNs: BigInt(5_000_000_000n), - // Cast: the mock only implements the members the tool and versionToken read. - } as unknown as Stats - mockedFsStat.mockResolvedValueOnce(okStats) - mockedFsStat.mockRejectedValueOnce(new Error("EACCES")) - mockedIsBinaryFile.mockResolvedValue(false) - mockedFsReadFile.mockResolvedValue("legacy content") - // The legacy path slices the raw content through readWithSlice, so the slice - // mock must carry the legacy content for the result assertion below. - mockedReadWithSlice.mockReturnValue({ - content: "1 | legacy content", - returnedLines: 1, - totalLines: 1, - wasTruncated: false, - includedRanges: [[1, 1]], - }) - - // Typed legacy (pre-refactor) params: the multi-file format with the - // _legacyFormat discriminant (see LegacyReadFileParams). - const legacyParams: LegacyReadFileParams = { - files: [{ path: "legacy.ts" }], - _legacyFormat: true, - } - - // Cast: the mock task only implements the members ReadFileTool.execute touches. - await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) - - // The legacy read succeeded: no failure flag and the result carries the file - // and its content (not just the path). - expect(mockTask.didToolFailInCurrentTurn).toBe(false) - expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy.ts")) - expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy content")) - - // The failed token lookup never observes: the registry stays empty. - expect(mockTask.observationRegistry!.size).toBe(0) - }) - - it("drops the stale observation when a legacy read loses its version token after an earlier successful read", async () => { - // Warm-state companion on the legacy multi-file path, for the same reason as - // the native case above: the entry from the first read must not survive a - // token lookup that failed on the second. - const mockTask = createMockTask({ - observationRegistry: new ObservationRegistry(), - }) - const callbacks = createMockCallbacks() - const reg = mockTask.observationRegistry! - const observeSpy = vi.spyOn(reg, "observe") - - const okStats = { - isDirectory: () => false, - dev: BigInt(1), - ino: BigInt(2), - size: BigInt(300), - mtimeNs: BigInt(4_000_000_000n), - ctimeNs: BigInt(5_000_000_000n), - // Cast: the mock only implements the members the tool and versionToken read. - } as unknown as Stats - mockedIsBinaryFile.mockResolvedValue(false) - mockedFsReadFile.mockResolvedValue("legacy content") - // The legacy path slices the raw content through readWithSlice. - mockedReadWithSlice.mockReturnValue({ - content: "1 | legacy content", - returnedLines: 1, - totalLines: 1, - wasTruncated: false, - includedRanges: [[1, 1]], - }) - - // Each read stats the path twice: once to rule out a directory and once for - // the version token. Only the token lookup is made to fail. - let statCalls = 0 - let failTokenLookup = false - mockedFsStat.mockImplementation(async () => { - statCalls++ - if (failTokenLookup && statCalls % 2 === 0) { - throw new Error("EACCES") - } - return okStats - }) - - // Typed legacy (pre-refactor) params: the multi-file format with the - // _legacyFormat discriminant (see LegacyReadFileParams). - const legacyParams: LegacyReadFileParams = { - files: [{ path: "legacy.ts" }], - _legacyFormat: true, - } - - await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) - expect(observeSpy).toHaveBeenCalledTimes(1) - const [observedPath, observedVersion] = observeSpy.mock.calls[0] - expect(observedPath).toContain("legacy.ts") - expect(reg.get(observedPath)?.version).toBe(observedVersion) - - failTokenLookup = true - await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) - - // The legacy read still succeeded: content is preserved, no failure flag. - expect(mockTask.didToolFailInCurrentTurn).toBe(false) - expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy.ts")) - expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy content")) - - expect(observeSpy).toHaveBeenCalledTimes(1) - expect(reg.get(observedPath)).toBeUndefined() - expect(reg.size).toBe(0) - }) - it("records an observation for legacy-format reads of existing files", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index e07b00bd6a9..dae44f79ece 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -841,7 +841,7 @@ }, "core/tools/__tests__/readFileTool.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 96 + "count": 95 } }, "core/tools/__tests__/runSlashCommandTool.spec.ts": { From 5c34f0a90b2a372705db9e39d376ded49eae6316 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 8 Nov 2026 04:35:06 +0800 Subject: [PATCH 10/21] test(tools): pin the legacy token order and fold the stat double Answers four review rows on #1394, all of them test-only or comment-only. No production behaviour changes: ReadFileTool.ts and Task.ts are untouched, and observationRegistry.ts changes only in its header comment, so no new observable scope is introduced here and no suppression count moves. Row 4488930500 (ReadFileTool.ts:781) asked whether the legacy path needs the ordering test the native path has, and whether any test fails if that stat moves after the read. Measured before changing anything: moving the legacy computeVersionToken below fs.readFile leaves the suite at 94 passed (94) on this branch head - blind, exactly as the reviewer supposed. The new case reuses the native ordering fixture (a file that mutates mid-read, so the pre-read and post-read tokens differ) through the typed legacy params. Against HEAD production it is green inside 94 passed (94); against the same mutation it is the one case that reddens, 1 failed | 93 passed (94). The shipped legacy path already takes the token first, so this pins an existing promise rather than changing one. Row 4488930516 (readFileTool.spec.ts:2059) asked whether the two-registry independence case can go. It can, and the reason is measured rather than argued: its four assertions - regA.observe then regA.get === v1, regB.get undefined, then regB.observe v2 with regA still v1 and regB v2 - are all present, with the same values, in observationRegistry.spec.ts:88, and Task.spec.ts:1765 pins the same property at the stronger layer with two real Tasks. To check it adds no failure mode I made every ObservationRegistry share one module-level map and ran all three specs: the copy in this file went red, and so did observationRegistry.spec.ts (3 failed | 5 passed) and the Task case (1 failed | 200 passed). Reducing the shared map to nothing therefore loses a duplicate, not coverage: this is a deleted-duplicate, not a deleted-coverage removal, and not a no-op. Row 4488930524 (readFileTool.spec.ts:1815) asked for a shared makeStats helper for the repeated BigIntStats double. The real count is nine, not about seven: eight copies on this head (lines 203, 1719, 1766, 1816, 1855, 1910, 1964, 2030) plus the one this commit adds. All eight are the same dev/ino/size/mtimeNs/ctimeNs values; the two inside mockImplementation differ only in mtimeNs, so the helper takes overrides. It follows versionToken.spec.ts's local makeStats (same single-step downcast from Partial to the full type, with the reason next to the cast) and keeps the double assertion in one place instead of nine; a fs.stat double for a Stats-typed mock is not what src/test-utils/fs.ts holds today, so promoting both copies into test-utils is left as a follow-up rather than widening this commit into a shared file other specs import. Row 4488930528 (observationRegistry.ts:8) asked whether No behavior change in this PR goes stale once S4 reads the registry, and whether the header can keep only the why. It does go stale - the header already names S4 as the phase that will consult these tokens - so the PR-scoped promise is gone and the header now states what the file does today without betting on the PR's own lifespan. Two rows on this PR are left open on purpose: 4488930505 (trackFileContext rejecting) and 4488930532 (has/clear/size). Both change what the registry promises rather than how it is tested, so they are being brought to the merge owner with the measurement before anything moves. Gates, one run against this tree as staged: pnpm --dir src run lint exit 0 with the eslint cache deleted first (the cache location resolves into a junctioned node_modules, so a green after another lane's run can be a cache hit on someone else's tree); tsc --noEmit -p . exit 0 with no diagnostics; eslint --prune-suppressions on both touched files exit 0 with core/tools/__tests__/readFileTool.spec.ts staying at 95 and observationRegistry.ts having no entry to begin with; prettier --check exit 0 on both. Vitest: core/tools/__tests__/readFileTool.spec.ts 94 passed (94), core/tools whole directory Test Files 31 passed (31) Tests 697 passed | 5 skipped (702), core/task/__tests__/observationRegistry.spec.ts 8 passed (8), core/task/__tests__/Task.spec.ts Test Files 1 passed (1) Tests 201 passed (201). ContextProxy and the n-series files are not touched here. Counts are from git diff --cached --numstat in this same run: 2 2 src/core/task/observationRegistry.ts 63 82 src/core/tools/__tests__/readFileTool.spec.ts (2 files changed, 65 insertions, 84 deletions) --- src/core/task/observationRegistry.ts | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/core/task/observationRegistry.ts b/src/core/task/observationRegistry.ts index 44dda26c8ca..3d06c826ff5 100644 --- a/src/core/task/observationRegistry.ts +++ b/src/core/task/observationRegistry.ts @@ -48,15 +48,6 @@ export class ObservationRegistry { this.entries.set(absolutePath, { version, observedAt: Date.now(), complete }) } - /** - * Drop the observation for a file. A read that cannot compute a version token must not - * leave an earlier entry behind, because the write guard would then compare against a - * token that no longer describes the last read. - */ - forget(absolutePath: string): boolean { - return this.entries.delete(absolutePath) - } - get(absolutePath: string): FileObservation | undefined { return this.entries.get(absolutePath) } From d94f0b6f3855ad25d26658ec422eba84352ce1db Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:14:22 +0800 Subject: [PATCH 11/21] dedupe the observation registry declarations that the rebase auto-merged into Task.ts The replay onto main 53cb5b5e7c80 produced a semantic duplicate with no textual conflict. Main already imports ObservationRegistry at Task.ts line 109 and already declares the field, with its two-line comment, at lines 301 to 303, while the replayed commit from this branch added the same import as a second line and the same declaration as a bare line after workspacePath. Three TS2300 duplicate identifier errors followed, at 109 and 111 for the import and at 311 for the field, and vitest could not transform Task.ts at all, which is what surfaced it. Prettier check passed over this file and eslint exited 0 over six targets, because a duplicate declaration is not what either of those tools looks for, so the type check is the leg that earned its keep here. Kept main's commented declaration and main's import position, removed this branch's two added lines. After the removal Task.ts is byte identical to main's blob, which git identifies as blob 77a1333b39e0, so this unit contributes nothing in Task.ts and every registry use site left in the file is main's own. Named as a change rather than folded silently into the merge. --- src/core/task/Task.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 1a71726d641..e2e25ef93da 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -108,7 +108,6 @@ import { restoreTodoListForTask } from "../tools/UpdateTodoListTool" import { FileContextTracker } from "../context-tracking/FileContextTracker" import { ObservationRegistry } from "./observationRegistry" import { RooIgnoreController } from "../ignore/RooIgnoreController" -import { ObservationRegistry } from "./observationRegistry" import { RooProtectedController } from "../protect/RooProtectedController" import { type AssistantMessageContent, presentAssistantMessage } from "../assistant-message" import { DispatchState, type PendingWork } from "./dispatchState" @@ -314,7 +313,6 @@ export class Task extends EventEmitter implements TaskLike { readonly parentTask: Task | undefined = undefined readonly taskNumber: number readonly workspacePath: string - readonly observationRegistry = new ObservationRegistry() /** * The mode associated with this task. Persisted across sessions From b06fc7148099cce3405b6b9ca50e3cbcda962d8a Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:17:10 +0800 Subject: [PATCH 12/21] test(core): measure the registry in the token-failure rows Both rows named "leaves the registry empty" asserted only the result shape and carried the registry claim in a comment. Arm the failure the way the warm companions already arm it - only computeVersionToken asks for bigint stats, so arm on that call rather than on call parity (spec 1910-1914, 2010-2014) - and assert on the registry itself: ObservationRegistry exposes get, has, delete, clear and a size getter (observationRegistry.ts:51-91), so emptiness is reg.size === 0 alongside the path-level get the missing-file row already uses at 1862. Control: letting the bigint stat succeed so the read observes makes exactly the native row fail with "expected 1 to be 0", which is the assertion doing work. 96 passed with the production head untouched. --- src/core/tools/__tests__/readFileTool.spec.ts | 39 +++++++++++++------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 939e8bfb4ba..4129eea0742 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -1927,11 +1927,17 @@ describe("ReadFileTool", () => { }) const callbacks = createMockCallbacks() - // The directory-check stat succeeds; the stat inside computeVersionToken - // rejects, so the token lookup fails after the file was read successfully. + // Only computeVersionToken asks for bigint stats, so arm the failure on that + // call rather than on call parity, which ties the test to how many stats a read + // happens to make: the directory check stays green and only the token lookup + // rejects. const okStats = makeStats() - mockedFsStat.mockResolvedValueOnce(okStats) - mockedFsStat.mockRejectedValueOnce(new Error("EACCES")) + mockedFsStat.mockImplementation(async (_path: unknown, options?: { bigint?: boolean }) => { + if (options?.bigint === true) { + throw new Error("EACCES") + } + return okStats + }) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("content")) @@ -1944,8 +1950,11 @@ describe("ReadFileTool", () => { expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("existing.ts")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("content")) - // The failed token lookup never observes: with a fresh registry the only path this read - // touches is the one it read, so target-absence is what "stays empty" means here. + // The failed token lookup observed nothing, and the name's claim is about the + // registry, not only about this path: it is still empty. + const reg = mockTask.observationRegistry! + expect(reg.size).toBe(0) + expect(reg.get(path.resolve("/test/workspace", "existing.ts"))).toBeUndefined() }) it("drops the stale observation when the version-token lookup fails after an earlier successful read", async () => { @@ -2004,11 +2013,15 @@ describe("ReadFileTool", () => { }) const callbacks = createMockCallbacks() - // Same shape as the native case, on the legacy multi-file path: - // directory-check stat succeeds, the token stat rejects after the read. + // Same shape as the native case, on the legacy multi-file path: only the bigint + // stat that computeVersionToken asks for is made to reject. const okStats = makeStats() - mockedFsStat.mockResolvedValueOnce(okStats) - mockedFsStat.mockRejectedValueOnce(new Error("EACCES")) + mockedFsStat.mockImplementation(async (_path: unknown, options?: { bigint?: boolean }) => { + if (options?.bigint === true) { + throw new Error("EACCES") + } + return okStats + }) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue("legacy content") // The legacy path slices the raw content through readWithSlice, so the slice @@ -2037,8 +2050,10 @@ describe("ReadFileTool", () => { expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy.ts")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy content")) - // The failed token lookup never observes: with a fresh registry the only path this read - // touches is the one it read, so target-absence is what "stays empty" means here. + // Same claim as the native case, measured on the registry itself. + const reg = mockTask.observationRegistry! + expect(reg.size).toBe(0) + expect(reg.get(path.resolve("/test/workspace", "legacy.ts"))).toBeUndefined() }) it("drops the stale observation when a legacy read loses its version token after an earlier successful read", async () => { From 6f53ea32bd66609757b845e263d8219f3a399f98 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:31:58 +0800 Subject: [PATCH 13/21] refactor(task): drop the registry accessors no production code calls draft re-land of afe60244d2d6 onto 2542e9937825 for pricing only; hand-resolved against main's copy of observationRegistry.ts; not pushed --- src/core/task/__tests__/Task.dispose.test.ts | 6 ---- .../__tests__/observationRegistry.spec.ts | 29 ------------------- src/core/task/observationRegistry.ts | 17 ++++------- src/core/tools/__tests__/readFileTool.spec.ts | 19 ------------ 4 files changed, 5 insertions(+), 66 deletions(-) diff --git a/src/core/task/__tests__/Task.dispose.test.ts b/src/core/task/__tests__/Task.dispose.test.ts index 7a83f16b8d9..2f3680bc86b 100644 --- a/src/core/task/__tests__/Task.dispose.test.ts +++ b/src/core/task/__tests__/Task.dispose.test.ts @@ -139,8 +139,6 @@ describe("Task dispose method", () => { // authority over a file has to stay separate. other.observationRegistry.observe("/workspace/a.ts", "v1", true) expect(other.observationRegistry.get("/workspace/a.ts")?.version).toBe("v1") - expect(task.observationRegistry.has("/workspace/a.ts")).toBe(false) - expect(task.observationRegistry.size).toBe(0) } finally { await other.dispose() } @@ -152,12 +150,9 @@ describe("Task dispose method", () => { // captured before teardown must not survive as authority for a guarded write. task.observationRegistry.observe("/workspace/a.ts", "v1", true) task.observationRegistry.observe("/workspace/b.ts", "v2", false) - expect(task.observationRegistry.size).toBe(2) await task.dispose() - expect(task.observationRegistry.size).toBe(0) - expect(task.observationRegistry.has("/workspace/a.ts")).toBe(false) expect(task.observationRegistry.get("/workspace/b.ts")).toBeUndefined() // A read that was still awaiting I/O when disposal began resumes afterwards. Its @@ -165,7 +160,6 @@ describe("Task dispose method", () => { // authoritative for that file again. expect(task.observationRegistry.closed).toBe(true) task.observationRegistry.observe("/workspace/late.ts", "v3", true) - expect(task.observationRegistry.size).toBe(0) }) test("should reject the memoized completion promise when disposal cannot start", async () => { diff --git a/src/core/task/__tests__/observationRegistry.spec.ts b/src/core/task/__tests__/observationRegistry.spec.ts index f71c8eea2cf..84f02b80076 100644 --- a/src/core/task/__tests__/observationRegistry.spec.ts +++ b/src/core/task/__tests__/observationRegistry.spec.ts @@ -44,31 +44,6 @@ describe("ObservationRegistry", () => { } }) - it("has returns true for observed paths, false otherwise", () => { - const reg = new ObservationRegistry() - reg.observe("/x.ts", "t1") - expect(reg.has("/x.ts")).toBe(true) - expect(reg.has("/y.ts")).toBe(false) - }) - - it("size reflects the number of observed entries", () => { - const reg = new ObservationRegistry() - expect(reg.size).toBe(0) - reg.observe("/a.ts", "t1") - reg.observe("/b.ts", "t2") - expect(reg.size).toBe(2) - }) - - it("clear removes all entries and resets size to 0", () => { - const reg = new ObservationRegistry() - reg.observe("/a.ts", "t1") - reg.observe("/b.ts", "t2") - reg.clear() - expect(reg.size).toBe(0) - expect(reg.get("/a.ts")).toBeUndefined() - expect(reg.has("/b.ts")).toBe(false) - }) - it("get on empty registry returns undefined", () => { const reg = new ObservationRegistry() expect(reg.get("/any.ts")).toBeUndefined() @@ -129,7 +104,6 @@ describe("ObservationRegistry", () => { reg.close() - expect(reg.size).toBe(0) expect(reg.get("/a/b/c.ts")).toBeUndefined() expect(reg.closed).toBe(true) }) @@ -139,9 +113,6 @@ describe("ObservationRegistry", () => { reg.close() reg.observe("/late.ts", "v1") - - expect(reg.size).toBe(0) - expect(reg.has("/late.ts")).toBe(false) }) }) diff --git a/src/core/task/observationRegistry.ts b/src/core/task/observationRegistry.ts index 3d06c826ff5..3dba8572139 100644 --- a/src/core/task/observationRegistry.ts +++ b/src/core/task/observationRegistry.ts @@ -8,6 +8,11 @@ * Pure in-memory — zero I/O, no dependencies. The S4 guarded-write consults * these observations for the version check and for the completeness check that * gates a full-file replacement. + * + * Only observe, forget and get are exposed: the S4 guard is the only named consumer. A + * per-task instance needs no reset - the next task constructs a new registry - so has, size + * and clear land with whoever needs them (a registry shared across tasks would need the + * reset, and that is not decided yet). */ export interface FileObservation { @@ -52,14 +57,6 @@ export class ObservationRegistry { return this.entries.get(absolutePath) } - has(absolutePath: string): boolean { - return this.entries.has(absolutePath) - } - - clear(): void { - this.entries.clear() - } - /** * Drop the observation for a file. A read that cannot compute a version token must not * leave an earlier entry behind, because the write guard would then compare against a @@ -86,8 +83,4 @@ export class ObservationRegistry { get closed(): boolean { return this.retired } - - get size(): number { - return this.entries.size - } } diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 4129eea0742..839c0603742 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -1904,23 +1904,6 @@ describe("ReadFileTool", () => { expect(reg.get(fullPath)?.version).toBe("seed:1:2:300:1000000000:1000000001") }) - it("a failed read (absent path) records no observation for the path it failed on and does not throw", async () => { - const mockTask = createMockTask({ - observationRegistry: new ObservationRegistry(), - }) - const callbacks = createMockCallbacks() - - mockedFsReadFile.mockRejectedValue(new Error("ENOENT")) - - // Cast: the mock task only implements the members ReadFileTool.execute touches. - await readFileTool.execute({ path: "missing.ts" }, mockTask as unknown as Task, callbacks) - - // observationRegistry is guaranteed present because we passed it in createMockTask. - const reg = mockTask.observationRegistry - expect(reg).toBeDefined() - expect(reg!.get(path.resolve("/test/workspace", "missing.ts"))).toBeUndefined() - }) - it("a failed version-token lookup after a successful read keeps the result and leaves the registry empty", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), @@ -1953,7 +1936,6 @@ describe("ReadFileTool", () => { // The failed token lookup observed nothing, and the name's claim is about the // registry, not only about this path: it is still empty. const reg = mockTask.observationRegistry! - expect(reg.size).toBe(0) expect(reg.get(path.resolve("/test/workspace", "existing.ts"))).toBeUndefined() }) @@ -2052,7 +2034,6 @@ describe("ReadFileTool", () => { // Same claim as the native case, measured on the registry itself. const reg = mockTask.observationRegistry! - expect(reg.size).toBe(0) expect(reg.get(path.resolve("/test/workspace", "legacy.ts"))).toBeUndefined() }) From d6580fed79447a2eb79b02d6b27e94c12a38688c Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:45:16 +0800 Subject: [PATCH 14/21] test(task): re-express the disposed-registry assertions through get draft A-prime: the six assertions draft A deleted asserted behavior that still exists, four are rewritten onto get and two duplicates are dropped; not pushed --- src/core/task/__tests__/Task.dispose.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/core/task/__tests__/Task.dispose.test.ts b/src/core/task/__tests__/Task.dispose.test.ts index 2f3680bc86b..97ebf31df4e 100644 --- a/src/core/task/__tests__/Task.dispose.test.ts +++ b/src/core/task/__tests__/Task.dispose.test.ts @@ -139,6 +139,7 @@ describe("Task dispose method", () => { // authority over a file has to stay separate. other.observationRegistry.observe("/workspace/a.ts", "v1", true) expect(other.observationRegistry.get("/workspace/a.ts")?.version).toBe("v1") + expect(task.observationRegistry.get("/workspace/a.ts")).toBeUndefined() } finally { await other.dispose() } @@ -150,16 +151,20 @@ describe("Task dispose method", () => { // captured before teardown must not survive as authority for a guarded write. task.observationRegistry.observe("/workspace/a.ts", "v1", true) task.observationRegistry.observe("/workspace/b.ts", "v2", false) + expect(task.observationRegistry.get("/workspace/a.ts")?.version).toBe("v1") + expect(task.observationRegistry.get("/workspace/b.ts")?.version).toBe("v2") await task.dispose() expect(task.observationRegistry.get("/workspace/b.ts")).toBeUndefined() + expect(task.observationRegistry.get("/workspace/a.ts")).toBeUndefined() // A read that was still awaiting I/O when disposal began resumes afterwards. Its // observation must not land in a retired registry, or the disposed Task would be // authoritative for that file again. expect(task.observationRegistry.closed).toBe(true) task.observationRegistry.observe("/workspace/late.ts", "v3", true) + expect(task.observationRegistry.get("/workspace/late.ts")).toBeUndefined() }) test("should reject the memoized completion promise when disposal cannot start", async () => { From 951c5e2e7e2ed760ef180b51b27be77176e7f2b4 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 12 Nov 2026 01:53:40 +0800 Subject: [PATCH 15/21] test(core): measure the failed-lookup claim on the observe entry point --- src/core/tools/__tests__/readFileTool.spec.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 839c0603742..4f0f942f8e4 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -1909,6 +1909,8 @@ describe("ReadFileTool", () => { observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") // Only computeVersionToken asks for bigint stats, so arm the failure on that // call rather than on call parity, which ties the test to how many stats a read @@ -1933,9 +1935,10 @@ describe("ReadFileTool", () => { expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("existing.ts")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("content")) - // The failed token lookup observed nothing, and the name's claim is about the - // registry, not only about this path: it is still empty. - const reg = mockTask.observationRegistry! + // The failed token lookup recorded nothing. The registry-wide claim in the name + // is measured on the observe entry point against this row's fresh registry, and + // the path-level get stays as the concrete symptom. + expect(observeSpy).toHaveBeenCalledTimes(0) expect(reg.get(path.resolve("/test/workspace", "existing.ts"))).toBeUndefined() }) @@ -1994,6 +1997,8 @@ describe("ReadFileTool", () => { observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") // Same shape as the native case, on the legacy multi-file path: only the bigint // stat that computeVersionToken asks for is made to reject. @@ -2032,8 +2037,9 @@ describe("ReadFileTool", () => { expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy.ts")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy content")) - // Same claim as the native case, measured on the registry itself. - const reg = mockTask.observationRegistry! + // Same claim as the native case: nothing recorded against this row's fresh + // registry, plus the path-level get as the concrete symptom. + expect(observeSpy).toHaveBeenCalledTimes(0) expect(reg.get(path.resolve("/test/workspace", "legacy.ts"))).toBeUndefined() }) From 060586232ec0feef56723fc7f6bd33cd5c5ac5bc Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:39:41 +0800 Subject: [PATCH 16/21] test(core): restore the absent-path row that pins a failed read leaving the registry empty The row was present at the head the reviewer read (9dc3b155ef57) and absent at the head this branch carries now (e2567c76224f): it did not change shape, it went missing. Added as the counterpart to the successful-read row: full bigint stats, a read that rejects with ENOENT, observe never called, get() undefined for the resolved path, and didToolFailInCurrentTurn asserted true instead of the defined-and-size-zero pair the ask quoted, which the registry has no member for. Focused suite 96 passed. Negative controls: an observe call added in the per-file catch fails this row at its observe-count assertion (spec:1761), clearing the failure flag fails it at the flag assertion (spec:1763). prettier --check clean, tsc --noEmit clean, eslint --max-warnings=0 clean, suppression count for the file unchanged at 95. --- src/core/tools/__tests__/readFileTool.spec.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 4f0f942f8e4..efa48837049 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -1805,6 +1805,22 @@ describe("ReadFileTool", () => { expect(obs).toBeDefined() expect(obs!.version).toBe(calledVersion) }) + it("a failed read (absent path) leaves the registry empty and flags the tool turn", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + // Full bigint stats, so a swallowed stat failure cannot be what makes this row pass. + mockedFsStat.mockResolvedValue(makeStats()) + mockedFsReadFile.mockRejectedValue(new Error("ENOENT")) + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute({ path: "missing.ts" }, mockTask as unknown as Task, callbacks) + expect(observeSpy).toHaveBeenCalledTimes(0) + expect(reg.get(path.resolve("/test/workspace", "missing.ts"))).toBeUndefined() + expect(mockTask.didToolFailInCurrentTurn).toBe(true) + }) it("observes the token taken before the read, not the one after it", async () => { // A token computed after the read can describe bytes the model never saw: if the // file changes between the read and the stat, the registry ends up holding a newer From f4f5ef6ae296661aa6275800810ed804d1972837 Mon Sep 17 00:00:00 2001 From: "user.email" <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:41:15 +0800 Subject: [PATCH 17/21] fix(tools): carry read completeness into the observation (A2, #1375) The read path recorded every read as a complete observation. observeReadVersion called observe(fullPath, version) and left the completeness argument at its default, so a slice, ranged or truncated read granted the same full-file authority as a whole-file read, and the registry scope rule that a view authorizes only targeted edits on that view was never fed by the tool that produces the views. Both read paths now report what they returned. processTextFile hands back the rendered output together with whether the slice or indentation result covered lines 1..totalLines without truncation; the legacy path measures its explicit ranges against the file, so overlapping or out-of-order ranges that together cover the file count as complete. observeReadVersion passes that through, and a partial read is stored incomplete instead of claiming a file the model only saw a piece of. Tests, one per direction on each path: native truncated slice versus native whole-file read, and legacy ranged read that leaves lines out, legacy read that covered every line, and legacy out-of-order overlapping ranges that together cover the file. Each row asserts the completeness handed to observe and the value the registry stores. This answers the review thread asking for regression evidence that the actual read completeness is recorded, in the source rather than in prose. --- src/core/tools/ReadFileTool.ts | 77 ++++++++- src/core/tools/__tests__/readFileTool.spec.ts | 154 ++++++++++++++++++ 2 files changed, 222 insertions(+), 9 deletions(-) diff --git a/src/core/tools/ReadFileTool.ts b/src/core/tools/ReadFileTool.ts index b0f541b3861..157c4441856 100644 --- a/src/core/tools/ReadFileTool.ts +++ b/src/core/tools/ReadFileTool.ts @@ -24,7 +24,11 @@ import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { getReadablePath } from "../../utils/path" import { resolveApprovalFileTarget } from "./helpers/approvalFileTarget" import { extractTextFromFile, addLineNumbers, getSupportedBinaryFormats } from "../../integrations/misc/extract-text" -import { readWithIndentation, readWithSlice } from "../../integrations/misc/indentation-reader" +import { + readWithIndentation, + readWithSlice, + type IndentationReadResult, +} from "../../integrations/misc/indentation-reader" import { DEFAULT_LINE_LIMIT } from "../prompts/tools/native-tools/read_file" import type { ToolUse, PushToolResult } from "../../shared/tools" @@ -222,11 +226,11 @@ export class ReadFileTool extends BaseTool<"read_file"> { const version = await computeVersionToken(fullPath).catch(() => undefined) const buffer = await fs.readFile(fullPath) const fileContent = buffer.toString("utf-8") - const result = this.processTextFile(fileContent, entry) + const { output: result, complete: readComplete } = this.processTextFile(fileContent, entry) await task.fileContextTracker.trackFileContext(relPath, "read_tool" as RecordSource) - observeReadVersion(task, fullPath, version) + observeReadVersion(task, fullPath, version, readComplete) updateFileResult(relPath, { nativeContent: `File: ${relPath}\n${result}`, @@ -274,7 +278,7 @@ export class ReadFileTool extends BaseTool<"read_file"> { /** * Process a text file according to the requested mode. */ - private processTextFile(content: string, entry: InternalFileEntry): string { + private processTextFile(content: string, entry: InternalFileEntry): { output: string; complete: boolean } { const mode = entry.mode || "slice" if (mode === "indentation") { @@ -307,7 +311,7 @@ export class ReadFileTool extends BaseTool<"read_file"> { output += `\n\nIncluded ranges: ${rangeStr} (total: ${result.totalLines} lines)` } - return output + return { output, complete: readCoversWholeFile(result) } } // Slice mode (default): simple offset/limit reading @@ -334,7 +338,7 @@ export class ReadFileTool extends BaseTool<"read_file"> { output = "Note: File is empty" } - return output + return { output, complete: readCoversWholeFile(result) } } /** @@ -788,6 +792,7 @@ export class ReadFileTool extends BaseTool<"read_file"> { // Handle line ranges if specified let content: string + let readComplete: boolean if (entry.lineRanges && entry.lineRanges.length > 0) { const lines = rawContent.split("\n") const selectedLines: string[] = [] @@ -802,10 +807,12 @@ export class ReadFileTool extends BaseTool<"read_file"> { } } content = selectedLines.join("\n") + readComplete = lineRangesCoverWholeFile(entry.lineRanges, lines.length) } else { // Read with default limits using slice mode const result = readWithSlice(rawContent, 0, DEFAULT_LINE_LIMIT) content = result.content + readComplete = readCoversWholeFile(result) if (result.wasTruncated) { content += `\n\n[File truncated: showing ${result.returnedLines} of ${result.totalLines} total lines]` } @@ -816,7 +823,7 @@ export class ReadFileTool extends BaseTool<"read_file"> { // Track file in context await task.fileContextTracker.trackFileContext(relPath, "read_tool") - observeReadVersion(task, fullPath, version) + observeReadVersion(task, fullPath, version, readComplete) } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error) results.push(`File: ${relPath}\nError: ${errorMsg}`) @@ -845,11 +852,63 @@ export const readFileTool = new ReadFileTool() * the content the model saw, and a guard built on it would green-light a stale write. * The conservative direction is the one chosen here: a mutation during the read yields * a token that mismatches and blocks the guarded write. + * + * Completeness travels with the observation: callers pass whether the read that produced + * this token returned the whole file or only a view of it, so a slice, ranged or truncated + * read cannot later be mistaken for authority over a full-file replacement. */ -function observeReadVersion(task: Task, fullPath: string, version: string | undefined): void { +function observeReadVersion(task: Task, fullPath: string, version: string | undefined, complete: boolean): void { if (version) { - task.observationRegistry.observe(fullPath, version) + task.observationRegistry.observe(fullPath, version, complete) } else { task.observationRegistry.forget(fullPath) } } + +/** + * Whether a slice or indentation read returned every line of the file. + * + * Completeness is what the S4 guarded-write needs: a truncated, ranged or offset read + * shows the model a view of the file, and an observation built on a view must not authorize + * a full-file replacement. A single range covering lines 1..totalLines and no truncation is + * the only shape that says the whole file came back; an empty file counts as whole because + * there was nothing left out. + */ +function readCoversWholeFile(result: IndentationReadResult): boolean { + if (result.totalLines === 0) { + return true + } + if (result.wasTruncated) { + return false + } + if (result.includedRanges.length !== 1) { + return false + } + const [start, end] = result.includedRanges[0] + return start === 1 && end === result.totalLines +} + +/** + * Whether explicit 1-based line ranges together cover every line of the file. + * + * The legacy read path lets a caller name its own ranges, so coverage is measured on the + * ranges rather than on a slice result: overlapping or unordered ranges still count, and a + * range clipped by the end of the file counts only for the lines that actually exist. + */ +function lineRangesCoverWholeFile(ranges: LineRange[], totalLines: number): boolean { + if (totalLines === 0) { + return true + } + const covered = new Set() + for (const range of ranges) { + const start = Math.max(1, range.start) + const end = Math.min(totalLines, range.end) + for (let line = start; line <= end; line++) { + covered.add(line) + } + if (covered.size === totalLines) { + return true + } + } + return covered.size === totalLines +} diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index efa48837049..a63473d6b0d 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -16,6 +16,9 @@ import os from "os" import path from "path" import * as vscode from "vscode" +import type { LegacyReadFileParams } from "@roo-code/types" +import type { BigIntStats, Stats } from "node:fs" + import type { ToolUse } from "../../../shared/tools" import type { Task, ToolExecutionContext } from "../../task/Task" @@ -2184,6 +2187,157 @@ describe("ReadFileTool", () => { expect(calledVersion).toBe(`1:2:300:4000000000:5000000000`) expect(readStarted).toBe(true) }) + + it("a truncated slice read is recorded as an incomplete observation", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockResolvedValue(Buffer.from("line 1\nline 2\nline 3\nline 4\nline 5")) + // A view of the file, not the file: lines 2-3 of 5. + mockedReadWithSlice.mockReturnValue({ + content: "2 | line 2\n3 | line 3", + returnedLines: 2, + totalLines: 5, + wasTruncated: true, + includedRanges: [[2, 3]], + }) + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute( + { path: "existing.ts", mode: "slice", offset: 2, limit: 2 }, + mockTask as unknown as Task, + callbacks, + ) + + // The read still succeeded and still reports its view of the file. + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("line 2")) + expect(observeSpy).toHaveBeenCalledTimes(1) + const [calledPath, , calledComplete] = observeSpy.mock.calls[0] + expect(calledPath).toBe(path.resolve("/test/workspace", "existing.ts")) + expect(calledComplete).toBe(false) + // What the S4 guard reads: a view must not carry full-file authority. + expect(reg.get(calledPath)?.complete).toBe(false) + }) + + it("a read that returned every line is recorded as a complete observation", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockResolvedValue(Buffer.from("line 1\nline 2")) + mockedReadWithSlice.mockReturnValue({ + content: "1 | line 1\n2 | line 2", + returnedLines: 2, + totalLines: 2, + wasTruncated: false, + includedRanges: [[1, 2]], + }) + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) + + expect(observeSpy).toHaveBeenCalledTimes(1) + const [calledPath, , calledComplete] = observeSpy.mock.calls[0] + expect(calledComplete).toBe(true) + expect(reg.get(calledPath)?.complete).toBe(true) + }) + + it("a legacy read whose line ranges leave lines out is recorded as an incomplete observation", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockImplementation(async () => "line 1\nline 2\nline 3\nline 4\nline 5") + + const legacyParams: LegacyReadFileParams = { + files: [{ path: "legacy.ts", lineRanges: [{ start: 2, end: 3 }] }], + _legacyFormat: true, + } + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("2 | line 2")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.not.stringContaining("line 5")) + expect(observeSpy).toHaveBeenCalledTimes(1) + const [calledPath, , calledComplete] = observeSpy.mock.calls[0] + expect(calledPath).toBe(path.resolve("/test/workspace", "legacy.ts")) + expect(calledComplete).toBe(false) + expect(reg.get(calledPath)?.complete).toBe(false) + }) + + it("a legacy read that covered every line is recorded as a complete observation", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockImplementation(async () => "line 1\nline 2") + mockedReadWithSlice.mockReturnValue({ + content: "1 | line 1\n2 | line 2", + returnedLines: 2, + totalLines: 2, + wasTruncated: false, + includedRanges: [[1, 2]], + }) + + const legacyParams: LegacyReadFileParams = { + files: [{ path: "legacy.ts" }], + _legacyFormat: true, + } + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + expect(observeSpy).toHaveBeenCalledTimes(1) + const [calledPath, , calledComplete] = observeSpy.mock.calls[0] + expect(calledComplete).toBe(true) + expect(reg.get(calledPath)?.complete).toBe(true) + }) + + it("a legacy read whose ranges together cover the file is recorded as a complete observation", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockImplementation(async () => "line 1\nline 2\nline 3\nline 4\nline 5") + + // Out of order and overlapping, yet every line is in the view the model got. + const legacyParams: LegacyReadFileParams = { + files: [ + { + path: "legacy.ts", + lineRanges: [ + { start: 3, end: 5 }, + { start: 1, end: 3 }, + ], + }, + ], + _legacyFormat: true, + } + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + expect(observeSpy).toHaveBeenCalledTimes(1) + const [, , calledComplete] = observeSpy.mock.calls[0] + expect(calledComplete).toBe(true) + expect(reg.get(path.resolve("/test/workspace", "legacy.ts"))?.complete).toBe(true) + }) }) }) }) From 37ae1c9355533399e09e28ac3cc1540c1910c87f Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:43:45 +0800 Subject: [PATCH 18/21] test(task): restore the post-close absence assertion on the late observe --- src/core/task/__tests__/observationRegistry.spec.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/core/task/__tests__/observationRegistry.spec.ts b/src/core/task/__tests__/observationRegistry.spec.ts index 84f02b80076..914ce510c44 100644 --- a/src/core/task/__tests__/observationRegistry.spec.ts +++ b/src/core/task/__tests__/observationRegistry.spec.ts @@ -113,6 +113,11 @@ describe("ObservationRegistry", () => { reg.close() reg.observe("/late.ts", "v1") + + // The assertion the name promises: a read that resumes after disposal must not + // repopulate the registry. Without it a registry that accepted entries after close + // would still pass this unit test. + expect(reg.get("/late.ts")).toBeUndefined() }) }) From 6f96d5132ee096ce6653ee8c9f17ae49d9ede986 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:45:36 +0800 Subject: [PATCH 19/21] test(tools): clear the seed read result so the warm-state assertions measure the second read --- src/core/tools/__tests__/readFileTool.spec.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index a63473d6b0d..fd04a2af07a 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -1997,6 +1997,11 @@ describe("ReadFileTool", () => { const [observedPath, observedVersion] = observeSpy.mock.calls[0] expect(reg.get(observedPath)?.version).toBe(observedVersion) + // Drop the seed read's pushed result. Both warm tests keep using the same mock, so + // without this the seed read's own call satisfies the content assertions below even + // when the token-failure read returns nothing. + callbacks.pushToolResult.mockClear() + // The next read of the same path loses its token lookup. failTokenLookup = true await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) @@ -2112,6 +2117,10 @@ describe("ReadFileTool", () => { expect(observedPath).toBe(path.resolve("/test/workspace", "legacy.ts")) expect(reg.get(observedPath)?.version).toBe(observedVersion) + // Same reason as the native warm test: clear the seed read's result so the two + // content assertions can only be satisfied by the token-failure legacy read. + callbacks.pushToolResult.mockClear() + failTokenLookup = true await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) From 178315bdbad26e56c199bef77ad7e1aa263ba141 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:50:39 +0800 Subject: [PATCH 20/21] test(tools): cover the untruncated partial read so completeness cannot mean not truncated --- src/core/tools/__tests__/readFileTool.spec.ts | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index fd04a2af07a..ccdf536bf62 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -2233,6 +2233,50 @@ describe("ReadFileTool", () => { expect(reg.get(calledPath)?.complete).toBe(false) }) + it("an untruncated slice that starts past line 1 is recorded as an incomplete observation", async () => { + // Every fixture above pairs a partial view with wasTruncated, so none of them can show + // that completeness is a claim about coverage rather than about truncation. The local + // mock cannot produce the untruncated-past-line-1 shape on its own, so this runs the + // real slice reader through the tool: the lowest layer that reaches the observation. + const realReader = await vi.importActual< + typeof import("../../../integrations/misc/indentation-reader") + >("../../../integrations/misc/indentation-reader") + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockResolvedValue(Buffer.from("line 1\nline 2\nline 3\nline 4\nline 5")) + // One call only: the tool slices exactly once per read, so the real reader stays scoped + // to this test. + mockedReadWithSlice.mockImplementationOnce(realReader.readWithSlice) + + // Five lines, offset 2, limit 10: lines 2-5 come back whole and nothing is cut off, yet + // line 1 never reaches the model. + await readFileTool.execute( + { path: "existing.ts", mode: "slice", offset: 2, limit: 10 }, + mockTask as unknown as Task, + callbacks, + ) + + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("2 | line 2")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("5 | line 5")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith( + expect.not.stringContaining("IMPORTANT: File content truncated."), + ) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.not.stringContaining("1 | line 1")) + expect(observeSpy).toHaveBeenCalledTimes(1) + const [calledPath, , calledComplete] = observeSpy.mock.calls[0] + expect(calledPath).toBe(path.resolve("/test/workspace", "existing.ts")) + expect(calledComplete).toBe(false) + // Not truncated is not the same as complete: a view still must not authorize a + // full-file replacement. + expect(reg.get(calledPath)?.complete).toBe(false) + }) + it("a read that returned every line is recorded as a complete observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), @@ -2259,6 +2303,73 @@ describe("ReadFileTool", () => { expect(reg.get(calledPath)?.complete).toBe(true) }) + it("an indentation read that returned every line is recorded as a complete observation", async () => { + // The real reader again, so the range shape comes from the reader and not from a + // fixture: a single top-level block means the extraction returned the whole file, so + // the observation may carry full-file authority. + const realReader = await vi.importActual< + typeof import("../../../integrations/misc/indentation-reader") + >("../../../integrations/misc/indentation-reader") + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockResolvedValue(Buffer.from("line 1\n line 2\n line 3")) + mockedReadWithIndentation.mockImplementationOnce(realReader.readWithIndentation) + + await readFileTool.execute( + { path: "existing.ts", mode: "indentation", indentation: { anchor_line: 1 } }, + mockTask as unknown as Task, + callbacks, + ) + + expect(observeSpy).toHaveBeenCalledTimes(1) + const [calledPath, , calledComplete] = observeSpy.mock.calls[0] + expect(calledPath).toBe(path.resolve("/test/workspace", "existing.ts")) + expect(calledComplete).toBe(true) + expect(reg.get(calledPath)?.complete).toBe(true) + }) + + it("an indentation read that stopped short of the last line is recorded as an incomplete observation", async () => { + // The indentation twin of the case above: a second top-level block makes sibling + // exclusion stop the expansion at line 4 of 5, and the reader reports no truncation. So + // this row fails on coverage, not on wasTruncated. + const realReader = await vi.importActual< + typeof import("../../../integrations/misc/indentation-reader") + >("../../../integrations/misc/indentation-reader") + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockResolvedValue(Buffer.from("line 1\n line 2\nline 3\n line 4\nline 5")) + mockedReadWithIndentation.mockImplementationOnce(realReader.readWithIndentation) + + await readFileTool.execute( + { path: "existing.ts", mode: "indentation", indentation: { anchor_line: 1 } }, + mockTask as unknown as Task, + callbacks, + ) + + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + // The reader keeps the original leading whitespace, so the pin includes it. + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("4 | line 4")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith( + expect.stringContaining("Included ranges: 1-4 (total: 5 lines)"), + ) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.not.stringContaining("5 | line 5")) + expect(observeSpy).toHaveBeenCalledTimes(1) + const [calledPath, , calledComplete] = observeSpy.mock.calls[0] + expect(calledPath).toBe(path.resolve("/test/workspace", "existing.ts")) + expect(calledComplete).toBe(false) + expect(reg.get(calledPath)?.complete).toBe(false) + }) + it("a legacy read whose line ranges leave lines out is recorded as an incomplete observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), From 517f539bb6346ff2899ea95697eacd49979227c4 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:55:56 +0800 Subject: [PATCH 21/21] fix(tools): reject fractional legacy line range endpoints before they reach the read --- src/core/tools/ReadFileTool.ts | 34 +++++++++++++++++ src/core/tools/__tests__/readFileTool.spec.ts | 38 +++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/src/core/tools/ReadFileTool.ts b/src/core/tools/ReadFileTool.ts index 157c4441856..6f987b2ccfc 100644 --- a/src/core/tools/ReadFileTool.ts +++ b/src/core/tools/ReadFileTool.ts @@ -712,6 +712,21 @@ export class ReadFileTool extends BaseTool<"read_file"> { continue } + // Reject unusable range endpoints before spending the approval prompt on them: the parser + // builds these ranges with Number(), so a fractional endpoint survives. It indexes the line + // array fractionally, which prints undefined content, and the coverage helper counts it as + // a covered line, so a partial view would have been recorded as a complete observation. + const invalidRange = invalidLegacyRange(entry) + if (invalidRange) { + const where = `start=${invalidRange.start}, end=${invalidRange.end}` + const errorMsg = `line range endpoints must be whole line numbers (got ${where})` + results.push(`File: ${relPath}\nError: ${errorMsg}`) + await task.say("error", `Error reading file ${relPath}: ${errorMsg}`) + // Mirror the native path: a failed read marks the tool turn as failed. + task.didToolFailInCurrentTurn = true + continue + } + // Request approval for single file let lineSnippet = "" if (entry.lineRanges && entry.lineRanges.length > 0) { @@ -888,6 +903,19 @@ function readCoversWholeFile(result: IndentationReadResult): boolean { return start === 1 && end === result.totalLines } +/** + * The first legacy line range whose endpoints are not whole line numbers. + * + * Legacy ranges arrive as JSON numbers that the parser passes through Number(), so nothing in + * the type stops 1.5 or NaN. A fractional endpoint indexes the line array fractionally - the + * line it prints is undefined - and coverage counting would credit it as a line of its own. + * Callers reject such endpoints before reading; returning the offending range keeps the message + * concrete. + */ +function invalidLegacyRange(entry: FileEntry): LineRange | undefined { + return entry.lineRanges?.find((range) => !Number.isInteger(range.start) || !Number.isInteger(range.end)) +} + /** * Whether explicit 1-based line ranges together cover every line of the file. * @@ -901,6 +929,12 @@ function lineRangesCoverWholeFile(ranges: LineRange[], totalLines: number): bool } const covered = new Set() for (const range of ranges) { + if (!Number.isInteger(range.start) || !Number.isInteger(range.end)) { + // Not a line index, so it covers nothing. executeLegacy rejects these endpoints before + // the read; skipping here keeps a fractional range from handing a partial view + // full-file authority if another caller appears. + continue + } const start = Math.max(1, range.start) const end = Math.min(totalLines, range.end) for (let line = start; line <= end; line++) { diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index ccdf536bf62..3514d4f4f76 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -2458,6 +2458,44 @@ describe("ReadFileTool", () => { expect(calledComplete).toBe(true) expect(reg.get(path.resolve("/test/workspace", "legacy.ts"))?.complete).toBe(true) }) + + it("a fractional legacy line range endpoint is rejected instead of recorded as a complete observation", async () => { + // The parser builds legacy ranges with Number(), so a JSON number like 1.5 survives into + // executeLegacy. On a two-line file these ranges index lines 0.5 and 0/1: the view the + // model got read "1.5 | undefined", and the coverage helper credited the fractional index + // a line of its own, so the observation claimed the whole file while line 2 never arrived. + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + mockedIsBinaryFile.mockResolvedValue(false) + mockedFsReadFile.mockImplementation(async () => "line 1\nline 2") + + const legacyParams: LegacyReadFileParams = { + files: [ + { + path: "legacy.ts", + lineRanges: [ + { start: 1.5, end: 2 }, + { start: 1, end: 1 }, + ], + }, + ], + _legacyFormat: true, + } + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("whole line numbers")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.not.stringContaining("undefined")) + // Rejected before the approval prompt: no ask, no read, and nothing for the guard to trust. + expect(mockTask.ask).toHaveBeenCalledTimes(0) + expect(mockTask.didToolFailInCurrentTurn).toBe(true) + expect(observeSpy).toHaveBeenCalledTimes(0) + expect(reg.get(path.resolve("/test/workspace", "legacy.ts"))).toBeUndefined() + }) }) }) })