ceulen 0.10.1 → 0.12.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 (69) hide show
  1. package/CHANGELOG.md +107 -1
  2. package/README.md +56 -1
  3. package/extensions/index.ts +5 -1
  4. package/extensions/lib/env.test.ts +147 -0
  5. package/extensions/lib/env.ts +180 -0
  6. package/extensions/lib/order.test.ts +74 -0
  7. package/extensions/lib/plan-bridge.ts +18 -0
  8. package/extensions/lib/registry.test.ts +8 -5
  9. package/extensions/lib/registry.ts +22 -3
  10. package/extensions/modules/a2a/configPanel.ts +42 -1
  11. package/extensions/modules/a2a/index.ts +4 -2
  12. package/extensions/modules/a2a/lib/config.ts +8 -3
  13. package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
  14. package/extensions/modules/advisor/index.ts +6 -3
  15. package/extensions/modules/advisor/test/module.test.ts +31 -0
  16. package/extensions/modules/attachments/configPanel.ts +91 -0
  17. package/extensions/modules/attachments/index.ts +274 -0
  18. package/extensions/modules/attachments/lib/clipboard-files.ts +80 -0
  19. package/extensions/modules/attachments/lib/pastes.ts +45 -0
  20. package/extensions/modules/attachments/lib/paths.ts +74 -0
  21. package/extensions/modules/attachments/lib/registry.ts +70 -0
  22. package/extensions/modules/attachments/lib/settings.ts +99 -0
  23. package/extensions/modules/attachments/lib/tray.ts +74 -0
  24. package/extensions/modules/attachments/test/configPanel.test.ts +122 -0
  25. package/extensions/modules/attachments/test/index.test.ts +870 -0
  26. package/extensions/modules/attachments/test/module.test.ts +53 -0
  27. package/extensions/modules/classifier/index.ts +55 -1
  28. package/extensions/modules/classifier/test/classifier.test.ts +62 -0
  29. package/extensions/modules/composer/test/module.test.ts +2 -2
  30. package/extensions/modules/config/index.ts +3 -0
  31. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  32. package/extensions/modules/cron/configPanel.ts +103 -0
  33. package/extensions/modules/cron/index.ts +638 -0
  34. package/extensions/modules/cron/lib/jobs.ts +201 -0
  35. package/extensions/modules/cron/lib/schedule.ts +161 -0
  36. package/extensions/modules/cron/test/cwd-repro.test.ts +98 -0
  37. package/extensions/modules/cron/test/index.test.ts +859 -0
  38. package/extensions/modules/cron/test/schedule.test.ts +93 -0
  39. package/extensions/modules/munin/index.ts +3 -1
  40. package/extensions/modules/permission/index.ts +567 -0
  41. package/extensions/modules/permission/test/permission.test.ts +789 -0
  42. package/extensions/modules/plan/index.ts +5 -0
  43. package/extensions/modules/repair/index.ts +160 -5
  44. package/extensions/modules/repair/test/freshness.test.ts +209 -0
  45. package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
  46. package/extensions/modules/router/configPanel.ts +4 -4
  47. package/extensions/modules/router/index.ts +1 -1
  48. package/extensions/modules/router/lib/config.ts +9 -4
  49. package/extensions/modules/router/lib/systemone.ts +17 -4
  50. package/extensions/modules/router/test/unit.test.ts +46 -1
  51. package/extensions/modules/rules/index.ts +13 -3
  52. package/extensions/modules/rules/lib/rules.ts +24 -12
  53. package/extensions/modules/rules/test/lib.test.ts +20 -0
  54. package/extensions/modules/rules/test/module.test.ts +21 -0
  55. package/extensions/modules/subagent/index.ts +49 -10
  56. package/extensions/modules/subagent/lib/herdr.ts +5 -0
  57. package/extensions/modules/subagent/lib/routing.ts +31 -8
  58. package/extensions/modules/subagent/lib/runner.ts +356 -14
  59. package/extensions/modules/subagent/test/routing.test.ts +45 -0
  60. package/extensions/modules/subagent/test/worktree.test.ts +230 -0
  61. package/extensions/modules/usage/index.ts +193 -71
  62. package/extensions/modules/usage/test/context.test.ts +160 -120
  63. package/extensions/modules/web/configPanel.ts +67 -8
  64. package/extensions/modules/web/index.ts +3 -1
  65. package/extensions/modules/web/test/a11y.test.ts +1 -1
  66. package/extensions/modules/web/test/configPanel.test.ts +7 -3
  67. package/extensions/modules/web/test/settings.test.ts +6 -0
  68. package/package.json +2 -2
  69. package/skills/cron/SKILL.md +58 -0
