glass-dev 0.3.14

Glass terminal-native development and browser workspace
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
//! Glass-owned scheduling for independent resident Pi agent sessions.

use crate::development::{DevelopmentError, DevelopmentResult};
use crate::pi_runtime::{GlassPiRuntime, PiRuntimeOptions, PiSessionRequest, PiToolExecutor};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver, SyncSender, TryRecvError, TrySendError};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

const COMMAND_CAPACITY: usize = 32;
const EVENT_CAPACITY: usize = 256;
const HISTORY_CAPACITY: usize = 512;
const AGENT_EVIDENCE_CAPACITY: usize = 64;
const MAX_AGENTS: usize = 32;
const MAX_PROMPT_BYTES: usize = 64 * 1024;

/// Connection metadata for an optional resident-agent broker.
#[derive(Debug, Clone)]
pub struct ResidentAgentBroker {
    /// Unix socket used to reach the broker.
    pub socket: PathBuf,
    /// Authentication token sent to the broker.
    pub token: String,
    /// Workspace identity asserted by the broker.
    pub workspace_id: String,
}

/// Stable identifier for one resident agent; values start with `agent-`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct AgentId(String);

impl AgentId {
    /// Borrow the stable identifier as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Parse an identifier, requiring the `agent-` prefix and a 64-byte bound.
    pub fn parse(value: impl Into<String>) -> DevelopmentResult<Self> {
        let value = value.into();
        if !value.starts_with("agent-")
            || value.len() > 64
            || value.chars().any(|character| character.is_control())
        {
            return Err(DevelopmentError::InvalidInput("invalid agent id".into()));
        }
        Ok(Self(value))
    }
}

/// Lifecycle state of a resident agent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AgentStatus {
    /// Accepted but waiting for dependencies or capacity.
    Queued,
    /// Worker process is being started.
    Starting,
    /// Worker is ready for a request.
    Idle,
    /// Worker is processing a request.
    Working,
    /// Worker is waiting on external/user input.
    Waiting,
    /// Agent completed successfully.
    Completed,
    /// Agent terminated with an error.
    Failed,
    /// Agent was explicitly cancelled.
    Cancelled,
}

impl AgentStatus {
    fn terminal(self) -> bool {
        matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
    }

    /// Human-readable label for terminal and TUI surfaces.
    pub fn label(self) -> &'static str {
        match self {
            Self::Queued => "queued",
            Self::Starting => "starting",
            Self::Idle => "idle",
            Self::Working => "working",
            Self::Waiting => "waiting",
            Self::Completed => "completed",
            Self::Failed => "failed",
            Self::Cancelled => "cancelled",
        }
    }
}

/// Declarative request for one resident agent session.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentSpec {
    /// Human-readable role assigned to the agent.
    pub role: String,
    /// Initial task prompt.
    pub task: String,
    /// Agents that must complete before this agent starts.
    #[serde(default)]
    pub dependencies: Vec<AgentId>,
    /// Optional Pi model override.
    pub model: Option<String>,
    /// Optional Pi thinking-level override.
    pub thinking: Option<String>,
    /// Optional existing worktree path.
    pub worktree: Option<PathBuf>,
    /// Optional architect session to fork as a Pi subagent.
    pub fork_from: Option<PathBuf>,
    /// Whether governed tool restrictions are disabled.
    #[serde(default)]
    pub unrestricted: bool,
    /// Optional worker runtime limit in seconds.
    pub max_runtime_seconds: Option<u64>,
    /// Optional retained-event limit for this agent.
    pub max_events: Option<u64>,
}

impl AgentSpec {
    /// Build a spec with governed defaults of 3,600 seconds and 10,000 events.
    pub fn new(role: impl Into<String>, task: impl Into<String>) -> Self {
        Self {
            role: role.into(),
            task: task.into(),
            dependencies: Vec::new(),
            model: None,
            thinking: None,
            worktree: None,
            fork_from: None,
            unrestricted: false,
            max_runtime_seconds: Some(3_600),
            max_events: Some(10_000),
        }
    }
}

/// Current serialized projection of an agent and its bounded evidence.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentSnapshot {
    /// Stable agent identifier.
    pub id: AgentId,
    /// Configured role.
    pub role: String,
    /// Configured task prompt.
    pub task: String,
    /// Current lifecycle status.
    pub status: AgentStatus,
    /// Dependency identifiers.
    pub dependencies: Vec<AgentId>,
    /// Effective model, if configured.
    pub model: Option<String>,
    /// Effective thinking level, if configured.
    pub thinking: Option<String>,
    /// Canonical worktree used by the worker.
    pub worktree: PathBuf,
    /// Persisted Pi session file, when the runtime has one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_file: Option<String>,
    /// Whether unrestricted tools were enabled.
    pub unrestricted: bool,
    /// Creation timestamp in Unix milliseconds.
    pub created_at_ms: u128,
    /// Start timestamp in Unix milliseconds.
    pub started_at_ms: Option<u128>,
    /// Last projection update timestamp in Unix milliseconds.
    pub updated_at_ms: u128,
    /// Number of events received for this agent.
    pub event_count: u64,
    /// Number of lossy events dropped by the bounded queue.
    pub dropped_event_count: u64,
    /// Last worker error, if any.
    pub last_error: Option<String>,
    /// Last Pi response identifier, if any.
    pub last_response_id: Option<String>,
    /// Bounded tool/runtime evidence values.
    pub evidence: Vec<Value>,
}

/// One ordered event emitted by an agent worker.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentEvent {
    /// Monotonic event sequence number.
    pub sequence: u64,
    /// Agent that emitted the event.
    pub agent_id: AgentId,
    /// Event timestamp in Unix milliseconds.
    pub timestamp_ms: u128,
    /// Event kind label.
    pub kind: String,
    /// Structured event payload.
    pub payload: Value,
}

#[derive(Debug)]
enum WorkerCommand {
    Request(PiSessionRequest),
    ApproveTool { frame_id: String, approved: bool },
    Shutdown,
}

