Skip to main content

release_kit/
projection.rs

1//! The one pure target-specific projection over this binary's embedded
2//! sources.
3//!
4//! [`Projection::compute`] takes a [`ProjectionInput`], values alone, and
5//! answers the complete candidate artifact tree this installed binary
6//! would land in one target: every destination with its ownership
7//! [`Kind`], its [`Placement`], the complete proposed bytes, the rendered
8//! region where the destination is a marked region, and the embedded
9//! source paths it was rendered from. Staging and production landing
10//! share it byte for byte, so what an agent studies in a stage is what a
11//! landing writes.
12//!
13//! This module reads snippets and blocks through `src/embedded.rs`
14//! directly and reads nothing else: no target file, no environment, no
15//! Git state, no clock, no registry, no network. Whatever a projection
16//! needs from the target arrives as [`TargetEvidence`], gathered before
17//! construction by [`evidence::gather`], which lives in its own file so a
18//! source scan can hold this one to the pure boundary.
19//!
20//! Every pure piece of the landing model has one implementation here: the
21//! kind table, the token substitution, the block templating, the splice
22//! and marker judgments, and the Nix crate-shape judgment. Which embedded
23//! source belongs to which capability, and whether a capability is
24//! available at the target's dimensions, is the catalog's answer in
25//! `crate::profile::catalog`, and this module renders what the catalog
26//! selects. `src/landing.rs` re-exports the pieces under their old names.
27//!
28//! One input type, one compute function, one candidate shape: staging and
29//! every landing verb consume this one projection.
30
31pub mod evidence;
32
33use std::collections::BTreeMap;
34
35use serde::{Deserialize, Serialize};
36
37use crate::embedded;
38use crate::error::RkError;
39pub use crate::landing::manifest::Provider;
40use crate::landing::{CheckoutMode, Integration, Params};
41use crate::profile::ReleaseMode;
42use crate::profile::catalog::{self, Availability, Selection, Status};
43
44/// The complete input to one projection: the resolved landing parameters
45/// and the typed evidence read from the target beforehand.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct ProjectionInput {
48    /// The resolved landing parameters.
49    pub params: Params,
50    /// What the target already holds, as values.
51    pub evidence: TargetEvidence,
52}
53
54/// What a projection needs to know about the target, gathered before the
55/// projection runs and carried as values.
56#[derive(Debug, Clone, PartialEq, Eq, Default)]
57#[allow(
58    clippy::struct_excessive_bools,
59    reason = "each field is one independent fact read off the target, not a state a smaller type could carry"
60)]
61pub struct TargetEvidence {
62    /// The complete existing document at each block destination that
63    /// exists on disk, keyed by destination. An absent key is an absent
64    /// file.
65    pub documents: BTreeMap<String, Vec<u8>>,
66    /// The crate facts the Nix seed relies on.
67    pub crate_shape: CrateShape,
68    /// Whether `flake.nix` is present at the target, a link included.
69    pub flake_nix_present: bool,
70    /// Whether `flake.lock` is present at the target, a link included.
71    pub flake_lock_present: bool,
72    /// Whether the receipt already records `flake.nix`: a pair release-kit
73    /// landed is its own and is never withheld.
74    pub flake_recorded: bool,
75    /// Whether `.gitlab-ci.yml` is present at the target, a link included.
76    pub root_pipeline_present: bool,
77    /// Whether the receipt already records `.gitlab-ci.yml`: a root
78    /// pipeline release-kit landed is its own and is never withheld.
79    pub root_pipeline_recorded: bool,
80}
81
82impl TargetEvidence {
83    /// The existing document at one block destination.
84    #[must_use]
85    pub fn document(&self, destination: &str) -> Option<&[u8]> {
86        self.documents.get(destination).map(Vec::as_slice)
87    }
88}
89
90/// The structural facts of the target's crate that the seeded Nix
91/// package expression and the seed flake's smoke check rely on.
92#[derive(Debug, Clone, PartialEq, Eq, Default)]
93pub struct CrateShape {
94    /// The text of the target's `Cargo.toml`, or `None` where none reads.
95    pub cargo_toml: Option<String>,
96    /// Whether `Cargo.lock` is a file at the target.
97    pub cargo_lock: bool,
98    /// Whether `src/main.rs` is a file at the target.
99    pub main_rs: bool,
100}
101
102/// The complete candidate artifact tree for one target.
103///
104/// A value, never a record: it carries no operation, no decision, and no
105/// apply state, and it is not serializable. A consumer renders it again
106/// from scratch rather than reading a saved copy.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct Projection {
109    /// Every capability the catalog answered for this target, in catalog
110    /// order: selected, withheld, or omitted with its reason.
111    pub capabilities: Vec<Selection>,
112    /// Every candidate, sorted by destination.
113    pub candidates: Vec<Candidate>,
114    /// The destinations the target's own state withholds, each with its
115    /// one reason and, where one exists, the operator's one edit. A
116    /// destination no selected capability ships is absent, never
117    /// omitted.
118    pub omissions: Vec<Omission>,
119    /// The block destinations whose existing document offers the block no
120    /// place, a target-side defect staging explains and landing refuses.
121    pub collisions: Vec<Collision>,
122    /// Why the recorded code scanning provider's licence condition refuses
123    /// this target, or `None` where no condition applies or the licence
124    /// satisfies it. A landing verb refuses on it and writes nothing; `rk
125    /// status` reports it as a warning and still exits 0, because the
126    /// target is not broken and the operator owns the licensing decision.
127    pub licence_refusal: Option<String>,
128    /// Why a recorded capability cannot run at this target at all, which is a
129    /// receipt nothing can honour rather than a decision anyone made. Empty on
130    /// every target whose parameters came through resolution, because
131    /// resolution refuses these before they are recorded.
132    pub record_defects: Vec<String>,
133}
134
135/// One proposed destination.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct Candidate {
138    /// The capability that lands it.
139    pub capability: &'static str,
140    /// The destination, relative to the target root.
141    pub destination: String,
142    /// Who owns the bytes after landing.
143    pub kind: Kind,
144    /// The whole file, or the one marked region.
145    pub placement: Placement,
146    /// The complete proposed destination bytes. For a region this is the
147    /// complete spliced document, computed from the existing document in
148    /// the evidence, so a staged view equals what production writes.
149    pub bytes: Vec<u8>,
150    /// The rendered block alone for a region destination: what the
151    /// receipt digests. `None` for a whole file.
152    pub region: Option<Vec<u8>>,
153    /// The embedded source paths the candidate was rendered from, each
154    /// carrying its distribution root as the first segment.
155    pub sources: Vec<String>,
156}
157
158/// How a candidate occupies its destination.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub enum Placement {
161    /// The candidate is the whole file.
162    Whole,
163    /// The candidate is the one marked region between these markers; the
164    /// bytes outside them belong to the target.
165    Region {
166        /// The opening marker.
167        begin: &'static str,
168        /// The closing marker.
169        end: &'static str,
170    },
171}
172
173/// One destination withheld from this target, with why.
174#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct Omission {
176    /// The destination that stays out.
177    pub destination: String,
178    /// The reason, stated once per destination.
179    pub reason: String,
180    /// The one edit the operator makes to activate what release-kit could
181    /// not, where the omission is a withheld activation rather than a
182    /// shape the target cannot take.
183    pub action: Option<String>,
184}
185
186/// One block destination the target's document cannot take.
187#[derive(Debug, Clone, PartialEq, Eq)]
188pub struct Collision {
189    /// The destination whose document offers the block no place.
190    pub destination: String,
191    /// The reason, for staging to explain and landing to refuse with.
192    pub reason: String,
193}
194
195impl Projection {
196    /// The complete candidate tree for `input`, from this binary's
197    /// embedded sources alone.
198    ///
199    /// # Errors
200    ///
201    /// A source defect in this binary: an unknown technology or an
202    /// unsupported pair as [`RkError::Usage`], and as [`RkError::Other`] a
203    /// destination two sources ship, a snippet the kind table does not
204    /// classify, or a block this binary does not embed.
205    pub fn compute(input: &ProjectionInput) -> Result<Self, RkError> {
206        Self::compute_over(&embedded_snippets(), input)
207    }
208
209    /// [`Self::compute`] over an explicit snippet list, whose paths carry
210    /// the `snippets/` root; the embedded tree in production, an injected
211    /// one under test.
212    #[allow(
213        clippy::too_many_lines,
214        reason = "one pass selects, renders, splices, and withholds; splitting it would separate a withheld destination from the selection that offered it"
215    )]
216    fn compute_over(files: &[(String, &[u8])], input: &ProjectionInput) -> Result<Self, RkError> {
217        let params = &input.params;
218        let evidence = &input.evidence;
219        let availability = Availability::over(
220            files
221                .iter()
222                .filter_map(|(path, _)| path.strip_prefix("snippets/").map(str::to_owned))
223                .collect(),
224        );
225        let mut capabilities = catalog::select(params, &availability);
226        let mut candidates: Vec<Candidate> = Vec::new();
227        for selection in &capabilities {
228            if !selection.lands() {
229                continue;
230            }
231            for source in &selection.sources {
232                let destination = source
233                    .splitn(3, '/')
234                    .nth(2)
235                    .ok_or_else(|| {
236                        anyhow::anyhow!(
237                            "{source}: a snippet path has a zone, a forge, and a destination"
238                        )
239                    })?
240                    .to_owned();
241                let path = format!("snippets/{source}");
242                let bytes = files
243                    .iter()
244                    .find(|(candidate, _)| *candidate == path)
245                    .map(|(_, bytes)| *bytes)
246                    .ok_or_else(|| {
247                        anyhow::anyhow!(
248                            "{path}: the catalog selected a source the tree does not carry"
249                        )
250                    })?;
251                if let Some(existing) = candidates
252                    .iter()
253                    .find(|candidate| candidate.destination == destination)
254                {
255                    return Err(anyhow::anyhow!(
256                        "{} and {} both ship {destination}: {} and {path}; the embedded sources are defective",
257                        existing.capability,
258                        selection.id,
259                        existing.sources.join(", ")
260                    )
261                    .into());
262                }
263                let kind = kind_of(&destination).ok_or_else(|| {
264                    anyhow::anyhow!(
265                        "the embedded sources do not classify {destination}; the kind table is stale"
266                    )
267                })?;
268                let rendered = match kind {
269                    Kind::Rendered => render(bytes, params),
270                    Kind::Seeded | Kind::State => bytes.to_vec(),
271                };
272                candidates.push(Candidate {
273                    capability: selection.id,
274                    destination,
275                    kind,
276                    placement: Placement::Whole,
277                    bytes: rendered,
278                    region: None,
279                    sources: vec![path],
280                });
281            }
282        }
283        let mut collisions = Vec::new();
284        for destination in BLOCK_DESTINATIONS {
285            let (template, sources) =
286                block_template(destination, params.checkout_mode(), params.integration())?;
287            if let Some(whole) = candidates
288                .iter()
289                .find(|candidate| candidate.destination == destination)
290            {
291                return Err(anyhow::anyhow!(
292                    "{destination} is both a whole file from {} and a marked region from {}; the embedded sources are defective",
293                    whole.sources.join(", "),
294                    sources.join(", ")
295                )
296                .into());
297            }
298            let region = render(template.as_bytes(), params);
299            let (begin, end) = block_markers(destination).ok_or_else(|| {
300                anyhow::anyhow!("{destination} is a block destination with no markers")
301            })?;
302            match propose_document(destination, evidence.document(destination), &region) {
303                Ok(bytes) => candidates.push(Candidate {
304                    capability: catalog::GUARDS,
305                    destination: destination.to_owned(),
306                    kind: Kind::Rendered,
307                    placement: Placement::Region { begin, end },
308                    bytes,
309                    region: Some(region),
310                    sources,
311                }),
312                Err(reason) => collisions.push(Collision {
313                    destination: destination.to_owned(),
314                    reason,
315                }),
316            }
317        }
318        let mut omissions = Vec::new();
319        if let Some((set, reason)) = nix_withholding(params.nix_packaging(), evidence)
320            && candidates
321                .iter()
322                .any(|candidate| candidate.capability == catalog::PACKAGING_NIX)
323        {
324            candidates.retain(|candidate| {
325                if set.contains(&candidate.destination.as_str()) {
326                    omissions.push(Omission {
327                        destination: candidate.destination.clone(),
328                        reason: reason.clone(),
329                        action: None,
330                    });
331                    false
332                } else {
333                    true
334                }
335            });
336            withhold(&mut capabilities, catalog::PACKAGING_NIX, &reason, None);
337        }
338        // The release-less GitLab root pipeline: where the target owns a
339        // root pipeline the receipt does not attribute, the fragment still
340        // lands as the gate's prerequisite, and the activation is the
341        // operator's one include line rather than a refusal of the whole
342        // landing.
343        let title_root = candidates.iter().position(|candidate| {
344            candidate.capability == catalog::TITLE_CHECK
345                && candidate.destination == GITLAB_ROOT_PIPELINE
346        });
347        if let Some(index) = title_root
348            && evidence.root_pipeline_present
349            && !evidence.root_pipeline_recorded
350        {
351            let candidate = candidates.remove(index);
352            let reason = format!(
353                "the target owns {GITLAB_ROOT_PIPELINE}, so the release-less root pipeline that would activate the title gate stays out; the fragment lands as the gate's prerequisite"
354            );
355            let action = format!(
356                "add the include to the target's own {GITLAB_ROOT_PIPELINE}: include:\n  - local: {GITLAB_TITLE_FRAGMENT}"
357            );
358            omissions.push(Omission {
359                destination: candidate.destination,
360                reason: reason.clone(),
361                action: Some(action.clone()),
362            });
363            withhold(
364                &mut capabilities,
365                catalog::TITLE_CHECK,
366                &reason,
367                Some(action),
368            );
369        }
370        candidates.sort_by(|a, b| a.destination.cmp(&b.destination));
371        omissions.sort_by(|a, b| a.destination.cmp(&b.destination));
372        // The licence judgment belongs to a workflow this landing will
373        // actually write. A provider the target's dimensions cannot run is
374        // already an unavailable optional capability, reported and omitted,
375        // and refusing it on its terms would refuse a landing over a file
376        // that was never going to land.
377        let scanning_selected = capabilities.iter().any(|selection| {
378            selection.id == catalog::CODE_SCANNING && selection.status == Status::Selected
379        });
380        let licence_refusal = scanning_selected
381            .then(|| {
382                code_scanning_licence_refusal(
383                    params.code_scanning(),
384                    params.driver(),
385                    &evidence.crate_shape,
386                )
387            })
388            .flatten();
389        // A scanner the target's dimensions cannot run is an unavailable
390        // optional capability, which the catalog already reports and this
391        // projection already omits. Naming it a record defect too would
392        // make a landing this binary itself wrote fail its own check.
393        let mut record_defects: Vec<String> = Vec::new();
394        // A recorded automatic release whose automation this release cannot
395        // land is a receipt nothing can honour: named here, so a
396        // record-only reader sees it.
397        if params.release_mode() == ReleaseMode::Automatic
398            && let Some(selection) = capabilities
399                .iter()
400                .find(|selection| selection.id == catalog::RELEASE_AUTOMATION)
401            && matches!(selection.status, Status::Unavailable | Status::Unknown)
402            && let Some(reason) = &selection.reason
403        {
404            record_defects.push(reason.clone());
405        }
406        Ok(Self {
407            capabilities,
408            candidates,
409            omissions,
410            collisions,
411            licence_refusal,
412            record_defects,
413        })
414    }
415
416    /// Why the selected release automation cannot land, where the profile
417    /// asked for one this release does not carry at its dimensions. An
418    /// apply refuses on it before any write; a preview reports it.
419    #[must_use]
420    pub fn release_unavailable(&self) -> Option<&str> {
421        self.capabilities
422            .iter()
423            .find(|selection| {
424                selection.id == catalog::RELEASE_AUTOMATION
425                    && matches!(selection.status, Status::Unavailable | Status::Unknown)
426            })
427            .and_then(|selection| selection.reason.as_deref())
428    }
429
430    /// The one selection for a capability.
431    #[must_use]
432    pub fn capability(&self, id: &str) -> Option<&Selection> {
433        self.capabilities
434            .iter()
435            .find(|selection| selection.id == id)
436    }
437}
438
439/// Mark one capability withheld with its reason and the operator's edit.
440fn withhold(capabilities: &mut [Selection], id: &str, reason: &str, action: Option<String>) {
441    if let Some(selection) = capabilities.iter_mut().find(|selection| selection.id == id) {
442        selection.status = Status::Withheld;
443        selection.reason = Some(reason.to_owned());
444        selection.action = action;
445    }
446}
447
448/// The GitLab root pipeline, the one destination a release-less landing
449/// withholds where the target owns it.
450pub const GITLAB_ROOT_PIPELINE: &str = ".gitlab-ci.yml";
451
452/// The GitLab title fragment the root pipeline includes.
453pub const GITLAB_TITLE_FRAGMENT: &str = ".gitlab/ci/mr-title.yml";
454
455/// Every snippet this binary embeds, as `(path, bytes)` with the path
456/// carrying the `snippets/` root, sorted by path.
457fn embedded_snippets() -> Vec<(String, &'static [u8])> {
458    embedded::walk(&embedded::SNIPPETS)
459        .into_iter()
460        .map(|(path, bytes)| (format!("snippets/{path}"), bytes))
461        .collect()
462}
463
464/// Every `(driver, forge)` pair at which the release automation is
465/// available, in path order.
466#[must_use]
467pub fn supported_pairs() -> Vec<(String, String)> {
468    Availability::embedded()
469        .automation_tuples()
470        .into_iter()
471        .filter_map(|entry| {
472            entry
473                .split_once(", ")
474                .map(|(driver, forge)| (driver.to_owned(), forge.to_owned()))
475        })
476        .collect()
477}
478
479/// Who owns a landed file's bytes after landing.
480#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
481#[serde(rename_all = "lowercase")]
482pub enum Kind {
483    /// release-kit owns it: a newer binary re-renders it, and a target
484    /// edit is a conflict.
485    Rendered,
486    /// The target owns it: a starting point the project tunes, reported
487    /// and never rewritten.
488    Seeded,
489    /// The release automation owns it: never written after the first
490    /// landing, never compared.
491    State,
492}
493
494impl Kind {
495    /// The wire and report form.
496    #[must_use]
497    pub const fn as_str(self) -> &'static str {
498        match self {
499            Self::Rendered => "rendered",
500            Self::Seeded => "seeded",
501            Self::State => "state",
502        }
503    }
504}
505
506/// The declared classification: every landable destination and its kind.
507/// The workflow and pipeline files carry the release automation and the
508/// OIDC permission, so release-kit owns them; the tool configurations are
509/// per-project judgment; the two state files are rewritten by the release
510/// automation itself.
511const KINDS: [(&str, Kind); 20] = [
512    (".github/workflows/release-plz.yml", Kind::Rendered),
513    (".github/workflows/release-please.yml", Kind::Rendered),
514    (".github/workflows/release.yml", Kind::Rendered),
515    (".github/workflows/pr-title.yml", Kind::Rendered),
516    (".github/workflows/scorecard.yml", Kind::Rendered),
517    (".github/workflows/code-scanning-codeql.yml", Kind::Rendered),
518    (
519        ".github/workflows/code-scanning-semgrep.yml",
520        Kind::Rendered,
521    ),
522    (".gitlab/ci/code-scanning-semgrep.yml", Kind::Rendered),
523    (".gitlab-ci.yml", Kind::Rendered),
524    ("SECURITY.md", Kind::Rendered),
525    (".gitlab/ci/mr-title.yml", Kind::Rendered),
526    ("release-plz.toml", Kind::Seeded),
527    ("dist-workspace.toml", Kind::Seeded),
528    ("release-please-config.json", Kind::Seeded),
529    ("cliff.toml", Kind::Seeded),
530    ("nix/package.nix", Kind::Seeded),
531    ("flake.nix", Kind::Seeded),
532    (".release-please-manifest.json", Kind::State),
533    ("VERSION", Kind::State),
534    ("flake.lock", Kind::State),
535];
536
537/// The destinations of the opt-in Nix capability, present in a projection
538/// only where the landing's `nix` parameter is on.
539///
540/// The parameter is recorded, so `status`, `upgrade`, and `adopt` can
541/// reconstruct whether these files are supposed to exist: an absent file
542/// under `nix = false` is not wanted, never drifted.
543///
544/// The capability lands no workflow, on either forge, and each forge's
545/// reason is its own. On GitHub a job gates the merge only inside the
546/// workflow the required check needs, and that workflow is the target's
547/// own. On GitLab the merge check is the whole pipeline, and a target's
548/// jobs live in the child pipeline the rendered parent triggers, which the
549/// target owns. The bindings serve the job for both.
550pub const NIX_DESTINATIONS: [&str; 3] = ["nix/package.nix", "flake.nix", "flake.lock"];
551
552/// The subset a target with a flake of its own keeps out: the seed pair,
553/// whose files would sit beside a flake release-kit did not author.
554///
555/// The seeded package expression is not in it: it lands either way, as
556/// the starting point the target integrates by hand.
557pub const NIX_WITHHOLDABLE: [&str; 2] = ["flake.nix", "flake.lock"];
558
559/// The destinations of the opt-in Scorecard capability, present in a
560/// projection only where the landing's `scorecard` parameter is on.
561///
562/// The parameter is recorded for the reason [`NIX_DESTINATIONS`] states:
563/// an absent file under `scorecard = false` is not wanted, never drifted.
564/// The capability is GitHub's alone, so the shared GitLab zone ships no
565/// counterpart and a GitLab landing projects nothing for it, whatever the
566/// parameter says. A Scorecard run needs no forge setting on a public
567/// repository, so the capability adds no setup step and cannot conflict
568/// with `forge-setup:every-supported-forge-runs-every-step`.
569///
570/// The file is `rendered`: its bytes carry the recorded trunk and nothing a
571/// target is expected to tune, so release-kit owns them and an edit is
572/// drift.
573pub const SCORECARD_DESTINATIONS: [&str; 1] = [".github/workflows/scorecard.yml"];
574
575/// Every destination the opt-in code scanning capability can land, against
576/// the provider that lands it.
577///
578/// One source owns one destination, so the provider is in the name: a
579/// landing writes exactly the entry its recorded provider names and the
580/// forge ships. Switching provider retires one destination and adds
581/// another, which `landing:a-dropped-file-stays` already answers.
582///
583/// `codeql` is GitHub's own analyzer and has no GitLab entry, so a GitLab
584/// landing that names it lands nothing; the catalog reports that pair
585/// unavailable by name, as it reports a binding outside
586/// [`CODE_SCANNING_TECHS`], and the landing omits the destination and
587/// proceeds.
588pub const CODE_SCANNING_DESTINATIONS: [(&str, Provider); 3] = [
589    (
590        ".github/workflows/code-scanning-codeql.yml",
591        Provider::CodeQl,
592    ),
593    (
594        ".github/workflows/code-scanning-semgrep.yml",
595        Provider::Semgrep,
596    ),
597    (".gitlab/ci/code-scanning-semgrep.yml", Provider::Semgrep),
598];
599
600/// The bindings that ship a code scanning workflow.
601///
602/// A scanner reads one language: the `CodeQL` arm fixes `languages: rust` and
603/// both Semgrep arms name the `p/rust` ruleset, so the sources live in the
604/// rust pairs rather than in a forge's technology-independent shared zone.
605/// A landing for any other binding reports the capability unavailable by
606/// name and omits its destinations, rather than writing nothing silently.
607pub const CODE_SCANNING_TECHS: [&str; 1] = ["rust"];
608
609/// Why the named code scanning provider cannot run at this
610/// `(technology, forge)`, or `None` where it can or none is named.
611///
612/// One owner for the question, because two callers ask it and they must not
613/// disagree. The reason is informational: it becomes the catalog's
614/// `Unavailable` status, and nothing refuses on it. An optional capability
615/// this release cannot build at the target's dimensions is reported and
616/// omitted, which is what
617/// `project-profile:an-operation-refuses-only-what-it-requires` states.
618///
619/// A receipt asks the same question and gets the same answer, because
620/// `Params::from_record` cannot fail and a hand-edited or foreign receipt
621/// reaches `rk status` through it: without this, a receipt naming a provider
622/// whose pair ships nothing would project nothing, name nothing, and read as
623/// clean. It is a report about the pair, not a record defect, so a landing
624/// this binary wrote still answers its own check.
625#[must_use]
626pub fn code_scanning_incompatibility(
627    provider: Option<Provider>,
628    driver: Option<&str>,
629    forge: Option<&str>,
630) -> Option<String> {
631    let named = provider?;
632    let Some(driver) = driver else {
633        return Some(format!(
634            "a scanner reads the release driver's language, and the profile names no automatic release driver; the bindings that carry one are: {}",
635            CODE_SCANNING_TECHS.join(", ")
636        ));
637    };
638    if !CODE_SCANNING_TECHS.contains(&driver) {
639        return Some(format!(
640            "the {driver} binding ships no code scanning workflow; a scanner reads one language, and the bindings that carry one are: {}",
641            CODE_SCANNING_TECHS.join(", ")
642        ));
643    }
644    let Some(forge) = forge else {
645        return Some(
646            "a code scanning workflow runs at a forge, and the profile names none".to_owned(),
647        );
648    };
649    if named == Provider::CodeQl && forge != "github" {
650        return Some(format!(
651            "codeql is GitHub's own analyzer and the {forge} pair ships no workflow for it; pass --code-scanning semgrep"
652        ));
653    }
654    None
655}
656
657/// The SPDX identifiers this convention recognizes as OSI-approved, sorted.
658///
659/// Lowercase, because the comparison is case-insensitive: SPDX asks for that
660/// and cargo accepts any casing.
661///
662/// A closed list rather than a parse of the OSI register: the register moves
663/// and this binary reads no network, so an identifier absent here is
664/// unrecognized rather than rejected, and the refusal says so. Every entry
665/// is an OSI-approved licence that appears on published Rust crates.
666const OSI_APPROVED: [&str; 18] = [
667    "0bsd",
668    "agpl-3.0",
669    "agpl-3.0-only",
670    "agpl-3.0-or-later",
671    "apache-2.0",
672    "bsd-2-clause",
673    "bsd-3-clause",
674    "bsl-1.0",
675    "epl-2.0",
676    "gpl-2.0",
677    "gpl-2.0-only",
678    "gpl-2.0-or-later",
679    "gpl-3.0",
680    "gpl-3.0-only",
681    "gpl-3.0-or-later",
682    "isc",
683    "mit",
684    "mpl-2.0",
685];
686
687/// The SPDX identifiers this convention recognizes as terms over material
688/// that is not code, sorted.
689///
690/// Lowercase, for the reason [`OSI_APPROVED`] is.
691///
692/// None of these is OSI-approved, and none of them grants a licence over
693/// code, so none of them states an open-source codebase on its own. They are
694/// recognized because a project that licenses its prose apart from its source
695/// declares both in one expression, and a conjunction naming one of these
696/// beside an OSI-approved licence still hands every reader the approved
697/// terms. The entries are the attribution and share-alike families at the two
698/// versions still in use, which is what a crate shipping documentation beside
699/// its source declares.
700///
701/// `CC0-1.0` is deliberately absent. It dedicates any material to the public
702/// domain, code included, so it is not a term over material that is not code
703/// and it belongs to a question this list does not answer.
704const CONTENT_LICENCES: [&str; 4] = ["cc-by-3.0", "cc-by-4.0", "cc-by-sa-3.0", "cc-by-sa-4.0"];
705
706/// Every SPDX exception identifier, lowercase.
707///
708/// SPDX requires the right operand of `WITH` to be a `<license-exception-id>`,
709/// so an operand outside this list makes the expression malformed and the
710/// licence unread. The whole register rather than a subset, because a subset
711/// refuses a legitimate crate: `GPL-2.0-only WITH GCC-exception-2.0` names a
712/// real exception, and a reader carrying only the newer `GCC-exception-3.1`
713/// would refuse it.
714///
715/// An exception grants permission rather than withdrawing it, so none of these
716/// changes whether the left operand is OSI-approved. It is validated because a
717/// reader that cannot parse the expression has not read the licence.
718///
719/// Taken from the SPDX license-list-data exception register, 86 identifiers, on
720/// 2026-09-15. A later addition upstream is a patch here, and the refusal names
721/// the operand it did not recognize.
722const SPDX_EXCEPTIONS: [&str; 86] = [
723    "389-exception",
724    "asterisk-exception",
725    "asterisk-linking-protocols-exception",
726    "autoconf-exception-2.0",
727    "autoconf-exception-3.0",
728    "autoconf-exception-generic",
729    "autoconf-exception-generic-3.0",
730    "autoconf-exception-macro",
731    "bison-exception-1.24",
732    "bison-exception-2.2",
733    "bootloader-exception",
734    "cgal-linking-exception",
735    "classpath-exception-2.0",
736    "classpath-exception-2.0-short",
737    "clisp-exception-2.0",
738    "cryptsetup-openssl-exception",
739    "digia-qt-lgpl-exception-1.1",
740    "digirule-foss-exception",
741    "ecos-exception-2.0",
742    "erlang-otp-linking-exception",
743    "fawkes-runtime-exception",
744    "fltk-exception",
745    "fmt-exception",
746    "font-exception-2.0",
747    "freertos-exception-2.0",
748    "gcc-exception-2.0",
749    "gcc-exception-2.0-note",
750    "gcc-exception-3.1",
751    "gmsh-exception",
752    "gnat-exception",
753    "gnome-examples-exception",
754    "gnu-compiler-exception",
755    "gnu-javamail-exception",
756    "google-patent-webm",
757    "gpl-3.0-389-ds-base-exception",
758    "gpl-3.0-interface-exception",
759    "gpl-3.0-linking-exception",
760    "gpl-3.0-linking-source-exception",
761    "gpl-cc-1.0",
762    "gstreamer-exception-2005",
763    "gstreamer-exception-2008",
764    "harbour-exception",
765    "i2p-gpl-java-exception",
766    "independent-modules-exception",
767    "kicad-libraries-exception",
768    "kvirc-openssl-exception",
769    "lgpl-3.0-linking-exception",
770    "libpri-openh323-exception",
771    "libtool-exception",
772    "linux-syscall-note",
773    "llgpl",
774    "llvm-exception",
775    "lzma-exception",
776    "mif-exception",
777    "mxml-exception",
778    "nokia-qt-exception-1.1",
779    "ocaml-lgpl-linking-exception",
780    "occt-exception-1.0",
781    "openjdk-assembly-exception-1.0",
782    "openvpn-openssl-exception",
783    "pcre2-exception",
784    "polyparse-exception",
785    "ps-or-pdf-font-exception-20170817",
786    "qpl-1.0-inria-2004-exception",
787    "qt-gpl-exception-1.0",
788    "qt-lgpl-exception-1.1",
789    "qwt-exception-1.0",
790    "romic-exception",
791    "rrdtool-floss-exception-2.0",
792    "rsync-linking-exception",
793    "sane-exception",
794    "shl-2.0",
795    "shl-2.1",
796    "simple-library-usage-exception",
797    "spelling-provider-lgpl-exception",
798    "sqlitestudio-openssl-exception",
799    "stunnel-exception",
800    "swi-exception",
801    "swift-exception",
802    "texinfo-exception",
803    "u-boot-exception-2.0",
804    "ubdl-exception",
805    "universal-foss-exception-1.0",
806    "vsftpd-openssl-exception",
807    "wxwindows-exception-3.1",
808    "x11vnc-openssl-exception",
809];
810
811/// Whether `identifier` is in `list`, matched the way SPDX asks for it.
812///
813/// Without regard to case: SPDX states that an identifier "should be matched
814/// in a case-insensitive manner", and cargo accepts `license = "mit"` without
815/// complaint, so a real crate can carry any casing and a case-sensitive
816/// comparison would refuse a licence it recognizes.
817fn listed(list: &[&str], identifier: &str) -> bool {
818    let lowered = identifier.to_ascii_lowercase();
819    list.contains(&lowered.as_str())
820}
821
822/// One token of an SPDX licence expression.
823#[derive(Debug, Clone, Copy, PartialEq, Eq)]
824enum Token<'a> {
825    /// An opening parenthesis.
826    Open,
827    /// A closing parenthesis.
828    Close,
829    /// The conjunction: the codebase is offered under both terms at once.
830    And,
831    /// The disjunction: the reader chooses one term.
832    Or,
833    /// The exception operator, whose right side names an exception rather
834    /// than a licence.
835    With,
836    /// A licence identifier, a licence reference, or an exception
837    /// identifier. Which one it is depends on its position.
838    Identifier(&'a str),
839}
840
841/// The tokens of one SPDX expression, or `None` where a character can begin
842/// no token.
843///
844/// The identifier alphabet is SPDX's own plus `:`, which a
845/// `DocumentRef-...:LicenseRef-...` reference carries. A reference
846/// tokenizes and then simply matches no approved identifier, which is the
847/// honest answer: it names a licence whose text lives outside the register.
848fn tokenize(expression: &str) -> Option<Vec<Token<'_>>> {
849    let mut tokens = Vec::new();
850    let bytes = expression.as_bytes();
851    let mut at = 0;
852    while at < bytes.len() {
853        let byte = bytes[at];
854        if byte.is_ascii_whitespace() {
855            at += 1;
856            continue;
857        }
858        if byte == b'(' {
859            tokens.push(Token::Open);
860            at += 1;
861            continue;
862        }
863        if byte == b')' {
864            tokens.push(Token::Close);
865            at += 1;
866            continue;
867        }
868        let start = at;
869        while at < bytes.len() {
870            let byte = bytes[at];
871            if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'+' | b':') {
872                at += 1;
873            } else {
874                break;
875            }
876        }
877        if at == start {
878            return None;
879        }
880        let word = &expression[start..at];
881        tokens.push(match word {
882            "AND" => Token::And,
883            "OR" => Token::Or,
884            "WITH" => Token::With,
885            other => Token::Identifier(other),
886        });
887    }
888    Some(tokens)
889}
890
891/// What one node of an SPDX expression states.
892///
893/// Two facts rather than one, because a single bit cannot answer the
894/// question. `MIT AND (CC-BY-4.0 OR CC-BY-SA-4.0)` needs an inner node that
895/// states no open-source codebase on its own and still leaves the conjunction
896/// around it stating one.
897#[derive(Debug, Clone, Copy)]
898struct Verdict {
899    /// Every reader of this node obtains an OSI-approved grant.
900    grants: bool,
901    /// Every licence this node names is one this release recognizes.
902    clean: bool,
903}
904
905/// A recursive-descent reader over one tokenized SPDX expression.
906///
907/// It answers three questions in one pass, and all three must hold: whether
908/// the expression is well formed, whether every reader of it obtains an
909/// OSI-approved grant, and whether every licence it names is one this release
910/// recognizes. A malformed expression answers `None` rather than falling
911/// back on the identifiers it happened to contain, because an expression
912/// nobody can parse states no terms at all.
913struct Spdx<'a> {
914    tokens: &'a [Token<'a>],
915    at: usize,
916}
917
918impl<'a> Spdx<'a> {
919    /// The token at the cursor, without consuming it.
920    fn peek(&self) -> Option<Token<'a>> {
921        self.tokens.get(self.at).copied()
922    }
923
924    /// The token at the cursor, consumed.
925    fn bump(&mut self) -> Option<Token<'a>> {
926        let token = self.peek()?;
927        self.at += 1;
928        Some(token)
929    }
930
931    /// One expression: conjunctions joined by `OR`.
932    ///
933    /// `OR` binds loosest, which is what SPDX states, and the precedence is
934    /// load-bearing here rather than decorative. A disjunction offers the
935    /// reader a choice, so it grants the approved terms only where every arm
936    /// does: one unapproved arm is an arm the reader may take. Read with the
937    /// operators flattened instead, `CC-BY-4.0 OR CC-BY-SA-4.0 AND MIT` would
938    /// state an open-source codebase, and its reader may hold a term over
939    /// prose alone.
940    fn expression(&mut self) -> Option<Verdict> {
941        let mut verdict = self.conjunction()?;
942        while self.peek() == Some(Token::Or) {
943            self.bump();
944            let right = self.conjunction()?;
945            verdict = Verdict {
946                grants: verdict.grants && right.grants,
947                clean: verdict.clean && right.clean,
948            };
949        }
950        Some(verdict)
951    }
952
953    /// One conjunction: operands joined by `AND`, each operand a
954    /// parenthesized expression or a simple licence.
955    ///
956    /// `AND` binds tighter than `OR`. A conjunction offers every term at
957    /// once, so it grants the approved terms where any operand does: a reader
958    /// who must accept both terms has accepted the approved one. What the
959    /// other operand may be is held by `clean` rather than by this field,
960    /// because a licence nobody here can read establishes nothing, while a
961    /// Creative Commons term over prose withdraws no grant over code.
962    fn conjunction(&mut self) -> Option<Verdict> {
963        let mut verdict = self.operand()?;
964        while self.peek() == Some(Token::And) {
965            self.bump();
966            let right = self.operand()?;
967            verdict = Verdict {
968                grants: verdict.grants || right.grants,
969                clean: verdict.clean && right.clean,
970            };
971        }
972        Some(verdict)
973    }
974
975    /// One operand: a parenthesized expression, or a licence identifier
976    /// optionally carrying `WITH` and an exception identifier.
977    ///
978    /// A `+` suffix reads as the bare identifier, which is what the
979    /// deprecated `GPL-3.0+` form means. The operand after `WITH` must be an
980    /// exception identifier this release recognizes, and it changes no
981    /// verdict: an exception grants permission rather than withdrawing it, so
982    /// which licence the codebase is offered under is answered by the left
983    /// operand alone.
984    fn operand(&mut self) -> Option<Verdict> {
985        match self.bump()? {
986            Token::Open => {
987                // A parenthesis restarts the whole grammar, so the loosest
988                // operator binds inside it too.
989                let inner = self.expression()?;
990                (self.bump()? == Token::Close).then_some(inner)
991            }
992            Token::Identifier(name) => {
993                let identifier = name.strip_suffix('+').unwrap_or(name);
994                let approved = listed(&OSI_APPROVED, identifier);
995                let verdict = Verdict {
996                    grants: approved,
997                    clean: approved || listed(&CONTENT_LICENCES, identifier),
998                };
999                if self.peek() == Some(Token::With) {
1000                    self.bump();
1001                    // SPDX requires an exception identifier here, so an
1002                    // operand this release does not recognize leaves the
1003                    // expression malformed and the licence unread.
1004                    match self.bump()? {
1005                        Token::Identifier(exception) if listed(&SPDX_EXCEPTIONS, exception) => {}
1006                        _ => return None,
1007                    }
1008                }
1009                Some(verdict)
1010            }
1011            Token::And | Token::Or | Token::With | Token::Close => None,
1012        }
1013    }
1014}
1015
1016/// Whether one SPDX expression is well formed and states an open-source
1017/// codebase.
1018///
1019/// Three conditions, and the trio is the point. The expression must parse,
1020/// because `MIT OR` names one licence and no complete offer, and accepting it
1021/// would land a workflow whose provider's terms nothing established. Every
1022/// reader of it must obtain an OSI-approved grant, which makes a disjunction
1023/// strict and a conjunction permissive. And every identifier in it must be
1024/// one this release recognizes, either OSI-approved or a Creative Commons
1025/// term over material that is not code.
1026///
1027/// The conjunction is the case this answers. A project that offers its source
1028/// under an OSI-approved licence and its prose under Creative Commons terms
1029/// declares both in one expression, and the second adds an obligation over
1030/// prose rather than withdrawing the grant over code.
1031#[must_use]
1032pub fn licence_states_an_open_source_codebase(expression: &str) -> bool {
1033    let Some(tokens) = tokenize(expression) else {
1034        return false;
1035    };
1036    let mut reader = Spdx {
1037        tokens: &tokens,
1038        at: 0,
1039    };
1040    let Some(verdict) = reader.expression() else {
1041        return false;
1042    };
1043    verdict.grants && verdict.clean && reader.at == tokens.len()
1044}
1045
1046/// Why the code scanning capability's licence condition refuses this
1047/// target, or `None` where no condition applies or the licence satisfies
1048/// it.
1049///
1050/// Only `codeql` carries a condition: its terms cover an open-source
1051/// codebase, and a run over anything else needs a paid seat, so a landing
1052/// that guessed would write a licence violation. Semgrep CE carries none,
1053/// and is the fallback the refusal names.
1054///
1055/// The licence is read where the binding declares it. For `rust` that is
1056/// the `license` field of `Cargo.toml`. A manifest that names a
1057/// `license-file` instead states no identifier this judgment can read, so
1058/// the pair refuses rather than guessing at the file's contents.
1059#[must_use]
1060pub fn code_scanning_licence_refusal(
1061    provider: Option<Provider>,
1062    driver: Option<&str>,
1063    shape: &CrateShape,
1064) -> Option<String> {
1065    if provider != Some(Provider::CodeQl) {
1066        return None;
1067    }
1068    if driver != Some("rust") {
1069        return Some(format!(
1070            "the {} binding declares no licence field this release reads, and codeql's terms cover an open-source codebase alone; land --code-scanning semgrep, which carries no licence condition",
1071            driver.unwrap_or("release-less")
1072        ));
1073    }
1074    let fallback = "land --code-scanning semgrep, which carries no licence condition";
1075    let Some(text) = shape.cargo_toml.as_deref() else {
1076        return Some(format!(
1077            "the target has no readable Cargo.toml, so the licence codeql's terms depend on cannot be read; {fallback}"
1078        ));
1079    };
1080    let Ok(table) = text.parse::<toml::Table>() else {
1081        return Some(format!(
1082            "the target's Cargo.toml does not parse, so the licence codeql's terms depend on cannot be read; {fallback}"
1083        ));
1084    };
1085    let licence = table
1086        .get("package")
1087        .and_then(toml::Value::as_table)
1088        .and_then(|package| package.get("license"))
1089        .and_then(toml::Value::as_str);
1090    match licence {
1091        None => Some(format!(
1092            "the target's Cargo.toml declares no license field, and codeql's terms cover an open-source codebase alone; declare one, or {fallback}"
1093        )),
1094        Some(expression) if !licence_states_an_open_source_codebase(expression) => Some(format!(
1095            "the target's license, {expression}, does not state a codebase this release recognizes as open source, and codeql's terms cover an open-source codebase alone; {fallback}"
1096        )),
1097        Some(_) => None,
1098    }
1099}
1100
1101/// The declared kind of a destination, or `None` for a file the sources
1102/// does not classify.
1103#[must_use]
1104pub fn kind_of(destination: &str) -> Option<Kind> {
1105    if BLOCK_DESTINATIONS.contains(&destination) {
1106        return Some(Kind::Rendered);
1107    }
1108    KINDS
1109        .iter()
1110        .find(|(name, _)| *name == destination)
1111        .map(|(_, kind)| *kind)
1112}
1113
1114/// Every destination the embedded sources can land, in declaration order.
1115///
1116/// The whole files and the three block destinations. The classification
1117/// reads it to ask whether a destination is already present at a target.
1118pub fn destinations() -> impl Iterator<Item = &'static str> {
1119    KINDS
1120        .iter()
1121        .map(|(name, _)| *name)
1122        .chain(BLOCK_DESTINATIONS)
1123}
1124
1125/// The mechanical substitution sites in `rendered` files.
1126///
1127/// Known values, substituted identically everywhere each appears. The
1128/// owner is derived from the landing's `repo` parameter and the scope
1129/// shape from [`SCOPE_SHAPE`], so the landed bytes stay a deterministic
1130/// function of the embedded sources plus parameters.
1131pub const OWNER_TOKEN: &[u8] = b"OWNER";
1132
1133/// The repository a preview stands in for where nothing answered.
1134///
1135/// It is a placeholder, never a project path: a plan that would render
1136/// it into a target is blocked, and only a preview may carry it.
1137pub const REPO_PLACEHOLDER: &str = "OWNER";
1138
1139/// The full recorded project path, including nested namespaces.
1140pub const REPO_TOKEN: &[u8] = b"RK_REPO";
1141
1142/// The one scope shape: the title checks' regular expression.
1143pub const SCOPE_SHAPE_TOKEN: &[u8] = b"RK_SCOPE_SHAPE";
1144
1145/// The recorded release style: `trunk` arms the bot's request in the
1146/// landed release workflow, `lines` leaves every request unarmed.
1147pub const STYLE_TOKEN: &[u8] = b"RK_STYLE";
1148
1149/// The one permanent branch. A landed release trigger, ref guard, and
1150/// branch guard each name it, so a target whose trunk is not `master`
1151/// needs its own answer in its own bytes.
1152pub const TRUNK_BRANCH_TOKEN: &[u8] = b"RK_TRUNK_BRANCH";
1153
1154/// The release-line branch prefix, naming the lines a release trigger
1155/// accepts beside the trunk.
1156pub const LINE_PREFIX_TOKEN: &[u8] = b"RK_LINE_PREFIX";
1157
1158/// The same prefix, escaped for a slash-delimited regular expression.
1159///
1160/// A GitLab rule names a line that way, and a raw `release/` would close
1161/// the delimiter and break the pipeline, so the two forms are two tokens.
1162/// This one substitutes first: the plain token is its own prefix.
1163pub const LINE_PREFIX_RE_TOKEN: &[u8] = b"RK_LINE_PREFIX_RE";
1164
1165/// The three replaceable spans of a landed security policy, each as its
1166/// ordered begin and end marker.
1167///
1168/// A span is not a token. Each forge's policy carries its own authored
1169/// prose inside the markers, so a landing that answers neither security
1170/// parameter strips the markers and reproduces the file the forge's
1171/// snippet states, byte for byte and in that forge's own words. A landing
1172/// that answers one replaces the interior of the spans that fact belongs
1173/// to. The markers are HTML comments because the snippet is Markdown a
1174/// reader may open before it is ever rendered.
1175pub const SECURITY_SPANS: [(&[u8], &[u8]); 3] = [
1176    (
1177        b"<!--RK_SECURITY_CONTACT_BEGIN-->",
1178        b"<!--RK_SECURITY_CONTACT_END-->",
1179    ),
1180    (
1181        b"<!--RK_SECURITY_RESPONSE_BEGIN-->",
1182        b"<!--RK_SECURITY_RESPONSE_END-->",
1183    ),
1184    (
1185        b"<!--RK_SECURITY_DEADLINE_BEGIN-->",
1186        b"<!--RK_SECURITY_DEADLINE_END-->",
1187    ),
1188];
1189
1190/// The sentence a policy with an acknowledgment window states in place of
1191/// the forge's best-effort wording.
1192fn acknowledgment(response: &str) -> String {
1193    format!("Maintainers acknowledge a report within {response}.")
1194}
1195
1196/// What a policy with an acknowledgment window says about deadlines: the
1197/// authored sentence disclaims a response deadline, which a stated window
1198/// contradicts, so only the disclosure half survives.
1199const DISCLOSURE_ONLY: &[u8] = b"This policy commits to no disclosure deadline.";
1200
1201/// The replacement for each span under one parameter set, or `None` where
1202/// the forge's authored interior stands.
1203fn security_replacements(params: &Params) -> [Option<Vec<u8>>; 3] {
1204    let contact = (!params.security_contact().is_empty())
1205        .then(|| params.security_contact().as_bytes().to_vec());
1206    let promised = params.security_response() != crate::config::RESPONSE_DEFAULT;
1207    [
1208        contact,
1209        promised.then(|| acknowledgment(params.security_response()).into_bytes()),
1210        promised.then(|| DISCLOSURE_ONLY.to_vec()),
1211    ]
1212}
1213
1214/// One marked span replaced, or the markers alone removed.
1215///
1216/// Exactly one ordered begin and end pair is a span; anything else is a
1217/// source defect a test holds, so this leaves such bytes untouched rather
1218/// than growing a runtime failure mode into every rendered file.
1219fn replace_span(baseline: &[u8], begin: &[u8], end: &[u8], value: Option<&[u8]>) -> Vec<u8> {
1220    let ordered = find(baseline, begin)
1221        .zip(find(baseline, end))
1222        .filter(|(start, stop)| stop > start);
1223    let Some((start, stop)) = ordered else {
1224        return baseline.to_vec();
1225    };
1226    let mut out = Vec::with_capacity(baseline.len());
1227    out.extend_from_slice(&baseline[..start]);
1228    out.extend_from_slice(value.unwrap_or_else(|| &baseline[start + begin.len()..stop]));
1229    out.extend_from_slice(&baseline[stop + end.len()..]);
1230    out
1231}
1232
1233/// Substitute the landing parameters into a `rendered` file's bytes.
1234///
1235/// The repository's owner, the project path's first segment, replaces
1236/// every `OWNER` occurrence; the full path replaces `RK_REPO` last. The
1237/// one scope shape replaces the scope token, and the recorded style
1238/// replaces the style token. The scope shape rests on no parameter, so it
1239/// substitutes always. An unresolved style leaves its token standing,
1240/// which only a preview renders under: an apply refuses before reaching
1241/// here.
1242///
1243/// The trunk and the line prefix substitute from the same parameters, so
1244/// a target that renames either carries the new name in every artifact
1245/// that names it rather than in the binary's behavior alone.
1246///
1247/// The security policy's marked spans resolve last, after every token, so
1248/// a contact that happens to spell a token name lands literally rather
1249/// than being read as one more substitution site.
1250#[must_use]
1251pub fn render(baseline: &[u8], params: &Params) -> Vec<u8> {
1252    let repo = params.repo();
1253    let owner = repo.split('/').next().unwrap_or(repo);
1254    let mut out = substitute(baseline, OWNER_TOKEN, owner.as_bytes());
1255    if let Some(style) = params.style() {
1256        out = substitute(&out, STYLE_TOKEN, style.as_str().as_bytes());
1257    }
1258    out = substitute(&out, SCOPE_SHAPE_TOKEN, SCOPE_SHAPE.as_bytes());
1259    out = substitute(&out, TRUNK_BRANCH_TOKEN, params.trunk().as_bytes());
1260    let escaped = params.line_prefix().replace('/', "\\/");
1261    out = substitute(&out, LINE_PREFIX_RE_TOKEN, escaped.as_bytes());
1262    out = substitute(&out, LINE_PREFIX_TOKEN, params.line_prefix().as_bytes());
1263    out = substitute(&out, REPO_TOKEN, repo.as_bytes());
1264    for ((begin, end), value) in SECURITY_SPANS.iter().zip(security_replacements(params)) {
1265        out = replace_span(&out, begin, end, value.as_deref());
1266    }
1267    out
1268}
1269
1270/// Every `token` occurrence replaced with `value`.
1271#[must_use]
1272pub fn substitute(baseline: &[u8], token: &[u8], value: &[u8]) -> Vec<u8> {
1273    let mut out = Vec::with_capacity(baseline.len());
1274    let mut rest = baseline;
1275    while let Some(at) = find(rest, token) {
1276        out.extend_from_slice(&rest[..at]);
1277        out.extend_from_slice(value);
1278        rest = &rest[at + token.len()..];
1279    }
1280    out.extend_from_slice(rest);
1281    out
1282}
1283
1284/// First occurrence of `needle` in `haystack`.
1285fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
1286    haystack
1287        .windows(needle.len())
1288        .position(|window| window == needle)
1289}
1290
1291/// The destination the routing block splices into.
1292pub const AGENTS_DESTINATION: &str = "AGENTS.md";
1293
1294/// The block's opening marker.
1295pub const BLOCK_BEGIN: &str = "<!-- BEGIN release-kit -->";
1296
1297/// The block's closing marker.
1298pub const BLOCK_END: &str = "<!-- END release-kit -->";
1299
1300/// The destination the glossary block splices into.
1301///
1302/// The document is the target's own vocabulary, so the block shares
1303/// `AGENTS.md`'s marker pair and owns nothing outside it.
1304pub const GLOSSARY_DESTINATION: &str = "GLOSSARY.md";
1305
1306/// The destination the hook block splices into.
1307pub const HOOKS_DESTINATION: &str = ".pre-commit-config.yaml";
1308
1309/// Every block destination, in the order a landing writes them.
1310///
1311/// A block destination owns the lines between its markers and nothing
1312/// else, so every verb that asks whether a destination is block-placed
1313/// reads this one list.
1314pub const BLOCK_DESTINATIONS: [&str; 3] =
1315    [AGENTS_DESTINATION, GLOSSARY_DESTINATION, HOOKS_DESTINATION];
1316
1317/// The hook block's opening marker, a YAML comment at column zero.
1318pub const HOOKS_BEGIN: &str = "# BEGIN release-kit";
1319
1320/// The hook block's closing marker.
1321pub const HOOKS_END: &str = "# END release-kit";
1322
1323/// The top-level key the fresh hook file carries and the skills verify on
1324/// an existing one: the commit-msg and pre-push hooks run only where their
1325/// hook types are installed.
1326pub const HOOK_TYPES_LINE: &str = "default_install_hook_types: [pre-commit, commit-msg, pre-push]";
1327
1328/// The authored routing-block template.
1329pub const AGENTS_BLOCK: &str = "blocks/agents-block.md.in";
1330
1331/// The authored glossary template.
1332pub const GLOSSARY_BLOCK: &str = "blocks/glossary.md.in";
1333
1334/// The routing block's mode line, worktree form.
1335pub const AGENTS_LINE_WORKTREE: &str = "blocks/agents-line-worktree.md.in";
1336
1337/// The routing block's mode line, branches form.
1338pub const AGENTS_LINE_BRANCHES: &str = "blocks/agents-line-branches.md.in";
1339
1340/// The routing block's integration line, forge form.
1341pub const AGENTS_LINE_INTEGRATION_FORGE: &str = "blocks/agents-line-integration-forge.md.in";
1342
1343/// The routing block's integration line, local form.
1344pub const AGENTS_LINE_INTEGRATION_LOCAL: &str = "blocks/agents-line-integration-local.md.in";
1345
1346/// The routing block's integration line for one integration mode.
1347#[must_use]
1348pub const fn integration_line(integration: Integration) -> &'static str {
1349    match integration {
1350        Integration::Forge => AGENTS_LINE_INTEGRATION_FORGE,
1351        Integration::Local => AGENTS_LINE_INTEGRATION_LOCAL,
1352    }
1353}
1354
1355/// The authored hook-block template.
1356pub const PRE_COMMIT_BLOCK: &str = "blocks/pre-commit-block.yaml.in";
1357
1358/// The worktree mode's guard entry.
1359pub const PRE_COMMIT_WORKTREE_GUARD: &str = "blocks/pre-commit-worktree-guard.yaml.in";
1360
1361/// The forge integration mode's guard against a trunk commit.
1362pub const PRE_COMMIT_TRUNK_COMMIT_GUARD: &str = "blocks/pre-commit-trunk-commit-guard.yaml.in";
1363
1364/// The forge integration mode's guard against a trunk push.
1365pub const PRE_COMMIT_TRUNK_PUSH_GUARD: &str = "blocks/pre-commit-trunk-push-guard.yaml.in";
1366
1367/// The header note naming what a CI sweep skips.
1368pub const PRE_COMMIT_SWEEP_SKIP: &str = "blocks/pre-commit-sweep-skip.yaml.in";
1369
1370/// The header note for the pairing whose sweep skips nothing.
1371pub const PRE_COMMIT_SWEEP_NONE: &str = "blocks/pre-commit-sweep-none.yaml.in";
1372
1373/// The header note naming the pre-integrate contract.
1374pub const PRE_COMMIT_INTEGRATE_NOTE: &str = "blocks/pre-commit-integrate-note.yaml.in";
1375
1376/// The routing block's mode line for one checkout mode.
1377#[must_use]
1378pub const fn routing_line(mode: CheckoutMode) -> &'static str {
1379    match mode {
1380        CheckoutMode::LinkedWorktree => AGENTS_LINE_WORKTREE,
1381        CheckoutMode::MainWorktree => AGENTS_LINE_BRANCHES,
1382    }
1383}
1384
1385/// One authored block this binary embeds, as text, by its embedded path.
1386///
1387/// # Errors
1388///
1389/// [`RkError::Other`] for a block this binary does not embed or one that
1390/// is not UTF-8, both defects in the binary.
1391pub fn embedded_block(path: &str) -> Result<&'static str, RkError> {
1392    let name = path.strip_prefix("blocks/").unwrap_or(path);
1393    let file = embedded::BLOCKS
1394        .get_file(name)
1395        .ok_or_else(|| anyhow::anyhow!("{path}: this binary embeds no such block"))?;
1396    std::str::from_utf8(file.contents())
1397        .map_err(|_| anyhow::anyhow!("{path}: a block is UTF-8").into())
1398}
1399
1400/// An authored block without the one final newline the repository's
1401/// hooks enforce on every file under `blocks/`; a test in
1402/// `src/embedded.rs` holds each file to exactly one.
1403#[must_use]
1404pub fn authored(text: &str) -> &str {
1405    text.strip_suffix('\n').unwrap_or(text)
1406}
1407
1408/// The one branch grammar.
1409///
1410/// The extended regular expression the landed `rk-branch-name` hook
1411/// tests, and the same anchored language `rk worktree add` validates
1412/// before creating anything. One owner by token: `concat!` cannot
1413/// interpolate a const, so [`compose_hooks`] substitutes it for the
1414/// template's `RK_BRANCH_GRAMMAR` token.
1415pub const BRANCH_GRAMMAR: &str = r"^((build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)/[A-Za-z0-9._/-]+|([0-9]+|[A-Z][A-Z0-9]+-[0-9]+)-[A-Za-z0-9._-]+|release[-/].+)$";
1416
1417/// The one commit scope shape.
1418///
1419/// A bracket expression, lowercase, admitting the digits and `_ . / -`
1420/// beside the letters, so `area/subarea` reads as one scope. It holds the
1421/// shape of a scope and never its vocabulary: the word itself is the
1422/// author's, guided by the routing block and by the repository's own
1423/// history. One owner by token: the title checks take it as
1424/// `RK_SCOPE_SHAPE` through [`render`], and `rk message --check` reads it
1425/// directly, so the desk and the forge judge one language.
1426pub const SCOPE_SHAPE: &str = "[a-z0-9._/-]+";
1427
1428/// Whether one scope matches [`SCOPE_SHAPE`].
1429///
1430/// The predicate and the pattern are one owner, so the desk's judgment
1431/// cannot drift from the forge's: `rk message --check` calls this, the
1432/// title checks render the pattern, and a test holds the two equal over
1433/// every ASCII character.
1434#[must_use]
1435pub fn scope_is_shaped(scope: &str) -> bool {
1436    !scope.is_empty()
1437        && scope.chars().all(|c| {
1438            c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '/' | '-')
1439        })
1440}
1441
1442/// The routing block from its authored template and the mode's one
1443/// orientation line.
1444///
1445/// Markers included, without a trailing newline and with its scope token
1446/// unrendered. Everything but the substituted line, the agent-boundary
1447/// line included, is byte-identical across modes.
1448#[must_use]
1449pub fn compose_routing(template: &str, line: &str, integration_line: &str) -> String {
1450    authored(template)
1451        .replacen("RK_WORKFLOW_LINE", authored(line), 1)
1452        .replacen("RK_INTEGRATION_LINE", authored(integration_line), 1)
1453}
1454
1455/// The glossary block from its authored template: markers included and
1456/// without a trailing newline. It carries no token and no mode, so the
1457/// same bytes land in every target.
1458#[must_use]
1459pub fn compose_glossary(template: &str) -> String {
1460    authored(template).to_owned()
1461}
1462
1463/// The hook block from its authored template, for one pairing of the two
1464/// Git workflow axes.
1465///
1466/// `guard` is the checkout mode's answer: `Some` is the worktree mode,
1467/// which carries the location guard, and `None` is the branches mode,
1468/// which carries no guard entry at all rather than one that reads local
1469/// state to decide whether to enforce.
1470///
1471/// `parts` is the integration mode's answer. Under forge integration the
1472/// two trunk guards render and the block is byte-identical to what every
1473/// landed target already carries. Under local integration neither
1474/// renders, because `rk integrate` writes the trunk commit and the
1475/// operator pushes the trunk, and the header carries the pre-integrate
1476/// note in their place.
1477///
1478/// The one branch grammar substitutes from [`BRANCH_GRAMMAR`]. Markers
1479/// included, without a trailing newline and with its scope token
1480/// unrendered.
1481#[must_use]
1482pub fn compose_hooks(template: &str, guard: Option<&str>, parts: &TrunkGuards) -> String {
1483    let guard = guard.map_or_else(String::new, |entry| format!("{}\n", authored(entry)));
1484    let mut skips: Vec<&str> = Vec::new();
1485    if parts.integration == Integration::Forge {
1486        skips.push("no-commit-to-branch");
1487    }
1488    if !guard.is_empty() {
1489        skips.push("rk-worktree-location");
1490    }
1491    let sweep = if skips.is_empty() {
1492        format!("{}\n", authored(parts.sweep_none))
1493    } else {
1494        format!(
1495            "{}\n",
1496            authored(parts.sweep_skip).replacen("RK_SWEEP_SKIP", &skips.join(","), 1)
1497        )
1498    };
1499    let (commit_guard, push_guard, note) = match parts.integration {
1500        Integration::Forge => (
1501            format!("{}\n", authored(parts.trunk_commit)),
1502            format!("{}\n", authored(parts.trunk_push)),
1503            String::new(),
1504        ),
1505        Integration::Local => (
1506            String::new(),
1507            String::new(),
1508            format!("{}\n", authored(parts.integrate_note)),
1509        ),
1510    };
1511    authored(template)
1512        .replacen("RK_BRANCH_GRAMMAR", BRANCH_GRAMMAR, 1)
1513        .replacen("RK_SWEEP_NOTE", &format!("{sweep}{note}"), 1)
1514        .replacen("RK_TRUNK_COMMIT_GUARD", &commit_guard, 1)
1515        .replacen("RK_WORKTREE_GUARD", &guard, 1)
1516        .replacen("RK_TRUNK_PUSH_GUARD", &push_guard, 1)
1517}
1518
1519/// The two authored guard entries the integration mode selects between,
1520/// beside the mode itself.
1521pub struct TrunkGuards<'a> {
1522    /// Which authority moves an implementation onto the trunk.
1523    pub integration: Integration,
1524    /// The `no-commit-to-branch` entry that refuses a trunk commit.
1525    pub trunk_commit: &'a str,
1526    /// The `rk-no-push-to-trunk` entry that refuses a trunk push.
1527    pub trunk_push: &'a str,
1528    /// The header note naming what a CI sweep skips.
1529    pub sweep_skip: &'a str,
1530    /// The header note for the pairing where a sweep skips nothing.
1531    pub sweep_none: &'a str,
1532    /// The header note naming the pre-integrate contract.
1533    pub integrate_note: &'a str,
1534}
1535
1536/// The routing block for one checkout mode, from this binary's embedded
1537/// templates.
1538///
1539/// # Errors
1540///
1541/// A block this binary does not embed, a defect in the binary.
1542pub fn routing_block(mode: CheckoutMode, integration: Integration) -> Result<String, RkError> {
1543    Ok(compose_routing(
1544        embedded_block(AGENTS_BLOCK)?,
1545        embedded_block(routing_line(mode))?,
1546        embedded_block(integration_line(integration))?,
1547    ))
1548}
1549
1550/// The glossary block from this binary's embedded template.
1551///
1552/// # Errors
1553///
1554/// A block this binary does not embed, a defect in the binary.
1555pub fn glossary_block() -> Result<String, RkError> {
1556    Ok(compose_glossary(embedded_block(GLOSSARY_BLOCK)?))
1557}
1558
1559/// The hook block for one checkout mode, from this binary's embedded
1560/// templates.
1561///
1562/// # Errors
1563///
1564/// A block this binary does not embed, a defect in the binary.
1565pub fn hooks_block(mode: CheckoutMode, integration: Integration) -> Result<String, RkError> {
1566    let guard = match mode {
1567        CheckoutMode::LinkedWorktree => Some(embedded_block(PRE_COMMIT_WORKTREE_GUARD)?),
1568        CheckoutMode::MainWorktree => None,
1569    };
1570    let parts = TrunkGuards {
1571        integration,
1572        trunk_commit: embedded_block(PRE_COMMIT_TRUNK_COMMIT_GUARD)?,
1573        trunk_push: embedded_block(PRE_COMMIT_TRUNK_PUSH_GUARD)?,
1574        sweep_skip: embedded_block(PRE_COMMIT_SWEEP_SKIP)?,
1575        sweep_none: embedded_block(PRE_COMMIT_SWEEP_NONE)?,
1576        integrate_note: embedded_block(PRE_COMMIT_INTEGRATE_NOTE)?,
1577    };
1578    Ok(compose_hooks(
1579        embedded_block(PRE_COMMIT_BLOCK)?,
1580        guard,
1581        &parts,
1582    ))
1583}
1584
1585/// The unrendered block for one block destination under one checkout mode,
1586/// with the embedded source paths it was composed from.
1587fn block_template(
1588    destination: &str,
1589    mode: CheckoutMode,
1590    integration: Integration,
1591) -> Result<(String, Vec<String>), RkError> {
1592    match destination {
1593        AGENTS_DESTINATION => Ok((
1594            routing_block(mode, integration)?,
1595            vec![
1596                AGENTS_BLOCK.to_owned(),
1597                routing_line(mode).to_owned(),
1598                integration_line(integration).to_owned(),
1599            ],
1600        )),
1601        GLOSSARY_DESTINATION => Ok((glossary_block()?, vec![GLOSSARY_BLOCK.to_owned()])),
1602        HOOKS_DESTINATION => {
1603            let mut sources = vec![PRE_COMMIT_BLOCK.to_owned()];
1604            if mode == CheckoutMode::LinkedWorktree {
1605                sources.push(PRE_COMMIT_WORKTREE_GUARD.to_owned());
1606            }
1607            match integration {
1608                Integration::Forge => {
1609                    sources.push(PRE_COMMIT_TRUNK_COMMIT_GUARD.to_owned());
1610                    sources.push(PRE_COMMIT_TRUNK_PUSH_GUARD.to_owned());
1611                    sources.push(PRE_COMMIT_SWEEP_SKIP.to_owned());
1612                }
1613                Integration::Local => {
1614                    if mode == CheckoutMode::LinkedWorktree {
1615                        sources.push(PRE_COMMIT_SWEEP_SKIP.to_owned());
1616                    } else {
1617                        sources.push(PRE_COMMIT_SWEEP_NONE.to_owned());
1618                    }
1619                    sources.push(PRE_COMMIT_INTEGRATE_NOTE.to_owned());
1620                }
1621            }
1622            Ok((hooks_block(mode, integration)?, sources))
1623        }
1624        other => Err(anyhow::anyhow!("{other} is not a block destination").into()),
1625    }
1626}
1627
1628/// The markers of a block destination, or `None` for a whole-file one.
1629#[must_use]
1630pub fn block_markers(destination: &str) -> Option<(&'static str, &'static str)> {
1631    match destination {
1632        AGENTS_DESTINATION | GLOSSARY_DESTINATION => Some((BLOCK_BEGIN, BLOCK_END)),
1633        HOOKS_DESTINATION => Some((HOOKS_BEGIN, HOOKS_END)),
1634        _ => None,
1635    }
1636}
1637
1638/// The marked block inside a document, markers included, or `None` where
1639/// the text carries no complete block.
1640#[must_use]
1641pub fn extract_block<'a>(text: &'a str, begin: &str, end: &str) -> Option<&'a str> {
1642    let start = text.find(begin)?;
1643    let stop = text[start..].find(end)? + start + end.len();
1644    Some(&text[start..stop])
1645}
1646
1647/// The whole document's bytes after splicing a marked block into it.
1648///
1649/// A fresh file where none exists, the block replaced in place where one
1650/// is marked, appended after the target's own content otherwise:
1651/// release-kit owns the lines inside the markers, not the document. Both
1652/// markdown destinations take this shape, `AGENTS.md` and the glossary.
1653#[must_use]
1654pub fn splice_marked_block(existing: Option<&[u8]>, block: &str) -> Vec<u8> {
1655    let block = block.as_bytes();
1656    let Some(text) = existing else {
1657        return [block, b"\n"].concat();
1658    };
1659    // Bytes, never text: the document belongs to the target and a decode
1660    // that replaces one invalid sequence rewrites a byte outside the
1661    // markers, which is the one thing a block destination never does.
1662    if let Some(start) = find(text, BLOCK_BEGIN.as_bytes())
1663        && let Some(offset) = find(&text[start..], BLOCK_END.as_bytes())
1664    {
1665        let stop = start + offset + BLOCK_END.len();
1666        return [&text[..start], block, &text[stop..]].concat();
1667    }
1668    // Appending keeps every byte the target wrote, trailing blank lines
1669    // and an absent final newline included. The only addition is the
1670    // separator that opens the block's own line.
1671    let mut out = Vec::with_capacity(text.len() + block.len() + 3);
1672    out.extend_from_slice(text);
1673    if !text.ends_with(b"\n") {
1674        out.push(b'\n');
1675    }
1676    out.push(b'\n');
1677    out.extend_from_slice(block);
1678    out.push(b'\n');
1679    out
1680}
1681
1682/// The whole `.pre-commit-config.yaml` content after splicing the
1683/// rendered hook block.
1684///
1685/// A fresh file carries the hook-types key, the `repos:` key, and the
1686/// block; a marked file takes the block in place; an unmarked file takes
1687/// it directly under its `repos:` line, above the target's own hooks. An
1688/// unmarked file with no `repos:` line is refused by name: the block's
1689/// entries are list items and have nowhere honest to go.
1690///
1691/// # Errors
1692///
1693/// The reason the block has no place, for the caller's refusal to carry.
1694pub fn splice_hooks_block(existing: Option<&str>, block: &str) -> Result<String, String> {
1695    let Some(text) = existing else {
1696        return Ok(format!("{HOOK_TYPES_LINE}\n\nrepos:\n{block}\n"));
1697    };
1698    if let Some(defect) = hooks_marker_defect(text) {
1699        return Err(defect);
1700    }
1701    if let Some(found) = extract_block(text, HOOKS_BEGIN, HOOKS_END) {
1702        return Ok(text.replacen(found, block, 1));
1703    }
1704    let mut out = String::with_capacity(text.len() + block.len() + 1);
1705    let mut placed = false;
1706    for line in text.split_inclusive('\n') {
1707        out.push_str(line);
1708        if !placed && line.trim_end() == "repos:" {
1709            if !out.ends_with('\n') {
1710                out.push('\n');
1711            }
1712            out.push_str(block);
1713            out.push('\n');
1714            placed = true;
1715        }
1716    }
1717    if placed {
1718        Ok(out)
1719    } else {
1720        Err(format!(
1721            "{HOOKS_DESTINATION} exists with no repos: line, so the hook block has nowhere to land"
1722        ))
1723    }
1724}
1725
1726/// The one definition of an ill-formed block document, shared by every
1727/// splice and every reader that judges one: `None` for a whole-file
1728/// destination or a well-formed document.
1729///
1730/// Ownership must be unambiguous: exactly one begin marker paired with
1731/// exactly one end marker after it, or none of either. A second begin is
1732/// a second block, which for the hook file pre-commit would still run,
1733/// and a marker without its pair, or an end before its begin, is a block
1734/// whose extent nothing can state.
1735#[must_use]
1736pub fn marker_defect(destination: &str, text: &str) -> Option<String> {
1737    let (begin, end) = block_markers(destination)?;
1738    let begins = text.matches(begin).count();
1739    let ends = text.matches(end).count();
1740    if begins > 1 || ends > 1 {
1741        return Some(format!(
1742            "{destination} carries more than one release-kit marker pair; release-kit owns exactly one block"
1743        ));
1744    }
1745    match (text.find(begin), text.find(end)) {
1746        (Some(begin), Some(end)) if end > begin => None,
1747        (None, None) => None,
1748        _ => Some(format!(
1749            "{destination} carries an unmatched or misordered release-kit marker, so the block's extent is ambiguous"
1750        )),
1751    }
1752}
1753
1754/// [`marker_defect`] for the hook file, the destination whose entries
1755/// execute.
1756#[must_use]
1757pub fn hooks_marker_defect(text: &str) -> Option<String> {
1758    marker_defect(HOOKS_DESTINATION, text)
1759}
1760
1761/// The complete proposed document for one block destination: the
1762/// rendered `region` spliced into the `existing` document the evidence
1763/// carries, or the reason the document offers it no place.
1764fn propose_document(
1765    destination: &str,
1766    existing: Option<&[u8]>,
1767    region: &[u8],
1768) -> Result<Vec<u8>, String> {
1769    // The block is release-kit's own text. The document is the target's
1770    // bytes: the markdown splice works on them directly, and the marker
1771    // judgment decodes a copy only to count ASCII markers, which a
1772    // replacement character neither creates nor hides.
1773    let block = String::from_utf8_lossy(region).into_owned();
1774    if let Some(text) = existing
1775        && let Some(defect) = marker_defect(destination, &String::from_utf8_lossy(text))
1776    {
1777        return Err(defect);
1778    }
1779    if destination == HOOKS_DESTINATION {
1780        // The hook splice is line-based text, so a document that is not
1781        // UTF-8 has no honest place for the block: a lossy decode would
1782        // rewrite a byte outside the markers, which a region never does.
1783        let text = match existing {
1784            None => None,
1785            Some(bytes) => Some(std::str::from_utf8(bytes).map_err(|_| {
1786                format!(
1787                    "{destination} is not UTF-8, so the hook block has nowhere to land without rewriting the target's bytes"
1788                )
1789            })?),
1790        };
1791        return splice_hooks_block(text, &block).map(String::into_bytes);
1792    }
1793    Ok(splice_marked_block(existing, &block))
1794}
1795
1796/// Why the whole Nix capability stays out of a landing, or `None` where
1797/// the target's crate shape supports the seed.
1798///
1799/// The gate holds every structural prerequisite the seed relies on, not
1800/// only evaluation: the package expression reads `Cargo.toml` through
1801/// `importTOML` and throws without `../Cargo.lock`, and the seed flake's
1802/// smoke check runs the crate's binary, which only an implicit
1803/// `src/main.rs` or an explicit `[[bin]]` entry produces. A shape
1804/// missing any of these would land files that fail on their first
1805/// evaluation or first check, so the landing reports the smaller product
1806/// with the missing piece named instead.
1807#[must_use]
1808pub fn nix_unsupported_shape(shape: &CrateShape) -> Option<String> {
1809    let Some(text) = shape.cargo_toml.as_deref() else {
1810        return Some(
1811            "the target has no readable Cargo.toml, which the seeded package expression reads; no Nix file lands".to_owned(),
1812        );
1813    };
1814    let Ok(table) = text.parse::<toml::Table>() else {
1815        return Some(
1816            "the target's Cargo.toml does not parse, and the seeded package expression reads it; no Nix file lands".to_owned(),
1817        );
1818    };
1819    if !table.contains_key("package") {
1820        return Some(
1821            "the target's Cargo.toml has no [package] table; the seed supports a single crate, so no Nix file lands".to_owned(),
1822        );
1823    }
1824    if !shape.cargo_lock {
1825        return Some(
1826            "the target has no Cargo.lock, which the seeded package expression builds from; commit one, then opt in".to_owned(),
1827        );
1828    }
1829    let implicit_bin = shape.main_rs
1830        && table
1831            .get("package")
1832            .and_then(toml::Value::as_table)
1833            .and_then(|package| package.get("autobins"))
1834            .and_then(toml::Value::as_bool)
1835            != Some(false);
1836    let explicit_bins = table.get("bin").and_then(toml::Value::as_array);
1837    if explicit_bins.is_none() && !implicit_bin {
1838        return Some(
1839            "the target declares no binary — no effective src/main.rs and no [[bin]] entry — and the seed flake's smoke check runs one; no Nix file lands".to_owned(),
1840        );
1841    }
1842    // The seed's mainProgram is the first [[bin]] entry; one whose
1843    // required-features a default build does not enable produces no
1844    // executable, so the smoke check would fail on a green landing. A
1845    // requirement the default feature set covers builds normally and
1846    // passes.
1847    if let Some(bins) = explicit_bins {
1848        let required = bins
1849            .first()
1850            .and_then(toml::Value::as_table)
1851            .and_then(|bin| bin.get("required-features"))
1852            .and_then(toml::Value::as_array);
1853        if let Some(required) = required {
1854            let enabled = default_features(&table);
1855            let missing = required
1856                .iter()
1857                .filter_map(toml::Value::as_str)
1858                .any(|feature| !enabled.contains(feature));
1859            if missing {
1860                return Some(
1861                    "the target's first [[bin]] entry requires features a default build does not enable; no Nix file lands".to_owned(),
1862                );
1863            }
1864        }
1865    }
1866    None
1867}
1868
1869/// Whether any feature's list carries a `dep:name` edge, which is what
1870/// suppresses the optional dependency's implicit same-named feature.
1871fn dep_edge_suppresses(features: &toml::Table, name: &str) -> bool {
1872    let edge = format!("dep:{name}");
1873    features.values().any(|list| {
1874        list.as_array().is_some_and(|entries| {
1875            entries
1876                .iter()
1877                .filter_map(toml::Value::as_str)
1878                .any(|entry| entry == edge)
1879        })
1880    })
1881}
1882
1883/// Whether `name` is declared an optional dependency, in any of the
1884/// dependency tables a binary's build reads.
1885fn is_optional_dependency(table: &toml::Table, name: &str) -> bool {
1886    ["dependencies", "build-dependencies"]
1887        .iter()
1888        .any(|section| {
1889            table
1890                .get(*section)
1891                .and_then(toml::Value::as_table)
1892                .and_then(|dependencies| dependencies.get(name))
1893                .and_then(toml::Value::as_table)
1894                .and_then(|dependency| dependency.get("optional"))
1895                .and_then(toml::Value::as_bool)
1896                == Some(true)
1897        })
1898}
1899
1900/// The features a default build enables: the `default` feature resolved
1901/// through the `[features]` table's own enables, an approximation of
1902/// cargo's default resolution for the documented supported shapes, erring
1903/// toward withholding where the semantics run deeper. Dependency forms,
1904/// `dep:name` and weak `name?/feature`, are not feature names here and are
1905/// skipped; the closure is bounded by the table's size.
1906fn default_features(table: &toml::Table) -> std::collections::BTreeSet<String> {
1907    let Some(features) = table.get("features").and_then(toml::Value::as_table) else {
1908        return std::collections::BTreeSet::new();
1909    };
1910    let mut enabled = std::collections::BTreeSet::new();
1911    let mut queue = vec!["default".to_owned()];
1912    while let Some(name) = queue.pop() {
1913        if !enabled.insert(name.clone()) {
1914            continue;
1915        }
1916        if let Some(implies) = features.get(&name).and_then(toml::Value::as_array) {
1917            for implied in implies.iter().filter_map(toml::Value::as_str) {
1918                if implied.starts_with("dep:") || implied.contains("?/") {
1919                    // `dep:name` enables the dependency without a feature
1920                    // of this crate; a weak `name?/feature` edge enables
1921                    // nothing by itself.
1922                    continue;
1923                }
1924                if let Some((package, _)) = implied.split_once('/') {
1925                    // A strong `name/feature` edge activates this crate's
1926                    // same-named feature only for an optional dependency,
1927                    // and only where that feature exists: declared
1928                    // explicitly, or implicit and not suppressed by a
1929                    // `dep:` edge anywhere in the table. A non-optional
1930                    // dependency's edge enables a feature of the
1931                    // dependency and nothing of this crate.
1932                    let feature_exists =
1933                        features.contains_key(package) || !dep_edge_suppresses(features, package);
1934                    if is_optional_dependency(table, package) && feature_exists {
1935                        queue.push(package.to_owned());
1936                    }
1937                } else {
1938                    queue.push(implied.to_owned());
1939                }
1940            }
1941        }
1942    }
1943    enabled
1944}
1945
1946/// Why the flake half of the Nix capability stays out of this landing, or
1947/// `None` where the pair lands whole.
1948///
1949/// The pair is all-or-nothing: a target that already carries a
1950/// `flake.nix` or `flake.lock` of its own keeps its pair, because a seed
1951/// lock beside a foreign flake describes the wrong input graph. A pair
1952/// the record names is release-kit's own landing and is never withheld.
1953#[must_use]
1954pub fn flake_pair_withheld(
1955    flake_recorded: bool,
1956    flake_nix_present: bool,
1957    flake_lock_present: bool,
1958) -> Option<String> {
1959    if flake_recorded {
1960        return None;
1961    }
1962    let present: Vec<&str> = [
1963        ("flake.nix", flake_nix_present),
1964        ("flake.lock", flake_lock_present),
1965    ]
1966    .into_iter()
1967    .filter_map(|(name, present)| present.then_some(name))
1968    .collect();
1969    if present.is_empty() {
1970        return None;
1971    }
1972    Some(format!(
1973        "the target already carries {}; its flake pair stays its own",
1974        present.join(" and ")
1975    ))
1976}
1977
1978/// The Nix destinations an opted-in landing withholds at this target, with
1979/// the one reason, or `None` where the capability lands whole or `nix` is
1980/// off.
1981///
1982/// An unsupported crate shape names the whole capability, and a flake
1983/// pair of the target's own names the pair while the seeded package
1984/// expression still lands. Every landing verb shares this one judgment, so
1985/// a stage, an apply, an upgrade, and an adoption all withhold
1986/// identically.
1987#[must_use]
1988pub fn nix_withholding(
1989    nix: bool,
1990    evidence: &TargetEvidence,
1991) -> Option<(&'static [&'static str], String)> {
1992    if !nix {
1993        return None;
1994    }
1995    if let Some(reason) = nix_unsupported_shape(&evidence.crate_shape) {
1996        return Some((&NIX_DESTINATIONS[..], reason));
1997    }
1998    flake_pair_withheld(
1999        evidence.flake_recorded,
2000        evidence.flake_nix_present,
2001        evidence.flake_lock_present,
2002    )
2003    .map(|reason| (&NIX_WITHHOLDABLE[..], reason))
2004}
2005
2006#[cfg(test)]
2007mod tests {
2008    use super::{
2009        AGENTS_DESTINATION, BLOCK_BEGIN, BLOCK_DESTINATIONS, BLOCK_END, Candidate, Collision,
2010        CrateShape, GLOSSARY_DESTINATION, HOOK_TYPES_LINE, HOOKS_BEGIN, HOOKS_DESTINATION,
2011        HOOKS_END, Placement, Projection, ProjectionInput, TargetEvidence, extract_block,
2012    };
2013    use crate::landing::{Params, Style};
2014
2015    /// A supported single-crate shape, so nothing is withheld.
2016    fn supported_shape() -> CrateShape {
2017        CrateShape {
2018            cargo_toml: Some("[package]\nname = \"widget\"\nversion = \"0.1.0\"\n".to_owned()),
2019            cargo_lock: true,
2020            main_rs: true,
2021        }
2022    }
2023
2024    fn input(evidence: TargetEvidence) -> ProjectionInput {
2025        let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2026        params.set_nix_for_test(true);
2027        ProjectionInput { params, evidence }
2028    }
2029
2030    fn compute(evidence: TargetEvidence) -> Projection {
2031        Projection::compute(&input(evidence)).expect("the embedded pair projects")
2032    }
2033
2034    fn candidate<'a>(projection: &'a Projection, destination: &str) -> &'a Candidate {
2035        projection
2036            .candidates
2037            .iter()
2038            .find(|candidate| candidate.destination == destination)
2039            .expect("the destination projects")
2040    }
2041
2042    /// The bytes of a document outside its one marked region.
2043    fn outside(bytes: &[u8], begin: &str, end: &str) -> (Vec<u8>, Vec<u8>) {
2044        let text = String::from_utf8_lossy(bytes);
2045        let start = text.find(begin).expect("the begin marker is present");
2046        let stop = text[start..].find(end).expect("the end marker is present") + start + end.len();
2047        (bytes[..start].to_vec(), bytes[stop..].to_vec())
2048    }
2049
2050    #[test]
2051    fn equal_projection_inputs_yield_byte_identical_projections() {
2052        let mut documents = std::collections::BTreeMap::new();
2053        documents.insert(
2054            AGENTS_DESTINATION.to_owned(),
2055            b"# Widget\n\nOwn rules.\n".to_vec(),
2056        );
2057        let evidence = TargetEvidence {
2058            documents,
2059            crate_shape: supported_shape(),
2060            ..TargetEvidence::default()
2061        };
2062        let first = input(evidence.clone());
2063        let second = input(evidence);
2064        assert_eq!(first, second, "the inputs are values and compare equal");
2065        let a = Projection::compute(&first).expect("the pair projects");
2066        let b = Projection::compute(&second).expect("the pair projects");
2067        assert_eq!(a.candidates.len(), b.candidates.len());
2068        for (x, y) in a.candidates.iter().zip(&b.candidates) {
2069            assert_eq!(x.destination, y.destination);
2070            assert_eq!(x.kind, y.kind);
2071            assert_eq!(x.placement, y.placement);
2072            assert_eq!(x.bytes, y.bytes, "{}", x.destination);
2073            assert_eq!(x.region, y.region, "{}", x.destination);
2074            assert_eq!(x.sources, y.sources, "{}", x.destination);
2075        }
2076        assert_eq!(a, b);
2077        let destinations: Vec<&str> = a
2078            .candidates
2079            .iter()
2080            .map(|candidate| candidate.destination.as_str())
2081            .collect();
2082        let mut sorted = destinations.clone();
2083        sorted.sort_unstable();
2084        assert_eq!(destinations, sorted, "candidates sort by destination");
2085        assert!(a.omissions.is_empty(), "{:?}", a.omissions);
2086        assert!(a.collisions.is_empty(), "{:?}", a.collisions);
2087    }
2088
2089    /// The Scorecard destination is classified, gated by its parameter
2090    /// alone, and rendered: the pure projection answers the capability
2091    /// with no target read and no forge call.
2092    #[test]
2093    fn the_scorecard_destination_projects_only_under_the_opt_in() {
2094        use super::{Kind, SCORECARD_DESTINATIONS, kind_of};
2095        let destination = SCORECARD_DESTINATIONS[0];
2096        assert_eq!(kind_of(destination), Some(Kind::Rendered));
2097
2098        let project = |scorecard: bool| {
2099            let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2100            params.set_scorecard_for_test(scorecard);
2101            Projection::compute(&ProjectionInput {
2102                params,
2103                evidence: TargetEvidence::default(),
2104            })
2105            .expect("the embedded pair projects")
2106        };
2107
2108        let off = project(false);
2109        assert!(
2110            !off.candidates
2111                .iter()
2112                .any(|candidate| candidate.destination == destination),
2113            "off by default, and an absent candidate is no omission"
2114        );
2115        assert!(off.omissions.is_empty(), "{:?}", off.omissions);
2116
2117        let on = project(true);
2118        let candidate = candidate(&on, destination);
2119        assert_eq!(candidate.kind, Kind::Rendered);
2120        assert_eq!(candidate.placement, Placement::Whole);
2121        let text = String::from_utf8_lossy(&candidate.bytes);
2122        assert!(!text.contains("RK_"), "a token survived: {text}");
2123    }
2124
2125    /// The licence judgment over the expression forms a crate manifest
2126    /// uses: every reader must obtain an OSI-approved grant, every licence
2127    /// named must be one this release recognizes, and a malformed expression
2128    /// states no terms at all.
2129    #[test]
2130    fn the_licence_judgment_reads_what_every_reader_obtains() {
2131        use super::licence_states_an_open_source_codebase as approved;
2132        for expression in [
2133            "MIT",
2134            "Apache-2.0",
2135            "MIT OR Apache-2.0",
2136            "MIT AND Apache-2.0",
2137            "(MIT OR Apache-2.0) AND ISC",
2138            "Apache-2.0 WITH LLVM-exception OR MIT",
2139            "GPL-3.0+",
2140        ] {
2141            assert!(approved(expression), "{expression} is OSI-approved");
2142        }
2143        // A conjunction hands the reader every term at once, so a Creative
2144        // Commons term beside an OSI-approved licence adds an obligation over
2145        // prose and withdraws no grant over code. This is what a project that
2146        // licenses its source apart from its documentation declares.
2147        for expression in [
2148            "MIT AND CC-BY-4.0",
2149            "CC-BY-4.0 AND MIT",
2150            "MIT AND (CC-BY-4.0 OR CC-BY-SA-4.0)",
2151            "(MIT OR CC-BY-4.0) AND MIT",
2152            "MIT OR Apache-2.0 AND CC-BY-4.0",
2153            "Apache-2.0 WITH LLVM-exception AND CC-BY-SA-3.0",
2154        ] {
2155            assert!(approved(expression), "{expression} states open source");
2156        }
2157        for expression in [
2158            "",
2159            "   ",
2160            "LicenseRef-proprietary",
2161            "MIT AND LicenseRef-proprietary",
2162            "SEE LICENSE IN COPYING",
2163            "CC-BY-4.0",
2164            "DocumentRef-spdx:LicenseRef-proprietary",
2165        ] {
2166            assert!(!approved(expression), "{expression} is not recognized");
2167        }
2168        // A disjunction offers the reader a choice, so an arm that grants no
2169        // code licence is an arm the reader may take. `CC0-1.0` is refused
2170        // outright: it is absent from both lists, and its own case belongs to
2171        // a question these lists do not answer.
2172        for expression in [
2173            "MIT OR CC-BY-4.0",
2174            "CC-BY-4.0 AND CC-BY-SA-4.0",
2175            "CC-BY-4.0 AND LicenseRef-proprietary",
2176            "CC0-1.0",
2177            "MIT AND CC-BY-4.0 AND LicenseRef-proprietary",
2178        ] {
2179            assert!(!approved(expression), "{expression} grants no code terms");
2180        }
2181        // The precedence witness. SPDX binds AND tighter than OR, so this
2182        // offers the reader `CC-BY-4.0` alone. Read with the operators
2183        // flattened into one left fold it would pass, which is why the
2184        // grammar carries the two levels rather than one.
2185        assert!(
2186            !approved("CC-BY-4.0 OR CC-BY-SA-4.0 AND MIT"),
2187            "AND binds tighter than OR"
2188        );
2189    }
2190
2191    /// The same judgment against the SPDX grammar and its matching rules:
2192    /// what parses, what does not, which casing an identifier may carry,
2193    /// which casing an operator may not, and which operand `WITH` takes. An
2194    /// expression that states no complete offer is refused rather than read
2195    /// for the identifiers it happens to carry.
2196    #[test]
2197    fn the_licence_judgment_holds_the_expression_to_the_spdx_grammar() {
2198        use super::licence_states_an_open_source_codebase as approved;
2199        // A malformed expression is refused rather than read for the
2200        // identifiers it happens to carry. Each of these names at least one
2201        // approved licence and states no complete offer, and accepting any
2202        // of them would land a workflow whose terms nothing established.
2203        for expression in [
2204            "MIT OR",
2205            "OR MIT",
2206            "MIT AND",
2207            "MIT WITH",
2208            "WITH LLVM-exception",
2209            "(MIT",
2210            "MIT)",
2211            "MIT Apache-2.0",
2212            "()",
2213            "(MIT OR Apache-2.0",
2214            "MIT OR (Apache-2.0",
2215            "MIT OR ()",
2216            "AND",
2217            "(",
2218            ")",
2219            "MIT WITH AND ISC",
2220            "MIT OR OR ISC",
2221            "MIT @ Apache-2.0",
2222        ] {
2223            assert!(!approved(expression), "{expression} is malformed");
2224        }
2225        // Well-formed nesting and a nested exception still read.
2226        for expression in [
2227            "MIT AND (Apache-2.0 OR ISC)",
2228            "((MIT))",
2229            "Apache-2.0 WITH LLVM-exception AND ISC",
2230            "(Apache-2.0 WITH LLVM-exception)",
2231        ] {
2232            assert!(approved(expression), "{expression} is well formed");
2233        }
2234        // SPDX states an identifier "should be matched in a case-insensitive
2235        // manner", and cargo accepts `license = "mit"` without complaint, so a
2236        // real crate can carry any casing and none of these may read as
2237        // unrecognized.
2238        for expression in [
2239            "mit",
2240            "MiT",
2241            "apache-2.0 OR mit",
2242            "APACHE-2.0 WITH llvm-exception",
2243        ] {
2244            assert!(
2245                approved(expression),
2246                "{expression} names an approved licence"
2247            );
2248        }
2249        // The operators are the other half of the same sentence: SPDX matches
2250        // them case-sensitively, so a lowercase one is not an operator and the
2251        // expression it appears in is malformed.
2252        for expression in [
2253            "MIT or Apache-2.0",
2254            "MIT and Apache-2.0",
2255            "MIT with LLVM-exception",
2256        ] {
2257            assert!(!approved(expression), "{expression} carries no operator");
2258        }
2259        // The operand after WITH must be an exception identifier. One this
2260        // release does not recognize leaves the expression malformed, so the
2261        // licence goes unread rather than being taken from the left operand.
2262        for expression in [
2263            "MIT WITH definitely-not-an-spdx-exception",
2264            "MIT WITH MIT",
2265            "MIT WITH Apache-2.0",
2266        ] {
2267            assert!(!approved(expression), "{expression} names no exception");
2268        }
2269        // The register is carried whole, not sampled. A subset refuses a real
2270        // crate: this one names an exception older than the version a sampled
2271        // list would have kept.
2272        for expression in [
2273            "GPL-2.0-only WITH GCC-exception-2.0",
2274            "GPL-2.0-or-later WITH Classpath-exception-2.0",
2275            "Apache-2.0 WITH Swift-exception",
2276            "GPL-3.0-only WITH Autoconf-exception-generic",
2277        ] {
2278            assert!(approved(expression), "{expression} names a real exception");
2279        }
2280    }
2281
2282    /// The compatibility question has one owner, and its answer is the
2283    /// catalog's unavailable reason: a receipt reaches `rk status` through
2284    /// `from_record`, which cannot fail, so a provider whose pair ships
2285    /// nothing is named rather than read as clean. It is a report about the
2286    /// pair, not a fault in the target, so nothing refuses on it.
2287    #[test]
2288    fn a_recorded_provider_its_pair_cannot_run_is_named() {
2289        use super::{Provider, code_scanning_incompatibility};
2290
2291        assert!(code_scanning_incompatibility(None, Some("bash"), Some("gitlab")).is_none());
2292        assert!(
2293            code_scanning_incompatibility(Some(Provider::Semgrep), Some("rust"), Some("gitlab"))
2294                .is_none()
2295        );
2296        assert!(
2297            code_scanning_incompatibility(Some(Provider::CodeQl), Some("rust"), Some("github"))
2298                .is_none()
2299        );
2300
2301        let bash =
2302            code_scanning_incompatibility(Some(Provider::Semgrep), Some("bash"), Some("github"))
2303                .expect("a binding with no scanner is named");
2304        assert!(bash.contains("bash binding"), "{bash}");
2305        let gitlab =
2306            code_scanning_incompatibility(Some(Provider::CodeQl), Some("rust"), Some("gitlab"))
2307                .expect("codeql on gitlab is named");
2308        assert!(gitlab.contains("codeql"), "{gitlab}");
2309        let release_less =
2310            code_scanning_incompatibility(Some(Provider::Semgrep), None, Some("github"))
2311                .expect("no driver is named");
2312        assert!(
2313            release_less.contains("no automatic release driver"),
2314            "{release_less}"
2315        );
2316
2317        // The projection carries the same reason, so a record-only reader sees
2318        // it without going through resolution.
2319        let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2320        params.set_code_scanning_for_test(Some(Provider::Semgrep));
2321        let clean = Projection::compute(&ProjectionInput {
2322            params: params.clone(),
2323            evidence: TargetEvidence::default(),
2324        })
2325        .expect("the pair projects");
2326        assert!(
2327            clean.record_defects.is_empty(),
2328            "{:?}",
2329            clean.record_defects
2330        );
2331    }
2332
2333    /// The code scanning capability: the provider gates its own destination,
2334    /// semgrep carries no licence condition, and codeql's condition reads the
2335    /// crate's declared licence without touching the filesystem.
2336    #[test]
2337    fn the_code_scanning_destinations_follow_the_recorded_provider() {
2338        use super::{
2339            CODE_SCANNING_DESTINATIONS, Kind, Provider, code_scanning_licence_refusal, kind_of,
2340        };
2341        for (destination, _) in CODE_SCANNING_DESTINATIONS {
2342            assert_eq!(kind_of(destination), Some(Kind::Rendered), "{destination}");
2343        }
2344
2345        let project = |provider: Option<Provider>| {
2346            let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2347            params.set_code_scanning_for_test(provider);
2348            Projection::compute(&ProjectionInput {
2349                params,
2350                evidence: TargetEvidence {
2351                    crate_shape: CrateShape {
2352                        cargo_toml: Some(
2353                            "[package]\nname = \"widget\"\nlicense = \"MIT\"\n".to_owned(),
2354                        ),
2355                        ..CrateShape::default()
2356                    },
2357                    ..TargetEvidence::default()
2358                },
2359            })
2360            .expect("the embedded pair projects")
2361        };
2362        let landed = |projection: &Projection, destination: &str| {
2363            projection
2364                .candidates
2365                .iter()
2366                .any(|candidate| candidate.destination == destination)
2367        };
2368
2369        let off = project(None);
2370        for (destination, _) in CODE_SCANNING_DESTINATIONS {
2371            assert!(!landed(&off, destination), "{destination}");
2372        }
2373        assert!(off.licence_refusal.is_none());
2374
2375        let codeql = project(Some(Provider::CodeQl));
2376        assert!(landed(
2377            &codeql,
2378            ".github/workflows/code-scanning-codeql.yml"
2379        ));
2380        assert!(!landed(
2381            &codeql,
2382            ".github/workflows/code-scanning-semgrep.yml"
2383        ));
2384        assert!(codeql.licence_refusal.is_none(), "MIT satisfies the terms");
2385
2386        let semgrep = project(Some(Provider::Semgrep));
2387        assert!(landed(
2388            &semgrep,
2389            ".github/workflows/code-scanning-semgrep.yml"
2390        ));
2391        assert!(!landed(
2392            &semgrep,
2393            ".github/workflows/code-scanning-codeql.yml"
2394        ));
2395
2396        // Semgrep carries no condition, whatever the licence says.
2397        let proprietary = CrateShape {
2398            cargo_toml: Some("[package]\nlicense = \"LicenseRef-proprietary\"\n".to_owned()),
2399            ..CrateShape::default()
2400        };
2401        assert!(
2402            code_scanning_licence_refusal(Some(Provider::Semgrep), Some("rust"), &proprietary)
2403                .is_none()
2404        );
2405        let refusal =
2406            code_scanning_licence_refusal(Some(Provider::CodeQl), Some("rust"), &proprietary)
2407                .expect("codeql refuses a licence its terms do not cover");
2408        assert!(refusal.contains("LicenseRef-proprietary"), "{refusal}");
2409        assert!(refusal.contains("semgrep"), "{refusal}");
2410        // A binding whose licence field this release does not read refuses
2411        // rather than assuming the terms are met.
2412        let bash =
2413            code_scanning_licence_refusal(Some(Provider::CodeQl), Some("bash"), &proprietary)
2414                .expect("an unread binding refuses");
2415        assert!(bash.contains("bash binding"), "{bash}");
2416    }
2417
2418    /// The pure boundary, held by a source scan over this file's
2419    /// production code: everything above the first `#[cfg(test)]`, with
2420    /// comment lines skipped. The evidence gathering that reads a target
2421    /// lives in `src/projection/evidence.rs`, which this scan does not
2422    /// cover on purpose.
2423    #[test]
2424    fn the_projection_performs_no_filesystem_git_environment_clock_registry_or_network_read() {
2425        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/projection.rs");
2426        let text = std::fs::read_to_string(&path).expect("the source reads");
2427        let production = text.split("#[cfg(test)]").next().unwrap_or("");
2428        let needles = [
2429            "std::fs",
2430            "std::env",
2431            "std::process",
2432            "std::time",
2433            "SystemTime",
2434            "Instant",
2435            "std::net",
2436            "Command::new",
2437            "registry::",
2438            "curl",
2439            "reqwest",
2440            "blob(",
2441        ];
2442        let mut hits = Vec::new();
2443        for (index, line) in production.lines().enumerate() {
2444            if line.trim_start().starts_with("//") {
2445                continue;
2446            }
2447            for needle in needles {
2448                if line.contains(needle) {
2449                    hits.push(format!("src/projection.rs:{}: {needle}", index + 1));
2450                }
2451            }
2452        }
2453        assert!(
2454            hits.is_empty(),
2455            "the projection reads beyond its inputs: {hits:?}"
2456        );
2457    }
2458
2459    #[test]
2460    #[allow(
2461        clippy::too_many_lines,
2462        reason = "one test walks the three marked destinations and the three unmarked shapes"
2463    )]
2464    fn marked_region_projection_preserves_every_target_byte_outside_the_markers() {
2465        let agents_before = "# Widget\n\nOperator prose above.\n\n";
2466        let agents_after = "\n\n## Our rules\n\nOperator prose below.   \n";
2467        let glossary_before = "# Glossary\n\n- `spike` is a throwaway branch.\n\n";
2468        let glossary_after = "\n\n## More terms\n\n- `own` is ours.";
2469        let hooks_before = "default_install_hook_types: [pre-commit]\n\nrepos:\n";
2470        let hooks_after =
2471            "\n  - repo: https://example.com/own\n    rev: v1\n    hooks:\n      - id: own\n";
2472        let stale = |begin: &str, end: &str| format!("{begin}\nstale block\n{end}");
2473        let mut documents = std::collections::BTreeMap::new();
2474        documents.insert(
2475            AGENTS_DESTINATION.to_owned(),
2476            format!(
2477                "{agents_before}{}{agents_after}",
2478                stale(BLOCK_BEGIN, BLOCK_END)
2479            )
2480            .into_bytes(),
2481        );
2482        documents.insert(
2483            GLOSSARY_DESTINATION.to_owned(),
2484            format!(
2485                "{glossary_before}{}{glossary_after}",
2486                stale(BLOCK_BEGIN, BLOCK_END)
2487            )
2488            .into_bytes(),
2489        );
2490        documents.insert(
2491            HOOKS_DESTINATION.to_owned(),
2492            format!(
2493                "{hooks_before}{}{hooks_after}",
2494                stale(HOOKS_BEGIN, HOOKS_END)
2495            )
2496            .into_bytes(),
2497        );
2498        let projection = compute(TargetEvidence {
2499            documents: documents.clone(),
2500            crate_shape: supported_shape(),
2501            ..TargetEvidence::default()
2502        });
2503        assert!(
2504            projection.collisions.is_empty(),
2505            "{:?}",
2506            projection.collisions
2507        );
2508        for (destination, before, after) in [
2509            (AGENTS_DESTINATION, agents_before, agents_after),
2510            (GLOSSARY_DESTINATION, glossary_before, glossary_after),
2511            (HOOKS_DESTINATION, hooks_before, hooks_after),
2512        ] {
2513            let candidate = candidate(&projection, destination);
2514            let Placement::Region { begin, end } = candidate.placement else {
2515                panic!("{destination} is a region");
2516            };
2517            let region = candidate
2518                .region
2519                .as_deref()
2520                .expect("a region carries its block");
2521            let (head, tail) = outside(&candidate.bytes, begin, end);
2522            assert_eq!(
2523                head,
2524                before.as_bytes(),
2525                "{destination}: bytes before the markers"
2526            );
2527            assert_eq!(
2528                tail,
2529                after.as_bytes(),
2530                "{destination}: bytes after the markers"
2531            );
2532            let inside = &candidate.bytes[head.len()..candidate.bytes.len() - tail.len()];
2533            assert_eq!(
2534                inside, region,
2535                "{destination}: the region is the rendered block"
2536            );
2537            let (existing_head, existing_tail) = outside(&documents[destination], begin, end);
2538            assert_eq!(head, existing_head);
2539            assert_eq!(tail, existing_tail);
2540        }
2541
2542        // Unmarked documents: the hook block lands under the owning key,
2543        // the routing block appends, and an absent file yields a fresh
2544        // document.
2545        let own_hooks =
2546            "repos:\n  - repo: https://example.com/own\n    rev: v1\n    hooks:\n      - id: own\n";
2547        let own_agents = "# Widget\n\nOwn rules.";
2548        let mut documents = std::collections::BTreeMap::new();
2549        documents.insert(HOOKS_DESTINATION.to_owned(), own_hooks.as_bytes().to_vec());
2550        documents.insert(
2551            AGENTS_DESTINATION.to_owned(),
2552            own_agents.as_bytes().to_vec(),
2553        );
2554        let projection = compute(TargetEvidence {
2555            documents,
2556            crate_shape: supported_shape(),
2557            ..TargetEvidence::default()
2558        });
2559        assert!(
2560            projection.collisions.is_empty(),
2561            "{:?}",
2562            projection.collisions
2563        );
2564        let hooks = candidate(&projection, HOOKS_DESTINATION);
2565        let hooks_text = String::from_utf8_lossy(&hooks.bytes);
2566        let region = String::from_utf8_lossy(hooks.region.as_deref().expect("a region"));
2567        assert!(
2568            hooks_text.starts_with(&format!(
2569                "repos:\n{region}\n  - repo: https://example.com/own"
2570            )),
2571            "{hooks_text}"
2572        );
2573        assert!(!hooks_text.contains(HOOK_TYPES_LINE));
2574        let agents = candidate(&projection, AGENTS_DESTINATION);
2575        assert!(agents.bytes.starts_with(own_agents.as_bytes()));
2576        assert_eq!(
2577            extract_block(
2578                &String::from_utf8_lossy(&agents.bytes),
2579                BLOCK_BEGIN,
2580                BLOCK_END
2581            )
2582            .map(str::as_bytes),
2583            agents.region.as_deref()
2584        );
2585        let glossary = candidate(&projection, GLOSSARY_DESTINATION);
2586        let region = glossary.region.as_deref().expect("a region");
2587        assert_eq!(
2588            glossary.bytes,
2589            [region, b"\n"].concat(),
2590            "an absent file is fresh"
2591        );
2592    }
2593
2594    /// A hook document that is not UTF-8 offers the block no place: the
2595    /// line-based splice would have to decode it, and a lossy decode
2596    /// rewrites a byte outside the markers. A valid document still
2597    /// splices, and the markdown destinations, spliced as bytes, take an
2598    /// invalid byte outside their markers unchanged.
2599    #[test]
2600    fn a_hook_document_that_is_not_utf8_collides_instead_of_being_rewritten() {
2601        let mut documents = std::collections::BTreeMap::new();
2602        let mut invalid = b"repos:\n# own \xff above\n".to_vec();
2603        invalid.extend_from_slice(format!("{HOOKS_BEGIN}\nstale\n{HOOKS_END}\n").as_bytes());
2604        invalid.extend_from_slice(b"  - repo: local \xff below\n");
2605        documents.insert(HOOKS_DESTINATION.to_owned(), invalid);
2606        let mut agents = b"# Widget r\xe9sum\xe9\n\n".to_vec();
2607        agents.extend_from_slice(format!("{BLOCK_BEGIN}\nstale\n{BLOCK_END}\n\n").as_bytes());
2608        agents.extend_from_slice(b"r\xe9sum\xe9\n");
2609        documents.insert(AGENTS_DESTINATION.to_owned(), agents.clone());
2610        let projection = compute(TargetEvidence {
2611            documents,
2612            crate_shape: supported_shape(),
2613            ..TargetEvidence::default()
2614        });
2615        let collided: Vec<&str> = projection
2616            .collisions
2617            .iter()
2618            .map(|c| c.destination.as_str())
2619            .collect();
2620        assert_eq!(collided, [HOOKS_DESTINATION]);
2621        assert!(
2622            projection.collisions[0].reason.contains("not UTF-8"),
2623            "{}",
2624            projection.collisions[0].reason
2625        );
2626        assert!(
2627            !projection
2628                .candidates
2629                .iter()
2630                .any(|c| c.destination == HOOKS_DESTINATION),
2631            "a colliding destination projects no candidate"
2632        );
2633        let agents = candidate(&projection, AGENTS_DESTINATION);
2634        assert!(
2635            agents.bytes.starts_with(b"# Widget r\xe9sum\xe9\n\n"),
2636            "{:?}",
2637            agents.bytes
2638        );
2639        assert!(
2640            agents.bytes.ends_with(b"\n\nr\xe9sum\xe9\n"),
2641            "{:?}",
2642            agents.bytes
2643        );
2644        assert!(
2645            !agents.bytes.contains(&0xEF),
2646            "a replacement character landed"
2647        );
2648
2649        let mut documents = std::collections::BTreeMap::new();
2650        let valid =
2651            format!("repos:\n# own above\n{HOOKS_BEGIN}\nstale\n{HOOKS_END}\n  - repo: local\n");
2652        documents.insert(HOOKS_DESTINATION.to_owned(), valid.into_bytes());
2653        let projection = compute(TargetEvidence {
2654            documents,
2655            crate_shape: supported_shape(),
2656            ..TargetEvidence::default()
2657        });
2658        assert!(
2659            projection.collisions.is_empty(),
2660            "{:?}",
2661            projection.collisions
2662        );
2663        let hooks = candidate(&projection, HOOKS_DESTINATION);
2664        let text = String::from_utf8(hooks.bytes.clone()).expect("a valid document stays text");
2665        assert!(text.starts_with("repos:\n# own above\n"), "{text}");
2666        assert!(text.ends_with("\n  - repo: local\n"), "{text}");
2667        assert!(!text.contains("stale"), "the region is replaced: {text}");
2668    }
2669
2670    /// A snippet that ships a block destination as a whole file is a
2671    /// source defect named by both sides: the snippet's source path and
2672    /// the block's template paths.
2673    #[test]
2674    fn a_whole_file_colliding_with_a_marked_region_names_both_source_paths() {
2675        let files: Vec<(String, &[u8])> = vec![
2676            ("snippets/_shared/github/SECURITY.md".to_owned(), b"policy"),
2677            ("snippets/rust/github/AGENTS.md".to_owned(), b"whole"),
2678        ];
2679        let err = Projection::compute_over(&files, &input(TargetEvidence::default()))
2680            .expect_err("a whole file at a block destination refuses");
2681        let text = err.to_string();
2682        assert!(text.contains("snippets/rust/github/AGENTS.md"), "{text}");
2683        assert!(text.contains(super::AGENTS_BLOCK), "{text}");
2684        assert!(text.contains(super::AGENTS_LINE_WORKTREE), "{text}");
2685        assert!(text.contains("embedded sources are defective"), "{text}");
2686    }
2687
2688    #[test]
2689    fn duplicate_whole_file_destinations_and_overlapping_marked_regions_refuse_with_the_conflicting_source_names()
2690     {
2691        // Two capabilities shipping one destination is a source defect
2692        // named by both sides.
2693        let files: Vec<(String, &[u8])> = vec![
2694            ("snippets/_shared/github/SECURITY.md".to_owned(), b"shared"),
2695            ("snippets/rust/github/SECURITY.md".to_owned(), b"pair"),
2696            ("snippets/rust/github/release-plz.toml".to_owned(), b"seed"),
2697        ];
2698        let err = Projection::compute_over(&files, &input(TargetEvidence::default()))
2699            .expect_err("a doubled destination refuses");
2700        let text = err.to_string();
2701        assert!(
2702            text.contains("snippets/_shared/github/SECURITY.md"),
2703            "{text}"
2704        );
2705        assert!(text.contains("snippets/rust/github/SECURITY.md"), "{text}");
2706        assert!(text.contains("embedded sources are defective"), "{text}");
2707
2708        let clean: Vec<(String, &[u8])> = vec![
2709            ("snippets/_shared/github/SECURITY.md".to_owned(), b"shared"),
2710            ("snippets/rust/github/release-plz.toml".to_owned(), b"seed"),
2711        ];
2712        let projection = Projection::compute_over(&clean, &input(TargetEvidence::default()))
2713            .expect("a clean list projects");
2714        let whole: Vec<&str> = projection
2715            .candidates
2716            .iter()
2717            .filter(|c| c.placement == Placement::Whole)
2718            .map(|c| c.destination.as_str())
2719            .collect();
2720        assert_eq!(whole, ["SECURITY.md", "release-plz.toml"]);
2721        assert_eq!(
2722            projection
2723                .candidates
2724                .iter()
2725                .find(|c| c.destination == "SECURITY.md")
2726                .map(|c| c.sources.clone()),
2727            Some(vec!["snippets/_shared/github/SECURITY.md".to_owned()])
2728        );
2729
2730        let doubled = format!("{BLOCK_BEGIN}\na\n{BLOCK_END}\n{BLOCK_BEGIN}\nb\n{BLOCK_END}\n");
2731        let unmatched = format!("repos:\n{HOOKS_BEGIN}\n  - repo: local\n");
2732        let misordered = format!("# G\n{BLOCK_END}\n{BLOCK_BEGIN}\n");
2733        let mut documents = std::collections::BTreeMap::new();
2734        documents.insert(AGENTS_DESTINATION.to_owned(), doubled.into_bytes());
2735        documents.insert(HOOKS_DESTINATION.to_owned(), unmatched.into_bytes());
2736        documents.insert(GLOSSARY_DESTINATION.to_owned(), misordered.into_bytes());
2737        let projection = compute(TargetEvidence {
2738            documents,
2739            crate_shape: supported_shape(),
2740            ..TargetEvidence::default()
2741        });
2742        let mut collided: Vec<&str> = projection
2743            .collisions
2744            .iter()
2745            .map(|Collision { destination, .. }| destination.as_str())
2746            .collect();
2747        collided.sort_unstable();
2748        let mut expected = BLOCK_DESTINATIONS.to_vec();
2749        expected.sort_unstable();
2750        assert_eq!(collided, expected);
2751        for collision in &projection.collisions {
2752            assert!(
2753                collision.reason.contains(&collision.destination),
2754                "{collision:?}"
2755            );
2756            assert!(
2757                !projection
2758                    .candidates
2759                    .iter()
2760                    .any(|candidate| candidate.destination == collision.destination),
2761                "{} collided and still projects",
2762                collision.destination
2763            );
2764        }
2765        let agents = projection
2766            .collisions
2767            .iter()
2768            .find(|c| c.destination == AGENTS_DESTINATION)
2769            .expect("the doubled document collides");
2770        assert!(agents.reason.contains("more than one"), "{}", agents.reason);
2771        let hooks = projection
2772            .collisions
2773            .iter()
2774            .find(|c| c.destination == HOOKS_DESTINATION)
2775            .expect("the unmatched document collides");
2776        assert!(hooks.reason.contains("unmatched"), "{}", hooks.reason);
2777    }
2778}