lean-ctx-cloud 3.12.12

The LeanCTX connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
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
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
// SPDX-License-Identifier: Apache-2.0
//! Tasks in the engine (H2, C0 1.9 §1): read a project's tasks, claim one,
//! report short summaries, submit one result with evidence, give it back.
//!
//! The rules the engine keeps:
//! - No tool call waits for Cloud ([`cache`]): reads answer from the last
//!   data Cloud sent and say when it is stale; changes are queued, and what
//!   Cloud answered comes with the caller's next call. Each queued request
//!   ends within [`BUDGET`]; offline or a lapsed lease answers at once.
//! - A claim passes the worker gate first ([`worker::admit_claim`], L1:
//!   the engine's opt-in for the repo, pause, today's budget) and goes out
//!   under that opt-in; a result passes [`worker::admit_submit`]. Cloud
//!   checks the same opt-in again (`optin_scope`, `optin_inactive`,
//!   `daily_budget`, `optin_changed`, `vetoed`); every refusal is shown as
//!   it is, an `optin_changed` claim reads the opt-in again once, and a
//!   stopped opt-in ends this machine's claims.
//! - The claim's lease id and fencing token stay on this machine
//!   ([`claims`], 0600) and are never printed. This process renews its
//!   claims while it runs (`keeper`) and gives them back on stop.
//! - Text leaving the machine (summaries, proposals, release reasons) passes
//!   the outbox screening; a text it refuses is not sent, never rewritten.
//! - Text arriving from Cloud (titles, goals, summaries of people and other
//!   agents) reaches the agent only fenced as foreign data
//!   ([`crate::untrusted::wrap`], X5).
//! - Cloud announces claims, releases and results on the bus itself; the
//!   engine sends no task frames.

pub mod cache;
pub mod claims;
mod client;
pub mod fields;
pub mod gate;
mod keeper;
pub mod local;
mod process;
pub mod propose;
pub mod reads;
mod render;

use crate::CloudConfigExt as _;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use lean_ctx_time::UtcDateTime;
use serde::Deserialize;

use crate::CloudError;
use crate::TaskRefusal;
use crate::auth::Session;
use crate::config::CloudConfig;
use crate::knowledge::screening::Screen;
use crate::metrics::cloud_use;
use crate::state::CloudStore;
use crate::vault::{VaultMap, VaultRecord};
use crate::worker::{self, Admission, EvidenceSummary, Refusal, TaskScope};
use claims::HeldClaim;
use client::TasksApi;
use lean_ctx_protocol::cloud::lease::{CloudRight, LeaseState};
use lean_ctx_protocol::cloud::tasks::{
    EvidenceKind, EvidenceV1, MAX_CLAIM_MINUTES, MAX_TASKS_PAGE, MIN_CLAIM_MINUTES,
    TASK_AMEND_SCHEMA, TASK_CLAIM_RENEW_SCHEMA, TASK_CLAIM_REQUEST_SCHEMA, TASK_RELEASE_SCHEMA,
    TASK_RESULT_SCHEMA, TASK_UPDATE_SCHEMA, TASK_VERIFY_SCHEMA, TaskAckV1, TaskActorKind,
    TaskAmendRequestV1, TaskClaimRenewRequestV1, TaskClaimRequestV1, TaskListV1, TaskOutcome,
    TaskPriority, TaskReleaseRequestV1, TaskResultRequestV1, TaskUpdateRequestV1, TaskV1,
    TaskVerdict, TaskVerifyRequestV1, UsageV1,
};

pub use client::ListFilter;
pub use render::{
    PARTIAL_NOTE, render_list, render_listing, render_result_ack, render_task, render_verify_ack,
};

/// The time one task call may take in all.
pub const BUDGET: Duration = Duration::from_secs(5);
/// Claim length when the caller names none.
pub const DEFAULT_CLAIM_MINUTES: u32 = 10;

/// A connected machine, its lease and the Cloud project of a local root.
pub struct Connected {
    pub store: CloudStore,
    pub session: Session,
    pub project: VaultRecord,
    pub root: PathBuf,
}

/// Whether tasks apply to `project_root` with `right`; `Err` says why not
/// (no request made).
pub fn connected(project_root: &Path, right: CloudRight) -> Result<Connected, CloudError> {
    let config = lean_ctx::core::config::Config::load().cloud.clone();
    connected_with(&config, CloudStore::open()?, project_root, right)
}

fn connected_with(
    config: &CloudConfig,
    store: CloudStore,
    project_root: &Path,
    right: CloudRight,
) -> Result<Connected, CloudError> {
    if config.enabled == Some(false) {
        return Err(CloudError::Config(
            "The Cloud is off ([cloud] enabled = false)".into(),
        ));
    }
    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
    let project = crate::resolution::vault_for_root(&store, project_root)?.ok_or_else(|| {
        CloudError::Config(
            "this repository is not linked to a vault (run `lean-ctx cloud sync` in it)".into(),
        )
    })?;
    let session = Session::load(store.clone(), config.root_key(&instance.url)?)?;
    if !matches!(
        session.lease.state_at(UtcDateTime::now()),
        LeaseState::Valid | LeaseState::Grace
    ) {
        return Err(CloudError::LeaseLapsed);
    }
    if !session.lease.lease.grants(right) {
        return Err(CloudError::Forbidden);
    }
    Ok(Connected {
        store,
        session,
        project,
        root: project_root.to_path_buf(),
    })
}

impl Connected {
    fn link(&self) -> Link<'_> {
        Link {
            data_dir: self.store.data_dir(),
            vault_id: &self.project.vault_id,
            root: &self.root,
            via: Via::Session(&self.session),
            budget: BUDGET,
            deadline: std::cell::Cell::new(None),
            workers: Some(&self.store),
            presence: &process::local_presence,
            announce: Some(crate::bus::presence::announce_and_wait),
        }
    }
}

/// How a call reaches Cloud: the enrolled session, or (tests) a local fake.
enum Via<'a> {
    Session(&'a Session),
    #[cfg(test)]
    Origin(String),
}

/// Everything one task operation needs.
struct Link<'a> {
    data_dir: &'a Path,
    vault_id: &'a str,
    root: &'a Path,
    via: Via<'a>,
    budget: Duration,
    /// One deadline for every request of a call (a claim: opt-in read,
    /// claim and its one retry); `None`: each request gets `budget`. A
    /// claim tried again after the relay announced gets a fresh one.
    deadline: std::cell::Cell<Option<Instant>>,
    /// Where a local bus agent's worker is looked up (`None`: the agent
    /// goes to Cloud as given).
    workers: Option<&'a CloudStore>,
    /// Where a bus agent's live presence on this Instance is looked up
    /// (the checker and the author of a verify, §3.1).
    presence: process::PresenceLookup<'a>,
    /// Asks the running relay to announce now and waits up to the given
    /// time for its hello: what it announced, `None` when no relay
    /// answered. `None` here: a claim refused for presence or role is not
    /// tried again.
    announce: Option<fn(Duration) -> Option<String>>,
}

/// The least time a task write's budget must still hold for its resend.
const RESEND_MIN_LEFT: Duration = Duration::from_secs(1);

/// A fresh `Idempotency-Key` for one logical task write.
fn write_key() -> String {
    uuid::Uuid::new_v4().simple().to_string()
}

/// Whether a write's answer may have been lost (the write may or may not
/// have happened): only these are resent. A 429 or a refusal is an answer.
fn lost_in_transit(error: &CloudError) -> bool {
    matches!(
        error,
        CloudError::Offline(_) | CloudError::Server { status: 500.., .. }
    )
}

