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                ..
419            }
420        ) || matches!(
421            &request,
422            Request::HostedStatus { .. }
423                | Request::Agent {
424                    action: AgentOp::BabysitterChatProbe { .. },
425                    ..
426                }
427        )) && !projection_pending;
428        let tx = self.db.transaction_with_behavior(if read_only {
429            TransactionBehavior::Deferred
430        } else {
431            TransactionBehavior::Immediate
432        })?;
433        let timestamp = if read_only {
434            requests::diagnostic_clock(&tx, now())?
435        } else {
436            requests::clock(&tx, now())?
437        };
438        let state = self.identity.state(&tx)?;
439        let mut config = self.config.clone();
440        config.policy = state.state().policy.clone();
441        config.cluster.name.clone_from(&state.state().name);
442        if let Some(node) = state.state().nodes.get(self.identity.node.id()) {
443            config.node.name.clone_from(&node.name);
444        }
445        config.applied_revision = Some(state.checkpoint().revision);
446        let mut session = StoreSession {
447            db: &tx,
448            home: &self.home,
449            config,
450            identity: &self.identity,
451            state,
452            timestamp,
453        };
454        let rename = matches!(
455            &request,
456            Request::Owner {
457                action: OwnerOp::RenameAgent { .. },
458                ..
459            }
460        );
461        let owner_request = matches!(&request, Request::Owner { .. });
462        let refresh_nodes = matches!(
463            &request,
464            Request::Owner {
465                action: OwnerOp::RefreshNodes,
466                ..
467            }
468        );
469        let status_request = matches!(
470            &request,
471            Request::Owner {
472                action: OwnerOp::Status,
473                ..
474            }
475        );
476        let mut value = match request {
477            Request::Owner { action, .. } => session.owner(action, &self.sync_health)?,
478            Request::DashboardDelegate {
479                agent,
480                secret,
481                action,
482            } => session.dashboard_delegate(&agent.to_string(), &secret, action)?,
483            Request::Agent { credential, action } => {
484                session.state.authorize_node(
485                    self.identity.node.id(),
486                    &self.identity.node.public_key(),
487                    timestamp as u64,
488                )?;
489                session.agent(self.identity.node.id(), &credential, action, export_step)?
490            }
491            Request::HostedAgent {
492                node_id,
493                gateway_credential,
494                credential,
495                action,
496                epoch,
497            } => {
498                session.check_hosted(&node_id, &gateway_credential)?;
499                hosted::check_epoch(&tx, &node_id, epoch)?;
500                session.require_web_lease(&node_id)?;
501                session.dirty_web(&node_id, &action)?;
502                ensure!(
503                    !matches!(
504                        action,
505                        AgentOp::FilePaths
506                            | AgentOp::FileImport { .. }
507                            | AgentOp::FileExport { .. }
508                    ),
509                    "local filesystem tools are unavailable to hosted chats"
510                );
511                let value = session.agent(&node_id, &credential, action, export_step)?;
512                if epoch.is_some() {
513                    hosted::check_epoch(&tx, &node_id, epoch)?;
514                }
515                value
516            }
517            Request::HostedStatus {
518                node_id,
519                gateway_credential,
520            } => {
521                session.check_hosted(&node_id, &gateway_credential)?;
522                session.hosted_status(&node_id)?
523            }
524        };
525        tx.commit()?;
526        if rename && value["state"] == "queued" {
527            self.rename_wakeup.notify_one();
528        }
529        if refresh_nodes
530            && value.as_array().is_some_and(|nodes| {
531                nodes
532                    .iter()
533                    .any(|n| n["presence"]["probe_started_at"].is_i64())
534            })
535            && self
536                .sync_health
537                .connected
538                .load(std::sync::atomic::Ordering::SeqCst)
539        {
540            self.sync_health.verify_watch.notify_one();
541        }
542        if status_request {
543            value["sync"] = self.synchronization_status()?;
544        }
545        if read_only || (local_only && !projection_pending) {
546            return Ok(value);
547        }
548        // Also wakes directory/message publication after a committed agent RPC.
549        self.sync_wakeup.notify_one();
550        // Filesystem projection is retryable after the authoritative commit.
551        // A caller must not interpret a projection failure as an unapplied edit.
552        let projected = self.project_config();
553        if owner_request
554            && (value.get("applied") == Some(&Value::Bool(true))
555                || value.get("config_saved").is_some())
556        {
557            value["config_saved"] = json!(projected.is_ok());
558            if let Err(error) = projected {
559                value["config_error"] = json!(error.to_string());
560            }
561        }
562        Ok(value)
563    }
564
565    fn project_config(&mut self) -> Result<()> {
566        let tx = self
567            .db
568            .transaction_with_behavior(TransactionBehavior::Immediate)?;
569        runtime::project(&self.home, &tx, &self.identity)?;
570        tx.commit()?;
571        Ok(())
572    }
573
574    /// The owner daemon renews its lease without requiring a chat turn.
575    /// Chat RPCs never bypass expiry or trigger a renewal themselves.
576    pub fn maintain(&mut self) -> Result<()> {
577        // Local cleanup remains available after membership/lease loss.
578        self.clean_invitations()?;
579        self.clean_files()?;
580        self.clean_history()?;
581        self.clean_wake()?;
582        {
583            let tx = self
584                .db
585                .transaction_with_behavior(TransactionBehavior::Immediate)?;
586            configuration::pending::recover(&tx, self.identity.node.id())?;
587            chat_rename::clean(
588                &tx,
589                requests::clock(&tx, now())?,
590                &self.identity.state(&tx)?,
591            )?;
592            encrypted::ordered::storage::clean(&tx, false)?;
593            tx.commit()?;
594        }
595        let timestamp = now() as u64;
596        let tx = self
597            .db
598            .transaction_with_behavior(TransactionBehavior::Immediate)?;
599        let state = self.identity.state(&tx)?;
600        ensure!(
601            state
602                .state()
603                .nodes
604                .get(self.identity.node.id())
605                .is_some_and(|n| n.signing_key == self.identity.node.public_key()),
606            "local node is no longer enrolled"
607        );
608        crate::file_objects::Objects::new(&tx, timestamp)?.reap()?;
609        let renew = !self.identity.legacy_signing_fenced()
610            && self.identity.legacy_service_checked
611            && self.identity.is_current_owner(&state)
612            && !handoff::frozen(&tx, &state)?
613            && state.state().expires_at.saturating_sub(timestamp) <= 6 * 60 * 60;
614        if renew {
615            let update = state.renew(&*self.identity.signing_owner(&tx)?, timestamp)?;
616            self.identity.apply(&tx, update)?;
617        }
618        tx.commit()?;
619        if renew {
620            self.sync_wakeup.notify_one();
621        }
622        self.project_config()?;
623        self.reconcile_configuration()
624    }
625
626    /// Trusted enrollment API. The supplied authority must already be verified
627    /// through protected pairing. It installs no owner signing secret.
628    pub fn install_joined(
629        home: &Path,
630        node: &gent_crypto::NodeIdentity,
631        state: &VerifiedState,
632    ) -> Result<()> {
633        runtime::install_joined(home, node, state)
634    }
635
636    pub(crate) fn relay_settings(&self) -> Option<(config::RelayConfig, PathBuf)> {
637        self.config
638            .relay
639            .clone()
640            .map(|relay| (relay, self.home.clone()))
641    }
642    pub(crate) fn sync_streams(&self) -> Result<Vec<crate::sync::Stream>> {
643        if self.identity.state(&self.db)?.state().peer.is_some() {
644            return self.data_streams();
645        }
646        let mut streams: Vec<_> =
647            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?
648                .configuration_streams(now() as u64)?
649                .into_iter()
650                .map(|s| crate::sync::Stream {
651                    group: s.group,
652                    outgoing: s.outgoing,
653                    configuration: true,
654                })
655                .collect();
656        streams.extend(self.data_streams()?);
657        Ok(streams)
658    }
659    pub(crate) fn sync_pending_groups(
660        &self,
661        streams: &[crate::sync::Stream],
662    ) -> Result<crate::sync::MailboxWork> {
663        let mut work = crate::sync::MailboxWork::default();
664        let mut pending = self.db.prepare(
665            "SELECT s.group_id,s.head>=COALESCE(u.next_sequence,0)
666             FROM streams s LEFT JOIN stream_relay_upload u USING(group_id)
667             LEFT JOIN stream_confirmed c USING(group_id)
668             WHERE s.writer=?1 AND s.head>COALESCE(c.sequence,-1)",
669        )?;
670        let mut rows = pending.query([self.identity.node.id()])?;
671        while let Some(row) = rows.next()? {
672            let group: Vec<u8> = row.get(0)?;
673            work.unconfirmed.insert(group.clone());
674            if row.get::<_, bool>(1)? {
675                work.ready.insert(group);
676            }
677        }
678        let local = self
679            .db
680            .prepare(
681                "SELECT group_id FROM owner_deliveries WHERE next<parts
682             UNION SELECT s.group_id FROM streams s JOIN stream_pending p
683               ON p.group_id=s.group_id AND p.sequence=s.head+1",
684            )?
685            .query_map([], |r| r.get(0))?
686            .collect::<rusqlite::Result<Vec<Vec<u8>>>>()?;
687        work.ready.extend(local);
688        self.add_ready_network_groups(&mut work.ready)?;
689
690        // An unpublished legacy configuration revision is work even before
691        // its first fragment has a stream position. Old owner epochs stop at
692        // their signed handoff baseline.
693        let writers: BTreeSet<_> = streams
694            .iter()
695            .filter(|s| s.configuration && s.outgoing)
696            .map(|s| s.group.as_slice())
697            .collect();
698        if writers.is_empty() {
699            return Ok(work);
700        }
701        let state = self.identity.state(&self.db)?;
702        let mut query = self.db.prepare(
703            "SELECT c.group_id,c.grant,h.revision FROM configuration_streams c
704             JOIN streams s USING(group_id) JOIN authority_history h ON h.revision=c.revision+1
705             WHERE s.writer=?1",
706        )?;
707        let mut rows = query.query([self.identity.node.id()])?;
708        while let Some(row) = rows.next()? {
709            let group: Vec<u8> = row.get(0)?;
710            if !writers.contains(group.as_slice()) {
711                continue;
712            }
713            let grant = gent_crypto::SignedConfigurationGrant::decode(&row.get::<_, Vec<u8>>(1)?)?;
714            let limit = encrypted::ordered::configuration::publication_limit(&grant, &state);
715            let revision: u64 = row.get(2)?;
716            if limit.is_none_or(|last| revision <= last) {
717                work.ready.insert(group);
718            }
719        }
720        Ok(work)
721    }
722
723    /// A relay can roll back its queue or lose a successful PUT response.
724    /// Replay from the lower position, excluding only the verified prefix.
725    pub(crate) fn relay_upload_start(
726        &self,
727        group: &[u8],
728        relay_next: u64,
729        confirmed_next: u64,
730    ) -> Result<u64> {
731        let (local_next, uploaded): (u64, u64) = self.db.query_row(
732            "SELECT s.head+1,COALESCE(u.next_sequence,0) FROM streams s
733             LEFT JOIN stream_relay_upload u USING(group_id) WHERE s.group_id=?1 AND s.writer=?2",
734            params![group, self.identity.node.id()],
735            |r| Ok((r.get(0)?, r.get(1)?)),
736        )?;
737        ensure!(
738            relay_next <= local_next,
739            "relay position exceeds local history"
740        );
741        if relay_next < uploaded {
742            self.record_relay_upload(group, relay_next)?;
743        }
744        Ok(uploaded.min(relay_next).max(confirmed_next))
745    }
746
747    pub(crate) fn record_relay_upload(&self, group: &[u8], next: u64) -> Result<()> {
748        self.db.execute(
749            "INSERT INTO stream_relay_upload(group_id,next_sequence) VALUES(?1,?2)
750             ON CONFLICT(group_id) DO UPDATE SET next_sequence=excluded.next_sequence",
751            params![group, next],
752        )?;
753        Ok(())
754    }
755    pub(crate) fn sync_prepare(&self, group: &[u8]) -> Result<()> {
756        let mut endpoint =
757            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
758        let timestamp = now() as u64;
759        if endpoint
760            .prepare_configuration(group, None, timestamp)?
761            .is_none()
762        {
763            endpoint.prepare_owner_handoff(group, timestamp)?;
764        }
765        Ok(())
766    }
767
768    pub(crate) fn transport_receipt(
769        &self,
770        group: &[u8],
771        configuration: bool,
772    ) -> Result<gent_crypto::stream::Receipt> {
773        if !configuration {
774            self.data_peer(&self.db, group, false)?;
775        }
776        encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?
777            .receipt(group, now() as u64)
778    }
779
780    pub(crate) fn transport_confirm(
781        &self,
782        group: &[u8],
783        configuration: bool,
784        receipt: Option<&gent_crypto::stream::Receipt>,
785    ) -> Result<Option<gent_crypto::stream::Receipt>> {
786        Ok(self
787            .transport_confirmation(group, configuration, receipt)?
788            .0)
789    }
790
791    /// The flag records a newly advanced durable checkpoint, excluding cached or replayed ACKs.
792    pub(crate) fn transport_confirmation(
793        &self,
794        group: &[u8],
795        configuration: bool,
796        receipt: Option<&gent_crypto::stream::Receipt>,
797    ) -> Result<(Option<gent_crypto::stream::Receipt>, bool)> {
798        let mut endpoint =
799            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
800        let reader = if configuration {
801            endpoint.configuration_reader(group)?
802        } else {
803            self.data_peer(&self.db, group, true)?
804        };
805        if let Some(receipt) = receipt {
806            ensure!(
807                receipt.group() == group,
808                "checkpoint belongs to another stream"
809            );
810            return endpoint
811                .confirm_and_get(receipt, &reader, now() as u64)
812                .map(|(receipt, advanced)| (Some(receipt), advanced));
813        }
814        Ok((endpoint.confirmed_receipt(group, now() as u64)?, false))
815    }
816    pub(crate) fn sync_outgoing(
817        &self,
818        group: &[u8],
819        next: u64,
820    ) -> Result<Option<gent_crypto::stream::Packet>> {
821        let mut endpoint =
822            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
823        let timestamp = now() as u64;
824        let status = endpoint.configuration_status(group, timestamp)?;
825        ensure!(next <= status.next, "relay position exceeds local history");
826        Ok(endpoint
827            .configuration_outbox(group, next.checked_sub(1), 1, timestamp)?
828            .pop())
829    }
830    pub(crate) fn sync_next(&mut self, group: &[u8]) -> Result<u64> {
831        let mut endpoint =
832            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
833        let timestamp = now() as u64;
834        // A restart may find a packet committed to the receive buffer before
835        // its authority transaction ran. Apply it without requiring the relay.
836        let pending = endpoint.drain_configuration(group, 1, timestamp)?;
837        let next = endpoint
838            .configuration_status(group, timestamp)
839            .map(|status| status.next);
840        drop(endpoint);
841        if !pending.is_empty() {
842            self.project_config()?;
843            self.reconcile_configuration()?;
844            self.sync_wakeup.notify_one();
845        }
846        next
847    }
848    pub(crate) fn sync_receive(&mut self, packet: &gent_crypto::stream::Packet) -> Result<()> {
849        let mut endpoint =
850            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
851        let timestamp = now() as u64;
852        endpoint.stage_configuration(packet, timestamp)?;
853        endpoint.drain_configuration(packet.group(), 1, timestamp)?;
854        self.sync_wakeup.notify_one();
855        self.project_config()?;
856        self.reconcile_configuration()
857    }
858}
859
860struct StoreSession<'a> {
861    db: &'a Connection,
862    home: &'a Path,
863    config: Config,
864    identity: &'a Identity,
865    state: VerifiedState,
866    timestamp: i64,
867}
868
869#[derive(Default)]
870struct SendContext {
871    parent: Option<Message>,
872    relay: Option<RelayMessage>,
873    file_ids: Vec<String>,
874}
875
876fn message_fingerprint(
877    recipient: &str,
878    text: &str,
879    files: &[FilePart],
880    reply_to: &Option<String>,
881    relay: &Option<RelayMessage>,
882    file_ids: &[String],
883) -> Result<String> {
884    let mut value = json!({"recipient":recipient,"text":text,"files":files,"reply_to":reply_to});
885    // Preserve exact retry fingerprints for pre-relay messages.
886    if let Some(relay) = relay {
887        value["relay"] = json!(relay);
888    }
889    if !file_ids.is_empty() {
890        value["file_ids"] = json!(file_ids);
891    }
892    Ok(hash(&serde_json::to_string(&value)?))
893}
894impl StoreSession<'_> {
895    fn decode_agent(row: &rusqlite::Row<'_>) -> rusqlite::Result<Agent> {
896        Ok(Agent {
897            id: row.get(0)?,
898            node_id: row.get(1)?,
899            name: row.get(2)?,
900            provider: row.get(3)?,
901            last_seen: row.get(4)?,
902            revoked: row.get(5)?,
903        })
904    }
905    fn get_agent(&self, id: &str) -> Result<Agent> {
906        let mut agent = self
907            .db
908            .query_row(
909                "SELECT id,node_id,name,provider,last_seen,revoked FROM agents WHERE id=?1",
910                [id],
911                Self::decode_agent,
912            )
913            .optional()?
914            .context(UNAVAILABLE)?;
915        agent.revoked |= !self.state.state().nodes.contains_key(&agent.node_id);
916        Ok(agent)
917    }
918    fn all_agents(&self) -> Result<Vec<Agent>> {
919        let mut agents = self
920            .db
921            .prepare("SELECT id,node_id,name,provider,last_seen,revoked FROM agents ORDER BY id")?
922            .query_map([], Self::decode_agent)?
923            .collect::<Result<Vec<_>, _>>()?;
924        for agent in &mut agents {
925            agent.revoked |= !self.state.state().nodes.contains_key(&agent.node_id);
926        }
927        Ok(agents)
928    }
929    fn owner(&mut self, action: OwnerOp, health: &crate::sync::health::Health) -> Result<Value> {
930        match action {
931            OwnerOp::WebDeliveryDemand { node_id } => self.web_delivery_demand(&node_id),
932            OwnerOp::WebDeliveryChecked {
933                node_id,
934                message_id,
935            } => {
936                let cleared = self.db.execute(
937                    "DELETE FROM web_delivery_demand WHERE node=?1 AND message=?2",
938                    params![node_id, message_id],
939                )?;
940                Ok(json!({"cleared":cleared==1}))
941            }
942            OwnerOp::WebAdmission { node_id, body_hash } => self.web_admission(&node_id, body_hash),
943            OwnerOp::WebCheckpoint { node_id } => self.web_checkpoint(&node_id),
944            OwnerOp::WebLease { node_id, seconds } => self.web_lease(&node_id, seconds),
945            OwnerOp::WebGrant {
946                node_id,
947                epoch,
948                expires_at,
949            } => self.web_grant(&node_id, epoch, expires_at),
950            OwnerOp::WebCommit {
951                node_id,
952                revision,
953                epoch,
954            } => self.web_commit(&node_id, revision, epoch),
955            OwnerOp::RestoreWebNode { .. } => unreachable!("handled before session"),
956            OwnerOp::NodeInvite {
957                request_id,
958                name,
959                can_configure,
960                activate,
961            } => self.request_node_invite(&request_id, &name, can_configure, activate),
962            OwnerOp::AgentRecover {
963                directory,
964                manifest_sha256,
965                source_agent,
966                agent_credential,
967                name,
968                provider,
969            } => {
970                let registered = self.agent(
971                    self.identity.node.id(),
972                    &agent_credential,
973                    AgentOp::Register {
974                        name: name.clone(),
975                        provider: provider.clone(),
976                    },
977                    files::ExportStep::Reserve,
978                )?;
979                let id = registered["agent"]["id"]
980                    .as_str()
981                    .context("missing recovered chat identity")?;
982                let agent = self.get_agent(id)?;
983                ensure!(
984                    agent.name == name && agent.provider == provider,
985                    "recovery registration arguments changed"
986                );
987                let history = self.recovered_import(
988                    Path::new(&directory),
989                    &manifest_sha256,
990                    &source_agent,
991                    id,
992                    None,
993                )?;
994                Ok(
995                    json!({"agent":agent,"history":history,"source_agent":source_agent,
996                    "scope":"fresh local registration with assigned history; old credentials, peer permissions and pending work are not restored"}),
997                )
998            }
999            OwnerOp::HistoryImports => self.recovered_imports(None),
1000            OwnerOp::HistoryImport {
1001                directory,
1002                manifest_sha256,
1003                source_agent,
1004                target_agent,
1005                restore_revision,
1006            } => self.recovered_import(
1007                Path::new(&directory),
1008                &manifest_sha256,
1009                &source_agent,
1010                &target_agent,
1011                restore_revision,
1012            ),
1013            OwnerOp::HistoryRemove {
1014                import_id,
1015                expected_revision,
1016            } => self.recovered_remove(&import_id, expected_revision),
1017            OwnerOp::Pair { .. }
1018            | OwnerOp::Invitation { .. }
1019            | OwnerOp::Diagnose
1020            | OwnerOp::PreparePeerConfiguration => {
1021                anyhow::bail!("pairing must use its owner-authenticated entry point")
1022            }
1023            OwnerOp::Stats | OwnerOp::RefreshStats => {
1024                anyhow::bail!("statistics require the owner statistics entry point")
1025            }
1026            OwnerOp::Status => Ok(
1027                json!({"process_id":std::process::id(),"node":self.config.node,"cluster":self.config.cluster,"transport":"local_unix_socket","remote_ready":self.remote_ready()?,
1028                    "release_channel":self.state.state().release_channel,
1029                    "can_set_release_channel":self.identity.is_current_owner(&self.state) || self.identity.has_configuration_grant(&self.state),
1030                    "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)?}),
1031            ),
1032            OwnerOp::Groups { name } => match name {
1033                Some(name) => Ok(
1034                    json!({"name":name,"members":self.config.policy.groups.get(&name).context("unknown group")?}),
1035                ),
1036                None => Ok(json!(self.config.policy.groups)),
1037            },
1038            OwnerOp::GroupAdmins => Ok(
1039                json!({"grants":self.config.policy.group_admin_grants,"retired":self.state.state().retired_admin_grants}),
1040            ),
1041            OwnerOp::GroupAdminHistory {
1042                administrator,
1043                before,
1044            } => self.administration_history(administrator.as_deref(), before, true),
1045            OwnerOp::NotificationPending { scope } => self.pending_notices(&scope),
1046            OwnerOp::NotificationPut { notice, scope } => self.enqueue_notice(&notice, scope),
1047            OwnerOp::NotificationSent { id } => {
1048                self.db
1049                    .execute("DELETE FROM account_outbox WHERE id=?1", [id.to_string()])?;
1050                Ok(json!({}))
1051            }
1052            OwnerOp::DashboardRemoteHtml { .. } => {
1053                anyhow::bail!("remote board view requires live transport")
1054            }
1055            OwnerOp::DashboardGrant { agent, action } => {
1056                self.authorize_dashboard_grant_admin(self.identity.node.id())?;
1057                self.dashboard_grant(&agent.to_string(), action)
1058            }
1059            OwnerOp::Dashboards { after } => self.dashboards(after.as_deref()),
1060            OwnerOp::DashboardClick {
1061                agent,
1062                revision,
1063                widget,
1064                request_id,
1065            } => self.dashboard_action(&agent, revision, Some(&widget), &request_id),
1066            OwnerOp::DashboardRefresh {
1067                agent,
1068                revision,
1069                request_id,
1070            } => self.dashboard_action(&agent, revision, None, &request_id),
1071            OwnerOp::PermissionRules => Ok(json!({"rules":self.state.state().policy.rules,
1072                "groups":self.state.state().policy.groups.keys().collect::<Vec<_>>()})),
1073            OwnerOp::PermissionExplain { actor, peer } => self.permission_explain(&actor, &peer),
1074            OwnerOp::PermissionAdmins => {
1075                Ok(json!({"grants":self.state.state().policy.admin_grants,
1076                "retired":self.state.state().retired_admin_grants,"revision":self.state.checkpoint().revision}))
1077            }
1078            OwnerOp::PermissionAdminHistory {
1079                administrator,
1080                before,
1081            } => self.permission_admin_history(administrator.as_deref(), before),
1082            OwnerOp::Nodes => self.nodes(health),
1083            OwnerOp::RefreshNodes => self.refresh_nodes(health),
1084            OwnerOp::Agents => Ok(serde_json::to_value(self.directory(None)?)?),
1085            OwnerOp::Resolve {
1086                name,
1087                node,
1088                provider,
1089            } => self.resolve_agent(None, &name, node.as_deref(), provider.as_deref()),
1090            OwnerOp::NativeMessageDates => self.local_native_message_dates(),
1091            OwnerOp::ObserveActivity {
1092                agent_id,
1093                last_activity_at,
1094                last_native_message_at,
1095            } => self.observe_activity(&agent_id, last_activity_at, last_native_message_at),
1096            OwnerOp::ClearRetiredAgents { dry_run } => self.clear_retired_agents(dry_run),
1097            OwnerOp::Agent { agent_id } => self.agent_details(&agent_id),
1098            OwnerOp::RenameAgent {
1099                agent_id,
1100                name,
1101                expected_generation,
1102            } => self.request_rename(&agent_id, &name, expected_generation),
1103            OwnerOp::FilesStatus => self.files_status(),
1104            OwnerOp::FilesClean { dry_run } => self.files_clean(dry_run),
1105            OwnerOp::HistoryStatus => self.history_status(),
1106            OwnerOp::OwnerHandoffStatus => handoff::status(self.db, &self.state),
1107            OwnerOp::OwnerTransfer { .. } => {
1108                anyhow::bail!("owner transfer requires the authenticated store entry point")
1109            }
1110            OwnerOp::RecoveryChallenge => Ok(serde_json::to_value(
1111                gent_crypto::recovery::RecoveryBaseline::new(&self.state, self.timestamp as u64)?,
1112            )?),
1113            OwnerOp::RecoveryObserve { challenge } => {
1114                let challenge =
1115                    gent_crypto::recovery::RecoveryChallenge::decode(challenge.as_bytes())?;
1116                Ok(serde_json::to_value(self.identity.node.observe_recovery(
1117                    &self.state,
1118                    &challenge,
1119                    self.timestamp as u64,
1120                )?)?)
1121            }
1122            OwnerOp::WorkList { after_message_id } => self.work_list(after_message_id.as_deref()),
1123            OwnerOp::WakeList { after_message_id } => self.wake_list(after_message_id.as_deref()),
1124            OwnerOp::WakeStatus => wake::retention::status(self.db, self.timestamp),
1125            OwnerOp::WakePendingAgents { after } => self.wake_pending_agents(after.as_deref()),
1126            OwnerOp::WakeDirectTurnEvidence {
1127                completed_relay,
1128                agent_credential,
1129                thread_id,
1130                turn,
1131            } => {
1132                let who = self.native_supervisor_agent(&agent_credential, thread_id)?;
1133                self.direct_turn_evidence(&who, thread_id, turn, completed_relay)
1134            }
1135            OwnerOp::BabysitterVerifiedBlockedClaim {
1136                agent_credential,
1137                thread_id,
1138                goal,
1139                turn,
1140                failed_at,
1141                reason,
1142            } => {
1143                let who = self.native_supervisor_agent(&agent_credential, thread_id)?;
1144                self.babysitter_claim(
1145                    &who,
1146                    &goal,
1147                    turn,
1148                    failed_at,
1149                    reason,
1150                    babysitter::Window::VerifiedBlocked,
1151                )
1152            }
1153            OwnerOp::WakeClean { dry_run } => {
1154                wake::retention::clean(self.db, self.timestamp, dry_run)
1155            }
1156            OwnerOp::WakeShow { message_id } => self.wake_show(&message_id),
1157            OwnerOp::WorkShow { message_id } => self.work_show(&message_id),
1158            OwnerOp::WorkReconcile {
1159                message_id,
1160                expect_revision,
1161                resolution,
1162                note,
1163            } => self.work_reconcile(&message_id, expect_revision, resolution, &note),
1164            OwnerOp::HistoryClean { dry_run } => self.history_clean(dry_run),
1165            OwnerOp::TransportStatus => encrypted::ordered::storage::status(self.db),
1166            OwnerOp::TransportClean { dry_run } => {
1167                encrypted::ordered::storage::clean(self.db, dry_run)
1168            }
1169            OwnerOp::Providers => {
1170                let mut providers = BTreeMap::<String, Vec<Agent>>::new();
1171                for agent in self.all_agents()? {
1172                    if !agent.revoked {
1173                        providers
1174                            .entry(agent.provider.clone())
1175                            .or_default()
1176                            .push(agent);
1177                    }
1178                }
1179                Ok(json!(providers))
1180            }
1181            OwnerOp::RelayGrants => Ok(json!({"grants":self.state.state().policy.relay_grants,
1182                "retired":self.state.state().retired_relay_grants,"revision":self.state.checkpoint().revision})),
1183            OwnerOp::RelayAttachments => self.relay_attachments(),
1184            OwnerOp::Configure { request_id, edit } => self.submit_configuration(&request_id, edit),
1185            OwnerOp::ConfigurationRequests { request_id } => match request_id {
1186                Some(id) => self.configuration_status(&id),
1187                None => self.configuration_requests(),
1188            },
1189            OwnerOp::DelegateConfiguration { node_id, allow } => {
1190                if self.state.state().peer.is_some() {
1191                    return self.submit_configuration(
1192                        &uuid::Uuid::new_v4().to_string(),
1193                        ConfigurationEdit::DelegateNode { node_id, allow },
1194                    );
1195                }
1196                let update = self.state.delegate_configuration(
1197                    &*self.identity.signing_owner(self.db)?,
1198                    &node_id,
1199                    allow,
1200                    self.timestamp as u64,
1201                )?;
1202                self.state = self.identity.apply(self.db, update)?;
1203                Ok(
1204                    json!({"applied":true,"revision":self.state.checkpoint().revision,"node_id":node_id,"can_configure":allow}),
1205                )
1206            }
1207            OwnerOp::RemoveNode { node_id } => self.remove_node(&node_id),
1208            OwnerOp::NodeRemovals {
1209                after,
1210                pending_only,
1211            } => self.node_removals(after.as_deref(), pending_only),
1212            OwnerOp::ConfirmNodeRemoval { node_id, revision } => {
1213                self.confirm_node_removal(&node_id, revision)
1214            }
1215            OwnerOp::SetPolicy { policy } => {
1216                let disk = config::load_for_runtime(self.home)?;
1217                ensure!(
1218                    disk.node.id == self.config.node.id
1219                        && disk.cluster.id == self.config.cluster.id,
1220                    "cannot change active identities while daemon runs"
1221                );
1222                self.submit_configuration(
1223                    &uuid::Uuid::new_v4().to_string(),
1224                    ConfigurationEdit::Replace {
1225                        cluster_name: disk.cluster.name,
1226                        node_name: disk.node.name,
1227                        policy,
1228                    },
1229                )
1230            }
1231            OwnerOp::Renew => self
1232                .submit_configuration(&uuid::Uuid::new_v4().to_string(), ConfigurationEdit::Renew),
1233            OwnerOp::RenameNode { name } => self.submit_configuration(
1234                &uuid::Uuid::new_v4().to_string(),
1235                ConfigurationEdit::RenameNode { name },
1236            ),
1237            OwnerOp::PrepareHostedNode { .. } => unreachable!("handled before session"),
1238            OwnerOp::Revoke { agent_id } => self.request_unregister(&agent_id),
1239        }
1240    }
1241
1242    fn native_supervisor_agent(&self, credential: &str, thread: uuid::Uuid) -> Result<Agent> {
1243        ensure!(!thread.is_nil(), "invalid native thread");
1244        let node = self.identity.node.id();
1245        self.state.authorize_node(
1246            node,
1247            &self.identity.node.public_key(),
1248            self.timestamp as u64,
1249        )?;
1250        self.registered_agent(node, &hash(credential))
1251    }
1252
1253    fn registered_agent(&self, node: &str, digest: &str) -> Result<Agent> {
1254        let who = self.db.query_row(
1255            "SELECT id,node_id,name,provider,last_seen,revoked FROM agents WHERE credential_hash=?1",
1256            [digest],
1257            Self::decode_agent,
1258        ).optional()?.context("register this connection first")?;
1259        ensure!(!who.revoked, "registration revoked");
1260        ensure!(
1261            who.node_id == node && self.local_node(node),
1262            "credential belongs to another node"
1263        );
1264        Ok(who)
1265    }
1266
1267    fn agent(
1268        &mut self,
1269        node: &str,
1270        credential: &str,
1271        action: AgentOp,
1272        export_step: files::ExportStep,
1273    ) -> Result<Value> {
1274        ensure!(
1275            credential.len() == 64 && credential.bytes().all(|b| b.is_ascii_hexdigit()),
1276            "invalid registration credential"
1277        );
1278        let digest = hash(credential);
1279        if let AgentOp::Register { name, provider } = &action {
1280            config::label(name)?;
1281            config::label(provider)?;
1282            if !self.db.query_row(
1283                "SELECT EXISTS(SELECT 1 FROM agents WHERE credential_hash=?1)",
1284                [&digest],
1285                |r| r.get::<_, bool>(0),
1286            )? {
1287                let nonce = uuid::Uuid::new_v4();
1288                let agent = gent_crypto::agent_id(node, nonce)?;
1289                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])?;
1290                self.db.execute("INSERT INTO network_origins(agent,nonce,legacy,generation) VALUES(?1,?2,NULL,1)",params![agent,nonce.to_string()])?;
1291                self.announce(&agent)?;
1292            }
1293        }
1294        let who = self.registered_agent(node, &digest)?;
1295        if !matches!(
1296            &action,
1297            AgentOp::BabysitterClaim { .. }
1298                | AgentOp::BabysitterChatProbe { .. }
1299                | AgentOp::BabysitterChatClaim { .. }
1300                | AgentOp::BabysitterChatCheck { .. }
1301                | AgentOp::BabysitterChatSubmitted { .. }
1302                | AgentOp::BabysitterCheck { .. }
1303                | AgentOp::BabysitterSubmitted { .. }
1304                | AgentOp::WakePending
1305                | AgentOp::WakeClaim { .. }
1306                | AgentOp::WakeCheck { .. }
1307                | AgentOp::WakeSubmitted { .. }
1308                | AgentOp::WakeDirectClaim { .. }
1309                | AgentOp::WakeDirectPending { .. }
1310                | AgentOp::WakeDirectRead { .. }
1311                | AgentOp::WakeDirectObserve { .. }
1312                | AgentOp::WakeDirectComplete { .. }
1313        ) {
1314            self.db.execute(
1315                "UPDATE agents SET last_seen=?1 WHERE id=?2",
1316                params![self.timestamp, who.id],
1317            )?;
1318        }
1319        match action {
1320            AgentOp::Register { .. } | AgentOp::Identity => self.agent_identity(&who.id),
1321            AgentOp::Rename {
1322                name,
1323                expected_generation,
1324            } => {
1325                self.rename_agent(&who.id, &name, expected_generation)?;
1326                self.agent_identity(&who.id)
1327            }
1328            AgentOp::Babysit { enabled } => self.babysit(&who, enabled),
1329            AgentOp::BabysitterClaim {
1330                goal,
1331                turn,
1332                failed_at,
1333                reason,
1334            } => self.babysitter_claim(
1335                &who,
1336                &goal,
1337                turn,
1338                failed_at,
1339                reason,
1340                babysitter::Window::Routine,
1341            ),
1342            AgentOp::BabysitterCheck { attempt } => {
1343                Ok(json!({"eligible":self.babysitter_check(&who,attempt)?}))
1344            }
1345            AgentOp::BabysitterSubmitted { attempt, scope } => {
1346                self.babysitter_submitted(&who, attempt, scope)
1347            }
1348            AgentOp::BabysitterChatProbe {
1349                turn,
1350                operator,
1351                failed_at,
1352            } => Ok(
1353                json!({"inspect":self.babysitter_chat_probe(&who, turn, operator, failed_at)?,
1354                           "direct_handoff":true}),
1355            ),
1356            AgentOp::BabysitterChatClaim {
1357                turn,
1358                failed_at,
1359                reason,
1360                origin,
1361            } => self.babysitter_chat_claim(&who, turn, failed_at, reason, origin),
1362            AgentOp::BabysitterChatCheck { attempt } => self.babysitter_chat_check(&who, attempt),
1363            AgentOp::BabysitterChatSubmitted { attempt } => {
1364                self.babysitter_chat_submitted(&who, attempt)
1365            }
1366            AgentOp::DashboardGet => self.dashboard_get(&who),
1367            op @ (AgentOp::DashboardPublish { .. }
1368            | AgentOp::DashboardDefine { .. }
1369            | AgentOp::DashboardAttachHtml { .. }
1370            | AgentOp::DashboardUpdate { .. }
1371            | AgentOp::DashboardDelete { .. }) => self.dashboard_mutate(&who, op),
1372            AgentOp::Agents => self.visible_agents(&who),
1373            AgentOp::Resolve {
1374                name,
1375                node,
1376                provider,
1377            } => self.resolve_agent(Some(&who), &name, node.as_deref(), provider.as_deref()),
1378            AgentOp::HistoryImports => self.recovered_imports(Some(&who)),
1379            AgentOp::HistoryMessages { import_id, after } => {
1380                self.recovered_messages(&who, &import_id, after)
1381            }
1382            AgentOp::HistoryFileRead {
1383                import_id,
1384                message_id,
1385                file_index,
1386                chunk_index,
1387            } => self.recovered_file_read(&who, &import_id, &message_id, file_index, chunk_index),
1388            AgentOp::HistoryFileView {
1389                import_id,
1390                message_id,
1391                file_index,
1392            } => self.recovered_file_view(&who, &import_id, &message_id, file_index),
1393            AgentOp::PermissionCheck { peer } => self.permission_check(&who, &peer),
1394            AgentOp::PermissionAdminCheck { actor, peer } => {
1395                self.permission_admin_check(&who, &actor, &peer)
1396            }
1397            AgentOp::PermissionPreview { changes } => self.permission_preview(&who, &changes),
1398            AgentOp::PermissionApply {
1399                request_id,
1400                changes,
1401            } => self.permission_apply(&who, &request_id, changes),
1402            AgentOp::PermissionRequest { request_id } => self.permission_request(&who, &request_id),
1403            AgentOp::PermissionRuleScopes => self.permission_rule_scopes(&who),
1404            AgentOp::GroupAdminScopes => self.group_admin_scopes(&who),
1405            AgentOp::GroupMembers { group } => self.group_members(&who, &group),
1406            AgentOp::GroupPreview { changes } => self.group_preview(&who, &changes),
1407            AgentOp::GroupApply {
1408                request_id,
1409                changes,
1410            } => self.group_apply(&who, &request_id, changes),
1411            AgentOp::GroupRequest { request_id } => self.permission_request(&who, &request_id),
1412            AgentOp::PermissionRulePreview { changes } => {
1413                self.permission_rule_preview(&who, &changes)
1414            }
1415            AgentOp::PermissionRuleApply {
1416                request_id,
1417                changes,
1418            } => self.permission_rule_apply(&who, &request_id, changes),
1419            AgentOp::RequestIds { count } => self.request_ids(count),
1420            AgentOp::WorkStatus { message_id } => self.work_status(&who, &message_id),
1421            AgentOp::WakeDirectClaim {
1422                message_id,
1423                attempt_id,
1424                target,
1425            } => self.wake_direct_claim(&who, &message_id, &attempt_id, target),
1426            AgentOp::WakeDirectPending { target } => self.wake_direct_pending(&who, &target),
1427            AgentOp::WakeDirectRead {
1428                message_id,
1429                attempt_id,
1430                target,
1431            } => self.wake_direct_read(&who, &message_id, &attempt_id, &target),
1432            AgentOp::WakeDirectObserve {
1433                message_id,
1434                attempt_id,
1435                target,
1436                turn_id,
1437            } => self.wake_direct_observe(&who, &message_id, &attempt_id, &target, &turn_id),
1438            AgentOp::WakeDirectComplete {
1439                message_id,
1440                attempt_id,
1441                target,
1442                turn_id,
1443                text,
1444            } => {
1445                self.wake_direct_complete(&who, &message_id, &attempt_id, &target, (&turn_id, text))
1446            }
1447            AgentOp::WakePending => self.wake_pending(&who),
1448            AgentOp::WakeClaim {
1449                message_id,
1450                attempt_id,
1451                target,
1452            } => self.wake_claim(&who, &message_id, &attempt_id, target),
1453            AgentOp::WakeCheck {
1454                message_id,
1455                attempt_id,
1456                target,
1457            } => self.wake_check(&who, &message_id, &attempt_id, &target),
1458            AgentOp::WakeSubmitted {
1459                message_id,
1460                attempt_id,
1461                submission_id,
1462            } => self.wake_submitted(&who, &message_id, &attempt_id, &submission_id),
1463            AgentOp::WorkBegin {
1464                message_id,
1465                expect_revision,
1466                description,
1467            } => self.work_begin(&who, &message_id, expect_revision, &description),
1468            AgentOp::WorkComplete {
1469                message_id,
1470                expect_revision,
1471                note,
1472            } => self.work_complete(&who, &message_id, expect_revision, &note),
1473            AgentOp::FilePaths => self.file_paths(&who),
1474            AgentOp::FileImport {
1475                request_id,
1476                name,
1477                media_type,
1478            } => self.file_import(&who, &request_id, &name, &media_type),
1479            AgentOp::FileStatus { file_id } => self.file_status(&who, &file_id),
1480            AgentOp::FileReceiveStatus { file } => self.file_receive_status(&who, &file),
1481            AgentOp::FileReceive {
1482                file,
1483                byte_length,
1484                sha256,
1485            } => {
1486                ensure!(
1487                    byte_length <= gent_protocol::file_objects::MAX_FILE_BYTES as u64,
1488                    "file exceeds 32 MiB"
1489                );
1490                ensure!(
1491                    sha256.len() == 64
1492                        && sha256
1493                            .bytes()
1494                            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
1495                    "invalid file digest"
1496                );
1497                let status = self.file_receive_status(&who, &file)?;
1498                ensure!(
1499                    status["state"] != "ready"
1500                        || (status["file"]["byte_length"] == byte_length
1501                            && status["file"]["sha256"] == sha256),
1502                    "request_id already used with different content"
1503                );
1504                Ok(status)
1505            }
1506            AgentOp::FileReceiveData { file, bytes } => self.file_receive(&who, &file, &bytes),
1507            AgentOp::FileRead {
1508                file_id,
1509                chunk_index,
1510            } => self.file_read(&who, &file_id, chunk_index),
1511            AgentOp::FileView { file_id } => self.file_view(&who, &file_id),
1512            AgentOp::FileExport { file_id } => self.file_export(&who, &file_id, export_step),
1513            AgentOp::RelayAttach { target, request_id } => {
1514                self.relay_attach(&who, &target, &request_id)
1515            }
1516            AgentOp::RelayStatus { attachment_id } => self.relay_status(&who, attachment_id),
1517            AgentOp::RelayDetach { attachment_id } => self.relay_detach(&who, &attachment_id),
1518            AgentOp::RelaySend {
1519                attachment_id,
1520                request_id,
1521                text,
1522                files,
1523                file_ids,
1524            } => self.relay_send(&who, &attachment_id, &request_id, (text, files, file_ids)),
1525            AgentOp::RelayTurnStatus {
1526                turn_id,
1527                after_message_id,
1528            } => self.relay_turn_status(&who, &turn_id, after_message_id.as_deref()),
1529            AgentOp::RelayNext => self.relay_next(&who),
1530            AgentOp::RelayTurns { after_turn_id } => {
1531                self.relay_turns(&who, after_turn_id.as_deref())
1532            }
1533            AgentOp::RelayRespond {
1534                turn_id,
1535                request_id,
1536                text,
1537                files,
1538                file_ids,
1539                outcome,
1540            } => self.relay_respond(
1541                &who,
1542                &turn_id,
1543                &request_id,
1544                (text, files, file_ids),
1545                outcome,
1546            ),
1547            AgentOp::RelayCancel {
1548                turn_id,
1549                request_id,
1550            } => self.relay_cancel(&who, &turn_id, &request_id),
1551            AgentOp::Send {
1552                recipient,
1553                request_id,
1554                text,
1555                files,
1556                file_ids,
1557            } => self.send(
1558                &who,
1559                &recipient,
1560                &request_id,
1561                text,
1562                files,
1563                SendContext {
1564                    file_ids,
1565                    ..Default::default()
1566                },
1567            ),
1568            AgentOp::RequestReply {
1569                recipient,
1570                request_id,
1571                text,
1572                files,
1573                file_ids,
1574            } => self.request_reply(&who, &recipient, &request_id, (text, files, file_ids)),
1575            AgentOp::Reply {
1576                message_id,
1577                request_id,
1578                text,
1579                files,
1580                file_ids,
1581            } => {
1582                let parent = self.message(&message_id)?;
1583                ensure!(parent.recipient == who.id, UNAVAILABLE);
1584                if parent.relay.as_ref().is_some_and(|r| {
1585                    r.kind == RelayMessageKind::Request && r.attachment_id == r.turn_id
1586                }) {
1587                    return self.relay_respond(
1588                        &who,
1589                        &message_id,
1590                        &request_id,
1591                        (text, files, file_ids),
1592                        RelayResponseKind::Complete,
1593                    );
1594                }
1595                ensure!(parent.relay.is_none(), "use relay_respond for a relay turn");
1596                self.send(
1597                    &who,
1598                    &parent.sender.clone(),
1599                    &request_id,
1600                    text,
1601                    files,
1602                    SendContext {
1603                        parent: Some(parent),
1604                        relay: None,
1605                        file_ids,
1606                    },
1607                )
1608            }
1609            AgentOp::Inbox => {
1610                let mut statement=self.db.prepare("SELECT payload,acknowledged FROM messages WHERE recipient=?1 AND acknowledged=0 ORDER BY rowid")?;
1611                let rows = statement.query_map([&who.id], |r| {
1612                    Ok((r.get::<_, String>(0)?, r.get::<_, bool>(1)?))
1613                })?;
1614                let mut inbox = Vec::new();
1615                let mut bytes = 0;
1616                for row in rows {
1617                    let (payload, acknowledged) = row?;
1618                    let mut message: Message = serde_json::from_str(&payload)?;
1619                    message.acknowledged = acknowledged;
1620                    if self.deliverable(&message)? && self.relay_inbox_visible(&message)? {
1621                        if inbox.len() >= 50 || bytes + payload.len() > MAX_FRAME_BYTES / 2 {
1622                            break;
1623                        }
1624                        bytes += payload.len();
1625                        self.wake_observe(&who, &message.id)?;
1626                        inbox.push(message);
1627                    }
1628                }
1629                Ok(json!(inbox))
1630            }
1631            AgentOp::Ack { message_id } => self.acknowledge(&who, &message_id),
1632            AgentOp::MessageStatus { message_id } => {
1633                let message = self.message(&message_id)?;
1634                ensure!(
1635                    message.sender == who.id || message.recipient == who.id,
1636                    UNAVAILABLE
1637                );
1638                let state = if message.expires_at <= self.timestamp {
1639                    "expired"
1640                } else if !self.deliverable(&message)?
1641                    || self.db.query_row(
1642                        "SELECT EXISTS(SELECT 1 FROM network_rejections WHERE message=?1)",
1643                        [&message.id],
1644                        |r| r.get::<_, bool>(0),
1645                    )?
1646                {
1647                    "revoked"
1648                } else if message.acknowledged {
1649                    "delivered"
1650                } else {
1651                    "queued"
1652                };
1653                Ok(json!({"message_id":message.id,"state":state}))
1654            }
1655        }
1656    }
1657
1658    fn acknowledge(&self, who: &Agent, message_id: &str) -> Result<Value> {
1659        let message = self.message(message_id)?;
1660        ensure!(
1661            message.recipient == who.id && self.deliverable(&message)?,
1662            UNAVAILABLE
1663        );
1664        let changed = self.db.execute(
1665            "UPDATE messages SET acknowledged=1 WHERE id=?1 AND acknowledged=0",
1666            [message_id],
1667        )?;
1668        let sender = self.get_agent(&message.sender)?;
1669        if changed == 1 {
1670            self.web_state_changed(&sender.node_id)?;
1671        }
1672        if !self.local_node(&sender.node_id) {
1673            self.receipt(
1674                self.state.transport_host(&sender.node_id)?,
1675                message_id,
1676                true,
1677                message.expires_at,
1678            )?;
1679        }
1680        Ok(json!({"acknowledged":true}))
1681    }
1682
1683    fn message(&self, message_id: &str) -> Result<Message> {
1684        let (payload, ack): (String, bool) = self
1685            .db
1686            .query_row(
1687                "SELECT payload,acknowledged FROM messages WHERE id=?1",
1688                [message_id],
1689                |r| Ok((r.get(0)?, r.get(1)?)),
1690            )
1691            .optional()?
1692            .context(UNAVAILABLE)?;
1693        let mut message: Message = serde_json::from_str(&payload)?;
1694        message.acknowledged = ack;
1695        Ok(message)
1696    }
1697    fn deliverable(&self, message: &Message) -> Result<bool> {
1698        if !self.web_message_ready(message)? {
1699            return Ok(false);
1700        }
1701        if message.expires_at <= self.timestamp {
1702            return Ok(false);
1703        }
1704        let a = self.get_agent(&message.sender)?;
1705        let b = self.get_agent(&message.recipient)?;
1706        if !self.relay_authorized(message)? {
1707            return Ok(false);
1708        }
1709        Ok(if message.reply_to.is_some() {
1710            self.config.policy.can_reply(&a, &b)
1711        } else {
1712            self.config.policy.can_open(&a, &b)
1713        })
1714    }
1715
1716    fn send(
1717        &mut self,
1718        sender: &Agent,
1719        recipient_id: &str,
1720        request_id: &str,
1721        text: String,
1722        files: Vec<FilePart>,
1723        context: SendContext,
1724    ) -> Result<Value> {
1725        uuid::Uuid::parse_str(request_id)
1726            .context("request_id must be a UUID; reuse it only when retrying the same message")?;
1727        let SendContext {
1728            parent,
1729            relay,
1730            file_ids,
1731        } = context;
1732        network::validate_contents(&text, &files, file_ids.len())?;
1733        ensure!(
1734            file_ids
1735                .iter()
1736                .collect::<std::collections::BTreeSet<_>>()
1737                .len()
1738                == file_ids.len(),
1739            "duplicate file ID"
1740        );
1741        let reply_to = parent.as_ref().map(|p| p.id.clone());
1742        let fingerprint =
1743            message_fingerprint(recipient_id, &text, &files, &reply_to, &relay, &file_ids)?;
1744        let existing: Option<(String, String)> = self
1745            .db
1746            .query_row(
1747                "SELECT id,fingerprint FROM messages WHERE sender=?1 AND request_id=?2",
1748                params![sender.id, request_id],
1749                |r| Ok((r.get(0)?, r.get(1)?)),
1750            )
1751            .optional()?;
1752        if let Some((message_id, previous)) = existing {
1753            ensure!(
1754                previous == fingerprint,
1755                "request_id already used with different content"
1756            );
1757            return Ok(json!({"message_id":message_id,"duplicate":true}));
1758        }
1759        requests::admit(request_id, self.timestamp)?;
1760        let recipient = self.get_agent(recipient_id)?;
1761        ensure!(sender.id != recipient.id, UNAVAILABLE);
1762        let remote = !self.local_node(&recipient.node_id);
1763        let message_id = crate::messages::message_id(&sender.id, request_id)?;
1764        let timestamp = self.timestamp;
1765        let (exchange_id, expires_at) = if let Some(parent) = parent {
1766            ensure!(
1767                self.config.policy.can_reply(sender, &recipient),
1768                UNAVAILABLE
1769            );
1770            let (a, b, expiry, count): (String, String, i64, u32) = self.db.query_row(
1771                "SELECT a,b,expires_at,count FROM exchanges WHERE id=?1",
1772                [&parent.exchange_id],
1773                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
1774            )?;
1775            ensure!(
1776                (a == sender.id && b == recipient.id) || (b == sender.id && a == recipient.id),
1777                UNAVAILABLE
1778            );
1779            ensure!(expiry > timestamp, "exchange expired");
1780            ensure!(
1781                count < MAX_EXCHANGE_MESSAGES,
1782                "exchange reply limit reached"
1783            );
1784            (parent.exchange_id, expiry)
1785        } else {
1786            ensure!(self.config.policy.can_open(sender, &recipient), UNAVAILABLE);
1787            let mut expiry = timestamp + EXCHANGE_TTL_SECONDS;
1788            if let Some(grant_id) = relay.as_ref().and_then(|relay| relay.grant_id.as_ref()) {
1789                let grant = self
1790                    .config
1791                    .policy
1792                    .relay_grants
1793                    .get(grant_id)
1794                    .context(UNAVAILABLE)?;
1795                expiry = expiry.min(grant.expires_at as i64);
1796            }
1797            (message_id.clone(), expiry)
1798        };
1799        if remote {
1800            let sent: u32 = self.db.query_row(
1801                "SELECT COUNT(*) FROM messages WHERE json_extract(payload,'$.exchange_id')=?1 AND sender=?2",
1802                params![exchange_id, sender.id],
1803                |r| r.get(0),
1804            )?;
1805            ensure!(
1806                sent < MAX_EXCHANGE_MESSAGES / 2,
1807                "remote exchange sender limit reached (16 messages)"
1808            );
1809        }
1810        let attachments = self.seal_attachments(sender, &file_ids, expires_at)?;
1811        let message = Message {
1812            id: message_id,
1813            exchange_id: exchange_id.clone(),
1814            sender: sender.id.clone(),
1815            recipient: recipient.id.clone(),
1816            text,
1817            files,
1818            attachments: attachments
1819                .iter()
1820                .map(|f| f.grant.descriptor().clone())
1821                .collect(),
1822            reply_to,
1823            created_at: timestamp,
1824            expires_at,
1825            acknowledged: false,
1826            relay,
1827        };
1828        self.validate_relay_message(&message)?;
1829        self.validate_local_relay(&message)?;
1830        let tx = self.db;
1831        if message.reply_to.is_none() {
1832            tx.execute(
1833                "INSERT INTO exchanges VALUES (?1,?2,?3,?4,0)",
1834                params![exchange_id, sender.id, recipient.id, expires_at],
1835            )?;
1836        }
1837        ensure!(
1838            tx.execute(
1839                "UPDATE exchanges SET count=count+1 WHERE id=?1 AND count<?2",
1840                params![exchange_id, MAX_EXCHANGE_MESSAGES]
1841            )? == 1,
1842            "exchange reply limit reached"
1843        );
1844        let payload = serde_json::to_string(&message)?;
1845        history::message_capacity(tx, payload.len())?;
1846        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])?;
1847        self.bind_attachments(&message, &attachments)?;
1848        self.record_relay_message(&message)?;
1849        self.web_state_changed(&recipient.node_id)?;
1850        if !self.gate_web_message(&message)? {
1851            usage::record_send(tx, &sender.name, &message)?;
1852        }
1853        self.save_activity(&sender.id, message.created_at)?;
1854        self.record_gent_message(&sender.id, message.created_at)?;
1855        if !remote {
1856            self.record_gent_message(&recipient.id, message.created_at)?;
1857        }
1858        if remote {
1859            self.record_web_demand(&recipient.node_id, &message.id)?;
1860            self.queue_message(
1861                self.state.transport_host(&recipient.node_id)?,
1862                request_id,
1863                &message,
1864            )?;
1865        }
1866        Ok(json!({"message_id":message.id,"exchange_id":exchange_id,"duplicate":false}))
1867    }
1868}