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