Skip to content

Commit 72141a7

Browse files
committed
fix(lifecycle): preserve replacement pending actions
1 parent a7f94b4 commit 72141a7

7 files changed

Lines changed: 336 additions & 32 deletions

File tree

‎docs/architecture/task-lifecycle-gap-report.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ The 40 IDs are not 40 independent projects. They group into eight programs with
227227
| ------------------------------------------ | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
228228
| P1. Persisted ownership and generation | 001, 002, 012, 017, 020 | Disk-authoritative lifecycle ownership/generation and immutable store reads across history types, lifecycle reducers, `TaskHistoryStore`, provider delegation, and reconciliation. | XL | High: persisted compatibility and cross-host races | Two-host stale-write tests, promoted invariants, restart/reconciliation evidence, backward-compatible optional data. |
229229
| P2. Durable operation and crash recovery | 004, 005, 006, 021, 023, 039, 040 | Operation intent/replay or explicit idempotent recovery for pair writes, delegation, completion messages, shutdown, and deletion. | XL | Very high: failure ordering can create new corruption | Fault injection at every durable boundary, crash/restart convergence, no false success, recovery reachability. |
230-
| P3. Schema, path, and lifecycle vocabulary | 013, 018, 019, 041 | Schema-derived status ownership, validated ordinary history reads, and one safe task-ID boundary across types, persistence, metadata, CLI, and import paths. | M | Medium: malformed legacy data and downgrade behavior | Migration/quarantine fixtures, traversal tests, type/static ratchets. |
230+
| P3. Schema, path, and lifecycle vocabulary | 013, 018, 019 | Schema-derived status ownership, validated ordinary history reads, and one safe task-ID boundary across types, persistence, metadata, CLI, and import paths. | M | Medium: malformed legacy data and downgrade behavior | Migration/quarantine fixtures, traversal tests, type/static ratchets. |
231231
| P4. Request, stream, and tool identity | 008, 010, 024, 025, 026, 030, 037, 038 | Request generation plus canonical call identity, then task/generation/call-scoped parser and partial-handler state. Owners include provider transforms, parser, `Task`, `BaseTool`, editing handlers, and tool-ID utilities. | XL | High: provider compatibility and duplicate execution | Adversarial IDs/index-less streams, delayed/cancelled generation tests, cleanup/deadline checks, production-backed call-state model. |
232232
| P5. Tool-owned task state and queueing | 003, 007, 031, 035, 036 | Task-local context, durable child initialization, correlated approval identity, and claim/persist/ack queueing across tools, `Task`, provider/webview, message queue, and history schema. | XL | High: cross-task contamination and persistence precedence | Omitted/explicit child controls, switch/restart E2E, two-approval schedules, queue failure retention, mode-permission tests. |
233233
| P6. Event and ingress contracts | 009, 011, 022, 027, 028, 029, 032, 033 | Classify barriers versus notifications; normalize lifecycle payloads and clear/resume semantics across Task, provider, public API, IPC, and webview. | L | Medium-high: public compatibility and ordering | Exactly-once event tests, consumer inventory, cross-surface contract matrix, compatibility adapters where required. |
@@ -241,7 +241,7 @@ The 40 IDs are not 40 independent projects. They group into eight programs with
241241
- One request-generation/canonical-call identity established before parser indexing can support 008, 010, 024–026, 030, 037, and 038.
242242
- One correlated `(taskId, actionId, toolCallId)` approval protocol can close 036 and support 007/035; it does not itself make child state durable.
243243
- One typed lifecycle operation layer can normalize P6, but public compatibility requires separate adapters rather than a flag-day payload rewrite.
244-
- One validated-read and cycle-safe traversal guard closes 041 beside 018 and 019.
244+
- One validated-read and cycle-safe traversal guard closes 018 and 019.
245245

246246
### Independent work that should not be collapsed
247247

@@ -313,7 +313,7 @@ Four workstreams can proceed concurrently after foundation decisions:
313313
| Correlated approval ownership | LIFE-GAP-036 |
314314
| Task/tool-call-scoped partial state | LIFE-GAP-037 with request-generation cleanup gaps 010 and 024 |
315315
| Canonical tool-call identity | LIFE-GAP-038 with generation/replay gap 012 |
316-
| Validated-read and traversal-guard design | LIFE-GAP-018, 019, 041 | |
316+
| Validated-read and traversal-guard design | LIFE-GAP-018, 019 | |
317317

318318
## Mechanically useful follow-up checklist
319319

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

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -41,20 +41,20 @@ TLA+/PlusCal or Quint with TLC becomes a better fit when the lifecycle needs tem
4141

4242
## Production mapping
4343

