polyc-tools 2026.8.3

The in-process tool core for polychrome agents: local executors (coding, web fetch, wallet, ...), the tool registry, and MCP composition. The networked connectors live in polyc-connectors.
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
//! Seeding a delegated worker's workspace with named parent files (`#2295`).
//!
//! `#2286` fenced every delegated worker in its own workspace subtree and
//! re-rooted all the coding tools against it — reads included. That closed the
//! concurrent-write race, but it also ended a contract that had been implicit:
//! a worker could read the parent's workspace. After `#2286` a delegation like
//! "review the file I just wrote" hands the worker an empty scratch directory.
//!
//! This module restores that reach, narrowly. The target agent's manifest
//! declares a [`ShareInCeiling`] — glob patterns plus file-count and byte
//! bounds — and a `__delegate_to` call names literal paths inside it. Only the
//! intersection is copied, into the worker's own subtree at the same relative
//! paths, before its nested turn starts.
//!
//! # What this is not
//!
//! Copies, not a share: the worker owns its copy outright and its writes stay
//! its own, so seeding cannot reintroduce `#2286`'s clobbering. Nothing copies
//! back — a worker's output is still its final message alone (`#2295` tracks
//! the copy-out half separately, deliberately: a copy-out collision policy is
//! the same race in a new place).
//!
//! # Refusals are hard
//!
//! Every violation fails the delegation instead of seeding a subset. A worker
//! silently given three of the five files its task named would produce a
//! confidently wrong answer against a partial view; a failed delegation the
//! orchestrator can see and retry is strictly better.

use std::path::{Component, Path, PathBuf};

use polyc_agent::delegate::{ShareInCeiling, ShareInError};

use super::search::glob_to_regex;
use super::workspace::{WORKER_SUBDIR_PREFIX, resolve};

/// One parent file selected for seeding: where it lives now, where it lands,
/// and how big it is.
struct Selected {
    /// Absolute path in the parent workspace.
    source: PathBuf,
    /// Workspace-relative path, `/`-joined — the key the ceiling matches
    /// against and the path the copy lands at under the worker root.
    relative: String,
    /// Size in bytes, summed against [`ShareInCeiling::max_bytes`].
    bytes: u64,
}

/// Copy the parent files `requested` names into `worker_root`, enforcing
/// `ceiling`.
///
/// Resolves and bounds-checks the whole request before copying a single byte,
/// so a refused delegation never leaves a half-seeded worker tree behind.
/// Returns the workspace-relative paths actually seeded, in copy order, for
/// the delegation's forensic record.
///
/// # Errors
///
/// Returns [`ShareInError`] when a path escapes the workspace, names a
/// delegated worker's subtree, resolves to nothing, falls outside `ceiling`'s
/// patterns, exceeds its file or byte bounds, or cannot be read or written.
pub fn seed(
    parent_root: &Path,
    worker_root: &Path,
    requested: &[String],
    ceiling: &ShareInCeiling,
) -> Result<Vec<String>, ShareInError> {
    if requested.is_empty() {
        return Ok(Vec::new());
    }
    // A closed ceiling refuses before any filesystem work: an agent that
    // declares no share-in never seeds, which is `#2286`'s behavior exactly.
    if !ceiling.admits_anything() {
        return Err(ShareInError::OutsideCeiling {
            path: requested[0].clone(),
        });
    }

    let patterns = compile(ceiling);
    let mut selected = Vec::new();
    for entry in requested {
        collect(parent_root, entry, ceiling, &mut selected)?;
    }

    // Bounds are checked against the fully expanded set, not per entry — a
    // request is one unit, and two directories that are individually under the
    // cap must not add up to a worker tree over it.
    if selected.len() > ceiling.max_files {
        return Err(ShareInError::TooManyFiles {
            found: selected.len(),
            limit: ceiling.max_files,
        });
    }
    let total: u64 = selected.iter().map(|f| f.bytes).sum();
    if total > ceiling.max_bytes {
        return Err(ShareInError::TooManyBytes {
            found: total,
            limit: ceiling.max_bytes,
        });
    }
    for file in &selected {
        if !patterns.iter().any(|re| re.is_match(&file.relative)) {
            return Err(ShareInError::OutsideCeiling {
                path: file.relative.clone(),
            });
        }
    }

    let mut seeded = Vec::with_capacity(selected.len());
    for file in selected {
        let destination =
            resolve(worker_root, &file.relative).map_err(|reason| ShareInError::Escapes {
                path: file.relative.clone(),
                reason,
            })?;
        if let Some(parent) = destination.parent() {
            std::fs::create_dir_all(parent).map_err(|err| ShareInError::Io {
                path: file.relative.clone(),
                reason: err.to_string(),
            })?;
        }
        std::fs::copy(&file.source, &destination).map_err(|err| ShareInError::Io {
            path: file.relative.clone(),
            reason: err.to_string(),
        })?;
        seeded.push(file.relative);
    }
    Ok(seeded)
}

