keel_cli/scan/mod.rs
1//! Static scanning — the first of the three evidence sources behind `keel init`
2//! and `keel doctor` (dx-spec §2). No code runs: we read the project's source
3//! and find where effects enter.
4//!
5//! Two scanners, one merged result:
6//! - [`python`] shells an `ast`-walker out to `python3 -` for precise Python
7//! parsing (imports of known effect libraries, URL/DSN string literals).
8//! - [`js`] parses JS/TS/JSX in-process with oxc (no Node toolchain needed)
9//! for `fetch`/`undici`/`node:http` usage, provider-SDK imports, effect-lib
10//! call sites, and URL literals.
11//!
12//! Both label every finding with `file:line`, so the generated `keel.toml` can
13//! cite where each target was found and trust stays inspectable.
14
15pub mod js;
16pub mod python;
17
18use std::collections::{BTreeMap, BTreeSet};
19use std::path::{Path, PathBuf};
20
21/// What kind of target a sighting resolves to. Governs the policy block
22/// `keel init` writes (an `llm:*` target gets the LLM pack; a host gets the
23/// outbound pack).
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum TargetClass {
26 /// A network host, e.g. `api.stripe.com` — from a URL/DSN literal.
27 Host,
28 /// A semantic `llm:<provider>` target — from a provider SDK import.
29 Llm,
30}
31
32/// How a sighted host's traffic is dispatched, best-known across sightings.
33/// Ordering is meaningful: `Tracked < UntrackedKnown < Unknown`, so merging
34/// (`min`) always keeps the most favorable class seen for a host across every
35/// file/language that sighted it. This is what `keel doctor` (a later
36/// program task) uses to say honestly what Keel can and cannot see: a host
37/// is `Tracked` if some sighting reached it through a registry-adapted
38/// library, `UntrackedKnown` if the best reach was a known-but-unadapted
39/// transport (`http.client`, or urllib without `urllib.request`; Python's
40/// `urllib.request` itself is adapted), and `Unknown` if no transport
41/// evidence was found near any sighting at all.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
43pub enum TransportClass {
44 /// A registry-adapted library is in reach — Keel can wrap this.
45 Tracked,
46 /// A known transport Keel does not adapt (http.client, or urllib without
47 /// `urllib.request`; Python's `urllib.request` itself is adapted).
48 UntrackedKnown,
49 /// A URL literal with no recognizable transport nearby.
50 Unknown,
51}
52
53/// One effect call site with enclosing-function attribution — an internal
54/// detail of the JS/TS pass ([`js`]), which uses it to verify its real
55/// scope-chain tracking (dotted paths like `Class.method`) independently of
56/// the coarser top-level-only [`FunctionFacts`] attribution `keel flows
57/// suggest` consumes. Not exposed on [`ScanResult`]. Field order is the sort
58/// order (file, then line).
59#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
60pub struct CallSite {
61 /// Project-relative path with `/` separators.
62 pub file: String,
63 /// 1-based line of the call expression.
64 pub line: u32,
65 /// What is called, rooted at the effect library where the receiver is
66 /// known (`fetch`, `undici.request`, `openai.chat.completions.create`).
67 pub callee: String,
68 /// Dotted enclosing-scope path (`Class.method`, `outer.inner`), or `None`
69 /// at module top level. Anonymous scopes inherit the nearest named scope.
70 pub function: Option<String>,
71}
72
73/// One externally-launched process the scan saw — traffic inside it is
74/// outside Keel's visibility regardless of policy. Field order is the sort
75/// order (file, then line).
76#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
77pub struct SubprocessSighting {
78 /// Project-relative path with `/` separators.
79 pub file: String,
80 /// 1-based line of the launching call.
81 pub line: u32,
82 /// The launching call, e.g. `subprocess.run`, `os.system`,
83 /// `child_process.spawn`.
84 pub launcher: String,
85 /// The literal argv/command line when statically extractable
86 /// (a bare string, or a list/tuple of string-literal elements); otherwise
87 /// `"<dynamic>"`.
88 pub command: String,
89}
90
91/// One hand-rolled resilience pattern sighted inside a function that also
92/// reaches a Keel-relevant target — a simplification lead: once the target
93/// is wrapped, the pattern becomes redundant. `kind` is a closed set:
94/// "hand-rolled-retry" | "hand-rolled-poll" | "silent-swallow". `line`
95/// anchors the construct to delete (the loop / the `except` line), not the
96/// sleep call inside it. Python-only as of this build (JS pattern parity is
97/// a spec'd follow-on program).
98#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
99pub struct SimplificationSighting {
100 pub file: String,
101 pub line: u32,
102 pub kind: String,
103 pub function: String,
104 pub targets: Vec<String>,
105}
106
107/// One file the scan judged dependency-averse: stdlib-only imports plus a
108/// risk/gate/guard/auth/valid/safety/kill name or docstring signal, or an
109/// explicit `# keel: exclude` marker. Markers win in both directions: an
110/// exclude marker forces this classification regardless of imports, and an
111/// include marker defeats the heuristic even where it would otherwise match.
112/// `keel doctor`/`keel init` (a later program task) use this to honestly
113/// exclude hosts seen only in such files from proposed policy. Field order
114/// is the sort order (by file).
115#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
116pub struct DepAverseFile {
117 /// Project-relative path with `/` separators.
118 pub file: String,
119 /// `"marker"` for an explicit `# keel: exclude`, or
120 /// `"stdlib-only + name/docstring signal: <word>"`.
121 pub reason: String,
122}
123
124/// One place a target was seen: a project-relative path and 1-based line.
125#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
126pub struct Sighting {
127 /// Project-relative path with `/` separators.
128 pub file: String,
129 /// 1-based line number.
130 pub line: u32,
131}
132
133impl Sighting {
134 /// Render as the `file:line` token used in evidence comments.
135 pub fn label(&self) -> String {
136 format!("{}:{}", self.file, self.line)
137 }
138}
139
140/// A target and everywhere the static scan saw it, deduplicated and ordered.
141#[derive(Debug, Clone)]
142pub struct TargetEvidence {
143 /// The target's class.
144 pub class: TargetClass,
145 /// Sorted, unique sightings.
146 pub sightings: BTreeSet<Sighting>,
147}
148
149/// Per-function effect attribution — the evidence behind `keel flows suggest`.
150///
151/// Each language pass attributes what it finds *inside* a function definition
152/// to that function: intercepted-effect call sites, calls that read time or
153/// randomness (virtualized under Tier 2 replay), and constructs that defeat
154/// replay outright (threads, subprocesses, raw sockets). Both passes
155/// attribute by real containment: the Python walker via `ast` module-level
156/// def bodies, the JS/TS pass via a real oxc scope walk (see [`js`]) — an
157/// entry opens only for a function bound directly at module top level; class
158/// methods and nested/inner functions roll up into the enclosing top-level
159/// entry rather than opening their own.
160#[derive(Debug, Clone, Default, PartialEq, Eq)]
161pub struct FunctionFacts {
162 /// The full flow-entrypoint ref this function would be designated as —
163 /// `py:pipeline.ingest:main` or `ts:jobs/nightly.ts#run` (the `ts:`
164 /// namespace covers all JS/TS files).
165 pub entrypoint: String,
166 /// Project-relative path of the defining file.
167 pub file: String,
168 /// 1-based line of the `def`/`function`.
169 pub line: u32,
170 /// Intercepted-effect call sites (HTTP / LLM / DSN-bearing libraries).
171 pub effects: u32,
172 /// Effect calls that are not idempotent-safe to re-send (POST/PATCH-shaped)
173 /// and carry no idempotency evidence.
174 pub idempotent_unsafe: u32,
175 /// Wall-clock reads (`time.time`, `datetime.now`, `Date.now`, …) — these
176 /// are virtualized (journaled + replayed) under Tier 2.
177 pub time_reads: u32,
178 /// Randomness reads (`random.*`, `uuid4`, `Math.random`, …) — also
179 /// virtualized under Tier 2.
180 pub random_reads: u32,
181 /// Why replay would be unsafe (empty = the replay-safe estimate holds).
182 /// Each reason cites `what at file:line`; sorted, deterministic.
183 pub unsafe_reasons: Vec<String>,
184 /// Targets referenced inside the function (hosts from URL literals,
185 /// `llm:<provider>` from SDK calls) — the join key into `.keel/discovery.db`.
186 pub targets: BTreeSet<String>,
187}
188
189/// The merged output of both scanners.
190#[derive(Debug, Clone, Default)]
191pub struct ScanResult {
192 /// Number of source files parsed (Python + JS/TS) — the header's "N static
193 /// scans".
194 pub files_scanned: usize,
195 /// Whether `python3` was available for the Python pass. When false, Python
196 /// files could not be scanned; `keel init` notes this on stderr rather than
197 /// letting it silently narrow coverage.
198 pub python_available: bool,
199 /// Discovered targets, keyed by target string, ordered.
200 pub targets: BTreeMap<String, TargetEvidence>,
201 /// Effect-library names detected across the project (e.g. `httpx`,
202 /// `openai`, `boto3`, `fetch`). `keel doctor` cross-references these against
203 /// its adapter registry to classify coverage.
204 pub libs: BTreeSet<String>,
205 /// Per-function attribution (see [`FunctionFacts`]), sorted by
206 /// `(file, line)` — deterministic across runs.
207 pub functions: Vec<FunctionFacts>,
208 /// Known resilience-library names detected (Python-only as of this
209 /// build — see [`LangFindings::resilience_libs`]).
210 pub resilience_libs: BTreeSet<String>,
211 /// Best-known [`TransportClass`] per sighted host, merged across every
212 /// file and language that sighted it (minimum = best class wins). Unlike
213 /// `targets`, this is never gated on `http_in_use` — it exists precisely
214 /// to let `keel doctor` report on hosts Keel cannot see at all.
215 pub host_transports: BTreeMap<String, TransportClass>,
216 /// Every externally-launched process the scan saw, sorted by
217 /// `(file, line)` — deterministic across runs. `keel doctor` uses this to
218 /// call out where Keel's visibility ends at a process boundary.
219 pub subprocesses: Vec<SubprocessSighting>,
220 /// Files judged dependency-averse across the project, sorted by file —
221 /// see [`DepAverseFile`]. Python-only as of this build (see
222 /// [`LangFindings::dependency_averse`]).
223 pub dependency_averse: Vec<DepAverseFile>,
224 /// Hand-rolled resilience patterns sighted in functions with target
225 /// attribution, sorted by (file, line, kind) — deterministic across
226 /// runs.
227 pub simplifications: Vec<SimplificationSighting>,
228}
229
230impl ScanResult {
231 fn add(&mut self, target: String, class: TargetClass, file: String, line: u32) {
232 self.targets
233 .entry(target)
234 .or_insert_with(|| TargetEvidence {
235 class,
236 sightings: BTreeSet::new(),
237 })
238 .sightings
239 .insert(Sighting { file, line });
240 }
241}
242
243/// Scan `project` with both scanners and merge. Host targets are only emitted
244/// when the language pass also saw an HTTP client in use (a bare URL in a
245/// non-networked file is not evidence of an outbound call), keeping the output
246/// honest.
247pub fn scan(project: &Path) -> ScanResult {
248 let mut result = ScanResult::default();
249
250 let py = python::scan(project);
251 result.python_available = py.available;
252 result.files_scanned += py.files_scanned;
253 merge_lang(&mut result, &py.findings);
254 result.functions.extend(py.functions);
255
256 let js = js::scan(project);
257 result.files_scanned += js.files_scanned;
258 merge_lang(&mut result, &js.findings);
259 result.functions.extend(js.functions);
260
261 result
262 .functions
263 .sort_by(|a, b| (&a.file, a.line, &a.entrypoint).cmp(&(&b.file, b.line, &b.entrypoint)));
264 result.subprocesses.sort();
265 result.dependency_averse.sort();
266 result.simplifications.sort();
267 result
268}
269
270/// One language scanner's raw findings before host-gating.
271#[derive(Debug, Clone, Default)]
272pub struct LangFindings {
273 /// Provider SDK imports → `llm:*` targets.
274 pub llm: Vec<(String, Sighting)>,
275 /// URL/DSN host literals → host targets (gated on `http_in_use`).
276 pub hosts: Vec<(String, Sighting)>,
277 /// Whether an HTTP client (http lib / fetch / undici) was seen at all.
278 pub http_in_use: bool,
279 /// Effect-library names detected (for `keel doctor`'s registry cross-check).
280 pub libs: BTreeSet<String>,
281 /// Effect call sites with enclosing-function attribution.
282 pub call_sites: Vec<CallSite>,
283 /// Known resilience-library names detected (e.g. `tenacity`, `backoff`)
284 /// — a `keel doctor` signal for pre-existing retry/backoff that might
285 /// now silently compound with Keel's own. Deliberately separate from
286 /// `libs`: these are libraries Keel never adapts, so merging them in
287 /// would misclassify them as an "invisible" coverage gap.
288 pub resilience_libs: BTreeSet<String>,
289 /// Per-sighting [`TransportClass`] for every host this language pass saw,
290 /// keyed by host. Never gated on `http_in_use` — a bare URL literal with
291 /// no reachable transport is exactly the `Unknown` case `keel doctor`
292 /// needs to report honestly.
293 pub host_transports: BTreeMap<String, TransportClass>,
294 /// Externally-launched processes this language pass saw (see
295 /// [`SubprocessSighting`]).
296 pub subprocesses: Vec<SubprocessSighting>,
297 /// Files this language pass judged dependency-averse (see
298 /// [`DepAverseFile`]).
299 pub dependency_averse: Vec<DepAverseFile>,
300 /// Hand-rolled resilience patterns this language pass saw (see
301 /// [`SimplificationSighting`]). Python-only as of this build.
302 pub simplifications: Vec<SimplificationSighting>,
303}
304
305fn merge_lang(result: &mut ScanResult, f: &LangFindings) {
306 for (provider, s) in &f.llm {
307 result.add(
308 format!("llm:{provider}"),
309 TargetClass::Llm,
310 s.file.clone(),
311 s.line,
312 );
313 }
314 if f.http_in_use {
315 for (host, s) in &f.hosts {
316 result.add(host.clone(), TargetClass::Host, s.file.clone(), s.line);
317 }
318 }
319 for lib in &f.libs {
320 result.libs.insert(lib.clone());
321 }
322 for lib in &f.resilience_libs {
323 result.resilience_libs.insert(lib.clone());
324 }
325 for (host, class) in &f.host_transports {
326 result
327 .host_transports
328 .entry(host.clone())
329 .and_modify(|c| *c = (*c).min(*class))
330 .or_insert(*class);
331 }
332 result.subprocesses.extend(f.subprocesses.iter().cloned());
333 result
334 .dependency_averse
335 .extend(f.dependency_averse.iter().cloned());
336 result
337 .simplifications
338 .extend(f.simplifications.iter().cloned());
339}
340
341/// Directory names never descended into during a filesystem walk — scans,
342/// `keel init`'s Python-file check, and `keel flows resume`'s module search
343/// all share this one list (previously three drifted copies; see the
344/// 2026-07-14 fast-follow that consolidated them).
345pub(crate) const SKIP_DIRS: &[&str] = &[
346 ".keel",
347 ".git",
348 ".hg",
349 ".svn",
350 "__pycache__",
351 "node_modules",
352 ".venv",
353 "venv",
354 ".mypy_cache",
355 ".pytest_cache",
356 "dist",
357 "build",
358 "target",
359];
360
361/// Recursively collect files under `dir` whose extension is one of
362/// `extensions`, skipping [`SKIP_DIRS`] and dot-prefixed directories. The
363/// one walker for "find source files by extension" in this crate — shared
364/// by the JS/TS scanner ([`js`]), `keel init`'s Python-file check, and
365/// `keel run`'s directory-entry resolution.
366pub(crate) fn collect_files(dir: &Path, extensions: &[&str], out: &mut Vec<PathBuf>) {
367 let Ok(entries) = std::fs::read_dir(dir) else {
368 return;
369 };
370 for entry in entries.flatten() {
371 let path = entry.path();
372 let name = entry.file_name();
373 let name = name.to_string_lossy();
374 if path.is_dir() {
375 if SKIP_DIRS.contains(&name.as_ref()) || name.starts_with('.') {
376 continue;
377 }
378 collect_files(&path, extensions, out);
379 } else if path
380 .extension()
381 .and_then(|e| e.to_str())
382 .is_some_and(|e| extensions.contains(&e))
383 {
384 out.push(path);
385 }
386 }
387}
388
389/// Extract the host from a `scheme://host[:port][/…]` literal, lowercased and
390/// without port/userinfo/path. Returns `None` for non-URL strings. Shared by
391/// both scanners so Python and JS agree on what a host is.
392pub(crate) fn host_from_url(s: &str) -> Option<String> {
393 let s = s.trim();
394 let (scheme, rest) = s.split_once("://")?;
395 if scheme.is_empty()
396 || !scheme
397 .chars()
398 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-'))
399 || !scheme
400 .chars()
401 .next()
402 .is_some_and(|c| c.is_ascii_alphabetic())
403 {
404 return None;
405 }
406 // authority ends at the first '/', '?', or '#'.
407 let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
408 // strip userinfo, then port.
409 let host_port = authority.rsplit('@').next().unwrap_or(authority);
410 let host = host_port.split(':').next().unwrap_or(host_port);
411 if host.is_empty() || host.contains(|c: char| c.is_whitespace()) {
412 return None;
413 }
414 Some(host.to_ascii_lowercase())
415}
416
417#[cfg(test)]
418mod tests {
419 use super::*;
420
421 #[test]
422 fn host_extraction_strips_port_userinfo_and_path() {
423 assert_eq!(
424 host_from_url("https://api.stripe.com/v1/x").as_deref(),
425 Some("api.stripe.com")
426 );
427 assert_eq!(
428 host_from_url("postgres://u:p@db.internal:5432/app").as_deref(),
429 Some("db.internal")
430 );
431 assert_eq!(host_from_url("HTTPS://API.X").as_deref(), Some("api.x"));
432 assert_eq!(host_from_url("not a url"), None);
433 assert_eq!(host_from_url("://nohost"), None);
434 assert_eq!(host_from_url("1bad://x"), None);
435 }
436}