alkgit 0.1.0

Git smart protocol for the alk family: pkt-line substrates, protocol V2 serving (upload-pack/receive-pack), producer/consumer halves on alkcall channels, and the backend seam traits — the shipped alkstore+alkblobs composition is the alkgit-substrate crate (ADR-010/025)
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
//! Producer half of the channels integration — the `register_openable`
//! helper, the `channels/git/sub` open op, and its establisher
//! (ADR-016 §1, the alktty `channels/tty/sub` template, alkcall
//! ADR-047/049).
//!
//! This is the path where git rides inside `alk/channels` rather than
//! directly on the `alk/git` ALPN connection. The assembly layer builds
//! the per-connection [`ChannelCore`] and calls [`register_openable`];
//! when a consumer invokes `channels/git/sub` with `{repo, service}
//! params, the alkcall channels wrapper does `check_open` →
//! `open_channel` → await the establisher bounded (alkcall ADR-049 §1)
//! → spawn the open handler → respond `{channel_id}`. The establisher
//! runs the full parse (both params required, the ADR-016 service
//! enum, `git-upload-archive` rejected at the gate), the repo-id
//! grammar rejection, and the resolve→authorize sequence with the
//! service-selected action — rejection replies `channel:open_failed`,
//! no phantom channel. The open handler receives the channel's
//! [`Connection`], takes its [`BiStream`](alkcall::core::BiStream),
//! and drives the duplex serving entry inline (the R-02 lifetime
//! contract — the handler tracks the data-plane lifetime).
//!
//! The spec's [`AccessControl`] stays empty: per-repo grant checks are
//! handler-side (ADR-011/015 — there is no static scope gate to express
//! them with); the establisher *is* the open-time ACL point. The
//! collapse rule holds here: resolution and authorization failures map
//! to one reason with one generic message (recorded interpretation —
//! the alktty vocabulary splits unknown-resource from ACL-denial, but
//! ADR-008's indistinguishability rule outranks it; the wave-2 review
//! confirms), which is [`EstablishmentError::HandlerError`] carrying
//! the ADR-008 denial shape.

use std::str::FromStr;
use std::sync::Arc;

use alkcall::channels::operations::{
    ChannelCore, ChannelPlan, Establishment, EstablishmentError, OpenEstablisher, OpenHandler,
};
use alkcall::core::auth::AuthContext;
use alkcall::registry::registration::OperationRegistry;
use alkcall::registry::spec::{
    AccessControl, ChannelOpenSpec, ErrorDefinition, OperationSpec, OperationType, Visibility,
};
use serde::Deserialize;
use serde_json::{json, Value};
use tokio::sync::Semaphore;

use alkcall::core::Connection;

use crate::adapter::SessionHandles;
use crate::authorize::AuthorizedRepo;
use crate::backend::{GitPackGen, GitPackIngest, GitRefs, GitRegistry};
use crate::duplex::{serve_duplex, serve_duplex_resolved};
use crate::limits::Limits;
use crate::registry::{validate_repo_id, AccessAction};
use crate::substrate::Service;

/// The per-ALPN open operation name (`channels/<alpn>/sub` convention,
/// ADR-047). Git is consumer-opens (the client requests a fetch/push
/// session), so the op is `sub`.
pub const OP_GIT_OPEN: &str = "channels/git/sub";

/// The data-plane ALPN the channel carries (ADR-010's
/// `alk/git` ALPN). Matches the ALPN returned by
/// [`GitAdapter`](crate::GitAdapter)'s `alpn()`.
pub const GIT_ALPN: &str = "alk/git";

/// The session-establishment plan the establisher hands the open
/// handler (alkcall ADR-049 amendment 2): the checked marker and the
/// service dimension — the ADR-016 §3 duplex tuple's authorization
/// inputs, crossed via the plan so the handler never re-resolves,
/// re-authorizes, or races the gate post-open.
struct GitChannelPlan {
    marker: AuthorizedRepo,
    service: Service,
}

