gent-daemon 0.2.4

Local daemon, storage and synchronization for Gent chat clusters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
use gent_daemon::{config, store::Store};
use gent_protocol::{wake::WakeTarget, *};
use rusqlite::{Connection, params};
use serde_json::Value;
use std::sync::{Arc, Barrier};
use std::{fs, os::unix::fs::PermissionsExt};
use uuid::Uuid;

#[path = "wake/direct.rs"]
mod direct;

#[path = "wake/blocked_claim.rs"]
mod blocked_claim;

#[path = "wake/retention.rs"]
mod retention;

fn ok(response: Response) -> Value {
    match response {
        Response::Ok(value) => value,
        Response::Error(error) => panic!("{error}"),
    }
}
fn error(response: Response) -> String {
    match response {
        Response::Error(error) => error,
        Response::Ok(value) => panic!("unexpected success: {value}"),
    }
}
struct Fixture {
    home: tempfile::TempDir,
    store: Store,
    owner: String,
    keys: [String; 3],
    agents: [String; 3],
}
impl Fixture {
    fn new() -> Self {
        let home = tempfile::tempdir().unwrap();
        fs::set_permissions(home.path(), fs::Permissions::from_mode(0o700)).unwrap();
        config::initialize(home.path(), "wake-test").unwrap();
        let owner = config::read_private(&home.path().join("owner.key")).unwrap();
        let mut store = Store::open(home.path()).unwrap();
        let keys = std::array::from_fn(|_| config::secret());
        let agents = std::array::from_fn(|i| {
            ok(store.handle(Request::Agent {
                credential: keys[i].clone(),
                action: AgentOp::Register {
                    name: format!("agent-{i}"),
                    provider: "generic".into(),
                },
            }))["agent"]["id"]
                .as_str()
                .unwrap()
                .into()
        });
        let mut f = Self {
            home,
            store,
            owner,
            keys,
            agents,
        };
        let policy = Policy {
            rules: [Permission::Enumerate, Permission::Send, Permission::Receive]
                .map(|permission| Rule {
                    actor: Selector::All,
                    peer: Selector::All,
                    permission,
                    effect: Effect::Allow,
                })
                .into(),
            ..Default::default()
        };
        ok(f.owner(OwnerOp::SetPolicy { policy }));
        f
    }
    fn agent(&mut self, index: usize, action: AgentOp) -> Response {
        self.store.handle(Request::Agent {
            credential: self.keys[index].clone(),
            action,
        })
    }
    fn owner(&mut self, action: OwnerOp) -> Response {
        self.store.handle(Request::Owner {
            credential: self.owner.clone(),
            action,
        })
    }
    fn db(&self) -> Connection {
        Connection::open(self.home.path().join("state.sqlite3")).unwrap()
    }
    fn send(&mut self) -> String {
        ok(self.agent(
            0,
            AgentOp::Send {
                recipient: self.agents[1].clone(),
                request_id: Uuid::now_v7().to_string(),
                text: "private request content".into(),
                files: vec![],
                file_ids: vec![],
            },
        ))["message_id"]
            .as_str()
            .unwrap()
            .into()
    }
    fn claim(message: &str) -> AgentOp {
        AgentOp::WakeClaim {
            message_id: message.into(),
            attempt_id: Uuid::new_v4().to_string(),
            target: WakeTarget::Codex {
                thread_id: Uuid::now_v7().to_string(),
            },
        }
    }
    fn show(&mut self, message: &str) -> Value {
        ok(self.owner(OwnerOp::WakeShow {
            message_id: message.into(),
        }))
    }
    fn submitted(message: &str, claim: &Value) -> AgentOp {
        AgentOp::WakeSubmitted {
            message_id: message.into(),
            attempt_id: claim["record"]["attempt_id"].as_str().unwrap().into(),
            submission_id: Uuid::now_v7().to_string(),
        }
    }
    fn advance(&self, seconds: i64) {
        self.db()
            .execute("UPDATE request_clock SET floor=floor+?1", [seconds])
            .unwrap();
    }
    fn count(&self) -> u64 {
        self.db()
            .query_row("SELECT COUNT(*) FROM wake_dispatches", [], |r| r.get(0))
            .unwrap()
    }
}

