double-o 0.7.0

Context-efficient command runner for AI coding agents
Documentation
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
use std::path::Path;

use humansize::{BINARY, format_size};
use std::io::Write;

use crate::classify::Classification;
pub use crate::init::InitFormat;
use crate::store::SessionMeta;
use crate::util::now_epoch;
use crate::{
    classify, commands_patterns, error::Error, exec, help, init, init_pi, learn, pattern,
    pattern_load, rewrite, session, store,
};

pub enum Action {
    Run(Vec<String>),
    Recall { query: String, full: bool },
    Forget,
    Learn(Vec<String>, Option<String>),
    Version,
    Help(Option<String>),
    Init(InitMode),
    Patterns,
    Rewrite(String),
    Hook(Option<String>),
}

/// Resolved mode for `oo init`: the legacy `--format` value or the new
/// `--agent` target (issue #171).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InitMode {
    /// `--format claude`/`generic` (or plain `oo init`) — behaviour unchanged.
    Format(InitFormat),
    /// `--agent pi [--global]` — install the pi extension.
    Pi { global: bool },
    /// `--agent claude-code [--global]` — install the Claude Code hook (issue #172).
    ClaudeCode { global: bool },
}

/// Agents supported by `oo init --agent`.
pub const SUPPORTED_AGENTS: &[&str] = &["pi", "claude-code"];

/// Parse the trailing args of `oo init` into an [`InitMode`].
///
/// Single pass over the args; each recognised flag is handled inline and no
/// value is silently discarded. `--agent` and `--format` are mutually
/// exclusive (issue #171, operator decision 1): passing both is a
/// parse-time error before anything is written. `--agent pi` installs the pi
/// extension, with `--global` writing to the user-level extensions directory
/// (`--global` without `--agent` is an error — there is no legacy global
/// install). `--agent`'s value is validated against [`SUPPORTED_AGENTS`]:
/// `pi` works, `claude-code` is supported by name but not yet implemented
/// (a sibling ticket ships it), and anything else errors. On the pure
/// `--format` path (no `--agent` at all), the original args are handed to
/// [`parse_init_format`], so `oo init`, `oo init --format generic` and
/// `oo init --format bogus` (warn, fall back to claude) behave exactly as
/// before. Unknown extra flags are ignored (today's behavior).
pub(crate) fn parse_init_mode(args: &[String]) -> Result<InitMode, String> {
    let supported = SUPPORTED_AGENTS.join(", ");
    let mut agent: Option<String> = None;
    let mut global = false;
    let mut has_format = false;
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        match arg.as_str() {
            "--agent" => {
                let Some(value) = iter.next().filter(|v| !v.starts_with("--")) else {
                    // No value, or the next token is itself a flag (e.g.
                    // `--agent --global`) — report it as missing.
                    return Err(format!(
                        "--agent requires a value; supported agents: {supported}"
                    ));
                };
                agent = Some(value.clone());
            }
            "--global" => global = true,
            // `--format` alone: the original args are re-scanned by
            // parse_init_format below (no value consumed here, so its warn
            // and fall-back-to-claude behavior is preserved).
            "--format" => has_format = true,
            _ => {}
        }
    }
    let Some(agent) = agent else {
        // `--global` without `--agent` is always an error, regardless of
        // whether `--format` is also present — there is no legacy global
        // install, so `--global` only makes sense with `--agent`.
        if global {
            return Err("--global requires --agent".to_string());
        }
        if has_format {
            return Ok(InitMode::Format(parse_init_format(args)));
        }
        return Ok(InitMode::Format(InitFormat::Claude));
    };
    if has_format {
        // Mutual exclusion regardless of flag order or value.
        return Err("--agent and --format cannot be used together".to_string());
    }
    if !SUPPORTED_AGENTS.contains(&agent.as_str()) {
        return Err(format!(
            "unknown --agent value '{agent}'; supported agents: {supported}"
        ));
    }
    match agent.as_str() {
        "pi" => Ok(InitMode::Pi { global }),
        "claude-code" => Ok(InitMode::ClaudeCode { global }),
        _ => unreachable!("agent validated against SUPPORTED_AGENTS above"),
    }
}