/// Registers the `channels/git/sub` open op on a per-connection
/// [`ChannelCore`] — the assembly layer's one-call registration of the
/// spec + establisher + open handler (`register_openable` from the
/// git adapter's shared backend handles; typically the same handles,
/// `push-options` negotiated-gate flag (ADR-013 §11), [`Limits`], and
/// pipeline semaphore the direct-ALPN [`GitAdapter`](crate::GitAdapter)
/// holds).
///
/// # Errors
///
/// Returns an error if `ChannelCore::register_openable_with_establisher`
/// rejects the spec (won't happen with the spec this helper builds, but
/// the underlying call is fallible).
#[allow(clippy::too_many_arguments)]
pub fn register_openable(
    core: &ChannelCore,
    registry: Arc<dyn GitRegistry>,
    refs: Arc<dyn GitRefs>,
    packgen: Arc<dyn GitPackGen>,
    ingest: Arc<dyn GitPackIngest>,
    push_options_negotiated: bool,
    limits: Limits,
    pipeline: Arc<Semaphore>,
    op_registry: &mut OperationRegistry,
    auth: AuthContext,
) -> Result<(), String> {
    let spec = git_open_spec();
    let establisher = make_git_establisher(Arc::clone(&registry));
    let open_handler = make_git_open_handler(
        registry,
        refs,
        packgen,
        ingest,
        push_options_negotiated,
        limits,
        pipeline,
    );
    core.register_openable_with_establisher(
        spec,
        Some(establisher),
        open_handler,
        op_registry,
        auth,
        None,
    )
}

/// Builds the [`OperationSpec`] for `channels/git/sub`.
///
/// The op is `Sub`-typed (consumer-opens — the data plane flows on the
/// channel's `BiStream`). The input schema is the ADR-016 §1 `{repo,
/// service}` params — both required, `service` the ADR-016 string
/// enum, `additionalProperties: false` (fail-closed extensions —
/// unknown fields fail rather than get silently ignored). The
/// [`AccessControl`] stays empty: per-repo grant checks are
/// handler-side (ADR-011/015) and the establisher runs them at open
/// time. The spec declares the `channel:open_failed` error (the
/// establisher's failure contract, ADR-049 §3's vocabulary) and the
/// `ChannelOpenSpec::new("alk/git")` marker.
pub fn git_open_spec() -> OperationSpec {
    let open_failed_schema = json!({
        "type": "object",
        "properties": {
            "reason": {
                "type": "string",
                "enum": ["dial_failed", "unknown_resource", "handler_error", "timeout"]
            },
            "message": { "type": "string" }
        },
        "required": ["reason", "message"]
    });
    OperationSpec::new(
        OP_GIT_OPEN,
        OperationType::Sub,
        Visibility::External,
        json!({
            "type": "object",
            "properties": {
                "repo": { "type": "string" },
                "service": {
                    "type": "string",
                    "enum": ["git-upload-pack", "git-receive-pack"]
                }
            },
            "required": ["repo", "service"],
            "additionalProperties": false
        }),
        json!({
            "type": "object",
            "properties": {
                "channel_id": { "type": "integer", "minimum": 0 }
            }
        }),
        vec![ErrorDefinition {
            code: "channel:open_failed".to_string(),
            description: "Establishment failed after channel allocation: the establisher \
                          rejected the params (malformed params, an unknown service — \
                          git-upload-archive is not in the enum — or a repo-id grammar \
                          violation) or the resolve→authorize gate denied the \
                          service-selected action. Details: { reason, message }. \
                          No channel_id is returned."
                .to_string(),
            schema: open_failed_schema,
            http_status: None,
        }],
        AccessControl::default(),
        None,
    )
    .with_description(
        "Open a git session (alk/git). The open-op params {repo, service} select the \
         repository and the git service; the establisher authorizes the service-selected \
         action (read for fetch, write for push) before any channel data flows. The data \
         plane is the pkt-line protocol session on the channel's duplex stream.",
    )
    .with_channel_open(ChannelOpenSpec::new(GIT_ALPN))
}

/// The `{repo, service}` open-op params (ADR-016 §1 — both required,
/// the service the ADR-016 string enum). `deny_unknown_fields` is the
/// fail-closed parse of the `additionalProperties: false` schema.
///
/// Exposed `#[doc(hidden)]` for the open-op-params fuzz target's drive
/// of the exact production param parse — the establisher's ingress and
/// the `plan: None` handler fallback's re-parse are this same
/// `Deserialize`; never stable API.
#[doc(hidden)]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OpenParams {
    /// The repo id reaching the grammar rejection and the registry
    /// resolve (an opaque key — never decomposed).
    pub repo: String,
    /// The service string reaching the ADR-016 enum parse.
    pub service: String,
}

