1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// CLI-specific modules
mod cli;
mod commands;
mod shell;
use std::process::ExitCode;
use clap::Parser;
use cli::{Args, Command, OutputFormat};
use commands::MapFormat;
use ctx::error::Result;
use ctx::exit::Outcome;
/// Exit codes: 0 = clean, 1 = findings, 2 = operational error,
/// 3 = version requirement not met (`ctx harness compat` only).
fn main() -> ExitCode {
// The OS-provided main thread stack is too small on some platforms (notably
// Windows, which defaults to ~1 MiB) for this program's parsing/graph-walking
// call depth; run on a thread with a larger, explicit stack instead.
std::thread::Builder::new()
.stack_size(16 * 1024 * 1024)
.spawn(run_main)
.expect("failed to spawn main worker thread")
.join()
.expect("main worker thread panicked")
}
fn run_main() -> ExitCode {
// Same rationale as the main thread above: give rayon's global pool (used by
// `ctx index --parallel`) an explicit stack size instead of the platform default.
let _ = rayon::ThreadPoolBuilder::new()
.stack_size(16 * 1024 * 1024)
.build_global();
let args = Args::parse();
let json = args.json;
// The passive update check never runs for update-related invocations
// (`ctx self-update`, `ctx --version [--check]`); its remaining
// suppression rules (TTY, --json, env vars, 24h cache) live in
// `ctx::update::passive_check`.
let skip_passive_check =
args.version || matches!(args.command, Some(Command::SelfUpdate { .. }));
let exit = match run(args) {
Ok(outcome) => ExitCode::from(outcome.code()),
Err(e) => {
eprintln!("Error: {}", e);
ExitCode::from(2)
}
};
// Passive update notice (stderr only, at most one network call per 24h,
// silent on failure; see docs/commands/self-update.md). Never automatic:
// this only prints a notice, it never installs anything.
if !skip_passive_check {
ctx::update::passive_check(json);
}
exit
}
fn run(args: Args) -> Result<Outcome> {
// Global machine-readable output flag (see docs/json-output.md)
let json = args.json;
// Custom --version handling: clap's auto flag is disabled (it would
// exit before `--check` could run). `ctx --version` prints the same
// line the auto flag did; `--check` adds a release comparison.
if args.version {
return commands::run_version(args.check, json);
}
// Handle subcommands
let result: Result<()> = match args.command {
Some(Command::Index {
watch,
verbose,
force,
parallel,
no_gitignore,
no_default_ignores,
ignore_patterns,
include_patterns,
}) => {
let config = commands::IndexConfig::new(
watch,
verbose,
force,
parallel,
no_gitignore,
no_default_ignores,
ignore_patterns,
include_patterns,
);
commands::run_index(config)
}
Some(Command::Query { query }) => commands::run_query(query, json),
Some(Command::Sql {
query,
file,
output,
json: json_flag,
max_rows,
timeout,
fail_on_rows,
schema,
snapshots,
}) => {
// `ctx sql` owns its exit code (0 clean / 1 with --fail-on-rows / 2 error),
// so it returns an Outcome directly like the other quality commands.
return commands::run_sql(commands::SqlArgs {
query,
file,
format: output,
json: json || json_flag,
max_rows,
timeout,
fail_on_rows,
schema,
snapshots,
});
}
Some(Command::Search {
query,
limit,
output,
}) => {
let output = if json { "json".to_string() } else { output };
commands::run_search(&query, limit, &output)
}
Some(Command::Source { symbol, file, kind }) => {
commands::run_source(&symbol, file.as_deref(), kind.as_deref())
}
Some(Command::Explain { symbol, file, kind }) => {
commands::run_explain(&symbol, file.as_deref(), kind.as_deref(), json)
}
Some(Command::Embed {
force,
verbose,
batch_size,
openai,
watch,
}) => {
if watch {
commands::run_embed_watch(verbose, batch_size, openai)
} else {
commands::run_embed(force, verbose, batch_size, openai)
}
}
Some(Command::Semantic {
query,
limit,
output,
openai,
}) => {
let output = if json { "json".to_string() } else { output };
commands::run_semantic(&query, limit, &output, openai)
}
Some(Command::Similar {
query,
limit,
keyword,
openai,
}) => {
// `similar` participates in the Outcome convention directly:
// Clean on success, Err (exit 2) when embeddings are missing.
return commands::run_similar(&query, limit, keyword, openai, json);
}
Some(Command::Complexity {
threshold,
warnings_only,
output,
}) => commands::run_complexity(threshold, warnings_only, &output),
Some(Command::Duplicates {
threshold,
min_tokens,
against,
fail_on_found,
}) => {
// Quality command: returns its own Outcome (Findings with
// --fail-on-found when pairs are reported).
return commands::run_duplicates(
threshold,
min_tokens,
against.as_deref(),
json,
fail_on_found,
);
}
Some(Command::Map {
budget,
focus,
format,
}) => {
// The global --json flag forces JSON format for consistency.
let format = if json {
Ok(MapFormat::Json)
} else {
match format {
OutputFormat::Text => Ok(MapFormat::Text),
OutputFormat::Markdown | OutputFormat::Md => Ok(MapFormat::Markdown),
OutputFormat::Json => Ok(MapFormat::Json),
OutputFormat::Xml | OutputFormat::Plain => Err(ctx::error::CtxError::Other(
"ctx map supports --format text, markdown, or json".to_string(),
)),
}
};
format.and_then(|format| commands::run_map(budget, focus.as_deref(), format))
}
Some(Command::Graph {
output,
by_file,
filter,
depth,
}) => commands::run_graph(&output, by_file, filter, depth),
Some(Command::Smart {
task,
max_tokens,
depth,
top,
explain,
dry_run,
openai,
format,
show_sizes,
no_tree,
}) => commands::run_smart(
&task, max_tokens, depth, top, explain, dry_run, openai, format, show_sizes, no_tree,
),
Some(Command::Diff {
revision,
max_tokens,
depth,
changes_only,
staged,
summary,
format,
show_sizes,
no_tree,
}) => commands::run_diff(
&revision,
max_tokens,
depth,
changes_only,
staged,
summary,
format,
show_sizes,
no_tree,
),
Some(Command::Review {
pr,
repo,
include_comments,
max_tokens,
depth,
changes_only,
summary,
format,
show_sizes,
no_tree,
}) => commands::run_review(
&pr,
repo.as_deref(),
include_comments,
max_tokens,
depth,
changes_only,
summary,
format,
show_sizes,
no_tree,
),
Some(Command::Hotspots {
since,
limit,
by,
min_churn,
against,
}) => commands::run_hotspots(&since, limit, by, min_churn, against.as_deref(), json),
Some(Command::Check {
rules,
against,
list,
}) => {
// Quality command: returns Outcome natively (0 clean / 1 findings).
return commands::run_check(rules, against, list, json);
}
Some(Command::Score { against, fail_on }) => {
// Quality command: returns Outcome natively (0 clean / 1 when a
// --fail-on condition is met).
return commands::run_score(&against, fail_on.as_deref(), json);
}
Some(Command::Audit {
output_format,
min_score,
categories,
incremental,
}) => commands::run_audit(&output_format, min_score, categories, incremental),
Some(Command::Snapshot {
cmd,
force,
churn_window,
}) => {
// Snapshot command: returns its own Outcome (always Clean on
// success; stub builds and git/IO failures map to exit 2).
return commands::run_snapshot(cmd, force, &churn_window, json);
}
Some(Command::Harness { cmd }) => {
// Harness command: returns its own Outcome (doctor exits 1 on
// problems; compat exits 3 on version mismatch).
return commands::run_harness(cmd, json);
}
Some(Command::SelfUpdate { version }) => {
// Update command: returns its own Outcome (Clean when updated or
// already up to date; any failure maps to exit 2 in main).
return commands::run_self_update(version.as_deref(), json);
}
Some(Command::Shell {
history,
no_history,
vi,
}) => commands::run_shell(history, no_history, vi),
#[cfg(feature = "mcp")]
Some(Command::Serve { mcp }) => commands::run_serve(mcp),
None => commands::run_context(args),
};
// Commands routed through this fallthrough never report findings;
// quality commands (e.g. `duplicates`) return early with their own
// Outcome above.
result.map(|_| Outcome::Clean)
}