44-
| Model concept | Production concept |
45-
| ------------------------- | ------------------------------------------------------------------------------------ |
46-
| Task record and status | `HistoryItem` persisted by `TaskHistoryStore` |
47-
| `delegate(parent, child)` | `ClineProvider.delegateParentAndOpenChild` |
48-
| `interrupt(child)` | cancellation or eviction through `markDelegatedChildInterrupted` |
49-
| `complete(child)` | `ClineProvider.reopenParentFromDelegation` |
50-
| `abandon(child)` | `ClineProvider.abandonSubtask` |
51-
| Pending-action settlement | `settleRejectedCreateSubtaskAction` inside the delegation update path (#1714) |
52-
| Atomic event step | `atomicReadAndUpdate`, `atomicUpdatePair`, and per-parent delegation transition lock |
53-
| Event interleaving | Competing completion, cancellation, abandonment, and new delegation calls |
44+
| Model concept | Production concept |
45+
| ------------------------- | -------------------------------------------------------------------------------------------------------------------- |
46+
| Task record and status | `HistoryItem` persisted by `TaskHistoryStore` |
47+
| `delegate(parent, child)` | `ClineProvider.delegateParentAndOpenChild` |
48+
| `interrupt(child)` | cancellation or eviction through `markDelegatedChildInterrupted` |
49+
| `complete(child)` | `ClineProvider.reopenParentFromDelegation` |
50+
| `abandon(child)` | `ClineProvider.abandonSubtask` |
51+
| Pending-action settlement | `TaskHistoryStore.clearPendingActionIfMatching` compare-and-clear in the rejected-delegation settlement path (#1714) |
52+
| Atomic event step | `atomicReadAndUpdate`, `atomicUpdatePair`, and per-parent delegation transition lock |
53+
| Event interleaving | Competing completion, cancellation, abandonment, and new delegation calls |
5454

5555
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.
5656

57-
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 preserves unrelated actions, 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 writes the settled record with one extra `atomicReadAndUpdate` call, then propagates the original rejection. Four named witnesses must remain reachable: settlement from an interrupted record after rejection, settlement through a successful active delegation, unrelated-action preservation during completion, and stale-action protection where a settlement targeting one action ID leaves a replacement action intact. A mismatched pending-action request keeps its production behavior: the atomic update throws before any transition, and no settlement runs.
57+
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.
5858

5959
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.
6060

@@ -66,6 +66,7 @@ The same `pnpm lifecycle:model-check` command also runs a second bounded explore
6666
- store read/update operations hold the host mutex, while live-task snapshots used by completion and message saves may outlive it;
6767
- a write delta is computed relative to that host's cache;
6868
- revalidation under the per-file disk lock checks only status-transition legality;
69+
- the rejected-delegation settlement compare-and-clear decides inside the disk merge callback, so a replacement action persisted by another host is never cleared;
6970
- fields absent from the delta preserve the current disk value, `childIds` are unioned, and other same-field conflicts are last-writer-wins;
7071
- `atomicUpdatePair` commits its files in order, with another host able to act between file commits;
7172
- successful pair-operation cache entries publish together after both file writes; if the second write fails, the cache publishes only the first committed record;
@@ -82,7 +83,7 @@ CI fails if either exact causal witness or violation class changes, a witness di
8283

8384
The known-unsafe witnesses currently compare exact shortest action sequences. This is intentionally simple and reviewable, but brittle to harmless action renames or serialization refactors. A causal partial-order comparator would reduce that brittleness but would add a second trace-equivalence protocol to maintain. Until that complexity is justified, update an exact witness only after confirming the terminal violation class and required causal ordering are unchanged.
8485

85-
`TaskHistoryStore.realConcurrency.spec.ts` complements the abstract interleavings with one synchronized integration smoke check through the real `proper-lockfile` and filesystem rename path; broader VS Code E2E remains reserved for restart and extension-host behavior.
86+
`TaskHistoryStore.realConcurrency.spec.ts` complements the abstract interleavings with real-filesystem checks through the real `proper-lockfile` and filesystem rename path, including the stale-settlement compare-and-clear regression; broader VS Code E2E remains reserved for restart and extension-host behavior.
8687

8788
## Task cleanup protocol model
8889

@@ -137,7 +138,8 @@ The task delegation checker currently enforces:
137138
5. Parent-child lineage is acyclic.
138139
6. Completed task records cannot be changed by later lifecycle events.
139140
7. Active-child re-delegation, stale completion after ownership moves to another child, duplicate/late completion, and abandonment of a live child are rejected by the shared production guards.
140-
8. A rejected delegation settles only the exact matching pending `create_subtask` action. Settlement preserves status, lineage, and accounting, never clears a replacement or different-kind action, and never mutates a completed record.
141+
8. A rejected delegation settles only the exact matching pending `create_subtask` action. Settlement preserves status, lineage, and accounting, never clears a replacement or different-kind action, and never mutates a completed record. The settlement compare-and-clear reads the persisted record under the per-file lock, so it never clears from a stale host cache.
142+
9. A completion clears the completing child's pending action only when the completion event carries the exact matching action ID. A completion with no action ID or a different ID preserves the pending action.
141143

142144
The completion persistence checker additionally enforces:
143145

‎scripts/check-task-lifecycle.ts‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ interface Transition {
1818
name: string
1919
next: ModelState
2020
delegation?: { parentId: TaskId }
21-
completion?: { childId: TaskId }
21+
completion?: { childId: TaskId; pendingActionId?: string }
2222
settlement?: { taskId: TaskId; actionId: string }
2323
}
2424

@@ -77,6 +77,28 @@ const semanticWitnesses = {
7777
next[transition.settlement.taskId]?.pendingAction?.actionId === beforeAction.actionId
7878
)
7979
},
80+
"matching-completion-clears-pending-action": ({ prev, next, transition }: WitnessContext) => {
81+
if (transition.completion?.pendingActionId === undefined) return false
82+
const beforeAction = prev[transition.completion.childId]?.pendingAction
83+
const after = next[transition.completion.childId]
84+
return (
85+
beforeAction?.kind === "create_subtask" &&
86+
beforeAction.actionId === transition.completion.pendingActionId &&
87+
after?.status === "completed" &&
88+
after.pendingAction === undefined
89+
)
90+
},
91+
"replacement-completion-preserves-pending-action": ({ prev, next, transition }: WitnessContext) => {
92+
if (transition.completion?.pendingActionId === undefined) return false
93+
const beforeAction = prev[transition.completion.childId]?.pendingAction
94+
const after = next[transition.completion.childId]
95+
return (
96+
beforeAction?.kind === "create_subtask" &&
97+
beforeAction.actionId !== transition.completion.pendingActionId &&
98+
after?.status === "completed" &&
99+
canonicalTask(after.pendingAction) === canonicalTask(beforeAction)
100+
)
101+
},
80102
} satisfies Record<string, (context: WitnessContext) => boolean>
81103

