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