/// How long a claim refused for presence or role waits for the relay's
/// fresh announcement before it is tried once more (Cloud task #27).
const ANNOUNCE_WAIT: Duration = Duration::from_secs(3);

impl Link<'_> {
    /// The gate's directories: private copies under the data dir, the run
    /// tree outside `$HOME`.
    fn gate_dirs(&self) -> gate::GateDirs {
        gate::GateDirs::for_instance(self.data_dir)
    }

    /// The id Cloud knows `agent` by. Cloud keeps presence and claims under
    /// the worker the relay announced (`wkr_…`), so a local bus agent id
    /// is sent as its worker; a worker id, or a name Cloud resolves, goes
    /// as it is.
    fn cloud_agent(&self, agent: &str) -> String {
        self.cloud_identity(agent).0
    }

    /// [`Self::cloud_agent`] and the role of the worker it names when the
    /// book knows it: whom a refusal says Cloud looked up (task #27).
    fn cloud_identity(&self, agent: &str) -> (String, Option<String>) {
        if crate::bus::address::is_worker_id(agent) {
            return (agent.to_owned(), None);
        }
        self.workers
            .and_then(|store| crate::bus::messages_v2::known_worker_and_role_of(store, agent))
            .map_or_else(|| (agent.to_owned(), None), |(id, role)| (id, Some(role)))
    }

    /// One request that may change the vault's tasks: what this Instance
    /// keeps of them ([`reads`]) is outdated afterwards, so the next read
    /// asks Cloud.
    fn call<T>(
        &self,
        call: impl FnOnce(&TasksApi<'_>) -> Result<T, CloudError>,
    ) -> Result<T, CloudError> {
        let result = self.call_read(call);
        reads::outdate(self.data_dir, self.vault_id);
        result
    }

    /// One logical task write (claim, release, update, result) whose
    /// request may be lost in transit: `send` is given the write's one
    /// `Idempotency-Key` and sent once more, with that same key, when the
    /// answer did not arrive (offline, timeout, 5xx) and the call's time
    /// budget still allows it. Cloud answers a resend it already applied
    /// with the first answer, so the write happens once.
    fn write_once<T>(
        &self,
        key: &str,
        send: impl Fn(&str) -> Result<T, CloudError>,
    ) -> Result<T, CloudError> {
        let own_deadline = self.deadline.get().is_none();
        if own_deadline {
            self.deadline.set(Some(Instant::now() + self.budget));
        }
        let deadline = self.deadline.get().unwrap_or_else(Instant::now);
        let mut result = send(key);
        if result.as_ref().is_err_and(lost_in_transit)
            && deadline.saturating_duration_since(Instant::now()) >= RESEND_MIN_LEFT
        {
            result = send(key);
        }
        if own_deadline {
            self.deadline.set(None);
        }
        result
    }

    /// The Cloud the requests go to (a 429 hold is kept per Cloud).
    fn cloud_url(&self) -> &str {
        match &self.via {
            Via::Session(session) => &session.instance.url,
            #[cfg(test)]
            Via::Origin(origin) => origin,
        }
    }

    /// One request that only reads.
    fn call_read<T>(
        &self,
        call: impl FnOnce(&TasksApi<'_>) -> Result<T, CloudError>,
    ) -> Result<T, CloudError> {
        let deadline = self
            .deadline
            .get()
            .unwrap_or_else(|| Instant::now() + self.budget);
        let client = match &self.via {
            Via::Session(session) => session.bounded_client(deadline)?,
            #[cfg(test)]
            Via::Origin(origin) => crate::transport::CloudClient::bounded(origin, self.budget)?,
        };
        let result = call(&TasksApi {
            client: &client,
            vault_id: self.vault_id,
        });
        match &self.via {
            Via::Session(session) => result.map_err(|e| session.noted(e)),
            #[cfg(test)]
            Via::Origin(_) => result,
        }
    }

    /// [`Self::call`] for a claim or its renewal: while a quota or policy
    /// throttle holds task claims nothing is asked (the refusal says until
    /// when); a `quota_exceeded`/`policy_denied` answer sets one.
    fn call_claim<T>(
        &self,
        call: impl FnOnce(&TasksApi<'_>) -> Result<T, CloudError>,
    ) -> Result<T, CloudError> {
        use crate::throttle::{self, Scope};
        let store = match &self.via {
            Via::Session(session) => &session.store,
            #[cfg(test)]
            Via::Origin(_) => return self.call(call),
        };
        throttle::check(store, Scope::Tasks, lean_ctx_time::UtcDateTime::now())?;
        match self.call(call) {
            Ok(value) => {
                throttle::passed(store, Scope::Tasks);
                Ok(value)
            }
            Err(error) => Err(throttle::note(
                store,
                Scope::Tasks,
                error,
                lean_ctx_time::UtcDateTime::now(),
            )),
        }
    }

    /// Now on the service's clock (claim ends are service time).
    fn now(&self) -> UtcDateTime {
        match &self.via {
            Via::Session(session) => session.lease.service_time(UtcDateTime::now()).to_utc(),
            #[cfg(test)]
            Via::Origin(_) => UtcDateTime::now(),
        }
    }

    /// Task `number` of this project as the worker gate sees it.
    fn scope(&self, number: u64) -> TaskScope {
        TaskScope {
            task_id: number.to_string(),
            vault_id: self.vault_id.to_owned(),
        }
    }

    /// The claim `agent` holds on task `number`: never another agent's, so
    /// no agent writes under another's fencing token. The process that
    /// renews it does not matter: the agent's CLI and its session (or the
    /// relay that kept a CLI claim alive) act for the same agent, and the
    /// claims file is this user's alone (0600).
    fn held(&self, number: u64, agent: &str) -> Result<HeldClaim, CloudError> {
        match claims::find(self.data_dir, self.vault_id, number) {
            Some(held) if held.agent == agent => Ok(held),
            Some(_) => Err(CloudError::Refused(format!(
                "task #{number} is claimed on this machine by another agent"
            ))),
            None => Err(CloudError::Refused(format!(
                "this machine holds no claim on task #{number}"
            ))),
        }
    }

    /// Forget the local claim when Cloud says it is gone for good.
    fn settle<T>(&self, number: u64, answer: Result<T, CloudError>) -> Result<T, CloudError> {
        let gone = match &answer {
            Err(CloudError::Task { refusal, .. }) => refusal.ends_claim(),
            Err(CloudError::NotFound | CloudError::Vetoed) => true,
            _ => false,
        };
        if gone {
            if matches!(
                &answer,
                Err(CloudError::Task {
                    refusal: TaskRefusal::StaleClaim,
                    ..
                })
            ) {
                let agent =
                    claims::find(self.data_dir, self.vault_id, number).map(|held| held.agent);
                lean_ctx::core::agents::friction::record_for(
                    lean_ctx::core::agents::friction::CLAIM_EXPIRED,
                    agent.as_deref(),
                    self.root.to_str(),
                );
            }
            let _ = claims::remove(self.data_dir, self.vault_id, number);
        }
        answer
    }
}

/// A task as the agent reads it: the view and its local claim.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskView {
    pub task: TaskV1,
    /// The claim end when this machine holds the claim.
    pub held_until: Option<String>,
}

/// Screen every outgoing `(field, text)`; the first refusal names the field
/// and the reason, never the text.
fn screened(fields: &[(&str, Option<&str>)]) -> Result<(), CloudError> {
    let mut screen = Screen::for_installation();
    for (field, text) in fields {
        if let Some(text) = text
            && let Err(blocked) = screen.check(text)
        {
            return Err(CloudError::Refused(format!(
                "the {field} was not sent: it contains {blocked}"
            )));
        }
    }
    Ok(())
}

/// One piece of evidence as a caller names it.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct EvidenceInput {
    pub kind: String,
    pub reference: String,
}

