spec_driven_docs/services/
installer.rs1use std::collections::BTreeMap;
12
13use camino::{Utf8Path, Utf8PathBuf};
14
15use crate::adapters::fs::{DestinationRefusal, check_destination, write_file};
16use crate::domain::manifest::{
17 CANON_SOURCE, MANIFEST_PATH, Manifest, PlanZone, SCHEMA_VERSION, validate_docs_scratch_path,
18 validate_plan_zone_path,
19};
20use crate::domain::ownership::{AdoptedEntry, IntegrationBlock, ManagedEntry, Sha256};
21use crate::domain::profile::{ProfileId, resolve_destination};
22use crate::domain::version::CanonVersion;
23use crate::error::AppError;
24use crate::services::hooks_render::{RenderOptions, render_block};
25use crate::services::verifier;
26
27#[derive(Debug, Clone)]
29pub struct InitOptions {
30 pub target: Utf8PathBuf,
32 pub profile: ProfileId,
34 pub apply: bool,
36 pub dry_run: bool,
38 pub plan_zone: Option<PlanZone>,
40 pub docs_scratch: Option<Option<Utf8PathBuf>>,
43 pub reserve: Vec<String>,
46}
47
48#[derive(Debug)]
50pub struct InitOutcome {
51 pub lines: Vec<String>,
53 pub applied: bool,
55}
56
57fn canonical_target(target: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
58 if !target.is_absolute() {
59 return Err(AppError::Usage("target must be absolute".to_string()));
60 }
61 if !target.is_dir() {
62 return Err(AppError::Usage(format!("unresolved target: {target}")));
63 }
64 let canonical = std::fs::canonicalize(target)?;
65 let canonical = Utf8PathBuf::from_path_buf(canonical)
66 .map_err(|p| AppError::Usage(format!("target is not UTF-8: {}", p.display())))?;
67 if canonical.as_str().chars().all(|c| c == '/') {
68 return Err(AppError::Usage("refusing root target".to_string()));
69 }
70 let mut ancestor = Some(canonical.as_path());
71 while let Some(dir) = ancestor {
72 if let Ok(cargo) = std::fs::read_to_string(dir.join("Cargo.toml"))
73 && cargo.contains("name = \"spec-driven-docs\"")
74 {
75 return Err(AppError::Usage(
76 "target is inside the canon checkout".to_string(),
77 ));
78 }
79 ancestor = dir.parent();
80 }
81 Ok(canonical)
82}
83
84fn target_has_content(target: &Utf8Path) -> Result<bool, AppError> {
85 for entry in target.read_dir_utf8()? {
86 let entry = entry?;
87 if entry.file_name() != ".git" {
88 return Ok(true);
89 }
90 }
91 Ok(false)
92}
93
94pub(crate) fn recorded_field(target: &Utf8Path, key: &str) -> Option<serde_json::Value> {
100 std::fs::read_to_string(target.join(MANIFEST_PATH))
101 .ok()
102 .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
103 .and_then(|value| value.get(key).cloned())
104 .filter(|value| !value.is_null())
105}
106
107fn installed_at(target: &Utf8Path) -> String {
108 recorded_field(target, "installed_at")
109 .and_then(|value| value.as_str().map(String::from))
110 .unwrap_or_else(|| {
111 jiff::Timestamp::now()
112 .strftime("%Y-%m-%dT%H:%M:%SZ")
113 .to_string()
114 })
115}
116
117pub(crate) fn resolved_plan_zone(
133 target: &Utf8Path,
134 flag: Option<&PlanZone>,
135) -> Result<PlanZone, AppError> {
136 if let Some(zone) = flag {
137 return Ok(zone.clone());
138 }
139 let Some(recorded) = recorded_field(target, "plan_zone") else {
140 return Ok(PlanZone::default());
141 };
142 let zone: PlanZone = serde_json::from_value(recorded).map_err(|source| {
143 AppError::ManifestInvalid(format!(
144 "the recorded plan_zone is in a shape this sdd does not read ({source}); \
145 upgrade sdd, or re-declare it with --plan-zone"
146 ))
147 })?;
148 if let Some(path) = zone.path()
152 && let Err(error) = validate_plan_zone_path(path)
153 {
154 return Err(AppError::ManifestInvalid(format!(
155 "the recorded plan_zone is not usable ({error}); re-declare it with --plan-zone"
156 )));
157 }
158 Ok(zone)
159}
160
161pub(crate) fn resolved_docs_scratch(
170 target: &Utf8Path,
171 flag: Option<&Option<Utf8PathBuf>>,
172) -> Result<Option<Utf8PathBuf>, AppError> {
173 if let Some(declared) = flag {
174 return Ok(declared.clone());
175 }
176 let Some(recorded) = recorded_field(target, "docs_scratch") else {
177 return Ok(None);
178 };
179 let path = recorded
180 .as_str()
181 .filter(|path| !path.is_empty())
182 .map(Utf8PathBuf::from)
183 .ok_or_else(|| {
184 AppError::ManifestInvalid(format!(
185 "the recorded docs_scratch is not a path ({recorded}); \
186 re-declare it with --docs-scratch"
187 ))
188 })?;
189 if let Err(error) = validate_docs_scratch_path(&path) {
190 return Err(AppError::ManifestInvalid(format!(
191 "the recorded docs_scratch is not usable ({error}); \
192 re-declare it with --docs-scratch"
193 )));
194 }
195 Ok(Some(path))
196}
197
198struct TargetState {
199 files: Vec<(Utf8PathBuf, Vec<u8>)>,
200 lines: Vec<String>,
201}
202
203#[allow(clippy::too_many_lines)]
205fn compute_target_state(target: &Utf8Path, options: &InitOptions) -> Result<TargetState, AppError> {
206 let profile = options.profile;
207 let declaration = profile.profile();
208 let mut files: Vec<(Utf8PathBuf, Vec<u8>)> = Vec::new();
209 let mut lines = Vec::new();
210 let mut managed_entries = Vec::new();
211 let mut adopted_entries = Vec::new();
212
213 for projection in declaration.managed {
214 let bytes = crate::embedded::asset(projection.source)
215 .ok_or_else(|| anyhow::anyhow!("payload asset missing: {}", projection.source))?;
216 let destination = Utf8PathBuf::from(projection.destination);
217 managed_entries.push(ManagedEntry {
218 source: projection.source.into(),
219 destination: destination.clone(),
220 sha256: Sha256::of(bytes),
221 });
222 lines.push(destination.to_string());
223 files.push((destination, bytes.to_vec()));
224 }
225
226 for projection in declaration.adopted {
227 let seed = crate::embedded::asset(projection.source)
228 .ok_or_else(|| anyhow::anyhow!("payload asset missing: {}", projection.source))?;
229 let destination = resolve_destination(projection.destination, declaration.docs_root);
230 let existing = target.join(&destination);
231 let mut bytes = if existing.is_file() {
232 std::fs::read(&existing)?
233 } else {
234 seed.to_vec()
235 };
236 if destination == crate::domain::instance_config::CONFIG_PATH && !options.reserve.is_empty()
239 {
240 if let Ok(text) = std::str::from_utf8(&bytes) {
241 bytes = crate::domain::instance_config::with_reserved(text, &options.reserve)
242 .into_bytes();
243 }
244 }
245 adopted_entries.push(AdoptedEntry {
246 source: projection.source.into(),
247 destination: destination.clone(),
248 sha256: Sha256::of(&bytes),
249 baseline_sha256: Sha256::of(seed),
250 });
251 lines.push(destination.to_string());
252 files.push((destination, bytes));
253 }
254
255 let config_path = target.join(".pre-commit-config.yaml");
256 let host = if config_path.is_file() {
257 std::fs::read_to_string(&config_path)?
258 } else {
259 "repos:\n".to_string()
260 };
261 let (base, _) = crate::domain::marker::split_block(&host)?;
262 let indent = crate::domain::marker::splice_indent(&base)?;
263 let declared = files
267 .iter()
268 .find(|(destination, _)| destination == crate::domain::instance_config::CONFIG_PATH)
269 .and_then(|(_, bytes)| std::str::from_utf8(bytes).ok())
270 .map(crate::domain::instance_config::InstanceConfig::parse)
271 .transpose()
272 .map_err(|error| anyhow::anyhow!("{error}"))?
273 .unwrap_or_default();
274 let block = render_block(&RenderOptions {
275 docs_root: declaration.docs_root.to_string(),
276 indent,
277 declaration: declared,
278 ..RenderOptions::default()
279 });
280 let spliced = crate::domain::marker::splice(&base, &block)?;
281 let marker_hash = crate::domain::marker::block_hash(&spliced)
282 .ok_or_else(|| anyhow::anyhow!("the rendered block lost its markers"))?;
283 lines.push(".pre-commit-config.yaml".to_string());
284 files.push((
285 Utf8PathBuf::from(".pre-commit-config.yaml"),
286 spliced.into_bytes(),
287 ));
288
289 let mut integration_blocks = vec![IntegrationBlock {
290 path: ".pre-commit-config.yaml".into(),
291 marker_hash,
292 }];
293
294 let agents_relative = Utf8Path::new("AGENTS.md");
298 if target.join(agents_relative).is_symlink() {
299 return Err(AppError::Refused(
300 "AGENTS.md is a symlink; refusing to write the documentation block through it"
301 .to_string(),
302 ));
303 }
304 let agents_host = if target.join(agents_relative).is_file() {
305 std::fs::read_to_string(target.join(agents_relative))?
306 } else {
307 String::new()
308 };
309 let agents_block =
310 crate::services::agents_render::render_block(&declaration.docs_root.to_string());
311 let agents = crate::domain::marker::place_agents_block(&agents_host, &agents_block)?;
312 let agents_hash = crate::domain::marker::block_hash_with(
313 &agents,
314 crate::domain::marker::AGENTS_BEGIN,
315 crate::domain::marker::AGENTS_END,
316 )
317 .ok_or_else(|| anyhow::anyhow!("the rendered AGENTS.md block lost its markers"))?;
318 if agents_host.contains("## Documentation")
321 && crate::domain::marker::block_region_with(
322 &agents_host,
323 crate::domain::marker::AGENTS_BEGIN,
324 crate::domain::marker::AGENTS_END,
325 )
326 .is_none()
327 {
328 lines.push(
329 "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(),
330 );
331 }
332 lines.push("AGENTS.md".to_string());
333 files.push((agents_relative.to_path_buf(), agents.into_bytes()));
334 integration_blocks.push(IntegrationBlock {
335 path: "AGENTS.md".into(),
336 marker_hash: agents_hash,
337 });
338
339 let manifest = Manifest {
340 schema_version: SCHEMA_VERSION,
341 canon_version: CanonVersion::current(),
342 canon_source: CANON_SOURCE.to_string(),
343 profile,
344 docs_root: declaration.docs_root,
345 installed_at: installed_at(target),
346 plan_zone: resolved_plan_zone(target, options.plan_zone.as_ref())?,
347 docs_scratch: resolved_docs_scratch(target, options.docs_scratch.as_ref())?,
348 managed_files: managed_entries,
349 adopted_files: adopted_entries,
350 integration_blocks,
351 };
352 lines.push(MANIFEST_PATH.to_string());
353 files.push((
354 Utf8PathBuf::from(MANIFEST_PATH),
355 manifest.to_json().into_bytes(),
356 ));
357
358 Ok(TargetState { files, lines })
359}
360
361fn refusal_line(destination: &Utf8Path, refusal: &DestinationRefusal) -> String {
362 match refusal {
363 DestinationRefusal::SymlinkEscape => {
364 format!("destination escapes the target through a symlink: {destination}")
365 }
366 DestinationRefusal::FileBlocksDirectory(blocked) => {
367 format!("a file blocks a directory the install needs: {blocked}")
368 }
369 DestinationRefusal::NotARegularFile => {
370 format!("destination exists and is not a regular file: {destination}")
371 }
372 }
373}
374
375fn apply(target: &Utf8Path, state: &TargetState) -> Result<(), AppError> {
376 let mut ordered: Vec<&(Utf8PathBuf, Vec<u8>)> = state.files.iter().collect();
377 ordered.sort_by(|a, b| a.0.as_str().as_bytes().cmp(b.0.as_str().as_bytes()));
378
379 for (destination, _) in &ordered {
380 check_destination(target, destination)
381 .map_err(|refusal| AppError::Refused(refusal_line(destination, &refusal)))?;
382 }
383
384 let mut backups: BTreeMap<Utf8PathBuf, Option<Vec<u8>>> = BTreeMap::new();
385 let rollback = |backups: &BTreeMap<Utf8PathBuf, Option<Vec<u8>>>| -> Vec<Utf8PathBuf> {
386 let mut unrestored = Vec::new();
387 for (destination, previous) in backups {
388 let full = target.join(destination);
389 let restored = previous.as_ref().map_or_else(
390 || std::fs::remove_file(&full).is_ok() || !full.exists(),
391 |bytes| write_file(&full, bytes).is_ok(),
392 );
393 if !restored {
394 unrestored.push(destination.clone());
395 }
396 }
397 unrestored
398 };
399 let abort = |unrestored: Vec<Utf8PathBuf>, cause: &str| {
403 if unrestored.is_empty() {
404 AppError::Refused(format!("apply aborted; the target was restored: {cause}"))
405 } else {
406 let paths: Vec<&str> = unrestored.iter().map(|p| p.as_str()).collect();
407 AppError::Refused(format!(
408 "apply aborted and restoration is incomplete; verify by hand: {}: {cause}",
409 paths.join(" ")
410 ))
411 }
412 };
413
414 for (destination, _) in &ordered {
415 let full = target.join(destination);
416 let previous = if full.is_file() {
417 Some(std::fs::read(&full).map_err(|source| {
418 AppError::Refused(format!("cannot back up {destination}: {source}"))
419 })?)
420 } else {
421 None
422 };
423 backups.insert((*destination).clone(), previous);
424 }
425
426 let write_all = || -> std::io::Result<()> {
427 for (destination, bytes) in &ordered {
428 if destination.as_str() != MANIFEST_PATH {
429 write_file(&target.join(destination), bytes)?;
430 }
431 }
432 for (destination, bytes) in &ordered {
433 if destination.as_str() == MANIFEST_PATH {
434 write_file(&target.join(destination), bytes)?;
435 }
436 }
437 Ok(())
438 };
439
440 if let Err(source) = write_all() {
441 return Err(abort(
442 rollback(&backups),
443 &format!("write failed: {source}"),
444 ));
445 }
446
447 match verifier::verify(target) {
448 Ok(report) if report.failures == 0 => Ok(()),
449 Ok(report) => {
450 let failures: Vec<&str> = report
451 .lines
452 .iter()
453 .filter(|line| line.starts_with("FAIL"))
454 .map(String::as_str)
455 .collect();
456 let cause = failures.join("; ");
457 Err(abort(rollback(&backups), &cause))
458 }
459 Err(source) => Err(abort(
460 rollback(&backups),
461 &format!("the written target could not be verified: {source}"),
462 )),
463 }
464}
465
466pub fn init(options: &InitOptions) -> Result<InitOutcome, AppError> {
475 let target = canonical_target(&options.target)?;
476 let forced_dry = !options.apply
477 && !options.dry_run
478 && target_has_content(&target)?
479 && !target.join(MANIFEST_PATH).is_file();
480 let dry = options.dry_run || forced_dry;
481
482 let state = compute_target_state(&target, options)?;
483 let mut lines = state.lines.clone();
484
485 if dry {
486 if forced_dry {
487 lines.push(
488 "DRY RUN: the target is a non-empty repository with no instance; re-run with --apply to write these files"
489 .to_string(),
490 );
491 }
492 lines.push("DRY RUN: no files written".to_string());
493 return Ok(InitOutcome {
494 lines,
495 applied: false,
496 });
497 }
498
499 apply(&target, &state)?;
500 Ok(InitOutcome {
501 lines,
502 applied: true,
503 })
504}