ceulen 0.10.1 → 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 (41) hide show
  1. package/CHANGELOG.md +56 -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/modules/a2a/index.ts +4 -2
  6. package/extensions/modules/attachments/configPanel.ts +91 -0
  7. package/extensions/modules/attachments/index.ts +274 -0
  8. package/extensions/modules/attachments/lib/clipboard-files.ts +80 -0
  9. package/extensions/modules/attachments/lib/pastes.ts +45 -0
  10. package/extensions/modules/attachments/lib/paths.ts +74 -0
  11. package/extensions/modules/attachments/lib/registry.ts +70 -0
  12. package/extensions/modules/attachments/lib/settings.ts +99 -0
  13. package/extensions/modules/attachments/lib/tray.ts +74 -0
  14. package/extensions/modules/attachments/test/configPanel.test.ts +122 -0
  15. package/extensions/modules/attachments/test/index.test.ts +870 -0
  16. package/extensions/modules/attachments/test/module.test.ts +53 -0
  17. package/extensions/modules/composer/test/module.test.ts +2 -2
  18. package/extensions/modules/config/index.ts +3 -0
  19. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  20. package/extensions/modules/cron/configPanel.ts +103 -0
  21. package/extensions/modules/cron/index.ts +638 -0
  22. package/extensions/modules/cron/lib/jobs.ts +201 -0
  23. package/extensions/modules/cron/lib/schedule.ts +161 -0
  24. package/extensions/modules/cron/test/cwd-repro.test.ts +98 -0
  25. package/extensions/modules/cron/test/index.test.ts +859 -0
  26. package/extensions/modules/cron/test/schedule.test.ts +93 -0
  27. package/extensions/modules/munin/index.ts +3 -1
  28. package/extensions/modules/permission/index.ts +567 -0
  29. package/extensions/modules/permission/test/permission.test.ts +789 -0
  30. package/extensions/modules/plan/index.ts +5 -0
  31. package/extensions/modules/repair/index.ts +134 -3
  32. package/extensions/modules/repair/test/freshness.test.ts +169 -0
  33. package/extensions/modules/subagent/index.ts +38 -5
  34. package/extensions/modules/subagent/lib/runner.ts +348 -12
  35. package/extensions/modules/subagent/test/worktree.test.ts +230 -0
  36. package/extensions/modules/usage/index.ts +193 -71
  37. package/extensions/modules/usage/test/context.test.ts +160 -120
  38. package/extensions/modules/web/index.ts +3 -1
  39. package/extensions/modules/web/test/a11y.test.ts +1 -1
  40. package/package.json +2 -2
  41. package/skills/cron/SKILL.md +58 -0
@@ -57,6 +57,7 @@ import { readDisabledTools } from "../../lib/tools.js";
57
57
  // frontmatter (user + project + bundled). discoverAgents is a pure fs loader,
58
58
  // independent of whether the subagent module itself is enabled.
59
59
  import { discoverAgents } from "../subagent/lib/agents.js";
60
+ import { setPlanActive } from "../../lib/plan-bridge.ts";
60
61
 
61
62
  export const PLAN_STATUS_KEY = "ceulen-plan";
62
63
  export const PLAN_ENTRY_TYPE = "ceulen-plan";
