longline 0.15.2

System-installed safety hook for Claude Code
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
//! Shared test harness for longline integration tests.
//!
//! Provides two patterns:
//! 1. `TestEnv` builder -- isolated HOME/project dirs, no --config flag (uses embedded defaults)
//! 2. Standalone helper functions -- shared static HOME, uses --config pointing to rules/rules.yaml

// Many helpers in this module are shared across multiple test binaries; not all are used by every
// binary, so dead_code warnings are expected and intentional.
#![allow(dead_code)]

use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::OnceLock;

// ---------------------------------------------------------------------------
// RunResult
// ---------------------------------------------------------------------------

/// Captures exit code, stdout, and stderr from a longline invocation.
pub struct RunResult {
    pub exit_code: i32,
    pub stdout: String,
    pub stderr: String,
}

impl RunResult {
    /// Parse hook JSON stdout and return the permissionDecision value.
    pub fn decision(&self) -> String {
        let parsed: serde_json::Value = serde_json::from_str(&self.stdout).unwrap_or_else(|e| {
            panic!(
                "Failed to parse stdout as JSON: {e}\nstdout: {}\nstderr: {}",
                self.stdout, self.stderr
            )
        });
        parsed["hookSpecificOutput"]["permissionDecision"]
            .as_str()
            .unwrap_or_else(|| {
                panic!(
                    "Missing hookSpecificOutput.permissionDecision in: {}",
                    self.stdout
                )
            })
            .to_string()
    }

    /// Parse hook JSON stdout and return the permissionDecisionReason value.
    pub fn reason(&self) -> String {
        let parsed: serde_json::Value = serde_json::from_str(&self.stdout).unwrap_or_else(|e| {
            panic!(
                "Failed to parse stdout as JSON: {e}\nstdout: {}\nstderr: {}",
                self.stdout, self.stderr
            )
        });
        parsed["hookSpecificOutput"]["permissionDecisionReason"]
            .as_str()
            .unwrap_or_else(|| {
                panic!(
                    "Missing hookSpecificOutput.permissionDecisionReason in: {}",
                    self.stdout
                )
            })
            .to_string()
    }

    /// Assert that the decision matches `expected`, with a descriptive panic on failure.
    pub fn assert_decision(&self, expected: &str) {
        let actual = self.decision();
        assert_eq!(
            actual, expected,
            "Expected decision '{}' but got '{}'\nstdout: {}\nstderr: {}",
            expected, actual, self.stdout, self.stderr
        );
    }

    /// Assert that the reason contains `substring`.
    pub fn assert_reason_contains(&self, substring: &str) {
        let reason = self.reason();
        assert!(
            reason.contains(substring),
            "Expected reason to contain '{}' but got: {}\nstdout: {}\nstderr: {}",
            substring,
            reason,
            self.stdout,
            self.stderr
        );
    }

    /// Assert that the reason does NOT contain `substring`.
    pub fn assert_reason_not_contains(&self, substring: &str) {
        let reason = self.reason();
        assert!(
            !reason.contains(substring),
            "Expected reason to NOT contain '{}' but got: {}\nstdout: {}\nstderr: {}",
            substring,
            reason,
            self.stdout,
            self.stderr
        );
    }
}

// ---------------------------------------------------------------------------
// TestEnv builder
// ---------------------------------------------------------------------------

/// Builder for constructing a `TestEnv` with optional project/global configs.
pub struct TestEnvBuilder {
    project_config: Option<String>,
    global_config: Option<String>,
}

/// An isolated test environment with its own HOME (and optionally a project dir).
/// Temp directories are cleaned up on drop.
pub struct TestEnv {
    home_dir: tempfile::TempDir,
    project_dir: Option<tempfile::TempDir>,
}

impl TestEnv {
    /// Start building a new test environment.
    #[allow(clippy::new_ret_no_self)]
    pub fn new() -> TestEnvBuilder {
        TestEnvBuilder {
            project_config: None,
            global_config: None,
        }
    }

    /// Run the longline binary in hook mode (no --config flag, uses embedded defaults).
    /// Sends a Bash tool hook JSON on stdin.
    pub fn run_hook(&self, command: &str) -> RunResult {
        self.run_hook_with_flags(command, &[])
    }