#[derive(Debug)]
enum WorkerEvent {
    Ready(AgentId),
    RequestStarted(AgentId, String, bool),
    Pi(AgentId, Value),
    Failed(AgentId, String),
    Stopped(AgentId),
}

struct AgentRecord {
    snapshot: AgentSnapshot,
    spec: AgentSpec,
    command: Option<SyncSender<WorkerCommand>>,
    worker: Option<thread::JoinHandle<()>>,
    awaiting_agent_settle: bool,
    dropped_events: Arc<AtomicU64>,
}

struct WorkerRuntime {
    worktree: PathBuf,
    fork_from: Option<PathBuf>,
    local_tool_executor: Option<PiToolExecutor>,
    sessions_dir: PathBuf,
    broker: Option<ResidentAgentBroker>,
    additional_system_prompt: Option<String>,
}

/// Registry and scheduler for independent Pi subprocesses.
///
/// Each running agent owns a distinct Pi process and persistent session. The
/// registry only starts dependency-ready work, bounds all queues and retained
/// evidence, and never silently promotes a failed dependency to success.
pub struct AgentRegistry {
    root: PathBuf,
    sessions_dir: PathBuf,
    records: BTreeMap<AgentId, AgentRecord>,
    events_tx: SyncSender<WorkerEvent>,
    events_rx: Receiver<WorkerEvent>,
    history: VecDeque<AgentEvent>,
    local_tool_executor: Option<PiToolExecutor>,
    next_agent: u64,
    next_event: u64,
    broker: Option<ResidentAgentBroker>,
    additional_system_prompt: Option<String>,
    default_model: Option<String>,
    default_thinking: Option<String>,
    default_unrestricted: bool,
}

impl AgentRegistry {
    /// Create a registry rooted at the canonical project directory.
    pub fn new(root: impl AsRef<Path>) -> DevelopmentResult<Self> {
        let root = std::fs::canonicalize(root)?;
        let sessions_dir = root.join(".glass").join("pi-sessions");
        let (events_tx, events_rx) = mpsc::sync_channel(EVENT_CAPACITY);
        Ok(Self {
            root,
            sessions_dir,
            records: BTreeMap::new(),
            events_tx,
            events_rx,
            history: VecDeque::new(),
            local_tool_executor: None,
            next_agent: 1,
            next_event: 1,
            broker: None,
            additional_system_prompt: None,
            default_model: None,
            default_thinking: None,
            default_unrestricted: false,
        })
    }

    /// Configure the authenticated broker used for resident-agent requests.
    pub fn set_resident_broker(&mut self, broker: ResidentAgentBroker) -> DevelopmentResult<()> {
        if !broker.socket.is_absolute()
            || broker.socket == Path::new("/")
            || broker.token.is_empty()
            || broker.token.len() > 256
            || broker.workspace_id.is_empty()
            || broker.workspace_id.len() > 128
            || broker
                .workspace_id
                .chars()
                .any(|character| character.is_control())
        {
            return Err(DevelopmentError::InvalidInput(
                "invalid resident agent broker context".into(),
            ));
        }
        self.broker = Some(broker);
        Ok(())
    }
    pub(crate) fn set_local_tool_executor(&mut self, executor: PiToolExecutor) {
        self.local_tool_executor = Some(executor);
    }

    pub fn set_additional_system_prompt(
        &mut self,
        prompt: Option<String>,
    ) -> DevelopmentResult<()> {
        if prompt
            .as_ref()
            .is_some_and(|prompt| prompt.len() > 128 * 1024 || prompt.contains('\0'))
        {
            return Err(DevelopmentError::InvalidInput(
                "agent project instructions exceed 128 KiB or contain NUL".into(),
            ));
        }
        self.additional_system_prompt = prompt;
        Ok(())
    }

    /// Active user-global and trusted-project instructions supplied to Pi.
    pub fn additional_system_prompt(&self) -> Option<&str> {
        self.additional_system_prompt.as_deref()
    }

    pub fn set_defaults(
        &mut self,
        model: Option<String>,
        thinking: Option<String>,
    ) -> DevelopmentResult<()> {
        for (label, value) in [("model", &model), ("thinking", &thinking)] {
            if value
                .as_ref()
                .is_some_and(|value| value.is_empty() || value.len() > 256 || value.contains('\0'))
            {
                return Err(DevelopmentError::InvalidInput(format!(
                    "default agent {label} must contain 1..=256 bytes without NUL"
                )));
            }
        }
        self.default_model = model;
        self.default_thinking = thinking;
        Ok(())
    }
    /// Make newly created resident agents unrestricted for this process.
    pub fn set_default_unrestricted(&mut self, unrestricted: bool) {
        self.default_unrestricted = unrestricted;
    }

    pub fn default_unrestricted(&self) -> bool {
        self.default_unrestricted
    }

    /// Validate and enqueue an agent; dependencies must be known and successful.
    pub fn create(&mut self, mut spec: AgentSpec) -> DevelopmentResult<AgentId> {
        self.refresh()?;
        if self.default_unrestricted {
            spec.unrestricted = true;
        }
        if spec.model.is_none() {
            spec.model.clone_from(&self.default_model);
        }
        if spec.thinking.is_none() {
            spec.thinking.clone_from(&self.default_thinking);
        }
        validate_spec(&self.root, &self.records, &spec)?;
        if self.records.len() >= MAX_AGENTS {
            return Err(DevelopmentError::Conflict(format!(
                "agent registry reached its {MAX_AGENTS} session limit"
            )));
        }
        let id = AgentId(format!("agent-{:04}", self.next_agent));
        self.next_agent = self
            .next_agent
            .checked_add(1)
            .ok_or_else(|| DevelopmentError::Conflict("agent identifier space exhausted".into()))?;
        let now = now_ms();
        let worktree = spec.worktree.clone().unwrap_or_else(|| self.root.clone());
        let status = if spec.dependencies.is_empty() {
            AgentStatus::Starting
        } else {
            AgentStatus::Queued
        };
        self.records.insert(
            id.clone(),
            AgentRecord {
                snapshot: AgentSnapshot {
                    id: id.clone(),
                    role: spec.role.clone(),
                    task: spec.task.clone(),
                    status,
                    dependencies: spec.dependencies.clone(),
                    model: spec.model.clone(),
                    thinking: spec.thinking.clone(),
                    worktree,
                    session_file: None,
                    unrestricted: spec.unrestricted,
                    created_at_ms: now,
                    started_at_ms: None,
                    updated_at_ms: now,
                    event_count: 0,
                    dropped_event_count: 0,
                    last_error: None,
                    last_response_id: None,
                    evidence: Vec::new(),
                },
                spec,
                command: None,
                worker: None,
                awaiting_agent_settle: false,
                dropped_events: Arc::new(AtomicU64::new(0)),
            },
        );
        if status == AgentStatus::Starting {
            self.spawn(&id)?;
        }
        Ok(id)
    }

