From d7bbc6e61359d5c2141129ba6b1d34326a91f732 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 18 May 2026 00:06:09 +0100 Subject: [PATCH] Extract thread archive routes --- notes/fresh-workspace-handoff.md | 1 + state/ledgers.msgpack | Bin 124442 -> 124833 bytes state/map.yaml | 10 +- .../app-server/src/codex_message_processor.rs | 1 + .../thread_admin_routes.rs | 218 ----------------- .../thread_archive_routes.rs | 221 ++++++++++++++++++ 6 files changed, 227 insertions(+), 224 deletions(-) create mode 100644 vendor/codex/codex-rs/app-server/src/codex_message_processor/thread_archive_routes.rs diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index ed147e5d..c0952b81 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -49,6 +49,7 @@ remembers doctrine; the branch remembers the blade. - Review-start orchestration now lives in `codex_message_processor/review_routes.rs`; review target normalization is unit-tested at the route module boundary. - Model/catalog routes now live in `codex_message_processor/catalog_routes.rs`: model list, collaboration-mode list, experimental feature list, and mock experimental method. The root processor is about 6,738 lines. - Thread administrative mutation routes now live in `codex_message_processor/thread_admin_routes.rs`: archive/unarchive, elicitation counters, set-name, memory mode, memory reset, metadata update, rollback, compact, background terminal cleanup, shell command submission, and guardian approval. The root processor is about 5,750 lines. +- Archive/unarchive now live in `codex_message_processor/thread_archive_routes.rs`; that module owns durable archive state transitions, spawned-descendant handling, archive-time subscription cleanup, unarchive projection, and archive notifications. The focused `thread_archive` and `thread_unarchive` integration suites pass. - Thread read/list projection routes now live in `codex_message_processor/thread_read_routes.rs`: persisted/live thread listing, loaded-thread listing, `thread/read`, read-list filter normalization/tests, Epiphany state attachment for reads, rollout turn paging, and read-side rollout field hydration. - Thread-store rollout-path reads are now an explicit `ThreadStore::read_thread_by_rollout_path` capability with typed params. App-server read routes no longer downcast `Arc` to `LocalThreadStore`; local and remote stores define the capability/rejection boundary, and the local rollout-path read test exercises the trait method. - Thread resume/fork orchestration has been split by lifecycle contract. `thread_resume_routes.rs` owns cold resume from history/rollout plus persisted resume metadata; `running_thread_resume_routes.rs` owns rejoining already loaded threads through listener replay; `thread_fork_routes.rs` owns new-thread materialization from a source rollout. The root processor is about 1,012 lines and mostly owns JSON-RPC dispatch, shared construction/error helpers, and shutdown lifecycle. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index c3dde71393d9950bf64b5f374737507efdf67b3a..ee69f5e25c5bac70d3a16a49a8effe5592bc4365 100644 GIT binary patch delta 389 zcmZ9Ize)o^5XM;r0~S8RfY@DPa*_yXEwuFy7B*qCJGmRV%r3io(Jq3GrIiO(`Urv` zLLNczB?7*MxQU4Y%b9QHH{UmpAGPPt+Wq$0SN5{=AjI+QM7&LeIGR>>hhnRGnu?9} zcDG%%IwBb#oZ5l{D5LQjq_uUAZiEh`Q#p+g%oU^aIoa;AwOjI19GVeo7&tS8kUNyR zC-soH=S&&U1932a!Y^+jB|zR3GSHYa(4~|80+)OUPO_&!hJ6AWy+YQK1LTr*L7XMv z%f45R>}&>9fs#v`z{;0(<`UIRO&~4-n?M6n@m^#$;2d2nqjM#z?{~3zVvExMGdkZ} lgj#`PBFx;J6HQPI*|>R4n`x)sY}Z@+XX#$I8DHDE_yOX0kt_fJ delta 49 zcmZ2@o_*FC_6f>NPakYloyN!*(7cCn`yNI{k0)XcTZ{~h%ybP*bq&o!jEt=e46O_; Fq5$6B5Q+c* diff --git a/state/map.yaml b/state/map.yaml index 97b3ebdf..6335f07f 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -286,11 +286,9 @@ rejected_paths: current_status: summary: The Codex starvation pass has five typing receipts, fifty-six processor/foundation cuts, a real physical extraction in `epiphany-codex-bridge`, a root `epiphany-state-model` crate for durable Epiphany state, a source-grounded Codex auth spine inventory, the native `epiphany-openai-adapter` document boundary, a buildable Codex auth/model wrapper in `epiphany-openai-codex-spine`, the first native runtime caller in `epiphany-openai-runtime`, native heartbeat launch planning/job opening in `epiphany-core`, native state-update contract/validation/application in `epiphany-core`, native exact retrieval path matching in `epiphany-core`, and the route-facing mutation/view/coordinator projection services in `epiphany-codex-bridge`. `codex-protocol` no longer defines the durable `Epiphany*` state structs; it re-exports the native model for legacy rollout/API compatibility while `epiphany-core` imports the native model directly. `epiphany-core` now has no direct vendored Codex dependency: pressure derivation accepts native `EpiphanyTokenUsageSnapshot`, Codex rollout replay moved to `codex-core::epiphany_rollout`, and exact retrieval search uses Epiphany-owned workspace walking/path scoring instead of `codex-file-search`. The bridge owns Codex-facing Epiphany adapters for scene, jobs, context/planning/graph query, retrieval/indexing projection, result projection, runtime-spine result adaptation, launch/prompt doctrine, mutation document mechanics, mutation service update/promote/role-accept/reorient-accept/role-launch/reorient-launch/job-launch/job-interrupt application, live-state projection, pressure/pre-compaction rendering, freshness/reorientation projection, CRRC/coordinator/role-board projection, watcher invalidation adaptation, full `thread/epiphany/view` response construction, freshness/context/graph-query response construction, role/reorient result response construction, distill/propose patch-response construction, coordinator status/view construction, and acceptance/evidence signal helpers. Vendored app-server no longer retains root Epiphany modules; `codex_message_processor.rs` still contains route dispatch, JSON-RPC response shaping, watcher registration/snapshotting calls, and notification emission, but its root no longer imports the evacuated Epiphany policy/protocol registry or owns the watcher invalidation manager. Codex product surfaces for apps, skills, plugins, marketplace, and external agent config import are cut from the live app-server/protocol path: list routes return empty lists only where compatibility shells still exist, mutation/detail routes report disabled where they survive, `externalAgentConfig/*` routes and import-completed notification are gone, helper/import modules and stale implementation-shape tests were deleted, runtime feature enablement no longer supports `apps` or `plugins`, config writes no longer emit plugin-toggle analytics, plugin/skill cache invalidation on config writes is gone, plugin startup warmups and app-list refreshes were removed, and app-server no longer directly depends on `codex-plugin`, `codex-chatgpt`, or `codex-core-plugins`. `Config::to_mcp_config` now keeps user-declared MCP servers but no longer accepts `PluginsManager`, folds plugin MCP servers into the runtime, enables Codex apps, enables skill MCP dependency install, or advertises plugin capability summaries; `TurnContext::apps_enabled()` now returns false so model turns cannot awaken Codex Apps through ChatGPT auth or feature flags; session startup and per-turn context no longer load skills, turns receive an empty `SkillLoadOutcome`, internal `Op::ListSkills` is gone from `codex-protocol` / `codex-core` / TUI command routing, the Codex skill watcher has been collapsed to a no-op marker with no file watcher, skill-root registration, cache-clear task, or `SkillsUpdateAvailable` session listener, model turns no longer run skill mention collection, skill env-var prompts, skill MCP dependency installation, skill instruction injection, or implicit skill invocation analytics from shell tools, and the turn prompt/router path no longer loads plugin/app capability summaries, injects available-skill/available-plugin/plugin instruction fragments, parses plugin/app mentions, records app/plugin invocation telemetry, or filters MCP tools through Codex app connectors. Skill mutation/list/notification is gone from the app-server edge too: `skills/list`, `skills/config/write`, `skills/changed`, `Op::ListSkills`, `EventMsg::ListSkillsResponse`, `EventMsg::SkillsUpdateAvailable`, the app-server handlers, TUI slash/startup/list/manage-skill surfaces, generated schema entries, core skill-list suite, and fake live-reload/developer-message tests were deleted. Skill mention plumbing is also gone from the live TUI/protocol edge: no `UserInput::Skill` variant, app-server schema branch, TUI skill popup, `skills_all` cache, composer `set_skill_mentions`, skill mention insertion, `skill://` / `SKILL.md` history decoding, or stale skill popup snapshot remains. The `codex-core-skills` crate, core `skills` re-export shim, no-op `skills_watcher`, session `SkillsManager` service, and per-turn `TurnSkillsContext` are deleted; core/protocol no longer keep legacy `` or `` prompt compatibility, memory usage classification, snapshot normalization, or cleanup paths. Remaining product-shaped skill residue is also cut from memory templates, app-server docs/tests/warnings, TUI tooltips/placeholders/warnings/comments, app-server v1 docs, agent-tool schema text, stale `UserInput::Skill` test arms, and obsolete feature flags/schema entries. App-instruction prompt compatibility is cut too: no `APPS_INSTRUCTIONS` protocol constants, no `` snapshot canonicalization, and MCP fixture tests now use neutral `demo_mcp` / `calendar_mcp` names instead of `codex_apps` / `/api/codex/apps` branding. The TUI app connector product path is also deleted: no `/apps` slash command, app-link view, connector AppEvent variants, app connector cache/popup/refresh loop, app mention insertion, `app://` mention codec support, stale app-popup tests, or TUI browser-opening shim remains. The `app/list` route and `app/list/updated` notification are gone from app-server protocol, generated schemas, app-server dispatch, test helpers, and docs; `AppInfo`/app-list metadata schema structs are deleted; the orphaned `codex-connectors` crate and `core::connectors` shim are deleted from the workspace; Codex app analytics no longer tracks `codex_app_mentioned` / `codex_app_used` facts, events, reducer arms, client APIs, or dedupe cache state; `[apps.*]`, `Feature::Apps`, `include_apps_instructions`, app config/read schemas, app managed requirements, app prompt tests, and app file-MCP tests are gone; `Feature::Plugins`, `Feature::RemotePlugin`, `plugin://` structured mentions, plugin instruction tags, and stale plugin popup snapshots are gone too; `[plugins]` / `[marketplaces]`, `PluginConfig`, `MarketplaceConfig`, marketplace edit helpers, stale plugin/external-agent README route claims, and generated schema entries are removed from config; and the bundled `codex-skills` sample-skill crate plus embedded imagegen/openai-docs/plugin-creator/skill-creator/skill-installer payloads are deleted from the workspace. The vendored `vendor/codex/sdk` subtree is deleted as non-spine app-server client/release scaffolding, including stale generated Python SDK route types for removed product surfaces; the root pnpm workspace no longer lists `sdk/typescript`. Live MCP tool approval is named `McpToolApproval`, not `AppToolApproval`, and remains under MCP server config; live structured user-input mentions are MCP-shaped only. `codex_message_processor.rs` is about 1,009 lines after route/lifecycle/projection/resume-helper/config-helper extraction; root `message_processor.rs` is about 1,292 lines after the external-agent/config-product cuts; `epiphany_read_routes.rs` is about 579 lines after the full view and read-response extractions; `epiphany_mutation_routes.rs` is about 694 lines after route-load/notification helper cuts and product-surface starvation; the old vendored `epiphany_state_helpers.rs` rollout-state loader is deleted and its remaining function lives in `epiphany-codex-bridge::state`; and `codex_thread.rs` is about 1,425 lines after state-update law moved native. `epiphany-openai-adapter` defines CultCache `DatabaseEntry` request/event/receipt/auth-status documents with no Codex app-server or generic JSON dependency. `epiphany-openai-codex-spine` owns the native OpenAI model transport path: it exposes `default_codex_home` and `auth_manager`, projects `epiphany-openai-auth-spine` `AuthManager` / `CodexAuth` into typed `EpiphanyOpenAiAdapterStatus`, builds a local serializable OpenAI Responses request body instead of Codex protocol request/item/config types, opens HTTP Responses streams through `codex-client`, parses Responses SSE frames into typed stream events and receipts, and no longer directly or transitively depends on Codex's Responses client, model-provider stack, `codex-protocol`, `codex-api`, `codex-model-provider`, or `codex-model-provider-info`; it intentionally reaches retained vendored `codex-login` only through `epiphany-openai-auth-spine`. Auth identity, credential storage, and ChatGPT token refresh remain owned by the Codex-compatible auth organ; external bearer command auth and agent identity remain retained Codex auth capabilities to expose only if a typed Epiphany surface needs them. `epiphany-openai-runtime` no longer depends directly on `codex-login`; it writes OpenAI status/request/stream-event/receipt records plus runtime sessions/jobs/results/events into `epiphany-core::runtime_spine_cache`, can emit the assistant text artifact for legacy result consumers, is now the default executor for startup-only repo birth specialists, and now has `run-worker` to load a durable `EpiphanyRuntimeWorkerLaunchRequest`, call the typed OpenAI runtime through the spine, persist typed `EpiphanyRuntimeRoleWorkerResult` / `EpiphanyRuntimeReorientWorkerResult` documents, and complete the original heartbeat/specialist runtime job without Codex worker execution; `codex exec` survives only as explicit fallback in repo-birth startup. `epiphany-mvp-coordinator` now invokes `epiphany-openai-runtime run-worker` for launched runtime job ids and no longer creates a second coordinator-owned shadow runtime job/result as a compensator. `epiphany-core::plan_runtime_spine_heartbeat_launch` validates launch contracts/conflicts and projects durable job bindings/runtime links; `epiphany-core::open_runtime_spine_heartbeat_job` owns the initialize-runtime/ensure-session/create-job sequence and now persists `EpiphanyRuntimeWorkerLaunchRequest` CultCache records keyed by runtime job id, with indexed kind/contract fields plus MessagePack-encoded typed launch documents instead of discarding work intent after queue receipt creation; `roleResult` and `reorientResult` now require typed worker result documents; generic job summaries are lifecycle receipts, not reviewable findings; `epiphany-core::EpiphanyStateUpdate`, `epiphany_state_update_validation_errors`, and `apply_epiphany_state_update` own state-update document shape and mutation law while `codex-core` calls them for compatibility. Vendored `CodexThread::epiphany_launch_job` is now mostly revision check, persistence validation, launch request handoff, and rollout/session writeback for the compatibility route. Vendored `codex-core` no longer has `epiphany_distillation`, `epiphany_promotion`, `epiphany_proposal`, or `epiphany_retrieval` husk modules; it re-exports native surfaces from `epiphany-core` directly, and now owns only the real Codex rollout adapter because it is a host seam. `epiphany-runtime-spine` advertises OpenAI adapter status/model-request/stream-event/receipt CultNet schemas and mutation contracts, so the native caller now has a real storage route instead of only JSON-RPC. MCP itself is correctly JSON at its protocol edge; the target is typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON. The current OpenAI request path no longer pulls `codex-api`; `codex-login` remains deliberately sealed behind `epiphany-openai-auth-spine`, and the next spine decision is another Epiphany-in-vendor evacuation surface unless a concrete typed auth-status/runtime need requires exposing external bearer or agent-identity auth. latest_cut: > - Thread fork and running-thread resume replay were split out of the cold - resume module. `thread_fork_routes.rs` owns new-thread materialization from - historical rollout state, `thread_resume_routes.rs` owns cold resume from - history/rollout plus persisted resume metadata, and - `running_thread_resume_routes.rs` owns rejoining an already loaded thread - through the listener replay contract. Focused fork and running-resume + Thread archive/unarchive were split out of the miscellaneous admin module. + `thread_archive_routes.rs` owns durable archive state transitions, + spawned-descendant handling, archive-time subscription cleanup, unarchive + projection, and archive notifications. Focused archive/unarchive integration tests pass. next_action: Continue the Codex starvation campaign at the next Epiphany-in-vendor evacuation surface; keep vendored Codex code as host routing/lifecycle glue only, preserve retained `codex-login` auth ownership, and prefer cuts that expose testable ownership boundaries over line-count theater. diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs index d0b72dbf..1bd31ba8 100644 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs @@ -10,6 +10,7 @@ mod realtime_routes; mod review_routes; mod running_thread_resume_routes; mod thread_admin_routes; +mod thread_archive_routes; mod thread_config; mod thread_fork_routes; mod thread_projection; diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor/thread_admin_routes.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor/thread_admin_routes.rs index e3f242bd..281a9ee5 100644 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor/thread_admin_routes.rs +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor/thread_admin_routes.rs @@ -1,156 +1,6 @@ use super::*; impl CodexMessageProcessor { - pub(super) async fn thread_archive( - &self, - request_id: ConnectionRequestId, - params: ThreadArchiveParams, - ) { - let thread_id = match ThreadId::from_string(¶ms.thread_id) { - Ok(id) => id, - Err(err) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("invalid thread id: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - let mut thread_ids = vec![thread_id]; - if let Some(state_db_ctx) = get_state_db(&self.config).await { - let descendants = match state_db_ctx.list_thread_spawn_descendants(thread_id).await { - Ok(descendants) => descendants, - Err(err) => { - self.outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!( - "failed to list spawned descendants for thread id {thread_id}: {err}" - ), - data: None, - }, - ) - .await; - return; - } - }; - let mut seen = HashSet::from([thread_id]); - for descendant_id in descendants { - if seen.insert(descendant_id) { - thread_ids.push(descendant_id); - } - } - } - - let mut archive_thread_ids = Vec::new(); - match self - .thread_store - .read_thread(StoreReadThreadParams { - thread_id, - include_archived: false, - include_history: false, - }) - .await - { - Ok(thread) => { - if thread.archived_at.is_none() { - archive_thread_ids.push(thread_id); - } - } - Err(err) => { - self.outgoing - .send_error(request_id, thread_store_archive_error("archive", err)) - .await; - return; - } - } - for descendant_thread_id in thread_ids.into_iter().skip(1) { - match self - .thread_store - .read_thread(StoreReadThreadParams { - thread_id: descendant_thread_id, - include_archived: true, - include_history: false, - }) - .await - { - Ok(thread) => { - if thread.archived_at.is_none() { - archive_thread_ids.push(descendant_thread_id); - } - } - Err(err) => { - warn!( - "failed to read spawned descendant thread {descendant_thread_id} while archiving {thread_id}: {err}" - ); - } - } - } - - let mut archived_thread_ids = Vec::new(); - let Some((parent_thread_id, descendant_thread_ids)) = archive_thread_ids.split_first() - else { - self.outgoing - .send_response(request_id, ThreadArchiveResponse {}) - .await; - return; - }; - - self.prepare_thread_for_archive(*parent_thread_id).await; - match self - .thread_store - .archive_thread(StoreArchiveThreadParams { - thread_id: *parent_thread_id, - }) - .await - { - Ok(()) => { - archived_thread_ids.push(parent_thread_id.to_string()); - } - Err(err) => { - self.outgoing - .send_error(request_id, thread_store_archive_error("archive", err)) - .await; - return; - } - } - - for descendant_thread_id in descendant_thread_ids.iter().rev().copied() { - self.prepare_thread_for_archive(descendant_thread_id).await; - match self - .thread_store - .archive_thread(StoreArchiveThreadParams { - thread_id: descendant_thread_id, - }) - .await - { - Ok(()) => { - archived_thread_ids.push(descendant_thread_id.to_string()); - } - Err(err) => { - warn!( - "failed to archive spawned descendant thread {descendant_thread_id} while archiving {thread_id}: {err}" - ); - } - } - } - - self.outgoing - .send_response(request_id, ThreadArchiveResponse {}) - .await; - for thread_id in archived_thread_ids { - let notification = ThreadArchivedNotification { thread_id }; - self.outgoing - .send_server_notification(ServerNotification::ThreadArchived(notification)) - .await; - } - } - pub(super) async fn thread_increment_elicitation( &self, request_id: ConnectionRequestId, @@ -701,74 +551,6 @@ impl CodexMessageProcessor { } } - pub(super) async fn thread_unarchive( - &self, - request_id: ConnectionRequestId, - params: ThreadUnarchiveParams, - ) { - let thread_id = match ThreadId::from_string(¶ms.thread_id) { - Ok(id) => id, - Err(err) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("invalid thread id: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - let fallback_provider = self.config.model_provider_id.clone(); - let result = self - .thread_store - .unarchive_thread(StoreArchiveThreadParams { thread_id }) - .await - .map_err(|err| thread_store_archive_error("unarchive", err)) - .and_then(|stored_thread| { - summary_from_stored_thread(stored_thread, fallback_provider.as_str()) - .map(|summary| summary_to_thread(summary, &self.config.cwd)) - .ok_or_else(|| JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to read unarchived thread {thread_id}"), - data: None, - }) - }); - - match result { - Ok(mut thread) => { - thread.status = resolve_thread_status( - self.thread_watch_manager - .loaded_status_for_thread(&thread.id) - .await, - /*has_in_progress_turn*/ false, - ); - self.attach_thread_name(thread_id, &mut thread).await; - if let Some(rollout_path) = thread.path.as_deref() { - match load_epiphany_state_from_rollout_path(rollout_path).await { - Ok(epiphany_state) => { - thread.epiphany_state = epiphany_state; - } - Err(message) => { - self.send_internal_error(request_id, message).await; - return; - } - } - } - let thread_id = thread.id.clone(); - let response = ThreadUnarchiveResponse { thread }; - self.outgoing.send_response(request_id, response).await; - let notification = ThreadUnarchivedNotification { thread_id }; - self.outgoing - .send_server_notification(ServerNotification::ThreadUnarchived(notification)) - .await; - } - Err(err) => { - self.outgoing.send_error(request_id, err).await; - } - } - } - pub(super) async fn thread_rollback( &self, request_id: ConnectionRequestId, diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor/thread_archive_routes.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor/thread_archive_routes.rs new file mode 100644 index 00000000..bc943dc2 --- /dev/null +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor/thread_archive_routes.rs @@ -0,0 +1,221 @@ +use super::*; + +impl CodexMessageProcessor { + pub(super) async fn thread_archive( + &self, + request_id: ConnectionRequestId, + params: ThreadArchiveParams, + ) { + let thread_id = match ThreadId::from_string(¶ms.thread_id) { + Ok(id) => id, + Err(err) => { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!("invalid thread id: {err}"), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + } + }; + + let mut thread_ids = vec![thread_id]; + if let Some(state_db_ctx) = get_state_db(&self.config).await { + let descendants = match state_db_ctx.list_thread_spawn_descendants(thread_id).await { + Ok(descendants) => descendants, + Err(err) => { + self.outgoing + .send_error( + request_id, + JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: format!( + "failed to list spawned descendants for thread id {thread_id}: {err}" + ), + data: None, + }, + ) + .await; + return; + } + }; + let mut seen = HashSet::from([thread_id]); + for descendant_id in descendants { + if seen.insert(descendant_id) { + thread_ids.push(descendant_id); + } + } + } + + let mut archive_thread_ids = Vec::new(); + match self + .thread_store + .read_thread(StoreReadThreadParams { + thread_id, + include_archived: false, + include_history: false, + }) + .await + { + Ok(thread) => { + if thread.archived_at.is_none() { + archive_thread_ids.push(thread_id); + } + } + Err(err) => { + self.outgoing + .send_error(request_id, thread_store_archive_error("archive", err)) + .await; + return; + } + } + for descendant_thread_id in thread_ids.into_iter().skip(1) { + match self + .thread_store + .read_thread(StoreReadThreadParams { + thread_id: descendant_thread_id, + include_archived: true, + include_history: false, + }) + .await + { + Ok(thread) => { + if thread.archived_at.is_none() { + archive_thread_ids.push(descendant_thread_id); + } + } + Err(err) => { + warn!( + "failed to read spawned descendant thread {descendant_thread_id} while archiving {thread_id}: {err}" + ); + } + } + } + + let mut archived_thread_ids = Vec::new(); + let Some((parent_thread_id, descendant_thread_ids)) = archive_thread_ids.split_first() + else { + self.outgoing + .send_response(request_id, ThreadArchiveResponse {}) + .await; + return; + }; + + self.prepare_thread_for_archive(*parent_thread_id).await; + match self + .thread_store + .archive_thread(StoreArchiveThreadParams { + thread_id: *parent_thread_id, + }) + .await + { + Ok(()) => { + archived_thread_ids.push(parent_thread_id.to_string()); + } + Err(err) => { + self.outgoing + .send_error(request_id, thread_store_archive_error("archive", err)) + .await; + return; + } + } + + for descendant_thread_id in descendant_thread_ids.iter().rev().copied() { + self.prepare_thread_for_archive(descendant_thread_id).await; + match self + .thread_store + .archive_thread(StoreArchiveThreadParams { + thread_id: descendant_thread_id, + }) + .await + { + Ok(()) => { + archived_thread_ids.push(descendant_thread_id.to_string()); + } + Err(err) => { + warn!( + "failed to archive spawned descendant thread {descendant_thread_id} while archiving {thread_id}: {err}" + ); + } + } + } + + self.outgoing + .send_response(request_id, ThreadArchiveResponse {}) + .await; + for thread_id in archived_thread_ids { + let notification = ThreadArchivedNotification { thread_id }; + self.outgoing + .send_server_notification(ServerNotification::ThreadArchived(notification)) + .await; + } + } + + pub(super) async fn thread_unarchive( + &self, + request_id: ConnectionRequestId, + params: ThreadUnarchiveParams, + ) { + let thread_id = match ThreadId::from_string(¶ms.thread_id) { + Ok(id) => id, + Err(err) => { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!("invalid thread id: {err}"), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + } + }; + + let fallback_provider = self.config.model_provider_id.clone(); + let result = self + .thread_store + .unarchive_thread(StoreArchiveThreadParams { thread_id }) + .await + .map_err(|err| thread_store_archive_error("unarchive", err)) + .and_then(|stored_thread| { + summary_from_stored_thread(stored_thread, fallback_provider.as_str()) + .map(|summary| summary_to_thread(summary, &self.config.cwd)) + .ok_or_else(|| JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: format!("failed to read unarchived thread {thread_id}"), + data: None, + }) + }); + + match result { + Ok(mut thread) => { + thread.status = resolve_thread_status( + self.thread_watch_manager + .loaded_status_for_thread(&thread.id) + .await, + /*has_in_progress_turn*/ false, + ); + self.attach_thread_name(thread_id, &mut thread).await; + if let Some(rollout_path) = thread.path.as_deref() { + match load_epiphany_state_from_rollout_path(rollout_path).await { + Ok(epiphany_state) => { + thread.epiphany_state = epiphany_state; + } + Err(message) => { + self.send_internal_error(request_id, message).await; + return; + } + } + } + let thread_id = thread.id.clone(); + let response = ThreadUnarchiveResponse { thread }; + self.outgoing.send_response(request_id, response).await; + let notification = ThreadUnarchivedNotification { thread_id }; + self.outgoing + .send_server_notification(ServerNotification::ThreadUnarchived(notification)) + .await; + } + Err(err) => { + self.outgoing.send_error(request_id, err).await; + } + } + } +}