/// Builds the [`OpenEstablisher`] for `channels/git/sub` (alkcall
/// ADR-049 §1): the full parse (the `{repo, service}` params, the
/// ADR-016 service enum — `git-upload-archive` fails here, one layer
/// earlier than the doors' fixed refusal), the repo-id grammar
/// rejection, and the resolve→authorize sequence with the
/// service-selected action (read for fetch, write for push — ADR-011/015).
///
/// Exposed `#[doc(hidden)]` for the open-op-params fuzz target — the
/// exact production establisher is the ingress it drives; never stable
/// API.
///
/// Failure mapping (ADR-049 §3's vocabulary, established once — no new
/// codes):
///
/// - params-parse failure, unknown service, repo-id grammar violation
///   → [`EstablishmentError::HandlerError`] with the correction (an
///   op-surface input failure — backend.md §repo-id grammar's `invalid`
///   side: the caller needs the correction, no collapse here because
///   the id shape leaks nothing about resolution state);
/// - a resolution failure and a failed authorize evaluation collapse
///   to one [`EstablishmentError::HandlerError`] with the ADR-008
///   denial shape (the unknown ≡ unauthorized collapse rule; recorded
///   interpretation confirmed at the wave-2 review).
///
/// On pass, the [`GitChannelPlan`] (marker + service) crosses to the
/// open handler via the establishment plan.
#[doc(hidden)]
pub fn make_git_establisher(registry: Arc<dyn GitRegistry>) -> OpenEstablisher {
    Arc::new(move |input: Value, auth: AuthContext| {
        let registry = Arc::clone(&registry);
        let identity = auth.identity.clone();
        Box::pin(async move {
            let params: OpenParams = match serde_json::from_value(input) {
                Ok(params) => params,
                Err(e) => {
                    return Err(EstablishmentError::HandlerError {
                        message: format!("malformed params: {e}"),
                    })
                }
            };
            if let Err(cause) = validate_repo_id(&params.repo) {
                return Err(EstablishmentError::HandlerError {
                    message: format!("invalid repo id: {cause}"),
                });
            }
            let service = match Service::from_str(&params.service) {
                Ok(service) => service,
                Err(e) => {
                    return Err(EstablishmentError::HandlerError {
                        message: format!("malformed params: {e}"),
                    })
                }
            };
            let action = if service.is_write() {
                AccessAction::Write
            } else {
                AccessAction::Read
            };
            let marker = match registry.resolve(&params.repo).await {
                Ok(record) => AuthorizedRepo::authorize(record, identity.as_ref(), action),
                Err(_) => None,
            };
            let Some(marker) = marker else {
                return Err(EstablishmentError::HandlerError {
                    message: format!("access denied: {}", params.repo),
                });
            };
            Ok(Establishment::new(
                Arc::new(GitChannelPlan { marker, service }) as ChannelPlan,
            ))
        })
    })
}