impl EvidenceInput {
    /// `root` is the checkout a `file_anchor` (`path` or `path::symbol`) is
    /// digested in, as it is now (J2 anchors).
    pub(crate) fn into_evidence(self, root: &Path) -> Result<EvidenceV1, CloudError> {
        let kind = match self.kind.as_str() {
            "receipt" => EvidenceKind::Receipt,
            "commit" => EvidenceKind::Commit,
            "ci_run" => EvidenceKind::CiRun,
            "url" => EvidenceKind::Url,
            "fact" => EvidenceKind::Fact,
            "file_anchor" => return file_anchor(root, self.reference.trim()),
            other => {
                return Err(CloudError::Refused(format!(
                    "unknown evidence kind {other:?} (receipt, commit, ci_run, file_anchor, url, fact)"
                )));
            }
        };
        let evidence = EvidenceV1 {
            kind,
            reference: Some(self.reference.trim().to_owned()),
            anchor: None,
        };
        evidence.validate().map_err(|_| {
            CloudError::Refused(format!(
                "{} evidence {:?} was refused: {}",
                self.kind,
                shown(self.reference.trim()),
                reference_form(&self.kind)
            ))
        })?;
        Ok(evidence)
    }
}

/// What a reference of `kind` looks like, in plain words (rc4-103: an agent
/// needed four tries because a refusal never said which form was expected).
fn reference_form(kind: &str) -> &'static str {
    match kind {
        "commit" => "a commit reference is a commit SHA, 7 to 64 lowercase hex characters.",
        "receipt" => "a receipt reference is a LeanCTX receipt id, 64 lowercase hex characters.",
        "ci_run" => "a ci_run reference is an https:// link to the CI run, or its run id.",
        "url" => "a url reference is an https:// link without spaces.",
        "fact" => {
            "a fact reference is the short id of a fact saved with ctx_knowledge (letters, digits and . _ : - only, no spaces), not a sentence. To cite a sentence, write it in the summary instead."
        }
        _ => "see the evidence kinds in the ctx_tasks tool description.",
    }
}

/// A reference as a refusal quotes it: at most 80 characters.
fn shown(reference: &str) -> String {
    const MAX: usize = 80;
    if reference.chars().count() <= MAX {
        return reference.to_owned();
    }
    let mut cut: String = reference.chars().take(MAX).collect();
    cut.push('…');
    cut
}

/// Whether every link on the way to `path` (relative, plain names) leads
/// to a place inside `root`. A link that leads out, or nowhere, is refused
/// whatever its target is, so the answer never depends on what exists
/// outside the folder.
fn links_stay_inside(root: &Path, path: &str) -> bool {
    let Ok(base) = std::fs::canonicalize(root) else {
        return true;
    };
    let mut at = root.to_path_buf();
    for part in Path::new(path).components() {
        at.push(part);
        match std::fs::symlink_metadata(&at) {
            Ok(meta) if meta.file_type().is_symlink() => match std::fs::canonicalize(&at) {
                Ok(target) if target.starts_with(&base) => {}
                _ => return false,
            },
            Ok(_) => {}
            // Nothing exists here, so nothing below it does either.
            Err(_) => return true,
        }
    }
    true
}

/// Why `path` cannot be cited, in plain words; `codes` are the reason codes
/// of the refused read.
fn anchor_refusal(root: &Path, path: &str, codes: &str) -> String {
    use std::path::Component;
    // Only plain names (and `.`): a Windows prefix like `C:foo`, a root or
    // `..` never names a file inside the project folder.
    let relative = !path.is_empty()
        && Path::new(path)
            .components()
            .all(|c| matches!(c, Component::Normal(_) | Component::CurDir));
    let joined = root.join(path);
    let inside = relative && links_stay_inside(root, path);
    if !relative || !inside {
        return "the path must be relative to the project folder and stay inside it".to_owned();
    }
    if !std::fs::symlink_metadata(&joined).is_ok_and(|m| m.is_file() || m.file_type().is_symlink())
    {
        return format!(
            "there is no file {path} in the project folder {}",
            root.display()
        );
    }
    if codes.contains("restricted") {
        return "the project's rules keep this file's content private".to_owned();
    }
    "the project's rules do not allow citing this file, or it is not a text file".to_owned()
}

/// The anchor of `spec` in `root`: the file is admitted like a source
/// binding first (a restricted, withheld or unreadable file is never
/// digested), then digested as it is now.
fn file_anchor(root: &Path, spec: &str) -> Result<EvidenceV1, CloudError> {
    use lean_ctx::core::knowledge::anchors;
    let (path, symbol) = anchors::parse_spec(spec);
    let root_text = root.to_string_lossy();
    if let Err(codes) = lean_ctx::core::archive::bindings::source_at(&root_text, path, "ctx_tasks")
    {
        return Err(CloudError::Refused(format!(
            "file_anchor {path:?} was refused: {}. Name a file by its path inside the project folder, for example README.md or src/main.rs (add ::name to point at one function or type).",
            anchor_refusal(root, path, &codes)
        )));
    }
    let anchor = anchors::capture(root, path, symbol).map_err(CloudError::Refused)?;
    let evidence = EvidenceV1 {
        kind: EvidenceKind::FileAnchor,
        reference: None,
        anchor: Some(anchor),
    };
    evidence
        .validate()
        .map_err(|e| CloudError::Refused(format!("evidence: {e}")))?;
    Ok(evidence)
}

/// A task list as the Instance shows it.
///
/// `partial`: a Cloud answer came back full ([`MAX_TASKS_PAGE`] tasks), so
/// older tasks of these filters may be missing. The list says so, never
/// silently incomplete. A list cached before 3.12.3 reads as whole.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, Deserialize)]
pub struct TaskListing {
    #[serde(flatten)]
    pub list: TaskListV1,
    #[serde(default)]
    pub partial: bool,
}

/// The project's tasks (shared and coalesced per Instance, [`reads`]).
/// Only a current list: when Cloud holds reads or is not reachable this is
/// an error, not the last good list ([`list_read`] serves that with its
/// age), so no caller takes tasks since claimed or closed for current.
pub fn list(project_root: &Path, filter: &ListFilter) -> Result<TaskListing, CloudError> {
    list_read(project_root, filter).and_then(reads::current)
}

/// [`list`] and, when Cloud holds reads (429) or is not reachable, the age
/// of the last good list served instead.
pub fn list_read(
    project_root: &Path,
    filter: &ListFilter,
) -> Result<reads::Read<TaskListing>, CloudError> {
    let c = connected(project_root, CloudRight::TasksRead)?;
    list_cached(&c.link(), filter)
}

fn list_cached(
    link: &Link<'_>,
    filter: &ListFilter,
) -> Result<reads::Read<TaskListing>, CloudError> {
    let key = format!("list{}", filter.query()?);
    reads::read_through(link.data_dir, link.cloud_url(), link.vault_id, &key, || {
        list_via(link, filter)
    })
}

/// The listing in board order ([`fields::sort_by_priority`]).
///
/// Cloud answers one page, the newest tasks by number, so an older high task
/// can fall off it: the high tasks of the same filters are fetched too and
/// merged in, each task once, before the sort. That answer is a page too, so
/// a full one marks the listing `partial`.
fn list_via(link: &Link<'_>, filter: &ListFilter) -> Result<TaskListing, CloudError> {
    let mut list = link.call_read(|api| api.list(filter))?;
    let mut partial = list.tasks.len() >= MAX_TASKS_PAGE;
    if filter.priority.is_none() {
        let high = ListFilter {
            priority: Some(TaskPriority::High),
            ..filter.clone()
        };
        let high = link.call_read(|api| api.list(&high))?;
        partial |= high.tasks.len() >= MAX_TASKS_PAGE;
        let seen: std::collections::HashSet<u64> = list.tasks.iter().map(|t| t.number).collect();
        list.tasks
            .extend(high.tasks.into_iter().filter(|t| !seen.contains(&t.number)));
    }
    fields::sort_by_priority(&mut list.tasks);
    Ok(TaskListing { list, partial })
}

