ptuf 0.5.0

PreToolUseFilter: a generic guardrail layer for 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
//! `ptuf init cline` — install ptuf as a Cline `PreToolUse` file hook.
//!
//! Unlike the other host adapters, Cline file hooks are *executable
//! scripts* rather than command strings registered in a config file.
//! The installer therefore writes a small wrapper script that `exec`s
//! `<ptuf> hook cline`:
//!
//! - repo-local (preferred): `<repo>/.clinerules/hooks/PreToolUse` on
//!   Unix / macOS, `PreToolUse.ps1` on Windows.
//! - global fallback (no repo root): `~/Documents/Cline/Hooks/PreToolUse`.
//!
//! Cline identifies a hook purely by its file name within the hooks
//! directory, so an existing `PreToolUse` that ptuf does not recognise
//! is never silently overwritten — that surfaces as
//! [`InitError::HookFileConflict`]. A wrapper ptuf already manages is
//! re-rendered idempotently so the embedded binary path stays current.

use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};

use super::{InitError, InstallOutcome, InstallPath, InstallStatus};

/// Marker comment embedded in every ptuf-managed Cline wrapper. Its
/// presence is what distinguishes a wrapper ptuf may rewrite from a
/// hand-written hook that must not be clobbered.
const MANAGED_MARKER: &str = "ptuf-managed: cline PreToolUse";

/// Matcher recorded in [`InstallOutcome`] for the rendered summary.
/// Cline file hooks do not use a regex matcher — the hook fires for
/// every `PreToolUse` event — so this is purely descriptive.
pub const DEFAULT_MATCHER: &str = "PreToolUse";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetPaths {
    /// Absolute path of the `PreToolUse` wrapper script to install.
    pub hook_path: PathBuf,
    /// `true` when the target is the `~/Documents/Cline/Hooks` global
    /// fallback rather than a repo-local `.clinerules/hooks` directory.
    pub global: bool,
}

/// Try `std::env::current_exe()`. Falls back to the literal `"ptuf"`.
pub fn detect_binary() -> String {
    super::detect_binary_impl()
}

/// File name of the Cline `PreToolUse` hook for the current platform.
fn cline_hook_file_name() -> &'static str {
    if cfg!(windows) {
        "PreToolUse.ps1"
    } else {
        "PreToolUse"
    }
}

/// Resolve the `PreToolUse` wrapper path Cline should be configured
/// against.
///
/// Prefers the repo-local `<repo>/.clinerules/hooks/PreToolUse` when the
/// caller is inside a git working tree; otherwise falls back to the
/// global `~/Documents/Cline/Hooks/PreToolUse`. Returns
/// [`InitError::HomeNotSet`] when neither a repo root nor `$HOME` is
/// available.
pub fn resolve_paths(start: Option<&Path>) -> Result<TargetPaths, InitError> {
    let file_name = cline_hook_file_name();
    if let Some(root) = start.and_then(crate::config::repo::discover) {
        return Ok(TargetPaths {
            hook_path: root.join(".clinerules/hooks").join(file_name),
            global: false,
        });
    }
    let home = std::env::var_os("HOME").ok_or(InitError::HomeNotSet)?;
    Ok(TargetPaths {
        hook_path: PathBuf::from(home)
            .join("Documents/Cline/Hooks")
            .join(file_name),
        global: true,
    })
}

pub fn install(
    targets: &TargetPaths,
    ptuf_binary: &str,
    dry_run: bool,
) -> Result<InstallOutcome, InitError> {
    let command = format!("{ptuf_binary} hook cline");
    let desired = render_wrapper(ptuf_binary);

    let status = match fs::read(&targets.hook_path) {
        Ok(existing) if !is_ptuf_managed(&existing) => {
            return Err(InitError::HookFileConflict {
                path: targets.hook_path.clone(),
            });
        },
        Ok(existing) if existing == desired => InstallStatus::AlreadyPresent,
        Ok(_) => apply(&targets.hook_path, &desired, dry_run)?,
        Err(e) if e.kind() == ErrorKind::NotFound => apply(&targets.hook_path, &desired, dry_run)?,
        Err(e) => {
            return Err(InitError::Io {
                path: targets.hook_path.clone(),
                source: e,
            });
        },
    };

    let label = if targets.global {
        "hook (global)"
    } else {
        "hook"
    };
    Ok(InstallOutcome {
        status,
        agent: "cline",
        paths: vec![InstallPath {
            label,
            path: targets.hook_path.clone(),
        }],
        matcher: DEFAULT_MATCHER.to_string(),
        command,
    })
}

/// Write `desired` to `path` unless this is a dry run.
fn apply(path: &Path, desired: &[u8], dry_run: bool) -> Result<InstallStatus, InitError> {
    if dry_run {
        return Ok(InstallStatus::WouldInstall);
    }
    write_executable_atomically(path, desired)?;
    Ok(InstallStatus::Installed)
}

