apm-core 0.1.24

Core library for APM — a git-native project manager for parallel 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
use std::path::{Component, Path, PathBuf};
use globset::{Glob, GlobSetBuilder};

pub struct PathGuard {
    worktree: PathBuf,             // canonicalised APM_TICKET_WORKTREE
    write_protected: Vec<PathBuf>, // APM_BIN, APM_SYSTEM_PROMPT_FILE, APM_USER_MESSAGE_FILE
}

impl PathGuard {
    pub fn new(
        worktree: &Path,
        read_allow_patterns: &[String],
        write_protected: &[PathBuf],
    ) -> anyhow::Result<Self> {
        let worktree = std::fs::canonicalize(worktree)
            .unwrap_or_else(|_| canonicalize_lenient(worktree));

        // Validate read_allow patterns so callers get an error on bad globs,
        // even though read-only commands are always permitted (they produce no
        // write targets that need checking).
        let mut builder = GlobSetBuilder::new();
        for pattern in read_allow_patterns {
            let expanded = expand_home_str(pattern);
            builder.add(Glob::new(&expanded).map_err(|e| anyhow::anyhow!("invalid glob {pattern:?}: {e}"))?);
        }
        builder.build().map_err(|e| anyhow::anyhow!("glob build failed: {e}"))?;

        let write_protected = write_protected
            .iter()
            .map(|p| std::fs::canonicalize(p).unwrap_or_else(|_| canonicalize_lenient(p)))
            .collect();

        Ok(PathGuard { worktree, write_protected })
    }

    pub fn check_write(&self, path: &Path) -> Result<(), String> {
        let resolved = canonicalize_lenient(path);

        // write_protected entries are always rejected — even if inside worktree
        if self.write_protected.iter().any(|p| p == &resolved) {
            return Err(rejection_msg(path, &self.worktree));
        }

        if resolved.starts_with(&self.worktree) {
            return Ok(());
        }

        Err(rejection_msg(path, &self.worktree))
    }

    pub fn check_bash(&self, cmd: &str) -> Result<(), String> {
        let targets = detect_write_targets(cmd);
        for target_str in targets {
            let path = PathBuf::from(&target_str);
            self.check_write(&path)?;
        }
        Ok(())
    }
}

/// Build a human-readable rejection message.
fn rejection_msg(requested: &Path, worktree: &Path) -> String {
    format!(
        "path outside ticket worktree; isolation enforced by APM wrapper.\n  Requested: {}\n  APM_TICKET_WORKTREE = {}",
        requested.display(),
        worktree.display()
    )
}

/// Canonicalize a path, following symlinks for components that exist on disk
/// and appending non-existent components lexically.
///
/// This ensures that existing intermediate symlinks are resolved while still
/// accepting paths to files that do not yet exist (e.g. the target of a Write
/// call that would create a new file).
pub fn canonicalize_lenient(path: &Path) -> PathBuf {
    let mut result = PathBuf::new();

    for component in path.components() {
        match component {
            Component::Prefix(p) => {
                result = PathBuf::from(p.as_os_str());
            }
            Component::RootDir => {
                result.push(component);
            }
            Component::CurDir => {
                // skip "."
            }
            Component::ParentDir => {
                // Try to canonicalize the path with ".." so the OS resolves symlinks
                let candidate = result.join("..");
                if candidate.exists() {
                    result = std::fs::canonicalize(&candidate).unwrap_or(candidate);
                } else {
                    // Non-existent parent: lexically remove the last component
                    result.pop();
                }
            }
            Component::Normal(_) => {
                result.push(component);
                if result.exists() {
                    result = std::fs::canonicalize(&result).unwrap_or_else(|_| result.clone());
                }
            }
        }
    }

    result
}

/// Expand `~` at the start of a path string to the user's home directory.
fn expand_home_str(s: &str) -> String {
    if let Some(rest) = s.strip_prefix("~/") {
        if let Ok(home) = std::env::var("HOME") {
            if !home.is_empty() {
                return format!("{home}/{rest}");
            }
        }
    }
    s.to_string()
}

/// Expand `~/` prefix to the home directory.
fn expand_home(s: &str) -> String {
    expand_home_str(s)
}

fn is_path_token(s: &str) -> bool {
    s.starts_with('/') || s.starts_with("~/")
}

fn is_shell_sep(s: &str) -> bool {
    matches!(s, ";" | "&&" | "||" | "|" | "&")
}