/// One task (shared and coalesced per Instance, [`reads`]). Only a current
/// answer: when Cloud holds reads or is not reachable this is an error, not
/// the last good answer ([`show_read`] serves that with its age).
pub fn show(project_root: &Path, number: u64) -> Result<TaskView, CloudError> {
    show_read(project_root, number).and_then(reads::current)
}

/// [`show`] and, when Cloud holds reads (429) or is not reachable, the age
/// of the last good answer served instead. A task Cloud does not know is
/// [`CloudError::NotFound`]; a rate limit never reads as one.
pub fn show_read(project_root: &Path, number: u64) -> Result<reads::Read<TaskView>, CloudError> {
    let c = connected(project_root, CloudRight::TasksRead)?;
    let link = c.link();
    show_cached(&link, number)
}

fn show_cached(link: &Link<'_>, number: u64) -> Result<reads::Read<TaskView>, CloudError> {
    let key = format!("task#{number}");
    reads::read_through(link.data_dir, link.cloud_url(), link.vault_id, &key, || {
        link.call_read(|api| api.show(number))
    })
    .map(|read| read.map(|task| view_of(link, task)))
}

/// `task` as the caller sees it, with its local claim (no request).
fn view_of(link: &Link<'_>, task: TaskV1) -> TaskView {
    let held_until = claims::find(link.data_dir, link.vault_id, task.number).map(|held| held.until);
    TaskView { task, held_until }
}

/// A granted claim, as the caller may see it (no lease id, no token).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClaimGranted {
    pub number: u64,
    pub until: String,
    pub minutes: u32,
}

/// Claim task `number` for bus agent `agent` in session `session_id`.
pub fn claim(
    project_root: &Path,
    number: u64,
    agent: &str,
    session_id: &str,
    minutes: Option<u32>,
) -> Result<ClaimGranted, CloudError> {
    let c = connected(project_root, CloudRight::TasksWork)?;
    let local = lean_ctx::core::config::Config::load().cloud.worker.clone();
    // The whole claim (opt-in read, claim, its one retry) ends within one
    // BUDGET, like every task call from a tool.
    let deadline = std::cell::Cell::new(Instant::now() + BUDGET);
    // Whether the gate let a request go to Cloud: then an `Ok` is Cloud's
    // grant (a claim this machine already holds never reaches the gate).
    let asked = std::cell::Cell::new(false);
    let gate = |scope: &TaskScope| {
        let unavailable = |e: CloudError| Refusal::Unavailable(e.to_string());
        let client = c
            .session
            .bounded_client(deadline.get())
            .map_err(unavailable)?;
        let optin = worker::fetch_optin_via(&client).map_err(unavailable)?;
        let admission = worker::admit_claim_for(&c.store, &local, scope, &optin)?;
        asked.set(true);
        Ok(admission)
    };
    let link = c.link();
    link.deadline.set(Some(deadline.get()));
    // A claim tried again after the relay announced gets a fresh BUDGET,
    // its opt-in read too.
    let restart = || {
        deadline.set(Instant::now() + BUDGET);
        link.deadline.set(Some(deadline.get()));
    };
    let granted = claim_via(&link, number, agent, session_id, minutes, &gate, &restart)
        .inspect_err(|error| record_claim_friction(error, agent, project_root))?;
    // Counted only once granted: a refused claim costs no task today. The
    // claim stands either way; Cloud counts it too.
    if asked.get()
        && let Err(error) = worker::count_claim(&c.store)
    {
        tracing::warn!("cloud worker: a granted claim was not counted here: {error}");
    }
    keeper::ensure_running();
    Ok(granted)
}

/// Count a claim Cloud refused for presence, role or consent (local
/// friction log, the retro loop's input; ids, no content).
fn record_claim_friction(error: &CloudError, agent: &str, root: &Path) {
    use lean_ctx::core::agents::friction;
    if let CloudError::Task {
        refusal: TaskRefusal::NotPermitted(check),
        ..
    } = error
    {
        let signal = match check {
            crate::error::PermitCheck::Presence => friction::CLAIM_REFUSED_PRESENCE,
            crate::error::PermitCheck::Role => friction::CLAIM_REFUSED_ROLE,
            crate::error::PermitCheck::Unknown => friction::CLAIM_REFUSED_PERMIT,
        };
        friction::record_for(signal, Some(agent), root.to_str());
    }
}

/// Cloud refused for presence or role: whom it found on the bus.
fn is_permit_refusal(error: &CloudError) -> bool {
    matches!(
        error,
        CloudError::Task {
            refusal: TaskRefusal::NotPermitted(
                crate::error::PermitCheck::Presence | crate::error::PermitCheck::Role
            ),
            ..
        }
    )
}

/// A presence or role refusal that names whom Cloud looked up: the id the
/// claim sent, the bus agent it stands for and that worker's role, and
/// whether the relay announced before the claim was tried again (Cloud
/// task #27). Any other error stays as it is.
fn looked_up(link: &Link<'_>, agent: &str, error: CloudError, announced: bool) -> CloudError {
    let CloudError::Task {
        refusal,
        number,
        detail,
    } = error
    else {
        return error;
    };
    if !matches!(refusal, TaskRefusal::NotPermitted(_)) {
        return CloudError::Task {
            refusal,
            number,
            detail,
        };
    }
    let (sent, role) = link.cloud_identity(agent);
    let mut line = detail.unwrap_or_else(|| refusal.to_string());
    line.push_str(&match role {
        Some(role) => {
            format!(" The Cloud looked up {sent} (the worker of bus agent {agent}, role {role}).")
        }
        None if sent == agent && !crate::bus::address::is_worker_id(agent) => format!(
            " The Cloud looked up {sent} as given: this machine's worker book has no worker for it."
        ),
        None => format!(" The Cloud looked up {sent}."),
    });
    if link.announce.is_some() {
        line.push_str(if announced {
            " The relay announced again and the claim was tried once more."
        } else {
            " No relay answered the request to announce."
        });
    }
    CloudError::Task {
        refusal,
        number,
        detail: Some(line),
    }
}

/// The worker gate of a claim (L1): the opt-in it works under, or why not.
type ClaimGate<'g> = &'g dyn Fn(&TaskScope) -> Result<Admission, Refusal>;