@@ -203,6 +204,10 @@ export default function planModule(pi: ExtensionAPI): void {
203
204
 
204
205
  function updateStatus(ctx: ExtensionContext): void {
205
206
  ctx.ui.setStatus(PLAN_STATUS_KEY, planModeEnabled ? ctx.ui.theme.fg("accent", "Plan mode") : undefined);
207
+ // Publish for the permission module (plan-bridge) — updateStatus runs after
208
+ // EVERY planModeEnabled assignment site, so this one line covers toggle,
209
+ // session restore, startup flag, and exit-for-execution.
210
+ setPlanActive(planModeEnabled);
206
211
  }
207
212
 
208
213
  /** Restore branch-scoped state (session_start / session_tree). */
@@ -27,7 +27,7 @@
27
27
 
28
28
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
29
29
  import { existsSync } from "node:fs";
30
- import { readFile } from "node:fs/promises";
30
+ import { readFile, stat } from "node:fs/promises";
31
31
  import { dirname, resolve as resolvePath } from "node:path";
32
32
  import {
33
33
  createBashToolDefinition,
@@ -182,11 +182,111 @@ function addReadDefaults(args: unknown): unknown {
182
182
  return out;
183
183
  }
184
184
 
185
+ // ── Write freshness guard (multi-session blind-overwrite protection) ──
186
+ // A `write` replaces a file wholesale: unlike edit/apply_patch (anchored on
187
+ // exact content) it cannot notice a foreign change. Record each file's mtime
188
+ // when read; before a write, compare — a mismatch means ANOTHER session or
189
+ // process changed the file since we last saw it. Only files this session
190
+ // actually read are guarded (intentional never-read overwrites stay legal).
191
+ const seenMtime = new Map<string, number>();
192
+
193
+ async function statMtime(abs: string): Promise<number | undefined> {
194
+ try {
195
+ return (await stat(abs)).mtimeMs;
196
+ } catch {
197
+ return undefined;
198
+ }
199
+ }
200
+
201
+ /** Record mtimes for files a successful read just returned. */
202
+ async function recordReadMtimes(params: any, cwd: string): Promise<void> {
203
+ if (!isRecord(params) || typeof params.path !== "string" || params.path.includes("://")) return;
204
+ const mtime = await statMtime(resolvePath(cwd, params.path));
205
+ if (mtime !== undefined) seenMtime.set(resolvePath(cwd, params.path), mtime);
206
+ // ponytail: the map grows with files-read-per-process; a cap keeps it
207
+ // bounded without an eviction policy.
208
+ if (seenMtime.size > 2000) seenMtime.clear();
209
+ }
210
+
211
+ /** After a successful mutation, refresh the recorded mtime so a FOLLOW-UP
212
+ * write compares against what this session last wrote, not what it read. */
213
+ async function recordMutatedMtimes(toolName: string, params: any, cwd: string): Promise<void> {
214
+ const paths: string[] = [];
215
+ if (toolName === "write" && isRecord(params) && typeof params.path === "string") paths.push(params.path);
216
+ if (toolName === "edit" && isRecord(params) && typeof params.path === "string") paths.push(params.path);
217
+ if (toolName === "apply_patch" && isRecord(params) && typeof params.patch === "string") {
218
+ paths.push(...parsePatchTargetPaths(params.patch));
219
+ }
220
+ for (const p of paths) {
221
+ const abs = resolvePath(cwd, p);
222
+ const mtime = await statMtime(abs);
223
+ if (mtime !== undefined) seenMtime.set(abs, mtime);
224
+ else seenMtime.delete(abs);
225
+ }
226
+ }
227
+
228
+ /** V4D patch targets: `*** Update File: <path>` / Add / Delete / rename. */
229
+ function parsePatchTargetPaths(patch: string): string[] {
230
+ const out: string[] = [];
231
+ for (const m of patch.matchAll(/^\*{3} (?:Add|Delete|Update) File: (.+?)(?: → .+)?$/gm)) {
232
+ const target = m[1].trim();
233
+ if (target && !target.includes("://")) out.push(target.split(" → ")[0].trim());
234
+ }
235
+ return out;
236
+ }
237
+
238
+ /** Public seam for tools registered outside wrapToolDefinition (apply_patch,
239
+ * str_replace_editor) to refresh the freshness baseline after their own
240
+ * successful mutations. */
241
+ export async function refreshMtime(path: string, cwd: string): Promise<void> {
242
+ const abs = resolvePath(cwd, path);
243
+ const mtime = await statMtime(abs);
244
+ if (mtime !== undefined) seenMtime.set(abs, mtime);
245
+ else seenMtime.delete(abs);
246
+ }
247
+
248
+ /** Pre-write check. Returns an error message when the file changed since this
249
+ * session last read it, else undefined (allowed). Exported for tests. */
250
+ export async function checkWriteFresh(params: any, cwd: string): Promise<string | undefined> {
251
+ if (!isRecord(params) || typeof params.path !== "string" || params.path.includes("://")) return undefined;
252
+ const abs = resolvePath(cwd, params.path);
253
+ const seen = seenMtime.get(abs);
254
+ if (seen === undefined) return undefined; // never read here — intentional overwrite is legal
255
+ const current = await statMtime(abs);
256
+ if (current === undefined) return undefined; // gone since read — write recreates it
257
+ if (current !== seen) {
258
+ return `File changed on disk since this session last read it (mtime differs — another session/process likely wrote it). Re-read the file, then re-apply your write to <${params.path}>.`;
259
+ }
260
+ return undefined;
261
+ }
262
+
185
263
  function appendReadNote(result: any, note: unknown) {
186
264
  if (typeof note !== "string" || !note) return result;
187
265
  return { ...result, content: [...(Array.isArray(result?.content) ? result.content : []), { type: "text", text: note }] };
188
266
  }
189
267
 
268
+ /** Auto-detect unresolved git conflict markers in a full-file read and append
269
+ * a footer naming them (OMP's conflict-detect workflow). Zero extra I/O —
270
+ * scans the text blocks the read already returned. The `:conflicts` selector
271
+ * path is excluded (it lists blocks explicitly). Exported for tests. */
272
+ export function appendConflictFooter(result: any, params: any, selector: ParsedSelector | undefined, cwd: string): any {
273
+ if (selector) return result;
274
+ const p = isRecord(params) && typeof params.path === "string" ? params.path : "";
275
+ if (!p) return result;
276
+ const texts = (Array.isArray(result?.content) ? result.content : [])
277
+ .filter((c: any) => c?.type === "text" && typeof c.text === "string")
278
+ .map((c: any) => c.text as string);
279
+ if (texts.length === 0) return result;
280
+ const lines = texts.join("\n").split("\n") as string[];
281
+ // Cheap pre-check before the block scanner.
282
+ if (!lines.some((l) => l.startsWith("<<<<<<<"))) return result;
283
+ const blocks = extractConflictBlocks(lines);
284
+ if (blocks.length === 0) return result;
285
+ const first = lines.indexOf(blocks[0][0]) + 1;
286
+ const footer = `⚠ ${blocks.length} unresolved merge conflict block(s) detected in ${p} (first at line ${first}) — read with :conflicts to list them, then edit to resolve.`;
287
+ return { ...result, content: [...(result.content as any[]), { type: "text", text: footer }] };
288
+ }
289
+
190
290
  // Strip read-tool contamination notices from an edit's oldText fields. Mutates
191
291
  // in place and reports whether anything changed.
192
292
  function decontaminateEditArgs(args: any): boolean {
@@ -289,8 +389,26 @@ export function wrapToolDefinition(
289
389
 
290
390
  if (base.name !== "edit") {
291
391
  try {
392
+ // Write freshness guard (see checkWriteFresh): a `write` to a file
393
+ // THIS session read earlier but someone else changed since must
394
+ // fail loudly instead of clobbering the foreign edit.
395
+ if (base.name === "write") {
396
+ const stale = await checkWriteFresh(params, cwd);
397
+ if (stale) {
398
+ return { content: [{ type: "text", text: stale }], isError: true, details: undefined };
399
+ }
400
+ }
292
401
  const result = await freshDef.execute(toolCallId, params, signal, onUpdate, ctx);
293
- return base.name === "read" ? appendReadNote(result, readNote) : result;
402
+ if (base.name === "read") {
403
+ const withNote = appendReadNote(result, readNote);
404
+ await recordReadMtimes(params, cwd);
405
+ return appendConflictFooter(withNote, params, selector ?? peeledSelector, cwd);
406
+ }
407
+ // Own mutations refresh the freshness baseline so later writes
408
+ // compare against what THIS session last left on disk. Awaited:
409
+ // a write immediately following must observe the new baseline.
410
+ await recordMutatedMtimes(base.name, params, cwd);
411
+ return result;
294
412
  } catch (err: any) {
295
413
  // Session mining: "(no output) / Command exited with code 1" after a
296
414
  // search reads as a crash, so models retry the same command. Annotate
@@ -460,6 +578,9 @@ export default function repairModule(pi: ExtensionAPI) {
460
578
  }
461
579
  try {
462
580
  const res = await applyPatchToFiles(parsed, cwd);
581
+ // Refresh freshness baselines: a later write to a patched file must
582
+ // compare against this patch's mtime, not an older read.
583
+ await Promise.all(res.files.map((f) => refreshMtime(f.path, cwd)));
463
584
  const summary = res.files.map((f) => {
464
585
  if (f.kind === "add") return `Added ${f.path}`;
465
586
  if (f.kind === "delete") return `Deleted ${f.path}`;
@@ -479,8 +600,18 @@ export default function repairModule(pi: ExtensionAPI) {
479
600
  });
480
601
 
481
602
  // ── str_replace_editor: DSH Minimal-pair editor (byte-faithful schema) ──
603
+ const strReplaceDef = createStrReplaceEditorToolDefinition(process.cwd());
482
604
  pi.registerTool({
483
- ...createStrReplaceEditorToolDefinition(process.cwd()),
605
+ ...strReplaceDef,
606
+ async execute(toolCallId: string, params: any, signal: any, onUpdate: any, ctx: any) {
607
+ const result = await strReplaceDef.execute(toolCallId, params, signal, onUpdate, ctx);
608
+ // Refresh the freshness baseline for the edited file (same rationale as
609
+ // apply_patch above) — only on success, only for plain file paths.
610
+ if (!result?.isError && isRecord(params) && typeof params.path === "string" && !params.path.includes("://")) {
611
+ await refreshMtime(params.path, ctx?.cwd || process.cwd());
612
+ }
613
+ return result;
614
+ },
484
615
  defaultActive: !disabled.has("str_replace_editor"),
485
616
  });
486
617
 
@@ -0,0 +1,169 @@
1
+ // Multi-session safety in the repair module: the write freshness guard
2
+ // (read→foreign-write→write must fail loud) and the auto conflict-marker
3
+ // footer on full-file reads. Real temp files, real wrapped tool definitions —
4
+ // the wrapper.test.ts integration precedent.
5
+
6
+ import assert from "node:assert/strict";
7
+ import { mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { after, describe, it } from "node:test";
11
+ import { createReadToolDefinition, createWriteToolDefinition } from "@earendil-works/pi-coding-agent";
12
+ import { appendConflictFooter, checkWriteFresh, wrapToolDefinition } from "../index.js";
13
+
14
+ const dirs: string[] = [];
15
+ const originalAgentDir = process.env.PI_CODING_AGENT_DIR;
16
+
17
+ after(async () => {
18
+ if (originalAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
19
+ else process.env.PI_CODING_AGENT_DIR = originalAgentDir;
20
+ await Promise.all(dirs.map((d) => rm(d, { recursive: true, force: true })));
21
+ });
22
+
23
+ async function tempDir(): Promise<string> {
24
+ const dir = await mkdtemp(join(tmpdir(), "repair-freshness-"));
25
+ dirs.push(dir);
26
+ process.env.PI_CODING_AGENT_DIR = dir;
27
+ return dir;
28
+ }
29
+
30
+ // Minimal wrapToolDefinition harness — the real core definitions, no repair
31
+ // toggles needed (defaults off for arguments; freshness/footer are always-on).
32
+ function makeWrapped(name: "read" | "write", cwd: string) {
33
+ const factory = name === "read" ? createReadToolDefinition : createWriteToolDefinition;
34
+ return wrapToolDefinition(factory(cwd), factory, () => false, () => {});
35
+ }
36
+
37
+ const exec = (wrapped: any, params: any, cwd: string) =>
38
+ wrapped.execute("t1", params, undefined, undefined, { cwd });
39
+
40
+ // ── Write freshness guard ───────────────────────────────────────────────────
41
+
42
+ describe("write freshness guard", () => {
43
+ it("write after read, no foreign change → succeeds and content lands", async () => {
44
+ const dir = await tempDir();
45
+ const file = join(dir, "a.txt");
46
+ await writeFile(file, "one\n");
47
+ const read = makeWrapped("read", dir);
48
+ await exec(read, { path: file }, dir);
49
+ const write = makeWrapped("write", dir);
50
+ const result = await exec(write, { path: file, content: "one\ntwo\n" }, dir);
51
+ assert.equal(result.isError, undefined);
52
+ assert.equal(await readFile(file, "utf8"), "one\ntwo\n");
53
+ });
54
+
55
+ it("read → FOREIGN write → write fails loud without clobbering", async () => {
56
+ const dir = await tempDir();
57
+ const file = join(dir, "b.txt");
58
+ await writeFile(file, "mine\n");
59
+ const read = makeWrapped("read", dir);
60
+ await exec(read, { path: file }, dir);
61
+ // Another session/process writes the file between our read and write.
62
+ await writeFile(file, "theirs\n");
63
+ // Ensure mtime actually advances (same-ms writes would false-pass).
64
+ const st = await readFile(file, "utf8");
65
+ const future = new Date(Date.now() + 1100);
66
+ await utimes(file, future, future);
67
+ assert.equal(st, "theirs\n");
68
+ const write = makeWrapped("write", dir);
69
+ const result = await exec(write, { path: file, content: "mine v2\n" }, dir);
70
+ assert.equal(result.isError, true);
71
+ assert.match(result.content[0].text, /Re-read the file/);
72
+ assert.equal(await readFile(file, "utf8"), "theirs\n"); // foreign edit survived
73
+ });
74
+
75
+ it("write after own edit does not false-positive", async () => {
76
+ const dir = await tempDir();
77
+ const file = join(dir, "c.txt");
78
+ await writeFile(file, "x\n");
79
+ const read = makeWrapped("read", dir);
80
+ await exec(read, { path: file }, dir);
81
+ const write = makeWrapped("write", dir);
82
+ await exec(write, { path: file, content: "y\n" }, dir);
83
+ const again = await exec(write, { path: file, content: "z\n" }, dir);
84
+ assert.equal(again.isError, undefined);
85
+ assert.equal(await readFile(file, "utf8"), "z\n");
86
+ });
87
+
88
+ it("write to a never-read file is allowed (intentional overwrite is legal)", async () => {
89
+ const dir = await tempDir();
90
+ const file = join(dir, "d.txt");
91
+ await writeFile(file, "old\n");
92
+ const write = makeWrapped("write", dir);
93
+ const result = await exec(write, { path: file, content: "new\n" }, dir);
94
+ assert.equal(result.isError, undefined);
95
+ });
96
+
97
+ it("write after own apply_patch does not false-positive", async () => {
98
+ const dir = await tempDir();
99
+ const file = join(dir, "e.txt");
100
+ await writeFile(file, "alpha\n");
101
+ const read = makeWrapped("read", dir);
102
+ await exec(read, { path: file }, dir);
103
+ // Simulate the apply_patch flow: patch tool mutates (externally to the
104
+ // wrapped write), refreshes the baseline, then a write must pass.
105
+ await writeFile(file, "alpha\nbeta\n");
106
+ const future = new Date(Date.now() + 1100);
107
+ await utimes(file, future, future);
108
+ const { refreshMtime } = await import("../index.js");
109
+ await refreshMtime(file, dir);
110
+ const write = makeWrapped("write", dir);
111
+ const result = await exec(write, { path: file, content: "alpha\nbeta\ngamma\n" }, dir);
112
+ assert.equal(result.isError, undefined);
113
+ });
114
+
115
+ it("checkWriteFresh unit: missing file since read is allowed (recreate)", async () => {
116
+ const dir = await tempDir();
117
+ const file = join(dir, "gone.txt");
118
+ await writeFile(file, "x\n");
119
+ const read = makeWrapped("read", dir);
120
+ await exec(read, { path: file }, dir);
121
+ await rm(file);
122
+ assert.equal(await checkWriteFresh({ path: file }, dir), undefined);
123
+ });
124
+ });
125
+
126
+ // ── Conflict-marker footer ──────────────────────────────────────────────────
127
+
128
+ describe("conflict footer", () => {
129
+ it("pure function: appends footer when completed blocks present", () => {
130
+ const content = "a\n<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> branch\nb\n";
131
+ const result = appendConflictFooter(
132
+ { content: [{ type: "text", text: content }] },
133
+ { path: "f.txt" },
134
+ undefined,
135
+ "/cwd",
136
+ );
137
+ const footer = result.content[result.content.length - 1];
138
+ assert.match(footer.text, /1 unresolved merge conflict block/);
139
+ assert.match(footer.text, /first at line 2/);
140
+ });
141
+
142
+ it("pure function: silent without conflicts, and open (unclosed) markers don't count", () => {
143
+ const clean = appendConflictFooter({ content: [{ type: "text", text: "no markers\n" }] }, { path: "f.txt" }, undefined, "/c");
144
+ assert.equal(clean.content.length, 1);
145
+ const open = appendConflictFooter({ content: [{ type: "text", text: "<<<<<<< HEAD\nnever closed\n" }] }, { path: "f.txt" }, undefined, "/c");
146
+ assert.equal(open.content.length, 1);
147
+ });
148
+
149
+ it("selector reads are excluded (the :conflicts path lists blocks explicitly)", () => {
150
+ const content = "<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> b\n";
151
+ const result = appendConflictFooter(
152
+ { content: [{ type: "text", text: content }] },
153
+ { path: "f.txt" },
154
+ { kind: "lines", startLine: 1 } as never,
155
+ "/c",
156
+ );
157
+ assert.equal(result.content.length, 1);
158
+ });
159
+
160
+ it("integration: wrapped read of a conflicted file carries the footer", async () => {
161
+ const dir = await tempDir();
162
+ const file = join(dir, "conflicted.txt");
163
+ await writeFile(file, "top\n<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> other\nbottom\n");
164
+ const read = makeWrapped("read", dir);
165
+ const result = await exec(read, { path: file }, dir);
166
+ const texts = result.content.map((c: any) => c.text).join("\n");
167
+ assert.match(texts, /1 unresolved merge conflict block/);
168
+ });
169
+ });
@@ -17,7 +17,7 @@
17
17
  */
18
18
 
19
19
  import * as path from "node:path";
20
- import * as fsPromises from "node:fs/promises";
20
+ import * as fs from "node:fs/promises";
21
21
  import { Container, Markdown, SelectList, Spacer, Text } from "@earendil-works/pi-tui";
22
22
  import { Type } from "typebox";
23
23
  import {
@@ -35,14 +35,18 @@ import { StringEnum } from "./lib/schema.ts";
35
35
  import { type AgentColor, type AgentConfig, type AgentScope, discoverAgents, formatAgentList, getModelCandidates, invalidateAgentCache } from "./lib/agents.ts";
36
36
  import {
37
37
  type SubAgentProgress,
38
+ type WorktreeOwner,
38
39
  type SubAgentResult,
39
40
  formatPatchBlock,
40
41
  getFinalOutput,
41
42
  getResultOutput,
42
43
  isFailedResult,
43
44
  mapWithConcurrencyLimit,
45
+ pidAlive,
44
46
  runSubAgent,
45
47
  startHeartbeat,
48
+ sweepStaleWorktrees,
49
+ WORKTREE_DIR_NAME,
46
50
  } from "./lib/runner.ts";
47
51
  import {
48
52
  flushWarnings,
@@ -296,6 +300,9 @@ export default function (pi: ExtensionAPI) {
296
300
  });
297
301
  // Clear any widget from a prior session.
298
302
  if (ctx.mode === "tui") widget.clearWidgetIfIdle(ctx);
303
+ // Reclaim crashed runs' worktree sandboxes (fire-and-forget: never blocks
304
+ // startup; a no-.pi-worktrees repo costs one rev-parse).
305
+ void sweepStaleWorktrees(ctx.cwd).catch(() => { /* best effort */ });
299
306
  // Mark prior-session running tasks as interrupted (we can't resume them),
300
307
  // but keep entries for background tasks still live in this process — only
301
308
  // shutdown aborts them, so a session reload must not mislabel them.
@@ -388,10 +395,10 @@ export default function (pi: ExtensionAPI) {
388
395
  return container;
389
396
  });
390
397
  pi.registerCommand("subagent", {
391
- description: "Configure model roles (/subagent), list agents (/subagent list), agent details (/subagent <name>), role detail (/subagent @role), reload definitions (/subagent reload), history (/subagent history)",
398
+ description: "Configure model roles (/subagent), list agents (/subagent list), agent details (/subagent <name>), role detail (/subagent @role), reload definitions (/subagent reload), history (/subagent history), worktree sandboxes (/subagent worktrees [clean])",
392
399
  getArgumentCompletions: (prefix) => {
393
400
  const ctx = currentCtx;
394
- const keywords = ["list", "all", "agents", "roles", "reload", "refresh", "history"];
401
+ const keywords = ["list", "all", "agents", "roles", "reload", "refresh", "history", "worktrees"];
395
402
  const vocab = [...keywords];
396
403
  if (ctx) {
397
404
  const discovery = discoverAgents(ctx.cwd, "both", bundledAgentsDir);
@@ -407,6 +414,32 @@ export default function (pi: ExtensionAPI) {
407
414
  const cmd = args.trim().toLowerCase();
408
415
  const discovery = discoverAgents(ctx.cwd, "both", bundledAgentsDir);
409
416
 
417
+ // /subagent worktrees [clean] — worktree sandbox inventory + GC.
418
+ if (cmd === "worktrees" || cmd.startsWith("worktrees ")) {
419
+ const force = cmd.includes("clean");
420
+ const ownerLabel = async (): Promise<string> => {
421
+ const base = path.join(path.resolve(ctx.cwd), WORKTREE_DIR_NAME);
422
+ let entries: string[] = [];
423
+ try { entries = (await fs.readdir(base)).filter((e) => e !== ".gitignore"); } catch { return "No worktree sandboxes."; }
424
+ if (entries.length === 0) return "No worktree sandboxes.";
425
+ const lines = await Promise.all(entries.map(async (entry) => {
426
+ let owner: WorktreeOwner | undefined;
427
+ try { owner = JSON.parse(await fs.readFile(path.join(base, `${entry}.owner.json`), "utf8")) as WorktreeOwner; } catch { /* stale/legacy */ }
428
+ const state = !owner ? "stale (no marker)"
429
+ : pidAlive(owner.pid) ? `live (pid ${owner.pid})`
430
+ : `dead (pid ${owner.pid}, ${Math.round((Date.now() - (owner.createdAt ?? Date.now())) / 60000)}min old)`;
431
+ return ` ${entry} — ${state}`;
432
+ }));
433
+ return `Worktree sandboxes (${entries.length}):
434
+ ${lines.join("\n")}`;
435
+ };
436
+ const result = force ? await sweepStaleWorktrees(ctx.cwd) : null;
437
+ const listing = await ownerLabel();
438
+ const sweepLine = result ? `\n\nSwept ${result.removed.length} stale sandbox(es): ${result.removed.map((r) => path.basename(r)).join(", ") || "none"}.` : "\n\n(/subagent worktrees clean to sweep stale entries)";
439
+ pi.sendMessage({ customType: "ceulen-subagent", content: `${listing}${sweepLine}`, display: true });
440
+ return;
441
+ }
442
+
410
443
  // /subagent history — list recent task delegations (durable metadata).
411
444
  if (cmd === "history" || cmd === "hist") {
412
445
  const piDir = path.join(ctx.cwd, CONFIG_DIR_NAME);
@@ -2115,7 +2148,7 @@ export default function (pi: ExtensionAPI) {
2115
2148
  if (params.wait) {
2116
2149
  const timeoutMs = params.timeout ?? 120_000;
2117
2150
  const fileStampBefore = entry
2118
- ? await fsPromises.stat(entry.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "")
2151
+ ? await fs.stat(entry.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "")
2119
2152
  : "";
2120
2153
  // Abortable: an aborted tool call interrupts the wait (esc to the
2121
2154
  // child) instead of blocking until the CLI timeout.
@@ -2151,7 +2184,7 @@ export default function (pi: ExtensionAPI) {
2151
2184
  // if THIS prompt changed it — otherwise the previous run's report
2152
2185
  // would come back as the answer.
2153
2186
  if (collected.source === "file") {
2154
- const stampAfter = await fsPromises.stat(entry.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
2187
+ const stampAfter = await fs.stat(entry.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
2155
2188
  if (stampAfter === fileStampBefore) {
2156
2189
  // Unchanged file = the previous run's report — don't return
2157
2190
  // it as the answer to this prompt.