/// Parse `--format <value>` from the remaining init args.
///
/// Recognised values: `claude` (default), `generic`.
/// Unknown values emit a warning to stderr and fall back to Claude.
fn parse_init_format(args: &[String]) -> InitFormat {
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        if arg == "--format" {
            return match iter.next().map(|s| s.as_str()) {
                Some("generic") => InitFormat::Generic,
                Some("claude") | None => InitFormat::Claude,
                Some(other) => {
                    eprintln!(
                        "oo: unknown --format value '{}', defaulting to claude",
                        other
                    );
                    InitFormat::Claude
                }
            };
        }
    }
    InitFormat::Claude
}

/// Parse `oo recall` arguments, extracting optional `--full` flag.
///
/// `--full` is stripped from ANY position in the trailing args (consistent
/// with `parse_learn_action`'s `--hint` handling). Searching for the literal
/// string `--full` in a query is unsupported; document that in help.
fn parse_recall_action(args: &[String]) -> Action {
    let query: String = args
        .iter()
        .filter(|a| a.as_str() != "--full")
        .cloned()
        .collect::<Vec<_>>()
        .join(" ");
    let full = args.iter().any(|a| a.as_str() == "--full");
    Action::Recall { query, full }
}

/// Parse `oo learn` arguments, extracting optional `--hint <text>` flag.
///
/// Returns (args_without_hint, hint_text). The hint text is removed from the
/// command args so it doesn't interfere with the actual command being run.
fn parse_learn_action(args: &[String]) -> Action {
    let mut result: Vec<String> = Vec::new();
    let mut hint: Option<String> = None;
    let mut iter = args.iter().peekable();

    while let Some(arg) = iter.next() {
        if arg == "--hint" {
            // Take the next argument as the hint text, but only if it's not a flag
            // If the next arg starts with '-', treat it as a command argument, not hint text
            if let Some(hint_text) = iter.next() {
                if !hint_text.starts_with('-') {
                    hint = Some(hint_text.clone());
                } else {
                    // The next arg is a flag, treat it as part of the command
                    result.push(hint_text.clone());
                }
            }
            // If no hint text after --hint, emit a warning and treat as no hint
        } else {
            result.push(arg.clone());
        }
    }

    Action::Learn(result, hint)
}

pub fn parse_action(args: &[String]) -> Action {
    match args.first().map(|s| s.as_str()) {
        None => Action::Help(None),
        Some("recall") => parse_recall_action(&args[1..]),
        Some("forget") => Action::Forget,
        Some("learn") => parse_learn_action(&args[1..]),
        Some("version") => Action::Version,
        // `oo help <cmd>` — look up cheat sheet; `oo help` alone shows usage
        Some("help") => Action::Help(args.get(1).cloned()),
        Some("init") => match parse_init_mode(&args[1..]) {
            Ok(mode) => Action::Init(mode),
            Err(e) => {
                eprintln!("oo: {e}");
                std::process::exit(1);
            }
        },
        Some("patterns") => Action::Patterns,
        Some("rewrite") => {
            let command: String = args
                .get(1..)
                .map(|rest| rest.join(" "))
                .filter(|s| !s.is_empty())
                .unwrap_or_default();
            Action::Rewrite(command)
        }
        // `oo hook claude` — stdin-JSON PreToolUse processor (issue #172).
        // Must be recognised before the `Run` fall-through, else `hook` would
        // be treated as a shell command to spawn.
        Some("hook") => Action::Hook(args.get(1).cloned()),
        _ => Action::Run(args.to_vec()),
    }
}

/// Run a command via [`exec::run`], load the pattern set used by `cmd_run`, classify the output,
/// and render it. Returns the exit code and the classification so tests can inspect the
/// classification directly (rendering happens here so the normal `cmd_run` path is exercised).
///
/// The classification is `None` on the two pre-classification error paths
/// (no command given, or exec failure) — there is no output to classify, so
/// no `Classification` value is fabricated.
pub fn run_command_args(args: &[String]) -> (i32, Option<Classification>) {
    if args.is_empty() {
        eprintln!("oo: no command specified");
        return (1, None);
    }

    // Load patterns (first match wins: project overrides user overrides builtins).
    let all_patterns = pattern_load::all_patterns();

    // Run command
    let output = match exec::run(args) {
        Ok(o) => o,
        Err(e) => {
            eprintln!("oo: {e}");
            return (1, None);
        }
    };

    let exit_code = output.exit_code;
    let command = args.join(" ");

    // Classify
    let merged = output.merged_lossy();
    let classification = classify::classify(&output, &command, &all_patterns);

    // Print result
    render_classification(&classification, &command, merged.len());

    (exit_code, Some(classification))
}