    /// Run the longline binary in hook mode with extra CLI flags.
    pub fn run_hook_with_flags(&self, command: &str, extra_args: &[&str]) -> RunResult {
        let cwd = self
            .project_dir
            .as_ref()
            .map(|d| d.path().to_string_lossy().to_string())
            .unwrap_or_else(|| "/tmp".to_string());

        let input = serde_json::json!({
            "hook_event_name": "PreToolUse",
            "tool_name": "Bash",
            "tool_input": { "command": command },
            "session_id": "test-session",
            "cwd": cwd
        });

        let home = self.home_dir.path().to_string_lossy().to_string();
        let mut child = Command::new(longline_bin())
            .args(extra_args)
            .env("HOME", &home)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("Failed to spawn longline");

        child
            .stdin
            .take()
            .unwrap()
            .write_all(input.to_string().as_bytes())
            .unwrap();

        let output = child.wait_with_output().unwrap();
        RunResult {
            exit_code: output.status.code().unwrap_or(-1),
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
        }
    }

    /// Run the longline binary in hook mode for a non-Bash tool.
    pub fn run_hook_tool(&self, tool_name: &str, command: &str) -> RunResult {
        let cwd = self
            .project_dir
            .as_ref()
            .map(|d| d.path().to_string_lossy().to_string())
            .unwrap_or_else(|| "/tmp".to_string());

        let input = serde_json::json!({
            "hook_event_name": "PreToolUse",
            "tool_name": tool_name,
            "tool_input": { "command": command },
            "session_id": "test-session",
            "cwd": cwd
        });

        let home = self.home_dir.path().to_string_lossy().to_string();
        let mut child = Command::new(longline_bin())
            .env("HOME", &home)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("Failed to spawn longline");

        child
            .stdin
            .take()
            .unwrap()
            .write_all(input.to_string().as_bytes())
            .unwrap();

        let output = child.wait_with_output().unwrap();
        RunResult {
            exit_code: output.status.code().unwrap_or(-1),
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
        }
    }

    /// Run a longline subcommand (rules, check, files, etc.).
    /// If a project dir exists and no --dir is in args, auto-adds --dir.
    pub fn run_subcommand(&self, args: &[&str]) -> RunResult {
        let home = self.home_dir.path().to_string_lossy().to_string();
        let has_dir_flag = args.contains(&"--dir");

        let mut full_args: Vec<&str> = args.to_vec();

        // We need to own the string so the borrow lives long enough
        let project_path_str;
        if !has_dir_flag {
            if let Some(ref project) = self.project_dir {
                project_path_str = project.path().to_string_lossy().to_string();
                full_args.push("--dir");
                full_args.push(&project_path_str);
            }
        }

        let child = Command::new(longline_bin())
            .args(&full_args)
            .env("HOME", &home)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("Failed to spawn longline");

        let output = child.wait_with_output().unwrap();
        RunResult {
            exit_code: output.status.code().unwrap_or(-1),
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
        }
    }

    /// Returns the project directory path (panics if no project dir was configured).
    pub fn project_path(&self) -> &Path {
        self.project_dir
            .as_ref()
            .expect("No project directory configured for this TestEnv")
            .path()
    }

    /// Returns the HOME directory path.
    pub fn home_path(&self) -> &Path {
        self.home_dir.path()
    }
}

impl TestEnvBuilder {
    /// Set the project config content (written to `.claude/longline.yaml`).
    pub fn with_project_config(mut self, yaml: &str) -> Self {
        self.project_config = Some(yaml.to_string());
        self
    }

    /// Set the global config content (written to `~/.config/longline/longline.yaml`).
    pub fn with_global_config(mut self, yaml: &str) -> Self {
        self.global_config = Some(yaml.to_string());
        self
    }