/// Render the `PreToolUse` wrapper script for the current platform.
///
/// The Unix wrapper `exec`s ptuf so the hook process is replaced and the
/// exit code passes straight through; the PowerShell wrapper forwards
/// `$LASTEXITCODE` explicitly since `&` does not replace the process.
fn render_wrapper(ptuf_binary: &str) -> Vec<u8> {
    if cfg!(windows) {
        format!(
            "# {MANAGED_MARKER}\n& {} hook cline\nexit $LASTEXITCODE\n",
            quote_powershell(ptuf_binary),
        )
        .into_bytes()
    } else {
        format!(
            "#!/usr/bin/env sh\n# {MANAGED_MARKER}\nexec {} hook cline\n",
            quote_sh(ptuf_binary),
        )
        .into_bytes()
    }
}

/// Single-quote `s` for a POSIX shell: wrap in `'...'` and rewrite every
/// embedded `'` as `'\''`.
fn quote_sh(s: &str) -> String {
    format!("'{}'", s.replace('\'', "'\\''"))
}

/// Single-quote `s` for PowerShell: wrap in `'...'` and double every
/// embedded `'`.
fn quote_powershell(s: &str) -> String {
    format!("'{}'", s.replace('\'', "''"))
}

/// A `PreToolUse` file is ptuf's to rewrite when it carries our managed
/// marker, or otherwise visibly invokes `ptuf hook cline`.
fn is_ptuf_managed(bytes: &[u8]) -> bool {
    let text = String::from_utf8_lossy(bytes);
    text.contains(MANAGED_MARKER) || text.contains("ptuf hook cline")
}

fn write_executable_atomically(path: &Path, bytes: &[u8]) -> Result<(), InitError> {
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        fs::create_dir_all(parent).map_err(|e| InitError::Io {
            path: parent.to_path_buf(),
            source: e,
        })?;
    }
    let tmp = sibling_temp_path(path);
    crate::init::write_executable(&tmp, bytes).map_err(|e| InitError::Io {
        path: tmp.clone(),
        source: e,
    })?;
    fs::rename(&tmp, path).map_err(|e| InitError::Io {
        path: path.to_path_buf(),
        source: e,
    })
}

fn sibling_temp_path(path: &Path) -> PathBuf {
    super::sibling_install_tmp_path(path, "PreToolUse")
}

#[cfg(test)]
mod tests {

    use super::*;

