feat(orchestrator): introduce new orchestrator
Summary
- wire orchestration V2 provider adapter registry/factory flow for Codex and Claude provider instances
- add Claude replay/query primitives, native fork/rollback fixtures, subagent fixture coverage, and provider replay harness updates
- update debugger model/provider picker and improve user-facing orchestration errors
Validation
- bun fmt
- bun lint
- bun typecheck
- bun run test -- src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts -t claudeAgent
- bun run test -- src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts
- bun run test -- src/orchestration-v2/testkit/ThreadFork.integration.test.ts -t Claude
Notes
- Draft PR for review of current branch state. Codex all-provider replay still needs schema alignment with latest app-server behavior before it can be treated as a full-suite signal.
Closes
Verified against the branch with code/commit evidence.
High confidence
Closes #4952 Closes #4873 Closes #4775 Closes #4795 Closes #4710 Closes #4668 Closes #4619 Closes #4584 Closes #4561 Closes #4713 Closes #4198 Closes #4452 Closes #3797 Closes #4232 Closes #3666 Closes #3580 Closes #2785 Closes #2789 Closes #3138 Closes #1404 Closes #231 Closes #216
Medium confidence (under review)
Closes #4568 Closes #4766 Closes #4495 Closes #4456 Closes #4399 Closes #3744 Closes #2921 Closes #3624 Closes #3149 Closes #2336 Closes #538 Closes #2173 Closes #2065
[!NOTE]
Introduce orchestration-v2 runtime with multi-provider adapters, scheduled tasks, and thread management
- Adds a complete
orchestration-v2runtime replacing the legacy orchestrator: event-sourced projections, typed domain events, new services for session/turn/checkpoint/fork/merge-back, and a composedOrchestrationV2LayerLivefor dependency injection- Implements provider adapters for Claude, Codex, Cursor, Grok, OpenCode, and ACP Registry under
apps/server/src/orchestration-v2/Adapters/, each with capabilities declarations and replay test harnesses- Adds database migrations 038–046 creating V2 event log, projection tables (threads, runs, attempts, nodes, subagents, provider sessions), effect outbox, scheduled tasks, and a unified application event source that migrates legacy V2 events
- Introduces a
ScheduledTaskServicewith interval and fixed-time schedule logic, CRUD operations, and a new/settings/scheduled-tasksroute in the web app- Adds MCP toolkits for orchestration (
delegate_task,task_status,schedule_task, etc.) and worktree (t3_worktree_handoff,t3_worktree_status) registered inMcpHttpServer- Updates web and mobile clients to consume V2 projections, shell snapshots, and runtime fields; adds thread details panel, queue management UI, and relationship graph
- Risk: schema version bumped to 3 for cached shell/thread snapshots; old caches are discarded on load. Migrations are irreversible and alter shared
orchestration_eventsandorchestration_command_receiptstables.Macroscope summarized adf1c26.
[!NOTE] High Risk Large orchestration rewrite touching auth-adjacent provider sessions, persistence migrations, and client protocol/cache compatibility; incorrect replay or projection semantics could corrupt thread state or drop user work.
Overview This PR lands orchestration V2 as the live agent stack—provider adapters, projections, durable effects, and client cutover—while retiring the old thread-transfer PR comment workflow and tightening CI for native test fixtures.
Backend & platform (per branch scope): V2 runtime wiring for multiple provider instances (Codex, Claude, Cursor, ACP registry, etc.), replay/integration coverage for fork, merge-back, subagents, and steering; MCP toolkits and scheduled tasks with new migrations; shared orchestration cache schema v3 so web/mobile discard stale V1-shaped offline snapshots.
Mobile (visible in diff): Persistence and home/archive flows move to V2 shell/thread snapshots and
visibleTurnItems-driven feeds; runtime summaries replace V1 session fields for archive/stop rules; thread visit watermarks, queue controls, relationship banner, and expandable activity inspectors (checkpoint rollback, file links, structured payloads); approvals/user-input use runtime request IDs and live/stale response capability.CI/docs: Removes
.github/workflows/thread-transfer-report.ymland its publisher scripts; CI still emits transfer-budget artifacts but no longer upserts PR comments. Adds build-essential on the test runner so ACP process-tree compile tests do not soft-skip. Adds/updates orchestration V2 integration plans and user appearance doc link.Reviewed by Cursor Bugbot for commit adf1c2649aa417e4ba4e494fa4900cd785448f0f. Bugbot is set up for automated code reviews on this repo. Configure here.
Navigate logical layers of code changes, visualize relationships, and explore their blast radius.
✨ Finishing Touches
📝 Generate docstrings
- [ ] Create stacked PR
- [ ] Commit on current branch
🧪 Generate unit tests (beta)
- [ ] Commit to this branch
- [ ] Create a new PR
- [ ] Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Autopilot is currently an internal CodeRabbit preview.
Comment @coderabbitai help to get the list of available commands.
🚀 Expo continuous deployment is ready!
- Project → t3-code
- Platforms → android, ios
- Scheme → t3code-preview
| 🤖 Android | 🍎 iOS | |
|---|---|---|
| Fingerprint | fe5a51f2e189da69dfc4c2cd458e6cfb5fdff2ea | ae3bd597809dfd7771d0898f735d172973d4c1c8 |
| Build Details | Build PermalinkDetailsDistribution:INTERNALBuild profile: preview:devRuntime version: fe5a51f2e189da69dfc4c2cd458e6cfb5fdff2eaApp version: 0.1.0Git commit: 1d5a64460414f9a2c6ff4a5e4f977932228b7f1b |
Build PermalinkDetailsDistribution:INTERNALBuild profile: preview:devRuntime version: ae3bd597809dfd7771d0898f735d172973d4c1c8App version: 0.1.0Git commit: eea0dcae4150df8341606520c074dc651ae7c00a |
| Update Details | Update PermalinkDetailsBranch:pr-2829Runtime version: fe5a51f2e189da69dfc4c2cd458e6cfb5fdff2eaGit commit: 1d5a64460414f9a2c6ff4a5e4f977932228b7f1b |
Update PermalinkDetailsBranch:pr-2829Runtime version: ae3bd597809dfd7771d0898f735d172973d4c1c8Git commit: 1d5a64460414f9a2c6ff4a5e4f977932228b7f1b |
| Update QR |
Provider-initiated turns are invisible: post-turn SDK activity is dropped entirely
Two reproductions today (threads 47763f5e, 71e29ba5), one root cause. Filing here since the fix is squarely in turn-mapping territory; relates to the t3code/scheduled-tasks follow-up "thread-bound fires steer active turns".
Symptom
A thread shows finished in the UI while the Claude SDK session is actively running a turn — making tool calls, pushing to PRs. The work is invisible: no run, no turn items, no activity log entries, nothing in orchestration_events after the last user-requested turn completed.
Repro timelines
Thread 47763f5e (background-task wakeup):
22:10:01— turn completes (result, end_turn: "…polling every minute, up to 25 min"). Run ordinal 9 →completed, session →ready. Last orchestration event for the thread.22:12:56— SDK wakes the session:system/task_updated+system/task_notification(watcher taskbdknlk0tpcompleted) →system/init→ full new streaming turn with tool calls (visible in the provider protocol log only).- Several minutes of real work (incl.
git push) with zero orchestration events.
Thread 71e29ba5 (ScheduleWakeup self-pacing loop):
22:36:13— run 58 completes withstop_reason: "tool_use"(agent calledScheduleWakeupand went to sleep). Last orchestration event.22:36:49—task_updated(statusfailed!) +task_notificationforblrc0l01r→system/init→ new turn.22:37:55— invisible turn completes (~66s, 8 SDK turns), callsScheduleWakeupagain. Loop repeats: one invisible turn per wakeup. No run 59 exists.
Root cause chain
- Adapter (
ClaudeAdapter.ts):context.turnStateis created only bysendTurn(orchestrator-requested prompt) and cleared inhandleResultMessage. When the SDK starts a turn on its own (task-notification wakeup), there is noturnState, sohandleStreamEventearly-returns and drops everything streamed. The synthetic-turn fallback inhandleAssistantMessage(~L2468) triggers too late (first complete assistant message) and demonstrably did not rescue either repro. - Ingestion (
ProviderRuntimeIngestion.ts): aturn.startedwith no active turn would be accepted (session →running), but no run exists — ordinals/userMessageId/provider-turn binding all come fromthread.turn-start-requested, so turn-scoped events have nowhere to project. - Bonus bug: the adapter has no
system/task_updatedcase — it falls through to the unknown-message default. 7 occurrences in one thread, includingfailedandkilledstatus patches, all dropped as "unknown SDK message" warnings.
Proposed fix
- Orchestrator: mint runs for turns nobody requested. In
processRuntimeEvent, when an acceptedturn.startedhas no pending turn-start (getPendingTurnStartByThreadId→None), dispatch arun.provider-initiatedcommand: next ordinal from the same counter, nouserMessageId,triggerpayload from the event, provider-turn→run binding as if a pending turn-start had been claimed. Key onturnIdfor replay idempotency. Everything downstream (turn items, messages, checkpoints,turn.completed→ run completed) reuses existing projection code. - Adapter: open the turn at the wakeup signal, not the first assistant message. On
stream_event/message_start(orsystem/status: requesting) withturnState === undefined, create a syntheticturnStateand emitturn.startedwith trigger metadata. Keep the assistant-message fallback as a safety net. - Schedule fires (t3code/scheduled-tasks): front door when idle. A thread-bound fire hitting a thread with no active turn should go through the normal turn-start pipeline (synthetic user message), not silently steer the idle session. Keep steer for genuinely-active turns. (Doesn't cover SDK-internal wakeups — hence 1+2.)
- Adapter: handle
system/task_updated— apply the patch toclaudeTasksstate / emit a task-updated runtime event instead of dropping failed/killed statuses. - Observability: loud warning when a decoded SDK message arrives while session status is
readywith noturnState. This was only diagnosable by diffing the provider protocol log against the event store.
Gift from the SDK
The post-wakeup result already carries "origin": {"kind": "task-notification"} — the SDK explicitly labels provider-initiated turns. The adapter can carry origin straight into the synthetic turn.started payload and the run record; no correlation heuristics needed.
UI implication: a run with trigger: "provider" renders with a trigger header ("resumed: background task completed / schedule fired") instead of a user bubble, and the thread correctly shows running during autonomous work.
🤖 Generated with Claude Code
Follow-up: post-turn wakeup handling implemented (design revised)
Implemented on this branch (t3code/codex-turn-mapping), with one significant revision to the plan in my earlier comment after re-reading the raw provider chunks: not every wakeup should become a new run. The SDK distinguishes two cases, and they now get different treatment:
1. ScheduleWakeup sleep loops — adapter-only, no orchestrator involvement
The recorded chunks are explicit: the yield result carries stop_reason: "tool_use" (not end_turn), and the ScheduleWakeup tool result carries structured {scheduledFor, clampedDelaySeconds} plus prose ("Nothing more to do this turn — the harness re-invokes you…"). ClaudeAdapterV2 now tracks the observed ScheduleWakeup result on the turn context and does not finalize such turns: the run stays active, run-scoped ingestion stays subscribed, and the wakeup continuation streams into the same run. A 25-minute poll loop is one run, not a run per wakeup.
2. True end_turn re-invocations — provider-initiated runs
When Claude genuinely ends the turn and the SDK later re-invokes it (background task notification), holding the run open is wrong (dev servers run forever), so:
ClaudeAdapterV2buffers the post-turn activity (skipping stream-event noise) and emits a newturn.wakeupadapter event once real activity starts, withoriginextracted from thetask_notification.ProviderWakeupService(new): relay queue + daemon (breaks the session-manager ↔ orchestrator layer cycle). The daemon waits for thread quiescence (the wakeup announce races the previous run's terminal commit by milliseconds), then dispatchesmessage.dispatchwith new modeattach_wakeup.- The orchestrator mints a run through the existing dispatch machinery — synthetic message (
createdBy: "system",creationSource: "provider", turn iteminputIntent: "provider_wakeup") — andRunExecutionServicedelivers via the new optional adapter methodattachTurn(adopt in-flight turn + replay buffer; nothing sent to the provider). - Guards: superseded by any blocking run; no provider switch; no pending context transfers. A user turn that races the wakeup wins; the adapter drops its buffer (task bookkeeping is still applied).
3. Backgrounded commands (Bash + run_in_background)
Previously these projected as completed command_execution items the instant the tool returned, while the command kept running. Now: a tool result carrying tool_use_result.backgroundTaskId keeps the item running, registered session-level; the matching task_updated flips it terminal (killed/failed no longer dropped — there was no task_updated handling at all), and task_notification enriches the output with the summary. This works cross-run: routeProviderEvent accepts item/node updates for owned provider threads, so a wakeup run can complete an earlier run's item.
Tests
New replay fixture claude_provider_wakeup built frame-by-frame from the recorded thread 47763f5e chunks (watcher task, second init, message_start announce, origin: task-notification result). It drives the full loop end-to-end: replay stream → adapter buffer/announce → session-manager pump → wakeup relay → attach_wakeup dispatch → run minting → attachTurn replay → cross-run background-command completion → follow-up user turn. New fixture step await_provider_wakeup_run awaits daemon-minted runs. Full orchestration-v2 suite green (273 tests; all 69 pre-existing replay fixtures unchanged).
Known follow-ups
- Session idle reaper (30 min) vs long scheduled sleeps (ScheduleWakeup clamps to 60 min) — a session could be reaped mid-sleep.
- Superseded wakeup buffers replay only task bookkeeping; the dropped wakeup turn's content is lost for that round (logged).
OrchestrationV2ProviderTurnhas nowaitingstatus literal — held-open turns read asrunning; consider addingwaitingfor honest UI during sleeps.- UI: render
inputIntent: "provider_wakeup"turn items as a resume marker instead of a user bubble.
🤖 Generated with Claude Code
I really want this feature, so I thought I’d help out by testing it. So far in testing it for an hour I haven’t had any major issues.
I found several small things that I noticed. Feel free to use/ignore at your own discretion:
What I noticed A queued message is both shown above the input box but also in the chat history. This confused me briefly at first. Because I thought the message was already sent directly.
Really like the interrupt UI. Maybe a bit harsh of a harsh red color. Feels like “Interrupt requested -> Run interrupted” is doubled up.
“Running” is not distinct and different copy than the sidebar “Working”. Would it make sense to harmonize those UIs? Currently it is hard to see at a glance which ones are running. Also it kept in "Running" even though the agents were done.

I didn’t see a way to see which model is being used for the subagents. This is also annoying in Cursor, so would be nice plus if you get it right. This is relevant because Fable is expensive and I don’t really want the subagents to be Fable either. It is nice to easily see if my CLAUDE.md is working correctly.
The lineage UI is confusing to me. When going back the ‘action’ icon is on the left. But when going into a child it is on the right. Also took me a while to notice the muted ‘this is a fork’ icon:

Had a bug where the tool calls were not in the correct location:
Default view
After opening "Worked for 2m 7s"
I've also been doing work on this, especially with Claude 5 and GPT 5.6 models heavily using sub-agents
I'm thinking about adding a toggle to the sidebar to enable or disable viewing sub-agents from the sidebar.
The work here on delegate_task and create_thread are huge wins for my workflow as well. I've got some in-flight work integrating Orchestrator V2 into the mobile app and it's honestly incredible.
Thanks @juliusmarminge. I'll get a few smaller PRs opened against this PR. I'll put up my work on the mobile app but it's probably going to need rebasing once everything lands.
Approvability
Verdict: Not approved
Macroscope's review found this PR not approvable — This is a large production orchestration replacement, not a bounded additive change: it introduces new persistence, provider execution, MCP workflows, checkpoint/rollback behavior, and web/mobile/native integration across 2,027 files. The unresolved review set also identifies material security, lifecycle, data-consistency, and runtime risks, while the PR changes Macroscope configuration and product defaults.
Not approved because:
- 452 blocking correctness issues found at or above your repo's Minimum Blocking Severity
Adjust the Minimum Blocking Severity for this repo — including turning it Off — in Settings. You can add or adjust custom eligibility rules. Learn more.
Scheduled task reports success while its new-thread launch fails in background
Tested on aec85c546e597dbcf78db81b134e7438d9a5ada3 with a scheduled task configured to create a new worktree. Reproduced twice with fresh threads.
Observed
The scheduled-task record ends with lastRunStatus: succeeded, but the generated thread has ordinal 1 failed before provider start:
Workspace preparation failed during generate metadata:
Text generation failed in generateBranchName: Failed to write temp file
ENOENT: no such file or directory, open
/tmp/t3code-codex-schema-208069-6MZJpS/919af017300b
The first reproduction used a custom TMPDIR; I restarted the desktop/server with TMPDIR=/tmp and confirmed the active server process inherited it. The second reproduction failed identically, so this is not caused by that local temp configuration, permissions, or available space.
Status propagation
ScheduledTaskService.runTask treats threadLaunch.launch(...) returning as completion and immediately derives lastRunStatus from that Exit. ThreadLaunchService.launch returns successfully after schedulePreparation(...) forks prepareInBackground into preparationScope. When generateBranchName later fails, the prepared run/thread is marked failed, but that failure cannot update the already-completed scheduled-task run.
This creates two user-visible problems:
- A recoverable branch-name metadata failure prevents the scheduled task from starting at all.
- The scheduled task still reports success because it tracks dispatch rather than background preparation outcome.
Local workaround confirmed from the launch conditions: choose Use the project checkout or Use a specific checkout; both bypass the implicit worktree branch-name generation path. New-worktree scheduled tasks remain broken in this environment.
Suggested direction: await a preparation receipt/outcome before completing the scheduled-task run, and either fall back to fallbackBranchName(threadId) when branch-name generation fails or otherwise make metadata failure non-fatal.
@macroscope-app review
Manual reviews triggered for commit 9fe8044:
All prior checks · these links stay valid even if you push more commits.
Code review has been triggered and is in progress. Results will be posted as check runs when complete.
[claude]
Independent verification: this branch fixes #4198 (idle reaper vs. background work)
Adding a tested-on-sha data point since #4198 is in the high-confidence closes list.
Real-world impact of the bug (0.0.31, macOS)
Forensics on one long-lived thread in my production state.sqlite: over ~18 h, the provider session was stopped and resumed 5 times (orchestration_events: thread.session-set status=stopped → later provider.operation:start-session with resume_cursor.source: "persisted"). Each time, every process-local watcher/poller died with the session while the detached work it was watching (Codex CLI jobs, k8s jobs) kept running and completed fine — the next turn just showed "No completion record was found for background agent…" and the agent had to manually rediscover results by job id. Sessions that never crossed a stop/resume boundary completed background work cleanly, which matches the reaper being the trigger.
Code-level verification at f0e1196
ProviderSessionReaper(all three files) is removed.orchestration-v2/ProviderSessionManager.tskeeps the 30-min idle release (DEFAULT_IDLE_TIMEOUT_MS) butreleaseIfStillIdlenow probes the adapter'shasPendingBackgroundWorkfirst; pending work defers release (idle-release-deferred), re-checked each idle window, bounded byDEFAULT_MAX_IDLE_PIN_MS(4 h →idle-release-pin-expired).ClaudeAdapterV2pins on exactly the states that were lost before: pending background tasks per native thread,runningsubagents, and undrained wake buffers;hasPendingBackgroundWorkForThreadgates the root-run stop path inRunExecutionService.
Test run (macOS arm64, node 26, pnpm 11.10.0, sha f0e1196)
vp test run src/orchestration-v2/ProviderSessionManager.test.ts → 25/25 passed
vp test run src/orchestration-v2/ProviderRuntimeRecoveryService*.test.ts → 10/10 passed
incl. the pin-specific cases: defers idle release while background work is pending, releases pinned idle sessions once the pin cap expires, does not apply a stale idle pin to a replacement session.
One note
The 4 h maxIdlePinMs cap means a background job longer than 4 h with zero foreground activity still gets released mid-run. That's a sane bound, but worth a line in the docs (and the idle-release-pin-expired warning is the right breadcrumb). From my side, this branch resolves the failure mode in #4198. 🚀
Thread transfer impact
✅ Thread transfer remains within every enforced ceiling.
⚠️ The thread fixture changed, so impact percentages are not directly comparable to the
mainbaseline.
| Provider | Metric | Main baseline | This PR | Impact | PR ceiling | |
|---|---|---|---|---|---|---|
| Codex | Total thread wire | — | 4.9 KiB | — | 6.8 KiB | ✅ |
| Codex | Thread snapshot wire | — | 3.7 KiB | — | 4.9 KiB | ✅ |
| Codex | Live turn WebSocket wire | — | 1.1 KiB | — | 2.0 KiB | ✅ |
| Codex | Live turn WebSocket decoded | — | 20.4 KiB | — | 29.3 KiB | ✅ |
| Codex | Live turn messages | — | 1 | — | 8 | ✅ |
| Claude | Total thread wire | — | 4.9 KiB | — | 6.8 KiB | ✅ |
| Claude | Thread snapshot wire | — | 3.7 KiB | — | 4.9 KiB | ✅ |
| Claude | Live turn WebSocket wire | — | 1.2 KiB | — | 2.0 KiB | ✅ |
| Claude | Live turn WebSocket decoded | — | 20.8 KiB | — | 29.3 KiB | ✅ |
| Claude | Live turn messages | — | 2 | — | 8 | ✅ |
Baseline: e0db2a5 · PR result: b37fcea · Source CI: success
Scenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
- Codex decoded thread snapshot: 106.1 KiB
- Claude decoded thread snapshot: 106.4 KiB
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.
@juliusmarminge Based on communications I've seen on twitter and elsewhere, it seems that this branch is, in some sense "the future" of t3code. I'm wondering why, then, it is kept in a constant state of conflict with main. Presumably, the two will have to be reconciled, at some point, right?
As someone who maintains a somewhat substantial set of patches on top of upstream t3code, its a bit difficult to know how to proceed with maintaining these. I don't mind not getting any of my stuff merged ever, but it would be nice to understand roughly where things are headed with this branch, because a lot of the patches that I have touch the surface of what is going on here, and its difficult to know what exactly I should be tracking...
Hey, just came across an issue with scheduled tasks for remote projects. The UI lets me select a project from another environment, but the task is created and executed in the local environment. Since it only stores the projectId, the local server tries to find the remote project in its own database, and the run fails with Project not found. I think the task should be routed to the selected project’s environment, or the project picker should only show projects from the environment where the task will run.
Is this pr actually just a stress test of github's pull request page? love to see +181,657 -85,511. There's really no way any of this could have been done more incrementally?
Is this pr actually just a stress test of github's pull request page? love to see +181,657 -85,511. There's really no way any of this could have been done more incrementally?
Stacked PRs would be a good fit. Maybe we could have stress tested stacked PRs as well.
Is this pr actually just a stress test of github's pull request page? love to see +181,657 -85,511. There's really no way any of this could have been done more incrementally?
Julius contributed :)
@guinnessworldrecords