    /// Build the test environment, creating temp dirs and writing config files.
    pub fn build(self) -> TestEnv {
        // Create HOME temp dir
        let home_dir = tempfile::TempDir::new().expect("Failed to create temp HOME dir");

        // Always create fake AI judge config so tests never invoke a real AI judge
        let config_dir = home_dir.path().join(".config").join("longline");
        std::fs::create_dir_all(&config_dir).unwrap();
        std::fs::write(
            config_dir.join("ai-judge.yaml"),
            "command: /definitely-not-a-real-ai-judge-command-12345\ntimeout: 1\n",
        )
        .unwrap();

        // Write global config if provided
        if let Some(ref yaml) = self.global_config {
            std::fs::write(config_dir.join("longline.yaml"), yaml).unwrap();
        }

        // Create project dir if project config was provided
        let project_dir = if let Some(ref yaml) = self.project_config {
            let dir = tempfile::TempDir::new().expect("Failed to create temp project dir");
            std::fs::create_dir_all(dir.path().join(".git")).unwrap();
            let claude_dir = dir.path().join(".claude");
            std::fs::create_dir_all(&claude_dir).unwrap();
            std::fs::write(claude_dir.join("longline.yaml"), yaml).unwrap();
            Some(dir)
        } else {
            None
        };

        TestEnv {
            home_dir,
            project_dir,
        }
    }
}

// ---------------------------------------------------------------------------
// Standalone helper functions (shared static HOME, uses --config)
// ---------------------------------------------------------------------------

/// Path to the compiled longline binary.
pub fn longline_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("target")
        .join("debug")
        .join("longline")
}

/// Path to the rules/rules.yaml file in the repo.
pub fn rules_path() -> String {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("rules")
        .join("rules.yaml")
        .to_string_lossy()
        .to_string()
}

/// Shared static HOME directory with a fake AI judge config.
/// Re-used across tests that don't need config isolation.
pub fn static_test_home() -> &'static PathBuf {
    static HOME: OnceLock<PathBuf> = OnceLock::new();
    HOME.get_or_init(|| {
        let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("target")
            .join("test-tmp")
            .join("common-home");
        std::fs::create_dir_all(&dir).unwrap();

        let config_dir = dir.join(".config").join("longline");
        std::fs::create_dir_all(&config_dir).unwrap();
        std::fs::write(
            config_dir.join("ai-judge.yaml"),
            "command: /definitely-not-a-real-ai-judge-command-12345\ntimeout: 1\n",
        )
        .unwrap();

        dir
    })
}

/// Run longline in hook mode with --config pointing to rules/rules.yaml.
pub fn run_hook(tool_name: &str, command: &str) -> RunResult {
    run_hook_with_flags(tool_name, command, &[])
}

/// Run longline in hook mode with --config and extra CLI flags.
pub fn run_hook_with_flags(tool_name: &str, command: &str, extra_args: &[&str]) -> RunResult {
    let input = serde_json::json!({
        "hook_event_name": "PreToolUse",
        "tool_name": tool_name,
        "tool_input": { "command": command },
        "session_id": "test-session",
        "cwd": "/tmp"
    });

    let config = rules_path();
    let mut args = vec!["--config", &config];
    args.extend_from_slice(extra_args);

    let home = static_test_home().to_string_lossy().to_string();
    let mut child = Command::new(longline_bin())
        .args(&args)
        .env("HOME", &home)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn longline");

    child
        .stdin
        .take()
        .unwrap()
        .write_all(input.to_string().as_bytes())
        .unwrap();

    let output = child.wait_with_output().unwrap();
    RunResult {
        exit_code: output.status.code().unwrap_or(-1),
        stdout: String::from_utf8_lossy(&output.stdout).to_string(),
        stderr: String::from_utf8_lossy(&output.stderr).to_string(),
    }
}

/// Run longline in hook mode with a specific config file path.
pub fn run_hook_with_config(tool_name: &str, command: &str, config: &str) -> RunResult {
    let input = serde_json::json!({
        "hook_event_name": "PreToolUse",
        "tool_name": tool_name,
        "tool_input": { "command": command },
        "session_id": "test-session",
        "cwd": "/tmp"
    });

    let home = static_test_home().to_string_lossy().to_string();
    let mut child = Command::new(longline_bin())
        .args(["--config", config])
        .env("HOME", &home)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn longline");

    child
        .stdin
        .take()
        .unwrap()
        .write_all(input.to_string().as_bytes())
        .unwrap();

    let output = child.wait_with_output().unwrap();
    RunResult {
        exit_code: output.status.code().unwrap_or(-1),
        stdout: String::from_utf8_lossy(&output.stdout).to_string(),
        stderr: String::from_utf8_lossy(&output.stderr).to_string(),
    }
}

