farhand-workspace 1.10.2

Agent-side workspace storage for Farhand: content-addressable store, copy-on-write cloning, locks, GC, and run history
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
use std::path::Path;
use walkdir::WalkDir;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Preset {
    pub name: &'static str,
    pub markers: &'static [&'static str],
    pub outputs: &'static [&'static str],
}

pub const DEFAULT_PRESETS: &[Preset] = &[
    Preset {
        name: "npm",
        markers: &["package.json"],
        outputs: &["dist", "build", ".next", "out"],
    },
    Preset {
        name: "rust",
        markers: &["Cargo.toml"],
        outputs: &["target/release", "target/debug"],
    },
    Preset {
        name: "go",
        markers: &["go.mod"],
        outputs: &["bin", "dist"],
    },
    Preset {
        name: "python",
        markers: &["pyproject.toml", "setup.py", "requirements.txt"],
        outputs: &["dist", "build"],
    },
];

/// Detect candidate output paths based on project marker files present in `workspace_root`.
pub fn detect_preset_outputs(workspace_root: &Path) -> Vec<String> {
    let mut candidates = Vec::new();
    for preset in DEFAULT_PRESETS {
        let matched = preset
            .markers
            .iter()
            .any(|marker| workspace_root.join(marker).exists());
        if matched {
            for output in preset.outputs {
                candidates.push((*output).to_string());
            }
        }
    }
    candidates
}

/// Resolve artifact paths to be retrieved from the remote workspace.
///
/// 1. If explicit `requested_outputs` is provided and non-empty, use those.
/// 2. Otherwise, detect candidate outputs using project marker presets.
/// 3. Filter and expand candidates (directories, files, or glob patterns) to existing paths
///    relative to `workspace_root`.
/// 4. All paths use wire-normalized forward slashes and prevent directory traversal.
pub fn resolve_artifact_paths(
    workspace_root: &Path,
    requested_outputs: Option<&[String]>,
    explicit_template: Option<&str>,
) -> Vec<String> {
    let (candidates, output_ignores): (Vec<String>, Vec<String>) = match requested_outputs {
        Some(outs) if !outs.is_empty() => (outs.to_vec(), Vec::new()),
        _ => {
            let tmpl_candidates =
                templates::resolve_template_outputs(workspace_root, explicit_template);
            let tmpl_ignores =
                templates::resolve_template_outputs_ignores(workspace_root, explicit_template);
            if !tmpl_candidates.is_empty() {
                (tmpl_candidates, tmpl_ignores)
            } else {
                (detect_preset_outputs(workspace_root), Vec::new())
            }
        }
    };

    let canonical_root = match workspace_root.canonicalize() {
        Ok(c) => c,
        Err(_) => return Vec::new(),
    };

    let mut resolved_paths = Vec::new();

    for candidate in candidates {
        let clean = candidate.trim().trim_matches('/');
        // Security check: reject empty or path traversal sequences
        if clean.is_empty()
            || clean.starts_with("..")
            || clean.contains("/../")
            || clean.contains("\\..\\")
            || clean.contains('\\')
        {
            continue;
        }

        // Check if candidate is a glob pattern
        if clean.contains('*') || clean.contains('?') || clean.contains('[') {
            let pattern_str = format!("{}/{}", canonical_root.to_string_lossy(), clean);
            if let Ok(entries) = glob::glob(&pattern_str) {
                for entry in entries.flatten() {
                    add_path_or_dir(
                        &canonical_root,
                        &entry,
                        &output_ignores,
                        &mut resolved_paths,
                    );
                }
            }
        } else {
            let candidate_path = canonical_root.join(clean);
            if candidate_path.exists() {
                add_path_or_dir(
                    &canonical_root,
                    &candidate_path,
                    &output_ignores,
                    &mut resolved_paths,
                );
            }
        }
    }

    resolved_paths.sort();
    resolved_paths.dedup();
    resolved_paths
}

/// Whether any component of a relative path is agent bookkeeping.
///
/// These files sit at the workspace root alongside the project, so an output
/// pattern broad enough to cover the root — `outputs: ["."]`, or a directory
/// that happens to contain them — would otherwise stream them to the client as
/// build artifacts. They are not project files and the client cannot use them;
/// the largest, `.farhand-hashindex.json`, also scales with the project's file
/// count.
///
/// Checked per component rather than as a prefix so it holds for nested
/// entries too, not only ones at the root.
fn is_agent_internal(rel_path: &str) -> bool {
    rel_path
        .split('/')
        .any(|c| c == crate::state::STATE_FILENAME || c.starts_with(".farhand-"))
}

