Skip to main content

spec_driven_docs/
candidate.rs

1//! The candidate this binary renders for one target.
2//!
3//! One pure function owns every byte a landing would write. It reads the
4//! sources compiled into this binary and the evidence the caller gathered
5//! from the target, and it returns an ordered list of destinations plus the
6//! record that describes them. It reads no filesystem, no environment, no
7//! clock, and no network, so the same input renders the same bytes whether
8//! a stage asked or a production landing did.
9//!
10//! What the caller observes about the target is a value in [`Evidence`].
11//! Observation is the caller's job, because a projection that looked at the
12//! world itself could not be replayed and could not be staged.
13
14use std::collections::BTreeMap;
15
16use camino::Utf8PathBuf;
17
18use crate::domain::instance_config::{InstanceConfig, WritingStyle};
19use crate::domain::manifest::{CANON_SOURCE, MANIFEST_PATH, Manifest, SCHEMA_VERSION};
20use crate::domain::ownership::{AdoptedEntry, IntegrationBlock, ManagedEntry, Sha256};
21use crate::domain::paths::{AGENTS_DIGEST_PATH, HOOKS_CONFIG_PATH};
22use crate::domain::profile::{DocsRoot, ProfileId, render_root, resolve_destination};
23use crate::domain::version::CanonVersion;
24use crate::error::AppError;
25use crate::services::hooks_render::{RenderOptions, render_block};
26
27/// The title a root `AGENTS.md` this landing creates opens with.
28pub const AGENTS_TITLE: &str = "# AGENTS";
29
30/// Who owns a destination's bytes after the landing.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Ownership {
33    /// This tool keeps owning the bytes and refreshes them.
34    Managed,
35    /// The project owns the bytes from the moment they land.
36    Adopted,
37    /// The project owns the file and this tool owns one region inside it.
38    Integration,
39}
40
41/// How much of the destination the candidate carries.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum Placement {
44    /// Every byte of the file.
45    WholeFile,
46    /// One marked region, with every byte outside it preserved.
47    MarkedRegion,
48}
49
50/// One destination of the candidate, and the bytes that would go there.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Destination {
53    /// The path, relative to the target root.
54    pub path: Utf8PathBuf,
55    /// Every byte the file would hold after the landing.
56    pub bytes: Vec<u8>,
57    /// Who owns those bytes afterwards.
58    pub ownership: Ownership,
59    /// Whether the candidate carries the file or one region of it.
60    pub placement: Placement,
61    /// The payload path that produced the bytes, where one did.
62    pub source: Option<String>,
63}
64
65/// The complete candidate for one target.
66#[derive(Debug, Clone)]
67pub struct Candidate {
68    /// Every destination, in the order a landing writes them.
69    pub destinations: Vec<Destination>,
70    /// The record that describes the landing, written after all of them.
71    pub manifest: Manifest,
72    /// What the gates judge, as the candidate's own declaration states it.
73    ///
74    /// This is the resolved value the rendered bytes carry, not the flags
75    /// the caller passed: a reader of the candidate needs what it says,
76    /// and the two differ wherever the project already declared something.
77    pub declaration: InstanceConfig,
78    /// What the operator is told about what the projection chose.
79    pub notes: Vec<String>,
80}
81
82impl Candidate {
83    /// Every destination and its bytes, with the record written last.
84    #[must_use]
85    pub fn files(&self) -> Vec<(Utf8PathBuf, Vec<u8>)> {
86        let mut files: Vec<(Utf8PathBuf, Vec<u8>)> = self
87            .destinations
88            .iter()
89            .map(|destination| (destination.path.clone(), destination.bytes.clone()))
90            .collect();
91        files.push((
92            Utf8PathBuf::from(MANIFEST_PATH),
93            self.manifest.to_json().into_bytes(),
94        ));
95        files
96    }
97}
98
99/// What the caller observed about the target before projecting.
100///
101/// Every field is a value the caller read once. The projection never looks
102/// at the target itself, so a stage and a production run that observed the
103/// same target project the same bytes.
104#[derive(Debug, Clone, Default)]
105pub struct Evidence {
106    /// The bytes each existing destination holds, by target-relative path.
107    pub existing: BTreeMap<Utf8PathBuf, Vec<u8>>,
108    /// The destinations the instance record already calls adopted.
109    pub recorded_adopted: Vec<String>,
110    /// The hook configuration the target holds, or the empty default.
111    pub hooks_host: String,
112    /// The root author-instructions file the target holds, or nothing.
113    pub agents_host: String,
114    /// Whether the root author-instructions file exists at all.
115    ///
116    /// An absent file and an existing empty one both leave `agents_host`
117    /// empty, and only the absent one is created with a title.
118    pub agents_exists: bool,
119    /// Which names of every declared yield set exist at the target root.
120    pub present_at_root: Vec<String>,
121}
122
123/// What a landing was asked to render.
124#[derive(Debug, Clone)]
125pub struct Input {
126    /// The profile to project.
127    pub profile: ProfileId,
128    /// The version of the binary doing the rendering.
129    pub version: CanonVersion,
130    /// The install timestamp to record, carried forward where one exists.
131    pub installed_at: String,
132    /// The documentation scratch to record.
133    pub docs_scratch: Option<Utf8PathBuf>,
134    /// Paths to record under `reserved:` in the instance declaration.
135    pub reserve: Vec<String>,
136    /// The writing-style selection to record in the declaration.
137    pub writing_style: Option<WritingStyle>,
138    /// The acquisition decision to record in the declaration.
139    pub acquisition: Option<crate::domain::instance_config::Acquisition>,
140    /// What the caller observed about the target.
141    pub evidence: Evidence,
142}
143
144/// Render the candidate this binary carries for one target.
145///
146/// # Errors
147///
148/// [`AppError::Refused`] where this release declares no such profile, where
149/// a marked region cannot be read, or where two sources project onto one
150/// destination.
151#[allow(
152    clippy::too_many_lines,
153    reason = "the candidate is one ordered pass, and splitting it would hide the order it defines"
154)]
155pub fn project(input: &Input) -> Result<Candidate, AppError> {
156    let declared = crate::domain::profile::DECLARATION
157        .profile(input.profile)
158        .ok_or_else(|| {
159            AppError::Refused(format!(
160                "this release declares no {} profile, so it cannot land one",
161                input.profile
162            ))
163        })?;
164    let docs_root = declared.docs_root;
165    let mut destinations: Vec<Destination> = Vec::new();
166    let mut notes: Vec<String> = Vec::new();
167    let mut managed_entries = Vec::new();
168    let mut adopted_entries = Vec::new();
169
170    for projection in declared.managed {
171        let bytes = source_bytes(&projection.source)?;
172        let path = resolve_destination(&projection.destination, docs_root);
173        managed_entries.push(ManagedEntry {
174            source: projection.source.clone().into(),
175            destination: path.clone(),
176            sha256: Sha256::of(&bytes),
177        });
178        destinations.push(Destination {
179            path,
180            bytes,
181            ownership: Ownership::Managed,
182            placement: Placement::WholeFile,
183            source: Some(projection.source.clone()),
184        });
185    }
186
187    // The skills come from the payload rather than the declaration, so
188    // they follow the binary that lands them and no projection row names
189    // them.
190    let inventory =
191        crate::embedded::skill_inventory().map_err(|error| AppError::Refused(error.to_string()))?;
192    for file in inventory {
193        managed_entries.push(ManagedEntry {
194            source: file.source.clone().into(),
195            destination: file.destination.clone().into(),
196            sha256: Sha256::of(file.bytes),
197        });
198        destinations.push(Destination {
199            path: file.destination.into(),
200            bytes: file.bytes.to_vec(),
201            ownership: Ownership::Managed,
202            placement: Placement::WholeFile,
203            source: Some(file.source),
204        });
205    }
206
207    for projection in declared.adopted {
208        let seed = rendered_seed(&projection.source, docs_root)?;
209        let path = resolve_destination(&projection.destination, docs_root);
210        let recorded = input
211            .evidence
212            .recorded_adopted
213            .iter()
214            .any(|recorded| recorded == path.as_str());
215        // A seed the record already attributes keeps its entry, its held
216        // bytes, and its baseline, like any other adopted file. The yield
217        // decides only whether to introduce one, and the seed's own name is
218        // in the set it yields to, so asking first would stop owning it at
219        // the second landing.
220        if !recorded
221            && let Some(cause) = projection.yield_set().and_then(|set| {
222                set.names().find(|name| {
223                    input
224                        .evidence
225                        .present_at_root
226                        .iter()
227                        .any(|held| held == name)
228                })
229            })
230        {
231            notes.push(format!(
232                "note: {path} was not seeded, because the target root already holds {cause}; that configuration stays the project's, and 'sdd method gates' states what it needs to load the relative-links rule"
233            ));
234            continue;
235        }
236        let mut held = input.evidence.existing.get(&path);
237        // A declaration an archive wrote holds the open migration alone. It
238        // is a seed still to land, not a project's own declaration: the
239        // landing writes the whole seed and carries the key into it, so the
240        // close leaves exactly what a greenfield landing writes.
241        let migration = (path == crate::domain::instance_config::CONFIG_PATH && !recorded)
242            .then(|| held.and_then(|bytes| pending_migration(bytes)))
243            .flatten();
244        if migration.is_some() {
245            held = None;
246        }
247        if let Some(held) = held
248            && held != &seed
249            && !recorded
250        {
251            notes.push(format!(
252                "note: {path} already exists and is kept; the seed was not written, so read it with 'sdd spec' and reconcile by hand"
253            ));
254        }
255        let mut bytes = held.cloned().unwrap_or_else(|| seed.clone());
256        // `--reserve` and `--writing-style` record into the declaration,
257        // keeping its comments and whatever the project already wrote there.
258        // What is already there is read first: a transformation applied to
259        // bytes nobody validated would repair a malformed declaration into
260        // a valid one and overwrite the file the operator has to fix. A
261        // choice the declaration already holds is not written again, so a
262        // stage that records the resolved choices lands the same bytes it
263        // showed, implicit defaults and comments included.
264        if path == crate::domain::instance_config::CONFIG_PATH {
265            let (text, held) = readable(&path, &bytes)?;
266            let mut text = text.to_string();
267            let reserve: Vec<String> = input
268                .reserve
269                .iter()
270                .filter(|pattern| !held.reserved.contains(pattern))
271                .cloned()
272                .collect();
273            if !reserve.is_empty() {
274                text = crate::domain::instance_config::with_reserved(&text, &reserve);
275            }
276            if let Some(selection) = &input.writing_style
277                && *selection != held.writing_style
278            {
279                text = crate::domain::instance_config::with_writing_style(&text, selection);
280            }
281            if let Some(decision) = &input.acquisition
282                && held.acquisition.as_ref() != Some(decision)
283            {
284                text = crate::domain::instance_config::with_acquisition(&text, decision);
285            }
286            if let Some(id) = &migration {
287                text = crate::domain::instance_config::with_migration(&text, id);
288            }
289            bytes = text.into_bytes();
290        }
291        adopted_entries.push(AdoptedEntry {
292            source: projection.source.clone().into(),
293            destination: path.clone(),
294            sha256: Sha256::of(&bytes),
295            baseline_sha256: Sha256::of(&seed),
296        });
297        destinations.push(Destination {
298            path,
299            bytes,
300            ownership: Ownership::Adopted,
301            placement: Placement::WholeFile,
302            source: Some(projection.source.clone()),
303        });
304    }
305
306    let host = if input.evidence.hooks_host.is_empty() {
307        "repos:\n".to_string()
308    } else {
309        input.evidence.hooks_host.clone()
310    };
311    let (base, _) = crate::domain::marker::split_block(&host)?;
312    let indent = crate::domain::marker::splice_indent(&base)?;
313    // Render from the declaration this landing is writing, not from the one
314    // on disk. With `--reserve` they differ, and a block rendered from the
315    // old one would disagree with the file the same landing writes.
316    // The declaration the block is rendered from is the one this landing
317    // writes, already validated above.
318    let declared = destinations
319        .iter()
320        .find(|destination| destination.path == crate::domain::instance_config::CONFIG_PATH);
321    let declaration = match declared {
322        Some(destination) => readable(&destination.path, &destination.bytes)?.1,
323        None => InstanceConfig::default(),
324    };
325    let writing_style = declaration.writing_style.clone();
326    let block = render_block(&RenderOptions {
327        docs_root: docs_root.to_string(),
328        indent,
329        declaration: declaration.clone(),
330        ..RenderOptions::default()
331    });
332    let spliced = crate::domain::marker::splice(&base, &block)?;
333    let marker_hash = crate::domain::marker::block_hash(&spliced)
334        .ok_or_else(|| anyhow::anyhow!("the rendered block lost its markers"))?;
335    destinations.push(Destination {
336        path: Utf8PathBuf::from(HOOKS_CONFIG_PATH),
337        bytes: spliced.into_bytes(),
338        ownership: Ownership::Integration,
339        placement: Placement::MarkedRegion,
340        source: None,
341    });
342    let mut integration_blocks = vec![IntegrationBlock {
343        path: HOOKS_CONFIG_PATH.into(),
344        marker_hash,
345    }];
346
347    let agents_block =
348        crate::services::agents_render::render_block(&docs_root.to_string(), &writing_style);
349    let mut agents =
350        crate::domain::marker::place_agents_block(&input.evidence.agents_host, &agents_block)?;
351    // A file this landing creates opens with a title, because a Markdown
352    // file whose first line is not one fails the linter's default. A host
353    // that exists, even an empty one, is the project's, and gets none.
354    if !input.evidence.agents_exists {
355        agents = format!("{AGENTS_TITLE}\n\n{agents}");
356    }
357    let agents_hash = crate::domain::marker::block_hash_with(
358        &agents,
359        crate::domain::marker::AGENTS_BEGIN,
360        crate::domain::marker::AGENTS_END,
361    )
362    .ok_or_else(|| anyhow::anyhow!("the rendered AGENTS.md block lost its markers"))?;
363    // An old unmarked documentation section is preserved, never deleted; the
364    // note tells the operator to remove the duplicate by hand.
365    if input.evidence.agents_host.contains("## Documentation")
366        && crate::domain::marker::block_region_with(
367            &input.evidence.agents_host,
368            crate::domain::marker::AGENTS_BEGIN,
369            crate::domain::marker::AGENTS_END,
370        )
371        .is_none()
372    {
373        notes.push(
374            "note: AGENTS.md carries an unmarked '## Documentation' section; the managed block was appended and the old section left in place — remove it by hand".to_string(),
375        );
376    }
377    destinations.push(Destination {
378        path: Utf8PathBuf::from(AGENTS_DIGEST_PATH),
379        bytes: agents.into_bytes(),
380        ownership: Ownership::Integration,
381        placement: Placement::MarkedRegion,
382        source: None,
383    });
384    integration_blocks.push(IntegrationBlock {
385        path: AGENTS_DIGEST_PATH.into(),
386        marker_hash: agents_hash,
387    });
388
389    one_destination_each(&destinations)?;
390
391    let manifest = Manifest {
392        schema_version: SCHEMA_VERSION,
393        canon_version: input.version,
394        canon_source: CANON_SOURCE.to_string(),
395        profile: input.profile,
396        docs_root,
397        installed_at: input.installed_at.clone(),
398        docs_scratch: input.docs_scratch.clone(),
399        managed_files: managed_entries,
400        adopted_files: adopted_entries,
401        integration_blocks,
402    };
403
404    Ok(Candidate {
405        destinations,
406        manifest,
407        declaration,
408        notes,
409    })
410}
411
412/// The documentation root one profile of this release lands into.
413///
414/// # Errors
415///
416/// [`AppError::Refused`] where this release declares no such profile.
417pub fn docs_root_of(profile: ProfileId) -> Result<DocsRoot, AppError> {
418    crate::domain::profile::DECLARATION
419        .docs_root(profile)
420        .ok_or_else(|| {
421            AppError::Refused(format!(
422                "this release declares no {profile} profile, so it cannot land one"
423            ))
424        })
425}
426
427/// The migration a declaration holds, where it holds that alone: the
428/// declaration an archive writes before any instance lands.
429fn pending_migration(bytes: &[u8]) -> Option<String> {
430    let text = std::str::from_utf8(bytes).ok()?;
431    let declaration = InstanceConfig::parse(text).ok()?;
432    let id = declaration.migration.clone()?;
433    let bare = InstanceConfig {
434        migration: None,
435        ..declaration
436    };
437    (bare == InstanceConfig::default()
438        && crate::domain::instance_config::with_migration("", &id) == text)
439        .then_some(id)
440}
441
442/// One declaration's text, refusing bytes no reader can take.
443///
444/// A declaration that cannot be read is a refusal, never a default and
445/// never something a flag repairs on the way past: the landing would
446/// otherwise keep the project's bytes and wire the block from something
447/// else, and the two would disagree from the first commit onward.
448fn readable<'a>(
449    path: &Utf8PathBuf,
450    bytes: &'a [u8],
451) -> Result<(&'a str, InstanceConfig), AppError> {
452    let text = std::str::from_utf8(bytes).map_err(|source| {
453        AppError::Refused(format!(
454            "{path} is not UTF-8, so what the gates judge cannot be read: {source}"
455        ))
456    })?;
457    let declaration = InstanceConfig::parse(text)
458        .map_err(|error| AppError::Refused(format!("{path} does not parse: {error}")))?;
459    Ok((text, declaration))
460}
461
462/// The bytes one payload source carries, from this binary's own sources.
463///
464/// # Errors
465///
466/// [`AppError::Refused`] where this release does not carry the source.
467pub fn source_bytes(source: &str) -> Result<Vec<u8>, AppError> {
468    crate::embedded::asset(source)
469        .map(<[u8]>::to_vec)
470        .ok_or_else(|| {
471            AppError::Refused(format!(
472                "this release projects {source}, and its own payload does not carry it"
473            ))
474        })
475}
476
477/// One adopted seed as it lands for a documentation root.
478///
479/// A seed names the instance's root by the placeholder, and the landing is
480/// the one moment that knows the root, so the landed bytes, the held-bytes
481/// comparison, and the recorded baseline all use this rendering. A seed
482/// that is not text carries no placeholder and lands as it is.
483///
484/// SATISFIES staging:a-seed-lands-rendered-for-its-root
485///
486/// # Errors
487///
488/// [`AppError::Refused`] where this release does not carry the source.
489pub fn rendered_seed(source: &str, docs_root: DocsRoot) -> Result<Vec<u8>, AppError> {
490    let bytes = source_bytes(source)?;
491    let rendered = std::str::from_utf8(&bytes)
492        .ok()
493        .map(|text| render_root(text, docs_root.as_str()).into_bytes());
494    Ok(rendered.unwrap_or(bytes))
495}
496
497/// Refuse two sources aimed at one destination before any writer runs.
498fn one_destination_each(destinations: &[Destination]) -> Result<(), AppError> {
499    let mut seen: Vec<&Utf8PathBuf> = Vec::with_capacity(destinations.len());
500    for destination in destinations {
501        if seen.contains(&&destination.path) {
502            return Err(AppError::Refused(format!(
503                "{} is projected twice, so the candidate does not describe one file",
504                destination.path
505            )));
506        }
507        seen.push(&destination.path);
508    }
509    Ok(())
510}
511
512#[cfg(test)]
513mod tests {
514    #![allow(
515        clippy::unwrap_used,
516        reason = "a test panics as its failure signal, not as control flow"
517    )]
518
519    use super::*;
520
521    fn input(profile: ProfileId) -> Input {
522        Input {
523            profile,
524            version: CanonVersion::current(),
525            installed_at: "2026-01-01T00:00:00Z".to_string(),
526            docs_scratch: None,
527            reserve: Vec::new(),
528            writing_style: None,
529            acquisition: None,
530            evidence: Evidence::default(),
531        }
532    }
533
534    #[test]
535    fn equal_inputs_render_byte_identical_candidates() {
536        let first = project(&input(ProfileId::Codebase)).unwrap();
537        let second = project(&input(ProfileId::Codebase)).unwrap();
538        assert_eq!(first.destinations, second.destinations);
539        assert_eq!(first.manifest.to_json(), second.manifest.to_json());
540    }
541
542    #[test]
543    fn every_profile_lands_its_own_root() {
544        for profile in ProfileId::every() {
545            let candidate = project(&input(profile)).unwrap();
546            assert_eq!(candidate.manifest.profile, profile);
547            assert_eq!(candidate.manifest.docs_root, docs_root_of(profile).unwrap());
548        }
549    }
550
551    #[test]
552    fn the_record_is_the_last_file_a_landing_writes() {
553        let candidate = project(&input(ProfileId::KnowledgeBase)).unwrap();
554        let files = candidate.files();
555        assert_eq!(files.last().unwrap().0, Utf8PathBuf::from(MANIFEST_PATH));
556        assert_eq!(files.len(), candidate.destinations.len() + 1);
557    }
558
559    #[test]
560    fn one_documentation_root_serves_the_whole_candidate() {
561        let candidate = project(&input(ProfileId::KnowledgeBase)).unwrap();
562        let root = candidate.manifest.docs_root;
563        let root_seeds: Vec<&str> = crate::domain::profile::DECLARATION
564            .adopted
565            .iter()
566            .filter(|projection| projection.yield_set().is_some())
567            .map(|projection| projection.destination.as_str())
568            .collect();
569        assert_eq!(root_seeds, [".markdownlint-cli2.jsonc"]);
570        for entry in candidate
571            .manifest
572            .managed_files
573            .iter()
574            .map(|entry| &entry.destination)
575            .chain(
576                candidate
577                    .manifest
578                    .adopted_files
579                    .iter()
580                    .map(|entry| &entry.destination),
581            )
582        {
583            if entry == crate::domain::paths::CONFIG_PATH
584                || root_seeds.contains(&entry.as_str())
585                || crate::embedded::SKILL_ROOTS
586                    .iter()
587                    .any(|skills| entry.as_str().starts_with(&format!("{skills}/")))
588            {
589                continue;
590            }
591            assert!(
592                entry.as_str().starts_with(&format!("{root}/")),
593                "{entry} is outside the recorded root {root}"
594            );
595        }
596    }
597
598    #[test]
599    fn an_adopted_destination_the_project_wrote_is_kept_and_noted() {
600        let mut held = input(ProfileId::KnowledgeBase);
601        let candidate = project(&held).unwrap();
602        let adopted = candidate
603            .destinations
604            .iter()
605            .find(|destination| {
606                destination.ownership == Ownership::Adopted
607                    && destination.path != crate::domain::paths::CONFIG_PATH
608            })
609            .unwrap()
610            .clone();
611        held.evidence
612            .existing
613            .insert(adopted.path.clone(), b"the project wrote this".to_vec());
614
615        let second = project(&held).unwrap();
616        let kept = second
617            .destinations
618            .iter()
619            .find(|destination| destination.path == adopted.path)
620            .unwrap();
621        assert_eq!(kept.bytes, b"the project wrote this");
622        assert!(
623            second
624                .notes
625                .iter()
626                .any(|note| note.contains(adopted.path.as_str()))
627        );
628    }
629
630    #[test]
631    fn a_recorded_adopted_destination_is_kept_without_a_note() {
632        let mut held = input(ProfileId::KnowledgeBase);
633        let candidate = project(&held).unwrap();
634        let adopted = candidate
635            .destinations
636            .iter()
637            .find(|destination| {
638                destination.ownership == Ownership::Adopted
639                    && destination.path != crate::domain::paths::CONFIG_PATH
640            })
641            .unwrap()
642            .clone();
643        held.evidence
644            .existing
645            .insert(adopted.path.clone(), b"the project wrote this".to_vec());
646        held.evidence
647            .recorded_adopted
648            .push(adopted.path.to_string());
649
650        let second = project(&held).unwrap();
651        assert!(second.notes.is_empty(), "{:?}", second.notes);
652    }
653
654    #[test]
655    fn a_marked_region_preserves_every_byte_outside_it() {
656        let mut held = input(ProfileId::Codebase);
657        held.evidence.agents_host = "# Project\n\nOur own paragraph.\n".to_string();
658        held.evidence.agents_exists = true;
659        let candidate = project(&held).unwrap();
660        let agents = candidate
661            .destinations
662            .iter()
663            .find(|destination| destination.path == AGENTS_DIGEST_PATH)
664            .unwrap();
665        let text = String::from_utf8(agents.bytes.clone()).unwrap();
666        assert!(text.contains("Our own paragraph."));
667        assert_eq!(agents.placement, Placement::MarkedRegion);
668    }
669
670    #[test]
671    fn a_declaration_that_cannot_be_read_refuses_rather_than_defaulting() {
672        let mut held = input(ProfileId::KnowledgeBase);
673        held.evidence.existing.insert(
674            Utf8PathBuf::from(crate::domain::paths::CONFIG_PATH),
675            b"\xff\xfe not text".to_vec(),
676        );
677        let error = project(&held).unwrap_err();
678        assert!(error.to_string().contains("not UTF-8"), "{error}");
679
680        held.evidence.existing.insert(
681            Utf8PathBuf::from(crate::domain::paths::CONFIG_PATH),
682            b"reserved: [".to_vec(),
683        );
684        let error = project(&held).unwrap_err();
685        assert!(error.to_string().contains("does not parse"), "{error}");
686
687        // And a flag does not repair it on the way past. A transformation
688        // over bytes nobody validated would rewrite the file the operator
689        // has to fix and call the result a landing.
690        held.reserve = vec!["vendor/**".to_string()];
691        let error = project(&held).unwrap_err();
692        assert!(error.to_string().contains("does not parse"), "{error}");
693    }
694
695    const ROOT_SEED: &str = ".markdownlint-cli2.jsonc";
696
697    #[test]
698    fn a_yielding_seed_the_record_does_not_name_is_not_introduced() {
699        let mut held = input(ProfileId::Codebase);
700        held.evidence.present_at_root = vec![".markdownlint.yaml".to_string()];
701        let candidate = project(&held).unwrap();
702        assert!(
703            !candidate
704                .destinations
705                .iter()
706                .any(|destination| destination.path == ROOT_SEED)
707        );
708        assert!(
709            !candidate
710                .manifest
711                .adopted_files
712                .iter()
713                .any(|entry| entry.destination == ROOT_SEED)
714        );
715        assert!(
716            candidate
717                .notes
718                .iter()
719                .any(|note| note.contains(&format!("{ROOT_SEED} was not seeded"))
720                    && note.contains("already holds .markdownlint.yaml")),
721            "{:?}",
722            candidate.notes
723        );
724    }
725
726    #[test]
727    fn a_yielding_seed_the_record_names_stays_adopted() {
728        let mut held = input(ProfileId::Codebase);
729        let seed = rendered_seed("instance/seeds/markdownlint-cli2.jsonc", DocsRoot::Docs).unwrap();
730        // The seed's own name is in the set it yields to, which is why the
731        // record is asked first.
732        held.evidence.present_at_root = vec![ROOT_SEED.to_string()];
733        held.evidence.existing.insert(
734            Utf8PathBuf::from(ROOT_SEED),
735            b"{ \"edited\": true }\n".to_vec(),
736        );
737        held.evidence.recorded_adopted.push(ROOT_SEED.to_string());
738
739        let candidate = project(&held).unwrap();
740        let kept = candidate
741            .destinations
742            .iter()
743            .find(|destination| destination.path == ROOT_SEED)
744            .unwrap();
745        assert_eq!(kept.bytes, b"{ \"edited\": true }\n");
746        assert_eq!(kept.ownership, Ownership::Adopted);
747        let entry = candidate
748            .manifest
749            .adopted_files
750            .iter()
751            .find(|entry| entry.destination == ROOT_SEED)
752            .unwrap();
753        assert_eq!(entry.baseline_sha256, Sha256::of(&seed));
754        assert!(candidate.notes.is_empty(), "{:?}", candidate.notes);
755    }
756
757    fn agents_bytes(candidate: &Candidate) -> String {
758        let agents = candidate
759            .destinations
760            .iter()
761            .find(|destination| destination.path == AGENTS_DIGEST_PATH)
762            .unwrap();
763        String::from_utf8(agents.bytes.clone()).unwrap()
764    }
765
766    #[test]
767    fn only_an_absent_host_receives_the_title() {
768        let absent = project(&input(ProfileId::Codebase)).unwrap();
769        let text = agents_bytes(&absent);
770        assert!(
771            text.starts_with(&format!("{AGENTS_TITLE}\n\n<!-- BEGIN")),
772            "{text}"
773        );
774
775        let mut empty = input(ProfileId::Codebase);
776        empty.evidence.agents_exists = true;
777        let text = agents_bytes(&project(&empty).unwrap());
778        assert!(text.starts_with("<!-- BEGIN"), "{text}");
779        assert!(!text.contains(AGENTS_TITLE), "{text}");
780        assert_ne!(agents_bytes(&absent), text);
781    }
782
783    #[test]
784    fn an_unmarked_documentation_section_is_kept_and_noted_without_a_title() {
785        let mut held = input(ProfileId::Codebase);
786        held.evidence.agents_exists = true;
787        held.evidence.agents_host = "## Documentation\n\n- Our own routing.\n".to_string();
788        let candidate = project(&held).unwrap();
789        let text = agents_bytes(&candidate);
790        assert!(
791            text.starts_with("## Documentation\n\n- Our own routing.\n\n<!-- BEGIN"),
792            "{text}"
793        );
794        assert!(!text.contains(AGENTS_TITLE), "{text}");
795        assert!(
796            candidate
797                .notes
798                .iter()
799                .any(|note| note.contains("unmarked '## Documentation' section")),
800            "{:?}",
801            candidate.notes
802        );
803    }
804
805    #[test]
806    fn a_seed_lands_rendered_for_its_root() {
807        let candidate = project(&input(ProfileId::Codebase)).unwrap();
808        let registry = candidate
809            .destinations
810            .iter()
811            .find(|destination| destination.path == "docs/reference/tracking.yaml")
812            .unwrap();
813        let text = String::from_utf8(registry.bytes.clone()).unwrap();
814        assert!(
815            text.contains("path: docs/reference/model-pricing.md"),
816            "{text}"
817        );
818        assert!(
819            !text.contains(crate::domain::profile::DOCS_ROOT_PLACEHOLDER),
820            "{text}"
821        );
822        let recorded = candidate
823            .manifest
824            .adopted_files
825            .iter()
826            .find(|entry| entry.destination == "docs/reference/tracking.yaml")
827            .unwrap();
828        assert_eq!(recorded.baseline_sha256, Sha256::of(&registry.bytes));
829        assert_ne!(
830            recorded.baseline_sha256,
831            Sha256::of(&source_bytes("templates/TEMPLATE-tracking.yaml").unwrap())
832        );
833    }
834
835    #[test]
836    fn every_projected_source_comes_from_the_embedded_inventory() {
837        let candidate = project(&input(ProfileId::Codebase)).unwrap();
838        for destination in &candidate.destinations {
839            let Some(source) = &destination.source else {
840                continue;
841            };
842            assert!(
843                crate::embedded::asset(source).is_some(),
844                "{source} is projected and not embedded"
845            );
846        }
847    }
848}