fn claim_via(
    link: &Link<'_>,
    number: u64,
    agent: &str,
    session_id: &str,
    minutes: Option<u32>,
    gate: ClaimGate<'_>,
    restart: &dyn Fn(),
) -> Result<ClaimGranted, CloudError> {
    let minutes = minutes
        .unwrap_or(DEFAULT_CLAIM_MINUTES)
        .clamp(MIN_CLAIM_MINUTES, MAX_CLAIM_MINUTES);
    if let Some(held) = claims::find(link.data_dir, link.vault_id, number)
        && held.until().is_some_and(|until| until > link.now())
    {
        if held.agent != agent {
            return Err(CloudError::Refused(format!(
                "task #{number} is claimed on this machine by another agent"
            )));
        }
        // The holder claiming again wants more time: renew, so the answer is
        // a fresh expiry, not the one it already had. A running session that
        // holds the claim renews it itself; it is reported as it stands.
        if held.pid != std::process::id() && lean_ctx::ipc::process::is_alive(held.pid) {
            return Ok(ClaimGranted {
                number,
                until: held.until,
                minutes: held.minutes,
            });
        }
        let renewed = renew_via(link, number, agent)?;
        return Ok(ClaimGranted {
            number,
            until: renewed.until,
            minutes: renewed.minutes,
        });
    }
    // The worker gate first (opt-in, scope, pause, today's budget); Cloud
    // then checks the same opt-in (C0 1.9 §4: `optin_scope`,
    // `optin_inactive`, `daily_budget`, `optin_changed`). An opt-in that
    // changed since it was read is read again, once. Every send of this
    // claim (a resend, the retries below) carries its one key; Cloud keeps
    // only a granted claim's answer under it, so a refusal is asked anew.
    let key = write_key();
    let attempt = || {
        let admission = gate(&link.scope(number))
            .map_err(|refusal| CloudError::Refused(refusal.to_string()))?;
        let request = TaskClaimRequestV1 {
            schema: TASK_CLAIM_REQUEST_SCHEMA.into(),
            agent: link.cloud_agent(agent),
            // Without the local key the claim is not sent at all.
            session_ref: crate::session_ref::uploaded_ses_ref(link.data_dir, session_id)?,
            minutes,
            optin_id: admission.optin_id,
        };
        link.write_once(&key, |key| {
            link.call_claim(|api| api.claim(number, &request, key))
        })
    };
    let answer = || match attempt() {
        Err(CloudError::Task {
            refusal: TaskRefusal::OptinChanged,
            ..
        }) => attempt(),
        answer => answer,
    };
    // Refused for presence or role (task #27): Cloud's presence of the
    // worker may be stale (a relay that reconnected, a role announced
    // late). The relay announces now and the claim is tried once more
    // when it did; a refusal that stands says whom Cloud looked up.
    let ack = match answer() {
        Err(error) if is_permit_refusal(&error) => {
            let announced = link.announce.and_then(|announce| announce(ANNOUNCE_WAIT));
            let retried = if announced.is_some() {
                restart();
                answer()
            } else {
                Err(error)
            };
            retried.map_err(|error| looked_up(link, agent, error, announced.is_some()))?
        }
        answer => answer?,
    };
    let until = ack.until.as_str().to_owned();
    claims::put(
        link.data_dir,
        HeldClaim {
            vault_id: link.vault_id.to_owned(),
            number,
            root: link.root.to_string_lossy().into_owned(),
            agent: agent.to_owned(),
            claim: ack.claim,
            until: until.clone(),
            minutes,
            pid: std::process::id(),
        },
    )?;
    // The commit this claim starts from (G6 of an S task pins it), and the
    // session that holds it (it never checks this task's result).
    claims::trace_claim(
        link.data_dir,
        link.vault_id,
        number,
        process::acting_identity(agent, link.presence),
        gate::head_commit(link.root).ok(),
    )?;
    Ok(ClaimGranted {
        number,
        until,
        minutes,
    })
}

/// Renew the claim this machine holds on `number`.
fn renew_via(link: &Link<'_>, number: u64, agent: &str) -> Result<HeldClaim, CloudError> {
    let mut held = link.held(number, agent)?;
    let request = TaskClaimRenewRequestV1 {
        schema: TASK_CLAIM_RENEW_SCHEMA.into(),
        claim: held.claim.clone(),
        minutes: held.minutes,
    };
    let ack = link.settle(number, link.call_claim(|api| api.renew(number, &request)))?;
    held.claim = ack.claim;
    ack.until.as_str().clone_into(&mut held.until);
    if !claims::renewed(link.data_dir, &held)? {
        return Err(CloudError::Refused(format!(
            "task #{number} was given back meanwhile; its renewal is not kept"
        )));
    }
    Ok(held)
}

/// Check the submitted result of task `number` as `agent` (C0 2.2 E48):
/// `accept` makes it done, `reject` (with its reason) opens it again. The
/// agent names itself as on its claims; Cloud refuses the agent that did the
/// work (`self_verify`) and a task that is not submitted.
pub fn verify(
    project_root: &Path,
    number: u64,
    agent: &str,
    verdict: TaskVerdict,
    reason: Option<&str>,
) -> Result<TaskAckV1, CloudError> {
    let c = connected(project_root, CloudRight::TasksWork)?;
    let ack = verify_via(&c.link(), number, agent, verdict, reason)?;
    // Trace per change (§36): pin what this engine saw, when receipts flow.
    crate::task_evidence::note_task_closed(
        &c.store,
        &c.project.vault_id,
        number,
        lean_ctx_time::UtcDateTime::now(),
    );
    Ok(ack)
}

fn verify_via(
    link: &Link<'_>,
    number: u64,
    agent: &str,
    verdict: TaskVerdict,
    reason: Option<&str>,
) -> Result<TaskAckV1, CloudError> {
    let reason = reason.map(str::trim).filter(|reason| !reason.is_empty());
    screened(&[("verify reason", reason)])?;
    // Checker ≠ author by the per-session identity (process v1 §3.1), and
    // for a process task a green G6 record of the judged commit with its
    // locked paths still unchanged (§5): decided here, before anything is
    // sent.
    // The checker is the live bus presence `agent`, held by this process
    // or its app session; never a free string.
    let task = link.call(|api| api.show(number))?;
    let checker = process::checker_identity(agent, (link.presence)(agent), task.process.is_some())?;
    let trace = claims::trace(link.data_dir, link.vault_id, number);
    process::checker_not_author(&task, &checker, trace.as_ref())?;
    process::verify_gate(&task, link.root, &link.gate_dirs().work)?;
    let request = TaskVerifyRequestV1 {
        schema: TASK_VERIFY_SCHEMA.into(),
        worker_id: link.cloud_agent(agent),
        verdict,
        reason: reason.map(str::to_owned),
    };
    let key = blake3::hash(
        serde_json::to_string(&(link.vault_id, number, &request))
            .unwrap_or_default()
            .as_bytes(),
    )
    .to_hex()[..32]
        .to_string();
    link.call(|api| api.verify(number, &request, &key))
}

/// [`screened`] for a result: its texts, and every path or symbol name of
/// its evidence (they leave the machine too).
fn screened_result(
    texts: &[(&str, Option<&str>)],
    evidence: &[EvidenceV1],
) -> Result<(), CloudError> {
    let mut fields = texts.to_vec();
    for item in evidence {
        let anchor = item.anchor.as_ref();
        for reference in [
            item.reference.as_deref(),
            anchor.map(|a| a.path.as_str()),
            anchor.and_then(|a| a.symbol.as_deref()),
        ]
        .into_iter()
        .flatten()
        {
            fields.push(("evidence", Some(reference)));
        }
    }
    screened(&fields)
}

/// What an amendment of a result says (see [`amend`]).
#[derive(Default)]
pub struct AmendInput {
    pub summary: Option<String>,
    pub evidence: Vec<EvidenceInput>,
    /// A `done` task's merge commit (the merge record).
    pub merge_commit: Option<String>,
    pub reason: Option<String>,
    /// The caller checked this process runs for a registered Queen session
    /// (`crate::queens::this_session_is_queen`): it may record a merge.
    pub queen: bool,
}

/// The Cloud route an amendment needs and no Cloud serves yet.
pub const AMEND_ROUTE: &str = "POST /v1/vaults/{vault_id}/tasks/{number}/amend";

