ceulen 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/README.md +56 -1
  3. package/extensions/lib/plan-bridge.ts +18 -0
  4. package/extensions/lib/registry.ts +14 -0
  5. package/extensions/lib/skill-path.test.ts +35 -0
  6. package/extensions/lib/skill-path.ts +22 -0
  7. package/extensions/modules/a2a/index.ts +5 -3
  8. package/extensions/modules/a2a/lib/config.ts +1 -1
  9. package/extensions/modules/a2a/lib/registry.ts +1 -1
  10. package/extensions/modules/attachments/configPanel.ts +91 -0
  11. package/extensions/modules/attachments/index.ts +274 -0
  12. package/extensions/modules/attachments/lib/clipboard-files.ts +80 -0
  13. package/extensions/modules/attachments/lib/pastes.ts +45 -0
  14. package/extensions/modules/attachments/lib/paths.ts +74 -0
  15. package/extensions/modules/attachments/lib/registry.ts +70 -0
  16. package/extensions/modules/attachments/lib/settings.ts +99 -0
  17. package/extensions/modules/attachments/lib/tray.ts +74 -0
  18. package/extensions/modules/attachments/test/configPanel.test.ts +122 -0
  19. package/extensions/modules/attachments/test/index.test.ts +870 -0
  20. package/extensions/modules/attachments/test/module.test.ts +53 -0
  21. package/extensions/modules/composer/index.ts +19 -1
  22. package/extensions/modules/composer/lib/footer.ts +7 -7
  23. package/extensions/modules/composer/lib/shapes.ts +237 -112
  24. package/extensions/modules/composer/test/editor.test.ts +3 -3
  25. package/extensions/modules/composer/test/footer.test.ts +1 -1
  26. package/extensions/modules/composer/test/module.test.ts +8 -7
  27. package/extensions/modules/composer/test/screen.test.ts +10 -9
  28. package/extensions/modules/composer/test/shapes.test.ts +83 -61
  29. package/extensions/modules/config/index.ts +3 -0
  30. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  31. package/extensions/modules/cron/configPanel.ts +103 -0
  32. package/extensions/modules/cron/index.ts +638 -0
  33. package/extensions/modules/cron/lib/jobs.ts +201 -0
  34. package/extensions/modules/cron/lib/schedule.ts +161 -0
  35. package/extensions/modules/cron/test/cwd-repro.test.ts +98 -0
  36. package/extensions/modules/cron/test/index.test.ts +859 -0
  37. package/extensions/modules/cron/test/schedule.test.ts +93 -0
  38. package/extensions/modules/munin/index.ts +4 -2
  39. package/extensions/modules/permission/index.ts +567 -0
  40. package/extensions/modules/permission/test/permission.test.ts +789 -0
  41. package/extensions/modules/plan/index.ts +5 -0
  42. package/extensions/modules/ponytail/index.ts +2 -2
  43. package/extensions/modules/repair/index.ts +134 -3
  44. package/extensions/modules/repair/lib/settings.ts +1 -1
  45. package/extensions/modules/repair/test/freshness.test.ts +169 -0
  46. package/extensions/modules/router/lib/provider.ts +13 -9
  47. package/extensions/modules/subagent/index.ts +38 -5
  48. package/extensions/modules/subagent/lib/runner.ts +352 -14
  49. package/extensions/modules/subagent/test/worktree.test.ts +230 -0
  50. package/extensions/modules/usage/index.ts +193 -71
  51. package/extensions/modules/usage/test/context.test.ts +160 -120
  52. package/extensions/modules/ux/index.ts +2 -2
  53. package/extensions/modules/web/index.ts +4 -2
  54. package/extensions/modules/web/lib/chrome.ts +1 -1
  55. package/extensions/modules/web/test/a11y.test.ts +1 -1
  56. package/package.json +2 -2
  57. package/skills/cron/SKILL.md +58 -0
@@ -39,6 +39,7 @@ import {
39
39
  HARD_TIMEOUT_MS,
40
40
  truncateParallelOutput,
41
41
  } from "./security.ts";
42
+ import { randomUUID } from "node:crypto";
42
43
 
43
44
  // ---------------------------------------------------------------------------
44
45
  // Types