    /// Drain worker events, update snapshots, and start newly ready agents.
    pub fn refresh(&mut self) -> DevelopmentResult<()> {
        loop {
            match self.events_rx.try_recv() {
                Ok(event) => self.apply_worker_event(event),
                Err(TryRecvError::Empty) => break,
                Err(TryRecvError::Disconnected) => {
                    return Err(DevelopmentError::Process(
                        "agent scheduler event channel closed".into(),
                    ));
                }
            }
        }
        for record in self.records.values_mut() {
            record.snapshot.dropped_event_count = record.dropped_events.load(Ordering::Relaxed);
        }
        self.reap_finished_workers();
        self.enforce_budgets();
        self.fail_blocked_dependents();
        self.start_ready_agents()?;
        Ok(())
    }

    /// Return one refreshed agent snapshot or a not-found error.
    pub fn snapshot(&mut self, id: &AgentId) -> DevelopmentResult<AgentSnapshot> {
        self.refresh()?;
        self.records
            .get(id)
            .map(|record| record.snapshot.clone())
            .ok_or_else(|| DevelopmentError::NotFound(format!("agent {}", id.as_str())))
    }

    /// Return refreshed snapshots for all registered agents.
    pub fn list(&mut self) -> DevelopmentResult<Vec<AgentSnapshot>> {
        self.refresh()?;
        Ok(self
            .records
            .values()
            .map(|record| record.snapshot.clone())
            .collect())
    }

    /// Return retained events at or after the supplied sequence number.
    pub fn history(&mut self, since: u64) -> DevelopmentResult<Vec<AgentEvent>> {
        self.refresh()?;
        Ok(self
            .history
            .iter()
            .filter(|event| event.sequence > since)
            .cloned()
            .collect())
    }

    /// Send an initial prompt to an agent, subject to prompt-size bounds.
    pub fn prompt(&mut self, id: &AgentId, text: impl Into<String>) -> DevelopmentResult<()> {
        self.prompt_with_context(id, text, None)
    }

    pub fn prompt_with_context(
        &mut self,
        id: &AgentId,
        text: impl Into<String>,
        context: Option<Value>,
    ) -> DevelopmentResult<()> {
        let text = text.into();
        validate_text("agent prompt", &text, MAX_PROMPT_BYTES)?;
        validate_context_attachment(context.as_ref())?;
        self.send(id, PiSessionRequest::Prompt { text, context })
    }

    pub fn steer(&mut self, id: &AgentId, text: impl Into<String>) -> DevelopmentResult<()> {
        self.steer_with_context(id, text, None)
    }

    pub fn steer_with_context(
        &mut self,
        id: &AgentId,
        text: impl Into<String>,
        context: Option<Value>,
    ) -> DevelopmentResult<()> {
        let text = text.into();
        validate_text("agent steering", &text, MAX_PROMPT_BYTES)?;
        validate_context_attachment(context.as_ref())?;
        self.send(id, PiSessionRequest::Steer { text, context })
    }

    pub fn follow_up(&mut self, id: &AgentId, text: impl Into<String>) -> DevelopmentResult<()> {
        self.follow_up_with_context(id, text, None)
    }

    pub fn follow_up_with_context(
        &mut self,
        id: &AgentId,
        text: impl Into<String>,
        context: Option<Value>,
    ) -> DevelopmentResult<()> {
        let text = text.into();
        validate_text("agent follow-up", &text, MAX_PROMPT_BYTES)?;
        validate_context_attachment(context.as_ref())?;
        self.send(id, PiSessionRequest::FollowUp { text, context })
    }

    pub fn approve_tool(
        &mut self,
        id: &AgentId,
        frame_id: impl Into<String>,
        approved: bool,
    ) -> DevelopmentResult<()> {
        self.refresh()?;
        let frame_id = frame_id.into();
        validate_text("Pi approval frame", &frame_id, 256)?;
        let record = self.record_mut(id)?;
        if record.snapshot.status.terminal() {
            return Err(DevelopmentError::Conflict(format!(
                "agent {} is already terminal",
                id.as_str()
            )));
        }
        let sender = record.command.as_ref().ok_or_else(|| {
            DevelopmentError::Conflict(format!("agent {} is still starting", id.as_str()))
        })?;
        sender
            .try_send(WorkerCommand::ApproveTool { frame_id, approved })
            .map_err(|error| match error {
                TrySendError::Full(_) => DevelopmentError::Conflict(format!(
                    "agent {} command queue is full",
                    id.as_str()
                )),
                TrySendError::Disconnected(_) => DevelopmentError::Process(format!(
                    "agent {} command channel closed",
                    id.as_str()
                )),
            })
    }

    pub fn request(&mut self, id: &AgentId, request: PiSessionRequest) -> DevelopmentResult<()> {
        self.send(id, request)
    }