/// Amend the result of vault task `number` as `agent` (the rules of
/// [`lean_ctx_protocol::cloud::tasks::amend_rule`] and `may_amend`). Fails
/// closed: it checks the request, the screening and the task (read only)
/// and then refuses, sending nothing, because no Cloud serves
/// [`AMEND_ROUTE`] yet; the task stays unchanged.
pub fn amend(
    project_root: &Path,
    number: u64,
    agent: &str,
    input: AmendInput,
) -> Result<TaskAckV1, CloudError> {
    let c = connected(project_root, CloudRight::TasksWork)?;
    amend_via(&c.link(), number, agent, input)
}

fn amend_via(
    link: &Link<'_>,
    number: u64,
    agent: &str,
    input: AmendInput,
) -> Result<TaskAckV1, CloudError> {
    let input_queen = input.queen;
    let trimmed =
        |text: Option<String>| text.map(|t| t.trim().to_owned()).filter(|t| !t.is_empty());
    let summary = trimmed(input.summary);
    let reason = trimmed(input.reason);
    let merge_commit = trimmed(input.merge_commit);
    let evidence = input
        .evidence
        .into_iter()
        .map(|item| item.into_evidence(link.root))
        .collect::<Result<Vec<_>, _>>()?;
    let worker_id = link.cloud_agent(agent);
    let request = TaskAmendRequestV1 {
        schema: TASK_AMEND_SCHEMA.into(),
        worker_id: worker_id.clone(),
        summary,
        evidence,
        merge_commit,
        reason,
    };
    request
        .validate()
        .map_err(|e| CloudError::Refused(format!("amendment of task #{number}: {e}")))?;
    screened_result(
        &[
            ("summary", request.summary.as_deref()),
            ("amend reason", request.reason.as_deref()),
        ],
        &request.evidence,
    )?;
    let task = link.call(|api| api.show(number))?;
    let mine = |by: &lean_ctx_protocol::cloud::tasks::TaskActorV1| {
        by.kind == TaskActorKind::Instance
            && by.mine
            && by
                .agent
                .as_deref()
                .is_some_and(|a| a == agent || a == worker_id)
    };
    let caller = lean_ctx_protocol::cloud::tasks::AmendCaller {
        submitter: task.result.as_ref().is_some_and(|r| mine(&r.by)),
        reviewer: task.verified_by.as_ref().is_some_and(mine),
        // A vault write always comes from an agent of this Instance.
        person: false,
        queen: input_queen,
    };
    lean_ctx_protocol::cloud::tasks::may_amend(&request, caller).map_err(|refusal| {
        CloudError::Refused(format!(
            "task #{number}: only its submitter corrects a result; a merge record also a person or a coordinator session, never the reviewer ({})",
            refusal.code()
        ))
    })?;
    lean_ctx_protocol::cloud::tasks::amend_rule(&task, &request).map_err(|refusal| {
        CloudError::Refused(format!(
            "task #{number} is {:?}: its result cannot be amended like this ({})",
            task.state,
            refusal.code()
        ))
    })?;
    Err(CloudError::Refused(format!(
        "not supported by the Cloud yet: this Cloud server has no route to amend a result ({AMEND_ROUTE}); task #{number} is unchanged"
    )))
}

/// Give task `number` back; `reason` is one line.
pub fn release(
    project_root: &Path,
    number: u64,
    agent: &str,
    reason: Option<&str>,
) -> Result<TaskAckV1, CloudError> {
    let c = connected(
        &claim_root(project_root, number, agent),
        CloudRight::TasksWork,
    )?;
    release_via(&c.link(), number, agent, reason)
}

fn release_via(
    link: &Link<'_>,
    number: u64,
    agent: &str,
    reason: Option<&str>,
) -> Result<TaskAckV1, CloudError> {
    let held = link.held(number, agent)?;
    let reason = reason.map(str::trim).filter(|reason| !reason.is_empty());
    screened(&[("release reason", reason)])?;
    let request = TaskReleaseRequestV1 {
        schema: TASK_RELEASE_SCHEMA.into(),
        claim: held.claim,
        reason: reason.map(str::to_owned),
    };
    let sent = link.write_once(&write_key(), |key| {
        link.call(|api| api.release(number, &request, key))
    });
    let ack = link.settle(number, sent)?;
    claims::remove(link.data_dir, link.vault_id, number)?;
    Ok(ack)
}

/// Report one short summary on the claimed task `number`. When the claim
/// lapsed while the agent worked (Cloud: stale claim), the task is claimed
/// again for it and the summary sent once more; another agent's claim
/// refuses that.
pub fn update(
    project_root: &Path,
    number: u64,
    agent: &str,
    session_id: &str,
    summary: &str,
    usage: Option<UsageV1>,
) -> Result<TaskAckV1, CloudError> {
    let project_root = &claim_root(project_root, number, agent);
    let c = connected(project_root, CloudRight::TasksWork)?;
    let usage = engine_usage(&c, number, usage);
    update_or_reclaim_via(&c.link(), number, agent, summary, usage, || {
        claim(project_root, number, agent, session_id, None)
    })
}

fn update_or_reclaim_via(
    link: &Link<'_>,
    number: u64,
    agent: &str,
    summary: &str,
    usage: Option<UsageV1>,
    reclaim: impl FnOnce() -> Result<ClaimGranted, CloudError>,
) -> Result<TaskAckV1, CloudError> {
    match update_via(link, number, agent, summary, usage) {
        Err(CloudError::Task {
            refusal: TaskRefusal::StaleClaim,
            ..
        }) => {
            reclaim()?;
            update_via(link, number, agent, summary, usage)
        }
        answer => answer,
    }
}

/// C9: the usage a write carries is the engine's own measure of the claim
/// (host sessions at list price), at least what the agent reported; only
/// where this machine recorded nothing does the report stand alone.
fn engine_usage(c: &Connected, number: u64, reported: Option<UsageV1>) -> Option<UsageV1> {
    let measured = dirs::home_dir().and_then(|home| {
        let others: Vec<String> = crate::vault::connected_map(&c.store)
            .vaults
            .into_values()
            .filter(|p| p.vault_id != c.project.vault_id)
            .flat_map(|p| p.roots)
            .collect();
        let now = UtcDateTime::now();
        let usage = cloud_use::host_window(&home, &c.project.roots, &others, now);
        cloud_use::claim_usage(c.store.data_dir(), &c.project.vault_id, number, now, &usage)
    });
    match (measured, reported) {
        (Some(measured), reported) => Some(UsageV1 {
            tokens: measured.tokens.max(reported.map_or(0, |r| r.tokens)),
            usd_micros: measured.usd_micros,
        }),
        (None, reported) => reported,
    }
}

fn update_via(
    link: &Link<'_>,
    number: u64,
    agent: &str,
    summary: &str,
    usage: Option<UsageV1>,
) -> Result<TaskAckV1, CloudError> {
    let held = link.held(number, agent)?;
    let summary = summary.trim();
    screened(&[("summary", Some(summary))])?;
    let request = TaskUpdateRequestV1 {
        schema: TASK_UPDATE_SCHEMA.into(),
        claim: held.claim,
        summary: Some(summary.to_owned()),
        usage,
    };
    let sent = link.write_once(&write_key(), |key| {
        link.call(|api| api.update(number, &request, key))
    });
    link.settle(number, sent)
}

