Skip to main content

subc_protocol/
scope.rs

1//! Scope records: owned identity records the daemon holds for sessions.
2//!
3//! A scope is identified by `(owner, ref)`. The owner is the module whose own
4//! registered connection synced it, never a value in the request, and the
5//! `ref` is an opaque string unique within that owner only. The design is
6//! `docs/designs/daemon-scopes.md`; the wire shapes here are the owner-facing
7//! half of it (`scope.sync`, `scope.apply`, `scope.describe`).
8//!
9//! Every record type refuses unknown fields. A field this daemon does not know
10//! may be one that narrows authority in a later version (a carrier's target
11//! list, say), and silently dropping it would widen what the scope grants, so
12//! an owner sending one is told its body is malformed instead.
13
14use serde::{Deserialize, Serialize};
15
16use crate::Principal;
17
18mod federated;
19pub use federated::{FederatedAttributes, FederatedPeerClass, FederatedProject, RemoteClaim};
20mod authorize;
21pub use authorize::{
22    RouteAuthorizeExpected, RouteAuthorizeOutcome, RouteAuthorizeResponse, RouteAuthorizeScope,
23    ROUTE_AUTHORIZE_CAPABILITY, ROUTE_AUTHORIZE_OP,
24};
25
26/// A reader declares this only after implementing the federated provider rules.
27pub const SCOPE_FEDERATED_CAPABILITY: &str = "scope-federated/v1";
28
29/// Advertised by a daemon that accepts the federated scope members added in
30/// 0.37.4 (`origin_principal`, `peer_box_id`, `project`, a run's `run_id`, a
31/// flow's `agent_id`, the `app` peer class) in `scope.sync` and `scope.apply`,
32/// and stamps them on routes. A daemon without it refuses those members, so a
33/// scope owner sends them only when the connected daemon lists this.
34pub const SCOPE_FEDERATED_V2_CAPABILITY: &str = "scope-federated/v2";
35
36// Scope principals are authority-bearing input: an unrecognized constraint must
37// not silently widen a grant. Principal elsewhere is a forward-compatible caller
38// fact, so keep its general decoder lenient and enforce this only on scope input.
39#[derive(Deserialize)]
40#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
41enum ScopePrincipal {
42    Reserved { module_id: String },
43    Direct {},
44    Unverified {},
45}
46
47impl From<ScopePrincipal> for Principal {
48    fn from(value: ScopePrincipal) -> Self {
49        match value {
50            ScopePrincipal::Reserved { module_id } => Self::Reserved { module_id },
51            ScopePrincipal::Direct {} => Self::Direct,
52            ScopePrincipal::Unverified {} => Self::Unverified,
53        }
54    }
55}
56
57fn deserialize_scope_principal<'de, D: serde::Deserializer<'de>>(
58    deserializer: D,
59) -> Result<Principal, D::Error> {
60    ScopePrincipal::deserialize(deserializer).map(Into::into)
61}
62
63fn deserialize_scope_principals<'de, D: serde::Deserializer<'de>>(
64    deserializer: D,
65) -> Result<Vec<Principal>, D::Error> {
66    Vec::<ScopePrincipal>::deserialize(deserializer)
67        .map(|principals| principals.into_iter().map(Into::into).collect())
68}
69
70/// A scope bind-proof hash is the lowercase hexadecimal SHA-256 digest.
71pub fn validate_bind_proof_sha256(hash: &str) -> Result<(), &'static str> {
72    if hash.len() == 64
73        && hash
74            .bytes()
75            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
76    {
77        Ok(())
78    } else {
79        Err("bind_proof_sha256 must be exactly 64 lowercase hexadecimal characters")
80    }
81}
82
83fn deserialize_bind_proof_sha256<'de, D: serde::Deserializer<'de>>(
84    deserializer: D,
85) -> Result<Option<String>, D::Error> {
86    let hash = Option::<String>::deserialize(deserializer)?;
87    if let Some(hash) = &hash {
88        validate_bind_proof_sha256(hash).map_err(serde::de::Error::custom)?;
89    }
90    Ok(hash)
91}
92
93/// The `server.describe` capability a daemon advertises when it admits routes
94/// under scopes. A carrier that needs a scoped route and does not see it fails
95/// the call (`scope_unsupported`) instead of opening an unscoped route.
96pub const CAP_SCOPES_V1: &str = "scopes/v1";
97
98/// The `server.describe` capability a daemon advertises when it checks a
99/// `route.open`'s `role_versions` and forwards them on the module's bind. A
100/// daemon without it drops the field silently, so a consumer that relies on
101/// the provider seeing its role versions checks for this first.
102pub const CAP_ROUTE_ROLE_VERSIONS_V1: &str = "route-role-versions/v1";
103
104/// A target declares this in `capabilities.provides` once it no longer reads
105/// project fields from `route.bind` identities. Declaring it makes the daemon
106/// omit those identity fields, independently of [`SCOPE_WORKDIR_CAPABILITY`],
107/// which gates both `workdir` and `project_id` in the admitted [`ScopeStamp`].
108pub const BIND_NO_PROJECT_CAPABILITY: &str = "bind-no-project/v1";
109
110/// Module-to-subc op that registers an owner's full scope set.
111pub const SCOPE_SYNC_OP: &str = "scope.sync";
112/// Module-to-subc op that upserts or ends scopes without replacing the owner's
113/// full scope set.
114pub const SCOPE_APPLY_OP: &str = "scope.apply";
115/// Module-to-subc op that reads one scope's current state.
116pub const SCOPE_DESCRIBE_OP: &str = "scope.describe";
117
118/// Most live scopes one owner may hold. A sync naming more is refused whole.
119pub const MAX_LIVE_SCOPES_PER_OWNER: usize = 10_000;
120/// Most bytes one scope's `attributes` may take, measured as compact JSON. A
121/// sync carrying a larger record is refused whole.
122pub const MAX_SCOPE_ATTRIBUTE_BYTES: usize = 4 * 1024;
123/// Most ended scopes the daemon remembers per owner. The oldest is forgotten
124/// first, and reaching the bound never refuses a sync.
125pub const MAX_SCOPE_TOMBSTONES_PER_OWNER: usize = 1_000;
126/// Most modules one targeted carrier entry may list.
127pub const MAX_CARRIER_TARGETS: usize = 16;
128/// Most milliseconds a new scope epoch's deadline may be ahead of the daemon's
129/// current Unix wall clock: 24 hours.
130pub const MAX_SCOPE_EXPIRY_AHEAD_MS: u64 = 86_400_000;
131
132/// What a scope stands for. Fixed for the life of one
133/// `scope_epoch`: a different kind needs a new epoch, which ends the old scope.
134#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
135#[serde(rename_all = "snake_case")]
136#[non_exhaustive]
137pub enum ScopeKind {
138    Head,
139    Worker,
140    Ephemeral,
141    Federated,
142}
143
144/// A link from a scope to another scope, pinned to that scope's session by its
145/// epoch.
146#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
147#[serde(deny_unknown_fields)]
148#[non_exhaustive]
149pub struct ScopeParent {
150    #[serde(deserialize_with = "deserialize_scope_principal")]
151    pub owner: Principal,
152    #[serde(rename = "ref")]
153    pub scope_ref: String,
154    pub scope_epoch: u64,
155}
156
157impl ScopeParent {
158    pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
159        Self {
160            owner,
161            scope_ref: scope_ref.into(),
162            scope_epoch,
163        }
164    }
165}
166
167/// Who, besides the owner, may open routes under a scope.
168///
169/// `targets` absent means the carrier may open to any module. Present, it
170/// names the only module ids the carrier may open to, and must hold between 1
171/// and [`MAX_CARRIER_TARGETS`] entries: an empty list is refused rather than
172/// read as either "none" or "all".
173#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
174#[serde(deny_unknown_fields)]
175#[non_exhaustive]
176pub struct ScopeCarrier {
177    #[serde(deserialize_with = "deserialize_scope_principal")]
178    pub principal: Principal,
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub targets: Option<Vec<String>>,
181}
182
183impl ScopeCarrier {
184    pub fn new(principal: Principal) -> Self {
185        Self {
186            principal,
187            targets: None,
188        }
189    }
190
191    #[must_use]
192    pub fn with_targets(mut self, targets: Option<Vec<String>>) -> Self {
193        self.targets = targets;
194        self
195    }
196}
197
198/// Declaring this in a manifest's `capabilities.provides` promises that the
199/// module recognises a scope carrying `flow_id` and applies flow behaviour:
200/// it never treats the flow as its owner agent.
201/// During migration, either this capability or
202/// [`crate::call_mode::CALL_MODES_CAPABILITY`] admits flow scopes.
203pub const FLOW_SCOPES_CAPABILITY: &str = "flow-scopes/v1";
204
205/// Declaring this capability promises that a reader accepts the installed flow
206/// identity fields in scope stamps. It does not replace flow-scope admission.
207pub const FLOW_IDENTITY_SCOPES_CAPABILITY: &str = "flow-identity-scopes/v1";
208
209/// Declaring this in a manifest's `capabilities.provides` promises that the
210/// module recognises `run_id` as one agent run and does not exercise the agent's
211/// delegated authority under that scope.
212/// During migration it admits non-delegating run scopes; delegating runs require
213/// [`crate::call_mode::CALL_MODES_CAPABILITY`] instead.
214pub const AGENT_RUN_SCOPES_CAPABILITY: &str = "agent-run-scopes/v1";
215
216/// Declaring this in a manifest's `capabilities.provides` promises that the
217/// module recognises `on_behalf_of_agent` as attribution only, never authority.
218/// The daemon also advertises this capability to scope-authority owners.
219pub const SCOPE_ON_BEHALF_OF_CAPABILITY: &str = "scope-on-behalf-of/v1";
220
221/// A *worker run* is a codemode run scope with `run_id` and
222/// `on_behalf_of_agent` but no `agent_id`: it works for an agent without that
223/// agent's authority. Declaring this in a manifest's `capabilities.provides`
224/// promises that the module handles a codemode bind carrying `run_id` and no
225/// `agent_id` as attribution only, and never acts as, consents for, or hands out
226/// per-agent handles of the attributed agent. A worker run binds only to a
227/// target declaring it; `call-modes/v1` and `agent-run-scopes/v1` alone do not
228/// admit one, because those providers assume a run carries its agent's
229/// identity. A declarer receives `call_mode: codemode` and the stamp's
230/// `on_behalf_of_agent` on a worker-run bind even without
231/// [`SCOPE_ON_BEHALF_OF_CAPABILITY`]. The daemon also advertises this capability
232/// so owners register worker runs only with a daemon that accepts them.
233pub const WORKER_RUNS_CAPABILITY: &str = "worker-runs/v1";
234
235/// The daemon can answer whether a module acknowledged a bind under an owned scope epoch.
236pub const SCOPE_SERVED_BY_CAPABILITY: &str = "scope-served-by/v1";
237
238/// The authority-controlled attributes the daemon copies into scope stamps,
239/// subject to each field's target capability gate.
240/// Only an owner module named in the daemon config's `scope_authority_owners`
241/// list (by default the module that owns agent sessions) may set them; a scope
242/// owned by any other module must leave them empty.
243/// The separate `federated` object is restricted to the configured federated
244/// owner instead, and never confers local-agent authority.
245#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
246#[serde(deny_unknown_fields)]
247#[non_exhaustive]
248pub struct ScopeAttributes {
249    /// Paired-peer facts, required only for a federated scope. Never local authority.
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub federated: Option<FederatedAttributes>,
252    /// The agent the scope's session belongs to. Identity, never permission.
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub agent_id: Option<String>,
255    /// Attribution only, never authority. A provider may use this to choose
256    /// identity-scoped presentation (bot choice, read budgets, bound
257    /// repositories) and for logging. It must never treat this as authority to
258    /// act as that agent, hand out the agent's per-agent handles or consent on
259    /// its strength, or treat it as `agent_id`.
260    ///
261    /// Set only by a scope-authority owner and validated with `agent_id`'s
262    /// token rule. Mutually exclusive with `agent_id`, `delegates` and `flow_id`.
263    /// With `run_id` and no `agent_id` it marks a worker run (see
264    /// [`WORKER_RUNS_CAPABILITY`]). Adding, changing or removing this within an
265    /// epoch increments the content version and closes routes with
266    /// `scope_delegation_changed`. Bind stamps include it only for targets
267    /// providing [`SCOPE_ON_BEHALF_OF_CAPABILITY`], except that a worker run's
268    /// bind, which reaches only a target providing [`WORKER_RUNS_CAPABILITY`],
269    /// always includes it. Describe replies include it only for callers
270    /// providing [`SCOPE_ON_BEHALF_OF_CAPABILITY`].
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub on_behalf_of_agent: Option<String>,
273    /// Whether a provider may act as `agent_id`. Refused without `agent_id`.
274    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
275    pub delegates: bool,
276    /// This scope belongs to the named flow, an automated workflow run on an
277    /// agent's behalf. Set only by an authority owner (see above), validated
278    /// with [`validate_flow_id`], and stamped verbatim. It needs neither
279    /// `agent_id` nor `delegates`. Providers treat a module other than the
280    /// owner that opens a route under a flow scope as the flow's carrier.
281    ///
282    /// Like an `agent_id` change, changing this within the same scope epoch is
283    /// accepted: the scope's content version increases (the number providers
284    /// compare to notice a change), and every route under the scope is closed
285    /// with the reason `scope_delegation_changed`, so no live route keeps the
286    /// old identity.
287    /// A target must provide [`FLOW_SCOPES_CAPABILITY`] or
288    /// [`crate::call_mode::CALL_MODES_CAPABILITY`] before the daemon may send a
289    /// bind stamped with this field. Decoding it alone is not enough:
290    /// the target must also apply flow behaviour instead of agent behaviour.
291    #[serde(default, skip_serializing_if = "Option::is_none")]
292    pub flow_id: Option<String>,
293    /// The approved installed version, from 1 through 2^53 - 1. Together with
294    /// `flow_code_hash` and `flow_install_id`, requires `flow_id` and is immutable
295    /// within an epoch (`scope_flow_identity_changed`). Stamped only for readers
296    /// providing [`FLOW_IDENTITY_SCOPES_CAPABILITY`].
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub flow_version: Option<u64>,
299    /// SHA-256 of the approved flow code: exactly 64 lowercase hex characters.
300    /// Present together with `flow_version` and `flow_install_id`, under the same
301    /// authority, immutability and capability rules.
302    #[serde(default, skip_serializing_if = "Option::is_none")]
303    pub flow_code_hash: Option<String>,
304    /// Opaque installed-flow token, validated with [`validate_flow_install_id`].
305    /// Present together with `flow_version` and `flow_code_hash`, under the same
306    /// authority, immutability and capability rules.
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub flow_install_id: Option<String>,
309    /// Identifies one run: an agent run on behalf of `agent_id`, or a worker run
310    /// attributed to `on_behalf_of_agent` without that agent's authority. A
311    /// record with `run_id` carries exactly one of the two, forbids `flow_id`,
312    /// and uses [`validate_run_id`]'s token rule.
313    /// Adding, changing or removing it within an epoch increments the scope's
314    /// content version and closes routes under the scope with
315    /// `scope_delegation_changed`. The daemon sends an agent run's bind only to
316    /// a target module providing [`AGENT_RUN_SCOPES_CAPABILITY`] or
317    /// [`crate::call_mode::CALL_MODES_CAPABILITY`]. A delegating run scope is
318    /// accepted as a record, but binds only to a target providing the latter.
319    /// A worker run binds only to a target providing [`WORKER_RUNS_CAPABILITY`].
320    #[serde(default, skip_serializing_if = "Option::is_none")]
321    pub run_id: Option<String>,
322}
323
324impl ScopeAttributes {
325    pub fn new() -> Self {
326        Self::default()
327    }
328
329    #[must_use]
330    pub fn with_federated(mut self, federated: Option<FederatedAttributes>) -> Self {
331        self.federated = federated;
332        self
333    }
334
335    #[must_use]
336    pub fn with_agent_id(mut self, agent_id: Option<String>) -> Self {
337        self.agent_id = agent_id;
338        self
339    }
340
341    #[must_use]
342    pub fn with_on_behalf_of_agent(mut self, on_behalf_of_agent: Option<String>) -> Self {
343        self.on_behalf_of_agent = on_behalf_of_agent;
344        self
345    }
346
347    #[must_use]
348    pub fn with_delegates(mut self, delegates: bool) -> Self {
349        self.delegates = delegates;
350        self
351    }
352
353    #[must_use]
354    pub fn with_flow_id(mut self, flow_id: Option<String>) -> Self {
355        self.flow_id = flow_id;
356        self
357    }
358
359    #[must_use]
360    pub fn with_flow_version(mut self, flow_version: Option<u64>) -> Self {
361        self.flow_version = flow_version;
362        self
363    }
364
365    #[must_use]
366    pub fn with_flow_code_hash(mut self, flow_code_hash: Option<String>) -> Self {
367        self.flow_code_hash = flow_code_hash;
368        self
369    }
370
371    #[must_use]
372    pub fn with_flow_install_id(mut self, flow_install_id: Option<String>) -> Self {
373        self.flow_install_id = flow_install_id;
374        self
375    }
376
377    #[must_use]
378    pub fn with_run_id(mut self, run_id: Option<String>) -> Self {
379        self.run_id = run_id;
380        self
381    }
382
383    pub fn is_empty(&self) -> bool {
384        self.federated.is_none()
385            && self.agent_id.is_none()
386            && self.on_behalf_of_agent.is_none()
387            && !self.delegates
388            && self.flow_id.is_none()
389            && self.flow_version.is_none()
390            && self.flow_code_hash.is_none()
391            && self.flow_install_id.is_none()
392            && self.run_id.is_none()
393    }
394}
395
396/// Check a flow id using the shared opaque-token rule: 1–256 printable,
397/// non-space ASCII bytes. Errors name `flow_id`. Scope refs remain opaque and
398/// are not subject to this token rule.
399pub fn validate_flow_id(flow_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
400    crate::tool_call::validate_opaque_field("flow_id", flow_id)
401}
402
403/// Check an installed flow version: 1 through 9007199254740991 (2^53 - 1), the
404/// largest integer every JSON reader, including JavaScript, decodes exactly.
405pub fn validate_flow_version(flow_version: u64) -> Result<(), &'static str> {
406    if !(1..=9_007_199_254_740_991).contains(&flow_version) {
407        return Err("flow_version must be from 1 to 9007199254740991");
408    }
409    Ok(())
410}
411
412/// Check the approved flow code's SHA-256. Errors name `flow_code_hash`.
413pub fn validate_flow_code_hash(flow_code_hash: &str) -> Result<(), &'static str> {
414    if flow_code_hash.len() != 64
415        || !flow_code_hash
416            .bytes()
417            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
418    {
419        return Err("flow_code_hash must contain exactly 64 lowercase hex characters");
420    }
421    Ok(())
422}
423
424/// Check an installed flow token using the same opaque-token rule as `flow_id`.
425/// Errors name `flow_install_id`.
426pub fn validate_flow_install_id(
427    flow_install_id: &str,
428) -> Result<(), crate::tool_call::OpaqueFieldError> {
429    crate::tool_call::validate_opaque_field("flow_install_id", flow_install_id)
430}
431
432/// Check a run id using the shared opaque-token rule: 1–256 ASCII bytes in
433/// `0x21`–`0x7E`. Errors name `run_id`.
434pub fn validate_run_id(run_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
435    crate::tool_call::validate_opaque_field("run_id", run_id)
436}
437
438/// Check attribution using the agent token rule: 1–256 printable, non-space
439/// ASCII bytes. Errors name `on_behalf_of_agent`.
440pub fn validate_on_behalf_of_agent(agent: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
441    crate::tool_call::validate_opaque_field("on_behalf_of_agent", agent)
442}
443
444/// Capability declaring that a provider accepts session folder and project stamps.
445pub const SCOPE_WORKDIR_CAPABILITY: &str = "scope-workdir/v1";
446
447/// Check an Entorhinal project id without interpreting its opaque contents.
448pub fn validate_project_id(value: &str) -> Result<(), &'static str> {
449    if value.is_empty() || value.len() > 128 {
450        return Err("project_id must contain 1 to 128 bytes");
451    }
452    if !value.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) {
453        return Err("project_id must be printable ASCII without whitespace");
454    }
455    Ok(())
456}
457
458/// Namespace of a portable root key: an owned GitHub remote or an operator label.
459#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
460#[serde(rename_all = "snake_case")]
461pub enum RootKeyKind {
462    Remote,
463    Label,
464}
465
466/// Repository key of a session folder's root within its project. Attribution
467/// only, fixed per epoch like `project_id`; the owner fills it from its project
468/// registry at registration. Labels and remote names are distinct namespaces.
469#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
470#[serde(deny_unknown_fields)]
471#[non_exhaustive]
472pub struct RootKey {
473    pub kind: RootKeyKind,
474    pub key: String,
475}
476
477impl RootKey {
478    pub fn new(kind: RootKeyKind, key: impl Into<String>) -> Self {
479        Self {
480            kind,
481            key: key.into(),
482        }
483    }
484
485    pub fn validate(&self) -> Result<(), &'static str> {
486        validate_root_key(&self.key)
487    }
488}
489
490/// Check a root key's text using the project-id token bounds, without interpreting it.
491pub fn validate_root_key(value: &str) -> Result<(), &'static str> {
492    validate_project_id(value).map_err(|error| match error {
493        "project_id must contain 1 to 128 bytes" => "root_key must contain 1 to 128 bytes",
494        _ => "root_key must be printable ASCII without whitespace",
495    })
496}
497
498/// One scope as its owner registers it in `scope.sync` or `scope.apply`.
499#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
500#[serde(deny_unknown_fields)]
501#[non_exhaustive]
502pub struct ScopeRecord {
503    #[serde(rename = "ref")]
504    pub scope_ref: String,
505    /// Owner-supplied session number. The owner keeps it with its own record of
506    /// the session, re-sends the same value for the same session after any
507    /// restart, and uses a higher one when it reuses the ref for a new session.
508    pub scope_epoch: u64,
509    pub kind: ScopeKind,
510    /// Absolute session folder, canonicalized by the daemon and fixed per epoch.
511    /// Attribution only: this grants no authority.
512    #[serde(default, skip_serializing_if = "Option::is_none")]
513    pub workdir: Option<String>,
514    /// Opaque Entorhinal project id, fixed per epoch and never authority-gated.
515    #[serde(default, skip_serializing_if = "Option::is_none")]
516    pub project_id: Option<String>,
517    /// Repository key of the session folder's root within the project.
518    /// Attribution only, fixed per epoch; the owner fills it from its project
519    /// registry at registration. Requires `project_id`.
520    #[serde(default, skip_serializing_if = "Option::is_none")]
521    pub root_key: Option<RootKey>,
522    /// Only the holder of the scope's bind proof can bind it when this hash is
523    /// present. Without a hash, admission is unchanged and proofs are ignored.
524    #[serde(
525        default,
526        skip_serializing_if = "Option::is_none",
527        deserialize_with = "deserialize_bind_proof_sha256"
528    )]
529    pub bind_proof_sha256: Option<String>,
530    /// Refuse an epoch replacement or bind-proof change while routes are bound
531    /// to the live epoch, including binds admitted but not yet committed, or
532    /// connected presence holders remain. Send only after capability discovery.
533    /// This is a request condition, not a stored scope attribute.
534    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
535    pub replace_only_if_idle: bool,
536    /// Absolute Unix wall-clock deadline in milliseconds. It cannot be added,
537    /// changed or removed within this scope epoch; absent means no deadline.
538    /// This is not an authority attribute.
539    #[serde(default, skip_serializing_if = "Option::is_none")]
540    pub expires_at_ms: Option<u64>,
541    #[serde(default, skip_serializing_if = "Option::is_none")]
542    pub parent: Option<ScopeParent>,
543    /// Principals, other than the owner, allowed to register child scopes under
544    /// this one. Listing a principal here grants it nothing else.
545    #[serde(
546        default,
547        skip_serializing_if = "Vec::is_empty",
548        deserialize_with = "deserialize_scope_principals"
549    )]
550    pub child_owners: Vec<Principal>,
551    #[serde(default, skip_serializing_if = "Vec::is_empty")]
552    pub carriers: Vec<ScopeCarrier>,
553    #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
554    pub attributes: ScopeAttributes,
555}
556
557impl ScopeRecord {
558    pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, kind: ScopeKind) -> Self {
559        Self {
560            scope_ref: scope_ref.into(),
561            scope_epoch,
562            kind,
563            workdir: None,
564            project_id: None,
565            root_key: None,
566            bind_proof_sha256: None,
567            replace_only_if_idle: false,
568            expires_at_ms: None,
569            parent: None,
570            child_owners: Vec::new(),
571            carriers: Vec::new(),
572            attributes: ScopeAttributes::default(),
573        }
574    }
575
576    #[must_use]
577    pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
578        self.workdir = workdir;
579        self
580    }
581
582    #[must_use]
583    pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
584        self.project_id = project_id;
585        self
586    }
587
588    #[must_use]
589    pub fn with_root_key(mut self, root_key: Option<RootKey>) -> Self {
590        self.root_key = root_key;
591        self
592    }
593
594    #[must_use]
595    pub fn with_bind_proof_sha256(mut self, hash: Option<String>) -> Self {
596        self.bind_proof_sha256 = hash;
597        self
598    }
599
600    #[must_use]
601    pub fn with_replace_only_if_idle(mut self, replace_only_if_idle: bool) -> Self {
602        self.replace_only_if_idle = replace_only_if_idle;
603        self
604    }
605
606    #[must_use]
607    pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
608        self.expires_at_ms = expires_at_ms;
609        self
610    }
611
612    #[must_use]
613    pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
614        self.parent = parent;
615        self
616    }
617
618    #[must_use]
619    pub fn with_child_owners(mut self, child_owners: Vec<Principal>) -> Self {
620        self.child_owners = child_owners;
621        self
622    }
623
624    #[must_use]
625    pub fn with_carriers(mut self, carriers: Vec<ScopeCarrier>) -> Self {
626        self.carriers = carriers;
627        self
628    }
629
630    #[must_use]
631    pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
632        self.attributes = attributes;
633        self
634    }
635}
636
637/// A request to end one scope session in `scope.apply`.
638#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
639#[serde(deny_unknown_fields)]
640#[non_exhaustive]
641pub struct ScopeEnd {
642    #[serde(rename = "ref")]
643    pub scope_ref: String,
644    pub scope_epoch: u64,
645}
646
647impl ScopeEnd {
648    pub fn new(scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
649        Self {
650            scope_ref: scope_ref.into(),
651            scope_epoch,
652        }
653    }
654}
655
656/// What `scope.apply` did with one requested end.
657#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
658#[serde(rename_all = "snake_case")]
659pub enum ScopeEndOutcome {
660    /// The named scope ref was live at this epoch and was ended.
661    Ended,
662    /// The named scope ref was not live at this epoch; this end request changed
663    /// nothing.
664    NotLive,
665}
666
667/// The per-end result in a `scope.apply` reply, in request order.
668#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
669#[serde(deny_unknown_fields)]
670#[non_exhaustive]
671pub struct ScopeEndResult {
672    #[serde(rename = "ref")]
673    pub scope_ref: String,
674    pub scope_epoch: u64,
675    pub outcome: ScopeEndOutcome,
676}
677
678impl ScopeEndResult {
679    pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, outcome: ScopeEndOutcome) -> Self {
680        Self {
681            scope_ref: scope_ref.into(),
682            scope_epoch,
683            outcome,
684        }
685    }
686}
687
688/// The scope a `route.open` asks to be admitted under.
689///
690/// `scope_epoch` is optional on the wire only so that leaving it out is
691/// refused by name (`scope_epoch_required`) rather than as a malformed body:
692/// every opener must name it, the owner included.
693#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
694#[serde(deny_unknown_fields)]
695#[non_exhaustive]
696pub struct ScopeSelector {
697    #[serde(deserialize_with = "deserialize_scope_principal")]
698    pub owner: Principal,
699    #[serde(rename = "ref")]
700    pub scope_ref: String,
701    #[serde(default, skip_serializing_if = "Option::is_none")]
702    pub scope_epoch: Option<u64>,
703    /// Base64url-encoded 32-byte secret, without padding. Ignored for records
704    /// without a bind-proof hash, so holders may always send their proof.
705    #[serde(default, skip_serializing_if = "Option::is_none")]
706    pub bind_proof: Option<String>,
707    /// Keep connection-held presence after an admitted open, even if its route
708    /// closes. Send only to daemons advertising `scope-replace-if-idle/v1`.
709    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
710    pub hold_presence: bool,
711}
712
713impl ScopeSelector {
714    pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: Option<u64>) -> Self {
715        Self {
716            owner,
717            scope_ref: scope_ref.into(),
718            scope_epoch,
719            bind_proof: None,
720            hold_presence: false,
721        }
722    }
723
724    #[must_use]
725    pub fn with_bind_proof(mut self, proof: Option<String>) -> Self {
726        self.bind_proof = proof;
727        self
728    }
729
730    #[must_use]
731    pub fn with_hold_presence(mut self, hold_presence: bool) -> Self {
732        self.hold_presence = hold_presence;
733        self
734    }
735}
736
737impl std::fmt::Debug for ScopeSelector {
738    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
739        f.debug_struct("ScopeSelector")
740            .field("owner", &self.owner)
741            .field("scope_ref", &self.scope_ref)
742            .field("scope_epoch", &self.scope_epoch)
743            .field(
744                "bind_proof",
745                &self.bind_proof.as_ref().map(|_| "<redacted>"),
746            )
747            .finish()
748    }
749}
750
751impl std::fmt::Display for ScopeSelector {
752    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
753        std::fmt::Debug::fmt(self, f)
754    }
755}
756
757/// The state of a scope's parent link.
758#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
759#[serde(rename_all = "snake_case")]
760pub enum ParentState {
761    /// The parent is live at the named epoch and the link was permitted.
762    Linked,
763    /// The parent's owner has not synced in this daemon incarnation, so the
764    /// link is unverified and grants nothing yet.
765    Pending,
766    /// The parent is gone or live at another epoch, or the link was refused
767    /// when the parent's owner synced. Final for this link.
768    Ended,
769}
770
771/// What a `scope.sync` or `scope.apply` did with one record.
772#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
773#[serde(rename_all = "snake_case")]
774pub enum ScopeRecordOutcome {
775    /// The ref was not live before; the scope was created.
776    Created,
777    /// The ref was live at a lower epoch; that scope ended and this one began.
778    Replaced,
779    /// The ref was live at this epoch and its content changed.
780    Updated,
781    /// The ref was live at this epoch with identical content; its `version`
782    /// did not move.
783    Unchanged,
784    /// The record was refused on its own merits (`code` says why). The refusal
785    /// itself does not change the ref or undo any expiry processing.
786    Refused,
787}
788
789/// The per-record result in a `scope.sync` or `scope.apply` reply, in request order.
790#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
791pub struct ScopeRecordResult {
792    #[serde(rename = "ref")]
793    pub scope_ref: String,
794    /// The epoch the record named, which for a refusal may differ from the
795    /// epoch still held.
796    pub scope_epoch: u64,
797    pub outcome: ScopeRecordOutcome,
798    /// The refusal code when `outcome` is `refused`.
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub code: Option<String>,
801    #[serde(default, skip_serializing_if = "Option::is_none")]
802    pub message: Option<String>,
803    /// The daemon's content counter for the scope held under this ref after
804    /// the sync; absent when no scope is live under it.
805    #[serde(default, skip_serializing_if = "Option::is_none")]
806    pub version: Option<u64>,
807    /// The parent link's state after the sync, for a scope with a parent.
808    #[serde(default, skip_serializing_if = "Option::is_none")]
809    pub parent_state: Option<ParentState>,
810}
811
812/// A scope session of the calling owner that ended through omission from
813/// `scope.sync`, an explicit `scope.apply` end, replacement by a higher epoch
814/// for the same ref or expiry.
815#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
816pub struct ScopeEnded {
817    #[serde(rename = "ref")]
818    pub scope_ref: String,
819    pub scope_epoch: u64,
820}
821
822/// `scope.describe`'s answer about one `(owner, ref)`.
823#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
824#[serde(rename_all = "snake_case")]
825pub enum ScopeStatus {
826    Live,
827    /// Ended in this daemon incarnation, and still remembered.
828    Ended,
829    /// Neither live nor remembered as ended. With `owner_synced` true the scope
830    /// is gone: an owner's first sync of an incarnation is its full set. With
831    /// `owner_synced` false and `owner_configured` true the owner has not
832    /// re-synced since a daemon restart, so a reader waits. With
833    /// `owner_configured` false the owner will never sync.
834    NotLive,
835}
836
837/// The fields the daemon stamps for a live scope.
838/// Build with [`ScopeStamp::new`] and the setters so future fields are additive.
839#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
840#[non_exhaustive]
841pub struct ScopeStamp {
842    pub owner: Principal,
843    #[serde(rename = "ref")]
844    pub scope_ref: String,
845    pub scope_epoch: u64,
846    pub kind: ScopeKind,
847    /// Canonical session folder. Sent on binds only to providers declaring
848    /// [`SCOPE_WORKDIR_CAPABILITY`]; absent fields keep older binds unchanged.
849    #[serde(default, skip_serializing_if = "Option::is_none")]
850    pub workdir: Option<String>,
851    /// Entorhinal project id for attribution, never authority.
852    #[serde(default, skip_serializing_if = "Option::is_none")]
853    pub project_id: Option<String>,
854    /// Repository key of the session folder's root within the project.
855    /// Attribution only, fixed per epoch like `project_id`; the owner supplies
856    /// it from its project registry at registration.
857    #[serde(default, skip_serializing_if = "Option::is_none")]
858    pub root_key: Option<RootKey>,
859    #[serde(default, skip_serializing_if = "Option::is_none")]
860    pub parent: Option<ScopeParent>,
861    #[serde(default, skip_serializing_if = "Option::is_none")]
862    pub parent_state: Option<ParentState>,
863    #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
864    pub attributes: ScopeAttributes,
865    /// Whether the owner is listed in the daemon's `scope_authority_owners`.
866    /// Providers decide on this flag and keep no copy of the list.
867    /// Always false for the configured federated owner, even if it is listed.
868    pub owner_authorized: bool,
869    /// Absolute Unix wall-clock deadline in milliseconds, fixed for this epoch.
870    /// On route binds the daemon sends this deadline only to targets declaring
871    /// [`crate::call_mode::CALL_MODES_CAPABILITY`], because older providers may
872    /// reject unfamiliar scope-stamp fields.
873    #[serde(default, skip_serializing_if = "Option::is_none")]
874    pub expires_at_ms: Option<u64>,
875}
876
877impl ScopeStamp {
878    /// A stamp with no parent, attributes or deadline, and no owner authority.
879    pub fn new(
880        owner: Principal,
881        scope_ref: impl Into<String>,
882        scope_epoch: u64,
883        kind: ScopeKind,
884    ) -> Self {
885        Self {
886            owner,
887            scope_ref: scope_ref.into(),
888            scope_epoch,
889            kind,
890            workdir: None,
891            project_id: None,
892            root_key: None,
893            parent: None,
894            parent_state: None,
895            attributes: ScopeAttributes::new(),
896            owner_authorized: false,
897            expires_at_ms: None,
898        }
899    }
900
901    #[must_use]
902    pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
903        self.workdir = workdir;
904        self
905    }
906
907    #[must_use]
908    pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
909        self.project_id = project_id;
910        self
911    }
912
913    #[must_use]
914    pub fn with_root_key(mut self, root_key: Option<RootKey>) -> Self {
915        self.root_key = root_key;
916        self
917    }
918
919    #[must_use]
920    pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
921        self.parent = parent;
922        self
923    }
924
925    #[must_use]
926    pub fn with_parent_state(mut self, parent_state: Option<ParentState>) -> Self {
927        self.parent_state = parent_state;
928        self
929    }
930
931    #[must_use]
932    pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
933        self.attributes = attributes;
934        self
935    }
936
937    #[must_use]
938    pub fn with_owner_authorized(mut self, owner_authorized: bool) -> Self {
939        self.owner_authorized = owner_authorized;
940        self
941    }
942
943    #[must_use]
944    pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
945        self.expires_at_ms = expires_at_ms;
946        self
947    }
948}
949
950#[cfg(test)]
951mod tests {
952    use super::*;
953    use crate::tool_call::OpaqueFieldError;
954
955    #[test]
956    fn scope_root_key_roundtrips_namespaces_and_enforces_key_bounds() {
957        for kind in [RootKeyKind::Remote, RootKeyKind::Label] {
958            for key in ["p", "!~owner/repo", &"p".repeat(128)] {
959                let root = RootKey::new(kind, key);
960                root.validate().unwrap();
961                let wire = serde_json::to_value(&root).unwrap();
962                assert_eq!(serde_json::from_value::<RootKey>(wire).unwrap(), root);
963            }
964        }
965        assert_ne!(
966            RootKey::new(RootKeyKind::Remote, "owner/repo"),
967            RootKey::new(RootKeyKind::Label, "owner/repo")
968        );
969        for key in ["", "has space", "a\n", "é", "\u{007f}", &"a".repeat(129)] {
970            let error = RootKey::new(RootKeyKind::Remote, key)
971                .validate()
972                .unwrap_err();
973            assert!(error.starts_with("root_key"));
974            assert_eq!(validate_root_key(key), Err(error));
975        }
976        for wire in [
977            serde_json::json!({"kind":"future", "key":"owner/repo"}),
978            serde_json::json!({"kind":"remote", "key":"owner/repo", "extra":true}),
979            serde_json::json!({"key":"owner/repo"}),
980            serde_json::json!({"kind":"label"}),
981            serde_json::json!("owner/repo"),
982        ] {
983            assert!(serde_json::from_value::<RootKey>(wire).is_err());
984        }
985    }
986
987    #[test]
988    fn scope_root_key_is_optional_on_records_and_stamps_and_old_stamp_readers_ignore_it() {
989        let record = ScopeRecord::new("session", 1, ScopeKind::Head);
990        assert!(serde_json::to_value(&record)
991            .unwrap()
992            .get("root_key")
993            .is_none());
994        let record = record
995            .with_project_id(Some("project".into()))
996            .with_root_key(Some(RootKey::new(RootKeyKind::Remote, "owner/repo")));
997        let wire = serde_json::to_value(&record).unwrap();
998        assert_eq!(
999            wire["root_key"],
1000            serde_json::json!({"kind":"remote", "key":"owner/repo"})
1001        );
1002        assert_eq!(serde_json::from_value::<ScopeRecord>(wire).unwrap(), record);
1003        let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head);
1004        assert!(serde_json::to_value(&stamp)
1005            .unwrap()
1006            .get("root_key")
1007            .is_none());
1008        let stamp = stamp
1009            .with_project_id(record.project_id)
1010            .with_root_key(record.root_key);
1011        let wire = serde_json::to_value(&stamp).unwrap();
1012        assert_eq!(
1013            serde_json::from_value::<ScopeStamp>(wire.clone()).unwrap(),
1014            stamp
1015        );
1016        #[derive(Deserialize)]
1017        struct OldStamp {
1018            project_id: Option<String>,
1019        }
1020        let old: OldStamp = serde_json::from_value(wire).unwrap();
1021        assert_eq!(old.project_id.as_deref(), Some("project"));
1022    }
1023
1024    #[test]
1025    fn project_id_is_an_opaque_non_space_ascii_token_of_at_most_128_bytes() {
1026        for valid in ["p", "!~Project:7/path", &"p".repeat(128)] {
1027            assert_eq!(validate_project_id(valid), Ok(()));
1028        }
1029        for invalid in ["", "p p", "p\t", "pé", "p\u{7f}", &"p".repeat(129)] {
1030            assert!(validate_project_id(invalid).is_err(), "{invalid:?}");
1031        }
1032    }
1033
1034    #[test]
1035    fn scope_project_fields_round_trip_and_absence_keeps_exact_bytes() {
1036        let record = ScopeRecord::new("session", 1, ScopeKind::Head);
1037        assert_eq!(
1038            serde_json::to_string(&record).unwrap(),
1039            r#"{"ref":"session","scope_epoch":1,"kind":"head"}"#
1040        );
1041        let record = record
1042            .with_workdir(Some("/folder".into()))
1043            .with_project_id(Some("project:1".into()));
1044        let encoded = serde_json::to_string(&record).unwrap();
1045        assert_eq!(
1046            serde_json::from_str::<ScopeRecord>(&encoded).unwrap(),
1047            record
1048        );
1049        let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head);
1050        assert_eq!(
1051            serde_json::to_string(&stamp).unwrap(),
1052            r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","owner_authorized":false}"#
1053        );
1054        let stamp = stamp
1055            .with_workdir(record.workdir)
1056            .with_project_id(record.project_id);
1057        let encoded = serde_json::to_string(&stamp).unwrap();
1058        assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
1059    }
1060
1061    #[test]
1062    fn flow_id_uses_the_shared_opaque_token_bounds_and_names_its_field() {
1063        let field = "flow_id";
1064        assert_eq!(validate_flow_id(""), Err(OpaqueFieldError::Empty { field }));
1065        assert_eq!(validate_flow_id("f"), Ok(()));
1066        assert_eq!(validate_flow_id(&"f".repeat(256)), Ok(()));
1067        assert_eq!(
1068            validate_flow_id(&"f".repeat(257)),
1069            Err(OpaqueFieldError::TooLong { field, length: 257 })
1070        );
1071        assert_eq!(validate_flow_id("!~Flow:7/step"), Ok(()));
1072        for bad in ["f é", "f\t", "fé", "f\u{7f}"] {
1073            let error = validate_flow_id(bad).unwrap_err();
1074            assert_eq!(
1075                error,
1076                OpaqueFieldError::InvalidCharacter { field, index: 1 }
1077            );
1078            assert_eq!(error.field(), "flow_id");
1079        }
1080    }
1081
1082    #[test]
1083    fn flow_identity_validators_enforce_boundaries_and_name_fields() {
1084        for valid in [1, 9_007_199_254_740_991] {
1085            assert_eq!(validate_flow_version(valid), Ok(()));
1086        }
1087        for invalid in [0, 9_007_199_254_740_992, u64::MAX] {
1088            assert!(validate_flow_version(invalid)
1089                .unwrap_err()
1090                .contains("flow_version"));
1091        }
1092        assert_eq!(
1093            validate_flow_code_hash(&"0123456789abcdef".repeat(4)),
1094            Ok(())
1095        );
1096        for invalid in [
1097            "a".repeat(63),
1098            "a".repeat(65),
1099            "A".repeat(64),
1100            "g".repeat(64),
1101        ] {
1102            assert!(validate_flow_code_hash(&invalid)
1103                .unwrap_err()
1104                .contains("flow_code_hash"));
1105        }
1106        for valid in ["i", "!~Install:7/path", &"i".repeat(256)] {
1107            assert_eq!(validate_flow_install_id(valid), Ok(()));
1108        }
1109        for invalid in ["", "i i", "i\t", "ié", "i\u{7f}", &"i".repeat(257)] {
1110            assert_eq!(
1111                validate_flow_install_id(invalid).unwrap_err().field(),
1112                "flow_install_id"
1113            );
1114        }
1115    }
1116
1117    #[test]
1118    fn flow_identity_round_trips_and_legacy_stamp_keeps_exact_bytes() {
1119        let attributes = ScopeAttributes::new().with_flow_id(Some("flow:7".into()));
1120        let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head)
1121            .with_attributes(attributes.clone());
1122        assert_eq!(
1123            serde_json::to_string(&stamp).unwrap(),
1124            r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","attributes":{"flow_id":"flow:7"},"owner_authorized":false}"#
1125        );
1126        let attributes = attributes
1127            .with_flow_version(Some(9_007_199_254_740_991))
1128            .with_flow_code_hash(Some("a".repeat(64)))
1129            .with_flow_install_id(Some("install:7".into()));
1130        let stamp = stamp.with_attributes(attributes.clone());
1131        let encoded = serde_json::to_string(&stamp).unwrap();
1132        assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
1133        assert_eq!(
1134            serde_json::from_str::<ScopeAttributes>(&serde_json::to_string(&attributes).unwrap())
1135                .unwrap(),
1136            attributes
1137        );
1138        assert!(
1139            serde_json::from_str::<ScopeAttributes>(r#"{"flow_version":1,"unknown":true}"#)
1140                .is_err()
1141        );
1142        assert!(!ScopeAttributes::new().with_flow_version(Some(1)).is_empty());
1143        assert!(!ScopeAttributes::new()
1144            .with_flow_code_hash(Some("a".repeat(64)))
1145            .is_empty());
1146        assert!(!ScopeAttributes::new()
1147            .with_flow_install_id(Some("i".into()))
1148            .is_empty());
1149    }
1150
1151    #[test]
1152    fn flow_only_attributes_round_trip_and_absence_keeps_the_bytes() {
1153        let attributes = ScopeAttributes::default();
1154        assert!(attributes.is_empty());
1155        assert_eq!(serde_json::to_string(&attributes).unwrap(), "{}");
1156        assert_eq!(
1157            serde_json::from_str::<ScopeAttributes>("{}").unwrap(),
1158            attributes
1159        );
1160        let attributes = ScopeAttributes {
1161            flow_id: Some("flow:7".to_string()),
1162            ..ScopeAttributes::default()
1163        };
1164        assert!(!attributes.is_empty());
1165        let encoded = serde_json::to_string(&attributes).unwrap();
1166        assert_eq!(encoded, r#"{"flow_id":"flow:7"}"#);
1167        assert_eq!(
1168            serde_json::from_str::<ScopeAttributes>(&encoded).unwrap(),
1169            attributes
1170        );
1171        assert!(
1172            serde_json::from_str::<ScopeAttributes>(r#"{"flow_id":"flow:7","unknown":true}"#)
1173                .is_err()
1174        );
1175    }
1176}