    /// Mark a non-terminal agent complete after its worker settles.
    pub fn complete(&mut self, id: &AgentId) -> DevelopmentResult<()> {
        self.refresh()?;
        if self.record_mut(id)?.snapshot.status.terminal() {
            return Err(DevelopmentError::Conflict(format!(
                "agent {} is already terminal",
                id.as_str()
            )));
        }
        if let Some(sender) = self.record_mut(id)?.command.take() {
            let _ = sender.try_send(WorkerCommand::Shutdown);
        }
        self.join_worker(id, AgentStatus::Completed)?;
        self.record_event(id, "completed", Value::Null);
        self.start_ready_agents()?;
        Ok(())
    }

    /// Cancel a non-terminal agent and stop its worker.
    pub fn cancel(&mut self, id: &AgentId) -> DevelopmentResult<()> {
        self.refresh()?;
        if self.record_mut(id)?.snapshot.status.terminal() {
            return Ok(());
        }
        if let Some(sender) = &self.record_mut(id)?.command {
            let _ = sender.try_send(WorkerCommand::Request(PiSessionRequest::Abort));
            let _ = sender.try_send(WorkerCommand::Shutdown);
        }
        self.record_mut(id)?.command = None;
        self.join_worker(id, AgentStatus::Cancelled)?;
        self.record_event(id, "cancelled", Value::Null);
        self.fail_blocked_dependents();
        Ok(())
    }
    /// Restart a failed or cancelled session under the same agent identity.
    ///
    /// Interactive callers keep the selected agent id, so retrying after an
    /// aborted or crashed turn should not strand the composer on a terminal
    /// worker. Completed sessions remain terminal by design; callers should
    /// create a new session when they explicitly finished one.
    pub fn restart(&mut self, id: &AgentId) -> DevelopmentResult<()> {
        self.refresh()?;
        let previous_status = {
            let record = self.record_mut(id)?;
            if !matches!(
                record.snapshot.status,
                AgentStatus::Failed | AgentStatus::Cancelled
            ) {
                return Err(DevelopmentError::Conflict(format!(
                    "agent {} can only restart from failed or cancelled, not {:?}",
                    id.as_str(),
                    record.snapshot.status
                )));
            }
            record.snapshot.status
        };
        // A failure event can be observed just before the worker thread
        // exits. Join it here instead of making the user retry a second time.
        self.join_worker(id, previous_status)?;
        {
            let record = self.record_mut(id)?;
            record.snapshot.last_error = None;
            record.snapshot.last_response_id = None;
            record.awaiting_agent_settle = false;
        }
        self.spawn(id)?;
        self.record_event(
            id,
            "restarted",
            serde_json::json!({"previousStatus": previous_status.label()}),
        );
        Ok(())
    }

    fn send(&mut self, id: &AgentId, request: PiSessionRequest) -> DevelopmentResult<()> {
        self.refresh()?;
        let user_event = match &request {
            PiSessionRequest::Prompt { text, context } => Some(
                serde_json::json!({"text": text, "mode": "prompt", "contextAttached": context.is_some()}),
            ),
            PiSessionRequest::Steer { text, context } => Some(
                serde_json::json!({"text": text, "mode": "steer", "contextAttached": context.is_some()}),
            ),
            PiSessionRequest::FollowUp { text, context } => Some(
                serde_json::json!({"text": text, "mode": "follow-up", "contextAttached": context.is_some()}),
            ),
            _ => None,
        };
        {
            let record = self.record_mut(id)?;
            if record.snapshot.status.terminal() || record.snapshot.status == AgentStatus::Queued {
                return Err(DevelopmentError::Conflict(format!(
                    "agent {} cannot accept requests while {:?}",
                    id.as_str(),
                    record.snapshot.status
                )));
            }
            let sender = record.command.as_ref().ok_or_else(|| {
                DevelopmentError::Conflict(format!("agent {} is still starting", id.as_str()))
            })?;
            sender
                .try_send(WorkerCommand::Request(request))
                .map_err(|error| match error {
                    TrySendError::Full(_) => DevelopmentError::Conflict(format!(
                        "agent {} command queue is full",
                        id.as_str()
                    )),
                    TrySendError::Disconnected(_) => DevelopmentError::Process(format!(
                        "agent {} command channel closed",
                        id.as_str()
                    )),
                })?;
        }
        if let Some(payload) = user_event {
            self.record_event(id, "user", payload);
        }
        Ok(())
    }

    fn spawn(&mut self, id: &AgentId) -> DevelopmentResult<()> {
        let sessions_dir = self.sessions_dir.clone();
        let events = self.events_tx.clone();
        let broker = self.broker.clone();
        let additional_system_prompt = self.additional_system_prompt.clone();
        let local_tool_executor = self.local_tool_executor.clone();
        let record = self.record_mut(id)?;
        let dropped_events = Arc::clone(&record.dropped_events);
        let spec = record.spec.clone();
        let worktree = record.snapshot.worktree.clone();
        let fork_from = record.spec.fork_from.clone();
        let worker_id = id.clone();
        let (commands_tx, commands_rx) = mpsc::sync_channel(COMMAND_CAPACITY);
        record.command = Some(commands_tx);
        record.snapshot.status = AgentStatus::Starting;
        record.snapshot.started_at_ms = Some(now_ms());
        record.snapshot.updated_at_ms = now_ms();
        let worker = thread::Builder::new()
            .name(format!("glass-{}", id.as_str()))
            .spawn(move || {
                run_worker(
                    worker_id,
                    spec,
                    WorkerRuntime {
                        local_tool_executor,
                        worktree,
                        fork_from,
                        sessions_dir,
                        broker,
                        additional_system_prompt,
                    },
                    commands_rx,
                    events,
                    dropped_events,
                )
            })
            .map_err(DevelopmentError::Io)?;
        record.worker = Some(worker);
        self.record_event(id, "starting", Value::Null);
        Ok(())
    }