/// Submit the result of the claimed task `number`: it ends the claim. The
/// task waits for a second agent's check (`submitted`), or ends at once
/// (`done`, or `failed` for [`TaskOutcome::Failed`]).
///
/// A result never carries a draft: knowledge the work produced travels
/// through the capture gate and `cloud sync` like any other (signed E5
/// events on a C0 2.0 Cloud, the draft path on 1.x).
pub fn submit(
    project_root: &Path,
    number: u64,
    agent: &str,
    summary: &str,
    evidence: Vec<EvidenceInput>,
    usage: Option<UsageV1>,
    outcome: TaskOutcome,
) -> Result<TaskAckV1, CloudError> {
    let c = connected(
        &claim_root(project_root, number, agent),
        CloudRight::TasksWork,
    )?;
    let usage = engine_usage(&c, number, usage);
    // The gate decides before anything is sent; the usage counts against
    // today's budget only once Cloud accepted the result (a refused or
    // repeated submit is not counted twice).
    let decided = std::cell::RefCell::new(None);
    let gate = |_: &TaskScope, evidence: &EvidenceSummary| {
        *decided.borrow_mut() = Some(evidence.clone());
        Ok(())
    };
    let ack = submit_via(
        &c.link(),
        number,
        agent,
        Submission {
            summary,
            evidence,
            usage,
            outcome,
        },
        &gate,
    )?;
    if let Some(evidence) = decided.take() {
        let _ = worker::admit_submit(&c.store, &evidence);
    }
    crate::task_evidence::note_task_closed(
        &c.store,
        &c.project.vault_id,
        number,
        lean_ctx_time::UtcDateTime::now(),
    );
    Ok(ack)
}

/// The worker gate of a result (L1): what it cites and costs, admitted
/// before anything is sent.
type SubmitGate<'g> = &'g dyn Fn(&TaskScope, &EvidenceSummary) -> Result<(), Refusal>;

/// What a result says.
struct Submission<'s> {
    summary: &'s str,
    evidence: Vec<EvidenceInput>,
    usage: Option<UsageV1>,
    outcome: TaskOutcome,
}

/// `outcome` as the request carries it. `completed` is never sent (absent
/// means completed on every line). `failed` goes only to a Cloud whose
/// task views carry the v5 `lifecycle`: a 1.x Cloud denies the unknown
/// field, so against it the failure is refused here, before anything is
/// sent, and the agent releases the task instead.
fn negotiated_outcome(
    task: &TaskV1,
    number: u64,
    outcome: TaskOutcome,
) -> Result<Option<TaskOutcome>, CloudError> {
    if outcome == TaskOutcome::Completed {
        return Ok(None);
    }
    if task.lifecycle.is_none() {
        return Err(CloudError::Refused(format!(
            "this Cloud server does not take failed results yet; release task #{number} with a reason instead"
        )));
    }
    Ok(Some(outcome))
}

fn submit_via(
    link: &Link<'_>,
    number: u64,
    agent: &str,
    submission: Submission<'_>,
    gate: SubmitGate<'_>,
) -> Result<TaskAckV1, CloudError> {
    let Submission {
        summary,
        evidence,
        usage,
        outcome,
    } = submission;
    let held = link.held(number, agent)?;
    let summary = summary.trim();
    let evidence = evidence
        .into_iter()
        .map(|item| item.into_evidence(link.root))
        .collect::<Result<Vec<_>, _>>()?;
    screened_result(&[("summary", Some(summary))], &evidence)?;
    gate(
        &link.scope(number),
        &EvidenceSummary {
            usage_tokens: usage.map_or(0, |usage| usage.tokens),
            usage_usd_micros: usage.and_then(|usage| usage.usd_micros).unwrap_or(0),
        },
    )
    .map_err(|refusal| CloudError::Refused(refusal.to_string()))?;
    // The task as Cloud has it: its v5 lifecycle (a failed result) and, for
    // a process task, what G6 runs. G6 runs here, in the Instance, on the
    // claim's worktree; only a green record goes out with the result.
    let task = link.call(|api| api.show(number))?;
    let trace = claims::trace(link.data_dir, link.vault_id, number);
    let gate_record = process::submit_gate(
        &task,
        link.root,
        &link.gate_dirs(),
        &evidence,
        outcome,
        trace.as_ref(),
    )?;
    let outcome = negotiated_outcome(&task, number, outcome)?;
    let commit = gate_record.as_ref().map_or_else(
        || {
            evidence
                .iter()
                .find(|e| e.kind == EvidenceKind::Commit)
                .and_then(|e| e.reference.clone())
        },
        |record| Some(record.artifact_commit.clone()),
    );
    let request = TaskResultRequestV1 {
        schema: TASK_RESULT_SCHEMA.into(),
        claim: held.claim,
        summary: Some(summary.to_owned()),
        evidence,
        draft: None,
        usage,
        outcome,
        gate_record,
    };
    let sent = link.write_once(&write_key(), |key| {
        link.call(|api| api.result(number, &request, key))
    });
    let ack = link.settle(number, sent)?;
    claims::remove(link.data_dir, link.vault_id, number)?;
    // The session that submitted it: a verify on this Instance is checked
    // against it (checker ≠ author per session, §3.1). A trace that cannot
    // be written leaves the verify refused (no per-session identity),
    // never allowed.
    let _ = claims::trace_submit(
        link.data_dir,
        link.vault_id,
        number,
        process::acting_identity(agent, link.presence),
        commit,
    );
    Ok(ack)
}

/// Give back every claim this process holds (worker stop, shutdown);
/// returns how many Cloud released. A claim Cloud cannot be reached for is
/// forgotten here and ends at its expiry there.
pub fn release_own_claims(reason: &str) -> usize {
    let Ok(store) = CloudStore::open() else {
        return 0;
    };
    let mut released = 0;
    for held in claims::own(store.data_dir()) {
        let answer = connected(Path::new(&held.root), CloudRight::TasksWork)
            .and_then(|c| release_via(&c.link(), held.number, &held.agent, Some(reason)));
        if answer.is_ok() {
            released += 1;
        }
        let _ = claims::remove(store.data_dir(), &held.vault_id, held.number);
    }
    released
}

/// How many claims this process holds.
fn own_claims() -> usize {
    CloudStore::open().map_or(0, |store| claims::own(store.data_dir()).len())
}

/// A session idle this long no longer keeps its claims alive: they end at
/// their expiry in Cloud, so a silent agent frees its task quickly.
const RENEW_IDLE: std::time::Duration = std::time::Duration::from_mins(30);

/// How long the MCP session this process serves has had no tool call in
/// flight; `None` while a call runs or when no session is served.
pub type IdleClock = fn() -> Option<Duration>;

static IDLE_CLOCK: std::sync::OnceLock<IdleClock> = std::sync::OnceLock::new();

/// Register the idle clock of the served MCP session (`server::mcp_idle`,
/// when it starts serving). The first registration wins. Without one the
/// process serves no session and is never idle, so claim renewal runs.
pub fn register_idle_clock(clock: IdleClock) {
    let _ = IDLE_CLOCK.set(clock);
}

/// Renew the claims of this process whose half-time has passed, unless the
/// process has been idle for [`RENEW_IDLE`] or worker mode is paused here;
/// returns how many this process still holds.
fn renew_own_due() -> usize {
    let Ok(store) = CloudStore::open() else {
        return 0;
    };
    let idle = IDLE_CLOCK
        .get()
        .and_then(|clock| clock())
        .is_some_and(|idle| idle >= RENEW_IDLE);
    if idle || crate::worker::read_state(&store).paused {
        return claims::own(store.data_dir()).len();
    }
    for held in claims::own(store.data_dir()) {
        let Ok(c) = connected(Path::new(&held.root), CloudRight::TasksWork) else {
            continue;
        };
        let link = c.link();
        if held.renew_due(link.now()) {
            let _ = renew_via(&link, held.number, &held.agent);
        }
    }
    claims::own(store.data_dir()).len()
}

