did-hosting-control 0.8.8

DID Hosting Control Plane — Unified management UI and service registry
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
//! Fit-for-purpose **typed** DID-management Trust Tasks
//! (`https://trusttasks.org/did-hosting/did/*/1.0`).
//!
//! This is the `1.0` webvh-owned protocol described in
//! `docs/did-hosting-trust-tasks-v1-design.md`. It replaces the
//! hand-rolled `messaging::dispatch_did_op` (a `match msg.typ` over ad-hoc
//! JSON bodies) with typed payloads dispatched through the framework's
//! §7.2 pipeline (`trust_tasks_rs::consume_inbound` via
//! `did_hosting_common::server::trust_tasks::run_pipeline`) — the same
//! machinery the ACL ops use.
//!
//! Unlike the upstream `trust-tasks-rs` `spec/did-management/*/0.1`
//! payloads (which are record-centric and carry no `did.jsonl` log), these
//! payloads carry exactly what each op needs, typed. The handlers delegate
//! to the existing `did_ops::*` business logic — no logic rewrite, only
//! typed request/response shaping.
//!
//! Coexistence: the legacy `MSG_*` path (`dispatch_did_op`) keeps working;
//! `messaging::dispatch_trust_task_doc` routes the new `1.0` URIs here and
//! everything else to the legacy bridge (deprecated over time).
//!
//! Migration status: **all eight ops** are implemented — check-name, info,
//! list, delete, publish, register, change-owner, witness-publish. Publish
//! and register carry the `did.jsonl` log as a first-class typed field
//! (`didLog`), the fit-for-purpose motivation the upstream record-centric
//! payloads miss. The legacy `MSG_*` path (`dispatch_did_op`) remains for
//! back-compat behind [`owns`], deprecated until clients adopt `1.0`.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use trust_tasks_rs::{
    Dispatcher, ErrorPayload, ErrorResponse, ProofPolicy, ProofVerifier, ResolvedParties,
    StandardCode, TransportHandler, TrustTask,
};

use did_hosting_common::did_ops::{DidRecord, did_key};
use did_hosting_common::server::domain::{DomainScope, get_default_domain, resolve_request_domain};
use did_hosting_common::server::trust_tasks::{DispatchOutcome, run_pipeline};

use crate::acl::check_acl;
use crate::auth::AuthClaims;
use crate::did_ops;
use crate::error::AppError;
use crate::messaging::spec_did_record_json;
use crate::server::AppState;

// ---------------------------------------------------------------------------
// Typed payloads
// ---------------------------------------------------------------------------

/// `did-hosting/did/request/1.0` — availability probe or slot reservation.
///
/// Fit-for-purpose re-typing of the legacy `MSG_DID_REQUEST` body:
/// * probe (`reserve = false`): read-only, MUST name a `path`.
/// * reserve (`reserve = true`): claims a slot; `path` omitted ⇒
///   server auto-assigns a mnemonic; `force` takes over an existing path
///   (admin / owner only, enforced by `did_ops::create_did`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckNameRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(default)]
    pub reserve: bool,
    #[serde(default)]
    pub force: bool,
    /// Explicit hosting domain (multi-domain deployments). Resolved
    /// against the caller's ACL scope + the system default when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
}

impl trust_tasks_rs::Payload for CheckNameRequest {
    // The framework's `TypeUri` requires the `/spec/<slug>/<major.minor>`
    // shape, so the webvh-owned slug is `did-hosting/did/request` under
    // `/spec/` (the bare `…/did-hosting/…` form in `did_hosting_tasks.rs`
    // is only a valid *opaque* trust-task URL, not a framework Type URI).
    const TYPE_URI: &'static str = "https://trusttasks.org/spec/did-hosting/did/request/1.0";
}

/// `did-hosting/did/request/1.0#response` — the offer.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckNameResponse {
    pub available: bool,
    pub reserved: bool,
    /// The committed record projection, present only on a successful
    /// reservation (matches the legacy `MSG_DID_OFFER` `record` field).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub record: Option<Value>,
}

/// `did-hosting/did/info/1.0` — fetch a record + stats by mnemonic.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InfoRequest {
    pub mnemonic: String,
}
impl trust_tasks_rs::Payload for InfoRequest {
    const TYPE_URI: &'static str = "https://trusttasks.org/spec/did-hosting/did/info/1.0";
}

/// `did-hosting/did/info/1.0#response`. The nested `stats` / `logMetadata`
/// are carried as `Value` (faithful to the legacy `MSG_INFO` body).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InfoResponse {
    pub mnemonic: String,
    pub did_id: Option<String>,
    pub did_url: String,
    pub owner: String,
    pub created_at: u64,
    pub updated_at: u64,
    pub version_count: u64,
    pub content_size: u64,
    pub stats: Value,
    pub log_metadata: Value,
}

/// `did-hosting/did/list/1.0` — list the caller's DIDs (admin may filter
/// by `owner`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub owner: Option<String>,
}
impl trust_tasks_rs::Payload for ListRequest {
    const TYPE_URI: &'static str = "https://trusttasks.org/spec/did-hosting/did/list/1.0";
}

/// `did-hosting/did/list/1.0#response`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListResponse {
    pub dids: Vec<Value>,
}

/// `did-hosting/did/delete/1.0` — delete a DID by mnemonic.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteRequest {
    pub mnemonic: String,
}
impl trust_tasks_rs::Payload for DeleteRequest {
    const TYPE_URI: &'static str = "https://trusttasks.org/spec/did-hosting/did/delete/1.0";
}

/// `did-hosting/did/delete/1.0#response`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteResponse {
    pub mnemonic: String,
    pub did_id: Option<String>,
}

/// `did-hosting/did/register/1.0` — atomic claim-and-publish (webvh-only).
/// `didLog` is the signed log for the freshly-claimed `path`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegisterRequest {
    pub path: String,
    pub did_log: String,
    #[serde(default)]
    pub force: bool,
}
impl trust_tasks_rs::Payload for RegisterRequest {
    const TYPE_URI: &'static str = "https://trusttasks.org/spec/did-hosting/did/register/1.0";
}

/// `did-hosting/did/register/1.0#response`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegisterResponse {
    pub mnemonic: String,
    pub did_url: String,
    pub server_did: String,
}

