ide на основе vs code
Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
> Generated by super-planner. Source: roadmap.md (phase 9). > Last updated: 2026-05-13 after live E2E pass.
Status: ✅ done — unit-tested and live E2E verified (see Implementation Notes → Live E2E results).
Implement the runtime-mutation API surface for live Claude sessions: abortSession, setPendingMessages (steering), and changeModel. Add the yield-restart primitive that future phases (and the genuine 'max' effort case) require, and recover gracefully from subprocess crashes so a session is reusable across aborts/errors instead of latching fatally.
In scope:
ClaudeAgent.abortSession(session) — cancel in-flight turn via _abortController.abort(). Mirror node/copilot/copilotAgent.ts routing through _sessionSequencer.ClaudeAgent.setPendingMessages(session, steering, queued) — push a priority: 'now' SDKUserMessage into the existing prompt iterable. queued param: no-op (matches Copilot reference; CONTEXT.md M10 confirms agent boundary always sees empty queued)._processMessages, match echoed type:'user' messages by uuid against an injection-time sdkUuid → pendingMessage.id map. Emit IAgentSteeringConsumedSignal only on echo.ClaudeAgent.changeModel(session, ModelSelection) — bundle-atomic. Provisional sessions mutate provisional.model directly. Materialized sessions fan out to Query.setModel(sdkId) + Query.applyFlagSettings({ effortLevel }) at the next yield boundary. Clamp 'max' → 'xhigh' on the runtime path (M11 effort-clamp).ClaudeAgentSessionOut of scope:
Query.setPermissionMode() exposure on the agent surface — IAgent has no generic live-edit setter today (CONTEXT.md M12). Mid-session permissionMode edits round-trip as a fresh createSession until that protocol grows. The SDK-internal EnterPlanMode/ExitPlanMode driver is wired regardless because it runs entirely SDK-side; this phase does not need to touch it.'max' mid-session via restart-required path — runtime path clamps to 'xhigh' and logs a warning. The yield-restart mechanism we land here makes the upgrade trivial (Phase 14 hardening, or as a follow-up commit within Phase 9 if there's appetite). Marked with // TODO(phase9-max-effort): ... at the clamp site._toolsMatch from production reference) — deferred to Phase 10 (client tools) and Phase 11 (customizations). The yield-restart primitive lands here; the trigger conditions land with their owning phases.Query.interrupt() validation — deferred. Production reference uses _abortController.abort() exclusively; revisit only if abort is observed to orphan subprocesses in dogfood.Query.setMcpServers — Phase 10/11 territory (covered by yield-restart primitive landing here)._sessionSequencer (Phase 6) — the per-session FIFO Phase 9 funnels every mutation through.ClaudeMaterializer.materialize() (Phase 5) — the function the restart path calls.ClaudeSessionMetadataStore.writeModel() (Phase 5) — the persistence path for changeModel.claudeModelConfig.ts::resolveClaudeEffort() — extended here with the runtime clamp.Make ClaudeAgentSession the single mutation barrier: every Phase 9 method on ClaudeAgent queues through _sessionSequencer and calls a session-level mutator. The session owns three pieces of new state — a steering queue (separate from _queuedPrompts so the pending-message id survives), a pending-mutation bundle (model + effort to apply at the next yield), and bijective values (_currentModel/_currentEffort/_currentPermissionMode) that survive Query rebuilds. _abortController and _query become swappable; _fatalError is no longer permanently latched on abort or crash, so the next sendMessage rebuilds the SDK plumbing via ClaudeMaterializer with resume: sessionId. The yield-restart primitive (drain iterable → close Query → re-materialize with resume → re-apply bijective state without re-firing onDidMaterializeSession) lands here as the substrate for genuine 'max' effort, settings/tools changes, and crash recovery — Phase 9 only wires the abort/crash triggers; tool-set and settings triggers land in their owning phases.
ClaudeAgentSession ✓Files: node/claude/claudeAgentSession.ts
Change:
_abortController from readonly to mutable. Convert _query similarly.private _currentModel: string | undefined — last applied SDK model id; re-applied on every fresh Query.private _currentEffort: ClaudeEffortLevel | undefined — last applied effort (post-clamp value, e.g. 'xhigh').private _currentPermissionMode: ClaudePermissionMode — initialized from materialization options; re-applied on restart. Not exposed via Phase 9 public API but tracked for the restart path.private readonly _pendingSteering: ISteeringEntry[] = [] — separate queue from _queuedPrompts. Each entry: { sdkMessage: SDKUserMessage; pendingMessageId: string; sdkUuid: string }.private readonly _steeringInFlight = new Map<string /*sdkUuid*/, string /*pendingMessageId*/>() — populated when the iterable yields a steering entry; consumed when _processMessages sees the echo.private _pendingMutation: { model?: string; effort?: ClaudeEffortLevel } | undefined — coalesced changeModel bundle, applied at the next yield boundary._fatalError permanent-latch from send()'s pre-check. Replace with: if _query is null AND no error pending, this is a fresh-start condition (post-abort or post-crash) — call Depends on: none
Done when: claudeAgentSession.ts compiles; existing tests still pass (no behavior change yet — new fields are unused at the consumer).
---
_createPromptIterable consumes steering and applies pending mutations at the yield boundary ✓Files: node/claude/claudeAgentSession.ts
Change: Inside the next() loop of _createPromptIterable():
1. Apply pending mutation bundle FIRST (before yielding any prompt). If _pendingMutation is set:
_pendingMutation.model && _pendingMutation.model !== _currentModel → await this._query?.setModel(_pendingMutation.model); update _currentModel._pendingMutation.effort && _pendingMutation.effort !== _currentEffort → await this._query?.applyFlagSettings({ effortLevel: _pendingMutation.effort }); update _currentEffort._pendingMutation.2. Drain `_pendingSteering` BEFORE `_queuedPrompts`. When a steering entry yields, copy sdkUuid → pendingMessageId from the entry into _steeringInFlight so the echo detector (Step 3) can match it. 3. Existing _queuedPrompts consumption follows.
The yield boundary is the only mutation barrier (CONTEXT.md M11). Mutations applied here cannot race with mid-turn SDK state.
Depends on: Step 1
Done when: mutator branches compile; new mapper tests in Step 8 covering "mutation applied on yield" pass.
---
Files: node/claude/claudeAgentSession.ts, node/claude/claudePromptResolver.ts (read-only — reuse), node/claude/claudeMapSessionEvents.ts (signal emission only — no mapper change needed)
Change:
injectSteering(steeringMessage: PendingMessage): void on ClaudeAgentSession: 1. Generate a fresh sdkUuid (use crypto.randomUUID() — protocol PendingMessage.id is string, not necessarily a UUID; the SDK's SDKUserMessage.uuid field is typed UUID). 2. Build the SDKUserMessage payload via the same prompt-resolver path sendMessage uses (handle attachments uniformly with regular prompts). 3. Set priority: 'now', parent_tool_use_id: null, session_id: this.sessionId, uuid: sdkUuid. 4. Push { sdkMessage, pendingMessageId: steeringMessage.id, sdkUuid } into _pendingSteering. 5. Resolve _pendingPromptDeferred.complete() to wake the iterable. 6. Do NOT push to _inFlightRequests — steering has no turn boundary, no DeferredPromise to settle, no turnId association.
_processMessages, before the existing tool-result mapper handling, when message.type === 'user': look up message.uuid in _steeringInFlight. If hit, fire _onDidSessionProgress.fire({ kind: 'steering_consumed', session: this.sessionUri, id: <pendingMessageId> }), delete the map entry, and continue (do NOT pass to the regular user-message mapper — steering echoes are not turn artifacts).Why a separate queue, not unshift into `_queuedPrompts`: _queuedPrompts stores raw SDKUserMessage. Steering needs the protocol PendingMessage.id ↔ SDK uuid mapping kept alive until echo. Two of the three council members independently flagged this; collapsing the queues drops the id mapping.
Why match on `uuid`, not content hash: the SDK echoes SDKUserMessage with its uuid preserved (per sdk.d.ts:3067-3083). Content-hash matching is brittle (whitespace, attachment normalization). If integration finds the SDK strips uuids on echo, fall back to content hash — record this as a Risk.
Depends on: Step 1, Step 2
Done when: unit test "steering preempts and emits steering_consumed on echo" (Step 8) passes against FakeQuery extended to echo user messages with the supplied uuid.
---
Files: common/claudeModelConfig.ts
Change: Add an exported helper alongside resolveClaudeEffort:
/**
* Clamp an effort level for the runtime SDK setter.
* `Options.effort` (startup) accepts `'max'`; `Query.applyFlagSettings({ effortLevel })`
* does NOT — its type union excludes `'max'`. Mid-session `'max'` selections silently
* degrade to `'xhigh'` until the restart-required path lands (CONTEXT.md M11).
*/
export function clampEffortForRuntime(effort: ClaudeEffortLevel | undefined): RuntimeEffortLevel | undefined {
if (effort === undefined) { return undefined; }
if (effort === 'max') { return 'xhigh'; }
return effort;
}RuntimeEffortLevel is the narrower union that matches the SDK's applyFlagSettings type.
Depends on: none (parallel with Step 1)
Done when: helper compiles; one-line unit test confirming 'max' → 'xhigh', others passthrough.
---
ClaudeAgentSession + ClaudeMaterializer resume mode ✓Files: node/claude/claudeAgentSession.ts, node/claude/claudeMaterializer.ts
Change:
ClaudeMaterializer:
IClaudeMaterializeProvisional (or add a sibling param) with startMode: { kind: 'fresh' } | { kind: 'resume'; sessionId: string }. Default 'fresh'._buildOptions, branch:'fresh' → set Options.sessionId (existing behavior).'resume' → set Options.resume; do NOT set sessionId.ClaudeAgentSession:
private async _rebindQuery(reason: 'initial' | 'restart' | 'recover'): Promise<void>: 1. If a _query exists, await its abort (controller already fired, but await lets the iterable drain cleanly). 2. If reason === 'recover' or 'restart', async-dispose the old WarmQuery so the subprocess is released. The new WarmQuery comes from re-calling the materializer through a callback the agent provides (see below). 3. Create a fresh _abortController and a fresh _pendingPromptDeferred. 4. Call back into the agent to re-materialize. The agent supplies a _rematerialize: (mode) => Promise<{ warm; query }> closure on session construction so the session doesn't need the materializer service injected directly. 5. Re-apply bijective state: if _currentModel, await _query.setModel(_currentModel); if _currentEffort, await _query.applyFlagSettings({ effortLevel: _currentEffort }); if _currentPermissionMode differs from the materializer default, await _query.setPermissionMode(_currentPermissionMode).
_onDidMaterializeSession.fire() — that event is once-per-provisional-promotion (claudeAgent.ts:211-220). The agent's _rematerialize closure must NOT re-fire it.Depends on: Step 1
Done when: unit test "abort then resend uses resume mode and rebinds Query" passes (Step 8).
---
ClaudeAgent API surface ✓Files: node/claude/claudeAgent.ts
Change: Replace the three TODO stubs (~line 825):
async abortSession(session: URI): Promise<void> {
const sessionId = AgentSession.id(session);
await this._sessionSequencer.queue(sessionId, async () => {
const entry = this._sessions.get(sessionId);
entry?.session.abort();
});
}
setPendingMessages(session: URI, steeringMessage: PendingMessage | undefined, _queuedMessages: readonly PendingMessage[]): void {
const sessionId = AgentSession.id(session);
const entry = this._sessions.get(sessionId);
if (!entry) {
this._logService.warn(`[Claude:${sessionId}] setPendingMessages: session not found`);
return;
}
if (steeringMessage) {
entry.session.injectSteering(steeringMessage);
}
// _queuedMessages: intentional no-op (CONTEXT.md M10 — agent boundary always sees empty queue).
}
async changeModel(session: URI, model: ModelSelection): Promise<void> {
const sessionId = AgentSession.id(session);
await this._sessionSequencer.queue(sessionId, async () => {
const provisional = this._provisionalSessions.get(sessionId);
if (provisional) {
provisional.model = model;
await this._metadataStore.writeModel(session, model);
return;
}
const entry = this._sessions.get(sessionId);
if (entry) {
const sdkId = model.id;
const requestedEffort = resolveClaudeEffort(model);
const runtimeEffort = clampEffortForRuntime(requestedEffort);
if (requestedEffort === 'max') {
this._logService.warn(`[Claude:${sessionId}] changeModel: 'max' effort clamped to 'xhigh' on runtime path. // TODO(phase9-max-effort): wire restart-required path.`);
}
entry.session.queueModelChange(sdkId, runtimeEffort);
}
await this._metadataStore.writeModel(session, model);
});
}ClaudeAgentSession.queueModelChange(sdkId, effort) is a new sync method that sets _pendingMutation and resolves _pendingPromptDeferred so the iterable wakes and applies the bundle (Step 2).
In _createSessionWrapper (where ClaudeAgentSession is constructed), supply the _rematerialize closure (Step 5):
const rematerialize = async (mode: 'restart' | 'recover'): Promise<...> => {
const startMode = { kind: 'resume' as const, sessionId };
return this._materializer.materialize(provisional, this._proxyHandle, permissionMode, canUseTool, startMode);
// This call path does NOT fire onDidMaterializeSession (handled inside ClaudeAgent on initial materialize only).
};Depends on: Steps 1–5
Done when: all three Phase 9 stubs compile and pass the new agent-level tests.
---
Files: node/claude/claudeAgentSession.ts
Change: In _processMessages catch block:
isCancellationError(err) → expected (abort path). Reject in-flight requests with CancellationError, clear queues, null _query. Do NOT set _fatalError. Session is reusable._onDidSessionProgress, reject in-flight requests with the error, null _query, clear _pendingSteering and _steeringInFlight. Do NOT permanently latch _fatalError — the next send() triggers _rebindQuery('recover') (Step 5). If the rebind itself fails (e.g. WarmQuery subprocess dead and re-materialize throws), surface that as the new error on the rebind's deferred — no permanent latch.AgentSideEffects.SessionError already has the existing send-failure code path (agentSideEffects.ts:707-723); turn errors flow through it untouched.
Depends on: Step 5
Done when: unit test "crash mid-stream → next sendMessage rebinds via resume" passes.
---
Files: test/node/claudeAgent.test.ts
Extend `FakeQuery`:
readonly recordedModels: string[] = [];
readonly recordedFlagSettings: Settings[] = [];
async setModel(modelId: string): Promise<void> { this.recordedModels.push(modelId); }
async applyFlagSettings(s: Settings): Promise<void> { this.recordedFlagSettings.push(s); }
// New: support echoing a user message with a supplied uuid back through the event stream.
echoSteering(uuid: string, content: string): void { /* push synthetic SDKUserMessage onto the outbound stream */ }New test suites in `claudeAgent.test.ts`:
1. abort mid-stream rejects with CancellationError — send, abort while FakeQuery is yielding, assert deferred rejects. 2. abort then resend rebinds via resume — abort, send again, assert ClaudeMaterializer.materialize called with startMode: { kind: 'resume', sessionId } and bijective state re-applied (FakeQuery sees setModel if _currentModel set). 3. steering preempts and SDK sees `priority: 'now'` — inject steering during in-flight turn; assert FakeQuery's drained prompts include the steering entry first with priority === 'now'. 4. steering_consumed fires on echo, not on enqueue — inject steering, assert no signal yet; have FakeQuery echo a user message with the steering uuid; assert IAgentSteeringConsumedSignal fires with the matching pendingMessage.id. 5. setPendingMessages with empty steering + non-empty queued is a no-op — assert FakeQuery sees nothing. 6. changeModel on provisional mutates `provisional.model` — assert no FakeQuery interaction; assert metadata write. 7. changeModel on materialized fans out at next yield — send a turn (drains the current prompt), call changeModel, send again; assert recordedModels and recordedFlagSettings populated in the right order. 8. changeModel `'max'` clamps to `'xhigh'` — assert recordedFlagSettings last entry has effortLevel: 'xhigh'; assert warning logged with TODO(phase9-max-effort) substring. 9. changeModel id-only does not call applyFlagSettings — assert recordedFlagSettings
`claudeMapSessionEvents.test.ts`: no new tests — steering echo handling lives in _processMessages (session level), not the mapper. Existing mapper tests must still pass (verify steering type:'user' echoes are filtered out before the mapper).
Smoke (`smoke.md`): add Phase-9 row covering: send long message → abort → confirm UI shows aborted state → send second message → confirm response. Steering: send long message → type a steering message → confirm preemption → confirm steering_consumed UI signal. ChangeModel: switch model mid-conversation → confirm next response uses new model.
Depends on: Steps 1–7
Done when: all new tests green; no regressions in claudeAgent.test.ts, claudeMapSessionEvents.test.ts, claudeAgentSession.test.ts (if present).
| Action | File | Purpose | |---|---|---| | Modify | node/claude/claudeAgent.ts | Implement abortSession, setPendingMessages, changeModel. Wire _rematerialize closure into session construction. | | Modify | node/claude/claudeAgentSession.ts | Mutable _abortController/_query; bijective state; _pendingSteering/_steeringInFlight; _pendingMutation; abort(), injectSteering(), queueModelChange(), _rebindQuery() methods; yield-boundary mutation application; steering-echo detection in _processMessages; crash recovery without permanent latch. | | Modify | node/claude/claudeMaterializer.ts | Accept startMode: 'fresh' \| { kind: 'resume', sessionId }; branch Options.sessionId vs Options.resume. Restart path does not re-fire onDidMaterializeSession. | | Modify | common/claudeModelConfig.ts | Add clampEffortForRuntime() helper + narrow RuntimeEffortLevel
claudeCodeAgent.ts:138, 274, 435, 719). Query.interrupt() exists in 0.2.112 but is untested in the codebase. Revisit only if abort orphans subprocesses in dogfood.AbortController + _rebindQuery() via materializer with resume: sessionId. Mirrors Copilot's copilotAgentSession.ts:800-803 behavior. Replaces the current permanent _fatalError latch.PendingMessage.id ↔ SDK uuid mapping alive until echo. Two of three council members flagged this independently; the third (Opus) acknowledged the simplicity argument was weaker than the id-mapping requirement.uuid field per sdk.d.ts:3067-3083. Content hashing is brittle (whitespace, attachment normalization). Fallback to content hash is a documented Risk if echo testing reveals the SDK strips uuids.agentSideEffects.ts:888 confirm queued messages are consumed server-side; the agent boundary always receives an empty queue. Match Copilot (copilotAgent.ts:1050-1052).WarmQuery subprocess survives _abortController.abort() and that _warm.query() can be called again. If the SDK tears down the subprocess on abort, abort recovery requires full re-materialize through ClaudeMaterializer (new proxy auth, new Options bag, new subprocess). Mitigation: try the cheap rebind in _rebindQuery('recover') first; on failure, escalate to full materialize. Validate against real SDK in the live E2E.type:'user' messages don't carry the host-supplied uuid, steering_consumed never fires. Mitigation: write a focused integration test that echoes a priority:'now' message and asserts the uuid round-trips. Fallback: content-hash matching with a one-time captured normalization rule.claudeAgent.ts:211-220). The _rematerialize closure must avoid the event-firing branch; if it doesn't, downstream listeners (workbench session list) corrupt. Mitigation: route the closure through a private _materializeWithoutNotification path on ClaudeAgent that takes the materializer call but skips the event dispatch._rebindQuery applies model AFTER the new query starts processing the resumed transcript, the first turn may render under the old model. Mitigation: re-apply BEFORE the prompt iterable yields its first prompt (the iterable's mutation barrier is the right point — Step 2 already runs mutations before yielding).scripts/test.sh --grep "claudeAgent|claudeAgentSession|claudeMaterializer|claudeModelConfig"Or use the unit-tests skill. Specific suites:
test/node/claudeAgent.test.ts — 12 new tests (Step 8) green.test/node/claudeMapSessionEvents.test.ts — no regressions; steering echoes filtered before mapper.test/node/claudeMaterializer.test.ts — extend with startMode: 'resume' Options assertion.Type-check:
npm run typecheck-client
npm run valid-layers-checkUse the `launch` skill (personal, ~/.agents/skills/launch/) and the `code-oss-logs` skill (.github/skills/code-oss-logs/).
Scenario A — abort + resend: 1. Launch Code OSS dev with a writable workspace. 2. Open a Claude session and send a long prompt ("write a 500-line essay on..."). 3. While streaming, click Abort. 4. Confirm UI surfaces aborted state. 5. Send a short follow-up; confirm response streams normally. 6. Verify in agent-host log: one abortSession entry + one materialize call with startMode.kind === 'resume'.
Scenario B — steering: 1. Same setup. Send a long prompt. 2. While streaming, send a steering message ("actually, switch topic to X"). 3. Confirm preemption (the original turn aborts, new direction streams). 4. Verify in log: a priority:'now' SDKUserMessage was sent and a steering_consumed signal fired with the steering message id.
Scenario C — changeModel hot-swap: 1. Send a turn with model A. Confirm response. 2. Switch model to B (different SDK id) via the model picker. 3. Send another turn. Confirm response uses model B (verifiable via response style or, more reliably, log inspection). 4. Verify in log: Query.setModel called with B's SDK id; no materialize re-call.
Scenario D — `'max'` clamp warning: 1. Send a turn at xhigh effort. 2. Switch to 'max' effort mid-session. 3. Verify in log: warning containing TODO(phase9-max-effort) substring; subsequent applyFlagSettings call has effortLevel: 'xhigh'.
If verify-claude-logs.sh exists by Phase 9 time, add a --phase=9 assertion block; otherwise the code-oss-logs skill covers the assertion pattern.
If E2E tooling unavailable, use scripts/code.sh and exercise scenarios A–D from a real workbench session.
None at plan-acceptance time. All six original open questions resolved during council synthesis (see Decisions §D1–D11).
./roadmap.md (Phase 9)./CONTEXT.md (M10 steering, M11 mutation taxonomy + effort clamp, M12 sessionMutable schema)./phase8-plan.md (most recent precedent for plan structure, FakeQuery test pattern)extensions/copilot/src/extension/chatSessions/claude/node/claudeCodeAgent.ts (abort: 138, 274, 435, 719; restart: 451-460, 520-548, 676, 733-740; resume vs sessionId: 461)node/copilot/copilotAgent.ts:1036-1050 (setPendingMessages), :1242-1254 (changeModel); copilotAgentSession.ts:800-803 (abort reusability), :816-820 (setModel)node_modules/@anthropic-ai/claude-agent-sdk/sdk.d.ts (Query.setModel, Query.applyFlagSettings, Query.setPermissionMode, Query.interrupt; SDKUserMessage.priority/uuid; Settings.effortLevel)launch (workspace .agents/skills/launch/), code-oss-logs (repo)Verified end of implementation: 84 ClaudeAgent tests + 7 claudeModelConfig tests + 23 ClaudeMapSessionEvents tests + 8 ClaudeToolDisplay tests + 24 fileEditTracker/sessionDiffAggregator tests all green; 146 across the agentHost test set; npx tsgo --noEmit -p src/tsconfig.json reports 0 errors; npm run valid-layers-check clean.
ClaudeRuntimeEffortLevel type alias and clampEffortForRuntime() helper (single seam mapping startup-only 'max' onto the runtime SDK setter's narrower union)._abortController and _warm to mutable fields; added _currentModel / _currentEffort / _currentPermissionMode bijective cache; _pendingSteering queue + _steeringInFlight echo-match map; _pendingMutation coalesced bundle; _rematerializer callback hook; _consumerLoopRunning flag with _ensureConsumerLoop() helper; new public methods abort(), injectSteering(), queueModelChange(), attachRematerializer(), seedBijectiveState(); new private _rebindQuery(); rewired _createPromptIterable() to drain mutations → steering → prompts in that order at every yield; added steering-echo detection in sendMessage's sequencer task awaits the in-flight turn deferred, so an abortSession queued behind it could never run — the deadlock self-perpetuates because abort is the only thing that *would* settle that deferred. Fix: abort runs as a control-plane operation (no sequencer), calls entry.session.abort() directly, which rejects the in-flight deferred and frees the sequencer. Caught and corrected during the test pass; the test "abortSession on a materialized session cancels the in-flight turn and leaves the session reusable" was timing out at 5s before this change.'phase-stub graduation' test (which already calls both abortSession and changeModel on claude:/unknown); (b) the planned "setPendingMessages with empty steering and non-empty queued is a no-op" test landed but doesn't need its own count entry separate from the steering preempt test — it's still present as a discrete test, just sharing the materialize() helper. Net effect: same surface area, slightly fewer top-level test names. The 10 tests cover all 12 planned behaviors._rebindQuery design started the consumer loop inside _rebindQuery itself. Implementation found this races re-apply: the consumer loop drained the (test-staged) [system_init, result] while await this._query.setModel(...)_currentModel/_currentEffort/_currentPermissionMode belong on ClaudeAgentSession because the rebind path needs them on the *new* Query immediately, before send() returns. Putting them on ClaudeAgent would have required a callback to read them — a layering smell when the session already owns its own runtime mutation surface.abort() (without yielding) MUST NOT leave a dangling echo-watch entry. Tying the map population to the yield event keeps the lifecycle paired with the SDK's view.materialize() path constructs a ClaudeAgentSession (and opens a DB ref) — things that don't make sense for a rebind, where those resources are already live on the recovering session. Splitting into two methods makes the contract explicit (resume returns just { warm, abortController }, not a session) and avoids a if (startMode === 'resume') throw mid-method that the type system can't enforce._abortController_query_fatalErrorsendMessageClaudeMaterializer learns a fresh-vs-resume start mode: initial sessions pass sessionId, restarts pass resume: sessionId. Restart path does NOT re-fire onDidMaterializeSession.ClaudeAgentSession (_currentModel, _currentEffort, _currentPermissionMode); re-applied on every fresh Query (initial start, yield-restart, post-abort/crash restart).CancellationError (clean abort) from other thrown errors. For both, clear the dead Query state, fire a turn-error signal, and let the next sendMessage rebuild via ClaudeMaterializer with resume.'max' clamp helper in claudeModelConfig.ts (single source of truth).claudeAgent.test.ts: extend FakeQuery to record setModel / applyFlagSettings and to model echoed steering messages; add coverage for abort, abort-then-resend, steering preemption, steering_consumed timing, changeModel hot-swap, 'max' clamp, id-only changeModel, provisional changeModel, crash-then-resend.smoke.md with Phase 9 row._rebindQuery()abort(): void — calls this._abortController.abort(), rejects every pending in-flight DeferredPromise with CancellationError, clears _pendingSteering and _steeringInFlight, and nulls _query. Does NOT dispose the session.send()setModelapplyFlagSettingstest/node/claudeAgent.test.tsFakeQueryechoSteeringnode/claude/smoke.md'max' reasoning tier (no upstream model routes it), so the SDK runtime hot-swap union excludes 'max'. Mid-session selections degrade to 'xhigh' here; if CAPI later adds a 'max' model the SDK union widens and the clamp becomes a passthrough._rebindQuery. changeModel separately persists ModelSelection to claudeSessionMetadataStore so reload/restart restoration works (Phase 13). Effort/permissionMode persistence in metadata: not needed in Phase 9 (no restoration scenario yet); add when Phase 13 lands transcript reconstruction if useful.claudeAgent.ts:211-220). The _rematerialize closure the agent supplies bypasses the event-firing branch in ClaudeAgent._toolsMatch) and settings-file change watchers are the responsibility of Phases 10/11. The materializer-resume capability and _rebindQuery are reusable.createSession. The SDK-internal EnterPlanMode/ExitPlanMode driver runs entirely SDK-side and needs no host wiring.'max' mid-session get 'xhigh' until the restart-required path lands. Mitigation: log warning with TODO(phase9-max-effort) substring; smoke note in smoke.md so QA notices.changeModel mutates provisional.model, but sendMessage reads provisional.model to build initial Options. Both go through _sessionSequencer, so the FIFO ordering covers this; the risk is anyone bypassing the sequencer. Mitigation: assert sequencer routing in unit test 6 (provisional changeModel)._processMessages_fatalError_needsRebindClaudeStartMode = 'fresh' | 'resume' plus a fifth startMode parameter on materialize() (defaulting to 'fresh'); added a sibling materializeResume() that returns { warm, abortController } for _rebindQuery (no DB ref, no session construction — those resources stay live on the recovering session); routed Options.sessionId vs Options.resume accordingly.IClaudeProvisionalSession.model mutable so changeModel can update a provisional pending model bag; in _materializeProvisional seeded the session's bijective cache + attached the _rematerializer closure that calls materializeResume with the live permission mode; replaced the three TODO: Phase 9 stubs with abortSession (control-plane, no sequencer — see deviation D1 below), setPendingMessages (steering forwarding; queued no-op per D5), and changeModel (provisional mutation OR queueModelChange bundle, with 'max' clamp warning).'stubbed methods throw with the right phase number' test with a Phase-9 graduation test asserting unknown-URI no-throw semantics; extended FakeQuery with recordedModels / recordedFlagSettings arrays and made setModel / applyFlagSettings record-and-resolve; added a 'ClaudeAgent (Phase 9 — runtime mutation surface)' suite covering 10 of the 12 planned tests (see deviation D2).'clampEffortForRuntime' suite (one snapshot test covering all six input cases).'max' clamp warning) plus the simulated subprocess crash.this._queryawait this._query?.setModel(...)const newQuery = this._querysend()_ensureConsumerLoop()_rebindQuerysend()'xhigh' and logs TODO(phase9-max-effort). The yield-restart primitive is in place, so the upgrade is mechanical when needed._rebindQuery + materializeResume) ships in this phase, but the trigger conditions belong to Phases 10/11. No new code added here for those triggers.claudeAgent.ts, claudeAgentSession.ts, claudeMaterializer.ts, claudeModelConfig.ts) found no private-method extractions worth a refactor: _rebindQuery, _applyPendingMutation, _wireAbortHandler, _ensureConsumerLoop all access mutable instance state (_query, _warm, _abortController, _pendingMutation, _currentModel/Effort/PermissionMode, _consumerLoopRunning); extracting them as standalone functions would require threading 6+ arguments and re-exposing the bijective cache. Recorded as avoid-private-methods: clean for this phase.smoke.md exercised against a running Code OSS dev build with a live Claude proxy: abort + resend (Scenario A), steering preemption + steering_consumed echo (Scenario B), changeModel hot-swap mid-conversation (Scenario C), and the 'max' → 'xhigh' clamp warning (Scenario D). No regressions observed; the unit-test posture matched live behavior. Phase 9 is production-ready.