Skip to content

Commit 666df9f

Browse files
committed
feat(run-state): add the turn sub-machine (#1800)
1 parent cb698be commit 666df9f

3 files changed

Lines changed: 215 additions & 13 deletions

File tree

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

Lines changed: 48 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -190,12 +190,28 @@ type RunState = {
190190
generation: number
191191
stream: Stream
192192
ask: Ask
193+
turn: Turn
193194
latches: Latches
194195
lastCompletionAskTs?: number
195196
}
196197

198+
type Turn = {
199+
waitingForFirstChunk: boolean
200+
toolRejected: boolean
201+
toolUsed: boolean
202+
toolFailed: boolean
203+
streamReadComplete: boolean
204+
}
205+
197206
type RunEvent =
198207
| { tag: "initialized" }
208+
| { tag: "turnStarted" }
209+
| { tag: "firstChunkAwaitStarted" }
210+
| { tag: "firstChunkAwaitEnded" }
211+
| { tag: "toolRejected" }
212+
| { tag: "toolUsed" }
213+
| { tag: "toolFailed" }
214+
| { tag: "streamReadCompleted" }
199215
| { tag: "streamStarted" }
200216
| { tag: "streamCleanupFinished" }
201217
| { tag: "streamEnded" }
@@ -235,19 +251,26 @@ Queued user input is out of scope for the kernel. The queued-input bugs (#1308,
235251

236252
Each event has a guard and an effect. If the guard fails, the event returns `rejected` with the state unchanged. An effect changes only the fields it names.
237253

238-
| Event | Guard | Effect |
239-
| ----------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
240-
| `initialized` | phase is uninitialized | phase = running |
241-
| `streamStarted` | phase is running, stream is none | generation + 1, stream = live(generation, cleanupFinished false), lastCompletionAskTs = empty |
242-
| `streamCleanupFinished` | stream is live | stream.cleanupFinished = true |
243-
| `streamEnded` | stream is live | stream = none |
244-
| `askStarted` | phase is running, abort is false | ask = the new ask. lastCompletionAskTs = its askTs if it is a completion ask, else empty |
245-
| `askSettled` | none | if ask.askTs equals the event askTs, ask = none. Else no change |
246-
| `completionAccepted` | phase is running, abort is false, askTs equals lastCompletionAskTs | phase = completed, ask = none |
247-
| `reasonSet` | none | if reason is empty, reason = the new reason. Else no change |
248-
| `abortRequested` | none | abort = true. If the event has abandoned true, abandoned = true |
249-
| `abandonRequested` | abort is true | abandoned = true |
250-
| `disposeRequested` | none | abort = true, disposed = true |
254+
| Event | Guard | Effect |
255+
| ------------------------ | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------- |
256+
| `initialized` | phase is uninitialized | phase = running |
257+
| `turnStarted` | none | toolRejected, toolUsed, toolFailed, streamReadComplete = false. waitingForFirstChunk unchanged |
258+
| `firstChunkAwaitStarted` | none | turn.waitingForFirstChunk = true |
259+
| `firstChunkAwaitEnded` | none | turn.waitingForFirstChunk = false |
260+
| `toolRejected` | none | turn.toolRejected = true |
261+
| `toolUsed` | none | turn.toolUsed = true |
262+
| `toolFailed` | none | turn.toolFailed = true |
263+
| `streamReadCompleted` | none | turn.streamReadComplete = true |
264+
| `streamStarted` | phase is running, stream is none | generation + 1, stream = live(generation, cleanupFinished false), lastCompletionAskTs = empty |
265+
| `streamCleanupFinished` | stream is live | stream.cleanupFinished = true |
266+
| `streamEnded` | stream is live | stream = none |
267+
| `askStarted` | phase is running, abort is false | ask = the new ask. lastCompletionAskTs = its askTs if it is a completion ask, else empty |
268+
| `askSettled` | none | if ask.askTs equals the event askTs, ask = none. Else no change |
269+
| `completionAccepted` | phase is running, abort is false, askTs equals lastCompletionAskTs | phase = completed, ask = none |
270+
| `reasonSet` | none | if reason is empty, reason = the new reason. Else no change |
271+
| `abortRequested` | none | abort = true. If the event has abandoned true, abandoned = true |
272+
| `abandonRequested` | abort is true | abandoned = true |
273+
| `disposeRequested` | none | abort = true, disposed = true |
251274

252275
Transition notes:
253276

@@ -324,6 +347,18 @@ The `didFinishAbortingStream` getter is false after the stream ends. The only re
324347

325348
The turn sub-machine holds five within-turn fields: `isWaitingForFirstChunk`, `didRejectTool`, `didAlreadyUseTool`, `didToolFailInCurrentTurn`, and `didCompleteReadingStream`. A turn is one request iteration of the loop. It starts at the per-request reset block (`Task.ts:3228-3245`), before `streamStarted`. It ends when the next iteration starts. It is independent of the stream region, because the loop writes these fields after the stream ends (`Task.ts:3768, 3810, 3830, 4029`).
326349

350+
Turn events have no guard. The loop and the tools write these fields in every phase, after abort, and after the stream ends. No other event changes the turn. Event and field names map to the `Task` fields as follows.
351+
352+
| Kernel field (event) | `Task` field |
353+
| ------------------------------------------------------- | -------------------------- |
354+
| `waitingForFirstChunk` (`firstChunkAwaitStarted/Ended`) | `isWaitingForFirstChunk` |
355+
| `toolRejected` (`toolRejected`) | `didRejectTool` |
356+
| `toolUsed` (`toolUsed`) | `didAlreadyUseTool` |
357+
| `toolFailed` (`toolFailed`) | `didToolFailInCurrentTurn` |
358+
| `streamReadComplete` (`streamReadCompleted`) | `didCompleteReadingStream` |
359+
360+
`turnStarted` does not reset `waitingForFirstChunk`. The legacy reset block does not clear `isWaitingForFirstChunk`, and `attemptApiRequest` clears it. If the chunk loop breaks on the first chunk, the generator never resumes and the flag stays true. The kernel keeps that behavior, so RSK-10 and RSK-16 do not change graceful-abort timing at `ClineProvider.ts:3641`.
361+
327362
#### External writers
328363

329364
`ClineProvider` writes `abortReason` (`:3572`) and `abandoned` (`:3588`) directly. It calls `abortTask` at `:631` and `:1389`. `checkpointRestoreHandler` calls `abortTask` (`:34`). RSK-06 routes every one of these writes through events before any read flips.

‎src/core/task/run-state/__tests__/runState.spec.ts‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,13 @@ const completedStreaming = deepFreeze(
6565
)
6666
const allEvents: RunEvent[] = [
6767
{ tag: "initialized" },
68+
{ tag: "turnStarted" },
69+
{ tag: "firstChunkAwaitStarted" },
70+
{ tag: "firstChunkAwaitEnded" },
71+
{ tag: "toolRejected" },
72+
{ tag: "toolUsed" },
73+
{ tag: "toolFailed" },
74+
{ tag: "streamReadCompleted" },
6875
{ tag: "streamStarted" },
6976
{ tag: "streamCleanupFinished" },
7077
{ tag: "streamEnded" },
@@ -78,6 +85,112 @@ const allEvents: RunEvent[] = [
7885
]
7986

8087
describe("nextRunState", () => {
88+
describe("turn", () => {
89+
const allSet = {
90+
waitingForFirstChunk: true,
91+
toolRejected: true,
92+
toolUsed: true,
93+
toolFailed: true,
94+
streamReadComplete: true,
95+
}
96+
const dirty = deepFreeze({ ...running, turn: allSet })
97+
const clean = deepFreeze({ ...running, turn: { ...running.turn } })
98+
const turnEvents = [
99+
["firstChunkAwaitStarted", "waitingForFirstChunk"],
100+
["toolRejected", "toolRejected"],
101+
["toolUsed", "toolUsed"],
102+
["toolFailed", "toolFailed"],
103+
["streamReadCompleted", "streamReadComplete"],
104+
] as const
105+
106+
it.each(turnEvents)("%s sets only %s", (tag, field) => {
107+
const next = accept(clean, { tag })
108+
expect(next.turn).toEqual({ ...clean.turn, [field]: true })
109+
expect({ ...next, turn: clean.turn }).toEqual(clean)
110+
})
111+
112+
it.each(turnEvents)("%s keeps the other four fields when they are set", (tag, field) => {
113+
const base = deepFreeze({ ...running, turn: { ...allSet, [field]: false } })
114+
expect(accept(base, { tag }).turn).toEqual(allSet)
115+
})
116+
117+
it("firstChunkAwaitEnded clears only waitingForFirstChunk", () => {
118+
const state = run([{ tag: "firstChunkAwaitStarted" }, { tag: "toolUsed" }], running)
119+
expect(accept(state, { tag: "firstChunkAwaitEnded" }).turn).toEqual({
120+
...state.turn,
121+
waitingForFirstChunk: false,
122+
})
123+
})
124+
125+
it("firstChunkAwaitEnded keeps the other four fields when they are set", () => {
126+
expect(accept(dirty, { tag: "firstChunkAwaitEnded" }).turn).toEqual({
127+
...allSet,
128+
waitingForFirstChunk: false,
129+
})
130+
})
131+
132+
it.each(["streamStarted", "streamCleanupFinished", "streamEnded"] as const)(
133+
"%s leaves the turn unchanged",
134+
(tag) => {
135+
const live = deepFreeze({ ...(tag === "streamStarted" ? running : streaming), turn: allSet })
136+
expect(accept(live, { tag }).turn).toEqual(allSet)
137+
},
138+
)
139+
140+
it("initialized leaves the turn unchanged", () => {
141+
expect(accept({ ...initialRunState, turn: allSet }, { tag: "initialized" }).turn).toEqual(allSet)
142+
})
143+
144+
it("turnStarted resets the four per-request fields and keeps waitingForFirstChunk", () => {
145+
expect(accept(dirty, { tag: "turnStarted" }).turn).toEqual({
146+
...running.turn,
147+
waitingForFirstChunk: true,
148+
})
149+
})
150+
151+
it.each([initialRunState, completed, aborted])("accepts every turn event when the phase is $phase", (state) => {
152+
const turnEvents: RunEvent[] = [
153+
{ tag: "turnStarted" },
154+
{ tag: "firstChunkAwaitStarted" },
155+
{ tag: "firstChunkAwaitEnded" },
156+
{ tag: "toolRejected" },
157+
{ tag: "toolUsed" },
158+
{ tag: "toolFailed" },
159+
{ tag: "streamReadCompleted" },
160+
]
161+
for (const event of turnEvents) {
162+
expect(nextRunState(state, event)).toHaveProperty("ok")
163+
}
164+
})
165+
166+
it("accepts tool writes after the stream ends", () => {
167+
const ended = run([{ tag: "streamEnded" }, { tag: "toolUsed" }, { tag: "toolFailed" }], streaming)
168+
expect(ended.stream).toEqual({ tag: "none" })
169+
expect(ended.turn).toMatchObject({ toolUsed: true, toolFailed: true })
170+
})
171+
172+
it("clears the first-chunk wait when abort lands before the first chunk", () => {
173+
const state = run(
174+
[
175+
{ tag: "turnStarted" },
176+
{ tag: "streamStarted" },
177+
{ tag: "firstChunkAwaitStarted" },
178+
{ tag: "abortRequested", abandoned: false },
179+
{ tag: "firstChunkAwaitEnded" },
180+
],
181+
running,
182+
)
183+
expect(state.latches.abort).toBe(true)
184+
expect(state.turn.waitingForFirstChunk).toBe(false)
185+
expect(state.turn.streamReadComplete).toBe(false)
186+
})
187+
188+
it("a turn started after an abort still resets the fields", () => {
189+
const state = run([{ tag: "toolFailed" }, { tag: "abortRequested", abandoned: false }], running)
190+
expect(accept(state, { tag: "turnStarted" }).turn).toEqual(running.turn)
191+
})
192+
})
193+
81194
describe("initialized", () => {
82195
it("moves uninitialized to running", () => {
83196
acceptOnly(initialRunState, { tag: "initialized" }, { phase: "running" })
@@ -414,9 +527,17 @@ describe("nextRunState", () => {
414527
generation: 0,
415528
stream: { tag: "none" },
416529
ask: { tag: "none" },
530+
turn: {
531+
waitingForFirstChunk: false,
532+
toolRejected: false,
533+
toolUsed: false,
534+
toolFailed: false,
535+
streamReadComplete: false,
536+
},
417537
latches: { abort: false, abandoned: false, disposed: false },
418538
})
419539
expect(Object.isFrozen(initialRunState)).toBe(true)
540+
expect(Object.isFrozen(initialRunState.turn)).toBe(true)
420541
expect(Object.isFrozen(initialRunState.stream)).toBe(true)
421542
expect(Object.isFrozen(initialRunState.ask)).toBe(true)
422543
expect(Object.isFrozen(initialRunState.latches)).toBe(true)

‎src/core/task/run-state/runState.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,14 @@ export type Ask =
1212
| { tag: "completion"; askTs: number }
1313
| { tag: "other"; askTs: number }
1414

15+
export type Turn = {
16+
waitingForFirstChunk: boolean
17+
toolRejected: boolean
18+
toolUsed: boolean
19+
toolFailed: boolean
20+
streamReadComplete: boolean
21+
}
22+
1523
export type Latches = {
1624
abort: boolean
1725
abandoned: boolean
@@ -24,12 +32,20 @@ export type RunState = {
2432
generation: number
2533
stream: Stream
2634
ask: Ask
35+
turn: Turn
2736
latches: Latches
2837
lastCompletionAskTs?: number
2938
}
3039

3140
export type RunEvent =
3241
| { tag: "initialized" }
42+
| { tag: "turnStarted" }
43+
| { tag: "firstChunkAwaitStarted" }
44+
| { tag: "firstChunkAwaitEnded" }
45+
| { tag: "toolRejected" }
46+
| { tag: "toolUsed" }
47+
| { tag: "toolFailed" }
48+
| { tag: "streamReadCompleted" }
3349
| { tag: "streamStarted" }
3450
| { tag: "streamCleanupFinished" }
3551
| { tag: "streamEnded" }
@@ -43,11 +59,20 @@ export type RunEvent =
4359

4460
export type Transition = { ok: RunState } | { rejected: RunState }
4561

62+
const initialTurn: Readonly<Turn> = Object.freeze({
63+
waitingForFirstChunk: false,
64+
toolRejected: false,
65+
toolUsed: false,
66+
toolFailed: false,
67+
streamReadComplete: false,
68+
})
69+
4670
export const initialRunState: Readonly<RunState> = Object.freeze({
4771
phase: "uninitialized",
4872
generation: 0,
4973
stream: Object.freeze({ tag: "none" }),
5074
ask: Object.freeze({ tag: "none" }),
75+
turn: initialTurn,
5176
latches: Object.freeze({ abort: false, abandoned: false, disposed: false }),
5277
})
5378

@@ -59,6 +84,27 @@ export function nextRunState(state: RunState, event: RunEvent): Transition {
5984
}
6085
return { ok: { ...state, phase: "running" } }
6186

87+
case "turnStarted":
88+
return { ok: { ...state, turn: { ...initialTurn, waitingForFirstChunk: state.turn.waitingForFirstChunk } } }
89+
90+
case "firstChunkAwaitStarted":
91+
return { ok: { ...state, turn: { ...state.turn, waitingForFirstChunk: true } } }
92+
93+
case "firstChunkAwaitEnded":
94+
return { ok: { ...state, turn: { ...state.turn, waitingForFirstChunk: false } } }
95+
96+
case "toolRejected":
97+
return { ok: { ...state, turn: { ...state.turn, toolRejected: true } } }
98+
99+
case "toolUsed":
100+
return { ok: { ...state, turn: { ...state.turn, toolUsed: true } } }
101+
102+
case "toolFailed":
103+
return { ok: { ...state, turn: { ...state.turn, toolFailed: true } } }
104+
105+
case "streamReadCompleted":
106+
return { ok: { ...state, turn: { ...state.turn, streamReadComplete: true } } }
107+
62108
case "streamStarted": {
63109
if (state.phase !== "running" || state.stream.tag !== "none") {
64110
return { rejected: state }

0 commit comments

Comments
 (0)