/// `did-hosting/did/change-owner/1.0` — transfer a DID to `newOwner`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangeOwnerRequest {
    pub mnemonic: String,
    pub new_owner: String,
}
impl trust_tasks_rs::Payload for ChangeOwnerRequest {
    const TYPE_URI: &'static str = "https://trusttasks.org/spec/did-hosting/did/change-owner/1.0";
}

/// `did-hosting/did/change-owner/1.0#response`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangeOwnerResponse {
    pub mnemonic: String,
    pub owner: String,
    pub updated_at: u64,
}

/// `did-hosting/webvh/witness/publish/1.0` — upload a witness proof set.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WitnessPublishRequest {
    pub mnemonic: String,
    /// The witness proof document (opaque JSON, serialised as-is).
    pub witness: Value,
}
impl trust_tasks_rs::Payload for WitnessPublishRequest {
    const TYPE_URI: &'static str =
        "https://trusttasks.org/spec/did-hosting/webvh/witness/publish/1.0";
}

/// `did-hosting/webvh/witness/publish/1.0#response`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WitnessPublishResponse {
    pub mnemonic: String,
    pub witness_url: String,
}

// --- Agent names -----------------------------------------------------------
//
// Bind a human-memorable name (`example.com/@alice`) to a hosted DID. Both
// ops carry the caller's new signed `did.jsonl` (`didData`), which the op
// publishes as a new DID version *and* which the `alsoKnownAs` gate checks:
// `update {state: active}` requires the document to claim the name;
// `update {state: parked}` and `remove` require it not to. See the
// `did-management/agent-name/update` and `agent-name/remove` specifications
// (the set / enable / disable verb trio is retired). Both share one
// `{record}` response.

/// `did-management/agent-name/update/0.1` — declarative binding state:
/// `active` binds a free name, refreshes an existing binding, or resumes a
/// parked one (the document MUST claim the name); `parked` stops it
/// resolving while keeping the reservation (the document MUST NOT claim
/// it). Replaces the retired set / enable / disable verb trio.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateAgentNameRequest {
    pub mnemonic: String,
    /// The name's local part, without the leading `@` (the `alice` in `/@alice`).
    pub name: String,
    /// Desired binding state, per the spec's `state` enum.
    pub state: crate::did_ops::AgentNameState,
    /// The new signed `did.jsonl` (the spec's `didData`). The pre-cutover
    /// `didLog` spelling is accepted as an inbound alias.
    #[serde(alias = "didLog")]
    pub did_data: String,
    /// Optional explicit hosting domain; cross-checked against the DID's host.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
}
impl trust_tasks_rs::Payload for UpdateAgentNameRequest {
    const TYPE_URI: &'static str =
        "https://trusttasks.org/spec/did-management/agent-name/update/0.1";
}

/// `did-management/agent-name/remove/0.1` — release a name (destructive).
/// The submitted document must no longer claim the name. Deliberately NOT a
/// state of `agent-name/update`: the destructive release stays separately
/// auditable.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RemoveAgentNameRequest {
    pub mnemonic: String,
    pub name: String,
    /// The new signed `did.jsonl` (the spec's `didData`); `didLog` accepted
    /// as an inbound alias.
    #[serde(alias = "didLog")]
    pub did_data: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
}
impl trust_tasks_rs::Payload for RemoveAgentNameRequest {
    const TYPE_URI: &'static str =
        "https://trusttasks.org/spec/did-management/agent-name/remove/0.1";
}

/// The shared `#response` for every agent-name verb: the updated DID record
/// (spec `DidRecord` shape). The response Type URI is derived from the
/// request's by the framework, so this struct needs no `Payload` impl.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentNameResponse {
    pub record: Value,
}

// ---------------------------------------------------------------------------
// Dispatch
// ---------------------------------------------------------------------------

/// The typed DID-management payloads this module routes. New ops are added
/// here in lockstep with their handler.
#[derive(Debug)]
enum DidHostingInbound {
    CheckName(TrustTask<CheckNameRequest>),
    Info(TrustTask<InfoRequest>),
    List(TrustTask<ListRequest>),
    Delete(TrustTask<DeleteRequest>),
    Register(TrustTask<RegisterRequest>),
    ChangeOwner(TrustTask<ChangeOwnerRequest>),
    WitnessPublish(TrustTask<WitnessPublishRequest>),
    UpdateAgentName(TrustTask<UpdateAgentNameRequest>),
    RemoveAgentName(TrustTask<RemoveAgentNameRequest>),
}

fn build_dispatcher() -> Dispatcher<DidHostingInbound> {
    Dispatcher::new()
        .on::<CheckNameRequest, _>(DidHostingInbound::CheckName)
        .on::<InfoRequest, _>(DidHostingInbound::Info)
        .on::<ListRequest, _>(DidHostingInbound::List)
        .on::<DeleteRequest, _>(DidHostingInbound::Delete)
        .on::<RegisterRequest, _>(DidHostingInbound::Register)
        .on::<ChangeOwnerRequest, _>(DidHostingInbound::ChangeOwner)
        .on::<WitnessPublishRequest, _>(DidHostingInbound::WitnessPublish)
        .on::<UpdateAgentNameRequest, _>(DidHostingInbound::UpdateAgentName)
        .on::<RemoveAgentNameRequest, _>(DidHostingInbound::RemoveAgentName)
}

/// Does the typed `did-hosting/*/1.0` protocol own this Type URI? The
/// unified router uses this to choose the typed path over the legacy
/// `dispatch_did_op` bridge.
pub fn owns(type_uri: &str) -> bool {
    build_dispatcher().registered_uris().contains(&type_uri)
}

/// Narrow an inbound `TrustTask<Value>` to a typed DID-management op and
/// run it through the framework pipeline. The caller has already checked
/// [`owns`], so an unknown type here is a framework-level rejection.
pub async fn dispatch<V>(
    state: &AppState,
    transport: &(impl TransportHandler + Sync),
    policy: ProofPolicy<'_, V>,
    doc: TrustTask<Value>,
) -> DispatchOutcome
where
    V: ProofVerifier + ?Sized,
{
    let error_id = new_id();
    match build_dispatcher().dispatch_or_reject(doc, error_id) {
        Ok(DidHostingInbound::CheckName(d)) => handle_check_name(state, transport, policy, d).await,
        Ok(DidHostingInbound::Info(d)) => handle_info(state, transport, policy, d).await,
        Ok(DidHostingInbound::List(d)) => handle_list(state, transport, policy, d).await,
        Ok(DidHostingInbound::Delete(d)) => handle_delete(state, transport, policy, d).await,
        Ok(DidHostingInbound::Register(d)) => handle_register(state, transport, policy, d).await,
        Ok(DidHostingInbound::ChangeOwner(d)) => {
            handle_change_owner(state, transport, policy, d).await
        }
        Ok(DidHostingInbound::WitnessPublish(d)) => {
            handle_witness_publish(state, transport, policy, d).await
        }
        Ok(DidHostingInbound::UpdateAgentName(d)) => {
            handle_update_agent_name(state, transport, policy, d).await
        }
        Ok(DidHostingInbound::RemoveAgentName(d)) => {
            handle_remove_agent_name(state, transport, policy, d).await
        }
        Err(err) => DispatchOutcome::Rejected(err),
    }
}

// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------

async fn handle_check_name<V>(
    state: &AppState,
    transport: &(impl TransportHandler + Sync),
    policy: ProofPolicy<'_, V>,
    doc: TrustTask<CheckNameRequest>,
) -> DispatchOutcome
where
    V: ProofVerifier + ?Sized,
{
    let my_vid = match state.config.server_did.as_deref() {
        Some(v) => v,
        None => {
            // No service DID → the pipeline has no recipient anchor. Surface
            // as an internal error document rather than panicking.
            return DispatchOutcome::Rejected(
                doc.reject_with(
                    new_id(),
                    ErrorPayload::new(StandardCode::InternalError)
                        .with_message("the maintainer is not fully configured (no service DID)"),
                ),
            );
        }
    };
    let state = state.clone();
    run_pipeline(
        transport,
        policy,
        doc,
        my_vid,
        move |doc, parties| async move {
            // The framework resolved the caller (in-band issuer wins, transport
            // fills in). Authorise against the maintainer's ACL — the same gate
            // the legacy `run_webvh_dispatch` applies before `dispatch_did_op`.
            let caller = parties.issuer.as_deref().ok_or_else(|| {
                doc.reject_with(
                    new_id(),
                    ErrorPayload::new(StandardCode::PermissionDenied).with_message(
                        "inbound document has no in-band or transport-derived issuer",
                    ),
                )
            })?;
            let role = check_acl(&state.acl_ks, caller).await.map_err(|_| {
                doc.reject_with(
                    new_id(),
                    ErrorPayload::new(StandardCode::PermissionDenied)
                        .with_message("caller is not present in the maintainer's ACL"),
                )
            })?;
            let auth = AuthClaims {
                did: caller.to_string(),
                role,
                session_id: String::new(),
                session_pubkey_b58btc: None,
                amr: vec!["did".to_string()],
                acr: "aal1".to_string(),
            };
            let req = &doc.payload;

            // ── Probe mode: read-only, MUST name a path. ──────────────────
            if !req.reserve {
                let path = req.path.as_deref().ok_or_else(|| {
                    doc.reject_with(
                        new_id(),
                        ErrorPayload::new(StandardCode::MalformedRequest).with_message(
                            "check-name without `reserve: true` requires a `path` to probe",
                        ),
                    )
                })?;
                let probe = did_ops::check_name(&state, path)
                    .await
                    .map_err(|e| reject_apperror(&doc, e))?;
                let resp = CheckNameResponse {
                    available: probe.available,
                    reserved: false,
                    record: None,
                };
                return Ok(doc.respond_with(new_id(), resp));
            }

            // ── Reserve mode: domain resolution + atomic claim. ───────────
            // Same chain as the legacy arm: explicit → ACL default → system
            // default; proceed un-domained when none resolves.
            let acl_scope =
                match did_hosting_common::server::acl::get_acl_entry(&state.acl_ks, &auth.did)
                    .await
                    .map_err(|e| reject_apperror(&doc, e))?
                {
                    Some(e) => e.domains,
                    None => DomainScope::All,
                };
            let system_default = get_default_domain(&state.store).await.ok().flatten();
            let resolved_domain = resolve_request_domain(
                req.domain.as_deref(),
                &acl_scope,
                system_default.as_deref(),
            )
            .ok();

            match did_ops::create_did(
                &auth,
                &state,
                req.path.as_deref(),
                req.force,
                resolved_domain.as_deref(),
            )
            .await
            {
                Ok(result) => {
                    let record: DidRecord = state
                        .dids_ks
                        .get(did_key(&result.mnemonic))
                        .await
                        .map_err(|e| reject_apperror(&doc, e))?
                        .ok_or_else(|| {
                            doc.reject_with(
                                new_id(),
                                ErrorPayload::new(StandardCode::InternalError)
                                    .with_message("record missing after reservation"),
                            )
                        })?;
                    let resp = CheckNameResponse {
                        available: true,
                        reserved: true,
                        record: Some(spec_did_record_json(&record, &result.did_url)),
                    };
                    Ok(doc.respond_with(new_id(), resp))
                }
                // Spec: an already-taken path without `force` is not an error —
                // return `available: false, reserved: false` and DO NOT mutate.
                Err(AppError::Conflict(_)) => Ok(doc.respond_with(
                    new_id(),
                    CheckNameResponse {
                        available: false,
                        reserved: false,
                        record: None,
                    },
                )),
                Err(e) => Err(reject_apperror(&doc, e)),
            }
        },
    )
    .await
}

async fn handle_info<V>(
    state: &AppState,
    transport: &(impl TransportHandler + Sync),
    policy: ProofPolicy<'_, V>,
    doc: TrustTask<InfoRequest>,
) -> DispatchOutcome
where
    V: ProofVerifier + ?Sized,
{
    let (my_vid, state) = match resolve_state(state, &doc) {
        Ok(v) => v,
        Err(o) => return *o,
    };
    run_pipeline(
        transport,
        policy,
        doc,
        &my_vid,
        move |doc, parties| async move {
            let auth = authorize(&state, &doc, &parties).await?;
            let mnemonic = doc.payload.mnemonic.clone();
            let (record, log_metadata) = did_ops::get_did_info(&auth, &state, &mnemonic)
                .await
                .map_err(|e| reject_apperror(&doc, e))?;
            let did_stats: did_hosting_common::DidStats = state
                .stats_ks
                .get(format!("stats:{mnemonic}"))
                .await
                .map_err(|e| reject_apperror(&doc, e))?
                .unwrap_or_default();
            let base_url = state
                .config
                .did_hosting_url
                .as_deref()
                .or(state.config.public_url.as_deref())
                .unwrap_or("http://localhost");
            let resp = InfoResponse {
                did_url: format!("{base_url}/{mnemonic}/did.jsonl"),
                mnemonic: record.mnemonic,
                did_id: record.did_id,
                owner: record.owner,
                created_at: record.created_at,
                updated_at: record.updated_at,
                version_count: record.version_count,
                content_size: record.content_size,
                stats: serde_json::json!({
                    "totalResolves": did_stats.total_resolves,
                    "totalUpdates": did_stats.total_updates,
                    "lastResolvedAt": did_stats.last_resolved_at,
                    "lastUpdatedAt": did_stats.last_updated_at,
                }),
                log_metadata: log_metadata
                    .map(|m| serde_json::to_value(m).unwrap_or(Value::Null))
                    .unwrap_or(Value::Null),
            };
            Ok(doc.respond_with(new_id(), resp))
        },
    )
    .await
}

