Skip to content

Commit b8f22ba

Browse files
committed
Reject stale or denied interrupted task resumes
1 parent 7843ca2 commit b8f22ba

11 files changed

Lines changed: 225 additions & 43 deletions

‎docs/architecture/task-lifecycle-model.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ Each task slot can also hold one of two pending `create_subtask` actions. A `sta
5959

6060
Production completion also accepts a recovery-compatible `active` parent that still awaits the returning child, then clears the stale pointers. Normal model transitions never create that intermediate state, so it is covered by a focused reducer test rather than admitted as a generally valid reachable state.
6161

62+
Explicit resume compares the caller's expected parent with the authoritative child backlink under the child-file lock. Abandonment writes child detachment before parent release, so a stale approval is rejected even in that partial-write window. Representative reducer scenarios cover stale linked and standalone approvals; a two-store provider test covers abandonment after the parent precheck. Rehydrated interrupted tasks omit lineage from message metadata saves, preventing their stale construction snapshots from restoring severed links after rejection. This closes abandonment-before-resume, not every cross-host ordering: parent-only redelegation, reverse-order stale abandonment, and other live-task writers remain within the ownership/generation gaps below.
63+
6264
## Shared-store concurrency model
6365

6466
The same `pnpm lifecycle:model-check` command also runs a second bounded explorer over two `TaskHistoryStore` hosts. It imports the production `computeHistoryDelta` and `mergeHistoryDelta` functions, so its semantics match the store rather than assuming coherent caches or transactional pair writes:

‎scripts/check-task-lifecycle.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ function transitions(state: ModelState): Transition[] {
195195
if (resumeValid) {
196196
result.push({
197197
name: `resume(${parentId})`,
198-
next: replace(state, { ...resumeInterruptedTask(parent), modelWasResumed: true }),
198+
next: replace(state, { ...resumeInterruptedTask(parent, parent.parentTaskId), modelWasResumed: true }),
199199
})
200200
}
201201
}
@@ -438,7 +438,7 @@ function runRepresentativeScenarios(): void {
438438
assert.throws(() => delegateTaskToChild(delegated, "child-b", "active"), /not interrupted/)
439439

440440
const interruptedA = interruptDelegatedChild(delegated, childA)
441-
const resumedA = resumeInterruptedTask(interruptedA)
441+
const resumedA = resumeInterruptedTask(interruptedA, parent.id)
442442
const resumedNested = delegateTaskToChild(resumedA, "child-b")
443443
assert.equal(resumedNested.status, "delegated")
444444
assert.equal(resumedNested.awaitingChildId, "child-b")
@@ -447,6 +447,10 @@ function runRepresentativeScenarios(): void {
447447

448448
const abandoned = abandonDelegatedChild(delegated, interruptedA)
449449
assert.throws(() => completeDelegatedChild(abandoned.parent, abandoned.child, "late"), /not delegated to child/)
450+
// A resume approved against the old linkage cannot revive an abandoned child.
451+
assert.throws(() => resumeInterruptedTask(abandoned.child, parent.id), /parent linkage changed/)
452+
assert.throws(() => resumeInterruptedTask(interruptedA), /parent linkage changed/)
453+
assert.equal(resumeInterruptedTask(abandoned.child).status, "active")
450454

451455
const childB = task("child-b", "child-a")
452456
const nestedParent = delegateTaskToChild(childA, childB.id)

‎src/__tests__/ClineProvider.delegation.spec.ts‎

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ import type { HistoryItem } from "@roo-code/types"
99
import { providerIdentifiers, RooCodeEventName } from "@roo-code/types"
1010
import { ClineProvider } from "../core/webview/ClineProvider"
1111
import { TaskScheduler } from "../core/task/TaskScheduler"
12-
import { LifecycleTransitionError } from "../core/task-persistence"
12+
import { LifecycleTransitionError, TaskHistoryStore } from "../core/task-persistence"
13+
import { abandonDelegatedChild } from "../core/task-persistence/taskLifecycle"
1314
import { makeProviderStub } from "./helpers/provider-stub"
1415

1516
const parentHistoryItem: HistoryItem = {
@@ -65,7 +66,62 @@ describe("ClineProvider.resumeInterruptedTask()", () => {
6566
await ClineProvider.prototype.resumeInterruptedTask.call(provider, "child-1", "parent-1")
6667

6768
expect(taskHistoryStore.invalidate).toHaveBeenCalledWith("parent-1")
68-
expect(taskHistoryStore.resumeInterruptedTask).toHaveBeenCalledWith("child-1")
69+
expect(taskHistoryStore.resumeInterruptedTask).toHaveBeenCalledWith("child-1", "parent-1")
70+
})
71+
72+
it("rejects abandonment committed by another host after the parent precheck", async () => {
73+
const storagePath = await fs.mkdtemp(path.join(os.tmpdir(), "resume-abandon-"))
74+
const storeA = new TaskHistoryStore(storagePath)
75+
const storeB = new TaskHistoryStore(storagePath)
76+
const parent: HistoryItem = {
77+
id: "parent",
78+
number: 1,
79+
ts: 1,
80+
task: "Parent",
81+
tokensIn: 0,
82+
tokensOut: 0,
83+
totalCost: 0,
84+
status: "delegated",
85+
awaitingChildId: "child",
86+
delegatedToId: "child",
87+
childIds: ["child"],
88+
}
89+
const child: HistoryItem = {
90+
...parent,
91+
id: "child",
92+
status: "interrupted",
93+
parentTaskId: "parent",
94+
rootTaskId: "parent",
95+
awaitingChildId: undefined,
96+
delegatedToId: undefined,
97+
childIds: [],
98+
}
99+
try {
100+
await storeA.initialize()
101+
await storeA.upsert(parent)
102+
await storeA.upsert(child)
103+
await storeB.initialize()
104+
const resume = storeA.resumeInterruptedTask.bind(storeA)
105+
vi.spyOn(storeA, "resumeInterruptedTask").mockImplementationOnce(async (id, expectedParent) => {
106+
// This hook runs after the provider's parent check. Commit only the
107+
// first half of abandonment: the parent still appears to await this child.
108+
await storeB.atomicReadAndUpdate("child", (current) => abandonDelegatedChild(parent, current).child)
109+
return resume(id, expectedParent)
110+
})
111+
const provider = makeProviderStub({ taskHistoryStore: storeA, isViewLaunched: false })
112+
await expect(
113+
ClineProvider.prototype.resumeInterruptedTask.call(provider, "child", "parent"),
114+
).rejects.toThrow("parent linkage changed")
115+
await storeB.invalidate("child")
116+
expect(storeA.get("child")).toEqual(storeB.get("child"))
117+
expect(storeB.get("child")).toMatchObject({ status: "interrupted" })
118+
expect(storeB.get("child")?.parentTaskId).toBeUndefined()
119+
expect(storeB.get("child")?.rootTaskId).toBeUndefined()
120+
} finally {
121+
storeA.dispose()
122+
storeB.dispose()
123+
await fs.rm(storagePath, { recursive: true, force: true })
124+
}
69125
})
70126

71127
it("rejects a stale interrupted child after its parent delegates elsewhere", async () => {

‎src/__tests__/removeClineFromStack-delegation.spec.ts‎

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { describe, it, expect, vi, type MockedFunction } from "vitest"
44
import { ClineProvider } from "../core/webview/ClineProvider"
55
import { TaskRegistry } from "../core/task/TaskRegistry"
66
import { PendingActionSettlementError, type Task } from "../core/task/Task"
7+
import { LifecycleTransitionError } from "../core/task-persistence/taskLifecycle"
78
import { makeProviderStub } from "./helpers/provider-stub"
89

910
type MockTask = Pick<Task, "taskId" | "instanceId"> &
@@ -178,35 +179,34 @@ describe("ClineProvider.removeClineFromStack() — pure lifecycle, no delegation
178179
})
179180

180181
describe("ClineProvider failed history restoration cleanup", () => {
181-
it("removes the failed task, its listeners, and its resources without saving stale history", async () => {
182-
const cleanupListener = vi.fn()
183-
const task = {
184-
taskId: "failed-history-task",
185-
instanceId: "inst-1",
186-
emit: vi.fn(),
187-
dispose: vi.fn().mockResolvedValue(undefined),
188-
} as unknown as Task
189-
const taskRegistry = new TaskRegistry()
190-
taskRegistry.push(task)
191-
const taskEventListeners = new Map([[task, [cleanupListener]]])
192-
const provider = {
193-
taskRegistry,
194-
taskEventListeners,
195-
log: vi.fn(),
196-
} as unknown as ClineProvider
197-
198-
await privateClineProvider.cleanupFailedHistoryTask.call(
199-
provider,
200-
task,
201-
new PendingActionSettlementError("settlement failed"),
202-
)
203-
204-
expect(taskRegistry.getById(task.taskId)).toBeUndefined()
205-
expect(taskRegistry.current).toBeUndefined()
206-
expect(cleanupListener).toHaveBeenCalledOnce()
207-
expect(taskEventListeners.has(task)).toBe(false)
208-
expect(task.dispose).toHaveBeenCalledOnce()
209-
})
182+
it.each([new PendingActionSettlementError("settlement failed"), new LifecycleTransitionError("resume rejected")])(
183+
"removes the failed task without saving stale history after %s",
184+
async (error) => {
185+
const cleanupListener = vi.fn()
186+
const task = {
187+
taskId: "failed-history-task",
188+
instanceId: "inst-1",
189+
emit: vi.fn(),
190+
dispose: vi.fn().mockResolvedValue(undefined),
191+
} as unknown as Task
192+
const taskRegistry = new TaskRegistry()
193+
taskRegistry.push(task)
194+
const taskEventListeners = new Map([[task, [cleanupListener]]])
195+
const provider = {
196+
taskRegistry,
197+
taskEventListeners,
198+
log: vi.fn(),
199+
} as unknown as ClineProvider
200+
201+
await privateClineProvider.cleanupFailedHistoryTask.call(provider, task, error)
202+
203+
expect(taskRegistry.getById(task.taskId)).toBeUndefined()
204+
expect(taskRegistry.current).toBeUndefined()
205+
expect(cleanupListener).toHaveBeenCalledOnce()
206+
expect(taskEventListeners.has(task)).toBe(false)
207+
expect(task.dispose).toHaveBeenCalledOnce()
208+
},
209+
)
210210

211211
it("keeps the task active after an unrelated history resume failure", async () => {
212212
const cleanupListener = vi.fn()

‎src/core/task-persistence/TaskHistoryStore.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1083,7 +1083,7 @@ export class TaskHistoryStore {
10831083
* prompt. Generic writes intentionally reject interrupted → active so stale
10841084
* task snapshots cannot revive cancelled work.
10851085
*/
1086-
public async resumeInterruptedTask(taskId: string): Promise<HistoryItem> {
1086+
public async resumeInterruptedTask(taskId: string, expectedParentTaskId?: string): Promise<HistoryItem> {
10871087
return this.withLock(async () => {
10881088
const cached = this.cache.get(taskId)
10891089
if (!cached) {
@@ -1103,7 +1103,10 @@ export class TaskHistoryStore {
11031103
)
11041104
}
11051105

1106-
authoritative = resumeInterruptedTaskRecord(existing as HistoryItem)
1106+
// Abandonment commits child detachment before releasing the parent.
1107+
// Compare the caller's linkage under this same child-file lock.
1108+
this.cache.set(taskId, existing as HistoryItem)
1109+
authoritative = resumeInterruptedTaskRecord(existing as HistoryItem, expectedParentTaskId)
11071110
return authoritative
11081111
},
11091112
})

‎src/core/task-persistence/__tests__/TaskHistoryStore.realConcurrency.spec.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,51 @@ function createAction(actionId: string, message: string) {
9191
}
9292

9393
describe("TaskHistoryStore real cross-host locking", () => {
94+
it("rejects resume for a task absent from cache without creating a record", async () => {
95+
const storagePath = await fs.mkdtemp(path.join(os.tmpdir(), "resume-cache-miss-"))
96+
const store = new TaskHistoryStore(storagePath)
97+
try {
98+
await store.initialize()
99+
await expect(store.resumeInterruptedTask("missing")).rejects.toThrow("task missing not found in cache")
100+
expect(store.get("missing")).toBeUndefined()
101+
await expect(
102+
fs.access(path.join(storagePath, "tasks", "missing", "history_item.json")),
103+
).rejects.toMatchObject({ code: "ENOENT" })
104+
} finally {
105+
store.dispose()
106+
await fs.rm(storagePath, { recursive: true, force: true })
107+
}
108+
})
109+
110+
it.each(["missing", "malformed", "schema", "identity"])(
111+
"rejects %s disk records during resume without overwriting them",
112+
async (scenario) => {
113+
const storagePath = await fs.mkdtemp(path.join(os.tmpdir(), "resume-invalid-"))
114+
const store = new TaskHistoryStore(storagePath)
115+
const filePath = path.join(storagePath, "tasks", "child", "history_item.json")
116+
try {
117+
await store.initialize()
118+
await store.upsert({ ...item("child"), status: "interrupted" })
119+
const contents =
120+
scenario === "malformed"
121+
? "{broken"
122+
: JSON.stringify(scenario === "schema" ? { id: "child" } : item("other"))
123+
if (scenario === "missing") await fs.unlink(filePath)
124+
else await fs.writeFile(filePath, contents)
125+
await expect(store.resumeInterruptedTask("child")).rejects.toThrow(
126+
"task child has no valid disk record",
127+
)
128+
expect(store.get("child")).toBeUndefined()
129+
expect(store["taskFileMtimes"].has("child")).toBe(false)
130+
if (scenario === "missing") await expect(fs.access(filePath)).rejects.toMatchObject({ code: "ENOENT" })
131+
else expect(await fs.readFile(filePath, "utf8")).toBe(contents)
132+
} finally {
133+
store.dispose()
134+
await fs.rm(storagePath, { recursive: true, force: true })
135+
}
136+
},
137+
)
138+
94139
it("resumes from the authoritative interrupted record even when the caller cache is stale", async () => {
95140
const storagePath = await fs.mkdtemp(path.join(os.tmpdir(), "task-history-resume-lock-"))
96141
const storeA = new TaskHistoryStore(storagePath)

‎src/core/task-persistence/__tests__/taskLifecycle.spec.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ describe("task lifecycle transitions", () => {
6666
expect(() => delegateTaskToChild(interruptedChild, "grandchild")).toThrow(
6767
"Invalid task status transition: interrupted → delegated",
6868
)
69-
expect(delegateTaskToChild(resumeInterruptedTask(interruptedChild), "grandchild")).toMatchObject({
69+
expect(delegateTaskToChild(resumeInterruptedTask(interruptedChild, "parent"), "grandchild")).toMatchObject({
7070
status: "delegated",
7171
parentTaskId: "parent",
7272
awaitingChildId: "grandchild",

‎src/core/task-persistence/taskLifecycle.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,13 @@ export function assertValidTransition(from: HistoryItemStatus | undefined, to: H
2929
* outside VALID_TASK_STATUS_TRANSITIONS so generic stale writes cannot revive
3030
* an interrupted task.
3131
*/
32-
export function resumeInterruptedTask(task: HistoryItem): HistoryItem {
32+
export function resumeInterruptedTask(task: HistoryItem, expectedParentTaskId?: string): HistoryItem {
3333
if (task.status !== "interrupted") {
3434
throw new LifecycleTransitionError(`Cannot resume task ${task.id} with status ${task.status ?? "active"}`)
3535
}
36+
if (task.parentTaskId !== expectedParentTaskId) {
37+
throw new LifecycleTransitionError(`Cannot resume task ${task.id}: parent linkage changed`)
38+
}
3639
return { ...task, status: "active" }
3740
}
3841

‎src/core/task/Task.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1706,6 +1706,12 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
17061706

17071707
const provider = this.providerRef.deref()
17081708
const existingStatus = provider?.taskHistoryStore.get(this.taskId)?.status
1709+
if (this.initialStatus === "interrupted") {
1710+
// A rehydrated task's links may have been severed by another host.
1711+
// Only lifecycle operations own lineage after interruption, not message saves.
1712+
delete historyItem.parentTaskId
1713+
delete historyItem.rootTaskId
1714+
}
17091715
await provider?.updateTaskHistory(existingStatus ? { ...historyItem, status: existingStatus } : historyItem)
17101716
return true
17111717
} catch (error) {
@@ -2973,7 +2979,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
29732979
this.isInitialized = true
29742980

29752981
const { response, text, images } = await this.ask(askType) // Calls `postStateToWebview`.
2976-
if (this.abort || this.abandoned) {
2982+
if (this.abort || this.abandoned || (response !== "yesButtonClicked" && response !== "messageResponse")) {
29772983
return
29782984
}
29792985
if (this.initialStatus === "interrupted") {

0 commit comments

Comments
 (0)