1use camino::{Utf8Path, Utf8PathBuf};
15
16use crate::domain::manifest::{DOCS_SCRATCH_VAR, MANIFEST_PATH, PLAN_ZONE_VAR};
17use crate::gates::{GateCtx, GateError};
18
19fn manifest_field(ctx: &GateCtx, key: &str) -> Option<serde_json::Value> {
25 let text = std::fs::read_to_string(ctx.path(MANIFEST_PATH)).ok()?;
26 let value: serde_json::Value = serde_json::from_str(&text).ok()?;
27 value.get(key).cloned().filter(|found| !found.is_null())
28}
29
30fn variable(name: &str) -> Option<Utf8PathBuf> {
32 std::env::var(name)
33 .ok()
34 .map(|value| value.trim().to_string())
35 .filter(|value| !value.is_empty())
36 .map(Utf8PathBuf::from)
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum PlanZoneTarget {
48 Variable(Utf8PathBuf),
50 Tracked(Utf8PathBuf),
52 Broken(String),
54 Unchecked,
56}
57
58#[must_use]
60pub fn plan_zone(ctx: &GateCtx) -> PlanZoneTarget {
61 plan_zone_with(ctx, variable(PLAN_ZONE_VAR))
62}
63
64#[must_use]
70pub fn plan_zone_with(ctx: &GateCtx, named: Option<Utf8PathBuf>) -> PlanZoneTarget {
71 if let Some(path) = named {
72 return PlanZoneTarget::Variable(path);
73 }
74 let Some(recorded) = manifest_field(ctx, "plan_zone") else {
75 return PlanZoneTarget::Unchecked;
76 };
77 if recorded.get("kind").and_then(serde_json::Value::as_str) != Some("tracked") {
78 return PlanZoneTarget::Unchecked;
79 }
80 recorded
85 .get("path")
86 .and_then(serde_json::Value::as_str)
87 .map_or_else(
88 || {
89 PlanZoneTarget::Broken(
90 "the recorded plan zone is tracked and carries no path".to_string(),
91 )
92 },
93 |path| {
94 if path.trim().is_empty() {
95 PlanZoneTarget::Broken(
96 "the recorded plan zone is tracked and its path is empty".to_string(),
97 )
98 } else {
99 PlanZoneTarget::Tracked(Utf8PathBuf::from(path))
100 }
101 },
102 )
103}
104
105#[must_use]
111pub fn docs_scratch(ctx: &GateCtx) -> Option<Utf8PathBuf> {
112 docs_scratch_with(ctx, variable(DOCS_SCRATCH_VAR))
113}
114
115#[must_use]
120pub fn docs_scratch_variable() -> Option<Utf8PathBuf> {
121 variable(DOCS_SCRATCH_VAR)
122}
123
124#[must_use]
126pub fn docs_scratch_with(ctx: &GateCtx, named: Option<Utf8PathBuf>) -> Option<Utf8PathBuf> {
127 named.or_else(|| {
128 manifest_field(ctx, "docs_scratch")
129 .and_then(|value| value.as_str().map(Utf8PathBuf::from))
130 .filter(|path| !path.as_str().is_empty())
131 })
132}
133
134#[must_use]
136pub fn docs_root(ctx: &GateCtx) -> Utf8PathBuf {
137 if let Ok(text) = std::fs::read_to_string(ctx.path(MANIFEST_PATH))
138 && let Ok(value) = serde_json::from_str::<serde_json::Value>(&text)
139 && let Some(root) = value.get("docs_root").and_then(serde_json::Value::as_str)
140 && !root.is_empty()
141 {
142 return Utf8PathBuf::from(root);
143 }
144 for candidate in ["_docs", "docs"] {
145 if discovered(ctx, &Utf8Path::new(candidate).join("specs")) {
146 return Utf8PathBuf::from(candidate);
147 }
148 }
149 Utf8PathBuf::from("_docs")
150}
151
152#[must_use]
156pub fn ki_record_roots(ctx: &GateCtx, args: &[String]) -> Vec<Utf8PathBuf> {
157 if !args.is_empty() {
158 return args.iter().map(Utf8PathBuf::from).collect();
159 }
160 if ctx.path(MANIFEST_PATH).is_file() {
161 return vec![docs_root(ctx).join("reference/known-issues")];
162 }
163 ["_docs", "docs"]
164 .into_iter()
165 .map(|candidate| Utf8Path::new(candidate).join("reference/known-issues"))
166 .filter(|root| discovered(ctx, root))
167 .collect()
168}
169
170fn discovered(ctx: &GateCtx, root: &Utf8Path) -> bool {
179 match std::fs::metadata(ctx.path(root)) {
180 Ok(metadata) => metadata.is_dir(),
181 Err(source) => source.kind() != std::io::ErrorKind::NotFound,
182 }
183}
184
185pub fn ki_records(ctx: &GateCtx, args: &[String]) -> Result<Vec<Utf8PathBuf>, GateError> {
196 let mut records = Vec::new();
197 for root in ki_record_roots(ctx, args) {
198 let entries = match ctx.path(&root).read_dir_utf8() {
199 Ok(entries) => entries,
200 Err(source) if source.kind() == std::io::ErrorKind::NotFound => continue,
201 Err(source) => return Err(GateError::io(&root, source)),
202 };
203 let mut names = Vec::new();
204 for entry in entries {
205 let entry = entry.map_err(|source| GateError::io(&root, source))?;
206 if !entry
207 .file_type()
208 .map_err(|source| GateError::io(&root, source))?
209 .is_file()
210 {
211 continue;
212 }
213 let name = entry.file_name().to_string();
214 if name
215 .strip_prefix("KI-")
216 .and_then(|rest| rest.strip_suffix(".md"))
217 .is_some_and(|slug| !slug.is_empty())
218 {
219 names.push(name);
220 }
221 }
222 names.sort();
223 records.extend(names.into_iter().map(|name| root.join(name)));
224 }
225 Ok(records)
226}
227
228#[cfg(test)]
229mod tests {
230 use super::*;
231
232 fn ctx(dir: &tempfile::TempDir) -> GateCtx {
233 GateCtx::new(dir.path().to_str().unwrap())
234 }
235
236 fn write(dir: &tempfile::TempDir, path: &str, text: &str) {
237 let path = dir.path().join(path);
238 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
239 std::fs::write(path, text).unwrap();
240 }
241
242 #[test]
243 fn the_plan_zone_resolves_only_what_a_command_may_check() {
244 let dir = tempfile::tempdir().unwrap();
245 let ctx = ctx(&dir);
246 assert_eq!(plan_zone_with(&ctx, None), PlanZoneTarget::Unchecked);
248
249 for (recorded, expected) in [
250 (
251 "{\"kind\": \"tracked\", \"path\": \"docs/plan\"}",
252 PlanZoneTarget::Tracked(Utf8PathBuf::from("docs/plan")),
253 ),
254 (
258 "{\"kind\": \"tracked\"}",
259 PlanZoneTarget::Broken(
260 "the recorded plan zone is tracked and carries no path".to_string(),
261 ),
262 ),
263 (
264 "{\"kind\": \"tracked\", \"path\": \" \"}",
265 PlanZoneTarget::Broken(
266 "the recorded plan zone is tracked and its path is empty".to_string(),
267 ),
268 ),
269 (
270 "{\"kind\": \"untracked\", \"path\": \"docs/plan\"}",
271 PlanZoneTarget::Unchecked,
272 ),
273 ("{\"kind\": \"env\"}", PlanZoneTarget::Unchecked),
274 ("{\"kind\": \"none\"}", PlanZoneTarget::Unchecked),
275 ] {
276 write(
277 &dir,
278 ".spec-driven-docs/manifest.json",
279 &format!("{{\"plan_zone\": {recorded}}}\n"),
280 );
281 assert_eq!(plan_zone_with(&ctx, None), expected, "{recorded}");
282 assert_eq!(
284 plan_zone_with(&ctx, Some(Utf8PathBuf::from("elsewhere"))),
285 PlanZoneTarget::Variable(Utf8PathBuf::from("elsewhere")),
286 "{recorded}"
287 );
288 }
289 }
290
291 #[test]
292 fn the_docs_scratch_takes_the_variable_then_the_record() {
293 let dir = tempfile::tempdir().unwrap();
294 let ctx = ctx(&dir);
295 assert_eq!(docs_scratch_with(&ctx, None), None);
296
297 write(
298 &dir,
299 ".spec-driven-docs/manifest.json",
300 "{\"docs_scratch\": \"../beside\"}\n",
301 );
302 assert_eq!(
303 docs_scratch_with(&ctx, None),
304 Some(Utf8PathBuf::from("../beside"))
305 );
306 assert_eq!(
307 docs_scratch_with(&ctx, Some(Utf8PathBuf::from("inside"))),
308 Some(Utf8PathBuf::from("inside"))
309 );
310 }
311
312 #[test]
313 fn manifest_root_wins() {
314 let dir = tempfile::tempdir().unwrap();
315 write(
316 &dir,
317 ".spec-driven-docs/manifest.json",
318 "{\n \"docs_root\": \"docs\"\n}\n",
319 );
320 assert_eq!(docs_root(&ctx(&dir)), "docs");
321 }
322
323 #[test]
324 fn roots_are_discovered_without_a_manifest() {
325 let dir = tempfile::tempdir().unwrap();
326 write(&dir, "docs/specs/SPEC-sample.md", "# S\n");
327 assert_eq!(docs_root(&ctx(&dir)), "docs");
328
329 let both = tempfile::tempdir().unwrap();
330 write(&both, "_docs/specs/SPEC-sample.md", "# S\n");
331 write(&both, "docs/specs/SPEC-sample.md", "# S\n");
332 assert_eq!(docs_root(&ctx(&both)), "_docs");
333
334 let neither = tempfile::tempdir().unwrap();
335 assert_eq!(docs_root(&ctx(&neither)), "_docs");
336 }
337
338 #[test]
339 fn record_arguments_win_over_discovery() {
340 let dir = tempfile::tempdir().unwrap();
341 write(&dir, "docs/reference/known-issues/KI-real.md", "# R\n");
342 let roots = ki_record_roots(&ctx(&dir), &["tests/fixtures".to_string()]);
343 assert_eq!(roots, vec![Utf8PathBuf::from("tests/fixtures")]);
344 }
345
346 #[test]
347 fn records_follow_the_manifest_root() {
348 let dir = tempfile::tempdir().unwrap();
349 write(
350 &dir,
351 ".spec-driven-docs/manifest.json",
352 "{\n \"docs_root\": \"docs\"\n}\n",
353 );
354 write(&dir, "docs/reference/known-issues/KI-vendor.md", "# V\n");
355 write(&dir, "docs/reference/known-issues/KI-.md", "# empty slug\n");
356 write(
357 &dir,
358 "docs/reference/known-issues/notes.md",
359 "# not a record\n",
360 );
361 assert_eq!(
362 ki_records(&ctx(&dir), &[]).unwrap(),
363 vec![Utf8PathBuf::from(
364 "docs/reference/known-issues/KI-vendor.md"
365 )]
366 );
367 }
368
369 #[test]
370 fn bare_consumer_roots_are_discovered() {
371 let dir = tempfile::tempdir().unwrap();
372 write(&dir, "docs/reference/known-issues/KI-a.md", "# A\n");
373 write(&dir, "docs/reference/known-issues/KI-b.md", "# B\n");
374 assert_eq!(
375 ki_records(&ctx(&dir), &[]).unwrap(),
376 vec![
377 Utf8PathBuf::from("docs/reference/known-issues/KI-a.md"),
378 Utf8PathBuf::from("docs/reference/known-issues/KI-b.md"),
379 ]
380 );
381 }
382
383 #[test]
384 fn an_unreadable_layout_is_not_read_as_an_absent_one() {
385 let dir = tempfile::tempdir().unwrap();
386 std::fs::create_dir_all(dir.path().join("docs/specs")).unwrap();
387 assert_eq!(docs_root(&ctx(&dir)), "docs");
388
389 let specs = dir.path().join("docs/specs");
390 let mut mode = std::fs::metadata(&specs).unwrap().permissions();
391 std::os::unix::fs::PermissionsExt::set_mode(&mut mode, 0o000);
392 std::fs::set_permissions(dir.path().join("docs"), mode.clone()).unwrap();
393 let resolved = docs_root(&ctx(&dir));
394 std::os::unix::fs::PermissionsExt::set_mode(&mut mode, 0o755);
395 std::fs::set_permissions(dir.path().join("docs"), mode).unwrap();
396 assert_eq!(
397 resolved, "docs",
398 "an unreadable layout fell through to the default root"
399 );
400 }
401
402 #[test]
403 fn an_unsearchable_ancestor_is_raised_rather_than_discovered_away() {
404 let dir = tempfile::tempdir().unwrap();
405 std::fs::create_dir_all(dir.path().join("docs/reference/known-issues")).unwrap();
406 let ancestor = dir.path().join("docs/reference");
407 let mut mode = std::fs::metadata(&ancestor).unwrap().permissions();
408 std::os::unix::fs::PermissionsExt::set_mode(&mut mode, 0o000);
409 std::fs::set_permissions(&ancestor, mode.clone()).unwrap();
410 let raised = ki_records(&ctx(&dir), &[]).is_err();
411 std::os::unix::fs::PermissionsExt::set_mode(&mut mode, 0o755);
412 std::fs::set_permissions(&ancestor, mode).unwrap();
413 assert!(raised, "an unsearchable ancestor listed as no zone");
414 }
415
416 #[test]
417 fn an_absent_zone_is_skipped_and_an_unreadable_one_is_raised() {
418 let dir = tempfile::tempdir().unwrap();
419 write(&dir, "docs/specs/SPEC-a.md", "# A\n");
420 assert!(ki_records(&ctx(&dir), &[]).unwrap().is_empty());
421
422 let zone = dir.path().join("docs/reference/known-issues");
423 std::fs::create_dir_all(&zone).unwrap();
424 let mut mode = std::fs::metadata(&zone).unwrap().permissions();
425 std::os::unix::fs::PermissionsExt::set_mode(&mut mode, 0o000);
426 std::fs::set_permissions(&zone, mode.clone()).unwrap();
427 let raised = ki_records(&ctx(&dir), &[]).is_err();
428 std::os::unix::fs::PermissionsExt::set_mode(&mut mode, 0o755);
429 std::fs::set_permissions(&zone, mode).unwrap();
430 assert!(raised, "an unreadable zone listed as empty");
431 }
432}