#[test]
fn lost_claim_response_never_reissues_submission_permission() {
    let mut f = Fixture::new();
    let message = f.send();
    let pending = ok(f.agent(1, AgentOp::WakePending));
    assert_eq!(pending["pending"][0]["message_id"], message);
    assert!(!pending.to_string().contains("private request content"));
    f.db()
        .execute("UPDATE agents SET last_seen=1 WHERE id=?1", [&f.agents[1]])
        .unwrap();
    let claim = Fixture::claim(&message);
    let first = ok(f.agent(1, claim.clone()));
    assert_eq!(first["may_submit"], true);
    assert_eq!(first["record"]["state"], "uncertain");
    f.store = Store::open(f.home.path()).unwrap();
    let repeated = ok(f.agent(1, claim.clone()));
    assert_eq!(repeated["may_submit"], false);
    assert_eq!(repeated["record"], first["record"]);
    assert!(
        ok(f.agent(1, AgentOp::WakePending))["pending"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    assert!(error(f.agent(1, Fixture::claim(&message))).contains("already claimed"));
    let mut changed = claim;
    if let AgentOp::WakeClaim { target, .. } = &mut changed {
        *target = WakeTarget::Codex {
            thread_id: Uuid::now_v7().to_string(),
        };
    }
    assert!(error(f.agent(1, changed)).contains("already claimed"));
    let submitted = Fixture::submitted(&message, &first);
    let outcome = ok(f.agent(1, submitted.clone()));
    f.advance(6);
    assert_eq!(ok(f.agent(1, submitted)), outcome);
    assert!(error(f.agent(1, Fixture::submitted(&message, &first))).contains("does not match"));
    let seen: i64 = f
        .db()
        .query_row(
            "SELECT last_seen FROM agents WHERE id=?1",
            [&f.agents[1]],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(
        seen, 1,
        "host adapter traffic must not make a model look active"
    );
    assert_eq!(f.count(), 1);
}

#[test]
fn claude_claim_checks_never_create_retry_or_retarget_a_dispatch() {
    let mut f = Fixture::new();
    let message = f.send();
    let attempt_id = Uuid::new_v4().to_string();
    let session_id = Uuid::new_v4().to_string();
    let target = WakeTarget::ClaudeCode {
        session_id: session_id.clone(),
    };
    let check = AgentOp::WakeCheck {
        message_id: message.clone(),
        attempt_id: attempt_id.clone(),
        target: target.clone(),
    };
    assert!(error(f.agent(1, check.clone())).contains("unavailable"));
    assert_eq!(f.count(), 0);
    let claim = AgentOp::WakeClaim {
        message_id: message.clone(),
        attempt_id: attempt_id.clone(),
        target,
    };
    let first = ok(f.agent(1, claim.clone()));
    assert_eq!(first["may_submit"], true);
    f.store = Store::open(f.home.path()).unwrap();
    f.db()
        .execute("UPDATE agents SET last_seen=1 WHERE id=?1", [&f.agents[1]])
        .unwrap();
    for _ in 0..3 {
        let value = ok(f.agent(1, check.clone()));
        assert_eq!(value["eligible"], true);
        assert_eq!(value["record"], first["record"]);
        assert!(value.get("may_submit").is_none());
        assert!(!value.to_string().contains("private request content"));
    }
    assert!(error(f.agent(2, check.clone())).contains("unavailable"));
    for target in [
        WakeTarget::Codex {
            thread_id: session_id,
        },
        WakeTarget::ClaudeCode {
            session_id: Uuid::new_v4().to_string(),
        },
    ] {
        let wrong = AgentOp::WakeCheck {
            message_id: message.clone(),
            attempt_id: attempt_id.clone(),
            target,
        };
        assert!(error(f.agent(1, wrong)).contains("does not match"));
    }
    let wrong = AgentOp::WakeCheck {
        message_id: message.clone(),
        attempt_id: Uuid::new_v4().to_string(),
        target: WakeTarget::ClaudeCode {
            session_id: first["record"]["target"]["session_id"]
                .as_str()
                .unwrap()
                .into(),
        },
    };
    assert!(error(f.agent(1, wrong)).contains("does not match"));
    assert_eq!(ok(f.agent(1, claim))["may_submit"], false);
    assert_eq!(f.count(), 1);
    assert_eq!(f.show(&message), first["record"]);
    let seen: i64 = f
        .db()
        .query_row(
            "SELECT last_seen FROM agents WHERE id=?1",
            [&f.agents[1]],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(seen, 1);
}

#[test]
fn queued_dispatch_checks_recheck_permissions_ack_expiry_and_submission() {
    for condition in ["permissions", "ack", "expiry", "submitted", "revoked"] {
        let mut f = Fixture::new();
        let message = f.send();
        let claim = Fixture::claim(&message);
        let first = ok(f.agent(1, claim.clone()));
        let AgentOp::WakeClaim {
            attempt_id, target, ..
        } = claim
        else {
            unreachable!()
        };
        let check = AgentOp::WakeCheck {
            message_id: message.clone(),
            attempt_id,
            target,
        };
        assert_eq!(ok(f.agent(1, check.clone()))["eligible"], true);
        match condition {
            "permissions" => {
                ok(f.owner(OwnerOp::SetPolicy {
                    policy: Policy::default(),
                }));
            }
            "ack" => {
                ok(f.agent(
                    1,
                    AgentOp::Ack {
                        message_id: message.clone(),
                    },
                ));
            }
            "expiry" => {
                f.db().execute("UPDATE messages SET payload=json_set(payload,'$.expires_at',0) WHERE id=?1", [&message]).unwrap();
            }
            "submitted" => {
                ok(f.agent(1, Fixture::submitted(&message, &first)));
            }
            "revoked" => {
                ok(f.owner(OwnerOp::Revoke {
                    agent_id: f.agents[1].clone(),
                }));
            }
            _ => unreachable!(),
        }
        if condition == "revoked" {
            assert!(error(f.agent(1, check)).contains("revoked"));
        } else {
            assert_eq!(ok(f.agent(1, check))["eligible"], false, "{condition}");
        }
        assert_eq!(f.count(), 1);
    }
}

#[test]
fn claude_targets_reject_invalid_session_ids_before_claiming() {
    let mut f = Fixture::new();
    let message = f.send();
    for session_id in [
        "../session".into(),
        Uuid::nil().to_string(),
        Uuid::new_v4().to_string().to_uppercase(),
    ] {
        assert!(
            error(f.agent(
                1,
                AgentOp::WakeClaim {
                    message_id: message.clone(),
                    attempt_id: Uuid::new_v4().to_string(),
                    target: WakeTarget::ClaudeCode { session_id }
                }
            ))
            .contains("invalid wake identifier")
        );
    }
    assert_eq!(f.count(), 0);
}

#[test]
fn inbox_observation_and_host_ack_are_independent_of_message_receipts_and_work() {
    let mut f = Fixture::new();
    let message = f.send();
    let claim = ok(f.agent(1, Fixture::claim(&message)));
    f.advance(6);
    let inbox = ok(f.agent(1, AgentOp::Inbox));
    assert_eq!(inbox[0]["id"], message);
    let observed = f.show(&message);
    assert_eq!(observed["state"], "uncertain");
    assert!(observed["inbox_seen_at"].is_i64());
    assert!(observed["submission_id"].is_null());
    assert_eq!(inbox[0]["acknowledged"], false);
    assert!(
        error(f.owner(OwnerOp::WorkShow {
            message_id: message.clone()
        }))
        .contains("not recorded")
    );
    f.advance(6);
    let submitted = ok(f.agent(1, Fixture::submitted(&message, &claim)));
    assert_eq!(submitted["inbox_seen_at"], observed["inbox_seen_at"]);
    assert_eq!(submitted["state"], "submitted");
    ok(f.agent(1, AgentOp::Inbox));
    assert_eq!(f.show(&message), submitted);
    ok(f.agent(
        1,
        AgentOp::Ack {
            message_id: message.clone(),
        },
    ));
    assert_eq!(f.show(&message), submitted);
}

#[test]
fn permissions_revocation_and_acknowledgment_gate_new_claims() {
    let mut f = Fixture::new();
    let claimed = f.send();
    let request = Fixture::claim(&claimed);
    let first = ok(f.agent(1, request.clone()));
    let fresh = f.send();
    assert!(
        ok(f.agent(2, AgentOp::WakePending))["pending"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    assert!(error(f.agent(2, request.clone())).contains("unavailable"));
    assert!(error(f.agent(2, Fixture::submitted(&claimed, &first))).contains("unavailable"));
    let acknowledged = f.send();
    ok(f.agent(
        1,
        AgentOp::Ack {
            message_id: acknowledged.clone(),
        },
    ));
    assert!(error(f.agent(1, Fixture::claim(&acknowledged))).contains("unavailable"));
    ok(f.owner(OwnerOp::SetPolicy {
        policy: Policy::default(),
    }));
    assert!(
        ok(f.agent(1, AgentOp::WakePending))["pending"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    assert!(error(f.agent(1, Fixture::claim(&fresh))).contains("unavailable"));
    assert_eq!(ok(f.agent(1, request.clone()))["may_submit"], false);
    // Recording an already attempted submission does not require renewed peer access.
    ok(f.agent(1, Fixture::submitted(&claimed, &first)));
    ok(f.owner(OwnerOp::Revoke {
        agent_id: f.agents[1].clone(),
    }));
    assert!(error(f.agent(1, request)).contains("revoked"));
    assert_eq!(f.count(), 1);
}

#[test]
fn concurrent_claimants_get_one_permission_and_failed_commits_grant_none() {
    let mut f = Fixture::new();
    let message = f.send();
    let claim = Fixture::claim(&message);
    f.db().execute_batch("CREATE TRIGGER reject_wake BEFORE INSERT ON wake_dispatches BEGIN SELECT RAISE(ABORT,'fixture insert failure'); END;").unwrap();
    assert!(error(f.agent(1, claim.clone())).contains("fixture insert failure"));
    assert_eq!(f.count(), 0);
    f.db().execute_batch("DROP TRIGGER reject_wake").unwrap();
    let barrier = Arc::new(Barrier::new(3));
    let mut workers = Vec::new();
    for _ in 0..2 {
        let mut store = Store::open(f.home.path()).unwrap();
        let barrier = barrier.clone();
        let credential = f.keys[1].clone();
        let action = claim.clone();
        workers.push(std::thread::spawn(move || {
            barrier.wait();
            ok(store.handle(Request::Agent { credential, action }))
        }));
    }
    barrier.wait();
    let results = workers
        .into_iter()
        .map(|w| w.join().unwrap())
        .collect::<Vec<_>>();
    assert_eq!(
        results.iter().filter(|r| r["may_submit"] == true).count(),
        1
    );
    assert_eq!(results[0]["record"], results[1]["record"]);
    f.db().execute_batch("CREATE TRIGGER reject_wake_update BEFORE UPDATE ON wake_dispatches BEGIN SELECT RAISE(ABORT,'fixture update failure'); END;").unwrap();
    let submitted = Fixture::submitted(&message, &results[0]);
    assert!(error(f.agent(1, submitted.clone())).contains("fixture update failure"));
    assert_eq!(f.show(&message)["state"], "uncertain");
    f.db()
        .execute_batch("DROP TRIGGER reject_wake_update")
        .unwrap();
    assert_eq!(ok(f.agent(1, claim))["may_submit"], false);
    ok(f.agent(1, submitted));
}

#[test]
fn claim_budgets_preserve_pending_messages_and_survive_restart() {
    let mut f = Fixture::new();
    for index in 0..14 {
        let message = f.send();
        let claim = Fixture::claim(&message);
        if index > 0 {
            assert!(error(f.agent(1, claim.clone())).contains("budget"));
            f.advance(5);
        }
        ok(f.agent(1, claim));
    }
    let first = ok(f.owner(OwnerOp::WakeList {
        after_message_id: None,
    }))["entries"][0]
        .clone();
    let mut db = f.db();
    let tx = db.transaction().unwrap();
    for _ in 14..720 {
        let mut record = first.clone();
        record["message_id"] = Uuid::now_v7().to_string().into();
        record["attempt_id"] = Uuid::new_v4().to_string().into();
        tx.execute("INSERT INTO wake_dispatches(message_id,agent,attempt_id,claimed_at,payload) VALUES(?1,?2,?3,?4,?5)",params![
            record["message_id"].as_str().unwrap(),record["agent"].as_str().unwrap(),record["attempt_id"].as_str().unwrap(),
            record["claimed_at"].as_i64().unwrap(),record.to_string()]).unwrap();
    }
    tx.commit().unwrap();
    let message = f.send();
    f.advance(5);
    f.store = Store::open(f.home.path()).unwrap();
    assert!(error(f.agent(1, Fixture::claim(&message))).contains("budget"));
    assert_eq!(f.count(), 720);
    assert_eq!(
        ok(f.agent(1, AgentOp::WakePending))["pending"][0]["message_id"],
        message
    );
    f.advance(3600);
    ok(f.agent(1, Fixture::claim(&message)));
    assert_eq!(f.count(), 721);
}

#[test]
fn storage_limits_and_corrupt_journal_fail_without_recreating_dispatch_permission() {
    let mut f = Fixture::new();
    let message = f.send();
    let first = ok(f.agent(1, Fixture::claim(&message)));
    let mut db = f.db();
    let tx = db.transaction().unwrap();
    for _ in 1..16_384 {
        let mut record = first["record"].clone();
        record["message_id"] = Uuid::now_v7().to_string().into();
        record["attempt_id"] = Uuid::new_v4().to_string().into();
        tx.execute("INSERT INTO wake_dispatches(message_id,agent,attempt_id,claimed_at,payload) VALUES(?1,?2,?3,?4,?5)",params![
            record["message_id"].as_str().unwrap(),record["agent"].as_str().unwrap(),record["attempt_id"].as_str().unwrap(),
            record["claimed_at"].as_i64().unwrap(),record.to_string()]).unwrap();
    }
    tx.commit().unwrap();
    let next = f.send();
    assert!(error(f.agent(1, Fixture::claim(&next))).contains("full"));
    let page = ok(f.owner(OwnerOp::WakeList {
        after_message_id: None,
    }));
    assert_eq!(page["entries"].as_array().unwrap().len(), 50);
    assert_eq!(page["has_more"], true);
    assert!(
        db.execute(
            "UPDATE wake_dispatches SET payload=?1 WHERE message_id=?2",
            params!["x".repeat(2049), message]
        )
        .is_err()
    );
    db.execute(
        "UPDATE wake_dispatches SET payload='{}' WHERE message_id=?1",
        [&message],
    )
    .unwrap();
    assert!(
        !error(f.owner(OwnerOp::WakeShow {
            message_id: message
        }))
        .is_empty()
    );
    db.execute("DROP TABLE wake_dispatches", []).unwrap();
    assert!(Store::open(f.home.path()).is_err());
}

#[test]
fn node_budget_counts_other_agents_and_expired_messages_never_get_claims() {
    let mut f = Fixture::new();
    let expired = f.send();
    f.db()
        .execute(
            "UPDATE messages SET payload=json_set(payload,'$.expires_at',0) WHERE id=?1",
            [&expired],
        )
        .unwrap();
    assert!(error(f.agent(1, Fixture::claim(&expired))).contains("unavailable"));
    assert!(
        ok(f.agent(1, AgentOp::WakePending))["pending"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    let message = f.send();
    let first = ok(f.agent(1, Fixture::claim(&message)));
    let mut db = f.db();
    let tx = db.transaction().unwrap();
    // Populate other agents' retained claims through real accounting columns.
    for _ in 1..7200 {
        let mut record = first["record"].clone();
        record["message_id"] = Uuid::now_v7().to_string().into();
        record["attempt_id"] = Uuid::new_v4().to_string().into();
        record["agent"] = f.agents[2].clone().into();
        tx.execute("INSERT INTO wake_dispatches(message_id,agent,attempt_id,claimed_at,payload) VALUES(?1,?2,?3,?4,?5)",params![
            record["message_id"].as_str().unwrap(),record["agent"].as_str().unwrap(),record["attempt_id"].as_str().unwrap(),
            record["claimed_at"].as_i64().unwrap(),record.to_string()]).unwrap();
    }
    tx.commit().unwrap();
    let next = f.send();
    f.advance(5);
    assert!(error(f.agent(1, Fixture::claim(&next))).contains("budget"));
    assert_eq!(f.count(), 7200);
    assert_eq!(
        ok(f.agent(1, AgentOp::WakePending))["pending"][0]["message_id"],
        next
    );
    f.advance(3600);
    ok(f.agent(1, Fixture::claim(&next)));
}