/// Builds the [`OpenHandler`] for `channels/git/sub`: takes the
/// channel's `Connection`, accepts the (yield-once) channel
/// [`BiStream`](alkcall::core::BiStream), and drives the duplex serving
/// entry **inline** — the R-02 lifetime contract: the returned task's
/// completion is the wrapper's teardown trigger, so the session is
/// awaited before the task returns, never spawn-and-forget.
///
/// With the establisher's plan the handler drives [`serve_duplex`] on
/// the crossed marker — the gate ran at open time and never re-runs.
/// With `plan: None` (a no-establisher registration — defense-in-depth,
/// the ADR-049 backward-compatibility shape) the handler re-parses the
/// params and runs [`serve_duplex_resolved`], whose gate keeps this
/// registration shape's only ACL point. A fallback parse failure is
/// session-over (nothing was promised — no channel data flows).
fn make_git_open_handler(
    registry: Arc<dyn GitRegistry>,
    refs: Arc<dyn GitRefs>,
    packgen: Arc<dyn GitPackGen>,
    ingest: Arc<dyn GitPackIngest>,
    push_options_negotiated: bool,
    limits: Limits,
    pipeline: Arc<Semaphore>,
) -> OpenHandler {
    Arc::new(
        move |input: Value,
              plan: Option<ChannelPlan>,
              channel_conn: Connection,
              auth: AuthContext| {
            let handles = SessionHandles {
                identity: auth.identity.clone(),
                registry: Arc::clone(&registry),
                refs: Arc::clone(&refs),
                packgen: Arc::clone(&packgen),
                ingest: Arc::clone(&ingest),
                push_options_negotiated,
                limits,
                pipeline: Arc::clone(&pipeline),
            };
            tokio::spawn(async move {
                let stream = match channel_conn.accept_bi().await {
                    Ok(stream) => stream,
                    Err(_) => return,
                };
                let established = plan
                    .as_ref()
                    .and_then(|plan| plan.downcast_ref::<GitChannelPlan>())
                    .map(|plan| (plan.marker.clone(), plan.service));
                match established {
                    Some((marker, service)) => {
                        let _ = serve_duplex(
                            &marker,
                            stream,
                            handles.limits,
                            service,
                            Arc::clone(&handles.refs),
                            Arc::clone(&handles.packgen),
                            Arc::clone(&handles.ingest),
                            handles.push_options_negotiated,
                            Arc::clone(&handles.pipeline),
                        )
                        .await;
                    }
                    None => {
                        let registry = Arc::clone(&handles.registry);
                        let params = serde_json::from_value::<OpenParams>(input);
                        if let Ok(params) = params {
                            if let Ok(service) = Service::from_str(&params.service) {
                                let _ = serve_duplex_resolved(
                                    &params.repo,
                                    handles.identity.as_ref(),
                                    service,
                                    stream,
                                    handles.limits,
                                    registry,
                                    Arc::clone(&handles.refs),
                                    Arc::clone(&handles.packgen),
                                    Arc::clone(&handles.ingest),
                                    handles.push_options_negotiated,
                                    Arc::clone(&handles.pipeline),
                                )
                                .await;
                            }
                        }
                    }
                }
            })
        },
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::authorize::authorize;
    use crate::error::RegistryError;
    use crate::registry::{RepoRecord, Visibility as RepoVisibility};
    use alkcall::core::Identity;
    use async_trait::async_trait;
    use std::collections::{BTreeMap, HashMap};

    /// A two-row registry stub keyed on put calls (test-local — the
    /// doubles stay out of `src/`, the location decision in
    /// `tests/common`).
    #[derive(Default)]
    struct TestRegistry {
        rows: parking_lot::Mutex<BTreeMap<String, RepoRecord>>,
    }

    impl TestRegistry {
        async fn put(&self, record: RepoRecord) {
            self.rows.lock().insert(record.repo_id.clone(), record);
        }
    }

    #[async_trait]
    impl GitRegistry for TestRegistry {
        async fn resolve(&self, repo_id: &str) -> Result<RepoRecord, RegistryError> {
            match self.rows.lock().get(repo_id) {
                Some(record) => Ok(record.clone()),
                None => Err(RegistryError::NotFound),
            }
        }
    }

    fn private_record(id: &str) -> RepoRecord {
        RepoRecord {
            repo_id: id.to_string(),
            visibility: RepoVisibility::Private,
            grants: BTreeMap::new(),
        }
    }

    fn identity(id: &str) -> Identity {
        Identity {
            id: id.to_string(),
            scopes: Vec::new(),
            resources: HashMap::new(),
        }
    }

    fn auth_with(identity: Option<Identity>) -> AuthContext {
        let mut auth = AuthContext::anonymous(b"alk/git");
        auth.identity = identity;
        auth
    }

    async fn establish(
        registry: Arc<TestRegistry>,
        input: Value,
        identity: Option<Identity>,
    ) -> Result<Establishment, EstablishmentError> {
        let establisher = make_git_establisher(registry);
        establisher(input, auth_with(identity)).await
    }

    async fn granted_registry(grant: AccessAction) -> Arc<TestRegistry> {
        let mut record = private_record("owner/doubled");
        record.grants.insert("u-7731".to_owned(), vec![grant]);
        let registry = Arc::new(TestRegistry::default());
        registry.put(record).await;
        registry
    }

    /// Contract stamp: ADR-016 §1 (`ChannelOpenSpec::new("alk/git")`,
    /// `channels/git/sub`, Sub-typed, External); core/w2-native-transport.
    #[test]
    fn git_open_spec_pins_the_channels_git_sub_operation() {
        let spec = git_open_spec();
        assert_eq!(spec.name, OP_GIT_OPEN);
        assert_eq!(OP_GIT_OPEN, "channels/git/sub");
        assert_eq!(spec.op_type, OperationType::Sub);
        assert_eq!(spec.visibility, Visibility::External);
        let marker = spec.channel_open.expect("channel_open marker set");
        assert_eq!(marker.alpn, GIT_ALPN);
        assert_eq!(GIT_ALPN, "alk/git");
    }

    /// Contract stamp: ADR-016 §1 (the `{repo, service}` params — both
    /// required, the ADR-016 service enum, `additionalProperties:
    /// false`); core/w2-native-transport.
    #[test]
    fn git_open_spec_pins_the_closed_repo_service_params_schema() {
        let spec = git_open_spec();
        let schema = &spec.input_schema;
        assert_eq!(
            schema["required"],
            json!(["repo", "service"]),
            "both params required"
        );
        assert_eq!(
            schema["properties"]["service"]["enum"],
            json!(["git-upload-pack", "git-receive-pack"]),
            "the ADR-016 service enum"
        );
        assert_eq!(
            schema["additionalProperties"],
            json!(false),
            "fail-closed extensions"
        );
    }

    /// Contract stamp: ADR-016 §1 (the `AccessControl` stays empty —
    /// per-repo grant checks are handler-side, ADR-011/015);
    /// core/w2-native-transport.
    #[test]
    fn git_open_spec_carries_an_empty_access_control() {
        let spec = git_open_spec();
        assert!(
            !spec.access_control.has_restrictions(),
            "no static scope gate: the establisher is the open-time ACL point"
        );
    }

    /// Contract stamp: alkcall ADR-049 §3 (the `channel:open_failed`
    /// failure vocabulary); core/w2-native-transport.
    #[test]
    fn git_open_spec_declares_the_open_failed_error() {
        let spec = git_open_spec();
        let def = spec
            .error_schemas
            .iter()
            .find(|e| e.code == "channel:open_failed")
            .expect("channel:open_failed ErrorDefinition declared");
        let reasons: Vec<&str> = def.schema["properties"]["reason"]["enum"]
            .as_array()
            .expect("reason enum")
            .iter()
            .filter_map(|v| v.as_str())
            .collect();
        assert_eq!(
            reasons,
            vec![
                "dial_failed",
                "unknown_resource",
                "handler_error",
                "timeout"
            ]
        );
    }

    /// Contract stamp: ADR-011 §3 / ADR-015 §2 (the service-selected
    /// authorize action — read for fetch, write for push);
    /// core/w2-native-transport.
    #[tokio::test]
    async fn the_establisher_authorizes_the_service_selected_action() {
        let registry = granted_registry(AccessAction::Read).await;

        let fetch = establish(
            registry.clone(),
            json!({ "repo": "owner/doubled", "service": "git-upload-pack" }),
            Some(identity("u-7731")),
        )
        .await;
        assert!(fetch.is_ok(), "read grant satisfies fetch");

        let push = establish(
            registry,
            json!({ "repo": "owner/doubled", "service": "git-receive-pack" }),
            Some(identity("u-7731")),
        )
        .await;
        assert!(
            matches!(&push, Err(EstablishmentError::HandlerError { message })
                if message == "access denied: owner/doubled"),
            "a read grant does not satisfy push (write is identity + write-or-manage)"
        );

        let mut write_record = private_record("owner/doubled");
        write_record
            .grants
            .insert("u-7731".to_owned(), vec![AccessAction::Write]);
        let registry = Arc::new(TestRegistry::default());
        registry.put(write_record).await;
        for service in ["git-receive-pack", "git-upload-pack"] {
            let open = establish(
                registry.clone(),
                json!({ "repo": "owner/doubled", "service": service }),
                Some(identity("u-7731")),
            )
            .await;
            assert!(open.is_ok(), "a write grant (⊇ read) satisfies {service}");
        }
    }

    /// Contract stamp: ADR-016 §1 (git-upload-archive is not in the
    /// enum — rejected at the gate, one layer earlier than the doors'
    /// fixed refusal); core/w2-native-transport.
    #[tokio::test]
    async fn the_establisher_rejects_git_upload_archive_at_the_gate() {
        let registry = Arc::new(TestRegistry::default());
        let rejected = establish(
            registry,
            json!({ "repo": "owner/doubled", "service": "git-upload-archive" }),
            Some(identity("u-7731")),
        )
        .await;
        match &rejected {
            Err(EstablishmentError::HandlerError { message }) => {
                assert!(message.contains("git-upload-archive"), "{message}");
            }
            _ => panic!("git-upload-archive is not in the enum"),
        }
    }

    /// Contract stamp: ADR-049 §3 (the establisher failure vocabulary);
    /// backend.md §repo-id grammar (`invalid` on the op paths — the
    /// caller needs the correction); core/w2-native-transport.
    #[tokio::test]
    async fn the_establisher_rejects_malformed_params_and_grammar_violations() {
        for (input, why) in [
            (json!({ "service": "git-upload-pack" }), "missing repo"),
            (json!({ "repo": "owner/doubled" }), "missing service"),
            (
                json!({ "repo": "owner/doubled", "service": "git-upload-pack", "cwd": 42 }),
                "an extra field fails closed",
            ),
        ] {
            let rejected = establish(Arc::new(TestRegistry::default()), input, None).await;
            match &rejected {
                Err(EstablishmentError::HandlerError { message }) => {
                    assert!(message.contains("malformed params"), "{why}: {message}");
                }
                _ => panic!("{why}: expected handler_error"),
            }
        }
        let rejected = establish(
            Arc::new(TestRegistry::default()),
            json!({ "repo": "UPPER/x", "service": "git-upload-pack" }),
            None,
        )
        .await;
        match &rejected {
            Err(EstablishmentError::HandlerError { message }) => {
                assert!(message.contains("invalid repo id"), "{message}");
            }
            _ => panic!("the correction is the message"),
        }
    }

    /// Contract stamp: ADR-008/N-2 (unknown ≡ unauthorized — the
    /// establisher collapses both into one reason with one generic
    /// message; recorded interpretation confirmed at the wave-2 review);
    /// core/w2-native-transport.
    #[tokio::test]
    async fn the_establisher_collapses_unknown_repo_and_unauthorized_into_one_denial() {
        let registry = Arc::new(TestRegistry::default());
        registry.put(private_record("owner/doubled")).await;
        let holder = identity("grantless");

        let unknown = match establish(
            Arc::new(TestRegistry::default()),
            json!({ "repo": "owner/doubled", "service": "git-upload-pack" }),
            Some(holder.clone()),
        )
        .await
        {
            Err(e) => e,
            Ok(_) => panic!("an unknown repo denies"),
        };
        let unauthorized = match establish(
            registry,
            json!({ "repo": "owner/doubled", "service": "git-upload-pack" }),
            Some(holder),
        )
        .await
        {
            Err(e) => e,
            Ok(_) => panic!("an unauthorized identity on a private repo denies"),
        };

        match (&unknown, &unauthorized) {
            (EstablishmentError::HandlerError { .. }, EstablishmentError::HandlerError { .. }) => {
                assert_eq!(unknown.reason(), unauthorized.reason(), "one reason");
                assert_eq!(
                    unknown.message(),
                    unauthorized.message(),
                    "one generic message"
                );
            }
            _other => panic!("both deny as the collapsed reason"),
        }
        assert!(unknown.message().contains("access denied"));
    }

    /// The passing open crosses the plan the handler takes: marker +
    /// service — the ADR-016 §3 duplex tuple's authorization inputs.
    ///
    /// Contract stamp: alkcall ADR-049 amendment 2 (the plan payload);
    /// ADR-016 §3 (the service dimension); core/w2-native-transport.
    #[tokio::test]
    async fn the_established_plan_crosses_marker_and_service() {
        let registry = granted_registry(AccessAction::Write).await;
        let identity = identity("u-7731");

        for service in ["git-upload-pack", "git-receive-pack"] {
            let establishment = establish(
                registry.clone(),
                json!({ "repo": "owner/doubled", "service": service }),
                Some(identity.clone()),
            )
            .await
            .expect("the granted identity's open establishes");
            let plan = establishment
                .plan
                .as_ref()
                .and_then(|plan| plan.downcast_ref::<GitChannelPlan>())
                .expect("the plan is the GitChannelPlan slot");
            assert_eq!(plan.service.as_str(), service);
            assert_eq!(
                plan.marker.action(),
                if service == "git-receive-pack" {
                    AccessAction::Write
                } else {
                    AccessAction::Read
                }
            );
            assert_eq!(plan.marker.record().repo_id, "owner/doubled");
        }
    }

    /// Belt-and-suspenders against the crate-root shape: `authorize`
    /// and `AuthorizedRepo::authorize` agree; the marker's fields are
    /// the inputs the session tuple consumes.
    #[test]
    fn the_checked_marker_agrees_with_the_policy_function() {
        let mut record = private_record("owner/doubled");
        record
            .grants
            .insert("u-7731".to_owned(), vec![AccessAction::Read]);
        let holder = identity("u-7731");
        assert!(authorize(&record, Some(&holder), AccessAction::Read));
        let marker = AuthorizedRepo::authorize(record, Some(&holder), AccessAction::Read)
            .expect("the passing check is a marker");
        assert_eq!(marker.identity_id(), Some("u-7731"));
        assert_eq!(marker.action(), AccessAction::Read);
    }
}