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>,
57 pub dropped: Vec<String>,
60}
61
62fn canonical_target(target: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
63 if !target.is_absolute() {
64 return Err(AppError::Usage("target must be absolute".to_string()));
65 }
66 if !target.is_dir() {
67 return Err(AppError::Usage(format!("unresolved target: {target}")));
68 }
69 let canonical = std::fs::canonicalize(target)?;
70 let canonical = Utf8PathBuf::from_path_buf(canonical)
71 .map_err(|p| AppError::Usage(format!("target is not UTF-8: {}", p.display())))?;
72 if canonical.as_str().chars().all(|c| c == '/') {
76 return Err(AppError::Usage("refusing root target".to_string()));
77 }
78 Ok(canonical)
79}
80
81fn target_has_content(target: &Utf8Path) -> Result<bool, AppError> {
82 for entry in target.read_dir_utf8()? {
83 let entry = entry?;
84 if entry.file_name() != ".git" {
85 return Ok(true);
86 }
87 }
88 Ok(false)
89}
90
91pub(crate) fn recorded_field(target: &Utf8Path, key: &str) -> Option<serde_json::Value> {
97 std::fs::read_to_string(target.join(MANIFEST_PATH))
98 .ok()
99 .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
100 .and_then(|value| value.get(key).cloned())
101 .filter(|value| !value.is_null())
102}
103
104fn installed_at(target: &Utf8Path) -> String {
105 recorded_field(target, "installed_at")
106 .and_then(|value| value.as_str().map(String::from))
107 .unwrap_or_else(|| {
108 jiff::Timestamp::now()
109 .strftime("%Y-%m-%dT%H:%M:%SZ")
110 .to_string()
111 })
112}
113
114pub(crate) fn resolved_docs_scratch(
126 target: &Utf8Path,
127 flag: Option<&Option<Utf8PathBuf>>,
128) -> Result<Option<Utf8PathBuf>, AppError> {
129 if let Some(declared) = flag {
130 return Ok(declared.clone());
131 }
132 let Some(recorded) = recorded_field(target, "docs_scratch") else {
133 return Ok(None);
134 };
135 let path = recorded
136 .as_str()
137 .filter(|path| !path.is_empty())
138 .map(Utf8PathBuf::from)
139 .ok_or_else(|| {
140 AppError::ManifestInvalid(format!(
141 "the recorded docs_scratch is not a path ({recorded}); \
142 re-declare it with --docs-scratch"
143 ))
144 })?;
145 if let Err(error) = validate_docs_scratch_path(&path) {
146 return Err(AppError::ManifestInvalid(format!(
147 "the recorded docs_scratch is not usable ({error}); \
148 re-declare it with --docs-scratch"
149 )));
150 }
151 Ok(Some(path))
152}
153
154#[derive(Debug, Clone)]
160pub struct TargetState {
161 pub files: Vec<(Utf8PathBuf, Vec<u8>)>,
163 pub lines: Vec<String>,
165}
166
167pub fn compute_target_state(
180 target: &Utf8Path,
181 options: &InitOptions,
182) -> Result<TargetState, AppError> {
183 let candidate = candidate_for(target, options)?;
184 let mut lines: Vec<String> = Vec::new();
185 for destination in &candidate.destinations {
186 lines.push(destination.path.to_string());
187 }
188 lines.extend(candidate.notes.iter().cloned());
189 lines.push(MANIFEST_PATH.to_string());
190 Ok(TargetState {
191 files: candidate.files(),
192 lines,
193 })
194}
195
196pub fn candidate_for(
202 target: &Utf8Path,
203 options: &InitOptions,
204) -> Result<crate::candidate::Candidate, AppError> {
205 crate::candidate::project(&gather(target, options)?)
206}
207
208pub fn resolved_target(target: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
215 canonical_target(target)
216}
217
218#[must_use]
224pub fn present_at_root(target: &Utf8Path) -> Vec<String> {
225 let mut present: Vec<String> = Vec::new();
226 for projection in &crate::domain::profile::DECLARATION.adopted {
227 let Some(set) = projection.yield_set() else {
228 continue;
229 };
230 for name in set.names() {
231 if target.join(name).is_file() && !present.iter().any(|held| held == name) {
232 present.push(name.to_string());
233 }
234 }
235 }
236 present
237}
238
239fn gather(target: &Utf8Path, options: &InitOptions) -> Result<crate::candidate::Input, AppError> {
241 let docs_root = crate::candidate::docs_root_of(options.profile)?;
242
243 let recorded_adopted: Vec<String> = recorded_field(target, "adopted_files")
248 .and_then(|value| {
249 value.as_array().map(|entries| {
250 entries
251 .iter()
252 .filter_map(|entry| entry.get("destination")?.as_str().map(String::from))
253 .collect()
254 })
255 })
256 .unwrap_or_default();
257
258 let mut existing = std::collections::BTreeMap::new();
259 for projection in &crate::domain::profile::DECLARATION.adopted {
260 let destination = resolve_destination(&projection.destination, docs_root);
261 let path = target.join(&destination);
262 if path.is_file() {
263 existing.insert(destination, std::fs::read(&path)?);
264 }
265 }
266
267 let present_at_root = present_at_root(target);
268
269 let hooks_path = target.join(HOOKS_CONFIG_PATH);
270 let hooks_host = if hooks_path.is_file() {
271 std::fs::read_to_string(&hooks_path)?
272 } else {
273 String::new()
274 };
275
276 let agents_path = target.join(AGENTS_DIGEST_PATH);
280 if agents_path.is_symlink() {
281 return Err(AppError::Refused(
282 "AGENTS.md is a symlink; refusing to write the documentation block through it"
283 .to_string(),
284 ));
285 }
286 let agents_exists = agents_path.is_file();
287 let agents_host = if agents_exists {
288 std::fs::read_to_string(&agents_path)?
289 } else {
290 String::new()
291 };
292
293 Ok(crate::candidate::Input {
294 profile: options.profile,
295 version: CanonVersion::current(),
296 installed_at: installed_at(target),
297 docs_scratch: resolved_docs_scratch(target, options.docs_scratch.as_ref())?,
298 reserve: options.reserve.clone(),
299 writing_style: options.writing_style.clone(),
300 acquisition: options.acquisition.clone(),
301 evidence: crate::candidate::Evidence {
302 existing,
303 recorded_adopted,
304 hooks_host,
305 agents_host,
306 agents_exists,
307 present_at_root,
308 },
309 })
310}
311
312pub fn init(
321 options: &InitOptions,
322 intent: crate::landing::classify::Intent,
323) -> Result<InitOutcome, AppError> {
324 init_holding(None, options, intent)
325}
326
327pub fn init_holding(
336 held: Option<crate::transaction::lock::Lock>,
337 options: &InitOptions,
338 intent: crate::landing::classify::Intent,
339) -> Result<InitOutcome, AppError> {
340 let target = canonical_target(&options.target)?;
341 crate::commands::front::serves(intent, &target)?;
345 let forced_dry = !options.apply
346 && !options.dry_run
347 && target_has_content(&target)?
348 && !target.join(MANIFEST_PATH).is_file();
349 let dry = options.dry_run || forced_dry;
350
351 let held = match (dry, held) {
357 (true, _) => None,
358 (false, Some(held)) => Some(held),
359 (false, None) => Some(crate::landing::lock::hold(&target)?),
360 };
361
362 if let Some(recorded) = recorded_field(&target, "profile").and_then(|value| {
367 ProfileId::every().find(|profile| Some(profile.as_str()) == value.as_str())
368 }) && recorded != options.profile
369 {
370 return Err(AppError::Refused(format!(
371 "{target} records the {recorded} profile and this run asks for {}; \
372 moving a profile moves the documentation root, which is a migration to ask for deliberately",
373 options.profile
374 )));
375 }
376
377 let candidate = candidate_for(&target, options)?;
378 let mut lines: Vec<String> = candidate
379 .destinations
380 .iter()
381 .map(|destination| destination.path.to_string())
382 .collect();
383 lines.extend(candidate.notes.iter().cloned());
384 lines.push(MANIFEST_PATH.to_string());
385
386 if dry {
387 if forced_dry {
388 lines.push(
389 "DRY RUN: the target is a non-empty repository with no instance; re-run with --apply to write these files"
390 .to_string(),
391 );
392 }
393 lines.push("DRY RUN: no files written".to_string());
394 let (removed, dropped) =
397 crate::landing::apply::departures(&target, &candidate, &recorded(&target)).into_paths();
398 return Ok(InitOutcome {
399 lines,
400 applied: false,
401 removed,
402 dropped,
403 });
404 }
405
406 let mut vouched = recorded(&target);
407 vouched.replace.clone_from(&options.replace);
408 let outcome = crate::landing::apply::land(&target, &candidate, &vouched)?;
409 drop(held);
410 Ok(InitOutcome {
411 lines,
412 applied: true,
413 removed: outcome.removed,
414 dropped: outcome.dropped,
415 })
416}
417
418pub(crate) fn recorded(target: &Utf8Path) -> crate::landing::apply::Recorded {
424 crate::landing::apply::Recorded {
425 managed: digests(target, "managed_files", "destination", "sha256"),
426 integration: digests(target, "integration_blocks", "path", "marker_hash"),
427 replace: Vec::new(),
428 }
429}
430
431fn digests(
433 target: &Utf8Path,
434 key: &str,
435 name: &str,
436 digest: &str,
437) -> Vec<(String, crate::domain::ownership::Sha256)> {
438 let Some(value) = recorded_field(target, key) else {
439 return Vec::new();
440 };
441 let Some(entries) = value.as_array() else {
442 return Vec::new();
443 };
444 entries
445 .iter()
446 .filter_map(|entry| {
447 let destination = entry.get(name)?.as_str()?.to_string();
448 let held = entry.get(digest)?.as_str()?;
449 let held = held.parse::<crate::domain::ownership::Sha256>().ok()?;
450 Some((destination, held))
451 })
452 .collect()
453}