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