1use 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
27pub const AGENTS_TITLE: &str = "# AGENTS";
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Ownership {
33 Managed,
35 Adopted,
37 Integration,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum Placement {
44 WholeFile,
46 MarkedRegion,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Destination {
53 pub path: Utf8PathBuf,
55 pub bytes: Vec<u8>,
57 pub ownership: Ownership,
59 pub placement: Placement,
61 pub source: Option<String>,
63}
64
65#[derive(Debug, Clone)]
67pub struct Candidate {
68 pub destinations: Vec<Destination>,
70 pub manifest: Manifest,
72 pub declaration: InstanceConfig,
78 pub notes: Vec<String>,
80}
81
82impl Candidate {
83 #[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#[derive(Debug, Clone, Default)]
105pub struct Evidence {
106 pub existing: BTreeMap<Utf8PathBuf, Vec<u8>>,
108 pub recorded_adopted: Vec<String>,
110 pub hooks_host: String,
112 pub agents_host: String,
114 pub agents_exists: bool,
119 pub present_at_root: Vec<String>,
121}
122
123#[derive(Debug, Clone)]
125pub struct Input {
126 pub profile: ProfileId,
128 pub version: CanonVersion,
130 pub installed_at: String,
132 pub docs_scratch: Option<Utf8PathBuf>,
134 pub reserve: Vec<String>,
136 pub writing_style: Option<WritingStyle>,
138 pub acquisition: Option<crate::domain::instance_config::Acquisition>,
140 pub evidence: Evidence,
142}
143
144#[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 for projection in declared.adopted {
188 let seed = rendered_seed(&projection.source, docs_root)?;
189 let path = resolve_destination(&projection.destination, docs_root);
190 let recorded = input
191 .evidence
192 .recorded_adopted
193 .iter()
194 .any(|recorded| recorded == path.as_str());
195 if !recorded
201 && let Some(cause) = projection.yield_set().and_then(|set| {
202 set.names().find(|name| {
203 input
204 .evidence
205 .present_at_root
206 .iter()
207 .any(|held| held == name)
208 })
209 })
210 {
211 notes.push(format!(
212 "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"
213 ));
214 continue;
215 }
216 let mut held = input.evidence.existing.get(&path);
217 let migration = (path == crate::domain::instance_config::CONFIG_PATH && !recorded)
222 .then(|| held.and_then(|bytes| pending_migration(bytes)))
223 .flatten();
224 if migration.is_some() {
225 held = None;
226 }
227 if let Some(held) = held
228 && held != &seed
229 && !recorded
230 {
231 notes.push(format!(
232 "note: {path} already exists and is kept; the seed was not written, so read it with 'sdd spec' and reconcile by hand"
233 ));
234 }
235 let mut bytes = held.cloned().unwrap_or_else(|| seed.clone());
236 if path == crate::domain::instance_config::CONFIG_PATH {
245 let (text, held) = readable(&path, &bytes)?;
246 let mut text = text.to_string();
247 let reserve: Vec<String> = input
248 .reserve
249 .iter()
250 .filter(|pattern| !held.reserved.contains(pattern))
251 .cloned()
252 .collect();
253 if !reserve.is_empty() {
254 text = crate::domain::instance_config::with_reserved(&text, &reserve);
255 }
256 if let Some(selection) = &input.writing_style
257 && *selection != held.writing_style
258 {
259 text = crate::domain::instance_config::with_writing_style(&text, selection);
260 }
261 if let Some(decision) = &input.acquisition
262 && held.acquisition.as_ref() != Some(decision)
263 {
264 text = crate::domain::instance_config::with_acquisition(&text, decision);
265 }
266 if let Some(id) = &migration {
267 text = crate::domain::instance_config::with_migration(&text, id);
268 }
269 bytes = text.into_bytes();
270 }
271 adopted_entries.push(AdoptedEntry {
272 source: projection.source.clone().into(),
273 destination: path.clone(),
274 sha256: Sha256::of(&bytes),
275 baseline_sha256: Sha256::of(&seed),
276 });
277 destinations.push(Destination {
278 path,
279 bytes,
280 ownership: Ownership::Adopted,
281 placement: Placement::WholeFile,
282 source: Some(projection.source.clone()),
283 });
284 }
285
286 let host = if input.evidence.hooks_host.is_empty() {
287 "repos:\n".to_string()
288 } else {
289 input.evidence.hooks_host.clone()
290 };
291 let (base, _) = crate::domain::marker::split_block(&host)?;
292 let indent = crate::domain::marker::splice_indent(&base)?;
293 let declared = destinations
299 .iter()
300 .find(|destination| destination.path == crate::domain::instance_config::CONFIG_PATH);
301 let declaration = match declared {
302 Some(destination) => readable(&destination.path, &destination.bytes)?.1,
303 None => InstanceConfig::default(),
304 };
305 let writing_style = declaration.writing_style.clone();
306 let block = render_block(&RenderOptions {
307 docs_root: docs_root.to_string(),
308 indent,
309 declaration: declaration.clone(),
310 ..RenderOptions::default()
311 });
312 let spliced = crate::domain::marker::splice(&base, &block)?;
313 let marker_hash = crate::domain::marker::block_hash(&spliced)
314 .ok_or_else(|| anyhow::anyhow!("the rendered block lost its markers"))?;
315 destinations.push(Destination {
316 path: Utf8PathBuf::from(HOOKS_CONFIG_PATH),
317 bytes: spliced.into_bytes(),
318 ownership: Ownership::Integration,
319 placement: Placement::MarkedRegion,
320 source: None,
321 });
322 let mut integration_blocks = vec![IntegrationBlock {
323 path: HOOKS_CONFIG_PATH.into(),
324 marker_hash,
325 }];
326
327 let agents_block =
328 crate::services::agents_render::render_block(&docs_root.to_string(), &writing_style);
329 let mut agents =
330 crate::domain::marker::place_agents_block(&input.evidence.agents_host, &agents_block)?;
331 if !input.evidence.agents_exists {
335 agents = format!("{AGENTS_TITLE}\n\n{agents}");
336 }
337 let agents_hash = crate::domain::marker::block_hash_with(
338 &agents,
339 crate::domain::marker::AGENTS_BEGIN,
340 crate::domain::marker::AGENTS_END,
341 )
342 .ok_or_else(|| anyhow::anyhow!("the rendered AGENTS.md block lost its markers"))?;
343 if input.evidence.agents_host.contains("## Documentation")
346 && crate::domain::marker::block_region_with(
347 &input.evidence.agents_host,
348 crate::domain::marker::AGENTS_BEGIN,
349 crate::domain::marker::AGENTS_END,
350 )
351 .is_none()
352 {
353 notes.push(
354 "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(),
355 );
356 }
357 destinations.push(Destination {
358 path: Utf8PathBuf::from(AGENTS_DIGEST_PATH),
359 bytes: agents.into_bytes(),
360 ownership: Ownership::Integration,
361 placement: Placement::MarkedRegion,
362 source: None,
363 });
364 integration_blocks.push(IntegrationBlock {
365 path: AGENTS_DIGEST_PATH.into(),
366 marker_hash: agents_hash,
367 });
368
369 one_destination_each(&destinations)?;
370
371 let manifest = Manifest {
372 schema_version: SCHEMA_VERSION,
373 canon_version: input.version,
374 canon_source: CANON_SOURCE.to_string(),
375 profile: input.profile,
376 docs_root,
377 installed_at: input.installed_at.clone(),
378 docs_scratch: input.docs_scratch.clone(),
379 managed_files: managed_entries,
380 adopted_files: adopted_entries,
381 integration_blocks,
382 };
383
384 Ok(Candidate {
385 destinations,
386 manifest,
387 declaration,
388 notes,
389 })
390}
391
392pub fn docs_root_of(profile: ProfileId) -> Result<DocsRoot, AppError> {
398 crate::domain::profile::DECLARATION
399 .docs_root(profile)
400 .ok_or_else(|| {
401 AppError::Refused(format!(
402 "this release declares no {profile} profile, so it cannot land one"
403 ))
404 })
405}
406
407fn pending_migration(bytes: &[u8]) -> Option<String> {
410 let text = std::str::from_utf8(bytes).ok()?;
411 let declaration = InstanceConfig::parse(text).ok()?;
412 let id = declaration.migration.clone()?;
413 let bare = InstanceConfig {
414 migration: None,
415 ..declaration
416 };
417 (bare == InstanceConfig::default()
418 && crate::domain::instance_config::with_migration("", &id) == text)
419 .then_some(id)
420}
421
422fn readable<'a>(
429 path: &Utf8PathBuf,
430 bytes: &'a [u8],
431) -> Result<(&'a str, InstanceConfig), AppError> {
432 let text = std::str::from_utf8(bytes).map_err(|source| {
433 AppError::Refused(format!(
434 "{path} is not UTF-8, so what the gates judge cannot be read: {source}"
435 ))
436 })?;
437 let declaration = InstanceConfig::parse(text)
438 .map_err(|error| AppError::Refused(format!("{path} does not parse: {error}")))?;
439 Ok((text, declaration))
440}
441
442pub fn source_bytes(source: &str) -> Result<Vec<u8>, AppError> {
448 crate::embedded::asset(source)
449 .map(<[u8]>::to_vec)
450 .ok_or_else(|| {
451 AppError::Refused(format!(
452 "this release projects {source}, and its own payload does not carry it"
453 ))
454 })
455}
456
457pub fn rendered_seed(source: &str, docs_root: DocsRoot) -> Result<Vec<u8>, AppError> {
470 let bytes = source_bytes(source)?;
471 let rendered = std::str::from_utf8(&bytes)
472 .ok()
473 .map(|text| render_root(text, docs_root.as_str()).into_bytes());
474 Ok(rendered.unwrap_or(bytes))
475}
476
477fn one_destination_each(destinations: &[Destination]) -> Result<(), AppError> {
479 let mut seen: Vec<&Utf8PathBuf> = Vec::with_capacity(destinations.len());
480 for destination in destinations {
481 if seen.contains(&&destination.path) {
482 return Err(AppError::Refused(format!(
483 "{} is projected twice, so the candidate does not describe one file",
484 destination.path
485 )));
486 }
487 seen.push(&destination.path);
488 }
489 Ok(())
490}
491
492#[cfg(test)]
493mod tests {
494 #![allow(
495 clippy::unwrap_used,
496 reason = "a test panics as its failure signal, not as control flow"
497 )]
498
499 use super::*;
500
501 fn input(profile: ProfileId) -> Input {
502 Input {
503 profile,
504 version: CanonVersion::current(),
505 installed_at: "2026-01-01T00:00:00Z".to_string(),
506 docs_scratch: None,
507 reserve: Vec::new(),
508 writing_style: None,
509 acquisition: None,
510 evidence: Evidence::default(),
511 }
512 }
513
514 #[test]
515 fn equal_inputs_render_byte_identical_candidates() {
516 let first = project(&input(ProfileId::Codebase)).unwrap();
517 let second = project(&input(ProfileId::Codebase)).unwrap();
518 assert_eq!(first.destinations, second.destinations);
519 assert_eq!(first.manifest.to_json(), second.manifest.to_json());
520 }
521
522 #[test]
523 fn every_profile_lands_its_own_root() {
524 for profile in ProfileId::every() {
525 let candidate = project(&input(profile)).unwrap();
526 assert_eq!(candidate.manifest.profile, profile);
527 assert_eq!(candidate.manifest.docs_root, docs_root_of(profile).unwrap());
528 }
529 }
530
531 #[test]
532 fn the_record_is_the_last_file_a_landing_writes() {
533 let candidate = project(&input(ProfileId::KnowledgeBase)).unwrap();
534 let files = candidate.files();
535 assert_eq!(files.last().unwrap().0, Utf8PathBuf::from(MANIFEST_PATH));
536 assert_eq!(files.len(), candidate.destinations.len() + 1);
537 }
538
539 #[test]
540 fn one_documentation_root_serves_the_whole_candidate() {
541 let candidate = project(&input(ProfileId::KnowledgeBase)).unwrap();
542 let root = candidate.manifest.docs_root;
543 let root_seeds: Vec<&str> = crate::domain::profile::DECLARATION
544 .adopted
545 .iter()
546 .filter(|projection| projection.yield_set().is_some())
547 .map(|projection| projection.destination.as_str())
548 .collect();
549 assert_eq!(root_seeds, [".markdownlint-cli2.jsonc"]);
550 for entry in candidate
551 .manifest
552 .managed_files
553 .iter()
554 .map(|entry| &entry.destination)
555 .chain(
556 candidate
557 .manifest
558 .adopted_files
559 .iter()
560 .map(|entry| &entry.destination),
561 )
562 {
563 if entry == crate::domain::paths::CONFIG_PATH || root_seeds.contains(&entry.as_str()) {
564 continue;
565 }
566 assert!(
567 entry.as_str().starts_with(&format!("{root}/")),
568 "{entry} is outside the recorded root {root}"
569 );
570 }
571 }
572
573 #[test]
574 fn an_adopted_destination_the_project_wrote_is_kept_and_noted() {
575 let mut held = input(ProfileId::KnowledgeBase);
576 let candidate = project(&held).unwrap();
577 let adopted = candidate
578 .destinations
579 .iter()
580 .find(|destination| {
581 destination.ownership == Ownership::Adopted
582 && destination.path != crate::domain::paths::CONFIG_PATH
583 })
584 .unwrap()
585 .clone();
586 held.evidence
587 .existing
588 .insert(adopted.path.clone(), b"the project wrote this".to_vec());
589
590 let second = project(&held).unwrap();
591 let kept = second
592 .destinations
593 .iter()
594 .find(|destination| destination.path == adopted.path)
595 .unwrap();
596 assert_eq!(kept.bytes, b"the project wrote this");
597 assert!(
598 second
599 .notes
600 .iter()
601 .any(|note| note.contains(adopted.path.as_str()))
602 );
603 }
604
605 #[test]
606 fn a_recorded_adopted_destination_is_kept_without_a_note() {
607 let mut held = input(ProfileId::KnowledgeBase);
608 let candidate = project(&held).unwrap();
609 let adopted = candidate
610 .destinations
611 .iter()
612 .find(|destination| {
613 destination.ownership == Ownership::Adopted
614 && destination.path != crate::domain::paths::CONFIG_PATH
615 })
616 .unwrap()
617 .clone();
618 held.evidence
619 .existing
620 .insert(adopted.path.clone(), b"the project wrote this".to_vec());
621 held.evidence
622 .recorded_adopted
623 .push(adopted.path.to_string());
624
625 let second = project(&held).unwrap();
626 assert!(second.notes.is_empty(), "{:?}", second.notes);
627 }
628
629 #[test]
630 fn a_marked_region_preserves_every_byte_outside_it() {
631 let mut held = input(ProfileId::Codebase);
632 held.evidence.agents_host = "# Project\n\nOur own paragraph.\n".to_string();
633 held.evidence.agents_exists = true;
634 let candidate = project(&held).unwrap();
635 let agents = candidate
636 .destinations
637 .iter()
638 .find(|destination| destination.path == AGENTS_DIGEST_PATH)
639 .unwrap();
640 let text = String::from_utf8(agents.bytes.clone()).unwrap();
641 assert!(text.contains("Our own paragraph."));
642 assert_eq!(agents.placement, Placement::MarkedRegion);
643 }
644
645 #[test]
646 fn a_declaration_that_cannot_be_read_refuses_rather_than_defaulting() {
647 let mut held = input(ProfileId::KnowledgeBase);
648 held.evidence.existing.insert(
649 Utf8PathBuf::from(crate::domain::paths::CONFIG_PATH),
650 b"\xff\xfe not text".to_vec(),
651 );
652 let error = project(&held).unwrap_err();
653 assert!(error.to_string().contains("not UTF-8"), "{error}");
654
655 held.evidence.existing.insert(
656 Utf8PathBuf::from(crate::domain::paths::CONFIG_PATH),
657 b"reserved: [".to_vec(),
658 );
659 let error = project(&held).unwrap_err();
660 assert!(error.to_string().contains("does not parse"), "{error}");
661
662 held.reserve = vec!["vendor/**".to_string()];
666 let error = project(&held).unwrap_err();
667 assert!(error.to_string().contains("does not parse"), "{error}");
668 }
669
670 const ROOT_SEED: &str = ".markdownlint-cli2.jsonc";
671
672 #[test]
673 fn a_yielding_seed_the_record_does_not_name_is_not_introduced() {
674 let mut held = input(ProfileId::Codebase);
675 held.evidence.present_at_root = vec![".markdownlint.yaml".to_string()];
676 let candidate = project(&held).unwrap();
677 assert!(
678 !candidate
679 .destinations
680 .iter()
681 .any(|destination| destination.path == ROOT_SEED)
682 );
683 assert!(
684 !candidate
685 .manifest
686 .adopted_files
687 .iter()
688 .any(|entry| entry.destination == ROOT_SEED)
689 );
690 assert!(
691 candidate
692 .notes
693 .iter()
694 .any(|note| note.contains(&format!("{ROOT_SEED} was not seeded"))
695 && note.contains("already holds .markdownlint.yaml")),
696 "{:?}",
697 candidate.notes
698 );
699 }
700
701 #[test]
702 fn a_yielding_seed_the_record_names_stays_adopted() {
703 let mut held = input(ProfileId::Codebase);
704 let seed = rendered_seed("instance/seeds/markdownlint-cli2.jsonc", DocsRoot::Docs).unwrap();
705 held.evidence.present_at_root = vec![ROOT_SEED.to_string()];
708 held.evidence.existing.insert(
709 Utf8PathBuf::from(ROOT_SEED),
710 b"{ \"edited\": true }\n".to_vec(),
711 );
712 held.evidence.recorded_adopted.push(ROOT_SEED.to_string());
713
714 let candidate = project(&held).unwrap();
715 let kept = candidate
716 .destinations
717 .iter()
718 .find(|destination| destination.path == ROOT_SEED)
719 .unwrap();
720 assert_eq!(kept.bytes, b"{ \"edited\": true }\n");
721 assert_eq!(kept.ownership, Ownership::Adopted);
722 let entry = candidate
723 .manifest
724 .adopted_files
725 .iter()
726 .find(|entry| entry.destination == ROOT_SEED)
727 .unwrap();
728 assert_eq!(entry.baseline_sha256, Sha256::of(&seed));
729 assert!(candidate.notes.is_empty(), "{:?}", candidate.notes);
730 }
731
732 fn agents_bytes(candidate: &Candidate) -> String {
733 let agents = candidate
734 .destinations
735 .iter()
736 .find(|destination| destination.path == AGENTS_DIGEST_PATH)
737 .unwrap();
738 String::from_utf8(agents.bytes.clone()).unwrap()
739 }
740
741 #[test]
742 fn only_an_absent_host_receives_the_title() {
743 let absent = project(&input(ProfileId::Codebase)).unwrap();
744 let text = agents_bytes(&absent);
745 assert!(
746 text.starts_with(&format!("{AGENTS_TITLE}\n\n<!-- BEGIN")),
747 "{text}"
748 );
749
750 let mut empty = input(ProfileId::Codebase);
751 empty.evidence.agents_exists = true;
752 let text = agents_bytes(&project(&empty).unwrap());
753 assert!(text.starts_with("<!-- BEGIN"), "{text}");
754 assert!(!text.contains(AGENTS_TITLE), "{text}");
755 assert_ne!(agents_bytes(&absent), text);
756 }
757
758 #[test]
759 fn an_unmarked_documentation_section_is_kept_and_noted_without_a_title() {
760 let mut held = input(ProfileId::Codebase);
761 held.evidence.agents_exists = true;
762 held.evidence.agents_host = "## Documentation\n\n- Our own routing.\n".to_string();
763 let candidate = project(&held).unwrap();
764 let text = agents_bytes(&candidate);
765 assert!(
766 text.starts_with("## Documentation\n\n- Our own routing.\n\n<!-- BEGIN"),
767 "{text}"
768 );
769 assert!(!text.contains(AGENTS_TITLE), "{text}");
770 assert!(
771 candidate
772 .notes
773 .iter()
774 .any(|note| note.contains("unmarked '## Documentation' section")),
775 "{:?}",
776 candidate.notes
777 );
778 }
779
780 #[test]
781 fn a_seed_lands_rendered_for_its_root() {
782 let candidate = project(&input(ProfileId::Codebase)).unwrap();
783 let registry = candidate
784 .destinations
785 .iter()
786 .find(|destination| destination.path == "docs/reference/tracking.yaml")
787 .unwrap();
788 let text = String::from_utf8(registry.bytes.clone()).unwrap();
789 assert!(
790 text.contains("path: docs/reference/model-pricing.md"),
791 "{text}"
792 );
793 assert!(
794 !text.contains(crate::domain::profile::DOCS_ROOT_PLACEHOLDER),
795 "{text}"
796 );
797 let recorded = candidate
798 .manifest
799 .adopted_files
800 .iter()
801 .find(|entry| entry.destination == "docs/reference/tracking.yaml")
802 .unwrap();
803 assert_eq!(recorded.baseline_sha256, Sha256::of(®istry.bytes));
804 assert_ne!(
805 recorded.baseline_sha256,
806 Sha256::of(&source_bytes("templates/TEMPLATE-tracking.yaml").unwrap())
807 );
808 }
809
810 #[test]
811 fn every_projected_source_comes_from_the_embedded_inventory() {
812 let candidate = project(&input(ProfileId::Codebase)).unwrap();
813 for destination in &candidate.destinations {
814 let Some(source) = &destination.source else {
815 continue;
816 };
817 assert!(
818 crate::embedded::asset(source).is_some(),
819 "{source} is projected and not embedded"
820 );
821 }
822 }
823}