/// Compile the ceiling's globs into anchored regexes over `/`-joined paths.
///
/// A pattern that fails to compile is dropped rather than propagated: it can
/// only ever narrow what is admitted, so a malformed manifest entry fails
/// closed on its own without taking the whole ceiling down with it.
fn compile(ceiling: &ShareInCeiling) -> Vec<regex::Regex> {
    ceiling
        .allow
        .iter()
        .filter_map(|pattern| regex::Regex::new(&glob_to_regex(pattern)).ok())
        .collect()
}

/// Resolve one request entry and append every file it names to `out`.
fn collect(
    parent_root: &Path,
    entry: &str,
    ceiling: &ShareInCeiling,
    out: &mut Vec<Selected>,
) -> Result<(), ShareInError> {
    let source = resolve(parent_root, entry).map_err(|reason| ShareInError::Escapes {
        path: entry.to_owned(),
        reason,
    })?;
    if names_worker_subtree(parent_root, &source) {
        return Err(ShareInError::WorkerSubtree {
            path: entry.to_owned(),
        });
    }
    // `symlink_metadata` deliberately, not `metadata`: a symlink planted in
    // the parent workspace would otherwise be followed by the copy below,
    // reading a file outside the workspace into a worker that could never
    // have reached it. A symlink named directly is refused; one met while
    // walking a directory is skipped (see `walk`).
    let meta = std::fs::symlink_metadata(&source).map_err(|_| ShareInError::NotFound {
        path: entry.to_owned(),
    })?;
    if meta.is_symlink() {
        return Err(ShareInError::Escapes {
            path: entry.to_owned(),
            reason: "symbolic links are never seeded".to_owned(),
        });
    }
    if meta.is_dir() {
        walk(parent_root, &source, ceiling, out)
    } else {
        out.push(Selected {
            relative: relative_to(parent_root, &source),
            source,
            bytes: meta.len(),
        });
        Ok(())
    }
}

/// Whether `source` lands inside a delegated worker's subtree.
///
/// Tested against the RESOLVED path, not the request string: [`resolve`] has
/// already normalized away `.` components, and a raw-string check would miss
/// `./.worker-b/notes.md` — its first component is `CurDir`, so a
/// first-component test on the request would read the entry as ordinary and
/// hand over a sibling's files.
///
/// Only the first component of the normalized path matters: a worker root is
/// always a single component directly under the conversation root, and
/// [`resolve`] has already rejected anything that could climb back out.
fn names_worker_subtree(parent_root: &Path, source: &Path) -> bool {
    source
        .strip_prefix(parent_root)
        .ok()
        .and_then(|rel| rel.components().next())
        .is_some_and(|first| {
            matches!(first, Component::Normal(part)
            if part.to_string_lossy().starts_with(WORKER_SUBDIR_PREFIX))
        })
}

/// Recursively append every regular file under `dir` to `out`.
///
/// Bails as soon as the running count passes [`ShareInCeiling::max_files`], so
/// a request naming a huge tree is refused without first materializing it.
/// Symlinks and delegated workers' subtrees are skipped.
fn walk(
    parent_root: &Path,
    dir: &Path,
    ceiling: &ShareInCeiling,
    out: &mut Vec<Selected>,
) -> Result<(), ShareInError> {
    let entries = std::fs::read_dir(dir).map_err(|err| ShareInError::Io {
        path: relative_to(parent_root, dir),
        reason: err.to_string(),
    })?;
    for entry in entries.flatten() {
        let path = entry.path();
        let Ok(meta) = std::fs::symlink_metadata(&path) else {
            continue;
        };
        if meta.is_symlink() {
            continue;
        }
        if meta.is_dir() {
            let is_worker_tree = path
                .file_name()
                .is_some_and(|name| name.to_string_lossy().starts_with(WORKER_SUBDIR_PREFIX));
            if is_worker_tree {
                continue;
            }
            walk(parent_root, &path, ceiling, out)?;
        } else {
            out.push(Selected {
                relative: relative_to(parent_root, &path),
                source: path,
                bytes: meta.len(),
            });
        }
        if out.len() > ceiling.max_files {
            return Err(ShareInError::TooManyFiles {
                found: out.len(),
                limit: ceiling.max_files,
            });
        }
    }
    Ok(())
}

