Skip to content

Commit 6819507

Browse files
committed
1 parent 3859e5d commit 6819507

10 files changed

Lines changed: 260 additions & 7 deletions

File tree

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,14 @@ TLA+/PlusCal or Quint with TLC becomes a better fit when the lifecycle needs tem
4646
| Task record and status | `HistoryItem` persisted by `TaskHistoryStore` |
4747
| `delegate(parent, child)` | `ClineProvider.delegateParentAndOpenChild` |
4848
| `interrupt(child)` | cancellation or eviction through `markDelegatedChildInterrupted` |
49+
| `resume(child)` | accepted `resume_task` prompt through `TaskHistoryStore.resumeInterruptedTask` |
4950
| `complete(child)` | `ClineProvider.reopenParentFromDelegation` |
5051
| `abandon(child)` | `ClineProvider.abandonSubtask` |
5152
| Pending-action settlement | `TaskHistoryStore.clearPendingActionIfMatching` compare-and-clear in the rejected-delegation settlement path (#1714) |
5253
| Atomic event step | `atomicReadAndUpdate`, `atomicUpdatePair`, and per-parent delegation transition lock |
5354
| Event interleaving | Competing completion, cancellation, abandonment, and new delegation calls |
5455

55-
The model has three fixed task slots, enough to cover competing siblings and a nested parent-child-grandchild chain. It explores every reachable interleaving through depth 12, deduplicating canonical states. Representative checks also exercise rejected operations that do not create a new state: a second concurrent delegation while the first child is active, stale completion after re-delegation, late completion after abandonment, completion after interruption, and nested completion. Named semantic landmarks require the graph to retain interrupted-child re-delegation and nested delegation even when the raw state total changes.
56+
The model has three fixed task slots, enough to cover competing siblings and a nested parent-child-grandchild chain. It explores every reachable interleaving through depth 13, deduplicating canonical states. Representative checks also exercise rejected operations that do not create a new state: a second concurrent delegation while the first child is active, stale completion after re-delegation, late completion after abandonment, completion after interruption, and nested completion. Named semantic landmarks require the graph to retain interrupted-child re-delegation, nested delegation, and an explicitly resumed interrupted child delegating to a grandchild even when the raw state total changes. The resume action calls the production reducer and carries a model-only provenance bit so the explorer can distinguish that path from a child that was never interrupted; generic persisted transitions still reject `interrupted → active`.
5657

5758
Each task slot can also hold one of two pending `create_subtask` actions. A `stage` action mirrors `setPendingTaskAction` overwrite semantics, delegation clears the action its request carried, completion clears the child's action only when its event carries the matching action ID, and a `settle-rejected` action models the settlement that follows an authoritative delegation rejection (#1714). Production settles through the typed `LifecycleTransitionError` from the shared guards: the provider calls the disk-authoritative `TaskHistoryStore.clearPendingActionIfMatching` compare-and-clear under the per-file lock, then propagates the original rejection. Six named witnesses must remain reachable: settlement from an interrupted record after rejection, settlement through a successful active delegation, unrelated-action preservation during completion, stale-action protection where a settlement targeting one action ID leaves a replacement action intact, matching-ID completion clearing, and replacement-ID completion preservation. A mismatched pending-action request keeps its production behavior: the atomic update throws before any transition, and no settlement runs.
5859

‎scripts/check-task-lifecycle.ts‎

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,16 @@ import {
77
completeDelegatedChild,
88
delegateTaskToChild,
99
interruptDelegatedChild,
10+
resumeInterruptedTask,
1011
settleRejectedCreateSubtaskAction,
1112
} from "../src/core/task-persistence/taskLifecycle"
1213

1314
const taskIds = ["parent", "child-a", "child-b"] as const
1415
type TaskId = (typeof taskIds)[number]
15-
type ModelState = Record<TaskId, HistoryItem | undefined>
16+
interface ModelTask extends HistoryItem {
17+
modelWasResumed?: boolean
18+
}
19+
type ModelState = Record<TaskId, ModelTask | undefined>
1620

1721
interface Transition {
1822
name: string
@@ -33,10 +37,10 @@ interface WitnessContext {
3337
transition: Transition
3438
}
3539

36-
const MAX_DEPTH = 12
40+
const MAX_DEPTH = 13
3741
const MAX_STATES = 10_000
3842
const actionIds = ["action-1", "action-2"] as const
39-
const expectedActions = ["delegate", "interrupt", "complete", "abandon", "stage", "settle-rejected"] as const
43+
const expectedActions = ["delegate", "interrupt", "resume", "complete", "abandon", "stage", "settle-rejected"] as const
4044
const semanticLandmarks = {
4145
"interrupted-child-redelegation": (state: ModelState) =>
4246
state.parent?.status === "delegated" &&
@@ -47,6 +51,12 @@ const semanticLandmarks = {
4751
state.parent.awaitingChildId === "child-a" &&
4852
state["child-a"]?.status === "delegated" &&
4953
state["child-a"].awaitingChildId === "child-b",
54+
"resumed-interrupted-child-nested-delegation": (state: ModelState) =>
55+
state.parent?.status === "delegated" &&
56+
state.parent.awaitingChildId === "child-a" &&
57+
state["child-a"]?.status === "delegated" &&
58+
state["child-a"].awaitingChildId === "child-b" &&
59+
state["child-a"].modelWasResumed === true,
5060
} satisfies Record<string, (state: ModelState) => boolean>
5161
const semanticWitnesses = {
5262
"interrupted-pending-delegation-settled": ({ prev, next, transition }: WitnessContext) =>
@@ -101,7 +111,7 @@ const semanticWitnesses = {
101111
},
102112
} satisfies Record<string, (context: WitnessContext) => boolean>
103113

104-
function task(id: TaskId, parentTaskId?: TaskId): HistoryItem {
114+
function task(id: TaskId, parentTaskId?: TaskId): ModelTask {
105115
return {
106116
id,
107117
number: taskIds.indexOf(id),
@@ -132,7 +142,7 @@ function initialState(): ModelState {
132142
return { parent: task("parent"), "child-a": undefined, "child-b": undefined }
133143
}
134144

135-
function replace(state: ModelState, ...updates: HistoryItem[]): ModelState {
145+
function replace(state: ModelState, ...updates: ModelTask[]): ModelState {
136146
const next = { ...state }
137147
for (const update of updates) next[update.id as TaskId] = update
138148
return next
@@ -176,6 +186,18 @@ function transitions(state: ModelState): Transition[] {
176186
})
177187
}
178188
}
189+
190+
const lineageParent = parent.parentTaskId ? state[parent.parentTaskId as TaskId] : undefined
191+
const resumeValid =
192+
parent.status === "interrupted" &&
193+
(!parent.parentTaskId ||
194+
(lineageParent?.status === "delegated" && lineageParent.awaitingChildId === parent.id))
195+
if (resumeValid) {
196+
result.push({
197+
name: `resume(${parentId})`,
198+
next: replace(state, { ...resumeInterruptedTask(parent), modelWasResumed: true }),
199+
})
200+
}
179201
}
180202

181203
for (const childId of taskIds) {
@@ -416,6 +438,10 @@ function runRepresentativeScenarios(): void {
416438
assert.throws(() => delegateTaskToChild(delegated, "child-b", "active"), /not interrupted/)
417439

418440
const interruptedA = interruptDelegatedChild(delegated, childA)
441+
const resumedA = resumeInterruptedTask(interruptedA)
442+
const resumedNested = delegateTaskToChild(resumedA, "child-b")
443+
assert.equal(resumedNested.status, "delegated")
444+
assert.equal(resumedNested.awaitingChildId, "child-b")
419445
const redelegated = delegateTaskToChild(delegated, "child-b", interruptedA.status)
420446
assert.throws(() => completeDelegatedChild(redelegated, interruptedA, "stale"), /not delegated to child/)
421447

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { providerIdentifiers, RooCodeEventName } from "@roo-code/types"
1010
import { ClineProvider } from "../core/webview/ClineProvider"
1111
import { TaskScheduler } from "../core/task/TaskScheduler"
1212
import { LifecycleTransitionError } from "../core/task-persistence"
13+
import { makeProviderStub } from "./helpers/provider-stub"
1314

1415
const parentHistoryItem: HistoryItem = {
1516
id: "parent-1",
@@ -51,6 +52,37 @@ const makeParentTask = () =>
5152
retrySaveApiConversationHistory: vi.fn(),
5253
}) as any
5354

55+
describe("ClineProvider.resumeInterruptedTask()", () => {
56+
it("resumes a delegated child only while its parent still awaits it", async () => {
57+
const resumed = { id: "child-1", status: "active" } as HistoryItem
58+
const taskHistoryStore = {
59+
invalidate: vi.fn().mockResolvedValue(undefined),
60+
get: vi.fn().mockReturnValue({ id: "parent-1", status: "delegated", awaitingChildId: "child-1" }),
61+
resumeInterruptedTask: vi.fn().mockResolvedValue(resumed),
62+
}
63+
const provider = makeProviderStub({ taskHistoryStore, isViewLaunched: false })
64+
65+
await ClineProvider.prototype.resumeInterruptedTask.call(provider, "child-1", "parent-1")
66+
67+
expect(taskHistoryStore.invalidate).toHaveBeenCalledWith("parent-1")
68+
expect(taskHistoryStore.resumeInterruptedTask).toHaveBeenCalledWith("child-1")
69+
})
70+
71+
it("rejects a stale interrupted child after its parent delegates elsewhere", async () => {
72+
const taskHistoryStore = {
73+
invalidate: vi.fn().mockResolvedValue(undefined),
74+
get: vi.fn().mockReturnValue({ id: "parent-1", status: "delegated", awaitingChildId: "child-2" }),
75+
resumeInterruptedTask: vi.fn(),
76+
}
77+
const provider = makeProviderStub({ taskHistoryStore, isViewLaunched: false })
78+
79+
await expect(
80+
ClineProvider.prototype.resumeInterruptedTask.call(provider, "child-1", "parent-1"),
81+
).rejects.toThrow("parent parent-1 no longer awaits it")
82+
expect(taskHistoryStore.resumeInterruptedTask).not.toHaveBeenCalled()
83+
})
84+
})
85+
5486
describe("ClineProvider.delegateParentAndOpenChild()", () => {
5587
it("rejects a stale restored action before delegation side effects", async () => {
5688
const parentTask = makeParentTask()

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

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,12 @@ import { GlobalFileNames } from "../../shared/globalFileNames"
1010
import { LOCK_STALE_MS, withFileLock } from "../../utils/fileLock"
1111
import { safeWriteJson } from "../../utils/safeWriteJson"
1212
import { getStorageBasePath } from "../../utils/storage"
13-
import { assertValidTransition, settleRejectedCreateSubtaskAction, type HistoryItemStatus } from "./taskLifecycle"
13+
import {
14+
assertValidTransition,
15+
resumeInterruptedTask as resumeInterruptedTaskRecord,
16+
settleRejectedCreateSubtaskAction,
17+
type HistoryItemStatus,
18+
} from "./taskLifecycle"
1419
import { computeHistoryDelta, DeltaRejectedError, mergeHistoryDelta } from "./taskStoreConcurrency"
1520

1621
export { assertValidTransition, type HistoryItemStatus } from "./taskLifecycle"
@@ -1073,6 +1078,44 @@ export class TaskHistoryStore {
10731078
})
10741079
}
10751080

1081+
/**
1082+
* Disk-authoritative transition used only after the user accepts a resume
1083+
* prompt. Generic writes intentionally reject interrupted → active so stale
1084+
* task snapshots cannot revive cancelled work.
1085+
*/
1086+
public async resumeInterruptedTask(taskId: string): Promise<HistoryItem> {
1087+
return this.withLock(async () => {
1088+
const cached = this.cache.get(taskId)
1089+
if (!cached) {
1090+
throw new Error(`[TaskHistoryStore] resumeInterruptedTask: task ${taskId} not found in cache`)
1091+
}
1092+
1093+
const filePath = await this.getTaskFilePath(taskId)
1094+
let authoritative: HistoryItem = cached
1095+
await safeWriteJson(filePath, cached, {
1096+
merge: (existing) => {
1097+
const parsed = historyItemSchema.safeParse(existing)
1098+
if (!parsed.success || parsed.data.id !== taskId) {
1099+
this.cache.delete(taskId)
1100+
this.taskFileMtimes.delete(taskId)
1101+
throw new Error(
1102+
`[TaskHistoryStore] resumeInterruptedTask: task ${taskId} has no valid disk record`,
1103+
)
1104+
}
1105+
1106+
authoritative = resumeInterruptedTaskRecord(existing as HistoryItem)
1107+
return authoritative
1108+
},
1109+
})
1110+
1111+
this.cache.set(taskId, authoritative)
1112+
if (this.onWrite) {
1113+
await this.onWrite(this.getAll())
1114+
}
1115+
return authoritative
1116+
})
1117+
}
1118+
10761119
/**
10771120
* Disk-authoritative compare-and-clear for a rejected `create_subtask`
10781121
* pending action (#1714). The comparison runs inside the per-file

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

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

9393
describe("TaskHistoryStore real cross-host locking", () => {
94+
it("resumes from the authoritative interrupted record even when the caller cache is stale", async () => {
95+
const storagePath = await fs.mkdtemp(path.join(os.tmpdir(), "task-history-resume-lock-"))
96+
const storeA = new TaskHistoryStore(storagePath)
97+
const storeB = new TaskHistoryStore(storagePath)
98+
99+
try {
100+
await storeA.initialize()
101+
await storeA.upsert(item("shared-task"))
102+
await storeB.initialize()
103+
await storeA.upsert({ ...item("shared-task"), status: "interrupted" })
104+
105+
expect(storeB.get("shared-task")?.status).toBe("active")
106+
await expect(storeB.resumeInterruptedTask("shared-task")).resolves.toMatchObject({
107+
id: "shared-task",
108+
status: "active",
109+
})
110+
await storeA.invalidate("shared-task")
111+
expect(storeA.get("shared-task")?.status).toBe("active")
112+
} finally {
113+
storeA.dispose()
114+
storeB.dispose()
115+
await fs.rm(storagePath, { recursive: true, force: true })
116+
}
117+
})
118+
119+
it("rejects resume when the authoritative record is no longer interrupted", async () => {
120+
const storagePath = await fs.mkdtemp(path.join(os.tmpdir(), "task-history-resume-rejected-"))
121+
const storeA = new TaskHistoryStore(storagePath)
122+
const storeB = new TaskHistoryStore(storagePath)
123+
124+
try {
125+
await storeA.initialize()
126+
await storeA.upsert(item("shared-task"))
127+
await storeB.initialize()
128+
await storeA.upsert({ ...item("shared-task"), status: "completed" })
129+
130+
await expect(storeB.resumeInterruptedTask("shared-task")).rejects.toThrow(
131+
"Cannot resume task shared-task with status completed",
132+
)
133+
await storeB.invalidate("shared-task")
134+
expect(storeB.get("shared-task")?.status).toBe("completed")
135+
} finally {
136+
storeA.dispose()
137+
storeB.dispose()
138+
await fs.rm(storagePath, { recursive: true, force: true })
139+
}
140+
})
141+
94142
it("preserves independent stale-cache deltas through the real per-file lock", async () => {
95143
const storagePath = await fs.mkdtemp(path.join(os.tmpdir(), "task-history-real-lock-"))
96144
const storeA = new TaskHistoryStore(storagePath)

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
delegateTaskToChild,
77
interruptDelegatedChild,
88
LifecycleTransitionError,
9+
resumeInterruptedTask,
910
settleRejectedCreateSubtaskAction,
1011
} from "../taskLifecycle"
1112

@@ -59,6 +60,24 @@ describe("task lifecycle transitions", () => {
5960
})
6061
})
6162

63+
it("allows an explicitly resumed interrupted child to delegate without weakening generic transitions", () => {
64+
const interruptedChild = item("child", { status: "interrupted", parentTaskId: "parent" })
65+
66+
expect(() => delegateTaskToChild(interruptedChild, "grandchild")).toThrow(
67+
"Invalid task status transition: interrupted → delegated",
68+
)
69+
expect(delegateTaskToChild(resumeInterruptedTask(interruptedChild), "grandchild")).toMatchObject({
70+
status: "delegated",
71+
parentTaskId: "parent",
72+
awaitingChildId: "grandchild",
73+
delegatedToId: "grandchild",
74+
})
75+
})
76+
77+
it("rejects explicit resume for a task that is no longer interrupted", () => {
78+
expect(() => resumeInterruptedTask(item("child"))).toThrow(LifecycleTransitionError)
79+
})
80+
6281
it("interrupts a child without clearing the parent's ownership", () => {
6382
const parent = item("parent", { status: "delegated", awaitingChildId: "child", delegatedToId: "child" })
6483
const child = item("child", { parentTaskId: "parent" })

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,18 @@ export function assertValidTransition(from: HistoryItemStatus | undefined, to: H
2424
}
2525
}
2626

27+
/**
28+
* Reactivates a task only through the explicit user-resume path. This is kept
29+
* outside VALID_TASK_STATUS_TRANSITIONS so generic stale writes cannot revive
30+
* an interrupted task.
31+
*/
32+
export function resumeInterruptedTask(task: HistoryItem): HistoryItem {
33+
if (task.status !== "interrupted") {
34+
throw new LifecycleTransitionError(`Cannot resume task ${task.id} with status ${task.status ?? "active"}`)
35+
}
36+
return { ...task, status: "active" }
37+
}
38+
2739
/**
2840
* Settles the pending create_subtask action whose delegation the authoritative
2941
* parent record rejected (#1714). Only the exact matching action ID is cleared;

‎src/core/task/Task.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2981,6 +2981,16 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
29812981
this.isInitialized = true
29822982

29832983
const { response, text, images } = await this.ask(askType) // Calls `postStateToWebview`.
2984+
if (this.abort || this.abandoned) {
2985+
return
2986+
}
2987+
if (this.initialStatus === "interrupted") {
2988+
const provider = this.providerRef.deref()
2989+
if (!provider) {
2990+
throw new Error(`[Task#resumeTaskFromHistory] Provider unavailable for task ${this.taskId}`)
2991+
}
2992+
await provider.resumeInterruptedTask(this.taskId, this.parentTaskId)
2993+
}
29842994

29852995
let responseText: string | undefined
29862996
let responseImages: string[] | undefined

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

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ vi.mock("../../task-persistence", async (importOriginal) => {
125125
delete: vi.fn().mockResolvedValue(undefined),
126126
deleteMany: vi.fn().mockResolvedValue(undefined),
127127
reconcile: vi.fn().mockResolvedValue(undefined),
128+
resumeInterruptedTask: vi.fn().mockResolvedValue({ id: "test-id", status: "active" }),
128129
initialized: Promise.resolve(),
129130
}
130131
}),
@@ -297,6 +298,7 @@ describe("Task persistence", () => {
297298
mockProvider.postStateToWebview = vi.fn().mockResolvedValue(undefined)
298299
mockProvider.postStateToWebviewWithoutTaskHistory = vi.fn().mockResolvedValue(undefined)
299300
mockProvider.updateTaskHistory = vi.fn().mockResolvedValue(undefined)
301+
mockProvider.resumeInterruptedTask = vi.fn().mockResolvedValue(undefined)
300302
mockProvider.log = vi.fn()
301303
})
302304

@@ -1201,6 +1203,40 @@ describe("Task persistence", () => {
12011203
// ── resumeTaskFromHistory — interrupted tool calls must be recorded as errors ──
12021204

12031205
describe("resumeTaskFromHistory interrupted tool calls", () => {
1206+
it("durably activates an interrupted task after the user accepts resume", async () => {
1207+
mockReadTaskMessages.mockResolvedValue([])
1208+
mockReadApiMessages.mockResolvedValue([{ role: "user", content: "Continue" }])
1209+
mockProvider.taskHistoryStore.get = vi.fn().mockReturnValue({
1210+
id: "interrupted-child-resume",
1211+
status: "interrupted",
1212+
})
1213+
const task = new Task({
1214+
provider: mockProvider,
1215+
apiConfiguration: mockApiConfig,
1216+
historyItem: {
1217+
id: "interrupted-child-resume",
1218+
number: 1,
1219+
ts: 1,
1220+
task: "Interrupted child",
1221+
tokensIn: 0,
1222+
tokensOut: 0,
1223+
totalCost: 0,
1224+
status: "interrupted",
1225+
parentTaskId: "parent",
1226+
},
1227+
startTask: false,
1228+
})
1229+
vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked" })
1230+
const initiateTaskLoop = vi
1231+
.spyOn(getTaskPersistenceAccess(task), "initiateTaskLoop")
1232+
.mockResolvedValue(undefined)
1233+
1234+
await getTaskPersistenceAccess(task).resumeTaskFromHistory()
1235+
1236+
expect(mockProvider.resumeInterruptedTask).toHaveBeenCalledWith("interrupted-child-resume", "parent")
1237+
expect(initiateTaskLoop).toHaveBeenCalledOnce()
1238+
})
1239+
12041240
const interruptedToolResultContent = "Task was interrupted before this tool call could be completed."
12051241

12061242
it("marks synthetic tool_results from an interrupted assistant turn as errors", async () => {

0 commit comments

Comments
 (0)