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