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