/// Detect write-target paths from a bash command string.
///
/// Handles:
/// - `>` and `>>` redirect targets (space-separated and embedded)
/// - `tee` first non-flag argument
/// - `cp` / `mv` last non-flag path argument (the destination)
/// - `truncate` path argument
///
/// Known false negatives (documented limitation, not in scope):
/// - Paths stored in shell variables: `OUT=/x; echo foo > "$OUT"`
/// - Subshell expansion: `echo foo > $(cat /tmp/path)`
/// - eval: `eval "echo foo > /x"`
fn detect_write_targets(cmd: &str) -> Vec<String> {
    let mut targets = Vec::new();

    // Phase 1: scan for redirect operators (>, >>) at the character level
    detect_redirects(cmd, &mut targets);

    // Phase 2: command-specific write patterns via token scan
    let tokens: Vec<&str> = cmd.split_whitespace().collect();
    detect_command_writes(&tokens, &mut targets);

    targets
}

/// Scan the command string character by character for `>` and `>>` operators,
/// skipping quoted strings, and collecting the path that follows.
fn detect_redirects(cmd: &str, targets: &mut Vec<String>) {
    let chars: Vec<char> = cmd.chars().collect();
    let n = chars.len();
    let mut i = 0;

    while i < n {
        let c = chars[i];

        // Skip single-quoted strings
        if c == '\'' {
            i += 1;
            while i < n && chars[i] != '\'' {
                i += 1;
            }
            if i < n {
                i += 1;
            }
            continue;
        }

        // Skip double-quoted strings
        if c == '"' {
            i += 1;
            while i < n && chars[i] != '"' {
                if chars[i] == '\\' {
                    i += 1; // skip escaped character
                }
                if i < n {
                    i += 1;
                }
            }
            if i < n {
                i += 1;
            }
            continue;
        }

        if c == '>' {
            let is_double = i + 1 < n && chars[i + 1] == '>';
            let advance = if is_double { 2 } else { 1 };

            // Skip whitespace after the redirect operator
            let mut j = i + advance;
            while j < n && chars[j] == ' ' {
                j += 1;
            }

            // Collect path token if it starts with / or ~/
            if j < n
                && (chars[j] == '/'
                    || (chars[j] == '~' && j + 1 < n && chars[j + 1] == '/'))
            {
                let path_start = j;
                while j < n
                    && !chars[j].is_whitespace()
                    && !matches!(chars[j], ';' | '|' | '&' | '(')
                {
                    j += 1;
                }
                let path: String = chars[path_start..j].iter().collect();
                targets.push(expand_home(&path));
            }

            i += advance;
            continue;
        }

        i += 1;
    }
}

