Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion knip.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
"!utils/versionToken.ts!",
"!services/tools/Bm25Ranker.ts!",
"!services/tools/types.ts!",
"!core/tools/helpers/toolResultFormatting.ts!"
"!core/tools/helpers/toolResultFormatting.ts!",
"!core/tools/guardedWrite.ts!"
],
"ignoreDependencies": [
"@roo-code/config-typescript",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,40 @@ function historyFilePath(storagePath: string, taskId: string): string {
return path.join(storagePath, "tasks", taskId, GlobalFileNames.historyItem)
}

// The delete locks the file it unlinks, and the spelling of that path is whatever the
// store was given: `delete` hands `deleteJsonFile` a joined path, `deleteJsonFile` hands it
// to `withFileLock`, and `withFileLock` only `path.resolve`s it -- the canonicalisation
// through fs/promises realpath happens deeper, when the lock file itself is placed, so it
// never reaches this spy. On the Windows runner the two spellings of one temp file differ
// (C:/Users/runneradmin/... and its NTFS 8.3 alias C:/Users/RUNNER~1/...), so comparing the
// key by text holds on a developer box and misses there. File identity is the comparison
// that holds on both spellings, which is how the landed
// src/utils/__tests__/safeWriteJson.interruption.test.ts handles the same hazard.
async function fileIdentity(candidate: string): Promise<string | null> {
try {
const stats = await actualFs.stat(candidate)
return `${stats.dev}:${stats.ino}`
} catch {
return null
}
}

async function lockKeyNamesTheSameFile(lockKey: unknown, expectedPath: string): Promise<boolean> {
if (typeof lockKey !== "string") {
return false
}
// The unlink removes the file and leaves the per-task directory in place, so both sides
// still carry an identity here. Case is folded because it is not significant on Windows,
// where the alias spelling appears.
const expectedDirectory = await fileIdentity(path.dirname(expectedPath))
const keyDirectory = await fileIdentity(path.dirname(lockKey))
return (
expectedDirectory !== null &&
keyDirectory === expectedDirectory &&
path.basename(lockKey).toLowerCase() === path.basename(expectedPath).toLowerCase()
)
}

function storeInternals(store: TaskHistoryStore): {
cache: Map<string, HistoryItem>
taskFileMtimes: Map<string, number>
Expand Down Expand Up @@ -152,14 +186,23 @@ describe("TaskHistoryStore best-effort deletion semantics", () => {
const store = createStore()
await store.initialize()
await store.upsert(makeHistoryItem({ id: "locked-delete" }))
// The lock spy is created once for the whole file, so clear it to make the
// assertion below about this delete and not about every case before it.
vi.mocked(withFileLock).mockClear()
onWrite.mockClear()

await expect(store.delete("locked-delete")).resolves.toBeUndefined()

expect(vi.mocked(withFileLock)).toHaveBeenCalledWith(
historyFilePath(storagePath, "locked-delete"),
expect.any(Function),
const lockCalls = vi.mocked(withFileLock).mock.calls
expect(lockCalls).toHaveLength(1)
// The lock is taken for the file the delete unlinked, under a function body: the key
// is pinned by identity rather than by text, and the arity and the body are pinned
// alongside it so an argument dropped or swapped cannot slip through.
expect(lockCalls[0]).toHaveLength(2)
expect(await lockKeyNamesTheSameFile(lockCalls[0][0], historyFilePath(storagePath, "locked-delete"))).toBe(
true,
)
expect(lockCalls[0][1]).toBeTypeOf("function")
await expect(fs.access(historyFilePath(storagePath, "locked-delete"))).rejects.toMatchObject({
code: "ENOENT",
})
Expand Down
27 changes: 27 additions & 0 deletions src/core/task/__tests__/Task.dispose.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,33 @@ describe("Task.run() idempotency", () => {
mockApiConfiguration = { apiProvider: providerIdentifiers.anthropic, apiKey: "test-key" } as ProviderSettings
})

test("each Task constructs its own observation registry", async () => {
// The guard authorizes a write from the observations of the task that made it. One
// shared registry would let a parent read authorize a subtask write, and one task
// clearing its registry would revoke the other task authorization. The field is an
// instance initializer, so this asserts the ownership rather than the type.
const first = new Task({
provider: mockProvider as unknown as ClineProvider,
apiConfiguration: mockApiConfiguration,
task: "first",
startTask: false,
})
const second = new Task({
provider: mockProvider as unknown as ClineProvider,
apiConfiguration: mockApiConfiguration,
task: "second",
startTask: false,
})

expect(first.observationRegistry).not.toBe(second.observationRegistry)
first.observationRegistry.observe("/same/path.ts", "1:2:22:100:100", true)
expect(second.observationRegistry.get("/same/path.ts")).toBeUndefined()
expect(second.observationRegistry.size).toBe(0)

await first.dispose()
await second.dispose()
})

test("run() does not invoke startTask when task was already started by constructor", async () => {
// Spy on the prototype before construction so we capture the constructor's call too.
const startTaskSpy = vi.spyOn(Task.prototype as any, "startTask").mockResolvedValue(undefined)
Expand Down
37 changes: 37 additions & 0 deletions src/core/task/__tests__/observationRegistry.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,43 @@ describe("ObservationRegistry", () => {
expect(regB.get("/shared.ts")!.version).toBe("v2")
})

describe("forget", () => {
it("removes the entry and reports that it removed one", () => {
const registry = new ObservationRegistry()
registry.observe("/a.ts", "1:1:1:1:1", true)

expect(registry.forget("/a.ts")).toBe(true)
expect(registry.has("/a.ts")).toBe(false)
expect(registry.get("/a.ts")).toBeUndefined()
expect(registry.size).toBe(0)
})

it("reports false for a path it never observed, and changes nothing", () => {
const registry = new ObservationRegistry()
registry.observe("/a.ts", "1:1:1:1:1", true)

expect(registry.forget("/missing.ts")).toBe(false)
expect(registry.size).toBe(1)
expect(registry.get("/a.ts")?.version).toBe("1:1:1:1:1")
})

it("leaves the other entries alone - that is why a caller uses forget and not clear", () => {
// A caller revoking an authorization it did not earn must not discard the
// observations other reads of the same task still rely on.
const registry = new ObservationRegistry()
registry.observe("/a.ts", "1:1:1:1:1", true)
registry.observe("/b.ts", "2:2:2:2:2", false)

expect(registry.forget("/a.ts")).toBe(true)
expect(registry.get("/b.ts")).toEqual({
version: "2:2:2:2:2",
observedAt: expect.any(Number),
complete: false,
})
expect(registry.size).toBe(1)
})
})

describe("completeness scope (S4b follow-up #46)", () => {
it("defaults to a complete observation when the read scope is not given", () => {
const reg = new ObservationRegistry()
Expand Down
10 changes: 10 additions & 0 deletions src/core/task/observationRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@ export class ObservationRegistry {
return this.entries.has(absolutePath)
}

/**
* Drop the observation for one path. A caller that must revoke an
* authorization it did not earn - a preview that observed a version the model
* never read - needs this instead of clear(), which would also discard the
* observations other reads of the same task still rely on.
*/
forget(absolutePath: string): boolean {
return this.entries.delete(absolutePath)
}

clear(): void {
this.entries.clear()
}
Expand Down
Loading
Loading