    fn start_ready_agents(&mut self) -> DevelopmentResult<()> {
        let ready: Vec<_> = self
            .records
            .iter()
            .filter(|(_, record)| record.snapshot.status == AgentStatus::Queued)
            .filter(|(_, record)| {
                record.spec.dependencies.iter().all(|dependency| {
                    self.records.get(dependency).is_some_and(|dependency| {
                        dependency.snapshot.status == AgentStatus::Completed
                    })
                })
            })
            .map(|(id, _)| id.clone())
            .collect();
        for id in ready {
            self.spawn(&id)?;
        }
        Ok(())
    }

    fn fail_blocked_dependents(&mut self) {
        let terminal_failures: BTreeSet<_> = self
            .records
            .iter()
            .filter(|(_, record)| {
                matches!(
                    record.snapshot.status,
                    AgentStatus::Failed | AgentStatus::Cancelled
                )
            })
            .map(|(id, _)| id.clone())
            .collect();
        let blocked: Vec<_> = self
            .records
            .iter()
            .filter(|(_, record)| record.snapshot.status == AgentStatus::Queued)
            .filter(|(_, record)| {
                record
                    .spec
                    .dependencies
                    .iter()
                    .any(|dependency| terminal_failures.contains(dependency))
            })
            .map(|(id, _)| id.clone())
            .collect();
        for id in blocked {
            if let Some(record) = self.records.get_mut(&id) {
                record.snapshot.status = AgentStatus::Failed;
                record.snapshot.last_error = Some("a required agent did not complete".into());
                record.snapshot.updated_at_ms = now_ms();
            }
            self.record_event(
                &id,
                "dependencyFailed",
                Value::String("a required agent did not complete".into()),
            );
        }
    }

    fn enforce_budgets(&mut self) {
        let now = now_ms();
        let exceeded: Vec<_> = self
            .records
            .iter()
            .filter(|(_, record)| !record.snapshot.status.terminal())
            .filter(|(_, record)| {
                record
                    .spec
                    .max_runtime_seconds
                    .zip(record.snapshot.started_at_ms)
                    .is_some_and(|(seconds, started)| {
                        now.saturating_sub(started) > u128::from(seconds) * 1_000
                    })
                    || record
                        .spec
                        .max_events
                        .is_some_and(|limit| record.snapshot.event_count >= limit)
            })
            .map(|(id, _)| id.clone())
            .collect();
        for id in exceeded {
            if let Some(record) = self.records.get_mut(&id) {
                if let Some(sender) = record.command.take() {
                    let _ = sender.try_send(WorkerCommand::Request(PiSessionRequest::Abort));
                    let _ = sender.try_send(WorkerCommand::Shutdown);
                }
                record.snapshot.status = AgentStatus::Failed;
                record.snapshot.last_error = Some("agent budget exceeded".into());
                record.snapshot.updated_at_ms = now;
            }
            self.record_event(&id, "budgetExceeded", Value::Null);
        }
    }

    fn apply_worker_event(&mut self, event: WorkerEvent) {
        match event {
            WorkerEvent::Ready(id) => {
                if let Some(record) = self.records.get_mut(&id)
                    && !record.snapshot.status.terminal()
                {
                    record.snapshot.status = AgentStatus::Idle;
                    record.snapshot.updated_at_ms = now_ms();
                }
                self.record_event(&id, "ready", Value::Null);
            }
            WorkerEvent::RequestStarted(id, request_id, waits_for_agent) => {
                if let Some(record) = self.records.get_mut(&id)
                    && !record.snapshot.status.terminal()
                {
                    record.snapshot.last_response_id = Some(request_id.clone());
                    record.snapshot.status = AgentStatus::Working;
                    record.awaiting_agent_settle |= waits_for_agent;
                    record.snapshot.updated_at_ms = now_ms();
                }
                self.record_event(&id, "requestStarted", Value::String(request_id));
            }
            WorkerEvent::Pi(id, value) => {
                if let Some(record) = self.records.get_mut(&id) {
                    if let Some(file) = value
                        .pointer("/result/sessionFile")
                        .or_else(|| value.pointer("/state/sessionFile"))
                        .or_else(|| value.get("sessionFile"))
                        .and_then(Value::as_str)
                        .filter(|file| !file.is_empty())
                    {
                        record.snapshot.session_file = Some(file.into());
                    }
                    let event_type = value.get("type").and_then(Value::as_str);
                    if event_type == Some("agent_settled") && !record.snapshot.status.terminal() {
                        record.awaiting_agent_settle = false;
                        record.snapshot.status = AgentStatus::Idle;
                    }
                    if event_type == Some("response")
                        && !record.awaiting_agent_settle
                        && !record.snapshot.status.terminal()
                    {
                        record.snapshot.status = AgentStatus::Idle;
                    }
                    record.snapshot.event_count = record.snapshot.event_count.saturating_add(1);
                    record.snapshot.updated_at_ms = now_ms();
                    if record.snapshot.evidence.len() == AGENT_EVIDENCE_CAPACITY {
                        record.snapshot.evidence.remove(0);
                    }
                    record.snapshot.evidence.push(value.clone());
                }
                let kind = value
                    .get("type")
                    .and_then(Value::as_str)
                    .unwrap_or("piEvent")
                    .to_string();
                self.record_event(&id, &kind, value);
            }
            WorkerEvent::Failed(id, error) => {
                if let Some(record) = self.records.get_mut(&id)
                    && !record.snapshot.status.terminal()
                {
                    record.snapshot.status = AgentStatus::Failed;
                    record.snapshot.last_error = Some(error.clone());
                    record.snapshot.updated_at_ms = now_ms();
                    record.command = None;
                }
                self.record_event(&id, "failed", Value::String(error));
            }
            WorkerEvent::Stopped(id) => {
                if let Some(record) = self.records.get_mut(&id) {
                    record.command = None;
                }
                self.record_event(&id, "stopped", Value::Null);
            }
        }
    }

    fn join_worker(&mut self, id: &AgentId, terminal: AgentStatus) -> DevelopmentResult<()> {
        let worker = self.record_mut(id)?.worker.take();
        if let Some(worker) = worker
            && worker.join().is_err()
        {
            let error = format!("agent {} worker panicked", id.as_str());
            let record = self.record_mut(id)?;
            record.command = None;
            record.snapshot.status = AgentStatus::Failed;
            record.snapshot.last_error = Some(error.clone());
            record.snapshot.updated_at_ms = now_ms();
            self.record_event(
                id,
                "workerPanicked",
                serde_json::json!({"agentId":id.as_str(),"error":error}),
            );
            return Err(DevelopmentError::Process(error));
        }
        let record = self.record_mut(id)?;
        record.command = None;
        record.snapshot.status = terminal;
        record.snapshot.updated_at_ms = now_ms();
        Ok(())
    }

    fn reap_finished_workers(&mut self) {
        let finished = self
            .records
            .iter()
            .filter(|(_, record)| {
                record
                    .worker
                    .as_ref()
                    .is_some_and(|worker| worker.is_finished())
            })
            .map(|(id, _)| id.clone())
            .collect::<Vec<_>>();
        for id in finished {
            let worker = self
                .records
                .get_mut(&id)
                .and_then(|record| record.worker.take());
            let panicked = worker.is_some_and(|worker| worker.join().is_err());
            let mut event = None;
            if let Some(record) = self.records.get_mut(&id) {
                record.command = None;
                if panicked {
                    let error = format!("agent {} worker panicked", id.as_str());
                    record.snapshot.status = AgentStatus::Failed;
                    record.snapshot.last_error = Some(error.clone());
                    record.snapshot.updated_at_ms = now_ms();
                    event = Some((
                        "workerPanicked",
                        serde_json::json!({
                            "agentId":id.as_str(),
                            "role":record.snapshot.role.clone(),
                            "task":record.snapshot.task.clone(),
                            "error":error,
                        }),
                    ));
                } else if !record.snapshot.status.terminal() {
                    let error = format!(
                        "agent {} worker exited before a terminal outcome",
                        id.as_str()
                    );
                    record.snapshot.status = AgentStatus::Failed;
                    record.snapshot.last_error = Some(error.clone());
                    record.snapshot.updated_at_ms = now_ms();
                    event = Some(("workerExited", Value::String(error)));
                }
            }
            if let Some((kind, payload)) = event {
                self.record_event(&id, kind, payload);
            }
        }
    }

    fn record_event(&mut self, id: &AgentId, kind: &str, payload: Value) {
        if self.history.len() == HISTORY_CAPACITY {
            self.history.pop_front();
        }
        self.history.push_back(AgentEvent {
            sequence: self.next_event,
            agent_id: id.clone(),
            timestamp_ms: now_ms(),
            kind: kind.into(),
            payload,
        });
        self.next_event = self.next_event.saturating_add(1);
    }

    fn record_mut(&mut self, id: &AgentId) -> DevelopmentResult<&mut AgentRecord> {
        self.records
            .get_mut(id)
            .ok_or_else(|| DevelopmentError::NotFound(format!("agent {}", id.as_str())))
    }
}

impl Drop for AgentRegistry {
    fn drop(&mut self) {
        let mut workers = Vec::new();
        for (id, record) in &mut self.records {
            if let Some(sender) = record.command.take() {
                let _ = sender.try_send(WorkerCommand::Shutdown);
            }
            if let Some(worker) = record.worker.take() {
                workers.push((id.clone(), worker));
            }
        }
        for (id, worker) in workers {
            if worker.join().is_err() {
                tracing::error!(agent_id = %id.as_str(), "agent worker panicked during registry drop");
            }
        }
    }
}

fn run_worker(
    id: AgentId,
    spec: AgentSpec,
    runtime: WorkerRuntime,
    commands: Receiver<WorkerCommand>,
    events: SyncSender<WorkerEvent>,
    dropped_events: Arc<AtomicU64>,
) {
    let options = PiRuntimeOptions {
        unrestricted: spec.unrestricted,
        session_dir: runtime.sessions_dir,
        name: Some(format!("{}: {}", spec.role, id.as_str())),
        model: spec.model,
        thinking: spec.thinking,
        broker: runtime.broker,
        local_tool_executor: runtime.local_tool_executor,
        additional_system_prompt: runtime.additional_system_prompt,
        resume: false,
        fork_from: runtime.fork_from,
    };
    let mut harness = match GlassPiRuntime::spawn(&runtime.worktree, options) {
        Ok(harness) => harness,
        Err(error) => {
            send_critical_worker_event(&events, WorkerEvent::Failed(id, error.to_string()));
            return;
        }
    };
    send_critical_worker_event(&events, WorkerEvent::Ready(id.clone()));
    loop {
        loop {
            match commands.try_recv() {
                Ok(WorkerCommand::Request(request)) => {
                    let waits_for_agent = matches!(
                        request,
                        PiSessionRequest::Prompt { .. }
                            | PiSessionRequest::FollowUp { .. }
                            | PiSessionRequest::Complete { .. }
                    );
                    match harness.start_request(request) {
                        Ok(request_id) => send_critical_worker_event(
                            &events,
                            WorkerEvent::RequestStarted(id.clone(), request_id, waits_for_agent),
                        ),
                        Err(error) => {
                            send_critical_worker_event(
                                &events,
                                WorkerEvent::Failed(id.clone(), error.to_string()),
                            );
                            return;
                        }
                    }
                }
                Ok(WorkerCommand::ApproveTool { frame_id, approved }) => {
                    if let Err(error) = harness.resolve_tool_approval(&frame_id, approved) {
                        send_critical_worker_event(
                            &events,
                            WorkerEvent::Pi(
                                id.clone(),
                                serde_json::json!({
                                    "type":"glass_tool_approval_resolved",
                                    "frameId":frame_id,
                                    "approved":approved,
                                    "ok":false,
                                    "error":error.to_string(),
                                }),
                            ),
                        );
                    }
                }
                Ok(WorkerCommand::Shutdown) | Err(TryRecvError::Disconnected) => {
                    send_critical_worker_event(&events, WorkerEvent::Stopped(id));
                    return;
                }
                Err(TryRecvError::Empty) => break,
            }
        }
        match harness.recv_event_timeout(Duration::from_millis(25)) {
            Ok(Some(value)) => send_lossy_worker_event(
                &events,
                WorkerEvent::Pi(id.clone(), value),
                &dropped_events,
            ),
            Ok(None) => {}
            Err(error) => {
                send_critical_worker_event(&events, WorkerEvent::Failed(id, error.to_string()));
                return;
            }
        }
    }
}

fn send_lossy_worker_event(
    events: &SyncSender<WorkerEvent>,
    event: WorkerEvent,
    dropped_events: &AtomicU64,
) {
    if matches!(events.try_send(event), Err(TrySendError::Full(_))) {
        dropped_events.fetch_add(1, Ordering::Relaxed);
    }
}

fn send_critical_worker_event(events: &SyncSender<WorkerEvent>, event: WorkerEvent) {
    let _ = events.send(event);
}

fn validate_spec(
    root: &Path,
    records: &BTreeMap<AgentId, AgentRecord>,
    spec: &AgentSpec,
) -> DevelopmentResult<()> {
    validate_text("agent role", &spec.role, 128)?;
    validate_text("agent task", &spec.task, MAX_PROMPT_BYTES)?;
    if spec.dependencies.len() > MAX_AGENTS {
        return Err(DevelopmentError::InvalidInput(
            "agent dependency list is too large".into(),
        ));
    }
    let mut unique = BTreeSet::new();
    for dependency in &spec.dependencies {
        if !unique.insert(dependency) {
            return Err(DevelopmentError::InvalidInput(format!(
                "duplicate dependency {}",
                dependency.as_str()
            )));
        }
        if !records.contains_key(dependency) {
            return Err(DevelopmentError::NotFound(format!(
                "dependency agent {}",
                dependency.as_str()
            )));
        }
    }
    if let Some(worktree) = &spec.worktree {
        let worktree = std::fs::canonicalize(worktree)?;
        if worktree == Path::new("/")
            || (!worktree.starts_with(root) && !worktree.join(".git").exists())
        {
            return Err(DevelopmentError::PathOutsideWorkspace(worktree));
        }
    }
    if let Some(path) = &spec.fork_from {
        let path = std::fs::canonicalize(path)?;
        if path == Path::new("/") || !path.starts_with(root) {
            return Err(DevelopmentError::PathOutsideWorkspace(path));
        }
    }
    if spec.max_runtime_seconds == Some(0) || spec.max_events == Some(0) {
        return Err(DevelopmentError::InvalidInput(
            "agent budgets must be greater than zero".into(),
        ));
    }
    Ok(())
}

fn validate_text(description: &str, text: &str, limit: usize) -> DevelopmentResult<()> {
    if text.trim().is_empty() || text.len() > limit || text.contains('\0') {
        return Err(DevelopmentError::InvalidInput(format!(
            "{description} must contain 1..={limit} bytes without NUL"
        )));
    }
    Ok(())
}

fn validate_context_attachment(context: Option<&Value>) -> DevelopmentResult<()> {
    let Some(context) = context else {
        return Ok(());
    };
    if !context.is_object() {
        return Err(DevelopmentError::InvalidInput(
            "agent context attachment must be a JSON object".into(),
        ));
    }
    let size = serde_json::to_vec(context)
        .map_err(|error| DevelopmentError::Serialization(error.to_string()))?
        .len();
    if size > 64 * 1024 {
        return Err(DevelopmentError::InvalidInput(
            "agent context attachment exceeds 64 KiB".into(),
        ));
    }
    Ok(())
}