async fn handle_list<V>(
    state: &AppState,
    transport: &(impl TransportHandler + Sync),
    policy: ProofPolicy<'_, V>,
    doc: TrustTask<ListRequest>,
) -> DispatchOutcome
where
    V: ProofVerifier + ?Sized,
{
    let (my_vid, state) = match resolve_state(state, &doc) {
        Ok(v) => v,
        Err(o) => return *o,
    };
    run_pipeline(
        transport,
        policy,
        doc,
        &my_vid,
        move |doc, parties| async move {
            let auth = authorize(&state, &doc, &parties).await?;
            let entries =
                did_ops::list_dids(&auth, &state, doc.payload.owner.as_deref(), None, None)
                    .await
                    .map_err(|e| reject_apperror(&doc, e))?;
            let dids: Vec<Value> = entries
                .into_iter()
                .map(|e| {
                    serde_json::json!({
                        "mnemonic": e.mnemonic,
                        "didId": e.did_id,
                        "createdAt": e.created_at,
                        "updatedAt": e.updated_at,
                        "versionCount": e.version_count,
                        "totalResolves": e.total_resolves,
                    })
                })
                .collect();
            Ok(doc.respond_with(new_id(), ListResponse { dids }))
        },
    )
    .await
}

async fn handle_delete<V>(
    state: &AppState,
    transport: &(impl TransportHandler + Sync),
    policy: ProofPolicy<'_, V>,
    doc: TrustTask<DeleteRequest>,
) -> DispatchOutcome
where
    V: ProofVerifier + ?Sized,
{
    let (my_vid, state) = match resolve_state(state, &doc) {
        Ok(v) => v,
        Err(o) => return *o,
    };
    run_pipeline(
        transport,
        policy,
        doc,
        &my_vid,
        move |doc, parties| async move {
            let auth = authorize(&state, &doc, &parties).await?;
            let mnemonic = doc.payload.mnemonic.clone();
            let did_id = did_ops::delete_did(&auth, &state, &mnemonic, None)
                .await
                .map_err(|e| reject_apperror(&doc, e))?;
            crate::server_push::notify_servers_delete(&state, mnemonic.clone());
            Ok(doc.respond_with(new_id(), DeleteResponse { mnemonic, did_id }))
        },
    )
    .await
}

async fn handle_register<V>(
    state: &AppState,
    transport: &(impl TransportHandler + Sync),
    policy: ProofPolicy<'_, V>,
    doc: TrustTask<RegisterRequest>,
) -> DispatchOutcome
where
    V: ProofVerifier + ?Sized,
{
    let (my_vid, state) = match resolve_state(state, &doc) {
        Ok(v) => v,
        Err(o) => return *o,
    };
    run_pipeline(
        transport,
        policy,
        doc,
        &my_vid,
        move |doc, parties| async move {
            let auth = authorize(&state, &doc, &parties).await?;
            let req = &doc.payload;
            if req.path.is_empty() {
                return Err(doc.reject_with(
                    new_id(),
                    ErrorPayload::new(StandardCode::MalformedRequest)
                        .with_message("register requires a non-empty `path`"),
                ));
            }
            let result =
                did_ops::register_did_atomic(&auth, &state, &req.path, &req.did_log, req.force)
                    .await
                    .map_err(|e| reject_apperror(&doc, e))?;
            crate::server_push::notify_servers_did(&state, result.mnemonic.clone());
            let server_did = state.config.server_did.clone().unwrap_or_default();
            Ok(doc.respond_with(
                new_id(),
                RegisterResponse {
                    mnemonic: result.mnemonic,
                    did_url: result.did_url,
                    server_did,
                },
            ))
        },
    )
    .await
}

async fn handle_change_owner<V>(
    state: &AppState,
    transport: &(impl TransportHandler + Sync),
    policy: ProofPolicy<'_, V>,
    doc: TrustTask<ChangeOwnerRequest>,
) -> DispatchOutcome
where
    V: ProofVerifier + ?Sized,
{
    let (my_vid, state) = match resolve_state(state, &doc) {
        Ok(v) => v,
        Err(o) => return *o,
    };
    run_pipeline(
        transport,
        policy,
        doc,
        &my_vid,
        move |doc, parties| async move {
            let auth = authorize(&state, &doc, &parties).await?;
            let record = did_ops::change_did_owner(
                &auth,
                &state,
                &doc.payload.mnemonic,
                &doc.payload.new_owner,
            )
            .await
            .map_err(|e| reject_apperror(&doc, e))?;
            Ok(doc.respond_with(
                new_id(),
                ChangeOwnerResponse {
                    mnemonic: record.mnemonic,
                    owner: record.owner,
                    updated_at: record.updated_at,
                },
            ))
        },
    )
    .await
}

