Skip to content

Commit 120cb05

Browse files
unit(u5b): guard machinery in the writer, with the identity and rights refusals
First unit of the #1914 split plan recorded on #1991: this branch's increment over PR #1913's head 416179d for the writer-side paths (safeWriteText.ts and its spec, fileLock.ts and its spec, Task.ts and Task.spec.ts). guardedWrite.ts and its spec stay in the next unit, because the tool consumes this unit's guard API rather than the reverse. Two refusals that the refresh merge surfaced as divergent between the two copies of safeWriteText.ts are re-added here rather than left as a silent loss, per the lead's ruling on #1991 question 1. Neither is a rival design: the staging-path (dev, ino) refusal applies the contract confirmed on #2356 (identity compared after canonicalisation, consumers compare identity) to the file this write stages through, and the DACL refusal is the same fail-closed principle ruled for _copyTargetMode in #1917 - publishing without knowing the target's access rights can widen who reads the file, and logging-and-continuing was rejected there. Both are recorded as requirements on #2350. 1. Staging identity: the supplied staging path and the target are compared by (dev, ino) read with bigint stats (file identities on NTFS/ReFS exceed Number.MAX_SAFE_INTEGER, and a rounded number either hides an alias or rejects a valid staging file). Only ENOENT may skip the comparison; EACCES/ELOOP/ENOTDIR means the comparison could not be made and is itself a refusal, because otherwise an alias reaches the commit and the failure handler unlinks the only remaining copy of the content - a failed write would delete the file it was meant to protect. Pinned by two tests: the alias itself, and the non-ENOENT reason. 2. Access rights on win32: a target that exists but whose DACL cannot be saved, or whose access rights cannot be read (getErrorCode != ENOENT), now yields DaclInspectionError before anything is committed, with the phase and target path on the error. The class is the one PR #1913's copy already carries; its text is taken unchanged. Contract change, stated because tests move with it: two tests in this branch's spec asserted the opposite behaviour - "win32 DACL failure falls back to plain rename (never fails the write)" and the partial-dump test's assertion that the write commits. Both are replaced with assertions of the refusal (rename never happens, the dump is still unlinked, one icacls attempt, phase and path pinned). A third test covers the inspection refusal; it injects platform win32 and stubs icacls, so it runs on either hosted leg rather than only on the windows one, and the hosted windows leg passes this file. One config line comes with this unit: knip.json declares services/file-safety/safeWriteText.ts as a src workspace entry. Without it, knip --production fails on this unit in isolation - knip does not credit imports from files it reports as unused, and the only production consumer of the exported safeWriteText function arrives with the next unit - and knip is a required status check on main (Protect Main ruleset: check-translations, both platform-unit-test legs, compile, knip, e2e-mock). With the entry declared, both knip modes and the knip-policy test pass on this unit alone.
1 parent 416179d commit 120cb05

7 files changed

Lines changed: 1196 additions & 441 deletions

File tree

