Skip to main content

gent_daemon/
store.rs

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