async fn handle_witness_publish<V>(
    state: &AppState,
    transport: &(impl TransportHandler + Sync),
    policy: ProofPolicy<'_, V>,
    doc: TrustTask<WitnessPublishRequest>,
) -> DispatchOutcome
where
    V: ProofVerifier + ?Sized,
{
    let (my_vid, state) = match resolve_state(state, &doc) {
        Ok(v) => v,
        Err(o) => return *o,
    };
    run_pipeline(
        transport,
        policy,
        doc,
        &my_vid,
        move |doc, parties| async move {
            let auth = authorize(&state, &doc, &parties).await?;
            let mnemonic = doc.payload.mnemonic.clone();
            let witness_str = serde_json::to_string(&doc.payload.witness).unwrap_or_default();
            if witness_str.is_empty() || witness_str == "null" {
                return Err(doc.reject_with(
                    new_id(),
                    ErrorPayload::new(StandardCode::MalformedRequest)
                        .with_message("witness content cannot be empty"),
                ));
            }
            did_ops::upload_witness(&auth, &state, &mnemonic, &witness_str)
                .await
                .map_err(|e| reject_apperror(&doc, e))?;
            let base_url = state
                .config
                .did_hosting_url
                .as_deref()
                .or(state.config.public_url.as_deref())
                .unwrap_or("http://localhost");
            let witness_url = format!("{base_url}/{mnemonic}/did-witness.json");
            crate::server_push::notify_servers_did(&state, mnemonic.clone());
            Ok(doc.respond_with(
                new_id(),
                WitnessPublishResponse {
                    mnemonic,
                    witness_url,
                },
            ))
        },
    )
    .await
}

/// Build the shared `{record}` agent-name response from an updated record.
fn agent_name_response(state: &AppState, record: &DidRecord) -> AgentNameResponse {
    let base_url = state
        .config
        .did_hosting_url
        .as_deref()
        .or(state.config.public_url.as_deref())
        .unwrap_or("http://localhost");
    let did_url = format!(
        "{}/{}/did.jsonl",
        base_url.trim_end_matches('/'),
        record.mnemonic
    );
    AgentNameResponse {
        record: spec_did_record_json(record, &did_url),
    }
}

/// The two agent-name ops share one handler shape — authorize, call the
/// matching `did_ops` op with `{mnemonic, name, didData, domain}`, fan the
/// new version out to edges, and reply with the updated record. (Step-up on
/// remove / parking is a consumer-policy gate enforced on the REST surface
/// via `StepUpAuth`; the Trust-Task path carries no assurance level, so —
/// like `handle_delete` — it relies on the proof-authenticated owner check
/// in `did_ops`.)
async fn handle_update_agent_name<V>(
    state: &AppState,
    transport: &(impl TransportHandler + Sync),
    policy: ProofPolicy<'_, V>,
    doc: TrustTask<UpdateAgentNameRequest>,
) -> DispatchOutcome
where
    V: ProofVerifier + ?Sized,
{
    let (my_vid, state) = match resolve_state(state, &doc) {
        Ok(v) => v,
        Err(o) => return *o,
    };
    run_pipeline(
        transport,
        policy,
        doc,
        &my_vid,
        move |doc, parties| async move {
            let auth = authorize(&state, &doc, &parties).await?;
            let mnemonic = doc.payload.mnemonic.clone();
            let record = did_ops::update_agent_name(
                &auth,
                &state,
                &mnemonic,
                &doc.payload.name,
                &doc.payload.did_data,
                doc.payload.domain.as_deref(),
                doc.payload.state,
            )
            .await
            .map_err(|e| reject_apperror(&doc, e))?;
            crate::server_push::notify_servers_did(&state, mnemonic.clone());
            let resp = agent_name_response(&state, &record);
            Ok(doc.respond_with(new_id(), resp))
        },
    )
    .await
}

