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    /// What the caller observed about the target.
139    pub evidence: Evidence,
140}
141
142/// Render the candidate this binary carries for one target.
143///
144/// # Errors
145///
146/// [`AppError::Refused`] where this release declares no such profile, where
147/// a marked region cannot be read, or where two sources project onto one
148/// destination.
149#[allow(
150    clippy::too_many_lines,
151    reason = "the candidate is one ordered pass, and splitting it would hide the order it defines"
152)]
153pub fn project(input: &Input) -> Result<Candidate, AppError> {
154    let declared = crate::domain::profile::DECLARATION
155        .profile(input.profile)
156        .ok_or_else(|| {
157            AppError::Refused(format!(
158                "this release declares no {} profile, so it cannot land one",
159                input.profile
160            ))
161        })?;
162    let docs_root = declared.docs_root;
163    let mut destinations: Vec<Destination> = Vec::new();
164    let mut notes: Vec<String> = Vec::new();
165    let mut managed_entries = Vec::new();
166    let mut adopted_entries = Vec::new();
167
168    for projection in declared.managed {
169        let bytes = source_bytes(&projection.source)?;
170        let path = resolve_destination(&projection.destination, docs_root);
171        managed_entries.push(ManagedEntry {
172            source: projection.source.clone().into(),
173            destination: path.clone(),
174            sha256: Sha256::of(&bytes),
175        });
176        destinations.push(Destination {
177            path,
178            bytes,
179            ownership: Ownership::Managed,
180            placement: Placement::WholeFile,
181            source: Some(projection.source.clone()),
182        });
183    }
184
185    for projection in declared.adopted {
186        let seed = rendered_seed(&projection.source, docs_root)?;
187        let path = resolve_destination(&projection.destination, docs_root);
188        let recorded = input
189            .evidence
190            .recorded_adopted
191            .iter()
192            .any(|recorded| recorded == path.as_str());
193        // A seed the record already attributes keeps its entry, its held
194        // bytes, and its baseline, like any other adopted file. The yield
195        // decides only whether to introduce one, and the seed's own name is
196        // in the set it yields to, so asking first would stop owning it at
197        // the second landing.
198        if !recorded
199            && let Some(cause) = projection.yield_set().and_then(|set| {
200                set.names().find(|name| {
201                    input
202                        .evidence
203                        .present_at_root
204                        .iter()
205                        .any(|held| held == name)
206                })
207            })
208        {
209            notes.push(format!(
210                "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"
211            ));
212            continue;
213        }
214        let held = input.evidence.existing.get(&path);
215        if let Some(held) = held
216            && held != &seed
217            && !recorded
218        {
219            notes.push(format!(
220                "note: {path} already exists and is kept; the seed was not written, so read it with 'sdd spec' and reconcile by hand"
221            ));
222        }
223        let mut bytes = held.cloned().unwrap_or_else(|| seed.clone());
224        // `--reserve` and `--writing-style` record into the declaration,
225        // keeping its comments and whatever the project already wrote there.
226        // What is already there is read first: a transformation applied to
227        // bytes nobody validated would repair a malformed declaration into
228        // a valid one and overwrite the file the operator has to fix.
229        if path == crate::domain::instance_config::CONFIG_PATH {
230            let text = readable(&path, &bytes)?;
231            let mut text = text.to_string();
232            if !input.reserve.is_empty() {
233                text = crate::domain::instance_config::with_reserved(&text, &input.reserve);
234            }
235            if let Some(selection) = &input.writing_style {
236                text = crate::domain::instance_config::with_writing_style(&text, selection);
237            }
238            bytes = text.into_bytes();
239        }
240        adopted_entries.push(AdoptedEntry {
241            source: projection.source.clone().into(),
242            destination: path.clone(),
243            sha256: Sha256::of(&bytes),
244            baseline_sha256: Sha256::of(&seed),
245        });
246        destinations.push(Destination {
247            path,
248            bytes,
249            ownership: Ownership::Adopted,
250            placement: Placement::WholeFile,
251            source: Some(projection.source.clone()),
252        });
253    }
254
255    let host = if input.evidence.hooks_host.is_empty() {
256        "repos:\n".to_string()
257    } else {
258        input.evidence.hooks_host.clone()
259    };
260    let (base, _) = crate::domain::marker::split_block(&host)?;
261    let indent = crate::domain::marker::splice_indent(&base)?;
262    // Render from the declaration this landing is writing, not from the one
263    // on disk. With `--reserve` they differ, and a block rendered from the
264    // old one would disagree with the file the same landing writes.
265    // The declaration the block is rendered from is the one this landing
266    // writes, already validated above.
267    let declared = destinations
268        .iter()
269        .find(|destination| destination.path == crate::domain::instance_config::CONFIG_PATH);
270    let declaration = match declared {
271        Some(destination) => {
272            let text = readable(&destination.path, &destination.bytes)?;
273            InstanceConfig::parse(text).map_err(|error| {
274                AppError::Refused(format!("{} does not parse: {error}", destination.path))
275            })?
276        }
277        None => InstanceConfig::default(),
278    };
279    let writing_style = declaration.writing_style.clone();
280    let block = render_block(&RenderOptions {
281        docs_root: docs_root.to_string(),
282        indent,
283        declaration: declaration.clone(),
284        ..RenderOptions::default()
285    });
286    let spliced = crate::domain::marker::splice(&base, &block)?;
287    let marker_hash = crate::domain::marker::block_hash(&spliced)
288        .ok_or_else(|| anyhow::anyhow!("the rendered block lost its markers"))?;
289    destinations.push(Destination {
290        path: Utf8PathBuf::from(HOOKS_CONFIG_PATH),
291        bytes: spliced.into_bytes(),
292        ownership: Ownership::Integration,
293        placement: Placement::MarkedRegion,
294        source: None,
295    });
296    let mut integration_blocks = vec![IntegrationBlock {
297        path: HOOKS_CONFIG_PATH.into(),
298        marker_hash,
299    }];
300
301    let agents_block =
302        crate::services::agents_render::render_block(&docs_root.to_string(), &writing_style);
303    let mut agents =
304        crate::domain::marker::place_agents_block(&input.evidence.agents_host, &agents_block)?;
305    // A file this landing creates opens with a title, because a Markdown
306    // file whose first line is not one fails the linter's default. A host
307    // that exists, even an empty one, is the project's, and gets none.
308    if !input.evidence.agents_exists {
309        agents = format!("{AGENTS_TITLE}\n\n{agents}");
310    }
311    let agents_hash = crate::domain::marker::block_hash_with(
312        &agents,
313        crate::domain::marker::AGENTS_BEGIN,
314        crate::domain::marker::AGENTS_END,
315    )
316    .ok_or_else(|| anyhow::anyhow!("the rendered AGENTS.md block lost its markers"))?;
317    // An old unmarked documentation section is preserved, never deleted; the
318    // note tells the operator to remove the duplicate by hand.
319    if input.evidence.agents_host.contains("## Documentation")
320        && crate::domain::marker::block_region_with(
321            &input.evidence.agents_host,
322            crate::domain::marker::AGENTS_BEGIN,
323            crate::domain::marker::AGENTS_END,
324        )
325        .is_none()
326    {
327        notes.push(
328            "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(),
329        );
330    }
331    destinations.push(Destination {
332        path: Utf8PathBuf::from(AGENTS_DIGEST_PATH),
333        bytes: agents.into_bytes(),
334        ownership: Ownership::Integration,
335        placement: Placement::MarkedRegion,
336        source: None,
337    });
338    integration_blocks.push(IntegrationBlock {
339        path: AGENTS_DIGEST_PATH.into(),
340        marker_hash: agents_hash,
341    });
342
343    one_destination_each(&destinations)?;
344
345    let manifest = Manifest {
346        schema_version: SCHEMA_VERSION,
347        canon_version: input.version,
348        canon_source: CANON_SOURCE.to_string(),
349        profile: input.profile,
350        docs_root,
351        installed_at: input.installed_at.clone(),
352        docs_scratch: input.docs_scratch.clone(),
353        managed_files: managed_entries,
354        adopted_files: adopted_entries,
355        integration_blocks,
356    };
357
358    Ok(Candidate {
359        destinations,
360        manifest,
361        declaration,
362        notes,
363    })
364}
365
366/// The documentation root one profile of this release lands into.
367///
368/// # Errors
369///
370/// [`AppError::Refused`] where this release declares no such profile.
371pub fn docs_root_of(profile: ProfileId) -> Result<DocsRoot, AppError> {
372    crate::domain::profile::DECLARATION
373        .docs_root(profile)
374        .ok_or_else(|| {
375            AppError::Refused(format!(
376                "this release declares no {profile} profile, so it cannot land one"
377            ))
378        })
379}
380
381/// One declaration's text, refusing bytes no reader can take.
382///
383/// A declaration that cannot be read is a refusal, never a default and
384/// never something a flag repairs on the way past: the landing would
385/// otherwise keep the project's bytes and wire the block from something
386/// else, and the two would disagree from the first commit onward.
387fn readable<'a>(path: &Utf8PathBuf, bytes: &'a [u8]) -> Result<&'a str, AppError> {
388    let text = std::str::from_utf8(bytes).map_err(|source| {
389        AppError::Refused(format!(
390            "{path} is not UTF-8, so what the gates judge cannot be read: {source}"
391        ))
392    })?;
393    InstanceConfig::parse(text)
394        .map_err(|error| AppError::Refused(format!("{path} does not parse: {error}")))?;
395    Ok(text)
396}
397
398/// The bytes one payload source carries, from this binary's own sources.
399///
400/// # Errors
401///
402/// [`AppError::Refused`] where this release does not carry the source.
403pub fn source_bytes(source: &str) -> Result<Vec<u8>, AppError> {
404    crate::embedded::asset(source)
405        .map(<[u8]>::to_vec)
406        .ok_or_else(|| {
407            AppError::Refused(format!(
408                "this release projects {source}, and its own payload does not carry it"
409            ))
410        })
411}
412
413/// One adopted seed as it lands for a documentation root.
414///
415/// A seed names the instance's root by the placeholder, and the landing is
416/// the one moment that knows the root, so the landed bytes, the held-bytes
417/// comparison, and the recorded baseline all use this rendering. A seed
418/// that is not text carries no placeholder and lands as it is.
419///
420/// SATISFIES staging:a-seed-lands-rendered-for-its-root
421///
422/// # Errors
423///
424/// [`AppError::Refused`] where this release does not carry the source.
425pub fn rendered_seed(source: &str, docs_root: DocsRoot) -> Result<Vec<u8>, AppError> {
426    let bytes = source_bytes(source)?;
427    let rendered = std::str::from_utf8(&bytes)
428        .ok()
429        .map(|text| render_root(text, docs_root.as_str()).into_bytes());
430    Ok(rendered.unwrap_or(bytes))
431}
432
433/// Refuse two sources aimed at one destination before any writer runs.
434fn one_destination_each(destinations: &[Destination]) -> Result<(), AppError> {
435    let mut seen: Vec<&Utf8PathBuf> = Vec::with_capacity(destinations.len());
436    for destination in destinations {
437        if seen.contains(&&destination.path) {
438            return Err(AppError::Refused(format!(
439                "{} is projected twice, so the candidate does not describe one file",
440                destination.path
441            )));
442        }
443        seen.push(&destination.path);
444    }
445    Ok(())
446}
447
448#[cfg(test)]
449mod tests {
450    #![allow(
451        clippy::unwrap_used,
452        reason = "a test panics as its failure signal, not as control flow"
453    )]
454
455    use super::*;
456
457    fn input(profile: ProfileId) -> Input {
458        Input {
459            profile,
460            version: CanonVersion::current(),
461            installed_at: "2026-01-01T00:00:00Z".to_string(),
462            docs_scratch: None,
463            reserve: Vec::new(),
464            writing_style: None,
465            evidence: Evidence::default(),
466        }
467    }
468
469    #[test]
470    fn equal_inputs_render_byte_identical_candidates() {
471        let first = project(&input(ProfileId::Codebase)).unwrap();
472        let second = project(&input(ProfileId::Codebase)).unwrap();
473        assert_eq!(first.destinations, second.destinations);
474        assert_eq!(first.manifest.to_json(), second.manifest.to_json());
475    }
476
477    #[test]
478    fn every_profile_lands_its_own_root() {
479        for profile in ProfileId::every() {
480            let candidate = project(&input(profile)).unwrap();
481            assert_eq!(candidate.manifest.profile, profile);
482            assert_eq!(candidate.manifest.docs_root, docs_root_of(profile).unwrap());
483        }
484    }
485
486    #[test]
487    fn the_record_is_the_last_file_a_landing_writes() {
488        let candidate = project(&input(ProfileId::KnowledgeBase)).unwrap();
489        let files = candidate.files();
490        assert_eq!(files.last().unwrap().0, Utf8PathBuf::from(MANIFEST_PATH));
491        assert_eq!(files.len(), candidate.destinations.len() + 1);
492    }
493
494    #[test]
495    fn one_documentation_root_serves_the_whole_candidate() {
496        let candidate = project(&input(ProfileId::KnowledgeBase)).unwrap();
497        let root = candidate.manifest.docs_root;
498        let root_seeds: Vec<&str> = crate::domain::profile::DECLARATION
499            .adopted
500            .iter()
501            .filter(|projection| projection.yield_set().is_some())
502            .map(|projection| projection.destination.as_str())
503            .collect();
504        assert_eq!(root_seeds, [".markdownlint-cli2.jsonc"]);
505        for entry in candidate
506            .manifest
507            .managed_files
508            .iter()
509            .map(|entry| &entry.destination)
510            .chain(
511                candidate
512                    .manifest
513                    .adopted_files
514                    .iter()
515                    .map(|entry| &entry.destination),
516            )
517        {
518            if entry == crate::domain::paths::CONFIG_PATH || root_seeds.contains(&entry.as_str()) {
519                continue;
520            }
521            assert!(
522                entry.as_str().starts_with(&format!("{root}/")),
523                "{entry} is outside the recorded root {root}"
524            );
525        }
526    }
527
528    #[test]
529    fn an_adopted_destination_the_project_wrote_is_kept_and_noted() {
530        let mut held = input(ProfileId::KnowledgeBase);
531        let candidate = project(&held).unwrap();
532        let adopted = candidate
533            .destinations
534            .iter()
535            .find(|destination| {
536                destination.ownership == Ownership::Adopted
537                    && destination.path != crate::domain::paths::CONFIG_PATH
538            })
539            .unwrap()
540            .clone();
541        held.evidence
542            .existing
543            .insert(adopted.path.clone(), b"the project wrote this".to_vec());
544
545        let second = project(&held).unwrap();
546        let kept = second
547            .destinations
548            .iter()
549            .find(|destination| destination.path == adopted.path)
550            .unwrap();
551        assert_eq!(kept.bytes, b"the project wrote this");
552        assert!(
553            second
554                .notes
555                .iter()
556                .any(|note| note.contains(adopted.path.as_str()))
557        );
558    }
559
560    #[test]
561    fn a_recorded_adopted_destination_is_kept_without_a_note() {
562        let mut held = input(ProfileId::KnowledgeBase);
563        let candidate = project(&held).unwrap();
564        let adopted = candidate
565            .destinations
566            .iter()
567            .find(|destination| {
568                destination.ownership == Ownership::Adopted
569                    && destination.path != crate::domain::paths::CONFIG_PATH
570            })
571            .unwrap()
572            .clone();
573        held.evidence
574            .existing
575            .insert(adopted.path.clone(), b"the project wrote this".to_vec());
576        held.evidence
577            .recorded_adopted
578            .push(adopted.path.to_string());
579
580        let second = project(&held).unwrap();
581        assert!(second.notes.is_empty(), "{:?}", second.notes);
582    }
583
584    #[test]
585    fn a_marked_region_preserves_every_byte_outside_it() {
586        let mut held = input(ProfileId::Codebase);
587        held.evidence.agents_host = "# Project\n\nOur own paragraph.\n".to_string();
588        held.evidence.agents_exists = true;
589        let candidate = project(&held).unwrap();
590        let agents = candidate
591            .destinations
592            .iter()
593            .find(|destination| destination.path == AGENTS_DIGEST_PATH)
594            .unwrap();
595        let text = String::from_utf8(agents.bytes.clone()).unwrap();
596        assert!(text.contains("Our own paragraph."));
597        assert_eq!(agents.placement, Placement::MarkedRegion);
598    }
599
600    #[test]
601    fn a_declaration_that_cannot_be_read_refuses_rather_than_defaulting() {
602        let mut held = input(ProfileId::KnowledgeBase);
603        held.evidence.existing.insert(
604            Utf8PathBuf::from(crate::domain::paths::CONFIG_PATH),
605            b"\xff\xfe not text".to_vec(),
606        );
607        let error = project(&held).unwrap_err();
608        assert!(error.to_string().contains("not UTF-8"), "{error}");
609
610        held.evidence.existing.insert(
611            Utf8PathBuf::from(crate::domain::paths::CONFIG_PATH),
612            b"reserved: [".to_vec(),
613        );
614        let error = project(&held).unwrap_err();
615        assert!(error.to_string().contains("does not parse"), "{error}");
616
617        // And a flag does not repair it on the way past. A transformation
618        // over bytes nobody validated would rewrite the file the operator
619        // has to fix and call the result a landing.
620        held.reserve = vec!["vendor/**".to_string()];
621        let error = project(&held).unwrap_err();
622        assert!(error.to_string().contains("does not parse"), "{error}");
623    }
624
625    const ROOT_SEED: &str = ".markdownlint-cli2.jsonc";
626
627    #[test]
628    fn a_yielding_seed_the_record_does_not_name_is_not_introduced() {
629        let mut held = input(ProfileId::Codebase);
630        held.evidence.present_at_root = vec![".markdownlint.yaml".to_string()];
631        let candidate = project(&held).unwrap();
632        assert!(
633            !candidate
634                .destinations
635                .iter()
636                .any(|destination| destination.path == ROOT_SEED)
637        );
638        assert!(
639            !candidate
640                .manifest
641                .adopted_files
642                .iter()
643                .any(|entry| entry.destination == ROOT_SEED)
644        );
645        assert!(
646            candidate
647                .notes
648                .iter()
649                .any(|note| note.contains(&format!("{ROOT_SEED} was not seeded"))
650                    && note.contains("already holds .markdownlint.yaml")),
651            "{:?}",
652            candidate.notes
653        );
654    }
655
656    #[test]
657    fn a_yielding_seed_the_record_names_stays_adopted() {
658        let mut held = input(ProfileId::Codebase);
659        let seed = rendered_seed("instance/seeds/markdownlint-cli2.jsonc", DocsRoot::Docs).unwrap();
660        // The seed's own name is in the set it yields to, which is why the
661        // record is asked first.
662        held.evidence.present_at_root = vec![ROOT_SEED.to_string()];
663        held.evidence.existing.insert(
664            Utf8PathBuf::from(ROOT_SEED),
665            b"{ \"edited\": true }\n".to_vec(),
666        );
667        held.evidence.recorded_adopted.push(ROOT_SEED.to_string());
668
669        let candidate = project(&held).unwrap();
670        let kept = candidate
671            .destinations
672            .iter()
673            .find(|destination| destination.path == ROOT_SEED)
674            .unwrap();
675        assert_eq!(kept.bytes, b"{ \"edited\": true }\n");
676        assert_eq!(kept.ownership, Ownership::Adopted);
677        let entry = candidate
678            .manifest
679            .adopted_files
680            .iter()
681            .find(|entry| entry.destination == ROOT_SEED)
682            .unwrap();
683        assert_eq!(entry.baseline_sha256, Sha256::of(&seed));
684        assert!(candidate.notes.is_empty(), "{:?}", candidate.notes);
685    }
686
687    fn agents_bytes(candidate: &Candidate) -> String {
688        let agents = candidate
689            .destinations
690            .iter()
691            .find(|destination| destination.path == AGENTS_DIGEST_PATH)
692            .unwrap();
693        String::from_utf8(agents.bytes.clone()).unwrap()
694    }
695
696    #[test]
697    fn only_an_absent_host_receives_the_title() {
698        let absent = project(&input(ProfileId::Codebase)).unwrap();
699        let text = agents_bytes(&absent);
700        assert!(
701            text.starts_with(&format!("{AGENTS_TITLE}\n\n<!-- BEGIN")),
702            "{text}"
703        );
704
705        let mut empty = input(ProfileId::Codebase);
706        empty.evidence.agents_exists = true;
707        let text = agents_bytes(&project(&empty).unwrap());
708        assert!(text.starts_with("<!-- BEGIN"), "{text}");
709        assert!(!text.contains(AGENTS_TITLE), "{text}");
710        assert_ne!(agents_bytes(&absent), text);
711    }
712
713    #[test]
714    fn an_unmarked_documentation_section_is_kept_and_noted_without_a_title() {
715        let mut held = input(ProfileId::Codebase);
716        held.evidence.agents_exists = true;
717        held.evidence.agents_host = "## Documentation\n\n- Our own routing.\n".to_string();
718        let candidate = project(&held).unwrap();
719        let text = agents_bytes(&candidate);
720        assert!(
721            text.starts_with("## Documentation\n\n- Our own routing.\n\n<!-- BEGIN"),
722            "{text}"
723        );
724        assert!(!text.contains(AGENTS_TITLE), "{text}");
725        assert!(
726            candidate
727                .notes
728                .iter()
729                .any(|note| note.contains("unmarked '## Documentation' section")),
730            "{:?}",
731            candidate.notes
732        );
733    }
734
735    #[test]
736    fn a_seed_lands_rendered_for_its_root() {
737        let candidate = project(&input(ProfileId::Codebase)).unwrap();
738        let registry = candidate
739            .destinations
740            .iter()
741            .find(|destination| destination.path == "docs/reference/tracking.yaml")
742            .unwrap();
743        let text = String::from_utf8(registry.bytes.clone()).unwrap();
744        assert!(
745            text.contains("path: docs/reference/model-pricing.md"),
746            "{text}"
747        );
748        assert!(
749            !text.contains(crate::domain::profile::DOCS_ROOT_PLACEHOLDER),
750            "{text}"
751        );
752        let recorded = candidate
753            .manifest
754            .adopted_files
755            .iter()
756            .find(|entry| entry.destination == "docs/reference/tracking.yaml")
757            .unwrap();
758        assert_eq!(recorded.baseline_sha256, Sha256::of(&registry.bytes));
759        assert_ne!(
760            recorded.baseline_sha256,
761            Sha256::of(&source_bytes("templates/TEMPLATE-tracking.yaml").unwrap())
762        );
763    }
764
765    #[test]
766    fn every_projected_source_comes_from_the_embedded_inventory() {
767        let candidate = project(&input(ProfileId::Codebase)).unwrap();
768        for destination in &candidate.destinations {
769            let Some(source) = &destination.source else {
770                continue;
771            };
772            assert!(
773                crate::embedded::asset(source).is_some(),
774                "{source} is projected and not embedded"
775            );
776        }
777    }
778}