diff --git a/.gitignore b/.gitignore index 5a9b6ae1a3..0c12972408 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ __pycache__/ *.tgz *.log .DS_Store + +# rustc crash dumps +rustc-ice-*.txt diff --git a/Cargo.lock b/Cargo.lock index fd24147d28..8d6277c385 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6113,6 +6113,7 @@ version = "0.1.0-alpha.29" dependencies = [ "proc-macro2", "rutis-types", + "serde", "serde_json", "syn 2.0.119", ] diff --git a/crates/dim-agent-capabilities/tests/capabilities_flow.rs b/crates/dim-agent-capabilities/tests/capabilities_flow.rs index 9c62c91b02..399df0ed82 100644 --- a/crates/dim-agent-capabilities/tests/capabilities_flow.rs +++ b/crates/dim-agent-capabilities/tests/capabilities_flow.rs @@ -28,5 +28,6 @@ mod model_stream_recovery_flow; mod permission_flow; mod recall_flow; mod review_flows; +mod routing_flow; mod session_extension; mod workspace_files; diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs new file mode 100644 index 0000000000..81ced4a78f --- /dev/null +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -0,0 +1,609 @@ +//! Flow: a Session's parts and their runtimes reach its own lines and faces by +//! id, and answer `SessionClosing`, `NoLine` or a reach refusal otherwise +//! ([#2127](https://github.com/arcships/dim/issues/2127)). + +use dim_agent_capabilities::defaults; +use dim_agent_runtime::testing::{MinimalHost, hold_close}; +use dim_agent_runtime::*; +use dim_agent_types::BranchSource; +use rutis::Ctx; +use rutis::host::{CtxHost, DynPlugin, Effect, InstanceId, TypeKey}; +use rutis_bridge::session::{ + Connection, Dispatch, Endpoint, Error as BridgeError, HostDispatch, Reply, Value, host_key, + host_key_in, +}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +/// A Session part that hands its context to the test, where a language's +/// Session runtime would run. +struct HandsSession(Arc>>); + +impl DynPlugin for HandsSession { + fn name(&self) -> &str { + "RoutingSessionProbe" + } + fn injects(&self) -> Vec { + Vec::new() + } + fn apply<'a>(&'a self, ctx: &'a Ctx) -> rutis::host::BoxFuture<'a, rutis::Result> { + Box::pin(async move { + *self.0.lock().unwrap() = Some(ctx.clone()); + Ok(Effect::Done) + }) + } +} + +struct Rig { + host: MinimalHost, + /// The context of the last Session's probe part, once that Session opened. + session_ctx: Arc>>, +} + +impl Rig { + async fn start() -> Self { + let session_ctx = Arc::new(Mutex::new(None)); + let probe = session_ctx.clone(); + let mut builder = AgentBuilder::new(AgentConfig::default()); + builder.timeline_store(TimelineStoreBinding::new(Arc::new( + MemoryTimelineStore::default(), + ))); + defaults::mock_hosts(&mut builder); + defaults::install(&mut builder); + // The product marks the same names (its `register_faces`); a route + // resolves data faces only. + builder.internal_name("loopState", "hot-path"); + // The product shares the faces a route resolves (`share_names`); the + // rig shares the ones its cases use and leaves a native-only name + // unshared. + for (name, group) in [ + ("approval", "branch"), + ("branchLine", "branch"), + ("dispatcher", "branch"), + ("inputQueue", "branch"), + ("permission", "branch"), + ("timeline", "branch"), + ("sessionConfig", "session"), + ("treeCommands", "session"), + ("uiResources", "session"), + ("sessionLoader", "session"), + // The mechanism names the product also shares: a route refuses them + // for being registration points or lifecycle services, not for + // being unshared. + ("guideEntries", "session"), + ("sessionLifecycle", "session"), + ("sessionMethods", "session"), + ("sessionScope", "session"), + ("toolRegistry", "session"), + ("branchLifecycle", "branch"), + ] { + builder.catalog_mut().register_shared_instance(name, group); + } + builder.require_feature( + Feature::new("RoutingSessionProbe").session("RoutingSessionProbe", move |_| { + Ok(Box::new(HandsSession(probe.clone()))) + }), + ); + let host = MinimalHost::start(&builder).await.unwrap(); + Self { host, session_ctx } + } + + async fn open(&self) -> Session { + self.host + .create_session(SessionConfig::default(), Default::default()) + .await + .expect("a Session opens") + } + + fn session_ctx(&self) -> Ctx { + self.session_ctx + .lock() + .unwrap() + .take() + .expect("the Session's part loaded") + } + + fn scope(&self, session: &Session) -> Arc { + // The facade offers no read for the router; its owner hands out a + // handle only the runtime can build. + self.host + .routed_session(session.id()) + .expect("the owning instance serves its scope") + .scope() + .clone() + } +} + +/// A language runtime's side of a rutis session: it names a service in the +/// instance the runtime lives in, then at the process. +struct Names { + ctx: Ctx, + instance: InstanceId, +} + +impl Names { + fn dispatch(&self, target: &str) -> Arc { + self.ctx + .get_at::(&host_key_in(target, self.instance)) + .or_else(|| self.ctx.get_at::(&host_key(target))) + .unwrap_or_else(|| panic!("{target} is not served")) + } +} + +impl Dispatch for Names { + fn invoke(&self, _: &Connection, target: &str, method: &str, args: Value) -> Reply { + self.dispatch(target).invoke(method, args) + } +} + +struct Language { + _host: Connection, + client: Connection, +} + +impl Language { + fn open(ctx: &Ctx, instance: InstanceId) -> Self { + let (host, far) = rutis_bridge::memory::pair(); + let peer = |id: &str| Endpoint::rust(rutis_bridge::channel::PeerId::new(id).unwrap()); + let names = || Names { + ctx: ctx.clone(), + instance, + }; + let host = Connection::open(host, Arc::new(names()), peer("scope-host")).unwrap(); + let client = Connection::open(far, Arc::new(names()), peer("scope-client")).unwrap(); + Self { + _host: host, + client, + } + } + + async fn call( + &self, + face: &str, + method: &str, + call: impl serde::Serialize, + ) -> std::result::Result { + let call: Value = serde_json::to_value(call).unwrap().into(); + let reply = self + .client + .invoke_settled(face, method, Value::List(vec![call])) + .unwrap(); + tokio::time::timeout(Duration::from_secs(30), reply) + .await + .expect("the far end answers")? + .json() + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_session_part_reaches_its_own_line_and_its_own_faces() { + let rig = Rig::start().await; + let session = rig.open().await; + let scope = rig.scope(&session); + + let sequence = scope + .line_call(LineCall::new("main", "timeline", "sequence", vec![])) + .await + .unwrap(); + assert_eq!( + sequence, + Some(serde_json::json!(session.sequence("main").unwrap())) + ); + assert_eq!( + scope + .line_call(LineCall::new("absent", "timeline", "sequence", vec![])) + .await + .unwrap_err(), + RouteError::NoLine { + session: session.id().into(), + line: "absent".into() + } + ); + + let config = scope + .call(SessionCall::new("sessionConfig", "get", vec![])) + .await + .unwrap(); + assert_eq!( + config, + Some(serde_json::to_value(session.config()).unwrap()) + ); + + rig.host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_session_language_call_reaches_its_own_line_and_names_no_session() { + let rig = Rig::start().await; + let session = rig.open().await; + let ctx = rig.session_ctx(); + let language = Language::open(&ctx, session.instance().unwrap()); + language.client.ready().await.unwrap(); + + let sequence = language + .call( + "sessionScope", + "lineCall", + LineCall::new("main", "timeline", "sequence", vec![]), + ) + .await + .unwrap(); + assert_eq!( + sequence, + serde_json::json!(session.sequence("main").unwrap()) + ); + let carried = serde_json::json!({ + "sessionId": session.id(), + "lineId": "main", + "service": "timeline", + "method": "sequence", + "args": [], + }); + let failed = language + .call("sessionScope", "lineCall", carried) + .await + .expect_err("a Session call names no Session"); + assert!(failed.to_string().contains("unknown field"), "{failed}"); + rig.host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_closing_session_answers_session_closing_for_its_lines_too() { + let rig = Rig::start().await; + let session = rig.open().await; + let id = session.id().to_owned(); + let scope = rig.scope(&session); + let mut held = hold_close(&id, "main"); + let closing = { + let session = session.clone(); + tokio::spawn(async move { session.close().await }) + }; + held.arrived().await; + + assert_eq!( + scope + .line_call(LineCall::new("main", "timeline", "sequence", vec![])) + .await + .unwrap_err(), + RouteError::SessionClosing(id.clone()) + ); + assert_eq!( + scope + .call(SessionCall::new("sessionConfig", "get", vec![])) + .await + .unwrap_err(), + RouteError::SessionClosing(id.clone()) + ); + held.release(); + closing.await.unwrap().unwrap(); + rig.host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_closed_line_answers_no_line_and_the_sessions_other_calls_still_arrive() { + let rig = Rig::start().await; + let session = rig.open().await; + let id = session.id().to_owned(); + let scope = rig.scope(&session); + let source = || BranchSource::Host { + operation_id: "routing".into(), + }; + let line_id = session + .branch( + "main".into(), + 0, + BranchOptions { + prompt: "a line the route reaches".into(), + source: source(), + }, + ) + .await + .unwrap(); + assert!( + scope + .line_call(LineCall::new(&line_id, "timeline", "sequence", vec![])) + .await + .is_ok() + ); + + session.end_branch(&line_id, source()).await.unwrap(); + let deadline = Instant::now() + Duration::from_secs(30); + loop { + let answer = scope + .line_call(LineCall::new(&line_id, "timeline", "sequence", vec![])) + .await; + if matches!(answer, Err(RouteError::NoLine { .. })) { + break; + } + assert!( + Instant::now() < deadline, + "the ended line closes: {answer:?}" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!( + scope + .call(SessionCall::new("sessionConfig", "get", vec![])) + .await + .is_ok(), + "one line's end does not affect the Session's other calls" + ); + assert!( + scope + .line_call(LineCall::new("main", "timeline", "sequence", vec![])) + .await + .is_ok(), + "the Session's own main line still answers {id}" + ); + rig.host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_idle_unloaded_session_answers_session_closing_until_it_loads_again() { + let rig = Rig::start().await; + let session = rig.open().await; + let id = session.id().to_owned(); + let scope = rig.scope(&session); + + assert!( + session.unload_if_idle().await.unwrap(), + "an idle Session unloads" + ); + assert_eq!( + scope + .line_call(LineCall::new("main", "timeline", "sequence", vec![])) + .await + .unwrap_err(), + RouteError::SessionClosing(id.clone()), + "a scope of a Session that is gone reports its Session as closing" + ); + + let restored = rig + .host + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); + assert!( + rig.scope(&restored) + .line_call(LineCall::new("main", "timeline", "sequence", vec![])) + .await + .is_ok(), + "the Session's new generation answers" + ); + restored.close().await.unwrap(); + rig.host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_owner_failure_keeps_its_code_through_the_route() { + use dim_agent_capabilities::input_queue::InputQueue; + use dim_agent_types::{InputMessageData, InputWithdrawData}; + + let rig = Rig::start().await; + let session = rig.open().await; + let scope = rig.scope(&session); + let command = InputWithdrawData { + input_id: "x".into(), + reason: None, + steer: Some(InputMessageData::text("x", None)), + }; + let direct = session + .service::("main") + .expect("the line serves its input queue") + .withdraw(command.clone()) + .await + .unwrap_err(); + let routed = scope + .line_call(LineCall::new( + "main", + "inputQueue", + "withdraw", + vec![serde_json::to_value(&command).unwrap()], + )) + .await + .unwrap_err(); + let RouteError::Owner { code, .. } = &routed else { + panic!("the owner's failure crosses as Owner: {routed:?}"); + }; + assert_eq!( + code.as_deref(), + Some("InvalidInput"), + "direct {direct:?}, routed {routed:?}" + ); + session.close().await.unwrap(); + rig.host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_void_reply_stays_undefined_and_a_value_stays_a_value() { + let rig = Rig::start().await; + let session = rig.open().await; + let scope = rig.scope(&session); + + let void = scope + .call(SessionCall::new( + "sessionLoader", + "remove", + vec![serde_json::json!({"instanceId": 0})], + )) + .await + .unwrap(); + assert_eq!( + void, None, + "a method that answers nothing crosses as undefined" + ); + + // A value the owner replied stays a value. + let value = scope + .line_call(LineCall::new("main", "timeline", "sequence", vec![])) + .await + .unwrap(); + assert!(value.is_some(), "a reply stays a value: {value:?}"); + session.close().await.unwrap(); + rig.host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { + let rig = Rig::start().await; + let session = rig.open().await; + let scope = rig.scope(&session); + + for service in ["sessionMethods", "toolRegistry", "guideEntries"] { + assert_eq!( + scope + .call(SessionCall::new(service, "register", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: service.into() + }, + "{service} is a registration point" + ); + } + for service in ["sessionLifecycle", "branchLifecycle"] { + assert_eq!( + scope + .call(SessionCall::new(service, "closing", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: service.into() + }, + "{service} is a lifecycle service" + ); + } + assert_eq!( + scope + .line_call(LineCall::new("main", "wait", "wait", vec![])) + .await + .unwrap_err(), + RouteError::MethodNotRoutable { + service: "wait".into(), + method: "wait".into() + }, + "an operation that needs a caller-side cancellation is not routed" + ); + assert_eq!( + scope + .call(SessionCall::new("sessionIdentity", "get", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: "sessionIdentity".into() + }, + "a native-only registration is not a data face" + ); + for (service, group) in [ + ("sessionMethods", "session"), + ("toolRegistry", "session"), + ("guideEntries", "session"), + ] { + assert_eq!( + scope + .call(SessionCall::new(service, "register", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: service.into() + }, + "{service} is a registration point of the {group} group" + ); + } + for service in ["sessionLifecycle", "branchLifecycle"] { + assert_eq!( + scope + .call(SessionCall::new(service, "activated", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: service.into() + }, + "{service} is a scope lifecycle service" + ); + } + assert_eq!( + scope + .call(SessionCall::new("sessionScope", "lineCall", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: "sessionScope".into() + }, + "the Session's own scope is not one of the faces it resolves" + ); + assert_eq!( + scope + .call(SessionCall::new("uiResources", "publishFile", vec![])) + .await + .unwrap_err(), + RouteError::MethodNotRoutable { + service: "uiResources".into(), + method: "publishFile".into() + }, + "an operation bound to the calling row is direct-only" + ); + assert_eq!( + scope + .line_call(LineCall::new("main", "dispatcher", "listen", vec![])) + .await + .unwrap_err(), + RouteError::MethodNotRoutable { + service: "dispatcher".into(), + method: "listen".into() + }, + "an operation that hands the caller a subscription is not routed" + ); + assert_eq!( + scope + .call(SessionCall::new("treeCommands", "create", vec![])) + .await + .unwrap_err(), + RouteError::MethodNotRoutable { + service: "treeCommands".into(), + method: "create".into() + } + ); + assert_eq!( + scope + .line_call(LineCall::new("main", "loopState", "state", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: "loopState".into() + }, + "an internal face is not a data face" + ); + assert_eq!( + scope + .call(SessionCall::new("timeline", "sequence", vec![])) + .await + .unwrap_err(), + RouteError::WrongScope { + service: "timeline".into(), + group: "session".into() + }, + "a line face is not a Session face" + ); + assert_eq!( + scope + .line_call(LineCall::new("main", "sessionConfig", "get", vec![])) + .await + .unwrap_err(), + RouteError::WrongScope { + service: "sessionConfig".into(), + group: "branch".into() + }, + "a Session face is not a line face" + ); + let error = scope + .line_call(LineCall::new("main", "timeline", "absent", vec![])) + .await + .unwrap_err(); + let RouteError::Owner { name, message, .. } = error else { + panic!("the owner's failure: {error:?}"); + }; + assert_eq!(name, "no-method", "the owner's own failure keeps its name"); + assert!(message.contains("absent"), "{message}"); + rig.host.close().await.unwrap(); +} diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 6394eedb1a..e4f0f2bdb4 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -384,6 +384,14 @@ impl Agent { }) .collect() } + /// The Session `id` with its router, for the mechanism caller that owns the + /// index (Agents) to route by id. Only the runtime builds the handle + /// (`RoutedSession::new` is crate-private), so a crate holding a bare + /// [`Session`] has no path to the router: no facade method and no free + /// function takes one to a scope. + pub fn routed_session(&self, id: &str) -> Option { + self.get_session(id)?.routed() + } pub fn get_session(&self, id: &str) -> Option { match self.0.entries.lock().unwrap().get(id) { Some(Entry::Ready(s)) => Some(s.clone()), @@ -744,12 +752,17 @@ impl Session { /// Reads a service of the Session group from the currently loaded /// Session subtree. pub fn session_service(&self) -> Result> { - crate::names::in_group::(&self.0.owner.assembly.catalog, SESSION_GROUP)?; - let loaded = self.0.owner.loaded()?; - loaded - .ctx - .get_at::(&loaded.scope.key::()) - .ok_or_else(|| AgentError::Reloading(std::any::type_name::().into())) + self.0.owner.session_face::() + } + /// This Session with its router, when its owning instance provides one: + /// the runtime alone builds the handle, so a bare [`Session`] has no path + /// to it. + fn routed(&self) -> Option { + let loaded = self.0.owner.loaded().ok()?; + let scope = loaded.ctx.get_at::( + &loaded.scope.key::(), + )?; + Some(crate::route::RoutedSession::new(self.clone(), scope)) } /// The instance of the loaded Session subtree, so a host can find the /// loader rows this Session runs. Keys under it stay readable only from diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index da3a3782ba..4acb13d358 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -250,7 +250,7 @@ type ExtensionMake = Arc< >; /// Builds one plugin of an extension copy. type ExtensionPart = Box std::result::Result, Error> + Send + Sync>; -type Provide = Arc std::result::Result<(), Error> + Send + Sync>; +type Provide = Arc std::result::Result<(), Error> + Send + Sync>; /// A value registered with [`AgentBuilder::process_value`]: its name, and /// how a copy provides it at the key the name has there. #[derive(Clone)] @@ -300,6 +300,9 @@ pub(crate) struct Assembly { /// The builder's catalog, as its Agents were built: the facades read a /// name in the group it registers. pub catalog: Arc, + /// The names the builder marked internal, as its Agents were built: a + /// route resolves only a name that is not among them. + pub faces: Arc, } /// The closed set of reasons a service face is internal (#1289). pub const FACE_REASONS: [&str; 8] = [ @@ -365,6 +368,7 @@ impl AgentBuilder { required_rows: Arc::default(), extensions: vec![], catalog: Arc::default(), + faces: Arc::default(), }, } } @@ -817,12 +821,6 @@ impl AgentBuilder { builder.assembly.parts = Arc::default(); builder } - /// Whether plugins were added ([`Self::plugin`]); a host without any - /// places no process rows. - #[cfg(feature = "testing")] - pub(crate) fn has_plugins(&self) -> bool { - !self.assembly.plugins.is_empty() - } /// The longest a host waits for its assembly without progress. #[cfg(feature = "testing")] pub(crate) fn opening_timeout(&self) -> Duration { @@ -832,6 +830,7 @@ impl AgentBuilder { let mut assembly = self.assembly.clone(); assembly.abandoned = tokio_util::task::TaskTracker::new(); assembly.catalog = Arc::new(self.catalog.clone()); + assembly.faces = Arc::new(self.faces.clone()); if !self.custom_store { let store = Arc::new(MemoryTimelineStore::default()); assembly.store = TimelineStoreBinding::new(store.clone()); @@ -1077,8 +1076,8 @@ pub(crate) fn row(module: &str) -> Value { fn group(id: &str, config: Vec) -> Value { json!({ "id": id, "group": true, "instanced": true, "config": config }) } -fn session_scope(build: &Build) -> std::result::Result { - Ok(SessionScope { +fn session_scope(build: &Build) -> std::result::Result { + Ok(SessionScopeId { instance: build.instance(SESSION_GROUP)?, }) } @@ -1135,7 +1134,7 @@ pub(crate) struct SessionAssembly { pub unloading: CancellationToken, pub closing: CancellationToken, pub lifecycle: SessionLifecycle, - pub loaded: Mutex>>>, + pub loaded: Mutex>>>, /// The parts the Session's mounters mounted when it opened, until its /// creation ends. pub(crate) mounted: Arc>, @@ -1144,18 +1143,47 @@ pub(crate) struct SessionAssembly { pub(crate) copies: crate::parts::Copies, } impl SessionAssembly { - pub(crate) fn loaded(&self) -> Result>> { + pub(crate) fn loaded(&self) -> Result>> { self.loaded .lock() .unwrap() .clone() .ok_or_else(|| AgentError::Closed(self.id.clone())) } + + /// The Session-scope data face `T` of the loaded Session subtree. + pub(crate) fn session_face(&self) -> Result> { + crate::names::in_group::(&self.assembly.catalog, SESSION_GROUP)?; + let loaded = self.loaded()?; + loaded + .ctx + .get_at::(&loaded.scope.key::()) + .ok_or_else(|| AgentError::Reloading(std::any::type_name::().into())) + } + + /// The published line `id` of this Session, or `None` when it is not + /// published, has ended, or is already closing. The tree's own view decides + /// publication, so the process path and a Session part see the same state + /// (ADR 027 D2). + pub(crate) fn line(&self, id: &str) -> Option> { + let loaded = self.loaded().ok()?; + let tree = loaded + .ctx + .get_at::(&loaded.scope.key::())?; + let line = tree.published(id).ok()?.0; + (!line.is_closing()).then_some(line) + } + + /// What a route reads of this Session's assembly to decide whether it may + /// resolve a name: the catalog's groups and the names it marked internal. + pub(crate) fn reach(&self) -> (&rutis_loader::ServiceCatalog, &Faces) { + (&self.assembly.catalog, &self.assembly.faces) + } } struct SessionScopePlugin { owner: Arc, - scope: SessionScope, + scope: SessionScopeId, /// The names of this copy's instances, for the mounters it builds. build: Build, required: Arc<[String]>, @@ -1209,6 +1237,10 @@ impl DynPlugin for SessionScopePlugin { for provide in &owner.assembly.values { provide(ctx, &scope)?; } + ctx.provide_at( + scope.key::(), + Arc::new(crate::SessionScope::new(owner)), + )?; { let mut loaded = owner.loaded.lock().unwrap(); if loaded.is_some() { @@ -1502,8 +1534,8 @@ impl TimelineFactory { let ctx = &branch.scope.ctx; let scope = branch.scope.scope; required::(ctx, scope.key::())?; - Ok(TimelineContext::start( - id, + let context = TimelineContext::start( + id.clone(), ctx.clone(), created.view.clone(), created.children.clone(), @@ -1521,7 +1553,9 @@ impl TimelineFactory { branch.lifecycle.clone(), parent.lifecycle.faults.clone(), parent.assembly.catalog.clone(), - )) + parent.assembly.faces.clone(), + ); + Ok(context) }) .catch_unwind() .await diff --git a/crates/dim-agent-runtime/src/lib.rs b/crates/dim-agent-runtime/src/lib.rs index 97bd574881..1d8cd46798 100644 --- a/crates/dim-agent-runtime/src/lib.rs +++ b/crates/dim-agent-runtime/src/lib.rs @@ -12,6 +12,7 @@ mod memory_timeline_store; pub mod names; mod parts; mod registrations; +mod route; mod scope; mod state; #[cfg(feature = "testing")] @@ -35,6 +36,7 @@ pub use memory_timeline_store::*; pub use names::Names; pub use parts::{Feature, Generator, Mount, PartRegistry, PartScope}; pub use registrations::{Registration, Registrations}; +pub use route::{LineCall, RouteError, RoutedSession, SessionCall, SessionScope, resolves}; pub use rutis::host::BoxFuture; pub use scope::*; pub use state::*; diff --git a/crates/dim-agent-runtime/src/names.rs b/crates/dim-agent-runtime/src/names.rs index 5986b784d0..e8252db8b1 100644 --- a/crates/dim-agent-runtime/src/names.rs +++ b/crates/dim-agent-runtime/src/names.rs @@ -102,6 +102,7 @@ pub fn catalog() -> ServiceCatalog { catalog.register_shared_instance("timelineStore", SESSION_GROUP); register::(&mut catalog, session); register::(&mut catalog, session); + register::(&mut catalog, session); let branch = Some(BRANCH_GROUP); register::(&mut catalog, branch); register::(&mut catalog, branch); diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs new file mode 100644 index 0000000000..4ada4e43b5 --- /dev/null +++ b/crates/dim-agent-runtime/src/route.rs @@ -0,0 +1,671 @@ +//! Calls by id to a live owner's data face +//! ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D1–D4, [#2127](https://github.com/arcships/dim/issues/2127)). +//! +//! A caller outside a scope holds no instance key, so it names what it wants, +//! and the owner of the target holds the index and does the lookup: +//! +//! - a Session's [`SessionScope`] resolves one of its own lines and its own +//! Session faces, for the Session's parts and their runtimes; it holds no +//! Session id, so a caller cannot name another Session, and the scope itself +//! is not one of the faces it resolves; +//! - Agents' `sessions` resolves a Session, and a line of it, for the process +//! (`dim-app-server`): it finds the Session — loading it for the call when it +//! is not loaded (D5) — and then calls [`SessionScope::line_call`] or +//! [`SessionScope::call`] in that instance. +//! +//! Three data operations carry every routed call, with the same arguments in +//! every language: +//! +//! - [`SessionScope::line_call`] — `{lineId, service, method, args}`; +//! - [`SessionScope::call`] — `{service, method, args}`, for the Session's own +//! faces; +//! - `sessions.call` — `{sessionId, lineId?, service, method, args}`, which +//! takes the same two forms for a process caller. +//! +//! Each call looks the target up again, so a caller never keeps a live target +//! (D4). Rust calls the same two operations: it builds `args` from the target +//! operation's request type and reads the reply as its reply type. +//! +//! What a call resolves is the target scope's data face in the catalog. A name +//! the assembly marks `internal(reason)`, a mechanism registration point +//! (whose entries belong to the registering generation) and a scope lifecycle +//! service are refused as [`RouteError::NotDataFace`]; a data face of the +//! other scope is [`RouteError::WrongScope`]. Everything else about the call +//! belongs to the owner: the route passes the method and its arguments through +//! and returns the owner's reply, or the owner's own failure as it wrote it. +//! +//! Only the process path can find a Session that has no live instance: Agents +//! loads it for the call (D5), so [`RouteError::NoSession`] means the Session +//! does not exist, or is closed and cannot load again. A Session that is +//! closing answers [`RouteError::SessionClosing`], and a line target answers it +//! too, because closing the Session closes its lines. A line that is closing or +//! closed, or that belongs to another Session, answers [`RouteError::NoLine`]; +//! that is final for the line: routing never retries it. + +use crate::*; +use rutis::Ctx; +use rutis::host::CtxHost; +use rutis_bridge::session::{ + Error as BridgeError, HostDispatch, Value as BridgeValue, decode_value, host_key_in, settle, +}; +use serde::{Deserialize, Serialize}; +use std::sync::{Arc, Weak}; + +/// What a route answers: the target's reply, or why it did not reach one. +pub type Routed = std::result::Result; + +/// Why a routed call did not reach a reply. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, thiserror::Error)] +#[serde(rename_all = "camelCase")] +pub enum RouteError { + /// The Session is not there, has no owner, or is closed and cannot load + /// again. Only a process caller receives it; Agents loads and holds a + /// Session that is merely not loaded (ADR 027 D5), so this is final. + #[error("no live Session {0}")] + NoSession(String), + /// The Session instance is closing, and so is a call to one of its lines. + /// A Session-scoped caller ends its work, and a process caller reads the + /// same answer as `session_closing` and ends the work it was doing. + #[error("Session {0} is closing")] + SessionClosing(String), + /// Agents is reloading and cannot take calls yet. A process caller retries + /// later. + #[error("Agents is reloading: {0}")] + SessionReloading(String), + /// The Session exists but cannot be loaded now: its restore failed, or the + /// Agent that owns it is unavailable. The caller reports the reason and + /// does not retry. + #[error("Session {session} is unavailable: {reason}")] + SessionUnavailable { session: String, reason: String }, + /// The Session is live but the line is closing, closed, or not one of its + /// lines. Final for that line: no hold and no retry. + #[error("no line {line} in Session {session}")] + NoLine { session: String, line: String }, + /// The name is not a data face a route resolves there: the assembly marks + /// it internal, it is a mechanism registration point, or it is a scope + /// lifecycle service. A permanent answer: the request is wrong. + #[error("{service} is not a routable data face")] + NotDataFace { service: String }, + /// The service is a data face a route resolves, but this operation of it + /// is not: its call needs a cancellation or a cleanup the routed call + /// cannot carry, so only a direct call keeps its lifetime behaviour. + #[error("{service}.{method} is not a routable operation")] + MethodNotRoutable { service: String, method: String }, + /// The name is a data face, but not of the scope the route reaches. + #[error("{service} is not a {group} service")] + WrongScope { service: String, group: String }, + /// The owner's own failure, with the name, the code it reported and the + /// message it wrote; routing does not restate them. `reloading` is that + /// code's "try again later", so a caller retries exactly what the owner + /// says it may retry. + #[error("{message}")] + Owner { + name: String, + code: Option, + message: String, + /// The owner's failure as data, when its error type carries a serde + /// value: a caller can act on the same structure a direct call would + /// read, instead of parsing the message. + data: Option>, + reloading: bool, + }, +} + +impl RouteError { + /// The code a caller matches on, as the `sessions` envelope carries it. + pub fn code(&self) -> &'static str { + match self { + Self::NoSession(_) => "no_session", + Self::SessionClosing(_) => "session_closing", + Self::SessionReloading(_) => "session_reloading", + Self::SessionUnavailable { .. } => "session_unavailable", + Self::NoLine { .. } => "no_line", + Self::NotDataFace { .. } => "not_data_face", + Self::MethodNotRoutable { .. } => "method_not_routable", + Self::WrongScope { .. } => "wrong_scope", + Self::Owner { .. } => "owner", + } + } +} + +/// A call to one of the caller's own Session's lines. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct LineCall { + pub line_id: String, + pub service: String, + pub method: String, + /// The method's arguments, in order. + #[serde(default)] + pub args: Vec, +} + +impl LineCall { + /// The call to `service.method(args...)` in the line `line_id`. + pub fn new( + line_id: impl Into, + service: impl Into, + method: impl Into, + args: Vec, + ) -> Self { + Self { + line_id: line_id.into(), + service: service.into(), + method: method.into(), + args, + } + } +} + +/// A call to one of the caller's own Session's data faces. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SessionCall { + pub service: String, + pub method: String, + /// The method's arguments, in order. + #[serde(default)] + pub args: Vec, +} + +impl SessionCall { + /// The call to `service.method(args...)` in this Session. + pub fn new( + service: impl Into, + method: impl Into, + args: Vec, + ) -> Self { + Self { + service: service.into(), + method: method.into(), + args, + } + } +} + +/// Names routing does not resolve: the mechanism's registration points, whose +/// entries belong to the part that registered them and are reachable only +/// inside that generation +/// ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D3), and the +/// scope lifecycle services the runtime provides. +/// The code a marked Rust service reports for `AgentError::Reloading`: the +/// owner's own word for "try again later". +const RELOADING: &str = "Reloading"; + +/// Operations a route does not resolve even though their service is a data +/// face: each takes a function, or hands the caller a subscription or a +/// cancellation to settle, and a routed call carries data only. The list is +/// maintained by hand; the generated authoring requests read this same +/// constant, so the runtime and the declarations cannot disagree. +pub const LIFECYCLE_METHODS: [(&str, &str); 8] = [ + ("dispatcher", "consume"), + ("dispatcher", "listen"), + ("permission", "check"), + ("toolHost", "execute"), + ("treeCommands", "create"), + ("uiResources", "publishFile"), + ("uiResources", "withdraw"), + ("wait", "wait"), +]; + +/// The Session's own scope resolves a line and the Session's faces; it is not +/// one of the faces a routed call resolves, so `sessionScope.call` cannot reach +/// `sessionScope.lineCall`. Session parts inject this Session's services +/// directly instead. +const NOT_CALLABLE: [&str; 1] = ["sessionScope"]; + +/// The scope lifecycle services: the runtime provides them, and a route does +/// not hand them to a caller. +const LIFECYCLE_SERVICES: [&str; 2] = ["sessionLifecycle", "branchLifecycle"]; + +const REGISTRATION_POINTS: [&str; 5] = [ + "sessionMethods", + "toolRegistry", + "promptRegistry", + "guideEntries", + "submitChecks", +]; + +/// One Session's own lines and data faces, provided to the Session's parts and +/// their runtimes as the Session name `sessionScope`. +/// +/// It holds its Session and no other: a part of a Session reaches its own +/// Session's lines only. `describe` joins it with base-3. +pub struct SessionScope { + session: Weak, + session_id: String, +} + +impl SessionScope { + /// The scope of the Session `session` is publishing. + pub(crate) fn new(session: &Arc) -> Self { + Self { + session: Arc::downgrade(session), + session_id: session.id.clone(), + } + } + + fn live(&self) -> Routed> { + let closing = || RouteError::SessionClosing(self.session_id.clone()); + let session = self.session.upgrade().ok_or_else(closing)?; + if session.closing.is_cancelled() { + return Err(closing()); + } + Ok(session) + } + + /// The live line `line_id` of this Session. A Session that started closing + /// while the line was being resolved answers `SessionClosing`, not + /// `NoLine`: closing the Session closes its lines. + fn line_context(&self, line_id: &str) -> Routed> { + let session = self.live()?; + let line = session.line(line_id); + // A Session that started closing while the line was being selected — + // or whose loaded scope went with that close — answers `SessionClosing`: + // its lines close with it. + match self.live() { + Ok(_) => {} + Err(closing) => return Err(closing), + } + line.ok_or_else(|| RouteError::NoLine { + session: self.session_id.clone(), + line: line_id.to_owned(), + }) + .and_then(|line| match self.live() { + Err(closing @ RouteError::SessionClosing(_)) => Err(closing), + _ => Ok(line), + }) + } +} + +/// A Session with the router its owning instance provides: what Agents routes +/// through. Only the runtime builds one, when a Session is loaded, so a crate +/// that merely holds a [`Session`] has no path to the router (ADR 027 appendix +/// F). A part of another language reaches the same router as the +/// `sessionScope` data face. +/// +/// A bare [`Session`] cannot reach the router in any of these ways: +/// +/// ```compile_fail +/// use dim_agent_runtime::Session; +/// fn read(session: &Session) { +/// let _ = session.routed(); +/// } +/// ``` +/// +/// ```compile_fail +/// use dim_agent_runtime::{routed_scope, Session}; +/// fn read(session: &Session) { +/// let _ = routed_scope(session); +/// } +/// ``` +/// +/// ```compile_fail +/// use dim_agent_runtime::RoutedSession; +/// fn build() { +/// let _ = RoutedSession::new(todo!(), todo!()); +/// } +/// ``` +#[derive(Clone)] +pub struct RoutedSession { + session: Session, + scope: Arc, +} + +impl RoutedSession { + pub(crate) fn new(session: Session, scope: Arc) -> Self { + Self { session, scope } + } + pub fn session(&self) -> &Session { + &self.session + } + pub fn scope(&self) -> &Arc { + &self.scope + } +} + +#[rutis::service] +impl SessionScope { + /// Calls one of this Session's own data faces. + pub async fn call(&self, call: SessionCall) -> Routed> { + let session = self.live()?; + let (catalog, faces) = session.reach(); + face(catalog, faces, &call.service, &call.method, SESSION_GROUP)?; + let loaded = session.loaded().map_err(|error| { + // The loaded scope goes away when the Session closes, so that + // answer wins over the owner's wrapper. + if session.closing.is_cancelled() { + RouteError::SessionClosing(self.session_id.clone()) + } else { + owner(error) + } + })?; + call_face( + &loaded.ctx, + loaded.scope.instance, + &call.service, + &call.method, + &call.args, + ) + .await + } + + /// Calls one of this Session's lines' data faces. + pub async fn line_call(&self, call: LineCall) -> Routed> { + let line = self.line_context(&call.line_id)?; + face( + line.catalog(), + line.faces(), + &call.service, + &call.method, + BRANCH_GROUP, + )?; + call_face( + line.ctx(), + line.scope_instance(), + &call.service, + &call.method, + &call.args, + ) + .await + } +} + +/// Whether a route resolves `service` as a data face of `group` (module docs). +/// The generated authoring types and the runtime's own answer must agree, and +/// this is the predicate a check compares them with. +pub fn resolves( + catalog: &names::ServiceCatalog, + faces: &Faces, + service: &str, + group: &str, +) -> bool { + face(catalog, faces, service, "", group).is_ok() +} + +/// Fails unless a route may resolve `service` as a data face of `group` +/// (module docs). +pub(crate) fn face( + catalog: &names::ServiceCatalog, + faces: &Faces, + service: &str, + method: &str, + group: &str, +) -> Routed<()> { + if LIFECYCLE_METHODS + .iter() + .any(|(refused_service, refused_method)| { + *refused_service == service && *refused_method == method + }) + { + return Err(RouteError::MethodNotRoutable { + service: service.into(), + method: method.into(), + }); + } + // Only a name shared across languages is a data face; a native-only + // registration stays inside its scope. + if !catalog.is_shared(service) { + return Err(RouteError::NotDataFace { + service: service.into(), + }); + } + if REGISTRATION_POINTS.contains(&service) + || LIFECYCLE_SERVICES.contains(&service) + || (group == SESSION_GROUP && NOT_CALLABLE.contains(&service)) + || faces.reason(service).is_some() + { + return Err(RouteError::NotDataFace { + service: service.into(), + }); + } + names::named_in_group(catalog, service, group).map_err(|_| RouteError::WrongScope { + service: service.into(), + group: group.into(), + }) +} + +/// Calls `method` of the data face `service` in `instance`, as another +/// language would: the arguments travel as data and the reply comes back as +/// data. +pub(crate) async fn call_face( + ctx: &Ctx, + instance: rutis::host::InstanceId, + service: &str, + method: &str, + args: &[serde_json::Value], +) -> Routed> { + let dispatch = ctx + .get_at::(&host_key_in(service, instance)) + .ok_or_else(|| RouteError::Owner { + name: service.into(), + code: None, + message: format!("{service} is not provided now"), + data: None, + reloading: false, + })?; + let args = BridgeValue::List( + args.iter() + .map(|arg| BridgeValue::Data(arg.clone())) + .collect(), + ); + let reply = dispatch.invoke(method, args).map_err(owner)?; + let value = settle(reply).await.map_err(owner)?; + reply_value(value) +} + +/// A method that answers nothing crosses as `undefined`; `null` is a value the +/// owner chose to reply with, and a caller reads the two differently. +fn reply_value(value: BridgeValue) -> Routed> { + if matches!(value, BridgeValue::Undefined) { + return Ok(None); + } + decode_value::(value) + .map(Some) + .map_err(owner) +} + +/// The owner's failure as the target wrote it, under the name it carries. +pub(crate) fn owner(error: impl Into) -> RouteError { + let failure = error.into(); + RouteError::Owner { + name: failure.name, + code: failure.code, + message: failure.message, + data: failure.data, + reloading: failure.reloading, + } +} + +/// A failure's name and message, from either error surface a read answers +/// with. +pub(crate) struct Failure { + name: String, + code: Option, + message: String, + data: Option>, + reloading: bool, +} + +impl From for Failure { + fn from(error: AgentError) -> Self { + Self { + name: "AgentError".into(), + code: Some(agent_code(&error).to_owned()), + reloading: matches!(error, AgentError::Reloading(_)), + message: error.to_string(), + data: None, + } + } +} + +/// The code a marked Rust service reports for an `AgentError`: its variant name, +/// spelled the way the generated declarations spell it. +fn agent_code(error: &AgentError) -> &'static str { + match error { + AgentError::InvalidInput(_) => "InvalidInput", + AgentError::Closed(_) => "Closed", + AgentError::UnknownBranch(_) => "UnknownBranch", + AgentError::BranchEnded(_) => "BranchEnded", + AgentError::BranchRefused { .. } => "BranchRefused", + AgentError::Storage(_) => "Storage", + AgentError::PublicationUnknown(_) => "PublicationUnknown", + AgentError::Build(_) => "Build", + AgentError::Cancelled(_) => "Cancelled", + AgentError::Reloading(_) => "Reloading", + AgentError::AmbiguousSubmission(_) => "AmbiguousSubmission", + AgentError::PartialSubmission(_) => "PartialSubmission", + AgentError::Fault { .. } => "Fault", + AgentError::Framework { .. } => "Framework", + AgentError::Multiple(_) => "Multiple", + } +} + +impl From for Failure { + fn from(error: BridgeError) -> Self { + match error { + error @ (BridgeError::Remote { .. } | BridgeError::Binding { .. }) => { + // The owner's own code says whether it may be retried; a Rust + // service reports a reload as `Reloading` (`AgentError`'s variant + // code), and the wire keeps it in the error graph. + let reloading = error.code() == Some(RELOADING); + let code = error.code().map(str::to_owned); + let data = error.data().map(Box::new); + let name = match &error { + BridgeError::Remote { name, .. } => name.clone(), + BridgeError::Binding { code, .. } => code.unwrap_or("BindingError").into(), + other => other.to_string(), + }; + match error { + BridgeError::Remote { message, .. } | BridgeError::Binding { message, .. } => { + Self { + code, + reloading, + data, + name, + message, + } + } + other => Self { + code, + reloading, + data, + name, + message: other.to_string(), + }, + } + } + other => Self { + name: "BridgeError".into(), + code: None, + message: other.to_string(), + data: None, + reloading: false, + }, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_void_reply_is_undefined_and_a_null_reply_is_a_value() { + assert_eq!(reply_value(BridgeValue::Undefined).unwrap(), None); + assert_eq!( + reply_value(serde_json::Value::Null.into()).unwrap(), + Some(serde_json::Value::Null) + ); + } + + #[test] + fn an_owner_failure_keeps_its_code() { + let remote = |code: &str| BridgeError::Remote { + name: "AgentError".into(), + message: format!("{code}: absent"), + graph: Some(serde_json::json!({ + "root": {"type": "reference", "value": 0}, + "nodes": [{"type": "error", "name": "AgentError", "code": code, "message": "absent"}], + })), + }; + let routed = owner(remote("UnknownBranch")); + let RouteError::Owner { + code, reloading, .. + } = &routed + else { + panic!("the owner's failure crosses as Owner: {routed:?}"); + }; + assert_eq!(code.as_deref(), Some("UnknownBranch"), "{routed:?}"); + assert!(!reloading, "{routed:?}"); + assert_eq!( + agent_code(&AgentError::UnknownBranch("absent".into())), + "UnknownBranch" + ); + } + + #[test] + fn an_owner_failure_is_retryable_only_when_its_code_says_reloading() { + let reloading = owner(AgentError::Reloading("timeline".into())); + assert!( + matches!( + reloading, + RouteError::Owner { + reloading: true, + .. + } + ), + "{reloading:?}" + ); + let permanent = owner(BridgeError::Binding { + code: Some("not_reloadable"), + message: "a permanent failure whose name mentions reload".into(), + data: None, + }); + assert!( + matches!( + permanent, + RouteError::Owner { + reloading: false, + .. + } + ), + "{permanent:?}" + ); + // The production path of a Rust service's `Err`: a `Remote` error + // whose graph carries the owner's own code. + let remote = |code: &str, message: &str| BridgeError::Remote { + name: "AgentError".into(), + message: message.into(), + graph: Some(serde_json::json!({ + "root": {"type": "reference", "value": 0}, + "nodes": [{"type": "error", "name": "AgentError", "code": code, "message": message}], + })), + }; + let reloading = owner(remote(RELOADING, "timeline is reloading")); + assert!( + matches!( + reloading, + RouteError::Owner { + reloading: true, + .. + } + ), + "{reloading:?}" + ); + let permanent = owner(remote( + "not_reloadable", + "a permanent failure whose name mentions reload", + )); + assert!( + matches!( + permanent, + RouteError::Owner { + reloading: false, + .. + } + ), + "{permanent:?}" + ); + } +} diff --git a/crates/dim-agent-runtime/src/scope.rs b/crates/dim-agent-runtime/src/scope.rs index 240f2cdc86..d9a71c7eef 100644 --- a/crates/dim-agent-runtime/src/scope.rs +++ b/crates/dim-agent-runtime/src/scope.rs @@ -157,10 +157,10 @@ impl SessionLoader { } /// Identity of one Session subtree, which the runtime builds keys from. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub(crate) struct SessionScope { +pub(crate) struct SessionScopeId { pub instance: InstanceId, } -impl SessionScope { +impl SessionScopeId { pub fn key(&self) -> Key { Key::of().instance(self.instance) } @@ -169,7 +169,7 @@ impl SessionScope { /// Identity of one branch subtree nested in its Session subtree. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub(crate) struct BranchScope { - pub session: SessionScope, + pub session: SessionScopeId, pub instance: InstanceId, } impl BranchScope { diff --git a/crates/dim-agent-runtime/src/testing.rs b/crates/dim-agent-runtime/src/testing.rs index e9886789e5..482eedd9dd 100644 --- a/crates/dim-agent-runtime/src/testing.rs +++ b/crates/dim-agent-runtime/src/testing.rs @@ -332,10 +332,7 @@ async fn assemble( Factory::new(move || Box::new(AgentAnchor((*slot).clone())) as Box) }); prepare(root, &mut builtins)?; - let mut rows = match builder.has_plugins() { - true => builder.plugin_rows(&mut builtins).await?.rows, - false => vec![], - }; + let mut rows = builder.plugin_rows(&mut builtins).await?.rows; let session_row = builder.install(&mut builtins, []).await?; rows.push(builder.agent_row([row("AgentAnchor"), session_row])); let plugin = rutis_loader::LoaderPlugin::new( diff --git a/crates/dim-agent-runtime/src/timeline_context.rs b/crates/dim-agent-runtime/src/timeline_context.rs index 0e410fe6da..178a2c564c 100644 --- a/crates/dim-agent-runtime/src/timeline_context.rs +++ b/crates/dim-agent-runtime/src/timeline_context.rs @@ -56,6 +56,8 @@ pub struct TimelineContext { stop_operation: Mutex>, /// Where the facade reads which group a name is in. catalog: Arc, + /// The names the assembly marked internal. + faces: Arc, } /// How often a wait looks for a reloading Loop's successor. const LOOP_RETURN_POLL: std::time::Duration = std::time::Duration::from_millis(10); @@ -146,9 +148,11 @@ impl TimelineContext { lifecycle: BranchLifecycle, faults: FaultReporter, catalog: Arc, + faces: Arc, ) -> Arc { let this = Arc::new(Self { catalog, + faces, id, ctx, view, @@ -345,6 +349,23 @@ impl TimelineContext { pub(crate) fn scope_view(&self) -> &FiberView { &self.view } + /// The branch instance's context, for reads of its data faces by id + /// ([`crate::route::SessionScope`]). + pub(crate) fn ctx(&self) -> &Ctx { + &self.ctx + } + /// The catalog this branch's group names come from. + pub(crate) fn catalog(&self) -> &rutis_loader::ServiceCatalog { + &self.catalog + } + /// The names the assembly marked internal. + pub(crate) fn faces(&self) -> &Faces { + &self.faces + } + /// The branch group instance this line runs in. + pub(crate) fn scope_instance(&self) -> rutis::host::InstanceId { + self.scope.instance + } /// The loader row ids this branch's profile requires. pub(crate) fn required_rows(&self) -> &[String] { &self.required diff --git a/crates/dim-agent-scheduler/tests/data_faces_flow.rs b/crates/dim-agent-scheduler/tests/data_faces_flow.rs index ea5080a2b7..89867af9cf 100644 --- a/crates/dim-agent-scheduler/tests/data_faces_flow.rs +++ b/crates/dim-agent-scheduler/tests/data_faces_flow.rs @@ -17,6 +17,7 @@ impl DynPlugin for Probe { } fn injects(&self) -> Vec { vec![ + host_key("sessions").erase(), host_key("scheduleJobs").erase(), host_key("wakeups").erase(), host_key("loops").erase(), @@ -786,3 +787,90 @@ async fn loop_face_cancellation_stops_reads_and_keeps_committed_starts() { assert!(reply["loopId"].is_string(), "{reply}"); rig.close().await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_process_call_by_id_reaches_a_live_session_and_names_the_reason_it_cannot() { + let rig = Rig::start().await; + let session = rig + .server + .agent() + .expect("the product profile has an Agent") + .create_session( + dim_agent_runtime::SessionConfig { + cwd: rig._home.path().to_string_lossy().into_owned(), + ..Default::default() + }, + Default::default(), + ) + .await + .unwrap(); + let id = session.id().to_owned(); + let face = rig + .call( + "sessions", + "call", + json!({"sessionId": id, "service": "sessionConfig", "method": "get"}), + ) + .await; + assert_eq!( + face["ok"], true, + "a Session-scope face answers through Agents: {face}" + ); + // The line's head may advance between the two reads (a fact publishes in + // between), so the routed answer must lie in the window the two direct + // reads bound, not equal one of them. + let before = session.sequence("main").unwrap(); + let line = rig + .call( + "sessions", + "call", + json!({"sessionId": id, "lineId": "main", "service": "timeline", "method": "sequence"}), + ) + .await; + let after = session.sequence("main").unwrap(); + let routed = line["value"].as_u64().unwrap_or_else(|| panic!("{line}")); + assert!( + (before..=after).contains(&routed), + "the routed head {routed} lies between {before} and {after}: {line}" + ); + let unknown = rig + .call( + "sessions", + "call", + json!({"sessionId": "absent", "service": "sessionConfig", "method": "get"}), + ) + .await; + assert_eq!(unknown["error"]["code"], "no_session", "{unknown}"); + let missing = rig + .call( + "sessions", + "call", + json!({"sessionId": id, "lineId": "absent", "service": "timeline", "method": "sequence"}), + ) + .await; + assert_eq!(missing["error"]["code"], "no_line", "{missing}"); + // A Session that closed itself keeps stored rows Agents cannot load, which + // is `session_unavailable`; a deleted one is `no_session`. + session.close().await.unwrap(); + let closed = rig + .call( + "sessions", + "call", + json!({"sessionId": id, "service": "sessionConfig", "method": "get"}), + ) + .await; + assert_eq!(closed["error"]["code"], "session_unavailable", "{closed}"); + let deleted = rig + .call("sessions", "delete", json!({"sessionId": id})) + .await; + assert_eq!(deleted["ok"], true, "{deleted}"); + let gone = rig + .call( + "sessions", + "call", + json!({"sessionId": id, "service": "sessionConfig", "method": "get"}), + ) + .await; + assert_eq!(gone["error"]["code"], "no_session", "{gone}"); + rig.close().await; +} diff --git a/crates/dim-app-server/Cargo.toml b/crates/dim-app-server/Cargo.toml index bcaf8bcf15..a65e520fe5 100644 --- a/crates/dim-app-server/Cargo.toml +++ b/crates/dim-app-server/Cargo.toml @@ -18,6 +18,10 @@ path = "tests/provider_memory_flow.rs" name = "app_server_flow" path = "tests/app_server_flow.rs" +[[test]] +name = "routed_call_flow" +path = "tests/routed_call_flow.rs" + [dependencies] dim-codemode.workspace = true dim-agent-runtime.workspace = true diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index ded1b0849b..1c282046fa 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -9,8 +9,9 @@ use dim_agent_capabilities::{host::ModelSelectionHost, methods::RpcError}; use dim_agent_runtime::{ AGENT_GROUP, Agent, AgentBuilder, AgentError, CollaborationRole, CreateSessionOptions, InUse, Modules, Names, NoConfig, QueryFilter, QueryOperand, QueryOutput, QueryPage, QueryPick, - QueryRow, QuerySelect, QuerySpec, QueryValue, RestoreSessionOptions, Session, SessionConfig, - TimelineKey, TimelineQuery, TimelineQueryScope, TimelineReadScope, TimelineReadSegment, + QueryRow, QuerySelect, QuerySpec, QueryValue, RestoreSessionOptions, RouteError, Session, + SessionConfig, TimelineKey, TimelineQuery, TimelineQueryScope, TimelineReadScope, + TimelineReadSegment, }; pub use dim_agent_types::AgentProfile; use dim_agent_types::{ROOT_BRANCH_ID, TimelinePosition}; @@ -1635,6 +1636,78 @@ impl AgentIndex { } created } + /// Calls a data face of the live Session `id`, or of one of its lines + /// ([#2127](https://github.com/arcships/dim/issues/2127), + /// [ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D1, D5): + /// the Session is loaded for the call and held while it runs, its own scope + /// resolves a line, and the target's reply and error come back unchanged. + /// A target that cannot be selected answers `NoSession`, + /// `SessionClosing`, `SessionReloading`, `SessionUnavailable` or `NoLine` + /// before the target's operation runs. + pub(crate) async fn call( + &self, + request: crate::agents::sessions::CallRequest, + ) -> std::result::Result, RouteError> { + let id = request.session_id.clone(); + // A replaced or stopping index is transient: the caller retries the + // Session it knows against the next generation (#2127). + if self.stopping.is_cancelled() { + return Err(RouteError::SessionReloading(id)); + } + let used = self.acquire(&id).await.map_err(|error| match error { + AgentError::Reloading(_) => RouteError::SessionReloading(id.clone()), + // The index stopped between the check above and the acquire: the + // same transient answer, not a missing Session. + AgentError::Closed(closed) if self.stopping.is_cancelled() => { + RouteError::SessionReloading(closed) + } + AgentError::Closed(_) => RouteError::NoSession(id.clone()), + error => RouteError::SessionUnavailable { + session: id.clone(), + reason: error.to_string(), + }, + })?; + let session = &used.session; + if session.is_closing() { + return Err(RouteError::SessionClosing(id)); + } + // The router comes from the owning instance: the runtime hands out a + // handle it alone can build, so a bare `Session` has no path to it. + let Some(routed) = used.host.agent.routed_session(&id) else { + // The scope goes away when the Session closes, so a close in this + // window is that answer rather than an unavailable Session. + return Err(if session.is_closing() { + RouteError::SessionClosing(id) + } else { + RouteError::SessionUnavailable { + session: id, + reason: "the Session's scope is not provided".into(), + } + }); + }; + let scope = routed.scope().clone(); + match request.line_id { + Some(line_id) => { + scope + .line_call(dim_agent_runtime::LineCall::new( + line_id, + request.service, + request.method, + request.args, + )) + .await + } + None => { + scope + .call(dim_agent_runtime::SessionCall::new( + request.service, + request.method, + request.args, + )) + .await + } + } + } /// `session.delete` ([S5c §3.2](../../../docs/design/appserver/session-deletion-and-fork.md#32-sequence)): /// holds S's admission gate, so nothing loads or builds S meanwhile, /// closes S if it is loaded, has SessionStore remove what it stores of diff --git a/crates/dim-app-server/src/agents/sessions.rs b/crates/dim-app-server/src/agents/sessions.rs index 84af4f3ad4..3126b4ca91 100644 --- a/crates/dim-app-server/src/agents/sessions.rs +++ b/crates/dim-app-server/src/agents/sessions.rs @@ -24,6 +24,21 @@ use serde_json::json; use std::{future::Future, sync::Arc, sync::atomic::Ordering}; use tokio_util::sync::CancellationToken; +/// A call by id to a data face of a Session, or of one of its lines. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CallRequest { + pub session_id: String, + /// The line whose faces this call reaches; absent: the Session's own. + #[serde(default)] + pub line_id: Option, + pub service: String, + pub method: String, + /// The method's arguments, in order. + #[serde(default)] + pub args: Vec, +} + /// A branch of a Session. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -281,6 +296,49 @@ pub struct StopRequest { pub enum SessionsError { #[error("{message}")] Rejected { message: String }, + /// A routed call could not select its target. These are the same codes a + /// Session's own scope answers: `no_session`, `session_closing`, + /// `session_reloading` (retryable), `session_unavailable`, `no_line`, + /// `not_data_face`, `method_not_routable` and `wrong_scope`. + #[error("{message}")] + NoSession { message: String }, + #[error("{message}")] + SessionClosing { message: String }, + #[error("{message}")] + SessionReloading { message: String }, + /// The Session exists but cannot load; `reason` says why. + #[error("{message}")] + SessionUnavailable { message: String, reason: String }, + /// The line is not the Session's, or it is gone; `line` names it. + #[error("{message}")] + NoLine { message: String, line: String }, + #[error("{message}")] + NotDataFace { message: String, service: String }, + #[error("{message}")] + MethodNotRoutable { + message: String, + service: String, + method: String, + }, + #[error("{message}")] + WrongScope { + message: String, + service: String, + group: String, + }, + /// The target owner's own failure, with the name and message it wrote and + /// whether the owner says it may be retried. + #[error("{message}")] + Routed { + name: String, + /// The code the owner reported, when its error carries one. + owner_code: Option, + message: String, + /// The owner's failure as data, when its error type carries a serde + /// value. + data: Option>, + retryable: bool, + }, #[error("{message}")] AgentUnknown { message: String }, #[error("{message}")] @@ -315,7 +373,13 @@ impl SessionsError { pub fn retryable(&self) -> bool { matches!( self, - Self::Reloading { .. } | Self::PublicationUnknown { .. } + Self::Reloading { .. } + | Self::PublicationUnknown { .. } + | Self::SessionReloading { .. } + | Self::Routed { + retryable: true, + .. + } ) } } @@ -819,7 +883,7 @@ impl HostDispatch for SessionsService { Some(json!({ "launch": "async", "input": "async", "lookup": "async", "exists": "async", "history": "async", "withdraw": "async", "pending": "async", "stop": "async", "idle": "async", - "delete": "async", "defaultBranchId": "async", + "delete": "async", "defaultBranchId": "async", "call": "async", })) } fn invoke(&self, method: &str, args: Value) -> Reply { @@ -832,12 +896,69 @@ impl HostDispatch for SessionsService { let args = args.json(); let operation = async move { match (index, args) { + // A routed call to a Session whose index is being replaced is + // transient: the caller retries the Session it knows (#2127). + (None, _) if method == "call" => Err(index_reloading()), (None, _) => Err(SessionsError::reloading("the Agents index")), (_, Err(error)) => Err(SessionsError::rejected(error.to_string())), (Some(index), Ok(args)) => call(&index, &method, args, row.as_ref()).await, } }; - Ok(Value::future(async move { Ok(envelope(operation.await)) })) + Ok(Value::future(async move { + match operation.await { + Ok(reply) if reply.get("ok").is_some() => Ok(reply.into()), + other => Ok(envelope(other)), + } + })) + } +} + +/// What a routed call answers while the Agents index is being replaced: the +/// one transient answer, so a caller retries instead of treating the Session as +/// gone. +fn index_reloading() -> SessionsError { + SessionsError::SessionReloading { + message: "the Agents index is reloading".into(), + } +} + +/// The routing answer as this face reports it: its own kind for a target that +/// could not be selected, and the owner's failure as the owner wrote it. +fn routed(error: dim_agent_runtime::RouteError) -> SessionsError { + use dim_agent_runtime::RouteError; + let message = error.to_string(); + match error { + RouteError::NoSession(_) => SessionsError::NoSession { message }, + RouteError::SessionClosing(_) => SessionsError::SessionClosing { message }, + RouteError::SessionReloading(_) => SessionsError::SessionReloading { message }, + RouteError::SessionUnavailable { reason, .. } => { + SessionsError::SessionUnavailable { message, reason } + } + RouteError::NoLine { line, .. } => SessionsError::NoLine { message, line }, + RouteError::Owner { + name, + code, + data, + reloading, + .. + } => SessionsError::Routed { + name, + owner_code: code, + message, + data, + retryable: reloading, + }, + RouteError::NotDataFace { service } => SessionsError::NotDataFace { message, service }, + RouteError::MethodNotRoutable { service, method } => SessionsError::MethodNotRoutable { + message, + service, + method, + }, + RouteError::WrongScope { service, group } => SessionsError::WrongScope { + message, + service, + group, + }, } } @@ -897,6 +1018,20 @@ async fn call( index.delete(&session_id).await?; reply(json!({})) } + "call" => index + .call(request(args)?) + .await + .map_err(routed) + .map(|value| { + let mut reply = serde_json::Map::new(); + reply.insert("ok".into(), serde_json::Value::Bool(true)); + // A method that answers nothing leaves `value` out: a caller reads + // absent as `undefined`, while `null` stays the owner's reply. + if let Some(value) = value { + reply.insert("value".into(), value); + } + serde_json::Value::Object(reply) + }), _ => Err(SessionsError::rejected(format!( "unknown sessions method {method}" ))), diff --git a/crates/dim-app-server/src/agents/sessions/tests.rs b/crates/dim-app-server/src/agents/sessions/tests.rs index 377076c9d3..71e3fc143e 100644 --- a/crates/dim-app-server/src/agents/sessions/tests.rs +++ b/crates/dim-app-server/src/agents/sessions/tests.rs @@ -229,3 +229,12 @@ async fn exists_answers_loaded_unloaded_closed_and_deleted() { server.shutdown(); server.join().await.unwrap(); } + +#[test] +fn a_routed_call_during_an_index_replacement_is_transient() { + use serde_json::json; + let error = super::index_reloading(); + let value = json!(error); + assert_eq!(value["code"], "session_reloading", "{value}"); + assert!(error.retryable(), "{value}"); +} diff --git a/crates/dim-app-server/src/session_typescript.rs b/crates/dim-app-server/src/session_typescript.rs index e941fb1859..bb2e91b2f8 100644 --- a/crates/dim-app-server/src/session_typescript.rs +++ b/crates/dim-app-server/src/session_typescript.rs @@ -92,9 +92,10 @@ fn crossing_instance_names() -> [(String, &'static str); 17] { /// The names a host of foreign parts shares across languages beyond those /// the catalog already shares: the marked Session and branch services, the /// tool, method and guide-entry registries, with which a part of any -/// language registers its contributions, and the part registry, with which a -/// plugin registers its parts. The generated catalog (`xtask graph`) shares -/// them the same way. +/// language registers its contributions, the part registry, with which a +/// plugin registers its parts, and the Session scope, which names a line and +/// the Session's own faces by id ([`SessionScope`](dim_agent_runtime::SessionScope)). +/// The generated catalog (`xtask graph`) shares them the same way. pub fn share_names(catalog: &mut ServiceCatalog) { for (name, group) in crossing_instance_names() { catalog.register_shared_instance(name, group); @@ -104,6 +105,7 @@ pub fn share_names(catalog: &mut ServiceCatalog) { .register_shared_instance(name_of::(), SESSION_GROUP) .register_shared_instance(name_of::(), SESSION_GROUP) .register_shared_instance(name_of::(), SESSION_GROUP) + .register_shared_instance(name_of::(), SESSION_GROUP) .register_shared(name_of::()) .register_shared(name_of::()); } diff --git a/crates/dim-app-server/tests/routed_call_flow.rs b/crates/dim-app-server/tests/routed_call_flow.rs new file mode 100644 index 0000000000..06010f5435 --- /dev/null +++ b/crates/dim-app-server/tests/routed_call_flow.rs @@ -0,0 +1,209 @@ +#![cfg(unix)] +//! A routed call by id against a minimal host that has only the offline model +//! catalog: Agents admits the Session, so the load-and-hold path of ADR 027 D5 +//! is the production one (#2127). +//! +//! Unix only: the host listens on a Unix socket. `scripts/test-windows-native.mjs` +//! compiles `dim-cli --lib` and the two flow targets it names, so Windows never +//! builds this file. + +use dim_agent_capabilities::defaults; +use dim_agent_runtime::{AgentBuilder, AgentConfig}; +use dim_app_server::{RunningServer, ServerConfig, serve}; +use rutis::Ctx; +use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, TypeKey}; +use rutis_bridge::session::{Connection, Dispatch, Endpoint, HostDispatch, Reply, Value, host_key}; +use serde_json::json; +use std::path::PathBuf; +use std::sync::{Arc, OnceLock}; +use std::time::Duration; + +/// A process row that hands its context to the test, so the test speaks to the +/// assembly as a plugin of another language would. +struct Probe(Arc>); + +impl DynPlugin for Probe { + fn name(&self) -> &str { + "routed-call-probe" + } + fn injects(&self) -> Vec { + vec![host_key("sessions").erase()] + } + fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { + Box::pin(async move { + self.0.set(ctx.clone()).ok(); + Ok(Effect::Done) + }) + } +} + +struct Faces(Ctx); + +impl Dispatch for Faces { + fn invoke(&self, _: &Connection, target: &str, method: &str, args: Value) -> Reply { + self.0 + .require_at::(&host_key(target)) + .unwrap() + .invoke(method, args) + } +} + +struct Rig { + home: tempfile::TempDir, + server: RunningServer, + _host: Connection, + client: Connection, +} + +impl Rig { + async fn start() -> Self { + let home = tempfile::tempdir().unwrap(); + std::fs::set_permissions( + home.path(), + std::os::unix::fs::PermissionsExt::from_mode(0o700), + ) + .unwrap(); + let catalog = dim_agent_aimux::config::ModelConfigFile::load( + &PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../dim-agent-aimux/examples/offline.json"), + ) + .expect("the offline model catalog loads"); + let mut builder = AgentBuilder::new(AgentConfig::default()); + defaults::mock_hosts(&mut builder); + defaults::install(&mut builder); + let observed = Arc::new(OnceLock::new()); + let probe = observed.clone(); + builder.plugin(move |_| Ok(Box::new(Probe(probe.clone())) as Box)); + let server = serve( + builder, + ServerConfig { + startup_timeout: Duration::from_secs(60), + database_path: Some(home.path().join("dimcode.sqlite")), + unix_path: Some(home.path().join("native.sock")), + model_catalog: Some(Arc::new( + dim_agent_aimux::AimuxModels::from_config(catalog).expect("the catalog builds"), + )), + ..Default::default() + }, + ) + .await + .expect("the minimal host serves"); + let ctx = observed.get().expect("the probe loads").clone(); + let (a, b) = rutis_bridge::memory::pair(); + let peer = |id: &str| Endpoint::rust(rutis_bridge::channel::PeerId::new(id).unwrap()); + let host = Connection::open(a, Arc::new(Faces(ctx.clone())), peer("routed-host")).unwrap(); + let client = Connection::open(b, Arc::new(Faces(ctx)), peer("routed-client")).unwrap(); + client.ready().await.unwrap(); + Self { + home, + server, + _host: host, + client, + } + } + + async fn call(&self, method: &str, request: serde_json::Value) -> serde_json::Value { + tokio::time::timeout( + Duration::from_secs(30), + self.client + .invoke_settled("sessions", method, Value::List(vec![request.into()])) + .unwrap(), + ) + .await + .expect("the call answers") + .expect("the call is served") + .json() + .expect("a reply is data") + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_routed_call_loads_and_holds_an_admitted_session() { + let rig = Rig::start().await; + let launched = rig + .call("launch", json!({"cwd": rig.home.path().to_string_lossy()})) + .await; + let id = launched["value"]["sessionId"] + .as_str() + .unwrap_or_else(|| panic!("a Session launches through Agents: {launched}")) + .to_owned(); + let before = rig + .call( + "call", + json!({"sessionId": id, "service": "sessionConfig", "method": "get"}), + ) + .await; + assert_eq!(before["ok"], true, "an admitted Session answers: {before}"); + let session = rig + .server + .agent() + .expect("the profile has an Agent") + .get_session(&id) + .expect("the launched Session is loaded"); + session.idle("main").await.unwrap(); + assert!( + session.unload_if_idle().await.unwrap(), + "an idle admitted Session unloads" + ); + assert!( + rig.server.agent().unwrap().get_session(&id).is_none(), + "the idle release takes the Session out of the Agent" + ); + let restored = rig + .call( + "call", + json!({"sessionId": id, "service": "sessionConfig", "method": "get"}), + ) + .await; + assert_eq!( + restored["ok"], true, + "sessions.call reloads an admitted Session (D5): {restored}" + ); + rig.server.shutdown(); + rig.server.join().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_call_during_an_agents_restart_is_retryable() { + let rig = Rig::start().await; + let launched = rig + .call("launch", json!({"cwd": rig.home.path().to_string_lossy()})) + .await; + let id = launched["value"]["sessionId"] + .as_str() + .unwrap_or_else(|| panic!("a Session launches through Agents: {launched}")) + .to_owned(); + let call = json!({"sessionId": id, "service": "sessionConfig", "method": "get"}); + let calls = async { + let mut transient = 0usize; + let mut answered = 0usize; + for _ in 0..150 { + let reply = rig.call("call", call.clone()).await; + if reply["error"]["code"] == "session_reloading" { + transient += 1; + assert_eq!(reply["error"]["retryable"], true, "{reply}"); + } else if reply["ok"] == true { + answered += 1; + } + } + (transient, answered) + }; + let ((transient, answered), restarted) = tokio::join!(calls, async { + tokio::time::sleep(Duration::from_millis(20)).await; + rig.server.restart("Agents").await + }); + restarted.expect("Agents restarts"); + println!("transient={transient} answered={answered}"); + assert!( + transient > 0, + "a call during the restart answers a retryable session_reloading: transient={transient} answered={answered}" + ); + let retried = rig.call("call", call.clone()).await; + assert_eq!( + retried["ok"], true, + "the retry after the restart answers: {retried}" + ); + println!("transient={transient} answered={answered}"); + rig.server.shutdown(); + rig.server.join().await.unwrap(); +} diff --git a/docs/design/appserver/sessions-service.md b/docs/design/appserver/sessions-service.md index 1b0231a8ed..cc5b5234c1 100644 --- a/docs/design/appserver/sessions-service.md +++ b/docs/design/appserver/sessions-service.md @@ -141,7 +141,8 @@ The call path from a consumer to a Session (a call path, not an assembly graph): | --- | --- | | Identity | Name `sessions`, process scope, control node only, no instance key | | Provider | Agents' directory part. Each call looks up the current `AgentIndex`; while there is none, the call fails `reloading`. Index reload ends cancellable calls, preserves own-outcome calls (§8.3), and never reloads a consumer (D1) | -| Calls | All methods are async. Each takes one request object, carried as `[request]` by rutis, and returns one envelope: `{ok: true, value}` or `{ok: false, error: SessionsError}`. The error carries `retryable` beside its `code` and `message`. An unknown method, a missing or extra argument, an unknown field or a wrong type replies `rejected` | +| Calls | All methods are async. Each takes one request object, carried as `[request]` by rutis, and returns one envelope: `{ok: true, value}` or `{ok: false, error: SessionsError}`. A routed method +that replies nothing omits `value` (`{ok: true}`), so a caller reads it as `undefined`. The error carries `retryable` beside its `code` and `message`. An unknown method, a missing or extra argument, an unknown field or a wrong type replies `rejected` | | Errors | `SessionsError {code, message, retryable}` (§9) | | Cancellation | The consumer drops the call. Dropping a Rust future ends cancellable work and releases its lease. A dropped `launch` still finishes creation (§6.1); admitted `input` retains its task and lease (§6.2) | | Rust consumers | Look up `AgentIndex` on each use, as Rpc looks up Provider, and call the typed methods in Appendix A. They may also use the named service | diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 6bb93141c4..3ceebfd579 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -32,18 +32,27 @@ ### Calls from a Session to a selected branch -Within a branch, inject its owner face directly. For Session callers the existing -`timelineTree` face gains `call({branchId,operation}, cancelled) → operation reply`. -TimelineTree resolves the admitted live branch once using its existing branch lookup and -dispatches on that branch instance. The operation is a tagged union of the calls below; -Direct variants use the owner method's arguments, reply and error. The compact RPC variant below returns the existing settled client result. The Session caller gets data. -Ended and unknown branches retain their original errors. Calls admitted before close stay -with that generation. Tree history, directory and batch input continue to use the tree's -own methods. +Within a branch, inject its owner face directly. A Session caller names the line and the +owner's face, and the owner of the line's index resolves it +([#2127](https://github.com/arcships/dim/issues/2127), +[ADR 027](../../adr/027-cross-scope-access-by-id.md)): `sessionScope.lineCall` reaches a +line of the caller's own Session, `sessions.call` a Session and a line of it for the +process, and both pass the owner's arguments, reply and error through. The two surfaces spell +the same failure differently: the `sessions` envelope answers snake_case codes, and a Session +part's scope throws `RouteError`, whose variants are camelCase and whose owner variant carries +the owner's name, message, data and reloading flag. A routed method that replies nothing answers +`null` through `sessionScope` (the bridge maps an absent value to JSON null), and the `sessions` +envelope leaves `value` out so a process caller reads `undefined`; a direct call answers nothing +(`undefined`) either way. Agents loads the +Session for the call and holds it while it runs (ADR 027 D5). A target that cannot be +selected answers `no_session`, `session_closing`, `session_reloading` (retry later), +`session_unavailable` (report the reason) or `no_line` (final for that line), before the +target's operation runs. Tree history, directory and batch input continue to use the +tree's own methods. | Session caller | Target operation | | --- | --- | -| Context RPC / PromptSuggestion | `contextUsage.read`. The `compactAndWait` variant runs the existing compact RPC handler: it calls `agentLoop.compact` and waits for the compaction fact matching that command sequence and returns the existing completed/skipped/failed reply. The committed sequence watch and bounded query run inside the selected branch for that wait. | +| Context RPC / PromptSuggestion | `contextUsage.read`, a direct call inside the Session's own face. A compaction that waits stays in the existing compact RPC handler: it takes its `Branch`, calls `AgentLoop::compact` there and waits on the branch's own `publication()`/`query`, then returns the existing completed/skipped/failed reply. These handlers are reached by the Session's own code today; routing them is written here only once `agentLoop`, `contextUsage`, `prompt` and `timelineTree` are routable faces with a wait operation, which they are not (`route::face` refuses them as internal). | | Session language / Agent configuration / Report | `prompt.configure` or `prompt.adoptedConfiguration` with the existing source, model and outcome records. | | InputQueue management / Collaboration | `inputQueue.withdraw` with the existing command; the caller runs the existing submit checks for steer before writing. `approval.pending` returns the branch's existing pending requests, and `approval.decide` settles the selected request. Collaboration retains its ended response on closed/ended/unknown detail lookup. | diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index d66a83afb2..3325678403 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -29,12 +29,71 @@ requires finite numbers and integers representable by Rust's signed or unsigned The external client protocol's `JsonValue` remains JSON-only and does not admit `bigint`. These types describe their respective boundaries, not a conversion step. +## Calling a Session or line by id + +A part of a line calls its own line's services directly. A part outside that line names +the id instead, and the owner of the index looks it up at the call: `sessionScope.lineCall` +for a line of its own Session, `sessions.call` for a Session or a line of it, from the +process. Both carry `{service, method, args}` — the target's own operation — and answer +`no_session`, `session_closing`, `session_reloading`, `session_unavailable` or `no_line` when +the target cannot be selected; the target owner's own failure arrives unchanged +([#2127](https://github.com/arcships/dim/issues/2127), ADR 027). + +```ts +import type { Sessions } from 'dimcode/plugin'; +import type { SessionScope } from 'dimcode/branch-services.js'; + +declare const sessionScope: SessionScope; +declare const sessions: Sessions; +declare const sessionId: string; +declare const id: string; + +// a Session part +await sessionScope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'withdraw', args: [{ input_id: id }] }) +// a process part +await sessions.call({ sessionId, lineId: 'main', service: 'inputQueue', method: 'withdraw', args: [{ input_id: id }] }) +await sessions.call({ sessionId, service: 'sessionConfig', method: 'get', args: [] }) +``` + +The request types are generated, so `service`, `method` and `args` are the target's own and +a typo fails `tsc`. Nothing a call returns may be kept: the next call looks the target up +again. + +The two entries name a failure with different spellings. `sessions.call` answers the +`sessions` envelope with snake_case codes — `no_session`, `session_closing`, +`session_reloading`, `session_unavailable`, `no_line`, `not_data_face`, +`method_not_routable`, `wrong_scope`, and `routed` for the owner's own failure. +`sessionScope.lineCall`/`call` throw a `RouteError` whose variants carry the same kinds in +camelCase (`noSession`, `sessionClosing`, `sessionReloading`, `sessionUnavailable`, +`noLine`, `notDataFace`, `methodNotRoutable`, `wrongScope`, `owner`), and `owner` keeps the +owner's `name`, `message`, `data` and `reloading`. Only `session_reloading`/`sessionReloading` +and an owner failure that says it reloads may be retried. A routed method that replies nothing +answers `null` through `sessionScope`; `sessions.call` leaves `value` out, so a process caller +reads `undefined`; a direct call answers `undefined`. Do not test such a reply for truthiness. + +Operations whose signature cannot cross languages — a callback, a cancellation, or the +calling row — are not routed: call them on an injected service directly. `xtask -- check` +derives them from the service signatures and fails when the runtime's refusal list and the +signatures disagree, so this stays true as operations are added. + +`sessionScope.call` serves the caller that selected a Session by id; a Session part calls its +own Session's services through injection as before. The Session's own scope is not one of the +faces a routed call resolves. + +A line is admitted while it is published and not closing. A running line that ends a tool call +commits that batch but stays selectable until its turn ends, so a call placed between the two +still reaches its owner. The cutoff is entering closing: after a durable `branch/end` the line +keeps answering while `close_and_record` waits for `deliver_final`, and once the instance starts +closing a new call answers `no_line`, which is final for that line. A call admitted before the +closing keeps its owner's own result and failure, including one that arrives after the end. Rust calls the same operations: it builds `args` from the target operation's request +type and reads the reply as that operation's reply type. + ## Available services | Need | Service and scope | Availability | | --- | --- | --- | | Persist a process plugin's own data | `pluginFiles`, process | Implemented when the host supplies an authorized product root and provisions parent directories; use its native transactions and lifecycle scope. | -| Start or drive another Session | `sessions`, process | Implemented by Agents; all nine methods are typed. | +| Start or drive another Session | `sessions`, process | Implemented by Agents; every method is typed. `call({sessionId, lineId?, service, method, args})` reaches a Session's or a line's data face by id ([Calling a Session or line by id](#calling-a-session-or-line-by-id)). | | Publish events to subscribed branches | `eventHub`, process | Implemented by EventHub: `declare` and `publish`, served to the calling row. Inject it: the row loads only while EventHub runs and declares at `apply`. | | Read current branch permissions or host defaults | `sessionPermissions`, process | Generated from Agents: `permission({sessionId, branchId})` and `permissionDefaults({})`. | | Read or set a Session's title | `sessionMetadata`, process | Implemented by SessionStore: `read` and the revision-checked `setTitle` ([title metadata](design/appserver/session-title-metadata.md)). SessionTitle is the title's one writer; other plugins only read. | diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 506d28a64c..3c4c521e6b 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1403,6 +1403,40 @@ export interface PartRegistry { registerDefinition(scope: PartScope, name: string, definition: import('@arcships/rutis').Plugin | ((ctx: any, config: any) => unknown) | { apply(ctx: any, config: any): unknown }): Promise } + +/** Why a routed call did not reach a reply. */ +export type RouteError = + | /** The Session is not there, has no owner, or is closed and cannot load again. Only a process caller receives it; Agents loads and holds a Session that is merely not loaded (ADR 027 D5), so this is final. */ { noSession: string } + | /** The Session instance is closing, and so is a call to one of its lines. A Session-scoped caller ends its work, and a process caller reads the same answer as `session_closing` and ends the work it was doing. */ { sessionClosing: string } + | /** Agents is reloading and cannot take calls yet. A process caller retries later. */ { sessionReloading: string } + | /** The Session exists but cannot be loaded now: its restore failed, or the Agent that owns it is unavailable. The caller reports the reason and does not retry. */ { sessionUnavailable: { session: string; reason: string } } + | /** The Session is live but the line is closing, closed, or not one of its lines. Final for that line: no hold and no retry. */ { noLine: { session: string; line: string } } + | /** The name is not a data face a route resolves there: the assembly marks it internal, it is a mechanism registration point, or it is a scope lifecycle service. A permanent answer: the request is wrong. */ { notDataFace: { service: string } } + | /** The service is a data face a route resolves, but this operation of it is not: its call needs a cancellation or a cleanup the routed call cannot carry, so only a direct call keeps its lifetime behaviour. */ { methodNotRoutable: { service: string; method: string } } + | /** The name is a data face, but not of the scope the route reaches. */ { wrongScope: { service: string; group: string } } + | /** The owner's own failure, with the name, the code it reported and the message it wrote; routing does not restate them. `reloading` is that code's "try again later", so a caller retries exactly what the owner says it may retry. */ { owner: { name: string; code?: string | null; message: string; data?: import('./plugin.js').BridgeJsonValue | null; reloading: boolean } } + + +/** + * One Session's own lines and data faces, provided to the Session's parts and + * their runtimes as the Session name `sessionScope`. + * + * It holds its Session and no other: a part of a Session reaches its own + * Session's lines only. `describe` joins it with base-3. + */ +export interface SessionScope { + /** + * Calls one of this Session's own data faces. + * @throws {RouteErrorThrown} + */ + call(call: SessionCall): Promise + /** + * Calls one of this Session's lines' data faces. + * @throws {RouteErrorThrown} + */ + lineCall(call: LineCall): Promise +} + export type SessionInstanceDefinition = { group: string definitionId: string @@ -1439,6 +1473,15 @@ export type PermissionState = { /** A Session service failure; generated exports throw this serde value. */ export type SessionsError = | { code: "rejected"; message: string } + | /** A routed call could not select its target. These are the same codes a Session's own scope answers: `no_session`, `session_closing`, `session_reloading` (retryable), `session_unavailable`, `no_line`, `not_data_face`, `method_not_routable` and `wrong_scope`. */ { code: "no_session"; message: string } + | { code: "session_closing"; message: string } + | { code: "session_reloading"; message: string } + | /** The Session exists but cannot load; `reason` says why. */ { code: "session_unavailable"; message: string; reason: string } + | /** The line is not the Session's, or it is gone; `line` names it. */ { code: "no_line"; message: string; line: string } + | { code: "not_data_face"; message: string; service: string } + | { code: "method_not_routable"; message: string; service: string; method: string } + | { code: "wrong_scope"; message: string; service: string; group: string } + | /** The target owner's own failure, with the name and message it wrote and whether the owner says it may be retried. */ { code: "routed"; name: string; owner_code?: string | null; message: string; data?: import('./plugin.js').BridgeJsonValue | null; retryable: boolean } | { code: "agent_unknown"; message: string } | { code: "session_closed"; message: string } | { code: "branch_missing"; message: string } @@ -1772,11 +1815,14 @@ export type ReservedMethodsErrorThrown = RustError<"ReservedMethodsError", "rese /** What a method returning `Err(ResourceError)` throws. */ export type ResourceErrorThrown = RustError<"ResourceError", string, ResourceError> +/** What a method returning `Err(RouteError)` throws. */ +export type RouteErrorThrown = RustError<"RouteError", "noSession" | "sessionClosing" | "sessionReloading" | "sessionUnavailable" | "noLine" | "notDataFace" | "methodNotRoutable" | "wrongScope" | "owner", RouteError> + /** What a method returning `Err(SessionInstanceError)` throws. */ export type SessionInstanceErrorThrown = RustError<"SessionInstanceError", "Create" | "NotReady" | "Cleanup", undefined> /** What a method returning `Err(SessionsError)` throws. */ -export type SessionsErrorThrown = RustError<"SessionsError", "rejected" | "agent_unknown" | "session_closed" | "branch_missing" | "branch_ended" | "reloading" | "future_sequence" | "ambiguous" | "publication_unknown" | "failed", SessionsError> +export type SessionsErrorThrown = RustError<"SessionsError", "rejected" | "no_session" | "session_closing" | "session_reloading" | "session_unavailable" | "no_line" | "not_data_face" | "method_not_routable" | "wrong_scope" | "routed" | "agent_unknown" | "session_closed" | "branch_missing" | "branch_ended" | "reloading" | "future_sequence" | "ambiguous" | "publication_unknown" | "failed", SessionsError> /** What a method returning `Err(TaskError)` throws. */ export type TaskErrorThrown = RustError<"TaskError", "read" | "unknown" | "closed", TaskError> @@ -1820,6 +1866,7 @@ export interface Services { dispatcher: Dispatcher timeline: Timeline partRegistry: PartRegistry + sessionScope: SessionScope sessionLoader: SessionLoader sessionPermissions: SessionPermissions collaborationConfig: CollaborationConfig @@ -1830,3 +1877,75 @@ export interface Services { listenAddresses: ListenAddresses uiResources: UiResources } + +/** The data faces a line reaches. */ +export type LineFaces = { + approval: Approval + backgroundExec: BackgroundExec + branchLine: BranchLine + dispatcher: Omit + inputQueue: InputQueue + permission: Omit + timeline: Timeline + timelineIdentity: TimelineIdentity + wait: Omit +} + +/** The data faces a Session reaches. */ +export type SessionFaces = { + agentConfig: AgentConfig + collaborationConfig: CollaborationConfig + initialPromptConfiguration: InitialPromptConfiguration + mcpSession: McpSession + sessionConfig: SessionConfig + sessionIdentity: SessionIdentity + sessionLanguage: SessionLanguage + sessionLoader: SessionLoader + skillsConfig: SkillsConfig + toolHost: Omit + treeCommands: Omit + uiResources: Omit +} + +/** One call a route resolves: `service` and `method` name a data face and one of its methods, and `args` are that method's parameters. */ +type Call = { + [S in keyof Faces]: { + [M in keyof Faces[S]]: Address & { + service: S + method: M + args: Faces[S][M] extends (...args: infer A) => unknown ? A : never + } + }[keyof Faces[S]] +}[keyof Faces] + +/** A call to one of the caller's own Session's lines. */ +export type LineCall = Call + +/** A call to one of the caller's own Session's data faces. */ +export type SessionCall = Call + +/** A call through Agents: a Session's face, or one of its lines' faces. A Session + * face takes no `lineId`. */ +export type SessionsCall = + | Call + | Call + +/** The reply of one call: the target method's own return type. */ +export type ReplyOf = C extends { service: infer S; method: infer M } + ? S extends keyof (LineFaces & SessionFaces) + ? M extends keyof (LineFaces & SessionFaces)[S] + ? Awaited< + (LineFaces & SessionFaces)[S][M] extends (...args: never[]) => infer R ? R : never + > + : never + : never + : never + +/** What a routed call answers: a method that replies nothing reaches the caller as `null`, while a direct call to it returns `undefined`. */ +export type RoutedReply = ReplyOf extends void ? null : ReplyOf + +/** A Session's own faces, typed per operation: `service` and `method` choose the reply. */ +export interface SessionScope { + call(call: C): Promise> + lineCall(call: C): Promise> +} diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 6ec5b5c954..64df6bdc5b 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -280,7 +280,10 @@ export type WithdrawReply = { status: 'deleted'; sequence: number } | { status: export interface StopRequest extends SessionRef { reason?: string | null } export interface SequenceReply { sequence: number } export type SessionsErrorCode = import('./branch-services.js').SessionsErrorThrown['code']; -export interface SessionsError { code: SessionsErrorCode; message: string; retryable: boolean } +/** The failure a `sessions` call reports: the generated union, so each code carries + * the details the server sends (`reason`, `line`, `service`, `name`, `data`), plus + * the envelope's own `retryable`, which every code answers. */ +export type SessionsError = import('./branch-services.js').SessionsError & { retryable: boolean }; export type SessionsResult = { ok: true; value: T } | { ok: false; error: SessionsError }; /** Process service `sessions`; these methods are not terminal RPC methods. */ @@ -301,6 +304,15 @@ export interface Sessions { stop(request: StopRequest): Promise>; idle(request: SessionRef): Promise>; delete(request: { sessionId: string }): Promise>>; + /** Calls a data face of a live Session, or of one of its lines, by id + * (#2127). Agents loads and holds the Session for the call. A target that + * cannot be selected answers `no_session`, `session_closing`, + * `session_reloading` (retry later), `session_unavailable` (report the + * reason) or `no_line`; the target owner's own failure is `routed` with its + * name and message. */ + call( + request: C, + ): Promise>>; } /** One type an `eventHub` source declares (design A.1). */ diff --git a/runtime/fixtures/branch-calls.ts b/runtime/fixtures/branch-calls.ts new file mode 100644 index 0000000000..05e559a768 --- /dev/null +++ b/runtime/fixtures/branch-calls.ts @@ -0,0 +1,82 @@ +// A plugin of any language calls a Session's or a line's data face by id with +// the two data operations (#2127). The request's `service`, `method` and +// `args` are the target's own, so a typo fails to compile. +import type { Sessions } from '../../npm/plugin.js' +import type { RouteError, SessionScope } from '../../npm/branch-services.js' + +/** Every `sessions` failure carries the envelope's retryability. */ +export function retryable(error: import('../../npm/plugin.js').SessionsError): boolean { + const retryable: boolean = error.retryable + return retryable +} + +/** A Session part reads the owner's structured failure from the routed error. */ +export function ownerFailure(error: RouteError): string | null { + return 'owner' in error ? `${error.owner.name}: ${error.owner.message}` : null +} + +export async function readByCalls( + scope: SessionScope, + sessions: Sessions, + sessionId: string, + inputId: string, +): Promise { + // Each reply is the target method's own type. + const withdrawn = await scope.lineCall({ + lineId: 'main', + service: 'inputQueue', + method: 'withdraw', + args: [{ input_id: inputId }], + }) + const status: string = withdrawn.status + const sequence = await scope.lineCall({ + lineId: 'main', + service: 'timeline', + method: 'sequence', + args: [], + }) + const committed: number | bigint = sequence + const config = await scope.call({ service: 'sessionConfig', method: 'get', args: [] }) + const cwd: string = config.cwd + // A method that replies nothing reaches a routed caller as `null`. + const removed: null = await scope.call({ + service: 'sessionLoader', + method: 'remove', + args: [{ instanceId: 0 }], + }) + void [status, committed, cwd, removed] + + // @ts-expect-error a service the route does not resolve is refused. + void scope.lineCall({ lineId: 'main', service: 'inputQueueX', method: 'withdraw', args: [] }) + // @ts-expect-error a method the service does not have is refused. + void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'submitX', args: [] }) + // @ts-expect-error arguments follow the method's parameters. + void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'withdraw', args: ['wrong'] }) + // @ts-expect-error a Session call reaches a Session face, not a line's. + void scope.call({ service: 'inputQueue', method: 'withdraw', args: [] }) + // @ts-expect-error a reply keeps the target method's own type. + void scope.lineCall({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }).then((reply: string) => reply) + // @ts-expect-error an operation bound to the calling row is direct-only. + void scope.call({ service: 'uiResources', method: 'publishFile', args: [{}] }) + // @ts-expect-error a subscription an operation hands the caller is not routed. + void scope.lineCall({ lineId: 'main', service: 'dispatcher', method: 'listen', args: ['n', [], (_e: unknown) => {}] }) + // @ts-expect-error an operation that needs a caller-side cancellation is not routed. + void scope.lineCall({ lineId: 'main', service: 'wait', method: 'wait', args: [] }) + // @ts-expect-error a Session service takes no lineId. + void sessions.call({ sessionId, lineId: 'main', service: 'sessionConfig', method: 'get', args: [] }) + // @ts-expect-error a line call takes no Session id. + void sessions.call({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }) + // @ts-expect-error `lineCall` takes no `sessionId`: it reaches its own Session only. + void scope.lineCall({ sessionId, lineId: 'main', service: 'timeline', method: 'sequence', args: [] }) + // @ts-expect-error `SessionScope.call` takes neither `lineId` nor `sessionId`. + void scope.call({ sessionId, lineId: 'main', service: 'sessionConfig', method: 'get', args: [] }) + + await sessions.call({ + sessionId, + lineId: 'main', + service: 'inputQueue', + method: 'withdraw', + args: [{ input_id: inputId }], + }) + await sessions.call({ sessionId, service: 'sessionConfig', method: 'get', args: [] }) +} diff --git a/runtime/plugin-sdk.test.mjs b/runtime/plugin-sdk.test.mjs index 8c9303a163..e41764ad34 100644 --- a/runtime/plugin-sdk.test.mjs +++ b/runtime/plugin-sdk.test.mjs @@ -53,6 +53,10 @@ test('packed plugin service types compile the author guide and enforce the publi .replace("'./part-row.ts'", "'./part-row.mjs'")); return file; }); + const routed = path.join(directory, 'branch-calls.mts'); + writeFileSync(routed, readFileSync(path.join(root, 'runtime/fixtures/branch-calls.ts'), 'utf8') + .replaceAll("'../../npm/branch-services.js'", "'dimcode/branch-services.js'") + .replaceAll("'../../npm/plugin.js'", "'dimcode/plugin'")); const calls = path.join(directory, 'calls.mts'); writeFileSync(calls, ` import type { Settings, SettingsResult, Sessions, WorkflowFiles, WorkflowFileEntry, WorkflowFilesErrorThrown, SessionPermissions, PermissionState, PermissionPolicy, SessionsErrorThrown, SessionMetadata, SessionMetadataResult, AuxiliaryModel, AuxiliaryReply, FileScope, FileResult, ToolRegistry, ToolExecute, ToolResult, SessionMethods, SessionMethodHandler, ManagementMethods, MethodHandler, MethodDeclaration, SessionConfig, SessionBroadcast, BranchEvent, Services, AgentErrorThrown, MethodReply, CallChannel, CallChannelError, EventHub, EventHubDeclaration, EventHubDelivery, EventHubErrorThrown, EventHubPublishReply } from 'dimcode/plugin'; @@ -133,7 +137,7 @@ const preset: 'read-only' | 'workspace-write' | 'full-access' = defaults.preset; const allowed: string[] = livePolicy.allowedTools; const disallowed: string[] = defaults.disallowedTools; declare const permissionError: SessionsErrorThrown; -const permissionCode: 'rejected' | 'agent_unknown' | 'session_closed' | 'branch_missing' | 'branch_ended' | 'reloading' | 'future_sequence' | 'ambiguous' | 'publication_unknown' | 'failed' = permissionError.code; +const permissionCode: 'rejected' | 'routed' | 'no_session' | 'session_closing' | 'session_reloading' | 'session_unavailable' | 'no_line' | 'not_data_face' | 'method_not_routable' | 'wrong_scope' | 'agent_unknown' | 'session_closed' | 'branch_missing' | 'branch_ended' | 'reloading' | 'future_sequence' | 'ambiguous' | 'publication_unknown' | 'failed' = permissionError.code; void permissionVersion; void preset; void allowed; void disallowed; void permissionCode; // @ts-expect-error permission reads require a branch identity. void permissions.permission({ sessionId: 'session' }); @@ -370,6 +374,6 @@ void panel; assert.equal(declarations.status, 0, declarations.stdout + declarations.stderr); const checked = spawnSync(process.execPath, [compiler, '--strict', '--noEmit', '--target', 'ES2022', '--module', 'NodeNext', '--moduleResolution', 'NodeNext', - ...files, ...promptFixtures, calls, branchFixture, partRow, permissionsFixture, workflowFixture, eventHubFixture, uiFixture], { encoding: 'utf8' }); + ...files, ...promptFixtures, routed, calls, branchFixture, partRow, permissionsFixture, workflowFixture, eventHubFixture, uiFixture], { encoding: 'utf8' }); assert.equal(checked.status, 0, checked.stdout + checked.stderr); }); diff --git a/xtask/access-layer.json b/xtask/access-layer.json new file mode 100644 index 0000000000..c397d34865 --- /dev/null +++ b/xtask/access-layer.json @@ -0,0 +1,870 @@ +{ + "allow": [ + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/approval.rs", + "item": "Approval::admit" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/approval.rs", + "item": "Approval::replay" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/approval.rs", + "item": "Approval::respond" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/auxiliary_model.rs", + "item": "AuxiliaryModel" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/execution_settings.rs", + "item": "ExecutionSettingsHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/file_storage/face.rs", + "item": "FsHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/host.rs", + "item": "ModelSelectionHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/host.rs", + "item": "PromptHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/host.rs", + "item": "SelectableModelsHost" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host.rs", + "item": "ToolHost::0" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::arch" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::build_process_spec" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::child_path_process" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::command_shutdown" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::command_workers" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::commands" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::configured" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::env" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::execution" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::home" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::installed_toolchains" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::os" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::platform_roots" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::prepare_isolated_process" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::remove_exec_directory" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::retained_output_page" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::spawn_pty" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::spawn_tree" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::spawn_with_stdin_process" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::start_shell" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::timezone" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::toolchain" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::with_execution_settings" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::with_toolchain_source" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform/confined.rs", + "item": "HostPlatform::spawn_confined_process" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform/exec_shell_settings.rs", + "item": "HostPlatform::read_exec_shell_settings" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform/exec_shell_settings.rs", + "item": "HostPlatform::update_exec_shell_settings" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform/isolation.rs", + "item": "HostPlatform::prepare_isolated_process" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/input_queue.rs", + "item": "InputQueue::pending" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/input_queue.rs", + "item": "InputQueue::withdraw_checked" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/input_queue/face.rs", + "item": "SubmitChecks" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/methods.rs", + "item": "ForeignMethods" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/methods.rs", + "item": "ReservedMethods::check_type" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "CommandRules" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "Permission::admit_decision" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "Permission::decide" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "Permission::register_advice" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "Permission::update" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/prompt.rs", + "item": "InitialPromptConfiguration::fixed" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/prompt.rs", + "item": "InitialPromptConfiguration::read" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/prompt_guide.rs", + "item": "ForeignGuideEntries" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/prompt_registry.rs", + "item": "PromptRegistry" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/prompt_sources.rs", + "item": "BasePromptSettingsHost" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/prompt_sources.rs", + "item": "SessionLanguage::gate" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/prompt_sources.rs", + "item": "SessionLanguage::replace" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/prompt_suggestion.rs", + "item": "PromptSuggestionSettingsHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/session_files.rs", + "item": "SessionFiles" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/skills/face.rs", + "item": "SkillsCatalog" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/skills/mod.rs", + "item": "SkillsConfig::instructions" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/skills/mod.rs", + "item": "SkillsInstructionsSettingsHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/skills/session.rs", + "item": "SkillsBranch" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/summary_strategy.rs", + "item": "SummaryPromptSettingsHost" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::activity_after" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::batch_end" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::branch" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::default_from" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::default_moves" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::end_with_final" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::get" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::head" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::inputs" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::next_move" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::page_end" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::turn_ends" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/timeline_tree/read.rs", + "item": "TreeCommands::adopted_configuration" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/timeline_tree/read.rs", + "item": "TreeCommands::display" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/timeline_tree/read.rs", + "item": "TreeCommands::end_committed" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/tool_registry.rs", + "item": "ForeignRegistry" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/tool_registry.rs", + "item": "ToolSourcesView" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/toolchain.rs", + "item": "ToolchainSourceHost" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/wait.rs", + "item": "Wait::subscription" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/workspace_tools/background.rs", + "item": "BackgroundExec::start" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/workspace_tools/exec.rs", + "item": "HostPlatform::command_task" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/workspace_tools/exec.rs", + "item": "HostPlatform::retain_output_by_id" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/workspace_tools/exec.rs", + "item": "HostPlatform::start_command" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/workspace_tools/exec.rs", + "item": "HostPlatform::tail_by_id" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::batch_end" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::branch_diagnostics" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::configure" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::dispatch_watch" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::end_branch" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::ended_head" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::get" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::idle" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::input" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::input_commit" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::inputs" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::interrupt" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::lookup" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::on" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::publication" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::query" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::sequence" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::service" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::service_opt" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::set_default_branch" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::state" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::stop" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::submit" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::watch" + }, + { + "kind": "branch-type", + "file": "crates/dim-agent-runtime/src/branch.rs", + "item": "Branch" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "BranchLifecycle::admit_opening" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "BranchLifecycle::admit_opening_with" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "BranchLifecycle::finish_opening" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "BranchLifecycle::opening_budget" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "BranchLifecycle::phase" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "BranchLifecycle::watch" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "SessionConfig::exclude_codemode_below" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "SessionLifecycle::faults" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "SessionLifecycle::phase" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "SessionLifecycle::report_native_fault" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "SessionLifecycle::take_hold" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/dispatcher.rs", + "item": "Dispatcher::fail" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/dispatcher.rs", + "item": "Dispatcher::failure" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/dispatcher.rs", + "item": "Dispatcher::subscribe" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/dispatcher.rs", + "item": "Dispatcher::subscribe_all" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/dispatcher.rs", + "item": "Dispatcher::watch" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::append_batch_registered" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::append_registered" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::append_with_create_at" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::batch_end" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::batch_end_at" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::before" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::bound" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::checkpoint" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::failure" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::restore" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::resume_position" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::save_snapshot" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::segments" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::watch" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-runtime/src/parts.rs", + "item": "PartRegistry::register" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-runtime/src/timeline_store_face.rs", + "item": "TimelineStoreBinding" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-scheduler/src/loops.rs", + "item": "LoopsFace" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-scheduler/src/methods.rs", + "item": "ScheduleJobsFace" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-scheduler/src/wakeups.rs", + "item": "WakeupsFace" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-app-server/src/agents/sessions.rs", + "item": "SessionPermissions::0" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/agents/sessions.rs", + "item": "SessionsService" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-app-server/src/collaboration.rs", + "item": "CollaborationConfig::leader_description" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-app-server/src/collaboration.rs", + "item": "CollaborationConfig::member_description" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-app-server/src/collaboration.rs", + "item": "CollaborationDirectory::record" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/collaboration/approvals.rs", + "item": "CollaborationSession" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/connection.rs", + "item": "ForeignCallChannel" + }, + { + "kind": "service-skip", + "file": "crates/dim-app-server/src/control.rs", + "item": "ProcessActivity::pause" + }, + { + "kind": "service-skip", + "file": "crates/dim-app-server/src/control.rs", + "item": "ProcessActivity::take_hold" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/hooks_settings.rs", + "item": "HooksService" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/lib.rs", + "item": "LocalIdDispatch" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/managed_provider.rs", + "item": "ManagedSearch" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/mcp/face.rs", + "item": "McpService" + }, + { + "kind": "service-skip", + "file": "crates/dim-app-server/src/mcp/session.rs", + "item": "McpSession::subscribe" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/plugin_files.rs", + "item": "PluginFiles" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/settings/declared.rs", + "item": "Settings" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/storage/face.rs", + "item": "Store" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/storage/metadata.rs", + "item": "SessionMetadata" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/storage/sqlite.rs", + "item": "SqliteDispatch" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-app-server/src/transport.rs", + "item": "ListenAddresses::pipe_name" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-app-server/src/transport.rs", + "item": "ListenAddresses::unix_path" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-app-server/src/transport.rs", + "item": "ListenAddresses::websocket_address" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-app-server/src/ui_extensions/resources.rs", + "item": "UiResources::read" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-event-hub/src/bridge.rs", + "item": "ForeignEventHub" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-event-hub/src/bridge.rs", + "item": "ForeignEventSubscriptions" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-modality/src/targets.rs", + "item": "ModalityTargets" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-oauth/src/session_title.rs", + "item": "DimOAuth" + } + ], + "removed": [] +} diff --git a/xtask/check/Cargo.toml b/xtask/check/Cargo.toml index 0846b22c95..d90d2dfa88 100644 --- a/xtask/check/Cargo.toml +++ b/xtask/check/Cargo.toml @@ -9,6 +9,7 @@ publish = false [dependencies] proc-macro2 = { version = "1", features = ["span-locations"] } rutis-types = "0.23.0" +serde.workspace = true serde_json.workspace = true syn = { version = "2", features = ["full", "visit"] } diff --git a/xtask/check/src/access.rs b/xtask/check/src/access.rs new file mode 100644 index 0000000000..0bdac984b9 --- /dev/null +++ b/xtask/check/src/access.rs @@ -0,0 +1,414 @@ +//! The access-layer rules of [#2015 §5](https://github.com/arcships/dim/issues/2015) +//! and the list that admits the violations still in the tree. +//! +//! A violation is one of: +//! +//! - `#[service(skip)]` on a method of a `#[rutis::service]` block; +//! - a method of a service type that takes `self` and is `pub` or +//! `pub(crate)`, written outside its `#[rutis::service]` blocks, or such a +//! field of a service type: Rust callers can use what other languages cannot, +//! which is what `#[service(skip)]` does. A constructor takes no `self` and +//! is not one of these, and a type that serializes has fields of data, the +//! payload a face carries, so its fields are not either; +//! - a hand-written `HostDispatch` implementation; +//! - a `Session` method that takes a line's name, the forwarding shape the +//! refactor removes. It reads the parameter's name (heuristic: the tree's +//! forwarding methods name it `branch`), so a method that takes a line under +//! another name is not found; +//! - the outward `Branch` type. +//! +//! The scan reads the product sources (`crates/*/src`) only: a test fixture is +//! not a public face. +//! +//! The allowlist (`xtask/access-layer.json`) names every violation the tree +//! still has. `check` fails when a violation is not listed, and when a listed +//! entry matches fewer occurrences than it is listed for; it cannot see a +//! violation that arrives together with its own entry. Keeping the list from +//! growing is a review rule: a change deletes the entries for what it removes +//! and adds none, so the list empties when the refactor ends. The same file's +//! `removed` list names catalog services a change deleted; the runtime catalog +//! check in `xtask` fails when one comes back. +use serde::{Deserialize, Serialize}; +use std::{ + collections::{BTreeMap, BTreeSet}, + path::{Path, PathBuf}, +}; + +type Result = std::result::Result>; + +/// The file holding the allowlist and the removed names, from the workspace +/// root. +pub const FILE: &str = "xtask/access-layer.json"; + +/// What kind of access-layer violation a rule names. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Kind { + /// A service method kept out of the face with `#[service(skip)]`. + ServiceSkip, + /// A `pub`/`pub(crate)` method that takes `self` on a service type, + /// outside its `#[rutis::service]` blocks. + RustOnlyMethod, + /// A `pub`/`pub(crate)` field of a service type. + RustOnlyField, + /// A `HostDispatch` implementation written by hand instead of a + /// `#[rutis::service]` block. + HostDispatch, + /// A `Session` method that forwards to a line named by an argument. + SessionForwarding, + /// The outward `Branch` type. + BranchType, +} + +/// One violation, identified by what it is and where it lives, not by line +/// numbers. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Rule { + pub kind: Kind, + /// The source file, from the workspace root. + pub file: String, + /// The item: `Type::method` for a method or field, the type for a type. + pub item: String, +} + +impl std::fmt::Display for Rule { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}: {} is {}", + self.file, + self.item, + kind_name(self.kind) + ) + } +} + +fn kind_name(kind: Kind) -> &'static str { + match kind { + Kind::ServiceSkip => "skipped with #[service(skip)]", + Kind::RustOnlyMethod => "a Rust-only method", + Kind::RustOnlyField => "a Rust-only field", + Kind::HostDispatch => "a hand-written HostDispatch", + Kind::SessionForwarding => "a Session method taking a line name", + Kind::BranchType => "the outward Branch type", + } +} + +/// The allowlist and the removed names. +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct AccessLayer { + /// Violations the tree still has, one entry per occurrence. + #[serde(default)] + pub allow: Vec, + /// Catalog services a change deleted. Empty until the first face goes. + #[serde(default)] + pub removed: Vec, +} + +/// Reads the file at `root`; a missing file admits nothing. +pub fn load(root: &Path) -> Result { + let path = root.join(FILE); + match std::fs::read_to_string(&path) { + Ok(text) => { + Ok(serde_json::from_str(&text) + .map_err(|error| format!("{}: {error}", path.display()))?) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(AccessLayer::default()), + Err(error) => Err(format!("{}: {error}", path.display()).into()), + } +} + +/// Fails when a violation is not allowed, or an entry matches fewer +/// occurrences than it is listed for. +pub fn check(root: &Path) -> Result<()> { + let mut found: BTreeMap = BTreeMap::new(); + for rule in violations(root)? { + *found.entry(rule).or_default() += 1; + } + let mut allowed: BTreeMap = BTreeMap::new(); + for rule in load(root)?.allow { + *allowed.entry(rule).or_default() += 1; + } + let mut problems = String::new(); + for (rule, count) in &found { + let listed = allowed.get(rule).copied().unwrap_or(0); + if listed < *count { + problems += &format!( + "{} ({count} found, {listed} listed)\n", + serde_json::to_string(rule).expect("a rule is JSON") + ); + } + } + if !problems.is_empty() { + return Err(format!( + "access-layer violations are not in {FILE}; the list may only shrink:\n{problems}" + ) + .into()); + } + let mut stale = String::new(); + for (rule, listed) in &allowed { + let count = found.get(rule).copied().unwrap_or(0); + if count < *listed { + stale += &format!("{rule} (listed {listed}, {count} found)\n"); + } + } + if !stale.is_empty() { + return Err(format!( + "entries of {FILE} match fewer occurrences and must be deleted:\n{stale}" + ) + .into()); + } + println!( + "access layer passed ({} allowed)", + allowed.values().sum::() + ); + Ok(()) +} + +/// Every violation in the product sources under `root`. +pub fn violations(root: &Path) -> Result> { + let mut parsed = Vec::new(); + for file in sources(root)? { + let text = std::fs::read_to_string(&file)?; + let ast = syn::parse_file(&text).map_err(|error| format!("{}: {error}", file.display()))?; + let relative = file + .strip_prefix(root) + .unwrap_or(&file) + .to_string_lossy() + .replace('\\', "/"); + parsed.push((relative, ast)); + } + let mut services = BTreeSet::new(); + for (file, ast) in &parsed { + service_types(crate_name(file), &ast.items, &mut services); + } + let mut found = Vec::new(); + for (file, ast) in &parsed { + scan(&ast.items, file, crate_name(file), &services, &mut found); + } + found.sort(); + Ok(found) +} + +/// The types that have a `#[rutis::service]` block, by crate: what they offer +/// other languages is that block, and nothing else. +fn service_types(crate_name: &str, items: &[syn::Item], services: &mut BTreeSet<(String, String)>) { + for item in items { + match item { + syn::Item::Impl(block) if block.attrs.iter().any(is_service_attribute) => { + services.insert((crate_name.to_owned(), type_name(&block.self_ty))); + } + syn::Item::Mod(module) => { + if let Some((_, items)) = &module.content { + service_types(crate_name, items, services); + } + } + _ => {} + } + } +} + +/// The product source files: every `.rs` under `crates/*/src`. +fn sources(root: &Path) -> Result> { + let mut files = Vec::new(); + let crates = root.join("crates"); + for entry in std::fs::read_dir(&crates)? { + let directory = entry?.path().join("src"); + if directory.is_dir() { + collect(&directory, &mut files)?; + } + } + files.sort(); + Ok(files) +} + +fn collect(directory: &Path, files: &mut Vec) -> Result<()> { + for entry in std::fs::read_dir(directory)? { + let path = entry?.path(); + if path.is_dir() { + collect(&path, files)?; + } else if path.extension().is_some_and(|extension| extension == "rs") { + files.push(path); + } + } + Ok(()) +} + +fn scan( + items: &[syn::Item], + file: &str, + crate_name: &str, + services: &BTreeSet<(String, String)>, + found: &mut Vec, +) { + let declared = |ty: &str| services.contains(&(crate_name.to_owned(), ty.to_owned())); + let rule = |kind, item: String| Rule { + kind, + file: file.to_owned(), + item, + }; + for item in items { + match item { + syn::Item::Mod(module) => { + if let Some((_, items)) = &module.content { + scan(items, file, crate_name, services, found); + } + } + syn::Item::Struct(structure) + if declared(&structure.ident.to_string()) && !serializes(&structure.attrs) => + { + for (index, field) in structure.fields.iter().enumerate() { + if !outward(&field.vis) { + continue; + } + let name = match &field.ident { + Some(ident) => ident.to_string(), + None => index.to_string(), + }; + found.push(rule( + Kind::RustOnlyField, + format!("{}::{name}", structure.ident), + )); + } + } + syn::Item::Impl(block) => { + let ty = type_name(&block.self_ty); + let service = block.attrs.iter().any(is_service_attribute); + for method in &block.items { + let syn::ImplItem::Fn(method) = method else { + continue; + }; + if service { + if method + .attrs + .iter() + .any(|attr| is_service_attribute(attr) && skips(attr)) + { + found.push(rule( + Kind::ServiceSkip, + format!("{ty}::{}", method.sig.ident), + )); + } + } else if declared(&ty) + && outward(&method.vis) + && method.sig.receiver().is_some() + { + found.push(rule( + Kind::RustOnlyMethod, + format!("{ty}::{}", method.sig.ident), + )); + } + } + if block + .trait_ + .as_ref() + .and_then(|(_, path, _)| path.segments.last()) + .is_some_and(|segment| segment.ident == "HostDispatch") + { + found.push(rule(Kind::HostDispatch, ty.clone())); + } + if block.trait_.is_none() && ty == "Session" { + for method in &block.items { + let syn::ImplItem::Fn(method) = method else { + continue; + }; + let named_line = method.sig.inputs.iter().any(|input| { + matches!(input, syn::FnArg::Typed(typed) + if matches!(&*typed.pat, syn::Pat::Ident(ident) if ident.ident == "branch")) + }); + if named_line { + found.push(rule( + Kind::SessionForwarding, + format!("Session::{}", method.sig.ident), + )); + } + } + } + } + syn::Item::Struct(item) + if matches!(item.vis, syn::Visibility::Public(_)) && item.ident == "Branch" => + { + found.push(rule(Kind::BranchType, "Branch".into())); + } + syn::Item::Enum(item) + if matches!(item.vis, syn::Visibility::Public(_)) && item.ident == "Branch" => + { + found.push(rule(Kind::BranchType, "Branch".into())); + } + _ => {} + } + } +} + +/// The crate a product source file belongs to, as its directory name. +fn crate_name(file: &str) -> &str { + file.strip_prefix("crates/") + .and_then(|rest| rest.split_once('/')) + .map(|(name, _)| name) + .unwrap_or(file) +} + +/// Whether a type serializes: its fields are the data a face carries, which +/// other languages read and write, not state a caller reaches around the face. +fn serializes(attrs: &[syn::Attribute]) -> bool { + attrs.iter().any(|attr| { + attr.path().is_ident("derive") + && attr + .parse_args_with( + syn::punctuated::Punctuated::::parse_terminated, + ) + .is_ok_and(|derives| { + derives.iter().any(|derive| { + derive + .segments + .last() + .is_some_and(|segment| segment.ident == "Serialize") + }) + }) + }) +} + +/// Whether a visibility lets a caller in another module of this crate use the +/// item: `pub` or `pub(crate)`. +fn outward(visibility: &syn::Visibility) -> bool { + match visibility { + syn::Visibility::Public(_) => true, + syn::Visibility::Restricted(restricted) => restricted.path.is_ident("crate"), + syn::Visibility::Inherited => false, + } +} + +/// `#[service]`, `#[service(skip)]` or their `rutis::` spellings. +fn is_service_attribute(attr: &syn::Attribute) -> bool { + path_is_service(attr.path()) +} + +fn path_is_service(path: &syn::Path) -> bool { + let segments: Vec = path + .segments + .iter() + .map(|segment| segment.ident.to_string()) + .collect(); + matches!(segments.as_slice(), [service] if service == "service") + || matches!(segments.as_slice(), [root, service] if root == "rutis" && service == "service") +} + +fn skips(attr: &syn::Attribute) -> bool { + attr.parse_args::() + .is_ok_and(|argument| argument == "skip") +} + +/// The last path segment of a type, `Branch` for `crate::Branch`. +fn type_name(ty: &syn::Type) -> String { + match ty { + syn::Type::Path(path) => path + .path + .segments + .last() + .map(|segment| segment.ident.to_string()) + .unwrap_or_default(), + _ => String::new(), + } +} diff --git a/xtask/check/src/lib.rs b/xtask/check/src/lib.rs index b04654883b..79cdbd0d3b 100644 --- a/xtask/check/src/lib.rs +++ b/xtask/check/src/lib.rs @@ -1,6 +1,7 @@ //! Pure static repository checks with no dependency on compiling business //! runtime crates (ADR 026 D2, D4). +pub mod access; pub mod boundaries; pub mod comment_links; pub mod i18n; @@ -27,6 +28,7 @@ pub fn root() -> PathBuf { /// Runs every pure static repository check against `root`. pub fn check_all(root: &Path) -> Result<()> { boundaries::check(root)?; + access::check(root)?; types::check(root)?; npm::check(root)?; plugin_skills::check(root)?; diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index f1288fc925..16e352e0b8 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -1,6 +1,9 @@ //! `types` writes the TypeScript declarations of the services marked //! `#[rutis::service]` that `dim-app-server` serves (rutis usage §3.4) to -//! `npm/branch-services.d.ts`; `check` fails when that file is stale. +//! `npm/branch-services.d.ts`, and the addresses a plugin of any language uses +//! to call a Session's or a line's data face by id +//! ([#2127](https://github.com/arcships/dim/issues/2127)); `check` fails when +//! that file is stale. use std::path::{Path, PathBuf}; type Result = std::result::Result>; @@ -9,8 +12,756 @@ fn file(root: &Path) -> PathBuf { root.join("npm/branch-services.d.ts") } +/// The two data operations' requests, narrowed to what a route resolves: the +/// `service` is a data face of the target scope, `method` one of its methods, +/// and `args` the method's parameters, so a typo fails `tsc` +/// ([#2127](https://github.com/arcships/dim/issues/2127)). +fn calls(root: &Path, services: &str) -> Result { + let unroutable = unroutable(root)?; + let declared: Vec<&str> = services + .lines() + .filter_map(|line| { + line.strip_prefix("export interface ") + .or_else(|| line.strip_prefix("export type ")) + .and_then(|rest| rest.split([' ', '<', '{', '=']).next()) + }) + .collect(); + let mut session = Vec::new(); + let mut line = Vec::new(); + for (name, group) in registered(root)? { + // The Session's own scope resolves a line and the Session's faces; it + // is not one of the faces a routed call resolves. + if unroutable.contains(&name) || name == "sessionScope" { + continue; + } + let Some(ty) = declared.iter().find(|ty| catalog_name(ty) == name).copied() else { + continue; + }; + match group.as_str() { + "session" => session.push((name, ty.to_owned())), + "branch" => line.push((name, ty.to_owned())), + _ => {} + } + } + session.sort(); + session.dedup(); + line.sort(); + line.dedup(); + let refused = lifecycle(root)?; + // The list and the signatures must name the same operations: a signature + // that cannot cross languages but is missing fails, and so does a listed + // operation whose signature can. + let groups = registered(root)?; + let derived: Vec<(String, String)> = derived_lifecycle(root)? + .into_iter() + // Only a service a route resolves, and only an operation the file + // declares, is part of that surface. + .filter(|(service, method)| { + // Only a Session or branch face crosses through a route at all. + let in_scope = groups + .iter() + .any(|(name, group)| name == service && (group == "session" || group == "branch")); + in_scope + && !unroutable.contains(service) + && service != "sessionScope" + && declares_method(services, service, method) + }) + .collect(); + let missing: Vec = derived + .iter() + .filter(|pair| !refused.contains(pair)) + .map(|(service, method)| format!("{service}.{method}")) + .collect(); + let extra: Vec = refused + .iter() + .filter(|pair| !derived.contains(pair)) + .map(|(service, method)| format!("{service}.{method}")) + .collect(); + if !missing.is_empty() || !extra.is_empty() { + return Err(format!( + "crates/dim-agent-runtime/src/route.rs: LIFECYCLE_METHODS does not match the service signatures; not listed: [{}], listed but routable: [{}]", + missing.join(", "), + extra.join(", ") + ) + .into()); + } + let faces = |items: &[(String, String)], name: &str| { + let mut text = format!("export type {name} = {{\n"); + for (member, ty) in items { + let omitted: Vec = refused + .iter() + .filter(|(service, _)| service == member) + .map(|(_, method)| format!("'{method}'")) + .collect(); + if omitted.is_empty() { + text += &format!(" {member}: {ty}\n"); + } else { + text += &format!(" {member}: Omit<{ty}, {}>\n", omitted.join(" | ")); + } + } + text + "}\n" + }; + let mut text = String::from("/** The data faces a line reaches. */\n"); + text += &faces(&line, "LineFaces"); + text += "\n/** The data faces a Session reaches. */\n"; + text += &faces(&session, "SessionFaces"); + text += "\n/** One call a route resolves: `service` and `method` name a data face and one of its methods, and `args` are that method's parameters. */\ntype Call = {\n [S in keyof Faces]: {\n [M in keyof Faces[S]]: Address & {\n service: S\n method: M\n args: Faces[S][M] extends (...args: infer A) => unknown ? A : never\n }\n }[keyof Faces[S]]\n}[keyof Faces]\n"; + text += "\n/** A call to one of the caller's own Session's lines. */\nexport type LineCall = Call\n"; + text += "\n/** A call to one of the caller's own Session's data faces. */\nexport type SessionCall = Call\n"; + text += "\n/** A call through Agents: a Session's face, or one of its lines' faces. A Session\n * face takes no `lineId`. */\nexport type SessionsCall =\n | Call\n | Call\n"; + text += "\n/** The reply of one call: the target method's own return type. */\nexport type ReplyOf = C extends { service: infer S; method: infer M }\n ? S extends keyof (LineFaces & SessionFaces)\n ? M extends keyof (LineFaces & SessionFaces)[S]\n ? Awaited<\n (LineFaces & SessionFaces)[S][M] extends (...args: never[]) => infer R ? R : never\n >\n : never\n : never\n : never\n"; + text += "\n/** What a routed call answers: a method that replies nothing reaches the caller as `null`, while a direct call to it returns `undefined`. */\nexport type RoutedReply = ReplyOf extends void ? null : ReplyOf\n"; + text += "\n/** A Session's own faces, typed per operation: `service` and `method` choose the reply. */\nexport interface SessionScope {\n call(call: C): Promise>\n lineCall(call: C): Promise>\n}\n"; + Ok(text) +} + +/// The catalog name and group of every service the workspaces' crates +/// register, read from the registration calls themselves: a name is in a group +/// because some `register`/`register_shared_instance` call puts it there. +fn registered(root: &Path) -> Result> { + let mut found = Vec::new(); + for entry in std::fs::read_dir(root.join("crates"))? { + let directory = entry?.path().join("src"); + if !directory.is_dir() { + continue; + } + let mut files = Vec::new(); + sources(&mut files, &directory)?; + for file in files { + let text = std::fs::read_to_string(&file)?; + let ast = syn::parse_file(&text)?; + registrations(&ast.items, &mut found); + } + } + Ok(found) +} + +fn sources(files: &mut Vec, directory: &Path) -> Result<()> { + for entry in std::fs::read_dir(directory)? { + let path = entry?.path(); + if path.is_dir() { + sources(files, &path)?; + } else if path.extension().is_some_and(|extension| extension == "rs") { + files.push(path); + } + } + Ok(()) +} + +fn registrations(items: &[syn::Item], found: &mut Vec<(String, String)>) { + for item in items { + match item { + syn::Item::Mod(module) => { + if let Some((_, items)) = &module.content { + registrations(items, found); + } + } + syn::Item::Impl(block) => { + for item in &block.items { + if let syn::ImplItem::Fn(function) = item { + expressions(&function.block, found); + } + } + } + syn::Item::Fn(function) => expressions(&function.block, found), + _ => {} + } + } +} + +fn expressions(block: &syn::Block, found: &mut Vec<(String, String)>) { + for statement in &block.stmts { + match statement { + syn::Stmt::Expr(expression, _) => call(expression, found), + syn::Stmt::Local(local) => { + if let Some(init) = &local.init { + call(&init.expr, found); + } + } + _ => {} + } + } +} + +/// One `register`/`register_shared_instance` call, with the group its +/// arguments name. +fn call(expression: &syn::Expr, found: &mut Vec<(String, String)>) { + if let syn::Expr::MethodCall(method) = expression { + if method.method == "register_shared_instance" { + let mut args = method.args.iter(); + let Some(name) = args.next().and_then(name_of) else { + return; + }; + let Some(group) = args.next().and_then(group_of) else { + return; + }; + found.push((name, group.to_owned())); + } + return; + } + let syn::Expr::Call(call) = expression else { + return; + }; + let syn::Expr::Path(path) = &*call.func else { + return; + }; + let Some(last) = path.path.segments.last() else { + return; + }; + match last.ident.to_string().as_str() { + "register" | "register_instance" | "register_keyed" => { + let Some(group) = call.args.iter().find_map(group_of) else { + return; + }; + if let Some(ty) = type_argument(&last.arguments) { + found.push((catalog_name(&ty), group.to_owned())); + } + } + "register_shared_instance" => { + let mut args = call.args.iter(); + let Some(name) = args.next().and_then(name_of) else { + return; + }; + let Some(group) = args.next().and_then(group_of) else { + return; + }; + found.push((name, group.to_owned())); + } + _ => {} + } +} + +/// The role a group argument names: `session`, `branch`, or their constants. +fn group_of(expression: &syn::Expr) -> Option<&'static str> { + match expression { + syn::Expr::Path(path) => { + let ident = path.path.segments.last()?.ident.to_string(); + match ident.as_str() { + "session" => Some("session"), + "branch" => Some("branch"), + "SESSION_GROUP" => Some("session"), + "BRANCH_GROUP" => Some("branch"), + _ => None, + } + } + syn::Expr::Call(call) => call.args.iter().find_map(group_of), + syn::Expr::Reference(reference) => group_of(&reference.expr), + _ => None, + } +} + +/// The Rust type a registration is for: `register::`'s argument, or a +/// string name. +fn type_argument(arguments: &syn::PathArguments) -> Option { + Some(catalog_name(&rust_type_argument(arguments)?)) +} + +/// The Rust type a turbofish names, as written. +fn rust_type_argument(arguments: &syn::PathArguments) -> Option { + let syn::PathArguments::AngleBracketed(arguments) = arguments else { + return None; + }; + arguments.args.iter().find_map(|argument| { + let syn::GenericArgument::Type(ty) = argument else { + return None; + }; + Some(match ty { + syn::Type::Path(path) => path.path.segments.last()?.ident.to_string(), + syn::Type::TraitObject(object) => object.bounds.iter().find_map(|bound| { + let syn::TypeParamBound::Trait(bound) = bound else { + return None; + }; + Some(bound.path.segments.last()?.ident.to_string()) + })?, + _ => return None, + }) + }) +} + +/// A name argument as written: `"name"` or `name_of::()`. +fn name_of(expression: &syn::Expr) -> Option { + match expression { + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(name), + .. + }) => Some(name.value()), + syn::Expr::Call(call) => { + let syn::Expr::Path(path) = &*call.func else { + return None; + }; + let last = path.path.segments.last()?; + if last.ident != "name_of" { + return None; + } + type_argument(&last.arguments) + } + syn::Expr::Path(_) => None, + syn::Expr::Reference(reference) => name_of(&reference.expr), + syn::Expr::Macro(mac) => { + let tokens = mac.mac.tokens.to_string(); + tokens.split('<').nth(1).map(|rest| { + catalog_name( + rest.trim_end_matches('>') + .trim() + .rsplit("::") + .next() + .unwrap_or(""), + ) + }) + } + _ => None, + } +} + +/// The operations routing does not resolve, read from the runtime's own list: +/// a call that needs a cancellation or a caller-side cleanup keeps its lifetime +/// only when it is made directly. +fn lifecycle(root: &Path) -> Result> { + let path = root.join("crates/dim-agent-runtime/src/route.rs"); + let ast = syn::parse_file(&std::fs::read_to_string(&path)?)?; + let mut found = Vec::new(); + let mut seen = false; + for item in &ast.items { + let syn::Item::Const(declaration) = item else { + continue; + }; + if declaration.ident != "LIFECYCLE_METHODS" { + continue; + } + let syn::Expr::Array(array) = &*declaration.expr else { + return Err(format!("{}: LIFECYCLE_METHODS is not an array", path.display()).into()); + }; + for element in &array.elems { + let syn::Expr::Tuple(tuple) = element else { + return Err(format!( + "{}: a LIFECYCLE_METHODS entry is not a pair", + path.display() + ) + .into()); + }; + let mut parts = tuple.elems.iter().filter_map(|part| match part { + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(text), + .. + }) => Some(text.value()), + _ => None, + }); + match (parts.next(), parts.next()) { + (Some(service), Some(method)) => found.push((service, method)), + _ => { + return Err(format!( + "{}: a LIFECYCLE_METHODS entry is not a pair of names", + path.display() + ) + .into()); + } + } + } + seen = true; + } + if !seen { + return Err(format!("{}: LIFECYCLE_METHODS is missing", path.display()).into()); + } + Ok(found) +} + +/// The operations a catalog's own method signatures say a routed call cannot +/// carry: a parameter that is the calling row, a cancellation, or a callback. +/// Read from the `#[rutis::service]` blocks themselves, so a new operation of +/// that kind cannot slip past the list the runtime refuses. +/// +/// What it recognizes: a `Ctx` or a reference to one, the `CancelledFn` and +/// `CancellationToken` aliases, and `Fn(..)` as a trait object, behind `Arc`, or +/// as `impl Fn`, and a bare `fn(..)` pointer. What it still misses: any other +/// alias of those types; an operation written that way is a review-time +/// guarantee, and the two-way comparison reports it as a listed operation whose +/// signature looks routable. +fn derived_lifecycle(root: &Path) -> Result> { + let mut found = Vec::new(); + for entry in std::fs::read_dir(root.join("crates"))? { + let directory = entry?.path().join("src"); + if !directory.is_dir() { + continue; + } + let mut files = Vec::new(); + sources(&mut files, &directory)?; + for file in files { + let ast = syn::parse_file(&std::fs::read_to_string(&file)?)?; + service_blocks(&ast.items, &mut found); + } + } + found.sort(); + found.dedup(); + Ok(found) +} + +fn service_blocks(items: &[syn::Item], found: &mut Vec<(String, String)>) { + for item in items { + match item { + syn::Item::Mod(module) => { + if let Some((_, items)) = &module.content { + service_blocks(items, found); + } + } + syn::Item::Impl(block) if block.attrs.iter().any(is_service) => { + let service = type_name(&block.self_ty); + for item in &block.items { + let syn::ImplItem::Fn(function) = item else { + continue; + }; + if function + .attrs + .iter() + .any(|attr| is_service(attr) && skip_argument(attr)) + { + continue; + } + let carried = function.sig.inputs.iter().any(|input| { + let syn::FnArg::Typed(typed) = input else { + return false; + }; + carries_lifecycle(&typed.ty) + }); + if carried { + found.push(( + catalog_name(&service), + camel(&function.sig.ident.to_string()), + )); + } + } + } + _ => {} + } + } +} + +/// Whether a parameter type is one a routed call cannot carry: the calling +/// row, a cancellation, or a callback. +fn carries_lifecycle(ty: &syn::Type) -> bool { + match ty { + syn::Type::Reference(reference) => carries_lifecycle(&reference.elem), + syn::Type::Path(path) => { + let Some(last) = path.path.segments.last() else { + return false; + }; + matches!( + last.ident.to_string().as_str(), + "Ctx" | "CancelledFn" | "CancellationToken" + ) || match &last.arguments { + syn::PathArguments::AngleBracketed(arguments) => { + arguments.args.iter().any(|argument| match argument { + syn::GenericArgument::Type(ty) => carries_lifecycle(ty), + _ => false, + }) + } + _ => false, + } + } + syn::Type::ImplTrait(implemented) => implemented.bounds.iter().any(|bound| { + matches!(bound, syn::TypeParamBound::Trait(bound) + if bound.path.segments.last().is_some_and(|segment| segment.ident == "Fn")) + }), + syn::Type::BareFn(_) => true, + syn::Type::TraitObject(object) => object.bounds.iter().any(|bound| { + matches!(bound, syn::TypeParamBound::Trait(bound) + if bound.path.segments.last().is_some_and(|segment| segment.ident == "Fn")) + }), + _ => false, + } +} + +/// Whether the file declares `method` on `service`'s interface. +fn declares_method(services: &str, service: &str, method: &str) -> bool { + let typed = services + .lines() + .filter_map(|line| { + line.strip_prefix("export interface ") + .or_else(|| line.strip_prefix("export type ")) + .and_then(|rest| rest.split([' ', '<', '{', '=']).next()) + }) + .find(|ty| catalog_name(ty) == service); + let Some(typed) = typed else { + return false; + }; + let start = match services.find(&format!("export interface {typed} {{")) { + Some(start) => start, + None => return false, + }; + services[start..] + .lines() + .take_while(|line| *line != "}") + .any(|line| line.trim_start().starts_with(&format!("{method}("))) +} + +/// `#[service]`, `#[service(skip)]` or their `rutis::` spellings. +fn is_service(attr: &syn::Attribute) -> bool { + let path = attr.path(); + let segments: Vec = path + .segments + .iter() + .map(|segment| segment.ident.to_string()) + .collect(); + matches!(segments.as_slice(), [service] if service == "service") + || matches!(segments.as_slice(), [root, service] if root == "rutis" && service == "service") +} + +fn skip_argument(attr: &syn::Attribute) -> bool { + attr.parse_args::() + .is_ok_and(|argument| argument == "skip") +} + +/// The last path segment of a type. +fn type_name(ty: &syn::Type) -> String { + match ty { + syn::Type::Path(path) => path + .path + .segments + .last() + .map(|segment| segment.ident.to_string()) + .unwrap_or_default(), + _ => String::new(), + } +} + +/// The name a method crosses as: `publish_file` is `publishFile`. +fn camel(ident: &str) -> String { + let mut camel = String::new(); + for (index, part) in ident.split('_').enumerate() { + if index == 0 { + camel += part; + continue; + } + let mut chars = part.chars(); + if let Some(first) = chars.next() { + camel += &first.to_uppercase().collect::(); + camel += chars.as_str(); + } + } + camel +} + +/// The names routing does not resolve, read from the runtime that refuses +/// them: its registration points, plus the two lifecycle services. A missing +/// list is an error, never an empty one. +fn unroutable(root: &Path) -> Result> { + let path = root.join("crates/dim-agent-runtime/src/route.rs"); + let source = std::fs::read_to_string(&path)?; + let ast = syn::parse_file(&source).map_err(|error| format!("{}: {error}", path.display()))?; + let mut names = vec!["sessionLifecycle".to_owned(), "branchLifecycle".to_owned()]; + let mut found = false; + for item in &ast.items { + let syn::Item::Const(declaration) = item else { + continue; + }; + if declaration.ident != "REGISTRATION_POINTS" { + continue; + } + let syn::Expr::Array(array) = &*declaration.expr else { + return Err(format!("{}: REGISTRATION_POINTS is not an array", path.display()).into()); + }; + for element in &array.elems { + let syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(name), + .. + }) = element + else { + return Err(format!( + "{}: REGISTRATION_POINTS holds an entry that is not a string", + path.display() + ) + .into()); + }; + names.push(name.value()); + } + found = true; + } + if !found { + return Err(format!("{}: REGISTRATION_POINTS is missing", path.display()).into()); + } + names.extend(internal(root)?); + Ok(names) +} + +/// The names an assembly marks internal, read from the calls that mark them and +/// from the product's table of `(name, reason)` pairs: a route refuses them, so +/// the generated requests do not offer them. +fn internal(root: &Path) -> Result> { + let mut names = Vec::new(); + for entry in std::fs::read_dir(root.join("crates"))? { + let directory = entry?.path().join("src"); + if !directory.is_dir() { + continue; + } + let mut files = Vec::new(); + sources(&mut files, &directory)?; + for file in files { + let ast = syn::parse_file(&std::fs::read_to_string(&file)?)?; + marks(&ast.items, &mut names); + internal_table(&ast.items, &mut names); + } + } + Ok(names) +} + +fn marks(items: &[syn::Item], names: &mut Vec) { + for item in items { + match item { + syn::Item::Mod(module) => { + if let Some((_, items)) = &module.content { + marks(items, names); + } + } + syn::Item::Fn(function) => marks_in(&function.block, names), + syn::Item::Impl(block) => { + for item in &block.items { + if let syn::ImplItem::Fn(function) = item { + marks_in(&function.block, names); + } + } + } + _ => {} + } + } +} + +/// The product's table of internal names: `for (name, reason) in [("a", "r"), …]` +/// feeding `internal_name(name, reason)`. +fn internal_table(items: &[syn::Item], names: &mut Vec) { + for item in items { + match item { + syn::Item::Mod(module) => { + if let Some((_, items)) = &module.content { + internal_table(items, names); + } + } + syn::Item::Fn(function) => tables_in(&function.block, names), + _ => {} + } + } +} + +fn tables_in(block: &syn::Block, names: &mut Vec) { + for statement in &block.stmts { + let syn::Stmt::Expr(expression, _) = statement else { + continue; + }; + let syn::Expr::ForLoop(loop_) = expression else { + continue; + }; + let syn::Expr::Array(array) = &*loop_.expr else { + continue; + }; + if !feeds_internal_name(&loop_.body) { + continue; + } + for element in &array.elems { + let syn::Expr::Tuple(tuple) = element else { + continue; + }; + if let Some(name) = tuple.elems.first().and_then(name_of) { + names.push(name); + } + } + } +} + +/// Whether a loop body hands its pair to `internal_name`, as the product's +/// face table does; any other table of pairs is unrelated data. +fn feeds_internal_name(block: &syn::Block) -> bool { + fn mentions(expression: &syn::Expr) -> bool { + match expression { + syn::Expr::Call(call) => { + let named = match &*call.func { + syn::Expr::Path(path) => path + .path + .segments + .last() + .is_some_and(|segment| segment.ident == "internal_name"), + _ => false, + }; + named || call.args.iter().any(mentions) + } + syn::Expr::MethodCall(call) => { + call.method == "internal_name" || call.args.iter().any(mentions) + } + _ => false, + } + } + block.stmts.iter().any(|statement| match statement { + syn::Stmt::Expr(expression, _) => mentions(expression), + syn::Stmt::Local(local) => local.init.as_ref().is_some_and(|init| mentions(&init.expr)), + _ => false, + }) +} + +fn marks_in(block: &syn::Block, names: &mut Vec) { + for statement in &block.stmts { + let expression = match statement { + syn::Stmt::Expr(expression, _) => expression, + syn::Stmt::Local(local) => match &local.init { + Some(init) => &init.expr, + None => continue, + }, + _ => continue, + }; + let syn::Expr::Call(call) = expression else { + continue; + }; + let syn::Expr::Path(path) = &*call.func else { + continue; + }; + let Some(last) = path.path.segments.last() else { + continue; + }; + let mut args = call.args.iter(); + match last.ident.to_string().as_str() { + "internal_name" => { + if let Some(name) = args.find_map(name_of) { + names.push(name); + } + } + "internal" => { + if let Some(name) = type_argument(&last.arguments) { + names.push(catalog_name(&name)); + } + } + _ => {} + } + } +} + +/// The catalog name of a Rust type: its type name with the leading word +/// lowercased, as `#[rutis::service]` names a type (`InputQueue` is +/// `inputQueue`). +fn catalog_name(type_name: &str) -> String { + let ident = type_name + .trim_start_matches("dyn ") + .split(['<', ' ']) + .next() + .unwrap_or(type_name); + let ident = ident.rsplit("::").next().unwrap_or(ident); + let chars: Vec = ident.chars().collect(); + let upper = chars.iter().take_while(|c| c.is_uppercase()).count(); + let lower = if upper > 1 && upper < chars.len() && chars[upper].is_lowercase() { + upper - 1 + } else { + upper.max(1).min(chars.len()) + }; + chars + .iter() + .enumerate() + .flat_map(|(index, c)| { + if index < lower { + c.to_lowercase().collect::>() + } else { + vec![*c] + } + }) + .collect() +} + fn declarations(root: &Path) -> Result { - rutis_types::Exports::new() + let services = rutis_types::Exports::new() .declared("serde_json::Value", "import('./plugin.js').BridgeJsonValue") .declared("serde_json::Map", "import('./plugin.js').BridgeJsonObject") .declared( @@ -54,7 +805,42 @@ fn declarations(root: &Path) -> Result { "dim_agent_types::TimelinePosition", "{ branch_id: string; sequence: number | bigint }", ) - .declarations(root.join("crates/dim-app-server")) + .declarations(root.join("crates/dim-app-server"))?; + let calls = calls(root, &services)?; + let mut text = replaced(services); + if !text.ends_with('\n') { + text.push('\n'); + } + Ok(text + "\n" + &calls) +} + +/// Drops the generated `LineCall`/`SessionCall` declarations, which the +/// narrowed ones replace. +fn replaced(services: String) -> String { + let mut text = String::new(); + let mut skipping = false; + for line in services.lines() { + if line.starts_with("export type LineCall = {") + || line.starts_with("export type SessionCall = {") + { + skipping = true; + continue; + } + if skipping { + if line == "}" { + skipping = false; + } + continue; + } + if line == "/** A call to one of the caller's own Session's lines. */" + || line == "/** A call to one of the caller's own Session's data faces. */" + { + continue; + } + text += line; + text.push('\n'); + } + text } pub fn write(root: &Path) -> Result<()> { @@ -75,3 +861,73 @@ pub fn check(root: &Path) -> Result<()> { println!("service declarations passed"); Ok(()) } + +#[cfg(test)] +mod derivation_tests { + use super::*; + + fn tree(source: &str) -> std::path::PathBuf { + let root = std::env::temp_dir().join(format!( + "dim-derived-{}-{}", + std::process::id(), + source.len() + )); + std::fs::create_dir_all(root.join("crates/example/src")).unwrap(); + std::fs::write(root.join("crates/example/src/lib.rs"), source).unwrap(); + root + } + + #[test] + fn a_callback_operation_is_derived_and_a_plain_one_is_not() { + let root = tree( + r#" + pub struct Example; + #[rutis::service] + impl Example { + /// A plain read. + pub async fn get(&self) -> Result { Ok(1) } + /// Takes the calling row. + pub async fn read(&self, caller: &Ctx, path: String) -> Result { Ok(1) } + /// Takes a cancellation. + pub async fn wait(&self, cancelled: CancelledFn) -> Result { Ok(1) } + } + "#, + ); + let derived = derived_lifecycle(&root).expect("the derivation reads the tree"); + assert_eq!( + derived, + vec![ + ("example".to_owned(), "read".to_owned()), + ("example".to_owned(), "wait".to_owned()), + ], + "{derived:?}" + ); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn the_comparison_names_the_operation_that_disagrees() { + let derived = [ + ("example".to_owned(), "read".to_owned()), + ("example".to_owned(), "wait".to_owned()), + ]; + let listed = [("example".to_owned(), "read".to_owned())]; + let missing: Vec = derived + .iter() + .filter(|pair| !listed.contains(pair)) + .map(|(service, method)| format!("{service}.{method}")) + .collect(); + assert_eq!(missing, vec!["example.wait".to_owned()]); + let listed = [ + ("example".to_owned(), "get".to_owned()), + ("example".to_owned(), "read".to_owned()), + ("example".to_owned(), "wait".to_owned()), + ]; + let extra: Vec = listed + .iter() + .filter(|pair| !derived.contains(pair)) + .map(|(service, method)| format!("{service}.{method}")) + .collect(); + assert_eq!(extra, vec!["example.get".to_owned()]); + } +} diff --git a/xtask/src/catalog.rs b/xtask/src/catalog.rs index f0611531a3..d7d19f9fd0 100644 --- a/xtask/src/catalog.rs +++ b/xtask/src/catalog.rs @@ -83,6 +83,8 @@ pub(super) async fn collect() -> Result { let ctx = probe.0.lock().unwrap().take(); let ctx = ctx.ok_or("the catalog probe did not load")?; let table = Table::new(agent.catalog(), agent.faces(), &layers, &ctx)?; + reach(&root_of(), agent.catalog(), agent.faces(), &table)?; + retired(&root_of(), agent.catalog())?; session.close().await?; Ok::<_, Box>(table) } @@ -93,6 +95,131 @@ pub(super) async fn collect() -> Result
{ table } +/// Fails when a service name the access layer records as retired is registered +/// again: the generated authoring types only cover names a route resolves, so a +/// retired name coming back would otherwise go unnoticed +/// (`xtask/access-layer.json`'s `removed` list). +fn retired(root: &std::path::Path, catalog: &ServiceCatalog) -> Result<()> { + let layer = xtask_check::access::load(root)?; + // A catalog name is known at the process, as a shared name, or inside an + // instance group: `key_in` answers `OutsideInstance` for the last. + let known = |name: &str| { + catalog.key(name).is_some() + || catalog.is_shared(name) + || matches!( + catalog.key_in(name, &rutis_loader::resolve::Build::default()), + Err(rutis_loader::LoaderError::OutsideInstance { .. }) + ) + }; + let back: Vec<&String> = layer.removed.iter().filter(|name| known(name)).collect(); + if !back.is_empty() { + return Err(format!( + "{}: retired service names are registered again: {back:?}", + xtask_check::access::FILE + ) + .into()); + } + Ok(()) +} + +/// The workspace root, from this crate's manifest directory. +fn root_of() -> std::path::PathBuf { + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .to_path_buf() +} + +/// Checks the generated authoring types against what the runtime resolves: every +/// name `npm/branch-services.d.ts` offers for a scope is a data face the route +/// accepts there. A name the route refuses, or a face of the other scope, must +/// not be offered, so this compares the two lists with the runtime's own rule +/// ([`dim_agent_runtime::route::resolves`]). +fn reach( + root: &std::path::Path, + catalog: &ServiceCatalog, + faces: &Faces, + table: &Table, +) -> Result<()> { + let text = std::fs::read_to_string(root.join("npm/branch-services.d.ts"))?; + let mut offered: Vec<(&str, &str)> = Vec::new(); + for (section, group) in [ + ("export type SessionFaces = {", "session"), + ("export type LineFaces = {", "branch"), + ] { + let Some(start) = text.find(section) else { + return Err(format!("npm/branch-services.d.ts: no {section}").into()); + }; + for line in text[start + section.len()..].lines() { + let line = line.trim(); + if line == "}" { + break; + } + let Some(name) = line.split(':').next().map(str::trim) else { + continue; + }; + if name.is_empty() { + continue; + } + offered.push((name, group)); + } + } + let mut refused = Vec::new(); + for (name, group) in &offered { + if !dim_agent_runtime::resolves(catalog, faces, name, group) { + refused.push(format!("{name} ({group})")); + } + } + if !refused.is_empty() { + return Err(format!( + "npm/branch-services.d.ts offers names the route refuses: {}", + refused.join(", ") + ) + .into()); + } + let unknown: Vec<&str> = offered + .iter() + .map(|(name, _)| *name) + .filter(|name| !table.services.contains_key(*name)) + .collect(); + if !unknown.is_empty() { + return Err(format!( + "npm/branch-services.d.ts offers names the assembly does not provide: {}", + unknown.join(", ") + ) + .into()); + } + // The other direction: a data face the route resolves and the file declares + // an interface for must be offered, or an author cannot write the call. + let mut missing = Vec::new(); + for (name, service) in &table.services { + let group: &str = match service.group { + group @ ("session" | "branch") => group, + _ => continue, + }; + if service.face != "data" || !dim_agent_runtime::resolves(catalog, faces, name, group) { + continue; + } + let declared = text.lines().any(|line| { + line.strip_prefix("export interface ") + .or_else(|| line.strip_prefix("export type ")) + .and_then(|rest| rest.split([' ', '<', '{', '=']).next()) + .is_some_and(|ty| dim_agent_runtime::names::name_of_type(ty) == *name) + }); + if declared && !offered.iter().any(|(offered, _)| *offered == name) { + missing.push(format!("{name} ({group})")); + } + } + if !missing.is_empty() { + return Err(format!( + "npm/branch-services.d.ts does not offer routable data faces: {}", + missing.join(", ") + ) + .into()); + } + Ok(()) +} + /// The face of one catalog name (#1289). fn face(name: &str, shared: bool, dispatcher: bool, reason: Option<&str>) -> Result { match (shared, dispatcher, reason) { @@ -491,3 +618,24 @@ mod face_tests { assert!(face("x", false, false, Some("hotpath")).is_err()); } } + +#[cfg(test)] +mod retired_tests { + use super::*; + + #[test] + fn a_retired_instance_name_is_refused() { + let directory = std::env::temp_dir().join(format!("dim-retired-{}", std::process::id())); + std::fs::create_dir_all(directory.join("xtask")).unwrap(); + // `sessionConfig` is registered inside the Session group only. + std::fs::write( + directory.join("xtask/access-layer.json"), + r#"{"allow": [], "removed": ["sessionConfig"]}"#, + ) + .unwrap(); + let catalog = dim_agent_runtime::names::catalog(); + let error = retired(&directory, &catalog).expect_err("an instance name is covered"); + assert!(error.to_string().contains("sessionConfig"), "{error}"); + let _ = std::fs::remove_dir_all(&directory); + } +}