/// Run a command via [`exec::run`], classify the output, and render it. Returns the exit code.
pub fn cmd_run(args: &[String]) -> i32 {
    run_command_args(args).0
}

/// Build the `[saved {humansize}]` suffix for a compressed indicator line.
///
/// `original_bytes` is the merged output size in bytes (`merged_lossy().len()`);
/// `indicator_bytes` is the byte length of the indicator line EXCLUDING the
/// savings suffix (call sites pass `line.len()` before the suffix is
/// appended), so the reported figure overstates displayed bytes by the
/// suffix's own length (~15 B — immaterial at the sizes where a suffix can
/// appear). Returns `None` when the saving is ≤ [`classify::MIN_SAVINGS`]
/// (i.e. the suffix appears only when `saved > MIN_SAVINGS`; saturating
/// arithmetic makes underflow impossible), so the caller prints the line
/// unchanged. Only the indicator line counts as displayed — the filtered
/// output lines printed after it (Failure arm) are not included.
pub fn savings_suffix(original_bytes: usize, indicator_bytes: usize) -> Option<String> {
    let saved = original_bytes.saturating_sub(indicator_bytes);
    (saved > classify::MIN_SAVINGS).then(|| format!(" [saved {}]", format_size(saved, BINARY)))
}

/// Print a [`Classification`] to stdout using the shared display path.
///
/// `original_size` is the merged output size in bytes, used to append the
/// savings suffix to the Success and Failure indicator lines via
/// [`savings_suffix`]. The Large tier indexes the output via [`try_index`]
/// and falls back to [`classify::smart_truncate`] on indexing failure.
/// Both `cmd_run` and `cmd_learn` use this so the arms cannot drift apart.
pub fn render_classification(classification: &Classification, command: &str, original_size: usize) {
    match classification {
        Classification::Failure { label, output } => {
            let line = format!("\u{2717} {label}");
            // The `\n` in the payload plus `println!`'s own newline is a
            // deliberate BLANK LINE between the indicator and the error
            // body — the suffix (if any) lands on the indicator line only,
            // and the blank line survives with or without it.
            println!(
                "{line}{}\n",
                savings_suffix(original_size, line.len()).unwrap_or_default()
            );
            println!("{output}");
        }
        Classification::Passthrough { output } => {
            print!("{output}");
        }
        Classification::Success { label, summary } => {
            let line = if summary.is_empty() {
                format!("\u{2713} {label}")
            } else {
                format!("\u{2713} {label} ({summary})")
            };
            println!(
                "{line}{}",
                savings_suffix(original_size, line.len()).unwrap_or_default()
            );
        }
        Classification::Bounded {
            label,
            output,
            display,
            size,
            ..
        } => {
            // SECURITY (residual risk, pre-existing): the framing line printed
            // below (`● {label} (output truncated: ...)`) is byte-predictable
            // and is followed by attacker-controlled `display`, which could
            // embed a byte-identical copy of it — so "the framing line comes
            // first" is a convention, not an enforceable guarantee, and an
            // agent that greps for the framing pattern can't distinguish the
            // host-authored line from a forged one. The Large arm's
            // `● ... (indexed ...)` line has the same property. NOT fixed
            // here (would require changing the output format); document the
            // residual risk at the point of use instead.
            //
            // Best-effort index the full output for recall; the display is
            // always printed — the byte-bounded head+tail slice IS the point
            // of this arm (issue #148). The truncation marker in `display`
            // makes it detectable as bounded output, but it lives inside
            // attacker-controlled output, so the host also prints its own
            // framing line carrying the authoritative size (mirrors the Large
            // arm) — an agent must never be told to recall data that was not
            // indexed.
            let indexed = try_index(command, output);
            let human_size = format_size(*size, BINARY);
            if indexed {
                println!(
                    "\u{25CF} {label} (output truncated: {human_size} total \u{2192} use `oo recall` to query)"
                );
            } else {
                // Indexing failed: do NOT advertise `oo recall` — the display
                // is all the agent gets, and the stderr note keeps the
                // failure visible instead of swallowed.
                eprintln!(
                    "oo: warning: could not index output for recall — full output LOST (not recoverable); what follows is a truncated slice only"
                );
                println!(
                    "\u{25CF} {label} (output truncated: {human_size} total — NOT indexed, recall unavailable)"
                );
            }
            print!("{display}");
        }
        Classification::Large {
            label,
            output,
            size,
            ..
        } => {
            // Index into store
            let indexed = try_index(command, output);
            let human_size = format_size(*size, BINARY);
            if indexed {
                println!(
                    "\u{25CF} {label} (indexed {human_size} \u{2192} use `oo recall` to query)"
                );
            } else {
                // Couldn't index, show truncated output instead
                let truncated = classify::smart_truncate(output);
                print!("{truncated}");
            }
        }
    }
}