‎knip.json‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,12 @@
1616
"playwright-ct": false,
1717
"workspaces": {
1818
"src": {
19-
"entry": ["extension.ts!", "extension/api.ts!", "workers/countTokens.ts!"],
19+
"entry": [
20+
"extension.ts!",
21+
"extension/api.ts!",
22+
"workers/countTokens.ts!",
23+
"services/file-safety/safeWriteText.ts!"
24+
],
2025
"project": [
2126
"**/*.ts!",
2227
"!**/__tests__/**!",

‎src/core/task/Task.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,11 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
398398
providerRef: WeakRef<ClineProvider>
399399
private readonly globalStoragePath: string
400400
abort: boolean = false
401+
// Monotonic cancellation counter. `requestAbort()` and `requestDispose()` advance
402+
// this fence, and the guarded-write path compares the value it captured when the
403+
// write was queued with the value at publish time, so a queued write cannot publish
404+
// after the task was cancelled or disposed.
405+
cancellationGeneration: number = 0
401406
currentRequestAbortController?: AbortController
402407
/**
403408
* Controller for the waiter on an in-flight `ensureModelFetched()` call (see
@@ -3596,6 +3601,11 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
35963601
this.abandoned = true
35973602
}
35983603
this.abort = true
3604+
// The S4a write guard compares this counter with the value a queued write
3605+
// captured when it started, so every cancellation must advance it; it must
3606+
// never go backwards because resumeAfterDelegation() clears `abort` (the
3607+
// flag alone cannot keep the cancelled run and the resumed run apart).
3608+
this.cancellationGeneration++
35993609
this.driveRunEvent({ tag: "abortRequested", abandoned: isAbandoned })
36003610
}
36013611

@@ -3606,6 +3616,10 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
36063616

36073617
requestDispose(): void {
36083618
this.abort = true
3619+
// A host teardown never calls abortTask(): disposal has to raise the same
3620+
// counter, or a write still parked on its path chain publishes after the
3621+
// task is gone.
3622+
this.cancellationGeneration++
36093623
this.driveRunEvent({ tag: "disposeRequested" })
36103624
}
36113625

@@ -3634,6 +3648,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
36343648

36353649
public abortTask(isAbandoned = false): Promise<void> {
36363650
this.requestAbort(isAbandoned)
3651+
36373652
this.cancelAssistantMessagePersistence()
36383653
this.abortPromise ??= this.abortTaskOnce()
36393654
return this.abortPromise

‎src/core/task/__tests__/Task.spec.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4768,6 +4768,56 @@ describe("Cline", () => {
47684768
).toHaveLength(1)
47694769
})
47704770

4771+
it("advances the cancellation generation on each cancellation and keeps it advanced across a resume", async () => {
4772+
// The S4a write guard compares the cancellation generation a queued write
4773+
// captured against the generation at publish time. The abort FLAG cannot do that
4774+
// on its own: resumeAfterDelegation() clears it, and a write that belongs to the
4775+
// cancelled run would then publish as if nothing had been cancelled. Only the
4776+
// generation keeps the two runs apart, so it must never go backwards.
4777+
const task = new Task({
4778+
provider: mockProvider,
4779+
apiConfiguration: mockApiConfig,
4780+
task: "test task",
4781+
startTask: false,
4782+
})
4783+
vi.spyOn(task, "dispose").mockResolvedValue(undefined)
4784+
4785+
expect(task.cancellationGeneration).toBe(0)
4786+
4787+
await task.abortTask()
4788+
expect(task.abort).toBe(true)
4789+
expect(task.cancellationGeneration).toBe(1)
4790+
4791+
await task.resumeAfterDelegation()
4792+
// The run-state model (RSK-06) no longer clears the legacy `abort` flag
4793+
// on resume: that is exactly why the generation exists. Only the
4794+
// generation keeps the cancelled run and the resumed run apart.
4795+
expect(task.cancellationGeneration).toBe(1)
4796+
4797+
await task.abortTask()
4798+
expect(task.abort).toBe(true)
4799+
expect(task.cancellationGeneration).toBe(2)
4800+
})
4801+
4802+
it("advances the cancellation generation on disposal, without any explicit cancel", async () => {
4803+
// A task torn down by the host never sees abortTask(). Disposal has to raise the
4804+
// same generation, or a write still parked on its path chain publishes after the
4805+
// task is gone.
4806+
const task = new Task({
4807+
provider: mockProvider,
4808+
apiConfiguration: mockApiConfig,
4809+
task: "test task",
4810+
startTask: false,
4811+
})
4812+
4813+
expect(task.cancellationGeneration).toBe(0)
4814+
4815+
await task.dispose()
4816+
4817+
expect(task.abort).toBe(true)
4818+
expect(task.cancellationGeneration).toBe(1)
4819+
})
4820+
47714821
it("flushes pending state before TaskAborted and disposal while queue state is intact", async () => {
47724822
const task = new Task({
47734823
provider: mockProvider,

0 commit comments

Comments
 (0)