fn is_artifact_ignored(rel_str: &str, output_ignores: &[String]) -> bool {
    let clean = rel_str.trim().trim_matches('/');
    if clean.is_empty() {
        return false;
    }

    // Check path segments against built-in intermediate compiler caches
    let segments: Vec<&str> = clean.split('/').collect();
    for seg in &segments {
        if matches!(
            *seg,
            "deps" | "incremental" | ".fingerprint" | "__pycache__" | ".git" | "node_modules"
        ) {
            return true;
        }
    }

    // Check against template outputsIgnore patterns
    for pattern in output_ignores {
        let pat_clean = pattern.trim().trim_matches('/');
        if pat_clean.contains('*') || pat_clean.contains('?') || pat_clean.contains('[') {
            if let Ok(glob_pat) = glob::Pattern::new(pat_clean) {
                if glob_pat.matches(clean) {
                    return true;
                }
                if let Some(file_name) = clean.rsplit('/').next() {
                    if glob_pat.matches(file_name) {
                        return true;
                    }
                }
            }
        } else if clean == pat_clean
            || clean.starts_with(&format!("{}/", pat_clean))
            || clean.ends_with(&format!("/{}", pat_clean))
        {
            return true;
        }
    }

    false
}

fn add_path_or_dir(
    canonical_root: &Path,
    target: &Path,
    output_ignores: &[String],
    out: &mut Vec<String>,
) {
    let canonical_target = match target.canonicalize() {
        Ok(c) => c,
        Err(_) => return,
    };

    // Prevent Zip-Slip: ensure target stays strictly within canonical_root
    if !canonical_target.starts_with(canonical_root) || canonical_target == canonical_root {
        return;
    }

    if target.is_dir() {
        let mut it = WalkDir::new(target).into_iter();
        loop {
            let entry = match it.next() {
                Some(Ok(e)) => e,
                Some(Err(_)) => continue,
                None => break,
            };

            // Verify entry canonical path also stays within root
            if let Ok(canon_entry) = entry.path().canonicalize() {
                if !canon_entry.starts_with(canonical_root) {
                    continue;
                }
            }

            if let Ok(rel) = entry.path().strip_prefix(canonical_root) {
                let rel_str = rel.to_string_lossy().replace('\\', "/");
                if rel_str.is_empty() {
                    continue;
                }

                if is_agent_internal(&rel_str) {
                    if entry.file_type().is_dir() {
                        it.skip_current_dir();
                    }
                    continue;
                }

                if is_artifact_ignored(&rel_str, output_ignores) {
                    if entry.file_type().is_dir() {
                        it.skip_current_dir();
                    }
                    continue;
                }

                out.push(rel_str);
            }
        }
    } else if let Ok(rel) = canonical_target.strip_prefix(canonical_root) {
        let rel_str = rel.to_string_lossy().replace('\\', "/");
        if !rel_str.is_empty()
            && !is_agent_internal(&rel_str)
            && !is_artifact_ignored(&rel_str, output_ignores)
        {
            out.push(rel_str);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::{self, File};
    use std::io::Write;
    use tempfile::tempdir;

    #[test]
    fn test_detect_preset_outputs_rust_and_npm() {
        let dir = tempdir().unwrap();
        // Initially empty: no candidates
        assert!(detect_preset_outputs(dir.path()).is_empty());

        // Add Cargo.toml
        File::create(dir.path().join("Cargo.toml")).unwrap();
        let detected = detect_preset_outputs(dir.path());
        assert!(detected.contains(&"target/release".to_string()));
        assert!(detected.contains(&"target/debug".to_string()));

        // Add package.json
        File::create(dir.path().join("package.json")).unwrap();
        let detected = detect_preset_outputs(dir.path());
        assert!(detected.contains(&"dist".to_string()));
        assert!(detected.contains(&"target/release".to_string()));
    }

    #[test]
    fn test_resolve_artifact_paths_explicit_files_and_dirs() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        // Create dist/bundle.js and dist/sub/style.css
        let dist = root.join("dist");
        let sub = dist.join("sub");
        fs::create_dir_all(&sub).unwrap();
        File::create(dist.join("bundle.js"))
            .unwrap()
            .write_all(b"console.log('hi');")
            .unwrap();
        File::create(sub.join("style.css"))
            .unwrap()
            .write_all(b"body { margin: 0; }")
            .unwrap();

        // Explicitly request "dist"
        let paths = resolve_artifact_paths(root, Some(&["dist".to_string()]), None);
        assert!(paths.contains(&"dist".to_string()));
        assert!(paths.contains(&"dist/bundle.js".to_string()));
        assert!(paths.contains(&"dist/sub".to_string()));
        assert!(paths.contains(&"dist/sub/style.css".to_string()));
    }

    #[test]
    fn test_resolve_artifact_paths_preset_fallback() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        // Create marker Cargo.toml and output target/release/my-bin
        File::create(root.join("Cargo.toml")).unwrap();
        let release_dir = root.join("target").join("release");
        fs::create_dir_all(&release_dir).unwrap();
        File::create(release_dir.join("my-bin")).unwrap();

        // Pass None for requested_outputs; should detect target/release
        let paths = resolve_artifact_paths(root, None, None);
        assert!(paths.contains(&"target/release".to_string()));
        assert!(paths.contains(&"target/release/my-bin".to_string()));
        // target/debug was not created, so it should not be in paths
        assert!(!paths.contains(&"target/debug".to_string()));
    }

    #[test]
    fn test_resolve_artifact_paths_glob() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        let out = root.join("out");
        fs::create_dir_all(&out).unwrap();
        File::create(out.join("test1.log")).unwrap();
        File::create(out.join("test2.log")).unwrap();
        File::create(out.join("other.txt")).unwrap();

        let paths = resolve_artifact_paths(root, Some(&["out/*.log".to_string()]), None);
        assert_eq!(paths, vec!["out/test1.log", "out/test2.log"]);
    }

    /// Agent bookkeeping sits at the workspace root, so an output pattern that
    /// covers it used to stream it back to the client as a build artifact.
    /// These are not project files and the client cannot use them.
    #[test]
    fn test_agent_internal_state_is_never_returned_as_an_artifact() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        // A real artifact, which must still be returned.
        let pkg = root.join("pkg");
        fs::create_dir_all(&pkg).unwrap();
        fs::write(pkg.join("app.txt"), b"real").unwrap();

        // Agent-internal state sitting alongside it, which must not.
        fs::write(pkg.join(fileset::HASH_INDEX_FILENAME), b"{}").unwrap();
        fs::write(pkg.join(crate::state::STATE_FILENAME), b"{}").unwrap();
        fs::create_dir_all(pkg.join(".farhand-runs")).unwrap();
        fs::write(pkg.join(".farhand-runs/run.json"), b"{}").unwrap();

        let paths = resolve_artifact_paths(root, Some(&["pkg".to_string()]), None);

        assert!(
            paths.contains(&"pkg/app.txt".to_string()),
            "the real artifact was filtered: {paths:?}"
        );
        assert!(
            !paths
                .iter()
                .any(|p| p.contains(".farhand-") || p.contains(".json")),
            "agent-internal state leaked into the artifact set: {paths:?}"
        );
    }

    #[test]
    fn test_resolve_artifact_paths_traversal_rejection() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        // Pass malicious paths
        let paths = resolve_artifact_paths(
            root,
            Some(&[
                "../outside".to_string(),
                "../../etc/passwd".to_string(),
                "out/../../escaped".to_string(),
            ]),
            None,
        );
        assert!(paths.is_empty());
    }

    #[test]
    fn test_resolve_artifact_paths_nonexistent() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        let paths = resolve_artifact_paths(root, Some(&["does_not_exist".to_string()]), None);
        assert!(paths.is_empty());
    }

    #[test]
    fn test_resolve_artifact_paths_template_integration() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        // Create package.json and dist/app.js
        File::create(root.join("package.json")).unwrap();
        let dist = root.join("dist");
        fs::create_dir_all(&dist).unwrap();
        File::create(dist.join("app.js")).unwrap();

        let paths = resolve_artifact_paths(root, None, None);
        assert!(paths.contains(&"dist".to_string()));
        assert!(paths.contains(&"dist/app.js".to_string()));
    }

    #[test]
    fn test_resolve_artifact_paths_excludes_intermediate_compiler_caches() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        // Create Cargo.toml to trigger rust template
        File::create(root.join("Cargo.toml")).unwrap();
        let release_dir = root.join("target").join("release");
        let deps_dir = release_dir.join("deps");
        let build_dir = release_dir.join("build");
        let inc_dir = release_dir.join("incremental");
        fs::create_dir_all(&deps_dir).unwrap();
        fs::create_dir_all(&build_dir).unwrap();
        fs::create_dir_all(&inc_dir).unwrap();

        // Output binary (should be retrieved)
        File::create(release_dir.join("app-bin")).unwrap();
        // Intermediate caches (should be EXCLUDED)
        File::create(deps_dir.join("libfoo.rlib")).unwrap();
        File::create(build_dir.join("build-script.o")).unwrap();
        File::create(inc_dir.join("inc.bin")).unwrap();
        File::create(release_dir.join("app-bin.d")).unwrap();

        let paths = resolve_artifact_paths(root, None, None);
        assert!(paths.contains(&"target/release/app-bin".to_string()));
        assert!(!paths.contains(&"target/release/deps/libfoo.rlib".to_string()));
        assert!(!paths.contains(&"target/release/build/build-script.o".to_string()));
        assert!(!paths.contains(&"target/release/incremental/inc.bin".to_string()));
        assert!(!paths.contains(&"target/release/app-bin.d".to_string()));
    }
}