Skip to content

🤖 refactor: give turn-engine ProviderRequest sole write access to the attempt request - #7483

Merged
ThomasK33 merged 6 commits into
mainfrom
turn-engine/attempt-request
Oct 25, 2026
Merged

ThomasK33 merged 6 commits into
mainfrom
turn-engine/attempt-request

Conversation

@ThomasK33

@ThomasK33 ThomasK33 commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Layer 5w of the turn-engine split in stack #7398 (based on #7482). Layer 5 slice 9, part (c): make the AttemptRequest record read-only outside ProviderRequest, so only ProviderRequest writes the stream result, request, model, thinking level and retry flags. No behavior change.

What changed

Layer 5 slice 9c. No behavior change. AttemptRequest (streamResult, model,
metadataModel, thinkingLevel, request, stepTracker, the three
didRetry* flags and modelFallback) is now Readonly in
WorkspaceStreamInfo. Only ProviderRequest writes it after the record is
built.

The writes that move behind ProviderRequest:

  • The four attempt restarts (AttemptLoop's empty-output retry,
    StreamRetries' previousResponseId and reasoning-replay retries, and
    RefusalFallback's model hop) call ProviderRequest.beginAttempt. It
    sets the request first, then the stream result built from that
    request, the same order the callers used.
  • The three step-boundary and empty-output retry flags go through
    ProviderRequest.markRetry.
  • RefusalFallback's model swap calls ProviderRequest.adoptModel. The
    thinking level still changes only when the fallback chose one.
  • TurnEngine's two thinking-override writes call
    ProviderRequest.setThinkingLevel.

The four methods are static: they only write the record, so no caller
gains a dep. Each call sits where its assignments were, so no ordering
changes. AttemptLoop, RefusalFallback, StreamRetries and TurnEngine now
import ProviderRequest as a value (no cycle).

Scratch mutations on this commit, against the streamManager, turnEngine,
aiService and agentSession suites: 15 of 15 fail a test.

Lines: 86 added and 40 removed in 6 files.

Validation

  • Scratch mutants on the new owner methods: 15 of 15 fail a test, so this PR has no test-only commit.
  • 1032 targeted tests pass here (streamManager*, aiService, turnEngine, continuousCompactor, turnRequestBuilder, coreServicesRoot, serviceContainer, errorRecovery), and make typecheck passes. The builder's wider run passed 2776 of 2776.
  • make static-check, make lint-eslint, make dry-check and the CRAP check (with coverage, 0 violations and 0 warnings) pass with the parent as the base. No import cycle exists.

Risks

Low. Field writes in AttemptLoop, StreamRetries, RefusalFallback and TurnEngine become calls to four static ProviderRequest writers (beginAttempt, markRetry, adoptModel, setThinkingLevel) that make the same assignments in the same order. beginAttempt sets the request before it builds the stream result from it, as the old code did. The compiler now rejects any other write to the record.


Generated with xum • Model: anthropic:claude-opus-5-5 • Thinking: high • Cost: $80.79

@ThomasK33
ThomasK33 added this pull request to stack #7398 October 25, 2026 14:11
@ThomasK33 ThomasK33 changed the title turn engine/attempt request 🤖 refactor: give turn-engine ProviderRequest sole write access to the attempt request Oct 25, 2026
@ThomasK33

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T20:56:02.818762Z 1595b80 New commits
🔒 Security Review ✅ Completed 2026-10-25T20:57:18.811232Z 1595b80 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 82136d1e8e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: 82136d1e8e

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@ThomasK33

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 35c7cafdaf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: 35c7cafdaf

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@ThomasK33
ThomasK33 marked this pull request as ready for review October 25, 2026 18:03
@github-actions

github-actions Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

🟢 e2e stories (Haiku): 14 passed

27 agent steps · 7 replayed from cache · 33 model calls · 235.5k tokens (77% cached)
Spend: $0.09 of the $1.00 cap (proxy ledger)

All 14 tests in 9 files
Test Agent Time
🟢 chatRestart.e2e.ts · 1 passed 2 steps · 5 calls 27.6s
🟢 a chat survives a restart of the server 2 steps · 5 calls 27.6s
🟢 compaction.e2e.ts · 1 passed 3 steps · 7 calls 43.8s
🟢 /compact replaces the old chat with a summary 3 steps · 7 calls 43.8s
🟢 pluginTrustRestart.e2e.ts · 1 passed 4 steps · 2 calls 9.8s
🟢 a trusted plugin hook stays trusted after the server restarts 4 steps · 2 calls 9.8s
🟢 settingsRoundTrip.e2e.ts · 1 passed 3 steps · 5 calls 28.7s
🟢 a chat survives trips through Settings 3 steps · 5 calls 28.7s
🟢 sidebarPerWorkspace.e2e.ts · 1 passed 4 steps · 1 call 4.2s
🟢 a new workspace starts with its right sidebar collapsed while another keeps it open 4 steps · 1 call 4.2s
🟢 smoke.e2e.ts · 1 passed 2 steps · 1 call 2.6s
🟢 the agent opens the playground workspace 2 steps · 1 call 2.6s
🟢 streamErrors.e2e.ts · 1 passed 1 step · 1 call 7.2s
🟢 stream errors show in the chat, and the chat recovers 1 step · 1 call 7.2s
🟢 todoNudge.e2e.ts · 1 passed 2 steps · 5 calls 23.7s
🟢 the agent finishes open TODO items after the turn-end nudge 2 steps · 5 calls 23.7s
🟢 touchAlignment.e2e.ts · 6 passed 6 steps · 6 calls 22.2s
🟢 the Settings close button is level with the title on a touch screen 390px wide 1 step · 1 call 3.7s
🟢 the Settings close button is level with the title on a touch screen 768px wide 1 step · 1 call 4.3s
🟢 Backup settings checkboxes are small and level with their labels on a touch phone 1 step · 1 call 4.7s
🟢 the heartbeat checkbox is small and level with its label on a touch phone 1 step · 1 call 3.4s
🟢 a reply's model and time stay on one line on a touch phone 1 step · 1 call 3.1s
🟢 the workspace actions menu stays on the title row on a touch phone 1 step · 1 call 3.0s

e2e 0.20.0 · 2m 53s · web · run artifacts

🟢 e2e Electron stories (Haiku): 3 passed

3 agent steps · 3 model calls · 8.0k tokens (32% cached)
Spend: $0.01 of the $1.00 cap (proxy ledger)

All 3 tests in 3 files
Test Agent Time
🟢 electron/deepLink.e2e.ts · 1 passed 1 step · 1 call 5.7s
🟢 a deep link of a second launch starts a chat in the running app 1 step · 1 call 5.7s
🟢 electron/menuBar.e2e.ts · 1 passed 1 step · 1 call 6.4s
🟢 the workspace menu bar is the desktop title bar 1 step · 1 call 6.4s
🟢 electron/smoke.e2e.ts · 1 passed 1 step · 1 call 5.3s
🟢 Xum Electron opens the playground workspace 1 step · 1 call 5.3s

e2e 0.20.0 · 19.7s · electron · run artifacts

🟢 e2e agent repros (Haiku): no tests selected

Spend: $0.00 of the $1.00 cap (proxy ledger)

e2e 0.20.0 · 6.1s · 2 targets (web, phone) · run artifacts

@ThomasK33
ThomasK33 force-pushed the turn-engine/attempt-request branch from 35c7caf to d2a735c Compare October 25, 2026 19:45
@ThomasK33

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: d2a735c3f3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: d2a735c3f3

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@ThomasK33
ThomasK33 added this pull request to the merge queue Oct 25, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue because a pull request earlier in the stack was removed Oct 25, 2026
Layer 5 slice 7, step 2 of 2. StreamManager no longer owns the abort
settle that TurnRegistry runs after a hard or soft stop. This commit
moves cleanupAbortedStream and its parts, unchanged, into
turnEngine/AttemptLoop.ts.

Why AttemptLoop: its module comment already says it settles every
terminal outcome, and it holds the other two (completeStream for
stream-end, persistStreamError for errors). The abort settle runs the
same steps on the same state: usage, the reasoning backfill, the session
usage settle, the partial, the terminal event, unregistering, then
terminalCompletion and the completion settle. Its lost-race guard
(terminalCompletion already set) is a contract with those two paths and
with settleStreamProcessing, and now all of them live in one file.
AttemptLoop already had seven of the eight deps it needs (only the
display registry is new). TurnRegistry would have needed six new deps
plus a wider turnEvents Pick, type imports of TurnResources,
PartialJournal and UsageLedger, and TurnResources built before it in
StreamManager.

Moved from streamManager.ts:
- Methods cleanupAbortedStream (now public: TurnRegistry calls it),
  persistAbortedStreamUsage and finishAbortedStream.
- Module code: AbortedStreamUsage, buildStreamAbortEvent and
  abortedPartialMetadata.

Rewrites outside the moved blocks:
- StreamManager wires TurnRegistry's cleanupAbortedStream dep to
  this.attemptLoop.cleanupAbortedStream. The forward reads the field at
  call time because AttemptLoop is built after TurnRegistry. TurnRegistry
  itself does not change, except its module comment.
- AttemptLoopDeps gains toolCallDisplayRegistry (Pick "close"). Its
  partialJournal Pick adds awaitPending, writeAbortPartial and
  settleAbort, and its turnEvents Pick adds deliver. StreamManager passes
  its toolCallDisplayRegistry.
- AttemptLoop imports hasCommitWorthyParts (historyService),
  StreamAbortEvent and StreamAbortReason, and the ToolCallDisplayRegistry
  type. streamManager.ts drops the imports only the moved code used.

Lines: 262 added and 262 removed in moved blocks, 32 added and 29
removed outside them. streamManager.ts goes from 1467 to 1185 lines.
AttemptLoop.ts goes from 889 to 1173 lines. No turnEngine module imports
streamManager.ts. No import cycles.

The test-only commit two back pins ten survivors of the unsplit
function. Scratch mutations on this commit, against the streamManager,
turnEngine, aiService and agentSession suites: 28 of 29
fail a test (one of them, run by hand, makes the TurnRegistry forward a
no-op). Not killed: skipping partialJournal.awaitPending before the
abort partial write, which is equivalent (see the test commit).

Gates: make static-check, make lint-eslint and make dry-check pass.
crap-check against the parent passes with coverage (0 violations, 0
warnings). Wide
suite: 2774 pass, 0 fail.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
Test-only commit before layer 5 slice 9a moves the stream's
unlinkAbortSignal from a post-construction write in TurnEngine into the
stream info literal. A scratch edit that drops the write (so the stream
never unlinks the caller's signal) survived the existing tests.

New test in streamManager.resources.test.ts, "stream resource scope": a
stream started with a caller abort signal adds one abort listener to it,
and the listener is gone once the stream completes.

Scratch mutation on this commit: the edit now fails the test.

No production code changes.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
Layer 5 slice 9a, the first of four stacked steps. No behavior change.
WorkspaceStreamInfo was one flat interface in types.ts. It now lives in
the new turnEngine/turnState.ts and is built from six records. Each
record names its owner: the one module that writes its fields after
TurnEngine builds the stream info.

| Record | Owner | Enforced |
|---|---|---|
| TurnState | StepApply | 9d |
| TurnSlot | TurnRegistry | 9b |
| AttemptRequest | ProviderRequest | 9c |
| TurnHandles | TurnResources | this commit |
| PartialJournalState | PartialJournal | this commit |
| UsageLedgerState | UsageLedger | already (#7412) |

Enforcement follows #7412: WorkspaceStreamInfo extends an enforced
record as Readonly, so a write from another module does not compile.
The owner takes `WorkspaceStreamInfo & Record`, which TypeScript lets it
write. The view is shallow: it stops reassigning a field, not changing
the Map or array the field holds.

Changes:
- turnState.ts (new): the four new records, plus PartialJournalState and
  UsageLedgerState moved from types.ts. Fields keep their comments. The
  record field lists follow the accepted plan's sketch. The 45 fields
  are the old WorkspaceStreamInfo's, each in exactly one record.
- types.ts loses WorkspaceStreamInfo, the two state records and their
  imports. It stays a leaf: turnState.ts imports it, not the reverse.
- Callers import WorkspaceStreamInfo (and the two state records) from
  turnState.ts. PartialJournal and UsageLedger still re-export their
  record, and StreamManager still re-exports WorkspaceStreamInfo.
- TurnHandles and PartialJournalState are now Readonly in
  WorkspaceStreamInfo. PartialJournal had no outside writer. TurnHandles
  had one: TurnEngine set unlinkAbortSignal right after
  createStreamAtomically returned. TurnEngine now passes it in the
  registration context, and createStreamInfo puts it in the literal.
  Nothing ran between the two points.
- TurnResources.closeStreamResources takes `WorkspaceStreamInfo &
  TurnHandles`, since it writes resourceCleanup and unlinkAbortSignal.

The parent commit pins the unlink: a scratch edit that drops
unlinkAbortSignal from the literal now fails its test.

Lines: turnState.ts is 227 lines, and types.ts goes from 540 to 365
lines. No import cycles.

Gates: make static-check, make lint-eslint and make dry-check pass.
crap-check against the parent passes with coverage (0 violations, 0
warnings). Wide suite: 2775 pass, 0 fail.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
Test-only commit before layer 5 slice 9b moves the attempt loop's
TurnSlot writes behind TurnRegistry. Two scratch edits survived the
existing tests:
- The loop does not set STREAMING when processing starts (the turn
  stays STARTING).
- The failure path does not set ERROR (the turn stays STREAMING while it
  persists the error).

New test in streamManager.completion.test.ts, "stream start": a turn
whose provider stream fails reports getStreamState "streaming" at
stream-start and "error" at its error event. isStreaming() reads this
state.

Scratch mutations on this commit: both edits now fail the test.

No production code changes.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
…rn slot

Layer 5 slice 9b. No behavior change. TurnSlot (state, token, messageId,
workspaceName, executionScope, historySequence, startTime,
processingPromise, cancelPromise, engineFiber, softInterrupt,
completionController, terminalCompletion) is now Readonly in
WorkspaceStreamInfo. Only TurnRegistry writes it.

The writes that move behind TurnRegistry:
- AttemptLoop's three state changes (STREAMING when processing starts,
  COMPLETED before stream-end, ERROR on failure) call
  TurnRegistry.setState. Its type takes only those three states:
  STOPPING stays the stop's own.
- AttemptLoop's three terminal outcomes (completed, failed, aborted)
  call TurnRegistry.recordTerminal. The abort path now builds the
  completion in a local and settles the handle with that same object.
- TurnEngine's processing promise goes through
  TurnRegistry.trackProcessing.

The three methods are static: they only write the record, so neither
AttemptLoop nor TurnEngine gains a dep. Each call sits where its
assignment was, so no ordering changes. AttemptLoop and TurnEngine now
import TurnRegistry as a value (no cycle: TurnRegistry imports neither).
TurnRegistry's own writers (cancelStreamSafely, checkSoftCancelStream,
superviseEngine, stopEngine) take `WorkspaceStreamInfo & TurnSlot`.

The parent commit pins two survivors (the STREAMING and ERROR states).
Scratch mutations on this commit, against the streamManager, turnEngine,
aiService and agentSession suites: 9 of 10 fail a test. Not killed:
dropping recordTerminal on the abort path. It is equivalent: nothing
reads terminalCompletion after the abort settle sets it. The cancel
latch runs the settle once, and processing has already finished, so the
completion handle takes the local object directly.

Lines: 56 added and 21 removed in 4 files.

Gates: make static-check, make lint-eslint and make dry-check pass.
crap-check against the parent passes with coverage (0 violations, 0
warnings). Wide suite: 2776 pass, 0 fail. No import cycles.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
… attempt request

Layer 5 slice 9c. No behavior change. AttemptRequest (streamResult, model,
metadataModel, thinkingLevel, request, stepTracker, the three
didRetry* flags and modelFallback) is now Readonly in
WorkspaceStreamInfo. Only ProviderRequest writes it after the record is
built.

The writes that move behind ProviderRequest:
- The four attempt restarts (AttemptLoop's empty-output retry,
  StreamRetries' previousResponseId and reasoning-replay retries, and
  RefusalFallback's model hop) call ProviderRequest.beginAttempt. It
  sets the request first, then the stream result built from that
  request, the same order the callers used.
- The three step-boundary and empty-output retry flags go through
  ProviderRequest.markRetry.
- RefusalFallback's model swap calls ProviderRequest.adoptModel. The
  thinking level still changes only when the fallback chose one.
- TurnEngine's two thinking-override writes call
  ProviderRequest.setThinkingLevel.

The four methods are static: they only write the record, so no caller
gains a dep. Each call sits where its assignments were, so no ordering
changes. AttemptLoop, RefusalFallback, StreamRetries and TurnEngine now
import ProviderRequest as a value (no cycle).

Scratch mutations on this commit, against the streamManager, turnEngine,
aiService and agentSession suites: 15 of 15 fail a test.

Lines: 86 added and 40 removed in 6 files.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
@ThomasK33
ThomasK33 force-pushed the turn-engine/attempt-request branch from d2a735c to 1595b80 Compare October 25, 2026 20:54
@ThomasK33
ThomasK33 added this pull request to the merge queue Oct 25, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue because a pull request earlier in the stack was removed Oct 25, 2026
@ThomasK33
ThomasK33 added this pull request to the merge queue Oct 25, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue because a pull request earlier in the stack was removed Oct 25, 2026
@ThomasK33
ThomasK33 added this pull request to the merge queue Oct 25, 2026
Merged via the queue into main with commit 19ac496 Oct 25, 2026
34 checks passed
Base automatically changed from turn-engine/turn-slot to main October 25, 2026 22:12
@ThomasK33
ThomasK33 deleted the turn-engine/attempt-request branch October 25, 2026 22:12
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Oct 26, 2026
…state (coder#7487)

Layer 5x of the turn-engine split in stack #7398 (based on coder#7483). Layer
5 slice 9, part (d): make the TurnState record read-only outside
StepApply, so only StepApply writes the parts, step indices, reasoning
state and initial metadata. With this PR each of the six records in
`turnEngine/turnState.ts` has one writer. No behavior change on any path
that builds the record with `createStreamInfo`.

## What changed

### Commit 1: tests first (`68e032442d`)

Test-only commit before layer 5 slice 9d moves the TurnState writes
behind StepApply. Scratch edits that survived the existing tests:
- The full retry reset keeps the old streamStepOrdinals,
  reasoningBackfillStartIndex, currentReasoningBlock or
  terminalFinishReason.
- recordStepStart does not set currentStepStartIndex.
- The refusal fallback does not apply prepare()'s initialMetadataPatch.

Changes:
- streamManager.completion.test.ts, "retry reset discards step indices
together with discarded parts": the fixture now starts with non-default
  values for those fields, and the test checks that a reset without
  preserveParts clears them and sets currentStepStartIndex to 0.
- streamManager.refusalFallback.test.ts, new test "the fallback's
  metadata patch reaches the committed row": a fallback whose patch sets
  systemMessageTokens commits a row with that value.

Scratch mutations on this commit: all six edits now fail a test.

No production code changes.


### Commit 2: enforce the owner (`c4653a4608`)

Layer 5 slice 9d. No behavior change for a well-formed stream record.
TurnState (parts, step and terminal bookkeeping, part timestamps, the
pending tool buffers and initialMetadata) is now Readonly in
WorkspaceStreamInfo. Only StepApply writes it. With this slice, all six
records have one writer each.

StepApply's own writers take StepStream (WorkspaceStreamInfo &
TurnState). The writes that move behind StepApply:
- StreamRetries' retry reset calls StepApply.restartStepNumbering
  before its first await and StepApply.resetForRetry after it, so the
  reset order across that await does not change. recordStepStart moves
  from StreamRetries into StepApply (its only other caller), so
  StreamRetries can import StepApply without a cycle.
- RefusalFallback's three initialMetadata writes and TurnEngine's three
  (the step tracker's system-section hook, the manual thinking override
  and Auto thinking escalation) call StepApply.setInitialMetadata.
- RefusalFallback's reasoning backfill start calls
  StepApply.setReasoningBackfillStart.

The four methods are static: they only write the record, so no caller
gains a dep. RefusalFallback, StreamRetries and TurnEngine now import
StepApply as a value (no cycle).

TurnEvents (StepApply imports it) and StreamManager initialized
pendingNestedCalls and pendingToolExecutionStarts with `??= new Map()`.
Both maps are required fields, and TurnEngine's createStreamInfo builds
them, so the two writes were dead. They now read the maps directly. A
record without the maps, which the type rejects, now throws there.

The parent commit pins six survivors. Scratch mutations on this commit,
against the streamManager, turnEngine, aiService and agentSession
suites: 21 of 21 fail a test.

Lines: 94 added and 50 removed in 8 files.

Gates: make static-check, make lint-eslint and make dry-check pass.
crap-check against the parent passes with coverage (0 violations, 0
warnings). Wide suite: 2777 pass, 0 fail. No import cycles.


## Validation

- The tests in commit 1 pass on the parent `82136d1e8e` and kill the 7
scratch mutants that survived there (step ordinal reset at 2 sites,
backfill reset, reasoning-block reset, finishReason reset,
`currentStepStartIndex` in `recordStepStart`, RefusalFallback's
`initialMetadataPatch`).
- Scratch mutants on the refactor: 21 of 21 fail a test.
- 2352 targeted tests pass here (streamManager*, aiService, turnEngine,
continuousCompactor, turnRequestBuilder, coreServicesRoot,
serviceContainer, errorRecovery, agentSession), and `make typecheck`
passes. The builder's wider run passed 2777 of 2777.
- `make static-check`, `make lint-eslint`, `make dry-check` and the CRAP
check (with coverage, 0 violations) pass with the parent as the base. No
import cycle exists.

## Risks

Low. Field writes in StreamRetries, RefusalFallback and TurnEngine
become calls to four static StepApply writers that make the same
assignments. StreamRetries keeps the order around its `await
partialJournal.resetForRetry`: `restartStepNumbering` before it and
`resetForRetry` after it.

One deliberate change: `TurnEvents` and `streamManager.ts` no longer
lazily create `pendingNestedCalls` and `pendingToolExecutionStarts` with
`??= new Map()`. Both fields are required by the type, and
`createStreamInfo` (`TurnEngine.ts:223-224`) always builds them, so the
fallback never ran. A hand-built record without them now fails at those
reads instead of silently getting a new map. `WorkspaceStreamInfo` is
in-memory only, so no persisted state can lack them.

---

_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking:
`high` • Cost: `$82.48`_

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs=82.48 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant