car-server-core 0.50.0

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
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
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
//! The `agent.chat` harness — makes the assistant a real conversational agent.
//!
//! [`AssistantService`] holds one runtime + a per-`session_id` conversation
//! thread and turns each `agent.chat` request into a loop run, streaming
//! `agent.chat.event` payloads as they're produced. It is transport-agnostic:
//! the caller supplies an async `emit` sink (the `--serve` path forwards it to
//! `DaemonClient::notify`), so the same service is unit-testable without a live
//! daemon. This is the reusable piece that closes the harness gap — until now
//! only bespoke agents (Milo) implemented the agent side of `agent.chat`.
//!
//! Streaming discipline (per `docs/host-protocol.md`): the loop's synchronous
//! `emit` writes into a bounded channel drained by a dedicated task that awaits
//! `emit`, so a slow downstream never blocks the loop and the ack is never
//! delayed behind token production.

use std::collections::HashMap;
use std::future::Future;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex as StdMutex};
use std::time::Duration;

use car_engine::Runtime;
use car_inference::tasks::generate::{ContentBlock, Message, Provenance, ToolCall};
use car_ir::{ActionProposal, ActionStatus};
use serde_json::{json, Value};
use tokio::sync::{mpsc, oneshot, Mutex as AsyncMutex};

use super::agent_loop::{
    run_assistant_goal_loop_in_session_durable, run_assistant_loop_cancellable_in_session_durable,
    ApprovalDecision, ApprovalGate, AssistantEvent,
};
use super::governance::AssistantDurability;
use super::AssistantConfig;
use crate::coder::native_loop::TurnGenerator;

/// How long a chat turn waits for a host approval before treating it as declined.
const APPROVAL_TIMEOUT: Duration = Duration::from_secs(300);

/// Deterministic completion check for a goal-driven chat turn.
#[derive(Clone, Debug)]
pub struct ChatGoal {
    pub check: String,
    pub max_iterations: u32,
}

/// A single-action `shell` proposal used to run a chat goal's completion check
/// on the bound substrate, audited through the runtime like any other tool.
fn shell_check_proposal(command: &str) -> car_ir::ActionProposal {
    serde_json::from_value(json!({
        "source": "chat-goal-check",
        "actions": [{
            "id": "goal_check",
            "type": "tool_call",
            "tool": "shell",
            "parameters": { "command": command },
        }],
    }))
    .expect("static shell-check proposal shape")
}

async fn run_shell_check_with_approval(
    runtime: &Runtime,
    cfg: &AssistantConfig,
    approval: Option<&dyn ApprovalGate>,
    command: &str,
) -> i32 {
    if cfg.gated_tools.iter().any(|tool| tool == "shell") {
        let params = json!({ "command": command, "purpose": "goal_check" });
        match approval {
            Some(gate) => match gate.request("shell", &params).await {
                ApprovalDecision::Approved => {}
                ApprovalDecision::Denied(_) => return 1,
            },
            None => return 1,
        }
    }

    let exec = runtime.execute(&shell_check_proposal(command)).await;
    exec.results
        .first()
        .and_then(|r| r.output.as_ref())
        .and_then(|o| o.get("exit_code"))
        .and_then(|v| v.as_i64())
        .unwrap_or(1) as i32
}

/// A conversational assistant over one runtime, multiplexed by `session_id`.
pub struct AssistantService {
    generator: Arc<dyn TurnGenerator>,
    runtime: Arc<Runtime>,
    cfg: AssistantConfig,
    /// System prompt seeded as the first message of every new thread.
    system: String,
    /// Per-session conversation threads (multi-turn continuity).
    threads: AsyncMutex<HashMap<String, Vec<Message>>>,
    /// Per-session cancellation flags, set by [`Self::cancel`].
    cancels: StdMutex<HashMap<String, Arc<AtomicBool>>>,
    /// Runtime session ids paired with externally visible chat session ids. The
    /// runtime uses these to keep stateful tool safety guards isolated while
    /// this service multiplexes conversations through one shared executor.
    runtime_sessions: AsyncMutex<HashMap<String, String>>,
    /// Pending approvals awaiting a host decision, keyed by approval id. Resolved
    /// by [`Self::resolve_approval`] (driven by the `agent.chat.approve` call).
    approvals: Arc<StdMutex<HashMap<String, oneshot::Sender<bool>>>>,
    /// Oplog-backed exact transcript/action persistence. `None` only for
    /// one-shot/tests that do not opt into supervised durability.
    durability: Option<Arc<dyn AssistantDurability>>,
    repository_root: Option<PathBuf>,
}

impl AssistantService {
    pub fn new(
        generator: Arc<dyn TurnGenerator>,
        runtime: Arc<Runtime>,
        cfg: AssistantConfig,
        system: String,
    ) -> Self {
        Self {
            generator,
            runtime,
            cfg,
            system,
            threads: AsyncMutex::new(HashMap::new()),
            cancels: StdMutex::new(HashMap::new()),
            runtime_sessions: AsyncMutex::new(HashMap::new()),
            approvals: Arc::new(StdMutex::new(HashMap::new())),
            durability: None,
            repository_root: None,
        }
    }

    pub fn new_durable(
        generator: Arc<dyn TurnGenerator>,
        runtime: Arc<Runtime>,
        cfg: AssistantConfig,
        system: String,
        durability: Arc<dyn AssistantDurability>,
        repository_root: PathBuf,
    ) -> Self {
        let mut service = Self::new(generator, runtime, cfg, system);
        service.durability = Some(durability);
        service.repository_root = Some(repository_root);
        service
    }

    fn config_for_model(&self, model: Option<&str>) -> AssistantConfig {
        let mut cfg = self.cfg.clone();
        if let Some(model) = model.map(str::trim).filter(|model| !model.is_empty()) {
            cfg.model = Some(model.to_string());
            cfg.strict_model = true;
        }
        cfg
    }

    async fn runtime_session_for(&self, session_id: &str) -> String {
        let mut sessions = self.runtime_sessions.lock().await;
        if let Some(runtime_session) = sessions.get(session_id) {
            return runtime_session.clone();
        }
        let runtime_session = self.runtime.open_session().await;
        sessions.insert(session_id.to_string(), runtime_session.clone());
        runtime_session
    }

    /// Close any tool-call exchange interrupted by a process restart. An
    /// approved action is dispatched once from its durable scope; a dispatched
    /// action is marked indeterminate and never replayed; a terminal action is
    /// represented by a synthetic tool result so provider history stays valid.
    async fn reconcile_dangling_actions(
        &self,
        session_id: &str,
        runtime_session: &str,
        messages: &mut Vec<Message>,
    ) -> Result<(), String> {
        let Some(store) = &self.durability else {
            return Ok(());
        };
        let answered: std::collections::HashSet<String> = messages
            .iter()
            .filter_map(|message| match message {
                Message::ToolResult { tool_use_id, .. } => Some(tool_use_id.clone()),
                _ => None,
            })
            .collect();
        let calls: Vec<ToolCall> = messages
            .iter()
            .flat_map(|message| match message {
                Message::Assistant { tool_calls, .. } => tool_calls.clone(),
                _ => Vec::new(),
            })
            .filter(|call| call.id.as_ref().is_some_and(|id| !answered.contains(id)))
            .collect();
        for call in calls {
            let call_id = call.id.clone().expect("filtered to calls with ids");
            let params = serde_json::to_value(&call.arguments).unwrap_or(Value::Null);
            let Some(scope) = action_scope(self.repository_root.as_ref(), &call.name, &params)
            else {
                messages.push(Message::ToolResult {
                    tool_use_id: call_id,
                    content: json!({"error": "tool call was interrupted before a durable action scope existed; not replayed"}).to_string(),
                    provenance: Provenance::Internal,
                });
                continue;
            };
            let candidate =
                super::governance::SupervisedActionRecord::propose(session_id, &call_id, scope);
            let Some(mut record) = store.load_action(&candidate.id).await? else {
                messages.push(Message::ToolResult {
                    tool_use_id: call_id,
                    content:
                        json!({"error": "tool call was interrupted before approval; not replayed"})
                            .to_string(),
                    provenance: Provenance::Internal,
                });
                continue;
            };
            let content = match record.state {
                super::governance::ActionState::Approved => {
                    record.transition(super::governance::ActionState::Dispatched, None)?;
                    store.record_action(&record).await?;
                    let proposal: ActionProposal = serde_json::from_value(json!({
                        "source": "durable-resume",
                        "actions": [{
                            "id": call_id,
                            "type": "tool_call",
                            "tool": call.name,
                            "parameters": params,
                        }],
                    }))
                    .map_err(|e| format!("cannot rebuild approved action on resume: {e}"))?;
                    let exec = self
                        .runtime
                        .execute_with_session(&proposal, runtime_session)
                        .await;
                    let result = exec.results.first();
                    let ok = result.is_some_and(|result| {
                        matches!(result.status, ActionStatus::Succeeded)
                            && (call.name != "shell"
                                || result
                                    .output
                                    .as_ref()
                                    .and_then(|output| output.get("exit_code"))
                                    .and_then(Value::as_i64)
                                    == Some(0))
                    });
                    let receipt = json!({
                        "ok": ok,
                        "action_id": result.map(|result| result.action_id.clone()),
                        "output": result.and_then(|result| result.output.clone()),
                    });
                    record.transition(
                        if ok {
                            super::governance::ActionState::Completed
                        } else {
                            super::governance::ActionState::Failed
                        },
                        Some(receipt.clone()),
                    )?;
                    store.record_action(&record).await?;
                    receipt.to_string()
                }
                super::governance::ActionState::Dispatched => {
                    record.transition(
                        super::governance::ActionState::Indeterminate,
                        Some(json!({"reason": "process restarted after dispatch without a terminal receipt"})),
                    )?;
                    store.record_action(&record).await?;
                    json!({"error": "action outcome is indeterminate after restart; it was not replayed"}).to_string()
                }
                super::governance::ActionState::Completed
                | super::governance::ActionState::Failed => record
                    .receipt
                    .clone()
                    .unwrap_or_else(|| json!({"status": format!("{:?}", record.state)}))
                    .to_string(),
                super::governance::ActionState::Proposed => {
                    json!({"error": "approval was interrupted; action was not dispatched"})
                        .to_string()
                }
                super::governance::ActionState::Denied
                | super::governance::ActionState::Indeterminate => {
                    json!({"error": format!("durable action is {:?}; not replayed", record.state)})
                        .to_string()
                }
            };
            messages.push(Message::ToolResult {
                tool_use_id: call_id,
                content,
                provenance: Provenance::Internal,
            });
        }
        Ok(())
    }

    /// Signal the session's in-flight turn to stop before its next model call.
    pub fn cancel(&self, session_id: &str) {
        if let Ok(g) = self.cancels.lock() {
            if let Some(flag) = g.get(session_id) {
                flag.store(true, Ordering::Relaxed);
            }
        }
    }

    /// Resolve a pending approval (from an `agent.chat.approve` reverse-call).
    /// Returns true if an approval by that id was waiting.
    pub fn resolve_approval(&self, approval_id: &str, approved: bool) -> bool {
        let tx = self
            .approvals
            .lock()
            .ok()
            .and_then(|mut g| g.remove(approval_id));
        match tx {
            Some(tx) => tx.send(approved).is_ok(),
            None => false,
        }
    }

    /// Run one chat turn for `session_id`, streaming `agent.chat.event` payloads
    /// (each already stamped with `session_id`) through `emit`. Returns when the
    /// turn reaches a terminal state. `attachments` are image `ContentBlock`s
    /// (`image_base64`/`image_url`) forwarded to a vision model on the first
    /// model call. The caller should have already acked the `agent.chat` request
    /// and spawned this on its own task.
    pub async fn handle_turn<E, Fut>(
        &self,
        session_id: &str,
        prompt: &str,
        attachments: Option<Vec<Value>>,
        emit: E,
    ) where
        E: Fn(Value) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.handle_turn_with_model(session_id, prompt, attachments, None, emit)
            .await;
    }

    /// Run one chat turn with an optional host-selected CAR model. A missing
    /// selector preserves the supervised agent's configured model; a supplied
    /// selector is strict so the explicit native choice cannot silently fall
    /// back to a different model.
    pub async fn handle_turn_with_model<E, Fut>(
        &self,
        session_id: &str,
        prompt: &str,
        attachments: Option<Vec<Value>>,
        model: Option<&str>,
        emit: E,
    ) where
        E: Fn(Value) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let cfg = self.config_for_model(model);
        let runtime_session = self.runtime_session_for(session_id).await;
        // Image attachments → ContentBlocks for the vision path. The daemon
        // already validated the shape; keep only image blocks.
        let images: Vec<ContentBlock> = attachments
            .unwrap_or_default()
            .into_iter()
            .filter_map(|a| serde_json::from_value::<ContentBlock>(a).ok())
            .filter(|c| {
                matches!(
                    c,
                    ContentBlock::ImageBase64 { .. } | ContentBlock::ImageUrl { .. }
                )
            })
            .collect();

        // Fresh cancel flag per turn.
        let cancel = Arc::new(AtomicBool::new(false));
        if let Ok(mut g) = self.cancels.lock() {
            g.insert(session_id.to_string(), cancel.clone());
        }

        // Load (or seed) the thread; append the user turn. Clone out so the loop
        // doesn't hold the threads lock across its awaits.
        let cached = self.threads.lock().await.get(session_id).cloned();
        let mut messages = match cached {
            Some(existing) => existing,
            None => {
                let restored = match &self.durability {
                    Some(store) => match store.load_checkpoint(session_id).await {
                        Ok(checkpoint) => checkpoint.map(|checkpoint| checkpoint.messages),
                        Err(e) => {
                            emit(json!({
                                "kind": "error",
                                "error": format!("durable transcript resume failed: {e}"),
                                "session_id": session_id,
                            }))
                            .await;
                            if let Ok(mut g) = self.cancels.lock() {
                                g.remove(session_id);
                            }
                            return;
                        }
                    },
                    None => None,
                };
                let seeded = restored.unwrap_or_else(|| {
                    vec![Message::System {
                        content: self.system.clone(),
                    }]
                });
                self.threads
                    .lock()
                    .await
                    .insert(session_id.to_string(), seeded.clone());
                seeded
            }
        };
        if let Err(e) = self
            .reconcile_dangling_actions(session_id, &runtime_session, &mut messages)
            .await
        {
            emit(json!({
                "kind": "error",
                "error": format!("durable action reconciliation failed: {e}"),
                "session_id": session_id,
            }))
            .await;
            return;
        }
        messages.push(Message::User {
            content: prompt.to_string(),
        });
        if let Some(store) = &self.durability {
            if let Err(e) = store
                .checkpoint(session_id, &messages, "user_turn", None)
                .await
            {
                emit(json!({
                    "kind": "error",
                    "error": format!("durable checkpoint failed before inference: {e}"),
                    "session_id": session_id,
                }))
                .await;
                return;
            }
        }

        // Stream events through a channel drained by a dedicated task, so the
        // loop's synchronous emit never blocks on the async sink.
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Value>();
        let drain = tokio::spawn(async move {
            while let Some(v) = rx.recv().await {
                emit(v).await;
            }
        });

        let sid = session_id.to_string();
        // `tx_term` streams the synthesized terminal event after the loop; the
        // loop's emit closure and the gate each hold their own clone. Dropping
        // all three closes the channel so the drain task ends.
        let tx_term = tx.clone();
        let gate = ChatApprovalGate {
            session_id: sid.clone(),
            tx: tx.clone(),
            approvals: self.approvals.clone(),
            counter: Arc::new(AtomicU64::new(0)),
            durability: self.durability.clone(),
            repository_root: self.repository_root.clone(),
        };
        let outcome = run_assistant_loop_cancellable_in_session_durable(
            &*self.generator,
            &self.runtime,
            &cfg,
            &mut messages,
            &cancel,
            Some(&gate),
            if images.is_empty() {
                None
            } else {
                Some(images.as_slice())
            },
            Some(&runtime_session),
            Some(session_id),
            self.durability.as_deref(),
            true,
            {
                let sid = sid.clone();
                move |ev| {
                    // Emit the receipt matrix immediately before one terminal
                    // event below, so hosts never see evidence arrive after
                    // `done` and mistake an earlier proxy for completion.
                    if matches!(ev, AssistantEvent::Done { .. } | AssistantEvent::Error(_)) {
                        return;
                    }
                    if let Some(mut payload) = event_to_wire(ev) {
                        payload["session_id"] = json!(sid);
                        let _ = tx.send(payload);
                    }
                }
            },
        )
        .await;
        drop(gate); // release the gate's channel clone

        let completion = super::governance::completion_matrix_from_messages(&messages);
        let ungrounded_claims =
            super::agent_loop::ungrounded_summary_claims(&outcome.summary, &outcome.tool_receipts);
        let _ = tx_term.send(json!({
            "kind": "receipt_report",
            "completion": completion,
            "ungrounded_claims": ungrounded_claims,
            "session_id": sid,
        }));
        let terminal_summary = super::agent_loop::annotate_summary_with_claim_note(
            &outcome.summary,
            &ungrounded_claims,
        );
        let terminal = match outcome.status {
            "cancelled" | "error" => {
                json!({ "kind": "error", "error": terminal_summary, "session_id": sid })
            }
            _ => json!({ "kind": "done", "text": terminal_summary, "session_id": sid }),
        };
        let _ = tx_term.send(terminal);

        drop(tx_term);
        let _ = drain.await;

        // Persist the thread (unless cancelled mid-turn, where the partial
        // assistant/tool messages would leave a dangling exchange).
        if outcome.status != "cancelled" {
            let mut g = self.threads.lock().await;
            g.insert(session_id.to_string(), messages);
        }
        if let Ok(mut g) = self.cancels.lock() {
            g.remove(session_id);
        }
    }

    /// Run one chat turn as a deterministic goal loop. The user prompt is the
    /// pinned objective; completion is decided by `goal.check` exiting 0 through
    /// the runtime, and every verifier pass streams `goal_evaluated`.
    pub async fn handle_goal_turn<E, Fut>(
        &self,
        session_id: &str,
        prompt: &str,
        _attachments: Option<Vec<Value>>,
        goal: ChatGoal,
        emit: E,
    ) where
        E: Fn(Value) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.handle_goal_turn_with_model(session_id, prompt, _attachments, goal, None, emit)
            .await;
    }

    /// Goal-turn counterpart to [`Self::handle_turn_with_model`].
    pub async fn handle_goal_turn_with_model<E, Fut>(
        &self,
        session_id: &str,
        prompt: &str,
        _attachments: Option<Vec<Value>>,
        goal: ChatGoal,
        model: Option<&str>,
        emit: E,
    ) where
        E: Fn(Value) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let cfg = self.config_for_model(model);
        use car_verify::goal::{GoalCondition, GoalGovernor, GoalSpec, GoalStatus};

        let runtime_session = self.runtime_session_for(session_id).await;

        let cancel = Arc::new(AtomicBool::new(false));
        if let Ok(mut g) = self.cancels.lock() {
            g.insert(session_id.to_string(), cancel.clone());
        }

        // Goal-loop turns are anchored to the objective every iteration. On a
        // process restart, resume the exact checkpoint instead of silently
        // seeding a fresh goal conversation.
        let mut messages = match &self.durability {
            Some(store) => match store.load_checkpoint(session_id).await {
                Ok(Some(checkpoint)) => checkpoint.messages,
                Ok(None) => vec![Message::System {
                    content: format!(
                        "{}\n\nYou are working toward a goal. Completion is verified \
                         deterministically by running this shell command:\n  {}\nIt is \
                         done only when that command exits 0. Keep working until it does.",
                        self.system, goal.check
                    ),
                }],
                Err(e) => {
                    emit(json!({
                        "kind": "error",
                        "error": format!("durable goal resume failed: {e}"),
                        "session_id": session_id,
                    }))
                    .await;
                    return;
                }
            },
            None => vec![Message::System {
                content: format!(
                    "{}\n\nYou are working toward a goal. Completion is verified \
                     deterministically by running this shell command:\n  {}\nIt is \
                     done only when that command exits 0. Keep working until it does.",
                    self.system, goal.check
                ),
            }],
        };
        if let Err(e) = self
            .reconcile_dangling_actions(session_id, &runtime_session, &mut messages)
            .await
        {
            emit(json!({
                "kind": "error",
                "error": format!("durable goal action reconciliation failed: {e}"),
                "session_id": session_id,
            }))
            .await;
            return;
        }

        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Value>();
        let drain = tokio::spawn(async move {
            while let Some(v) = rx.recv().await {
                emit(v).await;
            }
        });

        let sid = session_id.to_string();
        let tx_term = tx.clone();
        let gate = ChatApprovalGate {
            session_id: sid.clone(),
            tx: tx.clone(),
            approvals: self.approvals.clone(),
            counter: Arc::new(AtomicU64::new(0)),
            durability: self.durability.clone(),
            repository_root: self.repository_root.clone(),
        };
        let check_gate = gate.clone();
        let spec = GoalSpec {
            goal: prompt.to_string(),
            condition: GoalCondition::Command {
                id: "goal_check".into(),
                expect_exit: 0,
            },
            governor: GoalGovernor {
                max_turns: Some(goal.max_iterations.max(1)),
                ..Default::default()
            },
        };
        let check = goal.check.clone();
        let check_cfg = cfg.clone();
        let result = run_assistant_goal_loop_in_session_durable(
            &*self.generator,
            &self.runtime,
            &cfg,
            &mut messages,
            &cancel,
            Some(&gate),
            &spec,
            Some(&runtime_session),
            Some(session_id),
            self.durability.as_deref(),
            move |_outcome| {
                let cmd = check.clone();
                let check_gate = check_gate.clone();
                let check_cfg = check_cfg.clone();
                async move {
                    let exit = run_shell_check_with_approval(
                        &self.runtime,
                        &check_cfg,
                        Some(&check_gate),
                        &cmd,
                    )
                    .await;
                    let mut g = car_engine::GoalGather::default();
                    g.command_exits.insert("goal_check".into(), exit);
                    g
                }
            },
            {
                let sid = sid.clone();
                move |ev| {
                    // Inner loop `done`/`error` events are iteration-local; the
                    // goal loop sends one terminal event below after the verifier
                    // achieves or halts.
                    if matches!(ev, AssistantEvent::Done { .. } | AssistantEvent::Error(_)) {
                        return;
                    }
                    if let Some(mut payload) = event_to_wire(ev) {
                        payload["session_id"] = json!(sid);
                        let _ = tx.send(payload);
                    }
                }
            },
        )
        .await;
        drop(gate);

        let completion = super::governance::completion_matrix_from_messages(&messages);
        let _ = tx_term.send(json!({
            "kind": "receipt_report",
            "completion": completion,
            "session_id": sid,
        }));
        let terminal = match result.run.status {
            GoalStatus::Achieved => {
                json!({ "kind": "done", "text": result.outcome.summary, "session_id": sid })
            }
            GoalStatus::Halted { halt } => json!({
                "kind": "error",
                "error": format!(
                    "goal not reached: {} after {} iteration(s); last check: {}",
                    halt.as_str(),
                    result.run.iterations,
                    result.run.last_reason
                ),
                "session_id": sid,
            }),
        };
        let _ = tx_term.send(terminal);

        drop(tx_term);
        let _ = drain.await;

        if !matches!(result.run.status, GoalStatus::Halted { .. }) {
            let mut g = self.threads.lock().await;
            g.insert(session_id.to_string(), messages);
        }
        if let Ok(mut g) = self.cancels.lock() {
            g.remove(session_id);
        }
    }
}

/// The chat-surface approval gate: emit an `approval_pending` event and park on
/// a oneshot resolved by [`AssistantService::resolve_approval`] (driven by the
/// host's `agent.chat.approve` reverse-call). Times out to "declined".
fn action_scope(
    repository_root: Option<&PathBuf>,
    tool: &str,
    params: &Value,
) -> Option<super::governance::ActionScope> {
    let repository_root = repository_root?.clone();
    let command = params
        .get("command")
        .and_then(Value::as_str)
        .unwrap_or_default();
    let target = params
        .get("target")
        .or_else(|| params.get("url"))
        .or_else(|| params.get("path"))
        .and_then(Value::as_str)
        .unwrap_or(command)
        .to_string();
    let environment = params
        .get("environment")
        .and_then(Value::as_str)
        .unwrap_or("unspecified")
        .to_string();
    let lower = format!("{tool} {command}").to_ascii_lowercase();
    let mut capabilities = Vec::new();
    if lower.contains("git push") {
        capabilities.push(super::governance::CredentialCapability(
            "git:configured-remote".into(),
        ));
    }
    if lower.contains("az ") || lower.contains("azure") {
        capabilities.push(super::governance::CredentialCapability(
            "azure:active-account".into(),
        ));
    }
    if lower.contains("sql") || lower.contains("database") || lower.contains("migration") {
        capabilities.push(super::governance::CredentialCapability(
            "database:project-configured".into(),
        ));
    }
    Some(super::governance::ActionScope {
        tool: tool.to_string(),
        parameters: params.clone(),
        repository_root,
        target,
        environment,
        credential_capabilities: capabilities,
    })
}

#[derive(Clone)]
struct ChatApprovalGate {
    session_id: String,
    tx: mpsc::UnboundedSender<Value>,
    approvals: Arc<StdMutex<HashMap<String, oneshot::Sender<bool>>>>,
    counter: Arc<AtomicU64>,
    durability: Option<Arc<dyn AssistantDurability>>,
    repository_root: Option<PathBuf>,
}

impl ChatApprovalGate {
    fn action_scope(&self, tool: &str, params: &Value) -> Option<super::governance::ActionScope> {
        action_scope(self.repository_root.as_ref(), tool, params)
    }

    async fn durable_action(
        &self,
        call_id: &str,
        tool: &str,
        params: &Value,
    ) -> Result<Option<super::governance::SupervisedActionRecord>, String> {
        let (Some(store), Some(scope)) = (&self.durability, self.action_scope(tool, params)) else {
            return Ok(None);
        };
        let action =
            super::governance::SupervisedActionRecord::propose(&self.session_id, call_id, scope);
        Ok(store.load_action(&action.id).await?.or(Some(action)))
    }
}

#[async_trait::async_trait]
impl ApprovalGate for ChatApprovalGate {
    async fn request(&self, tool: &str, params: &Value) -> ApprovalDecision {
        let n = self.counter.fetch_add(1, Ordering::Relaxed);
        self.request_action(&format!("unbound-{n}"), tool, params)
            .await
    }

    async fn request_action(&self, call_id: &str, tool: &str, params: &Value) -> ApprovalDecision {
        let mut action = match self.durable_action(call_id, tool, params).await {
            Ok(action) => action,
            Err(e) => {
                return ApprovalDecision::Denied(format!("cannot persist approval scope: {e}"))
            }
        };
        if let Some(existing) = &action {
            match existing.state {
                super::governance::ActionState::Approved => return ApprovalDecision::Approved,
                super::governance::ActionState::Dispatched => {
                    let mut indeterminate = existing.clone();
                    let _ = indeterminate.transition(
                        super::governance::ActionState::Indeterminate,
                        Some(json!({"reason": "resumed after dispatch without terminal receipt"})),
                    );
                    if let Some(store) = &self.durability {
                        let _ = store.record_action(&indeterminate).await;
                    }
                    return ApprovalDecision::Denied(
                        "action was dispatched before restart and is indeterminate; reconcile it before retrying".into(),
                    );
                }
                super::governance::ActionState::Completed
                | super::governance::ActionState::Failed
                | super::governance::ActionState::Denied
                | super::governance::ActionState::Indeterminate => {
                    return ApprovalDecision::Denied(
                        "this durable action identity is terminal and cannot be replayed".into(),
                    );
                }
                super::governance::ActionState::Proposed => {}
            }
        }
        if let (Some(store), Some(proposed)) = (&self.durability, &action) {
            if store
                .load_action(&proposed.id)
                .await
                .ok()
                .flatten()
                .is_none()
            {
                if let Err(e) = store.record_action(proposed).await {
                    return ApprovalDecision::Denied(format!("cannot record action proposal: {e}"));
                }
            }
        }
        let n = self.counter.fetch_add(1, Ordering::Relaxed);
        let approval_id = format!("{}-appr-{n}", self.session_id);
        let (otx, orx) = oneshot::channel();
        if let Ok(mut g) = self.approvals.lock() {
            g.insert(approval_id.clone(), otx);
        }
        let _ = self.tx.send(json!({
            "kind": "approval_pending",
            "approval_id": approval_id,
            "tool": tool,
            "params": params,
            "session_id": self.session_id,
            "action_id": action.as_ref().map(|record| record.id.clone()),
            "scope": action.as_ref().map(|record| record.scope.clone()),
        }));
        let decision = match tokio::time::timeout(APPROVAL_TIMEOUT, orx).await {
            Ok(Ok(true)) => ApprovalDecision::Approved,
            Ok(Ok(false)) => ApprovalDecision::Denied("declined by user".into()),
            _ => {
                // Timed out or the sender dropped — clean up and treat as denied.
                if let Ok(mut g) = self.approvals.lock() {
                    g.remove(&approval_id);
                }
                ApprovalDecision::Denied("approval timed out".into())
            }
        };
        if let (Some(store), Some(record)) = (&self.durability, action.as_mut()) {
            let next = match &decision {
                ApprovalDecision::Approved => super::governance::ActionState::Approved,
                ApprovalDecision::Denied(_) => super::governance::ActionState::Denied,
            };
            if let Err(e) = record.transition(next, Some(json!({ "approval_id": approval_id }))) {
                return ApprovalDecision::Denied(format!("cannot durably record approval: {e}"));
            }
            if let Err(e) = store.record_action(record).await {
                return ApprovalDecision::Denied(format!("cannot durably record approval: {e}"));
            }
        }
        decision
    }

    async fn before_dispatch(
        &self,
        call_id: &str,
        tool: &str,
        params: &Value,
    ) -> Result<(), String> {
        let Some(mut record) = self.durable_action(call_id, tool, params).await? else {
            return Ok(());
        };
        if record.state != super::governance::ActionState::Approved {
            return Err(format!(
                "action {} is {:?}, not approved",
                record.id, record.state
            ));
        }
        record.transition(super::governance::ActionState::Dispatched, None)?;
        self.durability
            .as_ref()
            .expect("durable action has a store")
            .record_action(&record)
            .await
    }

    async fn after_dispatch(
        &self,
        call_id: &str,
        tool: &str,
        params: &Value,
        ok: bool,
        receipt: &Value,
    ) -> Result<(), String> {
        let Some(mut record) = self.durable_action(call_id, tool, params).await? else {
            return Ok(());
        };
        record.transition(
            if ok {
                super::governance::ActionState::Completed
            } else {
                super::governance::ActionState::Failed
            },
            Some(receipt.clone()),
        )?;
        self.durability
            .as_ref()
            .expect("durable action has a store")
            .record_action(&record)
            .await
    }
}

/// Translate a loop event into an `agent.chat.event` wire payload. Tool results
/// are internal to the loop and not surfaced as their own kind (the model's
/// subsequent text conveys them).
fn event_to_wire(ev: AssistantEvent) -> Option<Value> {
    match ev {
        AssistantEvent::Text(t) => Some(json!({ "kind": "token", "delta": t })),
        AssistantEvent::ToolCall { name, params } => {
            Some(json!({ "kind": "tool_call", "tool": name, "params": params }))
        }
        AssistantEvent::ToolResult { .. } => None,
        AssistantEvent::Done { text } => Some(json!({ "kind": "done", "text": text })),
        AssistantEvent::Error(e) => Some(json!({ "kind": "error", "error": e })),
        AssistantEvent::GoalEvaluated {
            iteration,
            met,
            grounded,
            reason,
        } => Some(json!({
            "kind": "goal_evaluated",
            "iteration": iteration,
            "met": met,
            "grounded": grounded,
            "reason": reason,
        })),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::assistant::executor::GeneralExecutor;
    use async_trait::async_trait;
    use car_engine::{LocalSubstrate, Substrate, ToolExecutor};
    use car_inference::{GenerateRequest, InferenceEngine, InferenceResult};
    use std::sync::atomic::AtomicUsize;

    fn turn(text: &str, tool_calls: Value) -> InferenceResult {
        serde_json::from_value(json!({
            "text": text, "tool_calls": tool_calls,
            "trace_id": "t", "model_used": "scripted", "latency_ms": 0,
        }))
        .unwrap()
    }

    struct Script {
        turns: Vec<InferenceResult>,
        cursor: AtomicUsize,
    }
    #[async_trait]
    impl TurnGenerator for Script {
        async fn generate(&self, _r: GenerateRequest) -> Result<InferenceResult, String> {
            let i = self.cursor.fetch_add(1, Ordering::SeqCst);
            self.turns.get(i).cloned().ok_or("exhausted".into())
        }
    }

    struct RecordingScript {
        requests: Arc<StdMutex<Vec<GenerateRequest>>>,
    }

    #[async_trait]
    impl TurnGenerator for RecordingScript {
        async fn generate(&self, request: GenerateRequest) -> Result<InferenceResult, String> {
            self.requests.lock().unwrap().push(request);
            Ok(turn("done", json!([])))
        }
    }

    async fn runtime(dir: &std::path::Path) -> Arc<Runtime> {
        let substrate: Arc<dyn Substrate> = Arc::new(LocalSubstrate::new());
        let exec: Arc<dyn ToolExecutor> =
            Arc::new(GeneralExecutor::new(substrate.clone(), dir, true));
        let rt = Runtime::new()
            .with_inference(Arc::new(InferenceEngine::new(Default::default())))
            .with_executor(exec)
            .with_substrate(substrate);
        rt.register_agent_basics().await;
        rt.register_tool_entry(
            car_engine::ToolEntry::new(car_ir::builtins::shell()).with_side_effects(true),
        )
        .await;
        Arc::new(rt)
    }

    struct FixedApproval(bool);

    #[async_trait]
    impl ApprovalGate for FixedApproval {
        async fn request(&self, _tool: &str, _params: &Value) -> ApprovalDecision {
            if self.0 {
                ApprovalDecision::Approved
            } else {
                ApprovalDecision::Denied("denied".into())
            }
        }
    }

    #[derive(Default)]
    struct MemoryDurability {
        actions: AsyncMutex<HashMap<String, super::super::governance::SupervisedActionRecord>>,
        checkpoints: AsyncMutex<HashMap<String, super::super::governance::AssistantCheckpoint>>,
    }

    #[async_trait]
    impl AssistantDurability for MemoryDurability {
        async fn load_checkpoint(
            &self,
            session_id: &str,
        ) -> Result<Option<super::super::governance::AssistantCheckpoint>, String> {
            Ok(self.checkpoints.lock().await.get(session_id).cloned())
        }

        async fn checkpoint(
            &self,
            session_id: &str,
            messages: &[Message],
            reason: &str,
            goal: Option<Value>,
        ) -> Result<(), String> {
            let mut checkpoints = self.checkpoints.lock().await;
            let revision = checkpoints
                .get(session_id)
                .map(|checkpoint| checkpoint.revision + 1)
                .unwrap_or(1);
            checkpoints.insert(
                session_id.to_string(),
                super::super::governance::AssistantCheckpoint {
                    id: session_id.to_string(),
                    session_id: session_id.to_string(),
                    revision,
                    repository_root: PathBuf::from("/fixture/repo"),
                    messages: messages.to_vec(),
                    goal,
                    compaction: Some(json!({ "reason": reason })),
                    completion: super::super::governance::completion_matrix_from_messages(messages),
                },
            );
            Ok(())
        }

        async fn load_action(
            &self,
            action_id: &str,
        ) -> Result<Option<super::super::governance::SupervisedActionRecord>, String> {
            Ok(self.actions.lock().await.get(action_id).cloned())
        }

        async fn record_action(
            &self,
            record: &super::super::governance::SupervisedActionRecord,
        ) -> Result<(), String> {
            self.actions
                .lock()
                .await
                .insert(record.id.clone(), record.clone());
            Ok(())
        }
    }

    #[tokio::test]
    async fn restarted_service_resumes_by_stable_host_session_id() {
        let dir = tempfile::tempdir().unwrap();
        let durability = Arc::new(MemoryDurability::default());
        let cfg = AssistantConfig {
            model: Some("scripted".into()),
            strict_model: false,
            max_turns: 2,
            tools: GeneralExecutor::tool_defs(),
            gated_tools: Vec::new(),
            approval_policy: None,
            proactive_memory: None,
            tool_labels: None,
            todos: None,
            value_store_previews: false,
        };

        let first = AssistantService::new_durable(
            Arc::new(Script {
                turns: vec![turn("phase-one-evidence", json!([]))],
                cursor: AtomicUsize::new(0),
            }),
            runtime(dir.path()).await,
            cfg.clone(),
            "sys".into(),
            durability.clone(),
            dir.path().to_path_buf(),
        );
        first
            .handle_turn("stable-host-session", "investigate", None, |_| async {})
            .await;
        drop(first);

        let second = AssistantService::new_durable(
            Arc::new(Script {
                turns: vec![turn("continuity-confirmed", json!([]))],
                cursor: AtomicUsize::new(0),
            }),
            runtime(dir.path()).await,
            cfg,
            "sys".into(),
            durability.clone(),
            dir.path().to_path_buf(),
        );
        second
            .handle_turn(
                "stable-host-session",
                "continue without repeating",
                None,
                |_| async {},
            )
            .await;

        let checkpoints = durability.checkpoints.lock().await;
        assert_eq!(
            checkpoints.len(),
            1,
            "runtime UUIDs must not become checkpoint keys"
        );
        let resumed = checkpoints
            .get("stable-host-session")
            .expect("stable session checkpoint");
        let transcript = serde_json::to_string(&resumed.messages).unwrap();
        assert!(transcript.contains("phase-one-evidence"));
        assert!(transcript.contains("continue without repeating"));
        assert!(transcript.contains("continuity-confirmed"));
    }

    #[tokio::test]
    async fn unsupported_final_claim_is_redriven_before_done() {
        let dir = tempfile::tempdir().unwrap();
        let script = Arc::new(Script {
            turns: vec![
                turn("The repository is clean.", json!([])),
                turn(
                    "No git status receipt is available, so repository state remains unknown.",
                    json!([]),
                ),
            ],
            cursor: AtomicUsize::new(0),
        });
        let cfg = AssistantConfig {
            model: Some("scripted".into()),
            strict_model: false,
            max_turns: 3,
            tools: GeneralExecutor::tool_defs(),
            gated_tools: Vec::new(),
            approval_policy: None,
            proactive_memory: None,
            tool_labels: None,
            todos: None,
            value_store_previews: false,
        };
        let service =
            AssistantService::new(script.clone(), runtime(dir.path()).await, cfg, "sys".into());
        let events = Arc::new(StdMutex::new(Vec::<Value>::new()));
        let captured = events.clone();
        service
            .handle_turn("claims", "inspect", None, move |event| {
                let captured = captured.clone();
                async move { captured.lock().unwrap().push(event) }
            })
            .await;

        assert_eq!(script.cursor.load(Ordering::SeqCst), 2);
        let events = events.lock().unwrap();
        let done = events.iter().find(|event| event["kind"] == "done").unwrap();
        assert!(done["text"].as_str().unwrap().contains("remains unknown"));
        assert!(!done["text"].as_str().unwrap().contains("[claim check]"));
    }

    #[tokio::test]
    async fn scoped_approval_is_durable_exact_and_auditable() {
        let repo = tempfile::tempdir().unwrap();
        std::fs::create_dir(repo.path().join(".git")).unwrap();
        let durability = Arc::new(MemoryDurability::default());
        let approvals = Arc::new(StdMutex::new(HashMap::new()));
        let (tx, mut rx) = mpsc::unbounded_channel();
        let gate = ChatApprovalGate {
            session_id: "s1".into(),
            tx,
            approvals: approvals.clone(),
            counter: Arc::new(AtomicU64::new(0)),
            durability: Some(durability.clone()),
            repository_root: Some(repo.path().to_path_buf()),
        };
        let params = json!({
            "command": "git push origin HEAD:main",
            "target": "origin/main",
            "environment": "fixture"
        });
        let pending_gate = gate.clone();
        let pending_params = params.clone();
        let pending = tokio::spawn(async move {
            pending_gate
                .request_action("call-1", "shell", &pending_params)
                .await
        });
        let event = rx.recv().await.expect("approval event");
        assert_eq!(event["kind"], "approval_pending");
        assert_eq!(event["scope"]["target"], "origin/main");
        assert_eq!(event["scope"]["environment"], "fixture");
        assert_eq!(
            event["scope"]["credential_capabilities"][0],
            "git:configured-remote"
        );
        let approval_id = event["approval_id"].as_str().unwrap();
        approvals
            .lock()
            .unwrap()
            .remove(approval_id)
            .unwrap()
            .send(true)
            .unwrap();
        assert!(matches!(pending.await.unwrap(), ApprovalDecision::Approved));

        gate.before_dispatch("call-1", "shell", &params)
            .await
            .unwrap();
        gate.after_dispatch(
            "call-1",
            "shell",
            &params,
            true,
            &json!({"remote_sha": "abc"}),
        )
        .await
        .unwrap();
        let action_id = event["action_id"].as_str().unwrap();
        let action = durability.load_action(action_id).await.unwrap().unwrap();
        assert_eq!(
            action.state,
            super::super::governance::ActionState::Completed
        );

        let changed = json!({
            "command": "git push origin HEAD:other",
            "target": "origin/other",
            "environment": "fixture"
        });
        assert!(gate
            .before_dispatch("call-1", "shell", &changed)
            .await
            .is_err());

        let denied_gate = gate.clone();
        let denied_params = changed.clone();
        let denied = tokio::spawn(async move {
            denied_gate
                .request_action("call-2", "shell", &denied_params)
                .await
        });
        let denied_event = rx.recv().await.expect("denial approval event");
        let denied_id = denied_event["approval_id"].as_str().unwrap();
        approvals
            .lock()
            .unwrap()
            .remove(denied_id)
            .unwrap()
            .send(false)
            .unwrap();
        assert!(matches!(denied.await.unwrap(), ApprovalDecision::Denied(_)));
        let denied_action = durability
            .load_action(denied_event["action_id"].as_str().unwrap())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            denied_action.state,
            super::super::governance::ActionState::Denied
        );
        assert!(denied_action.receipt.is_some(), "denial must be auditable");
        assert!(gate
            .before_dispatch("call-2", "shell", &changed)
            .await
            .is_err());
    }

    fn dangling_shell(call_id: &str, command: &str) -> Vec<Message> {
        vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "do it".into(),
            },
            Message::Assistant {
                content: String::new(),
                tool_calls: vec![serde_json::from_value(json!({
                    "id": call_id,
                    "name": "shell",
                    "arguments": {"command": command},
                }))
                .unwrap()],
                thinking: vec![],
            },
        ]
    }

    #[tokio::test]
    async fn restart_before_dispatch_runs_approved_action_once() {
        let repo = tempfile::tempdir().unwrap();
        std::fs::create_dir(repo.path().join(".git")).unwrap();
        let rt = runtime(repo.path()).await;
        let durability = Arc::new(MemoryDurability::default());
        let generator: Arc<dyn TurnGenerator> = Arc::new(Script {
            turns: vec![],
            cursor: AtomicUsize::new(0),
        });
        let service = AssistantService::new_durable(
            generator,
            rt,
            test_cfg_with_gated_shell(),
            "sys".into(),
            durability.clone(),
            repo.path().to_path_buf(),
        );
        let command = "printf x >> effect.txt";
        let params = json!({"command": command});
        let scope = action_scope(Some(&repo.path().to_path_buf()), "shell", &params).unwrap();
        let mut action = super::super::governance::SupervisedActionRecord::propose(
            "restart-before",
            "call-1",
            scope,
        );
        action
            .transition(super::super::governance::ActionState::Approved, None)
            .unwrap();
        durability.record_action(&action).await.unwrap();
        let mut messages = dangling_shell("call-1", command);
        let runtime_session = service.runtime_session_for("restart-before").await;
        service
            .reconcile_dangling_actions("restart-before", &runtime_session, &mut messages)
            .await
            .unwrap();
        service
            .reconcile_dangling_actions("restart-before", &runtime_session, &mut messages)
            .await
            .unwrap();
        assert_eq!(
            std::fs::read_to_string(repo.path().join("effect.txt")).unwrap(),
            "x",
            "the approved effect must execute exactly once"
        );
        let recovered = durability.load_action(&action.id).await.unwrap().unwrap();
        assert_eq!(
            recovered.state,
            super::super::governance::ActionState::Completed
        );
    }

    #[tokio::test]
    async fn restart_after_dispatch_marks_indeterminate_without_replay() {
        let repo = tempfile::tempdir().unwrap();
        std::fs::create_dir(repo.path().join(".git")).unwrap();
        let rt = runtime(repo.path()).await;
        let durability = Arc::new(MemoryDurability::default());
        let generator: Arc<dyn TurnGenerator> = Arc::new(Script {
            turns: vec![],
            cursor: AtomicUsize::new(0),
        });
        let service = AssistantService::new_durable(
            generator,
            rt,
            test_cfg_with_gated_shell(),
            "sys".into(),
            durability.clone(),
            repo.path().to_path_buf(),
        );
        let command = "printf x >> must-not-exist.txt";
        let params = json!({"command": command});
        let scope = action_scope(Some(&repo.path().to_path_buf()), "shell", &params).unwrap();
        let mut action = super::super::governance::SupervisedActionRecord::propose(
            "restart-after",
            "call-2",
            scope,
        );
        action
            .transition(super::super::governance::ActionState::Approved, None)
            .unwrap();
        action
            .transition(super::super::governance::ActionState::Dispatched, None)
            .unwrap();
        durability.record_action(&action).await.unwrap();
        let mut messages = dangling_shell("call-2", command);
        let runtime_session = service.runtime_session_for("restart-after").await;
        service
            .reconcile_dangling_actions("restart-after", &runtime_session, &mut messages)
            .await
            .unwrap();
        assert!(!repo.path().join("must-not-exist.txt").exists());
        let recovered = durability.load_action(&action.id).await.unwrap().unwrap();
        assert_eq!(
            recovered.state,
            super::super::governance::ActionState::Indeterminate
        );
    }

    fn test_cfg_with_gated_shell() -> AssistantConfig {
        AssistantConfig {
            model: Some("scripted".into()),
            strict_model: false,
            max_turns: 4,
            tools: GeneralExecutor::tool_defs(),
            gated_tools: vec!["shell".into()],
            approval_policy: None,
            proactive_memory: None,
            // None => built-in labels, which cover the network-reaching
            // commodity tools. A caller that loads .car/tool-labels.json
            // should pass the merged map (car#723).
            tool_labels: None,
            todos: None,
            value_store_previews: false,
        }
    }

    #[tokio::test]
    async fn goal_shell_check_does_not_run_without_required_approval() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime(dir.path()).await;
        let cfg = test_cfg_with_gated_shell();
        let target = dir.path().join("should-not-exist");

        let exit = run_shell_check_with_approval(
            &rt,
            &cfg,
            None,
            &crate::coder::test_cmds::touch("should-not-exist"),
        )
        .await;

        assert_eq!(exit, 1);
        assert!(
            !target.exists(),
            "gated goal verifier command must not run without approval"
        );
    }

    #[tokio::test]
    async fn goal_shell_check_runs_after_required_approval() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime(dir.path()).await;
        let cfg = test_cfg_with_gated_shell();
        let target = dir.path().join("approved-check");

        let exit = run_shell_check_with_approval(
            &rt,
            &cfg,
            Some(&FixedApproval(true)),
            &crate::coder::test_cmds::touch("approved-check"),
        )
        .await;

        assert_eq!(exit, 0);
        assert!(target.exists(), "approved verifier command should run");
    }

    #[tokio::test]
    async fn chat_turn_streams_tokens_and_done() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime(dir.path()).await;
        let generator: Arc<dyn TurnGenerator> = Arc::new(Script {
            turns: vec![
                turn(
                    "let me compute",
                    json!([{ "id": "c1", "name": "calculate", "arguments": { "expression": "2+2" } }]),
                ),
                turn("It's 4.", json!([])),
            ],
            cursor: AtomicUsize::new(0),
        });
        let cfg = AssistantConfig {
            model: Some("scripted".into()),
            strict_model: false,
            max_turns: 4,
            tools: GeneralExecutor::tool_defs(),
            gated_tools: Vec::new(),
            approval_policy: None,
            proactive_memory: None,
            // None => built-in labels, which cover the network-reaching
            // commodity tools. A caller that loads .car/tool-labels.json
            // should pass the merged map (car#723).
            tool_labels: None,
            todos: None,
            value_store_previews: false,
        };
        let svc = AssistantService::new(generator, rt, cfg, "sys".into());

        let events = Arc::new(StdMutex::new(Vec::<Value>::new()));
        let ev2 = events.clone();
        svc.handle_turn("s1", "what is 2+2?", None, move |v| {
            let ev = ev2.clone();
            async move {
                ev.lock().unwrap().push(v);
            }
        })
        .await;

        let got = events.lock().unwrap().clone();
        // Every event carries the session id.
        assert!(got.iter().all(|e| e["session_id"] == "s1"));
        // A tool_call for calculate was streamed.
        assert!(got
            .iter()
            .any(|e| e["kind"] == "tool_call" && e["tool"] == "calculate"));
        // The last event is the terminal done with the final text.
        let last = got.last().unwrap();
        assert_eq!(last["kind"], "done");
        assert_eq!(last["text"], "It's 4.");

        // Second turn on the same session continues the thread (3 messages
        // seeded: system+user+assistant... at least the thread persisted).
        let thread_len = svc.threads.lock().await.get("s1").map(|m| m.len()).unwrap();
        assert!(thread_len >= 3, "thread should persist across the turn");
    }

    /// The daemon's `try_forward_agent_chat_event` forwards a chat event iff it
    /// is a notification carrying `params.session_id`; the host then dispatches
    /// on `kind`. This asserts every event we emit across a full turn (text,
    /// tool_call, terminal) satisfies that contract — the wire compatibility the
    /// live `agents.chat` → `agent.chat.event` path depends on.
    #[tokio::test]
    async fn every_chat_event_is_forwardable_by_the_daemon() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime(dir.path()).await;
        let generator: Arc<dyn TurnGenerator> = Arc::new(Script {
            turns: vec![
                turn(
                    "let me compute",
                    json!([{ "id": "c1", "name": "calculate", "arguments": { "expression": "1+1" } }]),
                ),
                turn("It's 2.", json!([])),
            ],
            cursor: AtomicUsize::new(0),
        });
        let cfg = AssistantConfig {
            model: Some("scripted".into()),
            strict_model: false,
            max_turns: 4,
            tools: GeneralExecutor::tool_defs(),
            gated_tools: Vec::new(),
            approval_policy: None,
            proactive_memory: None,
            // None => built-in labels, which cover the network-reaching
            // commodity tools. A caller that loads .car/tool-labels.json
            // should pass the merged map (car#723).
            tool_labels: None,
            todos: None,
            value_store_previews: false,
        };
        let svc = AssistantService::new(generator, rt, cfg, "sys".into());
        let events = Arc::new(StdMutex::new(Vec::<Value>::new()));
        let ev2 = events.clone();
        svc.handle_turn("sess-42", "1+1?", None, move |v| {
            let ev = ev2.clone();
            async move {
                ev.lock().unwrap().push(v);
            }
        })
        .await;

        const KNOWN_KINDS: [&str; 7] = [
            "token",
            "tool_call",
            "approval_pending",
            "goal_evaluated",
            "receipt_report",
            "done",
            "error",
        ];
        let got = events.lock().unwrap().clone();
        assert!(!got.is_empty());
        for e in &got {
            // Forwarding precondition: session_id present and correct.
            assert_eq!(
                e.get("session_id").and_then(Value::as_str),
                Some("sess-42"),
                "every event must carry its session_id: {e}"
            );
            // Host-dispatchable: a known kind.
            let kind = e.get("kind").and_then(Value::as_str).unwrap_or("");
            assert!(KNOWN_KINDS.contains(&kind), "unknown event kind: {e}");
        }
        // The stream ends in a terminal `done`.
        assert_eq!(got.last().unwrap()["kind"], "done");
    }

    #[tokio::test]
    async fn explicit_chat_model_reaches_inference_and_unset_preserves_agent_default() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime(dir.path()).await;
        let requests = Arc::new(StdMutex::new(Vec::new()));
        let generator: Arc<dyn TurnGenerator> = Arc::new(RecordingScript {
            requests: requests.clone(),
        });
        let cfg = AssistantConfig {
            model: Some("agent/default".into()),
            strict_model: false,
            max_turns: 2,
            tools: Vec::new(),
            gated_tools: Vec::new(),
            approval_policy: None,
            proactive_memory: None,
            // None => built-in labels, which cover the network-reaching
            // commodity tools. A caller that loads .car/tool-labels.json
            // should pass the merged map (car#723).
            tool_labels: None,
            todos: None,
            value_store_previews: false,
        };
        let svc = AssistantService::new(generator, rt, cfg, "sys".into());

        svc.handle_turn_with_model(
            "selected",
            "hello",
            None,
            Some("openrouter/deepseek/deepseek-v3.2"),
            |_| async {},
        )
        .await;
        svc.handle_turn("adaptive", "hello", None, |_| async {})
            .await;

        let got = requests.lock().unwrap();
        assert_eq!(got.len(), 2);
        assert_eq!(
            got[0].model.as_deref(),
            Some("openrouter/deepseek/deepseek-v3.2")
        );
        assert!(
            got[0].params.strict_model,
            "a selected native model must not silently fall back"
        );
        assert_eq!(got[1].model.as_deref(), Some("agent/default"));
        assert!(
            !got[1].params.strict_model,
            "an unset native preference preserves the agent's routing policy"
        );
    }

    #[test]
    fn goal_evaluated_event_has_host_wire_shape() {
        let wire = event_to_wire(AssistantEvent::GoalEvaluated {
            iteration: 2,
            met: false,
            grounded: true,
            reason: "command goal_check exited 1".into(),
        })
        .expect("goal verifier events should be surfaced to hosts");

        assert_eq!(wire["kind"], "goal_evaluated");
        assert_eq!(wire["iteration"], 2);
        assert_eq!(wire["met"], false);
        assert_eq!(wire["grounded"], true);
        assert_eq!(wire["reason"], "command goal_check exited 1");
    }

    #[tokio::test]
    async fn goal_turn_streams_verifier_events_and_one_terminal() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime(dir.path()).await;
        let create = crate::coder::test_cmds::touch("goal.done");
        let generator: Arc<dyn TurnGenerator> = Arc::new(Script {
            turns: vec![
                turn("starting", json!([])),
                turn(
                    "creating sentinel",
                    json!([{ "id": "s1", "name": "shell", "arguments": { "command": create } }]),
                ),
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
        });
        let cfg = AssistantConfig {
            model: Some("scripted".into()),
            strict_model: false,
            max_turns: 4,
            tools: GeneralExecutor::tool_defs(),
            gated_tools: Vec::new(),
            approval_policy: None,
            proactive_memory: None,
            // None => built-in labels, which cover the network-reaching
            // commodity tools. A caller that loads .car/tool-labels.json
            // should pass the merged map (car#723).
            tool_labels: None,
            todos: None,
            value_store_previews: false,
        };
        let svc = AssistantService::new(generator, rt, cfg, "sys".into());

        let events = Arc::new(StdMutex::new(Vec::<Value>::new()));
        let ev2 = events.clone();
        svc.handle_goal_turn(
            "goal-s1",
            "create goal.done",
            None,
            ChatGoal {
                check: crate::coder::test_cmds::file_exists("goal.done"),
                max_iterations: 4,
            },
            move |v| {
                let ev = ev2.clone();
                async move {
                    ev.lock().unwrap().push(v);
                }
            },
        )
        .await;

        let got = events.lock().unwrap().clone();
        let verifier: Vec<_> = got
            .iter()
            .filter(|e| e["kind"] == "goal_evaluated")
            .collect();
        assert_eq!(verifier.len(), 2, "one verifier event per goal iteration");
        assert_eq!(verifier[0]["met"], false);
        assert_eq!(verifier[1]["met"], true);
        assert_eq!(verifier[1]["grounded"], true);
        assert_eq!(
            got.iter().filter(|e| e["kind"] == "done").count(),
            1,
            "iteration-local done events must not leak as terminal chat events"
        );
        assert_eq!(got.last().unwrap()["kind"], "done");
        assert_eq!(
            std::fs::read_to_string(dir.path().join("goal.done")).unwrap_or_default(),
            ""
        );
    }

    #[tokio::test]
    async fn chat_gated_write_emits_approval_and_resumes_on_approve() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime(dir.path()).await;
        let generator: Arc<dyn TurnGenerator> = Arc::new(Script {
            turns: vec![
                turn(
                    "",
                    json!([{ "id": "w1", "name": "write_file", "arguments": { "path": "z.txt", "content": "zephyr" } }]),
                ),
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
        });
        let cfg = AssistantConfig {
            model: Some("scripted".into()),
            strict_model: false,
            max_turns: 4,
            tools: GeneralExecutor::tool_defs(),
            gated_tools: vec!["write_file".into()],
            approval_policy: None,
            proactive_memory: None,
            // None => built-in labels, which cover the network-reaching
            // commodity tools. A caller that loads .car/tool-labels.json
            // should pass the merged map (car#723).
            tool_labels: None,
            todos: None,
            value_store_previews: false,
        };
        let svc = Arc::new(AssistantService::new(generator, rt, cfg, "sys".into()));

        let events = Arc::new(StdMutex::new(Vec::<Value>::new()));
        let ev2 = events.clone();

        // Drive the turn and, concurrently, approve the first pending request.
        let svc_run = svc.clone();
        let turn_task = tokio::spawn(async move {
            svc_run
                .handle_turn("s1", "write z.txt", None, move |v| {
                    let ev = ev2.clone();
                    async move {
                        ev.lock().unwrap().push(v);
                    }
                })
                .await;
        });

        // Poll for the approval_pending event, then approve it.
        let approved = {
            let mut ok = false;
            for _ in 0..200 {
                let id = events
                    .lock()
                    .unwrap()
                    .iter()
                    .find(|e| e["kind"] == "approval_pending")
                    .and_then(|e| e["approval_id"].as_str().map(String::from));
                if let Some(id) = id {
                    assert!(svc.resolve_approval(&id, true));
                    ok = true;
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
            ok
        };
        assert!(
            approved,
            "an approval_pending event should have been emitted"
        );
        turn_task.await.unwrap();

        // The write ran after approval.
        assert_eq!(
            std::fs::read_to_string(dir.path().join("z.txt")).unwrap(),
            "zephyr"
        );
    }
}