/// Scan tokenised command for command-specific write patterns.
fn detect_command_writes(tokens: &[&str], targets: &mut Vec<String>) {
    let n = tokens.len();
    let mut i = 0;

    while i < n {
        let tok = tokens[i];

        match tok {
            "tee" => {
                // First non-flag absolute path argument
                for j in (i + 1)..n {
                    let arg = tokens[j];
                    if is_shell_sep(arg) {
                        break;
                    }
                    if arg.starts_with('-') {
                        continue;
                    }
                    if is_path_token(arg) {
                        targets.push(expand_home(arg));
                    }
                    break;
                }
            }
            "cp" | "mv" => {
                // Destination = last non-flag absolute path argument
                let mut last: Option<String> = None;
                for j in (i + 1)..n {
                    let arg = tokens[j];
                    if is_shell_sep(arg) {
                        break;
                    }
                    if !arg.starts_with('-') && is_path_token(arg) {
                        last = Some(expand_home(arg));
                    }
                }
                if let Some(p) = last {
                    targets.push(p);
                }
            }
            "truncate" => {
                let mut j = i + 1;
                while j < n {
                    let arg = tokens[j];
                    if is_shell_sep(arg) {
                        break;
                    }
                    // -s / --size each consume the next token as the size value
                    if arg == "-s" || arg == "--size" {
                        j += 2;
                        continue;
                    }
                    if !arg.starts_with('-') && is_path_token(arg) {
                        targets.push(expand_home(arg));
                    }
                    j += 1;
                }
            }
            _ => {}
        }

        i += 1;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ---- canonicalize_lenient ----

    #[test]
    fn canonicalize_lenient_absolute_existing() {
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().to_path_buf();
        let result = canonicalize_lenient(&p);
        // Should resolve the tempdir path (may follow symlinks)
        assert!(result.is_absolute());
    }

    #[test]
    fn canonicalize_lenient_nonexistent_leaf() {
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("nonexistent.txt");
        let result = canonicalize_lenient(&p);
        // Parent must be resolved; leaf appended lexically
        assert!(result.is_absolute());
        assert_eq!(result.file_name().unwrap().to_str().unwrap(), "nonexistent.txt");
    }

    #[test]
    fn canonicalize_lenient_dotdot_inside_existing() {
        let tmp = tempfile::tempdir().unwrap();
        let sub = tmp.path().join("sub");
        std::fs::create_dir(&sub).unwrap();
        // sub/.. == tmp.path()
        let candidate = sub.join("..").join("other.txt");
        let result = canonicalize_lenient(&candidate);
        // result should be tmp.path()/other.txt
        let expected_parent = std::fs::canonicalize(tmp.path()).unwrap();
        assert_eq!(result.parent().unwrap(), expected_parent);
    }

    #[test]
    fn canonicalize_lenient_dotdot_escape_stays_out() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join("worktree");
        let sub = wt.join("subdir");
        std::fs::create_dir_all(&sub).unwrap();
        // worktree/subdir/../../etc/passwd
        let path = sub.join("..").join("..").join("etc").join("passwd");
        let result = canonicalize_lenient(&path);
        // Should resolve to tmp.path()/etc/passwd — outside wt
        let canon_wt = std::fs::canonicalize(&wt).unwrap();
        assert!(!result.starts_with(&canon_wt));
    }

    #[test]
    fn canonicalize_lenient_symlink_inside_worktree_resolves_outside() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join("wt");
        std::fs::create_dir(&wt).unwrap();
        let outside = tmp.path().join("outside");
        std::fs::create_dir(&outside).unwrap();
        let link = wt.join("link");
        std::os::unix::fs::symlink(&outside, &link).unwrap();
        let target = link.join("secret.txt");
        let result = canonicalize_lenient(&target);
        let canon_wt = std::fs::canonicalize(&wt).unwrap();
        assert!(!result.starts_with(&canon_wt));
    }

    // ---- PathGuard::check_write ----

    fn make_guard(wt: &Path) -> PathGuard {
        PathGuard::new(wt, &[], &[]).unwrap()
    }

    #[test]
    fn check_write_inside_worktree_allowed() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join("wt");
        std::fs::create_dir(&wt).unwrap();
        let guard = make_guard(&wt);
        assert!(guard.check_write(&wt.join("file.txt")).is_ok());
    }

    #[test]
    fn check_write_outside_worktree_rejected() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join("wt");
        std::fs::create_dir(&wt).unwrap();
        let guard = make_guard(&wt);
        let outside = tmp.path().join("outside.txt");
        let err = guard.check_write(&outside).unwrap_err();
        assert!(err.contains("path outside ticket worktree"));
        assert!(err.contains("APM_TICKET_WORKTREE"));
    }

    #[test]
    fn check_write_rejection_message_contains_worktree() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join("wt");
        std::fs::create_dir(&wt).unwrap();
        let guard = make_guard(&wt);
        let err = guard.check_write(&tmp.path().join("x")).unwrap_err();
        assert!(err.contains("APM_TICKET_WORKTREE"));
    }

    #[test]
    fn check_write_dotdot_escape_rejected() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join("wt");
        let sub = wt.join("sub");
        std::fs::create_dir_all(&sub).unwrap();
        let guard = make_guard(&wt);
        // wt/sub/../../etc/passwd
        let path = sub.join("..").join("..").join("etc").join("passwd");
        assert!(guard.check_write(&path).is_err());
    }

    #[test]
    fn check_write_symlink_to_outside_rejected() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join("wt");
        std::fs::create_dir(&wt).unwrap();
        let outside = tmp.path().join("outside");
        std::fs::create_dir(&outside).unwrap();
        let link = wt.join("link");
        std::os::unix::fs::symlink(&outside, &link).unwrap();
        let guard = make_guard(&wt);
        assert!(guard.check_write(&link.join("file.txt")).is_err());
    }

    #[test]
    fn check_write_protected_inside_worktree_rejected() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join("wt");
        std::fs::create_dir(&wt).unwrap();
        // apm_bin inside the worktree (e.g. target/debug/apm)
        let apm_bin = wt.join("target").join("debug").join("apm");
        std::fs::create_dir_all(apm_bin.parent().unwrap()).unwrap();
        std::fs::write(&apm_bin, "binary").unwrap();
        let guard = PathGuard::new(&wt, &[], &[apm_bin.clone()]).unwrap();
        let err = guard.check_write(&apm_bin).unwrap_err();
        assert!(err.contains("path outside ticket worktree"));
    }

    #[test]
    fn check_write_apm_bin_outside_worktree_rejected() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join("wt");
        std::fs::create_dir(&wt).unwrap();
        let apm_bin = tmp.path().join("usr").join("bin").join("apm");
        std::fs::create_dir_all(apm_bin.parent().unwrap()).unwrap();
        std::fs::write(&apm_bin, "binary").unwrap();
        let guard = PathGuard::new(&wt, &[], &[apm_bin.clone()]).unwrap();
        assert!(guard.check_write(&apm_bin).is_err());
    }

    // ---- detect_write_targets (bash heuristic) ----

    #[test]
    fn bash_redirect_gt_detected() {
        let targets = detect_write_targets("echo foo > /outside/file");
        assert!(targets.iter().any(|t| t == "/outside/file"), "got: {targets:?}");
    }

    #[test]
    fn bash_redirect_gtgt_detected() {
        let targets = detect_write_targets("cat data >> /outside/append.log");
        assert!(targets.iter().any(|t| t == "/outside/append.log"), "got: {targets:?}");
    }

    #[test]
    fn bash_tee_detected() {
        let targets = detect_write_targets("some-cmd | tee /outside/output.txt");
        assert!(targets.iter().any(|t| t == "/outside/output.txt"), "got: {targets:?}");
    }

    #[test]
    fn bash_tee_flag_skipped() {
        let targets = detect_write_targets("some-cmd | tee -a /outside/output.txt");
        assert!(targets.iter().any(|t| t == "/outside/output.txt"), "got: {targets:?}");
    }

    #[test]
    fn bash_cp_dest_detected() {
        let targets = detect_write_targets("cp /inside/src /outside/dest");
        assert!(targets.iter().any(|t| t == "/outside/dest"), "got: {targets:?}");
        // /inside/src should NOT be a target
        assert!(!targets.iter().any(|t| t == "/inside/src"), "src should not be write target: {targets:?}");
    }

    #[test]
    fn bash_mv_dest_detected() {
        let targets = detect_write_targets("mv /inside/file /outside/dest");
        assert!(targets.iter().any(|t| t == "/outside/dest"), "got: {targets:?}");
    }

    #[test]
    fn bash_truncate_detected() {
        let targets = detect_write_targets("truncate -s 0 /outside/file");
        assert!(targets.iter().any(|t| t == "/outside/file"), "got: {targets:?}");
    }

    #[test]
    fn bash_cat_not_detected() {
        let targets = detect_write_targets("cat /etc/resolv.conf");
        assert!(targets.is_empty(), "cat should produce no write targets: {targets:?}");
    }

    #[test]
    fn bash_grep_not_detected() {
        let targets = detect_write_targets("grep pattern /etc/hosts");
        assert!(targets.is_empty(), "grep should produce no write targets: {targets:?}");
    }

    #[test]
    fn bash_ls_not_detected() {
        let targets = detect_write_targets("ls /outside/dir");
        assert!(targets.is_empty(), "ls should produce no write targets: {targets:?}");
    }

    #[test]
    fn bash_diff_not_detected() {
        let targets = detect_write_targets("diff /file1 /file2");
        assert!(targets.is_empty(), "diff should produce no write targets: {targets:?}");
    }

    #[test]
    fn bash_wc_not_detected() {
        let targets = detect_write_targets("wc -l /var/log/syslog");
        assert!(targets.is_empty(), "wc should produce no write targets: {targets:?}");
    }

    #[test]
    fn bash_echo_no_path_not_detected() {
        let targets = detect_write_targets("echo hello");
        assert!(targets.is_empty(), "echo without path should produce no write targets: {targets:?}");
    }

    // ---- PathGuard::check_bash ----

    #[test]
    fn check_bash_redirect_outside_rejected() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join("wt");
        std::fs::create_dir(&wt).unwrap();
        let guard = make_guard(&wt);
        let outside = tmp.path().join("outside.txt");
        let cmd = format!("echo foo > {}", outside.display());
        assert!(guard.check_bash(&cmd).is_err());
    }

    #[test]
    fn check_bash_redirect_inside_allowed() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join("wt");
        std::fs::create_dir(&wt).unwrap();
        let guard = make_guard(&wt);
        let inside = wt.join("output.txt");
        let cmd = format!("echo foo > {}", inside.display());
        assert!(guard.check_bash(&cmd).is_ok());
    }

    #[test]
    fn check_bash_cat_read_allowed() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join("wt");
        std::fs::create_dir(&wt).unwrap();
        let guard = make_guard(&wt);
        assert!(guard.check_bash("cat /etc/resolv.conf").is_ok());
    }

    #[test]
    fn check_bash_tilde_gitconfig_allowed() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join("wt");
        std::fs::create_dir(&wt).unwrap();
        let guard = make_guard(&wt);
        assert!(guard.check_bash("cat ~/.gitconfig").is_ok());
    }
}