    fn workdir(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "ptuf-init-cline-{}-{}-{}",
            tag,
            std::process::id(),
            line!()
        ));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn read(path: &Path) -> String {
        fs::read_to_string(path).unwrap()
    }

    fn repo_targets(dir: &Path) -> TargetPaths {
        TargetPaths {
            hook_path: dir.join(".clinerules/hooks").join(cline_hook_file_name()),
            global: false,
        }
    }

    #[test]
    fn resolve_paths_targets_repo_local_clinerules_hooks() {
        let dir = workdir("resolve-repo");
        fs::create_dir_all(dir.join(".git")).unwrap();
        let targets = resolve_paths(Some(dir.as_path())).unwrap();
        assert!(!targets.global);
        assert!(
            targets.hook_path.ends_with(".clinerules/hooks/PreToolUse")
                || targets
                    .hook_path
                    .ends_with(".clinerules/hooks/PreToolUse.ps1"),
            "got: {:?}",
            targets.hook_path,
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_paths_falls_back_to_global_cline_hooks_dir() {
        // Outside a repo, resolution reads $HOME for the global fallback.
        match resolve_paths(None) {
            Ok(targets) => {
                assert!(targets.global);
                assert!(
                    targets.hook_path.starts_with(
                        PathBuf::from(std::env::var_os("HOME").unwrap())
                            .join("Documents/Cline/Hooks"),
                    ),
                    "got: {:?}",
                    targets.hook_path,
                );
            },
            Err(InitError::HomeNotSet) => {},
            Err(other) => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn cline_hook_file_name_matches_platform() {
        let name = cline_hook_file_name();
        if cfg!(windows) {
            assert_eq!(name, "PreToolUse.ps1");
        } else {
            assert_eq!(name, "PreToolUse");
        }
    }

    #[test]
    fn install_writes_wrapper_with_marker_and_hook_command() {
        let dir = workdir("install-marker");
        let targets = repo_targets(&dir);
        let outcome = install(&targets, "/usr/local/bin/ptuf", false).unwrap();
        assert_eq!(outcome.status, InstallStatus::Installed);
        assert_eq!(outcome.agent, "cline");
        assert_eq!(outcome.matcher, "PreToolUse");
        let body = read(&targets.hook_path);
        assert!(
            body.contains("ptuf-managed: cline PreToolUse"),
            "body: {body}"
        );
        assert!(body.contains("hook cline"), "body: {body}");
        assert!(body.contains("/usr/local/bin/ptuf"), "body: {body}");
        let _ = fs::remove_dir_all(&dir);
    }

    #[cfg(unix)]
    #[test]
    fn install_marks_wrapper_executable() {
        use std::os::unix::fs::PermissionsExt;
        let dir = workdir("install-exec");
        let targets = repo_targets(&dir);
        install(&targets, "/usr/local/bin/ptuf", false).unwrap();
        let mode = fs::metadata(&targets.hook_path)
            .unwrap()
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(mode, 0o700, "wrapper must be owner-only executable");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn install_dry_run_reports_changes_without_writing() {
        let dir = workdir("dry-run");
        let targets = repo_targets(&dir);
        let outcome = install(&targets, "/usr/local/bin/ptuf", true).unwrap();
        assert_eq!(outcome.status, InstallStatus::WouldInstall);
        assert!(!targets.hook_path.exists());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn install_is_idempotent_when_wrapper_is_byte_identical() {
        let dir = workdir("idempotent");
        let targets = repo_targets(&dir);
        install(&targets, "/x/ptuf", false).unwrap();
        let before = read(&targets.hook_path);
        let outcome = install(&targets, "/x/ptuf", false).unwrap();
        assert_eq!(outcome.status, InstallStatus::AlreadyPresent);
        assert_eq!(before, read(&targets.hook_path));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn install_rewrites_managed_wrapper_when_binary_path_changes() {
        let dir = workdir("update-binary");
        let targets = repo_targets(&dir);
        install(&targets, "/old/ptuf", false).unwrap();
        let outcome = install(&targets, "/new/ptuf", false).unwrap();
        assert_eq!(outcome.status, InstallStatus::Installed);
        let body = read(&targets.hook_path);
        assert!(body.contains("/new/ptuf"), "body: {body}");
        assert!(!body.contains("/old/ptuf"), "body: {body}");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn install_dry_run_on_managed_wrapper_change_does_not_write() {
        let dir = workdir("dry-run-update");
        let targets = repo_targets(&dir);
        install(&targets, "/old/ptuf", false).unwrap();
        let before = read(&targets.hook_path);
        let outcome = install(&targets, "/new/ptuf", true).unwrap();
        assert_eq!(outcome.status, InstallStatus::WouldInstall);
        assert_eq!(before, read(&targets.hook_path), "dry-run must not rewrite");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn install_refuses_to_overwrite_unmanaged_hook() {
        let dir = workdir("conflict");
        let targets = repo_targets(&dir);
        fs::create_dir_all(targets.hook_path.parent().unwrap()).unwrap();
        fs::write(&targets.hook_path, "#!/bin/sh\necho hand-written\n").unwrap();
        let err = install(&targets, "/x/ptuf", false).unwrap_err();
        match err {
            InitError::HookFileConflict { path } => assert_eq!(path, targets.hook_path),
            other => panic!("expected HookFileConflict, got {other:?}"),
        }
        // The hand-written hook is left exactly as it was.
        assert_eq!(read(&targets.hook_path), "#!/bin/sh\necho hand-written\n");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn install_reports_io_error_when_hook_path_is_a_directory() {
        let dir = workdir("hook-is-dir");
        let hook_path = dir.join("PreToolUse");
        fs::create_dir_all(&hook_path).unwrap();
        let targets = TargetPaths {
            hook_path,
            global: false,
        };
        let err = install(&targets, "/x/ptuf", false).unwrap_err();
        assert!(matches!(err, InitError::Io { .. }), "got: {err:?}");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn install_global_outcome_labels_path_as_global() {
        let dir = workdir("global-label");
        let targets = TargetPaths {
            hook_path: dir.join("Documents/Cline/Hooks/PreToolUse"),
            global: true,
        };
        let outcome = install(&targets, "/x/ptuf", false).unwrap();
        assert_eq!(outcome.paths[0].label, "hook (global)");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn quote_sh_escapes_embedded_single_quotes() {
        assert_eq!(quote_sh("/p/ptuf"), "'/p/ptuf'");
        assert_eq!(quote_sh("/a'b/ptuf"), "'/a'\\''b/ptuf'");
    }

    #[test]
    fn quote_powershell_doubles_embedded_single_quotes() {
        assert_eq!(quote_powershell(r"C:\p\ptuf.exe"), r"'C:\p\ptuf.exe'");
        assert_eq!(quote_powershell("a'b"), "'a''b'");
    }

    #[test]
    fn is_ptuf_managed_recognises_marker_and_invocation() {
        assert!(is_ptuf_managed(b"# ptuf-managed: cline PreToolUse\n"));
        assert!(is_ptuf_managed(b"do ptuf hook cline now"));
        assert!(!is_ptuf_managed(b"#!/bin/sh\necho hello\n"));
        assert!(!is_ptuf_managed(&[0xff, 0xfe]));
    }

    #[test]
    fn detect_binary_delegates_to_shared_impl() {
        assert!(!detect_binary().is_empty());
    }
}