82104
function task(id: TaskId, parentTaskId?: TaskId): HistoryItem {
@@ -178,6 +200,17 @@ function transitions(state: ModelState): Transition[] {
178200
next: replace(state, completed.parent, completed.child),
179201
completion: { childId },
180202
})
203+
for (const actionId of actionIds) {
204+
const completedChild: HistoryItem =
205+
child.pendingAction?.actionId === actionId
206+
? { ...completed.child, pendingAction: undefined }
207+
: completed.child
208+
result.push({
209+
name: `complete(${childId}, ${actionId})`,
210+
next: replace(state, completed.parent, completedChild),
211+
completion: { childId, pendingActionId: actionId },
212+
})
213+
}
181214
}
182215

183216
if (parent.status === "delegated" && parent.awaitingChildId === child.id && child.status === "interrupted") {
@@ -288,6 +321,19 @@ function checkTransitionInvariants(previous: ModelState, transition: Transition)
288321
)
289322
}
290323
}
324+
325+
const completion = transition.completion
326+
if (completion) {
327+
const beforeAction = previous[completion.childId]?.pendingAction
328+
const afterAction = transition.next[completion.childId]?.pendingAction
329+
330+
if (afterAction && canonicalTask(afterAction) !== canonicalTask(beforeAction)) {
331+
violations.push(`${completion.childId}: completion after ${transition.name} replaced a pending action`)
332+
}
333+
if (!afterAction && beforeAction && beforeAction.actionId !== completion.pendingActionId) {
334+
violations.push(`${completion.childId}: completion after ${transition.name} cleared a non-matching action`)
335+
}
336+
}
291337
return violations
292338
}
293339

@@ -409,5 +455,5 @@ function runRepresentativeScenarios(): void {
409455
runRepresentativeScenarios()
410456
const checkedStates = runModelCheck()
411457
console.log(
412-
`Task lifecycle model check passed: ${checkedStates} reachable states, ${expectedActions.length}/${expectedActions.length} actions reachable, ${Object.keys(semanticLandmarks).length}/${Object.keys(semanticLandmarks).length} landmarks reached, ${Object.keys(semanticWitnesses).length}/${Object.keys(semanticWitnesses).length} settlement witnesses reached, depth <= ${MAX_DEPTH}, ${taskIds.length} task slots`,
458+
`Task lifecycle model check passed: ${checkedStates} reachable states, ${expectedActions.length}/${expectedActions.length} actions reachable, ${Object.keys(semanticLandmarks).length}/${Object.keys(semanticLandmarks).length} landmarks reached, ${Object.keys(semanticWitnesses).length}/${Object.keys(semanticWitnesses).length} semantic witnesses reached, depth <= ${MAX_DEPTH}, ${taskIds.length} task slots`,
413459
)

0 commit comments

Comments
 (0)