pub fn try_index(command: &str, content: &str) -> bool {
    let mut store = match store::open() {
        Ok(s) => s,
        Err(_) => return false,
    };

    let project_id = session::project_id();
    let meta = SessionMeta {
        source: "oo".into(),
        session: session::session_id(),
        command: command.into(),
        timestamp: now_epoch(),
    };

    // Lazy TTL cleanup (best-effort)
    let _ = store.cleanup_stale(&project_id, 86400);

    store.index(&project_id, content, &meta).is_ok()
}

pub fn cmd_recall(query: &str, full: bool) -> i32 {
    crate::recall_display::cmd_recall(query, full)
}

pub fn cmd_forget() -> i32 {
    let mut store = match store::open() {
        Ok(s) => s,
        Err(e) => {
            eprintln!("oo: {e}");
            return 1;
        }
    };

    let project_id = session::project_id();

    match store.delete_project(&project_id) {
        Ok(count) => {
            println!("Cleared project data ({count} entries)");
            0
        }
        Err(e) => {
            eprintln!("oo: {e}");
            1
        }
    }
}

pub fn cmd_learn(args: &[String], hint: Option<&str>) -> i32 {
    if args.is_empty() {
        eprintln!("oo: learn requires a command");
        return 1;
    }

    // Run the command normally first
    let output = match exec::run(args) {
        Ok(o) => o,
        Err(e) => {
            eprintln!("oo: {e}");
            return 1;
        }
    };

    let exit_code = output.exit_code;
    let command = args.join(" ");
    let merged = output.merged_lossy();
    let original_size = merged.len();

    // Show normal oo output first (builtins only — project/user patterns are
    // intentionally not consulted here; see issue #151)
    let classification = classify::classify(&output, &command, pattern::builtins());
    render_classification(&classification, &command, original_size);

    // Print provider before spawning so the user sees it in the foreground
    let config = learn::load_learn_config().unwrap_or_else(|e| {
        eprintln!("oo: config error: {e}");
        learn::LearnConfig::default()
    });
    eprintln!(
        "  [learning pattern for \"{}\" ({})]",
        classify::label(&command),
        config.provider
    );

    // Spawn background learn process
    if let Err(e) = learn::spawn_background(&command, &merged, exit_code, hint) {
        eprintln!("oo: learn failed: {e}");
    }

    exit_code
}

/// Write a one-line status entry to the learn status file.
///
/// Called by the background process after successfully saving a pattern so
/// the NEXT foreground invocation can display the result.
pub fn write_learn_status(
    status_path: &Path,
    cmd_name: &str,
    pattern_path: &Path,
) -> Result<(), std::io::Error> {
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(status_path)?;
    writeln!(
        file,
        "learned pattern for {} → {}",
        cmd_name,
        pattern_path.display()
    )
}

/// Write a one-line failure entry to the learn status file.
///
/// Called by the background process when `run_learn` returns `Err`, so the
/// NEXT foreground invocation can display the error.
pub fn write_learn_status_failure(
    status_path: &Path,
    cmd_name: &str,
    error_msg: &str,
) -> Result<(), std::io::Error> {
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(status_path)?;
    let first_line = error_msg.lines().next().unwrap_or(error_msg);
    writeln!(file, "FAILED {cmd_name}: {first_line}")
}