@@ -261,6 +261,25 @@ export async function runSubAgent(options: {
261
261
  worktreeDir = wt.path;
262
262
  worktreeRepoRoot = wt.repoRoot;
263
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
+ }
264
283
  } else if (wt.error) {
265
284
  result.stderr = `Worktree unavailable (${wt.error}); running in workspace.`;
266
285
  }
@@ -276,7 +295,10 @@ export async function runSubAgent(options: {
276
295
  } as any);
277
296
  session = created.session;
278
297
  } catch (error) {
279
- if (worktreeDir) await removeWorktree(cwd, worktreeDir, exec);
298
+ // Lock on the RESOLVED repo root (createWorktree/applyWorktreePatch3way do): a
299
+ // child dispatched with a subdirectory cwd must not key the per-repo lock
300
+ // differently — parallel siblings would race git's O_EXCL index.lock.
301
+ if (worktreeDir) await removeWorktree(worktreeRepoRoot ?? cwd, worktreeDir, exec);
280
302
  throw error;
281
303
  }
282
304
  let unsubscribe: (() => void) | undefined;
@@ -351,7 +373,10 @@ export async function runSubAgent(options: {
351
373
  } finally {
352
374
  unsubscribe?.(); removeAbort?.();
353
375
  try { session.dispose(); } catch { /* best effort */ }
354
- if (worktreeDir) await removeWorktree(cwd, worktreeDir, exec);
376
+ // Lock on the RESOLVED repo root (createWorktree/applyWorktreePatch3way do): a
377
+ // child dispatched with a subdirectory cwd must not key the per-repo lock
378
+ // differently — parallel siblings would race git's O_EXCL index.lock.
379
+ if (worktreeDir) await removeWorktree(worktreeRepoRoot ?? cwd, worktreeDir, exec);
355
380
  }
356
381
  } catch (error) {
357
382
  result.exitCode = 1;
@@ -401,21 +426,333 @@ async function runGit(
401
426
  return { ok: res.code === 0, stdout: res.stdout, stderr: res.stderr };
402
427
  }
403
428
 
404
- /** Create a detached git worktree at .pi-worktrees/<rand> under the repo root. */
429
+ /** Per-repo serialization for git operations that mutate the SHARED parent
430
+ * `.git` (worktree add/remove registry, `git apply`'s index/ODB writes).
431
+ * Git's own locks are O_EXCL with no waiter — concurrent mutations fail
432
+ * instantly instead of blocking (OMP withRepoLock precedent), so callers
433
+ * that can collide must queue here. Keyed by repo root so parallel repos
434
+ * stay independent; a failing block does not poison the queue. */
435
+ const repoLocks = new Map<string, Promise<unknown>>();
436
+
437
+ export async function withRepoLock<T>(repoRoot: string, fn: () => Promise<T>): Promise<T> {
438
+ const key = path.resolve(repoRoot);
439
+ const prior = repoLocks.get(key) ?? Promise.resolve();
440
+ const run = prior.then(fn, fn);
441
+ // The stored chain swallows errors so the NEXT caller starts clean; the
442
+ // returned promise still propagates this block's error to its own caller.
443
+ const stored = run.then(() => undefined, () => undefined);
444
+ repoLocks.set(key, stored);
445
+ // Drop the key once idle so the map cannot grow unboundedly across repos.
446
+ // A concurrent waiter has already replaced the stored chain by then.
447
+ stored.then(() => { if (repoLocks.get(key) === stored) repoLocks.delete(key); });
448
+ return run;
449
+ }
450
+
451
+ /** Owner marker written into every worktree sandbox: lets the GC sweep tell a
452
+ * live session's sandbox from a crashed run's leftover. */
453
+ export interface WorktreeOwner {
454
+ pid: number;
455
+ id: string;
456
+ createdAt: number;
457
+ }
458
+
459
+ export const WORKTREE_DIR_NAME = ".pi-worktrees";
460
+
461
+ /** A nested `.gitignore` (content `*`) inside the sandbox base keeps sandboxes
462
+ * out of the parent's `git status` AND out of untracked baseline capture —
463
+ * without touching the user's own .gitignore. */
464
+ async function ensureWorktreeBaseGitignore(base: string): Promise<void> {
465
+ const ignoreFile = path.join(base, ".gitignore");
466
+ try {
467
+ await fs.mkdir(base, { recursive: true });
468
+ await fs.writeFile(ignoreFile, "*\n", { flag: "wx" });
469
+ } catch { /* exists (or unwritable) — either is fine */ }
470
+ }
471
+
472
+ /** Owner marker: a SIBLING file inside the (gitignored) sandbox base —
473
+ * deliberately NOT inside the sandbox, so it never leaks into
474
+ * captureWorktreeDiff (`add -A` + diff) or the child's own reads. Two
475
+ * parallel merges would otherwise add/add-conflict on it (found by the
476
+ * concurrent-merge race test). */
477
+ export const OWNER_SUFFIX = ".owner.json";
478
+
479
+ async function writeOwnerMarker(base: string, id: string): Promise<void> {
480
+ const owner: WorktreeOwner = { pid: process.pid, id, createdAt: Date.now() };
481
+ await fs.writeFile(path.join(base, `${id}${OWNER_SUFFIX}`), JSON.stringify(owner), { encoding: "utf8", mode: 0o600 });
482
+ }
483
+
484
+ async function readOwnerMarker(base: string, entry: string): Promise<WorktreeOwner | undefined> {
485
+ try {
486
+ const raw = await fs.readFile(path.join(base, `${entry}${OWNER_SUFFIX}`), "utf8");
487
+ const parsed = JSON.parse(raw) as WorktreeOwner;
488
+ if (typeof parsed?.pid !== "number" || typeof parsed?.id !== "string") return undefined;
489
+ return parsed;
490
+ } catch {
491
+ return undefined;
492
+ }
493
+ }
494
+
495
+ /** Is a pid alive? EPERM counts as alive (another user's process). */
496
+ export function pidAlive(pid: number): boolean {
497
+ try {
498
+ process.kill(pid, 0);
499
+ return true;
500
+ } catch (err) {
501
+ return (err as NodeJS.ErrnoException)?.code === "EPERM";
502
+ }
503
+ }
504
+
505
+ export interface SweepResult {
506
+ removed: string[];
507
+ kept: number;
508
+ }
509
+
510
+ /** Remove crashed runs' worktree sandboxes under <repoRoot>/.pi-worktrees.
511
+ * Source of truth is the DIRECTORY (covers both backends); the git
512
+ * registration check only decides HOW a stale dir is removed. Never removes
513
+ * a sandbox whose marker pid is alive. Best-effort throughout. */
514
+ export async function sweepStaleWorktrees(
515
+ cwd: string,
516
+ exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
517
+ ): Promise<SweepResult> {
518
+ const removed: string[] = [];
519
+ try {
520
+ const root = await runGit(cwd, ["rev-parse", "--show-toplevel"], exec);
521
+ if (!root.ok) return { removed, kept: 0 };
522
+ const repoRoot = root.stdout.trim();
523
+ const base = path.join(repoRoot, WORKTREE_DIR_NAME);
524
+ let entries: string[];
525
+ try {
526
+ entries = await fs.readdir(base);
527
+ } catch {
528
+ return { removed, kept: 0 }; // no .pi-worktrees — the common path
529
+ }
530
+ let kept = 0;
531
+ await withRepoLock(repoRoot, async () => {
532
+ const list = await runGit(repoRoot, ["worktree", "list", "--porcelain"], exec);
533
+ const registered = new Set(
534
+ (list.ok ? list.stdout : "").split("\n").filter((l) => l.startsWith("worktree ")).map((l) => l.slice("worktree ".length).trim()),
535
+ );
536
+ for (const entry of entries) {
537
+ if (entry.endsWith(OWNER_SUFFIX)) continue; // marker files, not sandboxes
538
+ const dir = path.join(base, entry);
539
+ // The nested .gitignore is a FILE, not a sandbox — never scan/rm it.
540
+ if (!(await fs.stat(dir).then((s) => s.isDirectory()).catch(() => false))) continue;
541
+ const owner = await readOwnerMarker(base, entry);
542
+ if (owner && pidAlive(owner.pid)) { kept++; continue; }
543
+ // ponytail: pid recycling can false-KEEP a stale sandbox (safe
544
+ // direction); `/subagent worktrees clean` is the manual override.
545
+ try {
546
+ if (registered.has(dir)) await runGit(repoRoot, ["worktree", "remove", "--force", dir], exec);
547
+ await fs.rm(dir, { recursive: true, force: true });
548
+ await fs.rm(path.join(base, `${entry}${OWNER_SUFFIX}`), { force: true });
549
+ removed.push(dir);
550
+ } catch { /* best effort per dir */ }
551
+ }
552
+ });
553
+ return { removed, kept };
554
+ } catch {
555
+ return { removed, kept: 0 };
556
+ }
557
+ }
558
+
559
+ /** Ponytail ceiling: baseline patches are buffered as JS strings — refuse a
560
+ * pathological tree instead of blowing the heap (OMP #8939 lesson). Not a
561
+ * setting. */
562
+ const BASELINE_MAX_BYTES = 256 * 1024 * 1024;
563
+
564
+ /** Capture the parent's uncommitted state as PURE READS — no `git add`, no
565
+ * `stash create` (both mutate the parent; add stages the user's files, stash
566
+ * writes ODB objects). Order mirrors working-tree construction: staged, then
567
+ * unstaged (they can overlap), then untracked as new-file diffs. */
568
+ export async function captureParentBaseline(
569
+ repoRoot: string,
570
+ exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
571
+ ): Promise<{ ok: boolean; patch?: string; error?: string }> {
572
+ try {
573
+ const staged = await runGit(repoRoot, ["diff", "--cached", "--binary"], exec);
574
+ if (!staged.ok) return { ok: false, error: staged.stderr.trim() || "git diff --cached failed" };
575
+ const unstaged = await runGit(repoRoot, ["diff", "--binary"], exec);
576
+ if (!unstaged.ok) return { ok: false, error: unstaged.stderr.trim() || "git diff failed" };
577
+ const ls = await runGit(repoRoot, ["ls-files", "--others", "--exclude-standard"], exec);
578
+ if (!ls.ok) return { ok: false, error: ls.stderr.trim() || "git ls-files failed" };
579
+ const parts: string[] = [];
580
+ let total = Buffer.byteLength(staged.stdout) + Buffer.byteLength(unstaged.stdout);
581
+ if (total > BASELINE_MAX_BYTES) return { ok: false, error: "baseline exceeds 256 MiB budget; skipping carry" };
582
+ if (staged.stdout.trim()) parts.push(staged.stdout);
583
+ if (unstaged.stdout.trim()) parts.push(unstaged.stdout);
584
+ const untracked = ls.stdout.split("\n").map((l) => l.trim()).filter(Boolean);
585
+ for (const entry of untracked) {
586
+ // `diff --no-index` exits 1 when files differ — here that IS success;
587
+ // empty stdout means a vanished entry.
588
+ const diff = await runGit(repoRoot, ["diff", "--no-index", "--binary", "--", "/dev/null", entry], exec);
589
+ if (!diff.stdout.trim()) continue;
590
+ total += Buffer.byteLength(diff.stdout);
591
+ if (total > BASELINE_MAX_BYTES) return { ok: false, error: "baseline exceeds 256 MiB budget; skipping carry" };
592
+ parts.push(diff.stdout);
593
+ }
594
+ return { ok: true, patch: parts.join("\n") };
595
+ } catch (error) {
596
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
597
+ }
598
+ }
599
+
600
+ /** Apply a captured baseline patch inside the worktree (its own index —
601
+ * disposable). Failure is the CALLER's cue to skip carry and note stderr. */
602
+ export async function applyBaselineToWorktree(
603
+ worktreeDir: string,
604
+ patch: string,
605
+ exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
606
+ ): Promise<{ ok: boolean; error?: string }> {
607
+ const tmp = path.join(os.tmpdir(), `pi-subagent-baseline-${randomUUID()}.patch`);
608
+ try {
609
+ const patchText = patch.endsWith("\n") ? patch : `${patch}\n`;
610
+ // wx: never follow a pre-planted symlink at this path (shared /tmp).
611
+ await fs.writeFile(tmp, patchText, { encoding: "utf8", flag: "wx" });
612
+ const res = await runGit(worktreeDir, ["apply", "--binary", "--whitespace=nowarn", tmp], exec);
613
+ return res.ok ? { ok: true } : { ok: false, error: (res.stderr || res.stdout).trim() || "git apply failed" };
614
+ } catch (error) {
615
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
616
+ } finally {
617
+ await fs.rm(tmp, { force: true }).catch(() => { /* best effort */ });
618
+ }
619
+ }
620
+
621
+ /** Where CoW cloning is attempted: darwin `cp -c` is clonefile(2) — near-zero
622
+ * time and marginal disk, and the copy carries uncommitted state, node_modules
623
+ * and .env for free. Linux cp --reflink=auto silently degrades to a FULL copy
624
+ * of a big tree, so it is deliberately NOT used (git worktree is safer there). */
625
+ function cowAvailable(): boolean {
626
+ return process.platform === "darwin";
627
+ }
628
+
629
+ /** Materialize the sandbox by CoW-cloning the working tree. The copy is a
630
+ * FULLY independent repo (copied .git — no shared ref namespace, no detach
631
+ * needed) and needs no baseline patches: it IS the working tree incl. WIP.
632
+ *
633
+ * Construction is self-copy-safe (BSD cp lacks GNU's guard): each top-level
634
+ * entry is copied individually into a staging dir OUTSIDE the copied tree
635
+ * (sibling of repoRoot — same FS, so the final rename is atomic), and
636
+ * `.pi-worktrees` is skipped so prior sandboxes never compound into the
637
+ * copy. Any failure → rm staging, caller falls back to `git worktree add`. */
638
+ async function createCowClone(
639
+ repoRoot: string,
640
+ wtPath: string,
641
+ exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
642
+ ): Promise<boolean> {
643
+ if (!cowAvailable()) return false;
644
+ const run = exec ?? defaultExec;
645
+ const staging = path.join(path.dirname(repoRoot), `.pi-wt-tmp-${path.basename(wtPath)}`);
646
+ try {
647
+ await fs.mkdir(staging, { recursive: true });
648
+ const entries = await fs.readdir(repoRoot, { withFileTypes: true });
649
+ for (const entry of entries) {
650
+ if (entry.name === WORKTREE_DIR_NAME) continue;
651
+ const res = await run("cp", ["-cR", path.join(repoRoot, entry.name), path.join(staging, entry.name)], { timeout: 300_000 });
652
+ if (res.code !== 0) return false;
653
+ }
654
+ await fs.mkdir(path.dirname(wtPath), { recursive: true });
655
+ try {
656
+ await fs.rename(staging, wtPath);
657
+ } catch {
658
+ // EXDEV (repoRoot is a mount point) — CoW unusable here.
659
+ return false;
660
+ }
661
+ return true;
662
+ } catch {
663
+ return false;
664
+ } finally {
665
+ await fs.rm(staging, { recursive: true, force: true }).catch(() => { /* best effort */ });
666
+ }
667
+ }
668
+
669
+ /** Copy gitignored files named in <repoRoot>/.worktreeinclude into the
670
+ * worktree (git-worktree fallback lacks them). Lines: gitignore-style globs,
671
+ * matched against gitignored files only (ls-files --others --ignored);
672
+ * `#` comments and blanks skipped. Zero-dep glob→regex, ~15 lines. */
673
+ export async function copyWorktreeIncludes(
674
+ repoRoot: string,
675
+ worktreeDir: string,
676
+ exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
677
+ ): Promise<number> {
678
+ let raw: string;
679
+ try {
680
+ raw = await fs.readFile(path.join(repoRoot, ".worktreeinclude"), "utf8");
681
+ } catch {
682
+ return 0;
683
+ }
684
+ const patterns = raw.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#"));
685
+ if (patterns.length === 0) return 0;
686
+ const regexes = patterns.map((p) => globToRegExp(p)).filter((r): r is RegExp => r !== null);
687
+ if (regexes.length === 0) return 0;
688
+ const ls = await runGit(repoRoot, ["ls-files", "--others", "--ignored", "--exclude-standard"], exec);
689
+ if (!ls.ok) return 0;
690
+ const matches = ls.stdout.split("\n").map((l) => l.trim()).filter(Boolean)
691
+ .filter((f) => regexes.some((re) => re.test(f)));
692
+ let copied = 0;
693
+ for (const rel of matches.slice(0, 500)) {
694
+ const src = path.join(repoRoot, rel);
695
+ const dst = path.join(worktreeDir, rel);
696
+ try {
697
+ const st = await fs.stat(src);
698
+ if (!st.isFile()) continue;
699
+ await fs.mkdir(path.dirname(dst), { recursive: true });
700
+ await fs.copyFile(src, dst);
701
+ copied++;
702
+ } catch { /* skip vanished/unreadable */ }
703
+ }
704
+ return copied;
705
+ }
706
+
707
+ /** Gitignore-style glob → RegExp. Supports `*`, `**`, `?`, leading/trailing
708
+ * `/`, and `dir/` (prefix). Negations unsupported (returns null). */
709
+ function globToRegExp(globRaw: string): RegExp | null {
710
+ let glob = globRaw;
711
+ if (glob.startsWith("!")) return null;
712
+ let prefix = false;
713
+ if (glob.endsWith("/")) { prefix = true; glob = glob.slice(0, -1); }
714
+ glob = glob.replace(/^\//, "");
715
+ let re = "";
716
+ for (let i = 0; i < glob.length; i++) {
717
+ const c = glob[i];
718
+ if (c === "*" && glob[i + 1] === "*") { re += ".*"; i++; }
719
+ else if (c === "*") re += "[^/]*";
720
+ else if (c === "?") re += "[^/]";
721
+ else re += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
722
+ }
723
+ try {
724
+ return prefix ? new RegExp(`^${re}(/|$)`) : new RegExp(`^${re}$`);
725
+ } catch {
726
+ return null;
727
+ }
728
+ }
729
+
730
+ /** Create a sandbox at .pi-worktrees/<rand> under the repo root: CoW clone of
731
+ * the working tree when available (carries WIP + node_modules + .env), else a
732
+ * detached git worktree the caller can seed with captureParentBaseline. */
405
733
  export async function createWorktree(
406
734
  cwd: string,
407
735
  exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
408
- ): Promise<{ ok: boolean; path?: string; repoRoot?: string; error?: string }> {
736
+ ): Promise<{ ok: boolean; path?: string; repoRoot?: string; error?: string; /** false when the git-worktree fallback ran (caller seeds baseline); undefined = CoW copy */ cow?: boolean }> {
409
737
  try {
410
738
  const root = await runGit(cwd, ["rev-parse", "--show-toplevel"], exec);
411
739
  if (!root.ok) return { ok: false, error: root.stderr.trim() || "not a git repo" };
412
740
  const repoRoot = root.stdout.trim();
413
741
  if (!repoRoot) return { ok: false, error: "empty git root" };
414
742
  const id = `pi-subagent-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
415
- const wtPath = path.join(repoRoot, ".pi-worktrees", id);
416
- const add = await runGit(repoRoot, ["worktree", "add", "--detach", wtPath, "HEAD"], exec);
743
+ const wtPath = path.join(repoRoot, WORKTREE_DIR_NAME, id);
744
+ await ensureWorktreeBaseGitignore(path.join(repoRoot, WORKTREE_DIR_NAME));
745
+ if (await createCowClone(repoRoot, wtPath, exec)) {
746
+ await writeOwnerMarker(path.join(repoRoot, WORKTREE_DIR_NAME), id).catch(() => { /* best effort */ });
747
+ return { ok: true, path: wtPath, repoRoot };
748
+ }
749
+ // Fallback: detached git worktree (clean HEAD; the caller seeds the
750
+ // parent's WIP via applyBaselineToWorktree). worktree add mutates the
751
+ // parent's shared .git/worktrees registry.
752
+ const add = await withRepoLock(repoRoot, () => runGit(repoRoot, ["worktree", "add", "--detach", wtPath, "HEAD"], exec));
417
753
  if (!add.ok) return { ok: false, error: add.stderr.trim() || "git worktree add failed" };
418
- return { ok: true, path: wtPath, repoRoot };
754
+ await writeOwnerMarker(path.join(repoRoot, WORKTREE_DIR_NAME), id).catch(() => { /* best effort */ });
755
+ return { ok: true, path: wtPath, repoRoot, cow: false };
419
756
  } catch (error) {
420
757
  return { ok: false, error: error instanceof Error ? error.message : String(error) };
421
758
  }
@@ -439,20 +776,27 @@ export async function captureWorktreeDiff(
439
776
  return { ok: true, diff: text || "(no changes)" };
440
777
  }
441
778
 
442
- /** Remove a worktree and its metadata, best-effort. */
779
+ /** Remove a worktree and its metadata, best-effort. Handles BOTH backends:
780
+ * registered git worktrees (worktree remove) and unregistered sandbox dirs
781
+ * (plain rm). */
443
782
  export async function removeWorktree(
444
783
  repoRoot: string,
445
784
  worktreeDir: string,
446
785
  exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
447
786
  ): Promise<void> {
448
787
  try {
449
- await runGit(repoRoot, ["worktree", "remove", "--force", worktreeDir], exec);
788
+ // Marker is a SIBLING file (never inside the sandbox — see OWNER_SUFFIX).
789
+ await fs.rm(`${worktreeDir}${OWNER_SUFFIX}`, { force: true }).catch(() => {});
790
+ await withRepoLock(repoRoot, async () => {
791
+ const removed = await runGit(repoRoot, ["worktree", "remove", "--force", worktreeDir], exec);
792
+ if (!removed.ok) await fs.rm(worktreeDir, { recursive: true, force: true }).catch(() => { /* best effort */ });
793
+ });
450
794
  } catch { /* best effort */ }
451
795
  }
452
796
 
453
797
  /** Serialized `git apply` on the parent checkout: parallel siblings finishing
454
- * at the same time must not race the merge (OMP's withRepoLock equivalent). */
455
- let applyChain: Promise<unknown> = Promise.resolve();
798
+ * at the same time must not race the merge (withRepoLock — the OMP
799
+ * withRepoLock equivalent, now shared with worktree add/remove too). */
456
800
 
457
801
  /** Apply a unified diff to the repo root via `git apply --3way`. Never throws;
458
802
  * ok:false means conflict/failure — the caller reports it and still delivers
@@ -462,7 +806,7 @@ export async function applyWorktreePatch3way(
462
806
  diff: string,
463
807
  exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
464
808
  ): Promise<{ ok: boolean; stderr: string }> {
465
- const run = applyChain.then(async (): Promise<{ ok: boolean; stderr: string }> => {
809
+ return withRepoLock(repoRoot, async (): Promise<{ ok: boolean; stderr: string }> => {
466
810
  const tmp = path.join(os.tmpdir(), `pi-subagent-apply-${randomUUID()}.patch`);
467
811
  try {
468
812
  // git apply interprets paths relative to cwd — write the diff to a file
@@ -481,8 +825,6 @@ export async function applyWorktreePatch3way(
481
825
  await fs.rm(tmp, { force: true }).catch(() => { /* best effort */ });
482
826
  }
483
827
  });
484
- applyChain = run.then(() => undefined, () => undefined);
485
- return run;
486
828
  }
487
829
 
488
830
  /** Model-facing patch block for a worktree result; "" when there is no patch.
@@ -509,6 +509,51 @@ test("classifyTask: a confident dispatch answer alone counts as applied", async
509
509
  assert.equal(verdict?.applied, true, "dispatch alone can carry the verdict");
510
510
  });
511
511
 
512
+ test("classifyTask: dispatch gates on the CHOSEN label's own probability — a high rival must not clear it", async () => {
513
+ // Live-found defect (reviewer 2026-10-06): the old gate took Math.max over
514
+ // ALL probabilities, so choice "background" at 0.4 applied because rival
515
+ // "pane" scored 0.65 — silently detaching a task the classifier wanted in
516
+ // a pane. Mirrors the tier question's chosen-label rule.
517
+ const rival = dispatchCtx({
518
+ ...TIER_AND_EFFORT,
519
+ dispatch: { choice: "background", probabilities: { background: 0.4, pane: 0.65 } },
520
+ });
521
+ const v1 = await classifyTask(rival, { ...DEFAULT_ROUTING, mode: "classify" }, WORKER, "long job", undefined, ROLES, { askDispatch: true });
522
+ assert.equal(v1?.dispatch, undefined, "rival probability must not clear the threshold for the choice");
523
+
524
+ const confident = dispatchCtx({
525
+ ...TIER_AND_EFFORT,
526
+ dispatch: { choice: "background", probabilities: { background: 0.72, pane: 0.28 } },
527
+ });
528
+ const v2 = await classifyTask(confident, { ...DEFAULT_ROUTING, mode: "classify" }, WORKER, "long job", undefined, ROLES, { askDispatch: true });
529
+ assert.equal(v2?.dispatch, "background");
530
+
531
+ // Out-of-range / bogus probabilities fail open (no dispatch override).
532
+ const bogus = dispatchCtx({
533
+ ...TIER_AND_EFFORT,
534
+ dispatch: { choice: "background", probabilities: { background: 7 } },
535
+ });
536
+ const v3 = await classifyTask(bogus, { ...DEFAULT_ROUTING, mode: "classify" }, WORKER, "long job", undefined, ROLES, { askDispatch: true });
537
+ assert.equal(v3?.dispatch, undefined, "out-of-range probability fails open to the pane default");
538
+ });
539
+
540
+ test("classifyTask: a never-resolving classify hits the deadline and fails open to the static chain", async () => {
541
+ // The 2026-10-06 live incident class: a silent endpoint parked the dispatch
542
+ // forever. The deadline race must return a fail-open verdict instead.
543
+ const ctx = {
544
+ modelRegistry: {
545
+ getAvailableOfType: async () => [{ provider: "router", id: "jev" }],
546
+ classify: () => new Promise(() => {}),
547
+ },
548
+ } as never;
549
+ const t0 = Date.now();
550
+ const verdict = await classifyTask(ctx, { ...DEFAULT_ROUTING, mode: "classify" }, WORKER, "anything", undefined, ROLES, { deadlineMs: 100 });
551
+ const ms = Date.now() - t0;
552
+ assert.ok(ms < 2_000, `deadline raced (${ms}ms) instead of hanging`);
553
+ assert.equal(verdict?.applied, false, "deadline expiry fails open");
554
+ assert.match(verdict?.reason ?? "", /deadline/);
555
+ });
556
+
512
557
  test("classifyTask: an unresolvable chain suppresses the tier question (typo fails loud, not papered over)", async () => {
513
558
  let asked: Record<string, unknown> = {};
514
559
  const ctx = dispatchCtx(