Add orchestration v2 docs and probe fixtures

- Document the target orchestration graph, IDs, lifecycles, and capability model
- Add Codex app-server probe fixtures and update the probe test harness
This commit is contained in:
Julius Marminge committed 2026-04-20 14:26:09 -07:00
1 parent d138a0bc31
commit 355eb2dade
17 files changed
+4331 -39

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
# Orchestration V2
This document set describes the target architecture for the next orchestration model. It is not a patch plan for the current implementation and it intentionally ignores migration/backward compatibility. Those concerns should be handled after the target model is coherent.
V2 is designed around the real provider behavior observed in the Codex app-server probes, but it is not Codex-specific. Codex is treated as the richest protocol we currently have; weaker providers are adapted into the same model with app-owned ids and explicit capability flags.
## Documents
- [Core Graph And Data Model](./core-graph-and-data-model.md)
- [Entity IDs And Correlation](./entity-ids-and-correlation.md)
- [Feature Lifecycles](./feature-lifecycles.md)
- [Provider Switching And Context Handoff](./provider-switching-and-context.md)
- [Provider Capability System](./provider-capability-system.md)
- [Testing Strategy](./testing-strategy.md)
## Primary Goals
- Preserve provider-native lifecycle fidelity without leaking provider ids into app identity.
- Model root turns, subagents, tools, approvals, plans, and checkpoints as one execution graph.
- Make root-run completion the only event that completes a user-visible turn.
- Support forking from normal threads and completed subagent/provider threads.
- Support changing providers between runs as a first-class context handoff.
- Support providers with weak or missing ids through deterministic app-owned id allocation.
- Make feature behavior capability-driven, not provider-name-driven.
## Key Invariants
1. App ids are primary. Provider ids are refs.
2. Provider events are never rewritten to look like another provider event.
3. Child execution completion never closes the parent run.
4. Checkpoints attach to checkpointable execution scopes. Root-run checkpoints advance app run history; child/subagent checkpoints are nested and do not advance the parent run count.
5. Rollback is expressed in app run count and reconciled with provider conversation state.
6. Every command targets app ids; adapters translate to provider refs at the edge.
7. Missing provider capability is represented explicitly and handled by policy.
8. Provider switches create explicit context handoff artifacts; they are not hidden prompt hacks.
9. Tests should prefer replay-backed integration coverage over mocked unit tests. The only normal substitute in orchestration tests is the provider runtime transport.
## Conceptual Layers
```text
Native provider protocol
-> Raw event log
-> Provider adapter / normalizer
-> Runtime execution graph
-> Conversation projection
-> UI / API views
```
The raw event log stores what happened. The runtime graph stores what it means. The conversation projection stores what users see.
## Minimal Mental Model
```text
AppThread
Run 1
root ExecutionNode
tool ExecutionNode
approval ExecutionNode
subagent ExecutionNode
ProviderThread
child root ExecutionNode
Run 2
root ExecutionNode
```
An app thread is the user-visible conversation. A run is the counted user-visible turn. Execution nodes are the tree of work inside the run. Provider threads are provider-native conversation handles that can be attached to app threads or nested execution nodes.
Provider switches do not create new app threads. They create or reactivate provider threads and attach context handoff summaries to the next run.
## Probe-Derived Requirements
The Codex app-server probes showed several protocol realities that the V2 model must preserve:
- `thread/status/changed` can become idle before or around completion, but `turn/completed` is the authoritative turn terminal event.
- `turn/interrupt` completes as a request first; the interrupted terminal state arrives later through `turn/completed`.
- Approval requests are provider-initiated JSON-RPC requests scoped to provider thread, turn, and item.
- `thread/rollback` returns an authoritative provider thread snapshot after rollback.
- Subagent child `turn/completed` events can occur before the parent/root turn completes.
- Child provider turns are real provider turns and must not be remapped onto the parent provider turn id.
These observations are why V2 separates app runs, provider turns, and execution nodes.
@@ -0,0 +1,543 @@
# Core Graph And Data Model
## Overview
V2 models orchestration as a graph with a small number of durable entity types:
```text
Project
AppThread
Run
ExecutionNode tree
ProviderThread handles
Context handoffs
Checkpoints
```
The central separation is:
- `AppThread`: the user-visible conversation in T3 Code.
- `Run`: a counted user-visible turn on an app thread.
- `ExecutionNode`: a unit of provider/runtime work inside a run.
- `ProviderThread`: a provider-native conversation handle.
- `ProviderSession`: a live or resumable provider process/runtime.
- `ContextHandoff`: a provider-switch summary that bridges runs into another provider thread.
Provider-specific lifecycle is preserved in provider refs and raw events. App behavior is driven by app-owned ids and graph relationships.
## Entity Summary
```text
AppThread
id: ThreadId
projectId: ProjectId
title
providerBinding
activeProviderThreadId?
forkSource?
status projection
Run
id: RunId
threadId: ThreadId
ordinal: number
status
rootNodeId
attempts[]
providerThreadId
contextHandoffId?
userMessageId
checkpoint?
ExecutionNode
id: NodeId
threadId: ThreadId
runId: RunId | null
parentNodeId: NodeId | null
rootNodeId: NodeId
kind
status
providerThreadId?
providerTurnId?
itemId?
countsForRun
checkpointScopeId?
CheckpointScope
id: CheckpointScopeId
threadId
runId?
nodeId
parentScopeId?
kind
advancesAppRunCount
ProviderSession
id: ProviderSessionId
provider
status
cwd
capabilities
ProviderThread
id: ProviderThreadId
providerSessionId?
appThreadId?
nativeThreadRef?
coveredRunRange?
contextHandoffIds[]
forkSource?
ContextHandoff
id: ContextHandoffId
threadId
fromProviderThreadIds[]
toProviderThreadId
coveredRunRange
strategy
summaryMessageId?
ProviderTurn
id: ProviderTurnId
providerThreadId
nativeTurnRef?
nodeId
runAttemptId?
status
RuntimeItem
id: RuntimeItemId
nodeId
providerItemRef?
kind
status
RuntimeRequest
id: RuntimeRequestId
nodeId
providerRequestRef?
kind
status
```
## AppThread
An `AppThread` is the stable user-facing conversation. It owns messages, runs, checkpoints, and UI state. It does not have to map one-to-one with a provider-native thread forever.
```ts
type AppThread = {
id: ThreadId;
projectId: ProjectId;
title: string;
defaultProvider: ProviderKind;
modelSelection: ModelSelection;
runtimeMode: RuntimeMode;
interactionMode: InteractionMode;
branch: string | null;
worktreePath: string | null;
activeProviderThreadId: ProviderThreadId | null;
forkedFrom: ForkSource | null;
createdAt: string;
updatedAt: string;
archivedAt: string | null;
deletedAt: string | null;
};
```
`activeProviderThreadId` points to the provider-native conversation currently backing the app thread. Forking, provider migration, or recovery may create new provider threads while preserving the same app thread, depending on the operation.
`defaultProvider` is only the currently selected default for future runs. Historical runs retain their own provider and provider thread bindings.
## Run
A `Run` is the counted user-visible turn. This replaces using provider turn ids as the app-level lifecycle boundary.
```ts
type Run = {
id: RunId;
threadId: ThreadId;
ordinal: number;
provider: ProviderKind;
providerThreadId: ProviderThreadId | null;
userMessageId: MessageId;
rootNodeId: NodeId | null;
activeAttemptId: RunAttemptId | null;
status:
| "queued"
| "starting"
| "running"
| "waiting"
| "completed"
| "interrupted"
| "failed"
| "cancelled"
| "rolled_back";
requestedAt: string;
startedAt: string | null;
completedAt: string | null;
checkpointId: CheckpointId | null;
contextHandoffId: ContextHandoffId | null;
sourcePlanRef?: {
threadId: ThreadId;
planId: ProposedPlanId;
};
};
```
Only a run with `countsForConversation = true` contributes to the user-visible turn count and checkpoint count.
`providerThreadId` is the provider-native conversation used for this run. This makes mixed-provider app threads explicit: run 1 may be Codex, run 2 may be Claude, and run 3 may return to the original Codex provider thread.
## RunAttempt
A `RunAttempt` represents one provider execution attempt for an app run. Most runs have exactly one attempt. Steering, retries, provider recovery, or provider-switch recovery may create more than one attempt.
```ts
type RunAttempt = {
id: RunAttemptId;
runId: RunId;
attemptOrdinal: number;
rootNodeId: NodeId;
provider: ProviderKind;
providerThreadId: ProviderThreadId;
providerTurnId: ProviderTurnId | null;
reason: "initial" | "steering_restart" | "retry" | "provider_recovery";
status:
| "pending"
| "running"
| "completed"
| "interrupted"
| "failed"
| "cancelled"
| "superseded";
startedAt: string | null;
completedAt: string | null;
};
```
Run attempts let app-level steering work even for providers that cannot steer an active native turn. The app can interrupt the active provider turn and create a replacement attempt under the same `RunId`.
Only one attempt is the final selected attempt for run completion and checkpointing. Superseded/interrupted attempts remain in the execution graph for audit/debugging.
## ExecutionNode
An `ExecutionNode` is the generic unit of runtime work. It is the bridge between provider events and app behavior.
```ts
type ExecutionNode = {
id: NodeId;
threadId: ThreadId;
runId: RunId | null;
parentNodeId: NodeId | null;
rootNodeId: NodeId;
kind:
| "root_turn"
| "assistant_message"
| "reasoning"
| "plan"
| "todo_list"
| "tool_call"
| "approval_request"
| "user_input_request"
| "subagent"
| "hook"
| "system";
status:
| "pending"
| "running"
| "waiting"
| "completed"
| "interrupted"
| "failed"
| "cancelled"
| "rolled_back";
countsForRun: boolean;
providerThreadId: ProviderThreadId | null;
providerTurnId: ProviderTurnId | null;
runtimeItemId: RuntimeItemId | null;
runtimeRequestId: RuntimeRequestId | null;
checkpointScopeId: CheckpointScopeId | null;
startedAt: string | null;
completedAt: string | null;
};
```
The root node of a run is the only node allowed to complete the run. Subagent nodes, tool nodes, approval nodes, and plan nodes may complete independently.
## CheckpointScope
A `CheckpointScope` describes a unit of filesystem state that can be checkpointed. Root runs and child execution nodes can both have checkpoint scopes.
```ts
type CheckpointScope = {
id: CheckpointScopeId;
threadId: ThreadId;
runId: RunId | null;
nodeId: NodeId;
parentScopeId: CheckpointScopeId | null;
providerThreadId: ProviderThreadId | null;
kind: "root_run" | "subagent" | "tool" | "provider_thread" | "manual";
ordinalWithinParent: number;
advancesAppRunCount: boolean;
cwd: string;
createdAt: string;
};
```
Root run scopes have `advancesAppRunCount = true`. Child scopes, such as subagents, have `advancesAppRunCount = false` and are nested under the parent run's scope.
## ProviderSession
A `ProviderSession` is a live provider runtime process/session, such as a Codex app-server process or a Claude SDK session.
```ts
type ProviderSession = {
id: ProviderSessionId;
provider: ProviderKind;
status: "starting" | "ready" | "running" | "waiting" | "stopped" | "error";
cwd: string;
model: string | null;
capabilities: ProviderCapabilities;
createdAt: string;
updatedAt: string;
lastError: string | null;
};
```
A provider session may host one or more provider threads if the provider supports it. If a provider only supports one active conversation per process, V2 still models that as one provider thread attached to the session.
## ProviderThread
A `ProviderThread` is a provider-native conversation handle. It is addressable even when it is nested under a subagent execution node.
```ts
type ProviderThread = {
id: ProviderThreadId;
provider: ProviderKind;
providerSessionId: ProviderSessionId | null;
appThreadId: ThreadId | null;
ownerNodeId: NodeId | null;
nativeThreadRef: string | null;
status: "not_loaded" | "idle" | "active" | "archived" | "closed" | "error";
firstRunOrdinal: number | null;
lastRunOrdinal: number | null;
handoffIds: ContextHandoffId[];
forkedFrom: ProviderThreadForkSource | null;
createdAt: string;
updatedAt: string;
};
```
`appThreadId` is set when the provider thread backs a first-class app thread. `ownerNodeId` is set when the provider thread is nested under an execution node, such as a subagent. A provider thread can later be forked or promoted into a first-class app thread.
A provider thread may have gaps in its native run coverage. Example: runs 1-5 use Codex provider thread A, runs 6-8 use Claude provider thread B, and run 9 returns to Codex thread A with a handoff summary covering runs 6-8. In that case, Codex thread A remains the same provider thread, but it has an explicit `ContextHandoff` before run 9.
## ContextHandoff
A `ContextHandoff` is a first-class artifact created when provider context must be bridged. It is most common when changing providers between runs, but it also applies when provider resume fails and a replacement provider thread must be seeded from app history.
```ts
type ContextHandoff = {
id: ContextHandoffId;
threadId: ThreadId;
targetRunId: RunId;
fromProviderThreadIds: ProviderThreadId[];
toProviderThreadId: ProviderThreadId;
coveredRunOrdinals: {
from: number;
to: number;
};
strategy:
| "delta_since_target_last_seen"
| "full_thread_summary"
| "checkpoint_summary"
| "manual_context";
status: "pending" | "ready" | "failed" | "superseded";
summaryMessageId: MessageId | null;
summaryText: string;
createdByProvider: ProviderKind | null;
createdAt: string;
updatedAt: string;
};
```
The handoff is not just prompt text. It is part of the graph and can be inspected, regenerated, superseded, or audited.
The preferred return-to-provider strategy is `delta_since_target_last_seen`: resume the previous provider thread and summarize only the runs that happened while that provider was inactive. Use `full_thread_summary` when resume fails, provider settings are incompatible, or the accumulated handoffs would create poor context quality.
## ProviderTurn
A `ProviderTurn` is the normalized handle for a provider-native turn.
```ts
type ProviderTurn = {
id: ProviderTurnId;
providerThreadId: ProviderThreadId;
nodeId: NodeId;
runAttemptId: RunAttemptId | null;
nativeTurnRef: string | null;
ordinal: number;
status: "pending" | "running" | "completed" | "interrupted" | "failed" | "cancelled";
startedAt: string | null;
completedAt: string | null;
};
```
Codex has strong native turn ids. Weaker providers may only have ordinals. Both map into `ProviderTurnId`.
## RuntimeItem
Items are provider-visible work units inside a turn or node.
```ts
type RuntimeItem = {
id: RuntimeItemId;
nodeId: NodeId;
providerTurnId: ProviderTurnId | null;
nativeItemRef: string | null;
ordinal: number;
kind:
| "assistant_message"
| "reasoning"
| "plan"
| "todo_list"
| "command_execution"
| "file_change"
| "mcp_tool_call"
| "dynamic_tool_call"
| "collab_agent_tool_call"
| "web_search"
| "unknown";
status: "pending" | "running" | "completed" | "failed" | "cancelled";
title: string | null;
detail: string | null;
};
```
The item id is app-owned. Provider-native item ids are refs.
## RuntimeRequest
Requests represent provider-originated callbacks that require app/user response.
```ts
type RuntimeRequest = {
id: RuntimeRequestId;
nodeId: NodeId;
providerTurnId: ProviderTurnId | null;
runtimeItemId: RuntimeItemId | null;
nativeRequestRef: string | null;
kind:
| "command_approval"
| "file_read_approval"
| "file_change_approval"
| "dynamic_tool_call"
| "user_input"
| "auth_refresh";
status: "pending" | "resolved" | "expired" | "cancelled";
responseCapability:
| { type: "live"; providerSessionId: ProviderSessionId }
| { type: "not_resumable"; reason: string };
createdAt: string;
resolvedAt: string | null;
};
```
Requests may remain visible after restart, but they are only respondable if their `responseCapability` is live.
## Messages
Messages are part of the conversation projection, not the raw provider graph. They link back to runs and nodes when possible.
```ts
type ConversationMessage = {
id: MessageId;
threadId: ThreadId;
runId: RunId | null;
nodeId: NodeId | null;
role: "user" | "assistant" | "system";
text: string;
attachments: Attachment[];
streaming: boolean;
createdAt: string;
updatedAt: string;
};
```
Provider message chunks are collected through items/content events and projected into messages. The projection may hide child/subagent messages by default while preserving them in the graph.
## Plans, Questions, And Todo Lists
V2 treats these as structured runtime items or nodes.
```ts
type PlanArtifact = {
id: PlanId;
threadId: ThreadId;
runId: RunId | null;
nodeId: NodeId;
kind: "proposed_plan" | "todo_list" | "questions";
status: "draft" | "active" | "completed" | "superseded";
markdown?: string;
steps?: Array<{ id: string; text: string; status: "pending" | "running" | "completed" }>;
questions?: UserInputQuestion[];
};
```
Codex `turn/plan/updated` maps to a `todo_list` artifact. Plan-mode final plan items map to `proposed_plan`. User-input question requests map to `questions` plus a `RuntimeRequest`.
## Checkpoint
Checkpoints attach to checkpoint scopes. A root run checkpoint is the user-visible conversation checkpoint. A child checkpoint records nested filesystem state for a subagent, tool, or provider thread without advancing the parent run count.
```ts
type Checkpoint = {
id: CheckpointId;
threadId: ThreadId;
scopeId: CheckpointScopeId;
runId: RunId | null;
nodeId: NodeId;
parentCheckpointId: CheckpointId | null;
ordinalWithinScope: number;
appRunOrdinal: number | null;
ref: string;
status: "ready" | "missing" | "error";
files: CheckpointFileSummary[];
capturedAt: string;
};
```
A child/subagent provider turn can create a child checkpoint. It does not create an app-run checkpoint unless it is running as a first-class app run in a forked/promoted thread.
## Raw Event Log
The raw event log is append-only evidence.
```ts
type RawProviderEvent = {
id: RawEventId;
provider: ProviderKind;
providerSessionId: ProviderSessionId;
sequence: number;
direction: "incoming" | "outgoing";
messageKind: "request" | "response" | "notification" | "error";
method: string | null;
jsonRpcId: string | number | null;
payload: unknown;
observedAt: string;
};
```
No domain behavior should depend on parsing historic UI events if raw provider events are available.
## Projections
V2 should expose separate projections:
- Thread shell: fast sidebar list.
- Thread detail: messages, runs, activities, checkpoints, plans.
- Execution graph: debug/developer view of nodes and provider refs.
- Provider sessions: live runtime/process state.
- Pending requests: actionable approvals/user input.
The UI can remain simple while the graph remains precise.
@@ -0,0 +1,233 @@
# Entity IDs And Correlation
## Principle
Provider ids are evidence. App ids are identity.
Every durable entity uses an app-owned id as its primary key. Provider-native ids are stored as optional refs and used only for correlation, debugging, replay, and command routing.
## ID Families
```text
ThreadId app-visible conversation thread
RunId counted app turn
NodeId execution graph node
ProviderSessionId live/resumable provider runtime session
ProviderThreadId app handle for provider-native conversation
ProviderTurnId app handle for provider-native turn
RuntimeItemId app handle for provider item/tool/message artifact
RuntimeRequestId app handle for provider callback/request
RawEventId raw provider event log id
CheckpointId app checkpoint id
PlanId app plan/todo/question artifact id
```
Provider ids never replace these ids.
## Provider Refs
Provider refs are metadata on runtime entities and events.
```ts
type ProviderRefs = {
provider: ProviderKind;
nativeSessionRef?: string;
nativeThreadRef?: string;
nativeTurnRef?: string;
nativeItemRef?: string;
nativeRequestRef?: string;
rawEventId?: RawEventId;
method?: string;
};
```
Codex can populate most of these fields. Other providers may populate only a subset.
## Correlation Scope
Correlation is always scoped. Never match a native id globally without a provider/session/thread scope.
Preferred matching keys:
```text
ProviderThread:
provider + providerSessionId + nativeThreadRef
ProviderTurn:
providerThreadId + nativeTurnRef
or providerThreadId + turnOrdinal
RuntimeItem:
providerTurnId + nativeItemRef
or providerTurnId + itemOrdinal
RuntimeRequest:
providerSessionId + nativeRequestRef
or providerTurnId + requestOrdinal
```
If a provider recycles ids, the provider adapter must widen the scope until the mapping is unambiguous.
## Mapping Store
V2 needs a durable correlation table or equivalent event-sourced binding stream.
```ts
type IdentityBinding = {
id: IdentityBindingId;
appEntityKind: "provider_thread" | "provider_turn" | "node" | "item" | "request" | "message";
appEntityId: string;
provider: ProviderKind;
providerSessionId: ProviderSessionId;
nativeKind: string | null;
nativeRef: string | null;
scope: {
threadId: ThreadId | null;
runId: RunId | null;
parentNodeId: NodeId | null;
providerThreadId: ProviderThreadId | null;
providerTurnId: ProviderTurnId | null;
};
correlation: "native_exact" | "native_scoped" | "ordinal" | "fingerprint" | "synthetic";
firstRawEventId: RawEventId;
lastRawEventId: RawEventId;
createdAt: string;
updatedAt: string;
};
```
This is not meant to be a large identity subsystem. It is the minimal durable place that says, "this native thing corresponds to this app thing."
## ID Allocation Rules
1. If the provider gives a stable native id, reuse the existing binding or allocate a new app id and bind it.
2. If the provider gives no stable id, allocate by scoped ordinal.
3. If ordinals are insufficient, add a fingerprint inside the scope.
4. Once allocated, never change the app id for that entity.
5. Never infer parent/root completion by string matching ids.
## Scoped Ordinals
Weak providers need deterministic ordinals.
```text
runOrdinalWithinThread
providerTurnOrdinalWithinProviderThread
nodeOrdinalWithinParent
itemOrdinalWithinProviderTurn
requestOrdinalWithinProviderTurn
messageOrdinalWithinNode
```
Ordinals are assigned by the normalizer when events are processed. They must be replay-deterministic for a given raw event log.
## Fingerprints
Fingerprints are only fallback correlation tools. They should include scope and stable structure, not large mutable text.
Examples:
```text
ProviderTurn fingerprint:
providerThreadId + runId + providerTurnOrdinalWithinProviderThread
RuntimeItem fingerprint:
providerTurnId + itemKind + itemOrdinalWithinProviderTurn + toolName?
RuntimeRequest fingerprint:
providerTurnId + requestKind + itemId? + requestOrdinalWithinProviderTurn
```
Do not use complete assistant text as a primary fingerprint. Text is mutable, can stream in chunks, and can be duplicated.
## Runtime Events
Normalized runtime events should carry both app ids and provider refs.
```ts
type RuntimeEvent = {
id: RuntimeEventId;
type: RuntimeEventType;
threadId: ThreadId;
runId: RunId | null;
nodeId: NodeId | null;
parentNodeId: NodeId | null;
providerSessionId: ProviderSessionId | null;
providerThreadId: ProviderThreadId | null;
providerTurnId: ProviderTurnId | null;
itemId: RuntimeItemId | null;
requestId: RuntimeRequestId | null;
providerRefs: ProviderRefs;
payload: unknown;
createdAt: string;
};
```
Downstream systems should use app ids. Provider refs are preserved for inspection and adapter routing.
## Command Routing
UI and orchestration commands target app ids.
```text
approval.respond(RuntimeRequestId)
interrupt.run(RunId)
interrupt.node(NodeId)
fork.fromNode(NodeId)
rollback.toRun(ThreadId, runOrdinal)
```
The provider command layer resolves app ids to provider refs at the edge. If the provider ref is missing or no longer live, the command fails with a typed capability/state error.
Examples:
```text
RuntimeRequestId -> nativeRequestRef + providerSessionId
RunId -> root NodeId -> ProviderTurnId -> nativeTurnRef
NodeId -> ProviderThreadId -> nativeThreadRef
```
## Pending Requests After Restart
Pending request records may survive restart, but provider callback state usually does not.
V2 should distinguish historical pending-looking requests from respondable requests:
```ts
type ResponseCapability =
| { type: "live"; providerSessionId: ProviderSessionId }
| { type: "not_resumable"; reason: string };
```
The UI can show that a request expired and the user must restart or rerun the turn.
## Subagent Correlation
Subagents are represented through parent-child execution nodes.
For Codex:
```text
collabAgentToolCall item
-> RuntimeItem
-> ExecutionNode(kind="subagent" or "tool_call")
receiverThreadIds[]
-> ProviderThread records
child turn/started and turn/completed
-> child ProviderTurn and child ExecutionNode
```
The child provider turn keeps its own provider refs. It is linked to the parent through `parentNodeId`, not by replacing its turn id with the parent turn id.
For weak providers, the adapter may create a child node by ordinal under the active parent node.
## Replay Determinism
Given the same raw event log and same initial app state, normalization must produce the same ids.
Requirements:
- Identity bindings are persisted as events or durable rows.
- Generated ids can be random if the binding is persisted before downstream projection.
- Fixture replay may use deterministic id generation to make assertions easier.
- Reprocessing the same raw event should find the existing binding, not allocate another entity.
+472
View File
@@ -0,0 +1,472 @@
# Feature Lifecycles
This document describes how core user-facing features should work in V2. These flows describe target behavior, not current implementation constraints.
## Creating Threads
Creating an app thread is separate from starting provider work.
```text
thread.create
-> AppThread created
-> no provider session required yet
-> no provider thread required yet unless eager provider creation is enabled
```
Provider thread creation may be lazy:
```text
first run starts
-> ensure ProviderSession
-> ensure ProviderThread
-> send provider turn
```
If the provider supports empty thread creation, V2 may create a provider thread early. If not, the provider thread is created at first run start.
## Starting A Run
When the user sends a message:
```text
thread.message.send
-> ConversationMessage(role=user)
-> Run(status=queued, ordinal=N)
-> root ExecutionNode(kind=root_turn, countsForRun=true)
-> enqueue provider command
```
When provider execution begins:
```text
provider turn accepted/started
-> ProviderTurn allocated or correlated
-> root node status=running
-> run status=running
```
When the root provider turn completes:
```text
root provider turn/completed
-> finalize assistant streams
-> finalize plans/todos/questions
-> root node terminal
-> capture checkpoint if applicable
-> run terminal
```
Only the root node can complete the run.
## Steering And Queueing Messages
V2 should support three classes of follow-up input:
```text
steer active run in place
steer active run by restart
queue next run
```
Steering is an app-level intent to change the active run's instructions. Provider-native steering is only one implementation strategy.
If the provider supports active-run steering, the app sends a steer command to the provider and keeps the same run active.
If the provider does not support active-run steering, the app interrupts the active provider turn, finalizes the interrupted attempt, and starts a replacement provider turn for the same app-level steering intent. This may be represented as either:
- the same `RunId` with a new root attempt node, if the UI should treat steering as revising the active run, or
- a new `RunId` linked by `supersedesRunId`, if preserving the interrupted attempt as a counted turn is important.
The preferred default is the same `RunId` with a new root attempt node until the first attempt has produced a user-meaningful terminal assistant response or checkpoint.
Queueing creates a new run after the active run.
Recommended command shape:
```ts
type MessageDispatchMode =
| { type: "steer_active"; targetRunId: RunId }
| { type: "restart_active"; targetRunId: RunId }
| { type: "queue_after_active" }
| { type: "start_immediately" };
```
Policy:
- If the provider supports active-run steering, send steer to the provider and attach the message to the active run.
- If not, interrupt the active provider turn and restart the active run with the steering message included.
- If the user explicitly requests a new turn, queue even if steering is available.
- If no run is active, start immediately.
The model supports this because `Run` and `ProviderTurn` are separate. A single app run may have multiple provider-turn attempts when the first attempt was interrupted for steering.
```ts
type RunAttempt = {
id: RunAttemptId;
runId: RunId;
attemptOrdinal: number;
rootNodeId: NodeId;
providerThreadId: ProviderThreadId;
providerTurnId: ProviderTurnId | null;
reason: "initial" | "steering_restart" | "retry" | "provider_recovery";
status: "running" | "completed" | "interrupted" | "failed" | "cancelled";
};
```
Only the selected/final attempt completes the run and creates the run checkpoint. Earlier interrupted steering attempts remain in the execution graph for audit/debugging.
## Follow-Up Turns
A normal follow-up after a completed run creates a new run.
```text
previous Run completed
user sends follow-up
-> new Run ordinal=N+1
-> new root node
-> same AppThread
-> same ProviderThread if resumable
```
If the previous provider thread cannot be resumed due to runtime error, missing native state, or incompatible provider settings, the provider thread is marked unavailable and the app creates a replacement provider thread from reconstructed context.
The replacement path is an error recovery flow, not a provider capability branch.
## Changing Providers Between Runs
Changing providers is a first-class context handoff. It does not fork the app thread and it does not rewrite prior provider history.
```text
user selects a different provider for next run
-> create Run with target provider
-> resolve or create target ProviderThread
-> create ContextHandoff if target provider thread lacks current app context
-> inject handoff summary into provider context
-> send user message as the new root turn
```
Example:
```text
runs 1-5: Codex provider thread C1
switch to Claude
-> summarize runs 1-5 for Claude
-> create Claude provider thread L1
runs 6-8: Claude provider thread L1
switch back to Codex
-> resume Codex provider thread C1 if possible
-> summarize runs 6-8 for Codex
-> send run 9 to C1 with the delta handoff
```
The default policy when returning to a provider is to resume the previous provider thread and bridge only the off-provider delta. This preserves native continuity for that provider's own earlier work while informing it about what happened elsewhere.
Fallback policy: create a fresh provider thread with a full app-thread summary when:
- the previous provider thread cannot be resumed,
- the provider's context is likely too stale or polluted by repeated handoffs,
- model/runtime settings changed incompatibly,
- the user explicitly requests a clean provider context.
The fallback should be explicit in the graph:
```text
new ProviderThread
forked/reconstructed from AppThread summary
ContextHandoff(strategy=full_thread_summary)
```
Provider switching should never concatenate hidden summaries into arbitrary prompts without recording the handoff. The handoff text is part of the run input contract and must be auditable.
## Interruption
Interruption targets a run or a node.
```text
interrupt.run(RunId)
-> resolve root node
-> resolve provider turn/thread refs
-> provider interrupt command if supported
-> mark interrupt requested
```
Terminal state arrives from provider lifecycle:
```text
provider interrupt request returns
-> command acknowledged only
provider emits root turn/completed status=interrupted
-> root node interrupted
-> run interrupted
-> checkpoint policy runs
```
The app should not mark the run terminal solely because the interrupt request returned.
If the provider does not support interruption:
- best case: stop provider session and mark run interrupted or cancelled by policy.
- worst case: mark interrupt unsupported and leave run active until provider exits.
## Resumption
Resumption has two meanings:
1. Resume an app thread in the UI from persisted projection.
2. Resume a provider-native conversation/session.
V2 always supports app-thread resumption from stored events/projections. Provider-thread resumption is a required provider adapter primitive. Every provider harness must expose a cursor/session/thread handle that can be used to resume prior provider state.
```text
open app thread
-> load AppThread, Runs, Messages, ExecutionGraph summary
-> if provider work must continue, resume the relevant ProviderThread
```
Provider resume flow:
```text
resolve activeProviderThreadId
resolve nativeThreadRef / resume cursor
start ProviderSession
provider resume
bind new ProviderSessionId to ProviderThread
```
If provider resume fails:
- preserve historical graph.
- mark provider thread not loaded or error.
- create replacement provider thread from reconstructed app context when the user continues.
- mark pending live requests as not resumable.
Provider resume failure is a runtime/recovery condition. It should not be modeled as "provider does not support resume."
## Forking
Forking creates a new first-class `AppThread` from a stable source.
Supported fork sources:
```ts
type ForkSource =
| { type: "run"; threadId: ThreadId; runId: RunId }
| { type: "node"; nodeId: NodeId }
| {
type: "provider_thread";
providerThreadId: ProviderThreadId;
providerTurnId?: ProviderTurnId;
};
```
Stable fork boundaries:
- completed run
- interrupted or failed run with a provider snapshot/checkpoint
- completed subagent node with a provider thread
- provider thread snapshot returned by the provider
- checkpoint boundary
Unstable boundaries:
- streaming message delta
- active tool call
- pending approval
- active subagent turn, unless live fork support is explicitly implemented
Forking from a subagent:
```text
subagent node selected
-> resolve ProviderThread owned by node
-> provider fork/resume if supported
-> create new AppThread
-> attach forked ProviderThread
-> copy/link checkpoint baseline
```
If the provider cannot fork native threads, V2 may synthesize a fork by creating a new app thread with projected messages/context, but that should be marked as lower fidelity by capability.
## Checkpointing
Checkpoints attach to checkpoint scopes. Root runs and child execution nodes can both be checkpointed.
Pre-run baseline:
```text
before root execution starts
-> ensure root checkpoint for current app run ordinal - 1
```
Post-root-run checkpoint:
```text
root node terminal
-> drain/finalize streams
-> capture root checkpoint for app run ordinal
-> compute diff from prior root checkpoint
-> mark run terminal with checkpoint
```
Child/subagent checkpoint:
```text
child checkpointable node starts
-> create child CheckpointScope under parent scope
child node terminal
-> drain/finalize child streams/items
-> capture child checkpoint for that scope
-> compute diff from parent/previous child checkpoint
-> mark child node checkpointed
```
Interrupted/failed runs:
- If filesystem state is meaningful and safe to capture, capture with status reflecting terminal state.
- If not, store a missing/error checkpoint summary.
- Child/subagent checkpoints are allowed, but they do not advance the parent app run count.
- Root run checkpointing should include or reference child checkpoint summaries so the run has a complete audit trail.
Rollback:
```text
rollback.toRun(threadId, targetRunOrdinal)
-> restore filesystem checkpoint targetRunOrdinal
-> compute provider turns to roll back if provider supports rollback
-> call provider rollback
-> reconcile returned provider snapshot if available
-> mark later runs rolled_back
-> delete or mark stale later checkpoint refs
```
Codex `thread/rollback` returns an authoritative provider thread snapshot. Other providers may require a synthetic provider thread restart from context.
Nested rollback:
```text
rollback.node(nodeId, checkpointId)
-> restore child checkpoint if scope cwd/ref is available
-> roll back provider thread for that child scope if supported
-> mark descendant child checkpoints stale/rolled_back
-> preserve parent run checkpoint history unless parent filesystem state changed
```
If a child checkpoint mutates the same workspace as the parent, restoring it may dirty the parent run's workspace state. The UI/API should make that explicit.
## Approvals
Approvals are runtime requests scoped to execution nodes.
```text
provider requestApproval
-> RuntimeRequest(kind=...)
-> approval ExecutionNode
-> thread pending request projection
-> optional thread status waiting
```
User response:
```text
approval.respond(RuntimeRequestId)
-> resolve live provider callback
-> send provider response
-> RuntimeRequest resolved
-> approval node completed/cancelled
```
Rules:
- Approval ids are app-owned.
- Provider request ids are refs.
- Pending approvals from subagents are still actionable if the provider exposes live response capability.
- Approval response should fail with `not_resumable` if provider callback state is gone.
## Ask Questions / User Input
Ask-questions is a user-input request, not a plan by itself.
```text
provider requests user input
-> RuntimeRequest(kind=user_input)
-> ExecutionNode(kind=user_input_request)
-> Question artifact
-> run status=waiting
```
On answer:
```text
user-input.respond(RuntimeRequestId, answers)
-> provider callback
-> request resolved
-> node completed
-> run resumes/runs
```
If the provider does not support structured questions, the adapter may project a plain assistant message and no respondable request.
## Plans And Todo Lists
V2 separates three concepts:
- Proposed plan: a durable plan artifact the user can accept/implement.
- Todo list: live execution progress for the current run.
- Ask questions: structured user-input request.
Codex examples:
```text
turn/plan/updated
-> PlanArtifact(kind=todo_list)
-> activity/projection update
item/plan/delta or plan item completed
-> PlanArtifact(kind=proposed_plan)
item/tool/requestUserInput
-> PlanArtifact(kind=questions)
-> RuntimeRequest(kind=user_input)
```
Rules:
- Root run todo lists update the main plan/progress UI.
- Child/subagent todo lists are nested under their execution node.
- Child plans do not replace root plans unless promoted/forked.
- Proposed plan implementation creates a new run or a new thread depending on user action.
## Activities
Activities are a projection of execution graph events.
Examples:
```text
tool.started
approval.requested
approval.resolved
plan.updated
checkpoint.captured
subagent.started
subagent.completed
runtime.warning
```
Activities should keep `nodeId` and `runId` so the UI can group them correctly.
## Completion Barriers
Before a run is marked terminal, V2 should pass a finalization barrier:
```text
root provider turn terminal
-> flush assistant text buffers
-> close active assistant messages
-> finalize plan/todo artifacts
-> close open non-live child nodes if provider marked them done
-> capture checkpoint
-> publish run terminal
```
This prevents early checkpoint capture and incomplete plan state.
@@ -0,0 +1,282 @@
# Provider Capability System
V2 must not assume every provider can do what Codex can do. Provider behavior should be expressed through capabilities and policies, not provider-name conditionals spread across orchestration.
## Capability Shape
```ts
type ProviderCapabilities = {
sessions: SessionCapabilities;
threads: ThreadCapabilities;
turns: TurnCapabilities;
streaming: StreamingCapabilities;
tools: ToolCapabilities;
approvals: ApprovalCapabilities;
planning: PlanningCapabilities;
subagents: SubagentCapabilities;
context: ContextCapabilities;
checkpointing: CheckpointCapabilities;
identity: IdentityCapabilities;
};
```
Capabilities should be versioned and emitted by each adapter at session start.
## Session Capabilities
```ts
type SessionCapabilities = {
supportsMultipleProviderThreadsPerSession: boolean;
supportsModelSwitchInSession: boolean;
supportsProviderSwitchingViaHandoff: boolean;
supportsRuntimeModeSwitchInSession: boolean;
pendingRequestsSurviveRestart: boolean;
};
```
Policy examples:
- If model switching is unsupported, start a new provider session.
- If pending requests do not survive restart, mark old requests `not_resumable`.
Provider-thread resumption is not a capability. It is a required adapter primitive. Adapters must be able to start from a stored provider cursor/session/thread handle or return a runtime resume failure.
## Thread Capabilities
```ts
type ThreadCapabilities = {
canCreateEmptyThread: boolean;
canReadThreadSnapshot: boolean;
canRollbackThread: boolean;
canForkThread: boolean;
canForkFromTurn: boolean;
canForkFromSubagentThread: boolean;
exposesNativeThreadId: boolean;
};
```
Codex can expose strong thread ids and rollback snapshots. Claude may support native forking through its own model/session primitives. Other providers may only support synthetic app forks.
## Turn Capabilities
```ts
type TurnCapabilities = {
exposesNativeTurnId: boolean;
emitsTurnStarted: boolean;
emitsTurnCompleted: boolean;
supportsInterrupt: boolean;
supportsActiveSteering: boolean;
supportsSteeringByInterruptRestart: boolean;
supportsQueuedMessages: boolean;
terminalStatusQuality: "strong" | "weak" | "none";
};
```
If `terminalStatusQuality` is weak, V2 should use adapter policy to infer terminal state, but still mark correlation strength accordingly.
`supportsActiveSteering` means the provider can modify an in-flight turn directly. `supportsSteeringByInterruptRestart` means V2 can implement app-level steering by interrupting the active turn and starting a replacement attempt. Most providers should support the latter if they support interruption and normal follow-up turns.
## Streaming Capabilities
```ts
type StreamingCapabilities = {
streamsAssistantText: boolean;
streamsReasoning: boolean;
streamsToolOutput: boolean;
streamsPlanText: boolean;
emitsMessageCompleted: boolean;
};
```
If message completion is not emitted, the normalizer closes assistant messages at root run terminal.
## Tool Capabilities
```ts
type ToolCapabilities = {
exposesToolItemIds: boolean;
emitsToolStarted: boolean;
emitsToolCompleted: boolean;
emitsToolOutput: boolean;
supportsMcpTools: boolean;
supportsDynamicToolCallbacks: boolean;
};
```
Weak providers may produce only textual tool summaries. The adapter can still create `RuntimeItem` records by scoped ordinal.
## Approval Capabilities
```ts
type ApprovalCapabilities = {
supportsCommandApproval: boolean;
supportsFileReadApproval: boolean;
supportsFileChangeApproval: boolean;
supportsApplyPatchApproval: boolean;
approvalsHaveNativeRequestIds: boolean;
approvalCallbacksAreLiveOnly: boolean;
approvalsCanOriginateFromSubagents: boolean;
};
```
The UI should show pending approvals from any execution node, including subagents, if they are respondable.
## Planning Capabilities
```ts
type PlanningCapabilities = {
emitsPlanUpdated: boolean;
emitsTodoList: boolean;
emitsProposedPlan: boolean;
supportsStructuredQuestions: boolean;
planDeltasHaveItemIds: boolean;
};
```
Mapping policy:
- `emitsTodoList`: update live run progress.
- `emitsProposedPlan`: create accept/implementable plan artifacts.
- `supportsStructuredQuestions`: create respondable user-input requests.
If a provider only emits plain assistant text, the app should not pretend it has structured plans.
## Subagent Capabilities
```ts
type SubagentCapabilities = {
supportsSubagents: boolean;
exposesSubagentThreadIds: boolean;
emitsSubagentLifecycle: boolean;
canWaitForSubagents: boolean;
canCloseSubagents: boolean;
canForkSubagentThread: boolean;
};
```
When `exposesSubagentThreadIds` is true, subagent provider threads become addressable `ProviderThread` records. When false, subagents can still be shown as nested execution nodes if the provider exposes enough lifecycle information.
## Context Handoff Capabilities
Context handoff controls provider switching and provider-thread reconstruction.
```ts
type ContextCapabilities = {
acceptsSystemContext: boolean;
acceptsDeveloperContext: boolean;
acceptsSyntheticUserContext: boolean;
canGenerateSummaries: boolean;
canConsumeHandoffSummaries: boolean;
supportsDeltaHandoff: boolean;
supportsFullThreadHandoff: boolean;
maxRecommendedHandoffChars: number | null;
};
```
Policy examples:
- If `supportsDeltaHandoff` is available, return to a previous provider thread with a summary of only off-provider runs.
- If delta handoff is unsupported or low quality, create a new provider thread with a full thread summary.
- If the provider cannot accept explicit context, provider switching should require synthetic user context or be marked unsupported.
- If no provider can generate summaries, use the app's configured summarization provider or a local summarizer capability.
## Checkpoint Capabilities
Checkpointing is primarily app-owned, but provider conversation rollback is provider-dependent.
```ts
type CheckpointCapabilities = {
appCanCheckpointFilesystem: boolean;
supportsNestedCheckpointScopes: boolean;
providerCanRollbackConversation: boolean;
providerRollbackReturnsSnapshot: boolean;
providerCanReadConversationSnapshot: boolean;
};
```
If provider rollback is unsupported, filesystem rollback can still happen, but provider conversation state must be restarted or marked divergent. Nested checkpoint scopes are app-owned; providers only affect whether their nested provider conversations can be rolled back to match restored filesystem state.
## Identity Capabilities
```ts
type IdentityCapabilities = {
nativeThreadIds: "strong" | "weak" | "none";
nativeTurnIds: "strong" | "weak" | "none";
nativeItemIds: "strong" | "weak" | "none";
nativeRequestIds: "strong" | "weak" | "none";
};
```
This controls how the normalizer correlates events:
- `strong`: use native id as scoped provider ref.
- `weak`: use native id plus ordinal/fingerprint.
- `none`: allocate by scoped ordinal.
## Degradation Policies
Every feature should declare what happens when capability is missing.
Examples:
```text
interrupt unsupported
-> stop session if allowed, otherwise mark unsupported
active steering unsupported
-> interrupt active turn and restart the run as a steering replacement attempt
fork unsupported
-> synthetic fork from app projection if policy allows
rollback unsupported
-> restore filesystem checkpoint, restart provider context, mark provider state divergent
nested checkpoint unsupported
-> capture only root-run checkpoint and record child filesystem activity as uncheckpointed
provider switch return unsupported
-> create fresh provider thread with full app-thread summary
structured approvals unsupported
-> provider runs under configured sandbox policy; no approval UI
plan_updated unsupported
-> no live todo UI; rely on assistant messages
```
The UI should not hide unsupported behavior behind provider-specific errors. It should receive typed capability results.
## Adapter Contract
Each provider adapter should expose:
```ts
type ProviderAdapter = {
getCapabilities(): ProviderCapabilities;
startSession(input): ProviderSession;
ensureProviderThread(input): ProviderThread;
sendRun(input): ProviderTurnStartResult;
steerRun?(input): void;
interrupt(input): void;
respondToRequest(input): void;
readThreadSnapshot?(input): ProviderThreadSnapshot;
rollbackThread?(input): ProviderThreadSnapshot | void;
forkThread?(input): ProviderThread;
streamRawEvents(): Stream<RawProviderEvent>;
};
```
Optional methods are guarded by capabilities. The orchestration layer should not call optional methods without checking capability or going through a policy wrapper.
## Capability-Driven UI
The UI should receive capability-informed affordances:
- show or hide fork action by fork source.
- show interrupt as available, destructive fallback, or unavailable.
- show approvals as respondable or expired.
- show plan/todo panels only when structured plan artifacts exist.
- show rollback only when app checkpoint exists, and annotate provider rollback support.
This keeps the product predictable across Codex, Claude, Cursor, OpenCode, and future providers.
@@ -0,0 +1,229 @@
# Provider Switching And Context Handoff
Provider switching is a first-class V2 feature. An app thread may contain runs from multiple providers while preserving each provider's native conversation handles and the app's canonical conversation history.
## Recommendation
When returning to a provider that was used earlier, default to resuming that provider's previous provider thread and inject a delta summary covering the runs that happened while the provider was inactive.
Create a fresh provider thread with a full app-thread summary only when resuming the prior provider thread fails, settings are incompatible, or delta handoff is likely to produce poor context.
This gives the best default tradeoff:
- preserves native continuity for provider-specific prior work,
- avoids repeatedly summarizing everything,
- lets each provider keep its own tool/history affordances,
- makes cross-provider context explicit and auditable,
- keeps a clean fallback when old provider context is stale.
## Example
```text
runs 1-5: Codex, ProviderThread C1
switch to Claude for run 6
-> ContextHandoff H1 covers runs 1-5
-> create ProviderThread L1
-> run 6 uses L1 with H1
runs 6-8: Claude, ProviderThread L1
switch back to Codex for run 9
-> ContextHandoff H2 covers runs 6-8
-> resume ProviderThread C1
-> run 9 uses C1 with H2
```
ProviderThread C1 is not expected to natively contain Claude's runs. It contains Codex's native conversation plus explicit handoff artifacts that summarize external progress.
## Why Not Always Create A Fresh Provider Thread?
Always creating a fresh provider thread is simpler but loses useful provider-native continuity:
- prior hidden reasoning/context that is only available in the provider thread,
- provider-side thread metadata,
- native tool state where available,
- continuity for provider-specific behavior.
It also forces every switch to depend on full summarization quality. Full summaries are useful fallback artifacts, but they should not be the default when a previous provider thread can be safely resumed.
## Why Not Resume Without Summary?
Because the app thread moved on while the provider was inactive. The resumed provider would not know what another provider did. That creates wrong answers, stale plans, and unsafe file assumptions.
Returning to a provider requires a handoff summary unless no runs happened since that provider last participated.
## Provider Thread Coverage
Provider threads have native coverage and handoff coverage.
```ts
type ProviderThreadCoverage = {
providerThreadId: ProviderThreadId;
nativeRunOrdinals: number[];
handoffIds: ContextHandoffId[];
};
```
For the example above:
```text
C1 native runs: 1,2,3,4,5,9
C1 handoffs: H2 covering 6-8
L1 native runs: 6,7,8
L1 handoffs: H1 covering 1-5
```
The app thread remains the source of truth for full history.
## Handoff Artifact
A handoff is explicit graph data.
```ts
type ContextHandoff = {
id: ContextHandoffId;
threadId: ThreadId;
targetRunId: RunId;
fromProviderThreadIds: ProviderThreadId[];
toProviderThreadId: ProviderThreadId;
coveredRunOrdinals: { from: number; to: number };
strategy:
| "delta_since_target_last_seen"
| "full_thread_summary"
| "checkpoint_summary"
| "manual_context";
summaryText: string;
status: "pending" | "ready" | "failed" | "superseded";
createdByProvider: ProviderKind | null;
createdAt: string;
updatedAt: string;
};
```
The handoff should be linked to the run that consumes it. If the same summary is regenerated, the old handoff is superseded rather than mutated invisibly.
## Switch Flow
```text
start run with target provider P
-> find current app thread history
-> find best ProviderThread for P
-> decide handoff strategy
-> generate ContextHandoff if needed
-> ensure ProviderSession for P
-> ensure/resume/create target ProviderThread
-> send provider turn with handoff context + user message
```
The user message remains the actual run input. The handoff context is a separate preamble/system/developer/synthetic-user context depending on provider capability.
## Strategy Selection
Recommended strategy order:
1. No handoff: target provider thread already has current app run coverage.
2. Delta handoff into existing provider thread: target provider thread can resume and only missed a run range.
3. Full thread handoff into existing provider thread: target provider can resume, but delta chain is too complex.
4. Full thread handoff into new provider thread: target provider resume failed, settings are incompatible, or old context is stale.
5. Unsupported: provider cannot accept handoff context and no safe reconstruction path exists.
## Staleness Policy
The app should be able to decide that returning to an old provider thread is no longer appropriate.
Possible staleness signals:
- too many off-provider runs since last use,
- too many chained handoffs,
- target provider model/runtime mode changed incompatibly,
- provider thread resume failed,
- prior provider thread was rolled back or forked in a conflicting way,
- user selected "clean context",
- handoff summary would exceed provider context policy.
When stale, create a new provider thread with `full_thread_summary`.
## Summarization Source
Summaries can be generated by:
- the provider being left,
- the provider being entered,
- a configured summarization provider,
- a local deterministic summarizer for structured artifacts.
The summary generator is not necessarily the target provider. The handoff records `createdByProvider` so quality and provenance can be inspected later.
## What The Summary Should Contain
The summary should be app-thread canonical, not provider transcript-only.
Include:
- user goals and constraints,
- decisions made,
- files changed,
- commands/tests run,
- plans/todo state,
- unresolved approvals/questions,
- current checkpoint/diff summary,
- known failures,
- relevant subagent results.
Do not include:
- irrelevant provider protocol noise,
- hidden chain-of-thought,
- stale tool output that is superseded by later runs,
- large diffs when a file summary is enough.
## Checkpoint Interaction
Provider switching does not change checkpoint ownership. Checkpoints still attach to app runs.
However, handoff generation should reference the latest checkpoint and diff summary so the next provider has a correct workspace-state picture.
```text
run N completed
-> checkpoint N captured
switch provider for run N+1
-> handoff includes summary through checkpoint N
```
## Rollback Interaction
Rollback invalidates handoffs that cover rolled-back runs.
```text
rollback to run 5
-> runs 6+ marked rolled_back
-> handoffs covering 6+ marked superseded
-> provider threads whose native/handoff coverage includes 6+ marked divergent or rolled back by capability
```
If the active provider supports provider rollback, call it. Otherwise, create a new provider thread from the retained app-thread summary when work resumes.
## Forking Interaction
Forking from a mixed-provider app thread should copy the app-thread history and choose provider context by fork source.
Examples:
- Fork from run 5 on Codex: prefer Codex provider thread at run 5 if available.
- Fork from run 8 on Claude: prefer Claude provider thread at run 8 if available.
- Fork from app checkpoint with no provider-native thread: create provider thread with full summary up to that checkpoint.
- Fork from subagent provider thread: use the subagent's provider thread directly if stable.
## Data Model Changes
Provider switching requires:
- `Run.provider`
- `Run.providerThreadId`
- `Run.contextHandoffId`
- `ProviderThread.firstRunOrdinal`
- `ProviderThread.lastRunOrdinal`
- `ProviderThread.handoffIds`
- `ContextHandoff`
- provider capabilities for handoff support
The app does not need separate conversation threads for provider switches. It needs multiple provider threads attached to the same app thread.
+192
View File
@@ -0,0 +1,192 @@
# Testing Strategy
V2 should be validated with a small number of high-value integration tests rather than a large suite of unit tests that mock away the behavior being tested.
The goal is not "no test doubles ever." The goal is that test doubles exist only at true process, network, clock, id, and filesystem boundaries. Core orchestration behavior must run for real.
## Testing Principle
The default V2 test shape is:
```text
command dispatch
-> real Orchestrator
-> real ProviderAdapter
-> replayed ProviderRuntime transport
-> real adapter normalizer
-> real EventLog
-> real Projection
-> real Checkpoint policy
-> assertions
```
The replay framework replaces the external provider process or network stream. It does not replace the adapter, normalizer, event log, projection, command router, checkpoint policy, or business logic.
## Allowed Test Substitutes
Allowed substitutes:
- provider runtime transport, backed by deterministic replay transcripts.
- Effect runtime time, controlled in tests with `TestClock` from `effect/testing`.
- Effect `Random`, provided with a deterministic test implementation for stable UUIDs/numbers.
- temporary filesystem/worktree.
- temporary database or in-memory database with the same repository interfaces.
- fake process supervisor only when it is testing process failure behavior directly.
Not allowed in integration tests:
- mocked orchestrator.
- mocked provider adapter.
- mocked provider event normalizer.
- mocked event log.
- mocked projection reducer.
- mocked checkpoint service behavior.
- mocked provider capability policy.
- pre-normalized domain events used as the input for adapter tests.
- custom clock/id services that duplicate Effect's `Clock`, `DateTime`, or `Random` services.
Pure reducer tests are still valid, but they should be few and targeted. They should test projection invariants directly, not replace integration coverage.
Production code should read time through Effect runtime APIs, such as `DateTime.now` and `Clock.currentTimeMillis`, not through `Date.now` or ad hoc wrappers. Production code should allocate random values through `effect/Random`, not through direct `crypto.randomUUID`, `Math.random`, or a custom global id generator.
Tests should provide Effect test services:
```ts
import { TestClock } from "effect/testing";
```
The id allocator can still expose domain-specific helpers such as `newRunId` or `newNodeId`, but those helpers should be implemented on top of `Random` so test layers can produce deterministic values without mocking orchestration logic.
## Generic Replay Runtime
Replay must be provider-neutral. Codex NDJSON fixtures are one provider's transcript format, not the framework itself.
```ts
type ProviderReplayTranscript = {
provider: ProviderKind;
protocol: string;
version: string;
scenario: string;
entries: ProviderReplayEntry[];
};
type ProviderReplayEntry =
| {
type: "expect_outbound";
label?: string;
frame: unknown;
}
| {
type: "emit_inbound";
label?: string;
frame: unknown;
afterMs?: number;
}
| {
type: "runtime_exit";
status: "success" | "error" | "cancelled";
error?: unknown;
};
```
The replay runtime owns deterministic transport semantics:
- ordered inbound event emission.
- outbound command assertion.
- pause/resume and timing control.
- runtime exit/error simulation.
- resume cursor/session restoration.
- transcript metadata validation.
The replay runtime must not know what a turn, plan, approval, subagent, or checkpoint means. Provider adapters interpret provider-specific frames.
## Provider Transcript Formats
Each provider can have its own raw frame format inside the generic replay envelope.
Examples:
```text
Codex replay transcript
-> JSON-RPC app-server requests/responses/notifications
-> consumed by CodexAdapter
Claude replay transcript
-> Claude SDK/API stream events and command responses
-> consumed by ClaudeAdapter
```
Fixtures should preserve raw provider evidence as closely as possible. Expected V2 events or projections are assertions, not fixture input.
## Contract Test Levels
Recommended levels:
1. Schema tests for V2 contracts.
2. Pure projection tests for hard invariants.
3. Provider adapter replay tests from raw transcript to V2 domain events.
4. Full orchestration integration tests from commands through replay runtime to final projection.
The fourth level is the most important one. It is the test that catches lifecycle mismatches such as child turns closing parent runs or checkpoints being captured too early.
## First Ten Integration Tests
V2 should start with roughly ten strong tests:
1. `simple`: sending one message creates one run, one root node, one provider turn, one assistant response, and one root checkpoint.
2. `multi_turn`: follow-up messages create monotonically ordered app runs on the same app thread.
3. `message_steering`: steering attaches to the active run intent instead of becoming an unrelated run.
4. `turn_interrupt`: interrupt acknowledgement does not complete the run until the provider terminal event arrives.
5. `steering_restart_fallback`: a provider without native steering interrupts the active attempt and creates a replacement attempt under the same run.
6. `subagent`: child provider turns create nested execution nodes and never complete the parent run.
7. `subagent_checkpoint`: child/subagent nodes create nested checkpoint scopes without advancing the app run count.
8. `thread_rollback`: rollback targets checkpoint scopes and reconciles provider rollback snapshots.
9. `approval_request`: provider approval callbacks become durable runtime requests and are resolved through the real adapter path.
10. `provider_switch_return`: switching away from a provider creates a context handoff, and switching back resumes the prior provider thread with a delta handoff.
Additional tests should be added only when they protect a new invariant or reproduce a real failure mode.
## Fixture Rules
- Fixtures are raw provider transcripts, not mocked domain events.
- Fixtures should include enough outbound expectations to prove the app sent the correct provider commands.
- Fixtures should include protocol metadata, provider version, model, cwd policy, and capture timestamp.
- Fixture playback must be deterministic under Effect `TestClock` and deterministic `Random` layers.
- When a provider transcript is generated from a real run, keep the original raw event ordering.
- Redaction should preserve ids, method names, lifecycle ordering, and correlation structure.
## Assertions
Assertions should prefer final projections and durable event logs over incidental implementation calls.
Good assertions:
- run status and ordinal.
- active/final run attempt.
- execution node parent/child structure.
- provider thread and provider turn correlation.
- checkpoint scope hierarchy.
- pending/resolved runtime requests.
- handoff coverage and strategy.
- raw event count and normalized event count when relevant.
Weak assertions:
- exact internal function call counts.
- private helper invocation order.
- mocked callback arguments below the adapter/runtime boundary.
## Implementation Order
Testing infrastructure should be built before production rewrites:
1. V2 contract schemas.
2. Effect service definitions.
3. provider runtime transport abstraction.
4. generic replay runtime.
5. Codex transcript loader for existing probe NDJSON files.
6. projection reducer tests for core invariants.
7. full command-to-projection integration tests.
8. production layers.
This keeps the architecture executable while it is being built and prevents tests from validating only simplified mocks.