1use super::stdout::{cli_print as print, cli_println as println};
6use crate::cli_args::{DocsCommand, DocsReadCommand, DocsSubcommand};
7use colored::Colorize;
8use md5::{Digest, Md5};
9use serde::{Deserialize, Serialize};
10use std::cell::RefCell;
11use std::collections::{HashMap, HashSet};
12use std::fs;
13use std::path::{Path, PathBuf};
14use std::sync::Arc;
15use std::sync::Once;
16use walkdir::WalkDir;
17
18use calcit_core::ProgramEntries;
19use calcit_core::calcit::LocatedWarning;
20use calcit_core::call_stack::CallStackList;
21use calcit_core::program;
22use calcit_core::runner;
23use calcit_core::snapshot;
24use calcit_core::util;
25
26use super::atomic_write::stage_atomic_file;
27use super::libs::handle_libs_command;
28use super::markdown_read::{RenderMarkdownOptions, build_heading_sections, render_markdown_sections};
29use super::tips::command_guidance_enabled;
30
31const VALID_DOC_CATEGORIES: &[&str] = &[
32 "run",
33 "features",
34 "installation",
35 "data",
36 "intro",
37 "syntax",
38 "tools",
39 "ecosystem",
40 "reference",
41 "docs",
42];
43
44#[derive(Debug, Clone)]
45pub struct GuideDoc {
46 filename: String,
47 path: String,
48 content: String,
49 scope: GuideDocScope,
50 frontmatter: GuideDocFrontmatter,
51}
52
53#[derive(Debug, Clone, Default, PartialEq, Eq)]
54struct GuideDocFrontmatter {
55 title: Option<String>,
56 summary: Option<String>,
57 scope: Option<String>,
58 kind: Option<String>,
59 category: Option<String>,
60 aliases: Vec<String>,
61 entry_for: Vec<String>,
62}
63
64#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
70#[allow(dead_code)]
71pub(crate) struct DocKnowledgeMetadata {
72 pub title: Option<String>,
73 pub summary: Option<String>,
74 pub id: Option<String>,
75 pub code_refs: Vec<String>,
76 pub parent: Option<String>,
77 pub related: Vec<String>,
78 pub requires: Vec<String>,
79 pub leads_to: Vec<String>,
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
83enum GuideDocScope {
84 Core,
85 Module(String),
86}
87
88#[derive(Debug, Clone, PartialEq, Eq)]
89struct SearchResult {
90 doc_index: usize,
91 merged_ranges: Vec<(usize, usize)>,
92 score: usize,
93}
94
95impl GuideDoc {
96 fn display_title(&self) -> String {
97 let base_title = self.frontmatter.title.as_deref().unwrap_or(&self.filename);
98 match &self.scope {
99 GuideDocScope::Core => base_title.to_string(),
100 GuideDocScope::Module(module) => format!("{base_title} [module:{module}]"),
101 }
102 }
103}
104
105fn match_score(value: &str, query_lower: &str, exact_score: usize, contains_score: usize) -> usize {
106 let value_lower = value.to_lowercase();
107 if value_lower == query_lower {
108 exact_score
109 } else if value_lower.contains(query_lower) {
110 contains_score
111 } else {
112 0
113 }
114}
115
116fn accumulate_match_score(total: &mut usize, matched: &mut bool, value: &str, query_lower: &str, exact: usize, contains: usize) {
117 let score = match_score(value, query_lower, exact, contains);
118 if score > 0 {
119 *total += score;
120 *matched = true;
121 }
122}
123
124fn parse_guide_doc(filename: String, path: String, raw_content: &str, scope: GuideDocScope) -> Result<GuideDoc, String> {
125 let (frontmatter, content) = parse_doc_frontmatter(raw_content);
126 validate_doc_frontmatter(&path, &frontmatter)?;
127 Ok(GuideDoc {
128 filename,
129 path,
130 content,
131 scope,
132 frontmatter,
133 })
134}
135
136struct ReadRenderOptions<'a> {
137 display_title: &'a str,
138 display_path: &'a str,
139 command_hint: &'a str,
140 no_match_error: &'a str,
141 content: &'a str,
142 heading_queries: &'a [String],
143 include_subheadings: bool,
144 full: bool,
145 with_lines: bool,
146}
147
148pub fn handle_docs_command(cmd: &DocsCommand) -> Result<(), String> {
149 match &cmd.subcommand {
150 DocsSubcommand::Scopes(_) => handle_scopes(),
151 DocsSubcommand::RemoteLibs(opts) => handle_libs_command(opts),
152 DocsSubcommand::Search(opts) => handle_search(
153 &opts.keyword,
154 opts.context,
155 opts.filename.as_deref(),
156 opts.module.as_deref(),
157 opts.summary,
158 ),
159 DocsSubcommand::List(opts) => handle_list(opts.module.as_deref()),
160 DocsSubcommand::Sections(opts) => handle_sections(&opts.filename, opts.module.as_deref(), opts.with_lines),
161 DocsSubcommand::Read(opts) if opts.start.is_some() || opts.lines.is_some() => {
162 reject_read_line_range_conflicts(opts)?;
163 handle_read_lines(
164 &opts.filename,
165 opts.start.unwrap_or(0),
166 opts.lines.unwrap_or(80),
167 opts.module.as_deref(),
168 )
169 }
170 DocsSubcommand::Read(opts) => handle_read(
171 &opts.filename,
172 &opts.headings,
173 !opts.no_subheadings,
174 opts.full,
175 opts.with_lines,
176 opts.module.as_deref(),
177 ),
178 DocsSubcommand::Agents(opts) => handle_agents(
179 &opts.headings,
180 !opts.no_subheadings,
181 opts.full,
182 opts.contract,
183 opts.with_lines,
184 opts.refresh,
185 ),
186 DocsSubcommand::CheckMd(opts) => {
187 if opts.legacy_entry.is_some() {
188 return Err(
189 "docs check-md --entry used to select a Snapshot file. Use --snapshot <file> instead; --entry selects a named entry in other commands."
190 .to_owned(),
191 );
192 }
193 handle_check_md(&opts.file, &opts.snapshot, &opts.dep, opts.quiet, opts.failures_only)
194 }
195 DocsSubcommand::FormatMd(opts) => handle_format_md(&opts.file, opts.check),
196 }
197}
198
199fn reject_read_line_range_conflicts(opts: &DocsReadCommand) -> Result<(), String> {
201 for (flag, present) in [
202 ("<headings>", !opts.headings.is_empty()),
203 ("--no-subheadings", opts.no_subheadings),
204 ("--full", opts.full),
205 ("--with-lines", opts.with_lines),
206 ] {
207 if present {
208 return Err(format!("`docs read --start/--lines` does not support `{flag}`."));
209 }
210 }
211 Ok(())
212}
213
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub(crate) struct DefinitionDocLink {
216 pub id: String,
217 pub path: String,
218 pub title: Option<String>,
219 pub summary: Option<String>,
220}
221
222#[derive(Debug, Clone, PartialEq, Eq)]
223pub(crate) struct DefinitionDocsLookup {
224 pub links: Vec<DefinitionDocLink>,
225 pub unreadable_files: Vec<(String, String)>,
226}
227
228pub(crate) fn lookup_definition_docs(definition: &str) -> Result<DefinitionDocsLookup, String> {
231 let docs_dir = get_guidebook_dir()?;
232 let mut links = Vec::new();
233 let mut unreadable_files = Vec::new();
234 let mut seen_ids: HashMap<String, String> = HashMap::new();
235 for entry in WalkDir::new(&docs_dir).sort_by_file_name() {
236 let entry = entry.map_err(|err| format!("Failed to walk documentation directory {docs_dir:?}: {err}"))?;
237 let path = entry.path();
238 if !entry.file_type().is_file() || path.extension().and_then(|value| value.to_str()) != Some("md") {
239 continue;
240 }
241 let relative_path = path
242 .strip_prefix(&docs_dir)
243 .map_err(|_| format!("Unable to make documentation path relative: {path:?}"))?
244 .to_string_lossy()
245 .replace(std::path::MAIN_SEPARATOR, "/");
246 let content = match fs::read_to_string(path) {
247 Ok(content) => content,
248 Err(err) => {
249 unreadable_files.push((relative_path, err.to_string()));
250 continue;
251 }
252 };
253 let metadata = parse_doc_knowledge_metadata(&content);
254 let Some(id) = metadata.id else {
255 continue;
256 };
257 if let Some(previous_path) = seen_ids.insert(id.clone(), relative_path.clone()) {
258 return Err(format!(
259 "Duplicate documentation node id '{id}' in '{previous_path}' and '{relative_path}'"
260 ));
261 }
262 if id != definition && !metadata.code_refs.iter().any(|reference| reference == definition) {
263 continue;
264 }
265 links.push(DefinitionDocLink {
266 id,
267 path: relative_path,
268 title: metadata.title,
269 summary: metadata.summary,
270 });
271 }
272 links.sort_by(|left, right| left.id.cmp(&right.id).then(left.path.cmp(&right.path)));
273 links.dedup_by(|left, right| left.id == right.id && left.path == right.path);
274 Ok(DefinitionDocsLookup { links, unreadable_files })
275}
276
277const AGENTS_DOC_URL: &str = "https://repo.calcit-lang.org/calcit/docs/CalcitAgent.md";
278const AGENT_MUTATION_CONTRACT_VERSION: u32 = 1;
279const AGENT_MUTATION_CONTRACT_HEADING: &str = "Mutation contract v1";
280
281struct AgentsDocument {
282 content: String,
283 display_path: String,
284 refreshed: bool,
285}
286
287#[derive(Debug, Clone, PartialEq, Eq)]
288struct AgentMutationContract {
289 content: String,
290 digest: String,
291}
292
293fn extract_agent_mutation_contract(content: &str) -> Result<AgentMutationContract, String> {
294 let (_, content) = parse_doc_frontmatter(content);
295 let sections = build_heading_sections(&content);
296 let section = sections
297 .iter()
298 .find(|section| section.title == AGENT_MUTATION_CONTRACT_HEADING)
299 .ok_or_else(|| format!("Agents.md is missing the required `{AGENT_MUTATION_CONTRACT_HEADING}` section"))?;
300 let lines = content.lines().collect::<Vec<_>>();
301 let contract = lines[section.line - 1..section.content_end].join("\n") + "\n";
302 let digest = format!("md5:{}", hex::encode(Md5::digest(contract.as_bytes())));
303 Ok(AgentMutationContract { content: contract, digest })
304}
305
306#[cfg(test)]
307thread_local! {
308 static TEST_HOME_OVERRIDE: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
309}
310
311fn calcit_home_dir() -> Result<PathBuf, String> {
312 #[cfg(test)]
313 if let Some(override_dir) = TEST_HOME_OVERRIDE.with(|slot| slot.borrow().clone()) {
314 return Ok(override_dir);
315 }
316 std::env::var("HOME")
317 .map(PathBuf::from)
318 .map_err(|_| "Unable to get HOME environment variable".to_string())
319}
320
321fn get_agents_cache_path() -> Result<PathBuf, String> {
322 Ok(calcit_home_dir()?.join(".config/calcit/Agents.md"))
323}
324
325fn download_agents_doc() -> Result<String, String> {
326 let response = ureq::get(AGENTS_DOC_URL)
327 .call()
328 .map_err(|e| format!("Failed to download Agents.md: {e}"))?;
329
330 response
331 .into_body()
332 .read_to_string()
333 .map_err(|e| format!("Failed to read Agents.md response: {e}"))
334}
335
336fn load_agents_document(force_refresh: bool) -> Result<AgentsDocument, String> {
337 if !force_refresh {
338 let content = crate::embedded_agents_doc().ok_or_else(|| {
339 "Embedded Agents guide is not registered; call calcit_cli::set_embedded_agents_doc(...) first or pass --refresh.".to_owned()
340 })?;
341 return Ok(AgentsDocument {
342 content: content.to_owned(),
343 display_path: format!("embedded:docs/CalcitAgent.md@{}", env!("CARGO_PKG_VERSION")),
344 refreshed: false,
345 });
346 }
347
348 let cache_path = get_agents_cache_path()?;
349 let content = download_agents_doc()?;
350 if let Some(parent) = cache_path.parent() {
351 fs::create_dir_all(parent).map_err(|e| format!("Failed to create cache directory {parent:?}: {e}"))?;
352 }
353 fs::write(&cache_path, &content).map_err(|e| format!("Failed to write Agents cache {cache_path:?}: {e}"))?;
354
355 Ok(AgentsDocument {
356 content,
357 display_path: cache_path.to_string_lossy().to_string(),
358 refreshed: true,
359 })
360}
361
362fn handle_read_content(options: ReadRenderOptions<'_>) -> Result<(), String> {
363 let command_prefix = format!("calcit docs {}", options.command_hint);
364
365 println!("{} ({})", options.display_title.cyan().bold(), options.display_path.dimmed());
366 println!("{}", "=".repeat(60).dimmed());
367
368 render_markdown_sections(
369 options.content,
370 options.heading_queries,
371 RenderMarkdownOptions {
372 include_subheadings: options.include_subheadings,
373 full: options.full,
374 with_lines: options.with_lines,
375 command_prefix: &command_prefix,
376 with_file_option: false,
377 no_headings_message: "No Markdown headings found in this document.",
378 print_full_when_no_headings: false,
379 no_match_error: options.no_match_error,
380 },
381 )
382}
383
384fn score_doc_query(doc: &GuideDoc, query_lower: &str) -> usize {
385 let mut score: usize = 0;
386 score += match_score(&doc.filename, query_lower, 320, 180);
387 score += match_score(&doc.path, query_lower, 280, 140);
388
389 if let Some(title) = &doc.frontmatter.title {
390 score += match_score(title, query_lower, 260, 150);
391 }
392
393 for alias in &doc.frontmatter.aliases {
394 score += match_score(alias, query_lower, 220, 120);
395 }
396
397 for entry in &doc.frontmatter.entry_for {
398 score += match_score(entry, query_lower, 180, 96);
399 }
400
401 if score == 0 {
403 return 0;
404 }
405 score.saturating_add_signed(score_doc_shape(doc))
406}
407
408fn find_doc_by_query<'a>(guide_docs: &'a [GuideDoc], query: &str) -> Result<&'a GuideDoc, String> {
409 let query_lower = query.to_lowercase();
410 guide_docs
411 .iter()
412 .filter_map(|doc| {
413 let score = score_doc_query(doc, &query_lower);
414 (score > 0).then_some((doc, score))
415 })
416 .max_by(|(left_doc, left_score), (right_doc, right_score)| {
417 left_score.cmp(right_score).then_with(|| right_doc.path.cmp(&left_doc.path))
418 })
419 .map(|(doc, _)| doc)
420 .ok_or_else(|| {
421 format!("Document '{query}' not found. Use 'calcit docs list' or 'calcit docs search {query}' to locate matching documents.")
422 })
423}
424
425fn get_guidebook_dir() -> Result<PathBuf, String> {
426 let home_dir = calcit_home_dir()?;
427 let docs_dir = home_dir.join(".config/calcit/docs");
428
429 if !docs_dir.exists() {
430 let calcit_repo_dir = home_dir.join(".config/calcit/calcit");
431 return Err(format!(
432 "Guidebook documentation directory not found: {docs_dir:?}\n\nDownload the Calcit docs repo with git, then create a symlink for the docs directory:\nmkdir -p ~/.config/calcit\ngit clone https://github.com/calcit-lang/calcit.git {}\nln -s {}/docs {}",
433 calcit_repo_dir.display(),
434 calcit_repo_dir.display(),
435 docs_dir.display()
436 ));
437 }
438
439 Ok(docs_dir)
440}
441
442fn trim_frontmatter_value(raw: &str) -> String {
443 let value = raw.trim();
444 if value.len() >= 2 {
445 let first = value.chars().next().unwrap_or_default();
446 let last = value.chars().last().unwrap_or_default();
447 if (first == '"' && last == '"') || (first == '\'' && last == '\'') {
448 return value[1..value.len() - 1].to_string();
449 }
450 }
451 value.to_string()
452}
453
454fn validate_doc_frontmatter(path: &str, frontmatter: &GuideDocFrontmatter) -> Result<(), String> {
455 if let Some(category) = frontmatter.category.as_deref()
456 && !VALID_DOC_CATEGORIES.contains(&category)
457 {
458 return Err(format!(
459 "Invalid frontmatter category '{category}' in {path}. Use one of: {}. See docs/docs-indexing.md.",
460 VALID_DOC_CATEGORIES.join(", ")
461 ));
462 }
463
464 Ok(())
465}
466
467fn parse_doc_frontmatter(raw: &str) -> (GuideDocFrontmatter, String) {
468 if !raw.starts_with("---\n") {
469 return (GuideDocFrontmatter::default(), raw.to_string());
470 }
471
472 let mut frontmatter = GuideDocFrontmatter::default();
473 let mut body_lines = Vec::new();
474 let mut in_frontmatter = true;
475 let mut saw_closing = false;
476 let mut active_list: Option<&str> = None;
477
478 for (index, line) in raw.lines().enumerate() {
479 if index == 0 {
480 continue;
481 }
482
483 if in_frontmatter {
484 if line.trim() == "---" {
485 in_frontmatter = false;
486 saw_closing = true;
487 active_list = None;
488 continue;
489 }
490
491 let trimmed = line.trim();
492 if let Some(item) = trimmed.strip_prefix("- ") {
493 let value = trim_frontmatter_value(item);
494 match active_list {
495 Some("aliases") => frontmatter.aliases.push(value),
496 Some("entry_for") => frontmatter.entry_for.push(value),
497 _ => {}
498 }
499 continue;
500 }
501
502 if let Some((key, value)) = trimmed.split_once(':') {
503 let key = key.trim();
504 let value = value.trim();
505 active_list = None;
506 match key {
507 "title" => frontmatter.title = Some(trim_frontmatter_value(value)),
508 "summary" => frontmatter.summary = Some(trim_frontmatter_value(value)),
509 "scope" => frontmatter.scope = Some(trim_frontmatter_value(value)),
510 "kind" => frontmatter.kind = Some(trim_frontmatter_value(value)),
511 "category" => frontmatter.category = Some(trim_frontmatter_value(value)),
512 "aliases" if value.is_empty() => active_list = Some("aliases"),
513 "entry_for" if value.is_empty() => active_list = Some("entry_for"),
514 "aliases" => frontmatter.aliases.push(trim_frontmatter_value(value)),
515 "entry_for" => frontmatter.entry_for.push(trim_frontmatter_value(value)),
516 _ => {}
517 }
518 continue;
519 }
520
521 active_list = None;
522 } else {
523 body_lines.push(line);
524 }
525 }
526
527 if !saw_closing {
528 return (GuideDocFrontmatter::default(), raw.to_string());
529 }
530
531 let body = body_lines.join("\n").trim_start_matches('\n').to_string();
532 (frontmatter, body)
533}
534
535pub(crate) fn parse_doc_knowledge_metadata(raw: &str) -> DocKnowledgeMetadata {
541 if !raw.starts_with("---\n") {
542 return DocKnowledgeMetadata::default();
543 }
544
545 let mut metadata = DocKnowledgeMetadata::default();
546 let mut active_list: Option<&str> = None;
547 let mut saw_closing = false;
548
549 for (index, line) in raw.lines().enumerate() {
550 if index == 0 {
551 continue;
552 }
553 if line.trim() == "---" {
554 saw_closing = true;
555 break;
556 }
557
558 let trimmed = line.trim();
559 if let Some(item) = trimmed.strip_prefix("- ") {
560 let value = trim_frontmatter_value(item);
561 match active_list {
562 Some("related") => metadata.related.push(value),
563 Some("requires") => metadata.requires.push(value),
564 Some("leads_to") => metadata.leads_to.push(value),
565 Some("code_refs") => metadata.code_refs.push(value),
566 _ => {}
567 }
568 continue;
569 }
570
571 let Some((key, value)) = trimmed.split_once(':') else {
572 active_list = None;
573 continue;
574 };
575 let key = key.trim();
576 let value = value.trim();
577 active_list = None;
578 match key {
579 "title" => metadata.title = Some(trim_frontmatter_value(value)),
580 "summary" => metadata.summary = Some(trim_frontmatter_value(value)),
581 "id" => metadata.id = Some(trim_frontmatter_value(value)),
582 "code_ref" => metadata.code_refs.push(trim_frontmatter_value(value)),
583 "code_refs" if value.is_empty() => active_list = Some("code_refs"),
584 "code_refs" => metadata.code_refs.push(trim_frontmatter_value(value)),
585 "parent" => metadata.parent = Some(trim_frontmatter_value(value)),
586 "related" if value.is_empty() => active_list = Some("related"),
587 "requires" if value.is_empty() => active_list = Some("requires"),
588 "leads_to" if value.is_empty() => active_list = Some("leads_to"),
589 "related" => metadata.related.push(trim_frontmatter_value(value)),
590 "requires" => metadata.requires.push(trim_frontmatter_value(value)),
591 "leads_to" => metadata.leads_to.push(trim_frontmatter_value(value)),
592 _ => {}
593 }
594 }
595
596 if saw_closing { metadata } else { DocKnowledgeMetadata::default() }
597}
598
599fn visit_markdown_dir(dir: &Path, base_dir: &Path, docs: &mut Vec<GuideDoc>, scope: &GuideDocScope) -> Result<(), String> {
600 for entry in fs::read_dir(dir).map_err(|e| format!("Failed to read directory: {e}"))? {
601 let entry = entry.map_err(|e| format!("Failed to read directory entry: {e}"))?;
602 let path = entry.path();
603
604 if path.is_dir() {
605 if path.file_name().and_then(|s| s.to_str()).is_some_and(|name| name.starts_with('.')) {
606 continue;
607 }
608 visit_markdown_dir(&path, base_dir, docs, scope)?;
609 } else if path.extension().and_then(|s| s.to_str()) == Some("md") {
610 let raw_content = fs::read_to_string(&path).map_err(|e| format!("Failed to read file {path:?}: {e}"))?;
611 let relative_path = path.strip_prefix(base_dir).map_err(|_| "Unable to get relative path")?;
612 let filename = path.file_name().and_then(|s| s.to_str()).unwrap_or("unknown").to_string();
613 let relative_path_str = relative_path.to_string_lossy().to_string();
614 docs.push(parse_guide_doc(filename, relative_path_str, &raw_content, scope.clone())?);
615 }
616 }
617 Ok(())
618}
619
620fn load_guidebook_docs() -> Result<Vec<GuideDoc>, String> {
621 let docs_dir = get_guidebook_dir()?;
622 let mut guide_docs = Vec::new();
623 visit_markdown_dir(&docs_dir, &docs_dir, &mut guide_docs, &GuideDocScope::Core)?;
624 Ok(guide_docs)
625}
626
627fn load_module_docs_from_dir(modules_dir: &Path, module_filter: Option<&str>) -> Result<Vec<GuideDoc>, String> {
628 let mut docs = Vec::new();
629 let mut seen_modules = HashSet::new();
630
631 for entry in fs::read_dir(modules_dir).map_err(|e| format!("Failed to read modules directory {modules_dir:?}: {e}"))? {
632 let entry = entry.map_err(|e| format!("Failed to read modules directory entry: {e}"))?;
633 let path = entry.path();
634 if !path.is_dir() {
635 continue;
636 }
637
638 let module_name = match path.file_name().and_then(|s| s.to_str()) {
639 Some(name) if !name.starts_with('.') => name.to_string(),
640 _ => continue,
641 };
642
643 if let Some(filter) = module_filter
644 && module_name != filter
645 {
646 continue;
647 }
648
649 seen_modules.insert(module_name.clone());
650 let scope = GuideDocScope::Module(module_name.clone());
651
652 let agents_path = path.join("Agents.md");
653 if agents_path.exists() {
654 let raw_content = fs::read_to_string(&agents_path).map_err(|e| format!("Failed to read file {agents_path:?}: {e}"))?;
655 let agents_doc_path = format!("{module_name}/Agents.md");
656 docs.push(parse_guide_doc(
657 "Agents.md".to_string(),
658 agents_doc_path,
659 &raw_content,
660 scope.clone(),
661 )?);
662 }
663
664 let docs_path = path.join("docs");
665 if docs_path.exists() {
666 visit_markdown_dir(&docs_path, &path, &mut docs, &scope)?;
667 }
668 }
669
670 if let Some(filter) = module_filter
671 && !seen_modules.contains(filter)
672 {
673 return Err(format!(
674 "Module '{filter}' not found under {modules_dir:?}. Run `caps` to materialize the current project's .calcit/modules/ view."
675 ));
676 }
677
678 Ok(docs)
679}
680
681fn load_module_docs(module_filter: Option<&str>) -> Result<Vec<GuideDoc>, String> {
682 let project_root = std::env::current_dir().map_err(|e| format!("Unable to get current directory: {e}"))?;
683 load_module_docs_for_project(&project_root, module_filter)
684}
685
686fn load_module_docs_for_project(project_root: &Path, module_filter: Option<&str>) -> Result<Vec<GuideDoc>, String> {
687 let modules_dir = calcit_core::project_module_folder(project_root);
688 load_module_docs_from_dir(&modules_dir, module_filter)
689}
690
691fn collect_docs_for_query(module_filter: Option<&str>) -> Result<Vec<GuideDoc>, String> {
692 let mut docs = if module_filter.is_some() {
693 load_module_docs(module_filter)?
694 } else {
695 load_guidebook_docs()?
696 };
697 docs.sort_by(|a, b| a.path.cmp(&b.path));
698 Ok(docs)
699}
700
701fn list_doc_scopes() -> Result<Vec<String>, String> {
702 let project_root = std::env::current_dir().map_err(|e| format!("Unable to get current directory: {e}"))?;
703 list_doc_scopes_for_project(&project_root)
704}
705
706fn list_doc_scopes_for_project(project_root: &Path) -> Result<Vec<String>, String> {
707 let modules_dir = calcit_core::project_module_folder(project_root);
708 list_doc_scopes_from_dir(&modules_dir)
709}
710
711fn list_doc_scopes_from_dir(modules_dir: &Path) -> Result<Vec<String>, String> {
712 let mut scopes = vec!["calcit".to_string()];
713
714 for entry in fs::read_dir(modules_dir).map_err(|e| format!("Failed to read modules directory {modules_dir:?}: {e}"))? {
715 let entry = entry.map_err(|e| format!("Failed to read modules directory entry: {e}"))?;
716 let path = entry.path();
717 if !path.is_dir() {
718 continue;
719 }
720
721 if let Some(name) = path.file_name().and_then(|s| s.to_str())
722 && !name.starts_with('.')
723 {
724 scopes.push(name.to_string());
725 }
726 }
727
728 scopes.sort();
729 scopes.dedup();
730 Ok(scopes)
731}
732
733fn score_metadata_hit(doc: &GuideDoc, keyword_lower: &str) -> (usize, bool) {
734 let mut score = 0;
735 let mut matched = false;
736
737 if let Some(title) = &doc.frontmatter.title {
738 accumulate_match_score(&mut score, &mut matched, title, keyword_lower, 240, 160);
739 }
740
741 if let Some(summary) = &doc.frontmatter.summary {
742 accumulate_match_score(&mut score, &mut matched, summary, keyword_lower, 200, 130);
743 }
744
745 for alias in &doc.frontmatter.aliases {
746 accumulate_match_score(&mut score, &mut matched, alias, keyword_lower, 220, 120);
747 }
748
749 for entry in &doc.frontmatter.entry_for {
750 accumulate_match_score(&mut score, &mut matched, entry, keyword_lower, 180, 90);
751 }
752
753 (score, matched)
754}
755
756fn score_doc_shape(doc: &GuideDoc) -> isize {
757 let kind_score = match doc.frontmatter.kind.as_deref() {
758 Some("reference") => 18,
759 Some("guide") => 14,
760 Some("hub") => 8,
761 Some("agent") => 4,
762 Some("spec") => -6,
763 Some(_) | None => 0,
764 };
765
766 let category_score = match doc.frontmatter.category.as_deref() {
767 Some("run") | Some("features") | Some("installation") | Some("data") | Some("intro") => 4,
768 Some("docs") => -2,
769 Some(_) | None => 0,
770 };
771
772 let scope_score = match (&doc.scope, doc.frontmatter.scope.as_deref()) {
773 (GuideDocScope::Module(_), Some("module")) => 4,
774 (GuideDocScope::Core, Some("core")) => 2,
775 _ => 0,
776 };
777
778 kind_score + category_score + scope_score
779}
780
781fn score_search_hit(doc: &GuideDoc, lines: &[&str], keyword_lower: &str, matching_lines: &[usize]) -> usize {
782 let (mut score, _) = score_metadata_hit(doc, keyword_lower);
783 score = score.saturating_add_signed(score_doc_shape(doc));
784 score += match_score(&doc.filename, keyword_lower, 140, 80);
785 score += match_score(&doc.path, keyword_lower, 120, 36);
786
787 for line_index in matching_lines {
788 let line = lines[*line_index];
789 let lower = line.to_lowercase();
790 let trimmed = line.trim_start();
791 let trimmed_lower = lower.trim_start();
792
793 if trimmed.starts_with('#') {
794 score += 48;
795 } else {
796 score += 10;
797 }
798
799 if trimmed_lower == keyword_lower {
800 score += 36;
801 }
802
803 if trimmed_lower.starts_with(keyword_lower) {
804 score += 18;
805 }
806
807 if lower.contains(&format!("`{keyword_lower}`")) {
808 score += 14;
809 }
810
811 if *line_index < 40 {
812 score += 6;
813 }
814 }
815
816 score
817}
818
819fn merge_ranges(mut matching_ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
820 matching_ranges.sort_by_key(|range| range.0);
821 let mut merged_ranges: Vec<(usize, usize)> = Vec::new();
822
823 for (start, end) in matching_ranges {
824 if let Some(last) = merged_ranges.last_mut()
825 && start <= last.1
826 {
827 last.1 = last.1.max(end);
828 continue;
829 }
830 merged_ranges.push((start, end));
831 }
832
833 merged_ranges
834}
835
836fn collect_search_results(
837 guide_docs: &[GuideDoc],
838 keyword_lower: &str,
839 context_lines: usize,
840 filename_filter: Option<&str>,
841) -> Vec<SearchResult> {
842 let mut results = Vec::new();
843
844 for (doc_index, doc) in guide_docs.iter().enumerate() {
845 if doc.filename.to_uppercase().contains("SUMMARY") {
846 continue;
847 }
848
849 if let Some(filter) = filename_filter
850 && !doc.filename.contains(filter)
851 && !doc.path.contains(filter)
852 {
853 continue;
854 }
855
856 let lines: Vec<&str> = doc.content.lines().collect();
857 let mut matching_ranges: Vec<(usize, usize)> = Vec::new();
858 let mut matching_lines: Vec<usize> = Vec::new();
859 let (_, metadata_matched) = score_metadata_hit(doc, keyword_lower);
860
861 for (line_num, line) in lines.iter().enumerate() {
862 if line.to_lowercase().contains(keyword_lower) {
863 let start = line_num.saturating_sub(context_lines);
864 let end = (line_num + context_lines + 1).min(lines.len());
865 matching_ranges.push((start, end));
866 matching_lines.push(line_num);
867 }
868 }
869
870 if matching_ranges.is_empty() && !metadata_matched {
871 continue;
872 }
873
874 if matching_ranges.is_empty() {
875 let preview_end = lines.len().min(context_lines.saturating_mul(2).max(6));
876 if preview_end > 0 {
877 matching_ranges.push((0, preview_end));
878 }
879 }
880
881 results.push(SearchResult {
882 doc_index,
883 merged_ranges: merge_ranges(matching_ranges),
884 score: score_search_hit(doc, &lines, keyword_lower, &matching_lines),
885 });
886 }
887
888 results.sort_by(|a, b| {
889 b.score
890 .cmp(&a.score)
891 .then_with(|| guide_docs[a.doc_index].path.cmp(&guide_docs[b.doc_index].path))
892 });
893
894 results
895}
896
897fn handle_scopes() -> Result<(), String> {
898 let scopes = list_doc_scopes()?;
899
900 println!("{}", "Available Documentation Scopes:".bold());
901 println!("{}", "calcit".cyan().bold());
902
903 for scope in scopes.iter().filter(|scope| scope.as_str() != "calcit") {
904 println!(" {}", scope.cyan());
905 }
906
907 println!("\n{} {} scopes", "Total:".dimmed(), scopes.len());
908 if command_guidance_enabled() {
909 println!("{}", "Use 'calcit docs list' to list guidebook files in calcit.".dimmed());
910 println!(
911 "{}",
912 " Use 'calcit docs list --module <module>' to list files in an installed module.".dimmed()
913 );
914 }
915
916 Ok(())
917}
918
919fn handle_search(
920 keyword: &str,
921 context_lines: usize,
922 filename_filter: Option<&str>,
923 module_filter: Option<&str>,
924 summary_mode: bool,
925) -> Result<(), String> {
926 let guide_docs = collect_docs_for_query(module_filter)?;
927 let keyword_lower = keyword.to_lowercase();
928
929 let results = collect_search_results(&guide_docs, &keyword_lower, context_lines, filename_filter);
930
931 for result in &results {
932 let doc = &guide_docs[result.doc_index];
933
934 let mut title = doc.display_title();
936 if doc.frontmatter.kind.as_deref() == Some("hub") {
937 title = format!("{} {}", "[Hub]", title);
938 }
939 println!("{} ({})", title.cyan().bold(), doc.path.dimmed());
940
941 if summary_mode {
943 if let Some(summary) = &doc.frontmatter.summary {
944 println!(" {}", summary.dimmed());
945 } else {
946 println!(" {}", "(no summary)".dimmed());
947 }
948 println!();
949 continue;
950 }
951
952 println!("{}", "-".repeat(60).dimmed());
953
954 let lines: Vec<&str> = doc.content.lines().collect();
955 for (start, end) in &result.merged_ranges {
956 for (idx, line) in lines[*start..*end].iter().enumerate() {
957 let line_num = *start + idx + 1;
958 if line.to_lowercase().contains(&keyword_lower) {
959 println!("{} {}", format!("{line_num:4}:").yellow(), line);
960 } else {
961 println!("{} {}", format!("{line_num:4}:").dimmed(), line.dimmed());
962 }
963 }
964 println!();
965 }
966 }
967
968 if results.is_empty() {
969 println!("{}", "No matching content found.".yellow());
970 } else if command_guidance_enabled() {
971 if summary_mode {
972 println!(
973 "{}",
974 "Tip: Omit --summary to see full context snippets. Use --context <num> for more context.".dimmed()
975 );
976 } else {
977 println!(
978 "{}",
979 "Tip: Use --context <num> to show more context lines (e.g., 'calcit docs search <keyword> --context 20')".dimmed()
980 );
981 }
982 println!(
983 "{}",
984 " Use --filename <filename> to filter by filename. Use --module <name> to search module docs.".dimmed()
985 );
986 }
987
988 Ok(())
989}
990
991fn handle_sections(filename: &str, module_filter: Option<&str>, with_lines: bool) -> Result<(), String> {
992 let guide_docs = collect_docs_for_query(module_filter)?;
993 let doc = find_doc_by_query(&guide_docs, filename)?;
994
995 handle_read_content(ReadRenderOptions {
996 display_title: &doc.display_title(),
997 display_path: &doc.path,
998 command_hint: "sections",
999 no_match_error: "No sections found in document.",
1000 content: &doc.content,
1001 heading_queries: &[],
1002 include_subheadings: true,
1003 full: false,
1004 with_lines,
1005 })
1006}
1007
1008fn handle_agents(
1009 heading_queries: &[String],
1010 include_subheadings: bool,
1011 full: bool,
1012 contract: bool,
1013 with_lines: bool,
1014 force_refresh: bool,
1015) -> Result<(), String> {
1016 if contract && (full || with_lines || !heading_queries.is_empty() || !include_subheadings) {
1017 return Err(
1018 "`calcit docs agents --contract` cannot be combined with headings, --full, --with-lines, or --no-subheadings".to_string(),
1019 );
1020 }
1021 let document = load_agents_document(force_refresh)?;
1022 if document.refreshed {
1023 println!("{}", format!("Refreshed remote Agents doc cache from: {AGENTS_DOC_URL}").dimmed());
1024 }
1025 let (frontmatter, content) = parse_doc_frontmatter(&document.content);
1026 validate_doc_frontmatter(&document.display_path, &frontmatter)?;
1027 let byte_len = content.len();
1028 let line_len = content.lines().count();
1029
1030 if contract {
1031 let contract = extract_agent_mutation_contract(&document.content)?;
1032 println!("{} v{AGENT_MUTATION_CONTRACT_VERSION}", "Agent mutation contract:".dimmed());
1033 println!("{} {}", "Agent source:".dimmed(), document.display_path.cyan());
1034 println!("{} {}", "Agent contract digest:".dimmed(), contract.digest.cyan());
1035 println!(
1036 "{} {} bytes, {} lines",
1037 "Agent contract length:".dimmed(),
1038 contract.content.len().to_string().cyan(),
1039 contract.content.lines().count().to_string().cyan()
1040 );
1041 println!();
1042 print!("{}", contract.content);
1043 return Ok(());
1044 }
1045
1046 println!("{} {}", "Agent source:".dimmed(), document.display_path.cyan());
1047 println!(
1048 "{} {} bytes, {} lines",
1049 "Agent length:".dimmed(),
1050 byte_len.to_string().cyan(),
1051 line_len.to_string().cyan()
1052 );
1053
1054 handle_read_content(ReadRenderOptions {
1055 display_title: frontmatter.title.as_deref().unwrap_or("Agents.md"),
1056 display_path: &document.display_path,
1057 command_hint: "agents",
1058 no_match_error: "No heading matched in Agents.md. Run 'calcit docs agents' to list available headings.",
1059 content: &content,
1060 heading_queries,
1061 include_subheadings,
1062 full,
1063 with_lines,
1064 })
1065}
1066
1067fn handle_read(
1068 filename: &str,
1069 heading_queries: &[String],
1070 include_subheadings: bool,
1071 full: bool,
1072 with_lines: bool,
1073 module_filter: Option<&str>,
1074) -> Result<(), String> {
1075 let guide_docs = collect_docs_for_query(module_filter)?;
1076 let doc = find_doc_by_query(&guide_docs, filename)?;
1077 let read_full = full || heading_queries.is_empty();
1078 let result = handle_read_content(ReadRenderOptions {
1079 display_title: &doc.display_title(),
1080 display_path: &doc.path,
1081 command_hint: "read",
1082 no_match_error: "No section matched in document.",
1083 content: &doc.content,
1084 heading_queries,
1085 include_subheadings,
1086 full: read_full,
1087 with_lines,
1088 });
1089
1090 if result.is_err() && !heading_queries.is_empty() {
1091 return Err(format!(
1092 "No section matched: {}. Use 'calcit docs sections {filename}' to list available headings.",
1093 heading_queries.join(", ")
1094 ));
1095 }
1096
1097 result
1098}
1099
1100fn handle_read_lines(filename: &str, start: usize, lines_to_read: usize, module_filter: Option<&str>) -> Result<(), String> {
1101 let guide_docs = collect_docs_for_query(module_filter)?;
1102 let doc = find_doc_by_query(&guide_docs, filename)?;
1103
1104 let all_lines: Vec<&str> = doc.content.lines().collect();
1105 let total_lines = all_lines.len();
1106 if start >= total_lines && start > 0 {
1107 return Err(format!(
1108 "`--start {start}` is past the end of `{}` ({total_lines} lines); use a start below {total_lines}.",
1109 doc.path
1110 ));
1111 }
1112 let end = start.saturating_add(lines_to_read).min(total_lines);
1113
1114 println!("{} ({})", doc.display_title().cyan().bold(), doc.path.dimmed());
1115 println!("{}", "=".repeat(60).dimmed());
1116
1117 for (idx, line) in all_lines[start..end].iter().enumerate() {
1118 let line_num = start + idx + 1;
1119 println!("{} {}", format!("{line_num:4}:").dimmed(), line);
1120 }
1121
1122 println!();
1123 println!(
1124 "{}",
1125 format!("Lines {}-{} of {} (total {} lines)", start + 1, end, total_lines, total_lines).dimmed()
1126 );
1127
1128 if end < total_lines {
1129 let remaining = total_lines - end;
1130 println!(
1131 "{}",
1132 format!("More content available ({remaining} lines remaining). Next start line: {end}.").yellow()
1133 );
1134 } else {
1135 println!("{}", "End of document.".green());
1136 }
1137
1138 if command_guidance_enabled() {
1139 println!(
1140 "{}",
1141 "Tip: Use --start <start> --lines <lines> to read a specific range (e.g., 'calcit docs read file.md --start 20 --lines 30')"
1142 .dimmed()
1143 );
1144 }
1145
1146 Ok(())
1147}
1148
1149fn handle_list(module_filter: Option<&str>) -> Result<(), String> {
1150 let guide_docs = collect_docs_for_query(module_filter)?;
1151 let header = match module_filter {
1152 Some(module) => format!("Available Documentation Files for module {module}:"),
1153 None => "Available Documentation Files for calcit:".to_string(),
1154 };
1155
1156 println!("{}", header.bold());
1157
1158 let mut docs: Vec<&GuideDoc> = guide_docs.iter().collect();
1159 docs.sort_by_key(|d| &d.path);
1160
1161 for doc in &docs {
1162 let preview = if doc.content.len() > 100 {
1163 format!("{}...", doc.content.lines().next().unwrap_or(""))
1164 } else {
1165 doc.content.lines().next().unwrap_or("").to_string()
1166 };
1167
1168 println!(" {} - {}", doc.filename.cyan(), preview.dimmed());
1169 }
1170
1171 println!("\n{} {} topics", "Total:".dimmed(), docs.len());
1172 if command_guidance_enabled() {
1173 println!(
1174 "{}",
1175 "Use 'calcit docs sections <filename>' to list headings in a document".dimmed()
1176 );
1177 println!(
1178 "{}",
1179 " 'calcit docs read <filename> <heading-keyword>' to read matched sections".dimmed()
1180 );
1181 println!("{}", " 'calcit docs read <filename>' to read the full document".dimmed());
1182 println!(
1183 "{}",
1184 " 'calcit docs read <filename> --start <start> --lines <lines>' for line-based reading".dimmed()
1185 );
1186 println!("{}", " 'calcit docs search <keyword>' to search content".dimmed());
1187 }
1188
1189 Ok(())
1190}
1191
1192#[cfg(test)]
1193#[path = "docs_tests.rs"]
1194mod tests;
1195
1196#[derive(Debug, Clone, Copy, PartialEq)]
1204enum CirruCheckMode {
1205 Run,
1206 NoRun,
1207 NoCli,
1208 NoCheck,
1209 Edn,
1210}
1211
1212fn cirru_fence_mode(fence: &str) -> Option<CirruCheckMode> {
1213 match fence {
1214 "```cirru" => Some(CirruCheckMode::Run),
1215 "```cirru.no-run" => Some(CirruCheckMode::NoRun),
1216 "```cirru.no-check" => Some(CirruCheckMode::NoCheck),
1217 "```cirru.cli" => Some(CirruCheckMode::NoCli),
1218 "```cirru.edn" => Some(CirruCheckMode::Edn),
1219 _ => None,
1220 }
1221}
1222
1223impl std::fmt::Display for CirruCheckMode {
1224 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1225 match self {
1226 CirruCheckMode::Run => write!(f, "run"),
1227 CirruCheckMode::NoRun => write!(f, "no-run"),
1228 CirruCheckMode::NoCli => write!(f, "no-cli"),
1229 CirruCheckMode::NoCheck => write!(f, "no-check"),
1230 CirruCheckMode::Edn => write!(f, "edn"),
1231 }
1232 }
1233}
1234
1235fn extract_cirru_blocks(content: &str) -> Vec<(usize, CirruCheckMode, String)> {
1239 let mut blocks = Vec::new();
1240 let mut in_block = false;
1241 let mut in_non_cirru_block = false;
1242 let mut block_start_line = 0;
1243 let mut block_mode = CirruCheckMode::Run;
1244 let mut block_lines: Vec<&str> = Vec::new();
1245
1246 for (idx, line) in content.lines().enumerate() {
1247 let trimmed = line.trim();
1248 if !in_block && !in_non_cirru_block && trimmed.starts_with("```") {
1249 if trimmed == "```cirru" {
1250 in_block = true;
1251 block_start_line = idx + 1;
1252 block_mode = CirruCheckMode::Run;
1253 block_lines.clear();
1254 } else if trimmed == "```cirru.no-run" {
1255 in_block = true;
1256 block_start_line = idx + 1;
1257 block_mode = CirruCheckMode::NoRun;
1258 block_lines.clear();
1259 } else if trimmed == "```cirru.no-check" {
1260 in_block = true;
1261 block_start_line = idx + 1;
1262 block_mode = CirruCheckMode::NoCheck;
1263 block_lines.clear();
1264 } else if trimmed == "```cirru.cli" {
1265 in_block = true;
1266 block_start_line = idx + 1;
1267 block_mode = CirruCheckMode::NoCli;
1268 block_lines.clear();
1269 } else if trimmed == "```cirru.edn" {
1270 in_block = true;
1271 block_start_line = idx + 1;
1272 block_mode = CirruCheckMode::Edn;
1273 block_lines.clear();
1274 } else {
1275 in_non_cirru_block = true;
1276 }
1277 } else if (in_block || in_non_cirru_block) && trimmed == "```" {
1278 if in_block && !block_lines.is_empty() {
1279 blocks.push((block_start_line, block_mode, block_lines.join("\n")));
1280 }
1281 in_block = false;
1282 in_non_cirru_block = false;
1283 } else if in_block {
1284 block_lines.push(line);
1285 }
1286 }
1287
1288 blocks
1289}
1290
1291#[derive(Debug)]
1292struct FormattedMarkdown {
1293 content: String,
1294 total_blocks: usize,
1295 changed_blocks: usize,
1296}
1297
1298fn format_markdown_cirru_blocks(content: &str) -> Result<FormattedMarkdown, String> {
1304 let line_ending = if content.contains("\r\n") { "\r\n" } else { "\n" };
1305 let mut output = String::with_capacity(content.len());
1306 let mut in_cirru_block = false;
1307 let mut format_cirru_block = false;
1308 let mut in_other_block = false;
1309 let mut block_start_line = 0;
1310 let mut code_lines: Vec<String> = Vec::new();
1311 let mut raw_code_lines: Vec<String> = Vec::new();
1312 let mut total_blocks = 0;
1313 let mut changed_blocks = 0;
1314
1315 for (line_index, raw_line) in content.split_inclusive('\n').enumerate() {
1316 let line = raw_line.strip_suffix('\n').unwrap_or(raw_line);
1317 let line = line.strip_suffix('\r').unwrap_or(line);
1318 let trimmed = line.trim();
1319
1320 if !in_cirru_block && !in_other_block && trimmed.starts_with("```") {
1321 if let Some(mode) = cirru_fence_mode(trimmed) {
1322 in_cirru_block = true;
1323 format_cirru_block = mode != CirruCheckMode::Edn;
1324 block_start_line = line_index + 2;
1325 code_lines.clear();
1326 raw_code_lines.clear();
1327 } else {
1328 in_other_block = true;
1329 }
1330 output.push_str(raw_line);
1331 } else if (in_cirru_block || in_other_block) && trimmed == "```" {
1332 if in_cirru_block {
1333 total_blocks += 1;
1334 if format_cirru_block {
1335 let source = code_lines.join("\n");
1336 let nodes = cirru_parser::parse(&source)
1337 .map_err(|error| format!("Failed to parse Cirru block starting at line {block_start_line}: {error}"))?;
1338 let formatted = cirru_parser::format(&nodes, true.into())
1339 .map_err(|error| format!("Failed to format Cirru block starting at line {block_start_line}: {error}"))?;
1340 let canonical = formatted.trim();
1341 if source != canonical {
1342 changed_blocks += 1;
1343 }
1344 if !canonical.is_empty() {
1345 for formatted_line in canonical.split('\n') {
1346 output.push_str(formatted_line);
1347 output.push_str(line_ending);
1348 }
1349 }
1350 } else {
1351 for raw_code_line in &raw_code_lines {
1352 output.push_str(raw_code_line);
1353 }
1354 }
1355 }
1356 in_cirru_block = false;
1357 format_cirru_block = false;
1358 in_other_block = false;
1359 output.push_str(raw_line);
1360 } else if in_cirru_block {
1361 code_lines.push(line.to_string());
1362 raw_code_lines.push(raw_line.to_string());
1363 } else {
1364 output.push_str(raw_line);
1365 }
1366 }
1367
1368 if in_cirru_block {
1369 return Err(format!("Unclosed Cirru code block starting at line {block_start_line}"));
1370 }
1371
1372 Ok(FormattedMarkdown {
1373 content: output,
1374 total_blocks,
1375 changed_blocks,
1376 })
1377}
1378
1379fn handle_format_md(file_path: &str, check: bool) -> Result<(), String> {
1380 let content = fs::read_to_string(file_path).map_err(|error| format!("Failed to read file '{file_path}': {error}"))?;
1381 let formatted = format_markdown_cirru_blocks(&content)?;
1382
1383 if check {
1384 if formatted.changed_blocks == 0 {
1385 println!(
1386 "{} {} Cirru blocks already canonical {}",
1387 file_path.cyan(),
1388 formatted.total_blocks,
1389 "✓".green()
1390 );
1391 return Ok(());
1392 }
1393 return Err(format!(
1394 "{} Cirru block(s) in '{file_path}' need formatting. Run `calcit docs format-md {file_path}`.",
1395 formatted.changed_blocks
1396 ));
1397 }
1398
1399 if formatted.changed_blocks == 0 {
1400 println!(
1401 "{} {} Cirru blocks already canonical {}",
1402 file_path.cyan(),
1403 formatted.total_blocks,
1404 "✓".green()
1405 );
1406 return Ok(());
1407 }
1408
1409 let staged = stage_atomic_file(Path::new(file_path), formatted.content.as_bytes(), "Markdown")?;
1410 staged.commit()?;
1411 println!(
1412 "{} formatted {} of {} Cirru blocks {}",
1413 file_path.cyan(),
1414 formatted.changed_blocks,
1415 formatted.total_blocks,
1416 "✓".green()
1417 );
1418 Ok(())
1419}
1420
1421fn ensure_runtime_initialized() {
1422 static RUNTIME_INIT: Once = Once::new();
1423 RUNTIME_INIT.call_once(|| {
1424 calcit_core::builtins::effects::init_effects_states();
1425 #[cfg(not(target_arch = "wasm32"))]
1426 crate::injection::inject_platform_apis();
1427 });
1428}
1429
1430fn collect_check_md_module_paths(entry: &str, deps: &[String]) -> Result<Vec<String>, String> {
1431 let snapshot = load_entry_snapshot_for_check_md(entry)?;
1432 let mut module_paths = snapshot.active_entry()?.modules.clone();
1433 module_paths.extend(deps.iter().cloned());
1434
1435 let mut seen_modules: HashSet<String> = HashSet::new();
1436 module_paths.retain(|module_path| seen_modules.insert(module_path.to_owned()));
1437 Ok(module_paths)
1438}
1439
1440pub(crate) fn load_entry_snapshot_for_check_md(entry: &str) -> Result<snapshot::Snapshot, String> {
1441 let resolved_entry = Path::new(entry);
1442 calcit_core::validate_snapshot_path(resolved_entry)?;
1443 let mut content =
1444 fs::read_to_string(resolved_entry).map_err(|e| format!("Failed to read entry file '{}': {e}", resolved_entry.display()))?;
1445 util::string::strip_shebang(&mut content);
1446 let data = cirru_edn::parse(&content).map_err(|e| format!("Failed to parse entry file '{}': {e}", resolved_entry.display()))?;
1447 snapshot::load_snapshot_data(&data, &resolved_entry.display().to_string())
1448}
1449
1450fn load_shared_files_for_check_md(entry: &str, deps: &[String]) -> Result<HashMap<String, snapshot::FileInSnapShot>, String> {
1451 ensure_runtime_initialized();
1452
1453 let entry_path = PathBuf::from(entry);
1454 let base_dir = entry_path.parent().unwrap_or_else(|| Path::new("."));
1455 let module_folder = calcit_core::project_module_folder(base_dir);
1456 let module_paths = collect_check_md_module_paths(entry, deps)?;
1457
1458 let mut shared_files: HashMap<String, snapshot::FileInSnapShot> = HashMap::new();
1459
1460 for module_path in &module_paths {
1461 let module_data = calcit_core::load_module(module_path, base_dir, &module_folder)?;
1462 for (k, v) in &module_data.files {
1463 if let Some(existing) = shared_files.get(k) {
1464 if existing == v {
1465 continue;
1466 }
1467 return Err(format!(
1468 "namespace `{k}` conflicts with existing content when loading module `{module_path}`"
1469 ));
1470 }
1471 shared_files.insert(k.to_owned(), v.to_owned());
1472 }
1473 }
1474
1475 let core_snapshot = calcit_core::load_core_snapshot()?;
1476 for (k, v) in core_snapshot.files {
1477 shared_files.insert(k, v);
1478 }
1479
1480 Ok(shared_files)
1481}
1482
1483fn build_entries_from_snapshot(snapshot: &snapshot::Snapshot) -> Result<ProgramEntries, String> {
1484 let selected_entry = snapshot.active_entry()?;
1485 let config_init = selected_entry.init_fn.to_string();
1486 let config_reload = selected_entry.reload_fn.to_string();
1487 let (init_ns, init_def) = util::string::extract_ns_def(&config_init)?;
1488 let (reload_ns, reload_def) = util::string::extract_ns_def(&config_reload)?;
1489
1490 Ok(ProgramEntries {
1491 init_fn: Arc::from(config_init),
1492 reload_fn: Arc::from(config_reload),
1493 init_def: Arc::from(init_def),
1494 init_ns: Arc::from(init_ns),
1495 reload_ns: Arc::from(reload_ns),
1496 reload_def: Arc::from(reload_def),
1497 })
1498}
1499
1500fn prepare_program_for_snippet(
1501 entry: &str,
1502 shared_files: &HashMap<String, snapshot::FileInSnapShot>,
1503 code: &str,
1504) -> Result<ProgramEntries, String> {
1505 ensure_runtime_initialized();
1506
1507 program::clear_runtime_caches_for_reload(Arc::from("app.main"), Arc::from("app.main"), true)?;
1510
1511 let mut snapshot = load_entry_snapshot_for_check_md(entry).map_err(|e| format!("check-md: failed to load entry `{entry}`: {e}"))?;
1512 let mut project_namespaces = snapshot.files.keys().cloned().collect::<HashSet<_>>();
1513 let main_file = snapshot::create_file_from_snippet(code)?;
1514
1515 for (k, v) in shared_files {
1516 snapshot.files.insert(k.to_owned(), v.to_owned());
1517 }
1518 snapshot.files.insert(String::from("app.main"), main_file);
1520 project_namespaces.insert(String::from("app.main"));
1521 runner::preprocess::set_project_namespaces(&project_namespaces);
1522
1523 {
1524 let mut prgm = program::PROGRAM_CODE_DATA.write().map_err(|_| "open program data".to_string())?;
1525 *prgm = program::extract_program_data(&snapshot)?;
1526 }
1527
1528 let check_warnings: &RefCell<Vec<LocatedWarning>> = &RefCell::new(vec![]);
1529 runner::preprocess::ensure_ns_def_compiled(
1530 calcit_core::calcit::CORE_NS,
1531 calcit_core::calcit::BUILTIN_IMPLS_ENTRY,
1532 check_warnings,
1533 &CallStackList::default(),
1534 )
1535 .map_err(|e| e.msg)?;
1536
1537 let mut entries = build_entries_from_snapshot(&snapshot)?;
1538 entries.init_ns = Arc::from("app.main");
1542 entries.init_def = Arc::from("main!");
1543 entries.init_fn = Arc::from("|app.main/main!");
1544 entries.reload_fn = Arc::from("|app.main/reload!");
1545 entries.reload_ns = Arc::from("app.main");
1546 entries.reload_def = Arc::from("reload!");
1547 Ok(entries)
1548}
1549
1550fn run_check_only_in_process(entries: &ProgramEntries) -> Result<(), String> {
1551 let check_warnings: &RefCell<Vec<LocatedWarning>> = &RefCell::new(vec![]);
1552
1553 let compile_entry_def = |ns: &Arc<str>, def: &Arc<str>| {
1554 runner::preprocess::ensure_ns_def_compiled(ns, def, check_warnings, &CallStackList::default()).map_err(|failure| failure.msg)
1555 };
1556
1557 let snippet_targets: Vec<(Arc<str>, Arc<str>)> = {
1561 let program_data = program::PROGRAM_CODE_DATA.read().map_err(|_| "open program data".to_string())?;
1562 program_data
1563 .get("app.main")
1564 .map(|file_data| {
1565 file_data
1566 .defs
1567 .keys()
1568 .map(|def_name| (Arc::from("app.main"), def_name.to_owned()))
1569 .collect()
1570 })
1571 .unwrap_or_default()
1572 };
1573
1574 if !snippet_targets.is_empty() {
1575 for (ns_name, def_name) in snippet_targets {
1576 compile_entry_def(&ns_name, &def_name).map_err(|e| format!("compile {ns_name}/{def_name}: {e}"))?;
1577 }
1578 } else {
1579 let entry_check =
1580 compile_entry_def(&entries.init_ns, &entries.init_def).and_then(|_| compile_entry_def(&entries.reload_ns, &entries.reload_def));
1581
1582 if let Err(entry_err) = entry_check {
1583 if entry_err.contains("unknown ns/def in program") {
1584 let targets: Vec<(Arc<str>, Arc<str>)> = {
1585 let program_data = program::PROGRAM_CODE_DATA.read().map_err(|_| "open program data".to_string())?;
1586 let mut pairs: Vec<(Arc<str>, Arc<str>)> = Vec::new();
1587 for (ns_name, file_data) in &*program_data {
1588 if ns_name.starts_with("app.") {
1589 for def_name in file_data.defs.keys() {
1590 pairs.push((ns_name.to_owned(), def_name.to_owned()));
1591 }
1592 }
1593 }
1594 pairs
1595 };
1596
1597 if targets.is_empty() {
1598 return Err(entry_err);
1599 }
1600
1601 for (ns_name, def_name) in targets {
1602 compile_entry_def(&ns_name, &def_name)?;
1603 }
1604 } else {
1605 return Err(entry_err);
1606 }
1607 }
1608 }
1609
1610 let warnings = check_warnings.borrow();
1611 if !warnings.is_empty() {
1612 let mut lines = vec![format!("Errors: ({} errors)", warnings.len())];
1613 lines.extend(warnings.iter().map(|w| w.to_string()));
1614 return Err(lines.join("\n"));
1615 }
1616
1617 Ok(())
1618}
1619
1620fn run_eval_in_process(entries: &ProgramEntries) -> Result<(), String> {
1621 match calcit_core::run_program_with_docs(entries.init_ns.to_owned(), entries.init_def.to_owned(), &[]) {
1622 Ok(_) => Ok(()),
1623 Err(e) => {
1624 let mut lines: Vec<String> = vec![];
1625 if !e.warnings.is_empty() {
1626 lines.push(format!("Errors: ({} errors)", e.warnings.len()));
1627 lines.extend(e.warnings.iter().map(|w| w.to_string()));
1628 }
1629 lines.push(format!("Error: {}", e.msg));
1630 Err(lines.join("\n"))
1631 }
1632 }
1633}
1634
1635fn run_parse_only_in_process(code: &str) -> Result<(), String> {
1636 cirru_parser::parse(code)
1637 .map(|_| ())
1638 .map_err(|e| format!("Error: Failed to parse code snippet: {e}"))
1639}
1640
1641fn run_edn_parse_only(code: &str) -> Result<(), String> {
1642 cirru_edn::parse(code)
1643 .map(|_| ())
1644 .map_err(|e| format!("Error: Failed to parse code snippet as EDN: {e}"))
1645}
1646
1647struct QuietToolOutputGuard {
1648 previous: bool,
1649}
1650
1651impl QuietToolOutputGuard {
1652 fn new(enabled: bool) -> Option<Self> {
1653 if enabled {
1654 let previous = calcit_core::quiet_tool_output();
1655 calcit_core::set_quiet_tool_output(true);
1656 Some(Self { previous })
1657 } else {
1658 None
1659 }
1660 }
1661}
1662
1663impl Drop for QuietToolOutputGuard {
1664 fn drop(&mut self) {
1665 calcit_core::set_quiet_tool_output(self.previous);
1666 }
1667}
1668
1669fn handle_check_md(file_path: &str, entry: &str, deps: &[String], quiet: bool, failures_only: bool) -> Result<(), String> {
1670 let content = fs::read_to_string(file_path).map_err(|e| format!("Failed to read file '{file_path}': {e}"))?;
1671
1672 let blocks = extract_cirru_blocks(&content);
1673
1674 if blocks.is_empty() {
1675 if !quiet && !failures_only {
1676 println!("{}", "No cirru code blocks found in the file.".yellow());
1677 }
1678 return Ok(());
1679 }
1680
1681 let requires_calcit_context = blocks.iter().any(|(_, mode, _)| *mode != CirruCheckMode::Edn);
1682 if requires_calcit_context && !Path::new(entry).exists() {
1683 return Err(format!(
1684 "Snapshot file '{entry}' not found. Use --snapshot <file> to select an existing .cirru evaluation context."
1685 ));
1686 }
1687
1688 let _quiet_guard = QuietToolOutputGuard::new(true);
1690 let shared_files = if requires_calcit_context {
1691 load_shared_files_for_check_md(entry, deps)?
1692 } else {
1693 HashMap::new()
1694 };
1695
1696 let mut passed = 0;
1697 let mut failed = 0;
1698 let total = blocks.len();
1699 let _run_count = blocks.iter().filter(|(_, mode, _)| *mode == CirruCheckMode::Run).count();
1700 let _no_run_count = blocks.iter().filter(|(_, mode, _)| *mode == CirruCheckMode::NoRun).count();
1701 let _no_cli_count = blocks.iter().filter(|(_, mode, _)| *mode == CirruCheckMode::NoCli).count();
1702 let _no_check_count = blocks.iter().filter(|(_, mode, _)| *mode == CirruCheckMode::NoCheck).count();
1703 let _edn_count = blocks.iter().filter(|(_, mode, _)| *mode == CirruCheckMode::Edn).count();
1704 let mut failure_details = String::new();
1705
1706 for (line_num, mode, code) in &blocks {
1707 let preview: String = code.lines().next().unwrap_or("").chars().take(60).collect();
1708 let preview_suffix = if code.lines().count() > 1 || preview.len() >= 60 {
1709 "..."
1710 } else {
1711 ""
1712 };
1713
1714 let mode_label = match mode {
1715 CirruCheckMode::Run => "",
1716 CirruCheckMode::NoRun => "[no-run] ",
1717 CirruCheckMode::NoCli => "[cli] ",
1718 CirruCheckMode::NoCheck => "[no-check] ",
1719 CirruCheckMode::Edn => "[edn] ",
1720 };
1721
1722 let check_result = match mode {
1723 CirruCheckMode::Run => prepare_program_for_snippet(entry, &shared_files, code).and_then(|entries| run_eval_in_process(&entries)),
1724 CirruCheckMode::NoRun | CirruCheckMode::NoCli => {
1725 prepare_program_for_snippet(entry, &shared_files, code).and_then(|entries| run_check_only_in_process(&entries))
1726 }
1727 CirruCheckMode::NoCheck => run_parse_only_in_process(code),
1728 CirruCheckMode::Edn => run_edn_parse_only(code),
1729 };
1730
1731 if check_result.is_ok() {
1732 passed += 1;
1733 } else {
1734 failed += 1;
1735 let stderr = check_result
1736 .as_ref()
1737 .err()
1738 .cloned()
1739 .unwrap_or_else(|| "Error: Unknown error".to_string());
1740 failure_details.push_str(&format!(
1741 " {} L{}: {}{}{}\n",
1742 "✗".red(),
1743 format!("{line_num}").yellow(),
1744 mode_label,
1745 preview,
1746 preview_suffix
1747 ));
1748 for line in stderr.lines() {
1749 if !line.trim().is_empty() {
1750 failure_details.push_str(&format!(" {}\n", line.red()));
1751 }
1752 }
1753 }
1754 }
1755
1756 if !quiet && !failures_only {
1757 if failed == 0 && !quiet {
1759 println!("{} {} blocks, {} passed {}", file_path.cyan(), total, passed, "✓".green());
1760 }
1761 }
1762
1763 if failed > 0 {
1764 if !failures_only {
1765 println!(
1766 "{} {} blocks, {} passed, {} failed {}",
1767 file_path.cyan(),
1768 total,
1769 passed,
1770 failed,
1771 "✗".red()
1772 );
1773 } else {
1774 println!("{} {} blocks, {} passed, {} failed", file_path.cyan(), total, passed, failed);
1776 }
1777 print!("{failure_details}");
1778 }
1779
1780 let summary = format!("Results: {total} blocks, {passed} passed, {failed} failed");
1781 if failed > 0 {
1782 if !quiet && !failures_only {
1783 println!("{}", summary.red().bold());
1784 }
1785 Err(format!("check-md failed: {summary}\n{failure_details}"))
1786 } else if quiet || failures_only {
1787 Ok(())
1788 } else {
1789 println!("{}", summary.green().bold());
1790 Ok(())
1791 }
1792}