/// Run longline in hook mode for a Read tool call with --config pointing to rules/rules.yaml.
pub fn run_hook_read(file_path: &str) -> RunResult {
    let input = serde_json::json!({
        "hook_event_name": "PreToolUse",
        "tool_name": "Read",
        "tool_input": { "file_path": file_path },
        "session_id": "test-session",
        "cwd": "/tmp"
    });

    let config = rules_path();
    let home = static_test_home().to_string_lossy().to_string();
    let mut child = Command::new(longline_bin())
        .args(["--config", &config])
        .env("HOME", &home)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn longline");

    child
        .stdin
        .take()
        .unwrap()
        .write_all(input.to_string().as_bytes())
        .unwrap();

    let output = child.wait_with_output().unwrap();
    RunResult {
        exit_code: output.status.code().unwrap_or(-1),
        stdout: String::from_utf8_lossy(&output.stdout).to_string(),
        stderr: String::from_utf8_lossy(&output.stderr).to_string(),
    }
}

/// Run longline in hook mode for a Grep tool call with --config pointing to rules/rules.yaml.
pub fn run_hook_grep(pattern: &str, path: Option<&str>) -> RunResult {
    let mut tool_input = serde_json::json!({ "pattern": pattern });
    if let Some(p) = path {
        tool_input["path"] = serde_json::Value::String(p.to_string());
    }

    let input = serde_json::json!({
        "hook_event_name": "PreToolUse",
        "tool_name": "Grep",
        "tool_input": tool_input,
        "session_id": "test-session",
        "cwd": "/tmp"
    });

    let config = rules_path();
    let home = static_test_home().to_string_lossy().to_string();
    let mut child = Command::new(longline_bin())
        .args(["--config", &config])
        .env("HOME", &home)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn longline");

    child
        .stdin
        .take()
        .unwrap()
        .write_all(input.to_string().as_bytes())
        .unwrap();

    let output = child.wait_with_output().unwrap();
    RunResult {
        exit_code: output.status.code().unwrap_or(-1),
        stdout: String::from_utf8_lossy(&output.stdout).to_string(),
        stderr: String::from_utf8_lossy(&output.stderr).to_string(),
    }
}

/// Run longline in hook mode for a Glob tool call with --config pointing to rules/rules.yaml.
pub fn run_hook_glob(pattern: &str, path: Option<&str>) -> RunResult {
    let mut tool_input = serde_json::json!({ "pattern": pattern });
    if let Some(p) = path {
        tool_input["path"] = serde_json::Value::String(p.to_string());
    }

    let input = serde_json::json!({
        "hook_event_name": "PreToolUse",
        "tool_name": "Glob",
        "tool_input": tool_input,
        "session_id": "test-session",
        "cwd": "/tmp"
    });

    let config = rules_path();
    let home = static_test_home().to_string_lossy().to_string();
    let mut child = Command::new(longline_bin())
        .args(["--config", &config])
        .env("HOME", &home)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn longline");

    child
        .stdin
        .take()
        .unwrap()
        .write_all(input.to_string().as_bytes())
        .unwrap();

    let output = child.wait_with_output().unwrap();
    RunResult {
        exit_code: output.status.code().unwrap_or(-1),
        stdout: String::from_utf8_lossy(&output.stdout).to_string(),
        stderr: String::from_utf8_lossy(&output.stderr).to_string(),
    }
}

/// Run a longline subcommand with the shared static HOME.
pub fn run_subcommand(args: &[&str]) -> RunResult {
    let home = static_test_home().to_string_lossy().to_string();
    run_subcommand_with_home(args, &home)
}

/// Run a longline subcommand with a specific HOME directory.
pub fn run_subcommand_with_home(args: &[&str], home: &str) -> RunResult {
    let child = Command::new(longline_bin())
        .args(args)
        .env("HOME", home)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn longline");

    let output = child.wait_with_output().unwrap();
    RunResult {
        exit_code: output.status.code().unwrap_or(-1),
        stdout: String::from_utf8_lossy(&output.stdout).to_string(),
        stderr: String::from_utf8_lossy(&output.stderr).to_string(),
    }
}