/// Check for a pending learn-status file, print its contents to stderr, then
/// delete the file.  Called early in each foreground invocation.
pub fn check_and_clear_learn_status(status_path: &Path) {
    if let Ok(content) = std::fs::read_to_string(status_path) {
        for line in content.lines() {
            if let Some(rest) = line.strip_prefix("FAILED ") {
                // Format: "FAILED cmd-name: error message"
                if let Some((cmd, msg)) = rest.split_once(": ") {
                    eprintln!("oo: learn failed for {cmd} — {msg}");
                } else {
                    eprintln!("oo: learn failed — {rest}");
                }
            } else {
                eprintln!("oo: {line}");
            }
        }
        let _ = std::fs::remove_file(status_path);
    }
}

/// Rewrite a command via `oo rewrite` for agent hooks: print the `oo`-prefixed
/// form on stdout (exit 0) when at least one segment has an oo pattern, or
/// print nothing and return 1 otherwise. Never executes the command.
pub fn cmd_rewrite(command: &str) -> i32 {
    match rewrite::rewrite(command, &rewrite::PATTERNS) {
        Some(rewritten) => {
            println!("{rewritten}");
            0
        }
        None => 1,
    }
}

/// List patterns from both project-local and user config directories.
pub fn cmd_patterns() -> i32 {
    self::commands_patterns::cmd_patterns()
}

/// List learned pattern files from a single directory (legacy test helper).
pub fn cmd_patterns_in(dir: &Path) -> i32 {
    self::commands_patterns::cmd_patterns_in(dir)
}

/// Print pattern entries from a single directory, returning true if any were found.
///
/// Each line is printed with a two-space indent so callers can add section headers.
pub fn list_patterns_in(dir: &Path) -> bool {
    self::commands_patterns::list_patterns_in(dir)
}

pub fn cmd_help(cmd: &str) -> i32 {
    match help::lookup(cmd) {
        Ok(text) => {
            print!("{text}");
            0
        }
        Err(e) => {
            eprintln!("oo: {e}");
            1
        }
    }
}

pub fn cmd_init(mode: InitMode) -> i32 {
    match &mode {
        InitMode::Format(format) => match init::run(*format) {
            Ok(()) => 0,
            Err(e) => {
                eprintln!("oo: {e}");
                1
            }
        },
        InitMode::Pi { global } => {
            let Ok(cwd) = std::env::current_dir() else {
                eprintln!("oo: cannot determine working directory");
                return 1;
            };
            match init_pi::run(&cwd, *global) {
                Ok(()) => 0,
                Err(e) => {
                    eprintln!("oo: {e}");
                    1
                }
            }
        }
        InitMode::ClaudeCode { global } => match std::env::current_dir().map_err(Error::from) {
            Err(e) => {
                eprintln!("oo: {e}");
                1
            }
            Ok(cwd) => match crate::hook::claude_settings_path(&cwd, *global) {
                Err(e) => {
                    eprintln!("oo: {e}");
                    1
                }
                Ok(path) => match crate::hook::merge_oo_hook(&path) {
                    Ok(_) => {
                        println!(
                            "Installed `oo hook claude` PreToolUse hook in {}",
                            path.display()
                        );
                        println!("Uninstall: remove the `oo hook claude` entry from that file.");
                        0
                    }
                    Err(e) => {
                        eprintln!("oo: {e}");
                        1
                    }
                },
            },
        },
    }
}

/// Entry point for `oo hook <agent>`: dispatch to the agent-specific stdin
/// processor. `claude` reads the PreToolUse JSON on stdin and rewrites Bash
/// commands (issue #172); anything else errors. The claude processor is
/// fail-open and returns 0.
pub fn cmd_hook(agent: &str) -> i32 {
    match agent {
        "claude" => crate::hook::cmd_hook_claude(),
        other => {
            eprintln!("oo: unknown hook agent '{other}'; supported hook agents: claude");
            1
        }
    }
}

#[cfg(test)]
#[path = "commands_tests.rs"]
mod tests;