/// Render `path` relative to `root` as a `/`-joined string.
///
/// `path` always sits under `root` here — every caller derived it from
/// [`resolve`] or from walking `root` — so the strip cannot fail; the fallback
/// keeps the lossy rendering total rather than panicking on a future caller
/// that breaks that assumption.
fn relative_to(root: &Path, path: &Path) -> String {
    path.strip_prefix(root)
        .unwrap_or(path)
        .components()
        .filter_map(|c| match c {
            Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("/")
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use super::*;

    fn ceiling(allow: &[&str], max_files: usize, max_bytes: u64) -> ShareInCeiling {
        ShareInCeiling {
            allow: allow.iter().map(|s| (*s).to_owned()).collect(),
            max_files,
            max_bytes,
        }
    }

    fn write(root: &Path, rel: &str, body: &str) {
        let path = root.join(rel);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, body).unwrap();
    }

    /// A parent workspace with one worker subtree already under it, matching
    /// the layout `ToolRegistry::for_worker` creates. The caller leaves the
    /// directory behind; `tmp_dir` keys it per-process and per-call.
    fn roots() -> (PathBuf, PathBuf) {
        let parent = super::super::tmp_dir("share-in").join("workspace");
        let worker = parent.join(".worker-call-a-0000");
        std::fs::create_dir_all(&worker).unwrap();
        (parent, worker)
    }

    #[test]
    fn seeds_a_named_file_at_the_same_relative_path() {
        let (parent, worker) = roots();
        write(&parent, "src/parser.rs", "fn parse() {}");

        let seeded = seed(
            &parent,
            &worker,
            &["src/parser.rs".to_owned()],
            &ceiling(&["src/**"], 10, 1024),
        )
        .expect("a file inside the ceiling seeds");

        assert_eq!(seeded, vec!["src/parser.rs".to_owned()]);
        assert_eq!(
            std::fs::read_to_string(worker.join("src/parser.rs")).unwrap(),
            "fn parse() {}",
        );
    }

    #[test]
    fn refuses_a_file_outside_the_ceiling() {
        let (parent, worker) = roots();
        write(&parent, "secrets/token", "s3cret");

        let err = seed(
            &parent,
            &worker,
            &["secrets/token".to_owned()],
            &ceiling(&["src/**"], 10, 1024),
        )
        .expect_err("a file the ceiling does not admit must be refused");

        assert!(
            matches!(err, ShareInError::OutsideCeiling { .. }),
            "{err:?}"
        );
        assert!(
            !worker.join("secrets/token").exists(),
            "a refused request must copy nothing"
        );
    }

    #[test]
    fn refuses_traversal_out_of_the_parent_workspace() {
        let (parent, worker) = roots();

        let err = seed(
            &parent,
            &worker,
            &["../outside.txt".to_owned()],
            &ceiling(&["**"], 10, 1024),
        )
        .expect_err("`..` must never leave the parent workspace");

        assert!(matches!(err, ShareInError::Escapes { .. }), "{err:?}");
    }

    #[test]
    fn refuses_reaching_into_a_sibling_workers_subtree() {
        // The cross-worker read `#2286` fenced off: without this check a
        // worker could name a sibling's scratch directory and be handed its
        // files, since `resolve` treats `.worker-*` as an ordinary component.
        let (parent, worker) = roots();
        write(&parent, ".worker-call-b-1111/notes.md", "sibling's work");

        let err = seed(
            &parent,
            &worker,
            &[".worker-call-b-1111/notes.md".to_owned()],
            &ceiling(&["**"], 10, 1024),
        )
        .expect_err("a sibling worker's subtree is never seedable");

        assert!(matches!(err, ShareInError::WorkerSubtree { .. }), "{err:?}");
    }

    #[test]
    fn refuses_a_dot_prefixed_path_into_a_worker_subtree() {
        // `./` normalizes away, so a first-component test against the REQUEST
        // string reads this as an ordinary path and hands over the sibling's
        // file. The guard has to run against the resolved path.
        let (parent, worker) = roots();
        write(&parent, ".worker-call-b-1111/notes.md", "sibling's work");

        let err = seed(
            &parent,
            &worker,
            &["./.worker-call-b-1111/notes.md".to_owned()],
            &ceiling(&["**"], 10, 1024),
        )
        .expect_err("`./` must not smuggle a request into a worker subtree");

        assert!(matches!(err, ShareInError::WorkerSubtree { .. }), "{err:?}");
    }

    #[test]
    fn refuses_when_over_the_file_bound() {
        let (parent, worker) = roots();
        for i in 0..5 {
            write(&parent, &format!("src/f{i}.rs"), "x");
        }

        let err = seed(
            &parent,
            &worker,
            &["src".to_owned()],
            &ceiling(&["src/**"], 3, 1024),
        )
        .expect_err("five files must not seed under a three-file ceiling");

        assert!(matches!(err, ShareInError::TooManyFiles { .. }), "{err:?}");
    }

    #[test]
    fn refuses_when_over_the_byte_bound() {
        let (parent, worker) = roots();
        write(&parent, "src/big.rs", &"x".repeat(200));

        let err = seed(
            &parent,
            &worker,
            &["src/big.rs".to_owned()],
            &ceiling(&["src/**"], 10, 64),
        )
        .expect_err("a file over the byte ceiling must be refused");

        assert!(matches!(err, ShareInError::TooManyBytes { .. }), "{err:?}");
        assert!(
            !worker.join("src/big.rs").exists(),
            "a refused request must copy nothing"
        );
    }

    #[test]
    fn seeds_a_directory_recursively() {
        let (parent, worker) = roots();
        write(&parent, "src/a.rs", "a");
        write(&parent, "src/nested/b.rs", "b");

        let mut seeded = seed(
            &parent,
            &worker,
            &["src".to_owned()],
            &ceiling(&["src/**"], 10, 1024),
        )
        .expect("a directory seeds every file under it");
        seeded.sort();

        assert_eq!(
            seeded,
            vec!["src/a.rs".to_owned(), "src/nested/b.rs".to_owned()]
        );
        assert_eq!(
            std::fs::read_to_string(worker.join("src/nested/b.rs")).unwrap(),
            "b"
        );
    }

    #[test]
    fn a_closed_ceiling_seeds_nothing() {
        // The default an agent gets when its manifest says nothing about
        // share-in: every request is refused, so `#2286`'s fencing is intact.
        let (parent, worker) = roots();
        write(&parent, "src/parser.rs", "fn parse() {}");

        let err = seed(
            &parent,
            &worker,
            &["src/parser.rs".to_owned()],
            &ShareInCeiling::default(),
        )
        .expect_err("an unconfigured ceiling admits nothing");

        assert!(
            matches!(err, ShareInError::OutsideCeiling { .. }),
            "{err:?}"
        );
    }

    #[test]
    fn an_empty_request_seeds_nothing_and_succeeds() {
        let (parent, worker) = roots();
        write(&parent, "src/parser.rs", "fn parse() {}");

        let seeded = seed(&parent, &worker, &[], &ceiling(&["src/**"], 10, 1024))
            .expect("no request is not an error");

        assert!(seeded.is_empty());
        assert!(!worker.join("src/parser.rs").exists());
    }

    #[test]
    fn refuses_a_symlink_named_directly() {
        let (parent, worker) = roots();
        write(&parent, "src/real.rs", "real");
        #[cfg(unix)]
        std::os::unix::fs::symlink("/etc/hostname", parent.join("src/link.rs")).unwrap();

        #[cfg(unix)]
        {
            let err = seed(
                &parent,
                &worker,
                &["src/link.rs".to_owned()],
                &ceiling(&["src/**"], 10, 1024),
            )
            .expect_err("a symlink could read outside the workspace");
            assert!(matches!(err, ShareInError::Escapes { .. }), "{err:?}");
        }
    }

    #[test]
    fn refuses_a_path_that_names_nothing() {
        let (parent, worker) = roots();

        let err = seed(
            &parent,
            &worker,
            &["src/missing.rs".to_owned()],
            &ceiling(&["src/**"], 10, 1024),
        )
        .expect_err("a path naming nothing is an error, not an empty seed");

        assert!(matches!(err, ShareInError::NotFound { .. }), "{err:?}");
    }
}