spec_driven_docs/services/
installer.rs1use camino::{Utf8Path, Utf8PathBuf};
12
13use crate::domain::manifest::{MANIFEST_PATH, validate_docs_scratch_path};
14use crate::domain::paths::{AGENTS_DIGEST_PATH, HOOKS_CONFIG_PATH};
15use crate::domain::profile::{ProfileId, resolve_destination};
16use crate::domain::version::CanonVersion;
17use crate::error::AppError;
18
19#[derive(Debug, Clone)]
21pub struct InitOptions {
22 pub target: Utf8PathBuf,
24 pub profile: ProfileId,
26 pub apply: bool,
28 pub dry_run: bool,
30 pub docs_scratch: Option<Option<Utf8PathBuf>>,
33 pub reserve: Vec<String>,
36 pub writing_style: Option<crate::domain::instance_config::WritingStyle>,
39 pub acquisition: Option<crate::domain::instance_config::Acquisition>,
42 pub replace: Vec<String>,
45}
46
47#[derive(Debug)]
49pub struct InitOutcome {
50 pub lines: Vec<String>,
52 pub applied: bool,
54 pub removed: Vec<String>,
56}
57
58fn canonical_target(target: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
59 if !target.is_absolute() {
60 return Err(AppError::Usage("target must be absolute".to_string()));
61 }
62 if !target.is_dir() {
63 return Err(AppError::Usage(format!("unresolved target: {target}")));
64 }
65 let canonical = std::fs::canonicalize(target)?;
66 let canonical = Utf8PathBuf::from_path_buf(canonical)
67 .map_err(|p| AppError::Usage(format!("target is not UTF-8: {}", p.display())))?;
68 if canonical.as_str().chars().all(|c| c == '/') {
69 return Err(AppError::Usage("refusing root target".to_string()));
70 }
71 let mut ancestor = Some(canonical.as_path());
72 while let Some(dir) = ancestor {
73 if let Ok(cargo) = std::fs::read_to_string(dir.join("Cargo.toml"))
74 && cargo.contains("name = \"spec-driven-docs\"")
75 {
76 return Err(AppError::Usage(
77 "target is inside the canon checkout".to_string(),
78 ));
79 }
80 ancestor = dir.parent();
81 }
82 Ok(canonical)
83}
84
85fn target_has_content(target: &Utf8Path) -> Result<bool, AppError> {
86 for entry in target.read_dir_utf8()? {
87 let entry = entry?;
88 if entry.file_name() != ".git" {
89 return Ok(true);
90 }
91 }
92 Ok(false)
93}
94
95pub(crate) fn recorded_field(target: &Utf8Path, key: &str) -> Option<serde_json::Value> {
101 std::fs::read_to_string(target.join(MANIFEST_PATH))
102 .ok()
103 .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
104 .and_then(|value| value.get(key).cloned())
105 .filter(|value| !value.is_null())
106}
107
108fn installed_at(target: &Utf8Path) -> String {
109 recorded_field(target, "installed_at")
110 .and_then(|value| value.as_str().map(String::from))
111 .unwrap_or_else(|| {
112 jiff::Timestamp::now()
113 .strftime("%Y-%m-%dT%H:%M:%SZ")
114 .to_string()
115 })
116}
117
118pub(crate) fn resolved_docs_scratch(
130 target: &Utf8Path,
131 flag: Option<&Option<Utf8PathBuf>>,
132) -> Result<Option<Utf8PathBuf>, AppError> {
133 if let Some(declared) = flag {
134 return Ok(declared.clone());
135 }
136 let Some(recorded) = recorded_field(target, "docs_scratch") else {
137 return Ok(None);
138 };
139 let path = recorded
140 .as_str()
141 .filter(|path| !path.is_empty())
142 .map(Utf8PathBuf::from)
143 .ok_or_else(|| {
144 AppError::ManifestInvalid(format!(
145 "the recorded docs_scratch is not a path ({recorded}); \
146 re-declare it with --docs-scratch"
147 ))
148 })?;
149 if let Err(error) = validate_docs_scratch_path(&path) {
150 return Err(AppError::ManifestInvalid(format!(
151 "the recorded docs_scratch is not usable ({error}); \
152 re-declare it with --docs-scratch"
153 )));
154 }
155 Ok(Some(path))
156}
157
158#[derive(Debug, Clone)]
164pub struct TargetState {
165 pub files: Vec<(Utf8PathBuf, Vec<u8>)>,
167 pub lines: Vec<String>,
169}
170
171pub fn compute_target_state(
184 target: &Utf8Path,
185 options: &InitOptions,
186) -> Result<TargetState, AppError> {
187 let candidate = candidate_for(target, options)?;
188 let mut lines: Vec<String> = Vec::new();
189 for destination in &candidate.destinations {
190 lines.push(destination.path.to_string());
191 }
192 lines.extend(candidate.notes.iter().cloned());
193 lines.push(MANIFEST_PATH.to_string());
194 Ok(TargetState {
195 files: candidate.files(),
196 lines,
197 })
198}
199
200pub fn candidate_for(
206 target: &Utf8Path,
207 options: &InitOptions,
208) -> Result<crate::candidate::Candidate, AppError> {
209 crate::candidate::project(&gather(target, options)?)
210}
211
212pub fn resolved_target(target: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
219 canonical_target(target)
220}
221
222#[must_use]
228pub fn present_at_root(target: &Utf8Path) -> Vec<String> {
229 let mut present: Vec<String> = Vec::new();
230 for projection in &crate::domain::profile::DECLARATION.adopted {
231 let Some(set) = projection.yield_set() else {
232 continue;
233 };
234 for name in set.names() {
235 if target.join(name).is_file() && !present.iter().any(|held| held == name) {
236 present.push(name.to_string());
237 }
238 }
239 }
240 present
241}
242
243fn gather(target: &Utf8Path, options: &InitOptions) -> Result<crate::candidate::Input, AppError> {
245 let docs_root = crate::candidate::docs_root_of(options.profile)?;
246
247 let recorded_adopted: Vec<String> = recorded_field(target, "adopted_files")
252 .and_then(|value| {
253 value.as_array().map(|entries| {
254 entries
255 .iter()
256 .filter_map(|entry| entry.get("destination")?.as_str().map(String::from))
257 .collect()
258 })
259 })
260 .unwrap_or_default();
261
262 let mut existing = std::collections::BTreeMap::new();
263 for projection in &crate::domain::profile::DECLARATION.adopted {
264 let destination = resolve_destination(&projection.destination, docs_root);
265 let path = target.join(&destination);
266 if path.is_file() {
267 existing.insert(destination, std::fs::read(&path)?);
268 }
269 }
270
271 let present_at_root = present_at_root(target);
272
273 let hooks_path = target.join(HOOKS_CONFIG_PATH);
274 let hooks_host = if hooks_path.is_file() {
275 std::fs::read_to_string(&hooks_path)?
276 } else {
277 String::new()
278 };
279
280 let agents_path = target.join(AGENTS_DIGEST_PATH);
284 if agents_path.is_symlink() {
285 return Err(AppError::Refused(
286 "AGENTS.md is a symlink; refusing to write the documentation block through it"
287 .to_string(),
288 ));
289 }
290 let agents_exists = agents_path.is_file();
291 let agents_host = if agents_exists {
292 std::fs::read_to_string(&agents_path)?
293 } else {
294 String::new()
295 };
296
297 Ok(crate::candidate::Input {
298 profile: options.profile,
299 version: CanonVersion::current(),
300 installed_at: installed_at(target),
301 docs_scratch: resolved_docs_scratch(target, options.docs_scratch.as_ref())?,
302 reserve: options.reserve.clone(),
303 writing_style: options.writing_style.clone(),
304 acquisition: options.acquisition.clone(),
305 evidence: crate::candidate::Evidence {
306 existing,
307 recorded_adopted,
308 hooks_host,
309 agents_host,
310 agents_exists,
311 present_at_root,
312 },
313 })
314}
315
316pub fn init(
325 options: &InitOptions,
326 intent: crate::landing::classify::Intent,
327) -> Result<InitOutcome, AppError> {
328 init_holding(None, options, intent)
329}
330
331pub fn init_holding(
340 held: Option<crate::transaction::lock::Lock>,
341 options: &InitOptions,
342 intent: crate::landing::classify::Intent,
343) -> Result<InitOutcome, AppError> {
344 let target = canonical_target(&options.target)?;
345 crate::commands::front::serves(intent, &target)?;
349 let forced_dry = !options.apply
350 && !options.dry_run
351 && target_has_content(&target)?
352 && !target.join(MANIFEST_PATH).is_file();
353 let dry = options.dry_run || forced_dry;
354
355 let held = match (dry, held) {
361 (true, _) => None,
362 (false, Some(held)) => Some(held),
363 (false, None) => Some(crate::landing::lock::hold(&target)?),
364 };
365
366 if let Some(recorded) = recorded_field(&target, "profile").and_then(|value| {
371 ProfileId::every().find(|profile| Some(profile.as_str()) == value.as_str())
372 }) && recorded != options.profile
373 {
374 return Err(AppError::Refused(format!(
375 "{target} records the {recorded} profile and this run asks for {}; \
376 moving a profile moves the documentation root, which is a migration to ask for deliberately",
377 options.profile
378 )));
379 }
380
381 let candidate = candidate_for(&target, options)?;
382 let mut lines: Vec<String> = candidate
383 .destinations
384 .iter()
385 .map(|destination| destination.path.to_string())
386 .collect();
387 lines.extend(candidate.notes.iter().cloned());
388 lines.push(MANIFEST_PATH.to_string());
389
390 if dry {
391 if forced_dry {
392 lines.push(
393 "DRY RUN: the target is a non-empty repository with no instance; re-run with --apply to write these files"
394 .to_string(),
395 );
396 }
397 lines.push("DRY RUN: no files written".to_string());
398 return Ok(InitOutcome {
399 lines,
400 applied: false,
401 removed: Vec::new(),
402 });
403 }
404
405 let mut vouched = recorded(&target);
406 vouched.replace.clone_from(&options.replace);
407 let outcome = crate::landing::apply::land(&target, &candidate, &vouched)?;
408 drop(held);
409 Ok(InitOutcome {
410 lines,
411 applied: true,
412 removed: outcome.removed,
413 })
414}
415
416pub(crate) fn recorded(target: &Utf8Path) -> crate::landing::apply::Recorded {
422 crate::landing::apply::Recorded {
423 managed: digests(target, "managed_files", "destination", "sha256"),
424 integration: digests(target, "integration_blocks", "path", "marker_hash"),
425 replace: Vec::new(),
426 }
427}
428
429fn digests(
431 target: &Utf8Path,
432 key: &str,
433 name: &str,
434 digest: &str,
435) -> Vec<(String, crate::domain::ownership::Sha256)> {
436 let Some(value) = recorded_field(target, key) else {
437 return Vec::new();
438 };
439 let Some(entries) = value.as_array() else {
440 return Vec::new();
441 };
442 entries
443 .iter()
444 .filter_map(|entry| {
445 let destination = entry.get(name)?.as_str()?.to_string();
446 let held = entry.get(digest)?.as_str()?;
447 let held = held.parse::<crate::domain::ownership::Sha256>().ok()?;
448 Some((destination, held))
449 })
450 .collect()
451}