fn now_ms() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};

    static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);

    fn test_root() -> PathBuf {
        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
        let root = std::env::temp_dir().join(format!(
            "glass-agent-registry-{}-{sequence}",
            std::process::id()
        ));
        std::fs::create_dir_all(&root).unwrap();
        root
    }

    #[test]
    fn lossy_worker_queue_reports_dropped_events() {
        let (sender, _receiver) = mpsc::sync_channel(1);
        let id = AgentId::parse("agent-overflow").unwrap();
        sender.send(WorkerEvent::Ready(id.clone())).unwrap();
        let dropped = AtomicU64::new(0);
        send_lossy_worker_event(
            &sender,
            WorkerEvent::Pi(id, serde_json::json!({"type":"delta"})),
            &dropped,
        );
        assert_eq!(dropped.load(Ordering::Relaxed), 1);
    }

    fn insert_test_worker(
        registry: &mut AgentRegistry,
        id: AgentId,
        command: SyncSender<WorkerCommand>,
        worker: thread::JoinHandle<()>,
    ) {
        let spec = AgentSpec::new("lifecycle-test", "prove worker ownership");
        let now = now_ms();
        registry.records.insert(
            id.clone(),
            AgentRecord {
                snapshot: AgentSnapshot {
                    id,
                    role: spec.role.clone(),
                    task: spec.task.clone(),
                    status: AgentStatus::Working,
                    dependencies: Vec::new(),
                    model: None,
                    thinking: None,
                    worktree: registry.root.clone(),
                    session_file: None,
                    unrestricted: false,
                    created_at_ms: now,
                    started_at_ms: Some(now),
                    updated_at_ms: now,
                    event_count: 0,
                    dropped_event_count: 0,
                    last_error: None,
                    last_response_id: None,
                    evidence: Vec::new(),
                },
                spec,
                command: Some(command),
                worker: Some(worker),
                awaiting_agent_settle: false,
                dropped_events: Arc::new(AtomicU64::new(0)),
            },
        );
    }

    #[test]
    fn repeated_cancel_joins_every_owned_worker() {
        let root = test_root();
        let mut registry = AgentRegistry::new(&root).unwrap();
        let exited = Arc::new(AtomicU64::new(0));
        for sequence in 0..128 {
            let id = AgentId::parse(format!("agent-test-{sequence}")).unwrap();
            let (command, commands) = mpsc::sync_channel(COMMAND_CAPACITY);
            let exits = Arc::clone(&exited);
            let worker = thread::spawn(move || {
                while let Ok(command) = commands.recv() {
                    if matches!(command, WorkerCommand::Shutdown) {
                        break;
                    }
                }
                exits.fetch_add(1, Ordering::SeqCst);
            });
            insert_test_worker(&mut registry, id.clone(), command, worker);
            registry.cancel(&id).unwrap();
            let record = registry.records.get(&id).unwrap();
            assert_eq!(record.snapshot.status, AgentStatus::Cancelled);
            assert!(record.worker.is_none());
        }
        assert_eq!(exited.load(Ordering::SeqCst), 128);
        drop(registry);
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn worker_panic_becomes_attributed_agent_failure() {
        let root = test_root();
        let mut registry = AgentRegistry::new(&root).unwrap();
        let id = AgentId::parse("agent-panic-test").unwrap();
        let (command, _commands) = mpsc::sync_channel(COMMAND_CAPACITY);
        let worker = thread::spawn(|| panic!("intentional worker panic"));
        worker.thread().unpark();
        insert_test_worker(&mut registry, id.clone(), command, worker);
        for _ in 0..100 {
            registry.refresh().unwrap();
            if registry.records[&id].snapshot.status == AgentStatus::Failed {
                break;
            }
            thread::sleep(Duration::from_millis(5));
        }
        let snapshot = registry.snapshot(&id).unwrap();
        assert_eq!(snapshot.status, AgentStatus::Failed);
        assert!(snapshot.last_error.unwrap().contains(id.as_str()));
        assert!(registry.history(0).unwrap().iter().any(|event| {
            event.agent_id == id
                && event.kind == "workerPanicked"
                && event.payload["role"] == "lifecycle-test"
        }));
        drop(registry);
        std::fs::remove_dir_all(root).unwrap();
    }

    fn wait_for_status(
        registry: &mut AgentRegistry,
        id: &AgentId,
        expected: AgentStatus,
    ) -> AgentSnapshot {
        for _ in 0..800 {
            let snapshot = registry.snapshot(id).unwrap();
            if snapshot.status == expected {
                return snapshot;
            }
            if snapshot.status == AgentStatus::Failed {
                panic!("agent failed: {:?}", snapshot.last_error);
            }
            thread::sleep(Duration::from_millis(25));
        }
        panic!("agent did not reach {expected:?}");
    }

    #[test]
    fn independent_pi_sessions_schedule_dependencies_and_stream_state() {
        if std::process::Command::new("pi")
            .arg("--version")
            .output()
            .is_err()
        {
            return;
        }
        let root = test_root();
        let mut registry = AgentRegistry::new(&root).unwrap();
        let first = registry
            .create(AgentSpec::new("implementer", "inspect state"))
            .unwrap();
        let peer = registry
            .create(AgentSpec::new("researcher", "inspect independent state"))
            .unwrap();
        wait_for_status(&mut registry, &first, AgentStatus::Idle);
        wait_for_status(&mut registry, &peer, AgentStatus::Idle);
        registry.request(&first, PiSessionRequest::State).unwrap();
        registry.request(&peer, PiSessionRequest::State).unwrap();
        for _ in 0..200 {
            let snapshot = registry.snapshot(&first).unwrap();
            if snapshot
                .evidence
                .iter()
                .any(|event| event.get("type").and_then(Value::as_str) == Some("response"))
            {
                break;
            }
            thread::sleep(Duration::from_millis(25));
        }
        assert!(registry.snapshot(&first).unwrap().event_count > 0);
        for _ in 0..200 {
            if registry.snapshot(&peer).unwrap().event_count > 0 {
                break;
            }
            thread::sleep(Duration::from_millis(25));
        }
        assert!(registry.snapshot(&peer).unwrap().event_count > 0);

        let mut dependent = AgentSpec::new("reviewer", "review evidence");
        dependent.dependencies.push(first.clone());
        let second = registry.create(dependent).unwrap();
        assert_eq!(
            registry.snapshot(&second).unwrap().status,
            AgentStatus::Queued
        );
        registry.complete(&first).unwrap();
        wait_for_status(&mut registry, &second, AgentStatus::Idle);
        assert_ne!(first, second);
        registry.cancel(&second).unwrap();
        assert_eq!(
            registry.snapshot(&second).unwrap().status,
            AgentStatus::Cancelled
        );
        registry.restart(&second).unwrap();
        wait_for_status(&mut registry, &second, AgentStatus::Idle);
        registry.cancel(&second).unwrap();
        registry.cancel(&peer).unwrap();
        drop(registry);
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn invalid_agent_specs_and_failed_dependencies_fail_closed() {
        let root = test_root();
        let mut registry = AgentRegistry::new(&root).unwrap();
        assert!(registry.create(AgentSpec::new("", "task")).is_err());
        let first = registry.create(AgentSpec::new("lead", "task")).unwrap();
        let mut dependent = AgentSpec::new("review", "task");
        dependent.dependencies.push(first.clone());
        let second = registry.create(dependent).unwrap();
        registry.cancel(&first).unwrap();
        assert_eq!(
            registry.snapshot(&second).unwrap().status,
            AgentStatus::Failed
        );
        drop(registry);
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn context_attachments_are_bounded_json_objects() {
        assert!(validate_context_attachment(None).is_ok());
        assert!(validate_context_attachment(Some(&serde_json::json!("text"))).is_err());
        let oversized = serde_json::json!({"text": "x".repeat(64 * 1024)});
        assert!(validate_context_attachment(Some(&oversized)).is_err());
        let bounded = serde_json::json!({
            "schemaVersion": "glass.agent-context.v1",
            "browser": {"browserRevision": 12}
        });
        assert!(validate_context_attachment(Some(&bounded)).is_ok());
    }
}