Skip to main content

gunnar_wire/
caps.rs

1//! Capabilities, and the table that keeps the advertisement honest.
2//!
3//! # The bug this module exists to make impossible
4//!
5//! A protocol-v2 client will not send an argument unless the corresponding
6//! **feature** appears in the value of the capability it belongs to. A server
7//! that parses `filter <spec>` but advertises `fetch=shallow wait-for-done` has
8//! partial-clone support that can never activate. Worse, it looks *exactly*
9//! like working code: no error is raised, no test fails, the client simply
10//! never exercises the path. Stock `git` 2.53 does this deliberately
11//! (`uploadpack.allowFilter` defaults off), which is why the shape is easy to
12//! copy by accident.
13//!
14//! So the advertisement is not written down anywhere. There is one table
15//! ([`FETCH_ARGUMENTS`], [`LS_REFS_ARGUMENTS`]) that says, per argument, which
16//! feature gates it, and both the **parser** and the **advertisement** are
17//! derived from it. Adding an argument to the parser without advertising its
18//! feature is not something you can forget to do; it is something you cannot
19//! express. That is a fix by construction rather than a guard watching two
20//! copies agree (one implementation), and `tests/advertisement.rs` still asserts the
21//! resulting invariant from the outside, red-first.
22//!
23//! # The other bug, which the paragraph above did NOT prevent
24//!
25//! That paragraph was true of the **v2 arguments** and of nothing else, and it
26//! was read as covering everything — an early audit
27//! said outright that *"advertised but not honoured is not something this
28//! codebase can express"*. It was expressible in three other places, and it was
29//! expressed:
30//!
31//! * `upload_pack_v0_capabilities` was a hand-written `vec![]`,
32//! * `receive_pack_capabilities` was a second one, and
33//! * the **v2 capability names** were a third, in `upload_pack.rs`.
34//!
35//! `"push-options".to_owned()` sat in the second of those. It was advertised,
36//! `receive_pack::ReceivePack::serve` parsed the section, and the only consumer
37//! anywhere in the tree was `.len()` in a log field. A client that ran
38//! `git push -o ci.skip` was told on the wire that the server speaks push
39//! options and the option went nowhere — a wrong answer on the wire, not a
40//! missing feature.
41//!
42//! [`ADVERTISED`] closes it the same way: **one place decides what is
43//! advertised, for all three surfaces**, every row carries a [`Honoured`]
44//! saying where it is honoured, and `tests/advertisement.rs` checks each claim
45//! against the source with comments stripped — because
46//! `contains("push-options")` is satisfied by the paragraph explaining
47//! push-options two lines above the call site.
48
49use gix_hash::Kind;
50
51/// The product half of the `agent=` capability.
52pub const PRODUCT: &str = "gunnar";
53
54/// The `agent=` value gunnar advertises: `gunnar/<crate version>`.
55pub fn default_agent() -> String {
56    format!("{PRODUCT}/{}", env!("CARGO_PKG_VERSION"))
57}
58
59/// git's name for a hash algorithm, as it appears in `object-format=`.
60pub fn object_format_name(kind: Kind) -> &'static str {
61    match kind {
62        Kind::Sha1 => "sha1",
63        Kind::Sha256 => "sha256",
64        // `gix_hash::Kind` is `#[non_exhaustive]`. A hash gunnar has never
65        // heard of cannot be advertised as one it has, so it gets a name no
66        // client will match and `check_object_format` rejects every request
67        // against it. Loudly wrong beats quietly wrong.
68        _ => "unsupported",
69    }
70}
71
72/// The inverse of [`object_format_name`].
73pub fn object_format_from_name(name: &str) -> Option<Kind> {
74    match name {
75        "sha1" => Some(Kind::Sha1),
76        "sha256" => Some(Kind::Sha256),
77        _ => None,
78    }
79}
80
81/// Whether an argument carries a value after its name.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum Value {
84    /// The whole line is the argument name: `done`, `thin-pack`.
85    None,
86    /// A single space, then the value: `want <oid>`, `ref-prefix <p>`.
87    Required,
88}
89
90/// One argument a protocol-v2 command accepts.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub struct Argument {
93    /// The name as it appears on the wire.
94    pub name: &'static str,
95    /// Whether a value follows.
96    pub value: Value,
97    /// The feature that must appear in the capability's advertised value
98    /// before a client is allowed to send this argument, or `None` for the
99    /// arguments every v2 client may always send.
100    pub feature: Option<&'static str>,
101}
102
103const fn plain(name: &'static str, value: Value) -> Argument {
104    Argument {
105        name,
106        value,
107        feature: None,
108    }
109}
110
111const fn gated(name: &'static str, value: Value, feature: &'static str) -> Argument {
112    Argument {
113        name,
114        value,
115        feature: Some(feature),
116    }
117}
118
119/// Every argument `command=ls-refs` accepts.
120pub const LS_REFS_ARGUMENTS: &[Argument] = &[
121    plain("symrefs", Value::None),
122    plain("peel", Value::None),
123    plain("ref-prefix", Value::Required),
124    gated("unborn", Value::None, "unborn"),
125];
126
127/// Every argument `command=fetch` accepts.
128///
129/// The four `deepen*` forms and `shallow` are all gated on the single
130/// `shallow` feature, exactly as git defines it: advertising `shallow` is a
131/// promise to accept all five, which is why they are implemented rather than
132/// rejected.
133pub const FETCH_ARGUMENTS: &[Argument] = &[
134    plain("want", Value::Required),
135    plain("have", Value::Required),
136    plain("done", Value::None),
137    plain("thin-pack", Value::None),
138    plain("no-progress", Value::None),
139    plain("include-tag", Value::None),
140    plain("ofs-delta", Value::None),
141    gated("shallow", Value::Required, "shallow"),
142    gated("deepen", Value::Required, "shallow"),
143    gated("deepen-relative", Value::None, "shallow"),
144    gated("deepen-since", Value::Required, "shallow"),
145    gated("deepen-not", Value::Required, "shallow"),
146    gated("filter", Value::Required, "filter"),
147    gated("want-ref", Value::Required, "ref-in-want"),
148    gated("wait-for-done", Value::None, "wait-for-done"),
149];
150
151/// Look an argument up by name.
152pub fn argument(table: &'static [Argument], name: &str) -> Option<&'static Argument> {
153    table.iter().find(|a| a.name == name)
154}
155
156/// The features of `table`, in first-seen order and without duplicates.
157///
158/// This is the only place an advertised feature list comes from.
159pub fn features(table: &'static [Argument]) -> Vec<&'static str> {
160    let mut out: Vec<&'static str> = Vec::new();
161    for arg in table {
162        if let Some(feature) = arg.feature {
163            if !out.contains(&feature) {
164                out.push(feature);
165            }
166        }
167    }
168    out
169}
170
171/// Render `name=<features>` for a v2 capability, or bare `name` when the
172/// command has no gated arguments at all.
173pub fn capability(name: &str, table: &'static [Argument]) -> String {
174    let features = features(table);
175    if features.is_empty() {
176        name.to_owned()
177    } else {
178        format!("{name}={}", features.join(" "))
179    }
180}
181
182/// What a client may turn off in the fetch capability.
183///
184/// `filter` is the one capability an operator plausibly wants to decline
185/// (serving a partial clone means serving arbitrary blob subsets), so it is a
186/// knob rather than a constant. Declining it removes the feature from the
187/// advertisement **and** makes the parser reject the argument, together, in
188/// [`fetch_capability`] and [`crate::upload_pack::FetchRequest::parse`].
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub struct Offered {
191    /// Whether `filter` is advertised and accepted.
192    pub filter: bool,
193}
194
195impl Default for Offered {
196    fn default() -> Self {
197        Offered { filter: true }
198    }
199}
200
201impl Offered {
202    /// Is `feature` on offer?
203    pub fn has(&self, feature: &str) -> bool {
204        match feature {
205            "filter" => self.filter,
206            _ => true,
207        }
208    }
209
210    /// May `argument` be sent by a client, given what is on offer?
211    pub fn accepts(&self, argument: &Argument) -> bool {
212        argument.feature.is_none_or(|f| self.has(f))
213    }
214}
215
216// ════════════════════════════════════════════════════════════════════════════
217// The advertisement — ONE table, all three surfaces
218// ════════════════════════════════════════════════════════════════════════════
219
220/// Where the code that honours a capability lives.
221///
222/// Every entry in every advertisement table carries one of these, and
223/// `tests/advertisement.rs` reads them: the named file, **with its comments
224/// stripped**, must contain the named code. Comments are stripped because
225/// `contains("push-options")` is satisfied by the paragraph explaining
226/// push-options two lines above the call — a guard that a doc comment can
227/// satisfy is a guard that survives the deletion of the thing it guards.
228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
229pub enum Honoured {
230    /// Read by code in `file` containing the substring `code`.
231    ///
232    /// `file` is relative to the workspace root.
233    By {
234        /// Workspace-relative path.
235        file: &'static str,
236        /// A substring of the line that reads it, e.g. `peer.has("atomic")`.
237        code: &'static str,
238    },
239    /// Read by a public item of a crate gunnar **depends on**, not by a file in
240    /// this tree.
241    ///
242    /// This variant exists because the other one could not tell the truth here.
243    /// `ofs-delta`'s obligation is discharged by `gunnar-pack`, which lived at
244    /// `../edda/crates/gunnar-pack` and was cited as a workspace-relative PATH —
245    /// a path that only resolves on a machine with an edda checkout beside
246    /// gunnar. From a fresh clone (and, since 2026-09-09, from every clone, since
247    /// the crate is a crates.io dependency) the citation named a file that is not
248    /// there, and the guard failed for the absence of a sibling rather than for
249    /// anything about gunnar.
250    ///
251    /// A path was the wrong shape for the claim anyway. What is being asserted is
252    /// that a named ITEM exists in a named CRATE, and the compiler can assert
253    /// that exactly — `advertisement.rs` carries a `use` of every item cited this
254    /// way, so the guard is a build error rather than a substring search, and it
255    /// holds whether the crate resolves from the registry or from a patched
256    /// sibling checkout.
257    ByDependency {
258        /// The crate as cargo names it, e.g. `gunnar-pack`.
259        krate: &'static str,
260        /// The public item that does the work, e.g. `index_thin_pack`.
261        item: &'static str,
262    },
263    /// There is nothing to do, and here is the argument for why.
264    ///
265    /// The reason is a sentence, not a marker: this variant is the escape hatch
266    /// and it has to cost something to use. Today exactly three capabilities
267    /// use it, and each says what makes it vacuous rather than unimplemented.
268    Vacuously(&'static str),
269}
270
271/// What follows a capability's name on the wire.
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub enum CapValue {
274    /// Nothing: the name alone, `atomic`.
275    Bare,
276    /// `=sha1` / `=sha256`, from the repository's hash.
277    ObjectFormat,
278    /// `=gunnar/1.1.0`, from the caller's agent string.
279    Agent,
280    /// `=<features>`, generated from a v2 argument table by [`features`].
281    ///
282    /// A bare name when the table gates nothing, which is what
283    /// [`capability`] already does.
284    Features(&'static [Argument]),
285}
286
287/// One capability gunnar advertises, and the thing that honours it.
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub struct Capability {
290    /// The name as it appears on the wire, without any `=value`.
291    pub name: &'static str,
292    /// What follows the name.
293    pub value: CapValue,
294    /// The [`Offered`] knob that can withdraw this capability, if any.
295    ///
296    /// `None` means it is always advertised. `Some(feature)` means it appears
297    /// only when [`Offered::has`] says so — and the parser must refuse the
298    /// argument in the same breath, which is what `Offered` exists to make
299    /// impossible to get wrong.
300    pub offered: Option<&'static str>,
301    /// Where it is honoured.
302    pub honoured: Honoured,
303    /// The [`WantPolicy`] this row is a promise about, if any.
304    ///
305    /// `None` for every capability whose truth does not depend on what a
306    /// client is allowed to `want` — which is all of them but the two
307    /// `allow-*-sha1-in-want` rows.
308    ///
309    /// This exists because the drift `Honoured` catches runs one way only. A
310    /// row honoured by nothing is caught by the guard; a **policy honoured by
311    /// no row** is not, because there is no row to look at. `WantPolicy` was
312    /// exactly that: enforced by `check_wants` on every request and named in no
313    /// advertisement, so a stock client refused the request on its own side and
314    /// the server never heard it. See [`WantPolicy::advertises`].
315    pub requires: Option<crate::upload_pack::WantPolicy>,
316}
317
318const fn cap(name: &'static str, code: &'static str, file: &'static str) -> Capability {
319    Capability {
320        name,
321        value: CapValue::Bare,
322        offered: None,
323        honoured: Honoured::By { file, code },
324        requires: None,
325    }
326}
327
328/// The file both push-side capability readers live in.
329const RECEIVE: &str = "crates/gunnar-wire/src/receive_pack.rs";
330/// The file the fetch-side capability readers live in.
331const UPLOAD: &str = "crates/gunnar-wire/src/upload_pack.rs";
332
333/// `agent=`, which is the same row on all three surfaces.
334const AGENT: Capability = Capability {
335    name: "agent",
336    value: CapValue::Agent,
337    offered: None,
338    honoured: Honoured::Vacuously(
339        "an identifier for the peer's logs. There is no behaviour attached to \
340         it at either end; git itself only records it.",
341    ),
342    requires: None,
343};
344
345/// `object-format=`, which is the same row on all three surfaces.
346const OBJECT_FORMAT: Capability = Capability {
347    name: "object-format",
348    value: CapValue::ObjectFormat,
349    offered: None,
350    honoured: Honoured::By {
351        file: "crates/gunnar-wire/src/caps.rs",
352        code: "pub fn check_object_format",
353    },
354    requires: None,
355};
356
357/// Every capability `git-upload-pack` advertises in **protocol v0**.
358///
359/// Plain `multi_ack` is deliberately absent: it is an ACK mode with its own
360/// semantics that nothing here implements, and advertising a negotiation richer
361/// than the one implemented is the same class of bug this module exists to
362/// prevent. It is absent by *not being in this table*, which is now the only
363/// way to be absent.
364///
365/// `multi_ack_detailed` and `no-done` **are** here, and the comment on the first
366/// row says why: without them stock git negotiates in single-ACK, which has no
367/// correct answer over stateless-rpc and cannot finish a fetch over smart HTTP.
368pub const UPLOAD_PACK_V0: &[Capability] = &[
369    // ── the ACK mode, and why these two are not optional ────────────────────
370    //
371    // This table used to carry neither, on the reasoning that gunnar negotiated
372    // in single-ACK mode and that advertising a richer ACK protocol than the
373    // one implemented is the bug this module exists to prevent. The reasoning
374    // was sound and the conclusion was wrong, and stock git rather than an
375    // argument is what decided it.
376    //
377    // A v0 client picks its ACK mode from what the server offers. Offered
378    // neither, git 2.53.0 falls back to single-ACK, in which a bare
379    // `ACK <oid>` is TERMINAL: it means "negotiation is over, a packfile
380    // follows". Over a CONNECTED session that can be served correctly, and
381    // `b9fee55` did exactly that — git's rule is on `have_obj.nr`, so nothing
382    // more goes out once the ACK has, and the surplus `NAK` that used to sit in
383    // the pipe is gone. That fix is real and the `else` arm in
384    // `serve_v0_session` still carries it.
385    //
386    // Over **stateless-rpc there is no correct answer at all**, which is the
387    // part a connected fix cannot reach. The round ends with the HTTP response,
388    // so the client takes the terminal `ACK`, opens a FRESH `POST` carrying
389    // `want` and `done` and no `have`s, and reads that response as a raw
390    // sideband packfile — while the server, seeing a request with no commons,
391    // correctly opens it with `NAK`. There is nothing else it could send: the
392    // request genuinely has no common `have` in it. git demuxes the `N` as a
393    // band number and dies with `fetch-pack: protocol error: bad band #78`.
394    //
395    // MEASURED 2026-08-05, git 2.53.0, a corpus of 12 pushes cut back a
396    // third: `git fetch http://…` exited **128 against `b9fee55` itself**, on
397    // both sha1 and sha256, and 0 against `git http-backend` on the identical
398    // repository. The advertisements differed in these two names and in nothing
399    // else that changes the client's behaviour. That is why the mode is now
400    // implemented rather than declined — not because the earlier fix was wrong.
401    //
402    // `no-done` is what stateless-rpc is really after: it lets the server send
403    // `ACK <oid> ready`, the terminal `ACK` and the packfile in ONE response
404    // rather than making the client spend a second HTTP request to say `done`.
405    //
406    // Plain `multi_ack` is still absent, and deliberately: it is a third ACK
407    // mode with its own semantics that nothing here implements, so it is not
408    // advertised. A client too old to know `multi_ack_detailed` gets
409    // single-ACK, which is correct on the connected sessions it can reach.
410    cap(
411        "multi_ack_detailed",
412        r#"peer.has("multi_ack_detailed")"#,
413        UPLOAD,
414    ),
415    cap("no-done", r#"peer.has("no-done")"#, UPLOAD),
416    cap("side-band-64k", r#"peer.has("side-band-64k")"#, UPLOAD),
417    // The **v0** reader, not the v2 argument arm. This row cited
418    // `"thin-pack" => out.thin_pack = true`, which is the v2 parser, while v0
419    // read the capability nowhere at all — so every v0 fetch was served as a
420    // whole pack against an advertisement promising otherwise (found and fixed
421    // in `222f7b2`: 1.343x the bytes on a real incremental). A v0 row must cite
422    // a v0 consumer, or the guard is satisfied by the other protocol's code.
423    cap("thin-pack", r#"peer.has("thin-pack")"#, UPLOAD),
424    cap("ofs-delta", r#"peer.has("ofs-delta")"#, UPLOAD),
425    cap("no-progress", r#"peer.has("no-progress")"#, UPLOAD),
426    cap("include-tag", r#"peer.has("include-tag")"#, UPLOAD),
427    // Again the **v0** arms (`parse_v0_shallow_line`), not the v2 ones. Both
428    // exist and both are real, but a v0 row citing the v2 parser would stay
429    // green if the v0 half were deleted — which is exactly what happened to
430    // `thin-pack` above.
431    cap("shallow", r#""shallow" => request"#, UPLOAD),
432    cap("deepen-since", "request.shallow.since =", UPLOAD),
433    cap("deepen-not", r#""deepen-not" => request"#, UPLOAD),
434    cap(
435        "deepen-relative",
436        r#""deepen-relative" => request.shallow.relative = true"#,
437        UPLOAD,
438    ),
439    Capability {
440        name: "filter",
441        value: CapValue::Bare,
442        // The one capability an operator plausibly declines. Withdrawing it
443        // removes it from HERE and makes the parser refuse the argument, in
444        // one place, which is what `Offered` is for.
445        offered: Some("filter"),
446        honoured: Honoured::By {
447            file: UPLOAD,
448            code: r#""filter" => out.filter"#,
449        },
450        requires: None,
451    },
452    // ── the two rows that were missing, and the failure they hid ────────────
453    //
454    // `check_wants` has always enforced a `WantPolicy`, and the v0
455    // advertisement said nothing about it. `fetch-pack.c` will not send a
456    // `want` for an unadvertised object unless one of these two names was in
457    // the advertisement, so the request was refused **client-side** — no
458    // server error, no log line, nothing to notice. That is the inverted form
459    // of the drift the rest of this table catches: not a promise nothing keeps,
460    // but something kept that was never promised.
461    //
462    // MEASURED 2026-08-05, stock git 2.53.0 over `ext::`, one commit two
463    // steps behind `main`'s tip:
464    //
465    // | request | v0 | v2 |
466    // |---|---|---|
467    // | `fetch <oid>` of a reachable non-tip commit | `Server does not allow request for unadvertised object` | 6 objects, OK |
468    // | `clone --filter=blob:none`, then check out | **4 refusals, checkout failed** | OK |
469    //
470    // The second row is the one that matters: a partial clone fetches its blobs
471    // back by bare oid. v2 has no such capability at all (`upload_pack_v2` sets
472    // `ALLOW_ANY_SHA1` unconditionally), which is why every v2 arm was green
473    // while every v0 arm was broken.
474    //
475    // Both are honoured by `check_wants`, and deliberately by the *same* line:
476    // there is one policy decision, not two, and a row citing a second site
477    // would go green on code that agreed with it by accident.
478    Capability {
479        name: "allow-reachable-sha1-in-want",
480        value: CapValue::Bare,
481        offered: None,
482        honoured: Honoured::By {
483            file: UPLOAD,
484            code: "fn check_wants",
485        },
486        requires: Some(crate::upload_pack::WantPolicy::ReachableFromRefs),
487    },
488    Capability {
489        name: "allow-tip-sha1-in-want",
490        value: CapValue::Bare,
491        offered: None,
492        honoured: Honoured::By {
493            file: UPLOAD,
494            code: "fn check_wants",
495        },
496        // git sets `ALLOW_TIP_SHA1` on its own or as part of `ALLOW_ANY_SHA1`,
497        // and gunnar has no separate "tips only, plus hidden ones" policy —
498        // `AdvertisedTips` already serves every tip it advertises, so the
499        // capability would say nothing. Only `Any` is a promise beyond
500        // reachability.
501        requires: Some(crate::upload_pack::WantPolicy::Any),
502    },
503    OBJECT_FORMAT,
504    AGENT,
505];
506
507/// Every capability `git-receive-pack` advertises. Push has only v0.
508pub const RECEIVE_PACK: &[Capability] = &[
509    cap("report-status", r#"peer.has("report-status")"#, RECEIVE),
510    cap(
511        "report-status-v2",
512        r#"peer.has("report-status-v2")"#,
513        RECEIVE,
514    ),
515    Capability {
516        name: "delete-refs",
517        value: CapValue::Bare,
518        offered: None,
519        // Not `peer.has("delete-refs")`, and that is correct rather than a
520        // gap: the capability tells the CLIENT it may send a delete command,
521        // and the server's obligation is to carry one out. The code that does
522        // is the honouring.
523        honoured: Honoured::By {
524            file: RECEIVE,
525            code: "if command.is_delete()",
526        },
527        requires: None,
528    },
529    cap("side-band-64k", r#"peer.has("side-band-64k")"#, RECEIVE),
530    Capability {
531        name: "quiet",
532        value: CapValue::Bare,
533        offered: None,
534        honoured: Honoured::Vacuously(
535            "`quiet` asks receive-pack to suppress its progress reporting. \
536             gunnar's receive-pack emits no progress on that connection at \
537             all, so there is nothing to suppress and nothing to read the \
538             capability for. Vacuously honoured, and recorded as such rather \
539             than counted as a reader.",
540        ),
541        requires: None,
542    },
543    cap("atomic", r#"peer.has("atomic")"#, RECEIVE),
544    Capability {
545        name: "ofs-delta",
546        value: CapValue::Bare,
547        offered: None,
548        // The push side is the RECEIVER of ofs-deltas: advertising it tells
549        // the client it may send them, and the obligation is to RESOLVE them.
550        // There is no `peer.has("ofs-delta")` on this surface and there should
551        // not be one — the consumer is the indexer that completes the chains.
552        honoured: Honoured::ByDependency {
553            krate: "gunnar-pack",
554            item: "index_thin_pack",
555        },
556        requires: None,
557    },
558    cap("push-options", r#"peer.has("push-options")"#, RECEIVE),
559    OBJECT_FORMAT,
560    AGENT,
561];
562
563/// Every capability the **protocol v2** advertisement carries.
564///
565/// `ls-refs` and `fetch` carry generated feature lists; the others are their
566/// own row. This is what `UploadPack::write_capability_advertisement` writes,
567/// rather than a fourth hand-written list beside the table — which is what it
568/// was until 2026-08-05, in a different file from the two above.
569pub const UPLOAD_PACK_V2: &[Capability] = &[
570    AGENT,
571    Capability {
572        name: "ls-refs",
573        value: CapValue::Features(LS_REFS_ARGUMENTS),
574        offered: None,
575        honoured: Honoured::By {
576            file: UPLOAD,
577            code: "impl LsRefsRequest",
578        },
579        requires: None,
580    },
581    Capability {
582        name: "fetch",
583        value: CapValue::Features(FETCH_ARGUMENTS),
584        offered: None,
585        honoured: Honoured::By {
586            file: UPLOAD,
587            code: "impl FetchRequest",
588        },
589        requires: None,
590    },
591    Capability {
592        name: "server-option",
593        value: CapValue::Bare,
594        offered: None,
595        honoured: Honoured::Vacuously(
596            "protocol v2 says a server SHOULD ignore server options it does \
597             not understand, and gunnar defines none. The lines are accepted \
598             into `PeerCapabilities` rather than rejected, so a client that \
599             sends one is not broken by it. This is NOT the `push-options` \
600             case: git hands push options to `pre-receive`, so discarding \
601             those was a wrong answer, while discarding server options is \
602             what the specification asks for.",
603        ),
604        requires: None,
605    },
606    OBJECT_FORMAT,
607];
608
609/// Every surface, so a guard can walk all of them without naming three
610/// constants and going stale when a fourth appears.
611pub const ADVERTISED: &[(&str, &[Capability])] = &[
612    ("upload-pack v2", UPLOAD_PACK_V2),
613    ("upload-pack v0", UPLOAD_PACK_V0),
614    ("receive-pack", RECEIVE_PACK),
615];
616
617/// Render one capability's wire spelling, or `None` if it is not on offer.
618///
619/// `want_policy` is a parameter and not a default because the advertisement
620/// genuinely depends on it, and a default would be the drift this whole table
621/// exists to prevent: the two `allow-*-sha1-in-want` rows are promises about
622/// what `check_wants` will serve, and a server that renders them from anything
623/// other than the policy it judges by is advertising a different server.
624pub fn render(
625    cap: &Capability,
626    hash_kind: Kind,
627    agent: &str,
628    offered: Offered,
629    want_policy: crate::upload_pack::WantPolicy,
630) -> Option<String> {
631    if let Some(feature) = cap.offered {
632        if !offered.has(feature) {
633            return None;
634        }
635    }
636    if let Some(required) = cap.requires {
637        if !want_policy.advertises(required) {
638            return None;
639        }
640    }
641    Some(match cap.value {
642        CapValue::Bare => cap.name.to_owned(),
643        CapValue::ObjectFormat => format!("{}={}", cap.name, object_format_name(hash_kind)),
644        CapValue::Agent => format!("{}={agent}", cap.name),
645        CapValue::Features(table) => {
646            // `Offered` also gates individual v2 features, so this is the same
647            // filter `fetch_capability` applies — one writer, not two.
648            let features: Vec<&str> = features(table)
649                .into_iter()
650                .filter(|f| offered.has(f))
651                .collect();
652            if features.is_empty() {
653                cap.name.to_owned()
654            } else {
655                format!("{}={}", cap.name, features.join(" "))
656            }
657        }
658    })
659}
660
661/// The wire lines for a whole surface, in table order.
662///
663/// **This is the only thing that decides what gunnar advertises.** Before
664/// 2026-08-05 the v2 list was generated from the argument table while v0 and
665/// receive-pack were hand-written `vec![]`s in this file and the v2 capability
666/// names were a fourth hand-written list in `upload_pack.rs` — so
667/// `push-options` was a bare string literal that nothing else in the tree had
668/// to agree with, and it was advertised, parsed and discarded for the whole of
669/// v1. An early audit claimed that *"advertised but
670/// not honoured is not something this codebase can express"*; that was true of
671/// the v2 arguments and false of the other three lists. Now it is true of all
672/// of them, because there is nowhere else to write one down.
673pub fn advertise(
674    table: &'static [Capability],
675    hash_kind: Kind,
676    agent: &str,
677    offered: Offered,
678    want_policy: crate::upload_pack::WantPolicy,
679) -> Vec<String> {
680    table
681        .iter()
682        .filter_map(|cap| render(cap, hash_kind, agent, offered, want_policy))
683        .collect()
684}
685
686/// The `fetch=…` capability line for what is on offer.
687pub fn fetch_capability(offered: Offered) -> String {
688    let features: Vec<&str> = features(FETCH_ARGUMENTS)
689        .into_iter()
690        .filter(|f| offered.has(f))
691        .collect();
692    if features.is_empty() {
693        "fetch".to_owned()
694    } else {
695        format!("fetch={}", features.join(" "))
696    }
697}
698
699/// The `ls-refs=…` capability line.
700pub fn ls_refs_capability() -> String {
701    capability("ls-refs", LS_REFS_ARGUMENTS)
702}
703
704/// The capabilities `git-upload-pack` advertises in **protocol v0**, where
705/// they ride on the first reference line rather than in their own section.
706///
707/// `multi_ack` and `multi_ack_detailed` are deliberately absent: gunnar
708/// negotiates in single-ACK mode, which every git since 2005 still speaks, and
709/// advertising a richer ACK protocol than the one implemented is the same
710/// class of bug this module exists to prevent.
711pub fn upload_pack_v0_capabilities(
712    hash_kind: Kind,
713    agent: &str,
714    offered: Offered,
715    want_policy: crate::upload_pack::WantPolicy,
716) -> Vec<String> {
717    advertise(UPLOAD_PACK_V0, hash_kind, agent, offered, want_policy)
718}
719
720/// The capabilities `git-receive-pack` advertises.
721pub fn receive_pack_capabilities(hash_kind: Kind, agent: &str) -> Vec<String> {
722    // `WantPolicy` decides what a client may *fetch*; push has no `want` at
723    // all, so no row in `RECEIVE_PACK` carries a `requires` and the value here
724    // cannot change a byte. Passed as the default rather than given its own
725    // parameter, because a knob that cannot move is one more thing to keep
726    // agreeing about.
727    advertise(
728        RECEIVE_PACK,
729        hash_kind,
730        agent,
731        Offered::default(),
732        crate::upload_pack::WantPolicy::default(),
733    )
734}
735
736/// The capability set a v0 peer sent on its first line, parsed.
737///
738/// Values are kept as `Option<String>` so `object-format=sha256` and a bare
739/// `atomic` are the same shape.
740#[derive(Debug, Clone, Default, PartialEq, Eq)]
741pub struct PeerCapabilities {
742    entries: Vec<(String, Option<String>)>,
743}
744
745impl PeerCapabilities {
746    /// Parse a space-separated capability string.
747    ///
748    /// Leading and repeated spaces are tolerated: git's own `receive-pack`
749    /// client emits `…\0 report-status-v2 …` with a leading space, which a
750    /// naive `split(' ')` turns into a phantom empty capability.
751    pub fn parse(text: &str) -> Self {
752        let entries = text
753            .split(' ')
754            .filter(|s| !s.is_empty())
755            .map(|item| match item.split_once('=') {
756                Some((k, v)) => (k.to_owned(), Some(v.to_owned())),
757                None => (item.to_owned(), None),
758            })
759            .collect();
760        PeerCapabilities { entries }
761    }
762
763    /// Is this capability present, with or without a value?
764    pub fn has(&self, name: &str) -> bool {
765        self.entries.iter().any(|(k, _)| k == name)
766    }
767
768    /// The value of `name=<value>`, if it was sent with one.
769    pub fn value(&self, name: &str) -> Option<&str> {
770        self.entries
771            .iter()
772            .find(|(k, _)| k == name)
773            .and_then(|(_, v)| v.as_deref())
774    }
775
776    /// Every capability name, in the order sent.
777    pub fn names(&self) -> impl Iterator<Item = &str> {
778        self.entries.iter().map(|(k, _)| k.as_str())
779    }
780}
781
782/// Check a peer's `object-format` against the repository's actual hash kind.
783///
784/// The whole point of object-format negotiation: answering `sha1` to a sha256 repository does not
785/// fail, it returns an *empty* response, so the mismatch has to be caught here
786/// and turned into an error.
787pub fn check_object_format(ours: Kind, theirs: Option<&str>) -> crate::Result<()> {
788    let Some(theirs) = theirs else {
789        return Ok(());
790    };
791    if object_format_from_name(theirs) == Some(ours) {
792        Ok(())
793    } else {
794        Err(crate::Error::ObjectFormatMismatch {
795            ours: object_format_name(ours),
796            theirs: theirs.to_owned(),
797        })
798    }
799}
800
801// ════════════════════════════════════════════════════════════════════════════
802// The census: every serving-side policy, and what on the wire declares it
803// ════════════════════════════════════════════════════════════════════════════
804//
805// # Why a second table
806//
807// [`ADVERTISED`] answers *"does everything gunnar promises have a consumer?"*.
808// It cannot answer the inverse — *"does everything gunnar enforces have a
809// promise?"* — because the inverse has nothing to walk. A row nothing reads is
810// visible; **a policy no row names** is not there at all.
811//
812// That inverse has produced four wrong answers in this tree in a single day,
813// and the sharpest of them, `WantPolicy` (`8f4e6e0`), was invisible in the most
814// complete way available: `check_wants` enforced it on every request, no
815// capability named it, so stock git refused the `want` on its **own** side and
816// gunnar never received the request. No error, no log line, no failing test —
817// only a user whose partial clone could not check out.
818//
819// So every field of every serving-side `Config`, plus every field of
820// [`Offered`], is listed here with a verdict, and
821// `tests/advertisement.rs::every_serving_policy_is_declared_somewhere` reads the
822// **struct definitions out of the source** and refuses to pass while one of
823// them is missing from this list. Adding a knob that changes what a client gets
824// is therefore not something you can forget to classify; it is something that
825// does not compile past the test suite.
826
827/// How a serving-side policy reaches the peer.
828///
829/// The three arms are not degrees of quality — they are three different
830/// contracts, and picking the wrong one is the defect. `WantPolicy` was
831/// implicitly treated as [`Self::Refuses`] and was in fact silent: the refusal
832/// happened inside the *client*, which is the one place a server's error can
833/// never reach.
834#[derive(Debug, Clone, Copy, PartialEq, Eq)]
835pub enum Declared {
836    /// Named on the wire as this capability, so a peer can see it **before it
837    /// asks** and shape its request around it.
838    ///
839    /// Required whenever the peer's behaviour depends on knowing: git's client
840    /// will not send `filter`, `thin-pack` or a `want` for an unadvertised
841    /// object unless the corresponding capability was advertised.
842    As(&'static str),
843    /// Not on the wire, and it does not have to be, because when it applies the
844    /// peer gets an **error that says so**.
845    ///
846    /// This arm is a claim about something arriving, so it carries the tests
847    /// that watched it arrive. "It refuses" is only a safe answer if the
848    /// refusal is observable at the far end; a limit that silently truncates a
849    /// pack, or that is enforced inside the client, is not this arm.
850    Refuses {
851        /// `<workspace-relative file>::<test fn>`, one or more, each of which
852        /// asserts the peer sees the refusal. Checked to exist.
853        seen_by: &'static [&'static str],
854        /// What the peer actually sees.
855        reason: &'static str,
856    },
857    /// The peer gets an error that says so — and **nothing in this repository has
858    /// watched it arrive**.
859    ///
860    /// Split out of [`Refuses`](Self::Refuses) on 2026-09-09, because `limits` was
861    /// using that arm while citing three tests at
862    /// `../edda/crates/storage-git-gix/parked-gix-2/gunnar-wire-gix/tests/fetch_memory.rs`.
863    /// Two things were wrong with that and only one of them was the sibling path:
864    /// `parked-gix-2` is quarantined salvage, named by neither edda's `include`
865    /// list nor any published tarball, so the citation resolved on exactly one
866    /// machine and nowhere else. The guard "checks the citation exists", and what
867    /// it was checking was one developer's disk.
868    ///
869    /// So the uncovered case gets its own name instead of borrowing the covered
870    /// one's. The reason must say what the peer sees AND what would cover it —
871    /// this arm is an admission, and an admission that does not name its way out
872    /// becomes furniture.
873    RefusesUncovered(&'static str),
874    /// Nothing a peer can observe, and here is the argument for why.
875    ///
876    /// The escape hatch, and it has to cost a sentence — the same rule
877    /// [`Honoured::Vacuously`] carries, for the same reason.
878    Invisible(&'static str),
879}
880
881/// One field of a serving-side configuration struct, and its verdict.
882#[derive(Debug, Clone, Copy, PartialEq, Eq)]
883pub struct Policy {
884    /// The field's name, exactly as the struct spells it.
885    pub field: &'static str,
886    /// How it reaches the peer.
887    pub declared: Declared,
888}
889
890/// A struct whose fields are serving-side policy, with a verdict on every one.
891#[derive(Debug, Clone, Copy, PartialEq, Eq)]
892pub struct PolicySurface {
893    /// The surface's name, for a failure message.
894    pub surface: &'static str,
895    /// Workspace-relative path to the file the struct is written in.
896    pub file: &'static str,
897    /// The struct's opening line, verbatim, so the guard can find it.
898    pub declaration: &'static str,
899    /// Every field, in any order. The guard asserts this set equals the set in
900    /// the source — in **both** directions, so a stale entry fails too.
901    pub fields: &'static [Policy],
902}
903
904/// Every configuration surface that decides what a peer gets.
905pub const SERVER_POLICIES: &[PolicySurface] = &[
906    PolicySurface {
907        surface: "upload-pack",
908        file: "crates/gunnar-wire/src/upload_pack.rs",
909        declaration: "pub struct Config {",
910        fields: &[
911            Policy {
912                field: "agent",
913                declared: Declared::As("agent"),
914            },
915            Policy {
916                field: "offered",
917                // The struct is one field wide and that field is `filter`;
918                // `Offered` has its own row below, so this is not the place the
919                // claim is checked.
920                declared: Declared::As("filter"),
921            },
922            Policy {
923                field: "want_policy",
924                // The defect of 2026-08-05. Before `8f4e6e0` this was enforced
925                // by `check_wants` and named by nothing, and the failure landed
926                // inside the client where no server error could reach.
927                declared: Declared::As("allow-reachable-sha1-in-want"),
928            },
929            Policy {
930                field: "budget",
931                declared: Declared::Refuses {
932                    seen_by: &["crates/gunnar-cli/tests/wire_config.rs::\
933                         a_traversal_budget_of_one_refuses_a_clone_rather_than_truncating_it"],
934                    reason: "the walk stops at the ceiling and the request is REFUSED, so the \
935                             client's `git clone` fails with the server's message. A budget \
936                             that truncated the pack instead would be a wrong answer and would \
937                             belong in no arm of this enum — which is why the test asserts the \
938                             clone failed AND that no repository was left behind, rather than \
939                             asserting an exit code.",
940                },
941            },
942            Policy {
943                field: "limits",
944                declared: Declared::RefusesUncovered(
945                    "UNCOVERED HERE, and the arm now says so rather than citing a path. All \
946                     three ceilings raise a named error — `ObjectTooLarge`, `RequestTooLarge`, \
947                     `WalkTooLarge` — that travels to the client as an `ERR` pkt-line or on \
948                     band 3, and an object over the ceiling is REFUSED and not skipped, \
949                     because a pack whose closure does not hold is a corrupt clone rather \
950                     than a refused one; `limits.rs` argues that at length. The tests that \
951                     watched two of the three arrive \
952                     (`a_blob_over_the_ceiling_is_refused_by_name`, \
953                     `a_v0_have_flood_is_refused_at_the_ceiling`, \
954                     `a_v2_argument_flood_is_refused_at_the_ceiling`) are PARKED in edda's \
955                     `storage-git-gix/parked-gix-2/` — quarantined salvage, in no published \
956                     tarball and in no clone of this repository — because their fixture \
957                     opened an FsStore and the packfile engine is amputated. THE WAY OUT is \
958                     a MemStore fixture, which is gix-free and already in gunnar-store: port \
959                     the three tests onto it, here, and this field goes back to `Refuses` \
960                     with citations that resolve for everyone. The third ceiling, \
961                     `walk_bytes`, IS covered — `walk_limit.rs` reads the sentence off the \
962                     wire — and is a separate field for that reason.",
963                ),
964            },
965            Policy {
966                field: "walk_pool",
967                declared: Declared::Refuses {
968                    seen_by: &["crates/gunnar-wire/tests/walk_limit.rs::\
969                         a_full_pool_is_a_different_sentence_from_a_request_that_will_never_fit"],
970                    reason: "the server-wide memory ceiling, and the one policy here whose \
971                             answer depends on what OTHER clients are doing. It refuses with \
972                             `WalkPoolFull`, which is deliberately a different sentence from \
973                             `WalkTooLarge`: this one says the machine is busy and a retry will \
974                             work, and the other says the request will never fit. A client that \
975                             cannot tell them apart retries the first forever and gives up on \
976                             the second. Nothing is advertised, because nothing a client could \
977                             be told before it asks would still be true when it did — the \
978                             answer is a property of the moment.",
979                },
980            },
981        ],
982    },
983    PolicySurface {
984        surface: "receive-pack",
985        file: "crates/gunnar-wire/src/receive_pack.rs",
986        declaration: "pub struct Config {",
987        fields: &[
988            Policy {
989                field: "agent",
990                declared: Declared::As("agent"),
991            },
992            Policy {
993                field: "budget",
994                declared: Declared::Refuses {
995                    seen_by: &[
996                        "crates/gunnar-wire/tests/protocol.rs::\
997                         the_connectivity_budget_refuses_a_push_rather_than_accepting_it_unchecked",
998                        "crates/gunnar-wire/tests/protocol.rs::\
999                         a_mixed_push_refuses_only_the_reference_that_does_not_close",
1000                    ],
1001                    reason: "the connectivity walk's ceiling. Exceeding it, like failing the \
1002                             walk itself, turns into a per-reference `RefStatus::Rejected` \
1003                             carrying the reason, which the status report puts in front of \
1004                             `git push`, and the reference does not move. The first test sets \
1005                             the budget to 1 over six unreachable commits and reads the status \
1006                             report; the second is what says the refusal is per reference and \
1007                             not per push. The first was written for this entry: until then \
1008                             the only citation available proved the reporting mechanism and \
1009                             never set a budget, which is a claim standing next to its \
1010                             evidence rather than on it.",
1011                },
1012            },
1013            Policy {
1014                field: "pack_ceiling",
1015                declared: Declared::Refuses {
1016                    seen_by: &[
1017                        "crates/gunnar-wire/tests/pack_ceiling.rs::\
1018                         a_push_over_its_ceiling_is_cut_mid_transfer",
1019                        "crates/gunnar-wire/tests/pack_ceiling.rs::\
1020                         a_push_of_exactly_the_ceiling_lands",
1021                        "crates/gunnar-server/tests/pack_ceiling_store.rs::\
1022                         a_cut_push_stores_nothing_and_leaves_the_repository_usable",
1023                        "crates/gunnar-wire/tests/concurrent_pack_ceiling.rs::\
1024                         simultaneous_pushes_are_not_each_admitted_against_the_same_measurement",
1025                    ],
1026                    reason: "the byte ceiling a push is held to WHILE it arrives, and the one \
1027                             policy here that a client cannot be told before it asks — because \
1028                             the thing it bounds is not knowable before it asks. A pack header \
1029                             carries an object count, not a byte count, so neither side knows \
1030                             the size of a push at negotiation time; there is no number to put \
1031                             in a capability and nothing a client could do differently if there \
1032                             were. So it refuses, and the refusal is the whole surface: the \
1033                             read is cut one byte past the ceiling, `unpack <reason>` carries \
1034                             the setter's own sentence (which names the ceiling and why \
1035                             — never the indexer's opinion of a truncated stream), \
1036                             and every reference is reported `ng`. The first citation is the \
1037                             one that matters and it asserts BYTES, not a verdict: a server \
1038                             that read the whole 400 GiB and then refused would satisfy any \
1039                             assertion about the report and is a different bug. The second is \
1040                             the boundary — a push of exactly the ceiling LANDS — and the \
1041                             third is the same cut against the real znippy engine, which is \
1042                             where `nothing was stored` costs something to be true. The \
1043                             fourth is the number's OTHER half, added 2026-09-08: the \
1044                             ceiling is one namespace's room and not one connection's, so \
1045                             eight pushes that measured it together spend it once between \
1046                             them (`PackCeiling::ledger`). Without it three green citations \
1047                             stood over a limit N simultaneous pushes could spend N times.",
1048                },
1049            },
1050            Policy {
1051                field: "notice",
1052                declared: Declared::Invisible(
1053                    "It is not a policy: the push it rides on is ALLOWED. `notice` is one \
1054                     human-readable line put on the progress band (`remote: …`) beside a \
1055                     report that is otherwise byte-for-byte what it would have been — the \
1056                     metered appliance's `plan expired <date>; renew at <url>` for a tenant in \
1057                     Grace. Nothing about the request has to be shaped around knowing it, so \
1058                     `As` would be a capability no client would read; nothing is refused, so \
1059                     `Refuses` would have no arrival to cite. The three things that make \
1060                     `Invisible` the honest arm rather than the convenient one, all readable \
1061                     at `receive_pack.rs:1445-1455`: it is sent ONLY inside the `if sideband` \
1062                     arm, so a client that negotiated no sideband gets the bare report and \
1063                     never a line where the report should be; it is framed separately on band \
1064                     2, so a client that ignores band 2 parses the report untouched; and it is \
1065                     written BEFORE the report on band 1, which is presentation order for a \
1066                     person and nothing a parser depends on. Its absence is exactly the \
1067                     behaviour that shipped before it existed. If it ever gates, blocks or \
1068                     shortens a push, it stops being this arm.",
1069                ),
1070            },
1071        ],
1072    },
1073    PolicySurface {
1074        surface: "what is on offer",
1075        file: "crates/gunnar-wire/src/caps.rs",
1076        declaration: "pub struct Offered {",
1077        fields: &[Policy {
1078            field: "filter",
1079            declared: Declared::As("filter"),
1080        }],
1081    },
1082];