@@ -260,6 +261,25 @@ export async function runSubAgent(options: {
260
261
  worktreeDir = wt.path;
261
262
  worktreeRepoRoot = wt.repoRoot;
262
263
  childCwd = wt.path!;
264
+ // Seed the parent's uncommitted state into a git-worktree fallback
265
+ // (the CoW copy already IS the working tree). Read-only capture; the
266
+ // child's delta (diff vs HEAD) then carries baseline + edits, which
267
+ // 3-way-merges cleanly onto a parent that holds the same baseline —
268
+ // conflicts surface only genuine mid-run parent changes.
269
+ if (wt.cow === false && worktreeRepoRoot && worktreeDir) {
270
+ const baseline = await captureParentBaseline(worktreeRepoRoot, exec);
271
+ if (baseline.ok && baseline.patch && baseline.patch.trim()) {
272
+ const applied = await applyBaselineToWorktree(worktreeDir, baseline.patch, exec);
273
+ if (!applied.ok) {
274
+ const note = `Baseline carry failed (${applied.error?.slice(0, 200)}); child runs on clean HEAD.`;
275
+ result.stderr = result.stderr ? `${result.stderr}; ${note}` : note;
276
+ }
277
+ } else if (!baseline.ok && baseline.error) {
278
+ const note = `Baseline capture failed (${baseline.error.slice(0, 200)}); child runs on clean HEAD.`;
279
+ result.stderr = result.stderr ? `${result.stderr}; ${note}` : note;
280
+ }
281
+ await copyWorktreeIncludes(worktreeRepoRoot, worktreeDir).catch(() => { /* best effort */ });
282
+ }
263
283
  } else if (wt.error) {
264
284
  result.stderr = `Worktree unavailable (${wt.error}); running in workspace.`;
265
285
  }
@@ -400,21 +420,333 @@ async function runGit(
400
420
  return { ok: res.code === 0, stdout: res.stdout, stderr: res.stderr };
401
421
  }
402
422
 
403
- /** Create a detached git worktree at .pi-worktrees/<rand> under the repo root. */
423
+ /** Per-repo serialization for git operations that mutate the SHARED parent
424
+ * `.git` (worktree add/remove registry, `git apply`'s index/ODB writes).
425
+ * Git's own locks are O_EXCL with no waiter — concurrent mutations fail
426
+ * instantly instead of blocking (OMP withRepoLock precedent), so callers
427
+ * that can collide must queue here. Keyed by repo root so parallel repos
428
+ * stay independent; a failing block does not poison the queue. */
429
+ const repoLocks = new Map<string, Promise<unknown>>();
430
+
431
+ export async function withRepoLock<T>(repoRoot: string, fn: () => Promise<T>): Promise<T> {
432
+ const key = path.resolve(repoRoot);
433
+ const prior = repoLocks.get(key) ?? Promise.resolve();
434
+ const run = prior.then(fn, fn);
435
+ // The stored chain swallows errors so the NEXT caller starts clean; the
436
+ // returned promise still propagates this block's error to its own caller.
437
+ const stored = run.then(() => undefined, () => undefined);
438
+ repoLocks.set(key, stored);
439
+ // Drop the key once idle so the map cannot grow unboundedly across repos.
440
+ // A concurrent waiter has already replaced the stored chain by then.
441
+ stored.then(() => { if (repoLocks.get(key) === stored) repoLocks.delete(key); });
442
+ return run;
443
+ }
444
+
445
+ /** Owner marker written into every worktree sandbox: lets the GC sweep tell a
446
+ * live session's sandbox from a crashed run's leftover. */
447
+ export interface WorktreeOwner {
448
+ pid: number;
449
+ id: string;
450
+ createdAt: number;
451
+ }
452
+
453
+ export const WORKTREE_DIR_NAME = ".pi-worktrees";
454
+
455
+ /** A nested `.gitignore` (content `*`) inside the sandbox base keeps sandboxes
456
+ * out of the parent's `git status` AND out of untracked baseline capture —
457
+ * without touching the user's own .gitignore. */
458
+ async function ensureWorktreeBaseGitignore(base: string): Promise<void> {
459
+ const ignoreFile = path.join(base, ".gitignore");
460
+ try {
461
+ await fs.mkdir(base, { recursive: true });
462
+ await fs.writeFile(ignoreFile, "*\n", { flag: "wx" });
463
+ } catch { /* exists (or unwritable) — either is fine */ }
464
+ }
465
+
466
+ /** Owner marker: a SIBLING file inside the (gitignored) sandbox base —
467
+ * deliberately NOT inside the sandbox, so it never leaks into
468
+ * captureWorktreeDiff (`add -A` + diff) or the child's own reads. Two
469
+ * parallel merges would otherwise add/add-conflict on it (found by the
470
+ * concurrent-merge race test). */
471
+ export const OWNER_SUFFIX = ".owner.json";
472
+
473
+ async function writeOwnerMarker(base: string, id: string): Promise<void> {
474
+ const owner: WorktreeOwner = { pid: process.pid, id, createdAt: Date.now() };
475
+ await fs.writeFile(path.join(base, `${id}${OWNER_SUFFIX}`), JSON.stringify(owner), { encoding: "utf8", mode: 0o600 });
476
+ }
477
+
478
+ async function readOwnerMarker(base: string, entry: string): Promise<WorktreeOwner | undefined> {
479
+ try {
480
+ const raw = await fs.readFile(path.join(base, `${entry}${OWNER_SUFFIX}`), "utf8");
481
+ const parsed = JSON.parse(raw) as WorktreeOwner;
482
+ if (typeof parsed?.pid !== "number" || typeof parsed?.id !== "string") return undefined;
483
+ return parsed;
484
+ } catch {
485
+ return undefined;
486
+ }
487
+ }
488
+
489
+ /** Is a pid alive? EPERM counts as alive (another user's process). */
490
+ export function pidAlive(pid: number): boolean {
491
+ try {
492
+ process.kill(pid, 0);
493
+ return true;
494
+ } catch (err) {
495
+ return (err as NodeJS.ErrnoException)?.code === "EPERM";
496
+ }
497
+ }
498
+
499
+ export interface SweepResult {
500
+ removed: string[];
501
+ kept: number;
502
+ }
503
+
504
+ /** Remove crashed runs' worktree sandboxes under <repoRoot>/.pi-worktrees.
505
+ * Source of truth is the DIRECTORY (covers both backends); the git
506
+ * registration check only decides HOW a stale dir is removed. Never removes
507
+ * a sandbox whose marker pid is alive. Best-effort throughout. */
508
+ export async function sweepStaleWorktrees(
509
+ cwd: string,
510
+ exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
511
+ ): Promise<SweepResult> {
512
+ const removed: string[] = [];
513
+ try {
514
+ const root = await runGit(cwd, ["rev-parse", "--show-toplevel"], exec);
515
+ if (!root.ok) return { removed, kept: 0 };
516
+ const repoRoot = root.stdout.trim();
517
+ const base = path.join(repoRoot, WORKTREE_DIR_NAME);
518
+ let entries: string[];
519
+ try {
520
+ entries = await fs.readdir(base);
521
+ } catch {
522
+ return { removed, kept: 0 }; // no .pi-worktrees — the common path
523
+ }
524
+ let kept = 0;
525
+ await withRepoLock(repoRoot, async () => {
526
+ const list = await runGit(repoRoot, ["worktree", "list", "--porcelain"], exec);
527
+ const registered = new Set(
528
+ (list.ok ? list.stdout : "").split("\n").filter((l) => l.startsWith("worktree ")).map((l) => l.slice("worktree ".length).trim()),
529
+ );
530
+ for (const entry of entries) {
531
+ if (entry.endsWith(OWNER_SUFFIX)) continue; // marker files, not sandboxes
532
+ const dir = path.join(base, entry);
533
+ // The nested .gitignore is a FILE, not a sandbox — never scan/rm it.
534
+ if (!(await fs.stat(dir).then((s) => s.isDirectory()).catch(() => false))) continue;
535
+ const owner = await readOwnerMarker(base, entry);
536
+ if (owner && pidAlive(owner.pid)) { kept++; continue; }
537
+ // ponytail: pid recycling can false-KEEP a stale sandbox (safe
538
+ // direction); `/subagent worktrees clean` is the manual override.
539
+ try {
540
+ if (registered.has(dir)) await runGit(repoRoot, ["worktree", "remove", "--force", dir], exec);
541
+ await fs.rm(dir, { recursive: true, force: true });
542
+ await fs.rm(path.join(base, `${entry}${OWNER_SUFFIX}`), { force: true });
543
+ removed.push(dir);
544
+ } catch { /* best effort per dir */ }
545
+ }
546
+ });
547
+ return { removed, kept };
548
+ } catch {
549
+ return { removed, kept: 0 };
550
+ }
551
+ }
552
+
553
+ /** Ponytail ceiling: baseline patches are buffered as JS strings — refuse a
554
+ * pathological tree instead of blowing the heap (OMP #8939 lesson). Not a
555
+ * setting. */
556
+ const BASELINE_MAX_BYTES = 256 * 1024 * 1024;
557
+
558
+ /** Capture the parent's uncommitted state as PURE READS — no `git add`, no
559
+ * `stash create` (both mutate the parent; add stages the user's files, stash
560
+ * writes ODB objects). Order mirrors working-tree construction: staged, then
561
+ * unstaged (they can overlap), then untracked as new-file diffs. */
562
+ export async function captureParentBaseline(
563
+ repoRoot: string,
564
+ exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
565
+ ): Promise<{ ok: boolean; patch?: string; error?: string }> {
566
+ try {
567
+ const staged = await runGit(repoRoot, ["diff", "--cached", "--binary"], exec);
568
+ if (!staged.ok) return { ok: false, error: staged.stderr.trim() || "git diff --cached failed" };
569
+ const unstaged = await runGit(repoRoot, ["diff", "--binary"], exec);
570
+ if (!unstaged.ok) return { ok: false, error: unstaged.stderr.trim() || "git diff failed" };
571
+ const ls = await runGit(repoRoot, ["ls-files", "--others", "--exclude-standard"], exec);
572
+ if (!ls.ok) return { ok: false, error: ls.stderr.trim() || "git ls-files failed" };
573
+ const parts: string[] = [];
574
+ let total = Buffer.byteLength(staged.stdout) + Buffer.byteLength(unstaged.stdout);
575
+ if (total > BASELINE_MAX_BYTES) return { ok: false, error: "baseline exceeds 256 MiB budget; skipping carry" };
576
+ if (staged.stdout.trim()) parts.push(staged.stdout);
577
+ if (unstaged.stdout.trim()) parts.push(unstaged.stdout);
578
+ const untracked = ls.stdout.split("\n").map((l) => l.trim()).filter(Boolean);
579
+ for (const entry of untracked) {
580
+ // `diff --no-index` exits 1 when files differ — here that IS success;
581
+ // empty stdout means a vanished entry.
582
+ const diff = await runGit(repoRoot, ["diff", "--no-index", "--binary", "--", "/dev/null", entry], exec);
583
+ if (!diff.stdout.trim()) continue;
584
+ total += Buffer.byteLength(diff.stdout);
585
+ if (total > BASELINE_MAX_BYTES) return { ok: false, error: "baseline exceeds 256 MiB budget; skipping carry" };
586
+ parts.push(diff.stdout);
587
+ }
588
+ return { ok: true, patch: parts.join("\n") };
589
+ } catch (error) {
590
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
591
+ }
592
+ }
593
+
594
+ /** Apply a captured baseline patch inside the worktree (its own index —
595
+ * disposable). Failure is the CALLER's cue to skip carry and note stderr. */
596
+ export async function applyBaselineToWorktree(
597
+ worktreeDir: string,
598
+ patch: string,
599
+ exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
600
+ ): Promise<{ ok: boolean; error?: string }> {
601
+ const tmp = path.join(os.tmpdir(), `pi-subagent-baseline-${randomUUID()}.patch`);
602
+ try {
603
+ const patchText = patch.endsWith("\n") ? patch : `${patch}\n`;
604
+ // wx: never follow a pre-planted symlink at this path (shared /tmp).
605
+ await fs.writeFile(tmp, patchText, { encoding: "utf8", flag: "wx" });
606
+ const res = await runGit(worktreeDir, ["apply", "--binary", "--whitespace=nowarn", tmp], exec);
607
+ return res.ok ? { ok: true } : { ok: false, error: (res.stderr || res.stdout).trim() || "git apply failed" };
608
+ } catch (error) {
609
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
610
+ } finally {
611
+ await fs.rm(tmp, { force: true }).catch(() => { /* best effort */ });
612
+ }
613
+ }
614
+
615
+ /** Where CoW cloning is attempted: darwin `cp -c` is clonefile(2) — near-zero
616
+ * time and marginal disk, and the copy carries uncommitted state, node_modules
617
+ * and .env for free. Linux cp --reflink=auto silently degrades to a FULL copy
618
+ * of a big tree, so it is deliberately NOT used (git worktree is safer there). */
619
+ function cowAvailable(): boolean {
620
+ return process.platform === "darwin";
621
+ }
622
+
623
+ /** Materialize the sandbox by CoW-cloning the working tree. The copy is a
624
+ * FULLY independent repo (copied .git — no shared ref namespace, no detach
625
+ * needed) and needs no baseline patches: it IS the working tree incl. WIP.
626
+ *
627
+ * Construction is self-copy-safe (BSD cp lacks GNU's guard): each top-level
628
+ * entry is copied individually into a staging dir OUTSIDE the copied tree
629
+ * (sibling of repoRoot — same FS, so the final rename is atomic), and
630
+ * `.pi-worktrees` is skipped so prior sandboxes never compound into the
631
+ * copy. Any failure → rm staging, caller falls back to `git worktree add`. */
632
+ async function createCowClone(
633
+ repoRoot: string,
634
+ wtPath: string,
635
+ exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
636
+ ): Promise<boolean> {
637
+ if (!cowAvailable()) return false;
638
+ const run = exec ?? defaultExec;
639
+ const staging = path.join(path.dirname(repoRoot), `.pi-wt-tmp-${path.basename(wtPath)}`);
640
+ try {
641
+ await fs.mkdir(staging, { recursive: true });
642
+ const entries = await fs.readdir(repoRoot, { withFileTypes: true });
643
+ for (const entry of entries) {
644
+ if (entry.name === WORKTREE_DIR_NAME) continue;
645
+ const res = await run("cp", ["-cR", path.join(repoRoot, entry.name), path.join(staging, entry.name)], { timeout: 300_000 });
646
+ if (res.code !== 0) return false;
647
+ }
648
+ await fs.mkdir(path.dirname(wtPath), { recursive: true });
649
+ try {
650
+ await fs.rename(staging, wtPath);
651
+ } catch {
652
+ // EXDEV (repoRoot is a mount point) — CoW unusable here.
653
+ return false;
654
+ }
655
+ return true;
656
+ } catch {
657
+ return false;
658
+ } finally {
659
+ await fs.rm(staging, { recursive: true, force: true }).catch(() => { /* best effort */ });
660
+ }
661
+ }
662
+
663
+ /** Copy gitignored files named in <repoRoot>/.worktreeinclude into the
664
+ * worktree (git-worktree fallback lacks them). Lines: gitignore-style globs,
665
+ * matched against gitignored files only (ls-files --others --ignored);
666
+ * `#` comments and blanks skipped. Zero-dep glob→regex, ~15 lines. */
667
+ export async function copyWorktreeIncludes(
668
+ repoRoot: string,
669
+ worktreeDir: string,
670
+ exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
671
+ ): Promise<number> {
672
+ let raw: string;
673
+ try {
674
+ raw = await fs.readFile(path.join(repoRoot, ".worktreeinclude"), "utf8");
675
+ } catch {
676
+ return 0;
677
+ }
678
+ const patterns = raw.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#"));
679
+ if (patterns.length === 0) return 0;
680
+ const regexes = patterns.map((p) => globToRegExp(p)).filter((r): r is RegExp => r !== null);
681
+ if (regexes.length === 0) return 0;
682
+ const ls = await runGit(repoRoot, ["ls-files", "--others", "--ignored", "--exclude-standard"], exec);
683
+ if (!ls.ok) return 0;
684
+ const matches = ls.stdout.split("\n").map((l) => l.trim()).filter(Boolean)
685
+ .filter((f) => regexes.some((re) => re.test(f)));
686
+ let copied = 0;
687
+ for (const rel of matches.slice(0, 500)) {
688
+ const src = path.join(repoRoot, rel);
689
+ const dst = path.join(worktreeDir, rel);
690
+ try {
691
+ const st = await fs.stat(src);
692
+ if (!st.isFile()) continue;
693
+ await fs.mkdir(path.dirname(dst), { recursive: true });
694
+ await fs.copyFile(src, dst);
695
+ copied++;
696
+ } catch { /* skip vanished/unreadable */ }
697
+ }
698
+ return copied;
699
+ }
700
+
701
+ /** Gitignore-style glob → RegExp. Supports `*`, `**`, `?`, leading/trailing
702
+ * `/`, and `dir/` (prefix). Negations unsupported (returns null). */
703
+ function globToRegExp(globRaw: string): RegExp | null {
704
+ let glob = globRaw;
705
+ if (glob.startsWith("!")) return null;
706
+ let prefix = false;
707
+ if (glob.endsWith("/")) { prefix = true; glob = glob.slice(0, -1); }
708
+ glob = glob.replace(/^\//, "");
709
+ let re = "";
710
+ for (let i = 0; i < glob.length; i++) {
711
+ const c = glob[i];
712
+ if (c === "*" && glob[i + 1] === "*") { re += ".*"; i++; }
713
+ else if (c === "*") re += "[^/]*";
714
+ else if (c === "?") re += "[^/]";
715
+ else re += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
716
+ }
717
+ try {
718
+ return prefix ? new RegExp(`^${re}(/|$)`) : new RegExp(`^${re}$`);
719
+ } catch {
720
+ return null;
721
+ }
722
+ }
723
+
724
+ /** Create a sandbox at .pi-worktrees/<rand> under the repo root: CoW clone of
725
+ * the working tree when available (carries WIP + node_modules + .env), else a
726
+ * detached git worktree the caller can seed with captureParentBaseline. */
404
727
  export async function createWorktree(
405
728
  cwd: string,
406
729
  exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
407
- ): Promise<{ ok: boolean; path?: string; repoRoot?: string; error?: string }> {
730
+ ): Promise<{ ok: boolean; path?: string; repoRoot?: string; error?: string; /** false when the git-worktree fallback ran (caller seeds baseline); undefined = CoW copy */ cow?: boolean }> {
408
731
  try {
409
732
  const root = await runGit(cwd, ["rev-parse", "--show-toplevel"], exec);
410
733
  if (!root.ok) return { ok: false, error: root.stderr.trim() || "not a git repo" };
411
734
  const repoRoot = root.stdout.trim();
412
735
  if (!repoRoot) return { ok: false, error: "empty git root" };
413
736
  const id = `pi-subagent-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
414
- const wtPath = path.join(repoRoot, ".pi-worktrees", id);
415
- const add = await runGit(repoRoot, ["worktree", "add", "--detach", wtPath, "HEAD"], exec);
737
+ const wtPath = path.join(repoRoot, WORKTREE_DIR_NAME, id);
738
+ await ensureWorktreeBaseGitignore(path.join(repoRoot, WORKTREE_DIR_NAME));
739
+ if (await createCowClone(repoRoot, wtPath, exec)) {
740
+ await writeOwnerMarker(path.join(repoRoot, WORKTREE_DIR_NAME), id).catch(() => { /* best effort */ });
741
+ return { ok: true, path: wtPath, repoRoot };
742
+ }
743
+ // Fallback: detached git worktree (clean HEAD; the caller seeds the
744
+ // parent's WIP via applyBaselineToWorktree). worktree add mutates the
745
+ // parent's shared .git/worktrees registry.
746
+ const add = await withRepoLock(repoRoot, () => runGit(repoRoot, ["worktree", "add", "--detach", wtPath, "HEAD"], exec));
416
747
  if (!add.ok) return { ok: false, error: add.stderr.trim() || "git worktree add failed" };
417
- return { ok: true, path: wtPath, repoRoot };
748
+ await writeOwnerMarker(path.join(repoRoot, WORKTREE_DIR_NAME), id).catch(() => { /* best effort */ });
749
+ return { ok: true, path: wtPath, repoRoot, cow: false };
418
750
  } catch (error) {
419
751
  return { ok: false, error: error instanceof Error ? error.message : String(error) };
420
752
  }
@@ -438,20 +770,27 @@ export async function captureWorktreeDiff(
438
770
  return { ok: true, diff: text || "(no changes)" };
439
771
  }
440
772
 
441
- /** Remove a worktree and its metadata, best-effort. */
773
+ /** Remove a worktree and its metadata, best-effort. Handles BOTH backends:
774
+ * registered git worktrees (worktree remove) and unregistered sandbox dirs
775
+ * (plain rm). */
442
776
  export async function removeWorktree(
443
777
  repoRoot: string,
444
778
  worktreeDir: string,
445
779
  exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
446
780
  ): Promise<void> {
447
781
  try {
448
- await runGit(repoRoot, ["worktree", "remove", "--force", worktreeDir], exec);
782
+ // Marker is a SIBLING file (never inside the sandbox — see OWNER_SUFFIX).
783
+ await fs.rm(`${worktreeDir}${OWNER_SUFFIX}`, { force: true }).catch(() => {});
784
+ await withRepoLock(repoRoot, async () => {
785
+ const removed = await runGit(repoRoot, ["worktree", "remove", "--force", worktreeDir], exec);
786
+ if (!removed.ok) await fs.rm(worktreeDir, { recursive: true, force: true }).catch(() => { /* best effort */ });
787
+ });
449
788
  } catch { /* best effort */ }
450
789
  }
451
790
 
452
791
  /** Serialized `git apply` on the parent checkout: parallel siblings finishing
453
- * at the same time must not race the merge (OMP's withRepoLock equivalent). */
454
- let applyChain: Promise<unknown> = Promise.resolve();
792
+ * at the same time must not race the merge (withRepoLock — the OMP
793
+ * withRepoLock equivalent, now shared with worktree add/remove too). */
455
794
 
456
795
  /** Apply a unified diff to the repo root via `git apply --3way`. Never throws;
457
796
  * ok:false means conflict/failure — the caller reports it and still delivers
@@ -461,8 +800,8 @@ export async function applyWorktreePatch3way(
461
800
  diff: string,
462
801
  exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
463
802
  ): Promise<{ ok: boolean; stderr: string }> {
464
- const run = applyChain.then(async (): Promise<{ ok: boolean; stderr: string }> => {
465
- const tmp = path.join(os.tmpdir(), `pi-subagent-apply-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}.patch`);
803
+ return withRepoLock(repoRoot, async (): Promise<{ ok: boolean; stderr: string }> => {
804
+ const tmp = path.join(os.tmpdir(), `pi-subagent-apply-${randomUUID()}.patch`);
466
805
  try {
467
806
  // git apply interprets paths relative to cwd — write the diff to a file
468
807
  // and apply at the repo root. captureWorktreeDiff trims trailing
@@ -470,7 +809,8 @@ export async function applyWorktreePatch3way(
470
809
  // restore it (CRLF-aware: trimming "...\r\n" must not downgrade the
471
810
  // final line ending to LF).
472
811
  const patchText = diff.endsWith("\n") ? diff : `${diff}${diff.includes("\r\n") ? "\r\n" : "\n"}`;
473
- await fs.writeFile(tmp, patchText, "utf8");
812
+ // wx: never follow a pre-planted symlink at this path (shared /tmp).
813
+ await fs.writeFile(tmp, patchText, { encoding: "utf8", flag: "wx" });
474
814
  const res = await runGit(repoRoot, ["apply", "--3way", tmp], exec);
475
815
  return { ok: res.ok, stderr: (res.stderr || res.stdout).trim() };
476
816
  } catch (error) {
@@ -479,8 +819,6 @@ export async function applyWorktreePatch3way(
479
819
  await fs.rm(tmp, { force: true }).catch(() => { /* best effort */ });
480
820
  }
481
821
  });
482
- applyChain = run.then(() => undefined, () => undefined);
483
- return run;
484
822
  }
485
823
 
486
824
  /** Model-facing patch block for a worktree result; "" when there is no patch.
@@ -0,0 +1,230 @@
1
+ // Worktree sandbox lifecycle — lock serialization, owner marker, GC sweep,
2
+ // CoW clone construction, baseline carry (READ-ONLY on the parent), and
3
+ // .worktreeinclude copying. Git state is exercised through a scripted exec
4
+ // fake (the module's established seam) so no assertion depends on the host's
5
+ // git version; on-disk effects use real temp dirs.
6
+
7
+ import assert from "node:assert/strict";
8
+ import { mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+ import { after, describe, it } from "node:test";
12
+ import {
13
+ applyBaselineToWorktree,
14
+ captureParentBaseline,
15
+ copyWorktreeIncludes,
16
+ createWorktree,
17
+ pidAlive,
18
+ sweepStaleWorktrees,
19
+ withRepoLock,
20
+ WORKTREE_DIR_NAME,
21
+ } from "../lib/runner.ts";
22
+
23
+ const dirs: string[] = [];
24
+ after(async () => {
25
+ await Promise.all(dirs.map((d) => rm(d, { recursive: true, force: true })));
26
+ });
27
+
28
+ async function tempDir(prefix: string): Promise<string> {
29
+ const dir = await mkdtemp(join(tmpdir(), prefix));
30
+ dirs.push(dir);
31
+ return dir;
32
+ }
33
+
34
+ type Exec = (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>;
35
+
36
+ /** Scripted exec: records every (command, args, cwd) and answers from a map of
37
+ * predicate → response (first match wins). Unmatched git calls succeed empty. */
38
+ function fakeExec(handlers: Array<{ match: (command: string, args: string[], cwd?: string) => boolean; code?: number; stdout?: string; stderr?: string }>): Exec & { calls: { command: string; args: string[]; cwd?: string }[] } {
39
+ const calls: { command: string; args: string[]; cwd?: string }[] = [];
40
+ const fn = async (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => {
41
+ calls.push({ command, args, cwd: options?.cwd });
42
+ const hit = handlers.find((h) => h.match(command, args, options?.cwd));
43
+ if (!hit && command === "git") return { code: 0, stdout: "", stderr: "" };
44
+ if (!hit) return { code: 1, stdout: "", stderr: `unexpected command: ${command} ${args.join(" ")}` };
45
+ return { code: hit.code ?? 0, stdout: hit.stdout ?? "", stderr: hit.stderr ?? "" };
46
+ };
47
+ (fn as Exec & { calls: typeof calls }).calls = calls;
48
+ return fn as Exec & { calls: typeof calls };
49
+ }
50
+
51
+ // ── withRepoLock: serialization + error isolation ──────────────────────────
52
+
53
+ describe("withRepoLock", () => {
54
+ it("serializes same-repo blocks and releases the key when idle", async () => {
55
+ const order: string[] = [];
56
+ let release1: (() => void) | undefined;
57
+ const gate = new Promise<void>((r) => { release1 = r; });
58
+ const p1 = withRepoLock("/repo", async () => { order.push("a-start"); await gate; order.push("a-end"); });
59
+ const p2 = withRepoLock("/repo", async () => { order.push("b-start"); });
60
+ await new Promise((r) => setTimeout(r, 10));
61
+ assert.deepEqual(order, ["a-start"]); // b must be waiting
62
+ release1!();
63
+ await Promise.all([p1, p2]);
64
+ assert.deepEqual(order, ["a-start", "a-end", "b-start"]);
65
+ });
66
+
67
+ it("a failing block does not poison the queue and still propagates to its caller", async () => {
68
+ await assert.rejects(withRepoLock("/repo2", async () => { throw new Error("boom"); }), /boom/);
69
+ const out = await withRepoLock("/repo2", async () => "clean");
70
+ assert.equal(out, "clean");
71
+ });
72
+
73
+ it("different repos do not block each other", async () => {
74
+ const order: string[] = [];
75
+ await Promise.all([
76
+ withRepoLock("/repoA", async () => { await new Promise((r) => setTimeout(r, 20)); order.push("A"); }),
77
+ withRepoLock("/repoB", async () => { order.push("B"); }),
78
+ ]);
79
+ assert.deepEqual(order, ["B", "A"]);
80
+ });
81
+ });
82
+
83
+ // ── Owner marker + pid liveness ─────────────────────────────────────────────
84
+
85
+ describe("owner marker + pid liveness", () => {
86
+ it("pidAlive: current process alive, pid 2^22 dead", () => {
87
+ assert.equal(pidAlive(process.pid), true);
88
+ // A pid that cannot exist on any supported host (max pid < 2^22 everywhere
89
+ // practical; on Linux pid_max default caps at 32768/4194304).
90
+ assert.equal(pidAlive(16 * 1024 * 1024), false);
91
+ });
92
+ });
93
+
94
+ // ── GC sweep decisions ──────────────────────────────────────────────────────
95
+
96
+ describe("sweepStaleWorktrees", () => {
97
+ it("removes dead-pid and marker-less sandboxes, keeps live ones, uses worktree remove for registered dirs", async () => {
98
+ const repo = await tempDir("wt-sweep-repo-");
99
+ const base = join(repo, WORKTREE_DIR_NAME);
100
+ await mkdir(join(base, "dead"), { recursive: true });
101
+ await mkdir(join(base, "live"), { recursive: true });
102
+ await mkdir(join(base, "legacy"), { recursive: true });
103
+ await writeFile(join(base, "dead.owner.json"), JSON.stringify({ pid: 16 * 1024 * 1024, id: "dead", createdAt: 1 }));
104
+ await writeFile(join(base, "live.owner.json"), JSON.stringify({ pid: process.pid, id: "live", createdAt: Date.now() }));
105
+ const wtList = `worktree ${repo}\nHEAD abc\n\nworktree ${join(base, "dead")}\nHEAD def\n\n`;
106
+ const exec = fakeExec([
107
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
108
+ { match: (_c, args) => args[0] === "worktree" && args[1] === "list", stdout: wtList },
109
+ ]);
110
+ const result = await sweepStaleWorktrees(repo, exec);
111
+ assert.deepEqual(result.removed.map((r) => r.split("/").pop()).sort(), ["dead", "legacy"]);
112
+ assert.equal(result.kept, 1);
113
+ const removeCalls = exec.calls.filter((c) => c.args[0] === "worktree" && c.args[1] === "remove");
114
+ assert.equal(removeCalls.length, 1); // only the registered one via git
115
+ assert.ok(removeCalls[0].args[3].includes("dead"));
116
+ await assert.rejects(stat(join(base, "dead")));
117
+ await assert.rejects(stat(join(base, "legacy")));
118
+ await stat(join(base, "live")); // still there
119
+ });
120
+
121
+ it("no .pi-worktrees dir → zero cost, no git calls beyond rev-parse", async () => {
122
+ const repo = await tempDir("wt-sweep-empty-");
123
+ const exec = fakeExec([{ match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` }]);
124
+ const result = await sweepStaleWorktrees(repo, exec);
125
+ assert.deepEqual(result, { removed: [], kept: 0 });
126
+ assert.equal(exec.calls.length, 1);
127
+ });
128
+ });
129
+
130
+ // ── Baseline capture: PURE READS on the parent ─────────────────────────────
131
+
132
+ describe("captureParentBaseline", () => {
133
+ it("composes staged + unstaged + untracked diffs; ZERO parent-mutating git args", async () => {
134
+ const repo = "/fake/repo";
135
+ const exec = fakeExec([
136
+ { match: (_c, args) => args[0] === "diff" && args.includes("--cached"), stdout: "STAGED-PATCH\n" },
137
+ { match: (_c, args) => args[0] === "diff" && args.includes("--no-index"), stdout: "UNTRACKED-PATCH\n" },
138
+ { match: (_c, args) => args[0] === "diff", stdout: "UNSTAGED-PATCH\n" },
139
+ { match: (_c, args) => args[0] === "ls-files", stdout: "new1.txt\nnew2.txt\n" },
140
+ ]);
141
+ const result = await captureParentBaseline(repo, exec);
142
+ assert.ok(result.ok);
143
+ // Order mirrors working-tree construction: staged, unstaged, untracked.
144
+ assert.equal(result.patch, "STAGED-PATCH\n\nUNSTAGED-PATCH\n\nUNTRACKED-PATCH\n\nUNTRACKED-PATCH\n");
145
+ const mutators = exec.calls.filter((c) =>
146
+ c.args.includes("add") || c.args.includes("stash") || c.args.includes("commit") || c.args.includes("apply"));
147
+ assert.deepEqual(mutators, []); // parent purity — the advisor-reviewed invariant
148
+ // Untracked diffs are new-file no-index diffs against /dev/null.
149
+ const noIndex = exec.calls.filter((c) => c.args.includes("--no-index"));
150
+ assert.equal(noIndex.length, 2);
151
+ assert.deepEqual(noIndex[0].args.slice(-2), ["/dev/null", "new1.txt"]);
152
+ });
153
+
154
+ it("256 MiB budget: oversized baseline is skipped with an error, not buffered", async () => {
155
+ const repo = "/fake/repo2";
156
+ const big = "x".repeat(300 * 1024 * 1024);
157
+ const exec = fakeExec([
158
+ { match: (_c, args) => args[0] === "diff" && args.includes("--cached"), stdout: big },
159
+ { match: (_c, args) => args[0] === "diff" && !args.includes("--cached"), stdout: "" },
160
+ { match: (_c, args) => args[0] === "ls-files", stdout: "" },
161
+ ]);
162
+ const result = await captureParentBaseline(repo, exec);
163
+ assert.equal(result.ok, false);
164
+ assert.match(result.error!, /budget/);
165
+ });
166
+ });
167
+
168
+ // ── Baseline apply: runs INSIDE the worktree cwd ────────────────────────────
169
+
170
+ describe("applyBaselineToWorktree", () => {
171
+ it("writes the patch to a temp file and applies it in the worktree cwd", async () => {
172
+ let seen: { args: string[]; cwd?: string } | undefined;
173
+ const exec = fakeExec([]);
174
+ const orig = exec;
175
+ const wrapped: Exec = async (command, args, options) => {
176
+ if (command === "git" && args[0] === "apply") seen = { args, cwd: options?.cwd };
177
+ return orig(command, args, options);
178
+ };
179
+ const result = await applyBaselineToWorktree("/wt/dir", "PATCH\n", wrapped);
180
+ assert.ok(result.ok);
181
+ assert.equal(seen!.cwd, "/wt/dir");
182
+ assert.deepEqual(seen!.args.slice(0, 3), ["apply", "--binary", "--whitespace=nowarn"]);
183
+ });
184
+
185
+ it("apply failure surfaces the error (caller skips carry)", async () => {
186
+ const exec = fakeExec([{ match: (_c, args) => args[0] === "apply", code: 1, stderr: "error: patch does not apply" }]);
187
+ const result = await applyBaselineToWorktree("/wt/dir", "PATCH\n", exec);
188
+ assert.equal(result.ok, false);
189
+ assert.match(result.error!, /does not apply/);
190
+ });
191
+ });
192
+
193
+ // ── .worktreeinclude ────────────────────────────────────────────────────────
194
+
195
+ describe("copyWorktreeIncludes", () => {
196
+ it("copies gitignored files matching the include globs into the worktree", async () => {
197
+ const repo = await tempDir("wt-include-repo-");
198
+ const wt = await tempDir("wt-include-dst-");
199
+ await writeFile(join(repo, ".worktreeinclude"), "# env and config\n.env\nconfig/*.local\n");
200
+ await mkdir(join(repo, "config"), { recursive: true });
201
+ await writeFile(join(repo, ".env"), "SECRET=1\n");
202
+ await writeFile(join(repo, "config", "dev.local"), "x=1\n");
203
+ await writeFile(join(repo, "config", "keep.txt"), "not matched\n");
204
+ const exec = fakeExec([{ match: (_c, args) => args[0] === "ls-files", stdout: ".env\nconfig/dev.local\nconfig/keep.txt\n" }]);
205
+ const copied = await copyWorktreeIncludes(repo, wt, exec);
206
+ assert.equal(copied, 2);
207
+ assert.equal(await readFile(join(wt, ".env"), "utf8"), "SECRET=1\n");
208
+ assert.equal(await readFile(join(wt, "config", "dev.local"), "utf8"), "x=1\n");
209
+ await assert.rejects(stat(join(wt, "config", "keep.txt"))); // not gitignored-matched
210
+ });
211
+
212
+ it("no .worktreeinclude → no git calls, returns 0", async () => {
213
+ const repo = await tempDir("wt-include-none-");
214
+ const exec = fakeExec([]);
215
+ assert.equal(await copyWorktreeIncludes(repo, "/wt", exec), 0);
216
+ assert.equal(exec.calls.length, 0);
217
+ });
218
+ });
219
+
220
+ // ── createWorktree: CoW construction + fallback ─────────────────────────────
221
+
222
+ describe("createWorktree", () => {
223
+ it("not-a-repo fails cleanly", async () => {
224
+ const dir = await tempDir("wt-create-norepo-");
225
+ const exec = fakeExec([{ match: (_c, args) => args[0] === "rev-parse", code: 128, stderr: "not a git repository" }]);
226
+ const result = await createWorktree(dir, exec);
227
+ assert.equal(result.ok, false);
228
+ assert.match(result.error!, /not a git repo/);
229
+ });
230
+ });