Skip to main content

harn_cli/commands/
mod.rs

1pub(crate) mod agents_conformance;
2pub(crate) mod app;
3mod app_host_assets;
4pub(crate) mod bench;
5pub(crate) mod canon;
6pub(crate) mod check;
7pub(crate) mod codemod;
8pub(crate) mod config_cmd;
9pub(crate) mod conformance_helper;
10pub(crate) mod connect;
11pub(crate) mod connector;
12pub(crate) mod connector_schema_codegen;
13pub(crate) mod contracts;
14pub(crate) mod counterfactual;
15pub(crate) mod crystallize;
16pub mod demo;
17pub(crate) mod dev;
18pub(crate) mod diagnostics_catalog;
19pub(crate) mod dispatch_explain;
20pub(crate) mod doc;
21pub(crate) mod doctor;
22pub(crate) mod dump_highlight_keywords;
23pub(crate) mod dump_portable_benchmark_schema;
24pub(crate) mod dump_prompt_grammar;
25pub(crate) mod dump_protocol_artifacts;
26pub(crate) mod dump_trigger_quickref;
27pub(crate) mod embedded_report;
28pub mod eval_coding_agent;
29pub(crate) mod eval_coding_agent_preset;
30pub mod eval_context;
31pub(crate) mod eval_model_selector;
32pub mod eval_prompt;
33pub(crate) mod eval_prompt_context;
34pub(crate) mod eval_scope_triage;
35pub mod eval_skill_gate;
36pub(crate) mod eval_tool_calls;
37pub(crate) mod explain;
38pub(crate) mod fix;
39pub mod flow;
40pub(crate) mod generate;
41pub(crate) mod graph;
42pub(crate) mod guard;
43pub(crate) mod hardware;
44pub(crate) mod host;
45pub(crate) mod init;
46pub(crate) mod json_schemas;
47pub(crate) mod local;
48pub(crate) mod local_readiness;
49pub(crate) mod mcp;
50pub(crate) mod merge_captain;
51pub(crate) mod merge_captain_mock;
52pub(crate) mod models;
53pub mod orchestrator;
54pub mod pack;
55pub(crate) mod package_scaffold;
56pub(crate) mod package_verify;
57pub(crate) mod parse_tokens;
58pub mod persona;
59pub mod persona_activation;
60pub mod persona_apply;
61pub mod persona_dispatch;
62pub mod persona_doctor;
63pub mod persona_prompt;
64pub mod persona_scaffold;
65pub mod persona_supervision;
66#[cfg(test)]
67pub(crate) mod persona_test_support;
68pub(crate) mod pg_codegen;
69pub mod playground;
70pub(crate) mod portal;
71pub mod precompile;
72pub(crate) mod protocol_conformance;
73pub(crate) mod provider;
74pub(crate) mod provider_capabilities;
75pub(crate) mod provider_limits;
76pub(crate) mod provider_report;
77pub(crate) mod provider_support;
78pub(crate) mod provider_tool_calibrate;
79pub(crate) mod providers;
80pub(crate) use provider_tool_calibrate::run as run_tool_calibrate;
81pub(crate) mod quickstart;
82pub(crate) mod repl;
83pub(crate) mod replay;
84pub(crate) mod routes;
85pub(crate) mod rule;
86pub(crate) mod rules_cli;
87pub mod run;
88pub(crate) mod runs_export_training;
89pub(crate) mod scaffold_common;
90pub(crate) mod scan;
91pub(crate) mod serve;
92pub(crate) mod session;
93pub(crate) mod skill;
94pub(crate) mod skills;
95pub(crate) mod supervisor;
96pub(crate) mod test;
97pub mod test_bench;
98pub(crate) mod test_worker;
99pub mod time;
100pub(crate) mod tool;
101pub(crate) mod tool_mode_parity;
102pub(crate) mod trace;
103pub mod trigger;
104pub(crate) mod trust;
105pub(crate) mod try_cmd;
106pub(crate) mod upgrade;
107pub(crate) mod usage;
108pub(crate) mod viz;
109pub(crate) mod workflow;
110
111use std::path::{Path, PathBuf};
112
113use harn_vm::ignore_policy::{self, IgnorePolicy};
114use ignore::WalkBuilder;
115
116/// Nearest-rank percentile over a pre-sorted slice. `quantile` is clamped to
117/// `[0, 1]`; returns `None` for an empty slice. Shared by the latency
118/// summaries in the eval and orchestrator stats commands.
119pub(crate) fn nearest_rank_percentile(sorted: &[u64], quantile: f64) -> Option<u64> {
120    if sorted.is_empty() {
121        return None;
122    }
123    let rank = ((sorted.len() as f64 * quantile.clamp(0.0, 1.0)).ceil() as usize)
124        .saturating_sub(1)
125        .min(sorted.len() - 1);
126    sorted.get(rank).copied()
127}
128
129const GENERATED_SOURCE_WALK_DIRS: &[&str] = &[
130    ".burin",
131    ".build",
132    ".claude",
133    ".codex",
134    ".git",
135    ".next",
136    ".svelte-kit",
137    ".turbo",
138    ".venv",
139    "build",
140    "coverage",
141    "dist",
142    "node_modules",
143    "target",
144];
145
146pub(crate) fn should_skip_recursive_source_dir(dir: &Path) -> bool {
147    let Some(name) = dir.file_name().and_then(|name| name.to_str()) else {
148        return false;
149    };
150    GENERATED_SOURCE_WALK_DIRS.contains(&name)
151        || crate::path_policy::is_harn_internal_entry(
152            name,
153            crate::path_policy::PathEntryKind::Directory,
154        )
155}
156
157pub(crate) fn should_skip_recursive_source_file(file: &Path) -> bool {
158    let Some(name) = file.file_name().and_then(|name| name.to_str()) else {
159        return false;
160    };
161    // Harn can emit generated source snapshots such as `.harn-eval-*.harn`.
162    // This source-file rule is separate from directory-owned runtime state.
163    name.starts_with(".harn-")
164}
165
166#[derive(Default)]
167pub(crate) struct SourceTargets {
168    pub(crate) harn: Vec<PathBuf>,
169    pub(crate) prompts: Vec<PathBuf>,
170}
171
172impl SourceTargets {
173    fn sort_and_dedup(&mut self) {
174        self.harn.sort();
175        self.harn.dedup();
176        self.prompts.sort();
177        self.prompts.dedup();
178    }
179}
180
181pub(crate) fn collect_source_targets(
182    targets: &[&str],
183    include_harn: bool,
184    include_prompts: bool,
185) -> SourceTargets {
186    let mut files = SourceTargets::default();
187    for target in targets {
188        let path = Path::new(target);
189        if path.is_dir() {
190            collect_source_targets_dir(path, include_harn, include_prompts, &mut files);
191        } else {
192            push_matching_source_target(path, include_harn, include_prompts, false, &mut files);
193        }
194    }
195    files.sort_and_dedup();
196    files
197}
198
199fn collect_source_targets_dir(
200    dir: &Path,
201    include_harn: bool,
202    include_prompts: bool,
203    files: &mut SourceTargets,
204) {
205    let root = dir.to_path_buf();
206    let mut walker = WalkBuilder::new(dir);
207    // `harn_vm::ignore_policy` owns what a Harn walk skips, and this walk is
208    // no exception even though it enumerates lint targets rather than user
209    // data. Configuring the `ignore` crate here by hand is what broke it: the
210    // crate's upward search for ignore files is only bounded when a
211    // repository anchors it, so `require_git(false)` plus `parents(true)` let
212    // a `.gitignore` *above* the checkout decide which of the project's own
213    // sources exist. A repository cloned under an ignoring parent — an agent
214    // worktree beneath `~/.cursor`, whose `.gitignore` is `*` — enumerated as
215    // empty, so every directory target expanded to nothing.
216    //
217    // Hidden entries stay visible: `.github/` and friends hold real sources,
218    // and dotfile filtering is a separate axis from the ignore stack.
219    //
220    // A configuration error means only that the built-in directory layer
221    // could not be materialized. This function has no error channel, and the
222    // walk is already correct without that layer — it would over-include some
223    // build directories, which the caller then reports on and a reader can
224    // see. Returning nothing is the failure worth avoiding.
225    let _ = ignore_policy::configure(&mut walker, dir, IgnorePolicy::Project, true);
226    walker.follow_links(false).filter_entry(move |entry| {
227        let path = entry.path();
228        if path == root {
229            return true;
230        }
231        if path.is_dir() {
232            !should_skip_recursive_source_dir(path)
233        } else {
234            !should_skip_recursive_source_file(path)
235        }
236    });
237
238    for entry in walker.build().filter_map(Result::ok) {
239        let path = entry.path();
240        if entry
241            .file_type()
242            .is_some_and(|file_type| file_type.is_file())
243        {
244            push_matching_source_target(path, include_harn, include_prompts, true, files);
245        }
246    }
247}
248
249fn push_matching_source_target(
250    path: &Path,
251    include_harn: bool,
252    include_prompts: bool,
253    honor_skip_marker: bool,
254    files: &mut SourceTargets,
255) {
256    if include_prompts && is_harn_prompt_file(path) {
257        files.prompts.push(path.to_path_buf());
258    } else if include_harn && is_harn_program_file(path) {
259        let skip_marker = path.with_extension("conformance-skip");
260        if !honor_skip_marker || !skip_marker.exists() {
261            files.harn.push(path.to_path_buf());
262        }
263    }
264}
265
266pub(crate) fn is_harn_program_file(path: &Path) -> bool {
267    let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
268        return false;
269    };
270    if name.ends_with(".harn.prompt") || name.ends_with(".prompt") {
271        return false;
272    }
273    name.ends_with(".harn") || name.ends_with(".harn.txt")
274}
275
276pub(crate) fn is_harn_prompt_file(path: &Path) -> bool {
277    let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
278        return false;
279    };
280    name.ends_with(".harn.prompt") || name.ends_with(".prompt")
281}
282
283/// Recursively collect `.harn` files under `dir`, sorted by path. Files with a
284/// sibling `<name>.conformance-skip` marker are excluded — used to temporarily
285/// park tests that are tracking a known regression in an issue so `make test`
286/// + `harn test conformance` can stay green while the fix is in flight.
287pub(crate) fn collect_harn_files(dir: &Path, out: &mut Vec<PathBuf>) {
288    if let Ok(entries) = std::fs::read_dir(dir) {
289        let mut entries: Vec<_> = entries.filter_map(|e| e.ok()).collect();
290        entries.sort_by_key(|e| e.path());
291        for entry in entries {
292            let path = entry.path();
293            if path.is_dir() {
294                if should_skip_recursive_source_dir(&path) {
295                    continue;
296                }
297                collect_harn_files(&path, out);
298            } else if should_skip_recursive_source_file(&path) {
299                continue;
300            } else if path.extension().is_some_and(|ext| ext == "harn") {
301                let skip_marker = path.with_extension("conformance-skip");
302                if skip_marker.exists() {
303                    continue;
304                }
305                out.push(path);
306            }
307        }
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::nearest_rank_percentile;
314
315    #[test]
316    fn percentile_handles_empty_and_bounds() {
317        assert_eq!(nearest_rank_percentile(&[], 0.5), None);
318        let data = [10u64, 20, 30, 40, 50];
319        assert_eq!(nearest_rank_percentile(&data, 0.0), Some(10));
320        assert_eq!(nearest_rank_percentile(&data, 0.5), Some(30));
321        assert_eq!(nearest_rank_percentile(&data, 1.0), Some(50));
322        // Out-of-range quantiles clamp instead of panicking.
323        assert_eq!(nearest_rank_percentile(&data, 2.0), Some(50));
324        assert_eq!(nearest_rank_percentile(&[7u64], 0.99), Some(7));
325    }
326}