Skip to main content

comindly_core/
pipeline.rs

1//! Indexing: check out repositories, parse and bind them across repositories, persist the graph,
2//! then the optional steps (search embeddings, summaries, style guides, flow walkthroughs).
3//! Async and cancellable; CPU-heavy work runs on the blocking pool; progress goes to the context's
4//! reporter. LLM output is saved as it is written and reused while its input is unchanged, so an
5//! interrupted run continues where it stopped.
6
7use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10
11use anyhow::{Context, Result};
12use futures::StreamExt;
13
14use crate::context::{Cancelled, IndexContext};
15use crate::events::Usage;
16use crate::model::{Edge, EdgeKind, GlobalSymbolId, Symbol, SymbolKind};
17use crate::prompts::{Prompts, Task};
18
19/// A repository to index: the folder of its clone and, for one comindly keeps itself, the URL it
20/// is cloned from when the folder is missing.
21#[derive(Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)]
22pub struct RepoEntry {
23    pub path: String,
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub remote: Option<String>,
26}
27
28/// A repository to index: its name and the folder holding its checkout.
29#[derive(Debug, Clone)]
30pub struct Source {
31    pub name: String,
32    pub path: PathBuf,
33    /// The default branch checked out, when comindly made the checkout.
34    pub branch: Option<String>,
35}
36
37impl Source {
38    /// A folder, named after itself.
39    pub fn at(path: impl Into<PathBuf>) -> Source {
40        let path = path.into();
41        let name = match path.file_name().and_then(|n| n.to_str()) {
42            Some(n) if n != "." && n != ".." => n.to_string(),
43            _ => std::fs::canonicalize(&path)
44                .ok()
45                .and_then(|c| c.file_name().map(|n| n.to_string_lossy().into_owned()))
46                .unwrap_or_else(|| "repo".to_string()),
47        };
48        Source {
49            name,
50            path,
51            branch: None,
52        }
53    }
54}
55
56/// A symbol many repositories depend on, for the link report.
57#[derive(Debug, Clone)]
58pub struct Dependency {
59    pub descriptor: String,
60    pub defined_in: String,
61    pub repos: BTreeSet<String>,
62    pub refs: usize,
63}
64
65/// What a link run produced.
66#[derive(Debug, Clone, Default)]
67pub struct LinkReport {
68    pub symbols: usize,
69    pub edges: usize,
70    pub cross_repo_edges: usize,
71    /// Cross-repository import targets, most depended-on first.
72    pub dependencies: Vec<Dependency>,
73}
74
75type TextRow = (GlobalSymbolId, String, Vec<String>);
76
77async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Result<T> {
78    tokio::task::spawn_blocking(f)
79        .await
80        .context("a worker thread failed")
81}
82
83/// Bring each configured repository to its default branch in comindly's own checkout.
84pub fn checkout<'a>(
85    ctx: &'a IndexContext,
86    repos: &'a [RepoEntry],
87) -> futures::future::BoxFuture<'a, Result<Vec<Source>>> {
88    Box::pin(async move {
89        anyhow::ensure!(
90            !repos.is_empty(),
91            "no repositories: pass folders, or add them with `comindly repos add <folder>`"
92        );
93        let r = &ctx.report;
94        r.step(format!("Checking out {} repo(s)", repos.len()));
95        let mut out = Vec::new();
96        for repo in repos {
97            ctx.check()?;
98            let path = PathBuf::from(&repo.path);
99            if let Some(url) = repo.remote.clone() {
100                if !path.exists() {
101                    r.note(format!("cloning {url}"));
102                }
103                let (dest, git) = (path.clone(), ctx.git.clone());
104                blocking(move || {
105                    crate::worktree::ensure_clone(&url, &dest, git.as_ref())
106                        .map_err(|e| anyhow::anyhow!("{url}: {e:#}"))
107                })
108                .await??;
109            }
110            let (dir, git, cache) = (path.clone(), ctx.git.clone(), ctx.cache.clone());
111            let c = blocking(move || crate::worktree::prepare(&cache, &dir, git.as_ref()))
112                .await?
113                .with_context(|| path.display().to_string())?;
114            r.done(format!(
115                "{} @ {} {}",
116                crate::worktree::name(&path),
117                c.target,
118                c.commit
119            ));
120            if let Some(why) = &c.stale {
121                r.warn(format!(
122                    "could not fetch, indexing the last fetched state: {why}"
123                ));
124            }
125            let branch = c.target.strip_prefix("origin/").map(str::to_string);
126            out.push(Source {
127                branch,
128                ..Source::at(c.dir)
129            });
130        }
131        Ok(out)
132    })
133}
134
135/// Parse `sources`, bind references across them, persist the graph and run the optional steps.
136pub fn link<'a>(
137    ctx: &'a IndexContext,
138    sources: Vec<Source>,
139    incremental: bool,
140    scip: crate::scip::Mode,
141) -> futures::future::BoxFuture<'a, Result<LinkReport>> {
142    Box::pin(async move {
143        if let Some(bad) = sources.iter().find(|s| !s.path.is_dir()) {
144            anyhow::bail!("no such repo directory: {}", bad.path.display());
145        }
146        let r = &ctx.report;
147        r.step(format!("Parsing {} repo(s)", sources.len()));
148        let mut symbols: Vec<Symbol> = Vec::new();
149        let mut edges: Vec<Edge> = Vec::new();
150        let mut facts = Vec::new();
151        for s in &sources {
152            ctx.check()?;
153            let (name, path) = (s.name.clone(), s.path.clone());
154            let (out, scip_note) = blocking(move || -> Result<_> {
155                let mut o = crate::parse::parse_repo(&path, &name)
156                    .with_context(|| format!("{name}: parse failed"))?;
157                let note = attach_scip(scip, &path, &name, &mut o)?;
158                Ok((o, note))
159            })
160            .await??;
161            r.note(format!(
162                "{}: {} symbols, {} files",
163                s.name,
164                out.symbols.len(),
165                out.facts.len()
166            ));
167            if let Some(n) = scip_note {
168                r.note(n);
169            }
170            symbols.extend(out.symbols);
171            edges.extend(out.edges);
172            facts.extend(out.facts);
173        }
174
175        ctx.check()?;
176        let (symbols, resolved, facts) = blocking(move || {
177            let resolved = crate::resolve::resolve(&symbols, &edges, &facts);
178            let mut symbols = symbols;
179            symbols.extend(resolved.symbols.iter().cloned());
180            (symbols, resolved, facts)
181        })
182        .await?;
183        report_resolution(ctx, &resolved);
184        let edges = resolved.edges;
185        let dependencies = dependencies(&edges);
186
187        let dst = ctx.graph();
188        r.step("Persisting");
189        r.note(format!("writing org graph to {dst}"));
190        let roots: Vec<(String, PathBuf)> = sources
191            .iter()
192            .map(|s| (s.name.clone(), s.path.clone()))
193            .collect();
194        let packages = scan_packages(ctx, roots.clone()).await?;
195        let recipes = mine_recipes(ctx, roots.clone()).await?;
196        let explain = |e: anyhow::Error| {
197            anyhow::anyhow!(
198                "write failed: {}",
199                crate::storage::explain(&format!("{e:#}"))
200            )
201        };
202        let (sv, ev) = crate::index::write_graph(&dst, &symbols, &edges)
203            .await
204            .map_err(explain)?;
205        crate::index::write_facts(&dst, &facts)
206            .await
207            .map_err(explain)?;
208        crate::index::write_packages(&dst, &packages)
209            .await
210            .map_err(explain)?;
211        crate::index::write_recipes(&dst, &recipes)
212            .await
213            .map_err(explain)?;
214        store_sources(ctx, &dst, roots.clone(), false).await?;
215        r.done(format!(
216            "org graph: symbols v{sv}, edges v{ev} (latest pointer)"
217        ));
218        let (sc, ec) = crate::index::count_rows(&dst)
219            .await
220            .context("read-back failed")?;
221        r.note(format!("read back: {sc} symbols, {ec} edges"));
222
223        let paths: Vec<(String, PathBuf, Option<String>)> = sources
224            .iter()
225            .map(|s| (s.name.clone(), s.path.clone(), s.branch.clone()))
226            .collect();
227        let heads = blocking(move || {
228            paths
229                .into_iter()
230                .filter_map(|(name, p, branch)| {
231                    crate::git::head_commit(&p)
232                        .ok()
233                        .map(|commit| crate::index::IndexedRepo {
234                            name,
235                            commit,
236                            remote: crate::worktree::remote_url(&p),
237                            branch: branch.or_else(|| crate::worktree::current_branch(&p)),
238                        })
239                })
240                .collect::<Vec<_>>()
241        })
242        .await?;
243        let stale: HashSet<String> = if incremental {
244            let stale = stale_ids(&dst, roots.clone(), &symbols).await?;
245            r.note(format!(
246                "incremental: {} of {} symbols stale",
247                stale.len(),
248                symbols.len()
249            ));
250            stale
251        } else {
252            symbols.iter().map(|s| s.id.render()).collect()
253        };
254
255        let symbols = Arc::new(symbols);
256        let edges = Arc::new(edges);
257        enrich_all(ctx, &dst, &symbols, &edges, &stale, incremental, &roots).await?;
258        crate::index::write_repo_commits(&dst, &heads).await?;
259
260        Ok(LinkReport {
261            symbols: symbols.len(),
262            edges: edges.len(),
263            cross_repo_edges: edges.iter().filter(|e| e.cross_repo).count(),
264            dependencies,
265        })
266    })
267}
268
269/// Index one repository into the shared index: the whole repository, or with `incremental` only
270/// the files changed since `since` (or the commit recorded last time).
271pub fn index_repo<'a>(
272    ctx: &'a IndexContext,
273    source: Source,
274    incremental: bool,
275    since: Option<String>,
276    scip: crate::scip::Mode,
277) -> futures::future::BoxFuture<'a, Result<()>> {
278    Box::pin(async move {
279        anyhow::ensure!(
280            source.path.is_dir(),
281            "no such repo directory: {}",
282            source.path.display()
283        );
284        let r = &ctx.report;
285        let dst = ctx.graph();
286        let incremental = incremental || since.is_some();
287        if incremental {
288            let base = match since {
289                Some(s) => Some(s),
290                None => crate::index::read_repo_meta(&dst).await.ok().flatten(),
291            };
292            match base {
293                Some(base) => return index_changes(ctx, &source, &base).await,
294                None => r.note("no recorded base commit — doing a full index"),
295            }
296        }
297
298        r.step(format!("Indexing {}", source.name));
299        let (name, path) = (source.name.clone(), source.path.clone());
300        let (symbols, edges, facts) = blocking(move || -> Result<_> {
301            let mut out = crate::parse::parse_repo(&path, &name)
302                .map_err(|e| anyhow::anyhow!(crate::storage::explain(&format!("{e:#}"))))?;
303            attach_scip(scip, &path, &name, &mut out)?;
304            let resolved = crate::resolve::resolve(&out.symbols, &out.edges, &out.facts);
305            let mut symbols = out.symbols;
306            symbols.extend(resolved.symbols);
307            Ok((symbols, resolved.edges, out.facts))
308        })
309        .await??;
310
311        let mut by_kind: BTreeMap<String, usize> = BTreeMap::new();
312        for s in &symbols {
313            *by_kind.entry(format!("{:?}", s.kind)).or_default() += 1;
314        }
315        let calls = edges.iter().filter(|e| e.kind == EdgeKind::Calls).count();
316        let contains = edges
317            .iter()
318            .filter(|e| e.kind == EdgeKind::Contains)
319            .count();
320        r.note(format!("symbols: {}", symbols.len()));
321        for (k, n) in &by_kind {
322            r.note(format!("{k:<10} {n}"));
323        }
324        r.note(format!(
325            "edges: {} (contains={contains}, calls={calls})",
326            edges.len()
327        ));
328
329        r.step("Persisting");
330        r.note(format!("writing graph to {dst}"));
331        let roots = vec![(source.name.clone(), source.path.clone())];
332        let explain = |e: anyhow::Error| {
333            anyhow::anyhow!(
334                "write failed: {}",
335                crate::storage::explain(&format!("{e:#}"))
336            )
337        };
338        let (sv, ev) = crate::index::write_graph(&dst, &symbols, &edges)
339            .await
340            .map_err(explain)?;
341        crate::index::write_facts(&dst, &facts)
342            .await
343            .map_err(explain)?;
344        // Keep other repositories' package and recipe rows in a shared index.
345        let mut packages: Vec<_> = crate::index::read_packages(&dst)
346            .await
347            .unwrap_or_default()
348            .into_iter()
349            .filter(|p| p.repo != source.name)
350            .collect();
351        packages.extend(scan_packages(ctx, roots.clone()).await?);
352        crate::index::write_packages(&dst, &packages)
353            .await
354            .map_err(explain)?;
355        let mut recipes: Vec<_> = crate::index::read_recipes(&dst)
356            .await
357            .unwrap_or_default()
358            .into_iter()
359            .filter(|c| c.repo != source.name)
360            .collect();
361        recipes.extend(mine_recipes(ctx, roots.clone()).await?);
362        crate::index::write_recipes(&dst, &recipes)
363            .await
364            .map_err(explain)?;
365        store_sources(ctx, &dst, roots.clone(), true).await?;
366        r.done(format!("graph: symbols v{sv}, edges v{ev}"));
367        let p = source.path.clone();
368        if let Ok(head) = blocking(move || crate::git::head_commit(&p)).await? {
369            let _ = crate::index::write_repo_meta(&dst, &source.name, &head).await;
370            r.note(format!("recorded commit {}", short(&head)));
371        }
372
373        let all: HashSet<String> = symbols.iter().map(|s| s.id.render()).collect();
374        enrich_all(
375            ctx,
376            &dst,
377            &Arc::new(symbols),
378            &Arc::new(edges),
379            &all,
380            false,
381            &roots,
382        )
383        .await
384    })
385}
386
387/// Reparse only the files changed since `base`, drop what they owned, re-bind, and rewrite.
388async fn index_changes(ctx: &IndexContext, source: &Source, base: &str) -> Result<()> {
389    let r = &ctx.report;
390    let dst = ctx.graph();
391    let (root, name, base_c) = (source.path.clone(), source.name.clone(), base.to_string());
392    let (head, cs) = blocking(move || -> Result<_> {
393        let explain =
394            |e: anyhow::Error| anyhow::anyhow!(crate::storage::explain(&format!("{e:#}")));
395        let head = crate::git::head_commit(&root).map_err(explain)?;
396        let cs = crate::git::changed_files(&root, &base_c).map_err(explain)?;
397        Ok((head, cs))
398    })
399    .await??;
400    r.step(format!(
401        "Incremental {} → {}: {} changed ({}+ {}~ {}-)",
402        short(base),
403        short(&head),
404        cs.total(),
405        cs.added.len(),
406        cs.modified.len(),
407        cs.deleted.len()
408    ));
409    if cs.total() == 0 {
410        let _ = crate::index::write_repo_meta(&dst, &name, &head).await;
411        r.done("index already up to date");
412        return Ok(());
413    }
414    let (prior_syms, prior_edges) = crate::index::read_graph(&dst)
415        .await
416        .with_context(|| format!("no prior index at {dst}; run a full index first"))?;
417    let prior_facts = crate::index::read_facts(&dst).await.ok().flatten();
418    if prior_facts.is_none() {
419        r.warn("index has no stored facts; run a full index for exact edges");
420    }
421    let root = source.path.clone();
422    let (symbols, edges, facts, before, parsed) = blocking(move || {
423        let dropped: HashSet<String> = cs.to_drop().cloned().collect();
424        let to_parse: Vec<String> = cs.to_parse().cloned().collect();
425        let newout = crate::parse::parse_files(&root, &name, &to_parse);
426        let file_of: HashMap<String, String> = prior_syms
427            .iter()
428            .filter(|s| s.repo.0 == name)
429            .map(|s| (s.id.render(), s.file_path.clone()))
430            .collect();
431        let before = prior_syms.len();
432        let mut symbols: Vec<Symbol> = prior_syms
433            .into_iter()
434            .filter(|s| !(s.repo.0 == name && dropped.contains(&s.file_path)))
435            .collect();
436        let mut edges: Vec<Edge> = prior_edges
437            .into_iter()
438            .filter(|e| {
439                file_of
440                    .get(&e.src.render())
441                    .is_none_or(|f| !dropped.contains(f))
442            })
443            .collect();
444        symbols.extend(newout.symbols);
445        edges.extend(newout.edges);
446        let facts = match prior_facts {
447            Some(prior) => {
448                edges.retain(|e| e.kind == EdgeKind::Contains);
449                let mut all: Vec<_> = prior
450                    .into_iter()
451                    .filter(|f| {
452                        f.repo != name || !(dropped.contains(&f.path) || to_parse.contains(&f.path))
453                    })
454                    .collect();
455                all.extend(newout.facts);
456                all
457            }
458            None => newout.facts,
459        };
460        symbols.retain(|s| s.kind != SymbolKind::Contract);
461        let resolved = crate::resolve::resolve(&symbols, &edges, &facts);
462        symbols.extend(resolved.symbols);
463        (symbols, resolved.edges, facts, before, to_parse.len())
464    })
465    .await?;
466    let explain = |e: anyhow::Error| {
467        anyhow::anyhow!(
468            "write failed: {}",
469            crate::storage::explain(&format!("{e:#}"))
470        )
471    };
472    crate::index::write_graph(&dst, &symbols, &edges)
473        .await
474        .map_err(explain)?;
475    crate::index::write_facts(&dst, &facts)
476        .await
477        .map_err(explain)?;
478    store_sources(
479        ctx,
480        &dst,
481        vec![(source.name.clone(), source.path.clone())],
482        true,
483    )
484    .await?;
485    let _ = crate::index::write_repo_meta(&dst, &source.name, &head).await;
486    r.done(format!(
487        "reparsed {parsed} files → symbols {before}→{}, edges {}",
488        symbols.len(),
489        edges.len()
490    ));
491    Ok(())
492}
493
494/// The optional steps, each only when the settings ask for it; LLM steps need an LLM.
495async fn enrich_all(
496    ctx: &IndexContext,
497    dst: &str,
498    symbols: &Arc<Vec<Symbol>>,
499    edges: &Arc<Vec<Edge>>,
500    stale: &HashSet<String>,
501    incremental: bool,
502    roots: &[(String, PathBuf)],
503) -> Result<()> {
504    let s = &ctx.settings;
505    if s.embed {
506        embed(ctx, dst, symbols, stale, incremental).await?;
507    }
508    let wanted = s.enrich || s.flows || s.guide;
509    let Some(llm) = ctx.llm.clone().filter(|_| wanted) else {
510        if wanted {
511            ctx.report.warn(
512                "summaries, style guides and walkthroughs skipped: no LLM key (set one in the settings, or OPENAI_API_KEY)",
513            );
514        }
515        return Ok(());
516    };
517    let prompts = crate::prompts::load(&ctx.root)
518        .await
519        .context("reading the prompts")?
520        .doc
521        .in_use();
522    ctx.report.note(format!("prompts: {}", prompts.describe()));
523    for t in &s.rewrite {
524        ctx.report.warn(format!(
525            "rewriting every {} result, as asked; nothing stored is reused",
526            t.name()
527        ));
528    }
529    if s.enrich {
530        summaries(ctx, &llm, &prompts, dst, symbols, edges, incremental, roots).await?;
531    }
532    if s.guide {
533        style_guides(ctx, &llm, &prompts, dst, symbols, edges, roots).await?;
534    }
535    if s.flows {
536        walkthroughs(ctx, &llm, &prompts, dst, symbols, edges, roots).await?;
537    }
538    Ok(())
539}
540
541/// Search embeddings, reusing the stored vector of every symbol whose code did not change.
542async fn embed(
543    ctx: &IndexContext,
544    dst: &str,
545    symbols: &Arc<Vec<Symbol>>,
546    stale: &HashSet<String>,
547    incremental: bool,
548) -> Result<()> {
549    ctx.check()?;
550    let prior: HashMap<String, Vec<f32>> = if incremental {
551        crate::index::read_search_vectors(dst)
552            .await
553            .ok()
554            .flatten()
555            .unwrap_or_default()
556            .into_iter()
557            .map(|(id, v)| (id.render(), v))
558            .collect()
559    } else {
560        HashMap::new()
561    };
562    ctx.report.step("Building search index");
563    let (model, syms, stale) = (
564        ctx.settings.embed_model.clone(),
565        symbols.clone(),
566        stale.clone(),
567    );
568    let (rows, reused, embedded) = blocking(move || -> Result<_> {
569        let embedder = crate::embed::Embedder::load(&model).context("embedding model")?;
570        let mut rows: Vec<(GlobalSymbolId, String, Vec<f32>)> = Vec::new();
571        let mut to_embed: Vec<&Symbol> = Vec::new();
572        for s in syms.iter().filter(|s| !matches!(s.kind, SymbolKind::File)) {
573            match prior
574                .get(&s.id.render())
575                .filter(|_| !stale.contains(&s.id.render()))
576            {
577                Some(v) => rows.push((s.id.clone(), crate::embed::symbol_text(s), v.clone())),
578                None => to_embed.push(s),
579            }
580        }
581        let reused = rows.len();
582        let texts: Vec<String> = to_embed
583            .iter()
584            .map(|s| crate::embed::symbol_text(s))
585            .collect();
586        for (s, v) in to_embed.iter().zip(embedder.embed(&texts)) {
587            rows.push((s.id.clone(), crate::embed::symbol_text(s), v));
588        }
589        Ok((rows, reused, to_embed.len()))
590    })
591    .await??;
592    ctx.report.note(format!(
593        "embedding {embedded} symbols + building BM25 index"
594    ));
595    let v = crate::index::write_search_table(dst, &rows)
596        .await
597        .context("write search table failed")?;
598    ctx.report.done(format!(
599        "search index v{v}: {} symbols ({reused} reused, {embedded} embedded) + BM25 FTS index",
600        rows.len()
601    ));
602    Ok(())
603}
604
605/// Summaries of the most-used definitions, saved every `CHECKPOINT` and reused while unchanged.
606#[allow(clippy::too_many_arguments)]
607async fn summaries(
608    ctx: &IndexContext,
609    llm: &Arc<crate::llm::LlmClient>,
610    prompts: &Prompts,
611    dst: &str,
612    symbols: &Arc<Vec<Symbol>>,
613    edges: &Arc<Vec<Edge>>,
614    incremental: bool,
615    roots: &[(String, PathBuf)],
616) -> Result<()> {
617    const CHECKPOINT: usize = 500;
618    let r = &ctx.report;
619    r.step("Enriching symbols (LLM)");
620    let (syms, edgs, top) = (symbols.clone(), edges.clone(), ctx.settings.max_enrich);
621    let roots = roots.to_vec();
622    let defs: Vec<(Symbol, String)> = blocking(move || {
623        let g = crate::graph::CodeGraph::build(&syms, &edgs);
624        let mut defs: Vec<&Symbol> = syms
625            .iter()
626            .filter(|s| {
627                matches!(
628                    s.kind,
629                    SymbolKind::Function
630                        | SymbolKind::Method
631                        | SymbolKind::Class
632                        | SymbolKind::Interface
633                        | SymbolKind::Struct
634                        | SymbolKind::Enum
635                )
636            })
637            .collect();
638        // Most-used first, ties by id, so a limit always picks the same symbols.
639        defs.sort_by_cached_key(|s| {
640            let id = s.id.render();
641            (std::cmp::Reverse(g.dependents_count(&id)), id)
642        });
643        let (n, mut sources) = (
644            crate::brief::Neighbours::new(&syms, &edgs),
645            crate::brief::Sources::new(&roots),
646        );
647        defs.into_iter()
648            .take(top)
649            .map(|s| (s.clone(), crate::brief::symbol(s, &n, &mut sources)))
650            .collect()
651    })
652    .await?;
653    let prior: HashMap<String, (String, Vec<String>)> = if incremental {
654        crate::index::read_enrichment(dst)
655            .await
656            .ok()
657            .flatten()
658            .unwrap_or_default()
659            .into_iter()
660            .map(|(id, s, q)| (id.render(), (s, q)))
661            .collect()
662    } else {
663        HashMap::new()
664    };
665    // A summary stays valid while the symbol's name, signature, place and body do.
666    let key = |s: &Symbol| {
667        fingerprint([
668            s.name.clone(),
669            s.signature.clone().unwrap_or_default(),
670            s.file_path.clone(),
671            s.fingerprint
672                .map(|f| f.body.to_string())
673                .unwrap_or_default(),
674        ])
675    };
676    let stored_keys = read_keys(dst, "enrich_keys").await;
677    let mut rows: Vec<TextRow> = Vec::new();
678    let mut keys: Vec<(String, String)> = Vec::new();
679    let mut todo: Vec<&(Symbol, String)> = Vec::new();
680    for d @ (s, _) in &defs {
681        let (rid, k) = (s.id.render(), key(s));
682        let valid = !ctx.settings.rewrite.contains(&Task::Summary)
683            && stored_keys.get(&rid).is_some_and(|old| *old == k);
684        match prior.get(&rid).filter(|_| valid) {
685            Some((sum, q)) => {
686                rows.push((s.id.clone(), sum.clone(), q.clone()));
687                keys.push((rid, k));
688            }
689            None => todo.push(d),
690        }
691    }
692    let reused = rows.len();
693    if !todo.is_empty() {
694        r.warn("Summaries send each symbol's code, signature and neighbours to the LLM.");
695        r.note(format!(
696            "{} symbols to summarise ({reused} reused)",
697            todo.len()
698        ));
699    }
700    let total = todo.len() as u64;
701    let mut done = 0u64;
702    let mut generated = 0usize;
703    for chunk in todo.chunks(CHECKPOINT) {
704        let out = run_llm(
705            ctx,
706            chunk.iter().map(|(_, brief)| brief.clone()).collect(),
707            |brief| {
708                let (llm, prompts) = (llm.clone(), prompts.clone());
709                async move { llm.enrich_symbol(&prompts, &brief).await.ok() }
710            },
711            |d| {
712                done += 1;
713                let _ = d;
714                r.progress("enriching symbols", done, total, Some(usage(ctx, llm)));
715            },
716        )
717        .await;
718        let cancelled = out.is_err();
719        for ((s, _), e) in chunk.iter().zip(out.unwrap_or_else(|v| v)) {
720            if let Some(e) = e {
721                rows.push((s.id.clone(), e.summary, e.queries));
722                keys.push((s.id.render(), key(s)));
723                generated += 1;
724            }
725        }
726        if cancelled || chunk.len() == CHECKPOINT {
727            crate::index::write_enrichment(dst, &rows)
728                .await
729                .context("saving summaries")?;
730            write_keys(dst, "enrich_keys", &keys)
731                .await
732                .context("saving summaries")?;
733        }
734        if cancelled {
735            return Err(Cancelled.into());
736        }
737    }
738    if total > 0 {
739        r.note(format!("spent: {}", usage(ctx, llm)));
740    }
741    let failed = todo.len().saturating_sub(generated);
742    let v = crate::index::write_enrichment(dst, &rows)
743        .await
744        .context("write enrichment failed")?;
745    write_keys(dst, "enrich_keys", &keys)
746        .await
747        .context("write enrichment failed")?;
748    r.done(format!(
749        "enrichment v{v}: {} symbols ({reused} reused, {generated} generated{})",
750        rows.len(),
751        if failed > 0 {
752            format!(", {failed} failed")
753        } else {
754            String::new()
755        }
756    ));
757    Ok(())
758}
759
760/// One LLM call per item, `concurrency` at a time; `Err` when cancelled, with the calls that
761/// finished before the cancellation in their positions.
762async fn run_llm<I, T, F, Fut>(
763    ctx: &IndexContext,
764    items: Vec<I>,
765    call: F,
766    mut each: impl FnMut(&Option<T>),
767) -> std::result::Result<Vec<Option<T>>, Vec<Option<T>>>
768where
769    F: Fn(I) -> Fut,
770    Fut: std::future::Future<Output = Option<T>> + Send + 'static,
771    T: Send + 'static,
772{
773    let mut out = Vec::with_capacity(items.len());
774    let mut stream =
775        futures::stream::iter(items.into_iter().map(call)).buffered(ctx.settings.llm_concurrency);
776    loop {
777        tokio::select! {
778            _ = ctx.cancel.cancelled() => return Err(out),
779            next = stream.next() => match next {
780                Some(r) => { each(&r); out.push(r); }
781                None => return Ok(out),
782            },
783        }
784    }
785}
786
787fn usage(ctx: &IndexContext, llm: &crate::llm::LlmClient) -> Usage {
788    let (i, o) = llm.token_usage();
789    Usage::priced(i, o, ctx.settings.prices)
790}
791
792/// A style guide per repository; a section is written again only when its evidence drifted.
793async fn style_guides(
794    ctx: &IndexContext,
795    llm: &Arc<crate::llm::LlmClient>,
796    prompts: &Prompts,
797    dst: &str,
798    symbols: &Arc<Vec<Symbol>>,
799    edges: &Arc<Vec<Edge>>,
800    roots: &[(String, PathBuf)],
801) -> Result<()> {
802    let r = &ctx.report;
803    r.step("Style guides (per repo)");
804    r.warn("Style guides send code samples and configuration to the LLM.");
805    let facts = crate::index::read_facts(dst).await.ok().flatten();
806    let stored_keys = read_keys(dst, "guide_keys").await;
807    let mut guides: Vec<(String, String)> = crate::index::read_style_guide(dst)
808        .await
809        .unwrap_or_default();
810    let mut keys: Vec<(String, String)> = stored_keys.clone().into_iter().collect();
811    let before = guides.len();
812    guides.retain(|(g, _)| roots.iter().any(|(r, _)| r == g));
813    keys.retain(|(g, _)| roots.iter().any(|(r, _)| r == g));
814    if guides.len() < before {
815        crate::index::write_style_guide(dst, &guides)
816            .await
817            .context("saving the style guide")?;
818        write_keys(dst, "guide_keys", &keys)
819            .await
820            .context("saving the style guide")?;
821        r.note(format!(
822            "{} style guide(s) of removed repositories dropped",
823            before - guides.len()
824        ));
825    }
826    let mut reused = 0usize;
827    let (syms, edgs, roots_owned) = (symbols.clone(), edges.clone(), roots.to_vec());
828    let guide_prompts = prompts.clone();
829    let per_repo = blocking(move || {
830        let conventions = match facts {
831            Some(f) => crate::conventions::mine(&syms, &edgs, &f),
832            None => Vec::new(),
833        };
834        roots_owned
835            .into_iter()
836            .filter_map(|(repo, root)| {
837                let rsyms: Vec<&Symbol> = syms.iter().filter(|s| s.id.package == repo).collect();
838                if rsyms.is_empty() {
839                    return None;
840                }
841                let redges: Vec<Edge> = edgs
842                    .iter()
843                    .filter(|e| e.src.package == repo)
844                    .cloned()
845                    .collect();
846                let rconv: Vec<_> = conventions
847                    .iter()
848                    .filter(|c| c.repo == repo)
849                    .cloned()
850                    .collect();
851                let mut sections =
852                    crate::styleguide::build_sections(&root, &rsyms, &redges, &rconv);
853                for sec in &mut sections {
854                    if let Some(g) = guide_prompts.guidance(&sec.title) {
855                        sec.guidance = g.to_string();
856                    }
857                }
858                (!sections.is_empty()).then_some((repo, sections))
859            })
860            .collect::<Vec<_>>()
861    })
862    .await?;
863    let mut bodies: HashMap<String, String> = read_keys(dst, "guide_sections").await;
864    let mut basis: HashMap<String, String> = read_keys(dst, "guide_basis").await;
865    let mut redone = 0usize;
866    for (repo, sections) in per_repo {
867        ctx.check()?;
868        let key = fingerprint(
869            sections
870                .iter()
871                .map(|s| format!("{}\0{}\0{}", s.title, s.guidance, s.evidence)),
872        );
873        let sid = |title: &str| format!("{repo}\0{title}");
874        let old_doc = guides
875            .iter()
876            .find(|(g, _)| *g == repo)
877            .map(|(_, d)| d.clone());
878        let rewrite = ctx.settings.rewrite.contains(&Task::Guide);
879        // Guides written before sections were stored: adopt the current one as the baseline.
880        if let Some(doc) = old_doc
881            .as_ref()
882            .filter(|_| !rewrite && stored_keys.get(&repo) == Some(&key))
883        {
884            for sec in &sections {
885                let id = sid(&sec.title);
886                if !bodies.contains_key(&id) {
887                    bodies.insert(id.clone(), guide_section_of(doc, &sec.title));
888                    basis.insert(id, guide_basis(sec));
889                }
890            }
891            reused += 1;
892            continue;
893        }
894        let todo: Vec<&crate::styleguide::Section> = sections
895            .iter()
896            .filter(|sec| {
897                let id = sid(&sec.title);
898                rewrite
899                    || !(bodies.contains_key(&id)
900                        && basis
901                            .get(&id)
902                            .is_some_and(|b| guide_similar(b, &guide_basis(sec))))
903            })
904            .collect();
905        let total = todo.len() as u64;
906        let mut done = 0u64;
907        let out = run_llm(
908            ctx,
909            todo.iter()
910                .map(|sec| {
911                    (
912                        sec.title.clone(),
913                        sec.guidance.clone(),
914                        sec.evidence.clone(),
915                    )
916                })
917                .collect(),
918            |(title, guidance, evidence)| {
919                let (llm, prompts, repo) = (llm.clone(), prompts.clone(), repo.clone());
920                async move {
921                    llm.guide_section(&prompts, &repo, &title, &guidance, &evidence)
922                        .await
923                        .ok()
924                        .map(|b| b.unwrap_or_else(|| NO_CONVENTION.to_string()))
925                }
926            },
927            |_| {
928                done += 1;
929                r.progress(
930                    &format!("{repo}: guide sections"),
931                    done,
932                    total,
933                    Some(usage(ctx, llm)),
934                );
935            },
936        )
937        .await
938        .map_err(|_| Cancelled)?;
939        for (sec, body) in todo.iter().zip(out) {
940            if let Some(body) = body {
941                let id = sid(&sec.title);
942                bodies.insert(id.clone(), body.trim().to_string());
943                basis.insert(id, guide_basis(sec));
944                redone += 1;
945            }
946        }
947        let mut doc = String::new();
948        for sec in &sections {
949            let t = bodies.get(&sid(&sec.title)).map(|b| b.trim()).unwrap_or("");
950            if t.is_empty() || t.eq_ignore_ascii_case(NO_CONVENTION) {
951                continue;
952            }
953            doc.push_str(&format!("## {}\n\n{}\n\n", sec.title, t));
954        }
955        if doc.is_empty() {
956            r.warn(format!("{repo}: no sections generated"));
957            continue;
958        }
959        doc.push_str("\n_AI-generated from the codebase; review before enforcing._\n");
960        r.done(format!(
961            "{repo}: style guide ({} sections, {} rewritten)",
962            doc.matches("\n## ").count() + 1,
963            todo.len()
964        ));
965        guides.retain(|(g, _)| *g != repo);
966        guides.push((repo.clone(), doc));
967        keys.retain(|(g, _)| *g != repo);
968        keys.push((repo, key));
969        crate::index::write_style_guide(dst, &guides)
970            .await
971            .context("saving the style guide")?;
972        write_keys(dst, "guide_keys", &keys)
973            .await
974            .context("saving the style guide")?;
975        save_guide_sections(dst, &bodies, &basis, roots).await?;
976    }
977    save_guide_sections(dst, &bodies, &basis, roots).await?;
978    if redone > 0 {
979        r.note(format!("{redone} style guide section(s) rewritten"));
980    }
981    if reused > 0 {
982        r.note(format!("{reused} unchanged style guide(s) reused"));
983    }
984    r.note(format!("spent: {}", usage(ctx, llm)));
985    Ok(())
986}
987
988/// Sections of indexed repositories only, so a removed repository's text goes too.
989async fn save_guide_sections(
990    dst: &str,
991    bodies: &HashMap<String, String>,
992    basis: &HashMap<String, String>,
993    roots: &[(String, PathBuf)],
994) -> Result<()> {
995    let keep = |id: &String| {
996        roots
997            .iter()
998            .any(|(r, _)| id.split('\0').next() == Some(r.as_str()))
999    };
1000    let pick = |m: &HashMap<String, String>| -> Vec<(String, String)> {
1001        m.iter()
1002            .filter(|(id, _)| keep(id))
1003            .map(|(a, b)| (a.clone(), b.clone()))
1004            .collect()
1005    };
1006    write_keys(dst, "guide_sections", &pick(bodies))
1007        .await
1008        .context("saving the style guide")?;
1009    write_keys(dst, "guide_basis", &pick(basis))
1010        .await
1011        .context("saving the style guide")?;
1012    Ok(())
1013}
1014
1015/// A section's body in a guide document, or empty.
1016fn guide_section_of(doc: &str, title: &str) -> String {
1017    let head = format!("## {title}\n");
1018    let Some(i) = doc.find(&head) else {
1019        return String::new();
1020    };
1021    let rest = &doc[i + head.len()..];
1022    let end = rest
1023        .find("\n## ")
1024        .or_else(|| rest.find("\n_AI-generated"))
1025        .unwrap_or(rest.len());
1026    rest[..end].trim().to_string()
1027}
1028
1029/// What a section is written from, with counts dropped and percentages rounded to tens, so
1030/// ordinary churn does not count as a change.
1031fn guide_basis(sec: &crate::styleguide::Section) -> String {
1032    let mut out = fingerprint([sec.title.clone(), sec.guidance.clone()]);
1033    for line in sec.evidence.lines() {
1034        let line = line.trim();
1035        if line.is_empty() {
1036            continue;
1037        }
1038        out.push('\n');
1039        let mut num = String::new();
1040        let mut chars = line.chars().peekable();
1041        while let Some(c) = chars.next() {
1042            if c.is_ascii_digit() || (c == '.' && !num.is_empty()) {
1043                num.push(c);
1044                if chars
1045                    .peek()
1046                    .is_some_and(|n| n.is_ascii_digit() || *n == '.')
1047                {
1048                    continue;
1049                }
1050                if chars.peek() == Some(&'%') {
1051                    let p: f64 = num.trim_end_matches('.').parse().unwrap_or(0.0);
1052                    out.push_str(&format!("{}", (p / 10.0).round() as u32 * 10));
1053                } else {
1054                    out.push('#');
1055                }
1056                num.clear();
1057            } else {
1058                out.push(c);
1059            }
1060        }
1061    }
1062    out
1063}
1064
1065/// Same guidance, the same measured ratios (to the nearest ten), and at most a fifth of the other
1066/// evidence lines differ.
1067fn guide_similar(a: &str, b: &str) -> bool {
1068    const MIN_SHARED: f64 = 0.8;
1069    let split = |t: &str| -> (Option<String>, HashSet<String>, HashSet<String>) {
1070        let mut l = t.lines();
1071        let head = l.next().map(str::to_string);
1072        let (measured, other): (Vec<&str>, Vec<&str>) = l.partition(|x| x.contains('%'));
1073        (
1074            head,
1075            measured.into_iter().map(str::to_string).collect(),
1076            other.into_iter().map(str::to_string).collect(),
1077        )
1078    };
1079    let ((ha, ma, oa), (hb, mb, ob)) = (split(a), split(b));
1080    if ha != hb || ma != mb {
1081        return false;
1082    }
1083    let union = oa.union(&ob).count();
1084    union == 0 || oa.intersection(&ob).count() as f64 / union as f64 >= MIN_SHARED
1085}
1086
1087/// Walkthroughs of the flows reaching furthest, reused while their trace is unchanged and saved
1088/// every `CHECKPOINT`.
1089async fn walkthroughs(
1090    ctx: &IndexContext,
1091    llm: &Arc<crate::llm::LlmClient>,
1092    prompts: &Prompts,
1093    dst: &str,
1094    symbols: &Arc<Vec<Symbol>>,
1095    edges: &Arc<Vec<Edge>>,
1096    roots: &[(String, PathBuf)],
1097) -> Result<()> {
1098    const CHECKPOINT: usize = 25;
1099    let r = &ctx.report;
1100    r.step("Narrating flows (LLM)");
1101    let (syms, edgs, top) = (symbols.clone(), edges.clone(), ctx.settings.max_flows);
1102    // Each step's summary, written just before, tells the walkthrough what the step does.
1103    let summaries: HashMap<String, String> = crate::index::read_enrichment(dst)
1104        .await
1105        .ok()
1106        .flatten()
1107        .unwrap_or_default()
1108        .into_iter()
1109        .map(|(id, s, _)| (id.render(), s))
1110        .collect();
1111    let roots = roots.to_vec();
1112    let prep: Vec<(GlobalSymbolId, String, String, String)> = blocking(move || {
1113        let g = crate::graph::CodeGraph::build(&syms, &edgs);
1114        let by_id: HashMap<String, &Symbol> = syms.iter().map(|s| (s.id.render(), s)).collect();
1115        let mut sources = crate::brief::Sources::new(&roots);
1116        g.entry_points(top)
1117            .into_iter()
1118            .filter_map(|(idx, _)| {
1119                let s = by_id.get(&g.node(idx).id)?;
1120                let trace = crate::brief::trace(&g.flow(idx, 6), &summaries);
1121                let trace = crate::brief::flow(trace, s, &mut sources);
1122                Some((
1123                    s.id.clone(),
1124                    s.name.clone(),
1125                    s.signature.clone().unwrap_or_default(),
1126                    trace,
1127                ))
1128            })
1129            .collect()
1130    })
1131    .await?;
1132    if prep.is_empty() {
1133        r.note("flows: no multi-step flows found to narrate");
1134        return Ok(());
1135    }
1136    r.warn("Walkthroughs send call traces, step summaries and the entry point's code to the LLM.");
1137    let key = |name: &str, sig: &str, trace: &str| fingerprint([format!("{name}\0{sig}\0{trace}")]);
1138    let stored_keys = read_keys(dst, "flow_keys").await;
1139    let stored: HashMap<String, (String, Vec<String>)> = crate::index::read_flows(dst)
1140        .await
1141        .ok()
1142        .flatten()
1143        .unwrap_or_default()
1144        .into_iter()
1145        .map(|(id, n, q)| (id.render(), (n, q)))
1146        .collect();
1147    let mut rows: Vec<TextRow> = Vec::new();
1148    let mut keys: Vec<(String, String)> = Vec::new();
1149    let mut todo = Vec::new();
1150    for p @ (id, name, sig, trace) in &prep {
1151        let (rid, k) = (id.render(), key(name, sig, trace));
1152        match stored
1153            .get(&rid)
1154            .filter(|_| !ctx.settings.rewrite.contains(&Task::Flow))
1155            .filter(|_| stored_keys.get(&rid) == Some(&k))
1156        {
1157            Some((n, q)) => {
1158                rows.push((id.clone(), n.clone(), q.clone()));
1159                keys.push((rid, k));
1160            }
1161            None => todo.push(p),
1162        }
1163    }
1164    let reused = rows.len();
1165    r.note(format!(
1166        "{} flows to walk through ({reused} reused)",
1167        todo.len()
1168    ));
1169    let total = todo.len() as u64;
1170    let mut done = 0u64;
1171    for chunk in todo.chunks(CHECKPOINT) {
1172        let out = run_llm(
1173            ctx,
1174            chunk
1175                .iter()
1176                .map(|(_, name, sig, trace)| (name.clone(), sig.clone(), trace.clone()))
1177                .collect(),
1178            |(name, sig, trace)| {
1179                let (llm, prompts) = (llm.clone(), prompts.clone());
1180                async move { llm.narrate_flow(&prompts, &name, &sig, &trace).await.ok() }
1181            },
1182            |_| {
1183                done += 1;
1184                r.progress("narrating flows", done, total, Some(usage(ctx, llm)));
1185            },
1186        )
1187        .await;
1188        let cancelled = out.is_err();
1189        for ((id, name, sig, trace), res) in chunk.iter().zip(out.unwrap_or_else(|v| v)) {
1190            if let Some((narr, q)) = res {
1191                keys.push((id.render(), key(name, sig, trace)));
1192                rows.push((id.clone(), narr, q));
1193            }
1194        }
1195        if cancelled || chunk.len() == CHECKPOINT {
1196            crate::index::write_flows(dst, &rows)
1197                .await
1198                .context("saving walkthroughs")?;
1199            write_keys(dst, "flow_keys", &keys)
1200                .await
1201                .context("saving walkthroughs")?;
1202        }
1203        if cancelled {
1204            return Err(Cancelled.into());
1205        }
1206    }
1207    r.note(format!("spent: {}", usage(ctx, llm)));
1208    let v = crate::index::write_flows(dst, &rows)
1209        .await
1210        .context("write flows failed")?;
1211    write_keys(dst, "flow_keys", &keys)
1212        .await
1213        .context("write flows failed")?;
1214    r.done(format!(
1215        "flows v{v}: {} narrated ({reused} reused, {} written)",
1216        rows.len(),
1217        rows.len() - reused
1218    ));
1219    if let Some((_, narr, _)) = rows.first() {
1220        r.note(format!(
1221            "e.g. {}",
1222            narr.chars().take(120).collect::<String>()
1223        ));
1224    }
1225    Ok(())
1226}
1227
1228/// A guide section's body when its evidence shows no consistent convention.
1229const NO_CONVENTION: &str = "No consistent convention observed.";
1230
1231fn fingerprint(parts: impl IntoIterator<Item = String>) -> String {
1232    let mut h = blake3::Hasher::new();
1233    for p in parts {
1234        h.update(p.as_bytes());
1235        h.update(b"\0\0");
1236    }
1237    h.finalize().to_hex().to_string()
1238}
1239
1240async fn read_keys(dst: &str, table: &str) -> HashMap<String, String> {
1241    crate::index::read_keys(dst, table)
1242        .await
1243        .unwrap_or_default()
1244}
1245
1246async fn write_keys(dst: &str, table: &str, keys: &[(String, String)]) -> Result<u64> {
1247    crate::index::write_keys(dst, table, keys).await
1248}
1249
1250/// Symbols whose repository changed files since the commits recorded last time.
1251async fn stale_ids(
1252    dst: &str,
1253    roots: Vec<(String, PathBuf)>,
1254    symbols: &[Symbol],
1255) -> Result<HashSet<String>> {
1256    let prior = crate::index::read_repo_commits(dst)
1257        .await
1258        .unwrap_or_default();
1259    let changed = blocking(move || {
1260        roots
1261            .into_iter()
1262            .map(|(name, p)| {
1263                let set = match (prior.get(&name), crate::git::head_commit(&p)) {
1264                    (Some(base), Ok(_)) => crate::git::changed_files(&p, base).ok().map(|cs| {
1265                        cs.added
1266                            .into_iter()
1267                            .chain(cs.modified)
1268                            .collect::<HashSet<_>>()
1269                    }),
1270                    _ => None,
1271                };
1272                (name, set)
1273            })
1274            .collect::<HashMap<_, _>>()
1275    })
1276    .await?;
1277    Ok(stale_of(&changed, symbols))
1278}
1279
1280/// Symbols in files that changed, by repository; a repository without a known base is all stale.
1281/// Symbols of no indexed repository (contracts) are never stale: new ones have no stored vector anyway.
1282fn stale_of(
1283    changed: &HashMap<String, Option<HashSet<String>>>,
1284    symbols: &[Symbol],
1285) -> HashSet<String> {
1286    symbols
1287        .iter()
1288        .filter(|s| match changed.get(&s.repo.0) {
1289            Some(Some(files)) => files.contains(&s.file_path),
1290            Some(None) => true,
1291            None => false,
1292        })
1293        .map(|s| s.id.render())
1294        .collect()
1295}
1296
1297/// Manifests and lockfiles of each repository.
1298async fn scan_packages(
1299    ctx: &IndexContext,
1300    roots: Vec<(String, PathBuf)>,
1301) -> Result<Vec<crate::manifests::PackageRow>> {
1302    let rows = blocking(move || {
1303        roots
1304            .iter()
1305            .flat_map(|(name, root)| crate::manifests::scan(root, name))
1306            .collect::<Vec<_>>()
1307    })
1308    .await?;
1309    let deps = crate::manifests::internal(&rows);
1310    if !deps.is_empty() {
1311        let skewed = deps.iter().filter(|d| d.skewed()).count();
1312        ctx.report.done(format!(
1313            "internal packages: {} dependency link(s), {skewed} pinned to a different version than their publisher",
1314            deps.len()
1315        ));
1316    }
1317    Ok(rows)
1318}
1319
1320/// Store the indexed files' contents, so code is shown from the index rather than a checkout.
1321async fn store_sources(
1322    ctx: &IndexContext,
1323    dst: &str,
1324    roots: Vec<(String, PathBuf)>,
1325    merge: bool,
1326) -> Result<()> {
1327    let files = blocking(move || {
1328        roots
1329            .iter()
1330            .map(|(name, root)| crate::sources::collect(name, root))
1331            .collect::<Result<Vec<_>>>()
1332    })
1333    .await??
1334    .concat();
1335    let (n, new) = crate::index::write_sources(dst, &files, merge)
1336        .await
1337        .map_err(|e| anyhow::anyhow!(crate::storage::explain(&format!("{e:#}"))))?;
1338    ctx.report
1339        .done(format!("file contents: {n} files ({new} new or changed)"));
1340    Ok(())
1341}
1342
1343/// Change recipes from each repository's recent history.
1344async fn mine_recipes(
1345    ctx: &IndexContext,
1346    roots: Vec<(String, PathBuf)>,
1347) -> Result<Vec<crate::conventions::Convention>> {
1348    let out = blocking(move || {
1349        roots
1350            .iter()
1351            .filter_map(|(name, root)| {
1352                crate::git::history(root, 500)
1353                    .ok()
1354                    .map(|h| crate::recipes::mine(name, &h))
1355            })
1356            .flatten()
1357            .collect::<Vec<_>>()
1358    })
1359    .await?;
1360    if !out.is_empty() {
1361        ctx.report
1362            .done(format!("recipes: {} from commit history", out.len()));
1363    }
1364    Ok(out)
1365}
1366
1367/// Attach SCIP to one parsed repository; a note when indexes were found.
1368fn attach_scip(
1369    mode: crate::scip::Mode,
1370    root: &Path,
1371    name: &str,
1372    out: &mut crate::parse::ParseOutput,
1373) -> Result<Option<String>> {
1374    let a = crate::scip::ingest(mode, root, name, &out.symbols, &mut out.facts)?;
1375    Ok((a.documents > 0).then(|| {
1376        format!(
1377            "{name}: SCIP {} index(es), {} files, {} defs, {} refs",
1378            a.indexes, a.documents, a.definitions, a.references
1379        )
1380    }))
1381}
1382
1383fn report_resolution(ctx: &IndexContext, resolved: &crate::resolve::Resolved) {
1384    let r = &ctx.report;
1385    if !resolved.symbols.is_empty() {
1386        let mut by_type: BTreeMap<&str, usize> = BTreeMap::new();
1387        for c in &resolved.symbols {
1388            *by_type
1389                .entry(c.name.split(':').next().unwrap_or_default())
1390                .or_default() += 1;
1391        }
1392        let parts: Vec<String> = by_type.iter().map(|(t, n)| format!("{t} {n}")).collect();
1393        r.done(format!(
1394            "contracts: {} ({}), {} participant edges",
1395            resolved.symbols.len(),
1396            parts.join(", "),
1397            resolved.stats.contract_edges
1398        ));
1399    }
1400    let s = &resolved.stats;
1401    r.done(format!(
1402        "resolved: {} imports, {} calls, {} inherits/implements; {} cross-repo edges{}",
1403        s.resolved_imports,
1404        s.resolved_calls,
1405        s.type_edges,
1406        s.cross_repo_edges,
1407        if s.scip_answers > 0 {
1408            format!(" ({} answered by SCIP)", s.scip_answers)
1409        } else {
1410            String::new()
1411        }
1412    ));
1413    r.note(format!(
1414        "unresolved: {} imports, {} calls (mostly third-party or dynamic)",
1415        s.unresolved_imports, s.unresolved_calls
1416    ));
1417    let mut top: Vec<_> = resolved.unresolved_modules.iter().collect();
1418    top.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
1419    let top: Vec<String> = top
1420        .iter()
1421        .take(12)
1422        .map(|(m, n)| format!("{m} {n}"))
1423        .collect();
1424    if !top.is_empty() {
1425        r.note(format!("top unresolved: {}", top.join(", ")));
1426    }
1427}
1428
1429/// Cross-repository import targets, most depended-on first.
1430fn dependencies(edges: &[Edge]) -> Vec<Dependency> {
1431    let mut targets: BTreeMap<String, (String, BTreeSet<String>, usize)> = BTreeMap::new();
1432    for e in edges
1433        .iter()
1434        .filter(|e| e.kind == EdgeKind::Imports && e.cross_repo)
1435    {
1436        let t = targets
1437            .entry(e.dst.descriptor.clone())
1438            .or_insert_with(|| (e.dst.package.clone(), BTreeSet::new(), 0));
1439        t.1.insert(e.src.package.clone());
1440        t.2 += 1;
1441    }
1442    let mut out: Vec<Dependency> = targets
1443        .into_iter()
1444        .map(|(descriptor, (defined_in, repos, refs))| Dependency {
1445            descriptor,
1446            defined_in,
1447            repos,
1448            refs,
1449        })
1450        .collect();
1451    out.sort_by(|a, b| b.repos.len().cmp(&a.repos.len()).then(b.refs.cmp(&a.refs)));
1452    out
1453}
1454
1455fn short(sha: &str) -> String {
1456    sha.chars().take(8).collect()
1457}
1458
1459#[cfg(test)]
1460mod tests {
1461    use super::*;
1462    use crate::styleguide::Section;
1463
1464    fn at(repo: &str, file: &str, name: &str) -> Symbol {
1465        use crate::model::{GlobalSymbolId, Language, Position, Range, RepoId};
1466        Symbol {
1467            id: GlobalSymbolId {
1468                scheme: "t".into(),
1469                package_manager: ".".into(),
1470                package: repo.into(),
1471                version: ".".into(),
1472                descriptor: format!("{file}/{name}"),
1473            },
1474            name: name.into(),
1475            kind: SymbolKind::Function,
1476            language: Language::Python,
1477            repo: RepoId(repo.into()),
1478            file_path: file.into(),
1479            range: Range {
1480                start: Position { line: 1, column: 0 },
1481                end: Position { line: 2, column: 0 },
1482            },
1483            signature: None,
1484            docstring: None,
1485            fingerprint: None,
1486        }
1487    }
1488
1489    #[test]
1490    fn only_changed_files_are_stale_and_contracts_never() {
1491        let changed: HashMap<String, Option<HashSet<String>>> = [
1492            (
1493                "orders".to_string(),
1494                Some(HashSet::from(["a.py".to_string()])),
1495            ),
1496            ("billing".to_string(), None),
1497        ]
1498        .into();
1499        let symbols = [
1500            at("orders", "a.py", "edited"),
1501            at("orders", "b.py", "untouched"),
1502            at("billing", "c.py", "no_base"),
1503            at(crate::resolve::CONTRACTS, "", "http:GET /orders"),
1504        ];
1505        let mut stale: Vec<String> = stale_of(&changed, &symbols).into_iter().collect();
1506        stale.sort();
1507        assert_eq!(stale, vec![symbols[2].id.render(), symbols[0].id.render()]);
1508    }
1509
1510    fn sec(evidence: &str) -> Section {
1511        Section {
1512            title: "Naming".into(),
1513            guidance: "State the casing".into(),
1514            evidence: evidence.into(),
1515        }
1516    }
1517
1518    #[test]
1519    fn guide_sections_ignore_churn_but_not_drift() {
1520        let lines: Vec<String> = (0..10)
1521            .map(|i| format!("def handler_{}(x): pass", (b'a' + i) as char))
1522            .collect();
1523        let base = format!("snake_case 97.3% (1234/1268)\n{}", lines.join("\n"));
1524        let a = guide_basis(&sec(&base));
1525        let counts = guide_basis(&sec(&base.replace("97.3% (1234/1268)", "96.8% (1301/1340)")));
1526        assert!(guide_similar(&a, &counts), "counts moving is churn");
1527        let shifted = guide_basis(&sec(&base.replace("97.3%", "61.0%")));
1528        assert!(
1529            !guide_similar(&a, &shifted),
1530            "a measured ratio moving rewrites"
1531        );
1532        let one = guide_basis(&sec(&base.replacen("handler_a", "handle_a", 1)));
1533        assert!(guide_similar(&a, &one), "one changed excerpt line is churn");
1534        let many = guide_basis(&sec(&base.replace("handler_", "Handler")));
1535        assert!(!guide_similar(&a, &many), "most lines changed is drift");
1536        let mut other = sec(&base);
1537        other.guidance = "New prompt".into();
1538        assert!(
1539            !guide_similar(&a, &guide_basis(&other)),
1540            "new guidance rewrites"
1541        );
1542    }
1543
1544    #[test]
1545    fn finds_a_section_in_a_guide() {
1546        let doc = "## Naming\n\nUse snake_case.\n\n## Testing\n\nPytest.\n\n\n_AI-generated from the codebase; review before enforcing._\n";
1547        assert_eq!(guide_section_of(doc, "Naming"), "Use snake_case.");
1548        assert_eq!(guide_section_of(doc, "Testing"), "Pytest.");
1549        assert_eq!(guide_section_of(doc, "Types"), "");
1550    }
1551}