async fn handle_remove_agent_name<V>(
    state: &AppState,
    transport: &(impl TransportHandler + Sync),
    policy: ProofPolicy<'_, V>,
    doc: TrustTask<RemoveAgentNameRequest>,
) -> DispatchOutcome
where
    V: ProofVerifier + ?Sized,
{
    let (my_vid, state) = match resolve_state(state, &doc) {
        Ok(v) => v,
        Err(o) => return *o,
    };
    run_pipeline(
        transport,
        policy,
        doc,
        &my_vid,
        move |doc, parties| async move {
            let auth = authorize(&state, &doc, &parties).await?;
            let mnemonic = doc.payload.mnemonic.clone();
            let record = did_ops::remove_agent_name(
                &auth,
                &state,
                &mnemonic,
                &doc.payload.name,
                &doc.payload.did_data,
                doc.payload.domain.as_deref(),
            )
            .await
            .map_err(|e| reject_apperror(&doc, e))?;
            crate::server_push::notify_servers_did(&state, mnemonic.clone());
            let resp = agent_name_response(&state, &record);
            Ok(doc.respond_with(new_id(), resp))
        },
    )
    .await
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Resolve the service DID (for the pipeline's recipient anchor) and clone
/// the `AppState` for capture into the `run_pipeline` handler closure.
/// Returns the failure `DispatchOutcome` when no service DID is configured.
fn resolve_state<P>(
    state: &AppState,
    doc: &TrustTask<P>,
) -> Result<(String, AppState), Box<DispatchOutcome>> {
    match state.config.server_did.as_deref() {
        Some(v) => Ok((v.to_string(), state.clone())),
        // Boxed: `DispatchOutcome` is a large framework enum, and clippy's
        // `result_large_err` flags returning it unboxed in a `Result`.
        None => Err(Box::new(DispatchOutcome::Rejected(
            doc.reject_with(
                new_id(),
                ErrorPayload::new(StandardCode::InternalError)
                    .with_message("the maintainer is not fully configured (no service DID)"),
            ),
        ))),
    }
}

/// Resolve the caller (framework-resolved `parties.issuer`, in-band wins)
/// and check the maintainer ACL, returning an `AuthClaims` for the
/// `did_ops::*` calls. The same authorisation gate the legacy transport
/// applies before `dispatch_did_op`.
async fn authorize<P>(
    state: &AppState,
    doc: &TrustTask<P>,
    parties: &ResolvedParties,
) -> Result<AuthClaims, ErrorResponse> {
    let caller = parties.issuer.as_deref().ok_or_else(|| {
        doc.reject_with(
            new_id(),
            ErrorPayload::new(StandardCode::PermissionDenied)
                .with_message("inbound document has no in-band or transport-derived issuer"),
        )
    })?;
    let role = check_acl(&state.acl_ks, caller).await.map_err(|_| {
        doc.reject_with(
            new_id(),
            ErrorPayload::new(StandardCode::PermissionDenied)
                .with_message("caller is not present in the maintainer's ACL"),
        )
    })?;
    Ok(AuthClaims {
        did: caller.to_string(),
        role,
        session_id: String::new(),
        session_pubkey_b58btc: None,
        amr: vec!["did".to_string()],
        acr: "aal1".to_string(),
    })
}

fn new_id() -> String {
    format!("urn:uuid:{}", uuid::Uuid::new_v4())
}

/// Map an [`AppError`] to a framework-routed error document, preserving
/// the request's `issuer`/`recipient` so it addresses the caller.
fn reject_apperror<P>(doc: &TrustTask<P>, e: AppError) -> trust_tasks_rs::ErrorResponse {
    // StandardCode has no NotFound/Conflict; map the closest framework code.
    let code = match &e {
        AppError::Validation(_) => StandardCode::MalformedRequest,
        AppError::Forbidden(_)
        | AppError::Authentication(_)
        | AppError::Unauthorized(_)
        | AppError::StepUpRequired(_) => StandardCode::PermissionDenied,
        AppError::NotFound(_) | AppError::Conflict(_) => StandardCode::TaskFailed,
        // Agent-name precondition failures are client errors, not maintainer
        // faults — surface them (with their message) rather than masking as an
        // internal error. `AlsoKnownAsMismatch` is a malformed submission (the
        // document doesn't match the request); the rest are task-state
        // failures (name taken, not found, wrong enabled-state, reserved).
        AppError::AgentName(
            did_hosting_common::server::error::AgentNameError::AlsoKnownAsMismatch,
        ) => StandardCode::MalformedRequest,
        AppError::AgentName(_) => StandardCode::TaskFailed,
        _ => StandardCode::InternalError,
    };
    // Internal failures keep their operator detail in the log, not the wire.
    if matches!(code, StandardCode::InternalError) {
        tracing::error!(error = %e, "did-hosting/1.0: internal failure");
        return doc.reject_with(
            new_id(),
            ErrorPayload::new(StandardCode::InternalError)
                .with_message("the maintainer encountered an internal failure"),
        );
    }
    doc.reject_with(
        new_id(),
        ErrorPayload::new(code).with_message(e.user_message()),
    )
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;
    use std::sync::{Arc, OnceLock};

    use did_hosting_common::server::acl::{AclEntry, Role, store_acl_entry};
    use did_hosting_common::server::config::{
        AuthConfig, FeaturesConfig, LogConfig, SecretsConfig, ServerConfig, StoreConfig, VtaConfig,
    };
    use did_hosting_common::server::stats_collector::StatsCollector;
    use did_hosting_common::server::store::{
        KS_ACL, KS_DIDS, KS_REGISTRY, KS_SESSIONS, KS_STATS, KS_TIMESERIES, Store,
    };
    use did_hosting_common::server::trust_tasks::TransportBoundVerifier;
    use serde_json::json;
    use trust_tasks_rs::handlers::InMemoryHandler;
    use trust_tasks_rs::{Payload, ProofPolicy};

    use crate::config::{AppConfig, RegistryConfig};

    use super::*;

    const SERVICE_DID: &str = "did:webvh:test:control.example.com";
    const ADMIN_DID: &str = "did:web:admin.example";

    async fn test_state() -> (AppState, tempfile::TempDir) {
        let dir = tempfile::tempdir().expect("temp dir");
        let store_config = StoreConfig {
            data_dir: PathBuf::from(dir.path()),
            ..StoreConfig::default()
        };
        let store = Store::open(&store_config).await.expect("open store");
        let config = AppConfig {
            features: FeaturesConfig::default(),
            server_did: Some(SERVICE_DID.into()),
            mediator_did: None,
            public_url: Some("http://control.test".into()),
            did_hosting_url: Some("http://control.test".into()),
            server: ServerConfig::default(),
            log: LogConfig::default(),
            store: store_config,
            auth: AuthConfig::default(),
            secrets: SecretsConfig::default(),
            vta: VtaConfig::default(),
            registry: RegistryConfig::default(),
            trust_tasks: Default::default(),
            hosting: Default::default(),
            identity: Default::default(),
            config_path: PathBuf::new(),
        };
        let state = AppState {
            store: store.clone(),
            sessions_ks: store.keyspace(KS_SESSIONS).unwrap(),
            acl_ks: store.keyspace(KS_ACL).unwrap(),
            registry_ks: store.keyspace(KS_REGISTRY).unwrap(),
            dids_ks: store.keyspace(KS_DIDS).unwrap(),
            config: Arc::new(config),
            did_resolver: None,
            secrets_resolver: None,
            identity: None,
            trust_tasks_verifier: None,
            jwt_keys: None,
            webauthn: None,
            http_client: reqwest::Client::new(),
            didcomm_service: Arc::new(OnceLock::new()),
            stats_collector: Arc::new(StatsCollector::new()),
            stats_ks: store.keyspace(KS_STATS).unwrap(),
            timeseries_ks: store.keyspace(KS_TIMESERIES).unwrap(),
            signing_key_bytes: None,
            replay_cache: Arc::new(crate::replay::ReplayCache::new()),
            path_locks: crate::path_locks::PathLocks::new(),
            acl_locks: did_hosting_common::server::path_locks::PathLocks::new(),
            pending_challenges: Arc::new(crate::pending_challenges::PendingChallengeTracker::new()),
            ip_rate_limiter: Arc::new(crate::rate_limit::IpRateLimiter::new()),
            pending_confirms: Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new())),
            outbox_notify: Arc::new(tokio::sync::Notify::new()),
        };
        (state, dir)
    }

    async fn seed_admin(state: &AppState) {
        store_acl_entry(
            &state.acl_ks,
            &AclEntry {
                did: ADMIN_DID.into(),
                role: Role::Admin,
                label: None,
                created_at: 1_700_000_000,
                max_total_size: None,
                max_did_count: None,
                domains: did_hosting_common::server::domain::DomainScope::All,
            },
        )
        .await
        .unwrap();
    }

    fn check_name_doc(path: &str, reserve: bool) -> TrustTask<Value> {
        let body = json!({
            "id": new_id(),
            "type": CheckNameRequest::TYPE_URI,
            "recipient": SERVICE_DID,
            "issuedAt": "2026-07-07T00:00:00Z",
            "payload": { "path": path, "reserve": reserve }
        });
        serde_json::from_value(body).expect("doc parses")
    }

    fn transport() -> InMemoryHandler {
        InMemoryHandler::new()
            .with_local(SERVICE_DID.to_string())
            .with_peer(ADMIN_DID.to_string())
    }

    /// `owns` recognises the typed request URI and rejects others.
    #[test]
    fn owns_recognises_did_hosting_uri() {
        assert!(owns(CheckNameRequest::TYPE_URI));
        assert!(!owns("https://trusttasks.org/spec/acl/grant/0.1"));
        assert!(!owns(
            "https://trusttasks.org/spec/did-management/did/publish/0.1"
        ));
    }

    /// Probe of a free path returns `available: true, reserved: false`
    /// through the typed framework pipeline, with the `#response` Type URI.
    #[tokio::test]
    async fn probe_available_over_typed_pipeline() {
        let (state, _dir) = test_state().await;
        seed_admin(&state).await;
        let transport = transport();
        let outcome = dispatch::<TransportBoundVerifier>(
            &state,
            &transport,
            ProofPolicy::AcceptUnverified,
            check_name_doc("alice", false),
        )
        .await;
        let resp = match outcome {
            DispatchOutcome::Handled(d) => d,
            other => panic!("expected Handled, got {other:?}"),
        };
        assert_eq!(
            resp.type_uri.to_string(),
            format!("{}#response", CheckNameRequest::TYPE_URI)
        );
        assert_eq!(resp.payload["available"], true);
        assert_eq!(resp.payload["reserved"], false);
    }

    /// Reserve claims the slot: `available: true, reserved: true` with the
    /// committed record, and the DID exists in the store afterwards.
    #[tokio::test]
    async fn reserve_claims_slot_over_typed_pipeline() {
        let (state, _dir) = test_state().await;
        seed_admin(&state).await;
        let transport = transport();
        let outcome = dispatch::<TransportBoundVerifier>(
            &state,
            &transport,
            ProofPolicy::AcceptUnverified,
            check_name_doc("bob", true),
        )
        .await;
        let resp = match outcome {
            DispatchOutcome::Handled(d) => d,
            other => panic!("expected Handled, got {other:?}"),
        };
        assert_eq!(resp.payload["available"], true);
        assert_eq!(resp.payload["reserved"], true);
        assert!(
            resp.payload["record"].is_object(),
            "reservation returns the committed record"
        );
        // The record projection carries the mnemonic; the DID is now stored.
        let mnemonic = resp.payload["record"]["mnemonic"]
            .as_str()
            .expect("record has a mnemonic");
        let stored: Option<DidRecord> = state.dids_ks.get(did_key(mnemonic)).await.unwrap();
        assert!(stored.is_some(), "reserved DID persisted");
    }

    /// A caller absent from the ACL is rejected `permission_denied` — the
    /// same gate the legacy transport applies.
    #[tokio::test]
    async fn unknown_caller_rejected_permission_denied() {
        let (state, _dir) = test_state().await;
        // No admin seeded → ADMIN_DID is not in the ACL.
        let transport = transport();
        let outcome = dispatch::<TransportBoundVerifier>(
            &state,
            &transport,
            ProofPolicy::AcceptUnverified,
            check_name_doc("carol", false),
        )
        .await;
        let err = match outcome {
            DispatchOutcome::Rejected(e) => e,
            other => panic!("expected Rejected, got {other:?}"),
        };
        assert_eq!(
            err.payload.code,
            trust_tasks_rs::TrustTaskCode::Standard(StandardCode::PermissionDenied)
        );
    }

    fn op_doc(type_uri: &str, payload: Value) -> TrustTask<Value> {
        let body = json!({
            "id": new_id(),
            "type": type_uri,
            "recipient": SERVICE_DID,
            "issuedAt": "2026-07-07T00:00:00Z",
            "payload": payload
        });
        serde_json::from_value(body).expect("doc parses")
    }

    fn expect_handled(outcome: DispatchOutcome) -> TrustTask<Value> {
        match outcome {
            DispatchOutcome::Handled(d) => d,
            other => panic!("expected Handled, got {other:?}"),
        }
    }

    /// Reserve a DID and return its mnemonic (setup for info/list/delete).
    async fn reserve_did(state: &AppState, path: &str) -> String {
        let outcome = dispatch::<TransportBoundVerifier>(
            state,
            &transport(),
            ProofPolicy::AcceptUnverified,
            check_name_doc(path, true),
        )
        .await;
        expect_handled(outcome).payload["record"]["mnemonic"]
            .as_str()
            .expect("reserved record has a mnemonic")
            .to_string()
    }

    #[tokio::test]
    async fn info_returns_record_over_typed() {
        let (state, _dir) = test_state().await;
        seed_admin(&state).await;
        let mnemonic = reserve_did(&state, "infotest").await;

        let resp = expect_handled(
            dispatch::<TransportBoundVerifier>(
                &state,
                &transport(),
                ProofPolicy::AcceptUnverified,
                op_doc(InfoRequest::TYPE_URI, json!({ "mnemonic": mnemonic })),
            )
            .await,
        );
        assert_eq!(
            resp.type_uri.to_string(),
            format!("{}#response", InfoRequest::TYPE_URI)
        );
        assert_eq!(resp.payload["mnemonic"], mnemonic);
        assert_eq!(resp.payload["owner"], ADMIN_DID);
        assert!(resp.payload["stats"].is_object());
    }

    #[tokio::test]
    async fn list_returns_dids_over_typed() {
        let (state, _dir) = test_state().await;
        seed_admin(&state).await;
        let mnemonic = reserve_did(&state, "listtest").await;

        let resp = expect_handled(
            dispatch::<TransportBoundVerifier>(
                &state,
                &transport(),
                ProofPolicy::AcceptUnverified,
                op_doc(ListRequest::TYPE_URI, json!({})),
            )
            .await,
        );
        let dids = resp.payload["dids"].as_array().expect("dids array");
        assert!(
            dids.iter().any(|d| d["mnemonic"] == mnemonic),
            "reserved DID appears in the list: {dids:?}"
        );
    }

    #[tokio::test]
    async fn delete_removes_did_over_typed() {
        let (state, _dir) = test_state().await;
        seed_admin(&state).await;
        let mnemonic = reserve_did(&state, "deltest").await;

        let resp = expect_handled(
            dispatch::<TransportBoundVerifier>(
                &state,
                &transport(),
                ProofPolicy::AcceptUnverified,
                op_doc(DeleteRequest::TYPE_URI, json!({ "mnemonic": mnemonic })),
            )
            .await,
        );
        assert_eq!(resp.payload["mnemonic"], mnemonic);
        let stored: Option<DidRecord> = state.dids_ks.get(did_key(&mnemonic)).await.unwrap();
        assert!(stored.is_none(), "deleted DID is gone from the store");
    }

    #[test]
    fn owns_recognises_all_registered_ops() {
        for uri in [
            CheckNameRequest::TYPE_URI,
            InfoRequest::TYPE_URI,
            ListRequest::TYPE_URI,
            DeleteRequest::TYPE_URI,
            RegisterRequest::TYPE_URI,
            ChangeOwnerRequest::TYPE_URI,
            WitnessPublishRequest::TYPE_URI,
            UpdateAgentNameRequest::TYPE_URI,
            RemoveAgentNameRequest::TYPE_URI,
        ] {
            assert!(owns(uri), "dispatcher should own {uri}");
        }
    }

    /// Register routes to `did_ops::register_did_atomic` — a malformed log
    /// is rejected there (a valid signed log is covered by the did_ops
    /// tests). Also proves the empty-path guard.
    #[tokio::test]
    async fn register_malformed_log_rejected_over_typed() {
        let (state, _dir) = test_state().await;
        seed_admin(&state).await;
        let outcome = dispatch::<TransportBoundVerifier>(
            &state,
            &transport(),
            ProofPolicy::AcceptUnverified,
            op_doc(
                RegisterRequest::TYPE_URI,
                json!({ "path": "regtest", "didLog": "garbage", "force": false }),
            ),
        )
        .await;
        assert!(
            matches!(outcome, DispatchOutcome::Rejected(_)),
            "malformed register log is rejected"
        );
    }

    /// Change-owner routes to `did_ops::change_did_owner`; transferring to
    /// an unknown owner is rejected there.
    #[tokio::test]
    async fn change_owner_unknown_target_rejected_over_typed() {
        let (state, _dir) = test_state().await;
        seed_admin(&state).await;
        let mnemonic = reserve_did(&state, "chowntest").await;
        let outcome = dispatch::<TransportBoundVerifier>(
            &state,
            &transport(),
            ProofPolicy::AcceptUnverified,
            op_doc(
                ChangeOwnerRequest::TYPE_URI,
                json!({ "mnemonic": mnemonic, "newOwner": "did:web:nobody.example" }),
            ),
        )
        .await;
        assert!(
            matches!(outcome, DispatchOutcome::Rejected(_)),
            "change to an unknown owner is rejected"
        );
    }

    /// Witness-publish validates a non-empty witness before delegating.
    #[tokio::test]
    async fn witness_publish_empty_rejected_over_typed() {
        let (state, _dir) = test_state().await;
        seed_admin(&state).await;
        let mnemonic = reserve_did(&state, "wittest").await;
        let outcome = dispatch::<TransportBoundVerifier>(
            &state,
            &transport(),
            ProofPolicy::AcceptUnverified,
            op_doc(
                WitnessPublishRequest::TYPE_URI,
                json!({ "mnemonic": mnemonic, "witness": null }),
            ),
        )
        .await;
        let err = match outcome {
            DispatchOutcome::Rejected(e) => e,
            other => panic!("expected Rejected, got {other:?}"),
        };
        assert_eq!(
            err.payload.code,
            trust_tasks_rs::TrustTaskCode::Standard(StandardCode::MalformedRequest)
        );
    }

    // --- Agent names -------------------------------------------------------

    /// A reserved name (`@admin`) routes to `did_ops::update_agent_name`, is
    /// refused there, and — crucially — surfaces as a routed `task_failed`,
    /// **not** a masked `internal_error`. This exercises the `reject_apperror`
    /// arm added for `AppError::AgentName`.
    #[tokio::test]
    async fn update_agent_name_reserved_maps_to_task_failed() {
        let (state, _dir) = test_state().await;
        seed_admin(&state).await;
        let mnemonic = reserve_did(&state, "aliceslot").await;

        let outcome = dispatch::<TransportBoundVerifier>(
            &state,
            &transport(),
            ProofPolicy::AcceptUnverified,
            op_doc(
                UpdateAgentNameRequest::TYPE_URI,
                json!({ "mnemonic": mnemonic, "name": "admin", "state": "active", "didData": "irrelevant" }),
            ),
        )
        .await;
        let err = match outcome {
            DispatchOutcome::Rejected(e) => e,
            other => panic!("expected Rejected (reserved name), got {other:?}"),
        };
        assert_eq!(
            err.payload.code,
            trust_tasks_rs::TrustTaskCode::Standard(StandardCode::TaskFailed),
            "a reserved agent name must map to task_failed, not internal_error"
        );
    }

    /// Update routes through the pipeline to `did_ops::update_agent_name`; a
    /// malformed `didData` is rejected in the shared publish path (a valid
    /// signed log + `alsoKnownAs` happy path is covered by the `did_ops`
    /// tests). Proves delegation for the whole agent-name family, and pins
    /// the pre-cutover `didLog` alias.
    #[tokio::test]
    async fn update_agent_name_malformed_log_rejected_over_typed() {
        let (state, _dir) = test_state().await;
        seed_admin(&state).await;
        let mnemonic = reserve_did(&state, "nameslot").await;

        for field in ["didData", "didLog"] {
            let outcome = dispatch::<TransportBoundVerifier>(
                &state,
                &transport(),
                ProofPolicy::AcceptUnverified,
                op_doc(
                    UpdateAgentNameRequest::TYPE_URI,
                    json!({ "mnemonic": mnemonic, "name": "alice", "state": "active", field: "not-a-valid-jsonl-log" }),
                ),
            )
            .await;
            assert!(
                matches!(outcome, DispatchOutcome::Rejected(_)),
                "a malformed {field} is rejected in did_ops"
            );
        }
    }

    /// A caller absent from the ACL cannot invoke a destructive agent-name
    /// verb — the auth gate runs before any `did_ops` work.
    #[tokio::test]
    async fn remove_agent_name_unknown_caller_denied() {
        let (state, _dir) = test_state().await;
        // No admin seeded → the caller is not in the ACL.
        let outcome = dispatch::<TransportBoundVerifier>(
            &state,
            &transport(),
            ProofPolicy::AcceptUnverified,
            op_doc(
                RemoveAgentNameRequest::TYPE_URI,
                json!({ "mnemonic": "whatever", "name": "alice", "didLog": "x" }),
            ),
        )
        .await;
        let err = match outcome {
            DispatchOutcome::Rejected(e) => e,
            other => panic!("expected Rejected (unknown caller), got {other:?}"),
        };
        assert_eq!(
            err.payload.code,
            trust_tasks_rs::TrustTaskCode::Standard(StandardCode::PermissionDenied)
        );
    }
}