From 8c350889deae423307c11a6023dc95e611c0f976 Mon Sep 17 00:00:00 2001 From: Bohao Tang Date: Wed, 18 Nov 2026 01:36:49 +0800 Subject: [PATCH 01/15] refactor(storage): extract nexus-session-storage from orchestration --- Cargo.lock | 20 + Cargo.toml | 1 + apps/nexus42/Cargo.toml | 2 + apps/nexus42/src/commands/ops.rs | 10 +- apps/nexus42/tests/ops_inspect_cli.rs | 2 +- .../nexus-agent-host/src/capability/model.rs | 2 +- .../src/local/schedule/http.rs | 2 +- crates/nexus-core/Cargo.toml | 3 + .../nexus-core/src/owner/applied_documents.rs | 2 +- crates/nexus-core/src/owner/handle_ops.rs | 4 +- crates/nexus-core/src/owner/lifecycle.rs | 4 +- crates/nexus-core/src/owner/production.rs | 4 +- .../nexus-core/tests/execution_lifecycle.rs | 64 +-- .../tests/retained_execution_contracts.rs | 25 +- crates/nexus-core/tests/workspace_commit.rs | 2 +- crates/nexus-execution/Cargo.toml | 1 + crates/nexus-execution/src/prompt_executor.rs | 45 +- crates/nexus-execution/src/run_events.rs | 2 +- crates/nexus-execution/src/workflow.rs | 388 +++++++++--------- crates/nexus-orchestration/Cargo.toml | 3 + crates/nexus-orchestration/src/auto_chain.rs | 12 +- .../nexus-orchestration/src/capability/mod.rs | 2 +- crates/nexus-orchestration/src/engine.rs | 382 ++++++++--------- crates/nexus-orchestration/src/lib.rs | 7 - .../nexus-orchestration/src/preset_runtime.rs | 4 +- .../nexus-orchestration/src/resume_rules.rs | 8 +- .../src/schedule/supervisor.rs | 14 +- .../tests/research_supervisor_e2e.rs | 2 +- .../tests/sqlite_storage_roundtrip.rs | 2 +- .../tests/system_preset_e2e.rs | 4 +- .../tests/workflow_run_state.rs | 85 ++-- crates/nexus-session-storage/Cargo.toml | 24 ++ crates/nexus-session-storage/src/lib.rs | 151 +++++++ .../src/run_state.rs | 2 +- .../src/storage/inspect.rs | 0 .../src/storage/mod.rs | 0 .../src/storage/sqlite.rs | 12 +- 37 files changed, 729 insertions(+), 568 deletions(-) create mode 100644 crates/nexus-session-storage/Cargo.toml create mode 100644 crates/nexus-session-storage/src/lib.rs rename crates/{nexus-orchestration => nexus-session-storage}/src/run_state.rs (99%) rename crates/{nexus-orchestration => nexus-session-storage}/src/storage/inspect.rs (100%) rename crates/{nexus-orchestration => nexus-session-storage}/src/storage/mod.rs (100%) rename crates/{nexus-orchestration => nexus-session-storage}/src/storage/sqlite.rs (99%) diff --git a/Cargo.lock b/Cargo.lock index 13ae2f630..326c0c90a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3762,6 +3762,7 @@ dependencies = [ "nexus-pattern", "nexus-preset", "nexus-provider-ports", + "nexus-session-storage", "nexus-spoke-adapter", "nexus-storage-guard", "nexus-wasm-host", @@ -3876,6 +3877,7 @@ dependencies = [ "nexus-local-db", "nexus-orchestration", "nexus-preset", + "nexus-session-storage", "nix 0.31.3", "parking_lot 0.13.0", "serde", @@ -4060,6 +4062,7 @@ dependencies = [ "nexus-local-db", "nexus-narrative", "nexus-preset", + "nexus-session-storage", "nexus-spoke-adapter", "nexus-wasm-host", "nexus-workflow-ir", @@ -4127,6 +4130,22 @@ dependencies = [ "nexus-contracts", ] +[[package]] +name = "nexus-session-storage" +version = "0.1.0" +dependencies = [ + "async-trait", + "chrono", + "graph-flow", + "nexus-home-layout", + "nexus-local-db", + "nexus-preset", + "serde", + "serde_json", + "sqlx", + "thiserror 2.0.21", +] + [[package]] name = "nexus-spoke-adapter" version = "0.1.0" @@ -4221,6 +4240,7 @@ dependencies = [ "nexus-narrative", "nexus-orchestration", "nexus-preset", + "nexus-session-storage", "nexus-spoke-adapter", "nexus-wasm-host", "nexus-workflow-ir", diff --git a/Cargo.toml b/Cargo.toml index 8ce62d0ab..2e75bdcfa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ members = [ "crates/nexus-pattern", "crates/nexus-preset", "crates/nexus-provider-conformance", + "crates/nexus-session-storage", "crates/nexus-spoke-adapter", "crates/nexus-wasm-host", "crates/nexus-workflow-ir", diff --git a/apps/nexus42/Cargo.toml b/apps/nexus42/Cargo.toml index 82fd4cceb..f4124edda 100644 --- a/apps/nexus42/Cargo.toml +++ b/apps/nexus42/Cargo.toml @@ -94,6 +94,7 @@ nexus-preset = { path = "../../crates/nexus-preset" } # (`nexus_workflow_ir::validate`) alongside the preset facade. nexus-workflow-ir = { path = "../../crates/nexus-workflow-ir" } nexus-orchestration = { path = "../../crates/nexus-orchestration", optional = true } +nexus-session-storage = { path = "../../crates/nexus-session-storage", optional = true } nexus-moment-context-assembly = { path = "../../crates/nexus-moment-context-assembly", optional = true, features = ["cloud-stage"] } nexus-creator-memory = { path = "../../crates/nexus-creator-memory", optional = true } nexus-creator = { path = "../../crates/nexus-creator", optional = true } @@ -252,6 +253,7 @@ cli = [ # nothing (v1.235 work-artifact IR, ADR #485 §7.8). "nexus-core/execution", "dep:nexus-orchestration", + "dep:nexus-session-storage", "dep:nexus-moment-context-assembly", "dep:nexus-creator-memory", "dep:nexus-creator", diff --git a/apps/nexus42/src/commands/ops.rs b/apps/nexus42/src/commands/ops.rs index 96e8d4c05..e01a09944 100644 --- a/apps/nexus42/src/commands/ops.rs +++ b/apps/nexus42/src/commands/ops.rs @@ -52,7 +52,7 @@ use crate::config::CliConfig; use crate::errors::{CliError, Result}; use clap::Subcommand; use nexus_orchestration::resume_rules::{self, RecoveryClass, ResumeClass}; -use nexus_orchestration::storage::{CheckpointRow, CheckpointSummary, SqliteSessionStorage}; +use nexus_session_storage::storage::{CheckpointRow, CheckpointSummary, SqliteSessionStorage}; use serde::Serialize; use serde_json::Value; use std::fmt::Write as _; @@ -315,14 +315,14 @@ async fn inspect_inner(session_id: Option, config: &CliConfig) -> Result /// but does not deserialize as [`RunStateV1`] (e.g. `{"cancel_requested": /// "false"}`) returns `None` just like corrupt bytes, so list and detail /// agree. -fn parse_run_state(bytes: Option<&[u8]>) -> Option { +fn parse_run_state(bytes: Option<&[u8]>) -> Option { let bytes = bytes?; serde_json::from_slice(bytes).ok() } fn descriptor_is_valid(bytes: Option<&[u8]>) -> bool { bytes.is_some_and(|bytes| { - serde_json::from_slice::(bytes).is_ok() + serde_json::from_slice::(bytes).is_ok() }) } @@ -339,7 +339,7 @@ fn descriptor_is_valid(bytes: Option<&[u8]>) -> bool { fn recovery_class_for( execution_version: i64, status: &str, - state: Option<&nexus_orchestration::run_state::RunStateV1>, + state: Option<&nexus_session_storage::run_state::RunStateV1>, descriptor_valid: bool, gate_park_live: bool, ) -> RecoveryClass { @@ -703,7 +703,7 @@ fn frozen_source_reconstructable(bytes: Option<&[u8]>) -> bool { return false; }; let Ok(descriptor) = - serde_json::from_slice::(bytes) + serde_json::from_slice::(bytes) else { return false; }; diff --git a/apps/nexus42/tests/ops_inspect_cli.rs b/apps/nexus42/tests/ops_inspect_cli.rs index 4706861a6..23562ed60 100644 --- a/apps/nexus42/tests/ops_inspect_cli.rs +++ b/apps/nexus42/tests/ops_inspect_cli.rs @@ -14,7 +14,7 @@ //! Run with: `cargo test -p nexus42 --test ops_inspect_cli` use assert_cmd::Command; -use nexus_orchestration::run_state::RunDescriptorV1; +use nexus_session_storage::run_state::RunDescriptorV1; use nexus_preset::source_identity::PresetSourceIdentity; use serde_json::{json, Value}; use std::collections::HashMap; diff --git a/crates/nexus-agent-host/src/capability/model.rs b/crates/nexus-agent-host/src/capability/model.rs index d0fe3badf..5aa1e8372 100644 --- a/crates/nexus-agent-host/src/capability/model.rs +++ b/crates/nexus-agent-host/src/capability/model.rs @@ -582,7 +582,7 @@ pub struct ManagedSessionHandle { /// Opaque owned-process identity (A5) — PID plus process-birth and group. /// /// Never identified by PID alone. Mirrors the durable -/// `nexus_orchestration::run_state::OwnedProcessIdentity` shape so the daemon +/// `nexus_session_storage::run_state::OwnedProcessIdentity` shape so the daemon /// can persist the fingerprint without importing provider crates. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct OwnedProcessIdentity { diff --git a/crates/nexus-contracts/src/local/schedule/http.rs b/crates/nexus-contracts/src/local/schedule/http.rs index f3192a50d..aea702203 100644 --- a/crates/nexus-contracts/src/local/schedule/http.rs +++ b/crates/nexus-contracts/src/local/schedule/http.rs @@ -61,7 +61,7 @@ pub struct AddScheduleRequest { } /// Role → provider binding (A1) — wire form of -/// [`nexus_orchestration::run_state::AgentBinding`]. +/// [`nexus_session_storage::run_state::AgentBinding`]. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AgentBindingDto { /// Provider id. diff --git a/crates/nexus-core/Cargo.toml b/crates/nexus-core/Cargo.toml index 53abbbeeb..55aa26f53 100644 --- a/crates/nexus-core/Cargo.toml +++ b/crates/nexus-core/Cargo.toml @@ -30,6 +30,7 @@ execution = [ # `nexus_connect::peer_tools` directly. "nexus-connect/peer-tools", "dep:nexus-orchestration", + "dep:nexus-session-storage", # The Simulate route is served at this execution edge only: the walk runs in-process, # constructs no executor or provider, and stays out of the default/domain cohort. "nexus-orchestration/simulate", @@ -118,6 +119,7 @@ nexus-creator-memory = { path = "../nexus-creator-memory" } nexus-memory-provider = { path = "../nexus-memory-provider" } nexus-moment-context-assembly = { path = "../nexus-moment-context-assembly" } nexus-orchestration = { path = "../nexus-orchestration", optional = true } +nexus-session-storage = { path = "../nexus-session-storage", optional = true } # Pattern registry reader + the candidate IR the Simulate walk reads. nexus-pattern = { path = "../nexus-pattern" } nexus-workflow-ir = { path = "../nexus-workflow-ir" } @@ -231,6 +233,7 @@ parking_lot = "0.13" # scanner's dependencies. nexus-wasm-host = { path = "../nexus-wasm-host" } nexus-orchestration = { path = "../nexus-orchestration" } +nexus-session-storage = { path = "../nexus-session-storage" } nexus-knowledge = { path = "../nexus-knowledge" } # The WAT compiler named above: the capability/compute target compiles the # runaway module its sandbox-limit cases trap on (the same way diff --git a/crates/nexus-core/src/owner/applied_documents.rs b/crates/nexus-core/src/owner/applied_documents.rs index 22b39e412..47256f0d4 100644 --- a/crates/nexus-core/src/owner/applied_documents.rs +++ b/crates/nexus-core/src/owner/applied_documents.rs @@ -19,7 +19,7 @@ use std::sync::Arc; use async_trait::async_trait; use nexus_execution::admission::{AppliedAdmission, AppliedAdmissionError, AppliedAdmissionPort}; use nexus_orchestration::capability::{AppliedDocument, AppliedDocumentSource}; -use nexus_orchestration::run_state::AppliedRunIdentity; +use nexus_session_storage::run_state::AppliedRunIdentity; use nexus_preset::LoadedPreset; use crate::apply::ApplyLoadRefusal; diff --git a/crates/nexus-core/src/owner/handle_ops.rs b/crates/nexus-core/src/owner/handle_ops.rs index a1b905529..e1907ecb7 100644 --- a/crates/nexus-core/src/owner/handle_ops.rs +++ b/crates/nexus-core/src/owner/handle_ops.rs @@ -1451,7 +1451,7 @@ impl ExecutionHandle { request: &AddScheduleRequest, loaded: Option<&nexus_preset::LoadedPreset>, ) -> CoreResult>> { - use nexus_orchestration::run_state::{AgentBinding, RunDescriptorV1}; + use nexus_session_storage::run_state::{AgentBinding, RunDescriptorV1}; let Some(loaded) = loaded else { // `_system.*`: never admitted, so no descriptor is required. @@ -1777,7 +1777,7 @@ fn failure_reason(row: &SessionRow) -> Option { row.run_state_json .as_deref() .and_then(|blob| { - serde_json::from_slice::(blob).ok() + serde_json::from_slice::(blob).ok() }) .and_then(|state| state.failure) .map(|failure| failure.message) diff --git a/crates/nexus-core/src/owner/lifecycle.rs b/crates/nexus-core/src/owner/lifecycle.rs index 6255f0509..a540eb26d 100644 --- a/crates/nexus-core/src/owner/lifecycle.rs +++ b/crates/nexus-core/src/owner/lifecycle.rs @@ -21,9 +21,9 @@ use nexus_orchestration::capability::{ CapabilityRegistry, CapabilityRegistryHolder, CapabilityRuntimeDeps, DaemonToolDispatch, PromptExecutor, WorkspaceExecutor, WorkspaceStateProvider, }; -use nexus_orchestration::run_state::WorkflowStateStore; +use nexus_session_storage::run_state::WorkflowStateStore; use nexus_orchestration::schedule::supervisor::{ScheduleRunStarter, ScheduleSupervisor}; -use nexus_orchestration::storage::sqlite::SqliteSessionStorage; +use nexus_session_storage::storage::sqlite::SqliteSessionStorage; use nexus_orchestration::{GraphFlowEngine, OrchestrationEngine}; use nexus_provider_ports::ProviderPort; use sqlx::SqlitePool; diff --git a/crates/nexus-core/src/owner/production.rs b/crates/nexus-core/src/owner/production.rs index 45ffed50e..b71cf6574 100644 --- a/crates/nexus-core/src/owner/production.rs +++ b/crates/nexus-core/src/owner/production.rs @@ -48,8 +48,8 @@ use async_trait::async_trait; use nexus_agent_host::config::TimeoutConfig; use nexus_agent_host::{HostFacade, ProviderId}; use nexus_orchestration::capability::{PromptExecutor, WorkspaceExecutor, WorkspaceStateProvider}; -use nexus_orchestration::run_state::{RunRecord, WorkflowStateStore}; -use nexus_orchestration::storage::sqlite::SqliteSessionStorage; +use nexus_session_storage::run_state::{RunRecord, WorkflowStateStore}; +use nexus_session_storage::storage::sqlite::SqliteSessionStorage; use nexus_provider_ports::ProviderPort; use crate::error::{CoreError, CoreResult}; diff --git a/crates/nexus-core/tests/execution_lifecycle.rs b/crates/nexus-core/tests/execution_lifecycle.rs index 8ede379d5..f783b4ab2 100644 --- a/crates/nexus-core/tests/execution_lifecycle.rs +++ b/crates/nexus-core/tests/execution_lifecycle.rs @@ -21,7 +21,7 @@ use nexus_execution::workflow::{RunControlError, RunSignal}; use nexus_orchestration::capability::{ CapabilityError, PromptExecutor, PromptRequest, PromptResult, }; -use nexus_orchestration::WorkflowStateStore; +use nexus_session_storage::run_state::WorkflowStateStore; use nexus_provider_ports::{ProviderPort, ProviderResult}; use std::future::Future; use std::path::Path; @@ -189,7 +189,7 @@ async fn seed_run( db_path: &Path, session_id: &str, creator: &str, - state: nexus_orchestration::RunStateV1, + state: nexus_session_storage::run_state::RunStateV1, ) { seed_run_at(db_path, session_id, creator, state, SEED_PRESET_INITIAL).await; } @@ -199,7 +199,7 @@ async fn seed_run_at( db_path: &Path, session_id: &str, creator: &str, - state: nexus_orchestration::RunStateV1, + state: nexus_session_storage::run_state::RunStateV1, initial: &str, ) { let preset_id = SEED_PRESET; @@ -215,12 +215,12 @@ async fn seed_run_at( let guarded = nexus_local_db::init_engine_pool(db_path) .await .expect("seed engine pool init"); - let store = nexus_orchestration::storage::sqlite::SqliteSessionStorage::new(Arc::new( + let store = nexus_session_storage::storage::sqlite::SqliteSessionStorage::new(Arc::new( guarded.clone_pool(), )); let sid = nexus_orchestration::SessionId(session_id.to_string()); - let descriptor = nexus_orchestration::RunDescriptorV1 { + let descriptor = nexus_session_storage::run_state::RunDescriptorV1 { creator_id: creator.to_string(), work_id: None, workspace_root: std::path::PathBuf::from("/tmp/ws"), @@ -240,7 +240,7 @@ async fn seed_run_at( root.context .set("_session_id", session_id.to_string()) .expect("seed session context"); - let checkpoint = nexus_orchestration::RunCheckpoint { + let checkpoint = nexus_session_storage::run_state::RunCheckpoint { root: &root, children: &[], }; @@ -261,7 +261,7 @@ async fn seed_committed_run(db_path: &Path, session_id: &str, creator: &str) { db_path, session_id, creator, - nexus_orchestration::RunStateV1::default(), + nexus_session_storage::run_state::RunStateV1::default(), ) .await; } @@ -272,7 +272,7 @@ async fn seed_in_flight_run(db_path: &Path, session_id: &str, creator: &str) { db_path, session_id, creator, - nexus_orchestration::RunStateV1 { + nexus_session_storage::run_state::RunStateV1 { step_in_flight: Some("s1".to_string()), ..Default::default() }, @@ -314,7 +314,7 @@ async fn second_owner_and_restart_are_fenced() { // `SqlitePool` beside a live engine owner is exactly what the writer // protocol fences, and it also carries none of the installed // `nexus_writer_*` functions; the owner's pool has both by construction. - let store = nexus_orchestration::storage::sqlite::SqliteSessionStorage::new(Arc::new( + let store = nexus_session_storage::storage::sqlite::SqliteSessionStorage::new(Arc::new( owner_a.pool().clone(), )); let uncertain = store @@ -418,7 +418,7 @@ async fn daemon_restart_safe_boundary_is_reconstructed_and_redriven() { &f.db_path, "test-preset:safe-boundary", CREATOR, - nexus_orchestration::RunStateV1::default(), + nexus_session_storage::run_state::RunStateV1::default(), "generate", ) .await; @@ -705,7 +705,7 @@ async fn close_seed_pool(db_path: &Path, guarded: nexus_local_db::GuardedPool) { async fn seed_restart_apply( pool: &sqlx::SqlitePool, preset_id: &str, -) -> nexus_orchestration::run_state::AppliedRunIdentity { +) -> nexus_session_storage::run_state::AppliedRunIdentity { let document = restart_applied_document(preset_id, APPLIED_ONLY_NODE); seed_apply(pool, preset_id, &document, "[]").await } @@ -717,7 +717,7 @@ async fn seed_pinned_restart_apply( pool: &sqlx::SqlitePool, preset_id: &str, pin_hash: &str, -) -> nexus_orchestration::run_state::AppliedRunIdentity { +) -> nexus_session_storage::run_state::AppliedRunIdentity { let document = restart_pinned_applied_document(preset_id, Some(pin_hash)); let pins = serde_json::json!([{ "id": RESTART_PINNED_PACKAGE, @@ -732,7 +732,7 @@ async fn seed_pinned_restart_apply( async fn seed_hashless_restart_apply( pool: &sqlx::SqlitePool, preset_id: &str, -) -> nexus_orchestration::run_state::AppliedRunIdentity { +) -> nexus_session_storage::run_state::AppliedRunIdentity { let document = restart_pinned_applied_document(preset_id, None); seed_apply(pool, preset_id, &document, "[]").await } @@ -744,7 +744,7 @@ async fn seed_apply( preset_id: &str, document_json: &str, pins_json: &str, -) -> nexus_orchestration::run_state::AppliedRunIdentity { +) -> nexus_session_storage::run_state::AppliedRunIdentity { let document: nexus_workflow_ir::WorkflowDocument = serde_json::from_str(document_json).expect("the applied-side document decodes"); let hash = nexus_workflow_ir::content_hash(&document).expect("the fixture document hashes"); @@ -797,7 +797,7 @@ async fn seed_apply( .await .expect("apply row"); - nexus_orchestration::run_state::AppliedRunIdentity { + nexus_session_storage::run_state::AppliedRunIdentity { apply_id: format!("apl_{preset_id}"), content_hash: hash, } @@ -811,7 +811,7 @@ async fn seed_superseding_apply( pool: &sqlx::SqlitePool, preset_id: &str, supersedes: &str, -) -> nexus_orchestration::run_state::AppliedRunIdentity { +) -> nexus_session_storage::run_state::AppliedRunIdentity { let document: nexus_workflow_ir::WorkflowDocument = serde_json::from_str(&restart_applied_document(preset_id, SUPERSEDING_ONLY_NODE)) .expect("the superseding document decodes"); @@ -850,7 +850,7 @@ async fn seed_superseding_apply( .await .expect("superseding apply row"); - nexus_orchestration::run_state::AppliedRunIdentity { + nexus_session_storage::run_state::AppliedRunIdentity { apply_id: format!("apl2_{preset_id}"), content_hash: hash, } @@ -872,7 +872,7 @@ async fn seed_restart_run( session_id: &str, preset_id: &str, bundle: &Path, - applied: Option, + applied: Option, intake_mode: Option, ) { let loaded = nexus_preset::load_preset( @@ -884,8 +884,8 @@ async fn seed_restart_run( .source_identity .expect("a directory bundle carries an identity"); let store = - nexus_orchestration::storage::sqlite::SqliteSessionStorage::new(Arc::new(pool.clone())); - let descriptor = nexus_orchestration::RunDescriptorV1 { + nexus_session_storage::storage::sqlite::SqliteSessionStorage::new(Arc::new(pool.clone())); + let descriptor = nexus_session_storage::run_state::RunDescriptorV1 { creator_id: CREATOR.to_string(), work_id: None, workspace_root: std::path::PathBuf::from("/tmp/ws"), @@ -903,7 +903,7 @@ async fn seed_restart_run( root.context .set("_session_id", session_id.to_string()) .expect("seed session context"); - let checkpoint = nexus_orchestration::RunCheckpoint { + let checkpoint = nexus_session_storage::run_state::RunCheckpoint { root: &root, children: &[], }; @@ -912,7 +912,7 @@ async fn seed_restart_run( &nexus_orchestration::SessionId(session_id.to_string()), &descriptor, checkpoint, - &nexus_orchestration::RunStateV1::default(), + &nexus_session_storage::run_state::RunStateV1::default(), ) .await .expect("seed start_run"); @@ -924,7 +924,7 @@ async fn read_restart_session( session_id: &str, ) -> Option { use graph_flow::SessionStorage as _; - nexus_orchestration::storage::sqlite::SqliteSessionStorage::new(Arc::new(pool.clone())) + nexus_session_storage::storage::sqlite::SqliteSessionStorage::new(Arc::new(pool.clone())) .get(session_id) .await .expect("read the run row") @@ -948,8 +948,8 @@ async fn wait_for_position(pool: &sqlx::SqlitePool, session_id: &str, node: &str async fn read_restart_record( pool: &sqlx::SqlitePool, session_id: &str, -) -> nexus_orchestration::run_state::RunRecord { - nexus_orchestration::storage::sqlite::SqliteSessionStorage::new(Arc::new(pool.clone())) +) -> nexus_session_storage::run_state::RunRecord { + nexus_session_storage::storage::sqlite::SqliteSessionStorage::new(Arc::new(pool.clone())) .load_run(&nexus_orchestration::SessionId(session_id.to_string())) .await .expect("read the run record") @@ -963,9 +963,9 @@ async fn wait_for_record( session_id: &str, what: &str, mut cond: F, -) -> nexus_orchestration::run_state::RunRecord +) -> nexus_session_storage::run_state::RunRecord where - F: FnMut(&nexus_orchestration::run_state::RunRecord) -> bool, + F: FnMut(&nexus_session_storage::run_state::RunRecord) -> bool, { tokio::time::timeout(Duration::from_secs(10), async { loop { @@ -1031,7 +1031,7 @@ async fn recovered_position(owner: &CoreService, session_id: &str) -> graph_flow async fn admit_and_park( f: &Fixture, nexus_home: &Path, - admitted: &nexus_orchestration::run_state::AppliedRunIdentity, + admitted: &nexus_session_storage::run_state::AppliedRunIdentity, ) -> (nexus_orchestration::SessionId, String) { let owner = open_engine_owner(f).await; let handle = owner @@ -2063,7 +2063,7 @@ async fn draining_close_holds_the_db_fence_until_drives_join() { &f.db_path, "test-preset:held", CREATOR, - nexus_orchestration::RunStateV1::default(), + nexus_session_storage::run_state::RunStateV1::default(), "generate", ) .await; @@ -2120,7 +2120,7 @@ async fn competing_owner_refused_while_close_is_draining() { &f.db_path, "test-preset:held", CREATOR, - nexus_orchestration::RunStateV1::default(), + nexus_session_storage::run_state::RunStateV1::default(), "generate", ) .await; @@ -2365,7 +2365,7 @@ async fn close_waits_for_a_canceled_builds_live_drives() { &f.db_path, "test-preset:canceled", CREATOR, - nexus_orchestration::RunStateV1::default(), + nexus_session_storage::run_state::RunStateV1::default(), "generate", ) .await; @@ -2574,7 +2574,7 @@ async fn close_waits_for_a_retired_owner_during_the_receipt_wait() { &f.db_path, "test-preset:retired", CREATOR, - nexus_orchestration::RunStateV1::default(), + nexus_session_storage::run_state::RunStateV1::default(), "generate", ) .await; diff --git a/crates/nexus-core/tests/retained_execution_contracts.rs b/crates/nexus-core/tests/retained_execution_contracts.rs index 264e60014..8ebc8f00e 100644 --- a/crates/nexus-core/tests/retained_execution_contracts.rs +++ b/crates/nexus-core/tests/retained_execution_contracts.rs @@ -100,9 +100,10 @@ use nexus_orchestration::engine::{ GraphFlowEngine, OrchestrationEngine, SessionStatus, SessionSummary, }; use nexus_orchestration::preset_runtime::build_wired_outer_graph; -use nexus_orchestration::run_state::RunRecord; -use nexus_orchestration::storage::sqlite::SqliteSessionStorage; -use nexus_orchestration::{CapabilityRegistry, CapabilityRegistryHolder, WorkflowStateStore}; +use nexus_session_storage::run_state::RunRecord; +use nexus_session_storage::storage::sqlite::SqliteSessionStorage; +use nexus_orchestration::{CapabilityRegistry, CapabilityRegistryHolder}; +use nexus_session_storage::run_state::WorkflowStateStore; use nexus_provider_ports::{ProviderPort, ProviderResult}; use serde_json::{json, Value}; use std::collections::HashMap; @@ -500,7 +501,7 @@ async fn owner_fixture() -> OwnerFixture { .expect("engine-owner core open"); let host = ParkedHost::new(); - let store: Arc = + let store: Arc = Arc::new(SqliteSessionStorage::new(Arc::new(core.pool().clone()))); let executor = Arc::new(HostPromptExecutor::new( host.clone(), @@ -737,7 +738,7 @@ async fn root_run_count(pool: &sqlx::SqlitePool) -> i64 { async fn durable_record( pool: &sqlx::SqlitePool, run_id: &str, -) -> nexus_orchestration::run_state::RunRecord { +) -> nexus_session_storage::run_state::RunRecord { SqliteSessionStorage::new(Arc::new(pool.clone())) .load_run(&nexus_orchestration::engine::SessionId(run_id.to_string())) .await @@ -2197,7 +2198,7 @@ async fn reconcile_dry_run_mutates_nothing_and_takes_no_lock() { async fn seed_prompt_run( store: &SqliteSessionStorage, session_id: &str, - bindings: HashMap, + bindings: HashMap, ) { let preset = PROMPT_PRESET; let source = nexus_preset::embedded_source_identity(preset).expect("embedded source identity"); @@ -2207,7 +2208,7 @@ async fn seed_prompt_run( ) .expect("embedded preset loads") .version; - let descriptor = nexus_orchestration::RunDescriptorV1 { + let descriptor = nexus_session_storage::run_state::RunDescriptorV1 { creator_id: CREATOR.to_string(), work_id: None, workspace_root: PathBuf::from("/tmp/retained-ws"), @@ -2225,7 +2226,7 @@ async fn seed_prompt_run( root.context .set("_session_id", session_id.to_string()) .expect("seed session context"); - let checkpoint = nexus_orchestration::RunCheckpoint { + let checkpoint = nexus_session_storage::run_state::RunCheckpoint { root: &root, children: &[], }; @@ -2234,7 +2235,7 @@ async fn seed_prompt_run( &nexus_orchestration::SessionId(session_id.to_string()), &descriptor, checkpoint, - &nexus_orchestration::RunStateV1::default(), + &nexus_session_storage::run_state::RunStateV1::default(), ) .await .expect("seed the v1 run"); @@ -2252,7 +2253,7 @@ async fn seed_prompt_run( #[tokio::test] async fn prompt_executor_single_flights_one_session_and_refuses_before_effect() { use nexus_orchestration::capability::{PromptExecutor, PromptRequest, ToolPolicy}; - use nexus_orchestration::run_state::AgentBinding; + use nexus_session_storage::run_state::AgentBinding; let tmp = tempfile::tempdir().unwrap(); let guarded = nexus_local_db::init_engine_pool(&tmp.path().join("state.db")) @@ -2404,7 +2405,7 @@ async fn prompt_executor_single_flights_one_session_and_refuses_before_effect() #[tokio::test] async fn prompt_executor_types_eof_after_initialize_as_a_launch_failure() { use nexus_orchestration::capability::{PromptExecutor, PromptRequest, ToolPolicy}; - use nexus_orchestration::run_state::AgentBinding; + use nexus_session_storage::run_state::AgentBinding; let tmp = tempfile::tempdir().unwrap(); let guarded = nexus_local_db::init_engine_pool(&tmp.path().join("state.db")) @@ -2505,7 +2506,7 @@ async fn prompt_executor_types_eof_after_initialize_as_a_launch_failure() { async fn graph_prompt_context_serializes_output_without_host_handles() { use graph_flow::Task as _; use nexus_orchestration::capability::{PromptExecutor, ToolPolicy}; - use nexus_orchestration::run_state::AgentBinding; + use nexus_session_storage::run_state::AgentBinding; use nexus_orchestration::tasks::InnerGraphNodeTask; use std::sync::RwLock; diff --git a/crates/nexus-core/tests/workspace_commit.rs b/crates/nexus-core/tests/workspace_commit.rs index b8e284f35..e0e18b969 100644 --- a/crates/nexus-core/tests/workspace_commit.rs +++ b/crates/nexus-core/tests/workspace_commit.rs @@ -28,7 +28,7 @@ use nexus_orchestration::capability::{ CapabilityRegistry, CapabilityRegistryHolder, CapabilityRuntimeDeps, WorkspaceExecutor, }; use nexus_orchestration::engine::GraphFlowEngine; -use nexus_orchestration::storage::sqlite::SqliteSessionStorage; +use nexus_session_storage::storage::sqlite::SqliteSessionStorage; use nexus_orchestration::OrchestrationEngine; use nexus_preset::load_preset_from_str; use serde_json::json; diff --git a/crates/nexus-execution/Cargo.toml b/crates/nexus-execution/Cargo.toml index cc565388f..9079abee2 100644 --- a/crates/nexus-execution/Cargo.toml +++ b/crates/nexus-execution/Cargo.toml @@ -26,6 +26,7 @@ test-hooks = ["nexus-local-db/test-hooks"] nexus-contracts = { path = "../nexus-contracts" } nexus-local-db = { path = "../nexus-local-db" } nexus-orchestration = { path = "../nexus-orchestration" } +nexus-session-storage = { path = "../nexus-session-storage" } nexus-home-layout = { path = "../nexus-home-layout" } nexus-preset = { path = "../nexus-preset" } nexus-creator-memory = { path = "../nexus-creator-memory" } diff --git a/crates/nexus-execution/src/prompt_executor.rs b/crates/nexus-execution/src/prompt_executor.rs index a64077bec..5a4a63831 100644 --- a/crates/nexus-execution/src/prompt_executor.rs +++ b/crates/nexus-execution/src/prompt_executor.rs @@ -50,8 +50,7 @@ use nexus_agent_host::{HostFacade, HostOperationId, ProviderId}; use nexus_orchestration::capability::{ CapabilityError, PromptExecutor, PromptRequest, PromptResult, }; -use nexus_orchestration::engine::EngineError; -use nexus_orchestration::run_state::{PromptAttempt, PromptPhase, WorkflowStateStore}; +use nexus_session_storage::{run_state::{PromptAttempt, PromptPhase, WorkflowStateStore}, StorageError}; use nexus_orchestration::SessionId; /// Key for a lazily-reused Host session: the same run+role reuses its @@ -267,7 +266,7 @@ impl HostPromptExecutor { // durable shape (identical fields; this crate persists the // fingerprint without importing provider crates). process_identity: process_identity.map(|pi| { - nexus_orchestration::run_state::OwnedProcessIdentity { + nexus_session_storage::run_state::OwnedProcessIdentity { pid: pi.pid, process_birth: pi.process_birth, group_id: pi.group_id, @@ -289,9 +288,9 @@ impl HostPromptExecutor { // operation won since admission — the prompt must not // launch and the caller sees the same typed cancellation a // post-fence cancellation produces. - EngineError::RevisionMismatch { .. } - | EngineError::TerminalState(_) - | EngineError::SessionNotFound(_) => CapabilityError::Cancelled, + StorageError::RevisionMismatch { .. } + | StorageError::TerminalState(_) + | StorageError::SessionNotFound(_) => CapabilityError::Cancelled, other => CapabilityError::Internal(format!("persist prompt attempt: {other}")), })?; Ok(()) @@ -1019,7 +1018,7 @@ mod tests { HostStartConfig, OperationFinishedEvent, SessionOwner, }; use nexus_agent_host::{HostFacade, HostResult, HostSession, ProviderCatalog, SessionState}; - use nexus_orchestration::storage::sqlite::SqliteSessionStorage; + use nexus_session_storage::storage::sqlite::SqliteSessionStorage; use nexus_orchestration::OrchestrationEngine; use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; @@ -1301,7 +1300,7 @@ mod tests { async fn real_executor_cancel_reaches_host_shutdown() { let host = ScriptedHost::new(); let (executor, sqlite, storage, _pool, _db) = test_executor(host.clone()).await; - let store: Arc = sqlite.clone(); + let store: Arc = sqlite.clone(); let caps = nexus_orchestration::CapabilityRegistryHolder::with_registry(Arc::new( nexus_orchestration::CapabilityRegistry::with_builtins(), @@ -1350,16 +1349,16 @@ mod tests { .await .expect("get root") .expect("root exists"); - let in_flight_state = nexus_orchestration::run_state::RunStateV1 { + let in_flight_state = nexus_session_storage::run_state::RunStateV1 { step_in_flight: Some(pre_step_root.current_task_id.clone()), - ..nexus_orchestration::run_state::RunStateV1::default() + ..nexus_session_storage::run_state::RunStateV1::default() }; store .mark_step_in_flight( &session_id, record.state_revision, Some(record.graph_version), - nexus_orchestration::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &pre_step_root, children: &[], }, @@ -1414,7 +1413,7 @@ mod tests { async fn real_executor_active_operation_cancel_reaches_host_and_reaps() { let host = ScriptedHost::new(); let (executor, sqlite, storage, pool, _db) = test_executor(host.clone()).await; - let store: Arc = sqlite.clone(); + let store: Arc = sqlite.clone(); let caps = nexus_orchestration::CapabilityRegistryHolder::with_registry(Arc::new( nexus_orchestration::CapabilityRegistry::with_builtins(), @@ -1453,7 +1452,7 @@ mod tests { let mut descriptor = record.descriptor.clone().expect("v1 descriptor present"); descriptor.agent_bindings.insert( "default".to_string(), - nexus_orchestration::run_state::AgentBinding { + nexus_session_storage::run_state::AgentBinding { provider_id: "scripted".to_string(), model: None, }, @@ -1481,16 +1480,16 @@ mod tests { .await .expect("get root") .expect("root exists"); - let in_flight_state = nexus_orchestration::run_state::RunStateV1 { + let in_flight_state = nexus_session_storage::run_state::RunStateV1 { step_in_flight: Some(pre_step_root.current_task_id.clone()), - ..nexus_orchestration::run_state::RunStateV1::default() + ..nexus_session_storage::run_state::RunStateV1::default() }; store .mark_step_in_flight( &session_id, record.state_revision, Some(record.graph_version), - nexus_orchestration::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &pre_step_root, children: &[], }, @@ -1616,7 +1615,7 @@ mod tests { async fn non_cooperative_host_cancel_is_bounded_and_never_falsely_cancelled() { let host = ScriptedHost::new(); let (executor, sqlite, storage, pool, _db) = test_executor(host.clone()).await; - let store: Arc = sqlite.clone(); + let store: Arc = sqlite.clone(); let caps = nexus_orchestration::CapabilityRegistryHolder::with_registry(Arc::new( nexus_orchestration::CapabilityRegistry::with_builtins(), @@ -1654,7 +1653,7 @@ mod tests { let mut descriptor = record.descriptor.clone().expect("v1 descriptor present"); descriptor.agent_bindings.insert( "default".to_string(), - nexus_orchestration::run_state::AgentBinding { + nexus_session_storage::run_state::AgentBinding { provider_id: "scripted".to_string(), model: None, }, @@ -1680,16 +1679,16 @@ mod tests { .await .expect("get root") .expect("root exists"); - let in_flight_state = nexus_orchestration::run_state::RunStateV1 { + let in_flight_state = nexus_session_storage::run_state::RunStateV1 { step_in_flight: Some(pre_step_root.current_task_id.clone()), - ..nexus_orchestration::run_state::RunStateV1::default() + ..nexus_session_storage::run_state::RunStateV1::default() }; store .mark_step_in_flight( &session_id, record.state_revision, Some(record.graph_version), - nexus_orchestration::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &pre_step_root, children: &[], }, @@ -1829,7 +1828,7 @@ mod tests { async fn real_executor_reaps_parked_child_and_grandchild_sessions() { let host = ScriptedHost::new(); let (executor, sqlite, storage, _pool, _db) = test_executor(host.clone()).await; - let store: Arc = sqlite.clone(); + let store: Arc = sqlite.clone(); let caps = nexus_orchestration::CapabilityRegistryHolder::with_registry(Arc::new( nexus_orchestration::CapabilityRegistry::with_builtins(), @@ -1934,7 +1933,7 @@ mod tests { async fn real_executor_failed_shutdown_retains_for_retry() { let host = ScriptedHost::new(); let (executor, sqlite, storage, _pool, _db) = test_executor(host.clone()).await; - let store: Arc = sqlite.clone(); + let store: Arc = sqlite.clone(); let caps = nexus_orchestration::CapabilityRegistryHolder::with_registry(Arc::new( nexus_orchestration::CapabilityRegistry::with_builtins(), diff --git a/crates/nexus-execution/src/run_events.rs b/crates/nexus-execution/src/run_events.rs index 3e987df23..9b8e43eab 100644 --- a/crates/nexus-execution/src/run_events.rs +++ b/crates/nexus-execution/src/run_events.rs @@ -1,6 +1,6 @@ //! Bounded per-run workflow event rings and live SSE replay (v1.188 P4 §6.3). -use nexus_orchestration::run_state::RunRecord; +use nexus_session_storage::run_state::RunRecord; use serde::Serialize; use std::collections::{HashMap, VecDeque}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; diff --git a/crates/nexus-execution/src/workflow.rs b/crates/nexus-execution/src/workflow.rs index 10002846f..80e95706f 100644 --- a/crates/nexus-execution/src/workflow.rs +++ b/crates/nexus-execution/src/workflow.rs @@ -46,9 +46,9 @@ use nexus_orchestration::engine::{ StepOutcome, }; use nexus_orchestration::resume_rules; -use nexus_orchestration::run_state::{RunRecord, WorkflowStateStore}; +use nexus_session_storage::{run_state::{RunRecord, WorkflowStateStore}, StorageError}; use nexus_orchestration::schedule::supervisor::{ScheduleRunStarter, SupervisorError}; -use nexus_orchestration::storage::sqlite::SqliteSessionStorage; +use nexus_session_storage::storage::sqlite::SqliteSessionStorage; use tokio_util::sync::CancellationToken; /// Per-run live-ring registry (v1.188 P4 §6.3). @@ -387,7 +387,7 @@ async fn settle_drive_failure( /// terminal write) must use these returned clocks — never a fresh load. struct AuthoritativeSettlement { disposition: FailurePersistenceDisposition, - committed: Option, + committed: Option, /// True ONLY when the durable row was positively read as a legacy v0 /// (`execution_version < 1`) run. The v0 context-only failure contract is /// selected from this persisted fact, never from whether a workflow-store @@ -406,7 +406,7 @@ const fn authoritative_failed( } fn failure_authority_rejection( - record: &nexus_orchestration::run_state::RunRecord, + record: &nexus_session_storage::run_state::RunRecord, witness: &FailedStepWitness, ) -> Option { if record.state.is_none() { @@ -491,7 +491,7 @@ async fn record_driver_failure( let mut next_state = record.state.clone().expect("v1 state checked above"); next_state.in_flight = None; next_state.step_in_flight = None; - next_state.failure = Some(nexus_orchestration::run_state::RunFailure { + next_state.failure = Some(nexus_session_storage::run_state::RunFailure { code: "driver_failed".to_string(), message: error.to_string(), }); @@ -512,7 +512,7 @@ async fn record_driver_failure( ); return authoritative_failed(FailurePersistenceDisposition::PersistenceFailed); } - let checkpoint = nexus_orchestration::run_state::RunCheckpoint { + let checkpoint = nexus_session_storage::run_state::RunCheckpoint { root: &root_with_failure, children: &[], }; @@ -532,7 +532,7 @@ async fn record_driver_failure( committed: Some(record), legacy_v0: false, }, - Err(EngineError::RevisionMismatch { .. } | EngineError::TerminalState(_)) => { + Err(StorageError::RevisionMismatch { .. } | StorageError::TerminalState(_)) => { authoritative_failed(FailurePersistenceDisposition::OwnershipLost) } Err(e) => { @@ -1150,9 +1150,9 @@ impl CancelOutcome { /// `completed`/`failed`-without-cancel-intent (or is still live) has no /// cancel outcome: the cancel genuinely did not happen. fn classify_cancel_outcome( - record: &nexus_orchestration::run_state::RunRecord, + record: &nexus_session_storage::run_state::RunRecord, ) -> Option { - if !nexus_orchestration::run_state::durable_cancel_outcome_accomplished(record) { + if !nexus_session_storage::run_state::durable_cancel_outcome_accomplished(record) { return None; } match record.status { @@ -1435,7 +1435,7 @@ impl WorkflowRunCoordinator { applied_admission: Arc, ) -> Self { let workflow_store: Arc = - Arc::new(nexus_orchestration::storage::sqlite::SqliteSessionStorage::new(pool.clone())); + Arc::new(nexus_session_storage::storage::sqlite::SqliteSessionStorage::new(pool.clone())); Self { engine, storage, @@ -1618,7 +1618,7 @@ impl WorkflowRunCoordinator { seed: Option<&str>, agent_bindings: std::collections::HashMap< String, - nexus_orchestration::run_state::AgentBinding, + nexus_session_storage::run_state::AgentBinding, >, nexus_home: &std::path::Path, caps: &nexus_orchestration::CapabilityRegistryHolder, @@ -2479,7 +2479,7 @@ impl WorkflowRunCoordinator { // Re-entry: the schedule already owns a run — drive it. if let Some(sid) = &row.current_session_id { - let store = nexus_orchestration::storage::sqlite::SqliteSessionStorage::new( + let store = nexus_session_storage::storage::sqlite::SqliteSessionStorage::new( std::sync::Arc::new(pool.clone()), ); let run_exists = store @@ -2620,7 +2620,7 @@ impl WorkflowRunCoordinator { .map(|role| { ( role, - nexus_orchestration::run_state::AgentBinding { + nexus_session_storage::run_state::AgentBinding { provider_id: provider_id.clone(), model: None, }, @@ -2660,7 +2660,7 @@ impl WorkflowRunCoordinator { // 5. Persist the frozen descriptor (idempotent under concurrent // explicit starts — the winner's identical descriptor wins). - let descriptor = nexus_orchestration::run_state::RunDescriptorV1 { + let descriptor = nexus_session_storage::run_state::RunDescriptorV1 { creator_id: row.creator_id.clone(), work_id: row.work_id.clone().filter(|id| !id.is_empty()), workspace_root: std::path::PathBuf::new(), @@ -2866,7 +2866,7 @@ impl WorkflowRunCoordinator { // Re-entry: the schedule already owns a run. Verify the run // actually exists; a stale claim (crash between claim and run // creation) is NOT cleared — boot recovery classifies it (C-1). - let store = nexus_orchestration::storage::sqlite::SqliteSessionStorage::new( + let store = nexus_session_storage::storage::sqlite::SqliteSessionStorage::new( std::sync::Arc::new(pool.clone()), ); let run_exists = store @@ -2901,7 +2901,7 @@ impl WorkflowRunCoordinator { )); } // Snapshot the matrix for the store's in-transaction recheck (N-1). - let admission_gate = nexus_orchestration::run_state::ScheduleAdmissionGate { + let admission_gate = nexus_session_storage::run_state::ScheduleAdmissionGate { creator_id: row.creator_id.clone(), scheduled_at: sqlx::query_scalar!( "SELECT scheduled_at FROM creator_schedules WHERE schedule_id = ?", @@ -2997,7 +2997,7 @@ impl WorkflowRunCoordinator { // descriptor at insertion. let (work_id, input, agent_bindings, frozen_source) = match &row.execution_descriptor_json { Some(bytes) => { - let descriptor: nexus_orchestration::run_state::RunDescriptorV1 = + let descriptor: nexus_session_storage::run_state::RunDescriptorV1 = serde_json::from_slice(bytes).map_err(|e| { RunControlError::Admission(format!( "schedule execution descriptor is corrupt: {e}" @@ -3363,7 +3363,7 @@ impl WorkflowRunCoordinator { // Project the persisted status + current wait id for the response. let store = - nexus_orchestration::storage::sqlite::SqliteSessionStorage::new(self.pool.clone()); + nexus_session_storage::storage::sqlite::SqliteSessionStorage::new(self.pool.clone()); let record = store .load_run(session_id) .await @@ -3763,7 +3763,7 @@ impl ScheduleRunStarter for CoordinatorScheduleRunStarter { /// inspection, never by deferring to the prompt executor. async fn validate_agent_bindings( manifest: &nexus_preset::manifest::PresetManifest, - bindings: &std::collections::HashMap, + bindings: &std::collections::HashMap, catalog: Option<&Arc>, ) -> Result<(), RunControlError> { let role_ids: std::collections::HashSet<&str> = @@ -3905,7 +3905,7 @@ mod tests { /// (concurrent cancel vs drive-failure race — R-V1186P3-004). #[test] fn cancel_fence_accepts_failed_driver_failed_when_cancel_requested() { - use nexus_orchestration::run_state::{RunFailure, RunRecord, RunStateV1}; + use nexus_session_storage::run_state::{RunFailure, RunRecord, RunStateV1}; let record = RunRecord { session_id: SessionId("s".into()), status: SessionStatus::Failed, @@ -3931,7 +3931,7 @@ mod tests { /// genuinely did not happen. #[test] fn classify_cancel_outcome_only_for_durable_cancel_outcomes() { - use nexus_orchestration::run_state::{RunRecord, RunStateV1}; + use nexus_session_storage::run_state::{RunRecord, RunStateV1}; let mk = |status, cancel_requested: bool| -> RunRecord { RunRecord { session_id: SessionId("s".into()), @@ -3982,7 +3982,7 @@ mod tests { let driver_failed = |code: &str| -> RunRecord { let mut record = mk(SessionStatus::Failed, true); if let Some(state) = record.state.as_mut() { - state.failure = Some(nexus_orchestration::run_state::RunFailure { + state.failure = Some(nexus_session_storage::run_state::RunFailure { code: code.to_string(), message: "drive failed".to_string(), }); @@ -3999,7 +3999,7 @@ mod tests { "an unrelated failure code is not a cancel outcome" ); } - use nexus_orchestration::storage::sqlite::SqliteSessionStorage; + use nexus_session_storage::storage::sqlite::SqliteSessionStorage; /// Delegating [`SessionStorage`] that reports a specific session as /// ABSENT (`Ok(None)`) while every other read/write hits the real store — @@ -5659,17 +5659,17 @@ mod tests { async fn load_run( &self, session_id: &SessionId, - ) -> Result, EngineError> { + ) -> Result, StorageError> { self.inner.load_run(session_id).await } async fn start_run( &self, session_id: &SessionId, - descriptor: &nexus_orchestration::run_state::RunDescriptorV1, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .start_run(session_id, descriptor, checkpoint, next_state) .await @@ -5679,13 +5679,13 @@ mod tests { &self, schedule_id: &str, session_id: &SessionId, - descriptor: &nexus_orchestration::run_state::RunDescriptorV1, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, core_context_version: u32, expected_core_context_version: u32, - admission_gate: Option<&nexus_orchestration::run_state::ScheduleAdmissionGate>, - ) -> Result { + admission_gate: Option<&nexus_session_storage::run_state::ScheduleAdmissionGate>, + ) -> Result { self.inner .admit_schedule_run( schedule_id, @@ -5704,10 +5704,10 @@ mod tests { &self, session_id: &SessionId, expected_revision: u64, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { if !self.injected.swap(true, Ordering::SeqCst) { // The competing transition wins the CAS first: a concurrent // cancel fence commits `cancel_requested` at the SAME @@ -5729,7 +5729,7 @@ mod tests { .commit_transition( session_id, record.state_revision, - nexus_orchestration::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &root, children: &[], }, @@ -5755,10 +5755,10 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { let _ = expected_graph_version; self.commit_transition( session_id, @@ -5775,10 +5775,10 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, - terminal_target: nexus_orchestration::run_state::TerminalSettlementTarget, - ) -> Result { + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, + terminal_target: nexus_session_storage::run_state::TerminalSettlementTarget, + ) -> Result { self.inner .settle_run( session_id, @@ -5796,7 +5796,7 @@ mod tests { session_id: &SessionId, expected_revision: u64, pre_step: &graph_flow::Session, - ) -> Result { + ) -> Result { self.inner .restore_pre_step(session_id, expected_revision, pre_step) .await @@ -5807,9 +5807,9 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - step_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + step_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .mark_step_in_flight( session_id, @@ -5827,8 +5827,8 @@ mod tests { expected_revision: u64, expected_step: Option<&str>, expected_attempt_id: Option<&str>, - attempt: &nexus_orchestration::run_state::PromptAttempt, - ) -> Result<(), EngineError> { + attempt: &nexus_session_storage::run_state::PromptAttempt, + ) -> Result<(), StorageError> { self.inner .persist_prompt_attempt( session_id, @@ -5846,7 +5846,7 @@ mod tests { expected_revision: u64, expected_step: Option<&str>, attempt_id: &str, - ) -> Result<(), EngineError> { + ) -> Result<(), StorageError> { self.inner .clear_prompt_attempt(session_id, expected_revision, expected_step, attempt_id) .await @@ -5855,7 +5855,7 @@ mod tests { async fn load_children( &self, parent_session_id: &SessionId, - ) -> Result, EngineError> { + ) -> Result, StorageError> { self.inner.load_children(parent_session_id).await } } @@ -5937,8 +5937,8 @@ mod tests { !self.fired.swap(true, Ordering::SeqCst) } - fn injected(message: &str) -> EngineError { - EngineError::GraphFlow(graph_flow::GraphError::StorageError(message.to_string())) + fn injected(message: &str) -> StorageError { + StorageError::GraphFlow(graph_flow::GraphError::StorageError(message.to_string())) } async fn inject_graph_only_winner(&self, session_id: &SessionId, marker: &str) { @@ -5961,7 +5961,7 @@ mod tests { async fn winner_commit_cancelled_after_failure( &self, session_id: &SessionId, - committed: &nexus_orchestration::run_state::RunRecord, + committed: &nexus_session_storage::run_state::RunRecord, marker: &str, ) { let winner_root = self @@ -5980,7 +5980,7 @@ mod tests { .commit_transition( session_id, committed.state_revision, - nexus_orchestration::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &winner_root, children: &[], }, @@ -5994,7 +5994,7 @@ mod tests { async fn winner_settle_cancelled_after_phase_one( &self, session_id: &SessionId, - committed: &nexus_orchestration::run_state::RunRecord, + committed: &nexus_session_storage::run_state::RunRecord, marker: &str, ) { let winner_root = self @@ -6015,12 +6015,12 @@ mod tests { session_id, committed.state_revision, None, - nexus_orchestration::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &winner_root, children: &[], }, &winner_state, - nexus_orchestration::run_state::TerminalSettlementTarget::Cancelled, + nexus_session_storage::run_state::TerminalSettlementTarget::Cancelled, ) .await .expect("concurrent owner settles Cancelled after phase 1"); @@ -6033,7 +6033,7 @@ mod tests { async fn load_run( &self, session_id: &SessionId, - ) -> Result, EngineError> { + ) -> Result, StorageError> { if self.fault == BoundaryFault::CorruptStateOnStepLoad && self.file_once() { // REAL external corruption of the authoritative state blob: // the row becomes non-replayable, exactly like an outside @@ -6053,10 +6053,10 @@ mod tests { async fn start_run( &self, session_id: &SessionId, - descriptor: &nexus_orchestration::run_state::RunDescriptorV1, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .start_run(session_id, descriptor, checkpoint, next_state) .await @@ -6067,13 +6067,13 @@ mod tests { &self, schedule_id: &str, session_id: &SessionId, - descriptor: &nexus_orchestration::run_state::RunDescriptorV1, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, core_context_version: u32, expected_core_context_version: u32, - admission_gate: Option<&nexus_orchestration::run_state::ScheduleAdmissionGate>, - ) -> Result { + admission_gate: Option<&nexus_session_storage::run_state::ScheduleAdmissionGate>, + ) -> Result { self.inner .admit_schedule_run( schedule_id, @@ -6092,10 +6092,10 @@ mod tests { &self, session_id: &SessionId, expected_revision: u64, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .commit_transition( session_id, @@ -6112,10 +6112,10 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { match self.fault { BoundaryFault::FailFailureCommit if next_state.failure.is_some() && self.file_once() => @@ -6186,11 +6186,11 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, - terminal_target: nexus_orchestration::run_state::TerminalSettlementTarget, - ) -> Result { - use nexus_orchestration::run_state::TerminalSettlementTarget; + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, + terminal_target: nexus_session_storage::run_state::TerminalSettlementTarget, + ) -> Result { + use nexus_session_storage::run_state::TerminalSettlementTarget; // QC2: P4 §6.2 consolidated the anchored `settle_cancelled` / // `settle_failed` cleanup writes into `settle_run`. The fault must // follow the boundary it proves, or the fixture silently stops @@ -6219,7 +6219,7 @@ mod tests { session_id: &SessionId, expected_revision: u64, pre_step: &graph_flow::Session, - ) -> Result { + ) -> Result { if self.fault == BoundaryFault::StepCommitAndRestoreFail && !self.restore_fired.swap(true, Ordering::SeqCst) { @@ -6235,10 +6235,10 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - step_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { - let nexus_orchestration::run_state::RunCheckpoint { root, children } = checkpoint; + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + step_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { + let nexus_session_storage::run_state::RunCheckpoint { root, children } = checkpoint; if self.fault == BoundaryFault::GraphOnlyWinnerBeatsStepMarker && self.file_once() { self.inject_graph_only_winner(session_id, "graph-only-before-marker") .await; @@ -6252,7 +6252,7 @@ mod tests { session_id, expected_revision, expected_graph_version, - nexus_orchestration::run_state::RunCheckpoint { root, children }, + nexus_session_storage::run_state::RunCheckpoint { root, children }, step_state, ) .await @@ -6263,7 +6263,7 @@ mod tests { session_id, expected_revision, expected_graph_version, - nexus_orchestration::run_state::RunCheckpoint { root, children }, + nexus_session_storage::run_state::RunCheckpoint { root, children }, step_state, ) .await @@ -6275,8 +6275,8 @@ mod tests { expected_revision: u64, expected_step: Option<&str>, expected_attempt_id: Option<&str>, - attempt: &nexus_orchestration::run_state::PromptAttempt, - ) -> Result<(), EngineError> { + attempt: &nexus_session_storage::run_state::PromptAttempt, + ) -> Result<(), StorageError> { self.inner .persist_prompt_attempt( session_id, @@ -6294,7 +6294,7 @@ mod tests { expected_revision: u64, expected_step: Option<&str>, attempt_id: &str, - ) -> Result<(), EngineError> { + ) -> Result<(), StorageError> { self.inner .clear_prompt_attempt(session_id, expected_revision, expected_step, attempt_id) .await @@ -6303,7 +6303,7 @@ mod tests { async fn load_children( &self, parent_session_id: &SessionId, - ) -> Result, EngineError> { + ) -> Result, StorageError> { self.inner.load_children(parent_session_id).await } } @@ -6447,21 +6447,21 @@ mod tests { .await .expect("get root") .expect("root exists"); - let waiting_state = nexus_orchestration::run_state::RunStateV1 { - wait: Some(nexus_orchestration::run_state::WaitRecord { + let waiting_state = nexus_session_storage::run_state::RunStateV1 { + wait: Some(nexus_session_storage::run_state::WaitRecord { wait_id: "wait-tok-1".to_string(), task_id: "persist".to_string(), child_session_id: None, child_task_id: None, - kind: nexus_orchestration::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }), - ..nexus_orchestration::run_state::RunStateV1::default() + ..nexus_session_storage::run_state::RunStateV1::default() }; real_store .commit_transition( &session_id, record.state_revision, - nexus_orchestration::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &root, children: &[], }, @@ -6570,12 +6570,12 @@ mod tests { .commit_transition( &SessionId(session_id), 2, - nexus_orchestration::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &winner, children: &[], }, SessionStatus::Running, - &nexus_orchestration::run_state::RunStateV1::default(), + &nexus_session_storage::run_state::RunStateV1::default(), ) .await .map_err(|e| { @@ -6730,12 +6730,12 @@ mod tests { .commit_transition( &SessionId(session_id), 2, - nexus_orchestration::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &winner, children: &[], }, SessionStatus::Running, - &nexus_orchestration::run_state::RunStateV1::default(), + &nexus_session_storage::run_state::RunStateV1::default(), ) .await .map_err(|e| { @@ -6884,12 +6884,12 @@ mod tests { .commit_transition( &SessionId(session_id), 2, - nexus_orchestration::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &winner, children: &[], }, SessionStatus::Running, - &nexus_orchestration::run_state::RunStateV1::default(), + &nexus_session_storage::run_state::RunStateV1::default(), ) .await .map_err(|e| { @@ -7487,12 +7487,12 @@ mod tests { .commit_transition( &session_id, 1, - nexus_orchestration::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &root, children: &[], }, SessionStatus::Cancelled, - &nexus_orchestration::run_state::RunStateV1::default(), + &nexus_session_storage::run_state::RunStateV1::default(), ) .await .expect("terminalize row"); @@ -9093,17 +9093,17 @@ mod tests { async fn load_run( &self, session_id: &SessionId, - ) -> Result, EngineError> + ) -> Result, StorageError> { self.inner.load_run(session_id).await } async fn start_run( &self, session_id: &SessionId, - descriptor: &nexus_orchestration::run_state::RunDescriptorV1, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .start_run(session_id, descriptor, checkpoint, next_state) .await @@ -9113,13 +9113,13 @@ mod tests { &self, schedule_id: &str, session_id: &SessionId, - descriptor: &nexus_orchestration::run_state::RunDescriptorV1, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, core_context_version: u32, expected_core_context_version: u32, - admission_gate: Option<&nexus_orchestration::run_state::ScheduleAdmissionGate>, - ) -> Result { + admission_gate: Option<&nexus_session_storage::run_state::ScheduleAdmissionGate>, + ) -> Result { self.inner .admit_schedule_run( schedule_id, @@ -9137,10 +9137,10 @@ mod tests { &self, session_id: &SessionId, expected_revision: u64, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .commit_transition( session_id, @@ -9156,10 +9156,10 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .commit_transition_with_graph_fence( session_id, @@ -9176,10 +9176,10 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, - terminal_target: nexus_orchestration::run_state::TerminalSettlementTarget, - ) -> Result { + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, + terminal_target: nexus_session_storage::run_state::TerminalSettlementTarget, + ) -> Result { self.inner .settle_run( session_id, @@ -9196,7 +9196,7 @@ mod tests { session_id: &SessionId, expected_revision: u64, pre_step: &graph_flow::Session, - ) -> Result { + ) -> Result { self.inner .restore_pre_step(session_id, expected_revision, pre_step) .await @@ -9206,9 +9206,9 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - step_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + step_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.at_barrier.store(true, Ordering::SeqCst); while !self.release.load(Ordering::SeqCst) { tokio::time::sleep(std::time::Duration::from_millis(5)).await; @@ -9229,8 +9229,8 @@ mod tests { expected_revision: u64, expected_step: Option<&str>, expected_attempt_id: Option<&str>, - attempt: &nexus_orchestration::run_state::PromptAttempt, - ) -> Result<(), EngineError> { + attempt: &nexus_session_storage::run_state::PromptAttempt, + ) -> Result<(), StorageError> { self.inner .persist_prompt_attempt( session_id, @@ -9247,7 +9247,7 @@ mod tests { expected_revision: u64, expected_step: Option<&str>, attempt_id: &str, - ) -> Result<(), EngineError> { + ) -> Result<(), StorageError> { self.inner .clear_prompt_attempt(session_id, expected_revision, expected_step, attempt_id) .await @@ -9256,7 +9256,7 @@ mod tests { async fn load_children( &self, parent_session_id: &SessionId, - ) -> Result, EngineError> { + ) -> Result, StorageError> { self.inner.load_children(parent_session_id).await } } @@ -9594,17 +9594,17 @@ mod tests { async fn load_run( &self, session_id: &SessionId, - ) -> Result, EngineError> + ) -> Result, StorageError> { self.inner.load_run(session_id).await } async fn start_run( &self, session_id: &SessionId, - descriptor: &nexus_orchestration::run_state::RunDescriptorV1, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .start_run(session_id, descriptor, checkpoint, next_state) .await @@ -9614,13 +9614,13 @@ mod tests { &self, schedule_id: &str, session_id: &SessionId, - descriptor: &nexus_orchestration::run_state::RunDescriptorV1, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, core_context_version: u32, expected_core_context_version: u32, - admission_gate: Option<&nexus_orchestration::run_state::ScheduleAdmissionGate>, - ) -> Result { + admission_gate: Option<&nexus_session_storage::run_state::ScheduleAdmissionGate>, + ) -> Result { self.inner .admit_schedule_run( schedule_id, @@ -9638,10 +9638,10 @@ mod tests { &self, session_id: &SessionId, expected_revision: u64, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .commit_transition( session_id, @@ -9657,10 +9657,10 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .commit_transition_with_graph_fence( session_id, @@ -9677,10 +9677,10 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, - terminal_target: nexus_orchestration::run_state::TerminalSettlementTarget, - ) -> Result { + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, + terminal_target: nexus_session_storage::run_state::TerminalSettlementTarget, + ) -> Result { let n = self.arrived.fetch_add(1, Ordering::SeqCst) + 1; if n == 1 { tokio::time::timeout(std::time::Duration::from_secs(2), async { @@ -9707,7 +9707,7 @@ mod tests { session_id: &SessionId, expected_revision: u64, pre_step: &graph_flow::Session, - ) -> Result { + ) -> Result { self.inner .restore_pre_step(session_id, expected_revision, pre_step) .await @@ -9717,9 +9717,9 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - step_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + step_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.dispatches.fetch_add(1, Ordering::SeqCst); self.inner .mark_step_in_flight( @@ -9737,8 +9737,8 @@ mod tests { expected_revision: u64, expected_step: Option<&str>, expected_attempt_id: Option<&str>, - attempt: &nexus_orchestration::run_state::PromptAttempt, - ) -> Result<(), EngineError> { + attempt: &nexus_session_storage::run_state::PromptAttempt, + ) -> Result<(), StorageError> { self.inner .persist_prompt_attempt( session_id, @@ -9756,7 +9756,7 @@ mod tests { expected_revision: u64, expected_step: Option<&str>, attempt_id: &str, - ) -> Result<(), EngineError> { + ) -> Result<(), StorageError> { self.inner .clear_prompt_attempt(session_id, expected_revision, expected_step, attempt_id) .await @@ -9765,7 +9765,7 @@ mod tests { async fn load_children( &self, parent_session_id: &SessionId, - ) -> Result, EngineError> { + ) -> Result, StorageError> { self.inner.load_children(parent_session_id).await } } @@ -9985,17 +9985,17 @@ mod tests { async fn load_run( &self, session_id: &SessionId, - ) -> Result, EngineError> + ) -> Result, StorageError> { self.inner.load_run(session_id).await } async fn start_run( &self, session_id: &SessionId, - descriptor: &nexus_orchestration::run_state::RunDescriptorV1, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .start_run(session_id, descriptor, checkpoint, next_state) .await @@ -10005,13 +10005,13 @@ mod tests { &self, schedule_id: &str, session_id: &SessionId, - descriptor: &nexus_orchestration::run_state::RunDescriptorV1, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, core_context_version: u32, expected_core_context_version: u32, - admission_gate: Option<&nexus_orchestration::run_state::ScheduleAdmissionGate>, - ) -> Result { + admission_gate: Option<&nexus_session_storage::run_state::ScheduleAdmissionGate>, + ) -> Result { self.inner .admit_schedule_run( schedule_id, @@ -10029,10 +10029,10 @@ mod tests { &self, session_id: &SessionId, expected_revision: u64, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .commit_transition( session_id, @@ -10048,10 +10048,10 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .commit_transition_with_graph_fence( session_id, @@ -10068,10 +10068,10 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - next_state: &nexus_orchestration::run_state::RunStateV1, - terminal_target: nexus_orchestration::run_state::TerminalSettlementTarget, - ) -> Result { + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, + terminal_target: nexus_session_storage::run_state::TerminalSettlementTarget, + ) -> Result { self.inner .settle_run( session_id, @@ -10088,7 +10088,7 @@ mod tests { session_id: &SessionId, expected_revision: u64, pre_step: &graph_flow::Session, - ) -> Result { + ) -> Result { self.inner .restore_pre_step(session_id, expected_revision, pre_step) .await @@ -10098,9 +10098,9 @@ mod tests { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: nexus_orchestration::run_state::RunCheckpoint<'_>, - step_state: &nexus_orchestration::run_state::RunStateV1, - ) -> Result { + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + step_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .mark_step_in_flight( session_id, @@ -10117,8 +10117,8 @@ mod tests { expected_revision: u64, expected_step: Option<&str>, expected_attempt_id: Option<&str>, - attempt: &nexus_orchestration::run_state::PromptAttempt, - ) -> Result<(), EngineError> { + attempt: &nexus_session_storage::run_state::PromptAttempt, + ) -> Result<(), StorageError> { self.inner .persist_prompt_attempt( session_id, @@ -10135,7 +10135,7 @@ mod tests { expected_revision: u64, expected_step: Option<&str>, attempt_id: &str, - ) -> Result<(), EngineError> { + ) -> Result<(), StorageError> { self.inner .clear_prompt_attempt(session_id, expected_revision, expected_step, attempt_id) .await @@ -10143,7 +10143,7 @@ mod tests { async fn load_children( &self, parent_session_id: &SessionId, - ) -> Result, EngineError> { + ) -> Result, StorageError> { if self.armed.swap(false, Ordering::SeqCst) { self.at_gate.store(true, Ordering::SeqCst); while !self.release.load(Ordering::SeqCst) { @@ -10631,9 +10631,9 @@ mod tests { .await .expect("get") .expect("root"); - let interrupted_state = nexus_orchestration::run_state::RunStateV1 { + let interrupted_state = nexus_session_storage::run_state::RunStateV1 { cancel_requested: true, - failure: Some(nexus_orchestration::run_state::RunFailure { + failure: Some(nexus_session_storage::run_state::RunFailure { code: "cancel_cleanup_unconfirmed".to_string(), message: "cancel cleanup unconfirmed for run".to_string(), }), @@ -10643,7 +10643,7 @@ mod tests { .commit_transition( &session_id, record.state_revision, - nexus_orchestration::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &root, children: &[], }, @@ -10681,18 +10681,18 @@ mod tests { &session_id, record.state_revision, None, - nexus_orchestration::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &root, children: &[], }, &cancelled_state, - nexus_orchestration::run_state::TerminalSettlementTarget::Cancelled, + nexus_session_storage::run_state::TerminalSettlementTarget::Cancelled, ) .await .expect("confirmed retry settle"); assert!(matches!( settled, - nexus_orchestration::run_state::SettlementResult::Applied(_) + nexus_session_storage::run_state::SettlementResult::Applied(_) )); coordinator.publish_durable_run_state(&session_id).await; diff --git a/crates/nexus-orchestration/Cargo.toml b/crates/nexus-orchestration/Cargo.toml index bf3cb0c22..0d5ac59ff 100644 --- a/crates/nexus-orchestration/Cargo.toml +++ b/crates/nexus-orchestration/Cargo.toml @@ -39,6 +39,9 @@ nexus-contracts = { path = "../nexus-contracts" } # pulls it, and it carries no provider or execution edge. nexus-workflow-ir = { path = "../nexus-workflow-ir", optional = true } nexus-preset = { path = "../nexus-preset" } +# Session identity/status types + StorageError contract moved out of engine.rs; +# engine re-exports them so consumer paths stay unchanged. +nexus-session-storage = { path = "../nexus-session-storage" } nexus-home-layout = { path = "../nexus-home-layout" } nexus-knowledge = { path = "../nexus-knowledge" } # V1.145 P1a: narrative.compute converts WorldKbEntry↔spoke KnowledgeEntry via diff --git a/crates/nexus-orchestration/src/auto_chain.rs b/crates/nexus-orchestration/src/auto_chain.rs index c88996a7b..77bd5d31e 100644 --- a/crates/nexus-orchestration/src/auto_chain.rs +++ b/crates/nexus-orchestration/src/auto_chain.rs @@ -1386,7 +1386,7 @@ fn enqueue_descriptor_json( preset_id: &str, preset_version: i64, input: serde_json::Map, - agent_bindings: std::collections::HashMap, + agent_bindings: std::collections::HashMap, ) -> Result, AutoChainError> { // N-5/N-5b/N-15: stamp the REAL content-addressed source identity // (manifest + referenced template bytes) — never a zero placeholder. @@ -1402,7 +1402,7 @@ fn enqueue_descriptor_json( refusing to publish a drive-enabled row" )) })?; - let descriptor = crate::run_state::RunDescriptorV1 { + let descriptor = nexus_session_storage::run_state::RunDescriptorV1 { creator_id: creator_id.to_string(), work_id: if work_id.is_empty() { None @@ -1452,7 +1452,7 @@ pub async fn enqueue_auto_chain_schedule( chapter: Option, volume: Option, work: &WorkRecord, - agent_bindings: std::collections::HashMap, + agent_bindings: std::collections::HashMap, source_run_id: Option<&str>, ) -> Result { // I-9: the schedule INSERT and the Work driver-pointer update commit in @@ -1607,7 +1607,7 @@ pub async fn enqueue_auto_chain_schedule_in_tx( chapter: Option, volume: Option, work: &WorkRecord, - agent_bindings: std::collections::HashMap, + agent_bindings: std::collections::HashMap, source_run_id: Option<&str>, ) -> Result { // V1.48 P1 (overlay §2 Consumer): render the open-findings prompt @@ -1794,7 +1794,7 @@ pub async fn enqueue_review_master_schedule( pool: &SqlitePool, creator_id: &str, work_id: &str, - agent_bindings: std::collections::HashMap, + agent_bindings: std::collections::HashMap, ) -> Result { // R-V147P0-05 (hotfix H-1): append a per-process monotonic counter suffix // (mirrors `ACH_COUNTER` / R-V139P0-W-B) so two enqueues in the same @@ -1914,7 +1914,7 @@ pub async fn enqueue_cron_schedule( work_id: &str, preset_id: &str, role: &str, - agent_bindings: std::collections::HashMap, + agent_bindings: std::collections::HashMap, ) -> Result { // CRON prefix + timestamp + per-process counter (collision-resistant, // mirrors `ACH_COUNTER` / `RVM_COUNTER`). Two roles firing in the same diff --git a/crates/nexus-orchestration/src/capability/mod.rs b/crates/nexus-orchestration/src/capability/mod.rs index c4ea7ef02..aab35146f 100644 --- a/crates/nexus-orchestration/src/capability/mod.rs +++ b/crates/nexus-orchestration/src/capability/mod.rs @@ -375,7 +375,7 @@ pub trait AppliedDocumentSource: Send + Sync { #[derive(Debug, Clone)] pub struct AppliedDocument { /// The apply row that is current for the strategy. - pub identity: crate::run_state::AppliedRunIdentity, + pub identity: nexus_session_storage::run_state::AppliedRunIdentity, /// The verified document those bytes decode to. pub document: nexus_contracts::generated::daemon_api::orchestration::workflow_document::WorkflowDocument, diff --git a/crates/nexus-orchestration/src/engine.rs b/crates/nexus-orchestration/src/engine.rs index 97e891ace..33f72d7ce 100644 --- a/crates/nexus-orchestration/src/engine.rs +++ b/crates/nexus-orchestration/src/engine.rs @@ -24,12 +24,13 @@ use thiserror::Error; #[cfg(test)] use crate::capability::CapabilityError; use crate::capability::CapabilityRegistry; -use crate::run_state::{ +use nexus_session_storage::run_state::{ ChildCheckpoint, RunCheckpoint, RunDescriptorV1, RunFailure, RunRecord, RunStateV1, SettlementResult, TerminalSettlementTarget, WorkflowStateStore, }; use nexus_contracts::local::schedule::CoreContextPayload; use nexus_preset::source_identity::PresetSourceIdentity; +use nexus_session_storage::StorageError; /// Context key that effectful tasks set when they perform an external effect /// (capability call, ACP/Host prompt dispatch, `HostTool` call, child spawn). @@ -163,9 +164,9 @@ fn clear_step_effect_marker(root: &graph_flow::Session) { // Helper types // --------------------------------------------------------------------------- -/// Opaque session identifier. -#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] -pub struct SessionId(pub String); +// Session identity/status/summary types live in `nexus-session-storage`; +// re-exported here so every existing consumer path stays unchanged. +pub use nexus_session_storage::{SessionId, SessionStatus, SessionSummary}; /// Composite key that uniquely identifies a session within the engine. #[derive(Debug, Clone)] @@ -194,81 +195,6 @@ pub struct SessionFilter { pub preset_id: Option, } -/// Lightweight summary returned by [`OrchestrationEngine::list_active`]. -#[derive(Debug, Clone)] -pub struct SessionSummary { - pub session_id: SessionId, - pub creator_id: String, - pub preset_id: String, - pub status: SessionStatus, - pub current_task_id: Option, -} - -/// Runtime status of a session. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub enum SessionStatus { - Running, - Paused, - WaitingForInput, - Completed, - Failed, - /// Cancelled by an operator; terminal, never auto-driven. - Cancelled, - /// Interrupted — uncertain in-flight work; stopped, never safe retry. - Interrupted, -} - -impl SessionStatus { - /// Returns `true` if the session is in a terminal state. - #[must_use] - pub const fn is_terminal(&self) -> bool { - matches!( - self, - Self::Completed | Self::Failed | Self::Cancelled | Self::Interrupted - ) - } - - /// Returns `true` if the session has completed successfully. - #[must_use] - pub const fn is_completed(&self) -> bool { - matches!(self, Self::Completed) - } - - /// Map to the authoritative DB `status` string (A2). - #[must_use] - pub const fn as_db_str(&self) -> &'static str { - match self { - Self::Running => "running", - Self::Paused => "paused", - Self::WaitingForInput => "waiting_for_input", - Self::Completed => "completed", - Self::Failed => "failed", - Self::Cancelled => "cancelled", - Self::Interrupted => "interrupted", - } - } - - /// Parse a DB `status` string back into a [`SessionStatus`]. - /// - /// Returns `None` for unknown/unsupported values (A7): a corrupt or - /// ambiguous status must never be silently reinterpreted as `Running`. - /// Callers that need strict parsing should treat `None` as - /// unknown/non-replayable. - #[must_use] - pub fn from_db_str(status: &str) -> Option { - match status { - "running" => Some(Self::Running), - "paused" => Some(Self::Paused), - "waiting_for_input" => Some(Self::WaitingForInput), - "completed" => Some(Self::Completed), - "failed" => Some(Self::Failed), - "cancelled" => Some(Self::Cancelled), - "interrupted" => Some(Self::Interrupted), - _ => None, - } - } -} - /// Successful stopping point of a single engine step. /// /// Failures use [`EngineError`], retaining any owned step witness. @@ -537,6 +463,41 @@ impl EngineError { } } +impl From for EngineError { + fn from(err: StorageError) -> Self { + match err { + StorageError::GraphFlow(source) => Self::GraphFlow(source), + StorageError::SessionNotFound(session_id) => Self::SessionNotFound(session_id), + StorageError::RevisionMismatch { + session_id, + expected, + found, + } => Self::RevisionMismatch { + session_id, + expected, + found, + }, + StorageError::TerminalState(session_id) => Self::TerminalState(session_id), + StorageError::RunAlreadyExists { + session_id, + execution_version, + } => Self::RunAlreadyExists { + session_id, + execution_version, + }, + StorageError::WaitConflict { + session_id, + status, + current_wait_id, + } => Self::WaitConflict { + session_id, + status, + current_wait_id, + }, + } + } +} + // --------------------------------------------------------------------------- // Trait // --------------------------------------------------------------------------- @@ -878,7 +839,7 @@ impl EngineSharedState { // (Minor 1: hydrate_children must not leave a stale entry on // a load/child-snapshot error). self.children.write().await.remove(&parent_session_id.0); - return Err(e); + return Err(e.into()); } }; let parent = self @@ -902,7 +863,7 @@ impl EngineSharedState { Ok(record) => record, Err(e) => { self.children.write().await.remove(&parent_session_id.0); - return Err(e); + return Err(e.into()); } }; if let Some(parent_record) = parent_record { @@ -1302,7 +1263,7 @@ impl EngineSharedState { } break; } - Err(EngineError::RevisionMismatch { .. }) => { + Err(StorageError::RevisionMismatch { .. }) => { if !cancel_allow_rebase { return Err(EngineError::RevisionMismatch { session_id: session_id.0.clone(), @@ -1344,7 +1305,7 @@ impl EngineSharedState { fence_state = current.state.unwrap_or_default(); fence_state.cancel_requested = true; } - Err(e) => return Err(e), + Err(e) => return Err(e.into()), } } } @@ -1538,7 +1499,7 @@ impl EngineSharedState { } match interrupted_result { Ok(_) => break, - Err(EngineError::RevisionMismatch { .. }) => { + Err(StorageError::RevisionMismatch { .. }) => { if !cancel_allow_rebase { return Err(EngineError::RevisionMismatch { session_id: session_id.0.clone(), @@ -1557,7 +1518,7 @@ impl EngineSharedState { // Reload and re-commit against the new // revision. } - Err(err) => return Err(err), + Err(err) => return Err(err.into()), } } // Durable Interrupted confirmed: only now update the @@ -1693,7 +1654,7 @@ impl EngineSharedState { // tokens or infer cleanup from Observed (P4 §6.2). return Ok(record.status); } - Err(EngineError::RevisionMismatch { .. }) => { + Err(StorageError::RevisionMismatch { .. }) => { if !cancel_allow_rebase { return Err(EngineError::RevisionMismatch { session_id: session_id.0.clone(), @@ -1711,7 +1672,7 @@ impl EngineSharedState { } // Reload and re-settle against the new revision. } - Err(e) => return Err(e), + Err(e) => return Err(e.into()), } } // M-004: reclaim the run's coordinator cancellation token at @@ -2009,7 +1970,7 @@ impl EngineSharedState { match store.load_run(session_id).await { Ok(Some(r)) => (r.state_revision, r.status, Some(r.execution_version)), Ok(None) => (0, SessionStatus::Running, None), - Err(e) => return Err(e), + Err(e) => return Err(e.into()), } } else { let status = self @@ -2110,9 +2071,9 @@ impl EngineSharedState { .await { Err( - e @ (EngineError::RevisionMismatch { .. } - | EngineError::TerminalState(_) - | EngineError::GraphFlow(graph_flow::GraphError::SessionConflict(_))), + e @ (StorageError::RevisionMismatch { .. } + | StorageError::TerminalState(_) + | StorageError::GraphFlow(graph_flow::GraphError::SessionConflict(_))), ) => { // A marker refusal that names the concurrent authoritative // winner (revision/graph ownership loss, terminal state, @@ -2120,7 +2081,7 @@ impl EngineSharedState { // authority: it must reach the drive loop as the losing // writer's own disposition, never wrapped into a // fabricated step-failure settlement. - return Err(e); + return Err(e.into()); } Err(e) => { // The marker did not commit: the attempt owns only the @@ -2131,7 +2092,7 @@ impl EngineSharedState { pre_step_status: pre_step_status.clone(), pre_step_root: pre.clone(), }; - return Err(EngineError::step_failed(&session_id.0, e, witness)); + return Err(EngineError::step_failed(&session_id.0, e.into(), witness)); } Ok(marker_record) => { transition_revision = marker_record.state_revision; @@ -2333,7 +2294,7 @@ impl EngineSharedState { { Ok(SettlementResult::Applied(record)) => Ok((true, record.status)), Ok(SettlementResult::Observed(record)) => Ok((false, record.status)), - Err(e) => Err(e), + Err(e) => Err(e.into()), } } else { store @@ -2347,6 +2308,7 @@ impl EngineSharedState { ) .await .map(|_| (true, status.clone())) + .map_err(EngineError::from) }; match commit_result { Ok((owned_commit, durable_status)) => { @@ -2519,8 +2481,8 @@ impl EngineSharedState { // error as the truthful outcome; the winner is // untouched. Err( - EngineError::RevisionMismatch { .. } - | EngineError::TerminalState(_), + StorageError::RevisionMismatch { .. } + | StorageError::TerminalState(_), ) => {} // Any other restore failure (storage fault, // corruption) must remain observable: an @@ -2836,7 +2798,7 @@ impl EngineSharedState { Ok(SettlementResult::Applied(_) | SettlementResult::Observed(_)) => { break; } - Err(EngineError::RevisionMismatch { .. }) => { + Err(StorageError::RevisionMismatch { .. }) => { settle_attempts += 1; if settle_attempts >= CANCEL_FENCE_RETRY_BOUND { return Err(EngineError::RevisionMismatch { @@ -2848,7 +2810,7 @@ impl EngineSharedState { // Reload and re-settle against the new // revision. } - Err(e) => return Err(e), + Err(e) => return Err(e.into()), } } child_map @@ -3181,7 +3143,7 @@ fn build_step_state( // `Err(GraphError)` and are persisted by the daemon driver's failure // path. A step that reached `build_step_state` therefore carries no // fabricated failure record. - let failure: Option = None; + let failure: Option = None; // Round-4 Critical 2 (A4): when THIS step parked because a nested child // is waiting for human input, the root WaitRecord names the exact // waiting descendant (`child_session_id` / `child_task_id`) so restart @@ -3197,12 +3159,12 @@ fn build_step_state( (None, None) }; let wait = if matches!(status, SessionStatus::WaitingForInput) { - Some(crate::run_state::WaitRecord { + Some(nexus_session_storage::run_state::WaitRecord { wait_id: uuid::Uuid::new_v4().to_string(), task_id: current_task_id.to_string(), child_session_id, child_task_id, - kind: crate::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }) } else { None @@ -4108,7 +4070,7 @@ impl GraphFlowEngine { .collect(); // Snapshot the closure first so no children-map lock is held // across the storage awaits below. - let snapshot: Vec<(SessionId, Vec)> = { + let snapshot: Vec<(SessionId, Vec)> = { let children_map = self.state.children.read().await; let mut queue: std::collections::VecDeque = std::collections::VecDeque::new(); @@ -4337,7 +4299,7 @@ impl GraphFlowEngine { &self, loaded: &nexus_preset::LoadedPreset, creator_id: &str, - applied: Option, + applied: Option, intake_mode: Option, ) -> Result { let source = loaded.source_identity.clone().ok_or_else(|| { @@ -4369,7 +4331,7 @@ impl GraphFlowEngine { &self, loaded: &nexus_preset::LoadedPreset, creator_id: &str, - applied: Option, + applied: Option, intake_mode: Option, graph: Arc, ) -> Result { @@ -4548,8 +4510,8 @@ impl GraphFlowEngine { work_id: Option, input: serde_json::Map, core_context: Option<&CoreContextPayload>, - agent_bindings: std::collections::HashMap, - applied: Option, + agent_bindings: std::collections::HashMap, + applied: Option, intake_mode: Option, graph: Arc, ) -> Result { @@ -4651,11 +4613,11 @@ impl GraphFlowEngine { core_context: Option<&CoreContextPayload>, core_context_version: u32, expected_core_context_version: u32, - agent_bindings: std::collections::HashMap, + agent_bindings: std::collections::HashMap, frozen_source: Option, - applied: Option, + applied: Option, intake_mode: Option, - admission_gate: Option, + admission_gate: Option, graph: Arc, ) -> Result { let Some(store) = &self.state.workflow_store else { @@ -5191,17 +5153,17 @@ impl WorkflowStateStore for InterruptedCasInjectingStore { async fn load_run( &self, session_id: &SessionId, - ) -> Result, EngineError> { + ) -> Result, StorageError> { self.inner.load_run(session_id).await } async fn start_run( &self, session_id: &SessionId, - descriptor: &crate::run_state::RunDescriptorV1, - checkpoint: crate::run_state::RunCheckpoint<'_>, - next_state: &crate::run_state::RunStateV1, - ) -> Result { + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .start_run(session_id, descriptor, checkpoint, next_state) .await @@ -5211,13 +5173,13 @@ impl WorkflowStateStore for InterruptedCasInjectingStore { &self, schedule_id: &str, session_id: &SessionId, - descriptor: &crate::run_state::RunDescriptorV1, - checkpoint: crate::run_state::RunCheckpoint<'_>, - next_state: &crate::run_state::RunStateV1, + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, core_context_version: u32, expected_core_context_version: u32, - admission_gate: Option<&crate::run_state::ScheduleAdmissionGate>, - ) -> Result { + admission_gate: Option<&nexus_session_storage::run_state::ScheduleAdmissionGate>, + ) -> Result { self.inner .admit_schedule_run( schedule_id, @@ -5236,10 +5198,10 @@ impl WorkflowStateStore for InterruptedCasInjectingStore { &self, session_id: &SessionId, expected_revision: u64, - checkpoint: crate::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &crate::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { if next_status == SessionStatus::Interrupted && !self .injected @@ -5265,7 +5227,7 @@ impl WorkflowStateStore for InterruptedCasInjectingStore { .commit_transition( session_id, record.state_revision, - crate::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &root, children: &[], }, @@ -5291,10 +5253,10 @@ impl WorkflowStateStore for InterruptedCasInjectingStore { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: crate::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &crate::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { let _ = expected_graph_version; self.commit_transition( session_id, @@ -5311,10 +5273,10 @@ impl WorkflowStateStore for InterruptedCasInjectingStore { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: crate::run_state::RunCheckpoint<'_>, - next_state: &crate::run_state::RunStateV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, terminal_target: TerminalSettlementTarget, - ) -> Result { + ) -> Result { self.inner .settle_run( session_id, @@ -5332,7 +5294,7 @@ impl WorkflowStateStore for InterruptedCasInjectingStore { session_id: &SessionId, expected_revision: u64, pre_step: &graph_flow::Session, - ) -> Result { + ) -> Result { self.inner .restore_pre_step(session_id, expected_revision, pre_step) .await @@ -5343,9 +5305,9 @@ impl WorkflowStateStore for InterruptedCasInjectingStore { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: crate::run_state::RunCheckpoint<'_>, - step_state: &crate::run_state::RunStateV1, - ) -> Result { + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + step_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .mark_step_in_flight( session_id, @@ -5363,8 +5325,8 @@ impl WorkflowStateStore for InterruptedCasInjectingStore { expected_revision: u64, expected_step: Option<&str>, expected_attempt_id: Option<&str>, - attempt: &crate::run_state::PromptAttempt, - ) -> Result<(), EngineError> { + attempt: &nexus_session_storage::run_state::PromptAttempt, + ) -> Result<(), StorageError> { self.inner .persist_prompt_attempt( session_id, @@ -5382,7 +5344,7 @@ impl WorkflowStateStore for InterruptedCasInjectingStore { expected_revision: u64, expected_step: Option<&str>, attempt_id: &str, - ) -> Result<(), EngineError> { + ) -> Result<(), StorageError> { self.inner .clear_prompt_attempt(session_id, expected_revision, expected_step, attempt_id) .await @@ -5391,7 +5353,7 @@ impl WorkflowStateStore for InterruptedCasInjectingStore { async fn load_children( &self, parent_session_id: &SessionId, - ) -> Result, EngineError> { + ) -> Result, StorageError> { self.inner.load_children(parent_session_id).await } } @@ -5438,17 +5400,17 @@ impl WorkflowStateStore for ContinueWinsBeforeCancelFenceStore { async fn load_run( &self, session_id: &SessionId, - ) -> Result, EngineError> { + ) -> Result, StorageError> { self.inner.load_run(session_id).await } async fn start_run( &self, session_id: &SessionId, - descriptor: &crate::run_state::RunDescriptorV1, - checkpoint: crate::run_state::RunCheckpoint<'_>, - next_state: &crate::run_state::RunStateV1, - ) -> Result { + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .start_run(session_id, descriptor, checkpoint, next_state) .await @@ -5458,13 +5420,13 @@ impl WorkflowStateStore for ContinueWinsBeforeCancelFenceStore { &self, schedule_id: &str, session_id: &SessionId, - descriptor: &crate::run_state::RunDescriptorV1, - checkpoint: crate::run_state::RunCheckpoint<'_>, - next_state: &crate::run_state::RunStateV1, + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, core_context_version: u32, expected_core_context_version: u32, - admission_gate: Option<&crate::run_state::ScheduleAdmissionGate>, - ) -> Result { + admission_gate: Option<&nexus_session_storage::run_state::ScheduleAdmissionGate>, + ) -> Result { self.inner .admit_schedule_run( schedule_id, @@ -5483,10 +5445,10 @@ impl WorkflowStateStore for ContinueWinsBeforeCancelFenceStore { &self, session_id: &SessionId, expected_revision: u64, - checkpoint: crate::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &crate::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { // The phase-1 cancel fence is the first commit carrying the durable // cancel intent on a non-terminal status. Inject the Continue winner // at the SAME revision BEFORE the fence commits, so the fence loses @@ -5517,12 +5479,12 @@ impl WorkflowStateStore for ContinueWinsBeforeCancelFenceStore { .commit_transition( session_id, record.state_revision, - crate::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &winner_root, children: &[], }, SessionStatus::Running, - &crate::run_state::RunStateV1::default(), + &nexus_session_storage::run_state::RunStateV1::default(), ) .await .expect("Continue wins the CAS before the cancel fence"); @@ -5543,10 +5505,10 @@ impl WorkflowStateStore for ContinueWinsBeforeCancelFenceStore { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: crate::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &crate::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { let _ = expected_graph_version; self.commit_transition( session_id, @@ -5563,10 +5525,10 @@ impl WorkflowStateStore for ContinueWinsBeforeCancelFenceStore { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: crate::run_state::RunCheckpoint<'_>, - next_state: &crate::run_state::RunStateV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, terminal_target: TerminalSettlementTarget, - ) -> Result { + ) -> Result { self.inner .settle_run( session_id, @@ -5584,7 +5546,7 @@ impl WorkflowStateStore for ContinueWinsBeforeCancelFenceStore { session_id: &SessionId, expected_revision: u64, pre_step: &graph_flow::Session, - ) -> Result { + ) -> Result { self.inner .restore_pre_step(session_id, expected_revision, pre_step) .await @@ -5595,9 +5557,9 @@ impl WorkflowStateStore for ContinueWinsBeforeCancelFenceStore { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: crate::run_state::RunCheckpoint<'_>, - step_state: &crate::run_state::RunStateV1, - ) -> Result { + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + step_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .mark_step_in_flight( session_id, @@ -5615,8 +5577,8 @@ impl WorkflowStateStore for ContinueWinsBeforeCancelFenceStore { expected_revision: u64, expected_step: Option<&str>, expected_attempt_id: Option<&str>, - attempt: &crate::run_state::PromptAttempt, - ) -> Result<(), EngineError> { + attempt: &nexus_session_storage::run_state::PromptAttempt, + ) -> Result<(), StorageError> { self.inner .persist_prompt_attempt( session_id, @@ -5634,7 +5596,7 @@ impl WorkflowStateStore for ContinueWinsBeforeCancelFenceStore { expected_revision: u64, expected_step: Option<&str>, attempt_id: &str, - ) -> Result<(), EngineError> { + ) -> Result<(), StorageError> { self.inner .clear_prompt_attempt(session_id, expected_revision, expected_step, attempt_id) .await @@ -5643,7 +5605,7 @@ impl WorkflowStateStore for ContinueWinsBeforeCancelFenceStore { async fn load_children( &self, parent_session_id: &SessionId, - ) -> Result, EngineError> { + ) -> Result, StorageError> { self.inner.load_children(parent_session_id).await } } @@ -5684,17 +5646,17 @@ impl WorkflowStateStore for ChildSettleCasLossStore { async fn load_run( &self, session_id: &SessionId, - ) -> Result, EngineError> { + ) -> Result, StorageError> { self.inner.load_run(session_id).await } async fn start_run( &self, session_id: &SessionId, - descriptor: &crate::run_state::RunDescriptorV1, - checkpoint: crate::run_state::RunCheckpoint<'_>, - next_state: &crate::run_state::RunStateV1, - ) -> Result { + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .start_run(session_id, descriptor, checkpoint, next_state) .await @@ -5704,13 +5666,13 @@ impl WorkflowStateStore for ChildSettleCasLossStore { &self, schedule_id: &str, session_id: &SessionId, - descriptor: &crate::run_state::RunDescriptorV1, - checkpoint: crate::run_state::RunCheckpoint<'_>, - next_state: &crate::run_state::RunStateV1, + descriptor: &nexus_session_storage::run_state::RunDescriptorV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, core_context_version: u32, expected_core_context_version: u32, - admission_gate: Option<&crate::run_state::ScheduleAdmissionGate>, - ) -> Result { + admission_gate: Option<&nexus_session_storage::run_state::ScheduleAdmissionGate>, + ) -> Result { self.inner .admit_schedule_run( schedule_id, @@ -5729,10 +5691,10 @@ impl WorkflowStateStore for ChildSettleCasLossStore { &self, session_id: &SessionId, expected_revision: u64, - checkpoint: crate::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &crate::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .commit_transition( session_id, @@ -5749,10 +5711,10 @@ impl WorkflowStateStore for ChildSettleCasLossStore { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: crate::run_state::RunCheckpoint<'_>, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, next_status: SessionStatus, - next_state: &crate::run_state::RunStateV1, - ) -> Result { + next_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { let _ = expected_graph_version; self.commit_transition( session_id, @@ -5769,10 +5731,10 @@ impl WorkflowStateStore for ChildSettleCasLossStore { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: crate::run_state::RunCheckpoint<'_>, - next_state: &crate::run_state::RunStateV1, + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + next_state: &nexus_session_storage::run_state::RunStateV1, terminal_target: TerminalSettlementTarget, - ) -> Result { + ) -> Result { if terminal_target == TerminalSettlementTarget::Cancelled && !self .injected @@ -5798,12 +5760,12 @@ impl WorkflowStateStore for ChildSettleCasLossStore { .commit_transition( session_id, record.state_revision, - crate::run_state::RunCheckpoint { + nexus_session_storage::run_state::RunCheckpoint { root: &winner_root, children: &[], }, SessionStatus::Running, - &crate::run_state::RunStateV1::default(), + &nexus_session_storage::run_state::RunStateV1::default(), ) .await .expect("competing transition wins the CAS before the child settle"); @@ -5825,7 +5787,7 @@ impl WorkflowStateStore for ChildSettleCasLossStore { session_id: &SessionId, expected_revision: u64, pre_step: &graph_flow::Session, - ) -> Result { + ) -> Result { self.inner .restore_pre_step(session_id, expected_revision, pre_step) .await @@ -5836,9 +5798,9 @@ impl WorkflowStateStore for ChildSettleCasLossStore { session_id: &SessionId, expected_revision: u64, expected_graph_version: Option, - checkpoint: crate::run_state::RunCheckpoint<'_>, - step_state: &crate::run_state::RunStateV1, - ) -> Result { + checkpoint: nexus_session_storage::run_state::RunCheckpoint<'_>, + step_state: &nexus_session_storage::run_state::RunStateV1, + ) -> Result { self.inner .mark_step_in_flight( session_id, @@ -5856,8 +5818,8 @@ impl WorkflowStateStore for ChildSettleCasLossStore { expected_revision: u64, expected_step: Option<&str>, expected_attempt_id: Option<&str>, - attempt: &crate::run_state::PromptAttempt, - ) -> Result<(), EngineError> { + attempt: &nexus_session_storage::run_state::PromptAttempt, + ) -> Result<(), StorageError> { self.inner .persist_prompt_attempt( session_id, @@ -5875,7 +5837,7 @@ impl WorkflowStateStore for ChildSettleCasLossStore { expected_revision: u64, expected_step: Option<&str>, attempt_id: &str, - ) -> Result<(), EngineError> { + ) -> Result<(), StorageError> { self.inner .clear_prompt_attempt(session_id, expected_revision, expected_step, attempt_id) .await @@ -5884,7 +5846,7 @@ impl WorkflowStateStore for ChildSettleCasLossStore { async fn load_children( &self, parent_session_id: &SessionId, - ) -> Result, EngineError> { + ) -> Result, StorageError> { self.inner.load_children(parent_session_id).await } } @@ -5900,7 +5862,7 @@ mod tests { #![allow(clippy::significant_drop_tightening)] // tests read state snapshots; early-drop noise without contention value use super::*; - use crate::storage::SqliteSessionStorage; + use nexus_session_storage::storage::SqliteSessionStorage; use graph_flow::InMemorySessionStorage; /// Helper: create a test engine with in-memory storage and built-in caps. @@ -7026,12 +6988,12 @@ mod tests { .expect("get root") .expect("root exists"); let waiting_state = RunStateV1 { - wait: Some(crate::run_state::WaitRecord { + wait: Some(nexus_session_storage::run_state::WaitRecord { wait_id: "wait-tok-1".to_string(), task_id: "persist".to_string(), child_session_id: None, child_task_id: None, - kind: crate::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }), ..RunStateV1::default() }; @@ -7174,12 +7136,12 @@ mod tests { .expect("get root") .expect("root exists"); let waiting_state = RunStateV1 { - wait: Some(crate::run_state::WaitRecord { + wait: Some(nexus_session_storage::run_state::WaitRecord { wait_id: "wait-tok-1".to_string(), task_id: "persist".to_string(), child_session_id: None, child_task_id: None, - kind: crate::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }), ..RunStateV1::default() }; @@ -7333,12 +7295,12 @@ mod tests { .expect("get root") .expect("root exists"); let waiting_state = RunStateV1 { - wait: Some(crate::run_state::WaitRecord { + wait: Some(nexus_session_storage::run_state::WaitRecord { wait_id: "wait-tok-1".to_string(), task_id: "persist".to_string(), child_session_id: None, child_task_id: None, - kind: crate::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }), ..RunStateV1::default() }; @@ -7496,12 +7458,12 @@ mod tests { .expect("get grandchild root") .expect("grandchild root exists"); let grandchild_waiting = RunStateV1 { - wait: Some(crate::run_state::WaitRecord { + wait: Some(nexus_session_storage::run_state::WaitRecord { wait_id: "grandchild-wait-tok".to_string(), task_id: "persist".to_string(), child_session_id: None, child_task_id: None, - kind: crate::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }), ..RunStateV1::default() }; @@ -8342,12 +8304,12 @@ mod tests { .expect("get grandchild root") .expect("grandchild root exists"); let grandchild_waiting = RunStateV1 { - wait: Some(crate::run_state::WaitRecord { + wait: Some(nexus_session_storage::run_state::WaitRecord { wait_id: "restart-grandchild-wait".to_string(), task_id: "persist".to_string(), child_session_id: None, child_task_id: None, - kind: crate::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }), ..RunStateV1::default() }; @@ -8831,12 +8793,12 @@ mod tests { .expect("get child root") .expect("child root exists"); let child_waiting = RunStateV1 { - wait: Some(crate::run_state::WaitRecord { + wait: Some(nexus_session_storage::run_state::WaitRecord { wait_id: "child-wait-tok".to_string(), task_id: "persist".to_string(), child_session_id: None, child_task_id: None, - kind: crate::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }), ..RunStateV1::default() }; @@ -9025,12 +8987,12 @@ mod tests { .expect("get root") .expect("root row"); let wait_state = RunStateV1 { - wait: Some(crate::run_state::WaitRecord { + wait: Some(nexus_session_storage::run_state::WaitRecord { wait_id: "wait-nested-1".to_string(), task_id: root.current_task_id.clone(), child_session_id: Some(child_id.0.clone()), child_task_id: None, - kind: crate::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }), ..RunStateV1::default() }; diff --git a/crates/nexus-orchestration/src/lib.rs b/crates/nexus-orchestration/src/lib.rs index ff0f42c8b..33d86af20 100644 --- a/crates/nexus-orchestration/src/lib.rs +++ b/crates/nexus-orchestration/src/lib.rs @@ -17,7 +17,6 @@ pub mod quality_loop; pub mod resume_rules; pub mod review_report; pub mod rules_layers; -pub mod run_state; pub mod schedule; /// Static Simulate (feature `simulate`): reachability walk over a candidate IR. #[cfg(feature = "simulate")] @@ -26,7 +25,6 @@ pub mod skill_link; pub mod skill_sync; pub mod stage_gates; pub mod state_delta; -pub mod storage; pub mod sync_module; pub mod system_preset; pub mod tasks; @@ -40,11 +38,6 @@ pub use engine::{ ChildSessionParams, EngineError, FailedStepWitness, FailurePersistenceDisposition, FailureSettlement, FailureSettlementSummary, GraphFlowEngine, OrchestrationEngine, SessionId, }; -pub use run_state::{ - durable_cancel_outcome_accomplished, AgentBinding, ChildCheckpoint, OwnedProcessIdentity, - PromptAttempt, PromptPhase, RunCheckpoint, RunDescriptorV1, RunFailure, RunRecord, RunStateV1, - SettlementResult, TerminalSettlementTarget, WaitKind, WaitRecord, WorkflowStateStore, -}; #[cfg(feature = "simulate")] pub use simulation::{simulate_document, SimulationError, SimulationOptions}; pub use stage_gates::{ diff --git a/crates/nexus-orchestration/src/preset_runtime.rs b/crates/nexus-orchestration/src/preset_runtime.rs index 599c54cc7..ba4c2d9f9 100644 --- a/crates/nexus-orchestration/src/preset_runtime.rs +++ b/crates/nexus-orchestration/src/preset_runtime.rs @@ -26,14 +26,14 @@ use std::sync::Arc; pub fn default_bindings_for_preset( preset_id: &str, provider_id: &str, -) -> Option> { +) -> Option> { let caps = crate::capability::CapabilityRegistry::with_builtins(); let loaded = load_embedded_preset(preset_id, &caps).ok()?; let roles = required_prompt_roles(&loaded.manifest); if roles.is_empty() { return Some(std::collections::HashMap::new()); } - let binding = crate::run_state::AgentBinding { + let binding = nexus_session_storage::run_state::AgentBinding { provider_id: provider_id.to_string(), model: None, }; diff --git a/crates/nexus-orchestration/src/resume_rules.rs b/crates/nexus-orchestration/src/resume_rules.rs index 08f806343..87d345b10 100644 --- a/crates/nexus-orchestration/src/resume_rules.rs +++ b/crates/nexus-orchestration/src/resume_rules.rs @@ -10,7 +10,7 @@ //! //! 1. **[`classify_recovery`]** — the canonical v1.186 A7 recovery classifier //! (P0 Task 2). It consumes the authoritative v1 status plus the -//! deserialized [`crate::run_state::RunStateV1`] (A2 durable state) and +//! deserialized [`nexus_session_storage::run_state::RunStateV1`] (A2 durable state) and //! yields one of seven [`RecoveryClass`] values. Daemon boot/resume, ops //! detail, and ops list all call it — there is exactly ONE recovery //! precedence for v1 rows (first rule that fires): @@ -48,7 +48,7 @@ //! consumers carry it as the separate `runner_check` caveat. use crate::engine::SessionStatus; -use crate::run_state::RunStateV1; +use nexus_session_storage::run_state::RunStateV1; use serde_json::{Map, Value}; /// Canonical A7 recovery classification (v1.186 P0, Task 2). @@ -520,12 +520,12 @@ mod tests { fn state(step_in_flight: Option<&str>, cancel_requested: bool, wait: bool) -> RunStateV1 { RunStateV1 { - wait: wait.then(|| crate::run_state::WaitRecord { + wait: wait.then(|| nexus_session_storage::run_state::WaitRecord { wait_id: "w1".to_string(), task_id: "t1".to_string(), child_session_id: None, child_task_id: None, - kind: crate::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }), step_in_flight: step_in_flight.map(str::to_string), in_flight: None, diff --git a/crates/nexus-orchestration/src/schedule/supervisor.rs b/crates/nexus-orchestration/src/schedule/supervisor.rs index edfdccdec..54e3ffc8d 100644 --- a/crates/nexus-orchestration/src/schedule/supervisor.rs +++ b/crates/nexus-orchestration/src/schedule/supervisor.rs @@ -20,7 +20,7 @@ use nexus_local_db::SqlitePool; use tokio::sync::Mutex; use super::admission::{admit, CompletedSet, RunningSet}; -use crate::run_state::WorkflowStateStore; +use nexus_session_storage::run_state::WorkflowStateStore; /// `creator_schedules.execution_policy` value for a never-started legacy row /// (the migration default). @@ -1078,7 +1078,7 @@ impl ScheduleSupervisor { &self, stage: &str, work_id: &str, - ) -> Option> { + ) -> Option> { let preset_id = crate::stage_gates::preset_for_stage(stage)?; if let Some(provider_id) = self.binding_provider.as_ref().as_ref() { crate::preset_runtime::default_bindings_for_preset(preset_id, provider_id).map_or_else( @@ -1434,7 +1434,7 @@ impl ScheduleSupervisor { /// Insert a pending schedule with a frozen execution descriptor (A3, /// C-2/I-5). /// - /// The descriptor (serialized [`crate::run_state::RunDescriptorV1`]) is + /// The descriptor (serialized [`nexus_session_storage::run_state::RunDescriptorV1`]) is /// persisted in the SAME transaction as the schedule row and dependency /// rows, so a concurrent tick can never observe a `driven_v1` row before /// its descriptor/input/bindings are durable. `_system.*` presets are @@ -1560,7 +1560,7 @@ impl ScheduleSupervisor { // descriptor). let descriptor_work_id: Option = execution_descriptor .and_then(|bytes| { - serde_json::from_slice::(bytes).ok() + serde_json::from_slice::(bytes).ok() }) .and_then(|d| d.work_id) .filter(|id| !id.is_empty()); @@ -1781,7 +1781,7 @@ impl ScheduleSupervisor { .fetch_all(&*self.pool) .await?; - let store = crate::storage::sqlite::SqliteSessionStorage::new(self.pool.clone()); + let store = nexus_session_storage::storage::sqlite::SqliteSessionStorage::new(self.pool.clone()); let mut reconciled = 0usize; for (schedule_id, session_id) in rows { let record = match store @@ -3376,7 +3376,7 @@ mod tests_t9 { // Durable v1 session: terminal `completed` with a CORRUPT run-state // blob — the previous recovery pass hit a transient storage error // while loading it. - let descriptor = serde_json::to_vec(&crate::run_state::RunDescriptorV1 { + let descriptor = serde_json::to_vec(&nexus_session_storage::run_state::RunDescriptorV1 { creator_id: "test-creator".to_string(), work_id: None, workspace_root: std::path::PathBuf::new(), @@ -3443,7 +3443,7 @@ mod tests_t9 { // retried and settles from the durable terminal — paused rows are // inside the reconcile scan and errors never permanently exclude. let good_state = - serde_json::to_vec(&crate::run_state::RunStateV1::default()).expect("run state json"); + serde_json::to_vec(&nexus_session_storage::run_state::RunStateV1::default()).expect("run state json"); sqlx::query("UPDATE orchestration_sessions SET run_state_json = ? WHERE session_id = ?") .bind(&good_state) .bind("SES-P1-1") diff --git a/crates/nexus-orchestration/tests/research_supervisor_e2e.rs b/crates/nexus-orchestration/tests/research_supervisor_e2e.rs index d3d75343e..d94cfea6c 100644 --- a/crates/nexus-orchestration/tests/research_supervisor_e2e.rs +++ b/crates/nexus-orchestration/tests/research_supervisor_e2e.rs @@ -162,7 +162,7 @@ impl ResearchScheduleFixture { // (manifest + referenced template bytes) — never a zero placeholder. let source = nexus_preset::embedded_source_identity("research") .expect("research preset must carry an embedded source identity"); - let descriptor = nexus_orchestration::run_state::RunDescriptorV1 { + let descriptor = nexus_session_storage::run_state::RunDescriptorV1 { creator_id: self.creator_id.to_string(), work_id: Some(self.work_id.to_string()), workspace_root: std::path::PathBuf::new(), diff --git a/crates/nexus-orchestration/tests/sqlite_storage_roundtrip.rs b/crates/nexus-orchestration/tests/sqlite_storage_roundtrip.rs index a8e6f0d0a..6ec98121f 100644 --- a/crates/nexus-orchestration/tests/sqlite_storage_roundtrip.rs +++ b/crates/nexus-orchestration/tests/sqlite_storage_roundtrip.rs @@ -1,5 +1,5 @@ use graph_flow::{Session, SessionStorage}; -use nexus_orchestration::storage::sqlite::SqliteSessionStorage; +use nexus_session_storage::storage::sqlite::SqliteSessionStorage; use std::sync::Arc; #[tokio::test] diff --git a/crates/nexus-orchestration/tests/system_preset_e2e.rs b/crates/nexus-orchestration/tests/system_preset_e2e.rs index 7e21d4470..598e185a5 100644 --- a/crates/nexus-orchestration/tests/system_preset_e2e.rs +++ b/crates/nexus-orchestration/tests/system_preset_e2e.rs @@ -58,7 +58,7 @@ async fn restart_durability_e2e() { .await .expect("open_pool"); let pool = guarded.clone_pool(); - let storage = Arc::new(nexus_orchestration::storage::SqliteSessionStorage::new( + let storage = Arc::new(nexus_session_storage::storage::SqliteSessionStorage::new( std::sync::Arc::new(pool), )); let registry = Arc::new(CapabilityRegistry::with_builtins()); @@ -93,7 +93,7 @@ async fn restart_durability_e2e() { .await .expect("open_pool v2"); let pool = guarded.clone_pool(); - let storage = Arc::new(nexus_orchestration::storage::SqliteSessionStorage::new( + let storage = Arc::new(nexus_session_storage::storage::SqliteSessionStorage::new( std::sync::Arc::new(pool), )); diff --git a/crates/nexus-orchestration/tests/workflow_run_state.rs b/crates/nexus-orchestration/tests/workflow_run_state.rs index 74bc8ac6e..95effbf08 100644 --- a/crates/nexus-orchestration/tests/workflow_run_state.rs +++ b/crates/nexus-orchestration/tests/workflow_run_state.rs @@ -23,11 +23,12 @@ use graph_flow::{Session, SessionStorage}; use nexus_contracts::generated::daemon_api::orchestration::workflow_document::WorkflowDocument; use nexus_orchestration::capability::{AppliedDocument, AppliedDocumentSource}; use nexus_orchestration::engine::{SessionId, SessionStatus}; -use nexus_orchestration::run_state::{ +use nexus_session_storage::StorageError as EngineError; +use nexus_session_storage::run_state::{ AgentBinding, AppliedRunIdentity, ChildCheckpoint, RunCheckpoint, RunDescriptorV1, RunStateV1, TerminalSettlementTarget, WorkflowStateStore, }; -use nexus_orchestration::storage::sqlite::SqliteSessionStorage; +use nexus_session_storage::storage::sqlite::SqliteSessionStorage; use nexus_orchestration::OrchestrationEngine; use nexus_preset::source_identity::PresetSourceIdentity; use std::collections::HashMap; @@ -200,12 +201,12 @@ async fn wait_status_survives_reopen() { // Commit a human-wait transition with a durable wait record. let wait_state = RunStateV1 { - wait: Some(nexus_orchestration::run_state::WaitRecord { + wait: Some(nexus_session_storage::run_state::WaitRecord { wait_id: "wait-abc".to_string(), task_id: "wait_task".to_string(), child_session_id: None, child_task_id: None, - kind: nexus_orchestration::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }), ..RunStateV1::default() }; @@ -362,7 +363,7 @@ async fn commit_transition_with_wrong_revision_fails() { .expect_err("wrong expected revision must fail the CAS"); match err { - nexus_orchestration::engine::EngineError::RevisionMismatch { + EngineError::RevisionMismatch { session_id: sid, expected, found, @@ -442,7 +443,7 @@ async fn commit_transition_after_terminal_fails() { assert!( matches!( err, - nexus_orchestration::engine::EngineError::TerminalState(_) + EngineError::TerminalState(_) ), "expected TerminalState, got {err:?}" ); @@ -531,7 +532,7 @@ fn descriptor_serializes_the_applied_identity_only_when_present() { ); let mut applied = test_descriptor("sess"); - applied.applied = Some(nexus_orchestration::run_state::AppliedRunIdentity { + applied.applied = Some(nexus_session_storage::run_state::AppliedRunIdentity { apply_id: "apl_1".to_string(), content_hash: "blake3:abc".to_string(), }); @@ -702,7 +703,7 @@ async fn corrupt_blobs_preserved_not_reinterpreted() { .expect_err("corrupt blob must not be silently reinterpreted"); assert!( - matches!(err, nexus_orchestration::engine::EngineError::GraphFlow(_)), + matches!(err, EngineError::GraphFlow(_)), "expected GraphFlow error for corrupt blob, got {err:?}" ); @@ -1080,7 +1081,7 @@ async fn engine_wait_produces_durable_wait_token() { !wait.wait_id.is_empty(), "wait token must be a fresh UUID, not empty" ); - assert_eq!(wait.kind, nexus_orchestration::run_state::WaitKind::Manual); + assert_eq!(wait.kind, nexus_session_storage::run_state::WaitKind::Manual); let wait_id = wait.wait_id; let revision = record.state_revision; @@ -1192,7 +1193,7 @@ async fn in_flight_marker_fences_control_signals_and_stale_transition() { .expect_err("transition loaded before the marker must lose its CAS"); assert!(matches!( stale, - nexus_orchestration::engine::EngineError::RevisionMismatch { .. } + EngineError::RevisionMismatch { .. } )); let after = storage .load_run(&sid) @@ -1480,7 +1481,7 @@ async fn unknown_v1_status_is_non_replayable() { .await .expect_err("unknown v1 status must be non-replayable"); assert!( - matches!(err, nexus_orchestration::engine::EngineError::GraphFlow(_)), + matches!(err, EngineError::GraphFlow(_)), "expected GraphFlow error for unknown status, got {err:?}" ); } @@ -1510,7 +1511,7 @@ async fn v1_row_missing_metadata_is_non_replayable() { .await .expect_err("v1 row missing descriptor must be non-replayable"); assert!( - matches!(err, nexus_orchestration::engine::EngineError::GraphFlow(_)), + matches!(err, EngineError::GraphFlow(_)), "expected GraphFlow error, got {err:?}" ); } @@ -1518,12 +1519,12 @@ async fn v1_row_missing_metadata_is_non_replayable() { // Important 7: WaitKind and PromptPhase encode as snake_case. #[test] fn wait_kind_and_prompt_phase_encode_snake_case() { - let wait = nexus_orchestration::run_state::WaitRecord { + let wait = nexus_session_storage::run_state::WaitRecord { wait_id: "w".to_string(), task_id: "t".to_string(), child_session_id: None, child_task_id: None, - kind: nexus_orchestration::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }; let json = serde_json::to_value(&wait).expect("serialize wait"); assert_eq!( @@ -1532,10 +1533,10 @@ fn wait_kind_and_prompt_phase_encode_snake_case() { json["kind"] ); - let attempt = nexus_orchestration::run_state::PromptAttempt { + let attempt = nexus_session_storage::run_state::PromptAttempt { attempt_id: "a".to_string(), task_id: "t".to_string(), - phase: nexus_orchestration::run_state::PromptPhase::Dispatching, + phase: nexus_session_storage::run_state::PromptPhase::Dispatching, host_session_id: None, operation_id: None, process_identity: None, @@ -1547,8 +1548,8 @@ fn wait_kind_and_prompt_phase_encode_snake_case() { json["phase"] ); - let active = nexus_orchestration::run_state::PromptAttempt { - phase: nexus_orchestration::run_state::PromptPhase::Active, + let active = nexus_session_storage::run_state::PromptAttempt { + phase: nexus_session_storage::run_state::PromptPhase::Active, ..attempt }; let json = serde_json::to_value(&active).expect("serialize active"); @@ -1594,7 +1595,7 @@ async fn start_run_refuses_existing_v0_row() { .expect_err("start_run must refuse an existing v0 row"); match err { - nexus_orchestration::engine::EngineError::RunAlreadyExists { + EngineError::RunAlreadyExists { session_id, execution_version, } => { @@ -1654,7 +1655,7 @@ async fn start_run_reports_accurate_conflict_for_v1_row() { .expect_err("second start_run must be refused"); match err { - nexus_orchestration::engine::EngineError::RunAlreadyExists { + EngineError::RunAlreadyExists { session_id: sid, execution_version, } => { @@ -1772,7 +1773,7 @@ async fn child_cas_stale_revision_rolls_back_root() { assert!( matches!( err, - nexus_orchestration::engine::EngineError::RevisionMismatch { .. } + EngineError::RevisionMismatch { .. } ), "expected RevisionMismatch for stale child, got {err:?}" ); @@ -1914,7 +1915,7 @@ async fn child_cas_terminal_child_rolls_back_root() { assert!( matches!( err, - nexus_orchestration::engine::EngineError::TerminalState(_) + EngineError::TerminalState(_) ), "expected TerminalState for terminal child at stale revision, got {err:?}" ); @@ -2228,7 +2229,7 @@ async fn unknown_v0_status_is_non_replayable() { .await .expect_err("unknown v0 status must be non-replayable"); assert!( - matches!(err, nexus_orchestration::engine::EngineError::GraphFlow(_)), + matches!(err, EngineError::GraphFlow(_)), "expected GraphFlow error for unknown v0 status, got {err:?}" ); @@ -2274,7 +2275,7 @@ async fn negative_v0_revision_is_non_replayable() { .await .expect_err("negative v0 revision must be non-replayable"); assert!( - matches!(err, nexus_orchestration::engine::EngineError::GraphFlow(_)), + matches!(err, EngineError::GraphFlow(_)), "expected GraphFlow error for negative revision, got {err:?}" ); @@ -4132,7 +4133,7 @@ async fn negative_v1_revision_is_non_replayable() { .await .expect_err("negative v1 revision must be non-replayable"); assert!( - matches!(err, nexus_orchestration::engine::EngineError::GraphFlow(_)), + matches!(err, EngineError::GraphFlow(_)), "expected GraphFlow error for negative v1 revision, got {err:?}" ); @@ -4197,7 +4198,7 @@ async fn child_terminal_status_mismatch_rejects_confirmation() { .expect_err("terminal child status mismatch must reject the parent's Completed commit"); assert!( - matches!(err, nexus_orchestration::engine::EngineError::GraphFlow(_)), + matches!(err, EngineError::GraphFlow(_)), "expected GraphFlow mismatch error, got {err:?}" ); @@ -4581,7 +4582,7 @@ async fn restore_pre_step_is_single_atomic_revision_fence() { assert!( matches!( err, - nexus_orchestration::engine::EngineError::RevisionMismatch { expected: 1, .. } + EngineError::RevisionMismatch { expected: 1, .. } ), "expected RevisionMismatch(expected=1), got {err:?}" ); @@ -4640,7 +4641,7 @@ async fn negative_execution_version_is_non_replayable() { .await .expect_err("negative execution_version must be non-replayable"); assert!( - matches!(err, nexus_orchestration::engine::EngineError::GraphFlow(_)), + matches!(err, EngineError::GraphFlow(_)), "expected GraphFlow error, got {err:?}" ); @@ -4684,7 +4685,7 @@ async fn unsupported_forward_execution_version_is_non_replayable() { .await .expect_err("forward execution_version must be non-replayable"); assert!( - matches!(err, nexus_orchestration::engine::EngineError::GraphFlow(_)), + matches!(err, EngineError::GraphFlow(_)), "expected GraphFlow error, got {err:?}" ); @@ -5126,7 +5127,7 @@ async fn negative_child_revision_is_non_replayable() { .await .expect_err("negative child state_revision must be non-replayable"); assert!( - matches!(err, nexus_orchestration::engine::EngineError::GraphFlow(_)), + matches!(err, EngineError::GraphFlow(_)), "expected GraphFlow error for negative child revision, got {err:?}" ); @@ -5182,12 +5183,12 @@ async fn stale_mark_step_in_flight_against_waiting_row_leaves_wait_untouched() { // Commit a human-wait transition with a durable WaitRecord (revision 1 → 2). let wait_state = RunStateV1 { - wait: Some(nexus_orchestration::run_state::WaitRecord { + wait: Some(nexus_session_storage::run_state::WaitRecord { wait_id: "wait-mark-token".to_string(), task_id: "wait_task".to_string(), child_session_id: None, child_task_id: None, - kind: nexus_orchestration::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }), ..RunStateV1::default() }; @@ -5281,12 +5282,12 @@ async fn stale_restore_pre_step_against_waiting_row_leaves_wait_untouched() { // Commit a human-wait transition with a durable WaitRecord (revision 1 → 2). let wait_state = RunStateV1 { - wait: Some(nexus_orchestration::run_state::WaitRecord { + wait: Some(nexus_session_storage::run_state::WaitRecord { wait_id: "wait-restore-token".to_string(), task_id: "wait_task".to_string(), child_session_id: None, child_task_id: None, - kind: nexus_orchestration::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }), ..RunStateV1::default() }; @@ -5317,7 +5318,7 @@ async fn stale_restore_pre_step_against_waiting_row_leaves_wait_untouched() { assert!( matches!( err, - nexus_orchestration::engine::EngineError::TerminalState(_) + EngineError::TerminalState(_) ), "expected TerminalState for a waiting_for_input restore, got {err:?}" ); @@ -5380,12 +5381,12 @@ async fn engine_effectful_task_does_not_dispatch_before_in_flight_mark() { .expect("get pre-wait root") .expect("root present"); let wait_state = RunStateV1 { - wait: Some(nexus_orchestration::run_state::WaitRecord { + wait: Some(nexus_session_storage::run_state::WaitRecord { wait_id: "wait-engine-gate".to_string(), task_id: root.current_task_id.clone(), child_session_id: None, child_task_id: None, - kind: nexus_orchestration::run_state::WaitKind::Manual, + kind: nexus_session_storage::run_state::WaitKind::Manual, }), ..RunStateV1::default() }; @@ -5703,7 +5704,7 @@ async fn engine_manual_wait_persists_waiting_for_input_fresh_retained_token() { !wait.wait_id.is_empty(), "the wait token must be a fresh UUID, not empty" ); - assert_eq!(wait.kind, nexus_orchestration::run_state::WaitKind::Manual); + assert_eq!(wait.kind, nexus_session_storage::run_state::WaitKind::Manual); let token = wait.wait_id.clone(); // Reopen the SAME DB file (daemon restart boundary): the token must @@ -6467,9 +6468,9 @@ async fn force_db_graph_version(pool: &sqlx::SqlitePool, session_id: &str, versi /// A corrupt/exhausted graph counter is a HARD storage error, never a /// concurrency (revision/terminal/conflict) outcome. -fn assert_hard_storage_error(err: &nexus_orchestration::engine::EngineError, what: &str) { +fn assert_hard_storage_error(err: &nexus_session_storage::StorageError, what: &str) { match err { - nexus_orchestration::engine::EngineError::GraphFlow( + nexus_session_storage::StorageError::GraphFlow( graph_flow::GraphError::StorageError(_), ) => {} other => panic!("{what}: expected hard GraphError::StorageError, got {other:?}"), @@ -6836,10 +6837,10 @@ async fn graph_version_clock_monotonic_across_writers_and_untouched_by_prompt_at // Prompt-attempt writes are in-task metadata under the runner-owned // session: they must NOT advance the graph clock (brief 3.3). - let attempt = nexus_orchestration::run_state::PromptAttempt { + let attempt = nexus_session_storage::run_state::PromptAttempt { attempt_id: uuid::Uuid::new_v4().to_string(), task_id: "task_b".to_string(), - phase: nexus_orchestration::run_state::PromptPhase::Dispatching, + phase: nexus_session_storage::run_state::PromptPhase::Dispatching, host_session_id: None, operation_id: None, process_identity: None, diff --git a/crates/nexus-session-storage/Cargo.toml b/crates/nexus-session-storage/Cargo.toml new file mode 100644 index 000000000..2649c7bd3 --- /dev/null +++ b/crates/nexus-session-storage/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "nexus-session-storage" +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +description = "Session identity/status types and the storage error contract for the orchestration session store" + +[lints] +workspace = true + +[dependencies] +async-trait = { workspace = true } +chrono = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +sqlx = { workspace = true } +thiserror = { workspace = true } + +graph-flow = { version = "=0.8.1", default-features = false } +nexus-home-layout = { path = "../nexus-home-layout" } +nexus-local-db = { path = "../nexus-local-db" } +nexus-preset = { path = "../nexus-preset" } diff --git a/crates/nexus-session-storage/src/lib.rs b/crates/nexus-session-storage/src/lib.rs new file mode 100644 index 000000000..d8c670f15 --- /dev/null +++ b/crates/nexus-session-storage/src/lib.rs @@ -0,0 +1,151 @@ +//! nexus-session-storage — session identity/status types and the storage +//! error contract for the orchestration session store. +//! +//! Extracted from `nexus-orchestration::engine` so session-store code can +//! depend on these types without depending on the engine; the engine module +//! re-exports them so existing consumer paths stay unchanged. + +pub mod run_state; +pub mod storage; + +pub use storage::sqlite::SqliteSessionStorage; + +use thiserror::Error; + +/// Opaque session identifier. +#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct SessionId(pub String); + +/// Lightweight summary returned by `OrchestrationEngine::list_active`. +#[derive(Debug, Clone)] +pub struct SessionSummary { + pub session_id: SessionId, + pub creator_id: String, + pub preset_id: String, + pub status: SessionStatus, + pub current_task_id: Option, +} + +/// Runtime status of a session. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum SessionStatus { + Running, + Paused, + WaitingForInput, + Completed, + Failed, + /// Cancelled by an operator; terminal, never auto-driven. + Cancelled, + /// Interrupted — uncertain in-flight work; stopped, never safe retry. + Interrupted, +} + +impl SessionStatus { + /// Returns `true` if the session is in a terminal state. + #[must_use] + pub const fn is_terminal(&self) -> bool { + matches!( + self, + Self::Completed | Self::Failed | Self::Cancelled | Self::Interrupted + ) + } + + /// Returns `true` if the session has completed successfully. + #[must_use] + pub const fn is_completed(&self) -> bool { + matches!(self, Self::Completed) + } + + /// Map to the authoritative DB `status` string (A2). + #[must_use] + pub const fn as_db_str(&self) -> &'static str { + match self { + Self::Running => "running", + Self::Paused => "paused", + Self::WaitingForInput => "waiting_for_input", + Self::Completed => "completed", + Self::Failed => "failed", + Self::Cancelled => "cancelled", + Self::Interrupted => "interrupted", + } + } + + /// Parse a DB `status` string back into a [`SessionStatus`]. + /// + /// Returns `None` for unknown/unsupported values (A7): a corrupt or + /// ambiguous status must never be silently reinterpreted as `Running`. + /// Callers that need strict parsing should treat `None` as + /// unknown/non-replayable. + #[must_use] + pub fn from_db_str(status: &str) -> Option { + match status { + "running" => Some(Self::Running), + "paused" => Some(Self::Paused), + "waiting_for_input" => Some(Self::WaitingForInput), + "completed" => Some(Self::Completed), + "failed" => Some(Self::Failed), + "cancelled" => Some(Self::Cancelled), + "interrupted" => Some(Self::Interrupted), + _ => None, + } + } +} + +/// Errors produced by the session storage layer. +/// +/// Variant shapes and `Display` strings mirror the session-persistence +/// variants of `nexus-orchestration::engine::EngineError` byte-for-byte, so +/// `From for EngineError` preserves the exact rendering. +#[derive(Error, Debug)] +pub enum StorageError { + /// Underlying graph-flow storage failure (serialization, CAS bookkeeping). + #[error("graph-flow error: {0}")] + GraphFlow(#[from] graph_flow::GraphError), + #[error("session not found: {0}")] + SessionNotFound(String), + /// A revision compare-and-swap failed: the persisted `state_revision` no + /// longer equals the expected value (a concurrent transition won). + #[error( + "state revision mismatch for session {session_id}: expected {expected}, found {found}" + )] + RevisionMismatch { + /// Session id. + session_id: String, + /// Expected revision. + expected: u64, + /// Persisted revision. + found: u64, + }, + /// A transition was attempted on a row that is already terminal or + /// cancelled — late graph saves must not overwrite newer checkpoint state. + #[error("session {0} is already terminal/cancelled; refusing transition")] + TerminalState(String), + /// A new v1 run was requested for a session id that already has a row. + /// + /// A real explicit new start creates a **new** v1 run (new session id); + /// it never launders an existing uncertain legacy row in place (A2). + #[error( + "session {session_id} already exists (execution_version={execution_version}); \ + a new run must use a new session id" + )] + RunAlreadyExists { + /// Session id. + session_id: String, + /// Persisted execution version of the existing row. + execution_version: u32, + }, + /// A human-wait continuation token was stale, consumed, or wrong (A4). + /// + /// The caller must surface the current persisted status and current + /// wait id (null when none) so the operator can re-issue the exact + /// token. No mutation occurred and no second driver was started. + #[error("wait conflict for session {session_id}: token does not match the current wait")] + WaitConflict { + /// Session id. + session_id: String, + /// Current persisted status. + status: SessionStatus, + /// Current durable wait id (null when the run is not waiting). + current_wait_id: Option, + }, +} diff --git a/crates/nexus-orchestration/src/run_state.rs b/crates/nexus-session-storage/src/run_state.rs similarity index 99% rename from crates/nexus-orchestration/src/run_state.rs rename to crates/nexus-session-storage/src/run_state.rs index 51d7bb050..36b95f2e7 100644 --- a/crates/nexus-orchestration/src/run_state.rs +++ b/crates/nexus-session-storage/src/run_state.rs @@ -13,7 +13,7 @@ use std::path::PathBuf; use async_trait::async_trait; use serde::{Deserialize, Serialize}; -use crate::engine::{EngineError, SessionId, SessionStatus}; +use crate::{SessionId, SessionStatus, StorageError as EngineError}; use nexus_preset::source_identity::PresetSourceIdentity; /// Frozen server-side descriptor for a v1 run (A2). diff --git a/crates/nexus-orchestration/src/storage/inspect.rs b/crates/nexus-session-storage/src/storage/inspect.rs similarity index 100% rename from crates/nexus-orchestration/src/storage/inspect.rs rename to crates/nexus-session-storage/src/storage/inspect.rs diff --git a/crates/nexus-orchestration/src/storage/mod.rs b/crates/nexus-session-storage/src/storage/mod.rs similarity index 100% rename from crates/nexus-orchestration/src/storage/mod.rs rename to crates/nexus-session-storage/src/storage/mod.rs diff --git a/crates/nexus-orchestration/src/storage/sqlite.rs b/crates/nexus-session-storage/src/storage/sqlite.rs similarity index 99% rename from crates/nexus-orchestration/src/storage/sqlite.rs rename to crates/nexus-session-storage/src/storage/sqlite.rs index 8e3a130eb..b1b79ba44 100644 --- a/crates/nexus-orchestration/src/storage/sqlite.rs +++ b/crates/nexus-session-storage/src/storage/sqlite.rs @@ -36,7 +36,7 @@ use graph_flow::{Session, SessionStorage}; use std::sync::Arc; use super::inspect::{CheckpointRow, CheckpointSummary}; -use crate::engine::{EngineError, SessionId, SessionStatus, SessionSummary}; +use crate::{SessionId, SessionStatus, SessionSummary, StorageError as EngineError}; use crate::run_state::{ ChildCheckpoint, PromptAttempt, RunCheckpoint, RunDescriptorV1, RunRecord, RunStateV1, SettlementResult, TerminalSettlementTarget, WorkflowStateStore, @@ -541,7 +541,7 @@ async fn child_cas_outcome( } let found_rev = row.state_revision; let status = row.status; - if crate::engine::SessionStatus::from_db_str(&status).is_none() { + if crate::SessionStatus::from_db_str(&status).is_none() { return Err(EngineError::GraphFlow(graph_flow::GraphError::StorageError( format!( "child CAS outcome for '{child_id}': unknown/corrupt status {status:?} (non-replayable)" @@ -1034,7 +1034,7 @@ async fn classify_transition_fence_miss( } // An unknown/corrupt status is corruption, never a concurrency or // terminal outcome (Important 6). - Some(row) if crate::engine::SessionStatus::from_db_str(&row.status).is_none() => { + Some(row) if crate::SessionStatus::from_db_str(&row.status).is_none() => { EngineError::GraphFlow(graph_flow::GraphError::StorageError(format!( "{op} '{}': unknown/corrupt status {:?} (non-replayable)", session_id.0, row.status @@ -1433,7 +1433,7 @@ async fn classify_restore_fence_miss( // deterministic `TerminalState`/`RevisionMismatch` outcomes the // engine treats as an expected concurrent winner — it is corruption, // checked before the revision fence (Important 6). - Some(row) if crate::engine::SessionStatus::from_db_str(&row.status).is_none() => { + Some(row) if crate::SessionStatus::from_db_str(&row.status).is_none() => { EngineError::GraphFlow(graph_flow::GraphError::StorageError(format!( "restore_pre_step '{}': unknown/corrupt status {:?} (non-replayable)", session_id.0, row.status @@ -1488,7 +1488,7 @@ async fn classify_mark_fence_miss( } // An unpersistable status string is corruption: a hard storage // error, never a concurrency/terminal outcome (Important 6). - Some(row) if crate::engine::SessionStatus::from_db_str(&row.status).is_none() => { + Some(row) if crate::SessionStatus::from_db_str(&row.status).is_none() => { EngineError::GraphFlow(graph_flow::GraphError::StorageError(format!( "mark_step_in_flight '{}': unknown/corrupt status {:?} (non-replayable)", session_id.0, row.status @@ -1606,7 +1606,7 @@ async fn read_post_write_clocks( session_id.0, clocks.graph_version ))) })?; - let status = crate::engine::SessionStatus::from_db_str(&clocks.status).ok_or_else(|| { + let status = crate::SessionStatus::from_db_str(&clocks.status).ok_or_else(|| { EngineError::GraphFlow(graph_flow::GraphError::StorageError(format!( "{op} '{}': unknown/corrupt status {:?} (non-replayable)", session_id.0, clocks.status From 51fbfb2be447ec80ca0e84e32d974755be9ee1f8 Mon Sep 17 00:00:00 2001 From: Bohao Tang Date: Wed, 18 Nov 2026 01:44:43 +0800 Subject: [PATCH 02/15] refactor(canvas): delete unreachable structural-write affordances --- .../strategy-canvas-compose.test.tsx | 20 +- ...ategy-canvas-no-create-affordance.test.tsx | 212 +++++++ .../strategy-canvas-simulate.test.tsx | 20 +- .../canvas/canvas-surface-commands.test.tsx | 49 +- .../src/components/canvas/strategy-canvas.tsx | 102 +--- .../canvas/strategy-canvas/canvas-layout.tsx | 38 -- .../edge-create-dialog.test.tsx | 123 ---- .../strategy-canvas/edge-create-dialog.tsx | 175 ------ .../hooks/use-strategy-canvas.test.tsx | 551 +----------------- .../hooks/use-strategy-canvas.ts | 302 +--------- .../inspectors/edge-inspector.test.tsx | 136 ----- .../inspectors/edge-inspector.tsx | 261 +-------- .../inspector-save-trigger.test.tsx | 235 -------- .../inspectors/prompt-inspector.tsx | 154 +---- .../inspectors/state-inspector.test.tsx | 93 --- .../inspectors/state-inspector.tsx | 155 +---- .../canvas/strategy-canvas/state-machine.tsx | 36 +- .../strategy-canvas-adapter.compose.test.tsx | 196 +------ .../strategy-canvas-adapter.tsx | 73 +-- .../canvas/strategy-yaml-authority.test.ts | 91 --- .../src/lib/canvas/strategy-yaml-authority.ts | 85 --- 21 files changed, 279 insertions(+), 2828 deletions(-) create mode 100644 apps/web/src/components/canvas/__tests__/strategy-canvas-no-create-affordance.test.tsx delete mode 100644 apps/web/src/components/canvas/strategy-canvas/edge-create-dialog.test.tsx delete mode 100644 apps/web/src/components/canvas/strategy-canvas/edge-create-dialog.tsx delete mode 100644 apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.test.tsx delete mode 100644 apps/web/src/components/canvas/strategy-canvas/inspectors/inspector-save-trigger.test.tsx delete mode 100644 apps/web/src/components/canvas/strategy-canvas/inspectors/state-inspector.test.tsx delete mode 100644 apps/web/src/lib/canvas/strategy-yaml-authority.test.ts delete mode 100644 apps/web/src/lib/canvas/strategy-yaml-authority.ts diff --git a/apps/web/src/components/canvas/__tests__/strategy-canvas-compose.test.tsx b/apps/web/src/components/canvas/__tests__/strategy-canvas-compose.test.tsx index a88b560ae..90de26aeb 100644 --- a/apps/web/src/components/canvas/__tests__/strategy-canvas-compose.test.tsx +++ b/apps/web/src/components/canvas/__tests__/strategy-canvas-compose.test.tsx @@ -41,30 +41,17 @@ vi.mock('@/components/canvas/strategy-canvas/hooks/use-strategy-canvas', () => ( revision: 1, activeSession: null, creatorId: 'c1', - baseRevision: 1, activeScheduleId: undefined, - draftEdges: [], - onConnect: () => {}, - onReconnect: () => {}, form: { label: '', description: '', nextTarget: '', promptBody: '' }, setForm: () => {}, - saveStatuses: {}, - setSaveStatuses: () => {}, + activeSection: 'state', setActiveSection: () => {}, conflict: null, setConflict: () => {}, - saveTriggers: {}, - workingRevisionRef: { current: 1 }, + saveTriggers: { state: 0, transition: 0, prompt: 0 }, + setSaveTriggers: () => {}, handleConflict: () => {}, handleReapply: () => {}, - selectedDraftEdge: null, - draftSourceState: null, - commitDraft: () => {}, - isCommittingDraft: false, - cancelDraft: () => {}, - commitKeyboardCreate: () => {}, - isCommittingKeyboardCreate: false, - isReconnecting: false, }), })); @@ -73,7 +60,6 @@ vi.mock('@/components/canvas/strategy-canvas/inspectors/state-inspector', () => })); vi.mock('@/components/canvas/strategy-canvas/inspectors/edge-inspector', () => ({ EdgeInspector: () => null, - DraftEdgeInspector: () => null, })); vi.mock('@/components/canvas/strategy-canvas/inspectors/prompt-inspector', () => ({ PromptInspector: () => null, diff --git a/apps/web/src/components/canvas/__tests__/strategy-canvas-no-create-affordance.test.tsx b/apps/web/src/components/canvas/__tests__/strategy-canvas-no-create-affordance.test.tsx new file mode 100644 index 000000000..c597a9a5c --- /dev/null +++ b/apps/web/src/components/canvas/__tests__/strategy-canvas-no-create-affordance.test.tsx @@ -0,0 +1,212 @@ +/** + * Strategy canvas — no create affordance on either document shape + * (canvas-legacy-affordances Task 4). + * + * Both shapes the canvas can render are read-only: the applied document and the + * Compose working document. Neither may offer edge creation, transition + * creation or an inspector save — the deleted YAML-authoring entry points must + * not come back through a graph gesture, the keyboard shortcut, the palette, + * the header, or the inspector sections the adapter renders for a selected node. + */ +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { http, HttpResponse } from 'msw'; +import type { NodeChange } from '@xyflow/react'; +import type { MutableRefObject } from 'react'; +import type { WorkflowDocument } from '@42ch/nexus-contracts'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { StrategyCanvas } from '@/components/canvas/strategy-canvas'; +import { + createStrategyCanvasAdapter, + type StrategyCanvasAdapterContext, +} from '@/components/canvas/strategy-canvas/strategy-canvas-adapter'; +import { originalFormOf } from '@/components/canvas/strategy-canvas/state-machine'; +import { clearCommands, getCommands } from '@/lib/canvas/command-registry'; +import { parsedPresetFromIr } from '@/lib/canvas/ir-preset'; +import { COMPOSE_FLAG_STORAGE_KEY } from '@/lib/canvas/strategy-compose-flag'; +import { BrowserClient } from '@/lib/nexus'; +import { useHandlers } from '@/test/msw-server'; +import { servedIrDocument } from '@/test/simulation-fixture'; +import { renderInApp } from '@/test/test-providers'; + +const shellProps = vi.hoisted(() => ({ current: {} as Record })); + +vi.mock('@/components/canvas/canvas-shell', () => ({ + // Keep React Flow out of jsdom. The children are the inspector chrome a + // selected node renders; the props are what the shell would wire. + CanvasShell: (props: { children?: React.ReactNode } & Record) => { + shellProps.current = props; + return <>{props.children}; + }, + useNodeChangeHandler: () => () => {}, +})); + +// Not part of this proof, and it mounts its own queries. +vi.mock('@/components/canvas/idea-input', () => ({ + IdeaInput: () => null, +})); + +const STRATEGY_ID = 'novel-writing'; +const APPLIED_PATH = `/v1/daemon/strategies/${STRATEGY_ID}/applied`; +const CANDIDATE_PATH = `/v1/daemon/strategies/${STRATEGY_ID}/candidate`; +const APPROVALS_PATH = `/v1/daemon/strategies/${STRATEGY_ID}/approvals`; +const PATTERNS_PATH = '/v1/daemon/patterns'; +const SESSIONS_PATH = '/v1/daemon/orchestration/sessions'; +const SCHEDULES_PATH = '/v1/daemon/orchestration/schedules'; + +const SEED = servedIrDocument({ id: STRATEGY_ID }); +// The entering state carries a prompt template, so all three inspector sections +// (state, transition, prompt) are rendered and asserted. +const DOCUMENT: WorkflowDocument = { + ...SEED, + nodes: SEED.nodes.map((node) => + node.id === 'draft' + ? { ...node, context_update: { op: 'append' as const, template: 'prompts/draft.md' } } + : node, + ), +}; + +function orchestrationHandlers() { + return [ + http.get(SESSIONS_PATH, () => HttpResponse.json({ items: [] })), + http.get(SCHEDULES_PATH, () => HttpResponse.json({ items: [] })), + ]; +} + +function renderCanvas() { + return renderInApp(, { client: new BrowserClient() }); +} + +const composeHandlers = () => ({ + isComposing: false, + onToggleSlotExpanded: () => {}, + onBindSlot: () => Promise.resolve(), + onReplaceSubtree: () => Promise.resolve(), + onUnnest: () => Promise.resolve(), +}); + +/** The canvas itself: no graph gesture, header button or palette create route. */ +function expectCanvasOffersNoCreateRoute(container: HTMLElement) { + const canvas = within(container); + + // Edge creation: no drag-to-connect and no reconnect gesture is wired. + expect(shellProps.current.onConnect).toBeUndefined(); + expect(shellProps.current.onReconnect).toBeUndefined(); + + // The deleted keyboard create gesture opens nothing. + fireEvent.keyDown(window, { key: 'N', shiftKey: true }); + expect(canvas.queryByText('Create Transition')).not.toBeInTheDocument(); + + // Transition create: no header entry, and the palette registers only the + // graph↔list toggle (the create-transition command is gone, not hidden). + expect(canvas.queryByRole('button', { name: 'Create' })).not.toBeInTheDocument(); + expect(getCommands().map((command) => command.id)).toEqual(['strategy.toggle-view']); + + // Inspector save: selecting the entry state and opening its editor reveals + // no save control anywhere in the canvas. + act(() => { + (shellProps.current.onNodesChange as (changes: NodeChange[]) => void)([ + { id: 'draft', type: 'select', selected: true }, + ]); + }); + fireEvent.click(canvas.getByRole('button', { name: 'Edit' })); + expect(canvas.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument(); +} + +/** The inspector sections the adapter renders for that shape's selected state. */ +function expectInspectorOffersNoSave(compose: boolean) { + const parsed = parsedPresetFromIr(DOCUMENT); + const selectedState = parsed.manifest.states.find((state) => state.id === 'draft'); + if (!selectedState) throw new Error('fixture lost its draft state'); + const ctxRef = { + current: { + form: originalFormOf(selectedState), + onChange: () => {}, + setActiveSection: () => {}, + selectedState, + promptTemplateRef: 'prompts/draft.md', + selectedNode: null, + parsed, + onUseCurrent: () => {}, + onReapply: () => {}, + onDismiss: () => {}, + danglingTargets: [], + ...(compose ? { compose: composeHandlers() } : {}), + }, + } as MutableRefObject; + + const { container } = render(<>{createStrategyCanvasAdapter(ctxRef).renderInspector?.(null as never)}); + const inspector = within(container); + expect(inspector.getByLabelText('State inspector')).toBeInTheDocument(); + expect(inspector.getByLabelText('Transition inspector')).toBeInTheDocument(); + expect(inspector.getByLabelText('Prompt inspector')).toBeInTheDocument(); + + const fields = inspector.getAllByRole('textbox'); + expect(fields.length).toBeGreaterThan(0); + for (const field of fields) expect(field).toBeDisabled(); + expect(inspector.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument(); +} + +beforeEach(() => { + clearCommands(); +}); + +afterEach(() => { + cleanup(); + clearCommands(); + window.localStorage.removeItem(COMPOSE_FLAG_STORAGE_KEY); +}); + +describe('StrategyCanvas — no create affordance', () => { + it('offers none on the applied document', async () => { + window.localStorage.removeItem(COMPOSE_FLAG_STORAGE_KEY); + useHandlers( + ...orchestrationHandlers(), + http.get(APPLIED_PATH, () => + HttpResponse.json({ + current_apply: { + apply_id: 'app_1', + approval_id: 'apr_42', + content_hash: 'hash-1', + applied_at: '2026-11-13T01:00:00Z', + supersedes_apply_id: null, + }, + newest_approval: null, + applied_document: DOCUMENT, + applied_document_refusal: null, + }), + ), + ); + + const { container } = renderCanvas(); + // The applied preset is what rendered (revision 0), not a compose candidate. + expect(await screen.findByText('rev 0')).toBeInTheDocument(); + + expectCanvasOffersNoCreateRoute(container); + expectInspectorOffersNoSave(false); + }); + + it('offers none on the Compose working document', async () => { + window.localStorage.setItem(COMPOSE_FLAG_STORAGE_KEY, 'on'); + const workingDocument = { ...DOCUMENT, revision: 4 }; + useHandlers( + ...orchestrationHandlers(), + http.get(APPLIED_PATH, () => + HttpResponse.json({ current_apply: null, newest_approval: null }), + ), + http.get(APPROVALS_PATH, () => HttpResponse.json({ items: [] })), + http.get(CANDIDATE_PATH, () => HttpResponse.json(workingDocument)), + http.get(PATTERNS_PATH, () => + HttpResponse.json({ items: [], pagination: { limit: 100, has_more: false } }), + ), + ); + + const { container } = renderCanvas(); + // The candidate is what rendered (revision 4), on the Compose surface. + expect(await screen.findByTestId('strategy-staging')).toBeInTheDocument(); + expect(await screen.findByText('rev 4')).toBeInTheDocument(); + + expectCanvasOffersNoCreateRoute(container); + expectInspectorOffersNoSave(true); + }); +}); diff --git a/apps/web/src/components/canvas/__tests__/strategy-canvas-simulate.test.tsx b/apps/web/src/components/canvas/__tests__/strategy-canvas-simulate.test.tsx index 1f3949d43..a5757c7dc 100644 --- a/apps/web/src/components/canvas/__tests__/strategy-canvas-simulate.test.tsx +++ b/apps/web/src/components/canvas/__tests__/strategy-canvas-simulate.test.tsx @@ -56,30 +56,17 @@ vi.mock('@/components/canvas/strategy-canvas/hooks/use-strategy-canvas', () => ( revision: 1, activeSession: null, creatorId: 'c1', - baseRevision: 1, activeScheduleId: undefined, - draftEdges: [], - onConnect: () => {}, - onReconnect: () => {}, form: { label: '', description: '', nextTarget: '', promptBody: '' }, setForm: () => {}, - saveStatuses: {}, - setSaveStatuses: () => {}, + activeSection: 'state', setActiveSection: () => {}, conflict: null, setConflict: () => {}, - saveTriggers: {}, - workingRevisionRef: { current: 1 }, + saveTriggers: { state: 0, transition: 0, prompt: 0 }, + setSaveTriggers: () => {}, handleConflict: () => {}, handleReapply: () => {}, - selectedDraftEdge: null, - draftSourceState: null, - commitDraft: () => {}, - isCommittingDraft: false, - cancelDraft: () => {}, - commitKeyboardCreate: () => {}, - isCommittingKeyboardCreate: false, - isReconnecting: false, }), })); @@ -88,7 +75,6 @@ vi.mock('@/components/canvas/strategy-canvas/inspectors/state-inspector', () => })); vi.mock('@/components/canvas/strategy-canvas/inspectors/edge-inspector', () => ({ EdgeInspector: () => null, - DraftEdgeInspector: () => null, })); vi.mock('@/components/canvas/strategy-canvas/inspectors/prompt-inspector', () => ({ PromptInspector: () => null, diff --git a/apps/web/src/components/canvas/canvas-surface-commands.test.tsx b/apps/web/src/components/canvas/canvas-surface-commands.test.tsx index 183a0c63d..a0a686598 100644 --- a/apps/web/src/components/canvas/canvas-surface-commands.test.tsx +++ b/apps/web/src/components/canvas/canvas-surface-commands.test.tsx @@ -12,8 +12,8 @@ * canvas internals (React Flow, daemon queries, inspectors, alt-views, conflict * modals) are mocked so the test focuses on the command registration and the * graph↔list toggle button, which is where the T4 wiring lives. The header - * (which owns the toggle button) and the Strategy edge-create dialog (the - * create-transition target) are kept real so handler effects are observable. + * (which owns the toggle button) is kept real so handler effects are + * observable. */ import { act, cleanup, render } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -194,28 +194,16 @@ vi.mock('@/components/canvas/strategy-canvas/hooks/use-strategy-canvas', () => { creatorId: 'c1', baseRevision: 1, activeScheduleId: undefined, - draftEdges: [] as never[], - onConnect: () => {}, - onReconnect: () => {}, form: { label: '', description: '', nextTarget: '', promptBody: '' }, setForm: () => {}, - saveStatuses: {}, - setSaveStatuses: () => {}, setActiveSection: () => {}, + activeSection: 'state', conflict: null, setConflict: () => {}, - saveTriggers: {}, - workingRevisionRef: { current: 1 }, + saveTriggers: { state: 0, transition: 0, prompt: 0 }, + setSaveTriggers: () => {}, handleConflict: () => {}, handleReapply: () => {}, - selectedDraftEdge: null, - draftSourceState: null, - commitDraft: () => {}, - isCommittingDraft: false, - cancelDraft: () => {}, - commitKeyboardCreate: () => {}, - isCommittingKeyboardCreate: false, - isReconnecting: false, }; return { useStrategyCanvas: () => strategyState }; }); @@ -226,7 +214,6 @@ vi.mock('@/components/canvas/strategy-canvas/inspectors/state-inspector', () => })); vi.mock('@/components/canvas/strategy-canvas/inspectors/edge-inspector', () => ({ EdgeInspector: () => null, - DraftEdgeInspector: () => null, })); vi.mock('@/components/canvas/strategy-canvas/inspectors/prompt-inspector', () => ({ PromptInspector: () => null, @@ -391,16 +378,13 @@ afterEach(() => { // --------------------------------------------------------------------------- describe('StrategyCanvas — palette commands', () => { - it('registers a toggle-view and a create-transition command on mount', async () => { + it('registers the toggle-view command on mount', async () => { const { StrategyCanvas } = await import('@/components/canvas/strategy-canvas'); render(withProviders()); - expect(getCommands().map((c) => c.id).sort()).toEqual([ - 'strategy.create-transition', - 'strategy.toggle-view', - ]); + expect(getCommands().map((c) => c.id)).toEqual(['strategy.toggle-view']); }); - it('unregisters both on unmount', async () => { + it('unregisters on unmount', async () => { const { StrategyCanvas } = await import('@/components/canvas/strategy-canvas'); const { unmount } = render(withProviders()); unmount(); @@ -435,23 +419,6 @@ describe('StrategyCanvas — palette commands', () => { }); expect(toggle.getAttribute('aria-pressed')).toBe('false'); }); - - it('create-transition handler opens the edge-create dialog', async () => { - const { StrategyCanvas } = await import('@/components/canvas/strategy-canvas'); - const renderResult = render(withProviders()); - - // The Radix Dialog is not mounted while closed. (The header's "Create - // Transition…" button is always visible, so assert on role="dialog" - // rather than text — the dialog content renders into a portal only when - // open=true.) - expect(renderResult.queryByRole('dialog')).toBeNull(); - - act(() => { - findById('strategy.create-transition')?.handler(); - }); - - expect(renderResult.getByRole('dialog')).toBeInTheDocument(); - }); }); // --------------------------------------------------------------------------- diff --git a/apps/web/src/components/canvas/strategy-canvas.tsx b/apps/web/src/components/canvas/strategy-canvas.tsx index 4c2e80234..63ebcabc6 100644 --- a/apps/web/src/components/canvas/strategy-canvas.tsx +++ b/apps/web/src/components/canvas/strategy-canvas.tsx @@ -15,7 +15,7 @@ */ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; -import type { Connection, Edge, Node } from '@xyflow/react'; +import type { Node } from '@xyflow/react'; import type { StrategyApprovals, WorkflowDocument } from '@42ch/nexus-contracts'; @@ -24,7 +24,7 @@ import { ErrorState, LoadingState, UnavailableState } from '@/components/ui/stat import { useRegisterCommand } from '@/lib/canvas/command-registry'; import { useSimulationTrajectory } from '@/lib/canvas/use-simulation-trajectory'; import { isOrchestrationEngineUnavailable } from '@/lib/nexus/errors'; -import type { StrategyEdgeData, StrategyNodeData } from '@/lib/canvas/strategy-graph'; +import type { StrategyNodeData } from '@/lib/canvas/strategy-graph'; import { useCanvasSurface, type CanvasSurfaceQueryResult } from '@/components/canvas/use-canvas-surface'; import { useStrategyCanvas } from '@/components/canvas/strategy-canvas/hooks/use-strategy-canvas'; @@ -46,15 +46,11 @@ import { StrategyAppliedState } from './strategy-canvas/applied-state'; import { ComposeConflictDialog } from './strategy-canvas/compose-conflict-dialog'; import { PatternPickerDialog } from './strategy-canvas/pattern-picker-dialog'; import { InspectorPanel, StrategyConflictModal } from './strategy-canvas/inspector-panel'; -import { EdgeCreateDialog } from './strategy-canvas/edge-create-dialog'; -import { DraftEdgeInspector } from './strategy-canvas/inspectors/edge-inspector'; import { ValidationPanel, isSectionDirty, originalFormOf, templateRefOf, - type SaveStatus, - type Section, } from './strategy-canvas/state-machine'; import type { IdeaArtifact } from '@/components/canvas/idea-input'; @@ -97,15 +93,10 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra // apply/approve produced, so this view is read-only and editing goes through // Compose (P6 condition 2, D18). const appliedView = document === appliedDocument; - // No rendered document is authored in place — the applied view is the running - // strategy and a compose candidate is written through compose ops — so the - // preset-YAML structural author is never offered and never dispatched. - const yamlWritesDisabled = appliedView || composeEnabled; - const strategyState = useStrategyCanvas( - presetId, - { document, refetch: () => applied.refetch() }, - yamlWritesDisabled, - ); + const strategyState = useStrategyCanvas(presetId, { + document, + refetch: () => applied.refetch(), + }); const approval = useApproveStrategy(presetId); const application = useApplyStrategy(presetId); // T4: every approval, so Apply can be aimed at a superseded one (rollback). @@ -119,21 +110,14 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra const [artifacts, setArtifacts] = useState([]); const [isEditing, setIsEditing] = useState(false); - const [createDialogOpen, setCreateDialogOpen] = useState(false); const [patternPickerOpen, setPatternPickerOpen] = useState(false); const [approveOpen, setApproveOpen] = useState(false); // Which listed approval Apply is aimed at; null means the newest (T4). const [applyTargetId, setApplyTargetId] = useState(null); const ctxRef = useRef({ - presetId, form: strategyState.form, - saveTriggers: strategyState.saveTriggers, - saveStatuses: strategyState.saveStatuses, - workingRevisionRef: strategyState.workingRevisionRef, - handleConflict: strategyState.handleConflict, onChange: () => {}, - onSaveStatus: () => {}, setActiveSection: strategyState.setActiveSection, selectedState: undefined, promptTemplateRef: undefined, @@ -143,8 +127,6 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra onReapply: () => {}, onDismiss: () => {}, danglingTargets: [], - localEdges: [], - appliedView, }); const adapter = useMemo(() => createStrategyCanvasAdapter(ctxRef), []); @@ -225,10 +207,6 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra strategyState.setForm((prev) => ({ ...prev, [field]: value })); } - function onSaveStatus(section: Section, status: SaveStatus | undefined) { - strategyState.setSaveStatuses((prev) => ({ ...prev, [section]: status })); - } - // One Simulate action for the open strategy: a supplied candidate is walked // as-is; otherwise the installed preset's IR is re-read and walked only when // it no longer matches the trajectory in hand. On the compose path the @@ -323,14 +301,8 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra // path. danglingTargets is written BY the adapter during projection and // read below for the ValidationPanel. ctxRef.current = { - presetId, form: strategyState.form, - saveTriggers: strategyState.saveTriggers, - saveStatuses: strategyState.saveStatuses, - workingRevisionRef: strategyState.workingRevisionRef, - handleConflict: strategyState.handleConflict, onChange: updateField, - onSaveStatus, setActiveSection: strategyState.setActiveSection, selectedState, promptTemplateRef, @@ -340,8 +312,6 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra onReapply: strategyState.handleReapply, onDismiss: () => strategyState.setConflict(null), danglingTargets: ctxRef.current.danglingTargets, - localEdges: strategyState.draftEdges as Edge[], - appliedView, patterns: compose.patternsQuery.data?.items, ...(composeEnabled ? { @@ -374,38 +344,14 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra ], handler: () => surface.setShowAlt(!showAltRef.current), }); - useRegisterCommand({ - id: 'strategy.create-transition', - labelKey: 'strategy.create-transition.label', - groupKey: 'group.strategy', - keywordKeys: [ - 'strategy.create-transition.keywords.add-edge', - 'strategy.create-transition.keywords.new-transition', - 'strategy.create-transition.keywords.state-machine', - 'strategy.create-transition.keywords.link-states', - ], - handler: () => setCreateDialogOpen(true), - // The YAML transition author writes the preset file, which is never the - // document on canvas — neither the applied view nor a compose candidate. - available: () => !yamlWritesDisabled, - }); useEffect(() => { if (!isEditing || !selectedState) { strategyState.setForm({ label: '', description: '', nextTarget: '', promptBody: '' }); - strategyState.setSaveStatuses({}); return; } strategyState.setForm(originalFormOf(selectedState)); - strategyState.setSaveStatuses({}); - }, [isEditing, selectedState?.id, strategyState.setForm, strategyState.setSaveStatuses]); - - const onConnect = useCallback( - (connection: Connection) => { - strategyState.onConnect(connection); - }, - [strategyState.onConnect], - ); + }, [isEditing, selectedState?.id, strategyState.setForm]); // D16(c): an apply is recorded but its document no longer verifies. This is // not an empty state — presenting it as "not yet applied" would invite an @@ -485,7 +431,6 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra activeSession={strategyState.activeSession} showAlt={surface.showAlt} setShowAlt={surface.setShowAlt} - onOpenCreateTransition={yamlWritesDisabled ? undefined : () => setCreateDialogOpen(true)} onSimulate={handleSimulate} staging={composeEnabled} onAddPattern={composeEnabled ? () => setPatternPickerOpen(true) : undefined} @@ -503,11 +448,6 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra edges={surface.edges} nodeTypes={surface.nodeTypes} onNodesChange={surface.onNodesChange} - // A displayed edge is never authored through the YAML authority: the - // applied view is read-only and connect/reconnect write the preset, - // not the candidate, so neither gesture is offered. - onConnect={yamlWritesDisabled ? undefined : onConnect} - onReconnect={yamlWritesDisabled ? undefined : strategyState.onReconnect} summaryText={surface.summaryText} ariaLabel={t('strategy.graphAriaLabel')} relayout={surface.relayout} @@ -523,21 +463,6 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra ? surface.inspector : null} - {strategyState.selectedDraftEdge ? ( - - ) : null} )} @@ -589,24 +514,13 @@ export function StrategyCanvas({ presetId, candidate, onApproveCandidate }: Stra strategyState.setConflict(null)} /> - { - strategyState.commitKeyboardCreate(args); - setCreateDialogOpen(false); - }} - /> - void; - /** - * FB-SE-004 — when provided, the header renders a **Create Transition…** - * button and binds the Shift+N keyboard shortcut that opens the keyboard - * edge-creation dialog. The shortcut is suppressed while focus is in a text - * field, select, or contenteditable so authors can type the letter N. - */ - onOpenCreateTransition?: () => void; /** * Simulate entry point: resolves the open strategy's IR (a supplied * candidate, or the installed preset read) and opens the disclosure that @@ -58,25 +49,6 @@ export function CanvasHeader({ }) { const { t } = useTranslation('canvas'); - // Shift+N opens the keyboard edge-creation dialog (FB-SE-004 §4.4). Suppressed - // inside text-entry controls so the letter is passed through to the field. - useEffect(() => { - if (!onOpenCreateTransition) return; - const open = onOpenCreateTransition; - function onKeyDown(e: KeyboardEvent) { - if (!e.shiftKey || e.key !== 'N') return; - const target = e.target as HTMLElement | null; - if (target) { - const tag = target.tagName; - if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable) return; - } - e.preventDefault(); - open(); - } - window.addEventListener('keydown', onKeyDown); - return () => window.removeEventListener('keydown', onKeyDown); - }, [onOpenCreateTransition]); - return ( <>
@@ -109,16 +81,6 @@ export function CanvasHeader({ {t('strategy.header.addPattern')} ) : null} - {onOpenCreateTransition ? ( - - ) : null} {onSimulate ? ( - -
- - - - ); -} diff --git a/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.test.tsx b/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.test.tsx index d20178595..88179c27c 100644 --- a/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.test.tsx +++ b/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.test.tsx @@ -5,23 +5,12 @@ * conflict/reapply coordination: when an inspector save fails with a conflict, * the canvas refetches the canonical preset before showing the reconcile modal, * and reapply refetches again before re-issuing the save trigger. - * - * V1.115 P0 T2 (W001): the hook no longer manages base node/edge state (the - * adapter owns projection). Tests target the hook's remaining responsibilities: - * draft edge management (draftEdges), conflict/reapply coordination, and the - * three transition-write mutations. Projection equivalence is covered by the - * adapter-level tests in `strategy-graph.test.ts`. */ import { describe, expect, it, vi } from 'vitest'; import { renderHook, act, waitFor } from '@testing-library/react'; import type { ReactNode } from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { ClientProvider } from '@/lib/client-context'; -import { NexusClientError } from '@/lib/nexus'; -import type { NexusClient } from '@/lib/nexus'; -import { ToastProvider } from '@/lib/use-toast'; - import { useStrategyCanvas, type StrategyDocumentSource } from './use-strategy-canvas'; const mocks = vi.hoisted(() => { @@ -73,37 +62,10 @@ function documentSource(): StrategyDocumentSource { } function wrapper({ children }: { children: ReactNode }) { - const client = { - strategyPatchState: vi.fn(), - strategyPatchTransition: vi.fn(), - strategyPatchPromptTemplate: vi.fn(), - } as unknown as NexusClient; const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, }); - return ( - - - {children} - - - ); -} - -/** Build a wrapper with a specific client for draft-commit tests (FB-SE-002). */ -function makeCommitWrapper(client: NexusClient) { - return function commitWrapper({ children }: { children: ReactNode }) { - const queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, - }); - return ( - - - {children} - - - ); - }; + return {children}; } describe('useStrategyCanvas edit-save-refetch (R-V171P0-QC1-008 B7)', () => { @@ -126,514 +88,3 @@ describe('useStrategyCanvas edit-save-refetch (R-V171P0-QC1-008 B7)', () => { }); }); }); - -describe('useStrategyCanvas onConnect draft edge (FB-SE-000)', () => { - it('creates a draft transition edge when connecting two different states', () => { - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { wrapper }); - - expect(result.current.draftEdges).toHaveLength(0); - expect(typeof result.current.onConnect).toBe('function'); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - - expect(result.current.draftEdges).toHaveLength(1); - const draft = result.current.draftEdges[0]; - expect(draft.source).toBe('s1'); - expect(draft.target).toBe('s2'); - expect(draft.label).toBe('Draft transition'); - expect(draft.selected).toBe(true); - expect((draft.data as { isDraft?: boolean }).isDraft).toBe(true); - }); - - it('does not create a draft edge for a self-loop', () => { - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { wrapper }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's1', sourceHandle: null, targetHandle: null }); - }); - - expect(result.current.draftEdges).toHaveLength(0); - }); - - it('does not call the daemon on connect (local-only draft)', () => { - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { wrapper }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - - // No save trigger fires from a connect — draft is local until inspector commit. - expect(result.current.saveTriggers.transition).toBe(0); - }); - - it('preserves the draft edge across re-renders (V1.115 T2: adapter owns base projection)', () => { - // V1.115 T2: the hook manages only drafts; base edges are projected by the - // adapter. A re-render (e.g. query refetch) does not touch draftEdges. - const { result, rerender } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { wrapper }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - - expect(result.current.draftEdges).toHaveLength(1); - const draft = result.current.draftEdges[0]; - expect((draft.data as { isDraft?: boolean }).isDraft).toBe(true); - - rerender(); - - // The draft survives — the adapter merges it with projected edges. - expect(result.current.draftEdges).toHaveLength(1); - expect(result.current.draftEdges.some((e) => e.id === draft.id)).toBe(true); - }); -}); - -describe('useStrategyCanvas draft transition commit (FB-SE-002)', () => { - function makeClient(patchImpl: () => Promise): NexusClient { - return { - strategyPatchState: vi.fn(), - strategyPatchTransition: vi.fn(patchImpl), - strategyPatchPromptTemplate: vi.fn(), - } as unknown as NexusClient; - } - - it('commits a draft edge via strategy.patch_transition with op: "create"', async () => { - const patch = vi.fn().mockResolvedValue({ - new_revision: 2, - validation_summary: { errors: [], warnings: [] }, - side_effects: [], - }); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - expect(result.current.selectedDraftEdge).not.toBeNull(); - - await act(async () => { - result.current.commitDraft({ condition: 'word_count > 1000' }); - }); - - await waitFor(() => expect(patch).toHaveBeenCalledTimes(1)); - const request = patch.mock.calls[0][1] as Record; - expect(request).toMatchObject({ - strategy_id: 'preset-1', - source_state_id: 's1', - new_target: 's2', - op: 'create', - condition: 'word_count > 1000', - }); - - // Successful commit replaces the draft (refetch brings the canonical edge). - await waitFor(() => expect(result.current.selectedDraftEdge).toBeNull()); - }); - - it('omits op on the existing-edit path so it defaults to "update"', async () => { - // The hook-owned commit is create-only; this test documents that the draft - // commit always sends op: "create" while the legacy inspector edit path - // (usePatchStrategyTransition) continues to omit op. We assert create here; - // the legacy path is covered by inspector-save-trigger.test.tsx. - const patch = vi.fn().mockResolvedValue({ new_revision: 3 }); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - - await act(async () => { - result.current.commitDraft({}); - }); - - await waitFor(() => expect(patch).toHaveBeenCalled()); - const request = patch.mock.calls[0][1] as Record; - expect(request.op).toBe('create'); - }); - - it('opens the conflict modal when the daemon returns strategy_conflict (409)', async () => { - // The document reports revision 1; the conflict's current_revision - // is set to match so the existing auto-clear effect (which dismisses a - // conflict once the refetched revision differs) does not race the - // assertion. This mirrors the established pattern in this file's - // edit-save-refetch suite. - const conflictError = new NexusClientError( - 409, - 'strategy_conflict', - 'Strategy revision is stale', - { current_revision: 1 }, - ); - const patch = vi.fn().mockRejectedValue(conflictError); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - expect(result.current.conflict).toBeNull(); - - await act(async () => { - result.current.commitDraft({}); - }); - - // 409 keeps the draft and routes to the existing conflict modal handler. - await waitFor(() => expect(result.current.conflict).not.toBeNull()); - expect(result.current.conflict).toMatchObject({ currentRevision: 1, section: 'transition' }); - // A retry command is stored so "Reapply my edit" replays the transition - // command, not the state-edit save trigger (QC1 W-001). - expect(typeof result.current.conflict?.retry).toBe('function'); - // Draft is preserved so the author can reconcile. - expect(result.current.selectedDraftEdge).not.toBeNull(); - }); - - it('cannot issue the YAML create for a draft authored with the flag off once compose takes authority (Y3)', async () => { - const patch = vi.fn().mockResolvedValue({ new_revision: 2 }); - const client = makeClient(patch); - const { result, rerender } = renderHook( - ({ structuralWritesDisabled }: { structuralWritesDisabled: boolean }) => - useStrategyCanvas('preset-1', documentSource(), structuralWritesDisabled), - { wrapper: makeCommitWrapper(client), initialProps: { structuralWritesDisabled: false } }, - ); - - // Flag off: the spatial gesture authors a local draft. - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - expect(result.current.selectedDraftEdge).not.toBeNull(); - - // Flag on: the candidate document is the one structural authority. - rerender({ structuralWritesDisabled: true }); - await act(async () => { - result.current.commitDraft({}); - }); - - // The author keeps the edge they can still see, and no structural patch was issued. - expect(patch).not.toHaveBeenCalled(); - expect(result.current.selectedDraftEdge).not.toBeNull(); - }); - - it('cancelDraft removes the draft edge without a daemon call', () => { - const patch = vi.fn(); - const client = makeClient(patch as () => Promise); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - act(() => { - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - expect(result.current.selectedDraftEdge).not.toBeNull(); - - act(() => { - result.current.cancelDraft(); - }); - - expect(result.current.selectedDraftEdge).toBeNull(); - expect(patch).not.toHaveBeenCalled(); - }); -}); - -describe('useStrategyCanvas keyboard create (FB-SE-004)', () => { - function makeClient(patchImpl: () => Promise): NexusClient { - return { - strategyPatchState: vi.fn(), - strategyPatchTransition: vi.fn(patchImpl), - strategyPatchPromptTemplate: vi.fn(), - } as unknown as NexusClient; - } - - it('commits via strategy.patch_transition with op: "create" and explicit source/target', async () => { - const patch = vi.fn().mockResolvedValue({ - new_revision: 2, - validation_summary: { errors: [], warnings: [] }, - side_effects: [], - }); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - await act(async () => { - result.current.commitKeyboardCreate({ - sourceStateId: 's1', - targetStateId: 's2', - transitionKind: 'branch', - condition: 'word_count > 1000', - }); - }); - - await waitFor(() => expect(patch).toHaveBeenCalledTimes(1)); - const request = patch.mock.calls[0][1] as Record; - expect(request).toMatchObject({ - strategy_id: 'preset-1', - source_state_id: 's1', - new_target: 's2', - op: 'create', - transition_kind: 'branch', - condition: 'word_count > 1000', - }); - }); - - it('routes a 409 conflict through the conflict modal handler', async () => { - const conflictError = new NexusClientError( - 409, - 'strategy_conflict', - 'Strategy revision is stale', - { current_revision: 1 }, - ); - const patch = vi.fn().mockRejectedValue(conflictError); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - expect(result.current.conflict).toBeNull(); - - await act(async () => { - result.current.commitKeyboardCreate({ - sourceStateId: 's1', - targetStateId: 's2', - }); - }); - - await waitFor(() => expect(result.current.conflict).not.toBeNull()); - expect(result.current.conflict).toMatchObject({ currentRevision: 1, section: 'transition' }); - }); - - it('reapplies the original transition command on reapply, not the state-edit save trigger (QC1 W-001)', async () => { - // First call rejects with 409; second call succeeds so we can observe - // the retry re-issuing the transition create. - const conflictError = new NexusClientError( - 409, - 'strategy_conflict', - 'Strategy revision is stale', - { current_revision: 1 }, - ); - const patch = vi - .fn() - .mockRejectedValueOnce(conflictError) - .mockResolvedValueOnce({ new_revision: 2 }); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - const createArgs = { - sourceStateId: 's1', - targetStateId: 's2', - transitionKind: 'branch' as const, - condition: 'word_count > 1000', - }; - - await act(async () => { - result.current.commitKeyboardCreate(createArgs); - }); - - await waitFor(() => expect(result.current.conflict).not.toBeNull()); - expect(patch).toHaveBeenCalledTimes(1); - - // Reapply should replay the original transition command, not increment - // the section save trigger (which would drive a state-edit save). - await act(async () => { - result.current.handleReapply(); - }); - - await waitFor(() => expect(patch).toHaveBeenCalledTimes(2)); - - // The second patch call is the retried transition create — same args. - const retryRequest = patch.mock.calls[1][1] as Record; - expect(retryRequest).toMatchObject({ - strategy_id: 'preset-1', - source_state_id: 's1', - new_target: 's2', - op: 'create', - transition_kind: 'branch', - condition: 'word_count > 1000', - }); - - // The transition save trigger must NOT have been incremented (that would - // drive the legacy state-edit EdgeInspector save, not the transition create). - expect(result.current.saveTriggers.transition).toBe(0); - }); -}); - -describe('useStrategyCanvas edge reconnection (FB-SE-003)', () => { - // V1.115 T2: the hook no longer manages base edge state — the adapter - // projects from `parsed`. Reconnect tests verify the daemon call shape and - // conflict routing. The optimistic edge update / revert (previously managed - // in hook edge state) is now handled at the adapter/orchestrator level: - // the edge moves to the new target on query refetch (success) or stays at - // the old target (failure — no daemon state changed). - const existingEdge = { - id: 'e-s1-s2-next-0', - source: 's1', - target: 's2', - type: 'strategy-edge', - data: { transitionKind: 'next' }, - }; - - function makeReconnClient(patchImpl: () => Promise): NexusClient { - return { - strategyPatchState: vi.fn(), - strategyPatchTransition: vi.fn(patchImpl), - strategyPatchPromptTemplate: vi.fn(), - } as unknown as NexusClient; - } - - it('reconnects via a single patch_transition with old_target + new_target (op: update)', async () => { - const patch = vi.fn().mockResolvedValue({ new_revision: 2 }); - const client = makeReconnClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - expect(typeof result.current.onReconnect).toBe('function'); - - act(() => { - result.current.onReconnect(existingEdge, { - source: 's1', - target: 's3', - sourceHandle: null, - targetHandle: null, - }); - }); - - // Single reconnect payload — no delete+create, one logical transition. - await waitFor(() => expect(patch).toHaveBeenCalledTimes(1)); - const request = patch.mock.calls[0][1] as Record; - expect(request).toMatchObject({ - strategy_id: 'preset-1', - source_state_id: 's1', - old_target: 's2', - new_target: 's3', - op: 'update', - }); - }); - - it('includes the branch condition on reconnect so sibling rules sharing a target are not all rewritten (Greptile Issue 1)', async () => { - const branchEdge = { - id: 'e-s1-s2-branch-0', - source: 's1', - target: 's2', - type: 'strategy-edge', - data: { transitionKind: 'branch', condition: '_context.branch_a' }, - }; - - const patch = vi.fn().mockResolvedValue({ new_revision: 2 }); - const client = makeReconnClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - act(() => { - result.current.onReconnect(branchEdge, { - source: 's1', - target: 's3', - sourceHandle: null, - targetHandle: null, - }); - }); - - await waitFor(() => expect(patch).toHaveBeenCalledTimes(1)); - const request = patch.mock.calls[0][1] as Record; - expect(request).toMatchObject({ - source_state_id: 's1', - old_target: 's2', - new_target: 's3', - condition: '_context.branch_a', - transition_kind: 'branch', - op: 'update', - }); - }); - - it('routes a 409 conflict through the conflict modal handler on reconnect failure', async () => { - const conflictError = new NexusClientError( - 409, - 'strategy_conflict', - 'Strategy revision is stale', - { current_revision: 1 }, - ); - const patch = vi.fn().mockRejectedValue(conflictError); - const client = makeReconnClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - expect(result.current.conflict).toBeNull(); - - await act(async () => { - result.current.onReconnect(existingEdge, { - source: 's1', - target: 's3', - sourceHandle: null, - targetHandle: null, - }); - }); - - await waitFor(() => expect(result.current.conflict).not.toBeNull()); - expect(result.current.conflict).toMatchObject({ currentRevision: 1, section: 'transition' }); - // A retry command is stored so "Reapply my edit" replays the reconnect, not a state-edit save. - expect(typeof result.current.conflict?.retry).toBe('function'); - }); - - it('does not reconnect onto the same source (self-loop guard)', () => { - const patch = vi.fn(); - const client = makeReconnClient(patch as () => Promise); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource()), { - wrapper: makeCommitWrapper(client), - }); - - act(() => { - result.current.onReconnect(existingEdge, { - source: 's1', - target: 's1', - sourceHandle: null, - targetHandle: null, - }); - }); - - expect(patch).not.toHaveBeenCalled(); - }); -}); - -describe('useStrategyCanvas structural write authority', () => { - function makeClient(patch: () => Promise): NexusClient { - return { - strategyPatchState: vi.fn(), - strategyPatchTransition: vi.fn(patch), - strategyPatchPromptTemplate: vi.fn(), - } as unknown as NexusClient; - } - - it('refuses every structural channel while the candidate owns the document', async () => { - const patch = vi.fn().mockResolvedValue({ new_revision: 2 }); - const client = makeClient(patch); - const { result } = renderHook(() => useStrategyCanvas('preset-1', documentSource(), true), { - wrapper: makeCommitWrapper(client), - }); - - await act(async () => { - // Spatial connect authors only a local draft; its commit is a YAML write. - result.current.onConnect({ source: 's1', target: 's2', sourceHandle: null, targetHandle: null }); - }); - await act(async () => { - result.current.commitDraft({}); - }); - await act(async () => { - result.current.commitKeyboardCreate({ sourceStateId: 's1', targetStateId: 's2' }); - result.current.onReconnect( - { id: 'edge-1', source: 's1', target: 's2', data: { transitionKind: 'next' } }, - { source: 's1', target: 's3', sourceHandle: null, targetHandle: null }, - ); - }); - - expect(patch).not.toHaveBeenCalled(); - }); -}); diff --git a/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.ts b/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.ts index 4b5b3fe0f..75a09ad9c 100644 --- a/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.ts +++ b/apps/web/src/components/canvas/strategy-canvas/hooks/use-strategy-canvas.ts @@ -2,46 +2,31 @@ * Orchestrator-level state hook for the Strategy canvas. * * The Canvas renders a workflow IR document (the applied one, or the candidate - * being composed) — never YAML. The hook owns: the shared edit form, - * per-section save triggers/statuses, revision tracking, conflict/reapply - * coordination, draft transition edges (local-only), and the three - * transition-write mutations (commit draft, keyboard create, reconnect). The - * editing surface still speaks the flat state shape, so `parsedPresetFromIr` - * presents the document's nodes to it without any YAML parse. + * being composed) — never YAML. The hook owns: the shared edit form, revision + * tracking, and conflict/reapply coordination. The editing surface still + * speaks the flat state shape, so `parsedPresetFromIr` presents the document's + * nodes to it without any YAML parse. */ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { useTranslation } from 'react-i18next'; -import { useMutation, useQueryClient } from '@tanstack/react-query'; -import type { Connection, Edge } from '@xyflow/react'; +import { useEffect, useMemo, useState } from 'react'; import type { WorkflowDocument } from '@42ch/nexus-contracts'; import { parsedPresetFromIr } from '@/lib/canvas/ir-preset'; import { - isStrategyConflictError, useActiveSession, useDerivedCreatorId, usePresetSchedules, } from '@/lib/canvas/use-strategy-data'; -import { useStrategyYamlAuthority } from '@/lib/canvas/strategy-yaml-authority'; -import { queryKeys } from '@/lib/nexus/query-keys'; -import { useToast } from '@/lib/use-toast'; -import { - createDraftTransitionEdge, - type EditForm, - type SaveStatus, - type Section, -} from '../state-machine'; +import type { EditForm, Section } from '../state-machine'; /** * Conflict state shared across the canvas write boundary. * - * `retry` is present when the conflict originated from a transition - * create/reconnect command (not a state-edit save). In that case - * {@link useStrategyCanvas.handleReapply} replays the original transition - * command instead of incrementing the section save trigger, which would - * wrongly replay a state-edit save (QC1 W-001). + * `retry` is present when the conflict carries the command that must be + * replayed instead of the section save trigger. In that case + * {@link useStrategyCanvas.handleReapply} replays the original command, which + * would otherwise wrongly replay a state-edit save (QC1 W-001). */ export interface ConflictInfo { currentRevision: number; @@ -57,12 +42,7 @@ export interface StrategyDocumentSource { refetch: () => Promise; } -export function useStrategyCanvas( - presetId: string, - source: StrategyDocumentSource, - structuralWritesDisabled = false, -) { - const { t } = useTranslation('canvas'); +export function useStrategyCanvas(presetId: string, source: StrategyDocumentSource) { const { document, refetch } = source; // The editing surface's flat state view of the rendered document. No YAML // is parsed on this path. @@ -73,7 +53,6 @@ export function useStrategyCanvas( const creatorId = useDerivedCreatorId(presetId); const [form, setForm] = useState({ label: '', description: '', nextTarget: '', promptBody: '' }); - const [saveStatuses, setSaveStatuses] = useState>>({}); const [activeSection, setActiveSection] = useState
('state'); const [conflict, setConflict] = useState(null); const [saveTriggers, setSaveTriggers] = useState>({ @@ -82,18 +61,6 @@ export function useStrategyCanvas( prompt: 0, }); - // Draft transition edges (local-only — created by onConnect, committed or - // cancelled in the inspector). The adapter merges these with the projected - // daemon edges so drafts appear on the canvas without the hook managing base - // node/edge state. - const [draftEdges, setDraftEdges] = useState([]); - - const workingRevisionRef = useRef(revision); - - useEffect(() => { - workingRevisionRef.current = revision; - }, [revision]); - useEffect(() => { if (conflict && revision !== conflict.currentRevision) { setConflict(null); @@ -111,8 +78,6 @@ export function useStrategyCanvas( return () => window.removeEventListener('keydown', onKeyDown); }, [activeSection]); - - const activeScheduleId = useMemo(() => { if (!activeSession) return undefined; const list = schedules.data ?? []; @@ -140,237 +105,6 @@ export function useStrategyCanvas( }); } - /** - * Spatial connect gesture → local draft transition edge (FB-SE-000). - * - * The draft is appended to `draftEdges` and selected so the edge inspector - * can take focus. No daemon call happens here — the author commits (or - * cancels) in the inspector (FB-SE-002). Re-attempting a connect from the - * same source replaces any existing draft rather than stacking duplicates. - */ - const onConnect = useCallback( - (connection: Connection) => { - const draft = createDraftTransitionEdge(connection, t('strategy.draftTransitionLabel')); - if (!draft) return; - setDraftEdges((prev) => [ - ...prev.map((e) => ({ ...e, selected: false })).filter( - (e) => !(e.data as { isDraft?: boolean })?.isDraft, - ), - draft, - ]); - }, - [t], - ); - - /** - * FB-SE-002 — the draft transition selected on the canvas. A draft edge is - * any edge carrying `data.isDraft = true` (created by {@link onConnect}). - * There is at most one draft at a time; {@link onConnect} replaces any - * existing draft instead of stacking duplicates. - */ - const selectedDraftEdge = useMemo( - () => draftEdges.find((e) => (e.data as { isDraft?: boolean } | undefined)?.isDraft) ?? null, - [draftEdges], - ); - - const states = parsed?.manifest.states; - const draftSourceState = useMemo(() => { - if (!selectedDraftEdge) return undefined; - return states?.find((s) => s.id === selectedDraftEdge.source); - }, [selectedDraftEdge, states]); - - const yaml = useStrategyYamlAuthority(structuralWritesDisabled); - const qc = useQueryClient(); - const { toast } = useToast(); - - /** - * Commit a draft transition via `strategy.patch_transition` with - * **`op: "create"`** (FB-SE-002). On success the draft is removed from - * `draftEdges` and the preset query is invalidated so the canonical edge — - * built by the daemon from the structured op — replaces it on refetch. A 409 - * revision conflict keeps the draft and routes through the same - * {@link handleConflict} path the existing edit inspector uses, so the - * conflict modal with Use current / Reapply / Review side-by-side opens. - * - * `handleConflict` is a hoisted function declaration, so it is safe to - * reference here even though it is defined textually later in the hook. - */ - const commitDraftMutation = useMutation({ - mutationFn: async (args: { condition?: string }) => { - if (!selectedDraftEdge) throw new Error('No draft transition to commit'); - return yaml.patchTransition(presetId, { - strategy_id: presetId, - base_revision: workingRevisionRef.current, - source_state_id: selectedDraftEdge.source, - new_target: selectedDraftEdge.target, - condition: args.condition, - op: 'create', - transition_kind: 'next', - }); - }, - onSuccess: (res) => { - workingRevisionRef.current = Number(res.new_revision); - setDraftEdges((prev) => prev.filter((e) => !(e.data as { isDraft?: boolean } | undefined)?.isDraft)); - toast({ - variant: 'success', - title: 'Transition created', - description: `${selectedDraftEdge?.source} → ${selectedDraftEdge?.target}`, - }); - void qc.invalidateQueries({ queryKey: queryKeys.presets.detail(presetId) }); - }, - onError: (error, args) => { - if (isStrategyConflictError(error)) { - const currentRevision = - typeof error.details === 'object' && error.details !== null - ? (error.details as { current_revision?: number }).current_revision ?? 0 - : 0; - // Keep the draft so the author can reconcile; refetch canonical. - // Pass a retry that replays the original transition command so - // "Reapply my edit" re-issues the create, not a state-edit save (QC1 W-001). - handleConflict(currentRevision, 'transition', () => commitDraftMutation.mutate(args)); - } else { - const message = error instanceof Error ? error.message : 'Failed to create transition'; - toast({ variant: 'error', title: message }); - } - }, - }); - - /** Discard the current draft transition without a daemon call (FB-SE-001 #4). */ - const cancelDraft = useCallback(() => { - setDraftEdges((prev) => prev.filter((e) => !(e.data as { isDraft?: boolean } | undefined)?.isDraft)); - }, []); - - /** - * FB-SE-004 — keyboard edge-creation commit. Sends the same - * `strategy.patch_transition` with **`op: "create"`** as the spatial path - * (FB-SE-002), but with explicit source/target from the dialog instead of a - * draft edge. On 409, routes through the same {@link handleConflict} path so - * the conflict modal opens. There is no local draft edge to remove on - * success — the dialog closes and the preset refetch brings the canonical - * edge. - * - * `handleConflict` is a hoisted function declaration, so it is safe to - * reference here even though it is defined textually later in the hook. - */ - const commitKeyboardCreateMutation = useMutation({ - mutationFn: async (args: { - sourceStateId: string; - targetStateId: string; - transitionKind?: 'next' | 'branch' | 'default'; - condition?: string; - }) => { - return yaml.patchTransition(presetId, { - strategy_id: presetId, - base_revision: workingRevisionRef.current, - source_state_id: args.sourceStateId, - new_target: args.targetStateId, - condition: args.condition, - transition_kind: args.transitionKind ?? 'next', - op: 'create', - }); - }, - onSuccess: (res, args) => { - workingRevisionRef.current = Number(res.new_revision); - toast({ - variant: 'success', - title: 'Transition created', - description: `${args.sourceStateId} → ${args.targetStateId}`, - }); - void qc.invalidateQueries({ queryKey: queryKeys.presets.detail(presetId) }); - }, - onError: (error, args) => { - if (isStrategyConflictError(error)) { - const currentRevision = - typeof error.details === 'object' && error.details !== null - ? (error.details as { current_revision?: number }).current_revision ?? 0 - : 0; - // Replay the original transition command on reapply (QC1 W-001). - handleConflict(currentRevision, 'transition', () => - commitKeyboardCreateMutation.mutate(args), - ); - } else { - const message = error instanceof Error ? error.message : 'Failed to create transition'; - toast({ variant: 'error', title: message }); - } - }, - }); - - /** - * FB-SE-003 — reconnect an existing transition edge to a new target by drag. - * - * Sends a single `strategy.patch_transition` with `op: "update"` (default) + - * `old_target` (the previous target) + `new_target` (the drag's new target). - * The daemon replaces the matched transition atomically — no delete+create, - * so the author ends with one edge for that logical rewiring. - * - * V1.115 T2: the optimistic edge update (and its revert-on-failure) are no - * longer managed in local edge state. The adapter projects from `parsed` on - * every render, so the canonical edge moves to the new target once the query - * refetch completes. On failure, the old target persists because no daemon - * state changed. - * - * `handleConflict` is a hoisted function declaration, so it is safe to - * reference here even though it is defined textually later in the hook. - */ - const reconnectTransitionMutation = useMutation({ - mutationFn: async (args: { oldEdge: Edge; newConnection: Connection }) => { - const { oldEdge, newConnection } = args; - if (!newConnection.target) throw new Error('Reconnect is missing a new target'); - const data = oldEdge.data as { transitionKind?: string; condition?: string } | undefined; - return yaml.patchTransition(presetId, { - strategy_id: presetId, - base_revision: workingRevisionRef.current, - source_state_id: oldEdge.source, - old_target: oldEdge.target, - new_target: newConnection.target, - condition: data?.condition, - transition_kind: (data?.transitionKind ?? 'next') as 'next' | 'branch' | 'default', - op: 'update', - }); - }, - onSuccess: (res, args) => { - workingRevisionRef.current = Number(res.new_revision); - toast({ - variant: 'success', - title: 'Transition reconnected', - description: `${args.oldEdge.source} → ${args.newConnection.target}`, - }); - void qc.invalidateQueries({ queryKey: queryKeys.presets.detail(presetId) }); - }, - onError: (error, args) => { - if (isStrategyConflictError(error)) { - const currentRevision = - typeof error.details === 'object' && error.details !== null - ? (error.details as { current_revision?: number }).current_revision ?? 0 - : 0; - // Replay the original reconnect command on reapply (QC1 W-001). - handleConflict(currentRevision, 'transition', () => - reconnectTransitionMutation.mutate(args), - ); - } else { - const message = error instanceof Error ? error.message : 'Failed to reconnect transition'; - toast({ variant: 'error', title: message }); - } - }, - }); - - /** - * React Flow reconnect gesture (dragging an existing edge end to a new - * target) → single `patch_transition` reconnect payload (FB-SE-003). - * - * Self-loops and missing endpoints are ignored so the edge snaps back to its - * prior target (no daemon call). V1.115 T2: no local optimistic update — - * the edge moves to the new target once the query refetch completes. - */ - const onReconnect = useCallback( - (oldEdge: Edge, newConnection: Connection) => { - if (!newConnection.target || newConnection.target === oldEdge.source) return; - if (newConnection.target === oldEdge.target) return; - reconnectTransitionMutation.mutate({ oldEdge, newConnection }); - }, - [reconnectTransitionMutation], - ); - return { parsed, revision, @@ -380,27 +114,13 @@ export function useStrategyCanvas( activeScheduleId, form, setForm, - saveStatuses, - setSaveStatuses, activeSection, setActiveSection, conflict, setConflict, saveTriggers, setSaveTriggers, - workingRevisionRef, handleConflict, handleReapply, - draftEdges, - selectedDraftEdge, - draftSourceState, - onConnect, - commitDraft: commitDraftMutation.mutate, - isCommittingDraft: commitDraftMutation.isPending, - cancelDraft, - commitKeyboardCreate: commitKeyboardCreateMutation.mutate, - isCommittingKeyboardCreate: commitKeyboardCreateMutation.isPending, - onReconnect, - isReconnecting: reconnectTransitionMutation.isPending, }; } diff --git a/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.test.tsx b/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.test.tsx deleted file mode 100644 index bba3dccb3..000000000 --- a/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.test.tsx +++ /dev/null @@ -1,136 +0,0 @@ -/** - * FB-SE-002 — draft transition commit UI (edge inspector draft mode). - * - * The `DraftEdgeInspector` renders the Condition field plus the locked - * Create Transition / Cancel actions, and routes commits through the - * hook-owned draft commit callback (op: "create") and cancel through the - * hook-owned draft removal. - */ -import { describe, expect, it, vi } from 'vitest'; - -import { renderInApp } from '@/test/test-providers'; -import { noopClient } from '@/test/test-providers'; -import { screen, fireEvent } from '@testing-library/react'; - -import { DraftEdgeInspector } from './edge-inspector'; - -describe('DraftEdgeInspector (FB-SE-002)', () => { - it('renders the locked copy: Create Transition, Cancel, Condition', () => { - renderInApp( - , - { client: noopClient }, - ); - - // Primary commit CTA — locked voice. - expect(screen.getByRole('button', { name: 'Create' })).toBeInTheDocument(); - // Cancel CTA — locked voice. - expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument(); - // Field labels — locked voice. - expect(screen.getByText('Condition')).toBeInTheDocument(); - // Read-only source/target display. - expect(screen.getByText('draft')).toBeInTheDocument(); - expect(screen.getByText('revise')).toBeInTheDocument(); - }); - - it('commits with the entered condition', () => { - const onCommit = vi.fn(); - renderInApp( - , - { client: noopClient }, - ); - - fireEvent.change(screen.getByLabelText('Condition'), { target: { value: 'word_count > 1000' } }); - fireEvent.click(screen.getByRole('button', { name: 'Create' })); - - expect(onCommit).toHaveBeenCalledTimes(1); - expect(onCommit).toHaveBeenCalledWith({ condition: 'word_count > 1000' }); - }); - - it('omits empty condition from the commit payload', () => { - const onCommit = vi.fn(); - renderInApp( - , - { client: noopClient }, - ); - - fireEvent.click(screen.getByRole('button', { name: 'Create' })); - expect(onCommit).toHaveBeenCalledWith({}); - }); - - it('disables the commit button while committing and shows Creating…', () => { - renderInApp( - , - { client: noopClient }, - ); - - const commit = screen.getByRole('button', { name: 'Creating…' }); - expect(commit).toBeDisabled(); - }); - - it('disables the commit with the named reason when the candidate is the structural authority (Y3)', () => { - const onCommit = vi.fn(); - renderInApp( - , - { client: noopClient }, - ); - - const commit = screen.getByRole('button', { name: 'Create' }); - expect(commit).toBeDisabled(); - expect(screen.getByTestId('draft-transition-structural-disabled')).toHaveTextContent( - 'The canvas shows a document, not the preset YAML this editor writes — author the change in Compose.', - ); - - fireEvent.click(commit); - expect(onCommit).not.toHaveBeenCalled(); - }); - - it('cancel discards the draft without committing', () => { - const onCancel = vi.fn(); - const onCommit = vi.fn(); - renderInApp( - , - { client: noopClient }, - ); - - fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); - expect(onCancel).toHaveBeenCalledTimes(1); - expect(onCommit).not.toHaveBeenCalled(); - }); -}); diff --git a/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.tsx b/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.tsx index 9b6583b18..8952a8302 100644 --- a/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.tsx +++ b/apps/web/src/components/canvas/strategy-canvas/inspectors/edge-inspector.tsx @@ -1,139 +1,22 @@ /** - * Transition / edge inspector section — edits the scalar `next` transition. + * Transition / edge inspector section — displays the scalar `next` transition. * - * Owns its own save button and partial-failure UI (R-V171P0-QC1-004). + * The rendered document is never the preset YAML this section would write, so + * the field is shown with the route that does reach it instead of a Save. */ -import type { MutableRefObject } from 'react'; -import { useCallback, useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query'; -import { useStrategyYamlAuthority } from '@/lib/canvas/strategy-yaml-authority'; -import { queryKeys } from '@/lib/nexus/query-keys'; -import { useToast } from '@/lib/use-toast'; -import type { StrategyPatchResponse, StrategyPatchTransitionRequest } from '@42ch/nexus-contracts'; - -import { isStrategyConflictError } from '@/lib/canvas/use-strategy-data'; -import { isSectionDirty, originalFormOf, type EditForm, type SaveStatus, type Section } from '../state-machine'; +import type { EditForm } from '../state-machine'; import type { PresetState } from '@/lib/canvas/preset-yaml'; -export interface PatchStrategyTransitionArgs { - strategyId: string; - sourceStateId: string; - baseRevision: number; - oldTarget: string; - newTarget?: string; - condition?: string; - transitionKind?: StrategyPatchTransitionRequest['transition_kind']; -} - -export function usePatchStrategyTransition( - structuralWritesDisabled = false, -): UseMutationResult { - const yaml = useStrategyYamlAuthority(structuralWritesDisabled); - const qc = useQueryClient(); - const { t } = useTranslation('canvas'); - const { toast } = useToast(); - return useMutation({ - mutationFn: (args: PatchStrategyTransitionArgs) => - yaml.patchTransition(args.strategyId, { - strategy_id: args.strategyId, - base_revision: args.baseRevision, - source_state_id: args.sourceStateId, - old_target: args.oldTarget, - new_target: args.newTarget, - condition: args.condition, - transition_kind: args.transitionKind, - }), - onSuccess: (_data, args) => { - toast({ - variant: 'success', - title: t('strategy.inspector.transition.updated'), - description: `${args.sourceStateId} → ${args.newTarget ?? args.oldTarget}`, - }); - void qc.invalidateQueries({ queryKey: queryKeys.presets.detail(args.strategyId) }); - }, - onError: () => {}, - }); -} - interface EdgeInspectorProps { - presetId: string; selectedState: PresetState; form: EditForm; onChange: (field: K, value: EditForm[K]) => void; - workingRevisionRef: MutableRefObject; - saveTrigger: number; - saveStatus: SaveStatus | undefined; - onSaveStatus: (status: SaveStatus | undefined) => void; - onConflict: (currentRevision: number, section: Section) => void; - /** - * Compose path: the candidate document is the only structural authority, so - * this YAML transition patch is shown with its reason but cannot be issued. - */ - structuralWritesDisabled?: boolean; } -export function EdgeInspector({ - presetId, - selectedState, - form, - onChange, - workingRevisionRef, - saveTrigger, - saveStatus, - onSaveStatus, - onConflict, - structuralWritesDisabled = false, -}: EdgeInspectorProps) { +export function EdgeInspector({ selectedState, form, onChange }: EdgeInspectorProps) { const { t } = useTranslation('canvas'); - const patch = usePatchStrategyTransition(structuralWritesDisabled); - const original = originalFormOf(selectedState); - const dirty = isSectionDirty('transition', form, original); - const lastHandledTriggerRef = useRef(0); - - const handleSave = useCallback(async () => { - if (!dirty || patch.isPending || typeof selectedState.next !== 'string') { - return; - } - onSaveStatus(undefined); - - try { - const res = await patch.mutateAsync({ - strategyId: presetId, - sourceStateId: selectedState.id, - baseRevision: workingRevisionRef.current, - oldTarget: original.nextTarget, - newTarget: form.nextTarget, - transitionKind: 'next', - }); - workingRevisionRef.current = Number(res.new_revision); - onSaveStatus({ type: 'success', message: t('strategy.inspector.transition.saved') }); - } catch (error) { - if (isStrategyConflictError(error)) { - const currentRevision = - typeof error.details === 'object' && error.details !== null - ? (error.details as { current_revision?: number }).current_revision ?? 0 - : 0; - onConflict(currentRevision, 'transition'); - } else { - const message = error instanceof Error ? error.message : t('strategy.inspector.transition.saveFailed'); - onSaveStatus({ type: 'error', message }); - } - } - }, [dirty, patch.isPending, form, original, presetId, selectedState, onSaveStatus, onConflict, t]); - - // Keep a fresh callback reference for the keyboard shortcut effect so the - // effect itself does not need to depend on the callback (R-V172P1-QC1-001). - const handleSaveRef = useRef(handleSave); - handleSaveRef.current = handleSave; - - useEffect(() => { - if (saveTrigger > 0 && saveTrigger !== lastHandledTriggerRef.current) { - lastHandledTriggerRef.current = saveTrigger; - void handleSaveRef.current(); - } - }, [saveTrigger]); if (typeof selectedState.next !== 'string') return null; @@ -141,14 +24,6 @@ export function EdgeInspector({
{t('strategy.inspector.transition.title')} -
- {structuralWritesDisabled ? ( -

- {t('strategy.inspector.structuralDisabled')} -

- ) : saveStatus ? ( -

- {saveStatus.message} -

- ) : null} -
- ); -} - -/** - * Commit payload assembled by {@link DraftEdgeInspector}. Empty strings are - * normalized to `undefined` so the wire request omits the field entirely - * (matches the optional `condition` semantics on the daemon side). - * - * Note: the DTO (`StrategyPatchTransitionRequest`) has no `label` field — the - * `condition` field is the branch identifier for conditional/labeled branches. - * A Label input was previously collected and silently dropped (QC1 W-002); - * it has been removed. - */ -export interface DraftCommitArgs { - condition?: string; -} - -export interface DraftEdgeInspectorProps { - /** Source state id (read-only display). */ - sourceStateId: string; - /** Target state id (read-only display). */ - targetStateId: string; - /** True while the hook-owned commit mutation is in flight. */ - isCommitting: boolean; - /** Commit the draft — sends `strategy.patch_transition` with `op: "create"`. */ - onCommit: (args: DraftCommitArgs) => void; - /** Discard the draft edge without a daemon call. */ - onCancel: () => void; - /** - * Compose path: the candidate document is the only structural authority, so a - * draft authored on the flag-off surface is shown with its reason but cannot - * be committed through this YAML path. - */ - structuralWritesDisabled?: boolean; -} - -/** - * FB-SE-001 / FB-SE-002 — draft transition commit UI. - * - * Renders when a spatial `onConnect` draft edge is selected. Collects - * Condition before commit; the commit routes through the hook-owned - * mutation that sends `strategy.patch_transition` with **`op: "create"`**. - * A 409 keeps the draft and opens the conflict modal (Use current / Reapply / - * Review side-by-side). Voice & Content is locked by the primary spec. - */ -export function DraftEdgeInspector({ - sourceStateId, - targetStateId, - isCommitting, - onCommit, - onCancel, - structuralWritesDisabled = false, -}: DraftEdgeInspectorProps) { - const { t } = useTranslation('canvas'); - const [condition, setCondition] = useState(''); - - function handleCommit() { - const args: DraftCommitArgs = {}; - if (condition.trim()) args.condition = condition.trim(); - onCommit(args); - } - - return ( -
-
- {t('strategy.edgeCreate.title')} -
- - -
-
-

- {sourceStateId} - - → - - {targetStateId} +

+ {t('strategy.inspector.structuralDisabled')}

- - {structuralWritesDisabled ? ( -

- {t('strategy.inspector.structuralDisabled')} -

- ) : null}
); } diff --git a/apps/web/src/components/canvas/strategy-canvas/inspectors/inspector-save-trigger.test.tsx b/apps/web/src/components/canvas/strategy-canvas/inspectors/inspector-save-trigger.test.tsx deleted file mode 100644 index 7da14fb78..000000000 --- a/apps/web/src/components/canvas/strategy-canvas/inspectors/inspector-save-trigger.test.tsx +++ /dev/null @@ -1,235 +0,0 @@ -/** - * Regression coverage for R-V172P1-QC3-001. - * - * Each inspector used to fire handleSave on every render once saveTrigger became - * non-zero because the effect depends on saveTrigger + handleSave, and - * handleSave is recreated every render. A single Cmd/Ctrl+S could therefore - * issue duplicate PATCH requests on later renders. - * - * The fix uses a last-handled trigger ref so each new trigger value is consumed - * exactly once, even if React re-renders the inspector before the mutation - * settles. - */ -import { waitFor } from '@testing-library/react'; -import type { MutableRefObject } from 'react'; -import { describe, expect, it, vi } from 'vitest'; - -import { renderInApp } from '@/test/test-providers'; -import type { NexusClient } from '@/lib/nexus'; -import type { PresetState } from '@/lib/canvas/preset-yaml'; -import type { EditForm } from '../state-machine'; - -import { StateInspector } from './state-inspector'; -import { EdgeInspector } from './edge-inspector'; -import { PromptInspector } from './prompt-inspector'; - -const baseState: PresetState = { - id: 'draft', - description: 'Original description', - next: 'revise', - context_update: { template_file: 'prompts/draft.md' }, -}; - -const baseForm: EditForm = { - label: 'edited-label', - description: 'Original description', - nextTarget: 'edit', - promptBody: '# edited prompt', -}; - -function makeWorkingRevisionRef(): MutableRefObject { - return { current: 1 }; -} - -function makeClient(): NexusClient { - return { - strategyPatchState: vi.fn().mockResolvedValue({ - new_revision: 2, - validation_summary: { errors: [], warnings: [] }, - side_effects: [], - }), - strategyPatchTransition: vi.fn().mockResolvedValue({ - new_revision: 2, - validation_summary: { errors: [], warnings: [] }, - side_effects: [], - }), - strategyPatchPromptTemplate: vi.fn().mockResolvedValue({ - new_revision: 2, - validation_summary: { errors: [], warnings: [] }, - side_effects: [], - }), - } as unknown as NexusClient; -} - -describe('inspector save trigger replay guard (R-V172P1-QC3-001)', () => { - it('StateInspector patches once per trigger value, not once per render', async () => { - const client = makeClient(); - const workingRevisionRef = makeWorkingRevisionRef(); - const { rerender } = renderInApp( - , - { client }, - ); - - rerender( - , - ); - - // Re-render with the same trigger value simulates an unrelated render - // (e.g., from parent state change) before the mutation settles. - rerender( - , - ); - - await waitFor(() => expect(client.strategyPatchState).toHaveBeenCalledTimes(1)); - - // A fresh trigger value should still be handled exactly once. - rerender( - , - ); - - await waitFor(() => expect(client.strategyPatchState).toHaveBeenCalledTimes(2)); - }); - - it('EdgeInspector patches once per trigger value, not once per render', async () => { - const client = makeClient(); - const workingRevisionRef = makeWorkingRevisionRef(); - const { rerender } = renderInApp( - , - { client }, - ); - - rerender( - , - ); - rerender( - , - ); - - await waitFor(() => expect(client.strategyPatchTransition).toHaveBeenCalledTimes(1)); - }); - - it('PromptInspector patches once per trigger value, not once per render', async () => { - const client = makeClient(); - const workingRevisionRef = makeWorkingRevisionRef(); - const { rerender } = renderInApp( - , - { client }, - ); - - rerender( - , - ); - rerender( - , - ); - - await waitFor(() => expect(client.strategyPatchPromptTemplate).toHaveBeenCalledTimes(1)); - // The component's enabled path must write the document it displays: the - // response's revision is the one the editor carries next. (The canvas never - // enables it — no canvas document is the preset YAML this writer targets.) - await waitFor(() => expect(workingRevisionRef.current).toBe(2)); - }); -}); diff --git a/apps/web/src/components/canvas/strategy-canvas/inspectors/prompt-inspector.tsx b/apps/web/src/components/canvas/strategy-canvas/inspectors/prompt-inspector.tsx index 54bcfc099..e5c971326 100644 --- a/apps/web/src/components/canvas/strategy-canvas/inspectors/prompt-inspector.tsx +++ b/apps/web/src/components/canvas/strategy-canvas/inspectors/prompt-inspector.tsx @@ -1,175 +1,39 @@ /** - * Prompt-template inspector section — edits the body of the state's prompt. + * Prompt-template inspector section — displays the body of the state's prompt. * - * Owns its own save button and partial-failure UI (R-V171P0-QC1-004). + * The rendered document is never the preset YAML this section would write, so + * the field states the route that does reach the template instead of a Save. */ -import type { MutableRefObject } from 'react'; -import { useCallback, useEffect, useRef } from 'react'; import { useTranslation } from 'react-i18next'; -import { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query'; -import { useNexusClient } from '@/lib/client-context'; -import { queryKeys } from '@/lib/nexus/query-keys'; -import { useToast } from '@/lib/use-toast'; -import type { StrategyPatchPromptTemplateRequest, StrategyPatchResponse } from '@42ch/nexus-contracts'; - -import { isStrategyConflictError } from '@/lib/canvas/use-strategy-data'; -import { isSectionDirty, originalFormOf, type EditForm, type SaveStatus, type Section } from '../state-machine'; -import type { PresetState } from '@/lib/canvas/preset-yaml'; - -export interface PatchStrategyPromptTemplateArgs { - strategyId: string; - stateId: string; - baseRevision: number; - templateRef: string; - body: string; -} - -export function usePatchStrategyPromptTemplate(): UseMutationResult< - StrategyPatchResponse, - unknown, - PatchStrategyPromptTemplateArgs -> { - const client = useNexusClient(); - const qc = useQueryClient(); - const { t } = useTranslation('canvas'); - const { toast } = useToast(); - return useMutation({ - mutationFn: (args: PatchStrategyPromptTemplateArgs) => { - const req: StrategyPatchPromptTemplateRequest = { - strategy_id: args.strategyId, - state_id: args.stateId, - base_revision: args.baseRevision, - template_ref: args.templateRef, - set: { body: args.body }, - }; - return client.strategyPatchPromptTemplate(args.strategyId, args.stateId, req); - }, - onSuccess: (_data, args) => { - toast({ variant: 'success', title: t('strategy.inspector.prompt.updated'), description: args.templateRef }); - void qc.invalidateQueries({ queryKey: queryKeys.presets.detail(args.strategyId) }); - }, - onError: () => {}, - }); -} +import type { EditForm } from '../state-machine'; interface PromptInspectorProps { - presetId: string; - selectedState: PresetState; form: EditForm; onChange: (field: K, value: EditForm[K]) => void; - workingRevisionRef: MutableRefObject; promptTemplateRef: string; - saveTrigger: number; - saveStatus: SaveStatus | undefined; - onSaveStatus: (status: SaveStatus | undefined) => void; - onConflict: (currentRevision: number, section: Section) => void; - /** - * The preset YAML this writer targets is never the rendered document — the - * applied view is frozen and a compose candidate has no prompt-body operation - * — so the editor stays visible but inert with its reason (P6). - */ - structuralWritesDisabled?: boolean; } -export function PromptInspector({ - presetId, - selectedState, - form, - onChange, - workingRevisionRef, - promptTemplateRef, - saveTrigger, - saveStatus, - onSaveStatus, - onConflict, - structuralWritesDisabled = false, -}: PromptInspectorProps) { +export function PromptInspector({ form, onChange, promptTemplateRef }: PromptInspectorProps) { const { t } = useTranslation('canvas'); - const patch = usePatchStrategyPromptTemplate(); - const original = originalFormOf(selectedState); - const dirty = isSectionDirty('prompt', form, original); - const lastHandledTriggerRef = useRef(0); - - const handleSave = useCallback(async () => { - // No canvas document is the preset YAML this patch writes, so the Save is - // refused rather than rewriting a bundle template behind the candidate. - if (structuralWritesDisabled || !dirty || patch.isPending) return; - onSaveStatus(undefined); - - try { - const res = await patch.mutateAsync({ - strategyId: presetId, - stateId: selectedState.id, - baseRevision: workingRevisionRef.current, - templateRef: promptTemplateRef, - body: form.promptBody, - }); - workingRevisionRef.current = Number(res.new_revision); - onSaveStatus({ type: 'success', message: t('strategy.inspector.prompt.saved') }); - } catch (error) { - if (isStrategyConflictError(error)) { - const currentRevision = - typeof error.details === 'object' && error.details !== null - ? (error.details as { current_revision?: number }).current_revision ?? 0 - : 0; - onConflict(currentRevision, 'prompt'); - } else { - const message = error instanceof Error ? error.message : t('strategy.inspector.prompt.saveFailed'); - onSaveStatus({ type: 'error', message }); - } - } - }, [structuralWritesDisabled, dirty, patch.isPending, form, original, presetId, selectedState, onSaveStatus, onConflict, promptTemplateRef, t]); - - // Keep a fresh callback reference for the keyboard shortcut effect so the - // effect itself does not need to depend on the callback (R-V172P1-QC1-001). - const handleSaveRef = useRef(handleSave); - handleSaveRef.current = handleSave; - - useEffect(() => { - if (saveTrigger > 0 && saveTrigger !== lastHandledTriggerRef.current) { - lastHandledTriggerRef.current = saveTrigger; - void handleSaveRef.current(); - } - }, [saveTrigger]); return (
{t('strategy.inspector.prompt.title')} -
{promptTemplateRef}