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 == '/') {
72 return Err(AppError::Usage("refusing root target".to_string()));
73 }
74 Ok(canonical)
75}
76
77fn target_has_content(target: &Utf8Path) -> Result<bool, AppError> {
78 for entry in target.read_dir_utf8()? {
79 let entry = entry?;
80 if entry.file_name() != ".git" {
81 return Ok(true);
82 }
83 }
84 Ok(false)
85}
86
87pub(crate) fn recorded_field(target: &Utf8Path, key: &str) -> Option<serde_json::Value> {
93 std::fs::read_to_string(target.join(MANIFEST_PATH))
94 .ok()
95 .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
96 .and_then(|value| value.get(key).cloned())
97 .filter(|value| !value.is_null())
98}
99
100fn installed_at(target: &Utf8Path) -> String {
101 recorded_field(target, "installed_at")
102 .and_then(|value| value.as_str().map(String::from))
103 .unwrap_or_else(|| {
104 jiff::Timestamp::now()
105 .strftime("%Y-%m-%dT%H:%M:%SZ")
106 .to_string()
107 })
108}
109
110pub(crate) fn resolved_docs_scratch(
122 target: &Utf8Path,
123 flag: Option<&Option<Utf8PathBuf>>,
124) -> Result<Option<Utf8PathBuf>, AppError> {
125 if let Some(declared) = flag {
126 return Ok(declared.clone());
127 }
128 let Some(recorded) = recorded_field(target, "docs_scratch") else {
129 return Ok(None);
130 };
131 let path = recorded
132 .as_str()
133 .filter(|path| !path.is_empty())
134 .map(Utf8PathBuf::from)
135 .ok_or_else(|| {
136 AppError::ManifestInvalid(format!(
137 "the recorded docs_scratch is not a path ({recorded}); \
138 re-declare it with --docs-scratch"
139 ))
140 })?;
141 if let Err(error) = validate_docs_scratch_path(&path) {
142 return Err(AppError::ManifestInvalid(format!(
143 "the recorded docs_scratch is not usable ({error}); \
144 re-declare it with --docs-scratch"
145 )));
146 }
147 Ok(Some(path))
148}
149
150#[derive(Debug, Clone)]
156pub struct TargetState {
157 pub files: Vec<(Utf8PathBuf, Vec<u8>)>,
159 pub lines: Vec<String>,
161}
162
163pub fn compute_target_state(
176 target: &Utf8Path,
177 options: &InitOptions,
178) -> Result<TargetState, AppError> {
179 let candidate = candidate_for(target, options)?;
180 let mut lines: Vec<String> = Vec::new();
181 for destination in &candidate.destinations {
182 lines.push(destination.path.to_string());
183 }
184 lines.extend(candidate.notes.iter().cloned());
185 lines.push(MANIFEST_PATH.to_string());
186 Ok(TargetState {
187 files: candidate.files(),
188 lines,
189 })
190}
191
192pub fn candidate_for(
198 target: &Utf8Path,
199 options: &InitOptions,
200) -> Result<crate::candidate::Candidate, AppError> {
201 crate::candidate::project(&gather(target, options)?)
202}
203
204pub fn resolved_target(target: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
211 canonical_target(target)
212}
213
214#[must_use]
220pub fn present_at_root(target: &Utf8Path) -> Vec<String> {
221 let mut present: Vec<String> = Vec::new();
222 for projection in &crate::domain::profile::DECLARATION.adopted {
223 let Some(set) = projection.yield_set() else {
224 continue;
225 };
226 for name in set.names() {
227 if target.join(name).is_file() && !present.iter().any(|held| held == name) {
228 present.push(name.to_string());
229 }
230 }
231 }
232 present
233}
234
235fn gather(target: &Utf8Path, options: &InitOptions) -> Result<crate::candidate::Input, AppError> {
237 let docs_root = crate::candidate::docs_root_of(options.profile)?;
238
239 let recorded_adopted: Vec<String> = recorded_field(target, "adopted_files")
244 .and_then(|value| {
245 value.as_array().map(|entries| {
246 entries
247 .iter()
248 .filter_map(|entry| entry.get("destination")?.as_str().map(String::from))
249 .collect()
250 })
251 })
252 .unwrap_or_default();
253
254 let mut existing = std::collections::BTreeMap::new();
255 for projection in &crate::domain::profile::DECLARATION.adopted {
256 let destination = resolve_destination(&projection.destination, docs_root);
257 let path = target.join(&destination);
258 if path.is_file() {
259 existing.insert(destination, std::fs::read(&path)?);
260 }
261 }
262
263 let present_at_root = present_at_root(target);
264
265 let hooks_path = target.join(HOOKS_CONFIG_PATH);
266 let hooks_host = if hooks_path.is_file() {
267 std::fs::read_to_string(&hooks_path)?
268 } else {
269 String::new()
270 };
271
272 let agents_path = target.join(AGENTS_DIGEST_PATH);
276 if agents_path.is_symlink() {
277 return Err(AppError::Refused(
278 "AGENTS.md is a symlink; refusing to write the documentation block through it"
279 .to_string(),
280 ));
281 }
282 let agents_exists = agents_path.is_file();
283 let agents_host = if agents_exists {
284 std::fs::read_to_string(&agents_path)?
285 } else {
286 String::new()
287 };
288
289 Ok(crate::candidate::Input {
290 profile: options.profile,
291 version: CanonVersion::current(),
292 installed_at: installed_at(target),
293 docs_scratch: resolved_docs_scratch(target, options.docs_scratch.as_ref())?,
294 reserve: options.reserve.clone(),
295 writing_style: options.writing_style.clone(),
296 acquisition: options.acquisition.clone(),
297 evidence: crate::candidate::Evidence {
298 existing,
299 recorded_adopted,
300 hooks_host,
301 agents_host,
302 agents_exists,
303 present_at_root,
304 },
305 })
306}
307
308pub fn init(
317 options: &InitOptions,
318 intent: crate::landing::classify::Intent,
319) -> Result<InitOutcome, AppError> {
320 init_holding(None, options, intent)
321}
322
323pub fn init_holding(
332 held: Option<crate::transaction::lock::Lock>,
333 options: &InitOptions,
334 intent: crate::landing::classify::Intent,
335) -> Result<InitOutcome, AppError> {
336 let target = canonical_target(&options.target)?;
337 crate::commands::front::serves(intent, &target)?;
341 let forced_dry = !options.apply
342 && !options.dry_run
343 && target_has_content(&target)?
344 && !target.join(MANIFEST_PATH).is_file();
345 let dry = options.dry_run || forced_dry;
346
347 let held = match (dry, held) {
353 (true, _) => None,
354 (false, Some(held)) => Some(held),
355 (false, None) => Some(crate::landing::lock::hold(&target)?),
356 };
357
358 if let Some(recorded) = recorded_field(&target, "profile").and_then(|value| {
363 ProfileId::every().find(|profile| Some(profile.as_str()) == value.as_str())
364 }) && recorded != options.profile
365 {
366 return Err(AppError::Refused(format!(
367 "{target} records the {recorded} profile and this run asks for {}; \
368 moving a profile moves the documentation root, which is a migration to ask for deliberately",
369 options.profile
370 )));
371 }
372
373 let candidate = candidate_for(&target, options)?;
374 let mut lines: Vec<String> = candidate
375 .destinations
376 .iter()
377 .map(|destination| destination.path.to_string())
378 .collect();
379 lines.extend(candidate.notes.iter().cloned());
380 lines.push(MANIFEST_PATH.to_string());
381
382 if dry {
383 if forced_dry {
384 lines.push(
385 "DRY RUN: the target is a non-empty repository with no instance; re-run with --apply to write these files"
386 .to_string(),
387 );
388 }
389 lines.push("DRY RUN: no files written".to_string());
390 return Ok(InitOutcome {
391 lines,
392 applied: false,
393 removed: Vec::new(),
394 });
395 }
396
397 let mut vouched = recorded(&target);
398 vouched.replace.clone_from(&options.replace);
399 let outcome = crate::landing::apply::land(&target, &candidate, &vouched)?;
400 drop(held);
401 Ok(InitOutcome {
402 lines,
403 applied: true,
404 removed: outcome.removed,
405 })
406}
407
408pub(crate) fn recorded(target: &Utf8Path) -> crate::landing::apply::Recorded {
414 crate::landing::apply::Recorded {
415 managed: digests(target, "managed_files", "destination", "sha256"),
416 integration: digests(target, "integration_blocks", "path", "marker_hash"),
417 replace: Vec::new(),
418 }
419}
420
421fn digests(
423 target: &Utf8Path,
424 key: &str,
425 name: &str,
426 digest: &str,
427) -> Vec<(String, crate::domain::ownership::Sha256)> {
428 let Some(value) = recorded_field(target, key) else {
429 return Vec::new();
430 };
431 let Some(entries) = value.as_array() else {
432 return Vec::new();
433 };
434 entries
435 .iter()
436 .filter_map(|entry| {
437 let destination = entry.get(name)?.as_str()?.to_string();
438 let held = entry.get(digest)?.as_str()?;
439 let held = held.parse::<crate::domain::ownership::Sha256>().ok()?;
440 Some((destination, held))
441 })
442 .collect()
443}