/// Take over the unexpired claims `agent` holds on this machine (a new
/// session of the same agent) and keep them renewed.
pub fn adopt_claims(agent: &str) {
    let Ok(store) = CloudStore::open() else {
        return;
    };
    let now = UtcDateTime::now();
    if claims::adopt(store.data_dir(), agent, now).is_ok_and(|held| !held.is_empty()) {
        keeper::ensure_running();
    }
}

/// Keep CLI claims alive (lean-ctx #3): `lean-ctx cloud tasks claim` ends
/// right after claiming, so nothing renewed its claim and an agent running
/// a long gate lost it before submitting. The bus relay's process renews a
/// claim whose holder has ended at half-time while the claiming agent still
/// works on this machine (registered, not finished, active within
/// `RENEW_IDLE`), without becoming its holder; once the agent stops
/// working the claim ends at its expiry in Cloud. Returns how many such
/// claims it kept.
pub fn keep_cli_claims() -> usize {
    let Ok(store) = CloudStore::open() else {
        return 0;
    };
    if crate::worker::read_state(&store).paused {
        return 0;
    }
    let now = UtcDateTime::now();
    let working = working_agents(now);
    keep_orphaned(
        store.data_dir(),
        now,
        |agent| working.contains(agent),
        |held| {
            if let Ok(c) = connected(Path::new(&held.root), CloudRight::TasksWork) {
                let _ = renew_via(&c.link(), held.number, &held.agent);
            }
        },
    )
}

/// Renew the orphaned claims of `working` agents whose half-time has
/// passed; returns how many orphaned claims of `working` agents there are.
fn keep_orphaned(
    data_dir: &Path,
    now: lean_ctx_time::UtcDateTime,
    working: impl Fn(&str) -> bool,
    renew: impl Fn(&HeldClaim),
) -> usize {
    let kept: Vec<HeldClaim> = claims::orphaned(data_dir, now)
        .into_iter()
        .filter(|held| working(&held.agent))
        .collect();
    for held in kept.iter().filter(|held| held.renew_due(now)) {
        renew(held);
    }
    kept.len()
}

/// The reason Cloud records when the daemon gives an abandoned claim back.
pub const ABANDONED_REASON: &str = "the claiming session ended on its machine";

/// Give back the claims nobody works on any more (k2 E2E: an ended
/// session's claim was neither renewed nor released, so nobody else could
/// take the task): a claim that has expired, or whose holding process has
/// ended while its agent no longer works on this machine. Runs in the
/// daemon (the bus relay's process); returns how many Cloud released.
pub fn release_abandoned_claims() -> usize {
    let Ok(store) = CloudStore::open() else {
        return 0;
    };
    let now = UtcDateTime::now();
    let working = working_agents(now);
    give_back_abandoned(
        store.data_dir(),
        now,
        |agent| working.contains(agent),
        |held| {
            connected(Path::new(&held.root), CloudRight::TasksWork).and_then(|c| {
                release_via(&c.link(), held.number, &held.agent, Some(ABANDONED_REASON)).map(|_| ())
            })
        },
    )
}

/// The bus agents of this machine at work (registered, not finished,
/// active within [`RENEW_IDLE`]).
fn working_agents(now: lean_ctx_time::UtcDateTime) -> std::collections::HashSet<String> {
    let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
    let idle =
        lean_ctx_time::Duration::from_std(RENEW_IDLE).unwrap_or(lean_ctx_time::Duration::MAX);
    registry
        .list_active(None)
        .into_iter()
        .filter(|agent| now - agent.last_active < idle)
        .map(|agent| agent.agent_id.clone())
        .collect()
}

/// Whether `held` is abandoned at `now`: expired, or its holder process
/// ended (not this one) and its agent is not `working`.
fn abandoned(
    held: &HeldClaim,
    now: lean_ctx_time::UtcDateTime,
    working: &impl Fn(&str) -> bool,
) -> bool {
    let expired = held.until().is_none_or(|until| until <= now);
    let holder_gone = held.pid != std::process::id() && !lean_ctx::ipc::process::is_alive(held.pid);
    expired || (holder_gone && !working(&held.agent))
}

/// [`release_abandoned_claims`] with the agents at work and the release
/// given. A claim Cloud released is gone from the file (`release_via`); an
/// expired one Cloud refused is dropped here too (it is over on this
/// machine; nothing can renew it). An unexpired one that could not be
/// released (offline) is tried again on the next pass.
fn give_back_abandoned(
    data_dir: &Path,
    now: lean_ctx_time::UtcDateTime,
    working: impl Fn(&str) -> bool,
    release: impl Fn(&HeldClaim) -> Result<(), CloudError>,
) -> usize {
    let mut released = 0;
    for held in claims::all(data_dir)
        .into_iter()
        .filter(|held| abandoned(held, now, &working))
    {
        match release(&held) {
            Ok(()) => {
                released += 1;
                // `release_via` removes it; a fake release may not.
                let _ = claims::remove(data_dir, &held.vault_id, held.number);
            }
            Err(error) if held.until().is_none_or(|until| until <= now) => {
                tracing::info!(
                    "cloud: expired claim of task #{} dropped ({error})",
                    held.number
                );
                let _ = claims::remove(data_dir, &held.vault_id, held.number);
                crate::metrics::cloud_use::claim_ended(
                    data_dir,
                    &held.vault_id,
                    held.number,
                    held.until().unwrap_or(now),
                );
            }
            Err(error) => {
                tracing::debug!(
                    "cloud: abandoned claim of task #{} kept: {error}",
                    held.number
                );
            }
        }
    }
    released
}

/// The checkout to act on claim `number` from: `project_root`, unless its
/// vault holds no claim of `agent` on `number` while exactly one other
/// vault does. An agent's session often runs in another repository than the
/// one it claimed in (the claim names its checkout), and the task number
/// alone then finds the claim the agent holds.
#[must_use]
pub fn claim_root(project_root: &Path, number: u64, agent: &str) -> PathBuf {
    let Ok(store) = CloudStore::open() else {
        return project_root.to_path_buf();
    };
    claim_root_in(store.data_dir(), project_root, number, agent)
}

fn claim_root_in(data_dir: &Path, project_root: &Path, number: u64, agent: &str) -> PathBuf {
    let here = VaultMap::load(data_dir)
        .for_root(&project_root.to_string_lossy())
        .map(|vault| vault.vault_id.clone());
    let mine: Vec<HeldClaim> = claims::all(data_dir)
        .into_iter()
        .filter(|held| held.number == number && held.agent == agent)
        .collect();
    let held_here = mine
        .iter()
        .any(|held| here.as_deref() == Some(held.vault_id.as_str()));
    match mine.as_slice() {
        [only] if !held_here => PathBuf::from(&only.root),
        _ => project_root.to_path_buf(),
    }
}

/// What a session starts with (H2): the claims this machine holds in the
/// project, then its open tasks from the task cache (a refresh is queued
/// when they are stale; [`cache`]). `None` when Cloud does not apply or
/// there is nothing to say. Never waits for Cloud.
pub fn briefing(project_root: &Path) -> Option<String> {
    let c = connected(project_root, CloudRight::TasksRead).ok()?;
    let mut lines: Vec<String> = {
        let link = c.link();
        let now = link.now();
        claims::all(link.data_dir)
            .into_iter()
            .filter(|held| {
                held.vault_id == link.vault_id && held.until().is_some_and(|until| until > now)
            })
            .map(|held| {
                format!(
                    "Cloud task #{} is claimed on this machine for agent {} until {}.",
                    held.number, held.agent, held.until
                )
            })
            .collect()
    };
    lines.extend(cache::open_tasks(c));
    (!lines.is_empty()).then(|| lines.join("\n"))
}

#[cfg(test)]
#[path = "tests.rs"]
mod tests;