Skip to main content

gent_daemon/
store.rs

1use crate::{
2    config::{self, Config},
3    encrypted,
4    runtime::{self, Identity},
5};
6use anyhow::{Context, Result, ensure};
7use base64::{Engine, engine::general_purpose::STANDARD};
8use gent_crypto::VerifiedState;
9use gent_protocol::*;
10use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
11use serde_json::{Value, json};
12use sha2::{Digest, Sha256};
13use std::{
14    collections::{BTreeMap, BTreeSet},
15    path::{Path, PathBuf},
16    sync::Arc,
17    time::{SystemTime, UNIX_EPOCH},
18};
19use tokio::sync::Notify;
20mod activity;
21mod administration;
22mod agents;
23mod babysitter;
24mod configuration;
25mod message_dates;
26mod notifications;
27mod ordinary_babysitter;
28mod wire;
29pub(crate) use configuration::pending::schema as pending_configuration_schema;
30pub(crate) use configuration::routing::schema as configuration_routing_schema;
31mod dashboards;
32mod diagnostics;
33pub mod direct;
34pub(crate) mod directory;
35mod directory_sync;
36mod files;
37pub(crate) mod handoff;
38mod history;
39pub(crate) mod hosted;
40pub mod invitations;
41mod mesh;
42mod network;
43pub mod node_invites;
44mod pairing;
45pub(crate) mod peer_configuration;
46mod permissions;
47mod presence;
48mod recovered;
49mod relay;
50pub(crate) mod removals;
51mod requests;
52#[cfg(test)]
53mod storage_tests;
54mod synchronization;
55mod wake;
56mod work;
57
58pub fn now() -> i64 {
59    SystemTime::now()
60        .duration_since(UNIX_EPOCH)
61        .expect("clock before epoch")
62        .as_secs()
63        .try_into()
64        .expect("clock overflow")
65}
66fn hash(value: &str) -> String {
67    format!("{:x}", Sha256::digest(value.as_bytes()))
68}
69fn require_pro(home: &Path, cfg: &Config, feature: &str) -> Result<()> {
70    ensure!(
71        crate::entitlements::paid(home, cfg),
72        "{feature} requires an active Gent Pro plan for this cluster. See https://gent.link/pricing"
73    );
74    Ok(())
75}
76const UNAVAILABLE: &str = "recipient or message unavailable";
77
78pub struct Store {
79    db: Connection,
80    direct_certs: direct::CertificateCache,
81    home: PathBuf,
82    config: Config,
83    identity: Identity,
84    owner_hash: String,
85    pub(crate) sync_wakeup: Arc<Notify>,
86    pub(crate) sync_health: Arc<crate::sync::health::Health>,
87}
88impl Store {
89    pub(crate) fn local_node_id(&self) -> &str {
90        self.identity.node.id()
91    }
92    /// Called by offline owner provisioning while holding daemon.lock. Service
93    /// registration cannot turn a joined node into a cryptographic owner.
94    pub fn require_provisioning_owner(&self) -> Result<()> {
95        self.identity.signing_owner(&self.db)?;
96        self.require_provisioning_member()
97    }
98
99    pub fn require_provisioning_member(&self) -> Result<()> {
100        let state = self.identity.state(&self.db)?;
101        ensure!(
102            state
103                .state()
104                .nodes
105                .get(self.identity.node.id())
106                .is_some_and(|n| n.signing_key == self.identity.node.public_key()),
107            "this node is no longer enrolled in the cluster"
108        );
109        // Expired authority can still obtain ciphertext transport to recover its
110        // latest signed configuration. RPC access continues to require freshness.
111        Ok(())
112    }
113    pub fn require_provisioning_joined(&self) -> Result<()> {
114        ensure!(
115            !self
116                .identity
117                .is_current_owner(&self.identity.state(&self.db)?),
118            "the existing owner cannot be replaced by a joined identity"
119        );
120        self.require_provisioning_member()
121    }
122
123    /// Service setup records describe enrollment history. A signed handoff can
124    /// change the configuration writer without changing account ownership or
125    /// removing either node's relay access.
126    pub fn require_service_setup_role(&self, originally_owner: bool) -> Result<()> {
127        let state = self.identity.state(&self.db)?;
128        if state.owner_epoch() > 0 || state.state().peer.is_some() {
129            self.require_provisioning_member()
130        } else if originally_owner {
131            self.require_provisioning_owner()
132        } else {
133            self.require_provisioning_joined()
134        }
135    }
136
137    pub fn open(home: &Path) -> Result<Self> {
138        let config = config::load_for_runtime(home)?;
139        ensure!(
140            config.hosted_parent()?.is_none(),
141            "this web node is served by its native host daemon"
142        );
143        let replacement = crate::pairing::replacement::check_intent(home, &config, None)?;
144        let owner_hash = hash(&config::read_private(&home.join("owner.key"))?);
145        ensure!(
146            home.join("state.sqlite3").exists() || !home.join(runtime::KEY_FILE).exists(),
147            "authority database is missing; restore this node's state"
148        );
149        let mut db = encrypted::open_database(home, "state.sqlite3")?;
150        db.busy_timeout(std::time::Duration::from_secs(5))?;
151        db.execute_batch("PRAGMA foreign_keys=ON;
152          CREATE TABLE IF NOT EXISTS agents (id TEXT PRIMARY KEY, credential_hash TEXT UNIQUE NOT NULL, node_id TEXT NOT NULL, name TEXT NOT NULL, provider TEXT NOT NULL, last_seen INTEGER NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);
153          CREATE TABLE IF NOT EXISTS exchanges (id TEXT PRIMARY KEY, a TEXT NOT NULL REFERENCES agents(id), b TEXT NOT NULL REFERENCES agents(id), expires_at INTEGER NOT NULL, count INTEGER NOT NULL);
154          CREATE TABLE IF NOT EXISTS messages (id TEXT PRIMARY KEY, sender TEXT NOT NULL REFERENCES agents(id), recipient TEXT NOT NULL REFERENCES agents(id), request_id TEXT NOT NULL, fingerprint TEXT NOT NULL, payload TEXT NOT NULL, acknowledged INTEGER NOT NULL DEFAULT 0, UNIQUE(sender,request_id));
155          CREATE INDEX IF NOT EXISTS messages_inbox ON messages(recipient,acknowledged);
156          CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY,value TEXT NOT NULL);
157          CREATE TABLE IF NOT EXISTS stream_relay_upload (
158            group_id BLOB PRIMARY KEY REFERENCES streams(group_id) ON DELETE CASCADE,
159            next_sequence INTEGER NOT NULL CHECK(next_sequence >= 0)
160          );")?;
161        network::schema(&db)?;
162        configuration::schema(&db)?;
163        peer_configuration::schema(&db)?;
164        mesh::schema(&db)?;
165        relay::schema(&db)?;
166        files::schema(&mut db)?;
167        requests::schema(&db, now())?;
168        history::schema(&db)?;
169        recovered::schema(&db)?;
170        work::schema(&db)?;
171        wake::schema(&db)?;
172        presence::schema(&db)?;
173        directory::schema(&db)?;
174        activity::schema(&db)?;
175        wire::schema(&db)?;
176        dashboards::schema(&db)?;
177        babysitter::schema(&db)?;
178        ordinary_babysitter::schema(&db)?;
179        notifications::schema(&db)?;
180        hosted::schema(&db)?;
181        directory_sync::schema(&db)?;
182        direct::schema(&db)?;
183        db.execute("UPDATE hosted_checkpoints SET lease_until=0", [])?;
184        let previous: Option<String> = db
185            .query_row("SELECT value FROM metadata WHERE key='cluster'", [], |r| {
186                r.get(0)
187            })
188            .optional()?;
189        if let Some(previous) = previous {
190            ensure!(
191                previous == config.cluster.id,
192                "database belongs to another cluster"
193            );
194        } else {
195            db.execute(
196                "INSERT INTO metadata VALUES ('cluster',?1)",
197                [&config.cluster.id],
198            )?;
199        }
200        let previous_node: Option<String> = db
201            .query_row("SELECT value FROM metadata WHERE key='node'", [], |r| {
202                r.get(0)
203            })
204            .optional()?;
205        if let Some(previous_node) = previous_node {
206            ensure!(
207                previous_node == config.node.id,
208                "database belongs to another node"
209            );
210        } else {
211            db.execute("INSERT INTO metadata VALUES ('node',?1)", [&config.node.id])?;
212        }
213        let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
214        let identity = Identity::load_or_create(home, &config, &tx, now() as u64)?;
215        peer_configuration::check_state(&tx, &identity.state(&tx)?)?;
216        directory::backfill_names(&tx, &identity.state(&tx)?)?;
217        message_dates::migrate(&tx, identity.node.id())?;
218        configuration::pending::recover(&tx, identity.node.id())?;
219        if let Some(record) = replacement {
220            record.verify_node(&identity.node)?;
221            let target = record.replaces;
222            let state = identity.state(&tx)?;
223            ensure!(
224                !state.state().nodes.contains_key(&target.id)
225                    && state.state().retired_nodes.contains(&target.id)
226                    && state.state().retired_keys.contains(&target.signing_key),
227                "replacement record does not match signed retirement"
228            );
229        }
230        if !identity.is_current_owner(&identity.state(&tx)?) {
231            // Only the SSH owner can issue enrollment snapshots. Conservative
232            // migration pins on a joined runtime cannot represent pending joins.
233            tx.execute("DELETE FROM authority_join_pins", [])?;
234        }
235        tx.commit()?;
236        let mut store = Self {
237            direct_certs: Default::default(),
238            db,
239            home: home.into(),
240            config,
241            owner_hash,
242            identity,
243            sync_wakeup: Arc::new(Notify::new()),
244            sync_health: Arc::default(),
245        };
246        // Projection failure must never replace committed authority with TOML.
247        let _ = store.project_config();
248        Ok(store)
249    }
250
251    pub fn handle(&mut self, request: Request) -> Response {
252        match self.execute(request) {
253            Ok(value) => Response::Ok(value),
254            Err(error) => Response::Error(error.to_string()),
255        }
256    }
257
258    fn execute(&mut self, request: Request) -> Result<Value> {
259        if let Request::Agent {
260            credential,
261            action: AgentOp::FileExport { file_id },
262        } = &request
263        {
264            // Persist capacity before creating plaintext, then persist the
265            // completed inode before publication. Each step rechecks authority.
266            for step in [
267                files::ExportStep::Reserve,
268                files::ExportStep::Write,
269                files::ExportStep::Publish,
270            ] {
271                let value = self.execute_step(
272                    Request::Agent {
273                        credential: credential.clone(),
274                        action: AgentOp::FileExport {
275                            file_id: file_id.clone(),
276                        },
277                    },
278                    step,
279                )?;
280                if !value.is_null() {
281                    return Ok(value);
282                }
283            }
284            anyhow::bail!("export did not finish");
285        }
286        self.execute_step(request, files::ExportStep::Reserve)
287    }
288
289    fn execute_step(&mut self, request: Request, export_step: files::ExportStep) -> Result<Value> {
290        if let Request::Owner { credential, .. } = &request {
291            ensure!(hash(credential) == self.owner_hash, "unauthorized");
292        }
293        if let Request::Owner {
294            action:
295                OwnerOp::RestoreWebNode {
296                    node_id,
297                    home,
298                    checkpoint,
299                    epoch,
300                },
301            ..
302        } = &request
303        {
304            return self.restore_web_node(node_id, home, checkpoint, *epoch);
305        }
306        if let Request::Owner {
307            action: OwnerOp::PrepareHostedNode { node_id, home },
308            ..
309        } = &request
310        {
311            return self.prepare_hosted_node(node_id, home);
312        }
313        if let Request::Owner {
314            credential,
315            action: OwnerOp::PreparePeerConfiguration,
316        } = &request
317        {
318            return Ok(serde_json::to_value(
319                self.prepare_configuration_log(credential)?,
320            )?);
321        }
322        if matches!(
323            &request,
324            Request::Owner {
325                action: OwnerOp::Diagnose,
326                ..
327            }
328        ) {
329            return self.diagnose();
330        }
331        if let Request::Owner {
332            action: OwnerOp::Pair { cluster_id, action },
333            ..
334        } = request
335        {
336            return self.pair(&cluster_id, action);
337        }
338        if let Request::Owner {
339            credential,
340            action: OwnerOp::Invitation { action },
341        } = request
342        {
343            return self.manage_invitation(&credential, action);
344        }
345        if let Request::Owner {
346            credential,
347            action: OwnerOp::OwnerTransfer { action },
348        } = request
349        {
350            return self.owner_transfer(&credential, action);
351        }
352        // Idle service probes and removal polling must not force a disk flush
353        // or wake the encrypted transport on every observation. Pending config
354        // projection retains its usual repair path.
355        let projection_pending = runtime::projection_pending(&self.db)?;
356        let local_only = matches!(
357            &request,
358            Request::Agent {
359                action: AgentOp::BabysitterClaim { .. }
360                    | AgentOp::BabysitterChatProbe { .. }
361                    | AgentOp::BabysitterChatClaim { .. }
362                    | AgentOp::BabysitterChatCheck { .. }
363                    | AgentOp::BabysitterChatSubmitted { .. }
364                    | AgentOp::BabysitterCheck { .. }
365                    | AgentOp::BabysitterSubmitted { .. },
366                ..
367            } | Request::Owner {
368                action: OwnerOp::NotificationPut { .. }
369                    | OwnerOp::NotificationSent { .. }
370                    | OwnerOp::BabysitterVerifiedBlockedClaim { .. },
371                ..
372            }
373        );
374        let read_only = (matches!(
375            &request,
376            Request::Owner {
377                action: OwnerOp::Status
378                    | OwnerOp::Agents
379                    | OwnerOp::Nodes
380                    | OwnerOp::Dashboards { .. }
381                    | OwnerOp::NotificationPending { .. }
382                    | OwnerOp::WebCheckpoint { .. }
383                    | OwnerOp::WebDeliveryDemand { .. }
384                    | OwnerOp::NodeRemovals { .. }
385                    | OwnerOp::WakePendingAgents { .. }
386                    | OwnerOp::WakeDirectTurnEvidence { .. },
387                ..
388            }
389        ) || matches!(
390            &request,
391            Request::HostedStatus { .. }
392                | Request::Agent {
393                    action: AgentOp::BabysitterChatProbe { .. },
394                    ..
395                }
396        )) && !projection_pending;
397        let tx = self.db.transaction_with_behavior(if read_only {
398            TransactionBehavior::Deferred
399        } else {
400            TransactionBehavior::Immediate
401        })?;
402        let timestamp = if read_only {
403            requests::diagnostic_clock(&tx, now())?
404        } else {
405            requests::clock(&tx, now())?
406        };
407        let state = self.identity.state(&tx)?;
408        let mut config = self.config.clone();
409        config.policy = state.state().policy.clone();
410        config.cluster.name.clone_from(&state.state().name);
411        if let Some(node) = state.state().nodes.get(self.identity.node.id()) {
412            config.node.name.clone_from(&node.name);
413        }
414        config.applied_revision = Some(state.checkpoint().revision);
415        let mut session = StoreSession {
416            db: &tx,
417            home: &self.home,
418            config,
419            identity: &self.identity,
420            state,
421            timestamp,
422        };
423        let owner_request = matches!(&request, Request::Owner { .. });
424        let refresh_nodes = matches!(
425            &request,
426            Request::Owner {
427                action: OwnerOp::RefreshNodes,
428                ..
429            }
430        );
431        let status_request = matches!(
432            &request,
433            Request::Owner {
434                action: OwnerOp::Status,
435                ..
436            }
437        );
438        let mut value = match request {
439            Request::Owner { action, .. } => session.owner(action, &self.sync_health)?,
440            Request::Agent { credential, action } => {
441                session.state.authorize_node(
442                    self.identity.node.id(),
443                    &self.identity.node.public_key(),
444                    timestamp as u64,
445                )?;
446                session.agent(self.identity.node.id(), &credential, action, export_step)?
447            }
448            Request::HostedAgent {
449                node_id,
450                gateway_credential,
451                credential,
452                action,
453                epoch,
454            } => {
455                session.check_hosted(&node_id, &gateway_credential)?;
456                hosted::check_epoch(&tx, &node_id, epoch)?;
457                session.require_web_lease(&node_id)?;
458                session.dirty_web(&node_id, &action)?;
459                ensure!(
460                    !matches!(
461                        action,
462                        AgentOp::FilePaths
463                            | AgentOp::FileImport { .. }
464                            | AgentOp::FileExport { .. }
465                    ),
466                    "local filesystem tools are unavailable to hosted chats"
467                );
468                let value = session.agent(&node_id, &credential, action, export_step)?;
469                if epoch.is_some() {
470                    hosted::check_epoch(&tx, &node_id, epoch)?;
471                }
472                value
473            }
474            Request::HostedStatus {
475                node_id,
476                gateway_credential,
477            } => {
478                session.check_hosted(&node_id, &gateway_credential)?;
479                session.hosted_status(&node_id)?
480            }
481        };
482        tx.commit()?;
483        if refresh_nodes
484            && value.as_array().is_some_and(|nodes| {
485                nodes
486                    .iter()
487                    .any(|n| n["presence"]["probe_started_at"].is_i64())
488            })
489            && self
490                .sync_health
491                .connected
492                .load(std::sync::atomic::Ordering::SeqCst)
493        {
494            self.sync_health.verify_watch.notify_one();
495        }
496        if status_request {
497            value["sync"] = self.synchronization_status()?;
498        }
499        if read_only || (local_only && !projection_pending) {
500            return Ok(value);
501        }
502        // Also wakes directory/message publication after a committed agent RPC.
503        self.sync_wakeup.notify_one();
504        // Filesystem projection is retryable after the authoritative commit.
505        // A caller must not interpret a projection failure as an unapplied edit.
506        let projected = self.project_config();
507        if owner_request
508            && (value.get("applied") == Some(&Value::Bool(true))
509                || value.get("config_saved").is_some())
510        {
511            value["config_saved"] = json!(projected.is_ok());
512            if let Err(error) = projected {
513                value["config_error"] = json!(error.to_string());
514            }
515        }
516        Ok(value)
517    }
518
519    fn project_config(&mut self) -> Result<()> {
520        let tx = self
521            .db
522            .transaction_with_behavior(TransactionBehavior::Immediate)?;
523        runtime::project(&self.home, &tx, &self.identity)?;
524        tx.commit()?;
525        Ok(())
526    }
527
528    /// The owner daemon renews its lease without requiring a chat turn.
529    /// Chat RPCs never bypass expiry or trigger a renewal themselves.
530    pub fn maintain(&mut self) -> Result<()> {
531        // Local cleanup remains available after membership/lease loss.
532        self.clean_invitations()?;
533        self.clean_files()?;
534        self.clean_history()?;
535        self.clean_wake()?;
536        {
537            let tx = self
538                .db
539                .transaction_with_behavior(TransactionBehavior::Immediate)?;
540            configuration::pending::recover(&tx, self.identity.node.id())?;
541            encrypted::ordered::storage::clean(&tx, false)?;
542            tx.commit()?;
543        }
544        let timestamp = now() as u64;
545        let tx = self
546            .db
547            .transaction_with_behavior(TransactionBehavior::Immediate)?;
548        let state = self.identity.state(&tx)?;
549        ensure!(
550            state
551                .state()
552                .nodes
553                .get(self.identity.node.id())
554                .is_some_and(|n| n.signing_key == self.identity.node.public_key()),
555            "local node is no longer enrolled"
556        );
557        crate::file_objects::Objects::new(&tx, timestamp)?.reap()?;
558        let renew = !self.identity.legacy_signing_fenced()
559            && self.identity.legacy_service_checked
560            && self.identity.is_current_owner(&state)
561            && !handoff::frozen(&tx, &state)?
562            && state.state().expires_at.saturating_sub(timestamp) <= 6 * 60 * 60;
563        if renew {
564            let update = state.renew(&*self.identity.signing_owner(&tx)?, timestamp)?;
565            self.identity.apply(&tx, update)?;
566        }
567        tx.commit()?;
568        if renew {
569            self.sync_wakeup.notify_one();
570        }
571        self.project_config()?;
572        self.reconcile_configuration()
573    }
574
575    /// Trusted enrollment API. The supplied authority must already be verified
576    /// through protected pairing. It installs no owner signing secret.
577    pub fn install_joined(
578        home: &Path,
579        node: &gent_crypto::NodeIdentity,
580        state: &VerifiedState,
581    ) -> Result<()> {
582        runtime::install_joined(home, node, state)
583    }
584
585    pub(crate) fn relay_settings(&self) -> Option<(config::RelayConfig, PathBuf)> {
586        self.config
587            .relay
588            .clone()
589            .map(|relay| (relay, self.home.clone()))
590    }
591    pub(crate) fn sync_streams(&self) -> Result<Vec<crate::sync::Stream>> {
592        if self.identity.state(&self.db)?.state().peer.is_some() {
593            return self.data_streams();
594        }
595        let mut streams: Vec<_> =
596            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?
597                .configuration_streams(now() as u64)?
598                .into_iter()
599                .map(|s| crate::sync::Stream {
600                    group: s.group,
601                    outgoing: s.outgoing,
602                    configuration: true,
603                })
604                .collect();
605        streams.extend(self.data_streams()?);
606        Ok(streams)
607    }
608    pub(crate) fn sync_pending_groups(
609        &self,
610        streams: &[crate::sync::Stream],
611    ) -> Result<crate::sync::MailboxWork> {
612        let mut work = crate::sync::MailboxWork::default();
613        let mut pending = self.db.prepare(
614            "SELECT s.group_id,s.head>=COALESCE(u.next_sequence,0)
615             FROM streams s LEFT JOIN stream_relay_upload u USING(group_id)
616             LEFT JOIN stream_confirmed c USING(group_id)
617             WHERE s.writer=?1 AND s.head>COALESCE(c.sequence,-1)",
618        )?;
619        let mut rows = pending.query([self.identity.node.id()])?;
620        while let Some(row) = rows.next()? {
621            let group: Vec<u8> = row.get(0)?;
622            work.unconfirmed.insert(group.clone());
623            if row.get::<_, bool>(1)? {
624                work.ready.insert(group);
625            }
626        }
627        let local = self
628            .db
629            .prepare(
630                "SELECT group_id FROM owner_deliveries WHERE next<parts
631             UNION SELECT s.group_id FROM streams s JOIN stream_pending p
632               ON p.group_id=s.group_id AND p.sequence=s.head+1",
633            )?
634            .query_map([], |r| r.get(0))?
635            .collect::<rusqlite::Result<Vec<Vec<u8>>>>()?;
636        work.ready.extend(local);
637        self.add_ready_network_groups(&mut work.ready)?;
638
639        // An unpublished legacy configuration revision is work even before
640        // its first fragment has a stream position. Old owner epochs stop at
641        // their signed handoff baseline.
642        let writers: BTreeSet<_> = streams
643            .iter()
644            .filter(|s| s.configuration && s.outgoing)
645            .map(|s| s.group.as_slice())
646            .collect();
647        if writers.is_empty() {
648            return Ok(work);
649        }
650        let state = self.identity.state(&self.db)?;
651        let mut query = self.db.prepare(
652            "SELECT c.group_id,c.grant,h.revision FROM configuration_streams c
653             JOIN streams s USING(group_id) JOIN authority_history h ON h.revision=c.revision+1
654             WHERE s.writer=?1",
655        )?;
656        let mut rows = query.query([self.identity.node.id()])?;
657        while let Some(row) = rows.next()? {
658            let group: Vec<u8> = row.get(0)?;
659            if !writers.contains(group.as_slice()) {
660                continue;
661            }
662            let grant = gent_crypto::SignedConfigurationGrant::decode(&row.get::<_, Vec<u8>>(1)?)?;
663            let limit = encrypted::ordered::configuration::publication_limit(&grant, &state);
664            let revision: u64 = row.get(2)?;
665            if limit.is_none_or(|last| revision <= last) {
666                work.ready.insert(group);
667            }
668        }
669        Ok(work)
670    }
671
672    /// A relay can roll back its queue or lose a successful PUT response.
673    /// Replay from the lower position, excluding only the verified prefix.
674    pub(crate) fn relay_upload_start(
675        &self,
676        group: &[u8],
677        relay_next: u64,
678        confirmed_next: u64,
679    ) -> Result<u64> {
680        let (local_next, uploaded): (u64, u64) = self.db.query_row(
681            "SELECT s.head+1,COALESCE(u.next_sequence,0) FROM streams s
682             LEFT JOIN stream_relay_upload u USING(group_id) WHERE s.group_id=?1 AND s.writer=?2",
683            params![group, self.identity.node.id()],
684            |r| Ok((r.get(0)?, r.get(1)?)),
685        )?;
686        ensure!(
687            relay_next <= local_next,
688            "relay position exceeds local history"
689        );
690        if relay_next < uploaded {
691            self.record_relay_upload(group, relay_next)?;
692        }
693        Ok(uploaded.min(relay_next).max(confirmed_next))
694    }
695
696    pub(crate) fn record_relay_upload(&self, group: &[u8], next: u64) -> Result<()> {
697        self.db.execute(
698            "INSERT INTO stream_relay_upload(group_id,next_sequence) VALUES(?1,?2)
699             ON CONFLICT(group_id) DO UPDATE SET next_sequence=excluded.next_sequence",
700            params![group, next],
701        )?;
702        Ok(())
703    }
704    pub(crate) fn sync_prepare(&self, group: &[u8]) -> Result<()> {
705        let mut endpoint =
706            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
707        let timestamp = now() as u64;
708        if endpoint
709            .prepare_configuration(group, None, timestamp)?
710            .is_none()
711        {
712            endpoint.prepare_owner_handoff(group, timestamp)?;
713        }
714        Ok(())
715    }
716
717    pub(crate) fn transport_receipt(
718        &self,
719        group: &[u8],
720        configuration: bool,
721    ) -> Result<gent_crypto::stream::Receipt> {
722        if !configuration {
723            self.data_peer(&self.db, group, false)?;
724        }
725        encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?
726            .receipt(group, now() as u64)
727    }
728
729    pub(crate) fn transport_confirm(
730        &self,
731        group: &[u8],
732        configuration: bool,
733        receipt: Option<&gent_crypto::stream::Receipt>,
734    ) -> Result<Option<gent_crypto::stream::Receipt>> {
735        Ok(self
736            .transport_confirmation(group, configuration, receipt)?
737            .0)
738    }
739
740    /// The flag records a newly advanced durable checkpoint, excluding cached or replayed ACKs.
741    pub(crate) fn transport_confirmation(
742        &self,
743        group: &[u8],
744        configuration: bool,
745        receipt: Option<&gent_crypto::stream::Receipt>,
746    ) -> Result<(Option<gent_crypto::stream::Receipt>, bool)> {
747        let mut endpoint =
748            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
749        let reader = if configuration {
750            endpoint.configuration_reader(group)?
751        } else {
752            self.data_peer(&self.db, group, true)?
753        };
754        if let Some(receipt) = receipt {
755            ensure!(
756                receipt.group() == group,
757                "checkpoint belongs to another stream"
758            );
759            return endpoint
760                .confirm_and_get(receipt, &reader, now() as u64)
761                .map(|(receipt, advanced)| (Some(receipt), advanced));
762        }
763        Ok((endpoint.confirmed_receipt(group, now() as u64)?, false))
764    }
765    pub(crate) fn sync_outgoing(
766        &self,
767        group: &[u8],
768        next: u64,
769    ) -> Result<Option<gent_crypto::stream::Packet>> {
770        let mut endpoint =
771            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
772        let timestamp = now() as u64;
773        let status = endpoint.configuration_status(group, timestamp)?;
774        ensure!(next <= status.next, "relay position exceeds local history");
775        Ok(endpoint
776            .configuration_outbox(group, next.checked_sub(1), 1, timestamp)?
777            .pop())
778    }
779    pub(crate) fn sync_next(&mut self, group: &[u8]) -> Result<u64> {
780        let mut endpoint =
781            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
782        let timestamp = now() as u64;
783        // A restart may find a packet committed to the receive buffer before
784        // its authority transaction ran. Apply it without requiring the relay.
785        let pending = endpoint.drain_configuration(group, 1, timestamp)?;
786        let next = endpoint
787            .configuration_status(group, timestamp)
788            .map(|status| status.next);
789        drop(endpoint);
790        if !pending.is_empty() {
791            self.project_config()?;
792            self.reconcile_configuration()?;
793            self.sync_wakeup.notify_one();
794        }
795        next
796    }
797    pub(crate) fn sync_receive(&mut self, packet: &gent_crypto::stream::Packet) -> Result<()> {
798        let mut endpoint =
799            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
800        let timestamp = now() as u64;
801        endpoint.stage_configuration(packet, timestamp)?;
802        endpoint.drain_configuration(packet.group(), 1, timestamp)?;
803        self.sync_wakeup.notify_one();
804        self.project_config()?;
805        self.reconcile_configuration()
806    }
807}
808
809struct StoreSession<'a> {
810    db: &'a Connection,
811    home: &'a Path,
812    config: Config,
813    identity: &'a Identity,
814    state: VerifiedState,
815    timestamp: i64,
816}
817
818#[derive(Default)]
819struct SendContext {
820    parent: Option<Message>,
821    relay: Option<RelayMessage>,
822    file_ids: Vec<String>,
823}
824
825fn message_fingerprint(
826    recipient: &str,
827    text: &str,
828    files: &[FilePart],
829    reply_to: &Option<String>,
830    relay: &Option<RelayMessage>,
831    file_ids: &[String],
832) -> Result<String> {
833    let mut value = json!({"recipient":recipient,"text":text,"files":files,"reply_to":reply_to});
834    // Preserve exact retry fingerprints for pre-relay messages.
835    if let Some(relay) = relay {
836        value["relay"] = json!(relay);
837    }
838    if !file_ids.is_empty() {
839        value["file_ids"] = json!(file_ids);
840    }
841    Ok(hash(&serde_json::to_string(&value)?))
842}
843impl StoreSession<'_> {
844    fn decode_agent(row: &rusqlite::Row<'_>) -> rusqlite::Result<Agent> {
845        Ok(Agent {
846            id: row.get(0)?,
847            node_id: row.get(1)?,
848            name: row.get(2)?,
849            provider: row.get(3)?,
850            last_seen: row.get(4)?,
851            revoked: row.get(5)?,
852        })
853    }
854    fn get_agent(&self, id: &str) -> Result<Agent> {
855        let mut agent = self
856            .db
857            .query_row(
858                "SELECT id,node_id,name,provider,last_seen,revoked FROM agents WHERE id=?1",
859                [id],
860                Self::decode_agent,
861            )
862            .optional()?
863            .context(UNAVAILABLE)?;
864        agent.revoked |= !self.state.state().nodes.contains_key(&agent.node_id);
865        Ok(agent)
866    }
867    fn all_agents(&self) -> Result<Vec<Agent>> {
868        let mut agents = self
869            .db
870            .prepare("SELECT id,node_id,name,provider,last_seen,revoked FROM agents ORDER BY id")?
871            .query_map([], Self::decode_agent)?
872            .collect::<Result<Vec<_>, _>>()?;
873        for agent in &mut agents {
874            agent.revoked |= !self.state.state().nodes.contains_key(&agent.node_id);
875        }
876        Ok(agents)
877    }
878    fn owner(&mut self, action: OwnerOp, health: &crate::sync::health::Health) -> Result<Value> {
879        match action {
880            OwnerOp::WebDeliveryDemand { node_id } => self.web_delivery_demand(&node_id),
881            OwnerOp::WebDeliveryChecked {
882                node_id,
883                message_id,
884            } => {
885                let cleared = self.db.execute(
886                    "DELETE FROM web_delivery_demand WHERE node=?1 AND message=?2",
887                    params![node_id, message_id],
888                )?;
889                Ok(json!({"cleared":cleared==1}))
890            }
891            OwnerOp::WebAdmission { node_id, body_hash } => self.web_admission(&node_id, body_hash),
892            OwnerOp::WebCheckpoint { node_id } => self.web_checkpoint(&node_id),
893            OwnerOp::WebLease { node_id, seconds } => self.web_lease(&node_id, seconds),
894            OwnerOp::WebGrant {
895                node_id,
896                epoch,
897                expires_at,
898            } => self.web_grant(&node_id, epoch, expires_at),
899            OwnerOp::WebCommit {
900                node_id,
901                revision,
902                epoch,
903            } => self.web_commit(&node_id, revision, epoch),
904            OwnerOp::RestoreWebNode { .. } => unreachable!("handled before session"),
905            OwnerOp::NodeInvite {
906                request_id,
907                name,
908                can_configure,
909                activate,
910            } => self.request_node_invite(&request_id, &name, can_configure, activate),
911            OwnerOp::AgentRecover {
912                directory,
913                manifest_sha256,
914                source_agent,
915                agent_credential,
916                name,
917                provider,
918            } => {
919                let registered = self.agent(
920                    self.identity.node.id(),
921                    &agent_credential,
922                    AgentOp::Register {
923                        name: name.clone(),
924                        provider: provider.clone(),
925                    },
926                    files::ExportStep::Reserve,
927                )?;
928                let id = registered["agent"]["id"]
929                    .as_str()
930                    .context("missing recovered chat identity")?;
931                let agent = self.get_agent(id)?;
932                ensure!(
933                    agent.name == name && agent.provider == provider,
934                    "recovery registration arguments changed"
935                );
936                let history = self.recovered_import(
937                    Path::new(&directory),
938                    &manifest_sha256,
939                    &source_agent,
940                    id,
941                    None,
942                )?;
943                Ok(
944                    json!({"agent":agent,"history":history,"source_agent":source_agent,
945                    "scope":"fresh local registration with assigned history; old credentials, peer permissions and pending work are not restored"}),
946                )
947            }
948            OwnerOp::HistoryImports => self.recovered_imports(None),
949            OwnerOp::HistoryImport {
950                directory,
951                manifest_sha256,
952                source_agent,
953                target_agent,
954                restore_revision,
955            } => self.recovered_import(
956                Path::new(&directory),
957                &manifest_sha256,
958                &source_agent,
959                &target_agent,
960                restore_revision,
961            ),
962            OwnerOp::HistoryRemove {
963                import_id,
964                expected_revision,
965            } => self.recovered_remove(&import_id, expected_revision),
966            OwnerOp::Pair { .. }
967            | OwnerOp::Invitation { .. }
968            | OwnerOp::Diagnose
969            | OwnerOp::PreparePeerConfiguration => {
970                anyhow::bail!("pairing must use its owner-authenticated entry point")
971            }
972            OwnerOp::Status => Ok(
973                json!({"process_id":std::process::id(),"node":self.config.node,"cluster":self.config.cluster,"transport":"local_unix_socket","remote_ready":self.remote_ready()?,
974                    "release_channel":self.state.state().release_channel,
975                    "can_set_release_channel":self.identity.is_current_owner(&self.state) || self.identity.has_configuration_grant(&self.state),
976                    "authority":{"mode":if self.state.state().peer.is_some(){"peers"}else{"legacy"},"sequence":self.state.checkpoint().revision,"revision":self.state.checkpoint().revision,"expires_at":self.state.state().expires_at,"fresh":self.state.require_fresh(self.timestamp as u64).is_ok()},"config_saved":!runtime::projection_pending(self.db)?}),
977            ),
978            OwnerOp::Groups { name } => match name {
979                Some(name) => Ok(
980                    json!({"name":name,"members":self.config.policy.groups.get(&name).context("unknown group")?}),
981                ),
982                None => Ok(json!(self.config.policy.groups)),
983            },
984            OwnerOp::GroupAdmins => Ok(
985                json!({"grants":self.config.policy.group_admin_grants,"retired":self.state.state().retired_admin_grants}),
986            ),
987            OwnerOp::GroupAdminHistory {
988                administrator,
989                before,
990            } => self.administration_history(administrator.as_deref(), before, true),
991            OwnerOp::NotificationPending { scope } => self.pending_notices(&scope),
992            OwnerOp::NotificationPut { notice, scope } => self.enqueue_notice(&notice, scope),
993            OwnerOp::NotificationSent { id } => {
994                self.db
995                    .execute("DELETE FROM account_outbox WHERE id=?1", [id.to_string()])?;
996                Ok(json!({}))
997            }
998            OwnerOp::Dashboards { after } => self.dashboards(after.as_deref()),
999            OwnerOp::DashboardClick {
1000                agent,
1001                revision,
1002                widget,
1003                request_id,
1004            } => self.dashboard_click(&agent, revision, &widget, &request_id),
1005            OwnerOp::PermissionRules => Ok(json!({"rules":self.state.state().policy.rules,
1006                "groups":self.state.state().policy.groups.keys().collect::<Vec<_>>()})),
1007            OwnerOp::PermissionExplain { actor, peer } => self.permission_explain(&actor, &peer),
1008            OwnerOp::PermissionAdmins => {
1009                Ok(json!({"grants":self.state.state().policy.admin_grants,
1010                "retired":self.state.state().retired_admin_grants,"revision":self.state.checkpoint().revision}))
1011            }
1012            OwnerOp::PermissionAdminHistory {
1013                administrator,
1014                before,
1015            } => self.permission_admin_history(administrator.as_deref(), before),
1016            OwnerOp::Nodes => self.nodes(health),
1017            OwnerOp::RefreshNodes => self.refresh_nodes(health),
1018            OwnerOp::Agents => Ok(serde_json::to_value(self.directory(None)?)?),
1019            OwnerOp::Resolve {
1020                name,
1021                node,
1022                provider,
1023            } => self.resolve_agent(None, &name, node.as_deref(), provider.as_deref()),
1024            OwnerOp::NativeMessageDates => self.local_native_message_dates(),
1025            OwnerOp::ObserveActivity {
1026                agent_id,
1027                last_activity_at,
1028                last_native_message_at,
1029            } => self.observe_activity(&agent_id, last_activity_at, last_native_message_at),
1030            OwnerOp::ClearRetiredAgents { dry_run } => self.clear_retired_agents(dry_run),
1031            OwnerOp::Agent { agent_id } => self.agent_details(&agent_id),
1032            OwnerOp::RenameAgent {
1033                agent_id,
1034                name,
1035                expected_generation,
1036            } => {
1037                self.rename_agent(&agent_id, &name, expected_generation)?;
1038                self.agent_details(&agent_id)
1039            }
1040            OwnerOp::FilesStatus => self.files_status(),
1041            OwnerOp::FilesClean { dry_run } => self.files_clean(dry_run),
1042            OwnerOp::HistoryStatus => self.history_status(),
1043            OwnerOp::OwnerHandoffStatus => handoff::status(self.db, &self.state),
1044            OwnerOp::OwnerTransfer { .. } => {
1045                anyhow::bail!("owner transfer requires the authenticated store entry point")
1046            }
1047            OwnerOp::RecoveryChallenge => Ok(serde_json::to_value(
1048                gent_crypto::recovery::RecoveryBaseline::new(&self.state, self.timestamp as u64)?,
1049            )?),
1050            OwnerOp::RecoveryObserve { challenge } => {
1051                let challenge =
1052                    gent_crypto::recovery::RecoveryChallenge::decode(challenge.as_bytes())?;
1053                Ok(serde_json::to_value(self.identity.node.observe_recovery(
1054                    &self.state,
1055                    &challenge,
1056                    self.timestamp as u64,
1057                )?)?)
1058            }
1059            OwnerOp::WorkList { after_message_id } => self.work_list(after_message_id.as_deref()),
1060            OwnerOp::WakeList { after_message_id } => self.wake_list(after_message_id.as_deref()),
1061            OwnerOp::WakeStatus => wake::retention::status(self.db, self.timestamp),
1062            OwnerOp::WakePendingAgents { after } => self.wake_pending_agents(after.as_deref()),
1063            OwnerOp::WakeDirectTurnEvidence {
1064                completed_relay,
1065                agent_credential,
1066                thread_id,
1067                turn,
1068            } => {
1069                let who = self.native_supervisor_agent(&agent_credential, thread_id)?;
1070                self.direct_turn_evidence(&who, thread_id, turn, completed_relay)
1071            }
1072            OwnerOp::BabysitterVerifiedBlockedClaim {
1073                agent_credential,
1074                thread_id,
1075                goal,
1076                turn,
1077                failed_at,
1078                reason,
1079            } => {
1080                let who = self.native_supervisor_agent(&agent_credential, thread_id)?;
1081                self.babysitter_claim(
1082                    &who,
1083                    &goal,
1084                    turn,
1085                    failed_at,
1086                    reason,
1087                    babysitter::Window::VerifiedBlocked,
1088                )
1089            }
1090            OwnerOp::WakeClean { dry_run } => {
1091                wake::retention::clean(self.db, self.timestamp, dry_run)
1092            }
1093            OwnerOp::WakeShow { message_id } => self.wake_show(&message_id),
1094            OwnerOp::WorkShow { message_id } => self.work_show(&message_id),
1095            OwnerOp::WorkReconcile {
1096                message_id,
1097                expect_revision,
1098                resolution,
1099                note,
1100            } => self.work_reconcile(&message_id, expect_revision, resolution, &note),
1101            OwnerOp::HistoryClean { dry_run } => self.history_clean(dry_run),
1102            OwnerOp::TransportStatus => encrypted::ordered::storage::status(self.db),
1103            OwnerOp::TransportClean { dry_run } => {
1104                encrypted::ordered::storage::clean(self.db, dry_run)
1105            }
1106            OwnerOp::Providers => {
1107                let mut providers = BTreeMap::<String, Vec<Agent>>::new();
1108                for agent in self.all_agents()? {
1109                    if !agent.revoked {
1110                        providers
1111                            .entry(agent.provider.clone())
1112                            .or_default()
1113                            .push(agent);
1114                    }
1115                }
1116                Ok(json!(providers))
1117            }
1118            OwnerOp::RelayGrants => Ok(json!({"grants":self.state.state().policy.relay_grants,
1119                "retired":self.state.state().retired_relay_grants,"revision":self.state.checkpoint().revision})),
1120            OwnerOp::RelayAttachments => self.relay_attachments(),
1121            OwnerOp::Configure { request_id, edit } => self.submit_configuration(&request_id, edit),
1122            OwnerOp::ConfigurationRequests { request_id } => match request_id {
1123                Some(id) => self.configuration_status(&id),
1124                None => self.configuration_requests(),
1125            },
1126            OwnerOp::DelegateConfiguration { node_id, allow } => {
1127                if self.state.state().peer.is_some() {
1128                    return self.submit_configuration(
1129                        &uuid::Uuid::new_v4().to_string(),
1130                        ConfigurationEdit::DelegateNode { node_id, allow },
1131                    );
1132                }
1133                let update = self.state.delegate_configuration(
1134                    &*self.identity.signing_owner(self.db)?,
1135                    &node_id,
1136                    allow,
1137                    self.timestamp as u64,
1138                )?;
1139                self.state = self.identity.apply(self.db, update)?;
1140                Ok(
1141                    json!({"applied":true,"revision":self.state.checkpoint().revision,"node_id":node_id,"can_configure":allow}),
1142                )
1143            }
1144            OwnerOp::RemoveNode { node_id } => self.remove_node(&node_id),
1145            OwnerOp::NodeRemovals {
1146                after,
1147                pending_only,
1148            } => self.node_removals(after.as_deref(), pending_only),
1149            OwnerOp::ConfirmNodeRemoval { node_id, revision } => {
1150                self.confirm_node_removal(&node_id, revision)
1151            }
1152            OwnerOp::SetPolicy { policy } => {
1153                let disk = config::load_for_runtime(self.home)?;
1154                ensure!(
1155                    disk.node.id == self.config.node.id
1156                        && disk.cluster.id == self.config.cluster.id,
1157                    "cannot change active identities while daemon runs"
1158                );
1159                self.submit_configuration(
1160                    &uuid::Uuid::new_v4().to_string(),
1161                    ConfigurationEdit::Replace {
1162                        cluster_name: disk.cluster.name,
1163                        node_name: disk.node.name,
1164                        policy,
1165                    },
1166                )
1167            }
1168            OwnerOp::Renew => self
1169                .submit_configuration(&uuid::Uuid::new_v4().to_string(), ConfigurationEdit::Renew),
1170            OwnerOp::RenameNode { name } => self.submit_configuration(
1171                &uuid::Uuid::new_v4().to_string(),
1172                ConfigurationEdit::RenameNode { name },
1173            ),
1174            OwnerOp::PrepareHostedNode { .. } => unreachable!("handled before session"),
1175            OwnerOp::Revoke { agent_id } => self.request_unregister(&agent_id),
1176        }
1177    }
1178
1179    fn native_supervisor_agent(&self, credential: &str, thread: uuid::Uuid) -> Result<Agent> {
1180        ensure!(!thread.is_nil(), "invalid native thread");
1181        let node = self.identity.node.id();
1182        self.state.authorize_node(
1183            node,
1184            &self.identity.node.public_key(),
1185            self.timestamp as u64,
1186        )?;
1187        self.registered_agent(node, &hash(credential))
1188    }
1189
1190    fn registered_agent(&self, node: &str, digest: &str) -> Result<Agent> {
1191        let who = self.db.query_row(
1192            "SELECT id,node_id,name,provider,last_seen,revoked FROM agents WHERE credential_hash=?1",
1193            [digest],
1194            Self::decode_agent,
1195        ).optional()?.context("register this connection first")?;
1196        ensure!(!who.revoked, "registration revoked");
1197        ensure!(
1198            who.node_id == node && self.local_node(node),
1199            "credential belongs to another node"
1200        );
1201        Ok(who)
1202    }
1203
1204    fn agent(
1205        &mut self,
1206        node: &str,
1207        credential: &str,
1208        action: AgentOp,
1209        export_step: files::ExportStep,
1210    ) -> Result<Value> {
1211        ensure!(
1212            credential.len() == 64 && credential.bytes().all(|b| b.is_ascii_hexdigit()),
1213            "invalid registration credential"
1214        );
1215        let digest = hash(credential);
1216        if let AgentOp::Register { name, provider } = &action {
1217            config::label(name)?;
1218            config::label(provider)?;
1219            if !self.db.query_row(
1220                "SELECT EXISTS(SELECT 1 FROM agents WHERE credential_hash=?1)",
1221                [&digest],
1222                |r| r.get::<_, bool>(0),
1223            )? {
1224                let nonce = uuid::Uuid::new_v4();
1225                let agent = gent_crypto::agent_id(node, nonce)?;
1226                self.db.execute("INSERT INTO agents(id,credential_hash,node_id,name,provider,last_seen) VALUES (?1,?2,?3,?4,?5,?6)",params![agent,digest,node,name,provider,self.timestamp])?;
1227                self.db.execute("INSERT INTO network_origins(agent,nonce,legacy,generation) VALUES(?1,?2,NULL,1)",params![agent,nonce.to_string()])?;
1228                self.announce(&agent)?;
1229            }
1230        }
1231        let who = self.registered_agent(node, &digest)?;
1232        if !matches!(
1233            &action,
1234            AgentOp::BabysitterClaim { .. }
1235                | AgentOp::BabysitterChatProbe { .. }
1236                | AgentOp::BabysitterChatClaim { .. }
1237                | AgentOp::BabysitterChatCheck { .. }
1238                | AgentOp::BabysitterChatSubmitted { .. }
1239                | AgentOp::BabysitterCheck { .. }
1240                | AgentOp::BabysitterSubmitted { .. }
1241                | AgentOp::WakePending
1242                | AgentOp::WakeClaim { .. }
1243                | AgentOp::WakeCheck { .. }
1244                | AgentOp::WakeSubmitted { .. }
1245                | AgentOp::WakeDirectClaim { .. }
1246                | AgentOp::WakeDirectPending { .. }
1247                | AgentOp::WakeDirectRead { .. }
1248                | AgentOp::WakeDirectObserve { .. }
1249                | AgentOp::WakeDirectComplete { .. }
1250        ) {
1251            self.db.execute(
1252                "UPDATE agents SET last_seen=?1 WHERE id=?2",
1253                params![self.timestamp, who.id],
1254            )?;
1255        }
1256        match action {
1257            AgentOp::Register { .. } | AgentOp::Identity => self.agent_identity(&who.id),
1258            AgentOp::Rename {
1259                name,
1260                expected_generation,
1261            } => {
1262                self.rename_agent(&who.id, &name, expected_generation)?;
1263                self.agent_identity(&who.id)
1264            }
1265            AgentOp::Babysit { enabled } => self.babysit(&who, enabled),
1266            AgentOp::BabysitterClaim {
1267                goal,
1268                turn,
1269                failed_at,
1270                reason,
1271            } => self.babysitter_claim(
1272                &who,
1273                &goal,
1274                turn,
1275                failed_at,
1276                reason,
1277                babysitter::Window::Routine,
1278            ),
1279            AgentOp::BabysitterCheck { attempt } => {
1280                Ok(json!({"eligible":self.babysitter_check(&who,attempt)?}))
1281            }
1282            AgentOp::BabysitterSubmitted { attempt, scope } => {
1283                self.babysitter_submitted(&who, attempt, scope)
1284            }
1285            AgentOp::BabysitterChatProbe {
1286                turn,
1287                operator,
1288                failed_at,
1289            } => Ok(
1290                json!({"inspect":self.babysitter_chat_probe(&who, turn, operator, failed_at)?,
1291                           "direct_handoff":true}),
1292            ),
1293            AgentOp::BabysitterChatClaim {
1294                turn,
1295                failed_at,
1296                reason,
1297                origin,
1298            } => self.babysitter_chat_claim(&who, turn, failed_at, reason, origin),
1299            AgentOp::BabysitterChatCheck { attempt } => self.babysitter_chat_check(&who, attempt),
1300            AgentOp::BabysitterChatSubmitted { attempt } => {
1301                self.babysitter_chat_submitted(&who, attempt)
1302            }
1303            AgentOp::DashboardGet => self.dashboard_get(&who),
1304            op @ (AgentOp::DashboardDefine { .. }
1305            | AgentOp::DashboardUpdate { .. }
1306            | AgentOp::DashboardDelete { .. }) => self.dashboard_mutate(&who, op),
1307            AgentOp::Agents => self.visible_agents(&who),
1308            AgentOp::Resolve {
1309                name,
1310                node,
1311                provider,
1312            } => self.resolve_agent(Some(&who), &name, node.as_deref(), provider.as_deref()),
1313            AgentOp::HistoryImports => self.recovered_imports(Some(&who)),
1314            AgentOp::HistoryMessages { import_id, after } => {
1315                self.recovered_messages(&who, &import_id, after)
1316            }
1317            AgentOp::HistoryFileRead {
1318                import_id,
1319                message_id,
1320                file_index,
1321                chunk_index,
1322            } => self.recovered_file_read(&who, &import_id, &message_id, file_index, chunk_index),
1323            AgentOp::HistoryFileView {
1324                import_id,
1325                message_id,
1326                file_index,
1327            } => self.recovered_file_view(&who, &import_id, &message_id, file_index),
1328            AgentOp::PermissionCheck { peer } => self.permission_check(&who, &peer),
1329            AgentOp::PermissionAdminCheck { actor, peer } => {
1330                self.permission_admin_check(&who, &actor, &peer)
1331            }
1332            AgentOp::PermissionPreview { changes } => self.permission_preview(&who, &changes),
1333            AgentOp::PermissionApply {
1334                request_id,
1335                changes,
1336            } => self.permission_apply(&who, &request_id, changes),
1337            AgentOp::PermissionRequest { request_id } => self.permission_request(&who, &request_id),
1338            AgentOp::PermissionRuleScopes => self.permission_rule_scopes(&who),
1339            AgentOp::GroupAdminScopes => self.group_admin_scopes(&who),
1340            AgentOp::GroupMembers { group } => self.group_members(&who, &group),
1341            AgentOp::GroupPreview { changes } => self.group_preview(&who, &changes),
1342            AgentOp::GroupApply {
1343                request_id,
1344                changes,
1345            } => self.group_apply(&who, &request_id, changes),
1346            AgentOp::GroupRequest { request_id } => self.permission_request(&who, &request_id),
1347            AgentOp::PermissionRulePreview { changes } => {
1348                self.permission_rule_preview(&who, &changes)
1349            }
1350            AgentOp::PermissionRuleApply {
1351                request_id,
1352                changes,
1353            } => self.permission_rule_apply(&who, &request_id, changes),
1354            AgentOp::RequestIds { count } => self.request_ids(count),
1355            AgentOp::WorkStatus { message_id } => self.work_status(&who, &message_id),
1356            AgentOp::WakeDirectClaim {
1357                message_id,
1358                attempt_id,
1359                target,
1360            } => self.wake_direct_claim(&who, &message_id, &attempt_id, target),
1361            AgentOp::WakeDirectPending { target } => self.wake_direct_pending(&who, &target),
1362            AgentOp::WakeDirectRead {
1363                message_id,
1364                attempt_id,
1365                target,
1366            } => self.wake_direct_read(&who, &message_id, &attempt_id, &target),
1367            AgentOp::WakeDirectObserve {
1368                message_id,
1369                attempt_id,
1370                target,
1371                turn_id,
1372            } => self.wake_direct_observe(&who, &message_id, &attempt_id, &target, &turn_id),
1373            AgentOp::WakeDirectComplete {
1374                message_id,
1375                attempt_id,
1376                target,
1377                turn_id,
1378                text,
1379            } => {
1380                self.wake_direct_complete(&who, &message_id, &attempt_id, &target, (&turn_id, text))
1381            }
1382            AgentOp::WakePending => self.wake_pending(&who),
1383            AgentOp::WakeClaim {
1384                message_id,
1385                attempt_id,
1386                target,
1387            } => self.wake_claim(&who, &message_id, &attempt_id, target),
1388            AgentOp::WakeCheck {
1389                message_id,
1390                attempt_id,
1391                target,
1392            } => self.wake_check(&who, &message_id, &attempt_id, &target),
1393            AgentOp::WakeSubmitted {
1394                message_id,
1395                attempt_id,
1396                submission_id,
1397            } => self.wake_submitted(&who, &message_id, &attempt_id, &submission_id),
1398            AgentOp::WorkBegin {
1399                message_id,
1400                expect_revision,
1401                description,
1402            } => self.work_begin(&who, &message_id, expect_revision, &description),
1403            AgentOp::WorkComplete {
1404                message_id,
1405                expect_revision,
1406                note,
1407            } => self.work_complete(&who, &message_id, expect_revision, &note),
1408            AgentOp::FilePaths => self.file_paths(&who),
1409            AgentOp::FileImport {
1410                request_id,
1411                name,
1412                media_type,
1413            } => self.file_import(&who, &request_id, &name, &media_type),
1414            AgentOp::FileStatus { file_id } => self.file_status(&who, &file_id),
1415            AgentOp::FileReceiveStatus { file } => self.file_receive_status(&who, &file),
1416            AgentOp::FileReceive {
1417                file,
1418                byte_length,
1419                sha256,
1420            } => {
1421                ensure!(
1422                    byte_length <= gent_protocol::file_objects::MAX_FILE_BYTES as u64,
1423                    "file exceeds 32 MiB"
1424                );
1425                ensure!(
1426                    sha256.len() == 64
1427                        && sha256
1428                            .bytes()
1429                            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
1430                    "invalid file digest"
1431                );
1432                let status = self.file_receive_status(&who, &file)?;
1433                ensure!(
1434                    status["state"] != "ready"
1435                        || (status["file"]["byte_length"] == byte_length
1436                            && status["file"]["sha256"] == sha256),
1437                    "request_id already used with different content"
1438                );
1439                Ok(status)
1440            }
1441            AgentOp::FileReceiveData { file, bytes } => self.file_receive(&who, &file, &bytes),
1442            AgentOp::FileRead {
1443                file_id,
1444                chunk_index,
1445            } => self.file_read(&who, &file_id, chunk_index),
1446            AgentOp::FileView { file_id } => self.file_view(&who, &file_id),
1447            AgentOp::FileExport { file_id } => self.file_export(&who, &file_id, export_step),
1448            AgentOp::RelayAttach { target, request_id } => {
1449                self.relay_attach(&who, &target, &request_id)
1450            }
1451            AgentOp::RelayStatus { attachment_id } => self.relay_status(&who, attachment_id),
1452            AgentOp::RelayDetach { attachment_id } => self.relay_detach(&who, &attachment_id),
1453            AgentOp::RelaySend {
1454                attachment_id,
1455                request_id,
1456                text,
1457                files,
1458                file_ids,
1459            } => self.relay_send(&who, &attachment_id, &request_id, (text, files, file_ids)),
1460            AgentOp::RelayTurnStatus {
1461                turn_id,
1462                after_message_id,
1463            } => self.relay_turn_status(&who, &turn_id, after_message_id.as_deref()),
1464            AgentOp::RelayNext => self.relay_next(&who),
1465            AgentOp::RelayTurns { after_turn_id } => {
1466                self.relay_turns(&who, after_turn_id.as_deref())
1467            }
1468            AgentOp::RelayRespond {
1469                turn_id,
1470                request_id,
1471                text,
1472                files,
1473                file_ids,
1474                outcome,
1475            } => self.relay_respond(
1476                &who,
1477                &turn_id,
1478                &request_id,
1479                (text, files, file_ids),
1480                outcome,
1481            ),
1482            AgentOp::RelayCancel {
1483                turn_id,
1484                request_id,
1485            } => self.relay_cancel(&who, &turn_id, &request_id),
1486            AgentOp::Send {
1487                recipient,
1488                request_id,
1489                text,
1490                files,
1491                file_ids,
1492            } => self.send(
1493                &who,
1494                &recipient,
1495                &request_id,
1496                text,
1497                files,
1498                SendContext {
1499                    file_ids,
1500                    ..Default::default()
1501                },
1502            ),
1503            AgentOp::RequestReply {
1504                recipient,
1505                request_id,
1506                text,
1507                files,
1508                file_ids,
1509            } => self.request_reply(&who, &recipient, &request_id, (text, files, file_ids)),
1510            AgentOp::Reply {
1511                message_id,
1512                request_id,
1513                text,
1514                files,
1515                file_ids,
1516            } => {
1517                let parent = self.message(&message_id)?;
1518                ensure!(parent.recipient == who.id, UNAVAILABLE);
1519                if parent.relay.as_ref().is_some_and(|r| {
1520                    r.kind == RelayMessageKind::Request && r.attachment_id == r.turn_id
1521                }) {
1522                    return self.relay_respond(
1523                        &who,
1524                        &message_id,
1525                        &request_id,
1526                        (text, files, file_ids),
1527                        RelayResponseKind::Complete,
1528                    );
1529                }
1530                ensure!(parent.relay.is_none(), "use relay_respond for a relay turn");
1531                self.send(
1532                    &who,
1533                    &parent.sender.clone(),
1534                    &request_id,
1535                    text,
1536                    files,
1537                    SendContext {
1538                        parent: Some(parent),
1539                        relay: None,
1540                        file_ids,
1541                    },
1542                )
1543            }
1544            AgentOp::Inbox => {
1545                let mut statement=self.db.prepare("SELECT payload,acknowledged FROM messages WHERE recipient=?1 AND acknowledged=0 ORDER BY rowid")?;
1546                let rows = statement.query_map([&who.id], |r| {
1547                    Ok((r.get::<_, String>(0)?, r.get::<_, bool>(1)?))
1548                })?;
1549                let mut inbox = Vec::new();
1550                let mut bytes = 0;
1551                for row in rows {
1552                    let (payload, acknowledged) = row?;
1553                    let mut message: Message = serde_json::from_str(&payload)?;
1554                    message.acknowledged = acknowledged;
1555                    if self.deliverable(&message)? && self.relay_inbox_visible(&message)? {
1556                        if inbox.len() >= 50 || bytes + payload.len() > MAX_FRAME_BYTES / 2 {
1557                            break;
1558                        }
1559                        bytes += payload.len();
1560                        self.wake_observe(&who, &message.id)?;
1561                        inbox.push(message);
1562                    }
1563                }
1564                Ok(json!(inbox))
1565            }
1566            AgentOp::Ack { message_id } => self.acknowledge(&who, &message_id),
1567            AgentOp::MessageStatus { message_id } => {
1568                let message = self.message(&message_id)?;
1569                ensure!(
1570                    message.sender == who.id || message.recipient == who.id,
1571                    UNAVAILABLE
1572                );
1573                let state = if message.expires_at <= self.timestamp {
1574                    "expired"
1575                } else if !self.deliverable(&message)?
1576                    || self.db.query_row(
1577                        "SELECT EXISTS(SELECT 1 FROM network_rejections WHERE message=?1)",
1578                        [&message.id],
1579                        |r| r.get::<_, bool>(0),
1580                    )?
1581                {
1582                    "revoked"
1583                } else if message.acknowledged {
1584                    "delivered"
1585                } else {
1586                    "queued"
1587                };
1588                Ok(json!({"message_id":message.id,"state":state}))
1589            }
1590        }
1591    }
1592
1593    fn acknowledge(&self, who: &Agent, message_id: &str) -> Result<Value> {
1594        let message = self.message(message_id)?;
1595        ensure!(
1596            message.recipient == who.id && self.deliverable(&message)?,
1597            UNAVAILABLE
1598        );
1599        let changed = self.db.execute(
1600            "UPDATE messages SET acknowledged=1 WHERE id=?1 AND acknowledged=0",
1601            [message_id],
1602        )?;
1603        let sender = self.get_agent(&message.sender)?;
1604        if changed == 1 {
1605            self.web_state_changed(&sender.node_id)?;
1606        }
1607        if !self.local_node(&sender.node_id) {
1608            self.receipt(
1609                self.state.transport_host(&sender.node_id)?,
1610                message_id,
1611                true,
1612                message.expires_at,
1613            )?;
1614        }
1615        Ok(json!({"acknowledged":true}))
1616    }
1617
1618    fn message(&self, message_id: &str) -> Result<Message> {
1619        let (payload, ack): (String, bool) = self
1620            .db
1621            .query_row(
1622                "SELECT payload,acknowledged FROM messages WHERE id=?1",
1623                [message_id],
1624                |r| Ok((r.get(0)?, r.get(1)?)),
1625            )
1626            .optional()?
1627            .context(UNAVAILABLE)?;
1628        let mut message: Message = serde_json::from_str(&payload)?;
1629        message.acknowledged = ack;
1630        Ok(message)
1631    }
1632    fn deliverable(&self, message: &Message) -> Result<bool> {
1633        if !self.web_message_ready(message)? {
1634            return Ok(false);
1635        }
1636        if message.expires_at <= self.timestamp {
1637            return Ok(false);
1638        }
1639        let a = self.get_agent(&message.sender)?;
1640        let b = self.get_agent(&message.recipient)?;
1641        if !self.relay_authorized(message)? {
1642            return Ok(false);
1643        }
1644        Ok(if message.reply_to.is_some() {
1645            self.config.policy.can_reply(&a, &b)
1646        } else {
1647            self.config.policy.can_open(&a, &b)
1648        })
1649    }
1650
1651    fn send(
1652        &mut self,
1653        sender: &Agent,
1654        recipient_id: &str,
1655        request_id: &str,
1656        text: String,
1657        files: Vec<FilePart>,
1658        context: SendContext,
1659    ) -> Result<Value> {
1660        uuid::Uuid::parse_str(request_id)
1661            .context("request_id must be a UUID; reuse it only when retrying the same message")?;
1662        let SendContext {
1663            parent,
1664            relay,
1665            file_ids,
1666        } = context;
1667        network::validate_contents(&text, &files, file_ids.len())?;
1668        ensure!(
1669            file_ids
1670                .iter()
1671                .collect::<std::collections::BTreeSet<_>>()
1672                .len()
1673                == file_ids.len(),
1674            "duplicate file ID"
1675        );
1676        let reply_to = parent.as_ref().map(|p| p.id.clone());
1677        let fingerprint =
1678            message_fingerprint(recipient_id, &text, &files, &reply_to, &relay, &file_ids)?;
1679        let existing: Option<(String, String)> = self
1680            .db
1681            .query_row(
1682                "SELECT id,fingerprint FROM messages WHERE sender=?1 AND request_id=?2",
1683                params![sender.id, request_id],
1684                |r| Ok((r.get(0)?, r.get(1)?)),
1685            )
1686            .optional()?;
1687        if let Some((message_id, previous)) = existing {
1688            ensure!(
1689                previous == fingerprint,
1690                "request_id already used with different content"
1691            );
1692            return Ok(json!({"message_id":message_id,"duplicate":true}));
1693        }
1694        requests::admit(request_id, self.timestamp)?;
1695        let recipient = self.get_agent(recipient_id)?;
1696        ensure!(sender.id != recipient.id, UNAVAILABLE);
1697        let remote = !self.local_node(&recipient.node_id);
1698        let message_id = crate::messages::message_id(&sender.id, request_id)?;
1699        let timestamp = self.timestamp;
1700        let (exchange_id, expires_at) = if let Some(parent) = parent {
1701            ensure!(
1702                self.config.policy.can_reply(sender, &recipient),
1703                UNAVAILABLE
1704            );
1705            let (a, b, expiry, count): (String, String, i64, u32) = self.db.query_row(
1706                "SELECT a,b,expires_at,count FROM exchanges WHERE id=?1",
1707                [&parent.exchange_id],
1708                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
1709            )?;
1710            ensure!(
1711                (a == sender.id && b == recipient.id) || (b == sender.id && a == recipient.id),
1712                UNAVAILABLE
1713            );
1714            ensure!(expiry > timestamp, "exchange expired");
1715            ensure!(
1716                count < MAX_EXCHANGE_MESSAGES,
1717                "exchange reply limit reached"
1718            );
1719            (parent.exchange_id, expiry)
1720        } else {
1721            ensure!(self.config.policy.can_open(sender, &recipient), UNAVAILABLE);
1722            let mut expiry = timestamp + EXCHANGE_TTL_SECONDS;
1723            if let Some(grant_id) = relay.as_ref().and_then(|relay| relay.grant_id.as_ref()) {
1724                let grant = self
1725                    .config
1726                    .policy
1727                    .relay_grants
1728                    .get(grant_id)
1729                    .context(UNAVAILABLE)?;
1730                expiry = expiry.min(grant.expires_at as i64);
1731            }
1732            (message_id.clone(), expiry)
1733        };
1734        if remote {
1735            let sent: u32 = self.db.query_row(
1736                "SELECT COUNT(*) FROM messages WHERE json_extract(payload,'$.exchange_id')=?1 AND sender=?2",
1737                params![exchange_id, sender.id],
1738                |r| r.get(0),
1739            )?;
1740            ensure!(
1741                sent < MAX_EXCHANGE_MESSAGES / 2,
1742                "remote exchange sender limit reached (16 messages)"
1743            );
1744        }
1745        let attachments = self.seal_attachments(sender, &file_ids, expires_at)?;
1746        let message = Message {
1747            id: message_id,
1748            exchange_id: exchange_id.clone(),
1749            sender: sender.id.clone(),
1750            recipient: recipient.id.clone(),
1751            text,
1752            files,
1753            attachments: attachments
1754                .iter()
1755                .map(|f| f.grant.descriptor().clone())
1756                .collect(),
1757            reply_to,
1758            created_at: timestamp,
1759            expires_at,
1760            acknowledged: false,
1761            relay,
1762        };
1763        self.validate_relay_message(&message)?;
1764        self.validate_local_relay(&message)?;
1765        let tx = self.db;
1766        if message.reply_to.is_none() {
1767            tx.execute(
1768                "INSERT INTO exchanges VALUES (?1,?2,?3,?4,0)",
1769                params![exchange_id, sender.id, recipient.id, expires_at],
1770            )?;
1771        }
1772        ensure!(
1773            tx.execute(
1774                "UPDATE exchanges SET count=count+1 WHERE id=?1 AND count<?2",
1775                params![exchange_id, MAX_EXCHANGE_MESSAGES]
1776            )? == 1,
1777            "exchange reply limit reached"
1778        );
1779        let payload = serde_json::to_string(&message)?;
1780        history::message_capacity(tx, payload.len())?;
1781        tx.execute("INSERT INTO messages(id,sender,recipient,request_id,fingerprint,payload) VALUES (?1,?2,?3,?4,?5,?6)",params![message.id,message.sender,message.recipient,request_id,fingerprint,payload])?;
1782        self.bind_attachments(&message, &attachments)?;
1783        self.record_relay_message(&message)?;
1784        self.web_state_changed(&recipient.node_id)?;
1785        self.gate_web_message(&message)?;
1786        self.save_activity(&sender.id, message.created_at)?;
1787        self.record_gent_message(&sender.id, message.created_at)?;
1788        if !remote {
1789            self.record_gent_message(&recipient.id, message.created_at)?;
1790        }
1791        if remote {
1792            self.record_web_demand(&recipient.node_id, &message.id)?;
1793            self.queue_message(
1794                self.state.transport_host(&recipient.node_id)?,
1795                request_id,
1796                &message,
1797            )?;
1798        }
1799        Ok(json!({"message_id":message.id,"exchange_id":exchange_id,"duplicate":false}))
1800    }
1801}